plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
tgen/lumosVar2-master
getMeanInRegionsExcludeNaN.m
.m
lumosVar2-master/src/getMeanInRegionsExcludeNaN.m
1,532
utf_8
047ae10f81e3e7f9048084bc801d97d0
function regionMean=getMeanInRegionsExcludeNaN(pos,values,regions) %getMeanInRegionsExcludeNaN - finds mean of values within each region % % Syntax: regionMean=getMeanInRegions(pos,values,regions) % % Inputs: % pos: two column matrix where 1st col is chr and 2nd is pos % values: values to find mean of, same length as pos % regions: three column matrix where each row specifies a region % 1st col is chr, 2nd is start pos, 3rd col is end pos % % Outputs: % regionMean: vector same height as regions with mean of value in regions % % Other m-files required: none % Subfunctions: none % MAT-files required: none % % See also: getMeanInRegions, getPosInRegions % Author: Rebecca F. Halperin, PhD % Translational Genomics Research Institute % email: [email protected] % Website: https://github.com/tgen % Last revision: 3-June-2016 %------------- BEGIN CODE -------------- for i=min(pos(:,1)):max(pos(:,1)) currPos=pos(pos(:,1)==i,:); currValues=values(pos(:,1)==i,:); currRegions=regions(regions(:,1)==i,:); if isempty(currPos) || isempty(currRegions) continue; end afterStart=ones(size(currRegions,1),1)*currPos(:,2)'>=currRegions(:,2)*ones(1,size(currPos,1)); beforeEnd=ones(size(currRegions,1),1)*currPos(:,2)'<=currRegions(:,3)*ones(1,size(currPos,1)); regionBool=logical(afterStart+beforeEnd==2); regionBool(:,~isfinite(currValues))=0; currValues(~isfinite(currValues))=0; regionMean(regions(:,1)==i,:)=(regionBool*currValues)./sum(regionBool,2); end return;
github
tgen/lumosVar2-master
calculateNormalMetrics.m
.m
lumosVar2-master/src/calculateNormalMetrics.m
2,545
utf_8
ba3c4e1a6576d69b37f559596ab8ece1
function [normalMetrics]=calculateNormalMetrics(NormalData, priorMapError,ploidy) %calculateNormalMetrics - calculates mean read depths and %position quality scores for a control sample %calls parsePileupData.packed.pl to parse samtools output % % [normalMetrics]=calculateNormalMetrics(NormalData, priorMapError) % % Inputs: % NormalData - matrix of normal data with the following columns: % 1-'Chr', 2-'Pos', 3-'ReadDepth', 4-'ReadDepthPass', 5-'Ref', 6-'A', % 7-'ACountF', 8-'ACountR', 9-'AmeanBQ', 10-'AmeanMQ', 11-'B', % 12-'BCountF', 13-'BCountR', 14-'BmeanBQ', 15-'BmeanMQ', % 16-'ApopAF', 17-'BpopAF' % priorMapError - prior probability that the position has poor quality % % Outputs: % normalMetrics - matrix with the following columns: 1-'Chr', 2-'Pos', % 3-'ReadDepthPass', 4-'pMapError', 5-'perReadPass', 6-'abFrac' % % Other m-files required: none % Other requirements: none % Subfunctions: none % MAT-files required: none % % See also: printNormalMetrics % Author: Rebecca F. Halperin, PhD % Translational Genomics Research Institute % email: [email protected] % Website: https://github.com/tgen % Last revision: 3-June-2016 %------------- BEGIN CODE -------------- %%% read data into tables NormalColHeaders={'Chr','Pos','ReadDepth','ReadDepthPass','Ref','A','ACountF','ACountR','AmeanBQ','AmeanMQ','B','BCountF','BCountR','BmeanBQ','BmeanMQ','ApopAF', 'BpopAF'}; N=array2table(NormalData,'VariableNames',NormalColHeaders); clear NormalColHeaders NormalData; %%% calculate priors if ploidy==2 priorHet=2.*N.ApopAF.*N.BpopAF; else priorHet=0; end priorHom=N.ApopAF.^2; %%% calculate liklihoods pDataMapError=10.^(-min([N.AmeanMQ N.BmeanMQ],[],2)./10); pDataHom=binopdf(N.BCountF+N.BCountR,N.ReadDepthPass,10.^(-N.BmeanBQ./10)); pDataHet=binopdf(N.BCountF+N.BCountR,N.ReadDepthPass,0.5); %%% calculate marginal pData=priorMapError.*pDataMapError+priorHet.*pDataHet+priorHom.*pDataHom; %%% calculate posteriors pMapError=priorMapError.*pDataMapError./pData; pHet=priorHet.*pDataHet./pData; pHom=priorHom.*pDataHom./pData; %%% calculate other quality metrics perReadPass=N.ReadDepthPass./N.ReadDepth; perReadPass(N.ReadDepth==0)=NaN; abFrac=(N.ACountF+N.ACountR+N.BCountF+N.BCountR)./N.ReadDepthPass; if ploidy==2 normalMetrics=[N.Chr N.Pos max(N.ReadDepthPass,0) pMapError perReadPass abFrac]; elseif ploidy==1 normalMetrics=[N.Chr N.Pos max(2*N.ReadDepthPass,0) pMapError perReadPass abFrac]; else normalMetrics=[N.Chr N.Pos nan(size(N,1),4)]; end return;
github
YutingZhang/caffe-recon-dec-master
classification_demo.m
.m
caffe-recon-dec-master/matlab/demo/classification_demo.m
5,412
utf_8
8f46deabe6cde287c4759f3bc8b7f819
function [scores, maxlabel] = classification_demo(im, use_gpu) % [scores, maxlabel] = classification_demo(im, use_gpu) % % Image classification demo using BVLC CaffeNet. % % IMPORTANT: before you run this demo, you should download BVLC CaffeNet % from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html) % % **************************************************************************** % For detailed documentation and usage on Caffe's Matlab interface, please % refer to Caffe Interface Tutorial at % http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab % **************************************************************************** % % input % im color image as uint8 HxWx3 % use_gpu 1 to use the GPU, 0 to use the CPU % % output % scores 1000-dimensional ILSVRC score vector % maxlabel the label of the highest score % % You may need to do the following before you start matlab: % $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64 % $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 % Or the equivalent based on where things are installed on your system % % Usage: % im = imread('../../examples/images/cat.jpg'); % scores = classification_demo(im, 1); % [score, class] = max(scores); % Five things to be aware of: % caffe uses row-major order % matlab uses column-major order % caffe uses BGR color channel order % matlab uses RGB color channel order % images need to have the data mean subtracted % Data coming in from matlab needs to be in the order % [width, height, channels, images] % where width is the fastest dimension. % Here is the rough matlab for putting image data into the correct % format in W x H x C with BGR channels: % % permute channels from RGB to BGR % im_data = im(:, :, [3, 2, 1]); % % flip width and height to make width the fastest dimension % im_data = permute(im_data, [2, 1, 3]); % % convert from uint8 to single % im_data = single(im_data); % % reshape to a fixed size (e.g., 227x227). % im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % % subtract mean_data (already in W x H x C with BGR channels) % im_data = im_data - mean_data; % If you have multiple images, cat them with cat(4, ...) % Add caffe/matlab to you Matlab search PATH to use matcaffe if exist('../+caffe', 'dir') addpath('..'); else error('Please run this demo from caffe/matlab/demo'); end % Set caffe mode if exist('use_gpu', 'var') && use_gpu caffe.set_mode_gpu(); gpu_id = 0; % we will use the first gpu in this demo caffe.set_device(gpu_id); else caffe.set_mode_cpu(); end % Initialize the network using BVLC CaffeNet for image classification % Weights (parameter) file needs to be downloaded from Model Zoo. model_dir = '../../models/bvlc_reference_caffenet/'; net_model = [model_dir 'deploy.prototxt']; net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel']; phase = 'test'; % run with phase test (so that dropout isn't applied) if ~exist(net_weights, 'file') error('Please download CaffeNet from Model Zoo before you run this demo'); end % Initialize a network net = caffe.Net(net_model, net_weights, phase); if nargin < 1 % For demo purposes we will use the cat image fprintf('using caffe/examples/images/cat.jpg as input image\n'); im = imread('../../examples/images/cat.jpg'); end % prepare oversampled input % input_data is Height x Width x Channel x Num tic; input_data = {prepare_image(im)}; toc; % do forward pass to get scores % scores are now Channels x Num, where Channels == 1000 tic; % The net forward function. It takes in a cell array of N-D arrays % (where N == 4 here) containing data of input blob(s) and outputs a cell % array containing data from output blob(s) scores = net.forward(input_data); toc; scores = scores{1}; scores = mean(scores, 2); % take average scores over 10 crops [~, maxlabel] = max(scores); % call caffe.reset_all() to reset caffe caffe.reset_all(); % ------------------------------------------------------------------------ function crops_data = prepare_image(im) % ------------------------------------------------------------------------ % caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that % is already in W x H x C with BGR channels d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat'); mean_data = d.mean_data; IMAGE_DIM = 256; CROPPED_DIM = 227; % Convert an image returned by Matlab's imread to im_data in caffe's data % format: W x H x C with BGR channels im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR im_data = permute(im_data, [2, 1, 3]); % flip width and height im_data = single(im_data); % convert from uint8 to single im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR) % oversample (4 corners, center, and their x-axis flips) crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices = [0 IMAGE_DIM-CROPPED_DIM] + 1; n = 1; for i = indices for j = indices crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :); crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n); n = n + 1; end end center = floor(indices(2) / 2) + 1; crops_data(:,:,:,5) = ... im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:); crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
github
lijiansong/Postgraduate-Course-master
spam.m
.m
Postgraduate-Course-master/Data-Mining/adaboost-bagging/src/spam.m
4,050
utf_8
3a03399af44909d5f2f7ef06d521cfea
function spam() %Spam data training and testing result clc; I = load('spamtest.ascii','-ascii'); X = I(:,1:57); %:x57 Y = I(:,58); %:x1 T = load('spamtrain.ascii','-ascii'); tX = T(:,1:57); %:x57 tY = T(:,58); %:x1 trees = floor(logspace(0,3,10)); tr_bag = cell(1000,3); tr_boost = cell(1000,3); wt_boost = zeros(1000,1); err_boost = zeros(1000,1); test_error_bag = zeros(1,size(trees,2)); train_error_bag = zeros(1,size(trees,2)); test_error_boost = zeros(1,size(trees,2)); train_error_boost = zeros(1,size(trees,2)); for d = 1:3 alpha = ones(size(Y,1),1); for i = 1:10 %sprintf('depth: %d trees: %d\n',d,trees(i)); remain = 1; if i >1 remain = trees(i) - trees(i-1); end for sz = 1:remain S = datasample(I,size(Y,1)); B_X = S(:,1:57); %80x57 B_Y = S(:,58); %80x1 t_bag = traindt(B_X,B_Y,d); t_boost = traindtw(X,Y,alpha,d); if i > 1 tr_bag(trees(i-1) + sz,:) = t_bag; tr_boost(trees(i-1) + sz,:) = t_boost; err_boost(trees(i-1) + sz) = error_calculation(X,Y,t_boost,1,alpha); wt_boost(trees(i-1) + sz) = log(1-err_boost(trees(i-1) + sz)) - log(err_boost(trees(i-1) + sz)); alpha = update_alpha(X,Y,t_boost,alpha,wt_boost(trees(i-1) + sz)); else tr_bag(sz,:) = t_bag; tr_boost(sz,:) = t_boost; err_boost(sz) = error_calculation(X,Y,t_boost,1,alpha); wt_boost(sz) = log(1-err_boost(sz)) - log(err_boost(sz)); alpha = update_alpha(X,Y,t_boost,alpha,wt_boost(sz)); end end test_error_bag(i) = classification_error(X,Y,tr_bag(1:trees(i),:),trees(i)); train_error_bag(i) = classification_error(tX,tY,tr_bag(1:trees(i),:),trees(i)); test_error_boost(i) = classification_error(X,Y,tr_boost(1:trees(i),:),trees(i)); train_error_boost(i) = classification_error(tX,tY,tr_boost(1:trees(i),:),trees(i)); end figure(1); semilogx(trees,test_error_bag,'--','LineWidth',d); hold on; semilogx(trees,train_error_bag,'LineWidth',d); title('Bagging'); xlabel('number of trees'); ylabel('error rate'); legend('depth = 1','depth = 1','depth = 2','depth = 2','depth = 3','depth = 3'); figure(2); semilogx(trees,test_error_boost,'--','LineWidth',d); hold on; semilogx(trees,train_error_boost,'LineWidth',d); title('AdaBoost'); xlabel('number of trees'); ylabel('error rate'); legend('depth = 1','depth = 1','depth = 2','depth = 2','depth = 3','depth = 3'); end end function err = classification_error(X,Y,t,B) tY = zeros(size(Y,1),1); for i = 1:B tY = tY + dt(X,t(i,:)); end tY = tY./B; [m n] = size(tY); for j = 1:m if tY(j) > 0 tY(j) = 1; else tY(j) = -1; end end err = 0; for j = 1:m if tY(j) ~= Y(j) err = err + 1; end end err = err./size(Y,1); end function err = error_calculation(X,Y,t,B,alpha) tY = zeros(size(Y,1),1); for i = 1:B tY = tY + dt(X,t(i,:)); end tY = tY./B; [m n] = size(tY); for j = 1:m if tY(j) > 0 tY(j) = 1; else tY(j) = -1; end end al = 0; for j = 1:m if tY(j) ~= Y(j) al = al + alpha(j); end end err = al./sum(alpha); end function al = update_alpha(X,Y,t,alpha,w) %testY = zeros(size(Y,1),1); testY = dt(X,t); [m n] = size(testY); al = alpha; for j = 1:m if testY(j) ~= Y(j) al(j) = alpha(j).*exp(w); end end end
github
lijiansong/Postgraduate-Course-master
adaboost.m
.m
Postgraduate-Course-master/Data-Mining/adaboost-bagging/src/adaboost.m
3,518
utf_8
cdca27d38d605ad049901dc7d93bbb8b
function adaboost() %Adaboost clc; I = load('class2d.ascii','-ascii'); X = I(:,1:2); %80x2 Y = I(:,3); %80x1 trees = [1,10,100,1000]; tr = cell(1000,3); wt = zeros(1000,1); err = zeros(1000,1); %Boosting for d = 1:3 alpha = ones(80,1); for i = 1:4 f = 4*(d-1)+i; figure(f) remain = 1; if i >1 remain = trees(i) - trees(i-1); end for sz = 1:remain t = traindtw(X,Y,alpha,d); if i > 1 tr(trees(i-1) + sz,:) = t; err(trees(i-1) + sz) = classification_error(X,Y,t,1,alpha); wt(trees(i-1) + sz) = log(1-err(trees(i-1) + sz)) - log(err(trees(i-1) + sz)); alpha = update_alpha(X,Y,t,alpha,wt(trees(i-1) + sz)); else tr(sz,:) = t; err(sz) = classification_error(X,Y,t,1,alpha); wt(sz) = log(1-err(sz)) - log(err(sz)); alpha = update_alpha(X,Y,t,alpha,wt(sz)); end end plotclassifier(X,Y,@(X) myclassifier(X,tr(1:trees(i),:),trees(i),wt(1:trees(i))),0.5,0); if(d == 1) if(trees(i) == 1) title('depth = 1, num of trees = 1'); elseif(trees(i) == 10) title('depth = 1, num of trees = 10'); elseif(trees(i) == 100) title('depth = 1, num of trees = 100'); elseif(trees(i) == 1000) title('depth = 1, num of trees = 1000'); end elseif(d == 2) if(trees(i) == 1) title('depth = 2, num of trees = 1'); elseif(trees(i) == 10) title('depth = 2, num of trees = 10'); elseif(trees(i) == 100) title('depth = 2, num of trees = 100'); elseif(trees(i) == 1000) title('depth = 2, num of trees = 1000'); end elseif(d == 3) if(trees(i) == 1) title('depth = 3, num of trees = 1'); elseif(trees(i) == 10) title('depth = 3, num of trees = 10'); elseif(trees(i) == 100) title('depth = 3, num of trees = 100'); elseif(trees(i) == 1000) title('depth = 3, num of trees = 1000'); end end end end end function Y = myclassifier(X,t,B,w) Y = zeros(2500,1); for i = 1:B Y = Y + dt(X,t(i,:)).*w(i); end [m n] = size(Y); for j = 1:m if Y(j) > 0 Y(j) = 1; else Y(j) = -1; end end end function err = classification_error(X,Y,t,B,alpha) tY = zeros(size(Y,1),1); for i = 1:B tY = tY + dt(X,t(i,:)); end tY = tY./B; [m n] = size(tY); for j = 1:m if tY(j) > 0 tY(j) = 1; else tY(j) = -1; end end al = 0; for j = 1:m if tY(j) ~= Y(j) al = al + alpha(j); end end err = al./sum(alpha); end function al = update_alpha(X,Y,t,alpha,w) tY = zeros(size(Y,1),1); tY = dt(X,t); [m n] = size(tY); al = alpha; for j = 1:m if tY(j) ~= Y(j) al(j) = alpha(j).*exp(w); end end end
github
lijiansong/Postgraduate-Course-master
bagging.m
.m
Postgraduate-Course-master/Data-Mining/adaboost-bagging/src/bagging.m
2,444
utf_8
bcc0e71f2bcef006d9cdcf37c64512ce
function bagging() %Bagging clc; I = load('class2d.ascii','-ascii'); X = I(:,1:2); %80x2 Y = I(:,3); %80x1 trees = [1,10,100,1000]; tr = cell(1000,3); %Bagging for d = 1:3 for i = 1:4 f = 4*(d-1)+i; figure(f) remain = 1; if i >1 remain = trees(i) - trees(i-1); end for sz = 1:remain S = datasample(I,80); B_X = S(:,1:2); %80x2 B_Y = S(:,3); %80x1 t = traindt(B_X,B_Y,d); if i > 1 tr(trees(i-1) + sz,:) = t; else tr(sz,:) = t; end end plotclassifier(X,Y,@(X) myclassifier(X,tr(1:trees(i),:),trees(i)),0.5,0); if(d == 1) if(trees(i) == 1) title('depth = 1, num of trees = 1'); elseif(trees(i) == 10) title('depth = 1, num of trees = 10'); elseif(trees(i) == 100) title('depth = 1, num of trees = 100'); elseif(trees(i) == 1000) title('depth = 1, num of trees = 1000'); end elseif(d == 2) if(trees(i) == 1) title('depth = 2, num of trees = 1'); elseif(trees(i) == 10) title('depth = 2, num of trees = 10'); elseif(trees(i) == 100) title('depth = 2, num of trees = 100'); elseif(trees(i) == 1000) title('depth = 2, num of trees = 1000'); end elseif(d == 3) if(trees(i) == 1) title('depth = 3, num of trees = 1'); elseif(trees(i) == 10) title('depth = 3, num of trees = 10'); elseif(trees(i) == 100) title('depth = 3, num of trees = 100'); elseif(trees(i) == 1000) title('depth = 3, num of trees = 1000'); end end end end end function Y = myclassifier(X,t,B) tY = zeros(2500,1); for i = 1:B tY = tY + dt(X,t(i,:)); end Y = tY./B; [m n] = size(Y); for j = 1:m if Y(j) > 0 Y(j) = 1; else Y(j) = -1; end end end
github
lijiansong/Postgraduate-Course-master
splitgini.m
.m
Postgraduate-Course-master/Data-Mining/adaboost-bagging/src/splitgini.m
1,097
utf_8
95971f11b53ed7b2adf25810163e154b
function split = splitgini(X,Y,alpha,isleaf,minnum) cl = unique(Y); Ys = repmat(Y,1,length(cl))==repmat(cl',size(Y,1),1); Ys = Ys.*repmat(alpha,1,length(cl)); [~,split] = max(sum(Ys,1),[],2); split = cl(split); if (~isleaf && size(X,1)>minnum && length(cl)>1) bestsc = inf; bestvar = 0; bestth = 0; for d=1:size(X,2) [sc,th] = splitginid(d,X,Y,alpha,cl); if (sc<bestsc) bestsc = sc; bestvar = d; bestth = th; end; end; if (~isinf(bestsc)) split = [bestvar,bestth]; end; end; function [bsc,th] = splitginid(d,X,Y,alpha,cl) [Xp,perm] = sort(X(:,d),1); Yp = Y(perm); ap = alpha(perm); csum = repmat(Yp,1,length(cl))==repmat(cl',size(Yp,1),1); csum = csum.*repmat(ap,1,length(cl)); csum = cumsum(csum,1); sm = sum(csum,2); csum2 = bsxfun(@minus,csum(end,:),csum); sm2 = sum(csum2,2); sc = sum(bsxfun(@ginihelp,csum,sm),2); scp = sum(bsxfun(@ginihelp,csum2,sm2),2); sc = sc + scp; eq = [Xp(1:end-1)==Xp(2:end); false]; sc(eq) = inf; [bsc,i] = min(sc); if (bsc==sc(end)) bsc = inf; th = 0; else th = (Xp(i)+Xp(i+1))/2; end; function v = ginihelp(a,b) v = a.*(1-a./b);
github
lijiansong/Postgraduate-Course-master
printdt.m
.m
Postgraduate-Course-master/Data-Mining/adaboost-bagging/src/printdt.m
697
utf_8
895adc09b06bdbe0f8c664511b57320d
function printdt(tree) % function printdt(tree) % % displays a tree in the format returned by traindt printdthelp(tree,'','',''); function printdthelp(tree,lstem,cstem,rstem) if (length(tree)==1) disp(sprintf('%s--[y = %d]',cstem,tree(1))); else d = tree{1}; add = sprintf('--[x(%d) < %g]-+',d(1),d(2)); b = blanks(length(add)-1); pre = sprintf('%s%s|',lstem,b); curr = sprintf('%s%s/',lstem,b); post = sprintf('%s%s ',lstem,b); printdthelp(tree{2},post,curr,pre); d = tree{1}; disp([lstem b 'Y']); disp([cstem add]); disp([rstem b 'N']); pre = sprintf('%s%s|',rstem,b); curr = sprintf('%s%s\\',rstem,b); post = sprintf('%s%s ',rstem,b); printdthelp(tree{3},pre,curr,post); end;
github
hagaygarty/mdCNN-master
backPropagate.m
.m
mdCNN-master/mdCNN/backPropagate.m
8,457
utf_8
bcd7467161d20ee1784bf0b1966df388
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Copyright (C) 2015-16 Hagay Garty. % [email protected] , mdCNN library %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [net] = backPropagate(net, input, expectedOut) % 3 steps to doing back prop , first is feedForward, second is calculating the % errors , third is calculating the derivitives % The conv in the code below is calculated using FFT. This is much faster net = feedForward(net, input , 0); batchNum=size(input,length(net.layers{1}.properties.sizeOut)+1); assert(isequal(size(expectedOut) , size(net.layers{end}.outs.activation))); net.layers{end}.error = net.layers{end}.properties.lossFunc(net.layers{end}.outs.activation,expectedOut); %% calculate the errors on every layer for k=size(net.layers,2)-1:-1:2 % reshape the error to match the layer out type net.layers{k}.error = net.layers{k+1}.error; %pass through activation net.layers{k}.error =net.layers{k}.error.*net.layers{k}.properties.dActivation(net.layers{k}.outs.z); if (net.layers{k}.properties.dropOut~=1) net.layers{k}.error = net.layers{k}.outs.dropout.*net.layers{k}.error;%dropout end %calc dW switch net.layers{k}.properties.type case net.types.softmax net.layers{k}.error =(net.layers{k}.outs.sumExp.*net.layers{k}.error- repmat(sumDim(net.layers{k}.outs.expIn.*net.layers{k}.error, 1:length(net.layers{k}.properties.sizeOut)),net.layers{k}.properties.sizeOut) ).*net.layers{k}.outs.expIn./net.layers{k}.outs.sumExp.^2; case net.types.fc net.layers{k}.dW = [reshape(net.layers{k-1}.outs.activation, [], batchNum) ; ones(1,batchNum) ]*reshape(net.layers{k}.error, [], batchNum).' ; net.layers{k}.error = net.layers{k}.fcweight(1:(end-1),:)*reshape(net.layers{k}.error, [], batchNum); net.layers{k}.error = reshape(net.layers{k}.error,[net.layers{k-1}.properties.sizeOut batchNum]); case net.types.batchNorm N = numel(net.layers{k+1}.error)/numel(net.layers{k}.outs.batchMean); net.layers{k}.dbeta = sum(net.layers{k}.error,length(net.layers{k}.properties.sizeOut)+1); net.layers{k}.dgamma = sum(net.layers{k}.error.*net.layers{k}.outs.Xh,length(net.layers{k}.properties.sizeOut)+1); net.layers{k}.error = repmat(net.layers{k}.gamma./sqrt(net.layers{k}.properties.EPS+net.layers{k}.outs.batchVar)/N , [ones(1,length(net.layers{k}.properties.sizeOut)) batchNum]).* (N*reshape(net.layers{k}.error,size(net.layers{k}.outs.Xh))- repmat(net.layers{k}.dgamma,[ones(1,length(net.layers{k}.properties.sizeOut)) batchNum]).*net.layers{k}.outs.Xh - repmat(net.layers{k}.dbeta,[ones(1,length(net.layers{k}.properties.sizeOut)) batchNum]) ); case net.types.reshape net.layers{k}.error = reshape(net.layers{k}.error,[net.layers{k-1}.properties.sizeOut batchNum]); case net.types.conv %expand with pooling if ( ~isempty(find(net.layers{k}.properties.pooling>1, 1))) %pooling exist nextErrors = zeros([floor((net.layers{k-1}.properties.sizeFm+2*net.layers{k}.properties.pad-net.layers{k}.properties.kernel)./net.layers{k}.properties.stride)+1 net.layers{k}.properties.numFm batchNum]); indexes = reshape(repmat((0:batchNum-1),length(net.layers{k}.properties.offsets),1),1,length(net.layers{k}.properties.offsets),batchNum)*numel(nextErrors)/batchNum + (net.layers{k}.properties.indexesIncludeOutBounds(net.layers{k}.outs.maxIdx + repmat(net.layers{k}.properties.offsets,1,1,batchNum) )); %indexes for fast pooling expansion nextErrors(indexes) = net.layers{k}.error; net.layers{k}.error = nextErrors; end % update weights net.layers{k}.biasdW = squeeze(sum(sum(sum(sum(net.layers{k}.error,1),2),3),5)); prevLayerOutput = net.layers{k-1}.outs.activation; if ( ~isempty(find(net.layers{k}.properties.pad>0, 1))) prevLayerOutput = padarray(prevLayerOutput, [net.layers{k}.properties.pad 0 0], 0 ); end szPrevOutput=net.layers{k-1}.properties.sizeFm+2*net.layers{k}.properties.pad; szOutput=net.layers{k-1}.properties.sizeFm+2*net.layers{k}.properties.pad-net.layers{k}.properties.kernel+1; %flip and expand with stride of net.layers{k}.error kernelFFT = zeros([szOutput net.layers{k}.properties.numFm batchNum]); kernelFFT( end+1-(1:net.layers{k}.properties.stride(1):end) , end+1-( 1:net.layers{k}.properties.stride(2):end), end+1-( 1:net.layers{k}.properties.stride(3):end),:,:) = net.layers{k}.error; prevLayerOutputFFT = prevLayerOutput; for dim=1:net.layers{k}.properties.inputDim prevLayerOutputFFT = fft(prevLayerOutputFFT,[],dim); kernelFFT = fft(kernelFFT,szPrevOutput(dim),dim); end for fm=1:net.layers{k}.properties.numFm im = prevLayerOutputFFT.*repmat(kernelFFT(:,:,:,fm,:),1,1,1,net.layers{k-1}.properties.numFm); for dim=1:net.layers{k}.properties.inputDim im = ifft(im,[],dim); end im=real(im); net.layers{k}.dW{fm} = sum ( im( (end-(szPrevOutput(1)-szOutput(1))):end , (end-(szPrevOutput(2)-szOutput(2))):end , (end-(szPrevOutput(3)-szOutput(3))):end , : ,:), 5); end if (net.properties.skipLastLayerErrorCalc==0) || (k>2) % to save cycles no need to propogate to input layer szNextError=net.layers{k-1}.properties.sizeFm+2*net.layers{k}.properties.pad-net.layers{k}.properties.kernel+1; szNextKernel=net.layers{k}.properties.kernel; %expand with stride of net.layers{k}.error if ( ~isempty(find(net.layers{k}.properties.stride>1, 1))) nextErrors = zeros([szNextError net.layers{k}.properties.numFm batchNum]); nextErrors( (1:net.layers{k}.properties.stride(1):end) , ( 1:net.layers{k}.properties.stride(2):end), ( 1:net.layers{k}.properties.stride(3):end),:,:) = net.layers{k}.error; net.layers{k}.error=nextErrors; end nextErrorFFT = zeros([(szNextError+szNextKernel-1) net.layers{k}.properties.numFm batchNum]); kernelFFT= zeros([(szNextError+szNextKernel-1) net.layers{k}.properties.numFm net.layers{k-1}.properties.numFm]); flipMat = net.layers{k}.flipMat; for nextFm=1:net.layers{k}.properties.numFm sz=size(net.layers{k}.error); sz = (szNextError+szNextKernel-1) - sz(1:length(szNextError+szNextKernel-1)); im=padarray(net.layers{k}.error(:,:,:,nextFm,:),sz,'post'); for dim=1:net.layers{k}.properties.inputDim im = fft(im,[],dim); end nextErrorFFT(:,:,:,nextFm,:) = im; kernelFFT(:,:,:,nextFm,:)=net.layers{k}.weightFFT{nextFm}.*flipMat; end kernelFFT = conj(kernelFFT); net.layers{k}.error = zeros([(szNextError+szNextKernel-1) net.layers{k-1}.properties.numFm batchNum]); for fm=1:net.layers{k-1}.properties.numFm Im=sum(nextErrorFFT.*repmat(kernelFFT(:,:,:,:,fm),[ones(1,ndims(nextErrorFFT)-1) batchNum]),4); for dim=1:net.layers{k}.properties.inputDim-1 Im = ifft(Im,[],dim); end Im = ifft(Im,[],net.layers{k}.properties.inputDim,'symmetric'); net.layers{k}.error(:,:,:,fm,:)= Im; end if ( ~isempty(find(net.layers{k}.properties.pad>0, 1))) net.layers{k}.error= net.layers{k}.error( (1+net.layers{k}.properties.pad(1)):(end-net.layers{k}.properties.pad(1)) , (1+net.layers{k}.properties.pad(2)):(end-net.layers{k}.properties.pad(2)) , (1+net.layers{k}.properties.pad(3)):(end-net.layers{k}.properties.pad(3)) ,:,:); end end end end end
github
hagaygarty/mdCNN-master
updateWeights.m
.m
mdCNN-master/mdCNN/updateWeights.m
2,586
utf_8
bf040d1713087d37a52fabe31522d1dd
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Copyright (C) 2015-16 Hagay Garty. % [email protected] , mdCNN library %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ net ] = updateWeights(net, ni, momentum , lambda ) batchNum=net.hyperParam.batchNum; %update network weights for k=size(net.layers,2):-1:1 if (net.layers{k}.properties.numWeights==0) continue; end if (isequal(net.layers{k}.properties.type,net.types.batchNorm)) % is batchnorm layer net.layers{k}.gamma = net.layers{k}.gamma - ni * net.layers{k}.properties.niFactor / batchNum * net.layers{k}.dgamma; net.layers{k}.beta = net.layers{k}.beta - ni * net.layers{k}.properties.niFactor / batchNum * net.layers{k}.dbeta; elseif (isequal(net.layers{k}.properties.type,net.types.fc)) % is fully connected layer if (lambda~=0) weightDecay = ones(size(net.layers{k}.fcweight)); weightDecay(1:(end-1),:) = (1-lambda*ni);%do not decay bias net.layers{k}.fcweight = weightDecay.*net.layers{k}.fcweight;%weight decay end if (momentum~=0) net.layers{k}.momentum = momentum*net.layers{k}.momentum - ni/batchNum*net.layers{k}.dW; net.layers{k}.fcweight = net.layers{k}.fcweight + net.layers{k}.momentum; else net.layers{k}.fcweight = net.layers{k}.fcweight - ni/batchNum*net.layers{k}.dW; end else for fm=1:net.layers{k}.properties.numFm if (momentum~=0) net.layers{k}.momentum{fm} = momentum * net.layers{k}.momentum{fm} - ni/batchNum*net.layers{k}.dW{fm}; net.layers{k}.weight{fm} = (1-lambda*ni)*net.layers{k}.weight{fm} + net.layers{k}.momentum{fm}; else net.layers{k}.weight{fm} = (1-lambda*ni)*net.layers{k}.weight{fm} - ni/batchNum*net.layers{k}.dW{fm}; end net.layers{k}.weightFFT{fm} = net.layers{k}.weight{fm}; for dim=1:net.layers{k}.properties.inputDim net.layers{k}.weightFFT{fm} = fft(flip(net.layers{k}.weightFFT{fm},dim),(net.layers{k-1}.properties.sizeFm(dim)+2*net.layers{k}.properties.pad(dim)),dim); end end if (momentum~=0) net.layers{k}.momentumBias = momentum * net.layers{k}.momentumBias - ni/batchNum*net.layers{k}.biasdW; net.layers{k}.bias = net.layers{k}.bias + net.layers{k}.momentumBias; else net.layers{k}.bias = net.layers{k}.bias - ni/batchNum*net.layers{k}.biasdW; end end end end
github
hagaygarty/mdCNN-master
initNetWeight.m
.m
mdCNN-master/mdCNN/initNetWeight.m
19,858
utf_8
383e2a17025ca64a0f8b212d87292a05
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Copyright (C) 2015-16 Hagay Garty. % [email protected] , mdCNN library %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ net ] = initNetWeight( net ) rng(0); fprintf('multi dimentional CNN , Hagay Garty 2016 | [email protected]\nInitializing network..\n'); %init W prevLayerActivation=1; %for input net.properties.numWeights = 0; assert( isequal(net.layers{1}.properties.type,net.types.input), 'Error - first layer must be input layer (type =-2)'); assert( isequal(net.layers{1}.properties.sizeFm(net.layers{1}.properties.sizeFm>0),net.layers{1}.properties.sizeFm), 'Error - sizeFm cannot have dim 0'); assert( ((length(net.layers{1}.properties.sizeFm)==1) || (isequal(net.layers{1}.properties.sizeFm(net.layers{1}.properties.sizeFm>1),net.layers{1}.properties.sizeFm))), 'Error - sizeFm cannot have useless 1 dims'); assert( isfield(net.layers{1}.properties,'numFm'), 'Error - numFm is not defined in first layer. Example: for 32x32 rgb please set to numFm=3'); assert( isempty(find(net.layers{1}.properties.sizeFm<1, 1)), 'Error - sizeFm must be >=1 for all dimensions'); assert( ((~isempty(net.layers{1}.properties.sizeFm)) && (length(net.layers{1}.properties.sizeFm)<=3)), 'Error - num of dimensions must be >0 and <=3'); assert( isfield(net.layers{1}.properties,'sizeFm'), 'Error - sizeFm is not defined in hyperParam. Example: for 32x32 rgb please set to [32 32] , numFm=3'); assert( length(net.layers{1}.properties.sizeFm)<=3, 'Error - sizeFm cannot have more then 3 dimensions'); assert( isequal(net.layers{end}.properties.type,net.types.output), 'Error - last layer must be output layer'); net.layers{1}.properties.sizeFm = [net.layers{1}.properties.sizeFm 1 1 1]; net.layers{1}.properties.sizeFm = net.layers{1}.properties.sizeFm(1:3); net.layers{1}.properties.numWeights = 0; if (isscalar(net.hyperParam.augmentParams.maxStride)) net.hyperParam.augmentParams.maxStride = net.hyperParam.augmentParams.maxStride*ones(1,length(net.layers{1}.properties.sizeFm)).*(net.layers{1}.properties.sizeFm>1); end for k=1:size(net.layers,2) assert( isfield(net.layers{k}.properties,'type')==1, 'Error - missing type definition in layer %d',k); fprintf('Initializing layer %d - %s\n',k,net.layers{k}.properties.type); switch net.layers{k}.properties.type case net.types.input assert(k==1,'Error input layer must be the first layer (%d)\n',k); if (isfield(net.layers{k}.properties,'Activation')==0) net.layers{k}.properties.Activation=@Unit; end if (isfield(net.layers{k}.properties,'dActivation')==0) net.layers{k}.properties.dActivation=@dUnit; end net.layers{k}.properties.sizeOut = [net.layers{k}.properties.sizeFm net.layers{k}.properties.numFm]; case net.types.softmax net.layers{k}.properties.numFm = net.layers{k-1}.properties.numFm; if (isfield(net.layers{k}.properties,'Activation')==0) net.layers{k}.properties.Activation=@Unit; end if (isfield(net.layers{k}.properties,'dActivation')==0) net.layers{k}.properties.dActivation=@dUnit; end case net.types.fc case net.types.reshape if (isfield(net.layers{k}.properties,'Activation')==0) net.layers{k}.properties.Activation=@Unit; end if (isfield(net.layers{k}.properties,'dActivation')==0) net.layers{k}.properties.dActivation=@dUnit; end case net.types.conv case net.types.batchNorm assert( isfield(net.layers{k}.properties,'numFm')==0, 'Error - no need to specify numFm in batchnorm layer, its inherited from previous layer. in layer %d',k); assert( net.hyperParam.batchNum>=2, 'Error - cannot use batch norm layer if batchSize<2. in layer %d',k); net.layers{k}.properties.numFm = net.layers{k-1}.properties.numFm; if (isfield(net.layers{k}.properties,'EPS')==0) net.layers{k}.properties.EPS=1e-5; end if (isfield(net.layers{k}.properties,'niFactor')==0) net.layers{k}.properties.niFactor=1; end if (isfield(net.layers{k}.properties,'Activation')==0) net.layers{k}.properties.Activation=@Unit; end if (isfield(net.layers{k}.properties,'dActivation')==0) net.layers{k}.properties.dActivation=@dUnit; end if (isfield(net.layers{k}.properties,'initGamma')==0) net.layers{k}.properties.initGamma = 1; end net.layers{k}.gamma=net.layers{k}.properties.initGamma * ones([net.layers{k-1}.properties.sizeFm net.layers{k-1}.properties.numFm]); if (isfield(net.layers{k}.properties,'initBeta')==0) net.layers{k}.properties.initBeta = 0; end net.layers{k}.beta=net.layers{k}.properties.initBeta * ones([net.layers{k-1}.properties.sizeFm net.layers{k-1}.properties.numFm]); net.layers{k}.properties.numWeights = numel(net.layers{k}.gamma)+numel(net.layers{k}.beta); if (isfield(net.layers{k}.properties,'alpha')==0) net.layers{k}.properties.alpha=2^-5; end assert( (net.layers{k}.properties.alpha<=1)&&(net.layers{k}.properties.alpha>=0),'alpha must be in the range [0 .. 1], layer %d\n',k); net.layers{k}.outs.runningBatchMean = []; net.layers{k}.outs.runningBatchVar = []; case net.types.output assert(k==size(net.layers,2),'Error - output layer must be the last layer, layer (%d)\n',k); net.layers{k}.properties.sizeFm = net.layers{k-1}.properties.sizeFm; net.layers{k}.properties.numFm = net.layers{k-1}.properties.numFm; net.layers{k}.properties.sizeOut = [net.layers{k}.properties.sizeFm net.layers{k}.properties.numFm]; net.layers{k}.properties.Activation=@Unit; net.layers{k}.properties.dActivation=@dUnit; continue; otherwise assert(false,'Error - unknown layer type %s in layer %d\n',net.layers{k}.properties.type,k); end assert( isfield(net.layers{k}.properties,'numFm')==1, 'Error - missing numFM definition in layer %d',k); if (isfield(net.layers{k}.properties,'dropOut')==0) net.layers{k}.properties.dropOut=1; end if (isfield(net.layers{k}.properties,'Activation')==0) net.layers{k}.properties.Activation=@Sigmoid; end if (isfield(net.layers{k}.properties,'dActivation')==0) net.layers{k}.properties.dActivation=@dSigmoid; end assert(((net.layers{k}.properties.dropOut<=1) &&(net.layers{k}.properties.dropOut>0)) ,'Dropout must be >0 and <=1 in layer %d',k); switch net.layers{k}.properties.type case net.types.input continue; case net.types.softmax net.layers{k}.properties.sizeFm = net.layers{k-1}.properties.sizeFm; case net.types.fc net.layers{k}.properties.sizeFm = 1; case net.types.batchNorm net.layers{k}.properties.sizeFm = net.layers{k-1}.properties.sizeFm; case net.types.reshape net.layers{k}.properties.sizeFm = [net.layers{k}.properties.sizeFm 1 1 1]; net.layers{k}.properties.sizeFm = net.layers{k}.properties.sizeFm(1:3); assert( prod(net.layers{k}.properties.sizeFm)*net.layers{k}.properties.numFm == prod(net.layers{k-1}.properties.sizeOut), 'Error - reshape must have the same num of elements as the layer before (%d != %d), layer %d\n',prod(net.layers{k}.properties.sizeFm)*net.layers{k}.properties.numFm , prod(net.layers{k-1}.properties.sizeOut),k); case net.types.conv net.layers{k}.properties.inputDim = max(1,sum(net.layers{k-1}.properties.sizeFm>1)); assert( ((isfield(net.layers{k}.properties,'pad')==0) || (length(net.layers{k}.properties.pad)==1) || (length(net.layers{k}.properties.pad)==net.layers{k}.properties.inputDim) ) , 'Error - pad can be a scalar or a vector with length as num dimnetions (%d), layer=%d',net.layers{k}.properties.inputDim,k); assert( ((isfield(net.layers{k}.properties,'stride')==0) || (length(net.layers{k}.properties.stride)==1) || (length(net.layers{k}.properties.stride)==net.layers{k}.properties.inputDim) ) , 'Error - stride can be a scalar or a vector with length as num dimnetions (%d), layer=%d',net.layers{k}.properties.inputDim,k); assert( ((isfield(net.layers{k}.properties,'pooling')==0)|| (length(net.layers{k}.properties.pooling)==1) || (length(net.layers{k}.properties.pooling)==net.layers{k}.properties.inputDim) ), 'Error - pooling can be a scalar or a vector with length as num dimnetions (%d), layer=%d',net.layers{k}.properties.inputDim,k); if (isfield(net.layers{k}.properties,'stride')==0) net.layers{k}.properties.stride=ones(1,sum(net.layers{k-1}.properties.sizeFm>1)); end if (isfield(net.layers{k}.properties,'pad')==0) net.layers{k}.properties.pad=zeros(1,sum(net.layers{k-1}.properties.sizeFm>1)); end if (isfield(net.layers{k}.properties,'pooling')==0) net.layers{k}.properties.pooling=ones(1,sum(net.layers{k-1}.properties.sizeFm>1)); end %sanity checks assert( isfield(net.layers{k}.properties,'kernel')==1, 'Error - missing kernel definition in layer %d',k); if (isscalar(net.layers{k}.properties.kernel)) net.layers{k}.properties.kernel = net.layers{k}.properties.kernel*ones(1,sum(net.layers{k-1}.properties.sizeFm>1)); end %pad default settings if (isscalar(net.layers{k}.properties.pad)) net.layers{k}.properties.pad = net.layers{k}.properties.pad*ones(1,sum(net.layers{k-1}.properties.sizeFm>1)); end net.layers{k}.properties.pad = [net.layers{k}.properties.pad 0 0 0]; net.layers{k}.properties.pad = net.layers{k}.properties.pad(1:3); net.layers{k}.properties.kernel = [net.layers{k}.properties.kernel 1 1 1]; net.layers{k}.properties.kernel = net.layers{k}.properties.kernel(1:3); %pooling default settings if (isscalar(net.layers{k}.properties.pooling)) net.layers{k}.properties.pooling = net.layers{k}.properties.pooling*ones(1,sum(net.layers{k-1}.properties.sizeFm>1)); end net.layers{k}.properties.pooling = [net.layers{k}.properties.pooling 1 1 1]; net.layers{k}.properties.pooling = net.layers{k}.properties.pooling(1:3); net.layers{k}.properties.pooling = min(net.layers{k}.properties.pooling ,net.layers{k-1}.properties.sizeFm); %stride default settings if (isscalar(net.layers{k}.properties.stride)) net.layers{k}.properties.stride = net.layers{k}.properties.stride*ones(1,sum(net.layers{k-1}.properties.sizeFm>1)); end net.layers{k}.properties.stride = [net.layers{k}.properties.stride 1 1 1]; net.layers{k}.properties.stride = net.layers{k}.properties.stride(1:3); net.layers{k}.properties.stride = min(net.layers{k}.properties.stride ,net.layers{1}.properties.sizeFm); assert( isempty(find(net.layers{k}.properties.pooling<1, 1)), 'Error - pooling must be >=1 for all dimensions, layer=%d',k); assert( isempty(find(net.layers{k}.properties.kernel<1, 1)) , 'Error - kernel must be >=1 for all dimensions, layer=%d',k); assert( isempty(find(net.layers{k}.properties.stride<1, 1)) , 'Error - stride must be >=1 for all dimensions, layer=%d',k); assert( isempty(find(net.layers{k}.properties.pad<0, 1)) , 'Error - pad must be >=0 for all dimensions, layer=%d',k); assert( (net.layers{k}.properties.dropOut<=1 && net.layers{k}.properties.dropOut>0), 'Error - dropOut must be >0 and <=1, layer=%d, dropOut=%d',k,net.layers{k}.properties.dropOut); assert( isempty(find(net.layers{k-1}.properties.sizeFm+2*net.layers{k}.properties.pad<net.layers{k}.properties.kernel, 1)) , 'Error - kernel too large (%s), must be smaller then prev layer FM size (%s) plus pad (%s), layer=%d',... num2str(net.layers{k}.properties.kernel) , num2str(net.layers{k-1}.properties.sizeFm) , num2str(net.layers{k}.properties.pad) ,k ); assert( isempty(find(net.layers{k}.properties.pad>=net.layers{k}.properties.kernel, 1)) , 'Error - pad too large (%s), must be smaller then kernel size (%s), layer=%d',... num2str(net.layers{k}.properties.pad),num2str(net.layers{k}.properties.kernel),k); [f,~] = log2(net.layers{k-1}.properties.sizeFm+2*net.layers{k}.properties.pad); if (~isempty(find(f~=0.5, 1))) warning(['Layer ' num2str(k) ' input plus pad is ' ... num2str(net.layers{k-1}.properties.sizeFm+2*net.layers{k}.properties.pad) ... ' , not a power of 2. May reduce speed']); end net.layers{k}.properties.sizeFm = ceil((floor((net.layers{k-1}.properties.sizeFm+2*net.layers{k}.properties.pad-net.layers{k}.properties.kernel)./net.layers{k}.properties.stride)+1)./net.layers{k}.properties.pooling); end if (~isequal(net.layers{k}.properties.type,net.types.conv)) % not conv numNewronsInPrevLayer = net.layers{k-1}.properties.numFm*prod(net.layers{k-1}.properties.sizeFm); numInputs=numNewronsInPrevLayer+1; if (isequal(net.layers{k}.properties.type,net.types.fc)) net.layers{k}.fcweight = normrnd(0,1/sqrt(numInputs*prevLayerActivation),numInputs,net.layers{k}.properties.numFm);% add one for bias net.layers{k}.momentum = net.layers{k}.fcweight * 0; if (~isnan(net.hyperParam.constInitWeight)) net.layers{k}.fcweight = net.layers{k}.fcweight*0+net.hyperParam.constInitWeight; end net.layers{k}.properties.numWeights = numel(net.layers{k}.fcweight); elseif (isequal(net.layers{k}.properties.type,net.types.batchNorm)) %batchnorm else net.layers{k}.properties.numWeights = 0; % softmax end else % is conv layer net.layers{k}.properties.numWeights = 0; for fm=1:net.layers{k}.properties.numFm for prevFm=1:net.layers{k-1}.properties.numFm numInputs=net.layers{k-1}.properties.numFm*prod(net.layers{k}.properties.kernel)+1; net.layers{k}.weight{fm}(:,:,:,prevFm) = normrnd(0,1/sqrt(numInputs*prevLayerActivation),net.layers{k}.properties.kernel); net.layers{k}.momentum{fm}(:,:,:,prevFm) = net.layers{k}.weight{fm}(:,:,:,prevFm) * 0; if (~isnan(net.hyperParam.constInitWeight)) net.layers{k}.weight{fm}(:,:,:,prevFm) = net.hyperParam.constInitWeight+0*net.layers{k}.weight{fm}(:,:,:,prevFm); end net.layers{k}.weightFFT{fm}(:,:,:,prevFm) = fftn(flip(flip(flip(net.layers{k}.weight{fm}(:,:,:,prevFm),1),2),3) , (net.layers{k-1}.properties.sizeFm+2*net.layers{k}.properties.pad)); net.layers{k}.properties.numWeights = net.layers{k}.properties.numWeights + numel(net.layers{k}.weight{fm}(:,:,:,prevFm)); end end fftWeightFlipped = conj(fftn(net.layers{k}.weight{1}(:,:,:,1) , (net.layers{k-1}.properties.sizeFm+2*net.layers{k}.properties.pad))); net.layers{k}.flipMat = repmat(fftWeightFlipped./net.layers{k}.weightFFT{1}(:,:,:,1) , [1 1 1 net.layers{k-1}.properties.numFm]); %bias val numInputs=net.layers{k-1}.properties.numFm*prod(net.layers{k}.properties.kernel)+1; net.layers{k}.bias = normrnd(0,1/sqrt(numInputs*prevLayerActivation),net.layers{k}.properties.numFm,1);% add one for bias if (~isnan(net.hyperParam.constInitWeight)) net.layers{k}.bias = net.hyperParam.constInitWeight+0*net.layers{k}.bias; end net.layers{k}.momentumBias = net.layers{k}.bias * 0 ; net.layers{k}.properties.numWeights = net.layers{k}.properties.numWeights + numel(net.layers{k}.bias); %%%%%% stride looksups , the below is used to speed performance for dim=1:3 net.layers{k}.properties.indexesStride{dim} = net.layers{k}.properties.kernel(dim):net.layers{k}.properties.stride(dim):(net.layers{k-1}.properties.sizeFm(dim)+2*net.layers{k}.properties.pad(dim)); end %%%%%% pooling looksups , the below is nasty code:) but done only during initialization if ( ~isempty(find(net.layers{k}.properties.pooling>1, 1))) %pooling exist net.layers{k}.properties.indexes=[]; net.layers{k}.properties.indexesIncludeOutBounds=[]; net.layers{k}.properties.indexesReshape=[]; elemSize = prod(net.layers{k}.properties.pooling); net.layers{k}.properties.offsets = ((1:(prod([net.layers{k}.properties.sizeFm net.layers{k}.properties.numFm]))) -1 )*elemSize; %init some indexes for optimized access during %feedForward/Backprop ranges=floor((net.layers{k-1}.properties.sizeFm+2*net.layers{k}.properties.pad-net.layers{k}.properties.kernel)./net.layers{k}.properties.stride)+1; for fm=1:net.layers{k}.properties.numFm for row=1:prod(net.layers{k}.properties.sizeFm) [y,x,z] = ind2sub(net.layers{k}.properties.sizeFm, row); for col=1:prod(net.layers{k}.properties.pooling) [yy,xx,zz] = ind2sub(net.layers{k}.properties.pooling, col); net.layers{k}.properties.indexesIncludeOutBounds(end+1) = (fm-1) *prod(ranges(1:3)) +... ((zz-1)+(z-1)*net.layers{k}.properties.pooling(3))*prod(ranges(1:2)) +... ((xx-1)+(x-1)*net.layers{k}.properties.pooling(2))*prod(ranges(1:1)) +... ((yy-1)+(y-1)*net.layers{k}.properties.pooling(1)) + ... 1; if ( isempty(find( ... ((([yy xx zz]-1)+([y x z]-1).*net.layers{k}.properties.pooling)+1) > ranges, 1 ))) net.layers{k}.properties.indexes(end+1) = net.layers{k}.properties.indexesIncludeOutBounds(end); net.layers{k}.properties.indexesReshape(end+1) = (col-1) + (row+(fm-1)*prod(net.layers{k}.properties.sizeFm)-1)*prod(net.layers{k}.properties.pooling) + 1; end end end end end end assert(isfield(net.layers{k}.properties,'sizeFm') , 'Error - missing sizeFm field in layer %d\n',k); assert(isfield(net.layers{k}.properties,'numFm') , 'Error - missing numFm field in layer %d\n',k); net.properties.numWeights = net.properties.numWeights + net.layers{k}.properties.numWeights; prevLayerActivation = net.layers{k}.properties.dropOut; net.layers{k}.properties.sizeOut = [net.layers{k}.properties.sizeFm net.layers{k}.properties.numFm]; end net.layers{end}.properties.numFm = net.layers{end-1}.properties.numFm; net.layers{end}.properties.numWeights = 0; assert(net.layers{end-1}.properties.dropOut==1,'Last layer must be with dropout=1'); end
github
hagaygarty/mdCNN-master
CreateNet.m
.m
mdCNN-master/mdCNN/CreateNet.m
4,684
utf_8
2c6cff6f4845ff272e1e2ddc6ed1d5df
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Copyright (C) 2015-16 Hagay Garty. % [email protected] , mdCNN library %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ net ] = CreateNet( conf_file ) %% Constructor for net struct , loads the configuration from conf_file net = initNetDefaults; txt=fileread(conf_file); eval(txt); net.properties.numLayers = length(net.layers); net.properties.version = 2.3; conf_dirStruct = dir(conf_file); conf_dirStruct.name=conf_file; net.properties.sources{1}=[dir('./*.m') ; dir('./Util/*.m') ; conf_dirStruct]; for i=1:length(net.properties.sources{1}) net.properties.sources{1}(i).data = fileread(net.properties.sources{1}(i).name); end net.runInfoParam.iter=0; net.runInfoParam.samplesLearned=0; net.runInfoParam.maxsucessRate=0; net.runInfoParam.noImprovementCount=0; net.runInfoParam.minLoss=Inf; net.runInfoParam.improvementRefLoss=inf; net = initNetWeight(net); net.properties.numOutputs = prod(net.layers{end}.properties.sizeOut); net.runInfoParam.endSeed = rng; printNetwork(net); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ net ] = initNetDefaults( net ) net.hyperParam.trainLoopCount=1000;%on how many samples to train before evaluating the network net.hyperParam.testImageNum=2000; net.hyperParam.batchNum = 1; % on how many samples to average weights update net.hyperParam.ni_initial = 0.05;% ni to start training process net.hyperParam.ni_final = 0.00001;% final ni to stop the training process net.hyperParam.noImprovementTh=50; % if after noImprovementTh there is no improvement , reduce ni net.hyperParam.momentum=0; net.hyperParam.constInitWeight=nan; %Use nan to set initial weight to random. Any other value to fixed net.hyperParam.lambda=0; %L2 regularization factor, set 0 for none. Above 0.01 not recommended net.hyperParam.testOnData=0; % to perform testing after each epoc on the data inputs or test inputs net.hyperParam.addBackround=0; % random background can be added to samples before passing to net in order to improve noise resistance. net.hyperParam.testOnNull=0;% Training on non data images without any feature to detect net.properties.skipLastLayerErrorCalc=1; % the input layer does not need errors hence calculation can be skipped %%%%%%%%%%%%%% Augmentation %%%%%%%%%%%%%% net.hyperParam.augmentImage=0; % set to 0 for no augmentation net.hyperParam.augmentParams.noiseVar=0.02; net.hyperParam.augmentParams.maxAngle=45/3; net.hyperParam.augmentParams.maxScaleFactor=1.1; net.hyperParam.augmentParams.minScaleFactor=1/1.5; net.hyperParam.augmentParams.maxStride=4; net.hyperParam.augmentParams.maxSigma=2;%for gauss filter smoothing net.hyperParam.augmentParams.imageComplement=0;% will reverse black/white of the image net.hyperParam.augmentParams.medianFilt=0; %between 0 and one - if this value is 0.75 it will zero all 75% lower points. 0 will mean no point is changed, 1 will keep the higest point only %%%%%%%%%%%%%% Centralize image before passing to net? %%%%%%%%%%%%%% net.hyperParam.centralizeImage=0; net.hyperParam.cropImage=0; net.hyperParam.flipImage=0; % fill randomly flip the input hor/vert before passing to the network. Improves learning in some instances net.hyperParam.useRandomPatch=0; net.hyperParam.testNumPatches=1; % on how many patches from a single image to perform testing. network is evaluated on several patches and result is averaged over all patches. net.hyperParam.selevtivePatchVarTh=0; %in order to drop patches that their variance is less then th net.hyperParam.testOnMiddlePatchOnly=0; %will test on the middle patch only net.hyperParam.normalizeNetworkInput=1; %will normalize every input to net to be with var=1, mean 0 net.hyperParam.randomizeTrainingSamples=1; % randomize the samples selected from dataset during training %%%%%%%%%%%%%% Run info - parameters that change every iteration %%%%%%%%%%%%%% net.runInfoParam.storeMinLossNet= 0; % this enables the trainer to store also the net with the lowest loss and max success rate found (in addition to the latest one) net.runInfoParam.verifyBP = 1; % can perform pre-train back-propagation verification. Useful to detect faults in the application %%%%%%%%%%%%%% types %%%%%%%%%%%%%% net.layers={}; net.types.input='input'; net.types.fc='fc'; net.types.conv='conv'; net.types.batchNorm='batchNorm'; net.types.output='output'; net.types.softmax='softmax'; net.types.reshape='reshape'; end
github
hagaygarty/mdCNN-master
verifyBackProp.m
.m
mdCNN-master/mdCNN/verifyBackProp.m
8,649
utf_8
6137d6dfa243eaf12da18b19c76cfa8f
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Copyright (C) 2015-16 Hagay Garty. % [email protected] , mdCNN library %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ ] = verifyBackProp(net) %% verification of network correctnes. Search for implementation errors by verifying the derivitives calculated by backProp are correct %% the function will verify backProp on some of the weights, (selected randomly) initSeed = rng; fprintf('Verifying backProp..\n'); batchNum=net.hyperParam.batchNum; input = normrnd(0,1, [net.layers{1}.properties.sizeFm net.layers{1}.properties.numFm batchNum]); net = feedForward(net, input, 0); expectedOut=net.layers{end}.outs.activation; expectedOut(expectedOut>0.5) = expectedOut(expectedOut>0.5)*0.99; expectedOut(expectedOut<0.5) = expectedOut(expectedOut<0.5)*1.01; expectedOut(expectedOut==0) = 0.001; rng(initSeed); % create calculated dCdW net = backPropagate(net, input, expectedOut); %create W+dW dw=1*10^-9.5; th = 1e-4; numIter=1; diffs=cell(length(net.layers),1); grads=diffs; diffsBias=grads; startVerification=clock; Cost = net.layers{end}.properties.costFunc(net.layers{end}.outs.activation,expectedOut); for k=1:size(net.layers,2) fprintf('Checking layer %-2d - %-10s ',k,net.layers{k}.properties.type); estimateddActivation = (net.layers{k}.properties.Activation([-1 1]+dw)-net.layers{k}.properties.Activation([-1 1])); realdActivation = net.layers{k}.properties.dActivation([-1 1]); diffs{k}(end+1) = max(abs(estimateddActivation-realdActivation*dw))/dw; if ( diffs{k}(end) > th) assert(0,'Activation and dActivation do not match!'); end estimatedLoss = ( net.layers{end}.properties.costFunc(1+dw,1)-net.layers{end}.properties.costFunc(1,1) ); realdLoss = net.layers{end}.properties.lossFunc(1,1); diffs{k}(end+1) = abs(estimatedLoss-realdLoss*dw)/dw; if ( diffs{k}(end) > th) assert(0,'costFunc and lossFunc do not match! Should be: lossFunc = d/dx costFunc'); end if (isequal(net.layers{k}.properties.type,net.types.batchNorm)) % only for batchnorm %check beta/gamma for fm=1:net.layers{k}.properties.numFm for iter=1:numIter curIdx = numel(net.layers{k}.dbeta)/net.layers{k}.properties.numFm * (fm-1) + randi(numel(net.layers{k}.dbeta)/net.layers{k}.properties.numFm); calculatedDcDbeta = net.layers{k}.dbeta(curIdx); calculatedDcDGamma = net.layers{k}.dgamma(curIdx); grads{k}(end+1) = calculatedDcDbeta; grads{k}(end+1) = calculatedDcDGamma; % check beta netVerify = net; netVerify.layers{k}.beta(curIdx) = netVerify.layers{k}.beta(curIdx) + dw; seedBefore=rng; rng(initSeed);%to set the same dropout each time.. netPdW = feedForward(netVerify, input, 0); rng(seedBefore); CostPlusDbeta = netPdW.layers{end}.properties.costFunc(netPdW.layers{end}.outs.activation,expectedOut); estimatedDcDbeta = CostPlusDbeta-Cost; diffs{k}(end+1) = abs(sum(estimatedDcDbeta(:))-calculatedDcDbeta*dw)/dw; if ( diffs{k}(end) > sqrt(numel(estimatedDcDbeta))*th) assert(0,'problem in beta gradient'); end % check gamma netVerify = net; netVerify.layers{k}.gamma(curIdx) = netVerify.layers{k}.gamma(curIdx) + dw; seedBefore=rng; rng(initSeed);%to set the same dropout each time.. netPdW = feedForward(netVerify, input, 0); rng(seedBefore); CostPlusDGamma = netPdW.layers{end}.properties.costFunc(netPdW.layers{end}.outs.activation,expectedOut); estimatedDcDgamma = (CostPlusDGamma-Cost); diffs{k}(end+1) = abs(sum(estimatedDcDgamma(:))-calculatedDcDGamma*dw)/dw; if ( diffs{k}(end) > sqrt(numel(estimatedDcDgamma))*th) assert(0,'problem in gamma gradient'); end end end end if (net.layers{k}.properties.numWeights>0) %check weights - fc and conv if (~isequal(net.layers{k}.properties.type,net.types.batchNorm)) % check first fm, last fm and up to 50 in between for fm=[1:ceil(net.layers{k}.properties.numFm/50):net.layers{k}.properties.numFm net.layers{k}.properties.numFm] if (isequal(net.layers{k}.properties.type,net.types.fc)) numprevFm = 1; else numprevFm = size(net.layers{k}.weight{1},4); end for prevFm=[1:ceil(numprevFm/50):numprevFm numprevFm] for iter=1:numIter if (isequal(net.layers{k}.properties.type,net.types.fc)) y=randi(size(net.layers{k}.fcweight,1)); x=randi(size(net.layers{k}.fcweight,2)); calculatedDcDw = net.layers{k}.dW(y,x); else y=randi(size(net.layers{k}.weight{1},1)); x=randi(size(net.layers{k}.weight{1},2)); z=randi(size(net.layers{k}.weight{1},3)); calculatedDcDw = net.layers{k}.dW{fm}(y,x,z,prevFm); end grads{k}(end+1) = calculatedDcDw; netPdW = net; if (isequal(netPdW.layers{k}.properties.type,netPdW.types.fc)) netPdW.layers{k}.fcweight(y,x) = netPdW.layers{k}.fcweight(y,x) + dw; else netPdW.layers{k}.weight{fm}(y,x,z,prevFm) = netPdW.layers{k}.weight{fm}(y,x,z,prevFm) + dw; netPdW.layers{k}.weightFFT{fm}(:,:,:,prevFm) = fftn( flip(flip(flip(netPdW.layers{k}.weight{fm}(:,:,:,prevFm),1),2),3) , (netPdW.layers{k-1}.properties.sizeFm+2*netPdW.layers{k}.properties.pad)); end seedBefore = rng; rng(initSeed);%to set the same dropout each time.. netPdW = feedForward(netPdW, input, 0); rng(seedBefore); cWPlusDw = netPdW.layers{end}.properties.costFunc(netPdW.layers{end}.outs.activation,expectedOut); estimatedDcDw = (cWPlusDw-Cost); diffs{k}(end+1) = abs(sum(estimatedDcDw(:))-calculatedDcDw*dw)/dw; if ( diffs{k}(end) > sqrt(numel(estimatedDcDw))*th ) assert(0,'Problem in weight. layer %d',k); end end end end end end if (isequal(net.layers{k}.properties.type,net.types.conv)) % only for conv %check bias weight for fm=1:net.layers{k}.properties.numFm calculatedDcDw = net.layers{k}.biasdW(fm); grads{k}(end+1) = calculatedDcDw; netPdW = net; netPdW.layers{k}.bias(fm) = netPdW.layers{k}.bias(fm) + dw; seedBefore = rng; rng(initSeed);%to set the same dropout each time.. netPdW = feedForward(netPdW, input, 0); rng(seedBefore); cWPlusDw = netPdW.layers{end}.properties.costFunc(netPdW.layers{end}.outs.activation,expectedOut); estimatedDcDw = (cWPlusDw-Cost); diffsBias{k}(end+1) = abs(sum(estimatedDcDw(:))-calculatedDcDw*dw)/dw; if ( diffsBias{k}(end) > sqrt(numel(estimatedDcDw))*th) assert(0,'Problem in bias weight. layer %d',k); end end end %fprintf('mean diff=%.2e,max diff=%.2e, var diff=%.2e, rmsGrad=%.2e,varGrad=%.2e\n',mean(diffs{k}),max(diffs{k}),var(diffs{k}),rms(grads{k}),var(grads{k})); fprintf('\n'); end endVerification=clock; fprintf('Network is OK. Verification time=%.2f\n',etime(endVerification,startVerification)); rng(initSeed);%revert seed
github
hagaygarty/mdCNN-master
feedForward.m
.m
mdCNN-master/mdCNN/feedForward.m
6,835
utf_8
b48d6306efe3b3598e47fe8768266c86
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Copyright (C) 2015-16 Hagay Garty. % [email protected] , mdCNN library %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ net ] = feedForward(net, input , testTime) %% feedForward - pass a sample throud the net. Returning an array where the first index is the layer num, second is: % 1 - the output of each neuron before activation. % 2 - the output of each neuron after activation. % 3 - selected dropout matrix % 4 - indexes of max pooling (the index of the max value in the pooling section) batchNum=size(input,length(net.layers{1}.properties.sizeOut)+1); net.layers{1}.outs.activation = input; for k=2:size(net.layers,2)-1 input = net.layers{k-1}.outs.activation; switch net.layers{k}.properties.type case net.types.softmax %% softmax layer maxInput = input; for dim=1:length(net.layers{k}.properties.sizeOut) maxInput = max(maxInput,[],dim); end net.layers{k}.outs.expIn = exp(input-repmat(maxInput,net.layers{k}.properties.sizeOut)); net.layers{k}.outs.sumExp=repmat(sumDim(net.layers{k}.outs.expIn, 1:length(net.layers{k}.properties.sizeOut) ) ,net.layers{k}.properties.sizeOut ); net.layers{k}.outs.z =net.layers{k}.outs.expIn./net.layers{k}.outs.sumExp; case net.types.fc %% fully connected layer net.layers{k}.outs.z = reshape(net.layers{k}.fcweight.' * [reshape(input, [], batchNum) ; ones(1,batchNum)], [net.layers{k}.properties.sizeOut batchNum]); case net.types.reshape net.layers{k}.outs.z = reshape(input, [net.layers{k}.properties.sizeOut batchNum]); case net.types.conv %% for conv layers if ( ~isempty(find(net.layers{k}.properties.pad>0, 1))) input = padarray(input, [net.layers{k}.properties.pad 0 0], 0 ); end inputFFT = input; for dim=1:net.layers{k}.properties.inputDim inputFFT = fft(inputFFT,[],dim); end Im=cell([net.layers{k}.properties.numFm 1]); indexesStride = net.layers{k}.properties.indexesStride; i1=indexesStride{1}; i2=indexesStride{2}; i3=indexesStride{3}; wFFT=net.layers{k}.weightFFT; bias=net.layers{k}.bias; for fm=1:net.layers{k}.properties.numFm img = sum(inputFFT.*reshape(repmat(wFFT{fm},[ones(1,ndims(wFFT{fm})) batchNum]),size(inputFFT)),4); for dim=1:net.layers{k}.properties.inputDim-1 img = ifft(img,[],dim); end img = ifft(img,[],net.layers{k}.properties.inputDim,'symmetric'); Im{fm} = bias(fm) + img( i1 , i2 , i3 , : , :); end net.layers{k}.outs.z = cat(4,Im{:}); if ( ~isempty(find(net.layers{k}.properties.pooling>1, 1))) %pooling exist elemSize = prod(net.layers{k}.properties.pooling); szOut=size(net.layers{k}.outs.z); poolMat=-1/eps+zeros([elemSize net.layers{k}.properties.numFm*prod(ceil(szOut(1:4)./[net.layers{k}.properties.pooling net.layers{k}.properties.numFm])) batchNum]); newIndexes=repmat((0:batchNum-1).',1,length(net.layers{k}.properties.indexes))*numel(net.layers{k}.outs.z)/batchNum + repmat(net.layers{k}.properties.indexes,batchNum,1) ; newIndexesReshape=repmat((0:batchNum-1).',1,length(net.layers{k}.properties.indexesReshape))*numel(poolMat)/batchNum + repmat(net.layers{k}.properties.indexesReshape,batchNum,1); poolMat(newIndexesReshape) = net.layers{k}.outs.z(newIndexes); [maxVals, net.layers{k}.outs.maxIdx] = max(poolMat); net.layers{k}.outs.z = reshape(maxVals , [net.layers{k}.properties.sizeFm net.layers{k}.properties.numFm batchNum]); end case net.types.batchNorm %% batchNorm layer if ( testTime ) net.layers{k}.outs.batchMean = net.layers{k}.outs.runningBatchMean; net.layers{k}.outs.batchVar = net.layers{k}.outs.runningBatchVar; else net.layers{k}.outs.batchMean = mean(input,length(net.layers{k}.properties.sizeOut)+1); net.layers{k}.outs.batchVar = mean((input-repmat(net.layers{k}.outs.batchMean, [ones(1,length(net.layers{k}.properties.sizeOut)) batchNum] ) ).^2,length(net.layers{k}.properties.sizeOut)+1) ; if (isempty(net.layers{k}.outs.runningBatchMean)) net.layers{k}.outs.runningBatchMean = net.layers{k}.outs.batchMean; net.layers{k}.outs.runningBatchVar = net.layers{k}.outs.batchVar; else net.layers{k}.outs.runningBatchMean = (1-net.layers{k}.properties.alpha)*net.layers{k}.outs.runningBatchMean + net.layers{k}.properties.alpha*net.layers{k}.outs.batchMean; net.layers{k}.outs.runningBatchVar = (1-net.layers{k}.properties.alpha)*net.layers{k}.outs.runningBatchVar + net.layers{k}.properties.alpha*net.layers{k}.outs.batchVar; end end net.layers{k}.outs.Xh = (input-repmat(net.layers{k}.outs.batchMean,[ones(1,length(net.layers{k}.properties.sizeOut)) batchNum]))./repmat(sqrt(net.layers{k}.properties.EPS+net.layers{k}.outs.batchVar), [ones(1,length(net.layers{k}.properties.sizeOut)) batchNum]); net.layers{k}.outs.z = net.layers{k}.outs.Xh.*repmat(net.layers{k}.gamma,[ones(1,length(net.layers{k}.properties.sizeOut)) batchNum])+repmat(net.layers{k}.beta,[ones(1,length(net.layers{k}.properties.sizeOut)) batchNum]); otherwise assert(false,'Error - unknown layer type %s in layer %d\n',net.layers{k}.properties.type,k); end %% do activation + dropout if (testTime==1) net.layers{k}.outs.activation = net.layers{k}.properties.Activation(net.layers{k}.outs.z*net.layers{k}.properties.dropOut); else net.layers{k}.outs.activation = net.layers{k}.properties.Activation(net.layers{k}.outs.z); if (net.layers{k}.properties.dropOut~=1) net.layers{k}.outs.dropout = repmat(binornd(1,net.layers{k}.properties.dropOut,net.layers{k}.properties.sizeOut),[ones(1,length(net.layers{k}.properties.sizeOut)) batchNum]); %set dropout matrix net.layers{k}.outs.activation = net.layers{k}.outs.activation.*net.layers{k}.outs.dropout; end end end net.layers{end}.outs.activation = net.layers{end-1}.outs.activation; % for loss layer end
github
hagaygarty/mdCNN-master
getCIFAR10data.m
.m
mdCNN-master/Demo/CIFAR10/getCIFAR10data.m
2,288
utf_8
152ca38ac7c80f8bf87b9d541f934790
function [ CIFAR10 ] = getCIFAR10data( dataset_folder ) % this function will download the CIFAR10 dataset if not exist already. % after downloading it will then parse the raw files and create a CIFAR10.mat file % containning the test/train images and labels. % function returns a struct containing the images+labels. % I,labels,I_test,labels_test. Every element is an array containing the images/labels outFile = fullfile(dataset_folder ,'CIFAR10.mat'); if (~exist(outFile,'file')) url='http://www.cs.toronto.edu/~kriz/'; files = {'cifar-10-matlab.tar.gz'}; fprintf('Preparing CIFAR10.mat file since it does not exist. (done only once)\n'); for fileIdx=1:numel(files) [~,fname,~] = fileparts(files{fileIdx}); if ( exist(fullfile(dataset_folder,fname),'file')) continue; end fprintf('Downloading file %s from %s .. this may take a while',files{fileIdx},url); gunzip([url files{fileIdx}], dataset_folder); untar(fullfile(dataset_folder ,'cifar-10-matlab.tar'),dataset_folder); fprintf('Done\n'); end parseCIFARfiles(fullfile(dataset_folder, 'cifar-10-batches-mat'),outFile); end fprintf('Loading CIFAR10 mat file\n'); CIFAR10 = load(outFile); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [] = parseCIFARfiles(path,outFile) fprintf('Parsing CIFAR10 dataset\n'); load(fullfile(path, 'batches.meta.mat')); %include the labels first sources=dir(fullfile(path, 'data_batch_*.mat')); imageIdx=1; for i=1:length(sources) fileData = load(fullfile(path,sources(i).name)); for j=1:length(fileData.labels) I{imageIdx} = permute(reshape(fileData.data(j,:),32,32,3),[2 1 3]); labels(imageIdx) = fileData.labels(j); imageIdx = imageIdx+1; end end sources=dir(fullfile(path, 'test_batch.mat')); imageIdx=1; for i=1:length(sources) fileData = load(fullfile(path, sources(i).name)); for j=1:length(fileData.labels) I_test{imageIdx} = permute(reshape(fileData.data(j,:),32,32,3),[2 1 3]); labels_test(imageIdx) = fileData.labels(j); imageIdx = imageIdx+1; end end save(outFile,'label_names','I','labels','I_test','labels_test'); end
github
hagaygarty/mdCNN-master
displayCIFAR10.m
.m
mdCNN-master/Demo/CIFAR10/displayCIFAR10.m
22,827
utf_8
46bbf153c6ea700239c3bb1399fb2cbe
function varargout = displayCIFAR10(nets, mCIFAR10File , testOnData) if ( ~iscell(nets) ) tmp{1}=nets; nets=tmp; end if (~exist('testOnData','var')) testOnData = 0; end images = []; labels = []; mOutputArgs = {}; % Variable for storing output when GUI returns mIconCData = []; % The icon CData edited by this GUI of dimension % [mIconHeight, mIconWidth, 3] mIsEditingIcon = false; % Flag for indicating whether the current mouse % move is used for editing color or not % Variables for supporting custom property/value pairs mPropertyDefs = {... % The supported custom property/value pairs of this GUI 'iconwidth', @localValidateInput, 'mIconWidth'; 'iconheight', @localValidateInput, 'mIconHeight'; 'CIFAR10file', @localValidateInput, 'mCIFAR10File'}; mIconWidth = 28; % Use input property 'iconwidth' to initialize mIconHeight = 28; % Use input property 'iconheight' to initialize Images = {0}; im_ptr = 1; % Create all the UI objects in this GUI here so that they can % be used in any functions in this GUI hMainFigure = figure(... 'Units','characters',... 'MenuBar','none',... 'Toolbar','none',... 'Position',[71.8 34.7 106 36.15],... 'WindowStyle', 'normal',... 'WindowButtonDownFcn', @hMainFigureWindowButtonDownFcn,... 'WindowButtonUpFcn', @hMainFigureWindowButtonUpFcn,... 'WindowButtonMotionFcn', @hMainFigureWindowButtonMotionFcn); hIconEditPanel = uipanel(... 'Parent',hMainFigure,... 'Units','characters',... 'Clipping','on',... 'Position',[1.8 4.3 68.2 27.77]); hIconEditAxes = axes(... 'Parent',hIconEditPanel,... 'vis','off',... 'Units','characters',... 'Position',[2 1.15 64 24.6]); hIconFileText = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'HorizontalAlignment','left',... 'Position',[3 32.9 16.2 1.46],... 'String','MNIST file: ',... 'Style','text'); hIconFileEdit = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'HorizontalAlignment','left',... 'Position',[14.8 32.9 27.2 1.62],... 'String','Create a new icon or type in an icon image file for editing',... 'Enable','inactive',... 'Style','edit',... 'ButtondownFcn',@hIconFileEditButtondownFcn,... 'Callback',@hIconFileEditCallback); hIconFileButton = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'Callback',@hIconFileButtonCallback,... 'Position',[48 32.9 5.8 1.77],... 'String','...',... 'TooltipString','Import From Image File'); hIconNumberText = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'HorizontalAlignment','right',... 'Position',[65.8 32.9 17.2 1.62],... 'String','Image idx: ',... 'Style','text'); hIconNumEdit = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'HorizontalAlignment','left',... 'Position',[83.8 32.9 9.2 1.62],... 'String','1',... 'Style','edit'); hIconNumberButton = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'Callback',@hIconNumButtonCallback,... 'Position',[95.8 32.9 7.2 1.62],... 'String','Set',... 'TooltipString','Set the desired Image idx'); hPreviewPanel = uipanel(... 'Parent',hMainFigure,... 'Units','characters',... 'Title','Preview',... 'Clipping','on',... 'Position',[71.8 19.15 32.2 13]); hPreviewControl = uicontrol(... 'Parent',hPreviewPanel,... 'Units','characters',... 'Enable','inactive',... 'Visible','off',... 'Position',[2 3.77 16.2 5.46],... 'String',''); hPreviewControlProcessed = uicontrol(... 'Parent',hPreviewPanel,... 'Units','characters',... 'Enable','inactive',... 'Visible','off',... 'Position',[2 3.77 16.2 5.46],... 'String',''); hPrevDigitButton = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'Position',[15 0.62 15 2.38],... 'String','<',... 'Callback',@hPrevDigitButtonCallback); hNextDigitButton = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'Position',[35 0.62 15 2.38],... 'String','>',... 'Callback',@hNextDigitButtonCallback); hResultPanel = uipanel(... 'Parent',hMainFigure,... 'Units','characters',... 'Title','Result',... 'Clipping','on',... 'Position',[71.8 4.3 32.2 13]); hResultText = uicontrol(... 'Parent',hResultPanel,... 'Units','normalized',... 'Style','text', ... 'Enable','inactive',... 'Visible','on',... 'FontSize', 12, ... 'Position',[.2 .2 .6 .6],... 'String',''); for i = 0:9, hResultDigits(1+i) = uicontrol(... 'Parent',hResultPanel,... 'Units','normalized',... 'Enable','inactive',... 'Style','text', ... 'FontSize', 14, ... 'Position',[.02+i*.095 .05 .09 .128],... 'String', char('0'+i), ... 'ForegroundColor', [1 1 1]); end hSectionLine = uipanel(... 'Parent',hMainFigure,... 'Units','characters',... 'HighlightColor',[0 0 0],... 'BorderType','line',... 'Title','',... 'Clipping','on',... 'Position',[2 3.62 102.4 0.077]); hCancelButton = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'Position',[85.8 0.62 17.8 2.38],... 'String','Exit',... 'Callback',@hCancelButtonCallback); hClearButton = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'Position',[65.0 0.62 17.8 2.38],... 'String','Clear',... 'Callback',@hClearButtonCallback); % Host the ColorPalette in the PaletteContainer and keep the function % handle for getting its selected color for editing icon % Make changes needed for proper look and feel and running on different % platforms prepareLayout(hMainFigure); % Process the command line input arguments supplied when the GUI is % invoked % Initialize the iconEditor using the defaults or custom data given through % property/value pairs localUpdateIconPlot(); % Make the GUI on screen set(hMainFigure,'visible', 'on'); movegui(hMainFigure,'onscreen'); figure(hMainFigure); %hClearButtonCallback(); % Make the GUI blocking %uiwait(hMainFigure); % Return the edited icon CData if it is requested mOutputArgs{1} =mIconCData; if nargout>0 [varargout{1:nargout}] = mOutputArgs{:}; end %------------------------------------------------------------------ function hMainFigureWindowButtonDownFcn(hObject, eventdata) % Callback called when mouse is pressed on the figure. Used to change % the color of the specific icon data point under the mouse to that of % the currently selected color of the colorPalette if (ancestor(gco,'axes') == hIconEditAxes) mIsEditingIcon = true; localEditColor(); end end %------------------------------------------------------------------ function hMainFigureWindowButtonUpFcn(hObject, eventdata) % Callback called when mouse is release to exit the icon editing mode mIsEditingIcon = false; end %------------------------------------------------------------------ function hMainFigureWindowButtonMotionFcn(hObject, eventdata) % Callback called when mouse is moving so that icon color data can be % updated in the editing mode if (ancestor(gco,'axes') == hIconEditAxes) localEditColor(); end end %------------------------------------------------------------------ function hIconFileEditCallback(hObject, eventdata) % Callback called when user has changed the icon file name from which % the icon can be loaded file = get(hObject,'String'); if exist(file, 'file') ~= 2 errordlg(['The given icon file cannot be found ' 10, file], ... 'Invalid Icon File', 'modal'); set(hObject, 'String', mCIFAR10File); else mIconCData = []; localUpdateIconPlot(); end end %------------------------------------------------------------------ function hIconFileEditButtondownFcn(hObject, eventdata) % Callback called the first time the user pressed mouse on the icon % file editbox set(hObject,'String',''); set(hObject,'Enable','on'); set(hObject,'ButtonDownFcn',[]); uicontrol(hObject); end %------------------------------------------------------------------ function hCancelButtonCallback(hObject, eventdata) % Callback called when the Cancel button is pressed mIconCData =[]; uiresume; delete(hMainFigure); end %------------------------------------------------------------------ function hRecognizeButtonCallback() image = preproc_image(mIconCData); outs=0; for netIdx=1:length(nets) input = GetNetworkInputs(image , nets{netIdx} , 1); nets{netIdx} = feedForward(nets{netIdx}, input , 1); outs=outs+nets{netIdx}.layers{end}.outs.activation; end outs = outs / length(nets); %a{2,end} [M,m] = max(outs); max_out = M; for out_i = 1:numel(outs), set(hResultDigits(out_i), 'ForegroundColor', [1 1 1]*(1.8-outs(out_i))/3.6) end digit = m - 1; str = sprintf('%s (%s)', Images.label_names{digit+1} , Images.label_names{labels(im_ptr)+1}); if (M>0.1) set(hResultText, 'string', str, 'ForegroundColor', [1 1 1]*(1.8-max_out)/3.6) else set(hResultText, 'string', '?', 'ForegroundColor', [1 1 1]*(1.8-max_out)/3.6) end set(hResultPanel, 'Title',['Result:' num2str(digit), ',Conf=' num2str(M*100,4) '%']); end %------------------------------------------------------------------ function hClearButtonCallback(hObject, eventdata) mIconCData = ones(mIconHeight, mIconWidth, 3); localUpdateIconPlot(); hRecognizeButtonCallback() end %------------------------------------------------------------------ function hIconNumButtonCallback(hObject, eventdata) % Callback called when the icon file selection button is pressed imgIdx = str2double(get(hIconNumEdit, 'String')); im_ptr = 1+mod(imgIdx-1,numel(images)); im = images{im_ptr}; mIconCData = im; localUpdateIconPlot(); hRecognizeButtonCallback() end %------------------------------------------------------------------ function hIconFileButtonCallback(hObject, eventdata) % Callback called when the icon file selection button is pressed filespec = {'*.*', 'Database file '}; [filename, pathname] = uigetfile(filespec, 'Pick an database file', mCIFAR10File); if ~isequal(filename,0) mCIFAR10File = fullfile(pathname, filename); set(hIconFileEdit, 'ButtonDownFcn',[]); set(hIconFileEdit, 'Enable','on'); set(hIconNumEdit, 'Enable','on'); mIconCData = []; localUpdateIconPlot(); elseif isempty(mIconCData) set(hPreviewControl,'Visible', 'off'); end end function hPrevDigitButtonCallback(hObject, eventdata) if(im_ptr>1) im_ptr=im_ptr-1; end im = images{im_ptr}; mIconCData = im; localUpdateIconPlot(); hRecognizeButtonCallback() end function hNextDigitButtonCallback(hObject, eventdata) if(im_ptr<numel(images)) im_ptr=im_ptr+1; end im = images{im_ptr}; mIconCData = im; localUpdateIconPlot(); hRecognizeButtonCallback() end %------------------------------------------------------------------ function localEditColor % helper function that changes the color of an icon data point to % that of the currently selected color in colorPalette if mIsEditingIcon pt = get(hIconEditAxes,'currentpoint'); localUpdateIconPlot(); end end %------------------------------------------------------------------ function localUpdateIconPlot % helper function that updates the iconEditor when the icon data % changes %initialize icon CData if it is not initialized if isempty(mIconCData) if exist(mCIFAR10File, 'file') == 2 try Images = load(mCIFAR10File); if (testOnData==1) images = Images.I; labels = Images.labels; else images = Images.I_test; labels = Images.labels_test; end %im_ptr = 1; im = images{im_ptr}; mIconCData = im; set(hIconFileEdit, 'String', mCIFAR10File); catch errordlg(['Could not load MNIST database file successfully. ',... 'Make sure the file name is correct: ' mCIFAR10File],... 'Invalid MNIST File', 'modal'); mIconCData = nan(mIconHeight, mIconWidth, 3); end else mIconCData = nan(mIconHeight, mIconWidth, 3); end end set(hPreviewPanel,'Title',['Preview, image idx=' num2str(im_ptr) '/' num2str(length(images))]); % update preview control rows = size(mIconCData, 1); cols = size(mIconCData, 2); previewSize = getpixelposition(hPreviewPanel); % compensate for the title previewSize(4) = previewSize(4) -15; controlWidth = previewSize(3); controlHeight = previewSize(4); controlMargin = 6; if rows+controlMargin<controlHeight controlHeight = rows+controlMargin; end if cols+controlMargin<controlWidth controlWidth = cols+controlMargin; end setpixelposition(hPreviewControl,[(previewSize(3)-2*controlWidth)/3,(previewSize(4)-controlHeight)/3*2, controlWidth, controlHeight]); iconCData = mIconCData; image = preproc_image(mIconCData); set(hPreviewControl,'CData', iconCData,'Visible','on'); setpixelposition(hPreviewControlProcessed,[(previewSize(3)-2*controlWidth)/3*2+controlWidth,(previewSize(4)-controlHeight)/3*2, controlWidth, controlHeight]); input = double(image); input = imresize(input,[size(mIconCData,1) size(mIconCData,2)]); input = input-min(input(:)); maxIm=max(input(:)); if (maxIm~=0) input = input/maxIm; end colimage = input; set(hPreviewControlProcessed,'CData', colimage,'Visible','on'); % update icon edit pane set(hIconEditPanel, 'Title',['Icon Edit Pane (', num2str(rows),' X ', num2str(cols),')']); s = findobj(hIconEditPanel,'type','surface'); if isempty(s) gridColor = get(0, 'defaultuicontrolbackgroundcolor') - 0.2; gridColor(gridColor<0)=0; s=surface('edgecolor','none','parent',hIconEditAxes); end %set xdata, ydata, zdata in case the rows and/or cols change set(s,'xdata',0:cols,'ydata',0:rows,'zdata',zeros(rows+1,cols+1),'cdata',localGetIconCDataWithNaNs()); axis(hIconEditAxes, 'ij', 'off'); hRecognizeButtonCallback(); end %------------------------------------------------------------------ function cdwithnan = localGetIconCDataWithNaNs() % Add NaN to edge of mIconCData so the entire icon renders in the % drawing pane. This is necessary because of surface behavior. cdwithnan = double(mIconCData); cdwithnan = cdwithnan-min(cdwithnan(:)); cdwithnan = cdwithnan/max(cdwithnan(:)); end %------------------------------------------------------------------ function isValid = localValidateInput(property, value) % helper function that validates the user provided input property/value % pairs. You can choose to show warnings or errors here. isValid = false; switch lower(property) case {'iconwidth', 'iconheight'} if isnumeric(value) && value >0 isValid = true; end case 'MNISTfile' if exist(value,'file')==2 isValid = true; end end end end % end of iconEditor %------------------------------------------------------------------ function prepareLayout(topContainer) % This is a utility function that takes care of issues related to % look&feel and running across multiple platforms. You can reuse % this function in other GUIs or modify it to fit your needs. allObjects = findall(topContainer); warning off %Temporary presentation fix try titles=get(allObjects(isprop(allObjects,'TitleHandle')), 'TitleHandle'); allObjects(ismember(allObjects,[titles{:}])) = []; catch end warning on % Use the name of this GUI file as the title of the figure defaultColor = get(0, 'defaultuicontrolbackgroundcolor'); if isa(handle(topContainer),'figure') set(topContainer,'Name', mfilename, 'NumberTitle','off'); % Make figure color matches that of GUI objects set(topContainer, 'Color',defaultColor); end % Make GUI objects available to callbacks so that they cannot % be changes accidentally by other MATLAB commands set(allObjects(isprop(allObjects,'HandleVisibility')), 'HandleVisibility', 'Callback'); % Make the GUI run properly across multiple platforms by using % the proper units if strcmpi(get(topContainer, 'Resize'),'on') set(allObjects(isprop(allObjects,'Units')),'Units','Normalized'); else set(allObjects(isprop(allObjects,'Units')),'Units','Characters'); end % You may want to change the default color of editbox, % popupmenu, and listbox to white on Windows if ispc candidates = [findobj(allObjects, 'Style','Popupmenu'),... findobj(allObjects, 'Style','Edit'),... findobj(allObjects, 'Style','Listbox')]; set(findobj(candidates,'BackgroundColor', defaultColor), 'BackgroundColor','white'); end end function out = preproc_image(id) %Preprocess single image out = id; return; Inorm = id(:,:,1); Inorm(~isfinite(Inorm)) = 1; Inorm = abs(Inorm-1)'; out = zeros(32); out(3:30,3:30) = Inorm; if sum(out(:))>0, out = reshape(mapstd(out(:)'), 32, 32); end end function I = readMNIST_image(filepath,num) %readMNIST_image MNIST handwriten image database reading. Reads only images %without labels, with specified filename % % Syntax % % I = readMNIST_image(filepath,num) % % Description % Input: % filepath - name of database file with path % n - number of images to process % Output: % I - cell array of training images 28x28 size % %(c) Sirotenko Mikhail, 2009 %===========Loading training set fid = fopen(filepath,'r','b'); %big-endian magicNum = fread(fid,1,'int32'); %Magic number if(magicNum~=2051) display('Error: cant find magic number'); return; end imgNum = fread(fid,1,'int32'); %Number of images rowSz = fread(fid,1,'int32'); %Image height colSz = fread(fid,1,'int32'); %Image width if(num<imgNum) imgNum=num; end for k=1:imgNum I{k} = uint8(fread(fid,[rowSz colSz],'uchar')); end fclose(fid); end
github
hagaygarty/mdCNN-master
getMNIST3Ddata.m
.m
mdCNN-master/Demo/MNIST3d/getMNIST3Ddata.m
5,646
utf_8
1ed7cd4f45036f0ead476de7cf7875a9
function [ MNIST ] = getMNIST3Ddata( dst_folder ) % this function will download the MNIST dataset if not exist already. % after downloading it will then parse the files and create a MNIST.mat file % containing the test/train images and labels. % function returns a struct containing the images+labels % I,labels,I_test,labels_test , every element in the struct is an array containing the images/labels outFile = fullfile(dst_folder ,'MNIST3d.mat'); if (~exist(outFile,'file')) url='http://yann.lecun.com/exdb/mnist/'; files = {'t10k-labels-idx1-ubyte.gz', 'train-labels-idx1-ubyte.gz' , 'train-images-idx3-ubyte.gz', 't10k-images-idx3-ubyte.gz'}; fprintf('Preparing MNIST.mat file since it does not exist. (done only once)\n'); for fileIdx=1:numel(files) [~,fname,~] = fileparts(files{fileIdx}); if ( exist(fullfile(dst_folder,fname),'file')) continue; end fprintf('Downloading file %s from %s ...',files{fileIdx},url); gunzip([url files{fileIdx}], dst_folder); fprintf('Done\n'); end parseMNIST3Dfiles(dst_folder,outFile); end MNIST = load(outFile); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [res] = Transform2dto3d(image,len) res = zeros([size(image) size(image,1)], 'uint8'); for z=0:(len-1) SE = strel('diamond',len-z); deIm = imdilate(image,SE,'same'); edgeIm = uint8(255*edge(deIm)); res(:,:, round(size(res,3)/2)+z) = edgeIm; res(:,:, round(size(res,3)/2)-z) = edgeIm; end z=len; res(:,:, round(size(res,3)/2)+z) = image; res(:,:, round(size(res,3)/2)-z) = image; end function [] = parseMNIST3Dfiles(path,outFile) %readMNIST MNIST handwriten image database reading. % Output: % I - cell array of training images 28x28 size % labels - vector of labels (true digits) for training set % I_test - cell array of testing images 28x28 size % labels_test - vector of labels (true digits) for testing set if (exist('path','var')==0) path = './'; end fact=1; len=floor(12*fact); len=3; fprintf('Prepering MNIST3d dataset... (done only once)\n'); if(~exist(fullfile(path ,'train-images-idx3-ubyte'),'file')) error('Training set of MNIST not found. Please download it from http://yann.lecun.com/exdb/mnist/ and put to ./MNIST folder'); end fid = fopen(fullfile(path ,'train-images-idx3-ubyte'),'r','b'); %big-endian magicNum = fread(fid,1,'int32'); %Magic number if(magicNum~=2051) display('Error: cant find magic number'); return; end imgNum = fread(fid,1,'int32'); %Number of images rowSz = fread(fid,1,'int32'); %Image height colSz = fread(fid,1,'int32'); %Image width for k=1:imgNum I{k} = uint8(fread(fid,[rowSz colSz],'uchar'))'; I{k} = imresize(I{k} , fact,'bilinear','Antialiasing',true ); I{k} = Transform2dto3d(I{k},len); if ( mod(k,5000)==0) % close all; % showIso(I{k},[]); fprintf('Finish preparing image %d of %d\n',k,imgNum); end end fclose(fid); %============Loading labels if(~exist(fullfile(path, 'train-labels-idx1-ubyte') ,'file')) error('Training labels of MNIST not found. Please download it from http://yann.lecun.com/exdb/mnist/ and put to ./MNIST folder'); end fid = fopen(fullfile(path ,'train-labels-idx1-ubyte'),'r','b'); %big-endian magicNum = fread(fid,1,'int32'); %Magic number if(magicNum~=2049) display('Error: cant find magic number'); return; end itmNum = fread(fid,1,'int32'); %Number of labels labels = uint8(fread(fid,itmNum,'uint8')); %Load all labels fclose(fid); %============All the same for test set if(~exist(fullfile(path, 't10k-images-idx3-ubyte'),'file')) error('Test images of MNIST not found. Please download it from http://yann.lecun.com/exdb/mnist/ and put to ./MNIST folder'); end fid = fopen(fullfile(path, 't10k-images-idx3-ubyte'),'r','b'); magicNum = fread(fid,1,'int32'); if(magicNum~=2051) display('Error: cant find magic number'); return; end imgNum = fread(fid,1,'int32'); rowSz = fread(fid,1,'int32'); colSz = fread(fid,1,'int32'); for k=1:imgNum I_test{k} = uint8(fread(fid,[rowSz colSz],'uchar'))'; I_test{k} = imresize(I_test{k} , fact,'bilinear','Antialiasing',true ); I_test{k} = Transform2dto3d(I_test{k},len); if ( mod(k,5000)==0) % close all; % showIso(I{k},[]); fprintf('Finish image (test) %d of %d\n',k,imgNum); end end fclose(fid); %============Test labels if(~exist(fullfile(path, 't10k-labels-idx1-ubyte'),'file')) error('Test labels of MNIST not found. Please download it from http://yann.lecun.com/exdb/mnist/ and put to ./MNIST folder'); end fid = fopen(fullfile(path, 't10k-labels-idx1-ubyte'),'r','b'); magicNum = fread(fid,1,'int32'); if(magicNum~=2049) display('Error: cant find magic number'); return; end itmNum = fread(fid,1,'int32'); labels_test = uint8(fread(fid,itmNum,'uint8')); fclose(fid); labels = fixErrorsInMNIST(labels); save(outFile,'I','labels','I_test','labels_test','-v7.3'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ labels ] = fixErrorsInMNIST( labels ) % some clear errors found on original MnisT data set. The below corrects % the labels errorsIdx = [59916 10995 26561 32343 43455 45353]; correctLabels = [ 7 9 1 7 3 1]; for idx=1:length(errorsIdx) labels(errorsIdx(idx)) = correctLabels(idx); end end
github
hagaygarty/mdCNN-master
getMNISTdata.m
.m
mdCNN-master/Demo/AutoEnc/getMNISTdata.m
4,421
utf_8
27ab6b4e73e15d9e9eba4af06ad04400
function [ MNIST ] = getMNISTdata( dst_folder ) % this function will download the MNIST dataset if not exist already. % after downloading it will then parse the files and create a MNIST.mat file % containing the test/train images and labels. % function returns a struct containing the images+labels % I,labels,I_test,labels_test , every element in the struct is an array containing the images/labels outFile = fullfile(dst_folder ,'MNIST.mat'); if (~exist(outFile,'file')) url='http://yann.lecun.com/exdb/mnist/'; files = {'t10k-labels-idx1-ubyte.gz', 'train-labels-idx1-ubyte.gz' , 'train-images-idx3-ubyte.gz', 't10k-images-idx3-ubyte.gz'}; fprintf('Preparing MNIST.mat file since it does not exist. (done only once)\n'); for fileIdx=1:numel(files) [~,fname,~] = fileparts(files{fileIdx}); if ( exist(fullfile(dst_folder,fname),'file')) continue; end fprintf('Downloading file %s from %s ...',files{fileIdx},url); gunzip([url files{fileIdx}], dst_folder); fprintf('Done\n'); end parseMNISTfiles(dst_folder,outFile); end MNIST = load(outFile); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [] = parseMNISTfiles(path,outFile) %readMNIST MNIST handwriten image database reading. % Output: % I - cell array of training images 28x28 size % labels - vector of labels (true digits) for training set % I_test - cell array of testing images 28x28 size % labels_test - vector of labels (true digits) for testing set if (exist('path','var')==0) path = './'; end fprintf('Parsing MNIST dataset\n'); if(~exist(fullfile(path ,'train-images-idx3-ubyte'),'file')) error('Training set of MNIST not found. Please download it from http://yann.lecun.com/exdb/mnist/ and put to ./MNIST folder'); end fid = fopen(fullfile(path ,'train-images-idx3-ubyte'),'r','b'); %big-endian magicNum = fread(fid,1,'int32'); %Magic number if(magicNum~=2051) display('Error: cant find magic number'); return; end imgNum = fread(fid,1,'int32'); %Number of images rowSz = fread(fid,1,'int32'); %Image height colSz = fread(fid,1,'int32'); %Image width for k=1:imgNum I{k} = uint8(fread(fid,[rowSz colSz],'uchar'))'; end fclose(fid); %============Loading labels if(~exist(fullfile(path, 'train-labels-idx1-ubyte') ,'file')) error('Training labels of MNIST not found. Please download it from http://yann.lecun.com/exdb/mnist/ and put to ./MNIST folder'); end fid = fopen(fullfile(path ,'train-labels-idx1-ubyte'),'r','b'); %big-endian magicNum = fread(fid,1,'int32'); %Magic number if(magicNum~=2049) display('Error: cant find magic number'); return; end itmNum = fread(fid,1,'int32'); %Number of labels labels = uint8(fread(fid,itmNum,'uint8')); %Load all labels fclose(fid); %============All the same for test set if(~exist(fullfile(path, 't10k-images-idx3-ubyte'),'file')) error('Test images of MNIST not found. Please download it from http://yann.lecun.com/exdb/mnist/ and put to ./MNIST folder'); end fid = fopen(fullfile(path, 't10k-images-idx3-ubyte'),'r','b'); magicNum = fread(fid,1,'int32'); if(magicNum~=2051) display('Error: cant find magic number'); return; end imgNum = fread(fid,1,'int32'); rowSz = fread(fid,1,'int32'); colSz = fread(fid,1,'int32'); for k=1:imgNum I_test{k} = uint8(fread(fid,[rowSz colSz],'uchar'))'; end fclose(fid); %============Test labels if(~exist(fullfile(path, 't10k-labels-idx1-ubyte'),'file')) error('Test labels of MNIST not found. Please download it from http://yann.lecun.com/exdb/mnist/ and put to ./MNIST folder'); end fid = fopen(fullfile(path, 't10k-labels-idx1-ubyte'),'r','b'); magicNum = fread(fid,1,'int32'); if(magicNum~=2049) display('Error: cant find magic number'); return; end itmNum = fread(fid,1,'int32'); labels_test = uint8(fread(fid,itmNum,'uint8')); fclose(fid); labels = fixErrorsInMNIST(labels); save(outFile,'I','labels','I_test','labels_test'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ labels ] = fixErrorsInMNIST( labels ) % some clear errors found on original MnisT data set. The below corrects % the labels errorsIdx = [59916 10995 26561 32343 43455 45353]; correctLabels = [ 7 9 1 7 3 1]; for idx=1:length(errorsIdx) labels(errorsIdx(idx)) = correctLabels(idx); end end
github
hagaygarty/mdCNN-master
displayMNIST.m
.m
mdCNN-master/Demo/MNIST/displayMNIST.m
23,646
utf_8
c9e31fb72c2e8f8a85057020b75e27c5
function varargout = displayMNIST(nets, dataset_folder) if ( ~iscell(nets) ) tmp{1}=nets; nets=tmp; end mOutputArgs = {}; % Variable for storing output when GUI returns mIconCData = []; % The icon CData edited by this GUI of dimension % [mIconHeight, mIconWidth, 3] mIsEditingIcon = false; % Flag for indicating whether the current mouse % move is used for editing color or not % Variables for supporting custom property/value pairs mPropertyDefs = {... % The supported custom property/value pairs of this GUI 'iconwidth', @localValidateInput, 'mIconWidth'; 'iconheight', @localValidateInput, 'mIconHeight'; 'MNISTfile', @localValidateInput, 'mMNISTFile'}; mIconWidth = 28; % Use input property 'iconwidth' to initialize mIconHeight = 28; % Use input property 'iconheight' to initialize mMNISTFile = fullfile(dataset_folder,'t10k-images-idx3-ubyte'); %fullfile(matlabroot,'./'); Images = {0}; im_ptr = 1; % Create all the UI objects in this GUI here so that they can % be used in any functions in this GUI hMainFigure = figure(... 'Units','characters',... 'MenuBar','none',... 'Toolbar','none',... 'Position',[71.8 34.7 106 36.15],... 'WindowStyle', 'normal',... 'WindowButtonDownFcn', @hMainFigureWindowButtonDownFcn,... 'WindowButtonUpFcn', @hMainFigureWindowButtonUpFcn,... 'WindowButtonMotionFcn', @hMainFigureWindowButtonMotionFcn); hIconEditPanel = uipanel(... 'Parent',hMainFigure,... 'Units','characters',... 'Clipping','on',... 'Position',[1.8 4.3 68.2 27.77]); hIconEditAxes = axes(... 'Parent',hIconEditPanel,... 'vis','off',... 'Units','characters',... 'Position',[2 1.15 64 24.6]); hIconFileText = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'HorizontalAlignment','left',... 'Position',[3 32.9 16.2 1.46],... 'String','MNIST file: ',... 'Style','text'); hIconFileEdit = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'HorizontalAlignment','left',... 'Position',[14.8 32.9 27.2 1.62],... 'String','Create a new icon or type in an icon image file for editing',... 'Enable','inactive',... 'Style','edit',... 'ButtondownFcn',@hIconFileEditButtondownFcn,... 'Callback',@hIconFileEditCallback); hIconFileButton = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'Callback',@hIconFileButtonCallback,... 'Position',[48 32.9 5.8 1.77],... 'String','...',... 'TooltipString','Import From Image File'); hIconNumberText = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'HorizontalAlignment','right',... 'Position',[65.8 32.9 17.2 1.62],... 'String','Image idx: ',... 'Style','text'); hIconNumEdit = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'HorizontalAlignment','left',... 'Position',[83.8 32.9 9.2 1.62],... 'String','1',... 'Style','edit'); hIconNumberButton = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'Callback',@hIconNumButtonCallback,... 'Position',[95.8 32.9 7.2 1.62],... 'String','Set',... 'TooltipString','Set the desired Image idx'); hPreviewPanel = uipanel(... 'Parent',hMainFigure,... 'Units','characters',... 'Title','Preview',... 'Clipping','on',... 'Position',[71.8 19.15 32.2 13]); hPreviewControl = uicontrol(... 'Parent',hPreviewPanel,... 'Units','characters',... 'Enable','inactive',... 'Visible','off',... 'Position',[2 3.77 16.2 5.46],... 'String',''); hPreviewControlProcessed = uicontrol(... 'Parent',hPreviewPanel,... 'Units','characters',... 'Enable','inactive',... 'Visible','off',... 'Position',[2 3.77 16.2 5.46],... 'String',''); hPrevDigitButton = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'Position',[15 0.62 15 2.38],... 'String','<',... 'Callback',@hPrevDigitButtonCallback); hNextDigitButton = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'Position',[35 0.62 15 2.38],... 'String','>',... 'Callback',@hNextDigitButtonCallback); hResultPanel = uipanel(... 'Parent',hMainFigure,... 'Units','characters',... 'Title','Result',... 'Clipping','on',... 'Position',[71.8 4.3 32.2 13]); hResultText = uicontrol(... 'Parent',hResultPanel,... 'Units','normalized',... 'Style','text', ... 'Enable','inactive',... 'Visible','on',... 'FontSize', 50, ... 'Position',[.2 .2 .6 .6],... 'String',''); for i = 0:9, hResultDigits(1+i) = uicontrol(... 'Parent',hResultPanel,... 'Units','normalized',... 'Enable','inactive',... 'Style','text', ... 'FontSize', 14, ... 'Position',[.02+i*.095 .05 .09 .128],... 'String', char('0'+i), ... 'ForegroundColor', [1 1 1]); end hSectionLine = uipanel(... 'Parent',hMainFigure,... 'Units','characters',... 'HighlightColor',[0 0 0],... 'BorderType','line',... 'Title','',... 'Clipping','on',... 'Position',[2 3.62 102.4 0.077]); hCancelButton = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'Position',[85.8 0.62 17.8 2.38],... 'String','Exit',... 'Callback',@hCancelButtonCallback); hClearButton = uicontrol(... 'Parent',hMainFigure,... 'Units','characters',... 'Position',[65.0 0.62 17.8 2.38],... 'String','Clear',... 'Callback',@hClearButtonCallback); % Host the ColorPalette in the PaletteContainer and keep the function % handle for getting its selected color for editing icon % Make changes needed for proper look and feel and running on different % platforms prepareLayout(hMainFigure); % Process the command line input arguments supplied when the GUI is % invoked % Initialize the iconEditor using the defaults or custom data given through % property/value pairs localUpdateIconPlot(); % Make the GUI on screen set(hMainFigure,'visible', 'on'); movegui(hMainFigure,'onscreen'); figure(hMainFigure); %hClearButtonCallback(); % Make the GUI blocking %uiwait(hMainFigure); % Return the edited icon CData if it is requested mOutputArgs{1} =mIconCData; if nargout>0 [varargout{1:nargout}] = mOutputArgs{:}; end %------------------------------------------------------------------ function hMainFigureWindowButtonDownFcn(hObject, eventdata) % Callback called when mouse is pressed on the figure. Used to change % the color of the specific icon data point under the mouse to that of % the currently selected color of the colorPalette if (ancestor(gco,'axes') == hIconEditAxes) mIsEditingIcon = true; localEditColor(); end end %------------------------------------------------------------------ function hMainFigureWindowButtonUpFcn(hObject, eventdata) % Callback called when mouse is release to exit the icon editing mode mIsEditingIcon = false; end %------------------------------------------------------------------ function hMainFigureWindowButtonMotionFcn(hObject, eventdata) % Callback called when mouse is moving so that icon color data can be % updated in the editing mode if (ancestor(gco,'axes') == hIconEditAxes) localEditColor(); end end %------------------------------------------------------------------ function hIconFileEditCallback(hObject, eventdata) % Callback called when user has changed the icon file name from which % the icon can be loaded file = get(hObject,'String'); if exist(file, 'file') ~= 2 errordlg(['The given icon file cannot be found ' 10, file], ... 'Invalid Icon File', 'modal'); set(hObject, 'String', mMNISTFile); else mIconCData = []; localUpdateIconPlot(); end end %------------------------------------------------------------------ function hIconFileEditButtondownFcn(hObject, eventdata) % Callback called the first time the user pressed mouse on the icon % file editbox set(hObject,'String',''); set(hObject,'Enable','on'); set(hObject,'ButtonDownFcn',[]); uicontrol(hObject); end %------------------------------------------------------------------ function hCancelButtonCallback(hObject, eventdata) % Callback called when the Cancel button is pressed mIconCData =[]; uiresume; delete(hMainFigure); end %------------------------------------------------------------------ function hRecognizeButtonCallback() image = preproc_image(mIconCData)'; net_outs=0; for netIdx=1:length(nets) input = GetNetworkInputs(image , nets{netIdx} , 1); nets{netIdx} = feedForward(nets{netIdx}, input , 1); net_outs=net_outs+nets{netIdx}.layers{end}.outs.activation; end net_outs = net_outs / length(nets); % outs = outs-min(outs); % outs = outs./sum(outs); %a{end}.activation [M,m] = max(net_outs); max_out = M; for out_i = 1:numel(net_outs), set(hResultDigits(out_i), 'ForegroundColor', [1 1 1]*(1.8-net_outs(out_i))/3.6) end digit = m - 1; if (M>0.2) set(hResultText, 'string', char('0'+digit), 'ForegroundColor', [1 1 1]*(1.8-max_out)/3.6) else set(hResultText, 'string', '?', 'ForegroundColor', [1 1 1]*(1.8-max_out)/3.6) end set(hResultPanel, 'Title',['Result:' num2str(digit), ',Conf=' num2str(M*100,4) '%']); end %------------------------------------------------------------------ function hClearButtonCallback(hObject, eventdata) mIconCData = ones(mIconHeight, mIconWidth, 3); localUpdateIconPlot(); hRecognizeButtonCallback() end %------------------------------------------------------------------ function hIconNumButtonCallback(hObject, eventdata) % Callback called when the icon file selection button is pressed imgIdx = str2double(get(hIconNumEdit, 'String')); im_ptr = 1+mod(imgIdx-1,numel(Images)); im = abs(double(Images{im_ptr})/255-1)'; mIconCData = cat(3,im,im,im); localUpdateIconPlot(); hRecognizeButtonCallback() end %------------------------------------------------------------------ function hIconFileButtonCallback(hObject, eventdata) % Callback called when the icon file selection button is pressed filespec = {'*.*', 'Database file '}; [filename, pathname] = uigetfile(filespec, 'Pick an database file', mMNISTFile); if ~isequal(filename,0) mMNISTFile = fullfile(pathname, filename); set(hIconFileEdit, 'ButtonDownFcn',[]); set(hIconFileEdit, 'Enable','on'); set(hIconNumEdit, 'Enable','on'); mIconCData = []; localUpdateIconPlot(); elseif isempty(mIconCData) set(hPreviewControl,'Visible', 'off'); end end function hPrevDigitButtonCallback(hObject, eventdata) if(im_ptr>1) im_ptr=im_ptr-1; end im = abs(double(Images{im_ptr})/255-1)'; mIconCData = cat(3,im,im,im); localUpdateIconPlot(); hRecognizeButtonCallback() end function hNextDigitButtonCallback(hObject, eventdata) if(im_ptr<numel(Images)) im_ptr=im_ptr+1; end im = abs(double(Images{im_ptr})/255-1)'; mIconCData = cat(3,im,im,im); localUpdateIconPlot(); hRecognizeButtonCallback() end %------------------------------------------------------------------ function localEditColor % helper function that changes the color of an icon data point to % that of the currently selected color in colorPalette if mIsEditingIcon pt = get(hIconEditAxes,'currentpoint'); x = max(1, min(ceil(pt(1,1)), mIconWidth)); y = max(1, min(ceil(pt(1,2)), mIconHeight)); % update color of the selected block m = get(gcf,'SelectionType'); if m(1) == 'n', % left button pressed %fprintf('Updateing %d,%d to 0\n',y,x); mIconCData(y, x,:) = 0; if y<mIconHeight, mIconCData(y+1,x,:) = .8*mIconCData(y+1,x,:); end if x<mIconWidth, mIconCData(y,x+1,:) = .8*mIconCData(y,x+1,:); end if y>1, mIconCData(y-1,x,:) = .8*mIconCData(y-1,x,:); end if x>1, mIconCData(y,x-1,:) = .8*mIconCData(y,x-1,:); end else mIconCData(y, x,:) = 1; %fprintf('Updateing %d,%d to 1\n',y,x); end localUpdateIconPlot(); end end %------------------------------------------------------------------ function localUpdateIconPlot % helper function that updates the iconEditor when the icon data % changes %initialize icon CData if it is not initialized set(hPreviewPanel,'Title',['Preview, image idx=' num2str(im_ptr)]); if isempty(mIconCData) if exist(mMNISTFile, 'file') == 2 try Images = readMNIST_image(mMNISTFile,60000); %im_ptr = 1; im = abs(double(Images{im_ptr})/255-1)'; mIconCData = cat(3,im,im,im); set(hIconFileEdit, 'String', mMNISTFile); catch errordlg(['Could not load MNIST database file successfully. ',... 'Make sure the file name is correct: ' mMNISTFile],... 'Invalid MNIST File', 'modal'); mIconCData = nan(mIconHeight, mIconWidth, 3); end else mIconCData = nan(mIconHeight, mIconWidth, 3); end end % update preview control rows = size(mIconCData, 1); cols = size(mIconCData, 2); previewSize = getpixelposition(hPreviewPanel); % compensate for the title previewSize(4) = previewSize(4) -15; controlWidth = previewSize(3); controlHeight = previewSize(4); controlMargin = 6; if rows+controlMargin<controlHeight controlHeight = rows+controlMargin; end if cols+controlMargin<controlWidth controlWidth = cols+controlMargin; end setpixelposition(hPreviewControl,[(previewSize(3)-2*controlWidth)/3,(previewSize(4)-controlHeight)/3*2, controlWidth, controlHeight]); iconCData = mIconCData; image = preproc_image(mIconCData)'; cm = round(centerOfMass(image-min(min(image))))+1; iconCData(cm(1),cm(2),:) = cat(3,1,0,0); set(hPreviewControl,'CData', iconCData,'Visible','on'); setpixelposition(hPreviewControlProcessed,[(previewSize(3)-2*controlWidth)/3*2+controlWidth,(previewSize(4)-controlHeight)/3*2, controlWidth, controlHeight]); input = GetNetworkInputs(image , nets{1} ,1 ); input = imresize(input,[size(mIconCData,1) size(mIconCData,2)]); input = input-min(min(input)); maxIm=max(max(input)); if (maxIm~=0) input = input/maxIm; end input = 1-input; colimage = cat(3, input, input, input); set(hPreviewControlProcessed,'CData', colimage,'Visible','on'); % update icon edit pane set(hIconEditPanel, 'Title',['Icon Edit Pane (', num2str(rows),' X ', num2str(cols),')']); s = findobj(hIconEditPanel,'type','surface'); if isempty(s) gridColor = get(0, 'defaultuicontrolbackgroundcolor') - 0.2; gridColor(gridColor<0)=0; s=surface('edgecolor',gridColor,'parent',hIconEditAxes); end %set xdata, ydata, zdata in case the rows and/or cols change set(s,'xdata',0:cols,'ydata',0:rows,'zdata',zeros(rows+1,cols+1),'cdata',localGetIconCDataWithNaNs()); set(hIconEditAxes,'xlim',[-.5 cols+.5],'ylim',[-.5 rows+.5]); axis(hIconEditAxes, 'ij', 'off'); hRecognizeButtonCallback(); end %------------------------------------------------------------------ function cdwithnan = localGetIconCDataWithNaNs() % Add NaN to edge of mIconCData so the entire icon renders in the % drawing pane. This is necessary because of surface behavior. cdwithnan = mIconCData; cdwithnan(:,end+1,:) = NaN; cdwithnan(end+1,:,:) = NaN; end %------------------------------------------------------------------ function isValid = localValidateInput(property, value) % helper function that validates the user provided input property/value % pairs. You can choose to show warnings or errors here. isValid = false; switch lower(property) case {'iconwidth', 'iconheight'} if isnumeric(value) && value >0 isValid = true; end case 'MNISTfile' if exist(value,'file')==2 isValid = true; end end end end % end of iconEditor %------------------------------------------------------------------ function prepareLayout(topContainer) % This is a utility function that takes care of issues related to % look&feel and running across multiple platforms. You can reuse % this function in other GUIs or modify it to fit your needs. allObjects = findall(topContainer); warning off %Temporary presentation fix try titles=get(allObjects(isprop(allObjects,'TitleHandle')), 'TitleHandle'); allObjects(ismember(allObjects,[titles{:}])) = []; catch end warning on % Use the name of this GUI file as the title of the figure defaultColor = get(0, 'defaultuicontrolbackgroundcolor'); if isa(handle(topContainer),'figure') set(topContainer,'Name', mfilename, 'NumberTitle','off'); % Make figure color matches that of GUI objects set(topContainer, 'Color',defaultColor); end % Make GUI objects available to callbacks so that they cannot % be changes accidentally by other MATLAB commands set(allObjects(isprop(allObjects,'HandleVisibility')), 'HandleVisibility', 'Callback'); % Make the GUI run properly across multiple platforms by using % the proper units if strcmpi(get(topContainer, 'Resize'),'on') set(allObjects(isprop(allObjects,'Units')),'Units','Normalized'); else set(allObjects(isprop(allObjects,'Units')),'Units','Characters'); end % You may want to change the default color of editbox, % popupmenu, and listbox to white on Windows if ispc candidates = [findobj(allObjects, 'Style','Popupmenu'),... findobj(allObjects, 'Style','Edit'),... findobj(allObjects, 'Style','Listbox')]; set(findobj(candidates,'BackgroundColor', defaultColor), 'BackgroundColor','white'); end end function out = preproc_image(id) %Preprocess single image Inorm = id(:,:,1); Inorm(~isfinite(Inorm)) = 1; Inorm = abs(Inorm-1)'; out = zeros(32); out(3:30,3:30) = Inorm; if sum(out(:))>0, out = reshape(mapstd(out(:)'), 32, 32); end end function I = readMNIST_image(filepath,num) %readMNIST_image MNIST handwriten image database reading. Reads only images %without labels, with specified filename % % Syntax % % I = readMNIST_image(filepath,num) % % Description % Input: % filepath - name of database file with path % n - number of images to process % Output: % I - cell array of training images 28x28 size % %(c) Sirotenko Mikhail, 2009 %===========Loading training set fid = fopen(filepath,'r','b'); %big-endian magicNum = fread(fid,1,'int32'); %Magic number if(magicNum~=2051) display('Error: cant find magic number'); return; end imgNum = fread(fid,1,'int32'); %Number of images rowSz = fread(fid,1,'int32'); %Image height colSz = fread(fid,1,'int32'); %Image width if(num<imgNum) imgNum=num; end for k=1:imgNum I{k} = uint8(fread(fid,[rowSz colSz],'uchar')); end fclose(fid); end
github
hagaygarty/mdCNN-master
getMNISTdata.m
.m
mdCNN-master/Demo/MNIST/getMNISTdata.m
4,562
utf_8
7c5420b0382bdcc938bba7643ec46b8a
function [ MNIST ] = getMNISTdata( dst_folder ) % this function will download the MNIST dataset if not exist already. % after downloading it will then parse the files and create a MNIST.mat file % containing the test/train images and labels. % function returns a struct containing the images+labels % I,labels,I_test,labels_test , every element in the struct is an array containing the images/labels outFile = fullfile(dst_folder ,'MNIST.mat'); if (~exist(outFile,'file')) url='http://yann.lecun.com/exdb/mnist/'; files = {'t10k-labels-idx1-ubyte.gz', 'train-labels-idx1-ubyte.gz' , 'train-images-idx3-ubyte.gz', 't10k-images-idx3-ubyte.gz'}; fprintf('Preparing MNIST.mat file since it does not exist. (done only once)\n'); for fileIdx=1:numel(files) [~,fname,~] = fileparts(files{fileIdx}); if ( exist(fullfile(dst_folder,fname),'file')) continue; end fprintf('Downloading file %s from %s ...',files{fileIdx},url); gunzip([url files{fileIdx}], dst_folder); fprintf('Done\n'); end parseMNISTfiles(dst_folder,outFile); end MNIST = load(outFile); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [] = parseMNISTfiles(path,outFile) %readMNIST MNIST handwriten image database reading. % Output: % I - cell array of training images 28x28 size % labels - vector of labels (true digits) for training set % I_test - cell array of testing images 28x28 size % labels_test - vector of labels (true digits) for testing set if (exist('path','var')==0) path = './'; end fprintf('Parsing MNIST dataset\n'); if(~exist(fullfile(path ,'train-images-idx3-ubyte'),'file')) error('Training set of MNIST not found. Please download it from http://yann.lecun.com/exdb/mnist/ and put to ./MNIST folder'); end fid = fopen(fullfile(path ,'train-images-idx3-ubyte'),'r','b'); %big-endian magicNum = fread(fid,1,'int32'); %Magic number if(magicNum~=2051) display('Error: cant find magic number'); return; end imgNum = fread(fid,1,'int32'); %Number of images rowSz = fread(fid,1,'int32'); %Image height colSz = fread(fid,1,'int32'); %Image width for k=1:imgNum I{k} = uint8(fread(fid,[rowSz colSz],'uchar'))'; end fclose(fid); %============Loading labels if(~exist(fullfile(path, 'train-labels-idx1-ubyte') ,'file')) error('Training labels of MNIST not found. Please download it from http://yann.lecun.com/exdb/mnist/ and put to ./MNIST folder'); end fid = fopen(fullfile(path ,'train-labels-idx1-ubyte'),'r','b'); %big-endian magicNum = fread(fid,1,'int32'); %Magic number if(magicNum~=2049) display('Error: cant find magic number'); return; end itmNum = fread(fid,1,'int32'); %Number of labels labels = uint8(fread(fid,itmNum,'uint8')); %Load all labels fclose(fid); %============All the same for test set if(~exist(fullfile(path, 't10k-images-idx3-ubyte'),'file')) error('Test images of MNIST not found. Please download it from http://yann.lecun.com/exdb/mnist/ and put to ./MNIST folder'); end fid = fopen(fullfile(path, 't10k-images-idx3-ubyte'),'r','b'); magicNum = fread(fid,1,'int32'); if(magicNum~=2051) display('Error: cant find magic number'); return; end imgNum = fread(fid,1,'int32'); rowSz = fread(fid,1,'int32'); colSz = fread(fid,1,'int32'); for k=1:imgNum I_test{k} = uint8(fread(fid,[rowSz colSz],'uchar'))'; end fclose(fid); %============Test labels if(~exist(fullfile(path, 't10k-labels-idx1-ubyte'),'file')) error('Test labels of MNIST not found. Please download it from http://yann.lecun.com/exdb/mnist/ and put to ./MNIST folder'); end fid = fopen(fullfile(path, 't10k-labels-idx1-ubyte'),'r','b'); magicNum = fread(fid,1,'int32'); if(magicNum~=2049) display('Error: cant find magic number'); return; end itmNum = fread(fid,1,'int32'); labels_test = uint8(fread(fid,itmNum,'uint8')); fclose(fid); labels = fixErrorsInMNIST(labels); save(outFile,'I','labels','I_test','labels_test'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ labels ] = fixErrorsInMNIST( labels ) % some clear errors found on original MnisT data set. The below corrects % the labels errorsIdx = [59916 10995 26561 32343 43455 45353]; correctLabels = [ 7 9 1 7 3 1]; for idx=1:length(errorsIdx) labels(errorsIdx(idx)) = correctLabels(idx); end end
github
hagaygarty/mdCNN-master
printNetwork.m
.m
mdCNN-master/utilCode/printNetwork.m
914
utf_8
5e6628fbb920522eeb1bff389249af27
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Copyright (C) 2015-16 Hagay Garty. % [email protected] , mdCNN library %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ ] = printNetwork( net ) disp(struct2table(net.hyperParam)); disp(struct2table(net.runInfoParam)); for k=1:size(net.layers,2) fprintf('Layer %d: ',k); if (isfield(net.layers{k}.properties,'Activation')) fprintf('Activation=%s, dActivation=%s\n', func2str(net.layers{k}.properties.Activation) , func2str(net.layers{k}.properties.dActivation)); elseif (isfield(net.layers{k}.properties,'lossFunc')) fprintf('lossFunc=%s, costFunc=%s\n', func2str(net.layers{k}.properties.lossFunc) , func2str(net.layers{k}.properties.costFunc)); else fprintf('\n'); end disp(struct2table(net.layers{k}.properties)); end fprintf('Network properties:\n\n'); disp(struct2table(net.properties)); end
github
hagaygarty/mdCNN-master
GetNetworkInputs.m
.m
mdCNN-master/Training/GetNetworkInputs.m
4,395
utf_8
1cf0ffc19a6babd506588af9d76875af
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Copyright (C) 2015-16 Hagay Garty. % [email protected] , mdCNN library %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ image ] = GetNetworkInputs(image , net , testTime) %% function manipulate a sample and preperes it for passing into the net first layer %% preperation can be bias removal , chane to variance 1 , scaling or patch selection , depending on the configuration inputDim = net.layers{1}.properties.sizeFm; inputDim(end+1) = net.layers{1}.properties.numFm; if ( (inputDim(end-1)==1) && (ndims(image)==3) && (net.layers{1}.properties.numFm~=size(image,ndims(image)))) image = rgb2gray(image); %TODO - for color images? color 3d Images?? end image=double(image); if (net.layers{1}.properties.numFm~=1) sz=size(image); singleFmDim=[sz(1:end-1) 1 1 1]; singleFmDim = singleFmDim(1:3); image = reshape(image , [singleFmDim net.layers{1}.properties.numFm] ); end if (net.hyperParam.normalizeNetworkInput==1) for fm=1:net.layers{1}.properties.numFm singleFm=image(:,:,:,fm); singleFm = singleFm-min(singleFm(:)); if ( isfield(net.hyperParam.augmentParams, 'medianFilt') && (net.hyperParam.augmentParams.medianFilt > 0) ) data = sort(singleFm(:)); th = data(floor((length(data)-1)*net.hyperParam.augmentParams.medianFilt+1)); singleFm(singleFm<th) = 0; end maxImg=max(singleFm(:)); if ( maxImg~=0 ) singleFm = singleFm/maxImg; end image(:,:,:,fm) = singleFm; end end if (net.hyperParam.centralizeImage) && (~testTime) cm = round(centerOfMass(image))+1; tmpImage = padarray(image, ceil(size(image)/2),image(1,1),'replicate'); image = tmpImage( cm(1):(cm(1)-1+size(image,1)) , cm(2):(cm(2)-1+size(image,2))); end if (net.hyperParam.cropImage) && (~testTime) maxBrightness=1/10; thFordetection = 0.03; outOfBounds = image >= maxBrightness; goodLines=find(sum(outOfBounds,2) > thFordetection * size(image,2)); if (isempty(goodLines)) goodLines = 1:size(image,1); end goodRows=find(sum(outOfBounds,1) > thFordetection * size(image,1)); if (isempty(goodRows)) goodRows = 1:size(image,2); end image([1:goodLines(1)-1 goodLines(end)+1:end],:) = []; image(:,[1:goodRows(1)-1 goodRows(end)+1:end]) = []; % border=2; % image = padarray(image, [border border],image(1,1),'replicate'); end if (net.hyperParam.useRandomPatch>0) varImage=-Inf; iter=0; maxIter=1000; origIm=image; while(varImage<net.hyperParam.selevtivePatchVarTh) image = origIm; % patchSize=net.layers{1}.properties.sizeFm; % patchSize = [patchSize(patchSize>1) net.layers{1}.properties.numFm]; patchSize = inputDim(1:3); szFm = [size(image) 1 1 1]; szFm = szFm(1:3); image = padarray(image,max(0,patchSize-szFm)); szFm = [size(image) 1 1 1]; szFm = szFm(1:3); maxStride = max(1,szFm-patchSize+1); if ((testTime) && (net.hyperParam.testOnMiddlePatchOnly==1)) starts = round(maxStride/2);%during test take only the middle patch else starts = arrayfun(@randi,maxStride); end ends = starts+patchSize-1; image = image(starts(1):ends(1) , starts(2):ends(2) , starts(3):ends(3),:); firstFm = image(:,:,:,1); varImage = var(firstFm(:)); iter=iter+1; if ( iter>1 ) % fprintf('\nSearch iter %d, size=%s, th=%f\n',iter, num2str(size(origIm)),net.hyperParam.selevtivePatchVarTh ); end if (iter>=maxIter) fprintf('\ncouldn''t find patch in an image after %d tries, size=%s, th=%f\n',maxIter, num2str(size(origIm)),net.hyperParam.selevtivePatchVarTh); %assert(iter<maxIter , 'How come? bad image?\n'); break; end end end image = imresize3d(image, inputDim); if (net.hyperParam.normalizeNetworkInput==1) varFact = sqrt(var(image(:))); if (varFact==0) varFact=1; end image = (image-mean(image(:))) /varFact;%normlize to mean 0 and var=1 end if (net.hyperParam.flipImage==1) && (~testTime) for dim=length(find(net.layers{1}.properties.sizeFm>1)):-1:1 if (randi(2)==1) image = flip(image,dim); end end end if (net.layers{1}.properties.numFm~=1) image = reshape(image , inputDim); end end
github
hagaygarty/mdCNN-master
Train.m
.m
mdCNN-master/Training/Train.m
17,319
utf_8
d0eb25c1612f419fa3af950ec9eb14ba
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Copyright (C) 2015-16 Hagay Garty. % [email protected] , mdCNN library %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ net ] = Train( dataset , net , numSamplesToTrain ) %% function will train the network on a given dataset if (~exist('numSamplesToTrain','var')) numSamplesToTrain=Inf; end logFolder = fullfile(pwd,'Logs'); if ( ~isdir(logFolder) ) mkdir(logFolder); end diary(fullfile(logFolder ,['Console_' datestr(now,'dd-mm-yyyy_hh-MM-ss') '.txt'])); %dataset = normalize(dataset); net.runInfoParam.datasetInfo.numTest = length(dataset.I_test); net.runInfoParam.datasetInfo.numTrain = length(dataset.I); net.runInfoParam.datasetInfo.firstImSize = num2str(size(dataset.I{1})); net.runInfoParam.datasetInfo.varFirstIm = var(double(dataset.I{1}(:))); net.runInfoParam.datasetInfo.minFirstIm = min(double(dataset.I{1}(:))); net.runInfoParam.datasetInfo.maxFirstIm = max(double(dataset.I{1}(:))); fprintf('Dataset info - test: %d, train: %d, first sample size:=%s, var=%.2f, min=%f, max=%f\n',... net.runInfoParam.datasetInfo.numTest,net.runInfoParam.datasetInfo.numTrain , net.runInfoParam.datasetInfo.firstImSize , ... net.runInfoParam.datasetInfo.varFirstIm, net.runInfoParam.datasetInfo.minFirstIm, net.runInfoParam.datasetInfo.maxFirstIm); %printNetwork(net); if(net.runInfoParam.verifyBP==1) verifyBackProp(net); net.runInfoParam.verifyBP=0;% no need to verify anymore end assert(net.layers{1}.properties.numFm==1 || net.layers{1}.properties.numFm==size(dataset.I{1},ndims(dataset.I{1})), 'Error - num Fm of input (%d) does not match network configuration (%s)',size(dataset.I{1},ndims(dataset.I{1})),num2str([net.layers{1}.properties.sizeFm net.layers{1}.properties.numFm])); assert(net.layers{end}.properties.numFm>max(dataset.labels) && min(dataset.labels)>=0, ['Error - size of output layer is too small for input. Output layer size is ' num2str(net.layers{end-1}.properties.numFm) ', labels should be in the range 0-' num2str(net.layers{end-1}.properties.numFm-1), '. current labels range is ' num2str(min(dataset.labels)) , '-' num2str(max(dataset.labels))]); if ( length(unique(dataset.labels)) ~= net.layers{end}.properties.numFm) warning(['Training samples does not contain all classes. These should be ' num2str(net.layers{end}.properties.numFm) ' unique classes in training set, but it looks like there are ' num2str(length(unique(dataset.labels))) ' classes']); end if ( runstest(dataset.labels) == 1 ) || issorted(dataset.labels) || issorted(fliplr(dataset.labels) ) warning('Training samples apear not to be in random order. For training to work well, class order in dataset need to be random. Please suffle labels and I (using the same seed) before passing to Train'); end assert(ndims((zeros([net.layers{1}.properties.sizeFm net.layers{1}.properties.numFm])))==ndims(GetNetworkInputs(dataset.I{1},net,1)), 'Error - input does not match network configuration (input size + num FM)'); tic; if (net.hyperParam.addBackround==1) backroundImages = loadBackroundImages(); fprintf('Finished loading backround images\n'); end rng(net.runInfoParam.endSeed); net.runInfoParam.startLoop=clock; maxSamplesToTrain = numSamplesToTrain + net.runInfoParam.samplesLearned; fprintf('Start training on %d samples (%.1f epocs, %d batches, batchSize=%d)\n', numSamplesToTrain , numSamplesToTrain/length(dataset.I), floor(numSamplesToTrain/net.hyperParam.batchNum),net.hyperParam.batchNum); if (net.runInfoParam.iter==0) net.runInfoParam.iterInfo(net.runInfoParam.iter+1).ni = net.hyperParam.ni_initial; else net.runInfoParam.iterInfo(net.runInfoParam.iter+1).ni = net.runInfoParam.iterInfo(net.runInfoParam.iter).ni; end if (~isfield(net.runInfoParam,'loss_train')) net.runInfoParam.loss_train=[]; net.runInfoParam.loss_test=[]; net.runInfoParam.sucessRate_Test=[]; net.runInfoParam.sucessRate_Train=[]; end figure('Name','Training stats'); trainLoopCount = ceil(net.hyperParam.trainLoopCount/net.hyperParam.batchNum)*net.hyperParam.batchNum; testLoopCount = ceil(net.hyperParam.testImageNum/net.hyperParam.batchNum)*net.hyperParam.batchNum; Batch = zeros([net.layers{1}.properties.sizeOut net.hyperParam.batchNum]); expectedOut = zeros([net.layers{end}.properties.sizeOut net.hyperParam.batchNum]); %% Main epoc loop while (1) net.runInfoParam.iter=net.runInfoParam.iter+1; fprintf('Iter %-3d| samples=%-4d',net.runInfoParam.iter,net.runInfoParam.samplesLearned+trainLoopCount); startIter=clock; net.runInfoParam.iterInfo(net.runInfoParam.iter).rmsErr=0; net.runInfoParam.iterInfo(net.runInfoParam.iter).rmsGrad=0; rmsErrCnt=0; %% start training loop batchIdx=0; for i=1:trainLoopCount batchIdx=batchIdx+1; if (net.hyperParam.randomizeTrainingSamples==1) idx = randi(length(dataset.I)); else idx = mod(net.runInfoParam.samplesLearned,length(dataset.I))+1; end sample=double(dataset.I{idx}); label = dataset.labels(idx); % do augmentation if rquired in configuration if (net.hyperParam.augmentImage==1) [sample,complement] = manipulateImage(sample,net.hyperParam.augmentParams.noiseVar , net.hyperParam.augmentParams.maxAngle , net.hyperParam.augmentParams.maxScaleFactor , net.hyperParam.augmentParams.minScaleFactor , net.hyperParam.augmentParams.maxStride, net.hyperParam.augmentParams.maxSigma , net.hyperParam.augmentParams.imageComplement); end % more optional augmentation, fusing with backround noise if (net.hyperParam.addBackround==1) backroundImage=backroundImages{randi(length(backroundImages))}; starty=randi(1+size(backroundImage,1)-size(sample,1)); startx=randi(1+size(backroundImage,2)-size(sample,2)); patch = double(backroundImage(starty:(starty+size(sample,1)-1) ,startx:(startx+size(sample,2)-1) )); switch randi(2) case 1 sample = imfuse(sample,patch); case 2 if (complement==1) sample = min(sample,patch); else sample = max(sample,patch); end end end % add a single sample to the batch %GetNetworkInputs will do flipping/scaling to the sample in order to match the network input layer. %Its a helper function not needed if the data is scaled correctly Batch(:,:,:,:,batchIdx) = GetNetworkInputs(sample, net, 0); expectedOut(:,:,batchIdx)=zeros(net.layers{end}.properties.sizeOut); expectedOut(1,label+1,batchIdx)=1; net.runInfoParam.samplesLearned=net.runInfoParam.samplesLearned+1; if (batchIdx<net.hyperParam.batchNum) continue; end batchIdx=0; % train on the batch net = backPropagate(net, Batch, expectedOut); % Calculate loss batchLoss = net.layers{end}.properties.costFunc(net.layers{end}.outs.activation,expectedOut); net.runInfoParam.loss_train(end+1) = mean(batchLoss(:)); % Get classification [~,netClassification] = max(squeeze(net.layers{end}.outs.activation)); [~,realClassification] = max(squeeze(expectedOut)); net.runInfoParam.sucessRate_Train(end+1) = sum(realClassification==netClassification)/length(realClassification)*100; net.runInfoParam.iterInfo(net.runInfoParam.iter).rmsGrad=net.runInfoParam.iterInfo(net.runInfoParam.iter).rmsGrad+perfomOnNetDerivatives(net,@(x)(rms(x))); net.runInfoParam.iterInfo(net.runInfoParam.iter).rmsErr=net.runInfoParam.iterInfo(net.runInfoParam.iter).rmsErr+rms(net.layers{end}.error(:)); % update weights net = updateWeights(net, net.runInfoParam.iterInfo(end).ni, net.hyperParam.momentum , net.hyperParam.lambda); rmsErrCnt=rmsErrCnt+1; end endIter=clock; net.runInfoParam.iterInfo(net.runInfoParam.iter).TrainTime=etime(endIter ,startIter); net.runInfoParam.iterInfo(net.runInfoParam.iter).rmsErr = net.runInfoParam.iterInfo(net.runInfoParam.iter).rmsErr/rmsErrCnt; net.runInfoParam.iterInfo(net.runInfoParam.iter).rmsGrad = net.runInfoParam.iterInfo(net.runInfoParam.iter).rmsGrad/rmsErrCnt; net.runInfoParam.iterInfo(net.runInfoParam.iter).rmsWeights = perfomOnNetWeights(net,@(x)(sqrt(mean(abs(x.^2))))); net.runInfoParam.iterInfo(net.runInfoParam.iter).varWeights = perfomOnNetWeights(net,@var); fprintf(' | time=%-5.2f | lossTrain=%f | rmsErr=%f | rmsGrad=%f | meanWeight=%f | varWeight=%f' ,etime(endIter ,startIter), net.runInfoParam.loss_train(end), net.runInfoParam.iterInfo(net.runInfoParam.iter).rmsErr, net.runInfoParam.iterInfo(net.runInfoParam.iter).rmsGrad, net.runInfoParam.iterInfo(net.runInfoParam.iter).rmsWeights, net.runInfoParam.iterInfo(net.runInfoParam.iter).varWeights ); startTesting=clock; %% testSet loop batchIdx=0;res=[];lossPerSample=[]; for i=1:testLoopCount batchIdx=batchIdx+1; idx=mod(i-1,length(dataset.I_test))+1; sample=double(dataset.I_test{idx}); label = dataset.labels_test(idx); Batch(:,:,:,:,batchIdx) = GetNetworkInputs(sample, net, 1); expectedOut(:,:,batchIdx)=zeros(net.layers{end}.properties.sizeOut); expectedOut(1,label+1,batchIdx)=1; if (batchIdx<net.hyperParam.batchNum) continue; end batchIdx=0; %classify the batch from test set net = feedForward(net, Batch , 1); % select the highest probability from network activations in last layer [~,netClassification] = max(squeeze(net.layers{end}.outs.activation)); [~,realClassification] = max(squeeze(expectedOut)); res = [res (realClassification==netClassification)]; batchLoss = net.layers{end}.properties.costFunc(net.layers{end}.outs.activation,expectedOut); lossPerSample = [lossPerSample ; squeeze(mean(batchLoss))]; end endTesting=clock; net.runInfoParam.loss_test(end+1) = mean(lossPerSample); net.runInfoParam.sucessRate_Test(end+1) = sum(res)/length(res)*100; %% plot training stats subplot(2,1,2); plot(net.runInfoParam.loss_train); hold on; plot( (1:length(net.runInfoParam.loss_test)) * length(net.runInfoParam.loss_train)/length(net.runInfoParam.loss_test) , net.runInfoParam.loss_test ,'-ok');hold off grid on;set(gca, 'YScale', 'log');xlabel('Batch num');ylabel('loss');title('loss');hold off;legend('train set','test set'); subplot(2,1,1); plot(net.runInfoParam.sucessRate_Train); hold on; plot( (1:length(net.runInfoParam.sucessRate_Test)) * length(net.runInfoParam.sucessRate_Train)/length(net.runInfoParam.sucessRate_Test) , net.runInfoParam.sucessRate_Test ,'-ok');hold off grid on;xlabel('Batch num');ylabel('success rate %');title('classification');hold off;legend('train set','test set','Location','SE'); drawnow; %% save iteration info net.runInfoParam.endSeed = rng; if (( net.runInfoParam.loss_test(end) <= net.runInfoParam.minLoss ) || ((exist('net_minM','var')==0)&& (net.runInfoParam.storeMinLossNet==1))) if ( net.runInfoParam.loss_test(end) <= net.runInfoParam.minLoss ) net.runInfoParam.minLoss = net.runInfoParam.loss_test(end); end if (net.runInfoParam.storeMinLossNet==1) net_minM=net; %#ok<NASGU> end end if (( net.runInfoParam.sucessRate_Test(end)>=net.runInfoParam.maxsucessRate ) || ((exist('net_maxS','var')==0)&& (net.runInfoParam.storeMinLossNet==1))) if ( net.runInfoParam.sucessRate_Test(end)>=net.runInfoParam.maxsucessRate ) net.runInfoParam.maxsucessRate = net.runInfoParam.sucessRate_Test(end); end if (net.runInfoParam.storeMinLossNet==1) net_maxS=net; %#ok<NASGU> end end save('net.mat','net'); if (net.runInfoParam.storeMinLossNet==1) save('net_maxS.mat','net_maxS'); save('net_minM.mat','net_minM'); end net.runInfoParam.iterInfo(net.runInfoParam.iter).loss=net.runInfoParam.loss_test(end); net.runInfoParam.iterInfo(net.runInfoParam.iter).sucessRate_Test=net.runInfoParam.sucessRate_Test(end); net.runInfoParam.iterInfo(end+1).ni=net.runInfoParam.iterInfo(end).ni; net.runInfoParam.iterInfo(net.runInfoParam.iter).TestTime=etime(endTesting ,startTesting ); net.runInfoParam.iterInfo(net.runInfoParam.iter).TotaolTime=etime(endTesting ,net.runInfoParam.startLoop ); net.runInfoParam.iterInfo(net.runInfoParam.iter).noImpCnt=net.runInfoParam.noImprovementCount; fprintf(' | lossTest=%f | scesRate=%-5.2f%% | minLoss=%f | maxS=%-5.2f%% | ni=%f' , net.runInfoParam.loss_test(end) , net.runInfoParam.sucessRate_Test(end),net.runInfoParam.minLoss,net.runInfoParam.maxsucessRate,net.runInfoParam.iterInfo(end).ni); fprintf(' | tstTime=%.2f',net.runInfoParam.iterInfo(net.runInfoParam.iter).TestTime); fprintf(' | totalTime=%.2f' ,net.runInfoParam.iterInfo(net.runInfoParam.iter).TotaolTime); fprintf(' | noImpCnt=%d/%d' ,net.runInfoParam.iterInfo(net.runInfoParam.iter).noImpCnt, net.hyperParam.noImprovementTh); fprintf('\n'); if (net.runInfoParam.samplesLearned>=maxSamplesToTrain) fprintf('Finish training. max samples reached\n'); break; end if (( net.runInfoParam.loss_test(end) <= net.runInfoParam.improvementRefLoss ) || ( net.runInfoParam.noImprovementCount > net.hyperParam.noImprovementTh )) if (net.runInfoParam.loss_test(end) > net.runInfoParam.improvementRefLoss) net.runInfoParam.iterInfo(end).ni=0.5*net.runInfoParam.iterInfo(end).ni; fprintf('Updating ni to %f after %d consecutive iterations with no improvement. Ref loss was %f\n', net.runInfoParam.iterInfo(end).ni, net.hyperParam.noImprovementTh, net.runInfoParam.improvementRefLoss); net.runInfoParam.improvementRefLoss = Inf; if (net.runInfoParam.iterInfo(end).ni< net.hyperParam.ni_final) fprintf('Finish testing. ni is smaller then %f\n',net.hyperParam.ni_final); break; end else net.runInfoParam.improvementRefLoss = net.runInfoParam.loss_test(end); end net.runInfoParam.noImprovementCount=0; else net.runInfoParam.noImprovementCount=net.runInfoParam.noImprovementCount+1; end end %%%%%%%%%%%%%%%%%%%%%%%%%% diary off; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ res ] = perfomOnNetWeights( net , func) weights=[]; for k=1:size(net.layers,2) if (net.layers{k}.properties.numWeights==0) continue end if (isequal(net.layers{k}.properties.type,net.types.fc)) % is fully connected layer weights=[weights ; net.layers{k}.fcweight(:)]; %#ok<AGROW> elseif (isequal(net.layers{k}.properties.type,net.types.conv)) for fm=1:length(net.layers{k}.weight) weights=[weights ; net.layers{k}.weight{fm}(:)]; %#ok<AGROW> end elseif (isequal(net.layers{k}.properties.type,net.types.batchNorm)) weights=[weights ; net.layers{k}.gamma(:) ; net.layers{k}.beta(:)]; %#ok<AGROW> end end res = func(weights); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ res ] = perfomOnNetDerivatives( net , func) dW=[]; for k=1:size(net.layers,2) if (net.layers{k}.properties.numWeights==0) continue end if (isequal(net.layers{k}.properties.type,net.types.fc)) % is fully connected layer dW=[dW ; net.layers{k}.dW(:)]; %#ok<AGROW> elseif (isequal(net.layers{k}.properties.type,net.types.conv)) for fm=1:length(net.layers{k}.weight) dW=[dW ; net.layers{k}.dW{fm}(:)]; %#ok<AGROW> end elseif (isequal(net.layers{k}.properties.type,net.types.batchNorm)) dW=[dW ; net.layers{k}.dgamma(:) ; net.layers{k}.dbeta(:)]; %#ok<AGROW> end end res = func(dW); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ images ] = normalizeSet( images ) avg = zeros(size(images{1})); for idx=1:length(images) images{idx} = rgb2ycbcr(double(images{idx})); avg = avg+images{idx}; end avg = avg / length(images); for idx=1:length(images) images{idx} = images{idx}-avg; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ images ] = normalize( images ) images.I = normalizeSet(images.I); images.I_test = normalizeSet(images.I_test); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ res ] = rms( x ) res = sqrt(mean(x.^2)); end
github
pquochuy/regression_forest-master
do_train.m
.m
regression_forest-master/forest_regression/do_train.m
1,133
utf_8
9de8d1db686fff6f6b0f41eca2af0d55
function forest = do_train(tr_X, tr_d, FOREST_CONFIG) fprintf('building the random forest\n'); forest(1, FOREST_CONFIG.numTree) = DecisionTree(); % use parfor for parallel training instead %parfor i = 1:FOREST_CONFIG.numTree for i = 1 : FOREST_CONFIG.numTree tree = DecisionTree(FOREST_CONFIG.maxDepth, FOREST_CONFIG.minSample, ... FOREST_CONFIG.inDim, FOREST_CONFIG.numThreshold, ... FOREST_CONFIG.iteration, FOREST_CONFIG.factory); % randomly pick dataPerTree amount of training data for each tree ind = (rand(size(tr_X,1), 1) <= FOREST_CONFIG.dataPerTree); % learn the tree with the selected subset of data forest(i) = parallelTrain(tree, tr_X(ind,:), tr_d(ind,:)); end % calibrate the trees with the whole training data fprintf('calibrating the forest\n'); data.X = X_tr; data.d = d_tr; for i = 1 : FOREST_CONFIG.numTree forest(i).fillAll(data); disp(['finished learning tree: %d']); end end function tree = parallelTrain(tree,X,d) data.X = X; data.d = d; tree.trainDepthFirst(data); end
github
trajtracker/trajtracker_analyze-master
xml2struct.m
.m
trajtracker_analyze-master/matlab/util/xml2struct.m
6,955
utf_8
58f0b998cc71b30b4a6a12b330cfe950
function [ s ] = xml2struct( file ) %Convert xml file into a MATLAB structure % [ s ] = xml2struct( file ) % % A file containing: % <XMLname attrib1="Some value"> % <Element>Some text</Element> % <DifferentElement attrib2="2">Some more text</Element> % <DifferentElement attrib3="2" attrib4="1">Even more text</DifferentElement> % </XMLname> % % Will produce: % s.XMLname.Attributes.attrib1 = "Some value"; % s.XMLname.Element.Text = "Some text"; % s.XMLname.DifferentElement{1}.Attributes.attrib2 = "2"; % s.XMLname.DifferentElement{1}.Text = "Some more text"; % s.XMLname.DifferentElement{2}.Attributes.attrib3 = "2"; % s.XMLname.DifferentElement{2}.Attributes.attrib4 = "1"; % s.XMLname.DifferentElement{2}.Text = "Even more text"; % % Please note that the following characters are substituted % '-' by '_dash_', ':' by '_colon_' and '.' by '_dot_' % % Written by W. Falkena, ASTI, TUDelft, 21-08-2010 % Attribute parsing speed increased by 40% by A. Wanner, 14-6-2011 % Added CDATA support by I. Smirnov, 20-3-2012 % % Modified by X. Mo, University of Wisconsin, 12-5-2012 if (nargin < 1) clc; help xml2struct return end if isa(file, 'org.apache.xerces.dom.DeferredDocumentImpl') || isa(file, 'org.apache.xerces.dom.DeferredElementImpl') % input is a java xml object xDoc = file; else %check for existance if (exist(file,'file') == 0) %Perhaps the xml extension was omitted from the file name. Add the %extension and try again. if (isempty(strfind(file,'.xml'))) file = [file '.xml']; end if (exist(file,'file') == 0) error(['The file ' file ' could not be found']); end end %read the xml file xDoc = xmlread(file); end %parse xDoc into a MATLAB structure s = parseChildNodes(xDoc); end % ----- Subfunction parseChildNodes ----- function [children,ptext,textflag] = parseChildNodes(theNode) % Recurse over node children. children = struct; ptext = struct; textflag = 'Text'; if hasChildNodes(theNode) childNodes = getChildNodes(theNode); numChildNodes = getLength(childNodes); for count = 1:numChildNodes theChild = item(childNodes,count-1); [text,name,attr,childs,textflag] = getNodeData(theChild); if (~strcmp(name,'#text') && ~strcmp(name,'#comment') && ~strcmp(name,'#cdata_dash_section')) %XML allows the same elements to be defined multiple times, %put each in a different cell if (isfield(children,name)) if (~iscell(children.(name))) %put existsing element into cell format children.(name) = {children.(name)}; end index = length(children.(name))+1; %add new element children.(name){index} = childs; if(~isempty(fieldnames(text))) children.(name){index} = text; end if(~isempty(attr)) children.(name){index}.('Attributes') = attr; end else %add previously unknown (new) element to the structure children.(name) = childs; if(~isempty(text) && ~isempty(fieldnames(text))) children.(name) = text; end if(~isempty(attr)) children.(name).('Attributes') = attr; end end else ptextflag = 'Text'; if (strcmp(name, '#cdata_dash_section')) ptextflag = 'CDATA'; elseif (strcmp(name, '#comment')) ptextflag = 'Comment'; end %this is the text in an element (i.e., the parentNode) if (~isempty(regexprep(text.(textflag),'[\s]*',''))) if (~isfield(ptext,ptextflag) || isempty(ptext.(ptextflag))) ptext.(ptextflag) = text.(textflag); else %what to do when element data is as follows: %<element>Text <!--Comment--> More text</element> %put the text in different cells: % if (~iscell(ptext)) ptext = {ptext}; end % ptext{length(ptext)+1} = text; %just append the text ptext.(ptextflag) = [ptext.(ptextflag) text.(textflag)]; end end end end end end % ----- Subfunction getNodeData ----- function [text,name,attr,childs,textflag] = getNodeData(theNode) % Create structure of node info. %make sure name is allowed as structure name name = toCharArray(getNodeName(theNode))'; name = strrep(name, '-', '_dash_'); name = strrep(name, ':', '_colon_'); name = strrep(name, '.', '_dot_'); attr = parseAttributes(theNode); if (isempty(fieldnames(attr))) attr = []; end %parse child nodes [childs,text,textflag] = parseChildNodes(theNode); if (isempty(fieldnames(childs)) && isempty(fieldnames(text))) %get the data of any childless nodes % faster than if any(strcmp(methods(theNode), 'getData')) % no need to try-catch (?) % faster than text = char(getData(theNode)); text.(textflag) = toCharArray(getTextContent(theNode))'; end end % ----- Subfunction parseAttributes ----- function attributes = parseAttributes(theNode) % Create attributes structure. attributes = struct; if hasAttributes(theNode) theAttributes = getAttributes(theNode); numAttributes = getLength(theAttributes); for count = 1:numAttributes %attrib = item(theAttributes,count-1); %attr_name = regexprep(char(getName(attrib)),'[-:.]','_'); %attributes.(attr_name) = char(getValue(attrib)); %Suggestion of Adrian Wanner str = toCharArray(toString(item(theAttributes,count-1)))'; k = strfind(str,'='); attr_name = str(1:(k(1)-1)); attr_name = strrep(attr_name, '-', '_dash_'); attr_name = strrep(attr_name, ':', '_colon_'); attr_name = strrep(attr_name, '.', '_dot_'); attributes.(attr_name) = str((k(1)+2):(end-1)); end end end
github
trajtracker/trajtracker_analyze-master
randl.m
.m
trajtracker_analyze-master/matlab/util/randl.m
1,023
utf_8
e04810eb8245f4f9ade58886ee568b76
% Return random variable(s) with linear distribution within [0,1] and % 0 outside; m specifies the slope % % In other word % P(x)= mx+b if 0<=x<=1 % P(x)= 0 otherwise % % where b=1-m/2 as int P(x) should be 1 % % Usage: ran=randl(m,SIZE) % % E.g. X=randl(1,[20,20]) % X is matrix with size [20,20] and with distribution % p(x)=x+0.5 if 0<=x<=1 and p(x)=0 otherwise % % Written by Samuel Cheng, Copyright 2005 % % You are allowed to redistribute or use the code if this mfile is unchanged. function ran=randl(m,SIZE) if exist('m')~=1 error('Please specified m. Help randl for more info'); end if abs(m)>2 error('abs(m) need to be smaller than 2'); end if exist('SIZE')~=1 SIZE=1; end if m>=0 randb=rand(SIZE)>(m/2); ran=randb.*rand(SIZE) + (1-randb).*randtri(SIZE); else m=-m; randb=rand(SIZE)>(m/2); ran=randb.*rand(SIZE) + (1-randb).*randtri(SIZE); ran=1-ran; end % triangle rand function function randtri=randtri(SIZE) randtri=rand(SIZE)+rand(SIZE); randtri(randtri>1)=2-randtri(randtri>1);
github
kourouklides/NPBayesHMM-master
sampleFromMatrixNormal.m
.m
NPBayesHMM-master/code/rndgen/sampleFromMatrixNormal.m
290
utf_8
fc9c1da677157415def05d75fcac5769
%function S = sampleFromMatrixNormal(M,V,K,nSamples=1) function S = sampleFromMatrixNormal(M,sqrtV,sqrtinvK,nSamples) if ~exist('nSamples','var'), nSamples = 1; end [mu,sqrtsigma] = matrixNormalToNormal(M,sqrtV,sqrtinvK); S = mu + sqrtsigma'*randn(length(mu),1); S = reshape(S,size(M));
github
kourouklides/NPBayesHMM-master
matrixNormalToNormal.m
.m
NPBayesHMM-master/code/rndgen/matrixNormalToNormal.m
391
utf_8
f3b050c133b9819518869bfda1b4e8ab
%function [mu,sigma,a] = matrixNormalToNormal(M,V,K) % % Converts the parameters for a matrix normal A ~ MN(M,V,K) % into a multivariate normal A(:) ~ N(mu,sigma) % function [mu,sqrtsigma] = matrixNormalToNormal(M,sqrtV,sqrtinvK) mu = M(:); sqrtsigma = kron(sqrtinvK,sqrtV); % sigma = sqrtsigma'*sqrtsigma; % From Minka's paper, but order is wrong: %sigma = kron(V,inv(K));
github
kourouklides/NPBayesHMM-master
RunTimedMCMCSimForBPHMM.m
.m
NPBayesHMM-master/code/BPHMM/RunTimedMCMCSimForBPHMM.m
2,835
utf_8
0e52d9151f5a3fda9489bcd9c02def92
% RunMCMCSimForBPHMM % Generic harness for running many iterations of MCMC, % allows sensible reporting/saving of samples and diagnostics %USAGE % Usually called from more "user-friendly" function "runBPHMM" % but if specific data and initial configuration Psi are available, % >> RunMCMCForBPHMM( data, Psi, algP, outP ) %INPUT % data : SeqData object, defining a collection of sequences to fit model % Psi : initial model state % usually generated by a function in the "init" folder % algParams : specifies MCMC behavior (# iterations, proposal distribs) % see defaults/defaultMCMCParams_BPHMM.m for details % outParams : specifies MCMC output behavior % how often to save samples, write to disk, etc. % see defaults/defaultOutputParams_BPHMM.m for details %OUTPUT % Markov Chain state variables saved at preset frequency to hard drive % at filepath location specified in outParams.saveDir function [ChainHist] = RunTimedMCMCSimForBPHMM( data, Psi, algParams, outParams, model ) tic; if isfield( Psi, 'F' ) % Stating chain from scratch n = 0; logPr = calcJointLogPr_BPHMMState( Psi, data ); ChainHist = recordMCMCHistory_BPHMM( 0, outParams, [], Psi, logPr ); fprintf( 'Initial Config: \n' ); printTimedMCMCSummary_BPHMM( 0, Psi, logPr, algParams); else ChainHist = Psi; Psi = unpackBPHMMState( ChainHist.Psi(end), data, model ); logPr = calcJointLogPr_BPHMMState( Psi, data ); n = ChainHist.iters.Psi(end ); fprintf( 'Resumed Config: \n' ); printTimedMCMCSummary_BPHMM( 0, Psi, logPr, algParams); end fprintf( 'Running MCMC Sampler %d : %d ... \n', outParams.jobID, outParams.taskID ); while toc < algParams.TimeLimit n = n + 1; Psi.iter = n; % Perform 1 iteration of MCMC, moving to next Markov state! [Psi, Stats] = BPHMMsample( Psi, data, algParams ); % Diagnose convergence by calculating joint log pr. of all sampled vars if n == 1 || rem(n, outParams.logPrEvery)==0 % NB: not passing "data" as arg means Psi stores all X suff stats logPr = calcJointLogPr_BPHMMState( Psi ); end %Record current sampler state % NB: internally only records at preset frequency ChainHist = recordMCMCHistory_BPHMM( n, outParams, ChainHist, Psi, logPr, Stats ); doSaveToDisk = n==1 || rem(n, outParams.saveEvery)==0 || toc > algParams.TimeLimit; if doSaveToDisk filename = fullfile( outParams.saveDir, 'SamplerOutput.mat' ); save(filename, '-struct', 'ChainHist'); end if n == 1 || rem(n, outParams.printEvery)==0 printTimedMCMCSummary_BPHMM( n, Psi, logPr, algParams); end end % loop over sampler iterations fprintf( '<<<<< --------------------------------------------------- \n'); end % main function
github
kourouklides/NPBayesHMM-master
RunMCMCSimForBPHMM.m
.m
NPBayesHMM-master/code/BPHMM/RunMCMCSimForBPHMM.m
2,798
utf_8
6cab19d0c33a28b0421ee357492ce6bb
% RunMCMCSimForBPHMM % Generic harness for running many iterations of MCMC, % allows sensible reporting/saving of samples and diagnostics %USAGE % Usually called from more "user-friendly" function "runBPHMM" % but if specific data and initial configuration Psi are available, % >> RunMCMCForBPHMM( data, Psi, algP, outP ) %INPUT % data : SeqData object, defining a collection of sequences to fit model % Psi : initial model state % usually generated by a function in the "init" folder % algParams : specifies MCMC behavior (# iterations, proposal distribs) % see defaults/defaultMCMCParams_BPHMM.m for details % outParams : specifies MCMC output behavior % how often to save samples, write to disk, etc. % see defaults/defaultOutputParams_BPHMM.m for details %OUTPUT % Markov Chain state variables saved at preset frequency to hard drive % at filepath location specified in outParams.saveDir function [ChainHist] = RunMCMCSimForBPHMM( data, Psi, algParams, outParams, model ) tic; if isfield( Psi, 'F' ) % Stating chain from scratch n = 0; logPr = calcJointLogPr_BPHMMState( Psi, data ); ChainHist = recordMCMCHistory_BPHMM( 0, outParams, [], Psi, logPr ); fprintf( 'Initial Config: \n' ); printMCMCSummary_BPHMM( 0, Psi, logPr, algParams); else ChainHist = Psi; Psi = unpackBPHMMState( ChainHist.Psi(end), data, model ); logPr = calcJointLogPr_BPHMMState( Psi, data ); n = ChainHist.iters.Psi(end ); fprintf( 'Resumed Config: \n' ); printMCMCSummary_BPHMM( n, Psi, logPr, algParams); end fprintf( 'Running MCMC Sampler %d : %d ... \n', outParams.jobID, outParams.taskID ); for n=n+1:algParams.Niter Psi.iter = n; % Perform 1 iteration of MCMC, moving to next Markov state! [Psi, Stats] = BPHMMsample( Psi, data, algParams ); % Diagnose convergence by calculating joint log pr. of all sampled vars if n == 1 || rem(n, outParams.logPrEvery)==0 % NB: not passing "data" as arg means Psi stores all X suff stats logPr = calcJointLogPr_BPHMMState( Psi ); end %Record current sampler state % NB: internally only records at preset frequency ChainHist = recordMCMCHistory_BPHMM( n, outParams, ChainHist, Psi, logPr, Stats ); doSaveToDisk = n==1 || rem(n, outParams.saveEvery)==0 || n == algParams.Niter; if doSaveToDisk filename = fullfile( outParams.saveDir, 'SamplerOutput.mat' ); save(filename, '-struct', 'ChainHist'); end if n == 1 || rem(n, outParams.printEvery)==0 printMCMCSummary_BPHMM( n, Psi, logPr, algParams); end end % loop over sampler iterations fprintf( '<<<<< --------------------------------------------------- \n'); end % main function
github
kourouklides/NPBayesHMM-master
sampleSingleFeat_UniqueRJStateSeq.m
.m
NPBayesHMM-master/code/BPHMM/sampler/sampleSingleFeat_UniqueRJStateSeq.m
9,527
utf_8
470385bdbd73ea5335d2157a32a7d43e
function [Psi, RhoTerms] = ... sampleSingleFeat_UniqueRJStateSeq( ii, Psi, data, algParams ) % Sample a unique entry in the feature vector of sequence "ii" % Uses reversible jump to either % Create new feature ("birth") % Delete cur feature ("death") %INPUT % ii : integer id of specific sequence to examine % Psi : model configuration (includes feat asgns and HMM params) % data : SeqObs data object % data for sequence ii accessed by call "data.seq(ii)" % algParams : param struct specifies details of proposal move %OUTPUT % Psi : new model config (with potentially new unique features for ii ) % RhoTerms : some stats about the MH proposal and what kind of move occurs doDebug=0; % ======================================================== UNPACK F = Psi.F; propStateSeq = Psi.stateSeq; propF = F; gamma = Psi.bpM.gamma; c = Psi.bpM.c; featureCounts = sum( F, 1 ); availFeatIDs = find( F(ii,:) > 0 ); K = size(F,2); N = size(F,1); Kii = length( availFeatIDs ); uniqueFeatIDs = availFeatIDs( featureCounts( availFeatIDs ) == 1 ); uCur = length(uniqueFeatIDs); % -------------------------------- DETERMINISTIC Eta prop propTransM = Psi.TransM.getAllEta_PriorMean( ii, [F zeros(N,1)], K+1 ); EtaHatAll = propTransM.seq(ii); % ------------------------------- DETERMINISTIC Theta prop ThetaHat = Psi.ThetaM; for kk = availFeatIDs PN = ThetaHat.getPosteriorParams( ThetaHat.Xstats(kk) ); ThetaHat.theta(kk) = Psi.ThetaM.getTheta_Mean( PN ); end switch algParams.RJ.birthPropDistr case {'Prior','prior'} wstart = 0; wend = 0; [thetaStar] = ThetaHat.getTheta_Mean( ); ThetaHat = ThetaHat.insertTheta( thetaStar ); case {'DataDriven', 'DD', 'datadriven'} [wstart, wend, L] = drawRandomSubwindow( data.Ts(ii), algParams.RJ.minW, algParams.RJ.maxW ); if strcmp( class(data), 'ARSeqData' ) X = data.seq(ii); Xprev = data.prev(ii); PN = ThetaHat.getPosteriorParams( ThetaHat.getXSuffStats( X(:,wstart:wend), Xprev(:,wstart:wend) ) ); else X = data.seq(ii); PN = ThetaHat.getPosteriorParams( ThetaHat.getXSuffStats( X(:,wstart:wend) ) ); end thetaStar = ThetaHat.getTheta_Mean(PN); ThetaHat = ThetaHat.insertTheta( thetaStar ); end seqSoftEv = ThetaHat.calcLogSoftEv( ii, data, [availFeatIDs K+1] ); % Define prob of proposing birth move % as deterministic function of the # of unique features PrBirth = @(uCur)1/2; qs = buildRJMoveDistr( uCur, Kii, PrBirth ); MoveType = multinomial_single_draw( qs ); if isfield( algParams, 'Debug' ) MoveType = algParams.Debug.MoveType; end if MoveType == 1 % ---------------------------------------------------- Birth: descrStr = 'birth'; kk = K+1; propF_ii = F(ii,:) == 1; propF_ii(kk) = 1; propF(ii,kk)=1; uNew = uCur + 1; % ----------------------------------------------- build eta % Birth move, keep around *all* of the entries in Pz EtaHat = EtaHatAll; % ----------------------------------------------- sample proposed z_ii propFeatIDs = [availFeatIDs K+1]; [propStateSeq(ii).z, logQ.z] = sampleSingleStateSeq_WithSoftEv( ii, EtaHat, seqSoftEv(propFeatIDs,:) ); propThetaHat = ThetaHat.decXStats( ii, data, Psi.stateSeq, availFeatIDs ); propThetaHat = propThetaHat.incXStats( ii, data, propStateSeq, propFeatIDs ); for jj = propFeatIDs PN = propThetaHat.getPosteriorParams( propThetaHat.Xstats(jj) ); propThetaHat.theta(jj) = propThetaHat.getTheta_Mean( PN ); end seqSoftEvRev = propThetaHat.calcLogSoftEv( ii, data, [availFeatIDs] ); seqSoftEvRev = seqSoftEvRev(availFeatIDs,:); % ----------------------------------------------- reverse to original z EtaHatOrig.availFeatIDs = availFeatIDs; EtaHatOrig.eta = EtaHatAll.eta( 1:Kii, 1:Kii); [~, logQ_Rev.z] = sampleSingleStateSeq_WithSoftEv( ii, EtaHatOrig, seqSoftEvRev, Psi ); % Probability of birth in current config logQ.moveChoice = log( qs(1) ); % Probability of killing the last feature in proposed config qsRev = buildRJMoveDistr( uNew, Kii+1, PrBirth ); logQ_Rev.moveChoice = log( qsRev( end ) ); RhoTerms.activeFeatIDs = kk; else % ---------------------------------------------------- Death: descrStr = 'death'; kk = uniqueFeatIDs( MoveType-1 ); propF_ii = F(ii,:) == 1; propF_ii( kk ) = 0; propF(ii,kk)=0; uNew = uCur - 1; % ----------------------------------------------- build eta jj = find( availFeatIDs == kk ); keepFeatIDs = [1:jj-1 jj+1:Kii]; EtaHat.availFeatIDs = availFeatIDs(keepFeatIDs); EtaHat.eta = EtaHatAll.eta( keepFeatIDs, keepFeatIDs ); % ----------------------------------------------- sample proposed z_ii [propStateSeq(ii).z, logQ.z] = sampleSingleStateSeq_WithSoftEv( ii, EtaHat, seqSoftEv( availFeatIDs(keepFeatIDs),:) ); propThetaHat = ThetaHat.decXStats( ii, data, Psi.stateSeq, availFeatIDs ); propThetaHat = propThetaHat.incXStats( ii, data, propStateSeq, availFeatIDs ); for jj = availFeatIDs(keepFeatIDs) PN = propThetaHat.getPosteriorParams( propThetaHat.Xstats(jj) ); propThetaHat.theta(jj) = propThetaHat.getTheta_Mean( PN ); end seqSoftEvRev = propThetaHat.calcLogSoftEv( ii, data, [availFeatIDs(keepFeatIDs) K+1] ); seqSoftEvRev = seqSoftEvRev( [availFeatIDs(keepFeatIDs) K+1],:); % ----------------------------------------------- reverse to original z EtaHatOrig.availFeatIDs = availFeatIDs; EtaHatOrig.eta = EtaHatAll.eta( 1:Kii, 1:Kii); [~, logQ_Rev.z] = sampleSingleStateSeq_WithSoftEv( ii, EtaHatOrig, seqSoftEvRev, Psi ); % Probability of death in current config logQ.moveChoice = log( qs(MoveType) ); % Probability of birth in proposed config qsRev = buildRJMoveDistr( uNew, Kii-1, PrBirth ); logQ_Rev.moveChoice = log( qsRev( 1 ) ); RhoTerms.activeFeatIDs = kk; end % Compute Joint Log Probability of Proposed/Current configurations % -------------------------------- p( F ) terms % U ~ Poisson( eta ) where eta = gamma*c/(c + N - 1) eta = gamma *c/(c + N -1 ); logPrNumFeat_Diff = ( uNew - uCur )*log( eta ) + gammaln( uCur + 1 ) - gammaln( uNew + 1 ); % -------------------------------- p( z_ii | F ) term logPrZ_Prop = Psi.TransM.calcMargPrStateSeq( propF, propStateSeq, ii ); logPrZ_Cur = Psi.TransM.calcMargPrStateSeq( F, Psi.stateSeq, ii ); % -------------------------------- p( x | z, F) terms if MoveType==1 logPrObs_Prop = propThetaHat.calcMargPrData( data, propStateSeq, propFeatIDs ); else logPrObs_Prop = propThetaHat.calcMargPrData( data, propStateSeq, availFeatIDs(keepFeatIDs) ); end % Only concerned with the active features! logPrObs_Cur = Psi.ThetaM.calcMargPrData([], [], availFeatIDs); logQHastings = logQ_Rev.z - logQ.z ... + logQ_Rev.moveChoice - logQ.moveChoice; if algParams.doAnneal if Psi.invTemp == 0 && isinf(logQHastings) logQHastings = -Inf; % always want to ignore in this case! % this is a sign of something seriously bad with construction else logQHastings = Psi.invTemp * logQHastings; end end % Compute accept-reject ratio: ( see eq. 15 in BP HMM paper ) log_rho_star = logPrObs_Prop - logPrObs_Cur ... + logPrNumFeat_Diff ... + logPrZ_Prop - logPrZ_Cur ... + logQHastings; RhoTerms.thetaStar = thetaStar; RhoTerms.window = [wstart wend]; rho = exp(log_rho_star); assert( ~isnan(rho), 'ERROR: Accept ratio *rho* for unique features should never be NaN') rho = min( rho, 1 ); doAccept = rand < rho; % Binary indicator for if cur proposal accepted RhoTerms.doAccept = doAccept; RhoTerms.doBirth = strcmp( descrStr, 'birth' ); % if doDebug % propPsi.F = propF; % propPsi.stateSeq = propStateSeq; % propPsi.TransM = Psi.TransM; % propPsi.TransM.seq(ii) = EtaHat; % propPsi.ThetaM = propThetaHat; % propPsi.bpM = Psi.bpM; % % lPP = calcJointLogPr_BPHMMState( propPsi, data); % lPC = calcJointLogPr_BPHMMState( Psi, data); % assert( allEq( lPP.obs-lPC.obs, logPrObs_Prop-logPrObs_Cur), 'bad' ); % assert( allEq( lPP.z -lPC.z , logPrZ_Prop-logPrZ_Cur), 'bad' ); % end if doAccept switch descrStr case 'birth' f_ii_kk = 1; case 'death' f_ii_kk = 0; end Psi.F( ii, kk ) = f_ii_kk; Psi.stateSeq = propStateSeq; Psi.ThetaM = propThetaHat; Psi.TransM = Psi.TransM.setEta( ii, propF_ii, EtaHat.eta ); if isfield( Psi, 'cache') Psi = rmfield( Psi, 'cache'); end %if isfield(Psi,'cache') && isfield( Psi.cache, 'logSoftEv' ) % if strcmp( descrStr, 'birth' ) % Psi.cache.logSoftEv{ii} = seqSoftEv; % end %else % Psi.cache.logSoftEv{ii} = seqSoftEv; %end if strcmp( descrStr,'death') Psi = reallocateFeatIDs( Psi ); end end end % MAIN FUNCTION % Draw a random subwindow for data-driven proposal % First choose window length L % Then choose starting position (which can support that length L ) function [wstart, wend, L] = drawRandomSubwindow( TT, minW, maxW ) Ls = minW:maxW; Ls = Ls( Ls >= 1 ); Ls = Ls( Ls <= TT ); if isempty(Ls) Ls = TT; end distrLs = ones( size(Ls) ); L = Ls( multinomial_single_draw( distrLs ) ); wstart = randi( [1 TT-L+1] ); wend = wstart + L - 1; end
github
kourouklides/NPBayesHMM-master
sampleSingleFeatEntry_UniqueRJ.m
.m
NPBayesHMM-master/code/BPHMM/sampler/sampleSingleFeatEntry_UniqueRJ.m
8,527
utf_8
88b619d965be1c3bfd4497784c3fd374
function [Psi, RhoTerms] = ... sampleSingleFeatEntry_UniqueRJ( ii, Psi, data, algParams ) % Sample a unique entry in the feature vector of sequence "ii" % Uses reversible jump to either % Create new feature ("birth") % Delete cur feature ("death") %INPUT % ii : integer id of specific sequence to examine % Psi : model configuration (includes feat asgns and HMM params) % data : SeqObs data object % data for sequence ii accessed by call "data.seq(ii)" % algParams : param struct specifies details of proposal move % algParams.theta.birthPropDistr can be any of: % --- 'prior' : emit param thetaStar drawn from prior % --- 'data-driven' : emit param thetaStar draw from data posterior %OUTPUT % Psi : new model config (with potentially new unique features for ii ) % RhoTerms : some stats about the MH proposal and what kind of move occurs % ======================================================== UNPACK F = Psi.F; TransM = Psi.TransM; ThetaM = Psi.ThetaM; gamma = Psi.bpM.gamma; c = Psi.bpM.c; featureCounts = sum( F, 1 ); availFeatIDs = find( F(ii,:) > 0 ); K = size(F,2); N = size(F,1); Kii = length( availFeatIDs ); uniqueFeatIDs = availFeatIDs( featureCounts( availFeatIDs ) == 1 ); uCur = length(uniqueFeatIDs); % -------------------------------- Eta prop propEta_ii = TransM.sampleEtaProposal_UniqueBirth( ii ); % ------------------------------- Theta prop switch algParams.RJ.birthPropDistr case {'Prior','prior'} choice = 1; wstart = 0; wend = 0; [thetaStar] = ThetaM.sampleThetaProposal_BirthPrior( ); propThetaM = ThetaM.insertTheta( thetaStar ); case {'DataDriven', 'DD', 'datadriven'} if isfield( algParams, 'Debug' ) && isfield( algParams.Debug, 'wstart' ) wstart = algParams.Debug.wstart; wend = algParams.Debug.wend; else [wstart, wend, L] = drawRandomSubwindow( data.Ts(ii), algParams.RJ.minW, algParams.RJ.maxW ); end [thetaStar,PPmix, choice] = ThetaM.sampleThetaProposal_BirthDataDriven( ii, data, wstart:wend ); propThetaM = ThetaM.insertTheta( thetaStar ); end % Define prob of proposing birth move % as deterministic function of the # of unique features PrBirth = @(uCur)1/2; qs = buildRJMoveDistr( uCur, Kii, PrBirth ); MoveType = multinomial_single_draw( qs ); if isfield( algParams, 'Debug' ) MoveType = algParams.Debug.MoveType; if MoveType == 0 if uCur == 0 || Kii==1 RhoTerms = struct('doBirth',0, 'doAccept',0); return; else MoveType = 1 + randsample( 1:uCur, 1); assert( MoveType <= length(qs), 'Bad choice for debug move selector'); end end end if MoveType == 1 % ---------------------------------------------------- Birth: descrStr = 'birth'; kk = K+1; propF_ii = F(ii,:) == 1; propF_ii(kk) = 1; uNew = uCur + 1; % ----------------------------------------------- build eta % Birth move, keep around *all* of the entries in Pz propEta = propEta_ii; switch algParams.RJ.birthPropDistr case {'DataDriven', 'DD', 'datadriven'} if algParams.RJ.doHastingsFactor logPrThetaStar_prior = propThetaM.calcLogPrTheta( thetaStar ); logPrThetaStar_prop = propThetaM.calcLogPrTheta_MixWithPrior( thetaStar, PPmix ); logPrTheta_Diff = logPrThetaStar_prior - logPrThetaStar_prop; else logPrTheta_Diff = -20; end case {'Prior', 'prior'} logPrTheta_Diff = 0; end % Probability of birth in current config logQ.moveChoice = log( qs(1) ); % Probability of killing the last feature in proposed config qsRev = buildRJMoveDistr( uNew, Kii+1, PrBirth ); logQ_Rev.moveChoice = log( qsRev( end ) ); RhoTerms.activeFeatIDs = kk; else % ---------------------------------------------------- Death: descrStr = 'death'; kk = uniqueFeatIDs( MoveType-1 ); propF_ii = F(ii,:) == 1; propF_ii( kk ) = 0; uNew = uCur - 1; % ----------------------------------------------- build eta jj = find( availFeatIDs == kk ); keepFeatIDs = [1:jj-1 jj+1:Kii]; propEta = propEta_ii( keepFeatIDs, keepFeatIDs ); % ----------------------------------------------- build theta switch algParams.RJ.birthPropDistr case {'DataDriven', 'DD', 'datadriven'} thetaStar = propThetaM.theta(kk); if algParams.RJ.doHastingsFactor logPrThetaKK_prior = propThetaM.calcLogPrTheta( propThetaM.theta(kk) ); logPrThetaKK_prop = propThetaM.calcLogPrTheta_MixWithPrior( propThetaM.theta(kk), PPmix ); logPrTheta_Diff = logPrThetaKK_prop - logPrThetaKK_prior; else logPrTheta_Diff=-20; end case {'Prior', 'prior'} logPrTheta_Diff = 0; end % Probability of death in current config logQ.moveChoice = log( qs(MoveType) ); % Probability of birth in proposed config qsRev = buildRJMoveDistr( uNew, Kii-1, PrBirth ); logQ_Rev.moveChoice = log( qsRev( 1 ) ); RhoTerms.activeFeatIDs = kk; end % Compute Joint Log Probability of Proposed/Current configurations % -------------------------------- p( F ) terms % U ~ Poisson( eta ) where eta = gamma*c/(c + N - 1) eta = gamma *c/(c + N -1 ); logPrNumFeat_Diff = ( uNew - uCur )*log( eta ) + gammaln( uCur + 1 ) - gammaln( uNew + 1 ); % -------------------------------- p( x | eta, theta, F) terms if isfield( Psi, 'cache' ) && isfield( Psi.cache, 'logSoftEv' ) logSoftEv = Psi.cache.logSoftEv{ii}; if strcmp( descrStr, 'birth' ) logSoftEvStar = propThetaM.calcLogSoftEv( ii, data, [K+1] ); logSoftEv( K+1,:) = logSoftEvStar(K+1,:); end else logSoftEv = propThetaM.calcLogSoftEv( ii, data, [availFeatIDs K+1] ); end if isfield(Psi,'cache') && isfield( Psi.cache, 'logMargPrObs' ) logMargPrObs_Cur = Psi.cache.logMargPrObs(ii); else curF_ii = false( size(propF_ii) ); curF_ii( availFeatIDs ) = true; logMargPrObs_Cur = calcLogMargPrObsSeqFAST( logSoftEv( curF_ii, :), propEta_ii( 1:Kii, 1:Kii ) ); end logMargPrObs_Prop = calcLogMargPrObsSeqFAST( logSoftEv( propF_ii, :), propEta ); % Compute accept-reject ratio: ( see eq. 15 in BP HMM paper ) log_rho_star = logMargPrObs_Prop - logMargPrObs_Cur ... + logPrNumFeat_Diff ... + logPrTheta_Diff ... + logQ_Rev.moveChoice - logQ.moveChoice; RhoTerms.logMargPrObs_Prop = logMargPrObs_Prop; RhoTerms.logMargPrObs_Cur = logMargPrObs_Cur; RhoTerms.logPrThetaDiff = logPrTheta_Diff; RhoTerms.logQMove.fwd = logQ.moveChoice; RhoTerms.logQMove.rev = logQ_Rev.moveChoice; RhoTerms.thetaStar = thetaStar; RhoTerms.choice = choice; RhoTerms.window = [wstart wend]; rho = exp(log_rho_star); assert( ~isnan(rho), 'ERROR: Accept ratio *rho* for unique features should never be NaN') rho = min( rho, 1 ); doAccept = rand < rho; % Binary indicator for if cur proposal accepted RhoTerms.doAccept = doAccept; RhoTerms.doBirth = strcmp( descrStr, 'birth' ); if doAccept switch descrStr case 'birth' f_ii_kk = 1; case 'death' f_ii_kk = 0; end Psi.F( ii, kk ) = f_ii_kk; Psi.ThetaM = propThetaM; Psi.TransM = Psi.TransM.setEta( ii, propF_ii, propEta ); if isfield(Psi,'cache') && isfield( Psi.cache, 'logSoftEv' ) Psi.cache.logMargPrObs(ii) = logMargPrObs_Prop; if strcmp( descrStr, 'birth' ) Psi.cache.logSoftEv{ii} = logSoftEv; end elseif isfield( algParams, 'doAvoidCache' ) && algParams.doAvoidCache assert( 1==1 ); % placeholder, skip caching! else Psi.cache.logMargPrObs(ii) = logMargPrObs_Prop; Psi.cache.logSoftEv{ii} = logSoftEv; end if strcmp( descrStr,'death') Psi = reallocateFeatIDs( Psi ); end end end % MAIN FUNCTION % Draw a random subwindow for data-driven proposal % First choose window length L % Then choose starting position (which can support that length L ) function [wstart, wend, L] = drawRandomSubwindow( TT, minW, maxW ) Ls = minW:maxW; Ls = Ls( Ls >= 1 ); Ls = Ls( Ls <= TT ); if isempty(Ls) Ls = TT; end distrLs = ones( size(Ls) ); L = Ls( multinomial_single_draw( distrLs ) ); wstart = randi( [1 TT-L+1] ); wend = wstart + L - 1; end
github
kourouklides/NPBayesHMM-master
sampleTransParams_RGS.m
.m
NPBayesHMM-master/code/BPHMM/sampler/RGSSplitMerge/sampleTransParams_RGS.m
3,143
utf_8
d5eb260fbf72f24114d56fb2aa6f441e
function [TS, logQ_RGS] = sampleTransParams_RGS(F, stateSeq, TS, hyperparams, model, objIDs, TargetPsi ) % Sample the transition distribution params stored in transStruct % state-to-state trans. : pi_z % init state distribution : pi_init % Each object ii has Pi_z matrix that is Kz_ii x Kz_ii % where Kz_ii := # features available for obj. ii = sum( F(ii,:) ) % Sample HMM transition parameters under RESTRICTED settings % which means we % (1) only update params for sequences in list "objIDs" % Executed under two circumstances: % (I) actually sample from posterior % (II) do not sample at all, but compute prob. % for moving from current state to TargetPsi state logQ_RGS = 0; alpha0 = hyperparams.alpha; kappa0 = hyperparams.kappa; Zstats = getZSuffStats( F, stateSeq, model ); switch model.HMMmodel.transType case 'byObject' % =========================================== Sample Individual Trans Structs for ii= objIDs f_ii = find( F(ii,:) ); Kz_ii = length( f_ii ); TS.obj(ii).availFeatIDs = f_ii; TS.obj(ii).pi_init = ones( 1, Kz_ii ); ParamMatrix = Zstats.obj(ii).Nz + alpha0*ones(Kz_ii,Kz_ii) + kappa0*eye( Kz_ii, Kz_ii ); if exist( 'TargetPsi', 'var' ) && ~isempty( TargetPsi ) % Pretend we obtained current TS from target TS.obj(ii).pi_z = TargetPsi.TS.obj(ii).pi_z; Pi_z = TargetPsi.TS.obj(ii).pi_z; EtaSum = sum( Pi_z, 2 ); Pi_z = bsxfun( @rdivide, Pi_z, sum(Pi_z,2) ); else % Draw Normalized Probabilities from Dirichlet Posterior % q ~ Dir( N_k + a + kappa*delta(j,k) ) Pi_z = randgamma( ParamMatrix ); Pi_z = bsxfun( @rdivide, Pi_z, sum( Pi_z,2) ); % Draw a scale factor for each row of Pi_z % proportional to *sum* of prior parameters EtaSum = randgamma( (kappa0 + Kz_ii*alpha0)*ones(Kz_ii,1) ); % Combine Dir draws with scale factor to get Gamma draws % via the transformation: % eta_k = q_k * EtaSum where sum( eta_k ) = EtaSum TS.obj(ii).pi_z = bsxfun( @times, Pi_z, EtaSum ); end if nargout > 1 logQ_RGS = logQ_RGS + calcLogPrDirichlet( log(Pi_z), ParamMatrix, 1 ); logQ_RGS = logQ_RGS + calcLogPrGamma( EtaSum, Kz_ii*alpha0 + kappa0, 1 ); end end % loop over time series objs case 'global' error( 'TO DO' ); case 'byCategory' error( 'TO DO (see code at end of this file for attempt 1' ); end % switch over trans sharing types end % main function % ==================================================================== function TS = initBlankTransStruct( nObj, Kz ) TS_Template = struct('pi_z',zeros(Kz,Kz, 'single'),'pi_init',zeros(1,Kz, 'single') ); TS = repmat( TS_Template, nObj, 1 ); end
github
kourouklides/NPBayesHMM-master
recordMCMCHistory_BPHMM.m
.m
NPBayesHMM-master/code/BPHMM/BPutil/recordMCMCHistory_BPHMM.m
3,392
utf_8
ed65bc3216378b2c59de29aa933058c4
function ChainHist = recordMCMCHistory_BPHMM( n, outParams, ChainHist, Psi, logPr, Stats ) % Save current state of sampler % -------------------------------------------------- update logPr trace if n == 1 || rem( n, outParams.logPrEvery ) == 0 if isfield( ChainHist, 'logPr' ) dC = length( ChainHist.logPr ) + 1; ChainHist.logPr(dC) = logPr; else ChainHist = struct(); ChainHist.logPr = logPr; dC = 1; end ChainHist.iters.logPr(dC) = n; ChainHist.times.logPr(dC) = toc; end % -------------------------------------------------- save current config if ( n==1 || rem( n, outParams.saveEvery)==0 ) storePsi = packBPHMMState( Psi ); if isfield( ChainHist, 'Psi' ) storeCount = length( ChainHist.Psi ) + 1; ChainHist.Psi( storeCount ) = storePsi; else storeCount = 1; ChainHist.Psi = storePsi; end ChainHist.iters.Psi( storeCount) = n; ChainHist.times.Psi( storeCount) = toc; ChainHist.RandSeed(storeCount).matlabPRNGState = RandStream.getGlobalStream.State; ChainHist.RandSeed(storeCount).mexPRNGState = randomseed; end % -------------------------------------------------- update SamplerAlg stats if exist( 'Stats','var') && ~isempty( fieldnames( Stats) ) if n == 1 || mod( n, outParams.statsEvery ) == 0 if isfield( ChainHist, 'stats' ) dC = length( ChainHist.stats ) + 1; else dC = 1; end ChainHist.iters.stats(dC) = n; ChainHist.times.stats(dC) = toc; if isfield( ChainHist, 'TempStats') ChainHist = UpdateTempSamplerStats( Stats, ChainHist ); ChainHist.stats(dC) = ChainHist.TempStats; ChainHist = rmfield( ChainHist, 'TempStats' ); else ChainHist.stats(dC) = Stats; end else ChainHist = UpdateTempSamplerStats( Stats, ChainHist ); end end end % MAIN FUNCTION % UpdateTempSamplerStats % temporarily stores sampler stats between saves to disk % so that we have good records about accept rates throughout the run function ChainHist = UpdateTempSamplerStats( SamplerStats, ChainHist ) if ~isfield( ChainHist, 'TempStats' ) ChainHist.TempStats = SamplerStats; else fNames = fieldnames( SamplerStats ); for aa = 1:length( fNames ) Stats = SamplerStats.( fNames{aa} ); if isfield( Stats, 'C' ) ChainHist.TempStats.( fNames{aa} ).C = ChainHist.TempStats.( fNames{aa} ).C + Stats.C; elseif isfield( Stats, 'nAccept' ) ChainHist.TempStats.( fNames{aa} ).nAccept = ChainHist.TempStats.( fNames{aa} ).nAccept + Stats.nAccept; ChainHist.TempStats.( fNames{aa} ).nTotal = ChainHist.TempStats.( fNames{aa} ).nTotal + Stats.nTotal; elseif isfield( Stats, 'ADD' ) ChainHist.TempStats.( fNames{aa} ).ADD.nAccept = ChainHist.TempStats.( fNames{aa} ).ADD.nAccept + Stats.ADD.nAccept; ChainHist.TempStats.( fNames{aa} ).ADD.nTotal = ChainHist.TempStats.( fNames{aa} ).ADD.nTotal + Stats.ADD.nTotal; ChainHist.TempStats.( fNames{aa} ).DEL.nAccept = ChainHist.TempStats.( fNames{aa} ).DEL.nAccept + Stats.DEL.nAccept; ChainHist.TempStats.( fNames{aa} ).DEL.nTotal = ChainHist.TempStats.( fNames{aa} ).DEL.nTotal + Stats.DEL.nTotal; end end end end
github
kourouklides/NPBayesHMM-master
lof.m
.m
NPBayesHMM-master/code/BPHMM/BPutil/lof.m
6,616
utf_8
7bd2ec8c1620411c6972c67103ce33b3
function [F_sorted sort_ind] = lof(F, recurN, doVerbose) % Map binary matrices to Left-Ordered Form (lof) % by ordering columns in descending order from left-to-right % according to magnitude of binary number expressed by each column. % Empty columns will be *removed*, so size(F_sorted,2) <= size(F,2) % Assumes first row represents the *most* significant bit. % Sorting performed using Matlab's built-in bin2dec function, % which we use to map each column to a unique decimal integer. % bin2dec.m can only handle binary strings of length ~50 or less (R2010a) % so we must perform recursive sorting if F has more than 50 rows. % EXAMPLE % F = [0 0 0 1 1 0; 1 0 1 0 1 0; 0 1 1 1 0 0 ; 0 1 0 0 0 0]; % F_sorted = lof( F ); % F F_sorted % 0 0 0 1 1 0 lof 1 1 0 0 0 (Note empty col. was removed) % 1 0 1 0 1 0 ------- > 1 0 1 1 0 % 0 1 1 1 0 0 0 1 1 0 1 % 0 1 0 0 0 0 0 0 0 0 1 % COMMENTS % Most users should happily omit all input args but the first one. % The others are only for students that seek a deeper understanding of % different possible algorithms for obtaining left-ordered form % In practice, the default options should always yield the fastest code. % INPUT (* indicates optional input which can be omitted ) % F := binary matrix (entries are either zero or one ) % *recurN := integer indicator for which recursion type to perform % 1 : sort first row, then recurse on F(2:end,:) % 2 : sort first 2 rows, recurse on F(3:end,:) % (default) 50 : sort first 50 rows, recurse on F(50:end,:) % *doVerbose := optional flag to print debugging info. % (default) 0 : no progress messages printed to stdout % OUTPUT % F_sorted := matrix F in Left-Ordered Form % sort_ind := vector gives indices for transformation of F to F_sorted % F_sorted = F( sort_ind, : ) % REFERENCES % Griffiths and Ghahramani. % "Infinite Latent Feature Models and the Indian Buffet Process" % In particular: Fig. 2 and section 2.2 "Equivalence classes" if ~exist( 'doVerbose', 'var' ) doVerbose = 0; end if ~exist( 'recurN', 'var' ) recurN = 50; end % Sort columns according to Left-Ordered Form if doVerbose initBufStr = ' '; else initBufStr = ''; end switch recurN case 1 sort_ind = recursiveLoF( F , initBufStr); case 2 sort_ind = recursiveLoF2( F , initBufStr); case 50 sort_ind = recursiveLoF50( F , initBufStr); end F_sorted = F(:,sort_ind); % Remove Empty Columns posColIDs = sum(F_sorted,1) > 0; F_sorted = F_sorted(:, posColIDs); sort_ind = sort_ind( posColIDs ); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [sort_ind] = recursiveLoF50( F, bufStr ) if ~isempty( bufStr ) fprintf( '%s Reforming matrix of size %d x %d\n', bufStr, size(F,1), size(F,2) ); bufStr = [bufStr ' ']; end MM = 50; if size( F , 2) == 0 sort_ind = []; elseif size(F, 2) == 1 sort_ind = 1; elseif size( F, 1 ) <= MM sort_ind = sortColsByBin2Dec( F ); else % Sort the first fifty rows (which is max allowed by bin2dec) [sort_ind, sort_vals] = sortColsByBin2Dec( F( 1:MM , : ) ); % Figure out where duplicates exist, and sort remaining rows within unique_vals = unique( sort_vals ); dupHist = histc( sort_vals, unique_vals ); dupIDs = find( dupHist > 1 ); for dupID = dupIDs curIDs = find( sort_vals == unique_vals(dupID) ); recurF = F( MM+1:end, sort_ind( curIDs ) ); subSortIDs = recursiveLoF50( recurF, bufStr ); sort_ind( curIDs ) = sort_ind( curIDs(subSortIDs) ); end end % make sure sort_ind has all unique entries assert( length( sort_ind) == length( unique(sort_ind) ), 'ERROR: Left-Ordered Form col. swap will fail.' ); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [sort_ind] = recursiveLoF2( F, bufStr ) if ~isempty( bufStr ) fprintf( '%s Reforming matrix of size %d x %d\n', bufStr, size(F,1), size(F,2) ); bufStr = [bufStr ' ']; end if size( F , 2) == 0 sort_ind = []; elseif size(F, 2) == 1 sort_ind = 1; elseif size( F, 1 ) < 50 sort_ind = sortColsByBin2Dec( F ); else ind_1 = find( F( 1, : ) ); ind_11 = find( F(2, ind_1) ); ind_10 = setdiff( 1:length( ind_1 ), ind_11 ); sort_11 = recursiveLoF( F( 3:end, ind_1( ind_11 ) ), bufStr ); sort_10 = recursiveLoF( F( 3:end, ind_1( ind_10 ) ), bufStr ); ind_0 = setdiff( 1:size(F,2), ind_1 ); ind_01 = find( F(2, ind_0) ); ind_00 = setdiff( 1:length( ind_0 ), ind_01 ); sort_01 = recursiveLoF( F( 3:end, ind_0( ind_01 ) ), bufStr ); sort_00 = recursiveLoF( F( 3:end, ind_0( ind_00 ) ), bufStr ); ind_1 = ind_1( [ind_11( sort_11 ) ind_10( sort_10 ) ] ); ind_0 = ind_0( [ind_01( sort_01 ) ind_00( sort_00 )] ); sort_ind = [ ind_1 ind_0 ]; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [sort_ind] = recursiveLoF( F, bufStr ) if ~isempty( bufStr ) fprintf( '%s Reforming matrix of size %d x %d\n', bufStr, size(F,1), size(F,2) ); bufStr = [bufStr ' ']; end if size( F , 2) == 0 sort_ind = []; elseif size(F, 2) == 1 sort_ind = 1; elseif size( F, 1 ) < 50 sort_ind = sortColsByBin2Dec( F ); else ind_1 = find( F( 1, : ) ); sort_1 = recursiveLoF( F( 2:end, ind_1 ), bufStr ); ind_0 = setdiff( 1:size(F,2), ind_1 ); sort_0 = recursiveLoF( F( 2:end, ind_0 ), bufStr ); sort_ind = [ ind_1( sort_1 ) ind_0( sort_0 ) ]; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [sort_ind, sort_vals] = sortColsByBin2Dec( F ) [N,Kz] = size(F); %val = zeros(1,Kz); % Rolled my own bin2dec... should be much faster! val = sum( bsxfun(@times, F, pow2(N-1:-1:0)' ), 1); %for kk=1:Kz %col_kk = num2str(F(:,kk)'); % colStr = sprintf( '%d', F(:,kk)' ); % val(kk) = bin2dec(colStr); %end [sort_vals, sort_ind] = sort(val,'descend'); end
github
kourouklides/NPBayesHMM-master
assignmentoptimal.m
.m
NPBayesHMM-master/code/BPHMM/BPutil/relabel/assignmentoptimal.m
7,787
utf_8
c9b870578bdec636e05ae1d4d711af41
function [assignment, cost] = assignmentoptimal(distMatrix) %ASSIGNMENTOPTIMAL Compute optimal assignment by Munkres algorithm % ASSIGNMENTOPTIMAL(DISTMATRIX) computes the optimal assignment (minimum % overall costs) for the given rectangular distance or cost matrix, for % example the assignment of tracks (in rows) to observations (in % columns). The result is a column vector containing the assigned column % number in each row (or 0 if no assignment could be done). % % [ASSIGNMENT, COST] = ASSIGNMENTOPTIMAL(DISTMATRIX) returns the % assignment vector and the overall cost. % % The distance matrix may contain infinite values (forbidden % assignments). Internally, the infinite values are set to a very large % finite number, so that the Munkres algorithm itself works on % finite-number matrices. Before returning the assignment, all % assignments with infinite distance are deleted (i.e. set to zero). % % A description of Munkres algorithm (also called Hungarian algorithm) % can easily be found on the web. % % Markus Buehren % Last modified 30.01.2008 % save original distMatrix for cost computation originalDistMatrix = distMatrix; % check for negative elements if any(distMatrix(:) < 0) error('All matrix elements have to be non-negative.'); end % get matrix dimensions [nOfRows, nOfColumns] = size(distMatrix); % check for infinite values finiteIndex = isfinite(distMatrix); infiniteIndex = find(~finiteIndex); if ~isempty(infiniteIndex) % set infinite values to large finite value maxFiniteValue = max(max(distMatrix(finiteIndex))); if maxFiniteValue > 0 infValue = abs(10 * maxFiniteValue * nOfRows * nOfColumns); else infValue = 10; end if isempty(infValue) % all elements are infinite assignment = zeros(nOfRows, 1); cost = 0; return end distMatrix(infiniteIndex) = infValue; end % memory allocation coveredColumns = zeros(1,nOfColumns); coveredRows = zeros(nOfRows,1); starMatrix = zeros(nOfRows, nOfColumns); primeMatrix = zeros(nOfRows, nOfColumns); % preliminary steps if nOfRows <= nOfColumns minDim = nOfRows; % find the smallest element of each row minVector = min(distMatrix,[],2); % subtract the smallest element of each row from the row distMatrix = distMatrix - repmat(minVector, 1, nOfColumns); % Steps 1 and 2 for row = 1:nOfRows for col = find(distMatrix(row,:)==0) if ~coveredColumns(col)%~any(starMatrix(:,col)) starMatrix(row, col) = 1; coveredColumns(col) = 1; break end end end else % nOfRows > nOfColumns minDim = nOfColumns; % find the smallest element of each column minVector = min(distMatrix); % subtract the smallest element of each column from the column distMatrix = distMatrix - repmat(minVector, nOfRows, 1); % Steps 1 and 2 for col = 1:nOfColumns for row = find(distMatrix(:,col)==0)' if ~coveredRows(row) starMatrix(row, col) = 1; coveredColumns(col) = 1; coveredRows(row) = 1; break end end end coveredRows(:) = 0; % was used auxiliary above end if sum(coveredColumns) == minDim % algorithm finished assignment = buildassignmentvector__(starMatrix); else % move to step 3 [assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step3__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, minDim); %#ok end % compute cost and remove invalid assignments [assignment, cost] = computeassignmentcost__(assignment, originalDistMatrix, nOfRows); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function assignment = buildassignmentvector__(starMatrix) [maxValue, assignment] = max(starMatrix, [], 2); assignment(maxValue == 0) = 0; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [assignment, cost] = computeassignmentcost__(assignment, distMatrix, nOfRows) rowIndex = find(assignment); costVector = distMatrix(rowIndex + nOfRows * (assignment(rowIndex)-1)); finiteIndex = isfinite(costVector); cost = sum(costVector(finiteIndex)); assignment(rowIndex(~finiteIndex)) = 0; % Step 2: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step2__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, minDim) % cover every column containing a starred zero maxValue = max(starMatrix); coveredColumns(maxValue == 1) = 1; if sum(coveredColumns) == minDim % algorithm finished assignment = buildassignmentvector__(starMatrix); else % move to step 3 [assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step3__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, minDim); end % Step 3: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step3__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, minDim) zerosFound = 1; while zerosFound zerosFound = 0; for col = find(~coveredColumns) for row = find(~coveredRows') if distMatrix(row,col) == 0 primeMatrix(row, col) = 1; starCol = find(starMatrix(row,:)); if isempty(starCol) % move to step 4 [assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step4__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, row, col, minDim); return else coveredRows(row) = 1; coveredColumns(starCol) = 0; zerosFound = 1; break % go on in next column end end end end end % move to step 5 [assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step5__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, minDim); % Step 4: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step4__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, row, col, minDim) newStarMatrix = starMatrix; newStarMatrix(row,col) = 1; starCol = col; starRow = find(starMatrix(:, starCol)); while ~isempty(starRow) % unstar the starred zero newStarMatrix(starRow, starCol) = 0; % find primed zero in row primeRow = starRow; primeCol = find(primeMatrix(primeRow, :)); % star the primed zero newStarMatrix(primeRow, primeCol) = 1; % find starred zero in column starCol = primeCol; starRow = find(starMatrix(:, starCol)); end starMatrix = newStarMatrix; primeMatrix(:) = 0; coveredRows(:) = 0; % move to step 2 [assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step2__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, minDim); % Step 5: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step5__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, minDim) % find smallest uncovered element uncoveredRowsIndex = find(~coveredRows'); uncoveredColumnsIndex = find(~coveredColumns); [s, index1] = min(distMatrix(uncoveredRowsIndex,uncoveredColumnsIndex)); [s, index2] = min(s); %#ok h = distMatrix(uncoveredRowsIndex(index1(index2)), uncoveredColumnsIndex(index2)); % add h to each covered row index = find(coveredRows); distMatrix(index, :) = distMatrix(index, :) + h; % subtract h from each uncovered column distMatrix(:, uncoveredColumnsIndex) = distMatrix(:, uncoveredColumnsIndex) - h; % move to step 3 [assignment, distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows] = step3__(distMatrix, starMatrix, primeMatrix, coveredColumns, coveredRows, minDim);
github
kourouklides/NPBayesHMM-master
readJointAnglesAsMatrixFromAMC.m
.m
NPBayesHMM-master/code/data/mocap/readJointAnglesAsMatrixFromAMC.m
4,009
utf_8
3dc5dd1694eaf3b2aae070c944f1916c
% readJointAnglesAsMatrixFromAMC.m % Read data from AMC motion capture file into Matlab matrix % CREDITS % Modified from amc_to_matrix.m (Jernej Barbic, CMU, March 2003) % with further changes by E.Sudderth and E. Fox (MIT, 2008-2009) % Smoothing Angle suggestion due to N. Lawrence (smoothAngleChannels.m) function [D,ColNames] = readJointAnglesAsMatrixFromAMC( fname, QueryChannelNames ) % Preallocate the matrix % since we usually have HUGE volumes of sensor data D = nan( 7200, 50 ); % Open file fid=fopen(fname, 'rt'); if (fid == -1) error('ERROR: Cannot open file %s.\n', fname); end; % Read lines until we've skipped past the header % assuming it ends with the line ":DEGREES" line=fgetl(fid); while ~strcmp(line,':DEGREES') line=fgetl(fid); end % Loop through each frame, one-at-a-time fID = 0; %partID = 0; %nDimsPerPart = []; fNames = {}; fCtr = 1; while ~feof(fid) line = fgets( fid ); SpaceLocs = strfind( line, ' '); if isempty( SpaceLocs ) && ~isempty(line) % Advance to next time frame (fID) and reset dimension counter (dID) fID = fID + 1; dID = 1; else nNumFields = length(SpaceLocs); if fID == 1 fNames{fCtr} = line( 1:SpaceLocs(1)-1 ); fCtr = fCtr + 1; fDim(fCtr) = nNumFields; end if fID > size(D,1) D( end+1:end+7200, :) = zeros( 7200, size(D,2) ); end D( fID, dID:dID+nNumFields-1 ) = sscanf( line(SpaceLocs(1)+1:end), '%f' ); dID = dID+nNumFields; %nDimsPerPart(end+1) = nNumFields; end end % Make sure to close file fclose(fid); % Cleanup resulting data to get rid of extra rows/cols % which we preallocated just in case D = D( 1:fID, :); keepCols = ~isnan( sum( D, 1 ) ); D = D( :, keepCols ); [basedir,~,~] = fileparts( fname ); [ColNames] = readChannelNamesFromSkeletonKey( fullfile( basedir, 'SkeletonJoints.key') ); % ================================== POST PROCESS % Keep only channels desired by the user, % as specified by the QueryChannelNames arg if exist( 'QueryChannelNames', 'var' ) keepCols = []; for qq = 1:length( QueryChannelNames ) needle = QueryChannelNames{qq}; mID = find( strncmp( needle, ColNames, length(needle) ) ); if ~isempty( mID ) keepCols(end+1) = mID; else fprintf( 'WARNING: Did not find desired channel named %s. Skipping...\n', needle ); end end D = D(:, keepCols ); ColNames = ColNames( keepCols ); end % ================================= SMOOTH ANGLE MEASUREMENTS % Look through all channels, and correct for sharp discontinuities % due to angle measurements jumping past boundaries % e.g. smooth transition from +178 deg to +182 deg could be recorded as % +178 deg to -178 deg, which is awkward didSmooth = 0; SmoothedChannels = {}; for chID = 1:size(D,2) didSmoothHere = 0; for tt = 2:size(D, 1) ttDelta= D( tt, chID) - D(tt-1, chID); if abs(ttDelta+360)<abs(ttDelta) % if y_tt +360 is closer to y_tt-1 than just y_tt % shift y_tt and all subsequent measurements by +360 D(tt:end, chID) = D(tt:end, chID)+360; didSmoothHere= 1; elseif abs(ttDelta-360)<abs(ttDelta) % if y_tt -360 is closer to y_tt-1 than just y_tt % shift y_tt and all subsequent measurements by -360 D(tt:end, chID) = D(tt:end, chID)-360; didSmoothHere= 1; end end if didSmoothHere SmoothedChannels{end+1} = ColNames{chID}; end didSmooth = didSmooth | didSmoothHere; end if didSmooth L = length( SmoothedChannels ); MyChannels(1:2:(2*L) ) = SmoothedChannels; for aa = 2:2:(2*L) MyChannels{aa} = ', '; end SmoothSummary = strcat( MyChannels{:} ); fprintf( 'Warning: did some smoothing on channels %s\n', SmoothSummary ); end end % readJointAnglesAsMatrixFromAMC.m function
github
Aureliu/Stock-Analysis-master
Graph.m
.m
Stock-Analysis-master/量化/金工/GUI/Graph.m
10,406
utf_8
9f108e2c085813ab6fcc0cd4f00e5c09
function varargout = Graph(varargin) % GRAPH MATLAB code for Graph.fig % GRAPH, by itself, creates a new GRAPH or raises the existing % singleton*. % % H = GRAPH returns the handle to a new GRAPH or the handle to % the existing singleton*. % % GRAPH('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in GRAPH.M with the given input arguments. % % GRAPH('Property','Value',...) creates a new GRAPH or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before Graph_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to Graph_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help Graph % Last Modified by GUIDE v2.5 07-Apr-2016 15:38:41 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @Graph_OpeningFcn, ... 'gui_OutputFcn', @Graph_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before Graph is made visible. function Graph_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to Graph (see VARARGIN) set(handles.uipanel1,'parent',handles.figure1,'Position',get(handles.uipanel2,'Position')); % set(handles.uipanel2,'parent',gcf); % set(handles.uipanel3,'parent',gcf); set(handles.uipanel2,'Parent',gcf); set(handles.uipanel3,'Parent',handles.figure1,'Position',get(handles.uipanel2,'Position')); set(handles.uipanel4,'Parent',handles.figure1,'Position',get(handles.uipanel2,'Position')); set(handles.uipanel1,'Visible','off'); set(handles.uipanel2,'Visible','off'); set(handles.uipanel3,'Visible','off'); set(handles.pushbutton1,'Visible','off'); set(handles.pushbutton3,'Visible','off'); set(handles.pushbutton7,'Visible','off'); set(handles.pushbutton8,'Visible','off'); set(handles.pushbutton9,'Visible','off'); set(handles.pushbutton10,'Visible','off'); set(handles.pushbutton11,'Visible','on'); set(handles.pushbutton12,'Visible','on'); set(handles.radiobutton1,'Visible','on'); set(handles.edit1,'Visible','on'); set(handles.edit2,'Visible','on'); set(handles.text2,'Visible','on'); set(handles.text3,'Visible','on'); set(handles.pushbutton13,'Visible','on'); set(handles.uipanel4,'Visible','on'); % Choose default command line output for Graph handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes Graph wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = Graph_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.uipanel1,'Visible','off'); set(handles.uipanel2,'Visible','off'); set(handles.uipanel3,'Visible','off'); set(handles.pushbutton1,'Visible','off'); set(handles.pushbutton3,'Visible','off'); set(handles.pushbutton7,'Visible','off'); set(handles.pushbutton8,'Visible','off'); set(handles.pushbutton9,'Visible','off'); set(handles.pushbutton10,'Visible','off'); set(handles.pushbutton11,'Visible','on'); set(handles.pushbutton12,'Visible','on'); set(handles.radiobutton1,'Visible','on'); set(handles.edit1,'Visible','on'); set(handles.edit2,'Visible','on'); set(handles.text2,'Visible','on'); set(handles.text3,'Visible','on'); set(handles.pushbutton13,'Visible','on'); set(handles.uipanel4,'Visible','on'); % --- Executes on button press in pushbutton3. function pushbutton3_Callback(hObject, eventdata, handles) % hObject handle to pushbutton3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in pushbutton8. function pushbutton8_Callback(hObject, eventdata, handles) % hObject handle to pushbutton8 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.uipanel1,'Visible','on'); set(handles.uipanel2,'Visible','off'); set(handles.uipanel3,'Visible','off'); % --- Executes on button press in pushbutton7. function pushbutton7_Callback(hObject, eventdata, handles) % hObject handle to pushbutton7 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in pushbutton9. function pushbutton9_Callback(hObject, eventdata, handles) % hObject handle to pushbutton9 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.uipanel1,'Visible','off'); set(handles.uipanel2,'Visible','on'); set(handles.uipanel3,'Visible','off'); % --- Executes on button press in pushbutton10. function pushbutton10_Callback(hObject, eventdata, handles) % hObject handle to pushbutton10 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.uipanel1,'Visible','off'); set(handles.uipanel2,'Visible','off'); set(handles.uipanel3,'Visible','on'); % --- Executes on button press in pushbutton11. function pushbutton11_Callback(hObject, eventdata, handles) % hObject handle to pushbutton11 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in pushbutton12. function pushbutton12_Callback(hObject, eventdata, handles) % hObject handle to pushbutton12 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in radiobutton1. function radiobutton1_Callback(hObject, eventdata, handles) % hObject handle to radiobutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of radiobutton1 function edit1_Callback(hObject, eventdata, handles) % hObject handle to edit1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit1 as text % str2double(get(hObject,'String')) returns contents of edit1 as a double % --- Executes during object creation, after setting all properties. function edit1_CreateFcn(hObject, eventdata, handles) % hObject handle to edit1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit2_Callback(hObject, eventdata, handles) % hObject handle to edit2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit2 as text % str2double(get(hObject,'String')) returns contents of edit2 as a double % --- Executes during object creation, after setting all properties. function edit2_CreateFcn(hObject, eventdata, handles) % hObject handle to edit2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pushbutton13. function pushbutton13_Callback(hObject, eventdata, handles) % hObject handle to pushbutton13 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.uipanel1,'Visible','on'); set(handles.uipanel2,'Visible','on'); set(handles.uipanel3,'Visible','on'); set(handles.pushbutton1,'Visible','on'); set(handles.pushbutton3,'Visible','on'); set(handles.pushbutton7,'Visible','on'); set(handles.pushbutton8,'Visible','on'); set(handles.pushbutton9,'Visible','on'); set(handles.pushbutton10,'Visible','on'); set(handles.pushbutton11,'Visible','off'); set(handles.pushbutton12,'Visible','off'); set(handles.radiobutton1,'Visible','off'); set(handles.edit1,'Visible','off'); set(handles.edit2,'Visible','off'); set(handles.text2,'Visible','off'); set(handles.text3,'Visible','off'); set(handles.pushbutton13,'Visible','off'); set(handles.uipanel4,'Visible','off');
github
Aureliu/Stock-Analysis-master
ExcelReader.m
.m
Stock-Analysis-master/量化/金工/GUI/ExcelReader.m
7,907
utf_8
f7e8dbb036e8683b5e6fbdcb65634cae
function varargout = ExcelReader(varargin) % EXCELREADER MATLAB code for ExcelReader.fig % EXCELREADER, by itself, creates a new EXCELREADER or raises the existing % singleton*. % % H = EXCELREADER returns the handle to a new EXCELREADER or the handle to % the existing singleton*. % % EXCELREADER('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in EXCELREADER.M with the given input arguments. % % EXCELREADER('Property','Value',...) creates a new EXCELREADER or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before ExcelReader_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to ExcelReader_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help ExcelReader % Last Modified by GUIDE v2.5 06-Apr-2016 14:38:08 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @ExcelReader_OpeningFcn, ... 'gui_OutputFcn', @ExcelReader_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before ExcelReader is made visible. function ExcelReader_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to ExcelReader (see VARARGIN) % Choose default command line output for ExcelReader handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes ExcelReader wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = ExcelReader_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in pushbutton2. function pushbutton2_Callback(hObject, eventdata, handles) % hObject handle to pushbutton2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) a = xlsread('Test.xls'); function edit1_Callback(hObject, eventdata, handles) % hObject handle to edit1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit1 as text % str2double(get(hObject,'String')) returns contents of edit1 as a double % --- Executes during object creation, after setting all properties. function edit1_CreateFcn(hObject, eventdata, handles) % hObject handle to edit1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit2_Callback(hObject, eventdata, handles) % hObject handle to edit2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit2 as text % str2double(get(hObject,'String')) returns contents of edit2 as a double % --- Executes during object creation, after setting all properties. function edit2_CreateFcn(hObject, eventdata, handles) % hObject handle to edit2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in radiobutton1. function radiobutton1_Callback(hObject, eventdata, handles) % hObject handle to radiobutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of radiobutton1 function edit5_Callback(hObject, eventdata, handles) % hObject handle to edit5 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit5 as text % str2double(get(hObject,'String')) returns contents of edit5 as a double % --- Executes during object creation, after setting all properties. function edit5_CreateFcn(hObject, eventdata, handles) % hObject handle to edit5 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit6_Callback(hObject, eventdata, handles) % hObject handle to edit6 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit6 as text % str2double(get(hObject,'String')) returns contents of edit6 as a double % --- Executes during object creation, after setting all properties. function edit6_CreateFcn(hObject, eventdata, handles) % hObject handle to edit6 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pushbutton3. function pushbutton3_Callback(hObject, eventdata, handles) % hObject handle to pushbutton3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) run('Graph');%Run the graph.m UI. %set('ExcelReader','visible','off')%Hide the ExxelReader. close('ExcelReader');
github
carlomt/dicom_tools-master
readMeta.m
.m
dicom_tools-master/dicom_tools/pyqtgraph/metaarray/readMeta.m
1,752
utf_8
274fb9beeede592c8b60dc697d518dcd
function f = readMeta(file) info = hdf5info(file); f = readMetaRecursive(info.GroupHierarchy.Groups(1)); end function f = readMetaRecursive(root) typ = 0; for i = 1:length(root.Attributes) if strcmp(root.Attributes(i).Shortname, '_metaType_') typ = root.Attributes(i).Value.Data; break end end if typ == 0 printf('group has no _metaType_') typ = 'dict'; end list = 0; if strcmp(typ, 'list') || strcmp(typ, 'tuple') data = {}; list = 1; elseif strcmp(typ, 'dict') data = struct(); else printf('Unrecognized meta type %s', typ); data = struct(); end for i = 1:length(root.Attributes) name = root.Attributes(i).Shortname; if strcmp(name, '_metaType_') continue end val = root.Attributes(i).Value; if isa(val, 'hdf5.h5string') val = val.Data; end if list ind = str2num(name)+1; data{ind} = val; else data.(name) = val; end end for i = 1:length(root.Datasets) fullName = root.Datasets(i).Name; name = stripName(fullName); file = root.Datasets(i).Filename; data2 = hdf5read(file, fullName); if list ind = str2num(name)+1; data{ind} = data2; else data.(name) = data2; end end for i = 1:length(root.Groups) name = stripName(root.Groups(i).Name); data2 = readMetaRecursive(root.Groups(i)); if list ind = str2num(name)+1; data{ind} = data2; else data.(name) = data2; end end f = data; return; end function f = stripName(str) inds = strfind(str, '/'); if isempty(inds) f = str; else f = str(inds(length(inds))+1:length(str)); end end
github
x75/otl-master
sq_dist.m
.m
otl-master/otl_matlab/helpers/KernelHelpers/sq_dist.m
1,981
utf_8
55df35340656b27e511f3ecbd2fc864a
% sq_dist - a function to compute a matrix of all pairwise squared distances % between two sets of vectors, stored in the columns of the two matrices, a % (of size D by n) and b (of size D by m). If only a single argument is given % or the second matrix is empty, the missing matrix is taken to be identical % to the first. % % Usage: C = sq_dist(a, b) % or: C = sq_dist(a) or equiv.: C = sq_dist(a, []) % % Where a is of size Dxn, b is of size Dxm (or empty), C is of size nxm. % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2010-12-13. function C = sq_dist(a, b) if nargin<1 || nargin>3 || nargout>1, error('Wrong number of arguments.'); end %bsx = exist('bsxfun','builtin'); % since Matlab R2007a 7.4.0 and Octave 3.0 %if ~bsx, bsx = exist('bsxfun'); end % bsxfun is not yes "builtin" in Octave bsx = true; [D, n] = size(a); % Computation of a^2 - 2*a*b + b^2 is less stable than (a-b)^2 because numerical % precision can be lost when both a and b have very large absolute value and the % same sign. For that reason, we subtract the mean from the data beforehand to % stabilise the computations. This is OK because the squared error is % independent of the mean. if nargin==1 % subtract mean mu = mean(a,2); if bsx a = bsxfun(@minus,a,mu); else a = a - repmat(mu,1,size(a,2)); end b = a; m = n; else [d, m] = size(b); if d ~= D, error('Error: column lengths must agree.'); end mu = (m/(n+m))*mean(b,2) + (n/(n+m))*mean(a,2); if bsx a = bsxfun(@minus,a,mu); b = bsxfun(@minus,b,mu); else a = a - repmat(mu,1,n); b = b - repmat(mu,1,m); end end if bsx % compute squared distances C = bsxfun(@plus,sum(a.*a,1)',bsxfun(@minus,sum(b.*b,1),2*a'*b)); else C = repmat(sum(a.*a,1)',1,m) + repmat(sum(b.*b,1),n,1) - 2*a'*b; end C = max(C,0); % numerical noise can cause C to negative i.e. C > -1e-14
github
x75/otl-master
EVT_GaussianDF_Gy.m
.m
otl-master/otl_matlab/helpers/EVT_Multivariate/EVT_GaussianDF_Gy.m
3,644
utf_8
a6e3e1c4cda67add62239522e878608d
%% Evaluate the df G_n(y) over densities, y % % DC Logbook 22.140 % Equations refer to Clifton et al. (2011), J. Sig. Proc. Sys. (65), pp. 371-389 function Gy = EVT_GaussianDF_Gy(SIGMA, YS) %% Initialisation if size(YS, 1) == 1 YS = YS'; % Transpose into a column vector, if necessary end Gy = nan(length(YS), 1); %% We need to check that the input isn't out of range; if they are, we can treat them immediately n = size(SIGMA,2); % Find the dimensionality SqrtDet = sqrt(det(SIGMA)); % Find the sqrt of the determinant of the covariance matrix C_n = (2*pi)^(n/2) .* SqrtDet; % Eq. 13 ymax = 1/C_n; % Find maximum pdf value, so that the x-axis can scale from [0 1] IS = find((YS > 0) & (YS <= ymax)); % Only find the values for the non-limiting densities if length(IS) > 0 if n == 1 % Use Eq.21 for the univariate case Gy(IS) = erfc(sqrt(-log(C_n .* YS(IS)))); else if (mod(n,2) == 0) % if n is even, use Eqs. 22 and 24 p = n/2; % Find the upper limit of p (n = 2p) ks = 0 : (p-1); % Indices ks for the summations in Eq. 22 omega = 2*pi^(n/2)/gamma(n/2); % Find the total solid angle subtended by the unit n-sphere, Omega_n C_2p = SqrtDet*(2*pi)^(n/2); % Eq. 13 again % Now use Eqs. 22 and 24 A_CommonTerm = omega .* SqrtDet; % Calculate the common term from Eq. 24 A_SumTerms = (2.^ks .* factorial(p-1)) ./factorial(p-ks-1); % Calculate the series A in Eq. 24 A_SumTerms = A_SumTerms .* A_CommonTerm; % Multiply each A by the common term G = zeros(length(IS), 1); % Eq. 22: sum G over the various terms in the series A for i_ks = 1 : length(ks) % Range over the indices in ks % (i.e., i_ks = 1 when ks = 0, and i_ks = max when ks = p-1 G = G + A_SumTerms(i_ks) .* (-2 .* log(C_2p .* YS(IS))).^(p-ks(i_ks)-1); end Gy(IS) = G .* YS(IS); % Complete Eq.22 by multiplying by y else % n is odd, so use Eqs. 23 and 25 p = floor(n/2); % Find the upper limit of p (n = 2p+1) ks = 0 : (p-1); % Indices ks for the summations in Eq. 23 omega = 2*pi^(n/2)/gamma(n/2); % Find the total solid angle subtended by the unit n-sphere, Omega_n C_2p1 = SqrtDet*(2*pi)^(n/2); % Eq. 13 again % Now use Eqs. 23 and 25 A_CommonTerm = omega .* SqrtDet; % Calculate the common term from Eq. 24 A_SumTerms = (factorial(2*p-1) .* factorial(p-ks)) ./ ... (2.^(ks-1) .* factorial(p-1) .* factorial(2*p - 2*ks)); % Calculate the series A in Eq. 25 A_SumTerms = A_SumTerms .* A_CommonTerm; % Multiply each A by the common term G = zeros(length(IS), 1); % Eq. 22: sum G over the various terms in the series A for i_ks = 1 : length(ks) % Range over the indices in ks % (i.e., i_ks = 1 when ks = 0, and i_ks = max when ks = p-1 G = G + A_SumTerms(i_ks) .* (-2 .* log(C_2p1 .* YS(IS))).^(p-ks(i_ks)-1/2); end Gy(IS) = G .* YS(IS) + erfc(sqrt(-log(C_2p1 .* YS(IS)))); % Complete Eq.22 by multiplying by y end end end
github
x75/otl-master
EVT_GaussianPDF_gy.m
.m
otl-master/otl_matlab/helpers/EVT_Multivariate/EVT_GaussianPDF_gy.m
624
utf_8
c4b489c2a2b6e75fde50f88d421ea636
%% Evaluate the pdf g_n(y) over densities, y % % DC Logbook 22.140 % Equations refer to Clifton et al. (2011), J. Sig. Proc. Sys. (65), pp. 371-389 function gy = EVT_GaussianPDF_gy(SIGMA, YS) n = size(SIGMA,2); % Find the dimensionality omega = 2*pi^(n/2)/gamma(n/2); % Find the total solid angle subtended by the unit n-sphere, Omega_n SqrtDet = sqrt(det(SIGMA)); % Find the sqrt of the determinant of the covariance matrix C_n = (2*pi)^(n/2) .* SqrtDet; % Eq. 13, the normalising coefficient %% Evaluate the df at densities YS gy = SqrtDet .* omega .* (-2*log(C_n .* YS)).^((n-2)/2);
github
x75/otl-master
Plot_GaussianDensities.m
.m
otl-master/otl_matlab/helpers/EVT_Multivariate/Plot_GaussianDensities.m
7,687
utf_8
8907a36ddabe773bf4eb078e020f1e11
%% Plot figures that demonstrate multivariate EVT % This shows pdfs g_n(y) over the densities, y, of an n-dimensional Gaussian distribution, f_n(x) % and probability distributions G_n(y) over the same. % % Equations refer to Clifton et al. (2011), J. Sig. Proc. Sys. (65), pp. 371-389 % DC, Oct 2010 function Plot_GaussianDensities %% Plot density g_n(y) of densities f_n(x) for standard multivariate Gaussian distributions (i.e., unit covariance) figure; for n = 1 : 6 % Dimensionality of the Gaussian distribution, f_n(x) sigma = eye(n); % Covariance matrix of the standard n-dimensional Gaussian, f_n(x) % (Try with some non-isotropic Gaussians, but change max_density(n) accordingly) % Find the maximum density value of the standard n-dimensional Gaussian SqrtDet = sqrt(det(sigma)); % Find the sqrt of the determinant of the covariance matrix C_n = (2*pi)^(n/2) .* SqrtDet; % Eq. 13, the normalising coefficient max_density(n) = 1/C_n; % Find maximum pdf value, so that the x-axis can scale from [0 1] % Make the x-axis of our plot range from 0 up to this maximum density y{n} = linspace(0, max_density(n), 1e6)'; % Find the density g_n(y) over density values f_n(x) over this range on the x-axis (Eq. 20) gy = EVT_GaussianPDF_gy(sigma, y{n}); % Now, print all graphs on the same axes g_sort = sort(gy); gmax = g_sort(round(0.999 * length(g_sort))); plot(y{n}./max_density(n), gy ./ gmax); % Normalise the x-axis to have a maximum of unity % and normalise each graph by its second-largest value % (the largest typically being Inf!) hold on; end xlabel('y, normalised to 1 for comparison') ylabel('g_n(y)') set(gca, 'YLim', [0 1]) %% Plot distribution G_n(y) of densities f_n(x) for standard multivariate Gaussian distributions % (i.e., the integration of the above) figure for n = 1 : 6 % Dimensionality of the Gaussian distribution, f_n(x) sigma = eye(n); % Covariance matrix of the n-dimensional Gaussian, f_n(x) Gy = EVT_GaussianDF_Gy(sigma, y{n}); % Find G_n(y) plot(y{n}./max_density(n), Gy); hold on; end xlabel('y, normalised to 1 for comparison') ylabel('G_n(y)') %% Plot the EVD, G_n^e(y) figure for n = 1 : 6 sigma = eye(n); m = 50; [c_m alpha_m] = EVT_GaussianEVD_FindParams(sigma, m); % Find the EVD parameters for this Gaussian % This uses G_n(y) to find c_m and % g_n(y) and c_m to find alpha_m (see paper sec. 6.3) Ge = EVT_GaussianEVD_Ge(y{n}, c_m, alpha_m); % Evaluate the EVD G_n^e(y) over the range of densities semilogx(y{n}./max_density(n), Ge); % Plot the EVD G_n^e(y) hold on end xlabel('y, normalised to 1 for comparison') ylabel('G_n^e(y)') set(gca, 'YLim', [0 1]); %% Run some numerical experiments, to determine if our EVDs G_n^e(y) over densities y were correct % Use the value of m from before figure NUMSETS = 1e3; % Number of sets to generate (i.e., number of minima in our resultant plot) YS = zeros(NUMSETS, 1); % For storing the minima, one per set RS = zeros(NUMSETS, 1); % Corresponding (Mahalanobis) radii, one per set for n = 1: 6 for k = 1 : NUMSETS XS = gsamp(zeros(n, 1), eye(n), m); % Generate m data for this set (gsamp.m from Netlab) setYS = mvnpdf(XS, zeros(1,n), eye(n)); % Find the densities for this set [minY minIdx] = min(setYS); % Find the most extreme (the minimum density) YS(k) = minY; % Store this minimum for later RS(k) = mahalanobis(XS(minIdx,:), zeros(1,n),eye(n)); % Store this Mahalanobis radius for later end % Plot the results subplot(2, 1, 1) [c_m alpha_m] = EVT_GaussianEVD_FindParams(eye(n), m); % Find the EVD parameters for this Gaussian Ge = EVT_GaussianEVD_Ge(y{n}, c_m, alpha_m); % Evaluate the EVD G_n^e(y) over the range of densities semilogx(y{n}./max_density(n), Ge); % Plot the EVD G_n^e(y) hold on; [NS, YBIN] = hist(YS, 100); % Find the histogram of our YS CDFNS = cumsum(NS./sum(NS)); % Turn into an empirical df semilogx(YBIN./max_density(n), CDFNS, 'r.'); subplot(2, 1, 2) r{n} = linspace(1, 6, 1e5)'; % Mahalanobis radii, for plotting Fe = EVT_GaussianEVD_Fe(r{n}, eye(n), c_m, alpha_m); % Evaluate the EVD F_n^e(r) over the range of radii plot(r{n}, Fe); hold on; [NS, RBIN] = hist(RS, 100); % Find the histogram of our YS CDFNS = cumsum(NS./sum(NS)); % Turn into an empirical df plot(RBIN, CDFNS, 'r.'); end subplot(2, 1, 1) xlabel('y, normalised to 1 for comparison') ylabel('G_n^e(y)') set(gca, 'YLim', [0 1]) set(gca, 'XLim', [1e-5 1]) subplot(2, 1, 2) xlabel('r, Mahalanobis radius') ylabel('F_n^e(r)') set(gca, 'YLim', [0 1]) %% Let's try the same for an n = 6 model, with an interesting covariance matrix n = 6; rng(7); % Set the random number generator's seed SIGMA = RandomCovar(n) % Create a "random" covariance matrix (using the rng seed) for k = 1 : NUMSETS XS = gsamp(zeros(n, 1), SIGMA, m); % Generate m data for this set (gsamp.m from Netlab) setYS = mvnpdf(XS, zeros(1,n), SIGMA); % Find the densities for this set [minY minIdx] = min(setYS); % Find the most extreme (the minimum density) YS(k) = minY; % Store this minimum for later RS(k) = mahalanobis(XS(minIdx,:), zeros(1,n), SIGMA); % Store this Mahalanobis radius for later end % Plot the results figure subplot(2, 1, 1) [c_m alpha_m] = EVT_GaussianEVD_FindParams(SIGMA, m); % Find the EVD parameters for this Gaussian Ge = EVT_GaussianEVD_Ge(y{n}, c_m, alpha_m); % Evaluate the EVD G_n^e(y) over the range of densities semilogx(y{n}./max_density(n), Ge); % Plot the EVD G_n^e(y) hold on; [NS, YBIN] = hist(YS, 100); % Find the histogram of our YS CDFNS = cumsum(NS./sum(NS)); % Turn into an empirical df semilogx(YBIN./max_density(n), CDFNS, 'r.'); set(gca, 'YLim', [0 1]) set(gca, 'XLim', [1e-6 1e-3]) xlabel('y, normalised to 1 for comparison') ylabel('G_n^e(y)') subplot(2, 1, 2) r{n} = linspace(1, 6, 1e5)'; % Mahalanobis radii, for plotting Fe = EVT_GaussianEVD_Fe(r{n}, SIGMA, c_m, alpha_m); % Evaluate the EVD F_n^e(r) over the range of radii plot(r{n}, Fe); hold on; [NS, RBIN] = hist(RS, 100); % Find the histogram of our YS CDFNS = cumsum(NS./sum(NS)); % Turn into an empirical df plot(RBIN, CDFNS, 'r.'); set(gca, 'YLim', [0 1]) set(gca, 'XLim', [3 6]) xlabel('r, Mahalanobis radius') ylabel('F_n^e(r)')
github
x75/otl-master
EVT_GaussianQuantile_Gy.m
.m
otl-master/otl_matlab/helpers/EVT_Multivariate/EVT_GaussianQuantile_Gy.m
1,126
utf_8
52fe5f5ed83123ec2749fc28b698298a
%% Find the p-quantile on the df over densities G_y % % DC Logbook 22.142 % Equations refer to Clifton et al. (2011), J. Sig. Proc. Sys. (65), pp. 371-389 function y = EVT_GaussianQuantile_Gy(SIGMA, p) DOPLOT = false; %% Find the maximum density ymax for this df n = size(SIGMA,2); % Find the dimensionality SqrtDet = sqrt(det(SIGMA)); % Find the sqrt of the determinant of the covariance matrix C_n = (2*pi)^(n/2) .* SqrtDet; % Eq. 13, the normalising coefficient ymax = 1/C_n; % Find maximum pdf output value (i.e., density) %% Find the p-quantile by finding the value of y that minimises |G_n(y) - p| FirstGuess = ymax*p; % Start at ymax * p, which is a good guess if G_n(y) is uniform... y = fminsearch(@(y) abs(EVT_GaussianDF_Gy(SIGMA, y)-p), ymax*p); if DOPLOT figure; YS = linspace(0, ymax, 10^6)'; subplot(2, 1, 1); plot(YS, EVT_GaussianDF_Gy(SIGMA, YS)); xlabel('y') ylabel('G_n(y)') subplot(2, 1, 2); plot(YS, abs(EVT_GaussianDF_Gy(SIGMA,YS)-p)); xlabel('y'); ylabel(sprintf('|G_n(y) - p|, p = %.3f |', p)); end
github
x75/otl-master
EVT_GaussianEVD_FindParams.m
.m
otl-master/otl_matlab/helpers/EVT_Multivariate/EVT_GaussianEVD_FindParams.m
450
utf_8
b0c2c1f8a4c6f0835ef81a0def148c3d
%% Find the alpha (shape) and c (scale) parameters for the EVD pdf G_n^e(y) over densities, y % % DC Logbook 22.142 % Equations refer to Clifton et al. (2011), J. Sig. Proc. Sys. (65), pp. 371-389 function [c_m alpha_m] = EVT_GaussianEVD_FindParams(SIGMA, m) %% Estimate the parameters of the Weibull c_m = EVT_GaussianQuantile_Gy(SIGMA, 1/m); % Equation 28 alpha_m = m * c_m * EVT_GaussianPDF_gy(SIGMA, c_m); % Equation 29
github
x75/otl-master
EVT_GaussianEVD_Ge.m
.m
otl-master/otl_matlab/helpers/EVT_Multivariate/EVT_GaussianEVD_Ge.m
361
utf_8
6fb9126b3539b60e24f66da3c723849a
%% Evaluate the pdf G_n^e(y) over densities, y % You might like to get the parameters c_m and alpha_m from EVT_GaussianEVT_FindParams.m % % DC Logbook 22.140 % Equations refer to Clifton et al. (2011), J. Sig. Proc. Sys. (65), pp. 371-389 function Ge = EVT_GaussianEVD_Ge(YS, c_m, alpha_m) Ge = 1 - exp(-(YS./c_m).^alpha_m); % Equation 30
github
x75/otl-master
EVT_GaussianEVD_Fe.m
.m
otl-master/otl_matlab/helpers/EVT_Multivariate/EVT_GaussianEVD_Fe.m
654
utf_8
d33e7c9938f960cf3c043cbb83f957a0
%% Evaluate the pdf F_n^e(y) over Mahalanobis radii, r % You might like to get the parameters c_m and alpha_m from EVT_GaussianEVT_FindParams.m % % DC Logbook 22.140 % Equations refer to Clifton et al. (2011), J. Sig. Proc. Sys. (65), pp. 371-389 function Fe = EVT_GaussianEVD_Fe(RS, SIGMA, c_m, alpha_m) n = size(SIGMA,2); % Find the dimensionality SqrtDet = sqrt(det(SIGMA)); % Find the sqrt of the determinant of the covariance matrix C_n = (2*pi)^(n/2) .* SqrtDet; % Eq. 13, the normalising coefficient YS = (1/C_n).*exp(-(RS.^2)/2); % Gaussian distribution in radius Fe = exp(-(YS./c_m).^alpha_m); % Eq. 32
github
x75/otl-master
RandomCovar.m
.m
otl-master/otl_matlab/helpers/EVT_Multivariate/RandomCovar.m
118
utf_8
1767832c0039cc8165635b9eeee466b2
%% Create a random covariance matrix % DC Logbook 22.142 function SIGMA = RandomCovar(n) S = randn(n); SIGMA = S'*S;
github
x75/otl-master
distinguishable_colors.m
.m
otl-master/otl_matlab/helpers/PlotHelpers/distinguishable_colors.m
5,753
utf_8
57960cf5d13cead2f1e291d1288bccb2
function colors = distinguishable_colors(n_colors,bg,func) % DISTINGUISHABLE_COLORS: pick colors that are maximally perceptually distinct % % When plotting a set of lines, you may want to distinguish them by color. % By default, Matlab chooses a small set of colors and cycles among them, % and so if you have more than a few lines there will be confusion about % which line is which. To fix this problem, one would want to be able to % pick a much larger set of distinct colors, where the number of colors % equals or exceeds the number of lines you want to plot. Because our % ability to distinguish among colors has limits, one should choose these % colors to be "maximally perceptually distinguishable." % % This function generates a set of colors which are distinguishable % by reference to the "Lab" color space, which more closely matches % human color perception than RGB. Given an initial large list of possible % colors, it iteratively chooses the entry in the list that is farthest (in % Lab space) from all previously-chosen entries. While this "greedy" % algorithm does not yield a global maximum, it is simple and efficient. % Moreover, the sequence of colors is consistent no matter how many you % request, which facilitates the users' ability to learn the color order % and avoids major changes in the appearance of plots when adding or % removing lines. % % Syntax: % colors = distinguishable_colors(n_colors) % Specify the number of colors you want as a scalar, n_colors. This will % generate an n_colors-by-3 matrix, each row representing an RGB % color triple. If you don't precisely know how many you will need in % advance, there is no harm (other than execution time) in specifying % slightly more than you think you will need. % % colors = distinguishable_colors(n_colors,bg) % This syntax allows you to specify the background color, to make sure that % your colors are also distinguishable from the background. Default value % is white. bg may be specified as an RGB triple or as one of the standard % "ColorSpec" strings. You can even specify multiple colors: % bg = {'w','k'} % or % bg = [1 1 1; 0 0 0] % will only produce colors that are distinguishable from both white and % black. % % colors = distinguishable_colors(n_colors,bg,rgb2labfunc) % By default, distinguishable_colors uses the image processing toolbox's % color conversion functions makecform and applycform. Alternatively, you % can supply your own color conversion function. % % Example: % c = distinguishable_colors(25); % figure % image(reshape(c,[1 size(c)])) % % Example using the file exchange's 'colorspace': % func = @(x) colorspace('RGB->Lab',x); % c = distinguishable_colors(25,'w',func); % Copyright 2010-2011 by Timothy E. Holy % Parse the inputs if (nargin < 2) bg = [1 1 1]; % default white background else if iscell(bg) % User specified a list of colors as a cell aray bgc = bg; for i = 1:length(bgc) bgc{i} = parsecolor(bgc{i}); end bg = cat(1,bgc{:}); else % User specified a numeric array of colors (n-by-3) bg = parsecolor(bg); end end % Generate a sizable number of RGB triples. This represents our space of % possible choices. By starting in RGB space, we ensure that all of the % colors can be generated by the monitor. n_grid = 30; % number of grid divisions along each axis in RGB space x = linspace(0,1,n_grid); [R,G,B] = ndgrid(x,x,x); rgb = [R(:) G(:) B(:)]; if (n_colors > size(rgb,1)/3) error('You can''t readily distinguish that many colors'); end % Convert to Lab color space, which more closely represents human % perception if (nargin > 2) lab = func(rgb); bglab = func(bg); else C = makecform('srgb2lab'); lab = applycform(rgb,C); bglab = applycform(bg,C); end % If the user specified multiple background colors, compute distances % from the candidate colors to the background colors mindist2 = inf(size(rgb,1),1); for i = 1:size(bglab,1)-1 dX = bsxfun(@minus,lab,bglab(i,:)); % displacement all colors from bg dist2 = sum(dX.^2,2); % square distance mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color end % Iteratively pick the color that maximizes the distance to the nearest % already-picked color colors = zeros(n_colors,3); lastlab = bglab(end,:); % initialize by making the "previous" color equal to background for i = 1:n_colors dX = bsxfun(@minus,lab,lastlab); % displacement of last from all colors on list dist2 = sum(dX.^2,2); % square distance mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color [~,index] = max(mindist2); % find the entry farthest from all previously-chosen colors colors(i,:) = rgb(index,:); % save for output lastlab = lab(index,:); % prepare for next iteration end end function c = parsecolor(s) if ischar(s) c = colorstr2rgb(s); elseif isnumeric(s) && size(s,2) == 3 c = s; else error('MATLAB:InvalidColorSpec','Color specification cannot be parsed.'); end end function c = colorstr2rgb(c) % Convert a color string to an RGB value. % This is cribbed from Matlab's whitebg function. % Why don't they make this a stand-alone function? rgbspec = [1 0 0;0 1 0;0 0 1;1 1 1;0 1 1;1 0 1;1 1 0;0 0 0]; cspec = 'rgbwcmyk'; k = find(cspec==c(1)); if isempty(k) error('MATLAB:InvalidColorString','Unknown color string.'); end if k~=3 || length(c)==1, c = rgbspec(k,:); elseif length(c)>2, if strcmpi(c(1:3),'bla') c = [0 0 0]; elseif strcmpi(c(1:3),'blu') c = [0 0 1]; else error('MATLAB:UnknownColorString', 'Unknown color string.'); end end end
github
x75/otl-master
smoothn.m
.m
otl-master/otl_matlab/helpers/smoothn/smoothn.m
16,852
utf_8
54eb929ec4730522e6e116048d127f45
function [z,s,exitflag] = smoothn(varargin) %SMOOTHN Robust spline smoothing for 1-D to N-D data. % SMOOTHN provides a fast, automatized and robust discretized smoothing % spline for data of arbitrary dimension. % % Z = SMOOTHN(Y) automatically smoothes the uniformly-sampled array Y. Y % can be any N-D noisy array (time series, images, 3D data,...). Non % finite data (NaN or Inf) are treated as missing values. % % Z = SMOOTHN(Y,S) smoothes the array Y using the smoothing parameter S. % S must be a real positive scalar. The larger S is, the smoother the % output will be. If the smoothing parameter S is omitted (see previous % option) or empty (i.e. S = []), it is automatically determined by % minimizing the generalized cross-validation (GCV) score. % % Z = SMOOTHN(Y,W) or Z = SMOOTHN(Y,W,S) smoothes Y using a weighting % array W of positive values, that must have the same size as Y. Note % that a nil weight corresponds to a missing value. % % Robust smoothing % ---------------- % Z = SMOOTHN(...,'robust') carries out a robust smoothing that minimizes % the influence of outlying data. % % [Z,S] = SMOOTHN(...) also returns the calculated value for the % smoothness parameter S so that you can fine-tune the smoothing % subsequently if needed. % % An iteration process is used in the presence of weighted and/or missing % values. Z = SMOOTHN(...,OPTION_NAME,OPTION_VALUE) smoothes with the % termination parameters specified by OPTION_NAME and OPTION_VALUE. They % can contain the following criteria: % ----------------- % TolZ: Termination tolerance on Z (default = 1e-3) % TolZ must be in ]0,1[ % MaxIter: Maximum number of iterations allowed (default = 100) % Initial: Initial value for the iterative process (default = % original data) % Weights: Weighting function for robust smoothing: % 'bisquare' (default), 'talworth' or 'cauchy' % ----------------- % Syntax: [Z,...] = SMOOTHN(...,'MaxIter',500,'TolZ',1e-4,'Initial',Z0); % % [Z,S,EXITFLAG] = SMOOTHN(...) returns a boolean value EXITFLAG that % describes the exit condition of SMOOTHN: % 1 SMOOTHN converged. % 0 Maximum number of iterations was reached. % % Notes % ----- % The N-D (inverse) discrete cosine transform functions <a % href="matlab:web('http://www.biomecardio.com/matlab/dctn.html')" % >DCTN</a> and <a % href="matlab:web('http://www.biomecardio.com/matlab/idctn.html')" % >IDCTN</a> are required. % % Reference % --------- % Garcia D, Robust smoothing of gridded data in one and higher dimensions % with missing values. Computational Statistics & Data Analysis, 2010. % <a % href="matlab:web('http://www.biomecardio.com/pageshtm/publi/csda10.pdf')">PDF download</a> % % Examples: % -------- % % 1-D example % x = linspace(0,100,2^8); % y = cos(x/10)+(x/50).^2 + randn(size(x))/10; % y([70 75 80]) = [5.5 5 6]; % z = smoothn(y); % Regular smoothing % zr = smoothn(y,'robust'); % Robust smoothing % subplot(121), plot(x,y,'r.',x,z,'k','LineWidth',2) % axis square, title('Regular smoothing') % subplot(122), plot(x,y,'r.',x,zr,'k','LineWidth',2) % axis square, title('Robust smoothing') % % % 2-D example % xp = 0:.02:1; % [x,y] = meshgrid(xp); % f = exp(x+y) + sin((x-2*y)*3); % fn = f + randn(size(f))*0.5; % fs = smoothn(fn); % subplot(121), surf(xp,xp,fn), zlim([0 8]), axis square % subplot(122), surf(xp,xp,fs), zlim([0 8]), axis square % % % 2-D example with missing data % n = 256; % y0 = peaks(n); % y = y0 + randn(size(y0))*2; % I = randperm(n^2); % y(I(1:n^2*0.5)) = NaN; % lose 1/2 of data % y(40:90,140:190) = NaN; % create a hole % z = smoothn(y); % smooth data % subplot(2,2,1:2), imagesc(y), axis equal off % title('Noisy corrupt data') % subplot(223), imagesc(z), axis equal off % title('Recovered data ...') % subplot(224), imagesc(y0), axis equal off % title('... compared with original data') % % % 3-D example % [x,y,z] = meshgrid(-2:.2:2); % xslice = [-0.8,1]; yslice = 2; zslice = [-2,0]; % vn = x.*exp(-x.^2-y.^2-z.^2) + randn(size(x))*0.06; % subplot(121), slice(x,y,z,vn,xslice,yslice,zslice,'cubic') % title('Noisy data') % v = smoothn(vn); % subplot(122), slice(x,y,z,v,xslice,yslice,zslice,'cubic') % title('Smoothed data') % % % Cardioid % t = linspace(0,2*pi,1000); % x = 2*cos(t).*(1-cos(t)) + randn(size(t))*0.1; % y = 2*sin(t).*(1-cos(t)) + randn(size(t))*0.1; % z = smoothn(complex(x,y)); % plot(x,y,'r.',real(z),imag(z),'k','linewidth',2) % axis equal tight % % % Cellular vortical flow % [x,y] = meshgrid(linspace(0,1,24)); % Vx = cos(2*pi*x+pi/2).*cos(2*pi*y); % Vy = sin(2*pi*x+pi/2).*sin(2*pi*y); % Vx = Vx + sqrt(0.05)*randn(24,24); % adding Gaussian noise % Vy = Vy + sqrt(0.05)*randn(24,24); % adding Gaussian noise % I = randperm(numel(Vx)); % Vx(I(1:30)) = (rand(30,1)-0.5)*5; % adding outliers % Vy(I(1:30)) = (rand(30,1)-0.5)*5; % adding outliers % Vx(I(31:60)) = NaN; % missing values % Vy(I(31:60)) = NaN; % missing values % Vs = smoothn(complex(Vx,Vy),'robust'); % automatic smoothing % subplot(121), quiver(x,y,Vx,Vy,2.5), axis square % title('Noisy velocity field') % subplot(122), quiver(x,y,real(Vs),imag(Vs)), axis square % title('Smoothed velocity field') % % See also DCTSMOOTH, DCTN, IDCTN. % % -- Damien Garcia -- 2009/03, revised 2012/04 % website: <a % href="matlab:web('http://www.biomecardio.com')">www.BiomeCardio.com</a> % Check input arguments error(nargchk(1,12,nargin)); %% Test & prepare the variables %--- k = 0; while k<nargin && ~ischar(varargin{k+1}), k = k+1; end %--- % y = array to be smoothed y = double(varargin{1}); sizy = size(y); noe = prod(sizy); % number of elements if noe<2, z = y; s = []; exitflag = true; return, end %--- % Smoothness parameter and weights W = ones(sizy); s = []; if k==2 if isempty(varargin{2}) || isscalar(varargin{2}) % smoothn(y,s) s = varargin{2}; % smoothness parameter else % smoothn(y,W) W = varargin{2}; % weight array end elseif k==3 % smoothn(y,W,s) W = varargin{2}; % weight array s = varargin{3}; % smoothness parameter end if ~isequal(size(W),sizy) error('MATLAB:smoothn:SizeMismatch',... 'Arrays for data and weights (Y and W) must have same size.') elseif ~isempty(s) && (~isscalar(s) || s<0) error('MATLAB:smoothn:IncorrectSmoothingParameter',... 'The smoothing parameter S must be a scalar >=0') end %--- % "Maximal number of iterations" criterion I = find(strcmpi(varargin,'MaxIter'),1); if isempty(I) MaxIter = 100; % default value for MaxIter else try MaxIter = varargin{I+1}; catch ME error('MATLAB:smoothn:IncorrectMaxIter',... 'MaxIter must be an integer >=1') end if ~isnumeric(MaxIter) || ~isscalar(MaxIter) ||... MaxIter<1 || MaxIter~=round(MaxIter) error('MATLAB:smoothn:IncorrectMaxIter',... 'MaxIter must be an integer >=1') end end %--- % "Tolerance on smoothed output" criterion I = find(strcmpi(varargin,'TolZ'),1); if isempty(I) TolZ = 1e-3; % default value for TolZ else try TolZ = varargin{I+1}; catch ME error('MATLAB:smoothn:IncorrectTolZ',... 'TolZ must be in ]0,1[') end if ~isnumeric(TolZ) || ~isscalar(TolZ) || TolZ<=0 || TolZ>=1 error('MATLAB:smoothn:IncorrectTolZ',... 'TolZ must be in ]0,1[') end end %--- % "Initial Guess" criterion I = find(strcmpi(varargin,'Initial'),1); if isempty(I) isinitial = false; % default value for TolZ else isinitial = true; try z0 = varargin{I+1}; catch ME error('MATLAB:smoothn:IncorrectInitialGuess',... 'Z0 must be a valid initial guess for Z') end if ~isnumeric(z0) || ~isequal(size(z0),sizy) error('MATLAB:smoothn:IncorrectTolZ',... 'Z0 must be a valid initial guess for Z') end end %--- % "Weighting function" criterion (for robust smoothing) I = find(strcmpi(varargin,'Weights'),1); if isempty(I) weightstr = 'bisquare'; % default weighting function else try weightstr = lower(varargin{I+1}); catch ME error('MATLAB:smoothn:IncorrectWeights',... 'A valid weighting function must be chosen') end if ~ischar(weightstr) error('MATLAB:smoothn:IncorrectWeights',... 'A valid weighting function must be chosen') end end %--- % Weights. Zero weights are assigned to not finite values (Inf or NaN), % (Inf/NaN values = missing data). IsFinite = isfinite(y); nof = nnz(IsFinite); % number of finite elements W = W.*IsFinite; if any(W<0) error('MATLAB:smoothn:NegativeWeights',... 'Weights must all be >=0') else W = W/max(W(:)); end %--- % Weighted or missing data? isweighted = any(W(:)<1); %--- % Robust smoothing? isrobust = any(strcmpi(varargin,'robust')); %--- % Automatic smoothing? isauto = isempty(s); %--- % DCTN and IDCTN are required test4DCTNandIDCTN %% Create the Lambda tensor %--- % Lambda contains the eingenvalues of the difference matrix used in this % penalized least squares process (see CSDA paper for details) d = ndims(y); m = 2; Lambda = zeros(sizy); for i = 1:d siz0 = ones(1,d); siz0(i) = sizy(i); Lambda = bsxfun(@plus,Lambda,... cos(pi*(reshape(1:sizy(i),siz0)-1)/sizy(i))); end Lambda = 2*(d-Lambda); if ~isauto, Gamma = 1./(1+s*Lambda.^m); end %% Upper and lower bound for the smoothness parameter % The average leverage (h) is by definition in [0 1]. Weak smoothing occurs % if h is close to 1, while over-smoothing appears when h is near 0. Upper % and lower bounds for h are given to avoid under- or over-smoothing. See % equation relating h to the smoothness parameter (Equation #12 in the % referenced CSDA paper). N = sum(sizy~=1); % tensor rank of the y-array hMin = 1e-6; hMax = 0.99; sMinBnd = (((1+sqrt(1+8*hMax.^(2/N)))/4./hMax.^(2/N)).^2-1)/16; sMaxBnd = (((1+sqrt(1+8*hMin.^(2/N)))/4./hMin.^(2/N)).^2-1)/16; %% Initialize before iterating %--- Wtot = W; %--- Initial conditions for z if isweighted %--- With weighted/missing data % An initial guess is provided to ensure faster convergence. For that % purpose, a nearest neighbor interpolation followed by a coarse % smoothing are performed. %--- if isinitial % an initial guess (z0) has been already given z = z0; else z = InitialGuess(y,IsFinite); end else z = zeros(sizy); end %--- z0 = z; y(~IsFinite) = 0; % arbitrary values for missing y-data %--- tol = 1; RobustIterativeProcess = true; RobustStep = 1; nit = 0; %--- Error on p. Smoothness parameter s = 10^p errp = 0.1; opt = optimset('TolX',errp); %--- Relaxation factor RF: to speedup convergence RF = 1 + 0.75*isweighted; %% Main iterative process %--- while RobustIterativeProcess %--- "amount" of weights (see the function GCVscore) aow = sum(Wtot(:))/noe; % 0 < aow <= 1 %--- while tol>TolZ && nit<MaxIter nit = nit+1; DCTy = dctn(Wtot.*(y-z)+z); if isauto && ~rem(log2(nit),1) %--- % The generalized cross-validation (GCV) method is used. % We seek the smoothing parameter S that minimizes the GCV % score i.e. S = Argmin(GCVscore). % Because this process is time-consuming, it is performed from % time to time (when the step number - nit - is a power of 2) %--- fminbnd(@gcv,log10(sMinBnd),log10(sMaxBnd),opt); end z = RF*idctn(Gamma.*DCTy) + (1-RF)*z; % if no weighted/missing data => tol=0 (no iteration) tol = isweighted*norm(z0(:)-z(:))/norm(z(:)); z0 = z; % re-initialization end exitflag = nit<MaxIter; if isrobust %-- Robust Smoothing: iteratively re-weighted process %--- average leverage h = sqrt(1+16*s); h = sqrt(1+h)/sqrt(2)/h; h = h^N; %--- take robust weights into account Wtot = W.*RobustWeights(y-z,IsFinite,h,weightstr); %--- re-initialize for another iterative weighted process isweighted = true; tol = 1; nit = 0; %--- RobustStep = RobustStep+1; RobustIterativeProcess = RobustStep<4; % 3 robust steps are enough. else RobustIterativeProcess = false; % stop the whole process end end %% Warning messages %--- if isauto if abs(log10(s)-log10(sMinBnd))<errp warning('MATLAB:smoothn:SLowerBound',... ['S = ' num2str(s,'%.3e') ': the lower bound for S ',... 'has been reached. Put S as an input variable if required.']) elseif abs(log10(s)-log10(sMaxBnd))<errp warning('MATLAB:smoothn:SUpperBound',... ['S = ' num2str(s,'%.3e') ': the upper bound for S ',... 'has been reached. Put S as an input variable if required.']) end end if nargout<3 && ~exitflag warning('MATLAB:smoothn:MaxIter',... ['Maximum number of iterations (' int2str(MaxIter) ') has ',... 'been exceeded. Increase MaxIter option or decrease TolZ value.']) end %% GCV score %--- function GCVscore = gcv(p) % Search the smoothing parameter s that minimizes the GCV score %--- s = 10^p; Gamma = 1./(1+s*Lambda.^m); %--- RSS = Residual sum-of-squares if aow>0.9 % aow = 1 means that all of the data are equally weighted % very much faster: does not require any inverse DCT RSS = norm(DCTy(:).*(Gamma(:)-1))^2; else % take account of the weights to calculate RSS: yhat = idctn(Gamma.*DCTy); RSS = norm(sqrt(Wtot(IsFinite)).*(y(IsFinite)-yhat(IsFinite)))^2; end %--- TrH = sum(Gamma(:)); GCVscore = RSS/nof/(1-TrH/noe)^2; end end %% Robust weights function W = RobustWeights(r,I,h,wstr) % weights for robust smoothing. MAD = median(abs(r(I)-median(r(I)))); % median absolute deviation u = abs(r/(1.4826*MAD)/sqrt(1-h)); % studentized residuals if strcmp(wstr,'cauchy') c = 2.385; W = 1./(1+(u/c).^2); % Cauchy weights elseif strcmp(wstr,'talworth') c = 2.795; W = u<c; % Talworth weights elseif strcmp(wstr,'bisquare') c = 4.685; W = (1-(u/c).^2).^2.*((u/c)<1); % bisquare weights else error('MATLAB:smoothn:IncorrectWeights',... 'A valid weighting function must be chosen') end W(isnan(W)) = 0; end %% Test for DCTN and IDCTN function test4DCTNandIDCTN if ~exist('dctn','file') error('MATLAB:smoothn:MissingFunction',... ['DCTN and IDCTN are required. Download DCTN <a href="matlab:web(''',... 'http://www.biomecardio.com/matlab/dctn.html'')">here</a>.']) elseif ~exist('idctn','file') error('MATLAB:smoothn:MissingFunction',... ['DCTN and IDCTN are required. Download IDCTN <a href="matlab:web(''',... 'http://www.biomecardio.com/matlab/idctn.html'')">here</a>.']) end end %% Initial Guess with weighted/missing data function z = InitialGuess(y,I) %-- nearest neighbor interpolation (in case of missing values) if any(~I(:)) if license('test','image_toolbox') [~,L] = bwdist(I); z = y; z(~I) = y(L(~I)); else % If BWDIST does not exist, NaN values are all replaced with the % same scalar. The initial guess is not optimal and a warning % message thus appears. z = y; z(~I) = mean(y(I)); warning('MATLAB:smoothn:InitialGuess',... ['BWDIST (Image Processing Toolbox) does not exist. ',... 'The initial guess may not be optimal; additional',... ' iterations can thus be required to ensure complete',... ' convergence. Increase ''MaxIter'' criterion if necessary.']) end else z = y; end %-- coarse fast smoothing using one-tenth of the DCT coefficients siz = size(z); z = dctn(z); for k = 1:ndims(z) z(ceil(siz(k)/10)+1:end,:) = 0; z = reshape(z,circshift(siz,[0 1-k])); z = shiftdim(z,1); end z = idctn(z); end
github
mc225/Softwares_Tom-master
monitor.m
.m
Softwares_Tom-master/GUI/monitor.m
65,754
utf_8
cdd840c3d90ca7c327e11fe824882e53
% % Graphical User Interface to control the SLM and laser while monitoring the camera output. % This tool can be used with all SLM based set-ups, both for quick testing, % alignment, aberration correction (various methods), and actual measurement. % % Current features: % - control of complex (amplitude and phase) on both phase-only and dual % head SLMs. % - simple syntax for defining complex, and dynamic pupil modulations: % - X: the horizontal coordinate in pixels, left from the center (rounded up) % - Y: the vertical coordinate in pixels, down from the center (rounded up) % - R (or Rho, or Rh): the radial coordinate in pixels (sqrt(X.^2+Y.^2)) % - P (or Phi, or Ph): the azimutal coordinate in pixels (atan2(Y,X)) % - t (or time): the time in seconds after entering the expression % - any other Matlab matrix function (including your custom functions). % - scalar notation works as well, e.g. exp(2i*pi*X^2) causes % - first order and zero-order modulation % - aberration correction using: % - Plane waves at back aperture plane (M)azilu method % - Plane waves at focal plane (C)izmar method % - (Z)ernike modes (local, phase only optimization) % - amplitude attenuation can be corrected as well as phase % - precalibrated aberration corrections can be loaded % - 3D control of first order spot % - gamma curve adjustement for different wavelengths % - recording of images or movies % - permits frame averaging to increase the SNR % - suports all cameras for which the Cam interface is implemented % - allows control of the light source (currently only the NKT SuperK supercontinuum) % - can be tested without camera and/or SLM % % % You are welcome to use and modify these files under the condition % that you leave this message included with the files at all time. % Do not redistribute these files outwith the optical manipulation % group in St. Andrews! % Please let me know if you have any suggestions for improving % this code, and feel free to commit your own improvements to the repository. % % Thanks, % % Tom Vettenburg % function varargout = monitor(varargin) % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @monitor_OpeningFcn, ... 'gui_OutputFcn', @monitor_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT end % --- Executes just before monitor is made visible. function monitor_OpeningFcn(fig, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to monitor (see VARARGIN) % Avoid racing conditions set(fig,'Interruptible','off') % Choose default command line output for monitor handles.output = fig; % Update handles structure guidata(fig, handles); % UIWAIT makes monitor wait for user response (see UIRESUME) % uiwait(handles.figure1); % Attempt to load the GUI status from disk loadStatus(); updateStatus('version',0.99); setUserData('isClosing',false); setUserData('probing',false); setUserData('slm',[]); setUserData('lightSource',[]); detectedLightSources=detectLightSources(); setUserData('detectedLightSources',detectedLightSources); setUserData('baseWavelength',[]); setUserData('sourceWavelengthForDeflectionCorrection',[]); setUserData('camRequestedRegionOfInterest',[-1 -1 -1 -1]); setUserData('currentImageOnSLM',[]); setUserData('initialTimeOfGUI',clock()); setUserData('frameUpdateTimes',NaN*ones(1,1000)); setUserData('fullScreenManager',DefaultScreenManager.instance); fontSize=16; set(fig,'Units','normalized','Position',getStatus('mainWindowPosition',[0 .1 .8 .8]),'Resize','on','ResizeFcn',@(obj,event) updateStatus('mainWindowPosition',get(obj,'Position'))); set(fig,'BackingStore','off'); % set(fig,'DoubleBuffer','off'); %Required? cameraPanel=uipanel('Parent',fig,'Units','normalized','Position',[0 0 .5 1],'Title','Camera'); slmPanel=uipanel('Parent',fig,'Units','normalized','Position',[.5 0 .5 .9],'Title','Spatial Light Modulator'); lightSourcePanel=uipanel('Parent',fig,'Units','normalized','Position',[.5 0.9 .5 .1],'Title','Light Source'); histogramAxes=axes('Parent',cameraPanel); set(histogramAxes,'Position',[.15 .875 .8 .1],'Units','normalized'); set(histogramAxes,'XTickMode','manual','YTickMode','manual','XTick',[0:.1:1],'XTickLabel',[0:10:100]); set(histogramAxes,'XLim',[0 1]); set(histogramAxes,'FontName','Arial','FontWeight','bold','FontSize',fontSize*.8); xlabel(histogramAxes,'intensity [%]','FontName','Arial','FontWeight','bold','FontSize',fontSize); ylabel(histogramAxes,'# [%]','FontName','Arial','FontWeight','bold','FontSize',fontSize); setUserData('histogramAxes',histogramAxes); cameraAxes=axes('Parent',cameraPanel); set(cameraAxes,'Position',[.15 .15 .8 .6],'Units','normalized'); set(cameraAxes,'FontName','Arial','FontWeight','bold','FontSize',fontSize*.8); xlabel(cameraAxes,'x [pixels]','FontName','Arial','FontWeight','bold','FontSize',fontSize); ylabel(cameraAxes,'y [pixels]','FontName','Arial','FontWeight','bold','FontSize',fontSize); setUserData('cameraAxes',cameraAxes); pupilAxes=axes('Parent',slmPanel); set(pupilAxes,'Position',[.05 .2 .8 .6],'Units','normalized'); colormap(pupilAxes,gray(256)); setUserData('pupilAxes',pupilAxes); set(fig,'CloseRequestFcn',@closeApp); cameraControlPanel=uipanel('Parent',cameraPanel,'Title','Camera Control','Units','pixels','Position',[10 10 320 40]); changeCamPopupMenu=uicontrol('Parent',cameraControlPanel,'Position',[5 5 80 20],'Tag','changeCam','Style', 'popupmenu', 'Callback', @changeCam); detectedCameras=detectCameras(); setUserData('detectedCameras',detectedCameras); %See if we can find the camera of last time again defaultCameraType=getStatus('defaultCameraType','DummyCam'); defaultCameraIndex=getStatus('defaultCameraIndex',1); defaultCameraDropDownIndex=find(strcmpi({detectedCameras.type},defaultCameraType)); switch(length(defaultCameraDropDownIndex)) case 0 defaultCameraDropDownIndex=1; % Dummy Cam 1 case 1 % Index may have changed, but we don't care otherwise closerMatchForDefaultCameraDropDownIndex=find(strcmpi({detectedCameras.type},defaultCameraType) & [detectedCameras.index]==defaultCameraIndex); if (~isempty(closerMatchForDefaultCameraDropDownIndex)) defaultCameraDropDownIndex=closerMatchForDefaultCameraDropDownIndex(1); else defaultCameraDropDownIndex=defaultCameraDropDownIndex(1); % Just pick the first one, even if the index doesn't match end end set(changeCamPopupMenu,'String',{detectedCameras.description},'Value',defaultCameraDropDownIndex); uicontrol('Parent',cameraControlPanel,'Position',[90 5 40 20],'Style', 'text','String','int. time:'); integrationTimeEdit=uicontrol('Parent',cameraControlPanel,'Position',[130 5 40 20],'Tag','integrationTimeEdit','Style', 'edit', 'Callback', @adjustIntegrationTime,'String',getStatus('integrationTime','20')); setUserData('integrationTimeEdit',integrationTimeEdit); uicontrol('Parent',cameraControlPanel,'Position',[160 5 20 20],'Style', 'text','String','ms'); uicontrol('Parent',cameraControlPanel,'Position',[180 5 25 20],'Style', 'text','String','gain:'); gainEdit=uicontrol('Parent',cameraControlPanel,'Position',[205 5 20 20],'Tag','gainEdit','Style', 'edit', 'Callback', @adjustGain, 'String',getStatus('gain','1')); setUserData('gainEdit',gainEdit); uicontrol('Parent',cameraControlPanel,'Position',[225 5 20 20],'Style', 'text','String','#:'); numberOfFramesEdit=uicontrol('Parent',cameraControlPanel,'Position',[240 5 20 20],'Tag','numberOfFramesEdit','Style', 'edit', 'Callback', @adjustNumberOfFrames,'String',getStatus('numberOfFrames','1')); setUserData('numberOfFramesEdit',numberOfFramesEdit); uicontrol('Parent',cameraControlPanel,'Position',[260 5 30 20],'Tag','darkButton','Style', 'togglebutton','String','Dark','FontWeight','bold','Callback',@updateDarkImage); pausePlayButton=uicontrol('Parent',cameraControlPanel,'Position',[290 5 20 20],'Tag','pausePlayButton','Style', 'togglebutton','String','','FontWeight','bold','Callback',@pausePlay); setUserData('pausePlayButton',pausePlayButton); setUserData('recording',false); changeCam(changeCamPopupMenu,[]); recordingPanel=uipanel('Parent',cameraPanel,'Title','Recording Control','Units','pixels','Position',[330 10 215 40]); uicontrol('Parent',recordingPanel,'Position',[5 5 60 20],'Style','pushbutton','String','Browse...','Callback',@selectOutputFile); outputFileEdit=uicontrol('Parent',recordingPanel,'Position',[65 5 110 20],'Style', 'edit','String',''); setUserData('outputFileEdit',outputFileEdit); uicontrol('Parent',recordingPanel,'Position',[175 5 35 20],'Style', 'togglebutton','String','REC!','Callback',@toggleOutputRecording); % % Source Panel % changeLightSourcePopUpMenu=uicontrol('Parent',lightSourcePanel,'Position',[5 5 70 20],'Tag','changeLightSourcePopUpMenu','Style', 'popupmenu', 'Callback', @changeLightSource); lightSourceTypeIdx=find(strcmp({detectedLightSources.type},getStatus('defaultLightSourceType')),1); if (isempty(lightSourceTypeIdx)) lightSourceTypeIdx=1; else lightSourceTypeIdx=lightSourceTypeIdx(1); end set(changeLightSourcePopUpMenu,'String',{detectedLightSources.description},'Value',lightSourceTypeIdx); setUserData('changeLightSourcePopUpMenu',changeLightSourcePopUpMenu); uicontrol('Parent',lightSourcePanel,'Position',[80 5 75 20],'Style','text','String','target power:'); targetPowerEdit=uicontrol('Parent',lightSourcePanel,'Position',[150 5 40 20],'Tag','targetPowerEdit','Style', 'edit', 'Callback', @adjustTargetPower,'String',getStatus('targetPower','0')); uicontrol('Parent',lightSourcePanel,'Position',[190 5 30 20],'Style','text','String','%'); setUserData('targetPowerEdit',targetPowerEdit); uicontrol('Parent',lightSourcePanel,'Position',[190 5 95 20],'Style','text','String','wavelengths:'); wavelengthsEdit=uicontrol('Parent',lightSourcePanel,'Position',[280 5 120 20],'Tag','wavelengthsEdit','Style', 'edit', 'Callback', @adjustWavelengths,'String',getStatus('wavelengths','500')); uicontrol('Parent',lightSourcePanel,'Position',[390 5 30 20],'Style','text','String','nm'); setUserData('wavelengthsEdit',wavelengthsEdit); uicontrol('Parent',lightSourcePanel,'Position',[415 5 95 20],'Style','text','String','base wavelength:'); baseWavelengthEdit=uicontrol('Parent',lightSourcePanel,'Position',[510 5 60 20],'Tag','baseWavelengthEdit','Style', 'edit', 'Callback', @adjustBaseWavelength,'String',getStatus('baseWavelength','500')); uicontrol('Parent',lightSourcePanel,'Position',[570 5 30 20],'Style','text','String','nm'); setUserData('baseWavelengthEdit',baseWavelengthEdit); % % Spatial Light Modulator % slmControlPanel=uipanel('Parent',slmPanel,'Title','SLM Control','Units','pixels','Position',[10 10 530 90]); changeSLMPopUpMenu=uicontrol('Parent',slmControlPanel,'Position',[5 55 90 20],'Tag','changeSLMPopUpMenu','Style', 'popupmenu', 'Callback', @updateSLMDisplayNumberOrSLM); set(changeSLMPopUpMenu,'String',{'phase only SLM','dual head SLM','BNS phase SLM'},'Value',getStatus('slmTypeIndex',1)); setUserData('changeSLMPopUpMenu',changeSLMPopUpMenu); uicontrol('Parent',slmControlPanel,'Position',[95 55 20 20],'Style','text','String','on:'); slmDisplayNumberPopUpMenu=uicontrol('Parent',slmControlPanel,'Position',[112 55 100 20],'Tag','slmDisplayNumberPopUpMenu','Style', 'popupmenu', 'Callback', @updateSLMDisplayNumberOrSLM); populateSLMDisplayNumberPopupMenu(slmDisplayNumberPopUpMenu); setUserData('slmDisplayNumberPopUpMenu',slmDisplayNumberPopUpMenu); setUserData('slmAxes',[]); defaultDisplayIndex=getStatus('slmDisplayNumber',1); if (defaultDisplayIndex>length(get(slmDisplayNumberPopUpMenu,'String'))) defaultDisplayIndex=1; % popup end set(slmDisplayNumberPopUpMenu,'Value',defaultDisplayIndex); updateSLMDisplayNumberOrSLM(slmDisplayNumberPopUpMenu); setUserData(slmDisplayNumberPopUpMenu); uicontrol('Parent',slmControlPanel,'Position',[215 55 20 20],'Style','text','String','2pi='); twoPiEquivalentEdit=uicontrol('Parent',slmControlPanel,'Position',[235 55 25 20],'Tag','twoPiEquivalentEdit','Style', 'edit', 'Callback', @adjustTwoPiEquivalent,'String',getStatus('twoPiEquivalent','100')); uicontrol('Parent',slmControlPanel,'Position',[260 55 20 20],'Tag','estimateTwoPiEquivalentButton','Style', 'pushbutton','String','%!','FontWeight','bold','Callback',@estimateTwoPiEquivalentCallback); %uicontrol('Parent',slmControlPanel,'Position',[263 55 10 20],'Style','text','String','%'); setUserData('twoPiEquivalentEdit',twoPiEquivalentEdit); uicontrol('Parent',slmControlPanel,'Position',[280 55 95 20],'Style','text','String','deflect(x,y,{w20}):'); deflectionEdit=uicontrol('Parent',slmControlPanel,'Position',[370 55 70 20],'Tag','deflectionEdit','Style', 'edit', 'Callback', @adjustDeflection,'String',getStatus('deflection','1/10 1/10 0')); uicontrol('Parent',slmControlPanel,'Position',[445 55 30 20],'Style','text','String','pix^-1'); setUserData('deflectionEdit',deflectionEdit); uicontrol('Parent',slmControlPanel,'Position',[5 30 50 20],'Style','text','String','correction:'); correctionEdit=uicontrol('Parent',slmControlPanel,'Position',[60 30 250 20],'Tag','correctionEdit','Style', 'edit', 'Callback',@adjustCorrection,'String',getStatus('correction','')); uicontrol('Parent',slmControlPanel,'Position',[310 30 60 20],'Style','pushbutton','String','Browse...','Callback',@loadCorrection); probeMethodToggle=uicontrol('Parent',slmControlPanel,'Position',[370 30 15 20],'Tag','probeMethod','Style','togglebutton','String',getStatus('probeMethodToggle','M'),'FontWeight','bold','Callback',@toggleProbeMethod); setUserData('probeMethodToggle',probeMethodToggle); uicontrol('Parent',slmControlPanel,'Position',[385 30 50 20],'Tag','estimateCorrectionButton','Style','pushbutton','String','Probe!','FontWeight','bold','Callback',@estimateCorrection); setUserData('correctionEdit',correctionEdit); uicontrol('Parent',slmControlPanel,'Position',[435 30 25 20],'Style','text','String','size:'); probeSizeEdit=uicontrol('Parent',slmControlPanel,'Position',[460 30 20 20],'Tag','probeSizeEdit','Style', 'edit', 'Callback',@updateProbeSize,'String',getStatus('probeSize','1')); setUserData('probeSizeEdit',probeSizeEdit); updateProbeSize(); uicontrol('Parent',slmControlPanel,'Position',[480 30 25 20],'Style','text','String','amp/'); amplificationLimitEdit=uicontrol('Parent',slmControlPanel,'Position',[505 30 20 20],'Tag','amplificationLimitEdit','Style', 'edit', 'Callback',@updateAmplificationLimit,'String',getStatus('amplificationLimit','1')); setUserData('amplificationLimitEdit',amplificationLimitEdit); uicontrol('Parent',slmControlPanel,'Position',[5 5 30 20],'Style','text','String','pupil:'); maskEdit=uicontrol('Parent',slmControlPanel,'Position',[45 5 280 20],'Tag','maskEdit','Style', 'edit', 'Callback', @updateSLMDisplayAndOutput,'String',getStatus('mask','R<200')); uicontrol('Parent',slmControlPanel,'Position',[330 5 30 20],'Style','text','String','pix^-1'); uicontrol('Parent',slmControlPanel,'Position',[360 5 20 20],'Style','pushbutton','String','T','FontWeight','bold','Callback', @(obj,event) insertPupilRadiusAndUpdateSLM('R<pupilRadius')); uicontrol('Parent',slmControlPanel,'Position',[380 5 20 20],'Style','pushbutton','String','B','FontWeight','bold','Callback', @(obj,event) insertPupilRadiusAndUpdateSLM('R>0.9*pupilRadius & R<pupilRadius')); uicontrol('Parent',slmControlPanel,'Position',[400 5 20 20],'Style','pushbutton','String','V','FontWeight','bold','Callback', @(obj,event) insertPupilRadiusAndUpdateSLM('(Rho<pupilRadius)*exp(i*Phi)')); uicontrol('Parent',slmControlPanel,'Position',[420 5 20 20],'Style','pushbutton','String','A','FontWeight','bold','Callback', @(obj,event) insertPupilRadiusAndUpdateSLM('(R<pupilRadius)*exp(3*2i*pi*((X/pupilRadius)^3+(Y/pupilRadius)^3))')); uicontrol('Parent',slmControlPanel,'Position',[440 5 20 20],'Style','pushbutton','String','+','FontWeight','bold','Callback', @(obj,event) insertPupilRadiusAndUpdateSLM('(R<pupilRadius)*(abs(R*cos(P-t*pi/20))<pupilRadius/50 | abs(R*sin(P-t*pi/20))<pupilRadius/50)')); setUserData('maskEdit',maskEdit); % align(HandleList,'Fixed',5,'Fixed',10); changeSLM(changeSLMPopUpMenu,[]); changeLightSource(); % Do this after setting the deflection dragzoom(cameraAxes); set(fig,'Name','monitor - SLM aberration correction GUI'); end % --- Outputs from this function are returned to the command line. function varargout = monitor_OutputFcn(fig, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure % varargout{1} = handles.output; pausePlay(); %Start recording varargout={}; end function updatePupilModulationOnSLM() pupilFunction=getUserData('pupilFunction'); lastPupilFunctionUpdate=getUserData('lastPupilFunctionUpdate'); initialTimeOfSLM = getUserData('initialTimeOfSLM'); timeNow=etime(clock(),initialTimeOfSLM); slm=getUserData('slm'); regionOfInterestSize=slm.regionOfInterest; regionOfInterestSize=regionOfInterestSize(3:4); regionOfInterestCenter=floor(regionOfInterestSize./2)+1; if (lastPupilFunctionUpdate<0 || getUserData('pupilFunctionTimeDependent')) [X,Y]=meshgrid([1:regionOfInterestSize(2)]-regionOfInterestCenter(2),[1:regionOfInterestSize(1)]-regionOfInterestCenter(1)); if (lastPupilFunctionUpdate<0 || any(any(pupilFunction(X,Y,lastPupilFunctionUpdate)~=pupilFunction(X,Y,timeNow)))) refreshPupilModulationOnSLM(); % % Display also on screen % % Remove image if the size is different pupilAxes=getUserData('pupilAxes'); imgObject=findobj(pupilAxes,'Type','image'); if (~isempty(imgObject)) %Determine current image size currentImgSize=size(get(imgObject,'CData')); %Check size and remove if needed if (any(currentImgSize(1:2)~=regionOfInterestSize)) set(imgObject,'CData',[]); end end % Update pupil display pupil=pupilFunction(X,Y,timeNow); if (max(abs(imag(pupil(:))))<10*eps(class(pupil))) pupil=pupil.*exp(1e-6i); %Make complex for display end showImage(pupil,[],X,Y,pupilAxes); end end end function refreshPupilModulationOnSLM() pupilFunction=getUserData('pupilFunction'); initialTimeOfSLM = getUserData('initialTimeOfSLM'); timeNow=etime(clock(),initialTimeOfSLM); slm=getUserData('slm'); % Set the stabilization time temporarily to zero because for this % situation we do not care if the camera is out-of-sync. origStabilizationTime=slm.stabilizationTime; slm.stabilizationTime=0; slm.modulate(@(X,Y) pupilFunction(X,Y,timeNow) ); slm.stabilizationTime=origStabilizationTime; setUserData('lastPupilFunctionUpdate',timeNow); end function acquireAndDisplayLoop() while (~getUserData('isClosing') && getUserData('recording')), acquireAndDisplay(); % pause(0.05); end end function acquireAndDisplay() %Update the SLM if the pupil function is time dependent if (~getUserData('probing')) updatePupilModulationOnSLM(); end camAx=getUserData('cameraAxes'); xLim=get(camAx,'XLim'); yLim=get(camAx,'YLim'); newROI=round([yLim(1) xLim(1) diff(yLim) diff(xLim)]); %Acquire a new image cam=getUserData('cam'); updateCamROI(newROI); img=cam.acquire(); %Draw image displayOnMonitor(img); end %Draw image function displayOnMonitor(img) cam=getUserData('cam'); %Check if anybody just changed the camera if (any(size(img,1)>cam.regionOfInterest(3:4))) img=zeros(cam.regionOfInterest(3:4)); end if (~isempty(cam.background)) nonSaturatedPixels=img+repmat(cam.background,[1 1 1 size(img,4)])<1; else nonSaturatedPixels=img<1; end normalizedImg=img; if (all(nonSaturatedPixels(:))) maxLevel=max(img(:)); normalizedImg=img/maxLevel; %Normalize image intensity to maximum else maxLevel=1; end normalizedImg=uint8(normalizedImg*256); %map to [0:255] interval %Mark saturated pixels as red colorImg=repmat(normalizedImg.*uint8(nonSaturatedPixels),[1 1 3]); % Only copy the non-saturated, leaving other pixels black colorImg(~nonSaturatedPixels)=255; %Mark as red when completeImage=zeros([cam.maxSize 3],'uint8'); try completeImage(cam.regionOfInterest(1)+[1:cam.regionOfInterest(3)],cam.regionOfInterest(2)+[1:cam.regionOfInterest(4)],:)=colorImg; catch Exc Exc cam cam.regionOfInterest size(completeImage) size(colorImg) rethrow(Exc); end camAx=getUserData('cameraAxes'); imgHandle=get(camAx,'Children'); while(~ishandle(imgHandle(end)) || ~strcmp(get(imgHandle(end),'Type'),'image')) imgHandle=imgHandle(1:end-1); %Remove elements that dragzoom added to it end imgHandle=imgHandle(end); set(imgHandle,'EraseMode','none'); set(imgHandle,'CData',completeImage); %Plot histogram histAx=getUserData('histogramAxes'); nbGrayLevelsForHistogram=256; if (numel(img)>1) relPixelCountsPerGrayLevel=histc(img(:),[0:nbGrayLevelsForHistogram]/nbGrayLevelsForHistogram)./numel(img); relPixelCountsPerGrayLevel(end-1)=relPixelCountsPerGrayLevel(end-1)+relPixelCountsPerGrayLevel(end); %The last bin has the border cases of value == 1.0 relPixelCountsPerGrayLevel=relPixelCountsPerGrayLevel(1:end-1).'; % Remove last bin after copying in penultimate else relPixelCountsPerGrayLevel=zeros(1,256); relPixelCountsPerGrayLevel(max(end,1+round([0:nbGrayLevelsForHistogram]/nbGrayLevelsForHistogram)))=1; end cla(histAx); patch(repmat([0.5:nbGrayLevelsForHistogram]/nbGrayLevelsForHistogram,[4 1])+repmat([-1 -1 1 1].'*.5/nbGrayLevelsForHistogram,[1 nbGrayLevelsForHistogram]),[0 1 1 0].'*relPixelCountsPerGrayLevel,[0:nbGrayLevelsForHistogram-1],'LineStyle','none','Parent',histAx); hold(histAx,'on'); plot((maxLevel+0.01)*[1; 1],[0; 1],'-','Color',[.8 .8 .8],'LineWidth',3,'Parent',histAx); yLims=[0 max(1e-4,10^ceil(log10(2*max(relPixelCountsPerGrayLevel(2:end-1)))))]; set(histAx,'YLim',yLims); set(histAx,'YTick',[0 yLims(2)/2 yLims(2)],'YTickLabel',{'0',formatNumberForTickLabel(100*yLims(2)/2,100*yLims(2)/2),formatNumberForTickLabel(100*yLims(2),100*yLims(2)/2)}); hold(histAx,'off'); colorMap=gray(256); colorMap(end,2:3)=0; %Add red marker for saturation colormap(histAx,colorMap); set(histAx,'Color',[0 .333 1]); %Show the frame rate initialTimeOfGUI=getUserData('initialTimeOfGUI'); frameUpdateTimes=getUserData('frameUpdateTimes'); frameUpdateTimes=[frameUpdateTimes(2:end) etime(clock(),initialTimeOfGUI)]; setUserData('frameUpdateTimes',frameUpdateTimes); relativeTimes=frameUpdateTimes-frameUpdateTimes(end); weights=exp(relativeTimes); averageFrameUpdateTime=[0 diff(relativeTimes(~isnan(relativeTimes)))]*weights(~isnan(relativeTimes)).'/sum(weights(~isnan(relativeTimes))); title(camAx,sprintf('%0.2f fps',1/averageFrameUpdateTime),'FontName','Arial','FontWeight','bold','FontSize',16); drawnow(); end function shutDown() %Keep the current window position get(getBaseFigureHandle(),'Position'); updateStatus('mainWindowPosition',get(getBaseFigureHandle(),'Position')); %Clean up before exit cam=getUserData('cam'); cam.delete(); % slmAxes=getUserData('slmAxes'); % if (ishandle(slmAxes)) % slmFigure=get(slmAxes,'Parent'); % updateStatus('slmFigurePosition',get(slmFigure,'Position')); % close(slmFigure); % else % getUserData('fullScreenManager').delete(); % end closereq(); end %% Callbacks function adjustIntegrationTime(obj,event) if (nargin<1) obj=getUserData('integrationTimeEdit'); end newIntegrationTime=str2num(get(obj,'String'))*1e-3; if (~isempty(newIntegrationTime)) newIntegrationTime=newIntegrationTime(1); end if (isnumeric(newIntegrationTime) && ~isnan(newIntegrationTime)) newIntegrationTime=abs(newIntegrationTime); cam=getUserData('cam'); cam.integrationTime=newIntegrationTime; setUserData('cam',cam); set(obj,'String',sprintf('%g',cam.integrationTime*1e3)); end updateStatus('integrationTime',get(obj,'String')); end function adjustGain(obj,event) if (nargin<1) obj=getUserData('gainEdit'); end newGain=str2num(get(obj,'String')); if (isnumeric(newGain) && ~isnan(newGain)) newGain=abs(newGain(1)); cam=getUserData('cam'); cam.gain=newGain; setUserData('cam',cam); set(obj,'String',sprintf('%g',cam.gain)); end updateStatus('gain',get(obj,'String')); end function adjustNumberOfFrames(obj,event) if (nargin<1) obj=getUserData('numberOfFramesEdit'); end newNumberOfFrames=str2num(get(obj,'String')); if (isnumeric(newNumberOfFrames) && ~isnan(newNumberOfFrames)) newIntegrationTime=max(1,round(newNumberOfFrames(1))); cam=getUserData('cam'); cam.numberOfFramesToAverage=newNumberOfFrames; setUserData('cam',cam); end updateStatus('numberOfFrames',get(obj,'String')); end function updateDarkImage(obj,event) cam=getUserData('cam'); if (get(obj,'Value')>0) logMessage('Updating dark image...'); cam=cam.acquireBackground(); else logMessage('Not using dark image.'); cam.background=[]; end setUserData('cam',cam); end function pausePlay(obj,event) if (nargin<1) obj=getUserData('pausePlayButton'); end recording=~getUserData('recording'); setUserData('recording',recording); pausePlayButton=getUserData('pausePlayButton'); set(pausePlayButton,'Value',recording); setUserData('pausePlayButton',pausePlayButton); switch(recording) case true set(obj,'String','||'); case false set(obj,'String','>>'); end if (recording && ~getUserData('probing')) acquireAndDisplayLoop(); end if (getUserData('isClosing')) shutDown(); end end % function adjustGain(obj,event) % if (nargin<1) % obj=getUserData('gainEdit'); % end % newGain=str2num(get(obj,'String')); % if (isnumeric(newGain) && ~isnan(newGain)) % newGain=round(abs(newGain(1))); % cam=getUserData('cam'); % cam.gain=newGain; % setUserData('cam',cam); % end % end function changeCam(obj,event) selectedCamIdx=get(obj,'Value'); detectedCameras=getUserData('detectedCameras'); if (selectedCamIdx<1 || selectedCamIdx>length(detectedCameras)) selectedCamIdx=1; end selectedCamera=detectedCameras(selectedCamIdx); try switch(selectedCamera.type), case 'BaslerGigE' %Basler GigE cam=BaslerGigECam(selectedCamera.index); case 'Andor' %Andor logMessage('Andor camera not implemented'); case 'ImagingSource' %Imaging Source cam=ImagingSourceCam(selectedCamera.index); case 'DirectShow' %Direct Show cam=DirectShowCam(selectedCamera.index); case 'PikeCam' %Pike Show % cam=PikeCam(selectedCamera.index); case 'OrcaFlash4' %Pike Show cam=OrcaFlash4Cam(selectedCamera.index); otherwise %DummyCam switch (selectedCamera.index) case 2 imgSize=[480 640]; otherwise imgSize=[1 1]*256; end cam=DummyCam(imgSize); cam.acquireDirectFunctor=@(cam,nbFrames) calcDummyImage(imgSize,cam,nbFrames); end setUserData('cam',cam); updateStatus('cam',get(obj,'Value')); updateStatus('defaultCameraType',selectedCamera.type); updateStatus('defaultCameraIndex',selectedCamera.index); cameraAxes=getUserData('cameraAxes'); % dragzoom(cameraAxes,'off'); adjustNumberOfFrames(); initializeCamROIAndAxes(); dragzoom(cameraAxes); % Update the default FOV adjustIntegrationTime(); catch Exc logMessage(strcat('Could not initialize camera: ',selectedCamera.description,', falling back to Dummy Cam...')); set(obj,'Value',1); changeCam(obj,event); end end function updateCamROI(newROI) cam=getUserData('cam'); %Clip the new region of interest newROI(3:4)=max(min(newROI(3:4),cam.maxSize),1); newROI(1:2)=min(max(0,newROI(1:2)),cam.maxSize-newROI(3:4)); if (~all(getUserData('camRequestedRegionOfInterest')==newROI)) cam.regionOfInterest=newROI; setUserData('cam',cam); setUserData('camRequestedRegionOfInterest',newROI); end end function initializeCamROIAndAxes() cam=getUserData('cam'); roi=[0 0 cam.maxSize]; updateCamROI(roi); roiSize = roi(3:4); ax = getUserData('cameraAxes'); hImage = image(roiSize,'Parent',ax); axis(ax,'equal'); set(ax,'XLim',[0 roiSize(2)],'YLim',[0 roiSize(1)]); end %% Light Source callbacks function changeLightSource(obj,event) if (nargin<1 || isempty(obj)) obj=getUserData('changeLightSourcePopUpMenu'); end if (nargin<2 || isempty(event)) event=[]; end delete(getUserData('lightSource')); % Stop the previous light source selectedLightSourceIdx=get(obj,'Value'); detectedLightSources=getUserData('detectedLightSources'); if (isempty(selectedLightSourceIdx) || selectedLightSourceIdx<1 || selectedLightSourceIdx>length(detectedLightSources)) selectedLightSourceIdx=1; end selectedLightSource=detectedLightSources(selectedLightSourceIdx); try switch(selectedLightSource.type), case 'SuperK' lightSource=SuperK(); otherwise %none lightSource=[]; end setUserData('lightSource',lightSource); updateStatus('lightSource',get(obj,'Value')); updateStatus('defaultLightSourceType',selectedLightSource.type); adjustTargetPower(); adjustWavelengths(); catch Exc logMessage(strcat('Could not initialize light source: ',selectedLightSource.description,', using none...')); set(obj,'Value',1); changeLightSource(obj,event); end end function adjustTargetPower(obj,event) lightSource=getUserData('lightSource'); if (~isempty(lightSource)) targetPower=str2double(get(getUserData('targetPowerEdit'),'String')); if (isempty(targetPower)) targetPower=0; end updateStatus('targetPower',sprintf('%d',targetPower)); targetPower=targetPower/100; lightSource.targetPower=targetPower; end end function adjustWavelengths(obj,event) wavelengths=str2num(get(getUserData('wavelengthsEdit'),'String')); if (isempty(wavelengths)) wavelengths=[]; end updateStatus('wavelengths',get(getUserData('wavelengthsEdit'),'String')); wavelengths=wavelengths*1e-9; lightSource=getUserData('lightSource'); if (~isempty(lightSource)) lightSource.setWavelengths(wavelengths); end if (~isempty(wavelengths)) sourceWavelengthForDeflectionCorrection=median(wavelengths); else sourceWavelengthForDeflectionCorrection=[]; end setUserData('sourceWavelengthForDeflectionCorrection',sourceWavelengthForDeflectionCorrection); adjustBaseWavelength(); end function adjustBaseWavelength(obj,event) baseWavelength=str2double(get(getUserData('baseWavelengthEdit'),'String')); if (isempty(baseWavelength)) baseWavelength=[]; end updateStatus('baseWavelength',baseWavelength); baseWavelength=baseWavelength*1e-9; setUserData('baseWavelength',baseWavelength); adjustDeflection(); end %% SLM callbacks function adjustDeflection(obj,event) if (nargin<1) obj=getUserData('deflectionEdit'); end newDeflection=str2num(get(obj,'String')); if (isnumeric(newDeflection) && ~any(isnan(newDeflection))) if (length(newDeflection)<2) logMessage('The deflection frequency should be two or three scalars, assuming diagonal deflection.'); newDeflection(2)=newDeflection(1); end if (length(newDeflection)<3) newDeflection(3)=0; end if (length(newDeflection)>3) logMessage('The deflection frequency should be maximum 3 scalars.'); newDeflection=newDeflection(1:3); end baseWavelength=getUserData('baseWavelength'); sourceWavelengthForDeflectionCorrection=getUserData('sourceWavelengthForDeflectionCorrection'); if (~isempty(baseWavelength) && ~isempty(sourceWavelengthForDeflectionCorrection)) wavelengthDeflectionCorrection=baseWavelength/sourceWavelengthForDeflectionCorrection; else wavelengthDeflectionCorrection=1; end slm=getUserData('slm'); slm.referenceDeflectionFrequency=newDeflection([2 1 3])*wavelengthDeflectionCorrection; setUserData('slm',slm); updateSLMDisplayAndOutput(); updateStatus('deflection',get(obj,'String')); end end function adjustTwoPiEquivalent(obj,event) if (nargin<1) obj=getUserData('twoPiEquivalentEdit'); end newTwoPiEquivalent=str2num(get(obj,'String')); if (isnumeric(newTwoPiEquivalent) && ~any(isnan(newTwoPiEquivalent))) newTwoPiEquivalent=newTwoPiEquivalent(1)/100; slm=getUserData('slm'); slm.twoPiEquivalent=newTwoPiEquivalent; setUserData('slm',slm); updateSLMDisplayAndOutput(); updateStatus('twoPiEquivalent',get(obj,'String')); end end function adjustCorrection(obj,event) if (nargin<1) obj=getUserData('correctionEdit'); end correctionFunctionFileName=strtrim(get(obj,'String')); slm=getUserData('slm'); if (~isempty(correctionFunctionFileName)) if (~strcmp(correctionFunctionFileName(end-3:end),'.mat')) correctionFunctionFileName=strcat(correctionFunctionFileName,'.mat'); end try correctionFileContents=whos('-file',correctionFunctionFileName); correctionFileContents={correctionFileContents.name}; % Configure the region of interest of the SLM as given in the correction archive if (any(strcmp(correctionFileContents,'slmRegionOfInterest'))) load(correctionFunctionFileName,'slmRegionOfInterest'); slm.regionOfInterest=slmRegionOfInterest; else logMessage('slmRegionOfInterest variable not found in the correction file %s, leaving the region-of-interest unchanged.',correctionFunctionFileName); end % If the amplification limit is specified in the archive, % recalculate the correction if the original info is known. amplificationLimit=getStatus('amplificationLimit'); if (isempty(amplificationLimit) && any(strcmp(correctionFileContents,'measuredPupilFunction'))) load(correctionFunctionFileName,'amplificationLimit'); % Update the GUI with the amplification limit read from file updateStatus('amplificationLimit',amplificationLimit); setUserData('amplificationLimitEdit',num2str(amplificationLimit)); end if (~isempty(amplificationLimit) && any(strcmp(correctionFileContents,'measuredPupilFunction'))) load(correctionFunctionFileName,'measuredPupilFunction'); if (any(strcmp(correctionFileContents,'initialCorrection'))) load(correctionFunctionFileName,'initialCorrection'); else initialCorrection=1; end slm.correctionFunction=calcCorrectionFromPupilFunction(measuredPupilFunction./initialCorrection,amplificationLimit); logMessage('Correction function updated using amplification limit %d.',amplificationLimit); else logMessage('No amplification limit specified, using the correction as specified in the file %s.',correctionFunctionFileName); load(correctionFunctionFileName,'pupilFunctionCorrection'); slm.correctionFunction=pupilFunctionCorrection; end catch Exc logMessage('Couldn''t load %s file, not a valid Matlab archive.',correctionFunctionFileName); end else slm.correctionFunction=1; slm.regionOfInterest=[]; logMessage('No correction loaded.'); end setUserData('slm',slm); updateStatus('correction',correctionFunctionFileName); refreshPupilModulationOnSLM(); end function loadCorrection(obj,event) correctionEdit=getUserData('correctionEdit'); [fileName,pathName,filterIndex] = uigetfile({'*.mat'},'Select Correction Function','pupilFunctionCorrection.mat'); if (~isempty(fileName)) set(correctionEdit,'String',strcat(pathName,fileName)); end adjustCorrection(); end function selectOutputFile(obj,event) outputFileEdit=getUserData('outputFileEdit'); % Suggest a non-existing file name defaultFileName='recording.avi'; if (exist(defaultFileName,'file')) idx=2; while (exist(strcat(defaultFileName,'_',num2str(idx)),'file')) idx=idx+1; end defaultFileName=strcat(defaultFileName,'_',idx); end [fileName,pathName,filterIndex] = uiputfile({'*.mat';'*.avi';'*.png';'*.tif';'*.jpg'},'Save as...',defaultFileName); if (~isempty(fileName)) set(outputFileEdit,'String',strcat(pathName,fileName)); end end function updateProbeSize(obj,event) if (nargin<1) obj=getUserData('probeSizeEdit'); end probeSize=str2num(get(obj,'String')).'; probeSize=probeSize(1:min(2,end)); if isempty(probeSize) || any(isnan(probeSize)) probeSize=1; end probeSize=max(1,round(probeSize)); if (length(probeSize)<2) probeSize(2)=probeSize(1); end updateStatus('probeSize',probeSize); set(obj,'String',sprintf('%d ',probeSize)); setUserData('probeSize',probeSize); end function updateAmplificationLimit(obj,event) if (nargin<1) obj=getUserData('amplificationLimitEdit'); end amplificationLimit=str2num(get(obj,'String')); if (length(amplificationLimit)>1) amplificationLimit=amplificationLimit(1); end if (~isempty(amplificationLimit) && isnan(amplificationLimit)) amplificationLimit=[]; end amplificationLimit=max(1,amplificationLimit); updateStatus('amplificationLimit',amplificationLimit); setUserData('amplificationLimitEdit',num2str(amplificationLimit)); % If a correction is already selected, update the correction pattern using the new amplification limit. adjustCorrection(); end function updateSLMDisplayNumberOrSLM(obj,event) slm=getUserData('slm'); if (~isempty(slm)) delete(slm); % Close any current SLM windows end slmDisplayNumberPopUpMenu=getUserData('slmDisplayNumberPopUpMenu'); slmDisplayNumber=get(slmDisplayNumberPopUpMenu,'Value'); descriptors=get(slmDisplayNumberPopUpMenu,'String'); if (slmDisplayNumber<1 || slmDisplayNumber>length(descriptors)) slmDisplayNumber=1; end if (strcmpi(descriptors{slmDisplayNumber},'popup')) slmAxes=getUserData('slmAxes'); if (isempty(slmAxes) || ~ishandle(slmAxes)) mainFigHandle=getBaseFigureHandle(); slmFigure=figure('Name','Dummy SLM','NumberTitle','off','UserData',struct('mainFigure',mainFigHandle)); %Make sure that we still know where the userData is kept slmAxes=axes('Parent',slmFigure); set(slmFigure,'Position',getStatus('slmFigurePosition',[0 0 200 150]),'Resize','on','ResizeFcn',@(obj,event) updateStatus('slmFigurePosition',get(obj,'Position'))); setUserData('slmAxes',slmAxes); end img=image(zeros(300/2,400/2,3),'Parent',slmAxes); slmDisplayNumber=get(img,'Parent'); else if (strcmpi(descriptors{slmDisplayNumber},'popup XL')) slmAxes=getUserData('slmAxes'); close(get(slmAxes,'Parent')); slmAxes=[]; if (isempty(slmAxes) || ~ishandle(slmAxes)) mainFigHandle=getBaseFigureHandle(); slmFigure=figure('Name','Dummy SLM XL','NumberTitle','off','UserData',struct('mainFigure',mainFigHandle)); %Make sure that we still know where the userData is kept slmAxes=axes('Parent',slmFigure); set(slmFigure,'Position',getStatus('slmFigurePosition',[0 0 200 150]),'Resize','on','ResizeFcn',@(obj,event) updateStatus('slmFigurePosition',get(obj,'Position'))); setUserData('slmAxes',slmAxes); end img=image(zeros(300,400,3),'Parent',slmAxes); slmDisplayNumber=get(img,'Parent'); else slmDisplayNumber=sscanf(descriptors{slmDisplayNumber},'%u'); % A full-screen, not a pop-up end end setUserData('slmDisplayNumber',slmDisplayNumber); populateSLMDisplayNumberPopupMenu(); %Update the list in case more were connected if (~isempty(slm)) changeSLM(); end updateStatus('slmDisplayNumber',get(slmDisplayNumberPopUpMenu,'Value')); end function populateSLMDisplayNumberPopupMenu(slmDisplayNumberPopUpMenu) if (nargin<1) slmDisplayNumberPopUpMenu=getUserData('slmDisplayNumberPopUpMenu'); end % Find out the number of displays and some properties fullScreenManager=getUserData('fullScreenManager'); optionsList={'popup',fullScreenManager.screens.description}; %,'popup XL' set(slmDisplayNumberPopUpMenu,'String',optionsList); setUserData('slmDisplayNumberPopUpMenu',slmDisplayNumberPopUpMenu); end function changeSLM(obj,event) if (nargin<1) obj=getUserData('changeSLMPopUpMenu'); end slmDisplayNumber=getUserData('slmDisplayNumber'); % slmAxes=getUserData('slmAxes'); % if (~isempty(slmAxes) && slmDisplayNumber~=slmAxes && ishandle(slmAxes)) % slmFigure=get(slmAxes,'Parent'); % updateStatus('slmFigurePosition',get(slmFigure,'Position')); % close(slmFigure); % setUserData('slmAxes',[]); % else % getUserData('fullScreenManager').close('all'); % end slmTypeIndex=get(obj,'Value'); switch (slmTypeIndex) case 1 slm=PhaseSLM(slmDisplayNumber); case 2 slm=DualHeadSLM(slmDisplayNumber); otherwise slm=BNSPhaseSLM(); end updateStatus('slmTypeIndex',slmTypeIndex); if (ishandle(slmDisplayNumber) && strcmpi(get(slmDisplayNumber,'Type'),'axes')) slm.stabilizationTime=0.01; % For testing with the popup SLM else slm.stabilizationTime=0.10; end % Adapt the SLM so we can know what it is doing when using the DummyCam slm.modulatePostFunctor=@(complexModulation,currentImageOnSLM) setUserData('currentImageOnSLM',currentImageOnSLM); setUserData('slm',slm); adjustDeflection(); adjustTwoPiEquivalent(); adjustCorrection(); updateSLMDisplayAndOutput(); end % Called by the pupil function text input function updateSLMDisplayAndOutput(obj,event) slm=getUserData('slm'); maskEdit=getUserData('maskEdit'); pupilEquation=get(maskEdit,'String'); [pupilEquationFunctor argumentsUsed]=parsePupilEquation(pupilEquation); setUserData('pupilFunction',pupilEquationFunctor); setUserData('pupilFunctionTimeDependent',argumentsUsed(3)) setUserData('lastPupilFunctionUpdate',-1); setUserData('initialTimeOfSLM',clock()); %Reset clock updateStatus('mask',get(maskEdit,'String')); end % Called by the buttons function filledInString = insertPupilRadiusAndUpdateSLM(stringWithPupilRadius) slm=getUserData('slm'); pupilRadius=min(slm.regionOfInterest(3:4))/2; filledInString=regexprep(stringWithPupilRadius,'(pupil|max)R(ad(ius)?)?',sprintf('%0.0f',pupilRadius)); maskEdit=getUserData('maskEdit'); set(maskEdit,'String',filledInString); setUserData('maskEdit',maskEdit); updateSLMDisplayAndOutput(); end function img=calcDummyImage(imgSize,cam,nbFrames) wellDepth=40e3; darkPhotonElectrons=10; photoElectronsPerGraylevel=wellDepth/(2^cam.bitsPerPixel); slm=getUserData('slm'); if (isempty(getUserData('currentImageOnSLM'))) pupilFunction=getUserData('pupilFunction'); lastPupilFunctionUpdate=getUserData('lastPupilFunctionUpdate'); [X,Y]=ndgrid([1:slm.regionOfInterest(3)]-floor(slm.regionOfInterest(3)/2)-1,[1:slm.regionOfInterest(4)]-floor(slm.regionOfInterest(4)/2)-1); pupil=pupilFunction(Y,X,lastPupilFunctionUpdate); pupil=pupil.*slm.referenceDeflection.*slm.correctionFunction; else currentImageOnSLM=getUserData('currentImageOnSLM'); pupil=currentImageOnSLM(:,:,3).*exp(2i*pi*currentImageOnSLM(:,:,2)); %Should work for both phase and amplitude SLMs end % if the SLM ROI is really small: if (any(size(pupil)<[256 256])) %pupil=pupil(floor(1:.5:(end+.5)),floor(1:.5:(end+.5))); %assume square pixels and interpolate pupil(256,256)=0; % assume dark outside end %Resize to the imgSize if (any(imgSize>size(pupil))) pupil(imgSize(1),imgSize(2))=0; end %Suppose the camera pixels are square, then the pupil must be square if (size(pupil,1)<size(pupil,2)) pupil(size(pupil,2),1)=0; elseif (size(pupil,2)<size(pupil,1)) pupil(1,size(pupil,1))=0; end % Calculate the simulated image with a Fourier transform frm=sqrt(prod(slm.regionOfInterest(3:4)))*abs(fftshift(ifft2(ifftshift(pupil(end:-1:1,end:-1:1)))).^2); %Crop if bigger than imgSize frm=frm(floor((size(frm,1)-imgSize(1))/2)+[1:imgSize(1)],floor((size(frm,2)-imgSize(2))/2)+[1:imgSize(2)]); %Pad if ROI larger than the calculated frame sizeDifference=cam.regionOfInterest(3:4)-size(pupil); if (any(sizeDifference>0)) frm(cam.regionOfInterest(3),cam.regionOfInterest(4))=0; frm=circshift(frm,floor(max(0,1+sizeDifference)./2)); end % Restrict to ROI frm=frm(cam.regionOfInterest(1)+[1:cam.regionOfInterest(3)],cam.regionOfInterest(2)+[1:cam.regionOfInterest(4)],:); outputSize=[size(frm,1) size(frm,2) size(frm,3) nbFrames]; img=zeros(outputSize); for frameIdx=1:nbFrames, %Simulate noise frm=frm*wellDepth; %Convert to photo electrons frm=frm+darkPhotonElectrons; %Add dark noise integrationTimeUnits=cam.numberOfFramesToAverage*cam.integrationTime/20e-3; %Assume that the laser power is adjusted for an integration time of 20ms frm=frm*integrationTimeUnits; frm=frm+sqrt(frm).*randn(size(frm)); frm=frm*cam.gain; frm=floor(frm/photoElectronsPerGraylevel); img(:,:,:,frameIdx)=frm/cam.numberOfFramesToAverage; end %Normalize the maximum graylevel to 1 img=min(1,img./(2^cam.bitsPerPixel-1)); end function closeApp(obj,event) setUserData('isClosing',true); if (~getUserData('recording')) shutDown(); end %else wait for the loop to exit and clean itself up end % % Data access functions % % % User data function are 'global' variables linked to this GUI, though not % persistent between program shutdowns. % function value=getUserData(fieldName) fig=getBaseFigureHandle(); userData=get(fig,'UserData'); value=userData.(fieldName); end function setUserData(fieldName,value) if (nargin<2) value=fieldName; fieldName=inputname(1); end fig=getBaseFigureHandle(); userData=get(fig,'UserData'); userData.(fieldName)=value; set(fig,'UserData',userData); end function fig=getBaseFigureHandle() fig=gcbf(); if (isempty(fig)) fig=gcf; end userData=get(fig,'UserData'); if (isfield(userData,'mainFigure')) fig=userData.mainFigure; end end % % 'Status' variables are stored persistently to disk and reloaded next time % function loadStatus() fullPath=mfilename('fullpath'); try load(strcat(fullPath,'.mat'),'status'); catch Exc end if (~exist('status','var')) status={}; status.version=-1; end setUserData('status',status); end function value=getStatus(fieldName,defaultValue) status=getUserData('status'); if (isfield(status,fieldName)) value=status.(fieldName); else if (nargin<2) defaultValue=[]; end value=defaultValue; end end function updateStatus(fieldName,value) status=getUserData('status'); status.(fieldName)=value; setUserData('status',status); saveStatus(); end function saveStatus() status=getUserData('status'); fullPath=mfilename('fullpath'); save(strcat(fullPath,'.mat'),'status'); end function estimateCorrection(obj,event) oldValue=get(obj,'String'); set(obj,'String','Stop!'); % Locally defined functions to be passed into the aberration correction algorithm amplificationLimit=getStatus('amplificationLimit'); cam=getUserData('cam'); slm=getUserData('slm'); if (~getUserData('probing')) [cam centerPos]=selectRegionOfInterestAroundPeakIntensity(cam,slm,min(cam.regionOfInterest(3:4),[1 1]*32),[]); else centerPos=[]; % We are going to stop the probing set(obj,'String','Wait....'); end camRegionOfInterest=cam.regionOfInterest; function value=probeFunctor() %combinedDeflection) probeSize=getUserData('probeSize'); %Make sure that nobody changes the region of interest of the camera! if (any(cam.regionOfInterest~=camRegionOfInterest)) cam.regionOfInterest=camRegionOfInterest; end img=cam.acquire(2); img=img(:,:,1,2); % Drop the transient frame if (size(img,1)<probeSize(1)) img(probeSize(1),:)=mean(img,1); end if (size(img,2)<probeSize(2)) img(:,probeSize(2))=mean(img,2); end vals=img(centerPos(1)-cam.regionOfInterest(1)+[-floor(probeSize(1)/2):floor((probeSize(1)-1)/2)],centerPos(2)-cam.regionOfInterest(2)+[-floor(probeSize(1)/2):floor((probeSize(1)-1)/2)]); value=mean(vals(:)); end prevFractionDone=0; function cont=progressFunctor(fractionDone,currentPupilFunctionEstimate) cont=true; if (floor(fractionDone*100)>floor(prevFractionDone*100)) logMessage('%0.0f%% done.',100*fractionDone); prevFractionDone=fractionDone; currentCorrectionEstimate=calcCorrectionFromPupilFunction(currentPupilFunctionEstimate,amplificationLimit); slm.modulate(currentCorrectionEstimate); showImage(currentPupilFunctionEstimate+.00001i,-1,[],[],getUserData('pupilAxes')); if (getUserData('recording')) acquireAndDisplay(); end if (getUserData('isClosing') || getUserData('probingInterupted')) cont=false; end end end if (~getUserData('probing')) setUserData('probingInterupted',false); setUserData('probing',true); % % Determine the file where to store the data % correctionEdit=getUserData('correctionEdit'); calibrationFileName=get(correctionEdit,'String'); if (isempty(strtrim(calibrationFileName))) calibrationFileName=fullfile(pwd(),['calibrateSetup_',datestr(now(),'YYYY-mm-DD'),'.mat']); set(correctionEdit,'String',calibrationFileName); end % % Determine the aberration and the correction % slm=getUserData('slm'); code=get(getUserData('probeMethodToggle'),'String'); code=upper(code(1)); switch(code) case 'C' probeGridSize=[12 16 8]; % [15 20 8] logMessage('Using Tom Cizmar''s aberration measurement method with %dx%d probes and %d phases.\nThe region of interest of the spatial light modulator is %dx%d and the probe size is %dx%d.',[probeGridSize, slm.regionOfInterest(3:4) floor(slm.regionOfInterest(3:4)./probeGridSize(1:2))]); measuredPupilFunction=aberrationMeasurementCizmarMethod(slm,probeGridSize,@probeFunctor,@progressFunctor); case 'Z' zernikeCoefficientIndexes=[2 3 4 5 6 7 8 9 10 11]; logMessage('Using Zernike wavefront measurement method with %d coefficients.',[size(zernikeCoefficientIndexes,2)]); measuredPupilFunction=aberrationMeasurementZernikeWavefront(slm,zernikeCoefficientIndexes,@probeFunctor,@progressFunctor); otherwise probeGridSize=[25 25 3];% probeGridSize=[25 25 3]; %probeGridSize=[12 12 3]; %test with smaller grid size; Mingzhou logMessage('Using Michael Mazilu''s aberration measurement method with a maximum of %dx%d probes and %d phases.',probeGridSize); measuredPupilFunction=aberrationMeasurement(slm,probeGridSize,@probeFunctor,@progressFunctor); end logMessage('Calculating correction function for a maximum amplitude reduction of %0.3f.',amplificationLimit); initialCorrection=slm.correctionFunction; pupilFunctionCorrection=calcCorrectionFromPupilFunction(measuredPupilFunction.*conj(initialCorrection),amplificationLimit); % % Store % %Additional information to be stored in the aberration measurement file referenceDeflectionFrequency=slm.referenceDeflectionFrequency; slmRegionOfInterest=slm.regionOfInterest; twoPiEquivalent=slm.twoPiEquivalent; save(calibrationFileName,'referenceDeflectionFrequency','slmRegionOfInterest','twoPiEquivalent','initialCorrection','measuredPupilFunction','pupilFunctionCorrection','amplificationLimit','centerPos'); set(obj,'String',oldValue); setUserData('probing',false); adjustCorrection(); else setUserData('probingInterupted',true); end end function toggleProbeMethod(obj,event) toggleButton=getUserData('probeMethodToggle'); code=get(toggleButton,'String'); code=upper(code(1)); switch(code) case 'C' set(toggleButton,'String','Z'); case 'Z' set(toggleButton,'String','M'); otherwise set(toggleButton,'String','C'); end setUserData('probeMethodToggle',toggleButton); updateStatus('probeMethodToggle',get(toggleButton,'String')); end function estimateTwoPiEquivalentCallback(obj,event) % function cont=progressFunctor(fractionDone,img) % cont=true; % logMessage('%0.1f%% done.',100*fractionDone); % if (floor(fractionDone*100)~=floor((fractionDone*100-1))) % if (getUserData('recording')) % displayOnMonitor(img); % if (getUserData('isClosing')) % cont=false; % end % end % end % end if (~getUserData('probing')) setUserData('probing',true); % % Determine the file where to store the data % correctionEdit=getUserData('correctionEdit'); calibrationFileName=get(correctionEdit,'String'); if (isempty(strtrim(calibrationFileName))) calibrationFileName=fullfile(pwd(),['calibrateSetup_',datestr(now(),'YYYY-mm-DD'),'.mat']); set(correctionEdit,'String',calibrationFileName); end % % Determine the two-pi-phase equivalent % cam=getUserData('cam'); slm=getUserData('slm'); [cam centerPos]=selectRegionOfInterestAroundPeakIntensity(cam,slm,min(cam.regionOfInterest(3:4),[1 1]*128),[]); try % Determine the phase shift with gray level %[phases,graylevels,values,slm,cam]=calibratePhase(slm,cam,@progressFunctor); [twoPiEquivalent slm]=estimateTwoPiEquivalent(slm,cam,centerPos,[1 1]*5); if (exist(calibrationFileName,'file')) save(calibrationFileName,'twoPiEquivalent','-append'); else save(calibrationFileName,'twoPiEquivalent'); end set(getUserData('twoPiEquivalentEdit'),'String',sprintf('%1.0f',twoPiEquivalent*100)); setUserData('slm',slm); setUserData('cam',cam); catch Exc % Probably user interupted, just stop end refreshPupilModulationOnSLM(); %Reset SLM setUserData('probing',false); else logMessage('Already probing, wait until correct measurement is done.'); end end function toggleOutputRecording(obj,event) outputFileEdit=getUserData('outputFileEdit'); outputFileName=get(outputFileEdit,'String'); outputFileName=strtrim(outputFileName); % Local function, only used to record movies to .mat files function appendFrame(img) recordingObj=getUserData('recordingObj'); if (~isempty(recordingObj)) recordingObj(:,:,end+1)=img; else recordingObj=img; end setUserData('recordingObj',recordingObj); end if (~isempty(outputFileName)) cam=getUserData('cam'); fileExtension=lower(outputFileName(end-3:end)); switch (fileExtension) case {'.mat','.avi'} if (get(obj,'Value')>0) logMessage('Starting recording...'); if (strcmp(fileExtension,'.avi')) try recordingObj = VideoWriter(outputFileName,'Uncompressed AVI'); %'Motion JPEG AVI'); %'Uncompressed AVI'); recordingObj.FrameRate=25; % recordingObj.Quality=75; open(recordingObj); cam.acquisitionFunctor=@(img) writeVideo(recordingObj,min(1,max(0,img))); catch Exc recordingObj = VideoWriter(outputFileName,'FrameRate',25); cam.acquisitionFunctor=@(img) addframe(recordingObj,min(1,max(0,img))); end else recordingObj=[]; cam.acquisitionFunctor=@appendFrame; end setUserData('recordingObj',recordingObj); else cam.acquisitionFunctor=[]; recordingObj=getUserData('recordingObj'); if (~isnumeric(recordingObj)) close(recordingObj); else save(outputFileName,'recordingObj'); end logMessage('Stopped the recording.'); end otherwise %Add an extension if not provided if (~strcmp(fileExtension,'.png') && ~strcmp(fileExtension,'.tif') && ~strcmp(fileExtension,'.bmp')) outputFileName=strcat(outputFileName,'.png'); end imwrite(min(1,max(0,cam.acquire())),outputFileName); logMessage('Took snapshot.'); set(obj,'Value',0); end setUserData('cam',cam); end end function cameras=detectCameras() cameras=[]; cameras(1).type='DummyCam'; cameras(1).index=1; cameras(1).description='Dummy Cam'; cameras(2).type='DummyCam'; cameras(2).index=2; cameras(2).description='Dummy Cam HD'; hwInfo=imaqhwinfo(); if (any(strcmpi(hwInfo.InstalledAdaptors,'gige'))) hwInfoGigE=imaqhwinfo('gige'); for (camIdx=1:length(hwInfoGigE.DeviceIDs)) cameras(end+1).type='BaslerGigE'; cameras(end).index=hwInfoGigE.DeviceIDs{camIdx}; cameras(end).description='Basler GigE'; if (length(hwInfoGigE.DeviceIDs)>1) cameras(end).description=strcat(cameras(end).description,sprintf(' %.0f',hwInfoGigE.DeviceIDs{camIdx})); end end end if (any(strcmpi(hwInfo.InstalledAdaptors,'andor'))) hwInfoAndor=imaqhwinfo('andor'); for (camIdx=1:length(hwInfoAndor.DeviceIDs)) cameras(end+1).type='Andor'; cameras(end).index=hwInfoAndor.DeviceIDs{camIdx}; cameras(end).description='Andor'; if (length(hwInfoGigE.DeviceIDs)>1) cameras(end).description=strcat(cameras(end).description,sprintf(' %.0f',hwInfoAndor.DeviceIDs{camIdx})); end end end if (any(strcmpi(hwInfo.InstalledAdaptors,'winvideo'))) hwInfoIC=imaqhwinfo('winvideo'); for (camIdx=1:length(hwInfoIC.DeviceIDs)) cameras(end+1).type='ImagingSource'; cameras(end).index=hwInfoIC.DeviceIDs{camIdx}; cameras(end).description='Imaging Source'; if (length(hwInfoIC.DeviceIDs)>1) cameras(end).description=strcat(cameras(end).description,sprintf(' %.0f',hwInfoIC.DeviceIDs{camIdx})); end end end if (any(strcmpi(hwInfo.InstalledAdaptors,'avtmatlabadaptor64_r2009b'))) hwInfoPC=imaqhwinfo('avtmatlabadaptor64_r2009b'); for (camIdx=1:length(hwInfoPC.DeviceIDs)) cameras(end+1).type='PikeCam'; cameras(end).index=hwInfoPC.DeviceIDs{camIdx}; cameras(end).description='PikeCam'; if (length(hwInfoPC.DeviceIDs)>1) cameras(end).description=strcat(cameras(end).description,sprintf(' %.0f',hwInfoPC.DeviceIDs{camIdx})); end end end if (any(strcmpi(hwInfo.InstalledAdaptors,'hamamatsu'))) hwInfoPC=imaqhwinfo('hamamatsu'); for (camIdx=1:length(hwInfoPC.DeviceIDs)) cameras(end+1).type='OrcaFlash4'; cameras(end).index=hwInfoPC.DeviceIDs{camIdx}; cameras(end).description='Orca Flash 4.0'; if (length(hwInfoPC.DeviceIDs)>1) cameras(end).description=strcat(cameras(end).description,sprintf(' %.0f',hwInfoPC.DeviceIDs{camIdx})); end end end if (exist('vcapg2')) numberOfCards=vcapg2(); for cardIdx=1:numberOfCards, cameras(end+1).type='DirectShow'; cameras(end).index=cardIdx; cameras(end).description='Win Direct Show'; if (numberOfCards>1) cameras(end).description=strcat(cameras(end).description,sprintf(' %.0f',cardIdx)); end end end end % TODO: Implement function detectedLightSources=detectLightSources() detectedLightSources=struct(); detectedLightSources.type='none'; detectedLightSources.description='none'; detectedLightSources(2).type='SuperK'; detectedLightSources(2).description='SuperK'; end function str=formatNumberForTickLabel(number,numberForPrec) digitsAfterDot=max(0,ceil(-log10(numberForPrec))); str=sprintf(sprintf('%%0.%if',digitsAfterDot),number); end
github
mc225/Softwares_Tom-master
waveMeter.m
.m
Softwares_Tom-master/GUI/waveMeter.m
13,654
utf_8
d7d127f122cec240fdea0a8a3cb990da
% A GUI to use speckle as a wavelength meter. % Load a mat file created by analyzeSpeckleImages, and select the camera in use from the menu. % function waveMeter(calibrationFileName) % Find the screen size and put the application window in the center set(0,'units','pixels'); screenSize=get(0,'screensize'); screenSize=screenSize([3 4]); windowSize=[600 145]; fig=figure('Units','pixels','Position',[floor(screenSize/2)-floor(windowSize/2) windowSize],'MenuBar','none','Color',[0 0 0],'NumberTitle','off','CloseRequestFcn',@exit); textDisplay=uicontrol('Parent',fig,'Style','text','Position',[25 25 550 95],'FontName','Arial','FontSize',64,'FontWeight','bold','BackgroundColor',[0 0 0]); setUserData('textDisplay',textDisplay); menuFile=uimenu(fig,'Label','File'); menuLoadCalibration=uimenu(menuFile,'Label','Load Calibration...','Callback',@selectAndLoadCalibration); menuExit=uimenu(menuFile,'Label','Exit','Callback',@exit); menuCam=uimenu(fig,'Label','Camera'); detectedCameras=detectCameras(); setUserData('detectedCameras',detectedCameras); for (camIdx=1:length(detectedCameras)) uimenu(menuCam,'Label',detectedCameras(camIdx).description,'Callback',@(obj,event) updateCam(detectedCameras(camIdx))); end menuSignal=uimenu(fig,'Label','Signal','Callback',@openSignalWindow); % Window intialized now loadStatus(); updateStatus('version',0.10); % Initial values setUserData('wavelengths',[]); setUserData('regionOfInterest',[]); setUserData('isClosing',false); setUserData('imageAxes',[]); setUserData('cam',[]); if (nargin<1 || isempty(calibrationFileName)) calibrationFileName=getStatus('calibrationFileName',[]); end updateStatus('calibrationFileName',calibrationFileName); % Hook up a camera selectedCamera={}; selectedCamera.type=getStatus('selectedCameraType',[]); selectedCamera.index=getStatus('selectedCameraIndex',[]); updateCam(selectedCamera); % Load the calibration file or ask the user loadCalibration(calibrationFileName); % Loop until stopped while (~getUserData('isClosing')), if (~isempty(getUserData('cam'))) updateDisplay(); drawnow(); else pause(.020); end end % Close any extra windows if needed closeSignalWindow(); %Shut the main window closereq(); end function setFigureTitle() wavelengths=getUserData('wavelengths'); if (~isempty(wavelengths)) precision=max(diff(wavelengths)); significantDigits=min(4,max(0,-log10(precision)-9)); significantDigitsPrecision=1; titleString=sprintf(sprintf('%%0.%0.0ff nm to %%0.%0.0ff nm, %%0.%0.0ff pm resolution',[[1 1]*significantDigits significantDigitsPrecision]),1e9*[min(wavelengths) max(wavelengths) 1e3*precision]); else titleString='no calibration data loaded'; end set(getBaseFigureHandle(),'NumberTitle','off','Name',strcat('waveMeter - ',titleString)); end function updateDisplay() textDisplay=getUserData('textDisplay'); [currentWavelength status]=determineWavelength(); switch (status) case 'signalTooLow' set(textDisplay,'ForegroundColor',[1 0 0],'String','LOW SIGNAL'); case 'signalTooHigh' set(textDisplay,'ForegroundColor',[.2 0.2 1],'String','TOO BRIGHT'); case 'outOfRange' set(textDisplay,'ForegroundColor',[.4 0.8 0.4],'String','OUT OF RANGE'); case 'noCalibrationLoaded' set(textDisplay,'ForegroundColor',[0 0.8 0],'String','NOT CALIB.'); otherwise set(textDisplay,'ForegroundColor',[1 1 1],'String',sprintf('%0.4f nm',currentWavelength*1e9)); end end function [wavelength status]=determineWavelength() shortestIntegrationTime=10e-6; longestIntegrationTime=.5; status=[]; %default wavelength=[]; %default % capture image cam=getUserData('cam'); img=cam.acquire(); while ((max(img(:))>=1 && cam.integrationTime>shortestIntegrationTime*2) || (max(img(:))<.5 && cam.integrationTime<longestIntegrationTime/2)) if (max(img(:))>=1) cam.integrationTime=cam.integrationTime/2; else cam.integrationTime=cam.integrationTime*2; end % cam.defaultNumberOfFramesToAverage=max(1,floor(.03/cam.integrationTime)); % logMessage('Integration time %f ms',cam.integrationTime*1e3); img=cam.acquire(); end setUserData('cam',cam); %Display output if required imageAxes=getUserData('imageAxes'); if (~isempty(imageAxes)) if (ishandle(imageAxes) && strcmpi(get(imageAxes,'BeingDeleted'),'off')) showImage(img,-1,[],[],imageAxes); else setUserData('imageAxes',[]); end end % Check the input if (max(img(:))>=1) status='signalTooHigh'; end if (max(img(:))<=.5) status='signalTooLow'; end wavelengths=getUserData('wavelengths'); if (isempty(wavelengths)) status='noCalibrationLoaded'; end if (isempty(status)) % no errors calibration=getUserData('calibration'); wavelength = determineWavelengthFromSpeckleImage(img,calibration); %TODO Check match error and output 'outOfRange' if needed status='ok'; % no errors end end function loadCalibration(fullFileName) try calibration=load(fullFileName); setUserData('calibration',calibration); cam=getUserData('cam'); if (~isempty(cam)) try cam.regionOfInterest=calibration.regionOfInterest; catch Exc logMessage('Region of interest invalid, please use the same camera!'); cam=[]; end setUserData('cam',cam); end wavelengths=sort(unique(calibration.trainingWavelengths)); setUserData('wavelengths',wavelengths); logMessage('Loaded calibration data for %d wavelengths from %0.1f nm to %0.1f nm',[length(wavelengths) 1e9*[min(wavelengths) max(wavelengths)]]); updateStatus('calibrationFileName',fullFileName); setFigureTitle(); catch Exc selectAndLoadCalibration(); end setFigureTitle(); end function cameras=detectCameras() cameras=[]; cameras(1).type='DummyCam'; cameras(1).index=1; cameras(1).description='Dummy Cam'; cameras(2).type='DummyCam'; cameras(2).index=2; cameras(2).description='Dummy Cam HD'; hwInfo=imaqhwinfo(); if (any(strcmpi(hwInfo.InstalledAdaptors,'gige'))) hwInfoGigE=imaqhwinfo('gige'); for (camIdx=1:length(hwInfoGigE.DeviceIDs)) cameras(end+1).type='BaslerGigE'; cameras(end).index=hwInfoGigE.DeviceIDs{camIdx}; cameras(end).description='Basler GigE'; if (length(hwInfoGigE.DeviceIDs)>1) cameras(end).description=strcat(cameras(end).description,sprintf(' %.0f',hwInfoGigE.DeviceIDs{camIdx})); end end end if (any(strcmpi(hwInfo.InstalledAdaptors,'andor'))) hwInfoAndor=imaqhwinfo('andor'); for (camIdx=1:length(hwInfoAndor.DeviceIDs)) cameras(end+1).type='Andor'; cameras(end).index=hwInfoAndor.DeviceIDs{camIdx}; cameras(end).description='Andor'; if (length(hwInfoGigE.DeviceIDs)>1) cameras(end).description=strcat(cameras(end).description,sprintf(' %.0f',hwInfoAndor.DeviceIDs{camIdx})); end end end if (any(strcmpi(hwInfo.InstalledAdaptors,'winvideo'))) hwInfoIC=imaqhwinfo('winvideo'); for (camIdx=1:length(hwInfoIC.DeviceIDs)) cameras(end+1).type='ImagingSource'; cameras(end).index=hwInfoIC.DeviceIDs{camIdx}; cameras(end).description='Imaging Source'; if (length(hwInfoIC.DeviceIDs)>1) cameras(end).description=strcat(cameras(end).description,sprintf(' %.0f',hwInfoIC.DeviceIDs{camIdx})); end end end if (any(strcmpi(hwInfo.InstalledAdaptors,'avtmatlabadaptor64_r2009b'))) hwInfoPC=imaqhwinfo('avtmatlabadaptor64_r2009b'); for (camIdx=1:length(hwInfoPC.DeviceIDs)) cameras(end+1).type='PikeCam'; cameras(end).index=hwInfoPC.DeviceIDs{camIdx}; cameras(end).description='PikeCam'; if (length(hwInfoPC.DeviceIDs)>1) cameras(end).description=strcat(cameras(end).description,sprintf(' %.0f',hwInfoPC.DeviceIDs{camIdx})); end end end if (exist('vcapg2')) numberOfCards=vcapg2(); for cardIdx=1:numberOfCards, cameras(end+1).type='DirectShow'; cameras(end).index=cardIdx; cameras(end).description='Win Direct Show'; if (numberOfCards>1) cameras(end).description=strcat(cameras(end).description,sprintf(' %.0f',cardIdx)); end end end end % % Menu callbacks % function selectAndLoadCalibration(obj,event) [fileName,pathName]=uigetfile('*.mat','Select calibration file...'); figure(getBaseFigureHandle()); % Bring the display back to the foreground if (~isempty(fileName) && ischar(fileName)) fullFileName=strcat(pathName,'/',fileName); loadCalibration(fullFileName); else logMessage('No file selected, keeping current calibration data.'); end end function exit(obj,event) setUserData('isClosing',true); end function openSignalWindow(obj,event) imageAxes=getUserData('imageAxes'); if (isempty(imageAxes)) cam=getUserData('cam'); mainFigHandle=getBaseFigureHandle(); windowOffset=get(mainFigHandle,'Position'); windowOffset=windowOffset(1:2)+windowOffset(3:4)-[0 cam.regionOfInterest(3)]; signalFig=figure('Name','Live Signal','Units','pixels','Position',[windowOffset cam.regionOfInterest([4 3])],'NumberTitle','off','UserData',struct('mainFigure',mainFigHandle)); imageAxes=axes('Parent',signalFig,'Units','normalized','Position',[0 0 1 1]); setUserData('imageAxes',imageAxes); else %Already open, user probably want to close it instead closeSignalWindow(); end end function closeSignalWindow() imageAxes=getUserData('imageAxes'); if (~isempty(imageAxes)) if (ishandle(imageAxes) && strcmpi(get(imageAxes,'BeingDeleted'),'off')) close(get(imageAxes,'Parent')); end end end function updateCam(selectedCamera) try switch(selectedCamera.type), case 'BaslerGigE' %Basler GigE cam=BaslerGigECam(selectedCamera.index); case 'Andor' %Andor logMessage('Andor camera not implemented'); case 'ImagingSource' %Imaging Source cam=ImagingSourceCam(selectedCamera.index); case 'DirectShow' %Direct Show cam=DirectShowCam(selectedCamera.index); case 'PikeCam' %Pike Show cam=PikeCam(selectedCamera.index); otherwise %DummyCam switch (selectedCamera.index) case 2 imgSize=[480 640]; otherwise imgSize=[240 320]; end cam=DummyCam(imgSize); end try cam.regionOfInterest=getUserData('regionOfInterest'); setUserData('cam',cam); updateStatus('selectedCameraType',selectedCamera.type); updateStatus('selectedCameraIndex',selectedCamera.index); catch Exc logMessage('Region of interest invalid, please use the same camera!'); cam=[]; end catch Exc logMessage('Could not set camera!'); end end % % Data access functions % % % User data function are 'global' variables linked to this GUI, though not % persistent between program shutdowns. % function value=getUserData(fieldName) fig=getBaseFigureHandle(); userData=get(fig,'UserData'); value=userData.(fieldName); end function setUserData(fieldName,value) if (nargin<2) value=fieldName; fieldName=inputname(1); end fig=getBaseFigureHandle(); userData=get(fig,'UserData'); userData.(fieldName)=value; set(fig,'UserData',userData); end function fig=getBaseFigureHandle() fig=gcbf(); if (isempty(fig)) fig=gcf(); end userData=get(fig,'UserData'); if (isfield(userData,'mainFigure')) fig=userData.mainFigure; end end function loadStatus() fullPath=mfilename('fullpath'); try load(strcat(fullPath,'.mat'),'status'); catch Exc end if (~exist('status','var')) status={}; status.version=-1; end setUserData('status',status); end function value=getStatus(fieldName,defaultValue) status=getUserData('status'); if (isfield(status,fieldName)) value=status.(fieldName); else if (nargin<2) defaultValue=[]; end value=defaultValue; end end function updateStatus(fieldName,value) status=getUserData('status'); status.(fieldName)=value; setUserData('status',status); saveStatus(); end function saveStatus() status=getUserData('status'); fullPath=mfilename('fullpath'); save(strcat(fullPath,'.mat'),'status'); end
github
mc225/Softwares_Tom-master
determineFrequencyAndBandwidth.m
.m
Softwares_Tom-master/VateriteRotation/determineFrequencyAndBandwidth.m
9,329
utf_8
00ffd9a872ab4a64a41810e898dadeb9
% [frequency bandwidth]=determineFrequencyAndBandWidth(signal,samplesPerSecond) % % function [frequency bandwidth]=determineFrequencyAndBandWidth(signal,samplesPerSecond) close all; if (nargin<1) data=load('C:\Users\Tom\Documents\labsoftware\matlab\VateriteRotation\s.10155.mat'); signalA=double(data.data16a)*2^-15; signalB=double(data.data16b)*2^-15; % Why has the b-signal more power in the higher orders than in the first order? signal=signalA; %./(signalA+signalB); clear data; end if (nargin<2) samplesPerSecond=2^14; end firstOrderFrequencyInitialEstimate=539; signal=signal(1:floor(4*end/16)); nbSamples=length(signal); samplePeriod=1/samplesPerSecond; recordingTime=nbSamples*samplePeriod; blockPeriod=16; % in seconds blockStepPeriod=1; % in seconds subSampling=1; times=[0:samplePeriod:recordingTime-samplePeriod]; % [Qs,params,resNorms]=determineProfile(times,signal,firstOrderFrequencyInitialEstimate,1); [Qs,params,resNorms]=determineProfile(times,signal,firstOrderFrequencyInitialEstimate,1); Qs % % Normalize signal % lowPass=bandPass(times,signal.^2,[0 firstOrderFrequencyInitialEstimate/10]); % signal=signal-lowPass; % envelope=sqrt(bandPass(times,signal.^2,[0 firstOrderFrequencyInitialEstimate/10])); % signal=signal./envelope; order=1; singleOrderOfSignal=bandPass(times,signal,order*firstOrderFrequencyInitialEstimate+[-1 1]*firstOrderFrequencyInitialEstimate/2); nbSelectedSamples=floor(blockPeriod*samplesPerSecond); nbSelectedSubSamples=nbSelectedSamples*subSampling; blockFrequencies=([1:nbSelectedSubSamples]-1-floor(nbSelectedSubSamples/2))*samplesPerSecond/nbSelectedSubSamples; blockStartTimes=[0:blockStepPeriod:(recordingTime-blockPeriod)]; dominantFrequencies=zeros(1,length(blockStartTimes)); spectra=zeros(length(blockStartTimes),nbSelectedSubSamples); for blockIdx=1:length(blockStartTimes) blockStartTime=blockStartTimes(blockIdx); [~, firstSample]=min(abs(times-blockStartTime)); selectedIndexes=firstSample-1+[1:nbSelectedSamples]; signalSelection=singleOrderOfSignal(selectedIndexes); timesSelection=times(selectedIndexes); window=hann(timesSelection,blockStartTime+blockPeriod/2,blockPeriod); windowedSignal=signalSelection.*window; if (subSampling>1) windowedSignal(end*subSampling)=0; % zero pad time domain, sinc interpolate spectrum end spectra(blockIdx,:)=fftshift(fft(windowedSignal)); [~,dominantFrequencyIndex]=max(abs(spectra(blockIdx,:))); dominantFrequency=abs(blockFrequencies(dominantFrequencyIndex)); dominantFrequencies(blockIdx)=dominantFrequency; if (floor(blockStartTime)>floor(blockStartTime-blockStepPeriod)) logMessage('Processed %0.0f seconds',blockStartTime); end end dominantFrequencies=dominantFrequencies/order; figure; subplot(2,2,1); plot(repmat(blockFrequencies.'*1e-3,[1 length(blockStartTimes)]),abs(spectra.')); xlim([0 blockFrequencies(end)]*1e-3); subplot(2,2,2); plot([0:blockStepPeriod:(recordingTime-blockPeriod)],dominantFrequencies); subplot(2,2,[3 4]); plot(times,singleOrderOfSignal); xlim([0 10/firstOrderFrequencyInitialEstimate]); end function window=hann(t,center,width) window=(abs(t-center)<width/2).*(0.5*(1+cos(2*pi*(t-center)/width))); end function window=hamm(t,center,width) alpha=0.54; window=(abs(t-center)<width/2).*(alpha+(1-alpha)*cos(2*pi*(t-center)/width)); end function filteredSignal=bandPass(times,signal,band) if (length(times)>1) samplesPerSecond=1./diff(times(1:2)); else samplesPerSecond=times; end nbSamples=length(signal); spectrum=fftshift(fft(signal)); frequencies=([1:nbSamples]-1-floor(nbSamples/2))*samplesPerSecond/nbSamples; filter=abs(frequencies)>=band(1) & abs(frequencies)<band(2); filteredSignal=ifft(ifftshift(spectrum.*filter)); end function [Qs params resNorms]=determineProfile(times,signal,firstOrderFrequencyInitialEstimate,maxNbOfOrders) if (length(times)>1) samplesPerSecond=1./diff(times(1:2)); else samplesPerSecond=times; end nbSamples=length(signal); frequencies=([1:nbSamples]-1-floor(nbSamples/2))*samplesPerSecond/nbSamples; if (nargin<4) maxNbOfOrders=ceil(frequencies(end)/firstOrderFrequencyInitialEstimate); end dFreq=diff(frequencies(1:2)); spectrum=fftshift(fft(signal)); centralFrequencies=[1:maxNbOfOrders]*firstOrderFrequencyInitialEstimate; centralFrequencies=centralFrequencies(centralFrequencies<=frequencies(end)-0.5*firstOrderFrequencyInitialEstimate); params=zeros(length(centralFrequencies),5); resNorms=zeros(1,length(centralFrequencies)); Qs=zeros(1,length(centralFrequencies)); estimatedCentralFrequencies=zeros(1,length(centralFrequencies)); gammas=zeros(1,length(centralFrequencies)); sigmas=zeros(1,length(centralFrequencies)); for orderIdx=1:length(centralFrequencies) centralFrequency=centralFrequencies(orderIdx); band=centralFrequency+[-0.5 0.5]*firstOrderFrequencyInitialEstimate; freqSel=frequencies>=band(1) & frequencies<band(2); absSpectrumSel=abs(spectrum(freqSel)); quartileDiffInSampleUnits = diff(quantile(absSpectrumSel,[.25 .75])); % gamma=0.5*diff(frequencies(1:2))*quartileDiffInSampleUnits; gamma= 1/pi/max(absSpectrumSel); params0=[dFreq 0 centralFrequency sum(absSpectrumSel)-median(absSpectrumSel)*numel(absSpectrumSel) median(absSpectrumSel)]; bounds= [0 0 band(1) min(absSpectrumSel)*length(absSpectrumSel) min(absSpectrumSel); Inf Inf band(2) 2*sum(absSpectrumSel) max(absSpectrumSel)]; % [yPrime, params(orderIdx,:), resNorms(orderIdx)] = voigtFit(frequencies(freqSel),absSpectrumSel,params0,bounds); [yPrime, params(orderIdx,:), resNorms(orderIdx)] = voigtTranslateScale(frequencies(freqSel),absSpectrumSel,params0,bounds); % [yPrime, params(orderIdx,:), resNorms(orderIdx)] = lorentzFit(frequencies(freqSel),absSpectrumSel,params0,bounds); figure(1); plot(frequencies(freqSel),absSpectrumSel); hold on; plot(frequencies(freqSel),yPrime,'r'); hold on; xlim(540+[-1 1]*20); message=sprintf('Res. Norm = %0.3f',sqrt(resNorms/numel(absSpectrumSel))); logMessage(message); title(message); %A=f0/Q %H(f)=A.*f./(f.^2+A.*f+f0^2)=A.*f/((f-f0).^2+(2*f0+A).*f) %H(f)=P1./((f - P2).^2 + P3)=P1./(f.^2 -2 P2 f +P2.^2 +P3) estimatedCentralFrequencies(orderIdx)=params(orderIdx,3); gammas(orderIdx)=params(orderIdx,1); lineWidths=2*gammas; sigmas(orderIdx)=params(orderIdx,2); % A=params(orderIdx,3)-2*estimatedCentralFrequencies(orderIdx); % Qs(orderIdx)=estimatedCentralFrequencies(orderIdx)/A; Qs(orderIdx)=estimatedCentralFrequencies(orderIdx)./lineWidths(orderIdx); end hold off; end % params=[gamma,sigma,x0l,integratedValue,offset]; % bounds=[lowerParam; upperParam]; % where lower/upperParam are row vectors as params function [fittedY, params, resNorm] = lorentzFit(X,Y,params0,bounds) fitoptions=optimset('Display','final'); fitFunctor=@(p,X) voigt(X,p(1),params0(2),p(3),p(2),0)+p(4); [params,resNorm,residual,exitflag,output,lambda,jacobian] = lsqcurvefit(fitFunctor,params0([1 3:end]),X,Y,bounds(1,[1 3:end]),bounds(2,[1 3:end]),fitoptions); % [params,resNorm,exitflag,output] = fminsearch(@(p) sum(abs(fitFunctor(p,X)-Y).^2),params0,fitoptions); fittedY=fitFunctor(params,X); % % % plot(X,Y,X,fittedY); xlim([500 580]); title(sqrt(resNorm./length(X))) params=[params(1) params0(2) params(2:end)]; end % params=[gamma,sigma,x0l,integratedValue,offset]; % bounds=[lowerParam; upperParam]; % where lower/upperParam are row vectors as params function [fittedY, params, resNorm] = voigtTranslateScale(X,Y,params0,bounds) fitoptions=optimset('Display','final'); fitFunctor=@(p,X) voigt(X,params0(1),params0(2),p(1),p(2),0)+p(3); [params,resNorm,residual,exitflag,output,lambda,jacobian] = lsqcurvefit(fitFunctor,params0(3:end),X,Y,bounds(1,3:end),bounds(2,3:end),fitoptions); fittedY=fitFunctor(params,X); % % % plot(X,Y,X,fittedY); xlim([500 580]); title(sqrt(resNorm./length(X))) params=[params0(1:2) params]; end % params=[gamma,sigma,x0l,integratedValue,offset]; % bounds=[lowerParam; upperParam]; % where lower/upperParam are row vectors as params function [fittedY, params, resNorm] = voigtFit(X,Y,params0,bounds) fitoptions=optimset('Display','final'); fitFunctor=@(p,X) voigt(X,p(1),p(2),p(4),p(3),0)+p(5); [params,resNorm,residual,exitflag,output,lambda,jacobian] = lsqcurvefit(fitFunctor,params0,X,Y,bounds(1,:),bounds(2,:),fitoptions); % [params,resNorm,exitflag,output] = fminsearch(@(p) sum(abs(fitFunctor(p,X)-Y).^2),params0,fitoptions); fittedY=fitFunctor(params,X); % % % plot(X,Y,X,fittedY); xlim([500 580]); title(sqrt(resNorm./length(X))) end
github
mc225/Softwares_Tom-master
voigt.m
.m
Softwares_Tom-master/VateriteRotation/voigt.m
3,703
utf_8
2ab55608b1e5047d4a76973dfa9d37e9
% v=voigt(x,gamma,sigma,integratedValue,x0l,x0g) % % Calculates the Voigt distribution at points x. % % Example: % x=[-100:.001:100]; % tic; % v=voigt(x,1,1,10,50,0); % toc % plot(x,v); % sum(v) % function v=voigt(x,gamma,sigma,integratedValue,x0l,x0g) if (nargin<1) x=[-10:.01:10]; end if (nargin<2) gamma=1; end if (nargin<3) sigma=1; end if (nargin<4) integratedValue=1; end if (nargin<5) x0l=0; end if (nargin<6) x0g=0; end maxCalculationLength=2^20; maxGaussianTails=1e-3; maxLorentzianTails=1e-3; maxLorentzianStdX=tan((1-maxLorentzianTails)*pi/2); maxGaussianStdX=erfinv(1-maxGaussianTails)/sqrt(0.5); dx=diff(x(1:2)); nbOutputSamples=length(x); x0=x0l+x0g; % Calculate as if Gaussian is centered at 0 from now on nbSamplesWithSignificantValuesLorentzian=max(1,ceil(2*gamma*maxLorentzianStdX/dx)); nbSamplesWithSignificantValuesGaussian=max(1,ceil(2*sigma*maxGaussianStdX/dx)); calculationLength=min(nbOutputSamples,nbSamplesWithSignificantValuesLorentzian)+nbSamplesWithSignificantValuesGaussian; if (calculationLength>maxCalculationLength) logMessage('Required calculation length %d is larger than the upper limit %d, will perform the calculation on the limitted range.',[calculationLength maxCalculationLength]); calculationLength=maxCalculationLength; end % Select a range, xCalc, on which to do the calculation if (calculationLength<nbOutputSamples) [~,centerIdx]=min(abs(x-x0)); leftCropped=min(max(0,centerIdx-ceil(calculationLength/2)),nbOutputSamples-calculationLength); rightCropped=nbOutputSamples-calculationLength-leftCropped; else leftCropped=0; rightCropped=0; end xCalc=x(leftCropped+1)+dx*[0:(calculationLength-1)]; if (nbSamplesWithSignificantValuesLorentzian>1 && nbSamplesWithSignificantValuesGaussian>1) lorentzian=lorentzianDistribution(xCalc,x0,gamma); gaussian=ifftshift(gaussianDistribution(xCalc,xCalc(1+floor(end/2)),sigma)); % Convolve v=ifft(fft(lorentzian).*fft(gaussian),'symmetric'); else if (nbSamplesWithSignificantValuesLorentzian>1) v=lorentzianDistribution(xCalc,x0,gamma); else v=gaussianDistribution(xCalc,x0,sigma); end end % Pad if needed v=v([ones(1,leftCropped), 1:end, end*ones(1,rightCropped)]); v([1:leftCropped, (end-(rightCropped-1)):end])=0; % Crop if needed v=v(1:nbOutputSamples); % Change amplitude as requested v=integratedValue*v; if (nargout==0) figure(); plot(x,v); logMessage('Integral value=%0.3f',sum(v)); clear v; end end % Calculates the Gaussian distribution that integrates to 1 over infinity % as integrated per sample interval function v=gaussianDistribution(x,x0,sigma) if ~isempty(x) dx=diff(x(1:2)); % v=dx*exp(-0.5*((x-x0)./sigma).^2)/(sigma*sqrt(2*pi)); xIntervalEdges=[x x(end)+dx]-dx/2-x0; expIntegrated=erf(xIntervalEdges*sqrt(0.5)/sigma); v=diff(expIntegrated)/2; else v=[]; end end % Calculates the Lorentzian distribution that integrates to 1 over infinity % as integrated per sample interval function v=lorentzianDistribution(x,x0,gamma) if ~isempty(x) dx=diff(x(1:2)); % v=dx*(gamma/pi)./((x-x0).^2+gamma^2); xIntervalEdges=[x x(end)+dx]-dx/2-x0; lorentzianIntegrated=atan2(xIntervalEdges,gamma); v=diff(lorentzianIntegrated)/pi; else v=[]; end end
github
mc225/Softwares_Tom-master
twoParticleRecording.m
.m
Softwares_Tom-master/VateriteRotation/twoParticleRecording.m
3,714
utf_8
54b54407f80a4b600d5a09967878a4b0
% % % function twoParticleRecording() fixedParticlePosition=5e-6; % metric units movingParticlePositions=-[5:10, 9:6]*1e-6; % metric units maximumStepSize=.2e-6; % metric units % Don't go above unity for both combined fixedParticlePower=0.35; movingParticlePower=0.35; fixedParticleDeflection=positionToDeflection(fixedParticlePosition); % Configure SLM and load aberration correction slm=PhaseSLM(2); slm.referenceDeflectionFrequency=[1/10 1/10]; correctionFunctionFileName='C:\Documents and Settings\sk495\My Documents\software\matlab\GUI\calibrateSetup_2013-09-24.mat'; correctionFileContents=whos('-file',correctionFunctionFileName); load(correctionFunctionFileName,'measuredPupilFunction'); amplificationLimit=1; if (any(strcmp(correctionFileContents,'initialCorrection'))) load(correctionFunctionFileName,'initialCorrection'); else initialCorrection=1; end slm.correctionFunction=calcCorrectionFromPupilFunction(measuredPupilFunction./initialCorrection,amplificationLimit); logMessage('Correction function updated using amplification limit %d.',amplificationLimit); movingParticleDeflection=positionToDeflection(movingParticlePositions(1)); slm.modulate(@(X,Y) (sqrt(X.^2+Y.^2)<300).*(fixedParticlePower*(exp(2i*pi*fixedParticleDeflection*X)) + movingParticlePower*(exp(2i*pi*movingParticleDeflection*X)))); previousMovingParticlePosition=movingParticlePositions(1); % Loop until CTRL-C stopMeasurement=false; while ~stopMeasurement % Loop through all particle positions for posIdx=[1:length(movingParticlePositions)] targetPosition=movingParticlePositions(posIdx); logMessage('Moving particle 2 from %0.3f to %0.3f um.',[previousMovingParticlePosition targetPosition]*1e6); % Move slowly for movingParticlePosition=previousMovingParticlePosition:sign(targetPosition-previousMovingParticlePosition)*maximumStepSize:targetPosition movingParticleDeflection=positionToDeflection(movingParticlePosition); slm.modulate(@(X,Y) (sqrt(X.^2+Y.^2)<300).*(fixedParticlePower*(exp(2i*pi*fixedParticleDeflection*X)) + movingParticlePower*(exp(2i*pi*movingParticleDeflection*X)))); end % Go to target position movingParticleDeflection=positionToDeflection(targetPosition); slm.modulate(@(X,Y) (sqrt(X.^2+Y.^2)<300).*(fixedParticlePower*(exp(2i*pi*fixedParticleDeflection*X)) + movingParticlePower*(exp(2i*pi*movingParticleDeflection*X)))); previousMovingParticlePosition=targetPosition; % Record what needs to be done result=recordData(movingParticlePositions(posIdx)); if ~result stopMeasurement=true; end end % Wait a bit for next measurement logMessage('Waiting for next movement.'); pause(5); end end function result=recordData(movingParticlePosition) logMessage('Recording data...'); pause(2); result=true; end function deflection=positionToDeflection(position) slmPixelPitch=20e-6; telescopeMagnifications=[100/175 250/250]; objectiveMagnification=100; objectiveTubeLensFocalLength=200e-3; wavelength=1070e-9; objectiveFocalLength=objectiveTubeLensFocalLength/objectiveMagnification; slmPixelPitchAtBackAperture=prod(telescopeMagnifications)*slmPixelPitch; tanOfUnityDeflection=wavelength/slmPixelPitchAtBackAperture; focalShiftOfUnityDeflection=objectiveFocalLength*tanOfUnityDeflection; deflection=position/focalShiftOfUnityDeflection; end
github
mc225/Softwares_Tom-master
logMessage.m
.m
Softwares_Tom-master/Utilities/logMessage.m
4,231
utf_8
ca34eb3eb53bd5a97c2985e9aa4b5ab0
% message=logMessage(message,values,recipientEmailToAddresses,attachments) % % Logs a message to the command line and to a file called 'log.txt' in the % current folder with a timestamp prefix. Optionally, it can be sent by e-mail % as well with (optional) attachments. % The message is formatted using escape characters when a second argument % is provided, containing either the substitions, or an empty list []. % % Input arguments: % message: a text string, which may be formatted using the sprintf % syntax (see help sprintf) % values: optional values that can be used by a formatted message. % recipientEmailToAddresses: optional email address notify, or a cell array thereof. % attachments: optional string or cell array of strings with filenames % to attachments to be included with the email % % Output arguments: % message: the formatted message % % Examples: % logMessage('This is a simple message.'); % 2013-01-26 17:08:56.589| This is a simple message % % logMessage('This is a formatted message:\n pi=%f, e=%f!',[pi exp(1)]); % 2013-01-26 17:14:9.627| This is a formatted message: % pi=3.141593, e=2.718282! % % logMessage('This is a formatted message\nwithout substitutions.',[]); % 2013-01-26 17:14:56.122| This is a formatted message % without substitutions. % % logMessage('This message is e-mailed to [email protected]',[],'[email protected]'); % 2013-01-26 17:16:46.277| This message is e-mailed to [email protected] % % logMessage('And this one e-mails an attachment with it.',[],'[email protected]','output.mat'); % 2013-01-26 17:18:46.409| And this one e-mails an attachment with it. % function message=logMessage(message,values,recipientEmailToAddresses,attachments) timeNow=clock(); if (nargin<1 || isempty(message)) message=''; end if (isnumeric(message)) message=num2str(message); end if (nargin>1), message=sprintf(message,values); end if (nargin<3) recipientEmailToAddresses=[]; end if (nargin<4) attachments={}; else if (ischar(attachments)) attachments={attachments}; end end %Prepare the message synopsis=message; message=sprintf('%04.0f-%02.0f-%02.0f %02.0f:%02.0f:%06.3f| %s',timeNow(1),timeNow(2),timeNow(3),timeNow(4),timeNow(5),timeNow(6),message); disp(message); %Write the message to file fid = fopen('log.txt','a'); if (fid>0) fprintf(fid,'%s\n',message); fclose(fid); end %Also e-mail this message if it was requested if (~isempty(recipientEmailToAddresses) && (~iscell(recipientEmailToAddresses) || ~isempty(recipientEmailToAddresses{1}))) if (~ispref('Internet','SMTP_Server') || isempty(getpref('Internet','SMTP_Server'))) setpref('Internet','SMTP_Server','mailhost.st-andrews.ac.uk'); end if (~ispref('Internet','E_mail') || isempty(getpref('Internet','E_mail'))) setpref('Internet','E_mail','[email protected]'); end synopsis=regexprep(synopsis,'\s+',' '); if (length(synopsis)>200) synopsis=[synopsis(1:150) '...' synopsis(end-46:end)]; end try existingAttachments={}; for attachmentIdx=1:length(attachments) attachment=attachments{attachmentIdx}; if (ischar(attachment)) if (exist(attachment,'file')) existingAttachments{end+1}=attachment; else message=[message sprintf('\n COULD NOT ATTACH FILE %s!',attachment)]; end else message=[message sprintf('\n SPECIFIED ELEMENT IS NOT A FILENAME!')]; end end try sendmail(recipientEmailToAddresses,synopsis,message,existingAttachments); catch Exc % Try without attachements sendmail(recipientEmailToAddresses,synopsis,[message sprintf('\n\n\n SENDING WITH ATTACHMENT FAILED!')]); end catch Exc Exc logMessage('Could not send as e-mail: %s',Exc.message); end end end
github
mc225/Softwares_Tom-master
removeTiltAndPiston.m
.m
Softwares_Tom-master/Utilities/removeTiltAndPiston.m
975
utf_8
948b7308f117d01530bde9c7454596ed
% [pupilFunctionWithoutTiltAndPiston tilt piston]=removeTiltAndPiston(pupilFunction) % % Calculates and removes the tilt and piston from a pupil function measurement. % % Output parameters: % pupilFunctionWithoutTilt: the input with the tilt removed % tilt: the removed tilt in units of wavelengths per pixel. % piston: the removed piston in units of wavelength. % function [pupilFunctionWithoutTiltAndPiston tilt piston]=removeTiltAndPiston(pupilFunction) if (nargin<1) % Test case [X,Y]=ndgrid([-50:50],[-100:100]); R=sqrt(X.^2+Y.^2); pupilFunction=exp(2i*pi*(0.05*X-0.10*Y + .001*R.^2 ))*1i.*(R<0.5*max(X(:))); end inputSize=size(pupilFunction); [output pupilFunctionWithoutTiltAndPiston]=dftregistration(ones(inputSize),ifftshift(pupilFunction),100); piston=-output(2)/(2*pi); tilt=output(3:4)./inputSize; pupilFunctionWithoutTiltAndPiston=fftshift(pupilFunctionWithoutTiltAndPiston); end
github
mc225/Softwares_Tom-master
spectrumToRGB.m
.m
Softwares_Tom-master/Utilities/spectrumToRGB.m
7,556
utf_8
ec4f544f967641c392792e9cb31e9976
% RGB=spectrumToRGB(wavelengths,wavelengthIntensities,constrainValues) % % Returns the red green and blue component to simulate a given spectrum. % The number of dimensions of the returned matrix is equal to that of the % wavelengthIntensities argument, and the dimensions are the same except % for the last dimension which is always three. % % wavelengths can be a vector of wavelengths or a function handle returning the intensity for a given wavelength, in the latter case the argument wavelengthIntensities is ignored. % If wavelengthIntensities is a matrix, its last dimension should equal the number of wavelengths. % % constrainValues (optional, default=true): a boolean to indicate if negative RGB values should be de-saturated to be non-negative % function RGB=spectrumToRGB(wavelengths,wavelengthIntensities,constrainValues) if (nargin<1 || isempty(wavelengths)) wavelengths=532e-9; %Nd-YAG, frequency-doubled % wavelengths=632.8e-9; %He-Ne wavelengths=1e-9*[300:800]; end % From John Walker's http://www.fourmilab.ch/documents/specrend/specrend.c wavelengthsXYZTable=[380:5:780]*1e-9; if (isa(wavelengths,'function_handle')) wavelengthIntensities=wavelengths(wavelengthsXYZTable); wavelengths=wavelengthsXYZTable; else if (nargin>=1) if (nargin<2 || isempty(wavelengthIntensities)) wavelengthIntensities=ones(size(wavelengths)); end else wavelengthIntensities=permute(eye(length(wavelengths)),[3 1 2]); end end if (nargin<3 || isempty(constrainValues)) constrainValues=true; end wavelengths=wavelengths(:); inputSize=size(wavelengthIntensities); nbWavelengths=numel(wavelengths); if (nbWavelengths==1 && inputSize(end)~=1) inputSize(end+1)=1; end wavelengthIntensities=reshape(wavelengthIntensities,[],nbWavelengths).'; if (nbWavelengths~=inputSize(end)) logMessage('spectrumToRGB Error: the number of wavelengths should be equal to the last dimension of the second argument.'); return; end % Define Color Systems % %White point chromaticities IlluminantC = [0.3101, 0.3162]; % For NTSC television IlluminantD65 = [0.3127, 0.3291]; % For EBU and SMPTE IlluminantE = [0.33333333, 0.33333333]; % CIE equal-energy illuminant % Gamma of nonlinear correction. See Charles Poynton's ColorFAQ Item 45 and GammaFAQ Item 6 at: http://www.poynton.com/ColorFAQ.html and http://www.poynton.com/GammaFAQ.html GAMMA_REC709=0; % Rec. 709 NTSC=struct('RGB',[0.67,0.33; 0.21,0.71; 0.14,0.08].','WhitePoint',IlluminantC,'Gamma',GAMMA_REC709); EBU=struct('RGB',[0.64,0.33;0.29,0.60;0.15,0.06].','WhitePoint',IlluminantD65,'Gamma',GAMMA_REC709); % PAL/SECAM SMPTE=struct('RGB',[0.630,0.340;0.310,0.595;0.155,0.070].','WhitePoint',IlluminantD65,'Gamma',GAMMA_REC709); HDTV=struct('RGB',[0.670,0.330;0.210,0.710;0.150,0.060].','WhitePoint',IlluminantD65,'Gamma',GAMMA_REC709); CIE=struct('RGB',[0.7355,0.2645;0.2658,0.7243;0.1669,0.0085].','WhitePoint',IlluminantE,'Gamma',GAMMA_REC709); CIERec709=struct('RGB',[0.64,0.33;0.30,0.60;0.15,0.06].','WhitePoint',IlluminantD65,'Gamma',GAMMA_REC709); %Pick this color system: colorSystem=SMPTE; % From John Walker's http://www.fourmilab.ch/documents/specrend/specrend.c XYZTable=[0.0014,0.0000,0.0065; 0.0022,0.0001,0.0105; 0.0042,0.0001,0.0201; ... 0.0076,0.0002,0.0362; 0.0143,0.0004,0.0679; 0.0232,0.0006,0.1102; ... 0.0435,0.0012,0.2074; 0.0776,0.0022,0.3713; 0.1344,0.0040,0.6456; ... 0.2148,0.0073,1.0391; 0.2839,0.0116,1.3856; 0.3285,0.0168,1.6230; ... 0.3483,0.0230,1.7471; 0.3481,0.0298,1.7826; 0.3362,0.0380,1.7721; ... 0.3187,0.0480,1.7441; 0.2908,0.0600,1.6692; 0.2511,0.0739,1.5281; ... 0.1954,0.0910,1.2876; 0.1421,0.1126,1.0419; 0.0956,0.1390,0.8130; ... 0.0580,0.1693,0.6162; 0.0320,0.2080,0.4652; 0.0147,0.2586,0.3533; ... 0.0049,0.3230,0.2720; 0.0024,0.4073,0.2123; 0.0093,0.5030,0.1582; ... 0.0291,0.6082,0.1117; 0.0633,0.7100,0.0782; 0.1096,0.7932,0.0573; ... 0.1655,0.8620,0.0422; 0.2257,0.9149,0.0298; 0.2904,0.9540,0.0203; ... 0.3597,0.9803,0.0134; 0.4334,0.9950,0.0087; 0.5121,1.0000,0.0057; ... 0.5945,0.9950,0.0039; 0.6784,0.9786,0.0027; 0.7621,0.9520,0.0021; ... 0.8425,0.9154,0.0018; 0.9163,0.8700,0.0017; 0.9786,0.8163,0.0014; ... 1.0263,0.7570,0.0011; 1.0567,0.6949,0.0010; 1.0622,0.6310,0.0008; ... 1.0456,0.5668,0.0006; 1.0026,0.5030,0.0003; 0.9384,0.4412,0.0002; ... 0.8544,0.3810,0.0002; 0.7514,0.3210,0.0001; 0.6424,0.2650,0.0000; ... 0.5419,0.2170,0.0000; 0.4479,0.1750,0.0000; 0.3608,0.1382,0.0000; ... 0.2835,0.1070,0.0000; 0.2187,0.0816,0.0000; 0.1649,0.0610,0.0000; ... 0.1212,0.0446,0.0000; 0.0874,0.0320,0.0000; 0.0636,0.0232,0.0000; ... 0.0468,0.0170,0.0000; 0.0329,0.0119,0.0000; 0.0227,0.0082,0.0000; ... 0.0158,0.0057,0.0000; 0.0114,0.0041,0.0000; 0.0081,0.0029,0.0000; ... 0.0058,0.0021,0.0000; 0.0041,0.0015,0.0000; 0.0029,0.0010,0.0000; ... 0.0020,0.0007,0.0000; 0.0014,0.0005,0.0000; 0.0010,0.0004,0.0000; ... 0.0007,0.0002,0.0000; 0.0005,0.0002,0.0000; 0.0003,0.0001,0.0000; ... 0.0002,0.0001,0.0000; 0.0002,0.0001,0.0000; 0.0001,0.0000,0.0000; ... 0.0001,0.0000,0.0000; 0.0001,0.0000,0.0000; 0.0000,0.0000,0.0000]; XYZPerWavelength=interp1(wavelengthsXYZTable,XYZTable,wavelengths,'cubic',0).'; %XYZ in rows XYZ=XYZPerWavelength*wavelengthIntensities; % XYZ in rows, data points in columns XYZ=XYZ./repmat(max(eps(1),sum(XYZ,1)),[3 1]); % Transform XYZ coordinate system to RGB coordinate system XYZRGBTransformMatrix=cat(2,colorSystem.RGB.',1-sum(colorSystem.RGB.',2)); %XYZ in columns whitePoint=[colorSystem.WhitePoint 1-sum(colorSystem.WhitePoint)]; %XYZ in columns RGBXYZTransformMatrix=cross(XYZRGBTransformMatrix(:,[2 3 1]),XYZRGBTransformMatrix(:,[3 1 2])); %RGB in columns whitePointRGB=whitePoint*RGBXYZTransformMatrix/whitePoint(2); RGBXYZTransformMatrix=RGBXYZTransformMatrix./repmat(whitePointRGB,[3 1]); RGB=RGBXYZTransformMatrix*XYZ; % RGB in rows, data points in columns if (constrainValues) %Constrain RGB to non-negative values approximated=min(RGB,[],1)<0; RGB = RGB-repmat(min(0,min(RGB,[],1)),[3 1]); else approximated=false; end %Adjust to intensity of input (TODO, probably needs to be log.-scaled) RGB=RGB.*repmat(sum(wavelengthIntensities,1),[3 1]); RGB=reshape(RGB.',[inputSize(1:end-1) 3]); %Display if (nargout==0 && ndims(RGB)>=3) RGB=RGB./max(eps(1),max(RGB(:))); %Make sure that it can be displayed as a color. RGB=max(0,RGB); figure; % axis off; image(wavelengths*1e9,1,RGB); xlabel('\lambda [nm]','Interpreter','Tex'); if (any(approximated)) logMessage('Approximated %u%% of the colors!',round(100*mean(approximated))); end clear RGB; end end
github
mc225/Softwares_Tom-master
calcFullWidthAtHalfMaximum.m
.m
Softwares_Tom-master/Utilities/calcFullWidthAtHalfMaximum.m
4,461
utf_8
80d5fd3ddb9c6c79e39c476390f70948
% fullWidthAtHalfMaximum=calcFullWidthAtHalfMaximum(X,Y,method) % % Calculates the full width at half the maximum using various methods. % % X must be a vector with the sample coordinates or a matrix with the % coordinates for a sample set in each column. If X is a vector than it % must have the same number as elements as the first dimension in Y. % The same coordinates are assumed for all sample sets. If it is a % matrix it must have the same size as Y. % Y must be a vector with the sample values or a matrix with the values of % a sample set in each column. % method: (default 'BiasedGaussian') % 'BiasedGaussian': fits a Gaussian and constant offset to the data. % 'Gaussian': fits an unbiased Gaussian to the data. % 'Linear': finds the FWHM starting from the maximum value and % finding the 50% points by linear interpolation. % 'LinearBiased': Same as Linear after subtraction of the minimum % value. % function fullWidthAtHalfMaximum=calcFullWidthAtHalfMaximum(X,Y,method) if (nargin<2 || isempty(Y)) Y=X; X=[1:size(Y,1)]; end if (nargin<3) method='BiasedGaussian'; end inputSize=size(Y); if (any(size(X)<inputSize)) X=repmat(X(:),[1 inputSize(2:end)]); end if (prod(inputSize)>max(inputSize)) fullWidthAtHalfMaximum=zeros([inputSize(2:end) 1]); for curveIdx=1:prod(inputSize(2:end)) fullWidthAtHalfMaximum(curveIdx)=calcSingleFullWidthAtHalfMaximum(X(:,curveIdx),Y(:,curveIdx),method); end else fullWidthAtHalfMaximum=calcSingleFullWidthAtHalfMaximum(X,Y,method); end end function fullWidthAtHalfMaximum=calcSingleFullWidthAtHalfMaximum(X,Y,method) switch (lower(method)) case {'gaussian','biasedgaussian'} fullWidthAtHalfMaximum=calcSingleGaussianFullWidthAtHalfMaximum(X,Y,method); case 'linear' fullWidthAtHalfMaximum=calcSingleLinearFullWidthAtHalfMaximum(X,Y); case 'biasedlinear' fullWidthAtHalfMaximum=calcSingleLinearFullWidthAtHalfMaximum(X,Y-min(Y(:))); otherwise error('Invalid method specified.'); end end function fullWidthAtHalfMaximum=calcSingleLinearFullWidthAtHalfMaximum(X,Y) [maxY, centerI]=max(Y); if (maxY<=0) fullWidthAtHalfMaximum=Inf; return; end Y=Y/maxY; leftI=find(Y(1:centerI-1)>0.5,1,'first'); rightI=find(Y(centerI+1:end)>0.5,1,'last'); if (isempty(leftI) || isempty(rightI) || leftI==1 || centerI+rightI==length(X)) fullWidthAtHalfMaximum=Inf; return; end rightI=centerI+rightI; % Interpolate linearly leftX=X(leftI-1)+(X(leftI)-X(leftI-1))*(0.5-Y(leftI-1))/(Y(leftI)-Y(leftI-1)); rightX=X(rightI+1)+(X(rightI)-X(rightI+1))*(0.5-Y(rightI+1))/(Y(rightI)-Y(rightI+1)); fullWidthAtHalfMaximum=rightX-leftX; end function fullWidthAtHalfMaximum=calcSingleGaussianFullWidthAtHalfMaximum(X,Y,method) % Or use [curve, goodness] = fit(double(X(:)),double(Y(:)),'gauss8'); Y=Y./max(Y); % Normalize to avoid the search from stopping to early if (strcmpi(method,'BiasedGaussian')) offset=min(Y); else offset=0; end magnitude=max(Y)-offset; % center=mean(X.*(Y-offset))/mean(Y); medianFilteredY=Y(:); medianFilteredY=median([medianFilteredY medianFilteredY([2:end 1]) medianFilteredY([end, 1:end-1])].'); [~, centerI]=max(medianFilteredY); center=X(centerI); sigma=sqrt(mean(((X-center).^2).*(Y-offset))); if (method) x0=double([offset magnitude center sigma]); [x]=fminsearch(@(x) norm(gaussian(x(1),x(2),x(3),x(4),X)-Y),x0,optimset('Display','none','TolX',1e-9,'TolFun',1e6*max(Y(:)))); else x0=double([magnitude center sigma]); [x]=fminsearch(@(x) norm(gaussian(0,x(1),x(2),x(3),X)-Y),x0,optimset('Display','none','TolX',1e-9,'TolFun',1e6*max(Y(:)))); end x=num2cell(x); if (method) [offset magnitude center sigma]=deal(x{:}); else [magnitude center sigma]=deal(x{:}); end sigma=abs(sigma); % only the absolute value is important really fullWidthAtHalfMaximum=2*sigma*sqrt(-2*log(.5)); % figure; plot(X,Y,'-',X,gaussian(offset,magnitude,center,sigma,X),':'); end function Y=gaussian(offset,magnitude,center,sigma,X) Y=offset+magnitude*exp(-(X-center).^2/(2*sigma^2)); end
github
mc225/Softwares_Tom-master
getFrame.m
.m
Softwares_Tom-master/Utilities/getFrame.m
1,652
utf_8
d64d714f6cbb5c8c32e75c5a9a9dc81d
% frm=getFrame(fig,roi) % % Figure window capture function that does not capture other things on the % screen. Functions identical to getframe(fig,rect). % % Use the zbuffer or OpenGL renderer for this to work best. % Example: % fig=figure('Renderer','zbuffer'); % fig=figure('Renderer','OpenGL'); % fig=figure(); % set(fig,'Renderer','zbuffer'); % % Usage: % frm=getFrame(fig); % writeVideo(videoWriter,frm); % function frm=getFrame(fig,roi) if (nargin<1 || isempty(fig)) fig=gcf(); end if (nargin<2) roi=[]; end if strcmpi(get(fig,'Type'),'axes') fig=get(fig,'Parent'); end switch lower(get(fig,'Renderer')) case 'zbuffer' device='-Dzbuffer'; case 'opengl' device='-DOpenGL'; otherwise errorMessage=sprintf('Renderer %s not supported for frame grabbing with getFrame(), use figure(''Renderer'',''zbuffer''). Switching to zbuffer now.',get(fig,'Renderer')); logMessage(errorMessage); % origRenderer=get(fig,'Renderer'); set(fig,'Renderer','zbuffer'); device='-Dzbuffer'; end % Need to have PaperPositionMode be auto origMode = get(fig, 'PaperPositionMode'); set(fig, 'PaperPositionMode', 'auto'); cdata = hardcopy(fig, device, '-r0'); cdata=cdata(1:(2*floor(end/2)),1:(2*floor(end/2)),:); if (~isempty(roi)) cdata=cdata(max(1,roi(1)):min(end,roi(1)+roi(3)),max(1,roi(2)):min(end,roi(2)+roi(4)),:); end % Restore figure to original state set(fig, 'PaperPositionMode', origMode); frm=im2frame(cdata); end
github
mc225/Softwares_Tom-master
cropDataCube.m
.m
Softwares_Tom-master/Utilities/cropDataCube.m
786
utf_8
f9a839de04350f32e8fe753085d2ebbf
%[dataCube xRange yRange zRange]=cropDataCube(dataCube, xLim,yLim,zLim, xRange,yRange,zRange) % function [dataCube xRange yRange zRange]=cropDataCube(dataCube, xLim,yLim,zLim, xRange,yRange,zRange) dataCubeSize=size(dataCube); if (nargin<4 || isempty(xRange)) xRange=[1:dataCubeSize(1)]; end if (nargin<5 || isempty(yRange)) yRange=[1:dataCubeSize(2)]; end if (nargin<6 || isempty(zRange)) zRange=[1:dataCubeSize(3)]; end xRangeSel=xRange>=xLim(1) & xRange<=xLim(end); yRangeSel=yRange>=yLim(1) & yRange<=yLim(end); zRangeSel=zRange>=zLim(1) & zRange<=zLim(end); dataCube=dataCube(xRangeSel,yRangeSel,zRangeSel,:); xRange=xRange(xRangeSel); yRange=yRange(yRangeSel); zRange=zRange(zRangeSel); end
github
mc225/Softwares_Tom-master
czt2fromRanges.m
.m
Softwares_Tom-master/Utilities/czt2fromRanges.m
2,176
utf_8
d3079d5831cd9f2f2c2ba162f53f864f
% f=czt2fromRanges(x,xRange,yRange) % % Calculate the partial spectrum of x using the 2-dimensional chirp z transform. % This would be the same as f=fftshift(fft2(ifftshift(x)))*sqrt(prod(size(x))) for: % xRange=[0:size(x,1)-1]-floor(size(x,1)/2);yRange=[0:size(x,2)-1]-floor(size(x,2)/2); % The L2-norm is scaled so that it would equal the L2-norm of the input for large output sizes. % % The units of x/yRange are thus twice the highest possible spatial frequency % of the field PSF when the pupil disc fits the sample area of input x. % Nyquist sampling is done for x/yRange=[from:0.5:to]; % % x should not be ifftshifted, implicit zero padding to the right! % function f=czt2fromRanges(x,xRange,yRange) inputSize=size(x); outputRanges={xRange,yRange}; nbRanges=length(outputRanges); deltaRng=0.5*ones(1,nbRanges); M=zeros(1,nbRanges); A=M; for (dimIdx=1:nbRanges) rng=outputRanges{dimIdx}; M(dimIdx)=length(rng); % The output length of the transform A(dimIdx)=exp(2i*pi*rng(1+floor(end/2))/inputSize(dimIdx)); % Offset on contour (fftshifted, hence~/2) if (M(dimIdx)>1) deltaRng(dimIdx)=diff(rng(1:2)); end end deltaOmegaInCycles=deltaRng./inputSize(1:2); W=exp(-2i*pi*deltaOmegaInCycles); % The ratio between the points on the spiral contour if (any(deltaOmegaInCycles.*M>1)) logMessage('Warning: undersampling pupil by a factor of (%0.3f, %0.3f). Image replication will occur! Reduce the number of pixels in the lateral dimension.',deltaOmegaInCycles.*M); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% f=cztn(x,M,W,A,'centered'); %TODO: Replace with 2D specific algorithm (~5% efficiency gain expected). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % The energy is spread over more sample points when sub-sampling. The next % line makes sure that the input and output norm are the same when the output space size M goes to infinity. f=f*prod(sqrt(deltaOmegaInCycles(deltaOmegaInCycles~=0))); % But, do skip any singleton dimensions as the sample size would be undefined end
github
mc225/Softwares_Tom-master
laguerreGaussian.m
.m
Softwares_Tom-master/Utilities/laguerreGaussian.m
2,460
utf_8
60b0aa63d5e14c6b610a8f80ca7d61e9
% fieldValues=laguerreGaussian(R,P,Z,pValue,lValue,lambda,beamWaist) % % Input: % R: radial coordinate grid [m] % P: azimutal coordinate grid [rad] % Z: axial coordinate grid [m] % pValue: the p value of the beam (radial) % lValue: the l value of the beam (azimutal phase index, must be integer) % lambda: the wavelength to simulate [m] % beamWaist: the beam waist [m] % % Example: % xRange=[-4e-6:.05e-6:4e-6]; % [X,Y]=meshgrid(xRange,xRange); % [P,R]=cart2pol(X,Y); % Z=[]; % lambda=500e-9; % beamWaist=2*lambda; % pValue=3; % lValue=0; % fieldValues=laguerreGaussian(R,P,Z,pValue,lValue,lambda,beamWaist); % imagesc(abs(fieldValues).^2) % function fieldValues=laguerreGaussian(R,P,Z,pValue,lValue,lambda,beamWaist) if (nargin<1), xRange=[-4e-6:.05e-6:4e-6]; [X,Y]=meshgrid(xRange,xRange); [P,R]=cart2pol(X,Y); Z=[]; pValue=0; lValue=0; end if (nargin<6) lambda=500e-9; end if (nargin<7) beamWaist=2*lambda; end if (isempty(Z)), Z=zeros(size(R)); end rayleighRange=pi*beamWaist^2/lambda; W=beamWaist*sqrt(1+(Z./rayleighRange).^2); radiusOfCurvature=(Z+(Z==0)).*(1+(rayleighRange./Z).^2); gouyPhase=atan2(Z,rayleighRange); fieldValues=(1./W).*(R.*sqrt(2)./W).^abs(lValue).*exp(-R.^2./W.^2)... .*L(abs(lValue),pValue,2*R.^2./W.^2).*exp(1i.*(2*pi/lambda).*R.^2./(2*radiusOfCurvature))... .*exp(1i*lValue.*P).*exp(-1i*(2*pValue+abs(lValue)+1).*gouyPhase); %Normalize fieldValues=fieldValues./sqrt(sum(abs(fieldValues(:)).^2)); if (nargout==0) showImage(fieldValues+1i*sqrt(eps('single')),-1,X,Y); axis square; % intensityValues=abs(fieldValues).^2; % beamWaistEstimate=sum(intensityValues(:).*R(:))./sum(intensityValues(:)); % psf=fftshift(abs(fft2(fieldValues)).^2); psf=exp(1)^2*psf/max(psf(:)); % beamDisplacement=[1 0]; % fieldValuesDisp=fieldValues.*exp(2i*(beamDisplacement(1)*X+beamDisplacement(2)*Y)/beamWaist); % psfDisp=fftshift(abs(fft2(fieldValuesDisp)).^2); psfDisp=exp(1)^2*psfDisp/max(psfDisp(:)); % plot([psf(1+floor(end/2),:); psfDisp(1+floor(end/2),:)].') clear fieldValues; end end function Y=L(lValue,pValue,X) Y=polyval(LaguerreGen(pValue,lValue),X); end
github
mc225/Softwares_Tom-master
cztn.m
.m
Softwares_Tom-master/Utilities/cztn.m
2,206
utf_8
1d74c2d270bbf524b7787c5ba22409f1
% f=cztn(x,M,W,A,originCentered) % % Calculate the partial spectrum of x using the n-dimensional chirp z transform. % x: input matrix, centered on central pixel. Implicit zero padding will % occur at the right and will be corrected for. % M,W, and A are vectors containing the scalars corresponding to each czt % per dimension. % originCentered: boolean, default false. Indicates if the input and output % matrices have the origin in the central pixel (as defined by fftshift). % Specify, true, 'centered' or 'originCentered' to set to true. Note that A % remains the same. % % f: output matrix of size [M, size(x,length(M)+1) size(x,length(M)+2) ... size(x,ndims(x))] % function f=cztn(x,M,W,A,originCentered) if (nargin<2 || isempty(M)) M = size(x); end if (nargin<3 || isempty(W)) W = exp(-2i*pi./M); end if (nargin<4 || isempty(A)) A = 1; end if (nargin<5 || isempty(originCentered)) originCentered=false; end if (ischar(originCentered)) switch(lower(originCentered)) case 'centered' case 'centred' case 'origincentered' case 'origincentred' originCentered=true; otherwise originCentered=false; end end nbDims=length(M); % Work back to deltaRng maxFieldSpFreqInInputUnits=floor(size(x)/2); halfDeltaRng=maxFieldSpFreqInInputUnits(1:nbDims).*log(W)./(-2i*pi); % Preshift if (originCentered) A=A.*W.^(floor(M/2)); end f=x; for (dimIdx=1:nbDims) if (size(f,dimIdx)>1) f=permute(f,[dimIdx, 1:dimIdx-1, dimIdx+1:ndims(x)]); previousSize=size(f); f = czt(f(:,:),M(dimIdx),W(dimIdx),A(dimIdx)); if (originCentered) f=f.*repmat(exp(2i*pi*[0:size(f,1)-1]*halfDeltaRng(dimIdx)).',[1 size(f,2)]); %Correct the pre-shift induced phase error end f=reshape(f,[size(f,1) previousSize(2:end)]); f=ipermute(f,[dimIdx, 1:dimIdx-1, dimIdx+1:ndims(x)]); else f=repmat(f,[ones(1,dimIdx-1) M(dimIdx) ones(1,ndims(f)-dimIdx)]); end end end
github
mc225/Softwares_Tom-master
readDataCubeFromFile.m
.m
Softwares_Tom-master/Utilities/readDataCubeFromFile.m
2,366
utf_8
52abd793b918c09008c6b1a1add29de4
% [dataCube maxValue]=readDataCubeFromFile(dataSource,projectionDimensionOrSubCube,frameIndexes,normalize) % % Inputs: % dataSource: string representing the file to read as a data cube, a matfile object, or a VideoReader object. % projectionDimensionOrSubCube: integer (default []). If not empty, the indicated dimension will be returned integrated. % frameIndexes: optional list of indexes to read, use -1 to select all (default: -1: all) % normalize: boolean indicating if the output data should be normalized to the dynamic range of the input, default: true % % Outputs: % dataCube: Returns a 3D matrix with the frames of an avi file in single precision and normalized to 1 unless the normalize argument is false; % maxValue: the maximum value that could have been stored in this file. % function [dataCube maxValue]=readDataCubeFromFile(dataSource,projectionDimensionOrSubCube,frameIndexes,normalize) if (nargin<2) projectionDimensionOrSubCube=[]; end if (nargin<3) frameIndexes=-1; end if (nargin<4) normalize=true; end showProcessedInMatFile=true; if (isa(dataSource,'matlab.io.MatFile')) if (showProcessedInMatFile && isprop(dataSource,'restoredDataCube')) dataCube=dataSource.restoredDataCube(:,:,frameIndexes); else dataCube=dataSource.recordedImageStack(:,:,frameIndexes); end maxValue=max(dataCube(:)); if (normalize) dataCube=dataCube./maxValue; end else if (~ischar(dataSource)) % It must be a VideoReader object [dataCube maxValue]=readDataCubeFromAviFile(dataSource,projectionDimensionOrSubCube,frameIndexes,normalize); else fileType=lower(dataSource(max(1,end-3):end)); switch(fileType) case '.avi' [dataCube maxValue]=readDataCubeFromAviFile(dataSource,projectionDimensionOrSubCube,frameIndexes,normalize); case {'.tif','tiff'} [dataCube maxValue]=readDataCubeFromTiffFile(dataSource,projectionDimensionOrSubCube,frameIndexes,normalize); otherwise logMessage('Error: Unknown file type'); end end end if (normalize) dataCube=dataCube./maxValue; end end
github
mc225/Softwares_Tom-master
removeDefocusTiltAndPiston.m
.m
Softwares_Tom-master/Utilities/removeDefocusTiltAndPiston.m
3,424
utf_8
60ae11d38141188b1b7fcf264f6a3a71
% [pupilFunctionWithoutDefocusTiltAndPiston defocus tilt piston]=removeDefocusTiltAndPiston(pupilFunction) % % Calculates and removes the defocus, tilt, and piston from a pupil function measurement. % % pupilFunctionWithoutTilt: the input with the tilt removed % tilt: the removed tilt in units of Nyquist pixel shifts or number of waves over two whole aperture. % Divide this by size(pupilFunction) to get the shift in number of waves per pixel. % piston: the removed piston in units of wavelength. % % Output parameters: % pupilFunctionWithoutTilt: the input with the tilt removed. % defocus: the removed defocus in number of wavelengths per pixel. % tilt: the removed tilt in units of wavelengths per pixel. % piston: the removed piston in units of wavelength. % % Example: % piston=0.25; % tilt=[0.05 -0.1]; % defocus=0.004; % % [X,Y]=ndgrid([-50:50],[-55:55]); % R2=X.^2+Y.^2; % % pupilFunction=(sqrt(R2)<0.9*max(X(:))).*exp(2i*pi*piston).*exp(2i*pi*(tilt(1)*X-tilt(2)*Y + defocus*R2)); % [pupilFunctionWithoutDefocusTiltAndPiston defocus tilt piston]=removeDefocusTiltAndPiston(pupilFunction); % function [pupilFunctionWithoutDefocusTiltAndPiston defocus tilt piston]=removeDefocusTiltAndPiston(pupilFunction) if (nargin<1) % Test case [X,Y]=ndgrid([-50:50],[-55:55]); R2=X.^2+Y.^2; pupilFunction=exp(2i*pi*(0.05*X-0.1*Y + -.0004*R2))*1i.*(sqrt(R2)<0.5*max(X(:))); end inputSize=size(pupilFunction); weights=abs(pupilFunction); weightsX=weights(1:end-2,:).*weights(2:end-1,:).*weights(3:end,:); weightsY=weights(:,1:end-2).*weights(:,2:end-1).*weights(:,3:end); clear weights; RXX=[zeros(1,inputSize(2));exp(1i*diff(angle(pupilFunction),2,1)/4).*weightsX;zeros(1,inputSize(2))]; RYY=[zeros(inputSize(1),1),exp(1i*diff(angle(pupilFunction),2,2)/4).*weightsY,zeros(inputSize(1),1)]; RXXYY=RXX.*sign(RXX)+RYY.*sign(RYY); % angle mod pi meanAngle=angle(sum(RXXYY(:))); defocus=meanAngle/2/pi; [X,Y]=ndgrid([1:inputSize(1)]-1-floor(inputSize(1)/2),[1:inputSize(2)]-1-floor(inputSize(2)/2)); R2=X.^2+Y.^2; clear X Y; pupilFunctionWithoutDefocus=pupilFunction.*exp(-2i*pi*R2*defocus); [pupilFunctionWithoutDefocusTiltAndPiston tilt piston]=removeTiltAndPiston(pupilFunctionWithoutDefocus); end %% Attempt to solve this in the Fourier domain % overSamplingRate=1; % % % linearize % maxR2=max(R2(:)); % R2lin=[0:max(1,floor(sqrt(maxR2))):maxR2]; % % R2lin=[0:maxR2]; % Plin=zeros(1,length(R2lin)-1); % for RIdx=1:(length(R2lin)-1) % Plin(RIdx)=sum(pupilFunction(R2>=R2lin(RIdx) & R2<R2lin(RIdx+1))); % end % Plin(end)=Plin(end)+sum(pupilFunction(R2==R2lin(RIdx+1))); % R2lin=R2lin(1:end-1); % % Plin=Plin.*exp(-1i*angle(Plin(1))); % Remove phase offset at center % % oversample % if (overSamplingRate>1) % Plin(overSamplingRate*end)=0; % R2lin=diff(R2lin(1:2))*[0:(length(Plin)-1)]; % end % % Plin=[Plin(1:end-1), conj(Plin(end:-1:2))]; % R2lin=[R2lin(1:end-1), -R2lin(end:-1:2)]; % % [ign I]=max(abs(ifft(Plin,'symmetric'))); % defocus=-0.5/R2lin(I)/overSamplingRate; % % I=mod(I,length(Plin)/2); % % close all; % plot(fftshift(R2lin),fftshift(angle(Plin)), fftshift(R2lin),fftshift(abs(Plin))./max(abs(Plin(:)))); % I
github
mc225/Softwares_Tom-master
parsePupilEquation.m
.m
Softwares_Tom-master/Utilities/parsePupilEquation.m
4,717
utf_8
d29b1bb727f91ba713bc8c622fe0889f
% [pupilEquationFunctor argumentsUsed]=parsePupilEquation(pupilEquation,X,Y,time,lambda) % % Parses a text string that describes a pupil function into an executable % matlab function and exectutes it if X and Y are specified. % % input: % pupilEquation: A text string containing the case insensitive variable % names: "X", "Y", "Rho", "Phi", "time", and "Lambda", or shorthands % "R", "P", "t", "L" for the latter four. The t must be lower case for % now to avoid problems with backwards incompatibilities. % Only point-wise operations are allowed, hence "*" is converted to % ".*", "/" to "./", and "^" to ".^". % X and Y: optional matrixes of the same dimensions that define the carthesian % coordinates. When specified, the parsed expression is executed % at these coordinates and the resulting matrix is returned. % time and lambda: scalar values that are only required if the % parsed expression contains these variables. The time variables is % suggested to be in seconds from an initial time, and the lambda % variables is suggested to be the wavelength in meters. % % output: % If only one input argument is specified, a function handle is returned % with four input arguments: X,Y,time,lambda. These arguments are substituted % in the parsed expression, and Rho is defined as sqrt(X.^2+Y.^2), while Phi % is defined as atan2(Y,X). The arguments X and Y must be matrices of % the same dimensions, and time and lambda are scalars. % When three or more arguments are supplied to this function, then the % function handle is executed for these arguments and a matrix of the % size of X and Y is returned instead. % % The second output argument 'argumentsUsed' is a vector of booleans % that indicates of respectivelly X, Y, time, and lambda are used. % function [pupilEquationFunctor argumentsUsed]=parsePupilEquation(pupilEquation,X,Y,time,lambda) pupilEquation=strcat('(',strtrim(pupilEquation),')*1.0'); % pupilEquation(pupilEquation==unicode2native('?'))='R'; % pupilEquation(pupilEquation==unicode2native('?'))='P'; pupilEquation=regexprep(pupilEquation,'(^|[^\w])R(HO)?([^\w]|$)','$1sqrt(X.^2+Y.^2)$3','ignorecase'); pupilEquation=regexprep(pupilEquation,'(^|[^\w])time([^\w]|$)','$1time$2','ignorecase'); pupilEquation=regexprep(pupilEquation,'(^|[^\w])Th(eta)?([^\w]|$)','$1P$3','ignorecase'); pupilEquation=regexprep(pupilEquation,'(^|[^\w])(Ph|F)(i)?([^\w]|$)','$1P$4','ignorecase'); pupilEquation=regexprep(pupilEquation,'(^|[^\w])P([^\w]|$)','$1atan2(Y,X)$2'); pupilEquation=regexprep(pupilEquation,'(^|[^\w])t([^\w]|$)','$1time$2'); pupilEquation=regexprep(pupilEquation,'(^|[^\w])L(AMBDA)?([^\w]|$)','$1lambda$3','ignorecase'); pupilEquation=regexprep(pupilEquation,'([^\.])([\*/\^])','$1.$2','ignorecase');%Force all matrix operations to be element-wise. pupilEquation=regexprep(pupilEquation,'\&\&','&'); %Convert logical operators to bit operators pupilEquation=regexprep(pupilEquation,'\|\|','|'); %Convert logical operators to bit operators % Check which arguments were used argumentsUsed(1)=~isempty(regexp(pupilEquation,'[^\w\d]X[^\w\d]', 'once')); argumentsUsed(2)=~isempty(regexp(pupilEquation,'[^\w\d]Y[^\w\d]', 'once')); argumentsUsed(3)=~isempty(regexp(pupilEquation,'[^\w\d]time[^\w\d]', 'once')); argumentsUsed(4)=~isempty(regexp(pupilEquation,'[^\w\d]lambda[^\w\d]', 'once')); % Check if no X, Y would be used if (~any(argumentsUsed(1:2))) % if so make sure that no scalar is returned pupilEquation=strcat(pupilEquation,'*ones(size(X))'); end %Do some quick tests before we break the program: try pupilEquationFunctor=@(X,Y,time,lambda) eval(pupilEquation); testResult=pupilEquationFunctor([-.1 .2; -.1 .2],[-.1 -.1; .2 .2],0); catch Exc logMessage('Couldn''t parse pupil phase equation ''%s'', blocking the pupil.',pupilEquation); pupilEquationFunctor=@(X,Y,time,lambda) zeros(size(X)); argumentsUsed=[false false false false]; end % Execute the function if X and Y are specified and return a matrix instead. if (nargin>=3) if (nargin>=4 && isempty(time)) time=0; end if (nargin>=4 && isempty(lambda)) lambda=1e-6; end switch nargin case 1+2 pupilEquationFunctor=pupilEquationFunctor(X,Y); case 1+3 pupilEquationFunctor=pupilEquationFunctor(X,Y,time); otherwise pupilEquationFunctor=pupilEquationFunctor(X,Y,time,lambda); end end end
github
mc225/Softwares_Tom-master
showImage.m
.m
Softwares_Tom-master/Utilities/showImage.m
10,057
utf_8
bcb00fbdb0b3c23fc03dbaf3d31487cb
% % showImage(imageMatrix,referenceIntensity,X,Y,ax) % % imageMatrix: input intensity input between 0 and 1. % referenceIntensity: Optional argument, the imageMatrix is scaled so that % its mean intensity(clipped) is equal to referenceIntensity. If % referenceIntensity is 0, no scaling is applied, if it is -1, the image % is normalized so that the maximum value==1'. No scaling, nor checking % is done when referenceIntensity is left empty ([]), this is faster. % X,Y: Optional arguments, the pixel positions for display on the axis, otherwise the unit is one pixel % If X and Y are scalars, these parameters are used as the top left pixel indexes into an existing image or display screen. % If left empty, the default positions are consecutive integers counting from 1 upwards. % ax: optional argument, axis where to render image. By default a new % figure window is created. If ax is not an axis but an integer than this % will be interpreted as the device number on which to display the image in % full-screen. The first device is numbered 1. Use ALT-TAB followed by "closescreen()" to exit. % % Note: the image must have a dimension of at least 2 pixels in X. % % Returns a handle to the axis % % Example: % showImage(getTestImage('boats'),[],[],[],gca); % in window % showImage(getTestImage('boats'),[],[],[],2); % in full-screen 2 % DefaultScreenManager.instance().delete(); % Close all full-screens % function res=showImage(imageMatrix,referenceIntensity,X,Y,ax) % Do some input checking, and salvage the situation if possible: if (islogical(imageMatrix)) imageMatrix=single(imageMatrix); end if (~isnumeric(imageMatrix)) logMessage('Image matrix is not numeric'); return; elseif (isempty(imageMatrix)) logMessage('Image matrix is empty!'); return; elseif (~any(size(imageMatrix,3)==[1 3])) message=sprintf('The third dimension of the input imageMatrix should be either 1 or 3, not %d.',size(imageMatrix,3)); logMessage(message); error(message); else %Convert to floating point if (~isfloat(imageMatrix)) imageMatrix=double(imageMatrix)*2^-16; else if (ndims(imageMatrix)>2 || max(abs(imag(imageMatrix(:))))<10*eps(1)) %Only use the real part imageMatrix=real(imageMatrix); else if (~isreal(imageMatrix)) hue=(angle(imageMatrix)+pi)/(2*pi); hue(hue>=1)=0; imageMatrix=hsv2rgb(hue,ones(size(imageMatrix)),abs(imageMatrix)); clear hue; end end end drawingInMatlabAxes=nargin<5 || (ishandle(ax) && strcmpi(get(ax,'Type'),'axes')); if (drawingInMatlabAxes), %Bring value in range [0,1] imageMatrix(imageMatrix<0)=0; end if (nargin<2 || ~isempty(referenceIntensity)) if (nargin>1 && ~isempty(referenceIntensity)) if (referenceIntensity>0), imageMatrix = scaleToIntensity(imageMatrix,referenceIntensity); elseif (referenceIntensity<0), imageMatrix=imageMatrix/max(imageMatrix(:)); end end end %If drawing in a regular axis, limit the image matrix to [0 1] if (drawingInMatlabAxes), imageMatrix(imageMatrix(:)>1)=1; end end % Keep the input image size inputImageSize=size(imageMatrix); %Check if the offsets are specified if (nargin>=4 && ~isempty(X) && ~isempty(Y)) if ((all(size(X) == inputImageSize(1:2)) || numel(X)==inputImageSize(2)) &&... (all(size(Y) == inputImageSize(1:2)) || numel(Y)==inputImageSize(1))) rangeSpecified=true; offsetSpecified=false; %Take a matrix or a vector of axis labels. xRange=X(1,:); yRange=Y(:,1).'; if (size(xRange,2)==1) xRange=X(:).'; %Ignore vector direction end if (size(yRange,2)==1) yRange=Y(:).'; %Ignore vector direction end clear X Y; % Not needed anymore, may save much memory if these are matrices else rangeSpecified=false; if ((isscalar(X) && isscalar(Y))) offsetSpecified=true; xOffset=X; yOffset=Y; else error('Size of X and Y should match the dimensions of the input image matrix.'); end end else rangeSpecified=false; offsetSpecified=false; end %Display in current axes if none is specified. Open new window if required. if (nargin<5 || isempty(ax)) ax=gca(); end % %Check if the displayNumber could be a screen device positive integer. % if (ax>0 && abs(round(ax)-ax)<eps(ax)), %Fullscreen fullScreenManager=DefaultScreenManager.instance(); displayNumber=ax; fullScreenManager.display(displayNumber,imageMatrix,[yOffset xOffset size(imageMatrix,1) size(imageMatrix,2)]); % % All done drawing in full-screen window % else % % Displaying in a regular Matlab figure window % % Copy axes settings for later use oldTag=get(ax,'Tag'); tickDir=get(ax,'TickDir'); xAxisLocation=get(ax,'XAxisLocation'); yAxisLocation=get(ax,'YAxisLocation'); if (length(get(ax,'Children'))==1 && strcmpi(get(get(ax,'Children'),'Type'),'image')) %Recycle image object im=get(ax,'Children'); else im=image(0,'Parent',ax); %Create a new one end %Convert grayscale to true color if (ndims(imageMatrix)<3 || size(imageMatrix,3)==1), imageMatrix=repmat(imageMatrix,[1 1 3]);%Slow, replace with colormap(gray(256)); ? end try if (offsetSpecified) % Retrieve the present image cData=get(im,'CData'); oldImageSize=size(cData); if (length(oldImageSize)<3) oldImageSize(3)=1; end % Determine the size in pixels of the final image newImageSize=max(oldImageSize,size(imageMatrix)+[yOffset xOffset 0]); % Zero-extend the CData array if required if (any(oldImageSize<newImageSize)) cData(newImageSize(1),newImageSize(2),newImageSize(3))=0; end % Update the image data cData(yOffset+[1:size(imageMatrix,1)],xOffset+[1:size(imageMatrix,2)],:)=imageMatrix; else % No offset specified, replace the original image newImageSize=size(imageMatrix); cData=imageMatrix; end % Calculate the viewport limits if (rangeSpecified) if (length(xRange)~=1) halfDiffX=[diff(xRange(1:2))/2 diff(xRange(end-1:end))/2]; else halfDiffX=[0.5 0.5]; end xLim=[xRange(1)-halfDiffX(1) xRange(end)+halfDiffX(2)]; if (length(yRange)~=1) halfDiffY=[diff(yRange(1:2))/2 diff(yRange(end-1:end))/2]; else halfDiffY=[0.5 0.5]; end yLim=[yRange(1)-halfDiffY(1) yRange(end)+halfDiffY(2)]; else % Unity spaced pixels if (offsetSpecified) % Show the full image xLim=[0.5 newImageSize(2)+0.5]; yLim=[0.5 newImageSize(1)+0.5]; else % Show only the new bit xLim=[0.5 inputImageSize(2)+0.5]; yLim=[0.5 inputImageSize(1)+0.5]; end end % set the x-limits and direction if (diff(xLim)<0) set(ax,'XDir','reverse'); xLim=-xLim; else set(ax,'XDir','normal'); end set(ax,'XLim',xLim); % set the y-limits and direction if (diff(yLim)<0) set(ax,'YDir','normal'); yLim=-yLim; else set(ax,'YDir','reverse'); end set(ax,'YLim',yLim); % Copy the image data to the figure window set(im,'CData',cData); clear('cData'); % Update the axis scales if (rangeSpecified) set(im,'XData',xRange,'YData',yRange); else set(im,'XData',[1:newImageSize(2)],'YData',[1:newImageSize(1)]); end catch Exc logMessage('Error in showImage.m: Min value trueColorImageMatrix is %f, and max value is %f.',[min(imageMatrix(:)) max(imageMatrix(:))]); logMessage('error message: %s',Exc.message); drawingInMatlabAxes rethrow(Exc); end %Restore axes settings set(ax,'TickDir',tickDir); set(ax,'XAxisLocation',xAxisLocation); set(ax,'YAxisLocation',yAxisLocation); set(ax,'Tag',oldTag); axis(ax,'equal'); end if (nargout>0) res=ax; end end function adaptedImageMatrix = scaleToIntensity(imageMatrix,referenceIntensity) adaptedImageMatrix=imageMatrix*referenceIntensity/mean(imageMatrix(:)); meanImageMatrixCropped=mean(min(adaptedImageMatrix(:),1)); recropTrials=5; while abs(meanImageMatrixCropped-referenceIntensity)>.001 && recropTrials>0, recropTrials=recropTrials-1; adaptedImageMatrix=adaptedImageMatrix*referenceIntensity/meanImageMatrixCropped; meanImageMatrixCropped=mean(min(adaptedImageMatrix(:),1)); end end
github
mc225/Softwares_Tom-master
readDataCubeFromTiffFile.m
.m
Softwares_Tom-master/Utilities/readDataCubeFromTiffFile.m
3,069
utf_8
42b2b1ffb2e0511874bc46c33899b26c
% [dataCube maxValue]=readDataCubeFromTiffFile(fileName,projectionDimensionOrSubCube,frameIndexes,normalize) % % Inputs: % fileName: string representing the tiff file to read as a data cube % projectionDimensionOrSubCube: integer (default []). If not empty, the indicated dimension will be returned integrated. % frameIndexes: optional list of indexes to read, use -1 to select all (default: -1: all) % normalize: boolean indicating if the output data should be normalized to the dynamic range of the input, default: true % % Outputs: % dataCube: the 3D matrix of values % maxValue: the maximum value that could have been stored in this file. % % Returns a 3D matrix with the frames of a tiff file in single precision and normalized to 1; % function [dataCube maxValue]=readDataCubeFromTiffFile(fileName,projectionDimensionOrSubCube,frameIndexes,normalize) if (nargin<2) projectionDimensionOrSubCube=[]; end if (nargin<3) frameIndexes=-1; end frameIndexes=sort(frameIndexes); if (nargin<4 || isempty(normalize)) normalize=true; end info=imfinfo(fileName); imgSize=[info(1).Height info(1).Width]; nbFrames=length(info); maxValue=2^(info(1).BitDepth)-1; if (length(frameIndexes)==1 && frameIndexes(1)==-1) frameIndexes=[1:nbFrames]; else frameIndexes=intersect([1:nbFrames],frameIndexes); end dataCube=zeros([imgSize length(frameIndexes)],'single'); for frameIndexIdx = 1:length(frameIndexes) frameIndex=frameIndexes(frameIndexIdx); img=single(imread(fileName,'Index',frameIndex)); % (project and) store if (isempty(projectionDimensionOrSubCube)) %Complete data cube dataCube(:,:,frameIndexIdx)=img; else %Project or crop the data cube if (max(size(projectionDimensionOrSubCube))==1) %Project the full cube along one dimension specified by projectionDimensionOrSubCube if (any(projectionDimensionOrSubCube==1)) img=max(img,[],1); end if (any(projectionDimensionOrSubCube==2)) img=max(img,[],2); end if (~any(projectionDimensionOrSubCube==3)) dataCube(:,:,frameIndexIdx)=img; else dataCube(:,:,1)=dataCube(:,:,1)+img; end else %Crop to a subset of the data cube given by the matrix projectionDimensionOrSubCube. if(frameIdx>=projectionDimensionOrSubCube(3,1) && frameIdx<=projectionDimensionOrSubCube(3,2)) img=img(projectionDimensionOrSubCube(1,1):projectionDimensionOrSubCube(1,2),projectionDimensionOrSubCube(2,1):projectionDimensionOrSubCube(2,2)); dataCube(:,:,frameIndexIdx-projectionDimensionOrSubCube(3,1)+1)=img; end end end end if (normalize) dataCube=dataCube./maxValue; end end
github
mc225/Softwares_Tom-master
writeDataCubeToTiffFile.m
.m
Softwares_Tom-master/Utilities/writeDataCubeToTiffFile.m
690
utf_8
048789c54302a950922a9ca9e89235b0
% writeDataCubeToTiffFile(dataCube,fileName) % % Stores a 3D matrix with the frames of a tiff file. % % Inputs: % dataCube: a 3D matrix of real numbers between o and 1. % fileName: string representing the tiff file to read as a data cube % function writeDataCubeToTiffFile(dataCube,fileName) nbFrames=size(dataCube,3); maxValue=2^16-1; for frameIdx=1:nbFrames, img=dataCube(:,:,frameIdx); img=uint16(img*maxValue); if (frameIdx>1) writeMode='append'; else writeMode='overwrite'; end imwrite(img,fileName,'tiff',... 'Compression','deflate','WriteMode',writeMode); end end
github
mc225/Softwares_Tom-master
calcOtfGridFromSampleFrequencies.m
.m
Softwares_Tom-master/Utilities/calcOtfGridFromSampleFrequencies.m
1,260
utf_8
02bdfb7179476c8431955f1d7ab5a07d
% [XOtf,YOtf,fRel]=calcOtfGridFromSampleFrequencies(sampleFrequencies,gridSize,cutOffSpatialFrequency) % % sampleFrequencies can be specified as a scalar for both dimensions or as a vector in the order [x y]. % gridSize must thus be specified in the order [y x] instead! % % The size of the output arguments equals gridSize. % % Example: % pixelPitch=[1e-6 1e-6]; % [XOtf,YOtf]=calcOtfGridFromSampleFrequencies(1./pixelPitch,[200 200]); % or: % cutOffSpatialFrequency=5e5; % [XOtf,YOtf,fRel]=calcOtfGridFromSampleFrequencies(1./pixelPitch,[200 200],cutOffSpatialFrequency); function [XOtf,YOtf,fRel]=calcOtfGridFromSampleFrequencies(sampleFrequencies,gridSize,cutOffSpatialFrequency) logMessage('Using obsolute function calcOtfGridFromSampleFrequencies.m. This will break in future releases. Please inform Tom Vettenburg [email protected] '); if (length(gridSize)==1), gridSize(2)=gridSize(1); end otfSteps=sampleFrequencies./gridSize([2 1]); %In order [x y] rangeX=([0:gridSize(2)-1]-floor(gridSize(2)/2))*otfSteps(1); rangeY=([0:gridSize(1)-1]-floor(gridSize(1)/2))*otfSteps(2); [XOtf,YOtf]=meshgrid(rangeX,rangeY); if (nargin>2), fRel=sqrt(XOtf.^2+YOtf.^2)./cutOffSpatialFrequency; end end
github
mc225/Softwares_Tom-master
getLibraryPath.m
.m
Softwares_Tom-master/Utilities/getLibraryPath.m
209
utf_8
6d68e5c4ae2f31a57c661868930a2096
% % Returns the full path to the matlab/lib/ folder % function basePath=getLibraryPath() functionName=mfilename(); fullPath=mfilename('fullpath'); basePath=fullPath(1:end-length(functionName)); end
github
mc225/Softwares_Tom-master
ssurf.m
.m
Softwares_Tom-master/Utilities/ssurf.m
1,967
utf_8
a7e13510f9fc04ae5d4eb33b7a91c10a
% % A replacement for surf that is more friendly to use. % Data is converted to double and undersampled if required so the system stays responsive. % % Use help surf for more information % function res=ssurf(varargin) if (min(size(varargin{1}))<=1), if (length(varargin{1})>1), if nargin>1, res=plot(varargin{1},varargin{2}); else res=plot(varargin{1}); end else logMessage('A scalar value instead of a matrix was specified: %f',varargin{1}); res=varargin{1}; end if (nargout==0), clear('res'); end return; end maxPoints=128; surfSize=size(varargin{1}); X=double(varargin{1}); if (nargin>2), Y=double(varargin{2}); Z=double(varargin{3}); else Z=double(varargin{1}); [X,Y]=meshgrid([1:size(Z,2)],[1:size(Z,1)]); end if (any(size(X)~=size(Z)) || any(size(Y)~=size(Z))), logMessage('The X, Y and Z gridsizes should be identical, ignoring X and Y.'); [X,Y]=meshgrid([1:size(Z,2)],[1:size(Z,1)]); end %Load the color index or function value in C. C=double(varargin{nargin}); if(any(surfSize>maxPoints)), %Only reduce the number of points, never increase it. if (surfSize(2)>maxPoints), xStep=(X(end)-X(1))/(maxPoints-1); else xStep=X(1,2)-X(1,1); end if (surfSize(1)>maxPoints), yStep=(Y(end)-Y(1))/(maxPoints-1); else yStep=Y(2,1)-Y(1,1); end [sX,sY]=meshgrid([X(1):xStep:X(end)],[Y(1):yStep:Y(end)]); Z = interp2(X,Y,Z,sX,sY,'*linear'); C = interp2(X,Y,C,sX,sY,'*linear'); X=sX; Y=sY; end res=surf(X,Y,single(Z),C);%Convert to single precission to avoid problems with the Axis settings if (nargout==0), clear('res'); end end
github
mc225/Softwares_Tom-master
convertAviToTiff.m
.m
Softwares_Tom-master/Utilities/convertAviToTiff.m
2,053
utf_8
4298ef4a027d6e77c0b53c2bbc7f0ff4
% convertAviToTiff(aviFileName,tiffFileName) % % Converts a 3D matrix from avi 16 bit format to 16 bit tiff format (lossless compressed). % % Inputs: % aviFileName: the avi file name used as input. % tiffFileName: (optional) the output file name. % function convertAviToTiff(aviFileName,tiffFileName) if (~strcmpi(aviFileName(max(1,end-3):end),'.avi')) aviFileName=[aviFileName,'.avi']; end if (nargin<2 || isempty(tiffFileName)) tiffFileName=[aviFileName(1:end-4), '.tif']; end if (exist('VideoReader','class')) vidReader = VideoReader(aviFileName, 'tag', 'vidReader1'); % Get the data size. nbFrames = vidReader.NumberOfFrames; colorEncodingFor16bits=vidReader.BitsPerPixel==24; for frameIdx = 1:nbFrames, % Read vidFrame = read(vidReader,frameIdx); if (colorEncodingFor16bits) % 16 bit encoded in green and blue channel img = uint16(vidFrame(:,:,3))+uint16(vidFrame(:,:,2))*256; else img = uint8(mean(single(vidFrame),3)); end %Write if (frameIdx>1) writeMode='append'; else writeMode='overwrite'; end nbTrials=10; while nbTrials>0 try nbTrials=nbTrials-1; imwrite(img,tiffFileName,'tiff',... 'Compression','deflate','WriteMode',writeMode); nbTrials=0; catch Exc if (nbTrials>0) logMessage('Attempting to open file for writing.'); else logMessage('Error opening file for writing.'); end pause(1); end end end else logMessage('VideoReader class not found, Matlab version not appropriate.'); end end
github
mc225/Softwares_Tom-master
readDataCubeFromAviFile.m
.m
Softwares_Tom-master/Utilities/readDataCubeFromAviFile.m
4,227
utf_8
ddce14a073f01179ec8b320eaba40595
% [dataCube maxValue]=readDataCubeFromAviFile(fileName,projectionDimensionOrSubCube,frameIndexes,normalize) % % Inputs: % fileName: string representing the avi file to read as a data cube, or a VideoReader object. % projectionDimensionOrSubCube: integer (default []). If not empty, the indicated dimension will be returned integrated. % frameIndexes: optional list of indexes to read, use -1 to select all (default: -1: all) % normalize: boolean indicating if the output data should be normalized to the dynamic range of the input, default: true % % Outputs: % dataCube: Returns a 3D matrix with the frames of an avi file in single precision and normalized to 1 unless the normalize argument is false; % maxValue: the maximum value that could have been stored in this file. % function [dataCube maxValue]=readDataCubeFromAviFile(fileName,projectionDimensionOrSubCube,frameIndexes,normalize) if (nargin<2) projectionDimensionOrSubCube=[]; end if (nargin<3) frameIndexes=-1; end frameIndexes=sort(frameIndexes); if (nargin<4) normalize=true; end if (exist('VideoReader','class')) if (ischar(fileName)) vidReader = VideoReader(fileName, 'tag', 'vidReader1'); else vidReader=fileName; end % Get the data size. imgSize = [vidReader.Height, vidReader.Width]; nbFrames = vidReader.NumberOfFrames; if (any(frameIndexes<0)) frameIndexes=[1:nbFrames]; end frameIndexes=intersect([1:nbFrames],frameIndexes); colorEncodingFor16bits=vidReader.BitsPerPixel==24; % Create a 3D matrix from the video frames. dataCube=zeros([imgSize length(frameIndexes)],'single'); for frameIndexIdx = 1:length(frameIndexes) frameIndex=frameIndexes(frameIndexIdx); vidFrame = read(vidReader,frameIndex); if (colorEncodingFor16bits) % 16 bit encoded in green and blue channel img = single(vidFrame(:,:,3))+single(vidFrame(:,:,2))*256; else img = mean(single(vidFrame),3); end if (isempty(projectionDimensionOrSubCube)) %Complete data cube dataCube(:,:,frameIndexIdx)=img; else %Project or crop the data cube if (max(size(projectionDimensionOrSubCube))==1) %Project the full cube along one dimension specified by projectionDimensionOrSubCube if (any(projectionDimensionOrSubCube==1)) img=max(img,[],1); end if (any(projectionDimensionOrSubCube==2)) img=max(img,[],2); end if (~any(projectionDimensionOrSubCube==3)) dataCube(:,:,frameIndexIdx)=img; else dataCube(:,:,1)=dataCube(:,:,1)+img; end else %Crop to a subset of the data cube given by the matrix projectionDimensionOrSubCube. if(frameIdx>=projectionDimensionOrSubCube(3,1) && frameIdx<=projectionDimensionOrSubCube(3,2)) img=img(projectionDimensionOrSubCube(1,1):projectionDimensionOrSubCube(1,2),projectionDimensionOrSubCube(2,1):projectionDimensionOrSubCube(2,2)); dataCube(:,:,frameIndexIdx-projectionDimensionOrSubCube(3,1)+1)=img; end end end end if (ischar(fileName)) delete(vidReader); end else warning off; mov=aviread(fileName,frameIdx); warning on; colorEncodingFor16bits=false; %Convert to matrix dataCubeCellArray=struct2cell(mov); dataCubeCellArray=dataCubeCellArray(1,1,:); dataCube=cell2mat(dataCubeCellArray); clear dataCubeCellArray; end if (colorEncodingFor16bits) maxValue=2^16-1; else maxValue=2^8-1; end if (normalize) dataCube=dataCube./maxValue; end end
github
mc225/Softwares_Tom-master
saveWithTransparency.m
.m
Softwares_Tom-master/Utilities/saveWithTransparency.m
1,121
utf_8
f33aa5e70c5f09b5d230c8f66234964a
% saveWithTransparency(figHandle,fileName) % % Saves a figure as a png image with a transparency % function saveWithTransparency(figHandle,fileName) if (~strcmpi(fileName(end-3:end),'.png')) fileName=strcat(fileName,'.png'); end % save the original settings oldBackGround = get(figHandle,'Color'); invertHardCopyStatus=get(figHandle,'InvertHardCopy'); set(figHandle,'InvertHardCopy','off'); % specify an all-black background and record the image set(figHandle,'Color',[0 0 0]); print(figHandle,'-dpng','-r300',fileName); noColorImg = imread(fileName); % Specify an all-white background and record the image set(figHandle,'Color',[1 1 1]); print(figHandle,'-dpng','-r300',fileName); maxColorImg = imread(fileName); % Calculate the alpha value from the modulation alpha=maxColorImg-noColorImg; % Write the image with alpha channel imwrite(noColorImg,fileName, 'png', 'BitDepth', 16,'Alpha',1.0-double(alpha)./256); set(figHandle,'Color',oldBackGround); set(figHandle,'InvertHardCopy',invertHardCopyStatus); end
github
mc225/Softwares_Tom-master
structUnion.m
.m
Softwares_Tom-master/Utilities/structUnion.m
1,354
utf_8
daee76f53f68c07d4875ed91e5be891e
% C=structUnion(A,B) % % Combines arrays or structs A and B recursively where leafs (strings and % scalars) of B have priority. This function is useful in combination with % the loadjson function. % function C=structUnion(A,B) if (isstruct(A)) if (isstruct(B)) C=A; for (fieldName=fieldnames(B).') fieldName=fieldName{1}; fieldB=B.(fieldName); if (isfield(C,fieldName)) fieldC=structUnion(C.(fieldName),fieldB); C.(fieldName)=fieldC; else C.(fieldName)=fieldB; end end else error('incompatible with structure'); end elseif (iscell(A)) if (iscell(B)) C=A; for element=B if (isfield(C,fieldName)) fieldC=structUnion(C.(fieldName),fieldB); C.(fieldName)=fieldC; else C.(fieldName)=fieldB; end end else error('incompatible with cell array'); end elseif (isnumeric(A) || ischar(A)) if ((isnumeric(A)&&isnumeric(B)) || (isscalar(A)&&isscalar(B))) C=B; else error('incompatible leaf element'); end end end
github
mc225/Softwares_Tom-master
calcVectorialPsf.m
.m
Softwares_Tom-master/Utilities/calcVectorialPsf.m
18,363
utf_8
3651612c0d00a7d8e9750789329c0a40
% [psf, psfField, varargout]=calcVectorialPsf(xRange,yRange,zRange,wavelength,... % pupilFunctorH,pupilFunctorV,... % objectiveNumericalAperture,refractiveIndexOfSample, % objectiveMagnification,objectiveTubeLength,... % projectionDimensions) % % Calculates the 3D point spread function at the grid specified by % x/y/zRange for a pupil function given by pupilFunctorH/V(U,V) where U and V % are normalized carthesian pupil coordinates, in a medium with % refractive index refractiveIndexOfSample and an objective. The horizontal % polarization given by pupilFunctorH is along the first dimension, and the % vertical given by pupilFunctorV is along the second dimension of the % output. % % This function gives approximately the same results as PSFLab: % http://onemolecule.chem.uwm.edu/software , though it is significantly % faster. Please contact Tom Vettenburg in case you suspect discrepancies % with the theoretical or simply for more information. % % Output: % psf: the single photon intensity % psfField: the electric field components (x,y,z listed in the fourth % dimension of the matrix). For non-vectorial calculations % (pupilFunctorV==[]), this matrix is of a maximum of three % dimensions. % varargout: the higher order nonlinear intensities. This is % effectivelly the same as psf.^(N-1) unless projectionDimensions is % specified. % % Inputs: % x/y/zRange: The sample position in metric cathesian coordinates. % Singleton dimensions x and y are treated for normalization % as if they were Nyquist sampled. % wavelength: The wavelength in the same metricf units. % pupilFunctorH: A function returning the complex horizontal pupil field (along X) % as a function of carthesian coordinates normalized to the pupil radius. % When a scalar is specified, a constant field of this value is assumed for the whole circular pupil. % Default: unity transmission inside the pupil % pupilFunctorV: A function returning the complex vertical pupil field (along Y) % as a function of carthesian coordinates normalized to the pupil radius. % When a scalar is specified, a constant field of this value is assumed for the whole circular pupil. % A scalar calculation will be done instead when nothing % or the empty list is give. Specify 0 when only % horizontal input fields are required. Don't use the % empty matrix unless scalar calculations are required. % Default: []: scalar calculation. % numericalApertureInSample: (default 1.0) The objective's numerical aperture (including refractive index, n, of the medium: n*sin(theta)). % refractiveIndexOfSample: (default 1.0 for vacuum) The refractive index of the medium at the focus. % Cover slip correction is assumed in the calculation, hence % this only scales the sample grid. % objectiveMagnification: The objective magnification (default 1x) % The focal length of the objective is objectiveTubeLength/objectiveMagnification % objectiveTubeLength: The focal length of the tube lens (default: 200mm) % projectionDimensions: % -when omitted or empty ([]), the full data cube is returned % -when a vector with integers, the data is integrated along % the dimensions indicated in the vector. % Default: no projection ([]) % % Examples: % % Plot a 1D cross section through the PSF of circularly polarized beam send of wavelength 532nm, focussed by an objective with NA=0.42 in water. % xRange=[-10:.1:10]*1e-6; % psf=calcVectorialPsf(xRange,0,0,532e-9,@(U,V) 1,@(U,V) 1i,0.42,1.33); % figure(); plot(xRange*1e6,psf); % % xRange=[-10:.1:10]*1e-6;yRange=[-10:.1:10]*1e-6;zRange=[-10:.1:10]*1e-6; % objectiveNumericalAperture=asin(1./sqrt(2)); % pupilFunctor=@(U,V) sqrt(U.^2+V.^2)>.9; %Bessel beam with 10% open fraction % [psf psfField]=calcVectorialPsf(xRange,yRange,zRange,500e-9,@(U,V) pupilFunctor(U,V)/sqrt(2),@(U,V) 1i*pupilFunctor(U,V)/sqrt(2),objectiveNumericalAperture,1.0,20,200e-3); % psfProj=calcVectorialPsf(xRange,yRange,zRange,500e-9,@(U,V) pupilFunctor(U,V)/sqrt(2),@(U,V) 1i*pupilFunctor(U,V)/sqrt(2),objectiveNumericalAperture,1.0,20,200e-3,[2]); % % img=squeeze(psf(:,1+floor(end/2),:)).'; % img=img./repmat(mean(img,2),[1 size(img,2)]); % figure(); % imagesc(xRange*1e6,zRange*1e6,img);axis equal;xlabel('x [\mu m]');ylabel('z [\mu m]'); % function [psf, psfField, varargout]=calcVectorialPsf(xRange,yRange,zRange,wavelength,pupilFunctorH,pupilFunctorV,objectiveNumericalAperture,refractiveIndexOfSample,objectiveMagnification,objectiveTubeLength,projectionDimensions) if (nargin<1 || isempty(xRange)) xRange=[-5000:50:5000]*1e-9; end if (nargin<2 || isempty(yRange)) yRange=[-5000:50:5000]*1e-9; end if (nargin<3 || isempty(zRange)) zRange=[-5000:500:5000]*1e-9; end if (nargin<4 || isempty(wavelength)) wavelength=532e-9; end if (nargin<5 || isempty(pupilFunctorH)) % Don't change the following, it is a sensible default! pupilFunctorH=@(normalU,normalV) 0.0; % Along the first dimension end if (nargin<6) pupilFunctorV=[]; %Along the second dimension end if (nargin<7 || isempty(objectiveNumericalAperture)) objectiveNumericalAperture=1.0; end if (nargin<8 || isempty(refractiveIndexOfSample)) refractiveIndexOfSample=1.0; end if (nargin<9 || isempty(objectiveMagnification)) objectiveMagnification=1; end if (nargin<10 || isempty(objectiveTubeLength)) objectiveTubeLength=200e-3; end if (nargin<11) projectionDimensions=[]; end %When scalars are specified instead of function, assume constant input fields if (~isa(pupilFunctorH,'function_handle') && isscalar(pupilFunctorH)) pupilFunctorH=@(normalU,normalV) pupilFunctorH; end if (~isa(pupilFunctorV,'function_handle') && isscalar(pupilFunctorV)) pupilFunctorV=@(normalU,normalV) pupilFunctorV; end vectorialCalculation=~isempty(pupilFunctorV); if (~vectorialCalculation) logMessage('Starting a scalar calculation of the PSF...'); end % Check how many multi-photon orders of the intensity have to be calculated highestOrderIntensityRequired=max(1,nargout-1); focalLengthInSample=objectiveTubeLength/objectiveMagnification; %TODO: Check for correctness objectiveSinMaxHalfAngleInSample=objectiveNumericalAperture/refractiveIndexOfSample; % Determine the requested step size for each non-singleton dimension sampleDelta=zeros(1,3); if (length(xRange)>1), sampleDelta(1)=diff(xRange(1:2)); end if (length(yRange)>1), sampleDelta(2)=diff(yRange(1:2)); end if (length(zRange)>1), sampleDelta(3)=diff(zRange(1:2)); end minPupilSize=[1 1]*256; % To ensure that rapid pupil changes are properly sampled maxPupilSize=[1 1]*1024; % To avoid memory problems %The minimum pupil size to avoid PSF replication requiredPupilSize=2*ceil([length(xRange) length(yRange)].*sampleDelta(1:2)/(wavelength/(objectiveSinMaxHalfAngleInSample*refractiveIndexOfSample))); if (requiredPupilSize>maxPupilSize) logMessage('Limiting pupil sampling grid size to (%0.0f,%0.0f) while (%0.0f,%0.0f) would be required in principle.\nThis will cause replicas.',[maxPupilSize,requiredPupilSize]); end %Check if pupil sampling not too sparse for the defocus we intend to simulate maxSampleNA=objectiveSinMaxHalfAngleInSample*(1-0.25/(max(maxPupilSize)/2)); % Use of 'max' because the sampling rate near the edge for NA=1 diverges minPupilSizeToHandleDefocus=minPupilSize+[1 1]*max(abs(zRange/(wavelength/refractiveIndexOfSample)))*4*objectiveSinMaxHalfAngleInSample*maxSampleNA/sqrt(1-maxSampleNA^2); if (minPupilSize<minPupilSizeToHandleDefocus) logMessage('A minimum pupil size of (%0.0f,%0.0f) is required to handle the specified defocus.',minPupilSizeToHandleDefocus); requiredPupilSize=max(requiredPupilSize,minPupilSizeToHandleDefocus); end if (minPupilSizeToHandleDefocus>maxPupilSize) logMessage('Limiting pupil sampling grid size to (%0.0f,%0.0f) while (%0.0f,%0.0f) would be required in principle. This can cause artefacts.',[maxPupilSize,minPupilSizeToHandleDefocus]); end pupilSize=ceil(min(maxPupilSize,max(minPupilSize,requiredPupilSize))); logMessage('Setting the pupil sampling grid size to (%0.0f,%0.0f)',pupilSize); %Choose the pupil grid wavelengthInSample=wavelength/refractiveIndexOfSample; uRange=objectiveSinMaxHalfAngleInSample*2*[-floor(pupilSize(1)/2):floor((pupilSize(1)-1)/2)]/pupilSize(1); vRange=objectiveSinMaxHalfAngleInSample*2*[-floor(pupilSize(2)/2):floor((pupilSize(2)-1)/2)]/pupilSize(2); [U,V]=ndgrid(uRange,vRange); sinApAngle2=U.^2+V.^2; apertureFieldTransmission=double(sinApAngle2<objectiveSinMaxHalfAngleInSample^2); % apertureArea=sum(sum(double(sinApAngle2<objectiveSinMaxHalfAngleInSample^2))); apertureArea=numel(U)*pi/4; sinApAngle=sqrt(apertureFieldTransmission.*sinApAngle2); cosApAngle=apertureFieldTransmission.*sqrt(1-apertureFieldTransmission.*sinApAngle2); clear sinApAngle2; %Scale so that the total intensity is 1 for a unity uniform %illumination apertureFieldTransmission=apertureFieldTransmission./sqrt(apertureArea); pupilFunctionX=apertureFieldTransmission.*pupilFunctorH(U/objectiveSinMaxHalfAngleInSample,V/objectiveSinMaxHalfAngleInSample); if (vectorialCalculation) pupilFunctionY=apertureFieldTransmission.*pupilFunctorV(U/objectiveSinMaxHalfAngleInSample,V/objectiveSinMaxHalfAngleInSample); %Convert pupil function to polar coordinates T=atan2(V,U); CT=cos(T); ST=sin(T); pupilFunctionR = CT.*pupilFunctionX+ST.*pupilFunctionY; % Radial component is rotated by the focusing pupilFunctionA = -ST.*pupilFunctionX+CT.*pupilFunctionY; % Azimutal component is unaffected by the focusing %Calculate the polarization change due to focussing pupilFunctionZ = sinApAngle.*pupilFunctionR; pupilFunctionR = cosApAngle.*pupilFunctionR; %Convert back to carthesian coordinates pupilFunctionX = CT.*pupilFunctionR-ST.*pupilFunctionA; pupilFunctionY = ST.*pupilFunctionR+CT.*pupilFunctionA; clear pupilFunctionR pupilFunctionA CT ST T apertureFieldTransmission sinApAngle cosApAngle; pupilFunction2D=cat(3,pupilFunctionX,pupilFunctionY,pupilFunctionZ); clear pupilFunctionX pupilFunctionY pupilFunctionZ; else pupilFunction2D=pupilFunctionX; clear pupilFunctionX; end %Calculate the focal plain fields [psfField psfIntensities]=czt2andDefocus(pupilFunction2D,objectiveSinMaxHalfAngleInSample,xRange/wavelengthInSample,yRange/wavelengthInSample,zRange/wavelengthInSample, focalLengthInSample/wavelengthInSample, projectionDimensions, highestOrderIntensityRequired); % Rename the output psf=psfIntensities(:,:,:,1); if (size(psfIntensities,4)>2) varargout=mat2cell(psfIntensities(:,:,:,2:end),size(psfIntensities,1),size(psfIntensities,2),size(psfIntensities,3),ones(1,size(psfIntensities,4)-1)); else if (size(psfIntensities,4)==2) varargout={psfIntensities(:,:,:,2)}; end end clear psfIntensities; if (nargout==0) % %Store results % logMessage('Writing PSF field and intensity to disk...'); % save('VectorialPsf.mat','psf','psfField','xRange','yRange','zRange','wavelength','pupilFunctorH','pupilFunctorV','pupilFunction2D','objectiveNumericalAperture','refractiveIndexOfSample'); close all; %Display results maxNormalization=1./max(abs(psf(:))); for (zIdx=1:size(psf,3)) subplot(2,2,1); showImage(psf(:,:,zIdx).'.*maxNormalization,[],xRange*1e6,yRange*1e6); title(sprintf('Total intensity for z=%0.3f \\mu m',zRange(zIdx)*1e6)); xlabel('x [\mu m]'); ylabel('y [\mu m]'); subplot(2,2,2); showImage(psfField(:,:,zIdx,3).',-1,xRange*1e6,yRange*1e6); title(sprintf('Ez for z=%0.3f \\mu m',zRange(zIdx)*1e6)) xlabel('x [\mu m]'); ylabel('y [\mu m]'); subplot(2,2,3); showImage(psfField(:,:,zIdx,1).',-1,xRange*1e6,yRange*1e6); title(sprintf('Ex for z=%0.3f \\mu m',zRange(zIdx)*1e6)) xlabel('x [\mu m]'); ylabel('y [\mu m]'); subplot(2,2,4); showImage(psfField(:,:,zIdx,2).',-1,xRange*1e6,yRange*1e6); title(sprintf('Ey for z=%0.3f \\mu m',zRange(zIdx)*1e6)) xlabel('x [\mu m]'); ylabel('y [\mu m]'); drawnow(); logMessage('Total intensity = %0.3f%%',100*sum(sum(psf(:,:,zIdx)))); pause(1/30); end clear psf; % Don't litter on the command prompt end end % Calculate the partial spectrum of x using the chirp z transform. % This returns the complex field. % % x is the pupil and should not be ifftshifted, implicit zero padding to the right! % objectiveSinMaxHalfAngleInSample: the input matrix must cover this disk exactly. % the following arguments, also specifyable as a list, are: % nxRange and nyRange: the sample points in the units of wavelength in the sample medium. % nzRange: the sample points in the z dimension in units of wavelength in the sample. % nfocalLengthInSample: (optional, default infinite) The focal length specified in units of wavelength. % projectionDimensions: (optional, default none) The dimension along which an integration is done % highestOrderIntensityRequired: (optional, default depends on nargout) If specified, (higher order) intensities upto this number are returned as well. % % If more than one output argument is specified, the first and higher order % intensities will be returned as 3D arrays stacked into a single 4D array. % function [f, psfIntensities]=czt2andDefocus(x,objectiveSinMaxHalfAngleInSample,nxRange,nyRange,nzRange, nfocalLengthInSample, projectionDimensions, highestOrderIntensityRequired) if (nargin<6 || isempty(nfocalLengthInSample)) nfocalLengthInSample=Inf; %Assuming that focusLength >> z end if (nargin<7) projectionDimensions=[]; end if (nargin<8) highestOrderIntensityRequired=max(0,nargout-1); end %Prepare the output matrix with zeros inputSize=size(x); %inputSize=x(1)*0+inputSize;%Cast to same class as the x input outputSize=[length(nxRange) length(nyRange) length(nzRange), inputSize(3:end)]; % Add dimension if (~isempty(projectionDimensions)) outputSize(projectionDimensions)=1; end f=zeros(outputSize,class(x)); psfIntensities=zeros([outputSize(1:3) highestOrderIntensityRequired],class(x)); uRange=objectiveSinMaxHalfAngleInSample*2*[-floor(inputSize(1)/2):floor((inputSize(1)-1)/2)]/inputSize(1); vRange=objectiveSinMaxHalfAngleInSample*2*[-floor(inputSize(2)/2):floor((inputSize(2)-1)/2)]/inputSize(2); [U,V]=ndgrid(uRange,vRange); R2=min(1.0,U.^2+V.^2); clear U V; cosHalfAngleInSampleMatrix=sqrt(1-R2); clear R2; if (isinf(nfocalLengthInSample)) unityDefocusInRad=2*pi*(cosHalfAngleInSampleMatrix-1); %Assuming that focalLength >> z end %Loop through the z-stack for zIdx=1:length(nzRange) normalizedZ=nzRange(zIdx); phaseOffsetOfAxialWaveletInRad=2*pi*mod(normalizedZ,1); %Center on focal point % Calculate the phase delay due to z-displacement with respect to % the wavelet leaving the center of the pupil. This causes the Gouy % phase shift. if (~isinf(nfocalLengthInSample)) % Geometrical difference between the axial and the off-axis ray relativeDefocusPhaseDelayAcrossPupilInRad=2*pi*(... sqrt(nfocalLengthInSample^2+2*nfocalLengthInSample*cosHalfAngleInSampleMatrix*normalizedZ+normalizedZ^2)... -(nfocalLengthInSample+normalizedZ)... ); else % Approximate the above equation for nfocalLengthInSample >> normalizedZ relativeDefocusPhaseDelayAcrossPupilInRad=normalizedZ*unityDefocusInRad; end pupil=x.*repmat(exp(1i*(phaseOffsetOfAxialWaveletInRad+relativeDefocusPhaseDelayAcrossPupilInRad)),[1 1 inputSize(3:end)]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% psfSlice=czt2fromRanges(pupil,nxRange*2*objectiveSinMaxHalfAngleInSample,nyRange*2*objectiveSinMaxHalfAngleInSample); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Project the output before continuing to save memory psfSliceIntensity=sum(abs(psfSlice).^2,3); psfSliceIntensity=repmat(psfSliceIntensity,[1 1 highestOrderIntensityRequired]); for (photonNb=1:highestOrderIntensityRequired) psfSliceIntensity(:,:,photonNb)=psfSliceIntensity(:,:,photonNb).^photonNb; end if (~isempty(projectionDimensions)) for (projIdx=1:size(projectionDimensions,2)) projectionDimension=projectionDimensions(projIdx); if (projectionDimension>=3) projectionDimension=projectionDimension-1; end psfSlice=sum(psfSlice,projectionDimension); psfSliceIntensity=sum(psfSliceIntensity,projectionDimension); end end if (any(projectionDimensions==3)) f(:,:,1,:)=f(:,:,1,:)+psfSlice; psfIntensities(:,:,1,:)=psfIntensities(:,:,1,:)+psfSliceIntensity; else f(:,:,zIdx,:)=psfSlice; psfIntensities(:,:,zIdx,:)=psfSliceIntensity; end end % of for loop over zIdx end
github
mc225/Softwares_Tom-master
zernikeDecomposition.m
.m
Softwares_Tom-master/Utilities/fitting/zernike/zernikeDecomposition.m
1,046
utf_8
f738c4549c3e2e49d209c22147fbfcf7
% coefficients=zernikeDecomposition(X,Y,Z,maxTerms) % % X, Y and Z should be matrices of real numbers. % % Returns: % coefficients: the vector of standard zernike coefficients, the first of % which are: piston, % tip(x),tilt(y), % defocus, astigmatism-diag,astigmatism-x, % coma-y,coma-x, trefoil-y,trefoil-x, % spherical aberration % where the postscripts indicate the position of the extreme % value on the pupil edge. % % % See also: zernikeComposition.m, and zernike.m % function coefficients=zernikeDecomposition(X,Y,Z,maxTerms) R=sqrt(X.^2+Y.^2); T=atan2(Y,X); invalidPoints=any(isnan(Z(R<=1))); for j=1:maxTerms, currZernike=zernike(j,R,T); if (invalidPoints || j==1), normalization=sum(currZernike(~isnan(Z)).^2); end coefficients(j)=sum(Z(~isnan(Z)).*currZernike(~isnan(Z)))./normalization; end end
github
mc225/Softwares_Tom-master
zernikeLinearCombination.m
.m
Softwares_Tom-master/Utilities/fitting/zernike/zernikeLinearCombination.m
1,130
utf_8
47a385416ec7957becff51b2eff49675
%The real part of the coefficients are for the even polynomials, %the imaginary part of the coefficients are for the odd polynomials function result=zernikeLinearCombination(coefficients,X,Y) result=zeros(size(X)); [M,N]=getMNFromCoeffiecientUpToIndex(length(coefficients)); for index=1:length(coefficients) if (abs(coefficients(index))>0) subResult=zernike(M(index),N(index),sqrt(X.^2+Y.^2),atan2(Y,X)); result=result + real(subResult)*real(coefficients(index)) + imag(subResult)*imag(coefficients(index)); end end end % n>=m>=0 and n-m even % Not the official order, but: % (m,n) = (0,0) (1,1) (0,2) (1,1) (1,3) (2,2) (0,4) (1,3) (2,2) (1,5) (2,4) % (3,3) (0,6) (1,5) (2,4) (3,3) (1,7) (2,6) (3,5) (4,4) function [M,N]=getMNFromCoeffiecientUpToIndex(coeffIndex) M=[]; N=[]; l=0; m=0; n=0; for index=1:coeffIndex-1, M(end+1)=m; N(end+1)=n; if (m<n) m=m+1; n=n-1; else l=l+1; n=l; m=mod(n,2); end end M(end+1)=m; N(end+1)=n; end
github
mc225/Softwares_Tom-master
zernike.m
.m
Softwares_Tom-master/Utilities/fitting/zernike/zernike.m
2,529
utf_8
50e1fc9b5c8f7291e2f166ed02d82743
% % WARNING: returns two complementary zernike polynomials at the same time as a complex function! % % result=zernike(m,n,rho,theta) % For m>=0, returns the even Zernike polynomial(cos) value as the real part, % and the odd polynomial(sin) value as the imaginary part. For m<0, the odd % Zernike value is returned as the real part, and the even is returned % as the imaginary part. % % result=zernike(j,rho,theta) % Returns the Zernike polynomial with standard coefficient j % "Zernike polynomials and atmospheric turbulence", Robert J. Noll, % JOSA, Vol. 66, Issue 3, pp. 207-211, doi:10.1364/JOSA.66.000207 % The first of which are: piston, % tip(x),tilt(y), % defocus, astigmatism-diag,astigmatism-x, % coma-y,coma-x, trefoil-y,trefoil-x, % spherical aberration % where the postscripts indicate the position of the extreme % value on the pupil edge. % %This function can handle rho and theta vectors but not m and n vectors. % % % Example: % grid=[64 64]; % uRange=-1:(2/(grid(2)-1)):1; % vRange=-1:(2/(grid(1)-1)):1; % [X,Y]=meshgrid(uRange,vRange); % R=sqrt(X.^2+Y.^2); % T=atan2(Y,X); % ssurf(zernike(4,R,T)); function result=zernike(m,n,rho,theta) if (nargin<4), theta=rho; rho=n; j=m;%Standard Zernike coefficient number: n=ceil((sqrt(1+8*j)-1)/2)-1; m=j-n*(n+1)/2-1; m=m+mod(n+m,2); end normalization=sqrt((2*(n+1)/(1+(m==0))));%Make orthonormal basis on unit disk (for 2-unit square, multiply with 4/pi) result=normalization*zernikeR(abs(m),n,rho).*exp(1i*abs(m)*theta); if (nargin<4), if (m==0 || mod(j,2)==0),%The first column's coefficients don't have sine or cosine result=real(result); else result=imag(result); end end if (m<0), result=conj(result)*1i; end end function result=zernikeR(m,n,rho) result=0; if (mod(n-m,2)==0), rhoPow=(rho<=1).*rho.^m; rhoSqd=(rho<=1).*rho.*rho; for l=((n-m)/2):-1:0, subResult=(((-1)^l)*faculty(n-l))/(faculty(l)*faculty((n+m)/2-l)*faculty((n-m)/2-l)); %For speedup: rhoPow=rho.^(n-2*l); subResult=subResult .* rhoPow; result=result+subResult; rhoPow=rhoPow.*rhoSqd; end end end function result=faculty(n) result=gamma(n+1); end
github
mc225/Softwares_Tom-master
zernikeComposition.m
.m
Softwares_Tom-master/Utilities/fitting/zernike/zernikeComposition.m
1,051
utf_8
4405071dfaf5ba4078800f64d46e9cc2
% Z=zernikeComposition(X,Y,coefficients) % % X and Y should be matrices of real numbers. % coefficients: the vector of standard zernike coefficients, the first of % which are: piston, % tip(x),tilt(y), % defocus, astigmatism-diag,astigmatism-x, % coma-y,coma-x, trefoil-y,trefoil-x, % spherical aberration % where the postscripts indicate the position of the extreme % value on the pupil edge. % % See also: zernikeDecomposition.m, and zernike.m % function Z=zernikeComposition(X,Y,coefficients) Z=zeros(size(X)); R=sqrt(X.^2+Y.^2); T=atan2(Y,X); for j=1:length(coefficients), currZernike=zernike(j,R,T); if (j==1), % normalization=sum(currZernike(:).^2); % coefficients=coefficients./normalization;% already normalized analytically for a rectangular grid fitted around the pupil end Z=Z+coefficients(j)*currZernike; end end
github
mc225/Softwares_Tom-master
redHotColorMap.m
.m
Softwares_Tom-master/Utilities/colormap/redHotColorMap.m
515
utf_8
b2a64149ce5f0f2b5893b511cdcfbf6f
% RGB=redHotColorMap(nbEntries) % % Creates a color map to be used with the command colormap % All arguments are optional. % % Example usage: % figure; % image([0:.001:1]*256); % colormap(redHotColorMap(256)) function RGB=redHotColorMap(nbEntries) if (nargin<1 || isempty(nbEntries)) nbEntries=64; end colors=[1 1 1; 1 1 0; 1 0 0; 0 0 0]; % colorPositions=[0 .375 .75 1]; colorPositions=[0 .375 .625 .95]; RGB=interpolatedColorMap(nbEntries,colors,colorPositions); end
github
mc225/Softwares_Tom-master
spectrumToRGB.m
.m
Softwares_Tom-master/Utilities/colormap/spectrumToRGB.m
7,556
utf_8
ec4f544f967641c392792e9cb31e9976
% RGB=spectrumToRGB(wavelengths,wavelengthIntensities,constrainValues) % % Returns the red green and blue component to simulate a given spectrum. % The number of dimensions of the returned matrix is equal to that of the % wavelengthIntensities argument, and the dimensions are the same except % for the last dimension which is always three. % % wavelengths can be a vector of wavelengths or a function handle returning the intensity for a given wavelength, in the latter case the argument wavelengthIntensities is ignored. % If wavelengthIntensities is a matrix, its last dimension should equal the number of wavelengths. % % constrainValues (optional, default=true): a boolean to indicate if negative RGB values should be de-saturated to be non-negative % function RGB=spectrumToRGB(wavelengths,wavelengthIntensities,constrainValues) if (nargin<1 || isempty(wavelengths)) wavelengths=532e-9; %Nd-YAG, frequency-doubled % wavelengths=632.8e-9; %He-Ne wavelengths=1e-9*[300:800]; end % From John Walker's http://www.fourmilab.ch/documents/specrend/specrend.c wavelengthsXYZTable=[380:5:780]*1e-9; if (isa(wavelengths,'function_handle')) wavelengthIntensities=wavelengths(wavelengthsXYZTable); wavelengths=wavelengthsXYZTable; else if (nargin>=1) if (nargin<2 || isempty(wavelengthIntensities)) wavelengthIntensities=ones(size(wavelengths)); end else wavelengthIntensities=permute(eye(length(wavelengths)),[3 1 2]); end end if (nargin<3 || isempty(constrainValues)) constrainValues=true; end wavelengths=wavelengths(:); inputSize=size(wavelengthIntensities); nbWavelengths=numel(wavelengths); if (nbWavelengths==1 && inputSize(end)~=1) inputSize(end+1)=1; end wavelengthIntensities=reshape(wavelengthIntensities,[],nbWavelengths).'; if (nbWavelengths~=inputSize(end)) logMessage('spectrumToRGB Error: the number of wavelengths should be equal to the last dimension of the second argument.'); return; end % Define Color Systems % %White point chromaticities IlluminantC = [0.3101, 0.3162]; % For NTSC television IlluminantD65 = [0.3127, 0.3291]; % For EBU and SMPTE IlluminantE = [0.33333333, 0.33333333]; % CIE equal-energy illuminant % Gamma of nonlinear correction. See Charles Poynton's ColorFAQ Item 45 and GammaFAQ Item 6 at: http://www.poynton.com/ColorFAQ.html and http://www.poynton.com/GammaFAQ.html GAMMA_REC709=0; % Rec. 709 NTSC=struct('RGB',[0.67,0.33; 0.21,0.71; 0.14,0.08].','WhitePoint',IlluminantC,'Gamma',GAMMA_REC709); EBU=struct('RGB',[0.64,0.33;0.29,0.60;0.15,0.06].','WhitePoint',IlluminantD65,'Gamma',GAMMA_REC709); % PAL/SECAM SMPTE=struct('RGB',[0.630,0.340;0.310,0.595;0.155,0.070].','WhitePoint',IlluminantD65,'Gamma',GAMMA_REC709); HDTV=struct('RGB',[0.670,0.330;0.210,0.710;0.150,0.060].','WhitePoint',IlluminantD65,'Gamma',GAMMA_REC709); CIE=struct('RGB',[0.7355,0.2645;0.2658,0.7243;0.1669,0.0085].','WhitePoint',IlluminantE,'Gamma',GAMMA_REC709); CIERec709=struct('RGB',[0.64,0.33;0.30,0.60;0.15,0.06].','WhitePoint',IlluminantD65,'Gamma',GAMMA_REC709); %Pick this color system: colorSystem=SMPTE; % From John Walker's http://www.fourmilab.ch/documents/specrend/specrend.c XYZTable=[0.0014,0.0000,0.0065; 0.0022,0.0001,0.0105; 0.0042,0.0001,0.0201; ... 0.0076,0.0002,0.0362; 0.0143,0.0004,0.0679; 0.0232,0.0006,0.1102; ... 0.0435,0.0012,0.2074; 0.0776,0.0022,0.3713; 0.1344,0.0040,0.6456; ... 0.2148,0.0073,1.0391; 0.2839,0.0116,1.3856; 0.3285,0.0168,1.6230; ... 0.3483,0.0230,1.7471; 0.3481,0.0298,1.7826; 0.3362,0.0380,1.7721; ... 0.3187,0.0480,1.7441; 0.2908,0.0600,1.6692; 0.2511,0.0739,1.5281; ... 0.1954,0.0910,1.2876; 0.1421,0.1126,1.0419; 0.0956,0.1390,0.8130; ... 0.0580,0.1693,0.6162; 0.0320,0.2080,0.4652; 0.0147,0.2586,0.3533; ... 0.0049,0.3230,0.2720; 0.0024,0.4073,0.2123; 0.0093,0.5030,0.1582; ... 0.0291,0.6082,0.1117; 0.0633,0.7100,0.0782; 0.1096,0.7932,0.0573; ... 0.1655,0.8620,0.0422; 0.2257,0.9149,0.0298; 0.2904,0.9540,0.0203; ... 0.3597,0.9803,0.0134; 0.4334,0.9950,0.0087; 0.5121,1.0000,0.0057; ... 0.5945,0.9950,0.0039; 0.6784,0.9786,0.0027; 0.7621,0.9520,0.0021; ... 0.8425,0.9154,0.0018; 0.9163,0.8700,0.0017; 0.9786,0.8163,0.0014; ... 1.0263,0.7570,0.0011; 1.0567,0.6949,0.0010; 1.0622,0.6310,0.0008; ... 1.0456,0.5668,0.0006; 1.0026,0.5030,0.0003; 0.9384,0.4412,0.0002; ... 0.8544,0.3810,0.0002; 0.7514,0.3210,0.0001; 0.6424,0.2650,0.0000; ... 0.5419,0.2170,0.0000; 0.4479,0.1750,0.0000; 0.3608,0.1382,0.0000; ... 0.2835,0.1070,0.0000; 0.2187,0.0816,0.0000; 0.1649,0.0610,0.0000; ... 0.1212,0.0446,0.0000; 0.0874,0.0320,0.0000; 0.0636,0.0232,0.0000; ... 0.0468,0.0170,0.0000; 0.0329,0.0119,0.0000; 0.0227,0.0082,0.0000; ... 0.0158,0.0057,0.0000; 0.0114,0.0041,0.0000; 0.0081,0.0029,0.0000; ... 0.0058,0.0021,0.0000; 0.0041,0.0015,0.0000; 0.0029,0.0010,0.0000; ... 0.0020,0.0007,0.0000; 0.0014,0.0005,0.0000; 0.0010,0.0004,0.0000; ... 0.0007,0.0002,0.0000; 0.0005,0.0002,0.0000; 0.0003,0.0001,0.0000; ... 0.0002,0.0001,0.0000; 0.0002,0.0001,0.0000; 0.0001,0.0000,0.0000; ... 0.0001,0.0000,0.0000; 0.0001,0.0000,0.0000; 0.0000,0.0000,0.0000]; XYZPerWavelength=interp1(wavelengthsXYZTable,XYZTable,wavelengths,'cubic',0).'; %XYZ in rows XYZ=XYZPerWavelength*wavelengthIntensities; % XYZ in rows, data points in columns XYZ=XYZ./repmat(max(eps(1),sum(XYZ,1)),[3 1]); % Transform XYZ coordinate system to RGB coordinate system XYZRGBTransformMatrix=cat(2,colorSystem.RGB.',1-sum(colorSystem.RGB.',2)); %XYZ in columns whitePoint=[colorSystem.WhitePoint 1-sum(colorSystem.WhitePoint)]; %XYZ in columns RGBXYZTransformMatrix=cross(XYZRGBTransformMatrix(:,[2 3 1]),XYZRGBTransformMatrix(:,[3 1 2])); %RGB in columns whitePointRGB=whitePoint*RGBXYZTransformMatrix/whitePoint(2); RGBXYZTransformMatrix=RGBXYZTransformMatrix./repmat(whitePointRGB,[3 1]); RGB=RGBXYZTransformMatrix*XYZ; % RGB in rows, data points in columns if (constrainValues) %Constrain RGB to non-negative values approximated=min(RGB,[],1)<0; RGB = RGB-repmat(min(0,min(RGB,[],1)),[3 1]); else approximated=false; end %Adjust to intensity of input (TODO, probably needs to be log.-scaled) RGB=RGB.*repmat(sum(wavelengthIntensities,1),[3 1]); RGB=reshape(RGB.',[inputSize(1:end-1) 3]); %Display if (nargout==0 && ndims(RGB)>=3) RGB=RGB./max(eps(1),max(RGB(:))); %Make sure that it can be displayed as a color. RGB=max(0,RGB); figure; % axis off; image(wavelengths*1e9,1,RGB); xlabel('\lambda [nm]','Interpreter','Tex'); if (any(approximated)) logMessage('Approximated %u%% of the colors!',round(100*mean(approximated))); end clear RGB; end end
github
mc225/Softwares_Tom-master
colorMapCizmarHighContrastPrint.m
.m
Softwares_Tom-master/Utilities/colormap/colorMapCizmarHighContrastPrint.m
691
utf_8
51dc78f7fc8819ec4d10e0fab6a8bc5f
% RGB=colorMapCizmarHighContrastPrint(nbEntries) % % Based on Tomas' colormap for producing good contrast black and white printouts. % Creates a color map to be used with the command colormap. % All arguments are optional. % % Example usage: % figure; % image([0:.001:1]*256); % colormap(colorMapCizmarHighContrastPrint(256)) function RGB = colorMapCizmarHighContrastPrint(nbEntries) if (nargin<1 || isempty(nbEntries)) nbEntries=64; end RGB=interpolatedColorMap(nbEntries,[0 0 .3; .7 0 .3; .7 1 .3; .7 1 1],[0 .292 .708 1]); end % levs=levs(:,1); % t=[min(2.4*levs,.7),levs,max(2.4*levs-1.4,.3)]; % t(:,2)=2.4*t(:,2)+.3-t(:,1)-t(:,3); % t=max(0,min(1,t));
github
mc225/Softwares_Tom-master
mapColor.m
.m
Softwares_Tom-master/Utilities/colormap/mapColor.m
1,206
utf_8
ecc38ab53fb4a290e9d884eaa8562c56
% imgRGB=mapColor(img,colorMap) % % Converts a gray scale image with values between zero and 1 to an RGB % image using a color map. % % Input parameters: % img: a two dimensional matrix of intensity values, either uint16, % uint8, or values between 0 and 1. % colorMap: a function handle with one input argument, the intensity, % or a matrix with three values per row (Red, Green, or Blue), % and one row per uniformely-spaced intensity. % % Output: a three-dimensional matrix of floating point values between 0 and % one, the third dimension indicating the color channel (Red, Green % , or Blue). function imgRGB=mapColor(img,colorMap) if (isa(colorMap,'function_handle')) colorMap=colorMap(4096); end if (isinteger(img)) switch class(img) case 'uint16' img=double(img)./(2^16-1); otherwise %Assume 8 bit img=double(img)./(2^8-1); end end nbColors=size(colorMap,1); img=1+floor(nbColors*img); img=min(max(1,img),nbColors); imgRGB=reshape(cat(3,colorMap(img,1),colorMap(img,2),colorMap(img,3)),[size(img) 3]); end
github
mc225/Softwares_Tom-master
interpolatedColorMap.m
.m
Softwares_Tom-master/Utilities/colormap/interpolatedColorMap.m
1,053
utf_8
ed6b33a97012a75c4a3573a488662222
% RGB=interpolatedColorMap(nbEntries,colors,colorPositions) % % Creates a color map to be used with the command colormap % All arguments are optional. % % Example usage: % figure; % image([0:.001:1]*256); % colormap(interpolatedColorMap(256,[0 .3 0; .7 .3 0; .7 .3 1; .7 1 1],[0 .3 .75 1])) function RGB=interpolatedColorMap(nbEntries,colors,colorPositions) if (nargin<1 || isempty(nbEntries)) nbEntries=64; end if (nargin<2 || isempty(colors)) if (nargin<3 || isempty(colorPositions)) colors=([1:length(colorPositions)]-1)/(length(colorPositions)-1); else colors=[0 0 0; 1 1 1]; end end if (nargin<3 || isempty(colorPositions)) colorPositions=[0:1/(size(colors,1)-1):1]; end [colorPositions sortI]=sort(colorPositions); colors=colors(sortI,:); fraction=([1:nbEntries]-1)/max(1,nbEntries-1); RGB=interp1q(colorPositions.',colors,max(min(fraction.',colorPositions(end)),colorPositions(1))); RGB=min(1,max(0,RGB)); end
github
mc225/Softwares_Tom-master
examplePartionedSLM.m
.m
Softwares_Tom-master/Examples/examplePartionedSLM.m
1,632
utf_8
4921f6ad0931333ac6bbc1cc58bf65e1
% % examplePartionedSLM() % % This example shows how to create two SLM objects that use each a separate part of the same SLM. % Both parts have different first order deflections and behave entirely independent. % This method may be used to build a set-up with two spatial light modulators using only one physical device. % Applications include: % * horizontal and vertical polarization modulation % * dispersion corrected modulation of short pulses % function examplePartionedSLM() close all; displayNumber=[]; %Set to [] to test with a Matlab window, or 2 to test with screen 2 %Create a fake screen for testing if displayNumber==[] if (isempty(displayNumber)) hFig=figure(); displayNumber=axes('Parent',hFig); image(zeros(600,800),'Parent',displayNumber); end %Create three SLM objects that use the same output device leftSLM=PhaseSLM(displayNumber,[1/10 1/10]); leftSLM.regionOfInterest=leftSLM.regionOfInterest.*[1 1 1 0.5]; leftSLM.stabilizationTime=0.0; %don't keep us waiting rightSLM=PhaseSLM(displayNumber,[-1/10 -1/10]); rightSLM.regionOfInterest=rightSLM.regionOfInterest.*[0 0 1 0.5]+[0 0.5*rightSLM.regionOfInterest(4) 0 0]; rightSLM.stabilizationTime=0.0; %don't keep us waiting %Modulate both parts of the SLM separately for innerRadius=[0:10:190], leftSLM.modulate(parsePupilEquation('R<200'); rightSLM.modulate(parsePupilEquation(sprintf('R<200 & R>%f',innerRadius)); end % Close everything again pause(5); close all; DefaultScreenManager.instance.delete(); % Close all full-screens end
github
mc225/Softwares_Tom-master
calcCorrectionFromPupilFunction.m
.m
Softwares_Tom-master/AberrationMeasurement/calcCorrectionFromPupilFunction.m
1,309
utf_8
035663d622768e77fa8cfe3fa093b48f
% pupilFunctionCorrection=calcCorrectionFromPupilFunction(measuredPupilFunction,amplificationLimit) % % Calculates the complex value that the SLM has to modulate to counteract % the aberration specified in measuredPupilFunction. The argument will thus % be the inverse, and the amplitude will approximatelly be the reciprocal, % however the signal reduction is limited by amplificationLimit to avoid % blocking large parts of the pupil when it is illuminated unevenly. % % measuredPupilFunction: a complex matrix with the to-be-corrected % aberration at each SLM pixel % amplificationLimit: The maximum dynamic range of the amplitude % modulation. An N-fold amplification of some parts of the pupil means % that part of the pupil has to be suppressed N-fold. To avoid low % signal this can be limited. (default: 10) function pupilFunctionCorrection=calcCorrectionFromPupilFunction(measuredPupilFunction,amplificationLimit) if (nargin<2 || isempty(amplificationLimit)) amplificationLimit=10; end measuredPupilFunction=amplificationLimit*measuredPupilFunction./max(abs(measuredPupilFunction(:))); pupilAmplitude=max(1,abs(measuredPupilFunction)); pupilPhase=angle(measuredPupilFunction); pupilFunctionCorrection=exp(-1i*pupilPhase)./pupilAmplitude; end
github
mc225/Softwares_Tom-master
aberrationMeasurementZernikeWavefront.m
.m
Softwares_Tom-master/AberrationMeasurement/aberrationMeasurementZernikeWavefront.m
8,697
utf_8
2042ae8413cb1ccd1e075fdf5be47ce2
% [measuredPupilFunction zernikeCoefficients Rho Phi]=aberrationMeasurementZernikeWavefront(slm,selectedZernikeCoefficientIndexes,probeFunctor,progressFunctor) % % Determines the aberration by tweaking the low-order Zernike terms, hence it cannot correct for amplitude modulations % % Input: % slm: An SLM object % selectedZernikeCoefficientIndexes: the indexes of the standard Zernike polynomials to probe. % probeFunctor: a function that returns the probe value, it optionally takes as argument the complex field at each pixel of the SLM % progressFunctor: When specified, this function will be executed every spatial frequency probe, it takes as optional arguments: % - fractionDone: the completion ratio % - currentPupilFunctionEstimate: the complex matrix with the current estimate of the pupil function % % Returns: % measuredPupilFunction: the complex matrix with the estimate of the aberrated pupil function % zernikeCoefficients: the standard Zernik coefficients of the measured aberration. % Rho: the radial coordinate % Phi: the azimutal coordinate % % Example: % slmSize=[20 20]; % [rows cols] % referenceDeflectionFrequency=[1/4 1/4]; % slm=PhaseSLM(2,referenceDeflectionFrequency,[0 0 slmSize]); % modulationFunctor=@(fieldModulationAtPupil) pause(1/30); % %Using: % function psf=calcPsf(fieldModulationAtPupil) % imgSize=size(fieldModulationAtPupil); % [X,Y]=meshgrid([1:imgSize(2)],[1:imgSize(1)]); % R2=((X-imgSize(2)/2).^2+(Y-imgSize(1)/2).^2)./(min(imgSize)/2/2).^2; % aperture=R2<1; % aperture=aperture.*exp(2*2i*pi*R2); % fieldPsf=fftshift(fft2(ifftshift(fieldModulationAtPupil.*aperture))); % psf=abs(fieldPsf).^2; % end % function value=simulateDetection(img,pos) % value=img(pos(1),pos(2))*(1+0.05*randn()); % end % probeFunctor=@(fieldModulationAtPupil) simulateDetection(calcPsf(fieldModulationAtPupil),[5 5]); % % selectedZernikeCoefficientIndexes=[1 2 3 4 5 6 7 8 9 10 11]; % piston, % tip(x),tilt(y), defocus, astigmatism-diag,astigmatism-x, % coma-y,coma-x, trefoil-y,trefoil-x, spherical % % measuredPupilFunction=aberrationMeasurementZernikeWavefront(slm,selectedZernikeCoefficientIndexes,probeFunctor) % function [measuredPupilFunction zernikeCoefficients X Y Rho Phi]=aberrationMeasurementZernikeWavefront(slm,selectedZernikeCoefficientIndexes,probeFunctor,progressFunctor,referenceAberration) if (nargin<1) close all; figure(); image(zeros(600,800)); displayNumber=gca(); referenceDeflectionFrequency=[1 1]/10; slm=PhaseSLM(displayNumber,referenceDeflectionFrequency); slm.stabilizationTime=0.01; end if (nargin<2) selectedZernikeCoefficientIndexes=[2 3 4]; % tip,tilt, and defocus only end slmSize=slm.regionOfInterest(3:4); if (nargin<3) probePos=1+floor(slmSize./2); probeFunctor=@(fieldModulationAtPupil) simulateDetection(calcPsf(fieldModulationAtPupil),probePos); end if (nargin<4) progressFunctor=@(fractionDone,currentPupilFunctionEstimate) progressFunction(fractionDone,currentPupilFunctionEstimate); end [X,Y]=meshgrid([1:slmSize(2)]-floor(slmSize(2)/2)-1,[1:slmSize(1)]-floor(slmSize(1)/2)-1); pupilRadius=sqrt(sum(ceil(slmSize./2).^2)); if (nargin<5 || isempty(referenceAberration)) referenceAberration=1; end if (isa(referenceAberration,'function_handle')) referenceAberration=referenceAberration(X-floor(slmSize(2)/2)-1,Y-floor(slmSize(1)/2)-1); end maxIterations=100; coefficientWeights=100; slm.correctionFunction=slm.correctionFunction.*referenceAberration; nbCoefficients=size(selectedZernikeCoefficientIndexes,2); selectedZernikeCoefficients0=zeros(1,nbCoefficients); function value=modulateAndProbe(selectedZernikeCoefficients) zernikeCoefficients=[]; zernikeCoefficients(selectedZernikeCoefficientIndexes)=selectedZernikeCoefficients.*coefficientWeights; wavefront=zernikeComposition(X/pupilRadius,Y/pupilRadius,zernikeCoefficients); slm.modulate(exp(-2i*pi*wavefront)); value = -probeFunctor(); % Maximize the intensity end function stop = outputFunction(selectedZernikeCoefficients,optimValues,state) zernikeCoefficients=[]; zernikeCoefficients(selectedZernikeCoefficientIndexes)=selectedZernikeCoefficients.*coefficientWeights; zernikeCoefficients optimValues.fval %Report progress try switch (nargin(progressFunctor)) case 0 cont=progressFunctor(); case 1 cont=progressFunctor(optimValues.iteration/maxIterations); otherwise wavefront=zernikeComposition(X/pupilRadius,Y/pupilRadius,zernikeCoefficients); currentPupilFunctionEstimate=exp(2i*pi*wavefront); cont=progressFunctor(optimValues.iteration/maxIterations,currentPupilFunctionEstimate); end catch TooManyLHSExc if (strcmp(TooManyLHSExc.identifier,'MATLAB:maxlhs') || strcmp(TooManyLHSExc.identifier,'MATLAB:TooManyOutputs')) cont=true; % continue until all probes are done or the progress functor returns false else % Error occured in the progress display, exiting... rethrow(TooManyLHSExc); end end stop=(cont==false); % Add some fool-proving for incorrect progressFunctor's end % Optimize now selectedZernikeCoefficients=fminsearch(@modulateAndProbe,selectedZernikeCoefficients0,optimset('MaxIter',maxIterations,'TolX',1e-6,'Display','iter','OutputFcn',@outputFunction)); zernikeCoefficients=[]; zernikeCoefficients(selectedZernikeCoefficientIndexes)=selectedZernikeCoefficients.*coefficientWeights; wavefront=zernikeComposition(X/pupilRadius,Y/pupilRadius,zernikeCoefficients); measuredPupilFunction=exp(2i*pi*wavefront); if (nargout==0) showImage(measuredPupilFunction,-1); clear('measuredPupilFunction'); end if (nargout>4) [Phi Rho]=cart2pol(X/pupilRadius,Y/pupilRadius); end end function progressFunction(fractionDone,currentPupilFunctionEstimate) global debugOutput; persistent prevPctDone; pctDone=floor(100*fractionDone); if (~exist('prevPctDone') || isempty(prevPctDone) || prevPctDone~=pctDone) logMessage('%u%% done.',pctDone); prevPctDone=pctDone; end if (debugOutput) currentPupilFunctionEstimate=currentPupilFunctionEstimate./max(abs(currentPupilFunctionEstimate(:))); SNR=100; pupilFunctionCorrection=conj(currentPupilFunctionEstimate)./(abs(currentPupilFunctionEstimate).^2+(1/SNR).^2); nbGrayLevels=20; pupilFunctionCorrection=exp(1i*angle(pupilFunctionCorrection)).*floor(nbGrayLevels*min(1,abs(pupilFunctionCorrection)))./nbGrayLevels; psf=calcPsf(pupilFunctionCorrection); subplot(2,2,2); showImage(psf./max(abs(psf(:))),[],[],[],gca); drawnow(); end end function [value auxValues]=displayOnSLMAndAcquireSignal(slm,sampleProbe,probeFunctor,referenceProbe) %Display mask combinedProbes=referenceProbe+sampleProbe; slm.modulate(combinedProbes); switch (nargout(probeFunctor)) case 1 if (nargin(probeFunctor)==0) value=probeFunctor(); else value=probeFunctor(combinedProbes); end otherwise if (nargin(probeFunctor)==0) [value auxValues]=probeFunctor(); else [value auxValues]=probeFunctor(combinedProbes); end end end function psf=calcPsf(fieldModulationAtPupil) %Simulate defocus w20=3; imgSize=size(fieldModulationAtPupil); [X,Y]=meshgrid([1:imgSize(2)],[1:imgSize(1)]); R2=((X-imgSize(2)/2).^2+(Y-imgSize(1)/2).^2)./(min(imgSize)/2).^2; aperture=R2<(1/2)^2; openFraction=sum(aperture(:))/numel(aperture); aperture=aperture.*exp(2i*pi*w20*R2); fieldPsf=fftshift(fft2(ifftshift(fieldModulationAtPupil.*aperture)))/sqrt(numel(fieldModulationAtPupil)^2*openFraction); psf=abs(fieldPsf).^2; % Integral 1 psf=psf*1000; end function [value auxValues]=simulateDetection(img,pos) img=img.*(1+0.05*randn(size(img))); %Simulate photon noise value=img(pos(1),pos(2)); auxValues=img; end
github
mc225/Softwares_Tom-master
aberrationMeasurement.m
.m
Softwares_Tom-master/AberrationMeasurement/aberrationMeasurement.m
15,252
utf_8
d9185bb0214172a021f968c69be51b14
% [measuredPupilFunction eigenVector probeField4DMatrix sampleX sampleY]=aberrationMeasurement(slm,probeGridSize,probeFunctor,progressFunctor) % % Determines the aberration based on interference of different deflections % and calculates the correction function. Multiple probes can be used, such % as individual pixels of a camera, or NSOM tip. See % camAberrationMeasurement.m for an example. When multiple probes are % given, the aberrations are estimated simulatanously for each probe. % % Input: % slm: An Slm object % probeGridSize: a vector of three scalars, the number of probes in y and x followed by the number of phase probes (must be >=3) % probeFunctor: a function that returns the probe value, it optionally takes as argument the complex field at each pixel of the SLM % progressFunctor: When specified, this function will be executed every spatial frequency probe, it takes as optional arguments: % - fractionDone: the completion ratio % - currentPupilFunctionEstimate: the complex matrix with the current estimate of the pupil function % % Returns: % measuredPupilFunction: the complex matrix with the estimate of the aberrated pupil function % eigenVector: the eigenvector maximizing the probe value, ordered into a matrix where the rows and columns correspond to the spatial frequencies of the probes as specified by sampleX and sampleY. % probeField4DMatrix: the same as eigenVector, but for every auxilary value returned by the probeFunctor. If the auxilary value is a matrix, it will be stacked along the higher dimensions of this matrix. Typical usage would be that the probeFunctor returns the full image. % sampleX: the horizontal spatial frequency in cycles/SLM pixel for each probe % sampleY: the vertical spatial frequency in cycles/SLM pixel for each probe % referenceProbeAmplitude: The amplitude of the reference beam at the probe position. This is required if the reference caries an additional aberration. % referenceAuxProbesAmplitude: The amplitude of the reference beam at the auxilary reference probe positions. This is required if the reference caries an additional aberration. % % % Example: % slmSize=[20 20]; % [rows cols] % referenceDeflectionFrequency=[1/4 1/4]; % slm=PhaseSLM(2,referenceDeflectionFrequency,[0 0 slmSize]); % nbOfPhaseProbes=3; % probeGridSize=[20 20 nbOfPhaseProbes]; % modulationFunctor=@(fieldModulationAtPupil) pause(1/30); % %Using: % function psf=calcPsf(fieldModulationAtPupil) % imgSize=size(fieldModulationAtPupil); % [X,Y]=meshgrid([1:imgSize(2)],[1:imgSize(1)]); % R2=((X-imgSize(2)/2).^2+(Y-imgSize(1)/2).^2)./(min(imgSize)/2/2).^2; % aperture=R2<1; % aperture=aperture.*exp(2*2i*pi*R2); % fieldPsf=fftshift(fft2(ifftshift(fieldModulationAtPupil.*aperture))); % psf=abs(fieldPsf).^2; % end % function value=simulateDetection(img,pos) % value=img(pos(1),pos(2))*(1+0.05*randn()); % end % probeFunctor=@(fieldModulationAtPupil) simulateDetection(calcPsf(fieldModulationAtPupil),[15,15]); % % measuredPupilFunction=aberrationMeasurement(slm,probeGridSize,probeFunctor) % function [measuredPupilFunction eigenVector probeField4DMatrix sampleX sampleY referenceProbeAmplitude referenceAuxProbesAmplitude]=aberrationMeasurement(slm,probeGridSize,probeFunctor,progressFunctor,referenceAberration) if (nargin<1) referenceDeflectionFrequency=[1 -1]*1/10; slm=PhaseSLM(2,referenceDeflectionFrequency,[0 0 60 40]); end if (nargin<2) probeGridSize=[15 15 3]; % [rows,cols,phases] end if (length(probeGridSize)<2) probeGridSize(2)=0; logMessage('The horizontal deflection has not been specified, defaulting to 0 (vertical only deflection).'); end if (length(probeGridSize)<3) probeGridSize(3)=3; logMessage('The number of phases to sample has not been specified, defaulting to %u',probeGridSize(3)); end slmSize=slm.regionOfInterest; slmSize=slmSize(3:4); if (nargin<3) probePos=1+floor(slmSize./2)+round(slm.referenceDeflectionFrequency(1:2).*slmSize)+[0 -5]; probeFunctor=@(fieldModulationAtPupil) simulateDetection(calcPsf(fieldModulationAtPupil),probePos); end %the base deflection for a phase SLM in cycles per pixel, [cycles/row cycles/col] samplingDeflectionFrequencyStep=[1 1]./slmSize; % [y, x] = [row,col] nbOfPhaseProbes=probeGridSize(3); [X,Y]=meshgrid([1:slmSize(2)],[1:slmSize(1)]); if (nargin<4) progressFunctor=@(fractionDone,currentPupilFunctionEstimate) progressFunction(fractionDone,currentPupilFunctionEstimate); end [sampleX,sampleY]=meshgrid([-floor(probeGridSize(2)/2):floor((probeGridSize(2)-1)/2)]*samplingDeflectionFrequencyStep(2),[-floor(probeGridSize(1)/2):floor((probeGridSize(1)-1)/2)]*samplingDeflectionFrequencyStep(1)); sampleR2=sampleX.^2+sampleY.^2; [ign sortI]=sort(sampleR2(:)); if (nargin<5 || isempty(referenceAberration)) referenceAberration=1; end if (isa(referenceAberration,'function_handle')) referenceAberration=referenceAberration(X-floor(slmSize(2)/2)-1,Y-floor(slmSize(1)/2)-1); end % %Pick exactly 50% of the pixels % slmPixelsForReferenceField=mod(X+Y,2); %checker-board pattern encoding %Start with half the field in the reference beam referenceFraction=0.5; % Randomize phase probes to limit a bias due to laser fluctuations [ign randomizedPhaseI]=sort(rand(1,nbOfPhaseProbes)); %Probe for different deflections currentPupilFunctionEstimate=zeros(slmSize); eigenVector=zeros(size(sampleX)); probeField4DMatrix=[]; auxProbesCoefficientInMatrixForm=[]; nbSampleDeflections=prod(probeGridSize(1:2)); referenceProbeAmplitude=[]; referenceAuxProbesAmplitude=[]; for sampleDeflectionIdx=double(all(referenceAberration(:)==1)):nbSampleDeflections, if (sampleDeflectionIdx>0) samplingDeflectionFrequency=[sampleY(sortI(sampleDeflectionIdx)) sampleX(sortI(sampleDeflectionIdx))]; differentialDeflection=exp(2i*pi*(X*samplingDeflectionFrequency(2)+Y*samplingDeflectionFrequency(1))); else %If an aberration of the reference is specified, probe this first differentialDeflection=referenceAberration; end %Test different phase offsets newValues=zeros(1,nbOfPhaseProbes); auxValues={}; for phaseIdx=randomizedPhaseI, if (nargout(probeFunctor)==1 || nargout<3) newValues(phaseIdx)=displayOnSLMAndAcquireSignal(referenceFraction,slm,differentialDeflection*exp(2i*pi*(phaseIdx-1)/nbOfPhaseProbes),probeFunctor,referenceAberration); else [newValues(phaseIdx) auxValues{phaseIdx}]=displayOnSLMAndAcquireSignal(referenceFraction,slm,differentialDeflection*exp(2i*pi*(phaseIdx-1)/nbOfPhaseProbes),probeFunctor,referenceAberration); end end referenceFractionCorrection=1/(referenceFraction*(1-referenceFraction)); %Work out the phase and amplitude from the sampling using 'lock-in' amplification probeCoefficient=referenceFractionCorrection*newValues*exp(-2i*pi*([1:nbOfPhaseProbes]-1)/nbOfPhaseProbes).'; % probeScaling=mean(newValues); % proportional with rrAA+(1-r)(1-r)BB % maximize r*(1-r)/sqrt(r^2+((1-r)*x)^2) for r=refFrac, with x is the fraction B/A if (nargout>2 && ~isempty(auxValues)) auxProbesCoefficientInMatrixForm=auxValues{1}; for phaseIdx=2:nbOfPhaseProbes, % Correct for reduction in referenceFraction auxProbesCoefficientInMatrixForm=auxProbesCoefficientInMatrixForm+referenceFractionCorrection*auxValues{phaseIdx}*exp(-2i*pi*(phaseIdx-1)/nbOfPhaseProbes); end end %Verify and store the reference, this is always calculated first if (isempty(referenceProbeAmplitude)) %The first probe is a self-reference test, so the result should be a positive real number probeErrorEstimate=abs(angle(probeCoefficient)); if (probeErrorEstimate>0.01) logMessage('The estimated measurement error is large: %0.2f%%',probeErrorEstimate*100); end if (~isempty(auxValues)) auxMatrixErrorEstimate=sqrt(mean(abs(angle(auxProbesCoefficientInMatrixForm(:))).^2)); if (auxMatrixErrorEstimate>0.01) logMessage('The estimated measurement error for the auxilary probes is large: %0.2f%%',auxMatrixErrorEstimate*100); end end %Force to be real, the imaginary must be a measurement error probeCoefficient=real(probeCoefficient); if (~isempty(auxProbesCoefficientInMatrixForm)) auxProbesCoefficientInMatrixForm=real(auxProbesCoefficientInMatrixForm); end %Store the reference referenceProbeAmplitude=sqrt(max(0,probeCoefficient)); if (~isempty(auxValues)) referenceAuxProbesAmplitude=sqrt(max(0,auxProbesCoefficientInMatrixForm)); end end %Store the measurements if (sampleDeflectionIdx>0) %The probe scalar eigenVector(sortI(sampleDeflectionIdx))=probeCoefficient; currentPupilFunctionEstimate=currentPupilFunctionEstimate+probeCoefficient*conj(differentialDeflection); %Store any auxilary values as well if (~isempty(auxProbesCoefficientInMatrixForm)) if (isempty(probeField4DMatrix)) probeField4DMatrix=zeros([size(sampleX) size(auxProbesCoefficientInMatrixForm)]); end probeField4DMatrix(sortI(sampleDeflectionIdx)+numel(sampleX)*[0:numel(auxProbesCoefficientInMatrixForm)-1])=auxProbesCoefficientInMatrixForm; end %Report progress try switch (nargin(progressFunctor)) case 0 cont=progressFunctor(); case 1 cont=progressFunctor(sampleDeflectionIdx/nbSampleDeflections); otherwise cont=progressFunctor(sampleDeflectionIdx/nbSampleDeflections,currentPupilFunctionEstimate); end catch TooManyLHSExc if (strcmp(TooManyLHSExc.identifier,'MATLAB:maxlhs')) cont=true; % continue until all probes are done or the progress functor returns false else % Error occured in the progress display, exiting... rethrow(TooManyLHSExc); end end end cont=(cont~=false); % Add some fool-proving for incorrect progressFunctor's if (~cont) break; end end measuredPupilFunction=currentPupilFunctionEstimate; % or calcPupilFunctionFromProbes(slmSize,eigenVector); % %Re-interpolate the pixels on the SLM that were used for the reference beam (absolute value and argument separately to avoid a bias towards lower absolute amplitudes) % %for measuredPupilFunction: % measuredPupilFunctionAbs=abs(measuredPupilFunction); % interpolatedFunctionAbs=(measuredPupilFunctionAbs([1 1:end-1],:)+measuredPupilFunctionAbs([2:end end],:)+measuredPupilFunctionAbs(:,[1 1:end-1])+measuredPupilFunctionAbs(:,[2:end end]))./4; % interpolatedFunctionArg=angle(measuredPupilFunction([1 1:end-1],:)+measuredPupilFunction([2:end end],:)+measuredPupilFunction(:,[1 1:end-1])+measuredPupilFunction(:,[2:end end])); % interpolatedFunction=exp(1i*interpolatedFunctionArg).*interpolatedFunctionAbs; % measuredPupilFunction(slmPixelsForReferenceField>0)=interpolatedFunction(slmPixelsForReferenceField>0); %If no special reference aberration has been given, it is that of the zero deflection if (isempty(referenceProbeAmplitude)) referenceProbe=max(0,real(eigenVector(floor(end/2)+1,floor(end/2)+1))); referenceProbeAmplitude=sqrt(referenceProbe); if (~isempty(probeField4DMatrix)) referenceAuxProbes=max(0,real(probeField4DMatrix(floor(end/2)+1,floor(end/2)+1,:,:))); %size == [1 1 roiSize(1:2)] referenceAuxProbesAmplitude=sqrt(squeeze(referenceAuxProbes)); end end if (nargout==0) showImage(measuredPupilFunction./max(abs(measuredPupilFunction(:)))); clear('measuredPupilFunction'); end end function cont=progressFunction(fractionDone,currentPupilFunctionEstimate) global debugOutput; persistent prevPctDone; pctDone=floor(100*fractionDone); if (~exist('prevPctDone') || isempty(prevPctDone) || prevPctDone~=pctDone) logMessage('%u%% done.',pctDone); prevPctDone=pctDone; end if (debugOutput) currentPupilFunctionEstimate=currentPupilFunctionEstimate./max(abs(currentPupilFunctionEstimate(:))); SNR=100; pupilFunctionCorrection=conj(currentPupilFunctionEstimate)./(abs(currentPupilFunctionEstimate).^2+(1/SNR).^2); nbGrayLevels=20; pupilFunctionCorrection=exp(1i*angle(pupilFunctionCorrection)).*floor(nbGrayLevels*min(1,abs(pupilFunctionCorrection)))./nbGrayLevels; psf=calcPsf(pupilFunctionCorrection); subplot(2,2,2); showImage(psf./max(abs(psf(:))),[],[],[],gca); end cont=true; end function [value auxValues]=displayOnSLMAndAcquireSignal(referenceFraction,slm,sampleDeflection,probeFunctor,referenceAberration) %Display mask % combinedDeflection=referenceAberration.*slmPixelsForReferenceField + sampleDeflection.*(1-slmPixelsForReferenceField); %checker-board pattern encoding combinedDeflection=referenceFraction*referenceAberration + (1-referenceFraction)*sampleDeflection; slm.modulate(combinedDeflection); switch (nargout(probeFunctor)) case 1 if (nargin(probeFunctor)==0) value=probeFunctor(); else value=probeFunctor(combinedDeflection); end otherwise if (nargin(probeFunctor)==0) [value auxValues]=probeFunctor(); else [value auxValues]=probeFunctor(combinedDeflection); end end end function psf=calcPsf(fieldModulationAtPupil) %Simulate defocus w20=3; imgSize=size(fieldModulationAtPupil); [X,Y]=meshgrid([1:imgSize(2)],[1:imgSize(1)]); R2=((X-imgSize(2)/2).^2+(Y-imgSize(1)/2).^2)./(min(imgSize)/2).^2; aperture=R2<(1/2)^2; aperture=aperture.*exp(2i*pi*w20*R2); % aperture=aperture.*exp(-R2./(.25.^2)); % aperture=aperture.*R2; %sinc(sqrt(R2)./.25); fieldPsf=fftshift(fft2(ifftshift(fieldModulationAtPupil.*aperture))); psf=abs(fieldPsf).^2; end function [value auxValues]=simulateDetection(img,pos) img=img.*(1+0.05*randn(size(img))); %Simulate photon noise value=img(pos(1),pos(2)); auxValues=img; end
github
mc225/Softwares_Tom-master
selectRegionOfInterestAroundPeakIntensity.m
.m
Softwares_Tom-master/AberrationMeasurement/selectRegionOfInterestAroundPeakIntensity.m
2,268
utf_8
eb0ad4c710b43c1d9d29650c21de21e6
% [cam centerPos]=selectRegionOfInterestAroundPeakIntensity(cam,slm,roiSizeForCam,centerPos) % % Updates the cameras cam's region of interest to a size roiSizeForCam (rows, columns) around the peak intensity, and re-acquires the dark image. % % Argument centerPos is optional, when given the algorithm assumes that the % peak intensity is at the coordinates as given by centerPos. function [cam centerPos]=selectRegionOfInterestAroundPeakIntensity(cam,slm,roiSizeForCam,centerPos) if (nargin<4 || isempty(centerPos)) %Capture dark image slm.modulate(0); %The CCD should now be unilluminated in principle cam=cam.acquireBackground(); %GT 10Dec15 - to avoid the failure in capturing the bright spot cam=cam.acquireBackground(cam.numberOfFramesToAverage*4); irradiationIntensityScaling=1; maxValue=2; while(maxValue>.90 && irradiationIntensityScaling>1/16) %Capture the spot without the zeroth order slm.modulate(irradiationIntensityScaling); initialImage=cam.acquire(); initialImage=cam.acquire(); %Get peak position [maxValue, maxIdx]=max(initialImage(:)); irradiationIntensityScaling=irradiationIntensityScaling/2; end [maxRow, maxCol]=ind2sub(size(initialImage),maxIdx); centerPos=[maxRow,maxCol]; % [row, col] centerPos=centerPos+cam.regionOfInterest(1:2); %There might be an initial offset logMessage('Centering the camera region of interest around the coordinates [row,col]=[%u,%u].',centerPos); else logMessage('Forcing the camera region of interest to be around the coordinates [row,col]=[%u,%u].',centerPos); end %Adjust the region of interest centerPos=2*floor(centerPos/2); %Align with Bayer filter if necessary %Make sure that the region of interest is on the CCD centerPos=min(max(centerPos,floor((roiSizeForCam+1)/2)),cam.maxSize-floor((roiSizeForCam+1)/2)); cam.regionOfInterest=[centerPos-floor(roiSizeForCam/2), roiSizeForCam]; slm.modulate(0); cam=cam.acquireBackground(); cam=cam.acquireBackground(cam.numberOfFramesToAverage*4);%Measure background for the new ROI end
github
mc225/Softwares_Tom-master
aberrationMeasurementCizmarMethod.m
.m
Softwares_Tom-master/AberrationMeasurement/aberrationMeasurementCizmarMethod.m
14,304
utf_8
470715ef80614ec9134ede2f3097a4c6
% [measuredPupilFunction pupilFunctionEstimates probeField4DMatrix samplePosX samplePosY]=aberrationMeasurementCizmarMethod(slm,probeGridSize,probeFunctor,progressFunctor) % % Determines the aberration using Tomas Cizmar's method as published in Nature Photonics. % % Input: % slm: An Slm object % probeGridSize: a vector of three scalars, the number of probes in y and x followed by the number of phase probes (must be >=3) % probeFunctor: a function that returns the probe value, it optionally takes as argument the complex field at each pixel of the SLM % progressFunctor: When specified, this function will be executed every spatial frequency probe, it takes as optional arguments: % - fractionDone: the completion ratio % - currentPupilFunctionEstimate: the complex matrix with the current estimate of the pupil function % % Returns: % measuredPupilFunction: the complex matrix with the estimate of the aberrated pupil function % pupilFunctionEstimates: the eigenvector maximizing the probe value, ordered into a matrix where the rows and columns correspond to the spatial frequencies of the probes as specified by samplePosX and samplePosY. % probeField4DMatrix: the same as pupilFunctionEstimates, but for every auxilary value returned by the probeFunctor. If the auxilary value is a matrix, it will be stacked along the higher dimensions of this matrix. Typical usage would be that the probeFunctor returns the full image. % samplePosX: the horizontal spatial frequency in cycles/SLM pixel for each probe % samplePosY: the vertical spatial frequency in cycles/SLM pixel for each probe % referenceProbeAmplitude: The amplitude of the reference beam at the probe position. This is required if the reference caries an additional aberration. % referenceAuxProbesAmplitude: The amplitude of the reference beam at the auxilary reference probe positions. This is required if the reference caries an additional aberration. % % % Example: % slmSize=[20 20]; % [rows cols] % referenceDeflectionFrequency=[1/4 1/4]; % slm=PhaseSLM(2,referenceDeflectionFrequency,[0 0 slmSize]); % nbOfPhaseProbes=3; % probeGridSize=[20 20 nbOfPhaseProbes]; % modulationFunctor=@(fieldModulationAtPupil) pause(1/30); % %Using: % function psf=calcPsf(fieldModulationAtPupil) % imgSize=size(fieldModulationAtPupil); % [X,Y]=meshgrid([1:imgSize(2)],[1:imgSize(1)]); % R2=((X-imgSize(2)/2).^2+(Y-imgSize(1)/2).^2)./(min(imgSize)/2/2).^2; % aperture=R2<1; % aperture=aperture.*exp(2*2i*pi*R2); % fieldPsf=fftshift(fft2(ifftshift(fieldModulationAtPupil.*aperture))); % psf=abs(fieldPsf).^2; % end % function value=simulateDetection(img,pos) % value=img(pos(1),pos(2))*(1+0.05*randn()); % end % probeFunctor=@(fieldModulationAtPupil) simulateDetection(calcPsf(fieldModulationAtPupil),[15,15]); % % measuredPupilFunction=aberrationMeasurementCizmarMethod(slm,probeGridSize,probeFunctor) % function [measuredPupilFunction pupilFunctionEstimates probeField4DMatrix samplePosX samplePosY referenceProbeAmplitude referenceAuxProbesAmplitude]=aberrationMeasurementCizmarMethod(slm,probeGridSize,probeFunctor,progressFunctor,referenceAberration) if (nargin<1) close all; figure(); image(zeros(600,800)); displayNumber=gca(); referenceDeflectionFrequency=[1 1]/10; slm=PhaseSLM(displayNumber,referenceDeflectionFrequency); slm.stabilizationTime=0.01; end if (nargin<2) probeGridSize=[25 25 3]; %[12 16 3]; % [rows,cols,phases] end if (length(probeGridSize)<2) probeGridSize(2)=0; logMessage('The horizontal deflection has not been specified, defaulting to 0 (vertical only deflection).'); end if (length(probeGridSize)<3) probeGridSize(3)=3; logMessage('The number of phases to sample has not been specified, defaulting to %u',probeGridSize(3)); end slmSize=slm.regionOfInterest(3:4); if (nargin<3) probePos=1+floor(slmSize./2); probeFunctor=@(fieldModulationAtPupil) simulateDetection(calcPsf(fieldModulationAtPupil),probePos); end if (nargin<4) progressFunctor=@(fractionDone,currentPupilFunctionEstimate) progressFunction(fractionDone,currentPupilFunctionEstimate); end nbOfPhaseProbes=probeGridSize(3); probeSpacing=floor(slmSize./probeGridSize(1:2)); % [y, x] = [row,col] probeSize=probeSpacing; probeShapeFunctor=@(X,Y) double(X>=-probeSize(1)/2 & X<probeSize(1)/2 & Y>=-probeSize(2)/2 & Y<probeSize(2)/2); [X,Y]=meshgrid([1:slmSize(2)]-floor(slmSize(2)/2)-1,[1:slmSize(1)]-floor(slmSize(1)/2)-1); [samplePosX,samplePosY]=meshgrid(probeSpacing(2)*([0.5:probeGridSize(2)]-probeGridSize(2)/2),probeSpacing(1)*([0.5:probeGridSize(1)]-probeGridSize(1)/2)); sampleR2=samplePosX.^2+samplePosY.^2; [ign sortI]=sort(sampleR2(:)); if (nargin<5 || isempty(referenceAberration)) referenceAberration=1; end if (isa(referenceAberration,'function_handle')) referenceAberration=referenceAberration(X-floor(slmSize(2)/2)-1,Y-floor(slmSize(1)/2)-1); end slm.correctionFunction=slm.correctionFunction.*referenceAberration; referenceProbe=probeShapeFunctor(X-samplePosX(sortI(1)),Y-samplePosY(sortI(1))); [ign randomizedPhaseI]=sort(rand(1,nbOfPhaseProbes)); %Probe for different deflections currentPupilFunctionEstimate=ones(slmSize); pupilFunctionEstimates=ones(size(samplePosX)); probeField4DMatrix=[]; auxProbesCoefficientInMatrixForm=[]; nbSampleDeflections=prod(probeGridSize(1:2)); referenceProbeAmplitude=[]; referenceAuxProbesAmplitude=[]; for sampleProbeIdx=1:nbSampleDeflections, sampleProbe=probeShapeFunctor(X-samplePosX(sortI(sampleProbeIdx)),Y-samplePosY(sortI(sampleProbeIdx))); coincidenceFactor=1+double(any(abs(referenceProbe(:)+sampleProbe(:))>1)); %Test different phase offsets newValues=zeros(1,nbOfPhaseProbes); auxValues={}; for phaseIdx=randomizedPhaseI, if (nargout(probeFunctor)==1 || nargout<3) newValues(phaseIdx)=displayOnSLMAndAcquireSignal(slm,sampleProbe*exp(2i*pi*(phaseIdx-1)/nbOfPhaseProbes)/coincidenceFactor,probeFunctor,referenceProbe/coincidenceFactor); else [newValues(phaseIdx) auxValues{phaseIdx}]=displayOnSLMAndAcquireSignal(slm,sampleProbe*exp(2i*pi*(phaseIdx-1)/nbOfPhaseProbes)/coincidenceFactor,probeFunctor,referenceProbe/coincidenceFactor); auxValues{phaseIdx}=(coincidenceFactor^2)*auxValues{phaseIdx}; end end newValues=(coincidenceFactor^2)*newValues; %Work out the phase and amplitude from the sampling using 'lock-in' amplification probeCoefficient=newValues*exp(-2i*pi*([1:nbOfPhaseProbes]-1)/nbOfPhaseProbes).'; %Do the same for the auxilary probes if (nargout>2 && ~isempty(auxValues)) auxProbesCoefficientInMatrixForm=auxValues{1}; for phaseIdx=2:nbOfPhaseProbes, % Correct for reduction in referenceFraction auxProbesCoefficientInMatrixForm=auxProbesCoefficientInMatrixForm+auxValues{phaseIdx}*exp(-2i*pi*(phaseIdx-1)/nbOfPhaseProbes); end end %Verify and store the reference, this is always calculated first if (isempty(referenceProbeAmplitude)) %The first probe is a self-reference test, so the result should be a positive real number probeErrorEstimate=abs(angle(probeCoefficient)); if (probeErrorEstimate>0.01) logMessage('The estimated measurement error is large: %0.2f%%',probeErrorEstimate*100); end if (~isempty(auxValues)) auxMatrixErrorEstimate=sqrt(mean(abs(angle(auxProbesCoefficientInMatrixForm(:))).^2)); if (auxMatrixErrorEstimate>0.01) logMessage('The estimated measurement error for the auxilary probes is large: %0.2f%%',auxMatrixErrorEstimate*100); end end %Force to be real, the imaginary must be a measurement error probeCoefficient=real(probeCoefficient); if (~isempty(auxProbesCoefficientInMatrixForm)) auxProbesCoefficientInMatrixForm=real(auxProbesCoefficientInMatrixForm); end %Store the reference referenceProbeAmplitude=sqrt(max(0,probeCoefficient)); if (~isempty(auxValues)) referenceAuxProbesAmplitude=sqrt(max(0,auxProbesCoefficientInMatrixForm)); end end %Store the measurements if (sampleProbeIdx>0) %The probe scalar pupilFunctionEstimates(sortI(sampleProbeIdx))=probeCoefficient; currentPupilFunctionEstimate=currentPupilFunctionEstimate+probeCoefficient*conj(sampleProbe); %Store any auxilary values as well if (~isempty(auxProbesCoefficientInMatrixForm)) if (isempty(probeField4DMatrix)) probeField4DMatrix=zeros([size(samplePosX) size(auxProbesCoefficientInMatrixForm)]); end probeField4DMatrix(sortI(sampleProbeIdx)+numel(samplePosX)*[0:numel(auxProbesCoefficientInMatrixForm)-1])=auxProbesCoefficientInMatrixForm; end %Report progress try switch (nargin(progressFunctor)) case 0 cont=progressFunctor(); case 1 cont=progressFunctor(sampleProbeIdx/nbSampleDeflections); otherwise cont=progressFunctor(sampleProbeIdx/nbSampleDeflections,currentPupilFunctionEstimate); end catch TooManyLHSExc if (strcmp(TooManyLHSExc.identifier,'MATLAB:maxlhs') || strcmp(TooManyLHSExc.identifier,'MATLAB:TooManyOutputs')) cont=true; % continue until all probes are done or the progress functor returns false else % Error occured in the progress display, exiting... rethrow(TooManyLHSExc); end end end cont=(cont~=false); % Add some fool-proving for incorrect progressFunctor's if (~cont) break; end end % Measurement done %Normalize the measurements to a maximum of unity transmission pupilFunctionEstimates(sortI(1:sampleProbeIdx))=pupilFunctionEstimates(sortI(1:sampleProbeIdx))./max(abs(pupilFunctionEstimates(sortI(1:sampleProbeIdx)))); % Prepare output % measuredPupilFunction=currentPupilFunctionEstimate; %Will not work if the probe size is not equal to the probe spacing % Interpolate amplitude and phase separately measuredPupilFunctionAbs=interp2(samplePosX,samplePosY,abs(pupilFunctionEstimates),X,Y,'*nearest',0); measuredPupilFunction=interp2(samplePosX,samplePosY,pupilFunctionEstimates,X,Y,'*nearest',0); measuredPupilFunction=measuredPupilFunctionAbs.*exp(1i*angle(measuredPupilFunction)); %If no special reference aberration has been given, it is that of the zero deflection if (isempty(referenceProbeAmplitude)) referenceProbe=max(0,real(pupilFunctionEstimates(floor(end/2)+1,floor(end/2)+1))); referenceProbeAmplitude=sqrt(referenceProbe); if (~isempty(probeField4DMatrix)) referenceAuxProbes=max(0,real(probeField4DMatrix(floor(end/2)+1,floor(end/2)+1,:,:))); %size == [1 1 roiSize(1:2)] referenceAuxProbesAmplitude=sqrt(squeeze(referenceAuxProbes)); end end if (nargout==0) showImage(measuredPupilFunction,-1); clear('measuredPupilFunction'); end end function progressFunction(fractionDone,currentPupilFunctionEstimate) global debugOutput; persistent prevPctDone; pctDone=floor(100*fractionDone); if (~exist('prevPctDone') || isempty(prevPctDone) || prevPctDone~=pctDone) logMessage('%u%% done.',pctDone); prevPctDone=pctDone; end if (debugOutput) currentPupilFunctionEstimate=currentPupilFunctionEstimate./max(abs(currentPupilFunctionEstimate(:))); SNR=100; pupilFunctionCorrection=conj(currentPupilFunctionEstimate)./(abs(currentPupilFunctionEstimate).^2+(1/SNR).^2); nbGrayLevels=20; pupilFunctionCorrection=exp(1i*angle(pupilFunctionCorrection)).*floor(nbGrayLevels*min(1,abs(pupilFunctionCorrection)))./nbGrayLevels; psf=calcPsf(pupilFunctionCorrection); subplot(2,2,2); showImage(psf./max(abs(psf(:))),[],[],[],gca); drawnow(); end end function [value auxValues]=displayOnSLMAndAcquireSignal(slm,sampleProbe,probeFunctor,referenceProbe) %Display mask combinedProbes=referenceProbe+sampleProbe; slm.modulate(combinedProbes); switch (nargout(probeFunctor)) case 1 if (nargin(probeFunctor)==0) value=probeFunctor(); else value=probeFunctor(combinedProbes); end otherwise if (nargin(probeFunctor)==0) [value auxValues]=probeFunctor(); else [value auxValues]=probeFunctor(combinedProbes); end end end function psf=calcPsf(fieldModulationAtPupil) %Simulate defocus w20=3; imgSize=size(fieldModulationAtPupil); [X,Y]=meshgrid([1:imgSize(2)],[1:imgSize(1)]); R2=((X-imgSize(2)/2).^2+(Y-imgSize(1)/2).^2)./(min(imgSize)/2).^2; aperture=R2<(1/2)^2; openFraction=sum(aperture(:))/numel(aperture); aperture=aperture.*exp(2i*pi*w20*R2); fieldPsf=fftshift(fft2(ifftshift(fieldModulationAtPupil.*aperture)))/sqrt(numel(fieldModulationAtPupil)^2*openFraction); psf=abs(fieldPsf).^2; % Integral 1 psf=psf*1000; end function [value auxValues]=simulateDetection(img,pos) img=img.*(1+0.05*randn(size(img))); %Simulate photon noise value=img(pos(1),pos(2)); auxValues=img; end
github
mc225/Softwares_Tom-master
laguerreGaussian.m
.m
Softwares_Tom-master/Vortices/laguerreGaussian.m
2,460
utf_8
60b0aa63d5e14c6b610a8f80ca7d61e9
% fieldValues=laguerreGaussian(R,P,Z,pValue,lValue,lambda,beamWaist) % % Input: % R: radial coordinate grid [m] % P: azimutal coordinate grid [rad] % Z: axial coordinate grid [m] % pValue: the p value of the beam (radial) % lValue: the l value of the beam (azimutal phase index, must be integer) % lambda: the wavelength to simulate [m] % beamWaist: the beam waist [m] % % Example: % xRange=[-4e-6:.05e-6:4e-6]; % [X,Y]=meshgrid(xRange,xRange); % [P,R]=cart2pol(X,Y); % Z=[]; % lambda=500e-9; % beamWaist=2*lambda; % pValue=3; % lValue=0; % fieldValues=laguerreGaussian(R,P,Z,pValue,lValue,lambda,beamWaist); % imagesc(abs(fieldValues).^2) % function fieldValues=laguerreGaussian(R,P,Z,pValue,lValue,lambda,beamWaist) if (nargin<1), xRange=[-4e-6:.05e-6:4e-6]; [X,Y]=meshgrid(xRange,xRange); [P,R]=cart2pol(X,Y); Z=[]; pValue=0; lValue=0; end if (nargin<6) lambda=500e-9; end if (nargin<7) beamWaist=2*lambda; end if (isempty(Z)), Z=zeros(size(R)); end rayleighRange=pi*beamWaist^2/lambda; W=beamWaist*sqrt(1+(Z./rayleighRange).^2); radiusOfCurvature=(Z+(Z==0)).*(1+(rayleighRange./Z).^2); gouyPhase=atan2(Z,rayleighRange); fieldValues=(1./W).*(R.*sqrt(2)./W).^abs(lValue).*exp(-R.^2./W.^2)... .*L(abs(lValue),pValue,2*R.^2./W.^2).*exp(1i.*(2*pi/lambda).*R.^2./(2*radiusOfCurvature))... .*exp(1i*lValue.*P).*exp(-1i*(2*pValue+abs(lValue)+1).*gouyPhase); %Normalize fieldValues=fieldValues./sqrt(sum(abs(fieldValues(:)).^2)); if (nargout==0) showImage(fieldValues+1i*sqrt(eps('single')),-1,X,Y); axis square; % intensityValues=abs(fieldValues).^2; % beamWaistEstimate=sum(intensityValues(:).*R(:))./sum(intensityValues(:)); % psf=fftshift(abs(fft2(fieldValues)).^2); psf=exp(1)^2*psf/max(psf(:)); % beamDisplacement=[1 0]; % fieldValuesDisp=fieldValues.*exp(2i*(beamDisplacement(1)*X+beamDisplacement(2)*Y)/beamWaist); % psfDisp=fftshift(abs(fft2(fieldValuesDisp)).^2); psfDisp=exp(1)^2*psfDisp/max(psfDisp(:)); % plot([psf(1+floor(end/2),:); psfDisp(1+floor(end/2),:)].') clear fieldValues; end end function Y=L(lValue,pValue,X) Y=polyval(LaguerreGen(pValue,lValue),X); end
github
mc225/Softwares_Tom-master
createCellRotationMovie.m
.m
Softwares_Tom-master/LightSheet/createCellRotationMovie.m
7,854
utf_8
4bd6ac1b97e8b2ad135c26d237d96471
function createCellRotationMovie(inputFolder,outputFileName) close all; if (nargin<1 || isempty(inputFolder)) inputFolder='Z:\RESULTS\2013-05-14_cellspheroidsWGA\2013-05-14_cellspheroidsWGA_filter_ap1-2B'; end if (nargin<2 || isempty(outputFileName)) outputFileName='rotatingCells.avi'; end gaussianFileName=[inputFolder, '/recording_lambda488nm_alpha0_beta100_cropped.mat']; airyFileName=[inputFolder, '/recording_lambda488nm_alpha2_beta100_cropped.mat']; %Load the data [GaussData AiryData xRange yRange zRange]=loadData(gaussianFileName,airyFileName); %Normalize the data GaussData=.1*GaussData/findPercentileCutOffValue(GaussData(:),.9); AiryData=.1*AiryData/findPercentileCutOffValue(AiryData(:),.9); writerObj = VideoWriter(outputFileName,'Uncompressed AVI'); set(writerObj,'FrameRate',25); open(writerObj); colorMap=interpolatedColorMap(1024,[0 0 0; 0 .8 0; 1 1 1],[0 .5 1]); fig=figure('Position',[50 50 640 480],'Color',[0 0 0]); % set(fig,'Renderer','zbuffer'); % Turn of Windows 64 bit Aero!! [writerObj fig]=constructDataCube(fig,GaussData,AiryData,xRange,yRange,zRange,1,colorMap,writerObj); [writerObj fig]=rotateCamera(fig,20*[0 1 0]*pi/180,5,writerObj); [writerObj fig]=rotateCamera(fig,2*pi*[1 0 0],25,writerObj,5); close(writerObj); end function cutOffValue=findPercentileCutOffValue(values,percentile) values=sort(values); cutOffIndex=sum(cumsum(values)<percentile*sum(values)); cutOffValue=values(max(1,cutOffIndex)); end function [writerObj fig]=constructDataCube(fig,GaussData,AiryData,xRange,yRange,zRange,nbSteps,colorMap,writerObj) isovalGauss=0.1; isovalAiry=0.1; [X,Y,Z]=meshgrid(xRange,yRange,zRange); % Built up of data cube userData={}; userData.subplots=subplot(1,2,1,'Parent',fig,'Color','none'); userData.subplots(2)=subplot(1,2,2,'Parent',fig,'Color','none'); for fractionToShow=[1:nbSteps]./nbSteps, userData.subplots(1)=drawPartialVolume(userData.subplots(1),GaussData,isovalGauss,colorMap,'Gaussian',X,Y,Z,fractionToShow); userData.subplots(2)=drawPartialVolume(userData.subplots(2),AiryData,isovalAiry,colorMap,'Airy',X,Y,Z,fractionToShow); drawnow(); writeVideo(writerObj,getframe(fig)); if(fractionToShow<1) cla(userData.subplots(1)); cla(userData.subplots(2)); end end set(fig,'UserData',userData); % linkaxes(userData.subplots); end function ax=drawPartialVolume(ax,dataCube,isoval,colorMap,description,X,Y,Z,fractionToShow) alphaValue=0.50; cameraPosition=[100 -100 500]; cameraUp=[0 1 0]; fractionSel=size(dataCube,2)-ceil(fractionToShow*size(dataCube,2)-1):size(dataCube,2); dataCube=dataCube(:,fractionSel,:); GaussPatch1=patch(isosurface(X(:,fractionSel,:),Y(:,fractionSel,:),Z(:,fractionSel,:),... dataCube,isoval),'Parent',ax,'FaceColor','green',... 'FaceLighting','phong','AmbientStrength',0.5,... 'EdgeColor','none','FaceAlpha',alphaValue); patch(isocaps(X(:,fractionSel,:),Y(:,fractionSel,:),Z(:,fractionSel,:),... dataCube,isoval),'Parent',ax,'FaceColor','interp',... 'FaceLighting','phong','AmbientStrength',0.5,... 'EdgeColor','none','FaceAlpha',alphaValue); isonormals(X(:,fractionSel,:),Y(:,fractionSel,:),Z(:,fractionSel,:),dataCube,GaussPatch1); colormap(ax,colorMap); grid(ax,'on'); box(ax,'on'); axis(ax,'vis3d','image'); xlim(ax,[X(1) X(end)]); ylim(ax,[Y(1) Y(end)]); zlim(ax,[Z(1) Z(end)]); xlabel(ax,'x [\mu m]','FontSize',14,'FontWeight','bold'); ylabel(ax,'y [\mu m]','FontSize',14,'FontWeight','bold'); zlabel(ax,'z [\mu m]','FontSize',14,'FontWeight','bold'); title(ax,description,'FontSize',20,'FontWeight','bold'); axisColor=[1 1 1]; set(ax,'FontSize',16,'LineWidth',1.5,'XColor',axisColor,'YColor',axisColor,'ZColor',axisColor); % view(ax,315,30); set(ax,'CameraPositionMode','manual','CameraPosition',cameraPosition); set(ax,'CameraUpVectorMode','manual','CameraUpVector',cameraUp); set(ax,'CameraTargetMode','manual','CameraTarget',[mean(X(:)) mean(Y(:)) mean(Z(:))]); % set(ax,'Projection','perspective'); set(ax,'CameraViewAngleMode','manual','CameraViewAngle',10); setLights(ax); end function [writerObj fig]=rotateCamera(fig,rotationVector,nbSteps,writerObj,nbCycles) if (nargin<5 || isempty(nbCycles)) nbCycles=1; end userData=get(fig,'UserData'); initialCameraPosition=get(userData.subplots(1),'CameraPosition'); initialCameraUpVector=get(userData.subplots(1),'CameraUpVector'); nRAx=rotationVector./norm(rotationVector); % Rotate to position rotationFrames=struct('cdata',{},'colormap',[]); for fractionOfTranslation=[1:nbSteps]./nbSteps, ct=cos(-fractionOfTranslation*norm(rotationVector)); st=sin(-fractionOfTranslation*norm(rotationVector)); rotationMatrix=[ct+nRAx(1)^2*(1-ct) nRAx(1)*nRAx(2)*(1-ct)-nRAx(3)*st nRAx(1)*nRAx(3)*(1-ct)+nRAx(2)*st;... nRAx(2)*nRAx(1)*(1-ct)+nRAx(3)*st ct+nRAx(2)^2*(1-ct) nRAx(2)*nRAx(3)*(1-ct)-nRAx(1)*st;... nRAx(3)*nRAx(1)*(1-ct)+nRAx(2)*st nRAx(3)*+nRAx(2)*(1-ct)+nRAx(1)*st ct+nRAx(3)^2*(1-ct) ]; cameraPosition=initialCameraPosition*rotationMatrix; cameraUpVector=initialCameraUpVector*rotationMatrix; set(userData.subplots(1),'CameraPositionMode','manual','CameraPosition',cameraPosition); set(userData.subplots(1),'CameraUpVectorMode','manual','CameraUpVector',cameraUpVector); setLights(userData.subplots(1)); set(userData.subplots(2),'CameraPositionMode','manual','CameraPosition',cameraPosition); set(userData.subplots(2),'CameraUpVectorMode','manual','CameraUpVector',cameraUpVector); setLights(userData.subplots(2)); drawnow(); rotationFrames(end+1)=getframe(fig); end % Do multiple rotations if requested for cycleIdx=1:nbCycles, for (rotationFrame=rotationFrames) writeVideo(writerObj,rotationFrame); end end end function setLights(ax) camH1=camlight(30,30); set(camH1,'Parent',ax); % camH2=camlight('left'); set(camH2,'Parent',ax); lighting(ax,'phong'); end function [GaussData AiryData xRange yRange zRange]=loadFakeData(gaussianFileName,airyFileName) xRange=[-42.8:2:12.8]; yRange=[-40.4:2:15.4]; zRange=[-24.4:1:31.4]; rand('seed',0) GaussData = rand(length(xRange),length(yRange),length(zRange)); GaussData = smooth3(GaussData,'box',15); AiryData = rand(length(xRange),length(yRange),length(zRange)); AiryData = smooth3(AiryData,'box',5); AiryData=swapXY(AiryData); end function [GaussData AiryData xRange yRange zRange]=loadData(gaussianFileName,airyFileName) load(gaussianFileName,'recordedImageStack','xRange','yRange','zRange'); GaussData=recordedImageStack; load(airyFileName,'restoredDataCube'); AiryData=restoredDataCube; xRange=xRange*1e6; yRange=yRange*1e6; zRange=zRange*1e6; [GaussData,xRange,yRange]=swapXY(GaussData,xRange,yRange); AiryData=swapXY(AiryData); % % Subsample % step=4; % xRange=xRange(1:step:end); % yRange=yRange(1:step:end); % zRange=zRange(1:step:end); % GaussData=GaussData(1:step:end,1:step:end,1:step:end); % AiryData=AiryData(1:step:end,1:step:end,1:step:end); end function [dataCube xRange yRange]=swapXY(dataCube,xRange,yRange) % if(nargin>=3) % tmp=xRange; % xRange=yRange; % yRange=tmp; % end dataCube=permute(dataCube,[2 1 3]); end
github
mc225/Softwares_Tom-master
processBeadsDataForResolutionPlot.m
.m
Softwares_Tom-master/LightSheet/processBeadsDataForResolutionPlot.m
8,844
utf_8
8f3e4c42781b7132bc9478b2ed1fe959
% processBeadsDataForResolutionPlot(xRange,yRange,zRange,localizationData,testData) % % function processBeadsDataForResolutionPlot(inputFolder) close all; if (nargin<1) % inputFolder='Z:\RESULTS\20120501_alpha7_int1000_g1_littlemorepower_betterfocus_beads_leftofprobe\backwardScans\'; % inputFolder='Z:\RESULTS\20120501_alpha7_int1000_g1_littlemorepower_betterfocus_beads_leftofprobe\forwardScans\'; % inputFolder='Z:\RESULTS\20120501_alpha7_int1000_g1_littlemorepower_betterfocus_beads_leftofprobe\forwardScans2\'; inputFolder='Z:\RESULTS\20120501_alpha7_int1000_g1_morepower_beads_leftofprobe\'; % load('Z:\RESULTS\20120501_alpha7_int1000_g1_littlemorepower_betterfocus_beads_leftofprobe\forwardScans\Gaussian_0F.mat'); % load('Z:\RESULTS\20120501_alpha7_int1000_g1_littlemorepower_betterfocus_beads_leftofprobe\forwardScans\Airy_0F.mat'); % load('Z:\RESULTS\600nmBeadsApOneThird\B\at0\recording_lambda532nm_alpha7_beta100.mat'); % load('E:\Stored Files\RESULTS\compressed\offsetBeads\at_25um\recording_lambda532nm_alpha0_beta100.mat'); % load('E:\Stored Files\RESULTS\2013_01_15_SmallBeadSample\2013-01-15 16_14_11.433_green_0.05_(2)\recording_lambda532nm_alpha0_beta100.mat'); % load('Z:\RESULTS\2013-04-10_Beads200nm\2013-04-10 16_10_20.097_ApOneHalf\recording_lambda488nm_alpha10_beta100.mat'); % load('Z:\RESULTS\2013-04-10_Beads200nm\2013-04-10 16_10_20.097_ApOneHalf\recording_lambda488nm_alpha0_beta100.mat'); % load('E:\Stored Files\RESULTS\compressed\2013-01-29 11_11_55.143_mixedSmallBeads_inAgarose_on_PDMS_green_blue\recording_lambda488nm_alpha5_beta100.mat'); end scanType='Bessel5'; scanDir='B'; deconvolvedTestData=strcmpi(scanType,'Airy'); [xRange,yRange,zRange,localizationData,testData]=loadFrom(inputFolder,['Airy_0',scanDir,'.mat'],[scanType,'_0',scanDir,'.mat'],deconvolvedTestData); outputPath=fullfile(inputFolder,['images',scanType,'.mat']); voxelSize=[diff(xRange(1:2)) diff(yRange(1:2)) diff(zRange(1:2))]; if (deconvolvedTestData) shiftInXYPerZ=[0 0]; else shiftInXYPerZ=[0.026 0.03]; end threshold=localizationData(1:16:end,1:16:end,1:16:end); backgroundLevel=0; %median(threshold(:)); threshold=quantile(threshold(:),.9999); hotSpots=localizationData>threshold; regions = regionprops(hotSpots, 'Centroid','BoundingBox'); boundingBoxes = cat(1, regions.BoundingBox); boundingBoxSizes=boundingBoxes(:,4:6).*repmat(voxelSize,[numel(regions) 1]); localizationBoxSize=[1.25 1.25 1.75]*1e-6; maxDevBoundingBoxSize=[1 1 1.5]*1e-6; projBoundingBoxSize=[5 5 30]*1e-6; displayBoundingBoxSize=[5 5 30]*1e-6; % % Co-register the testData % localizationSliceXZ=squeeze(mean(localizationData(:,abs(yRange)<5e-6,zRange<80e-6),2)); % testSliceXZ=squeeze(mean(testData(:,abs(yRange)<5e-6,zRange<80e-6),2)); % localizationSliceXY=squeeze(mean(localizationData(:,abs(yRange)<50e-6,zRange>40e-6 & zRange<80e-6),3)); % testSliceXY=squeeze(mean(testData(:,abs(yRange)<50e-6,zRange>40e-6 & zRange<80e-6),3)); % % [shiftXZ Greg] = dftregistration(fft2(localizationSliceXZ),fft2(testSliceXZ),100); % % dataShiftXZ=shiftXZ(3:4).*[diff(xRange(1:2)) diff(yRange(1:2))]; % [shiftXY Greg] = dftregistration(fft2(localizationSliceXY),fft2(testSliceXY),100); % dataShiftXY=shiftXY(3:4).*[diff(xRange(1:2)) diff(yRange(1:2))]; % figure();axs(1)=subplot(1,2,1);showImage(localizationSliceXZ,-1,zRange(zRange<80e-6)*1e6,xRange*1e6); axis equal; axs(2)=subplot(1,2,2);showImage(ifft2(Greg,'symmetric'),-1,zRange(zRange<80e-6)*1e6,xRange*1e6); axis equal; linkaxes(axs) % Filter out clusters and noise regions=regions(all(abs(boundingBoxSizes-repmat(localizationBoxSize,[numel(regions) 1])) < repmat(maxDevBoundingBoxSize,[numel(regions) 1]),2)); centroids = cat(1, regions.Centroid); centroids=centroids(:,[2 1 3]); centroids(:,1)=xRange(round(centroids(:,1))); centroids(:,2)=yRange(round(centroids(:,2))); centroids(:,3)=zRange(round(centroids(:,3))); centroids=sortrows(centroids,2); fwhmsZ=zeros(1,numel(regions)); fwhmsX=fwhmsZ; fwhmsY=fwhmsX; % shiftXYs=zeros(numel(regions),2); samples=[]; for beadIdx=1:numel(regions) centroid=centroids(beadIdx,:); xSel=abs(xRange-centroid(1))<=projBoundingBoxSize(1)/2; ySel=abs(yRange-centroid(2))<=projBoundingBoxSize(2)/2; zSel=abs(zRange-centroid(3))<=projBoundingBoxSize(3)/2; localizationDataSubCube=localizationData(xSel,ySel,zSel); localizationDataSubCubeProjZ=max(localizationDataSubCube,[],3); % Translate the test data cube back to origin shiftInXY=round(shiftInXYPerZ*centroid(3)./voxelSize(1:2)); testDataSubCube=testData(circshift(xSel,[0 shiftInXY(1)]),circshift(ySel,[0 shiftInXY(2)]),zSel); testDataSubCubeProjZ=max(testDataSubCube,[],3); if all(size(localizationDataSubCubeProjZ)==size(testDataSubCubeProjZ)) % % Test alignment % [shiftXY Greg] = dftregistration(fft2(localizationDataSubCubeProjZ),fft2(testDataSubCubeProjZ),10); % shiftXYs(beadIdx,:)=shiftXY(3:4); % testDataSubCube=circshift(testDataSubCube,1-round(shiftXYs(beadIdx,:))+floor(1+localizationBoxSize(1:2).*voxelSize(1:2)/2)); testDataProjectionZ=squeeze(mean(mean(testDataSubCube))).'; fwhmsZ(beadIdx)=calcFullWidthAtHalfMaximum(zRange(zSel),testDataProjectionZ-backgroundLevel,'Linear'); else fwhmsZ(beadIdx)=Inf; end % Find FWHM in lateral dimensions testDataProjectionX=squeeze(mean(mean(testDataSubCube,2),3)).'; fwhmsX(beadIdx)=calcFullWidthAtHalfMaximum(xRange(xSel),testDataProjectionX-backgroundLevel,'Linear'); testDataProjectionY=squeeze(mean(mean(testDataSubCube,1),3)).'; fwhmsY(beadIdx)=calcFullWidthAtHalfMaximum(xRange(xSel),testDataProjectionY-backgroundLevel,'Linear'); % % Store results % sample=struct(); sample.centroid=centroid; sample.fwhm=[fwhmsX(beadIdx) fwhmsY(beadIdx) fwhmsZ(beadIdx)]; % logMessage(sprintf('Propagation position: %0.1f um',sample.centroid(2)*1e6)); xSelDisplay=abs(xRange-sample.centroid(1))<displayBoundingBoxSize(1)/2; ySelDisplay=abs(yRange-sample.centroid(2))<displayBoundingBoxSize(2)/2; zSelDisplay=abs(zRange-sample.centroid(3))<displayBoundingBoxSize(3)/2; sample.xRange=xRange(xSelDisplay); sample.yRange=yRange(ySelDisplay); sample.zRange=zRange(zSelDisplay); sample.localization=struct(); sample.localization.proj1=squeeze(max(localizationData(xSelDisplay,ySelDisplay,zSelDisplay),[],1)).'; sample.localization.proj2=squeeze(max(localizationData(xSelDisplay,ySelDisplay,zSelDisplay),[],2)).'; sample.localization.proj3=squeeze(max(localizationData(xSelDisplay,ySelDisplay,zSelDisplay),[],3)); sample.test=struct(); % Translate the test data cube back to origin testDataSubCube=testData(circshift(xSelDisplay,[0 shiftInXY(1)]),circshift(ySelDisplay,[0 shiftInXY(2)]),zSelDisplay); sample.test.proj1=squeeze(max(testDataSubCube,[],1)).'; sample.test.proj2=squeeze(max(testDataSubCube,[],2)).'; sample.test.proj3=squeeze(max(testDataSubCube,[],3)); if (~isempty(samples)) samples(beadIdx)=sample; else samples=sample; end end save(outputPath,'samples'); % Plot results scatterFig=figure(); scatter(abs(centroids(:,2))*1e6,fwhmsZ*1e6,'+'); xlim([0 150]);ylim([0 50]); title([scanType,' ',scanDir]); end function [xRange yRange,zRange,localizationData,testData]=loadFrom(folderName,localizationDataFileName,fittingDataFileName,loadProcessedData) if (nargin<3 || isempty(fittingDataFileName)) fittingDataFileName=localizationDataFileName; end if (nargin<4) loadProcessedData=true; end load(fullfile(folderName,localizationDataFileName),'xRange'); load(fullfile(folderName,localizationDataFileName),'yRange'); load(fullfile(folderName,localizationDataFileName),'zRange'); localizationData=load(fullfile(folderName,localizationDataFileName),'restoredDataCube'); localizationData=localizationData.restoredDataCube; if loadProcessedData testData=load(fullfile(folderName,fittingDataFileName),'restoredDataCube'); testData=testData.restoredDataCube; else testData=load(fullfile(folderName,fittingDataFileName),'recordedImageStack'); testData=testData.recordedImageStack; end end
github
mc225/Softwares_Tom-master
processWaterImmersionLightSheetVideos.m
.m
Softwares_Tom-master/LightSheet/processWaterImmersionLightSheetVideos.m
12,633
utf_8
6028c4132c363cffd845cac365f8b6ed
% processWaterImmersionLightSheetVideos(folderNames,reprocessData,centerOffset,scanShear,perspectiveScaling) % % Reads the recorded date, converts it the matrices and deconvolves. % % Input: % folderNames: a string or cell array of strings indicating folders with avi and json files. % reprocessData: When false, date which already has a mat file with % a restoredDataCube matrix in it will be skipped. % centerOffset: The offset of the light sheet beam waist in meters given % as a two-element vector containing the vertical (swipe direction, Y) and the % horizontal (propagation direction, X) offset, respectivelly. % scanShear: The fraction change in x and y (vertical and horizontal) when moving in z (axially) % perspectiveScaling: The linear change in [x,y]=[vertical,horizontal] magnification when increasing z by one meter, units m^-1. % % % Note: projections can be shown using: % figure;axs=subplot(1,2,1);imagesc(yRange*1e6,zRange*1e6,squeeze(max(recordedImageStack,[],1)).');axis equal;axs(2)=subplot(1,2,2);imagesc(yRange*1e6,tRange*1e6,squeeze(max(restoredDataCube,[],1)).'); linkaxes(axs); % figure;imagesc(yRange*1e6,xRange*1e6,squeeze(max(recordedImageStack,[],3))); axis equal; % function processWaterImmersionLightSheetVideos(folderNames,reprocessData,centerOffset,scanShear,perspectiveScaling) if (nargin<1 || isempty(folderNames)) % folderNames={pwd()}; % folderNames={'20120815_215406_gain300_amph1'}; % folderNames='E:\RESULTS\TEST\2012-12-05 19_45_35.753'; % folderNames='E:\RESULTS\TEST\2012-12-06 19_07_05.401'; % folderNames='E:\RESULTS\TEST\2012-12-07 17_01_37.652'; % folderNames='E:\RESULTS\TEST\600nmBeadsInAgarose'; % folderNames='E:\RESULTS\TEST\600nmBeadsInAgarose_2'; % folderNames='E:\RESULTS\TEST\600nmBeadsInAgarose_3'; % folderNames='E:\RESULTS\TEST\600nmBeadsInAgarose_Andor'; % folderNames={'E:\RESULTS\TEST\HEK_Andor','E:\RESULTS\TEST\HEK_Andor2'}; % folderNames={'E:\RESULTS\TEST\HEK_Andor2','E:\RESULTS\TEST\2012-12-13 16_01_45.688'}; % folderNames={'E:\RESULTS\TEST\2013-01-14 17_19_36.146_greenblue_2um'}; % folderNames={'E:\RESULTS\2013_01_15_SmallBeadSample/','E:\RESULTS\2013_01_17_SmallBeadSample/','E:\RESULTS\2013_01_17_SmallBeadSample_2/'}; % folderNames={'E:\RESULTS\Amphioxus1'}; % folderNames={'E:\RESULTS\Amphioxus2'}; % folderNames={'E:\RESULTS\TEST\2013-01-29 11_11_55.143_mixedSmallBeads_inAgarose_on_PDMS_green_blue'}; % folderNames={'E:\RESULTS\smallBeadSample2'}; % folderNames={'E:\RESULTS\TEST\DoubleRingSampleHolder\2013-02-12_green_blue'}; % folderNames={'E:\RESULTS\NanoschellsInMCF7Spheroids'}; % folderNames={'E:\RESULTS\NonClippedAiry'}; % folderNames={'E:\RESULTS\NonClippedAiry3'}; % folderNames={'E:\RESULTS\BaslerTestForPerspectiveError'}; % folderNames={'E:\RESULTS\BaslerTestForPerspectiveError2\fullAp'}; % folderNames={'E:\RESULTS\BaslerTestForPerspectiveError2\2013-02-20 11_49_09.543_halfAp_blue_green'}; % folderNames={'E:\RESULTS\TEST\AciniMarch\NotFixedToSurface'}; % folderNames={'E:\RESULTS\TEST\AciniMarch7'}; % folderNames={'Z:\RESULTS\'}; % folderNames={'Z:\RESULTS\03_27_2013\'}; % folderNames={'Z:\RESULTS\2013-04-03\'}; % folderNames={'Z:\RESULTS\03_27_2013\Acini_1\2013-03-27 10_38_45.594'}; % folderNames={'Z:\RESULTS\03_27_2013\Bead_Test','Z:\RESULTS\03_27_2013\Acini_2\2013-03-27 10_43_10.564'}; % folderNames={'F:\RESULTS\04_03_2013_bluebeads'}; % folderNames={'F:\RESULTS\2013-04-04'}; % folderNames={'F:\RESULTS\March22'}; % folderNames={'F:\RESULTS\2013-04-05notmovingGaussian'}; % folderNames={'F:\RESULTS\2013-04-05b','F:\RESULTS\2013-04-05d'}; % folderNames={'F:\RESULTS\2013-04-08_multiColorBeads'}; % folderNames={'F:\RESULTS\600nmBeads100micronScanIncBessel_BackApOneThird'}; % folderNames={'F:\RESULTS\BeadsUnderAgarose100micronScan_BackApOneThird'}; % folderNames={'F:\RESULTS\mirrorScan'}; % folderNames={'F:\RESULTS\redbeads2013-04-18\2013-04-18 17_11_51.448'}; % folderNames={'F:\RESULTS\redbeads2013-04-19halfAp\2013-04-19 10_42_17.196'}; % folderNames={'F:\RESULTS\redbeads2013-04-19halfAp\2013-04-19 10_42_17.196'}; % folderNames={'F:\RESULTS\2013-04-22beads\'}; % folderNames={'F:\RESULTS\2013-04-22beads\2013-04-22 18_38_59.782\','F:\RESULTS\2013-04-22cellsHEK\','F:\RESULTS\2013-04-22cellsHEK2\'}; % folderNames={'F:\RESULTS\2013-04-23beadsApOneThird'}; % folderNames={'F:\RESULTS\2013-04-23HEK_ApOneThird'}; % folderNames={'F:\RESULTS\2013-04-24HEK_ApOneThird','F:\RESULTS\2013-04-24Amphioxus'}; % folderNames={'F:\RESULTS\redbeads2013-04-19halfAp\2013-04-19 10_42_17.196'}; % folderNames={'Z:\RESULTS\2013-04-24HEK_ApOneThird\'}; % folderNames={'Z:\RESULTS\2013-04-24HEK_ApOneThird\test'}; % folderNames={'Z:\RESULTS\2013-04-26HEK_ApOneThird'}; % folderNames={'Z:\RESULTS\2013-04-30 16_38_27.946_tiny'}; % folderNames={'Z:\RESULTS\2013-04-26HEK_ApOneThird'}; % folderNames={'Z:\RESULTS\2013-05-14_cellspheroidsWGA'}; % folderNames={'Z:\RESULTS\2013-05-15'}; % folderNames={'F:\RESULTS\2013-08-01_HEKdense','F:\RESULTS\2013-08-02_HEKdense1','F:\RESULTS\2013-08-02_HEKdense2','F:\RESULTS\2013-08-02_HEKdense3'}; % folderNames={'F:\RESULTS\2013-08-08','F:\RESULTS\2013-08-09'}; % center 1051 603 % folderNames={'F:\RESULTS\2013-08-29'}; % folderNames={'H:\RESULTS\'}; % folderNames={'F:\RESULTS\2013-08-29\HEKCellsApOneHalf'}; % folderNames={'H:\RESULTS\2013-09-06'}; % folderNames={'H:\RESULTS\2013-09-09_600nmRed_ApOneThird'}; % folderNames={'H:\RESULTS\2013-09-11 13_17_32.106 Bessel in Fluorescene'}; % folderNames={'H:\RESULTS\2013-09-11_600nmRed_ApOneThird_limitedScans\offsetScan'}; % [0 -63e-6] % folderNames={'H:\RESULTS\200nmBeadsApOneThird','H:\RESULTS\600nmBeadsApOneThird'}; % [0 0] % folderNames={'H:\RESULTS\2013-09-13_Amphioxus'}; % [0 0] % folderNames={'Z:\RESULTS\2013-04-10_Beads200nm'}; % folderNames={'Z:\RESULTS\2013-04-10_Beads200nm\2013-04-10 16_10_20.097_ApOneHalf'}; % folderNames={'Z:\RESULTS\2013-10-10_200nmBeadsNearEntranceInSmallAgaroseDroplet'}; % folderNames={'E:\Stored Files\RESULTS\Amphioxus'}; folderNames={'H:\RESULTS\2013-11-26_zebrafish_1','H:\RESULTS\2013-11-26_zebrafish_2'... ,'H:\RESULTS\2013-11-26_zebrafish_3','H:\RESULTS\2013-11-26_zebrafish_4','H:\RESULTS\2013-11-26_zebrafish_5'}; end if (nargin<2) % reprocessData=false; reprocessData=true; end if (nargin<3) % centerOffset=[0 -63e-6]; % [] == [0 0] means: don't change. % vertical horizontal centerOffset=[0 0]; end if (nargin<4) scanShear=[]; % [0 0.09]; % [fraction] vertical horizontal end if (nargin<5) perspectiveScaling=[]; % [0 500]; % [m^-1] vertical horizontal end if (ischar(folderNames)) folderNames={folderNames}; end %Load the default configuration functionName=mfilename(); configPath=mfilename('fullpath'); configPath=configPath(1:end-length(functionName)); defaultConfigFileName=strcat(configPath,'/waterImmersion.json'); defaultConfig=loadjson(defaultConfigFileName); % Go through all the specified folders for (folderName=folderNames(:).') folderName=folderName{1}; logMessage('Checking folder %s for recorded videos.',folderName); experimentConfigFileName=fullfile(folderName,'experimentConfig.json'); if (exist(experimentConfigFileName,'file')) experimentConfig=loadjson(experimentConfigFileName); else experimentConfig=struct(); experimentConfig.detector=struct(); experimentConfig.detector.center=[0 0]; experimentConfig.detector.scanShear=[0 0]; experimentConfig.detector.perspectiveScaling=[0 0]; end if (~isempty(centerOffset)) experimentConfig.detector.center=centerOffset; end if (~isempty(scanShear)) experimentConfig.detector.scanShear=scanShear; end if (~isempty(perspectiveScaling)) experimentConfig.detector.perspectiveScaling=perspectiveScaling; end savejson([],experimentConfig,experimentConfigFileName); experimentConfig=structUnion(defaultConfig,experimentConfig); % and process all videos videoFileNameList=dir(strcat(folderName,'/*.avi')); for (fileName={videoFileNameList.name}) fileName=fileName{1}(1:end-4); filePathAndName=strcat(folderName,'/',fileName); logMessage('Processing %s...',filePathAndName); % Load specific configuration description configFile=strcat(filePathAndName,'.json'); inputFileName=strcat(filePathAndName,'.avi'); outputFileName=strcat(filePathAndName,'.mat'); reprocessThisFile=true; if (~reprocessData && exist(outputFileName,'file')) storedVariables = whos('-file',outputFileName); if (ismember('restoredDataCube', {storedVariables.name})) reprocessThisFile=false; logMessage('Already done %s, skipping it!',outputFileName); end end if (reprocessThisFile) if (exist(configFile,'file')) try specificConfig=loadjson(configFile); % specificConfig.stagePositions.target=specificConfig.stagePositions.target*1e-6; % specificConfig.stagePositions.target=specificConfig.stagePositions.actual*1e-6; % savejson([],specificConfig,configFile); setupConfig=structUnion(experimentConfig,specificConfig); catch Exc logMessage('Could not read json config file %s, assuming defaults!',configFile); setupConfig=experimentConfig; end else logMessage('Description file with extension .json is missing, assuming defaults!'); end % Load recorded data logMessage('Loading %s...',inputFileName); try recordedImageStack=readDataCubeFromAviFile(inputFileName); catch Exc logMessage('Failed to load data stack from %s!',inputFileName); recordedImageStack=[]; end if (~isempty(recordedImageStack)) % Store partial results logMessage('Saving recorded data to %s...',outputFileName); save(outputFileName,'recordedImageStack','setupConfig', '-v7.3'); % Deconvolve logMessage('Starting image reconstruction...'); [recordedImageStack lightSheetDeconvFilter lightSheetOtf ZOtf xRange,yRange,zRange tRange lightSheetPsf]=deconvolveRecordedImageStack(recordedImageStack,setupConfig); restoredDataCube=recordedImageStack; clear recordedImageStack; % This operation does not take extra memory in Matlab % Append the rest of the results logMessage('Saving restored data cube to %s...',outputFileName); save(outputFileName,'restoredDataCube','xRange','yRange','zRange','tRange','ZOtf','lightSheetPsf','lightSheetOtf','lightSheetDeconvFilter','-append'); clear restoredDataCube; end else logMessage('Skipping file %s, already done.',inputFileName); end end % Check for subfolders and handles these recursively directoryList=dir(folderName); for listIdx=1:length(directoryList), if directoryList(listIdx).isdir && directoryList(listIdx).name(1)~='.' expandedFolderName=strcat(folderName,'/',directoryList(listIdx).name); processWaterImmersionLightSheetVideos(expandedFolderName,reprocessData); end end end end
github
mc225/Softwares_Tom-master
previewLightSheetRecording.m
.m
Softwares_Tom-master/LightSheet/previewLightSheetRecording.m
14,251
utf_8
bb3e71b726033e265c16bae42cd79784
% outputFullFileName=previewLightSheetRecording(fileNameGreen,fileNameRed) % % A function to show recorded light sheet movies before deconvolution. % The second argument is optional. % Instead of two arguments, both file names can be specified as a cell % array of strings % % Returns the full file name path to a video recording. % function outputFullFileName=previewLightSheetRecording(fileNameGreen,fileNameRed) close all force; if nargin>1 && ~isempty(fileNameRed) fullFileNames={fileNameGreen,fileNameRed}; else fullFileNames=fileNameGreen; if ~iscell(fullFileNames) fullFileNames={fullFileNames}; end end clear fileNameRed fileNameGreen; if isempty(fullFileNames) [fileNames,pathName]=uigetfile({'*.avi;*.tif;*.tiff;recording_*.mat','Image Sequences (*.avi,*.tif,*.tiff,recording_*.mat)';... '*.avi','AVI Videos (*.avi)';... '*.tif;*.tiff','TIFF Image Sequences (*.tif,*.tiff)';... 'recording_*.mat','Matlab Image Sequences (recording_*.mat)';... '*.*','All Files (*.*)'},... 'Select Recording(s)','recording_lambda488nm_alpha0_beta100.avi','MultiSelect','on'); if (~iscell(fileNames) && ~ischar(fileNames) && ~isempty(fileNames)) logMessage('File open canceled.'); return; end if (~iscell(fileNames)) fileNames={fileNames}; end fullFileNames={fullfile(pathName,fileNames{1})}; if (length(fileNames)>1) fullFileNames(2)=fullfile(pathName,fileNames{2}); end end try wavelength=regexpi(fullFileNames{1},'lambda([\d]*)nm_alpha[^\\/]+','tokens'); wavelengths(1)=str2double(wavelength{1})*1e-9; catch Exc jsonFile=[fullFileNames{1}(1:end-4),'.json']; if (exist(jsonFile)) setupConfig=loadjson(jsonFile); wavelengths(1)=setupConfig.excitation.wavelength; end end % If multiple files are specified, make sure that the first one is the green fluorescent one (488 excitation) if numel(fullFileNames)>=2 wavelength=regexpi(fullFileNames{2},'lambda([\d]*)nm_alpha[^\\/]+','tokens'); wavelengths(2)=str2double(wavelength{1})*1e-9; if (round(wavelengths(2)*1e9)==488) % Wrong order fullFileNames=fullFileNames{[2 1]}; wavelengths=wavelengths([2 1]); end end nbChannels=length(fullFileNames); %Open all video files nbFrames=Inf; for (channelIdx=1:nbChannels) fullFileName=fullFileNames{channelIdx}; logMessage('Reading channel from %s',fullFileName); fileExtension=lower(fullFileName(max(1,end-3):end)); switch (fileExtension) case '.avi' dataSource=VideoReader(fullFileName); imgSize = [dataSource.Height, dataSource.Width]; newNbFrames=dataSource.NumberOfFrames; nbFrames=min(nbFrames,newNbFrames); case '.mat' matFile=matfile(fullFileName,'Writable',false); dataSource=matFile; if (isprop(matFile,'restoredDataCube')) imgSize=whos(matFile,'restoredDataCube'); else if (isprop(matFile,'recordedImageStack')) imgSize=whos(matFile,'recordedImageStack'); else logMessage('Did not find deconvolvedDataCube nor recordedImageStack in %s!',fullFileName); return; end end imgSize=imgSize.size; nbFrames=imgSize(3); imgSize=imgSize(1:2); otherwise % Must be multi-page image info=imfinfo(fullFileName); imgSize=[info(1).Height info(1).Width]; nbFrames=length(info); dataSource=fullFileName; end dataSources{channelIdx}=dataSource; end [xRange yRange zRange alpha beta]=loadSettings(fullFileNames,[imgSize nbFrames]); nbChannels=length(fullFileNames); fig=figure('Visible','off','Units','pixels','CloseRequestFcn',@(obj,event) shutDown(obj),'Renderer','zbuffer'); getBaseFigureHandle(fig); loadStatus(); % Prepare video output. [outputPath, outputFileName]=fileparts(fullFileNames{1}); if (length(fullFileNames)>1) [~,outputFileName2]=fileparts(fullFileNames{2}); outputFileName=strcat(outputFileName,'_and_',outputFileName2); end outputFullFileName=fullfile(outputPath,strcat(outputFileName,'.mp4')); videoWriter=VideoWriter(outputFullFileName,'MPEG-4'); open(videoWriter); % Open the figure window setUserData('drawing',true); windowMargins=[1 1]*128; initialPosition=get(0,'ScreenSize')+[windowMargins -2*windowMargins]; set(fig,'Position',getStatus('windowPosition',initialPosition)); set(fig,'ResizeFcn',@(obj,event) updateStatus('windowPosition',get(obj,'Position'))); axs(1)=subplot(2,1,1,'Visible','off'); axs(2)=subplot(2,1,2,'Visible','off'); colorMaps{1}=@(values) interpolatedColorMap(values,[0 0 0; 0 1 0; 1 1 1],[0 .5 1]); colorMaps{2}=@(values) interpolatedColorMap(values,[0 0 0; 1 0 0; 1 1 1],[0 .5 1]); logMessage('Estimating SNR for %d channel(s)...',nbChannels); for (channelIdx=1:nbChannels) img=readDataCubeFromFile(dataSources{channelIdx},[],ceil(ceil(nbFrames/10)):ceil(nbFrames/5):nbFrames,false); normalizations(channelIdx)=1.333/max(img(:)); backgrounds(channelIdx)=median(median(min(img,[],3))); logMessage('Channel %d: background=%0.2f%%, normalization=%0.1fx.',[channelIdx 100*backgrounds(channelIdx) normalizations(channelIdx)]); end logMessage('Displaying %d channel(s)...',nbChannels); set(fig,'Visible','on'); projection=zeros(imgSize(2),nbFrames,nbChannels); setUserData('closing',false); frameIdx=0; while (~getUserData('closing') && frameIdx<nbFrames) frameIdx=frameIdx+1; img=zeros([imgSize nbChannels]); for (channelIdx=1:nbChannels) img(:,:,channelIdx)=readDataCubeFromFile(dataSources{channelIdx},[],frameIdx,false); end projectionSelection=1+floor(size(img,1)/2)+[-2:2]; projection(:,nbFrames-(frameIdx-1),:)=max(img(projectionSelection,:,:),[],1); if (mod(frameIdx,2)==1 || frameIdx==nbFrames) % Create a color image if (nbChannels==1) wideField=(img-backgrounds(1))*normalizations(1); topView=(projection-backgrounds(1))*normalizations(1); else wideField=zeros([size(img,1) size(img,2) 3]); for channelIdx=1:nbChannels wideField=wideField+mapColor((img(:,:,channelIdx)-backgrounds(channelIdx))*normalizations(channelIdx),colorMaps{channelIdx}); end topView=zeros([size(projection,1) size(projection,2) 3]); for channelIdx=1:nbChannels topView=topView+mapColor((projection(:,:,channelIdx)-backgrounds(channelIdx))*normalizations(channelIdx),colorMaps{channelIdx}); end end margins=[75 75; 10 10; 0 0]; % before; center; after wideFieldSize=[diff(yRange([1 end])) diff(xRange([1 end]))]; topViewSize=[diff(yRange([1 end])) diff(zRange([1 end]))]; windowSize=get(fig,'Position'); windowSize=windowSize(3:4)-sum(margins); wideFieldSize=wideFieldSize.*windowSize(1)/wideFieldSize(1); topViewSize=topViewSize.*windowSize(1)/topViewSize(1); scaling=min(1,windowSize(2)/(wideFieldSize(2)+topViewSize(2))); wideFieldSize=wideFieldSize*scaling; topViewSize=topViewSize*scaling; posOffset=margins(1,:)+(windowSize-[wideFieldSize(1) wideFieldSize(2)+topViewSize(2)])/2; showImage(wideField,[],yRange*1e6,xRange*1e6,axs(1)); set(axs(1),'Units','pixels','Position',[posOffset+[0 margins(2,2)+topViewSize(2)] wideFieldSize]); set(axs(1),'LineWidth',2,'TickDir','out','TickLength',[.01 .01]); set(axs(1),'XTick',[-1000:20:1000],'XTickLabel',[]); set(axs(1),'YTick',[-1000:20:1000],'FontSize',18,'FontWeight','bold'); ylabel(axs(1),'swipe [\mum]','FontSize',20,'FontWeight','bold'); showImage(permute(topView(:,end:-1:1,:),[2 1 3]),[],yRange*1e6,zRange*1e6,axs(2)); set(axs(2),'Units','pixels','Position',[posOffset topViewSize]); set(axs(2),'LineWidth',2,'TickDir','out','TickLength',[.01 .01]); set(axs(2),'XTick',[-1000:20:1000],'FontSize',18,'FontWeight','bold'); set(axs(2),'YTick',[-1000:20:1000],'FontSize',18,'FontWeight','bold'); xlabel(axs(2),'propagation [\mum]','FontSize',20,'FontWeight','bold'); ylabel(axs(2),'scan [\mum]','FontSize',20,'FontWeight','bold'); set(axs,'Visible','on'); linkaxes(axs,'x'); drawnow(); writeVideo(videoWriter,getFrame(fig)); end %Update the figure window title if (frameIdx<nbFrames) progressText=sprintf('%0.0f%%%% read - ',100*frameIdx/nbFrames); else progressText=''; end wavelengthText=[', lambda=',sprintf('%0.0fnm, ',wavelengths*1e9)]; if (length(wavelengths)<2), wavelengthText=wavelengthText(1:end-2); end set(gcf,'NumberTitle','off','Name',sprintf([progressText,'alpha=%0.0f, beta=%0.0f%%',wavelengthText],[alpha beta*100])); end % Close all video files for (channelIdx=1:nbChannels) dataSource=dataSources{channelIdx}; if (isa(dataSource,'VideoReader')) delete(dataSource); end end close(videoWriter); setUserData('drawing',false); if (getUserData('closing')) closereq(); end end function shutDown(obj,event) setUserData('closing',true); if (~getUserData('drawing')) closereq(); % else that routine will take care of closing the window end end function [xRange yRange zRange alpha beta]=loadSettings(specificConfigFileNames,dataCubeSize) %Load the configuration functionName=mfilename(); configPath=mfilename('fullpath'); configPath=configPath(1:end-length(functionName)); defaultConfigFileName=strcat(configPath,'/waterImmersion.json'); defaultConfig=loadjson(defaultConfigFileName); if (~iscell(specificConfigFileNames)) specificConfigFileNames={specificConfigFileNames}; end % Find a json file fileIdx=1; while(fileIdx<=length(specificConfigFileNames) && ~exist([specificConfigFileNames{fileIdx}(1:end-4),'.json'],'file')), fileIdx=fileIdx+1; end if (fileIdx<=length(specificConfigFileNames)) specificConfig=loadjson([specificConfigFileNames{fileIdx}(1:end-4),'.json']); config=structUnion(defaultConfig,specificConfig); else logMessage('Description file with extension .json is missing, trying to load .mat file.'); try matFile=matfile(specificConfigFileNames{1},'Writable',false); config=matFile.setupConfig; catch Exc logMessage('Failed... assuming defaults!'); config=defaultConfig; end end if (~isfield(config.detector,'center') || isempty(config.detector.center)) config.detector.center=[0 0]; end % Prepare the results stageTranslationStepSize=norm(median(diff(config.stagePositions.target))); realMagnification=config.detection.objective.magnification*config.detection.tubeLength/config.detection.objective.tubeLength; xRange=-config.detector.center(1)+config.detector.pixelSize(1)*([1:dataCubeSize(1)]-floor(dataCubeSize(1)/2)-1)/realMagnification; % up/down yRange=-config.detector.center(2)+config.detector.pixelSize(2)*([1:dataCubeSize(2)]-floor(dataCubeSize(2)/2)-1)/realMagnification; % left/right zRange=stageTranslationStepSize*([1:dataCubeSize(3)]-floor(dataCubeSize(3)/2+1))/config.detector.framesPerSecond; %Translation range (along z-axis) alpha=config.modulation.alpha; beta=config.modulation.beta; end % % Data access functions % % % User data function are 'global' variables linked to this GUI, though not % persistent between program shutdowns. % function value=getUserData(fieldName) fig=getBaseFigureHandle(); userData=get(fig,'UserData'); if (isfield(userData,fieldName)) value=userData.(fieldName); else value=[]; end end function setUserData(fieldName,value) if (nargin<2) value=fieldName; fieldName=inputname(1); end fig=getBaseFigureHandle(); userData=get(fig,'UserData'); userData.(fieldName)=value; set(fig,'UserData',userData); end function fig=getBaseFigureHandle(fig) persistent persistentFig; if (nargin>=1) if (~isempty(fig)) persistentFig=fig; else clear persistentFig; end else fig=persistentFig; end end % % 'Status' variables are stored persistently to disk and reloaded next time % function loadStatus(pathToStatusFile) if (nargin<1 || isempty(pathToStatusFile)) pathToStatusFile=[mfilename('fullpath'),'.mat']; end try load(pathToStatusFile,'status'); catch Exc status={}; status.version=-1; end status.pathToStatusFile=pathToStatusFile; setUserData('status',status); end function value=getStatus(fieldName,defaultValue) status=getUserData('status'); if (isfield(status,fieldName)) value=status.(fieldName); else if (nargin<2) defaultValue=[]; end value=defaultValue; end end function updateStatus(fieldName,value) status=getUserData('status'); status.(fieldName)=value; setUserData('status',status); saveStatus(); end function saveStatus() status=getUserData('status'); save(status.pathToStatusFile,'status'); end
github
mc225/Softwares_Tom-master
createResolutionPlots.m
.m
Softwares_Tom-master/LightSheet/createResolutionPlots.m
5,848
utf_8
3926c9cb0e53005fde863d823f74127a
% createResolutionPlots(sourceFolder) % % function createResolutionPlots(sourceFolder) if nargin<1 || isempty(sourceFolder) sourceFolder=uigetdir('.','Select Data Folder...'); if (isempty(sourceFolder)) logMessage('User cancelled'); return; end end sliceWidth=10e-6; perspectiveScaling=[0 500]; %[373.4900 722.6800]; scanShear=[0 .16]; folderDescs=dir(sourceFolder); for folderIdx=1:length(folderDescs) folderDesc=folderDescs(folderIdx); if folderDesc.isdir && ~ismember(folderDesc.name,{'.','..'}) tokens=regexp(folderDesc.name,'(\d\d\d\d-\d\d-\d\d\ \d\d_\d\d_\d\d\.\d\d\d )?at(_?)(\d+)um$','tokens'); if ~isempty(tokens) approximateOffset=str2double(tokens{1}{3})*1e-6; if ~strcmp(tokens{1}{2},'_') approximateOffset=-approximateOffset; end inputFolder=fullfile(sourceFolder,folderDesc.name); targetFolder=fullfile([sourceFolder,'_sliced'],folderDesc.name); logMessage('Creating folder %s...',targetFolder); mkdir(targetFolder); fileDescs=dir(fullfile(inputFolder,'recording_*.mat')); inputFileNames=arrayfun(@(fn) fullfile(inputFolder,fn.name),fileDescs,'UniformOutput',false); outputFileNames=arrayfun(@(fn) fullfile(targetFolder,fn.name),fileDescs,'UniformOutput',false); for fileIdx=1:length(inputFileNames) inputMatFile=matfile(inputFileNames{fileIdx},'Writable',false); % Prepare slicing limits=approximateOffset+[-0.5 0.5]*sliceWidth; xRange=inputMatFile.xRange; yRange=inputMatFile.yRange+63e-6; zRange=inputMatFile.zRange; selectedIndexes=find(yRange>=limits(1) & yRange<=limits(2)); %Slice yRange=yRange(1,selectedIndexes); recordedImageStack=inputMatFile.recordedImageStack(:,selectedIndexes,:); restoredDataCube=inputMatFile.restoredDataCube(:,selectedIndexes,:); lightSheetPsf=inputMatFile.lightSheetPsf(1,selectedIndexes,:); ZOtf=inputMatFile.ZOtf; setupConfig=inputMatFile.setupConfig; delete(inputMatFile); effectiveNA=setupConfig.excitation.fractionOfNumericalApertureUsed*setupConfig.excitation.objective.numericalAperture; spFreqCutOff=(2*effectiveNA)/setupConfig.excitation.wavelength; recordedImageStack=geometricCorrection(scanShear,perspectiveScaling,xRange,yRange,zRange,recordedImageStack); recordedImageStack=recordedImageStack-median(recordedImageStack(:)); %Subtract background noise % Find maximum intensity axialProj=sum(recordedImageStack,3); [~, maxI]=max(axialProj(:)); [maxRow maxCol]=ind2sub(size(axialProj),maxI); %Select some pixels around it and integrate %intensityTrace=recordedImageStack(maxRow+[-1:1],maxCol+[-1:1],:); intensityTrace=recordedImageStack(:,:,:); intensityTrace=squeeze(mean(mean(intensityTrace))); % Calculate MTF mtf=fft(intensityTrace([1:end end*ones(1,floor(end/2)) 1*ones(1,floor((1+end)/2))])); mtf=mtf./mtf(1); mtf=fftshift(abs(mtf)); fig=figure('Position',[50 50 1024 768]); subplot(2,2,1); plot(zRange*1e6,intensityTrace); xlabel('z [um]'); subplot(2,2,2); plot(ZOtf*1e-3,mtf); xlim([0 spFreqCutOff*1e-3]); xlabel('\nu_z [cycles/mm]'); % showImage(squeeze(max(recordedImageStack,[],1)).',-1,yRange*1e6,zRange*1e6); subplot(2,2,3); imagesc(yRange*1e6,zRange*1e6,squeeze(max(recordedImageStack,[],1)).'); axis equal; xlabel('x [\mum]'); ylabel('z [\mum]'); subplot(2,2,4); imagesc(xRange*1e6,zRange*1e6,squeeze(max(recordedImageStack,[],2)).'); axis equal; xlabel('y [\mum]'); ylabel('z [\mum]'); title(inputFileNames{fileIdx}); saveas(fig,[inputFileNames{fileIdx}(1:end-4),'.png'],'png'); close(fig); end end end end end function recordedImageStack=geometricCorrection(scanShear,scaling,xRange,yRange,zRange,recordedImageStack) cubicInterpolation=true; if (~all(scanShear==0) || ~all(scaling==0)) % Geometrically correcting recorded data cube and light sheet logMessage('Geometrically shifting and deforming recorded date cube and light sheet by [%0.3f%%,%0.3f%%] and a magnification change of [%0.3f%%,%0.3f%%] per micrometer...',-[scanShear scaling*1e-6]*100); for (zIdx=1:size(recordedImageStack,3)) zPos=zRange(zIdx); sampleXRange = scanShear(1)*zPos + xRange*(1-scaling(1)*zPos); sampleYRange = scanShear(2)*zPos + yRange*(1-scaling(2)*zPos); if (cubicInterpolation) interpolatedSlice=interp2(yRange.',xRange,recordedImageStack(:,:,zIdx),sampleYRange.',sampleXRange,'*cubic',0); else interpolatedSlice=interp2(yRange.',xRange,recordedImageStack(:,:,zIdx),sampleYRange.',sampleXRange,'*linear',0); end recordedImageStack(:,:,zIdx)=interpolatedSlice; end end end