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
mehta-lab/Instantaneous-PolScope-master
overlayPositionOrientation.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/overlayPositionOrientation.m
9,980
utf_8
ef6930d0f6004cdd62ddcf79d3c20649
function [movOrient,hAxisOverlay,hAxisIntensity,xstart,ystart,xend,yend]=overlayPositionOrientation(xPart,yPart,anisoPart,orientPart,intPart,polstack,varargin) % [movOrient,hAxisOverlay,hAxisIntensity,xstart,ystart,xend,yend]=overlayPositionOrientation(xPart,yPart,anisoPart,orientPart,intPart,polstack,varargin) % Function that overlays positon and orientation information on image. params.Parent=NaN; % Set to NaN to create new figure. Set to 0 to use the axes handles supplied below. params.IntensityAxes=NaN; % If Parent is NaN of if the handle is valid, intensity image is drawn. params.OrientationAxes=NaN; params.drawParticlesOn='average'; %params.intensityImage=params.drawParticlesOn; params.delay=0.05; params.glyphDiameter=6; params.lineLength=50; % Line-length corresponding to anisotropy of 1 when length is set proportional to anisotropy. If this is set to zero, no line is drawn. params.lineLengthProp=true; params.intensityRange=[0 0]; params.anisotropyRange=[0 1]; params.orientationRange=[0 180]; params.excludeAboveOrientation=false; params.referenceOrientation=0; params.colorMap='sbm'; params.glyphColor='green'; params.glyphLineWidth=2; params.roiX=NaN; params.roiY=NaN; params.scalePix=1/0.07; params.xdata=[1 size(polstack,2)]; params.ydata=[1 size(polstack,1)]; params.anisoScale=true; params.clims=NaN; params=parsepropval(params,varargin{:}); if(isnan(params.Parent)) hfigOrient=togglefig('Overlay of images and particles.'); set(hfigOrient,'Position',[100 100 1400 700],'color','w'); colormap gray; delete(get(hfigOrient,'Children')); hAxisIntensity=axes('Parent',hfigOrient,'Position',[0.1 0.1 0.4 0.9]); hAxisOverlay=axes('Parent',hfigOrient,'Position',[0.5 0.1 0.4 0.9]); linkaxes([hAxisIntensity hAxisOverlay]); elseif(ishandle(params.Parent) && params.Parent>0) hfigOrient=params.Parent; delete(get(hfigOrient,'Children')); hAxisIntensity=axes('Parent',hfigOrient,'Position',[0.1 0.1 0.4 0.9]); hAxisOverlay=axes('Parent',hfigOrient,'Position',[0.5 0.1 0.4 0.9]); linkaxes([hAxisIntensity hAxisOverlay]); else % If params.Parent is 0, assume that required axes are supplied independently. hAxisIntensity=params.IntensityAxes; hAxisOverlay=params.OrientationAxes; if(ishandle(hAxisIntensity) && ishandle(hAxisOverlay)) linkaxes([hAxisIntensity hAxisOverlay]); end end % Select particles based on intensity. if all(params.intensityRange) intensityMask=intPart>params.intensityRange(1) & intPart<params.intensityRange(2); else intensityMask=~isnan(intPart); %NaNs in intPart matrix are excluded. params.intensityRange=[min(~isnan(intPart)) max(~isnan(intPart))]; end % Select based on anisotropy. anisotropyMask=(anisoPart >= params.anisotropyRange(1) ) & ... (anisoPart <= params.anisotropyRange(2) ); % Select based on orientation. % Convert to radians. params.orientationRange=params.orientationRange*(pi/180); orientPartFilter=mod(orientPart-params.referenceOrientation,pi); % The orientation w.r.t. reference is used to select what particles are % drawn. % But, the particle orientation must not be changed. orientationMask= (orientPartFilter > params.orientationRange(1)) & ... (orientPartFilter < params.orientationRange(2)); if(params.excludeAboveOrientation) % Exclude above orientation. orientationMask=~orientationMask; end useParticles=intensityMask & anisotropyMask & orientationMask; % Determine display limits if(isnumeric(params.drawParticlesOn)) % If 3D matrix. % Reshape into 4D matrix to match with format of polstack and orientationmap. drawParticlesOn=reshape(params.drawParticlesOn,size(params.drawParticlesOn,1),size(params.drawParticlesOn,2),[],size(params.drawParticlesOn,3)); elseif(ischar(params.drawParticlesOn)) % If string switch(params.drawParticlesOn) case 'average' drawParticlesOn= polstack(:,:,3,:); case 'anisotropy' drawParticlesOn=polstack(:,:,1,:); case 'orientation' drawParticlesOn= polstack(:,:,2,:); case 'orientationmap' drawParticlesOn=pol2color(squeeze(polstack(:,:,1,:)),... squeeze(polstack(:,:,2,:)),... squeeze(polstack(:,:,3,:)),... params.colorMap,'legend',false,'avgCeiling',params.intensityRange(2),'anisoCeiling',params.anisotropyRange(2)); end end % if(isnumeric(params.intensityImage)) % If 3D matrix. % % Reshape into 4D matrix to match with format of polstack and orientationmap. % intensityImage=reshape(params.intensityImage,size(params.intensityImage,1),size(params.intensityImage,2),[],size(params.intensityImage,3)); % elseif(ischar(params.intensityImage)) % If string % switch(params.intensityImage) % case 'average' % intensityImage= polstack(:,:,3,:); % case 'anisotropy' % intensityImage=polstack(:,:,1,:); % case 'orientation' % intensityImage= polstack(:,:,2,:); % case 'orientationmap' % intensityImage=pol2color(squeeze(polstack(:,:,1,:)),... % squeeze(polstack(:,:,2,:)),... % squeeze(polstack(:,:,3,:)),... % params.colorMap,'legend',false,'avgCeiling',params.intensityRange(2),'anisoCeiling',params.anisotropyRange(2)); % end % end if(isnan(params.clims)) clims=[min(drawParticlesOn(:)) max(drawParticlesOn(:))]; else clims=params.clims; end for frameno=1:size(drawParticlesOn,4) hold off; % if(isnumeric(params.drawParticlesOn)) % If 3D matrix. % drawImage(xdata,ydata,params.drawParticlesOn(:,:,frameno),[hImg hOverlay],params.roiX,params.roiY,clims); % elseif(ischar(params.drawParticlesOn)) % If string % switch(params.drawParticlesOn) % case 'average' % drawImage(xdata,ydata,polstack(:,:,3,frameno),[hImg hOverlay],params.roiX,params.roiY,clims); % case 'anisotropy' % drawImage(xdata,ydata,polstack(:,:,1,frameno),[hImg hOverlay],params.roiX,params.roiY,clims); % case 'orientation' % drawImage(xdata,ydata,polstack(:,:,2,frameno),[hImg hOverlay],params.roiX,params.roiY,clims); % case 'orientationmap' % colormap=pol2color(polstack(:,:,1,frameno),polstack(:,:,2,frameno),polstack(:,:,3,frameno),params.colorMap,'legend',true); % drawImage(xdata,ydata,colormap,[hImg hOverlay],params.roiX,params.roiY,clims); % end % end drawImage(params.xdata,params.ydata,drawParticlesOn(:,:,:,frameno),hAxisOverlay,params.roiX,params.roiY,clims,params.scalePix); drawImage(params.xdata,params.ydata,drawParticlesOn(:,:,:,frameno),hAxisIntensity,params.roiX,params.roiY,clims,params.scalePix); particlesToDraw=useParticles(:,frameno)'; xcen=xPart(:,frameno)'.*particlesToDraw; ycen=yPart(:,frameno)'.*particlesToDraw; orientcen=orientPart(:,frameno)'.*particlesToDraw; % intead of (X-,Y-) to (X+,Y+) we need to do (X-,Y+), (X+,Y-), since Y % axis runs from top to bottom, whereas we perceive and measure angle % assuming Y running from bottom to top. axes(hAxisOverlay); % Draw the particles on overlay axes. hold on; if(params.lineLength) % since particles can have a wide range of intensities, it is not a % good idea to scale line lengths with intensity. lineL=0.5*params.lineLength; % Half the line length; if(params.lineLengthProp) lineLParticles=bsxfun(@times,lineL,anisoPart(:,frameno)'); end xstart=xcen-lineLParticles.*cos(orientcen); xend=xcen+lineLParticles.*cos(orientcen); ystart=ycen+lineLParticles.*sin(orientcen); yend=ycen-lineLParticles.*sin(orientcen); %%quiver(xcen,ycen,cos(orientcen),sin(orientcen),0,'ShowArrowHead','off','AutoScale','on','Marker','o'); line([xstart;xend],[ystart;yend],'color',params.glyphColor,'LineWidth',params.glyphLineWidth); if(params.anisoScale) line([2 2*lineL+2],[2 2],'color',params.glyphColor,'LineWidth',4); text(2,-5,'anisotropy=1','FontSize',18,'color',params.glyphColor); end end plot(xcen,ycen,'o','MarkerEdgeColor',params.glyphColor,'LineWidth',params.glyphLineWidth,'MarkerSize',params.glyphDiameter); % drawnow; % Make sure figure is updated, before taking a screenshot. pause(params.delay); % Delay so that figure is updated. frameOrient=frame2im(getframe(hAxisOverlay)); %getframe is better than screencapture, because it updates the figures before capture. if(ishandle(hAxisIntensity)) frameImg=frame2im(getframe(hAxisIntensity)); % Construct the frame frameImg=imresize(frameImg,[size(frameOrient,1) size(frameOrient,2)]); thisframe=cat(2,frameImg,frameOrient); movOrient(:,:,:,frameno)=imresize(thisframe,[600 NaN]); else movOrient(:,:,:,frameno)=imresize(frameOrient,[600 NaN]); %thisframe=frame2im(getframe(hfigOrient)); end end end function drawImage(xdata,ydata,img,haxes,roiX,roiY,clims,scalePix) if(~isnan(roiX) && ~isnan(roiY)) xlims=[min(roiX) max(roiX)]; ylims=[min(roiY) max(roiY)]; else xlims=xdata; ylims=ydata; end for idx=1:numel(haxes) if(ishandle(haxes(idx))) axes(haxes(idx)); imagesc(xdata,ydata,squeeze(img),clims); axis equal; axis tight; ylim([ydata(1)-20 ydata(end)]); set(gca,'XTick',[],'YTick',[]); hold on; plot([roiX; roiX(1)],[roiY; roiY(1)],'--w','Linewidth',1.5); xlim(xlims); ylim(ylims) if(scalePix) line([xlims(1)+2 xlims(1)+2+scalePix],[ylims(2)-2 ylims(2)-2],'color','w','LineWidth',5); end hold off; end end end
github
mehta-lab/Instantaneous-PolScope-master
exportHyperStack.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/exportHyperStack.m
2,931
utf_8
456d02abfb6eb940fa93b8e6412c4906
function exportHyperStack(stackData, filename,varargin) % exportHyperStack(stackData, filename) exports multi-D data as ImageJ % hyperstack assuming XYCZT order of the dimensions. % Usage: % teststack=zeros(100,100,8,5,'uint16'); % exportHyperStack(teststack,'test_hyperstack.tif'); % % % arg=parsepropval(arg,varargin{:}); % parse image dimentions & type channelsN = size(stackData,3); slicesN = size(stackData,4); framesN = size(stackData,5); imagesN = channelsN * slicesN * framesN; xN=size(stackData,2); yN=size(stackData,1); % % loop dims % for t=1:framesN % for s=1:slicesN % for c=1:channelN % if (t==1 && s==1 && c==1) % imwrite(stackData(:,:,c,s,t),fullfile(filename),'tiff','Compression','none','WriteMode','overwrite'); % else % imwrite(stackData(:,:,c,s,t),fullfile(filename),'tiff','Compression','none','WriteMode','append'); % end % end % end % end % Or use saveastiff to write the entire stack - allows writing double/single stacks. saveastiff(reshape(stackData,[yN xN imagesN]),filename); % Now write metadata that allows ImageJ to open the file correctly. writeHyperStackTag(filename,xN,yN,channelsN,slicesN,framesN) end function writeHyperStackTag(filename,xN,yN,channelsN,slicesN,framesN) % Writing following Metadata entry to TIFF stack converts it into % Hyperstack. The default write order in hyperstack is XYCZT. % This function contributed by Amitabh Verma. imagesN=channelsN*slicesN*framesN; % http://metarabbit.wordpress.com/2014/04/30/building-imagej-hyperstacks-from-python/ metadata_text = char([ ['ImageJ=1.48o', 10],... ['ImageLength=', num2str(yN), 10],... ['ImageWidth=', num2str(xN), 10],... ['images=', num2str(imagesN), 10],... ['channels=', num2str(channelsN), 10],... ['slices=', num2str(slicesN), 10],... ['frames=', num2str(framesN), 10],... ['hyperstack=true', 10],... ['mode=grayscale', 10],... ['loop=false', 10],... ['IsInterleaved=false',10],... ]); t = Tiff(fullfile(filename), 'r+'); % Modify the value of a tag. % http://www.digitalpreservation.gov/formats/content/tiff_tags.shtml % t.setTag('Software',['OI-DIC',' ',num2str(version_number),'x']); % t.setTag('Model', 'Lumenera Infinity 3M'); % set tag t.setTag('ImageDescription', metadata_text); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Orientation tag is critical for ImageJ to display the hyperstack correctly. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% t.setTag('Orientation',Tiff.Orientation.TopLeft); % write tag to file t.rewriteDirectory(); % close tiff t.close() end
github
mehta-lab/Instantaneous-PolScope-master
TIFFStack.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/@TIFFStack/TIFFStack.m
13,989
utf_8
287162d4012fbcbc09fd0bf123b35837
% TIFFStack - Manipulate a TIFF file like a tensor % % Usage: tsStack = TIFFStack(strFilename <, bInvert>) % % A TIFFStack object behaves like a read-only memory mapped TIF file. The % entire image stack is treated as a matlab tensor. Each frame of the file must % have the same dimensions. Reading the image data is optimised to the extent % possible; the header information is only read once. % % This class uses a modified version of tiffread [1, 2] to read data. Code is % included (but disabled) to use the matlab imread function, but this function % returns invalid data for some TIFF formats. % % Construction: % % >> tsStack = TIFFStack('test.tiff'); % Construct a TIFF stack associated with a file % % >> tsStack = TIFFStack('test.tiff', true); % Indicate that the image data should be inverted % % tsStack = % % TIFFStack handle % % Properties: % bInvert: 0 % strFilename: [1x9 char] % sImageInfo: [5x1 struct] % strDataClass: 'uint16' % % Usage: % % >> tsStack(:, :, 3); % Retrieve the 3rd frame of the stack, all planes % % >> tsStack(:, :, 1, 3); % Retrieve the 3rd plane of the 1st frame % % >> size(tsStack) % Find the size of the stack (rows, cols, frames, planes per pixel) % % ans = % % 128 128 5 1 % % >> tsStack(4); % Linear indexing is supported % % >> tsStack.bInvert = true; % Turn on data inversion % % References: % [1] Francois Nedelec, Thomas Surrey and A.C. Maggs. Physical Review Letters % 86: 3192-3195; 2001. DOI: 10.1103/PhysRevLett.86.3192 % % [2] http://www.embl.de/~nedelec/ % Author: Dylan Muir <[email protected]> % Created: 28th June, 2011 classdef TIFFStack < handle properties bInvert; % - A boolean flag that determines whether or not the image data will be inverted end properties (SetAccess = private) strFilename = []; % - The name of the TIFF file on disk sImageInfo; % - The TIFF header information strDataClass; % - The matlab class in which data will be returned end properties (SetAccess = private, GetAccess = private) vnStackSize; TIF; % \_ Cached header infor for tiffread29 speedups HEADER; % / end methods % TIFFStack - CONSTRUCTOR function oStack = TIFFStack(strFilename, bInvert) % - Check for inversion flag if (~exist('bInvert', 'var')) bInvert = false; end oStack.bInvert = bInvert; % - See if filename exists if (~exist(strFilename, 'file')) error('TIFFStack:InvalidFile', ... '*** TIFFStack: File [%s] does not exist.', strFilename); end % - Assign absolute file path to stack oStack.strFilename = get_full_file_path(strFilename); % - Get image information try % - Read and save image information sInfo = imfinfo(strFilename); oStack.sImageInfo = sInfo; % - Read TIFF header for tiffread29 [oStack.TIF, oStack.HEADER] = tiffread29_header(strFilename); % - Use imread to get the data class for this tiff % fPixel = imread(strFilename, 'TIFF', 1, 'PixelRegion', {[1 1], [1 1]}); % oStack.strDataClass = class(fPixel); % - Use tiffread29 to get the data class for this tiff fPixel = tiffread29_readimage(oStack.TIF, oStack.HEADER, 1); fPixel = fPixel(1, 1, :); oStack.strDataClass = class(fPixel); % - Record stack size oStack.vnStackSize = [sInfo(1).Height sInfo(1).Width numel(sInfo) numel(fPixel)]; catch mErr base_ME = MException('TIFFStack:InvalidFile', ... '*** TIFFStack: Could not open file [%s].', strFilename); new_ME = addCause(base_ME, mErr); throw(new_ME); end end % delete - DESTRUCTOR function delete(oStack) % - Close the TIFF file, if opened by tiffread29_header if (isfield(oStack.TIF, 'file')) fclose(oStack.TIF.file); end end %% --- Overloaded subsref function [tfData] = subsref(oStack, S) switch S(1).type case '()' nNumDims = numel(S.subs); nNumStackDims = numel(oStack.vnStackSize); % - Check dimensionality and trailing dimensions if (nNumDims == 1) % - Translate from linear refs to indices nNumDims = nNumStackDims; % - Translate colon indexing if (isequal(S.subs{1}, ':')) S.subs{1} = (1:prod(oStack.vnStackSize))'; end % - Get equivalent subscripted indexes [S.subs{1:nNumDims}] = ind2sub(oStack.vnStackSize, S.subs{1}); elseif (nNumDims < nNumStackDims) % - Assume trailing references are ':" S.subs(nNumDims+1:nNumStackDims) = {':'}; elseif (nNumDims > nNumStackDims) % - Check for non-colon references vbNonColon = cellfun(@(c)(~ischar(c) | ~isequal(c, ':')), S.subs); % - Check only trailing dimensions vbNonColon(1:nNumStackDims) = false; % - Check trailing dimensions for non-'1' indices if (any(cellfun(@(c)(~isequal(c, 1)), S.subs(vbNonColon)))) % - This is an error error('TIFFStack:badsubscript', ... '*** TIFFStack: Index exceeds stack dimensions.'); end % - Only keep relevant dimensions S.subs = S.subs(1:nNumStackDims); end % - Access stack tfData = TS_read_data_tiffread(oStack, S.subs); % - Reshape return data to concatenate trailing dimensions (just as % matlab does) if (nNumDims < nNumStackDims) cnSize = num2cell(size(tfData)); tfData = reshape(tfData, cnSize{1:nNumDims-1}, []); end case '.' tfData = builtin('subsref', oStack, S); otherwise error('TIFFStack:InvalidReferencing', ... '*** TIFFStack: Only ''()'' referencing is supported by TIFFStacks.'); end end %% --- Overloaded size function [varargout] = size(oStack, vnDimensions) % - Return the size of the stack vnSize = oStack.vnStackSize; % - Return specific dimension(s) if (exist('vnDimensions', 'var')) if (~isnumeric(vnDimensions)) error('TIFFStack:dimensionMustBePositiveInteger', ... '*** TIFFStack: Dimensions argument must be a positive integer within indexing range.'); end % - Return the specified dimension(s) vnSize = vnSize(vnDimensions); end % - Handle differing number of size dimensions and number of output % arguments nNumArgout = max(1, nargout); if (nNumArgout == 1) % - Single return argument -- return entire size vector varargout{1} = vnSize; elseif (nNumArgout <= numel(vnSize)) % - Several return arguments -- return single size vector elements, % with the remaining elements grouped in the last value varargout(1:nNumArgout-1) = num2cell(vnSize(1:nNumArgout-1)); varargout{nNumArgout} = prod(vnSize(nNumArgout:end)); else %(nNumArgout > numel(vnSize)) % - Output all size elements varargout(1:numel(vnSize)) = num2cell(vnSize); % - Deal out trailing dimensions as '1' varargout(numel(vnSize)+1:nNumArgout) = {1}; end end %% --- Property accessors % set.bInvert - SETTER method for 'bInvert' function set.bInvert(oStack, bInvert) % - Check contents if (~islogical(bInvert) || ~isscalar(bInvert)) error('TIFFStack:invalidArgument', ... '*** TIFFStack/set.bInvert: ''bInvert'' must be a logical scalar.'); else % - Assign bInvert value oStack.bInvert = bInvert; end end end end %% --- Helper functions --- % TS_read_data_imread - FUNCTION Read the requested pixels from the TIFF file (using imread) % % Usage: [tfData] = TS_read_data_imread(oStack, cIndices) % % 'oStack' is a TIFFStack. 'cIndices' are the indices passed in from subsref. % Colon indexing will be converted to full range indexing. Reading is optimsed, % by only reading pixels in a minimal-size window surrouding the requested % pixels. cIndices is a cell array with the format {rows, cols, frames, % slices}. Slices are RGB or CMYK or so on. function [tfData] = TS_read_data_imread(oStack, cIndices) %#ok<DEFNU> % - Convert colon indexing vbIsColon = cellfun(@(c)(isequal(c, ':')), cIndices); for (nColonDim = find(vbIsColon)) cIndices{nColonDim} = 1:oStack.vnStackSize(nColonDim); end % - Check ranges vnMinRange = cellfun(@(c)(min(c)), cIndices); vnMaxRange = cellfun(@(c)(max(c)), cIndices); if (any(vnMinRange < 1) || any(vnMaxRange > oStack.vnStackSize)) error('TIFFStack:badsubscript', ... '*** TIFFStack: Index exceeds stack dimensions.'); end % - Allocate large tensor vnBlockSize = vnMaxRange(1:2) - vnMinRange(1:2) + [1 1]; vnBlockSize(3) = numel(cIndices{3}); vnBlockSize(4) = oStack.vnStackSize(4); tfDataBlock = zeros(vnBlockSize, oStack.strDataClass); cBlock = {[vnMinRange(1) vnMaxRange(1)] [vnMinRange(2) vnMaxRange(2)]}; % - Loop over frames to read data block try % - Disable warnings wOld = warning('off', 'MATLAB:rtifc:notPhotoTransformed'); for (nFrame = 1:numel(cIndices{3})) %#ok<FORPF> tfDataBlock(:, :, nFrame, :) = imread(oStack.strFilename, 'TIFF', cIndices{3}(nFrame), 'PixelRegion', cBlock); end % - Re-enable warnings warning(wOld); catch mErr % - Record error state base_ME = MException('TIFFStack:ReadError', ... '*** TIFFStack: Could not read data from image file.'); new_ME = addCause(base_ME, mErr); throw(new_ME); end % - Do we need to resample the data block? bResample = any(~vbIsColon(1:3)); if (bResample) cIndices{1} = cIndices{1} - vnMinRange(1) + 1; cIndices{2} = cIndices{2} - vnMinRange(2) + 1; tfData = tfDataBlock(cIndices{1}, cIndices{2}, :, cIndices{4}); else tfData = tfDataBlock; end % - Invert data if requested if (oStack.bInvert) tfData = oStack.sImageInfo(1).MaxSampleValue - (tfData - oStack.sImageInfo(1).MinSampleValue); end end % TS_read_data_tiffread - FUNCTION Read the requested pixels from the TIFF file (using tiffread29) % % Usage: [tfData] = TS_read_data_imread(oStack, cIndices) % % 'oStack' is a TIFFStack. 'cIndices' are the indices passed in from subsref. % Colon indexing will be converted to full range indexing. cIndices is a cell % array with the format {rows, cols, frames, slices}. Slices are RGB or CMYK % or so on. function [tfData] = TS_read_data_tiffread(oStack, cIndices) % - Convert colon indexing vbIsColon = cellfun(@(c)(ischar(c) & isequal(c, ':')), cIndices); for (nColonDim = find(vbIsColon)) cIndices{nColonDim} = 1:oStack.vnStackSize(nColonDim); end % - Check ranges vnMinRange = cellfun(@(c)(min(c)), cIndices); vnMaxRange = cellfun(@(c)(max(c)), cIndices); if (any(vnMinRange < 1) || any(vnMaxRange > oStack.vnStackSize)) error('TIFFStack:badsubscript', ... '*** TIFFStack: Index exceeds stack dimensions.'); end % - Allocate large tensor vnBlockSize = oStack.vnStackSize(1:2); vnBlockSize(3) = numel(cIndices{3}); vnBlockSize(4) = oStack.vnStackSize(4); tfDataBlock = zeros(vnBlockSize, oStack.strDataClass); % - Read data block try tfDataBlock = tiffread29_readimage(oStack.TIF, oStack.HEADER, cIndices{3}); catch mErr % - Record error state base_ME = MException('TIFFStack:ReadError', ... '*** TIFFStack: Could not read data from image file.'); new_ME = addCause(base_ME, mErr); throw(new_ME); end % - Do we need to resample the data block? bResample = any(~vbIsColon(1:3)); if (bResample) tfData = tfDataBlock(cIndices{1}, cIndices{2}, :, cIndices{4}); else tfData = tfDataBlock; end % - Invert data if requested if (oStack.bInvert) tfData = oStack.sImageInfo(1).MaxSampleValue - (tfData - oStack.sImageInfo(1).MinSampleValue); end end % get_full_file_path - FUNCTION Calculate the absolute path to a given (possibly relative) filename % % Usage: strFullPath = get_full_file_path(strFile) % % 'strFile' is a filename, which may include relative path elements. The file % does not have to exist. % % 'strFullPath' will be the absolute path to the file indicated in 'strFile'. function strFullPath = get_full_file_path(strFile) [strDir, strName, strExt] = fileparts(strFile); if (isempty(strDir)) strDir = '.'; end strFullDirPath = cd(cd(strDir)); strFullPath = fullfile(strFullDirPath, [strName strExt]); end
github
mehta-lab/Instantaneous-PolScope-master
tiffread29_header.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/@TIFFStack/private/tiffread29_header.m
14,865
utf_8
35a2408a96acaa8010a29500dba775cf
function [TIF, HEADER] = tiffread29_header(filename) %% set defaults values : TIF.BOS = 'ieee-le'; %byte order string TIF.strFilename = filename; consolidateStrips = true; if isempty(findstr(filename,'.')) filename = [filename,'.tif']; end TIF.file = fopen(filename,'r','l'); if TIF.file == -1 stkname = strrep(filename, '.tif', '.stk'); TIF.file = fopen(stkname,'r','l'); if TIF.file == -1 error('tiffread2:filenotfound', ['File "',filename,'" not found.']); else filename = stkname; end end [s, m] = fileattrib(filename); % obtain the full file path: filename = m.Name; %% read header % read byte order: II = little endian, MM = big endian byte_order = fread(TIF.file, 2, '*char'); if ( strcmp(byte_order', 'II') ) TIF.BOS = 'ieee-le'; % Intel little-endian format elseif ( strcmp(byte_order','MM') ) TIF.BOS = 'ieee-be'; else error('tiffread2:notATIF', 'This is not a TIFF file (no MM or II).'); end %% ---- read in a number which identifies file as TIFF format tiff_id = fread(TIF.file,1,'uint16', TIF.BOS); if (tiff_id ~= 42) error('tiffread2:notATIF', 'This is not a TIFF file (missing 42).'); end %% ---- read the byte offset for the first image file directory (IFD) nCurrImg = 1; HEADER(nCurrImg).img_pos = fread(TIF.file, 1, 'uint32', TIF.BOS); nImgIndex = 1; while HEADER(nCurrImg).img_pos ~= 0 % - Defaults HEADER(nCurrImg).SampleFormat = 1; HEADER(nCurrImg).SamplesPerPixel = 1; % move in the file to the first IFD status = fseek(TIF.file, HEADER(nCurrImg).img_pos, -1); if status == -1 error('tiffread2:readerr', 'invalid file offset (error on fseek)'); end %disp(strcat('reading img at pos :',num2str(TIF.img_pos))); %read in the number of IFD entries num_entries = fread(TIF.file,1,'uint16', TIF.BOS); %disp(strcat('num_entries =', num2str(num_entries))); %read and process each IFD entry for i = 1:num_entries % save the current position in the file file_pos = ftell(TIF.file); % read entry tag entry_tag = fread(TIF.file, 1, 'uint16', TIF.BOS); % read entry entry = readIFDentry(TIF, entry_tag); switch entry_tag case 254 HEADER(nCurrImg).NewSubfiletype = entry.val; case 256 % image width - number of column HEADER(nCurrImg).width = entry.val; case 257 % image height - number of row HEADER(nCurrImg).height = entry.val; HEADER(nCurrImg).ImageLength = entry.val; case 258 % BitsPerSample per sample HEADER(nCurrImg).BitsPerSample = entry.val; HEADER(nCurrImg).BytesPerSample = HEADER(nCurrImg).BitsPerSample / 8; HEADER(nCurrImg).bits = HEADER(nCurrImg).BitsPerSample(1); %fprintf('BitsPerSample %i %i %i\n', entry.val); case 259 % compression if ( entry.val ~= 1 ) error('tiffread2:unsupported', ['Compression format ', num2str(entry.val),' not supported.']); end case 262 % photometric interpretation HEADER(nCurrImg).PhotometricInterpretation = entry.val; if ( HEADER(nCurrImg).PhotometricInterpretation == 3 ) warning('tiffread2:LookUp', 'Ignoring TIFF look-up table'); end case 269 HEADER(nCurrImg).document_name = entry.val; case 270 % comments: HEADER(nCurrImg).info = entry.val; case 271 HEADER(nCurrImg).make = entry.val; case 273 % strip offset HEADER(nCurrImg).StripOffsets = entry.val; HEADER(nCurrImg).StripNumber = entry.cnt; %fprintf('StripNumber = %i, size(StripOffsets) = %i %i\n', TIF.StripNumber, size(TIF.StripOffsets)); case 277 % sample_per pixel HEADER(nCurrImg).SamplesPerPixel = entry.val; %fprintf('Color image: sample_per_pixel=%i\n', TIF.SamplesPerPixel); case 278 % rows per strip HEADER(nCurrImg).RowsPerStrip = entry.val; case 279 % strip byte counts - number of bytes in each strip after any compressio HEADER(nCurrImg).StripByteCounts= entry.val; case 282 % X resolution HEADER(nCurrImg).x_resolution = entry.val; case 283 % Y resolution HEADER(nCurrImg).y_resolution = entry.val; case 284 %planar configuration describe the order of RGB HEADER(nCurrImg).PlanarConfiguration = entry.val; case 296 % resolution unit HEADER(nCurrImg).resolution_unit= entry.val; case 305 % software HEADER(nCurrImg).software = entry.val; case 306 % datetime HEADER(nCurrImg).datetime = entry.val; case 315 HEADER(nCurrImg).artist = entry.val; case 317 %predictor for compression if (entry.val ~= 1); error('tiffread2:unsupported', 'unsuported predictor value'); end case 320 % color map HEADER(nCurrImg).cmap = entry.val; HEADER(nCurrImg).colors = entry.cnt/3; case 339 HEADER(nCurrImg).SampleFormat = entry.val; case 33550 % GeoTIFF ModelPixelScaleTag HEADER(nCurrImg).ModelPixelScaleTag = entry.val; case 33628 %metamorph specific data HEADER(nCurrImg).MM_private1 = entry.val; case 33629 %this tag identify the image as a Metamorph stack! TIF.MM_stack = entry.val; TIF.MM_stackCnt = entry.cnt; case 33630 %metamorph stack data: wavelength HEADER(nCurrImg).MM_wavelength = entry.val; case 33631 %metamorph stack data: gain/background? HEADER(nCurrImg).MM_private2 = entry.val; case 33922 % GeoTIFF ModelTiePointTag IMG.ModelTiePointTag = entry.val; case 34412 % Zeiss LSM data HEADER(nCurrImg).LSM_info = entry.val; case 34735 % GeoTIFF GeoKeyDirectory HEADER(nCurrImg).GeoKeyDirTag = entry.val; case 34737 % GeoTIFF GeoASCIIParameters HEADER(nCurrImg).GeoASCII = entry.val; case 42113 % GeoTIFF GDAL_NODATA HEADER(nCurrImg).GDAL_NODATA = entry.val; otherwise warning('tiffread2:ignored_tag', 'Ignored TIFF entry with tag %i (cnt %i)\n', entry_tag, entry.cnt); end % calculate bounding box if you've got the stuff if isfield(HEADER(nCurrImg), 'ModelPixelScaleTag') && isfield(HEADER(nCurrImg), 'ModelTiePointTag') && isfield(HEADER(nCurrImg), 'height')&& isfield(HEADER(nCurrImg), 'width'), HEADER(nCurrImg).North=HEADER(nCurrImg).ModelTiePointTag(5)-HEADER(nCurrImg).ModelPixelScaleTag(2)*HEADER(nCurrImg).ModelTiePointTag(2); HEADER(nCurrImg).South=HEADER(nCurrImg).North-HEADER(nCurrImg).height*HEADER(nCurrImg).ModelPixelScaleTag(2); HEADER(nCurrImg).West=HEADER(nCurrImg).ModelTiePointTag(4)+HEADER(nCurrImg).ModelPixelScaleTag(1)*HEADER(nCurrImg).ModelTiePointTag(1); HEADER(nCurrImg).East=HEADER(nCurrImg).West+HEADER(nCurrImg).width*HEADER(nCurrImg).ModelPixelScaleTag(1); end % move to next IFD entry in the file status = fseek(TIF.file, file_pos+12, -1); if status == -1 error('tiffread2:readerr', 'invalid file offset (error on fseek)'); end end %Planar configuration is not fully supported %Per tiff spec 6.0 PlanarConfiguration irrelevent if SamplesPerPixel==1 %Contributed by Stephen Lang if (HEADER(nCurrImg).SamplesPerPixel ~= 1) && ( ~isfield(HEADER(nCurrImg), 'PlanarConfiguration') || HEADER(nCurrImg).PlanarConfiguration == 1 ) error('tiffread2:unsupported', 'PlanarConfiguration = 1 is not supported'); end %total number of bytes per image: PlaneBytesCnt = HEADER(nCurrImg).width * HEADER(nCurrImg).height * HEADER(nCurrImg).BytesPerSample; %% try to consolidate the TIFF strips if possible if consolidateStrips %Try to consolidate the strips into a single one to speed-up reading: BytesCnt = HEADER(nCurrImg).StripByteCounts(1); if BytesCnt < PlaneBytesCnt ConsolidateCnt = 1; %Count how many Strip are needed to produce a plane while HEADER(nCurrImg).StripOffsets(1) + BytesCnt == HEADER(nCurrImg).StripOffsets(ConsolidateCnt+1) ConsolidateCnt = ConsolidateCnt + 1; BytesCnt = BytesCnt + HEADER(nCurrImg).StripByteCounts(ConsolidateCnt); if ( BytesCnt >= PlaneBytesCnt ); break; end end %Consolidate the Strips if ( BytesCnt <= PlaneBytesCnt(1) ) && ( ConsolidateCnt > 1 ) %fprintf('Consolidating %i stripes out of %i', ConsolidateCnt, TIF.StripNumber); HEADER(nCurrImg).StripByteCounts = [BytesCnt; HEADER(nCurrImg).StripByteCounts(ConsolidateCnt+1:HEADER(nCurrImg).StripNumber ) ]; HEADER(nCurrImg).StripOffsets = HEADER(nCurrImg).StripOffsets( [1 , ConsolidateCnt+1:HEADER(nCurrImg).StripNumber] ); HEADER(nCurrImg).StripNumber = 1 + HEADER(nCurrImg).StripNumber - ConsolidateCnt; end end end %% Record the next IFD address: HEADER(nCurrImg+1).img_pos = fread(TIF.file, 1, 'uint32', TIF.BOS); %if (TIF.img_pos) disp(['next ifd at', num2str(TIF.img_pos)]); end % - Record the start of the image data for this image HEADER(nCurrImg).nImageOffset = ftell(TIF.file); % - Skip to next image nCurrImg = nCurrImg + 1; end % clean-up HEADER = HEADER(1:end-1); % fclose(TIF.file); end %% ==================sub-functions that reads an IFD entry:=================== function [nbBytes, matlabType] = convertType(tiffType) switch (tiffType) case 1 nbBytes=1; matlabType='uint8'; case 2 nbBytes=1; matlabType='uchar'; case 3 nbBytes=2; matlabType='uint16'; case 4 nbBytes=4; matlabType='uint32'; case 5 nbBytes=8; matlabType='uint32'; case 7 nbBytes=1; matlabType='uchar'; case 11 nbBytes=4; matlabType='float32'; case 12 nbBytes=8; matlabType='float64'; otherwise error('tiffread2:unsupported', 'tiff type %i not supported', tiffType) end end %% ==================sub-functions that reads an IFD entry:=================== function entry = readIFDentry(TIF, entry_tag) entry.tiffType = fread(TIF.file, 1, 'uint16', TIF.BOS); entry.cnt = fread(TIF.file, 1, 'uint32', TIF.BOS); %disp(['tiffType =', num2str(entry.tiffType),', cnt = ',num2str(entry.cnt)]); [ entry.nbBytes, entry.matlabType ] = convertType(entry.tiffType); if entry.nbBytes * entry.cnt > 4 %next field contains an offset: offset = fread(TIF.file, 1, 'uint32', TIF.BOS); %disp(strcat('offset = ', num2str(offset))); status = fseek(TIF.file, offset, -1); if status == -1 error('tiffread2:corrupted', 'invalid file offset (error on fseek)'); end end if entry_tag == 33629 % metamorph 'rationals' entry.val = fread(TIF.file, 6*entry.cnt, entry.matlabType, TIF.BOS); elseif entry_tag == 34412 %TIF_CZ_LSMINFO entry.val = readLSMinfo(TIF); else if entry.tiffType == 5 entry.val = fread(TIF.file, 2*entry.cnt, entry.matlabType, TIF.BOS); else entry.val = fread(TIF.file, entry.cnt, entry.matlabType, TIF.BOS); end end if ( entry.tiffType == 2 ); entry.val = char(entry.val'); end end %% ==============partial-parse of LSM info: function R = readLSMinfo(TIF) % Read part of the LSM info table version 2 % this provides only very partial information, since the offset indicate that % additional data is stored in the file R.MagicNumber = sprintf('0x%09X',fread(TIF.file, 1, 'uint32', TIF.BOS)); StructureSize = fread(TIF.file, 1, 'uint32', TIF.BOS); R.DimensionX = fread(TIF.file, 1, 'uint32', TIF.BOS); R.DimensionY = fread(TIF.file, 1, 'uint32', TIF.BOS); R.DimensionZ = fread(TIF.file, 1, 'uint32', TIF.BOS); R.DimensionChannels = fread(TIF.file, 1, 'uint32', TIF.BOS); R.DimensionTime = fread(TIF.file, 1, 'uint32', TIF.BOS); R.IntensityDataType = fread(TIF.file, 1, 'uint32', TIF.BOS); R.ThumbnailX = fread(TIF.file, 1, 'uint32', TIF.BOS); R.ThumbnailY = fread(TIF.file, 1, 'uint32', TIF.BOS); R.VoxelSizeX = fread(TIF.file, 1, 'float64', TIF.BOS); R.VoxelSizeY = fread(TIF.file, 1, 'float64', TIF.BOS); R.VoxelSizeZ = fread(TIF.file, 1, 'float64', TIF.BOS); R.OriginX = fread(TIF.file, 1, 'float64', TIF.BOS); R.OriginY = fread(TIF.file, 1, 'float64', TIF.BOS); R.OriginZ = fread(TIF.file, 1, 'float64', TIF.BOS); R.ScanType = fread(TIF.file, 1, 'uint16', TIF.BOS); R.SpectralScan = fread(TIF.file, 1, 'uint16', TIF.BOS); R.DataType = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetVectorOverlay = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetInputLut = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetOutputLut = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetChannelColors = fread(TIF.file, 1, 'uint32', TIF.BOS); R.TimeInterval = fread(TIF.file, 1, 'float64', TIF.BOS); OffsetChannelDataTypes = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetScanInformation = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetKsData = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetTimeStamps = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetEventList = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetRoi = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetBleachRoi = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetNextRecording = fread(TIF.file, 1, 'uint32', TIF.BOS); % There are more information stored in this table, which is not read here %read real acquisition times: if ( OffsetTimeStamps > 0 ) status = fseek(TIF.file, OffsetTimeStamps, -1); if status == -1 error('tiffread2:readerror', 'error on fseek'); end StructureSize = fread(TIF.file, 1, 'int32', TIF.BOS); NumberTimeStamps = fread(TIF.file, 1, 'int32', TIF.BOS); for i=1:NumberTimeStamps R.TimeStamp(i) = fread(TIF.file, 1, 'float64', TIF.BOS); end %calculate elapsed time from first acquisition: R.TimeOffset = R.TimeStamp - R.TimeStamp(1); end end
github
mehta-lab/Instantaneous-PolScope-master
tiffread29_readimage.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/@TIFFStack/private/tiffread29_readimage.m
4,906
utf_8
f3afa2f5e5294c9f00734aecee2a8473
function [data, stack] = tiffread29_readimage(TIF, HEADER, vnFrames) % - Preallocate data block classname = get_data_class(HEADER(vnFrames(1)), 1); data = zeros(HEADER(vnFrames(1)).height, HEADER(vnFrames(1)).width, numel(vnFrames), HEADER(vnFrames(1)).SamplesPerPixel, classname); stack = []; for (nFrame = numel(vnFrames):-1:1) % Go backwards to pre-allocate % - Skip to image offset fseek(TIF.file, HEADER(nFrame).nImageOffset, 'bof'); if isfield( TIF, 'MM_stack' ) % This part reads a metamorph TIF % Only take existing frames vnFrames = vnFrames(vnFrames <= TIF.MM_stackCnt); %this loop reads metamorph stacks: for ii = vnFrames StripCnt = 1; offset = PlaneBytesCnt * (ii-1); %read the image channels for c = 1:HEADER(vnFrames(nFrame)).SamplesPerPixel data(:, :, nFrame, c) = read_plane(TIF, HEADER(vnFrames(nFrame)), offset, c, StripCnt); end [ IMG.MM_stack, IMG.MM_wavelength, IMG.MM_private2 ] = splitMetamorph(ii, TIF); stack(nFrame) = IMG; %#ok<AGROW> end else %this part reads a normal TIFF stack: StripCnt = 1; %read the image channels for c = 1:HEADER(nFrame).SamplesPerPixel data(:, :, nFrame, c) = read_plane(TIF, HEADER(vnFrames(nFrame)), 0, c, StripCnt); end end end end %% =========================================================================== function plane = read_plane(TIF, HEADER_frame, offset, plane_nb, StripCnt) %return an empty array if the sample format has zero bits if ( HEADER_frame.BitsPerSample(plane_nb) == 0 ) plane=[]; return; end %fprintf('reading plane %i size %i %i\n', plane_nb, width, height); classname = get_data_class(HEADER_frame, plane_nb); % Preallocate a matrix to hold the sample data: try plane = zeros(HEADER_frame.height, HEADER_frame.width, classname); catch %compatibility with older matlab versions: eval(['plane = ', classname, '(zeros(HEADER_frame.height, HEADER_frame.width));']); end % Read the strips and concatenate them: line = 1; while ( StripCnt <= HEADER_frame.StripNumber ) strip = read_strip(TIF, HEADER_frame, offset, plane_nb, StripCnt, classname); StripCnt = StripCnt + 1; % copy the strip onto the data plane(line:(line+size(strip,1)-1), :) = strip; line = line + size(strip,2); if ( line > HEADER_frame.height ) break; end end % Extract valid part of data if needed if ~all(size(plane) == [HEADER_frame.height HEADER_frame.width]), plane = plane(1:HEADER_frame.height, 1:HEADER_frame.width); warning('tiffread2:Crop','Cropping data: found more bytes than needed'); end end %% ================== sub-functions to read a strip =================== function strip = read_strip(TIF, HEADER_frame, offset, plane_nb, stripCnt, classname) %fprintf('reading strip at position %i\n',TIF.StripOffsets(stripCnt) + offset); StripLength = HEADER_frame.StripByteCounts(stripCnt) ./ HEADER_frame.BytesPerSample(plane_nb); %fprintf( 'reading strip %i\n', stripCnt); status = fseek(TIF.file, HEADER_frame.StripOffsets(stripCnt) + offset, 'bof'); if status == -1 error('tiffread2:readerr', 'invalid file offset (error on fseek)'); end bytes = fread( TIF.file, StripLength, classname, TIF.BOS ); if any( length(bytes) ~= StripLength ) error('tiffread2:corrupted', 'End of file reached unexpectedly.'); end strip = reshape(bytes, HEADER_frame.width, StripLength / HEADER_frame.width)'; end %% =============distribute the metamorph infos to each frame: function [MMstack, MMwavelength, MMprivate2] = splitMetamorph(imgCnt) global TIF; MMstack = []; MMwavelength = []; MMprivate2 = []; if TIF.MM_stackCnt == 1 return; end left = imgCnt - 1; if isfield( TIF, 'MM_stack' ) S = length(TIF.MM_stack) / TIF.MM_stackCnt; MMstack = TIF.MM_stack(S*left+1:S*left+S); end if isfield( TIF, 'MM_wavelength' ) S = length(TIF.MM_wavelength) / TIF.MM_stackCnt; MMwavelength = TIF.MM_wavelength(S*left+1:S*left+S); end if isfield( TIF, 'MM_private2' ) S = length(TIF.MM_private2) / TIF.MM_stackCnt; MMprivate2 = TIF.MM_private2(S*left+1:S*left+S); end end %% === determine the data class for this frame function strClass = get_data_class(HEADER_frame, plane_nb) %determine the type needed to store the pixel values: switch( HEADER_frame.SampleFormat ) case 1 strClass = sprintf('uint%i', HEADER_frame.BitsPerSample(plane_nb)); case 2 strClass = sprintf('int%i', HEADER_frame.BitsPerSample(plane_nb)); case 3 if ( HEADER_frame.BitsPerSample(plane_nb) == 32 ) strClass = 'single'; else strClass = 'double'; end otherwise error('tiffread2:unsupported', 'unsuported TIFF sample format %i', HEADER_frame.SampleFormat); end end
github
mehta-lab/Instantaneous-PolScope-master
calibReg.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/@RTFluorPol/calibReg.m
12,545
utf_8
256ebdffb16c8ef50c262cdac506894f
function calibReg(self,Ireg,varargin) % calibReg(RTFluorPolObject,Ireg,'Property','value') % Property Possible values (Default in bracket) % 'regMethod' ('manual'),'matlab','phasecor','reset' % 'preProcReg' ('none'),'lowpass','edge' % 'diagnosis' (true), false. % 'regType' 'translation',('rigid'),'similarity' (valid only for % automated regMethods) %% Process optional parameters. params.regMethod='auto'; params.preProcReg='none'; params.diagnosis=true; params.regType='similarity'; params.Parent=NaN; % Parent canvas on which to draw the images. Useful when calibReg is used as a callback within GUI. params.regEndCallBack=NaN; % Function to execute after the registration 'ends'. This is used for updating the calling GUI. params=parsepropval(params,varargin{:}); %% See if the registration should be reset. if(isempty(Ireg) || any(isnan(Ireg(:)))) % Reset registration. self.tformI45=eye(3); self.tformI90=eye(3); self.tformI135=eye(3); %return; end %% Crop and normalize. switch(params.regMethod) case {'AUTO','auto','reset'} % Starting with current registration typically leads to better % registration when performing auto-reg. [I0, I45, I90, I135]=self.quadstoPolStack(Ireg,'computeWhat','Channels'); case 'manual' % Manual registration function always uses un-registered images % as reference. It does use current registration stored in the % class. [I0, I45, I90, I135]=self.quadstoPolStack(Ireg,'computeWhat','Channels','register',false); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% switch(params.preProcReg) case 'none' % No filtering is good for punctate images like beads. I0BeforeReg=I0; I45BeforeReg=I45; I90BeforeReg=I90; I135BeforeReg=I135; case 'lowpass' % Lowpass is good for noisy images. freqcut=self.ObjectiveNA/(self.Wavelength); I0BeforeReg=opticalLowpassInterpolation(I0,self.PixSize,freqcut,1); I45BeforeReg=opticalLowpassInterpolation(I45,self.PixSize,freqcut,1); I90BeforeReg=opticalLowpassInterpolation(I90,self.PixSize,freqcut,1); I135BeforeReg=opticalLowpassInterpolation(I135,self.PixSize,freqcut,1); case 'edge' % Edge is good for transmission image and % Compute gradients of registration data to enhance sensitivity to % registration mismatch. % sigma=(0.5*self.Wavelength/self.objectiveNA)/self.PixSize; % At this sigma, anisotropic intensity distribution at the % sub-resolution scale is smoothed out, leaving only the % above-resolution mismatches in location. sigma=(0.2*self.Wavelength/self.ObjectiveNA)/self.PixSize; % Use this sigma for isotropic specimens to improve the registration. I0BeforeReg=gradcalc(I0,sigma); I45BeforeReg=gradcalc(I45,sigma); I90BeforeReg=gradcalc(I90,sigma); I135BeforeReg=gradcalc(I135,sigma); otherwise error('filterReg parameter should be :''none'', ''lowpass'', or ''edge'''); end %% Calculate registration. switch(params.regMethod) case {'AUTO','auto'} % self.coordinates='centered'; % x=self.xaxis/self.PixSize; y=1:self.quadHeight; % [I90RegToI0, tformI90toI0,I90x,I90y,I90cor]=imregphasecor(I0BeforeReg,I90BeforeReg,... % x,y,'rigid','pos','pixel',min(I90BeforeReg(:))); %#ok<ASGLU,NASGU> % [I135RegToI45, tformI135toI45,I135x,I135y,I135cor]=imregphasecor(I45BeforeReg,I135BeforeReg,... % x,y,'rigid','pos','pixel',min(I90BeforeReg(:))); %#ok<ASGLU,NASGU> % S2=I45BeforeReg-I135RegToI45; % S1=I0BeforeReg-I90RegToI0; % [S2RegToS1, tformS2toS1,S2x,S2y,S2cor]=imregphasecor(S1,S2,... % x,y,'rigid','pos','pixel',min(I135BeforeReg(:))); %#ok<ASGLU,NASGU> % if verLessThan('images','9.0') error('Optimization-based registration is available only for Image Processing Toolbox ver 9.0 (release 2014a) or later.'); end % I90 and I0 share the splitter, so do I135 and I45. xLims=0.5*[-size(I0BeforeReg,2) size(I0BeforeReg,2)]; yLims=0.5*[-size(I0BeforeReg,1) size(I0BeforeReg,1)]; R=imref2d(size(I0BeforeReg),xLims,yLims); [optimizer, metric] = imregconfig('monomodal'); optimizer.MaximumStepLength=0.05; optimizer.MinimumStepLength=1E-6; optimizer.MaximumIterations = 500; [tformI90,I90RegToI0] = regQuads(I90BeforeReg,I0BeforeReg,R,optimizer,metric); [tformI45,I45RegToI0] = regQuads(I45BeforeReg,I0BeforeReg,R,optimizer,metric); [tformI135,I135RegToI0] = regQuads(I135BeforeReg,I0BeforeReg,R,optimizer,metric); % S2=I45BeforeReg-I135RegToI45; % S1=I0BeforeReg-I90RegToI0; % % [tformS2toS1,S2RegToS1]=regQuads(S2,S1,R,optimizer,metric); % % self.tformI45=tformS2toS1; % self.tformI90=tformI90toI0; % self.tformI135=tformS2toS1*tformI135toI45; self.tformI90=tformI90.T*self.tformI90; self.tformI45=tformI45.T*self.tformI45; self.tformI135=tformI135.T*self.tformI135; % Important to sync the shifts with transform matrix. [self.I45xShift, self.I45yShift,self.I45xScale, self.I45yScale, self.I45Rotation ]=affineToShiftScaleRot(self.tformI45); [self.I90xShift, self.I90yShift, self.I90xScale, self.I90yScale, self.I90Rotation]=affineToShiftScaleRot(self.tformI90); [self.I135xShift, self.I135yShift, self.I135xScale, self.I135yScale, self.I135Rotation]=affineToShiftScaleRot(self.tformI135); % case {'MATLAB','matlab'} % %Note: MATLAB computes registration in non-centered frame, % %whereas we assume centered frame for manual registration and % %phase-corraltion based registration. % % if verLessThan('images','9.0') % error('Optimization-based registration is available only for Image Processing Toolbox ver 9.0 (release 2014a) or later.'); % end % self.coordinates='matlab'; % [optimizer,metric]=imregconfig('monomodal'); % optimizer.MaximumIterations = 500; % optimizer.MinimumStepLength = 5e-6; % tform=imregtform(I90BeforeReg,I0BeforeReg,params.regType,optimizer,metric); % tformI90toI0=tform.tdata.T; % I90RegToI0=imtransformAffineMat(I90BeforeReg, tformI90toI0, 'linear'); % % tform=imregtform(I135BeforeReg,I45BeforeReg,params.regType,optimizer,metric); % tformI135toI45=tform.tdata.T; % I135RegToI45=imtransformAffineMat(I135BeforeReg, tformI135toI45, 'linear'); % % S2=abs(I45BeforeReg- I135RegToI45); % S1=abs(I0BeforeReg-I90RegToI0); % tform=imregtform(S2,S1,params.regType,optimizer,metric); % tformS2toS1=tform.tdata.T; % % S2RegToS1=imtransformAffineMat(S2, tformS2toS1, 'linear'); % % self.tformI45=tformS2toS1; % self.tformI90=tformI90toI0; % self.tformI135=tformS2toS1*tformI135toI45; case 'manual' self.regQuadsManual(... I0BeforeReg,I45BeforeReg,I90BeforeReg,I135BeforeReg,... 'Parent',params.Parent,'regEndCallBack',params.regEndCallBack); case 'reset' self.tformI45=eye(3); self.tformI90=eye(3); self.tformI135=eye(3); % Important to sync the shifts with transform matrix. [self.I45xShift, self.I45yShift,self.I45xScale, self.I45yScale, self.I45Rotation ]=affineToShiftScaleRot(self.tformI45); [self.I90xShift, self.I90yShift, self.I90xScale, self.I90yScale, self.I90Rotation]=affineToShiftScaleRot(self.tformI90); [self.I135xShift, self.I135yShift, self.I135xScale, self.I135yScale, self.I135Rotation]=affineToShiftScaleRot(self.tformI135); otherwise error(['Registration function ' params.regMethod ' not implemented.']); end % Registration complete. Run the end callback. if(isa(params.regEndCallBack,'function_handle')) params.regEndCallBack(); end %% Generate a diagnostic plot if user asked for it. No need to generate diagnostic plots for manual registration. if(params.diagnosis && ~strcmpi(params.regMethod,'manual')) % Obtain the images after registration. [I0AfterReg, I45AfterReg, I90AfterReg, I135AfterReg]=self.quadstoPolStack(Ireg,'computeWhat','Channels'); switch(params.preProcReg) case 'none' % No filtering is good for punctate images like beads. case 'lowpass' % Lowpass is good for noisy images. freqcut=self.ObjectiveNA/(self.Wavelength); I0AfterReg=opticalLowpassInterpolation(I0AfterReg,self.PixSize,freqcut,1); I45AfterReg=opticalLowpassInterpolation(I45AfterReg,self.PixSize,freqcut,1); I90AfterReg=opticalLowpassInterpolation(I90AfterReg,self.PixSize,freqcut,1); I135AfterReg=opticalLowpassInterpolation(I135AfterReg,self.PixSize,freqcut,1); case 'edge' % Edge is good for transmission image and % Compute gradients of registration data to enhance sensitivity to % registration mismatch. % sigma=(0.5*self.Wavelength/self.objectiveNA)/self.PixSize; % At this sigma, anisotropic intensity distribution at the % sub-resolution scale is smoothed out, leaving only the % above-resolution mismatches in location. sigma=(0.2*self.Wavelength/self.ObjectiveNA)/self.PixSize; % Use this sigma for isotropic specimens to improve the registration. I0AfterReg=gradcalc(I0AfterReg,sigma); I45AfterReg=gradcalc(I45AfterReg,sigma); I90AfterReg=gradcalc(I90AfterReg,sigma); I135AfterReg=gradcalc(I135AfterReg,sigma); otherwise error('filterReg parameter should be :''none'', ''lowpass'', or ''edge'''); end % Orientation and anisotropy before and after registration. [OrientationBefore,AnisotropyBefore]=ComputeFluorAnisotropy... (I0BeforeReg,I45BeforeReg,I90BeforeReg,I135BeforeReg,'anisotropy'); [OrientationAfter,AnisotropyAfter]=ComputeFluorAnisotropy... (I0AfterReg,I45AfterReg,I90AfterReg,I135AfterReg,'anisotropy'); % If no parent canvas has been provided. if(~ishandle(params.Parent)) hfigreg=togglefig('Before and after registration',1); set(hfigreg,'Units','Normalized','Position',[0.05 0.05 0.9 0.9],... 'defaultaxesfontsize',15,'Color','white'); colormap gray; else hfigreg=params.Parent; delete(get(hfigreg,'Children')); end hReg=imagecat(self.xaxis,self.yaxis,... I0BeforeReg,I45AfterReg,I90AfterReg,I135AfterReg,... OrientationBefore,OrientationAfter,AnisotropyBefore,AnisotropyAfter,... 'equal','link','colorbar',hfigreg); Ivec=[I0BeforeReg(:);I45BeforeReg(:);I90BeforeReg(:);I135BeforeReg(:)]; set(hReg(1:4),'clim',[min(Ivec) max(Ivec)]); set(hReg(5:6),'clim',[min(OrientationBefore(:)) max(OrientationBefore(:))]); minAnisotropy=min(AnisotropyBefore(:)); if(minAnisotropy<0) minAnisotropy =0; end; maxAnisotropy=max(AnisotropyBefore(:)); if(maxAnisotropy>1) maxAnisotropy=1; end; set(hReg(7:8),'clim',[minAnisotropy maxAnisotropy]); end end function [tform,movingreg]=regQuads(moving,fixed,R,optimizer,metric) % imregcorr cannot detect scaling less than 1/4 or larger than 4. % Our images have very small scaling. % tformEstimate=imregcorr(moving,fixed,'translation'); % movingApproxReg=imwarp(moving,tformEstimate,'OutputView',R); % Small changes in magnification can be accounted for by similarity % transformation. tform=imregtform(moving,R,fixed,R, 'affine', optimizer, metric);%,'InitialTransformation',tformEstimate); movingreg=imtransformAffineMat(moving,tform.T,'cubic','coordinates','centered'); end
github
mehta-lab/Instantaneous-PolScope-master
normQuadsManual.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/@RTFluorPol/normQuadsManual.m
6,995
utf_8
9880601af4ef3fad717be211366a5a14
function normQuadsManual(self,I0,I45,I90,I135,varargin) % normQuadsManual(RTFluorPol Object,I0,I45,I90,I135,'Parameter',value) % Optional arguments % Parameter Value % 'normRange' 2-value vector [minNorm maxNorm]. % 'normROI' Isotropic ROI known to have low anisotropy. %% Assign defaults to optional arguments optargs.normRange=[0.8 1.2]; optargs.normROI=[1 1 self.quadWidth self.quadHeight]; optargs.Parent=NaN; % Parent UIPanel or optargs.normEndCallBack=NaN; % Specifying this callback allows custom action - such as updating of GUI, when normalization is over. optargs.normalizeExcitation=false; % This option is silently ignored. optargs.WaitForClose=false; % Set true if running from script and need to wait for user to finish normalizaiton step manually. optargs=parsepropval(optargs,varargin{:}); % If no callback is specified, the figure is closed when Done button is pressed. if(~isa(optargs.normEndCallBack, 'function_handle')) optargs.normEndCallBack=@closefunction; end if(optargs.normalizeExcitation) error('Manual normalization of excitation is not implemented so far'); end %% Initialize variables here so that they are accessible to all nested callbacks. and handles accessible to all callbacks. I0=double(I0); I45=double(I45); I90=double(I90); I135=double(I135); Inorm45=I45*self.NormI45; Inorm90=I90*self.NormI90; Inorm135=I135*self.NormI135; [Orient,Aniso]=ComputeFluorAnisotropy(I0,Inorm45,Inorm90,Inorm135,'anisotropy','ItoSMatrix',self.ItoSMatrix); Orient=(180/pi)*Orient; %% Draw the UI elements and initialize normalization factors to those found in the object. if(isnan(optargs.Parent)) hdl.mainfig = togglefig('Manual adjustment to normalization',1); jFrame = get(handle(hdl.mainfig),'JavaFrame'); jFrame.setMaximized(true); set(hdl.mainfig,'CloseRequestFcn',@closefunction,... 'defaultaxesfontsize',12,'Units','normalized','Toolbar','figure'); else hdl.mainfig=optargs.Parent; delete(get(hdl.mainfig,'Children')); end hdl.a45=axes('Units','normalized','Position',[0.02 0.5 0.25 0.4],'Parent',hdl.mainfig); hdl.a90=axes('Units','normalized','Position',[0.3 0.5 0.25 0.4],'Parent',hdl.mainfig); hdl.a135=axes('Units','normalized','Position',[0.6 0.5 0.25 0.4],'Parent',hdl.mainfig); hdl.aAniso=axes('Units','normalized','Position',[0.02 0.01 0.25 0.4],'Parent',hdl.mainfig); hdl.aOrient=axes('Units','normalized','Position',[0.3 0.01 0.25 0.4],'Parent',hdl.mainfig); hdl.aOrientHist=axes('Units','normalized','Position',[0.6 0.01 0.25 0.4],'Parent',hdl.mainfig); hdl.CmapTitle=uicontrol('Parent',hdl.mainfig,... 'Style', 'text',... 'String','Colormap',... 'Units','normalized',... 'Position',[0.86 0.88 0.05 0.02],... 'FontSize',12); hdl.popCmap=uicontrol('Parent',hdl.mainfig,... 'Style', 'popupmenu',... 'String', {'gray','hot','cool','bone','jet'},... 'Units','normalized',... 'Position', [0.86 0.84 0.06 0.04],... 'FontSize',12,... 'Callback', @setcmap); [hdl.I45ControlS,hdl.I45ControlP,hdl.I45ControlE]=sliderPanel(... 'Parent',hdl.mainfig,... 'Title','Norm factor: I45',... 'Position',[0.86 0.7 0.12 0.1],... 'Min',optargs.normRange(1),... 'Max',optargs.normRange(2),... 'Value',self.NormI45,... 'SliderStep',[0.005 0.005],... 'FontSize',12,... 'Callback',@updatenorm); [hdl.I90ControlS,hdl.I90ControlP,hdl.I90ControlE]=sliderPanel(... 'Parent',hdl.mainfig,... 'Title','Norm factor: I90',... 'Position',[0.86 0.55 0.12 0.1],... 'Min',optargs.normRange(1),... 'Max',optargs.normRange(2),... 'Value',self.NormI90,... 'SliderStep',[0.005 0.005],... 'FontSize',12,... 'Callback',@updatenorm); [hdl.I135ControlS,hdl.I135ControlP,hdl.I135ControlE]=sliderPanel(... 'Parent',hdl.mainfig,... 'Title','Norm factor: I135',... 'Position',[0.86 0.4 0.12 0.1],... 'Min',optargs.normRange(1),... 'Max',optargs.normRange(2),... 'Value',self.NormI135,... 'SliderStep',[0.005 0.005],... 'FontSize',12,... 'Callback',@updatenorm); hdl.buttondone=uicontrol('Parent',hdl.mainfig,... 'Style','pushbutton',... 'String','Done',... 'Units','normalized',... 'Position',[0.86 0.02 0.04 0.04],... 'FontSize',12,... 'Callback',optargs.normEndCallBack); %% Initialize the axes. setcmap(); % Initialize color limits and keep them constant. Ilims= @(I)[min(abs(I(:))) max(abs(I(:)))]; Alims=Ilims(imcrop(Aniso,optargs.normROI)); DiffPer=@(I1,I2) 100*abs((I2-I1)./I1); axes(hdl.a45); hdl.I45=imagesc(DiffPer(I0,Inorm45),[0 5]); axis equal; title('$\frac{I45-I0}{I0} \,\%$','interpreter','latex'); colorbar; rectangle('Position',optargs.normROI,'EdgeColor','Blue'); axes(hdl.a90); hdl.I90=imagesc(DiffPer(I0,Inorm90),[0 5]); axis equal; title('$\frac{I90-I0}{I0} \,\%$','interpreter','latex'); colorbar; rectangle('Position',optargs.normROI,'EdgeColor','Blue'); axes(hdl.a135); hdl.I135=imagesc(DiffPer(I0,Inorm135),[0 5]); axis equal; title('$\frac{I135-I0}{I0} \,\%$','interpreter','latex'); colorbar; rectangle('Position',optargs.normROI,'EdgeColor','Blue'); axes(hdl.aAniso); hdl.IAniso=imagesc(Aniso,Alims); axis equal; title('Anisotropy'); colorbar; rectangle('Position',optargs.normROI,'EdgeColor','Blue'); axes(hdl.aOrient); hdl.IOrient=imagesc(Orient,[0 180]); axis equal; title('Orientation'); colorbar; axes(hdl.aOrientHist); [counts,levels]=hist(Orient(:),180); hdl.histOrient=stem(levels,counts); title('Histogram of orientation image'); axis tight; linkaxes([hdl.a45 hdl.a90 hdl.a135 hdl.aAniso hdl.aOrient ]); %%%%%%%%%% Callbacks %%%%%%%%%%%% %% update: callback for all controls, update the object and axes. function updatenorm(~,~,~) %update is the callback for all sliders. % Update normalization factors. self.NormI45=get(hdl.I45ControlS,'value'); self.NormI90=get(hdl.I90ControlS,'value'); self.NormI135=get(hdl.I135ControlS,'value'); % update the images displayed on axes. Inorm45=I45*self.NormI45; Inorm90=I90*self.NormI90; Inorm135=I135*self.NormI135; [Orient,Aniso]=ComputeFluorAnisotropy(I0,Inorm45,Inorm90,Inorm135,'anisotropy','ItoSMatrix',self.ItoSMatrix); Orient=(180/pi)*Orient; % I set Cdata instead of redrawing images so that any axes properties % set by the user are not reset. set(hdl.I45,'CData',DiffPer(I0,Inorm45)); set(hdl.I90,'CData',DiffPer(I0,Inorm90)); set(hdl.I135,'CData',DiffPer(I0,Inorm135)); set(hdl.IAniso,'CData',Aniso); set(hdl.IOrient,'CData',Orient); [counts,levels]=hist(Orient(:),180); set(hdl.histOrient,'XData',levels,'YData',counts); end %% setcmap: set the colormap for figure. function setcmap(~,~,~) list=get(hdl.popCmap,'String'); value=get(hdl.popCmap,'value'); colormap(eval(list{value})); end %% closefunction: closes the figure. function closefunction(~,~,~) % close GUI delete(hdl.mainfig); end if(optargs.WaitForClose) waitfor(hdl.mainfig); end end
github
mehta-lab/Instantaneous-PolScope-master
regQuadsManual.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/@RTFluorPol/regQuadsManual.m
13,131
utf_8
037412c4de5c13229fefb3d3ca2e5cba
function regQuadsManual(self,I0,I45,I90,I135,varargin) % [tformI45,tformI90,tformI135]=regQuadsManual(I0,I45,I90,I135) % Optional arguments % Parameter Value % 'ShiftRange' 2-value vector [minshift maxshift] in pixels. % 'RotationRange' 2-value vector [minrotation maxrotation] in deg. % 'ScaleRange' 2-value vector [minscale maxscale]. %% Assign defaults to optional arguments optargs.ShiftRange=[-25 25]; optargs.RotationRange=[-50 50]; optargs.ScaleRange=[1/1.5 1.5]; optargs.Parent=NaN; optargs.regEndCallBack=NaN; % Handle to the function that is executed when Done button is pressed. optargs.WaitForClose=false; % Set true if running from script and need to wait for user to finish registration step manually. optargs=parsepropval(optargs,varargin{:}); if(~isa(optargs.regEndCallBack, 'function_handle')) optargs.regEndCallBack=@closefunction; end %% Declare variables and handles accessible to all callbacks. I0=double(I0); I45=double(I45); I90=double(I90); I135=double(I135); I45reg=imtransformAffineMat(I45,self.tformI45,'cubic','coordinates','centered'); I90reg=imtransformAffineMat(I90,self.tformI90,'cubic','coordinates','centered'); I135reg=imtransformAffineMat(I135,self.tformI135,'cubic','coordinates','centered'); xshift=0; yshift=0; rotation=0; xscale=1; yscale=1; % Values of controls in the UI. %% Initialize main figure if(isnan(optargs.Parent)) hdl.mainfig = togglefig('Manual adjustment to registration',1); jFrame = get(handle(hdl.mainfig),'JavaFrame'); jFrame.setMaximized(true); set(hdl.mainfig,'CloseRequestFcn',@closefunction,... 'defaultaxesfontsize',15,'Units','normalized','Toolbar','figure'); else hdl.mainfig=optargs.Parent; delete(get(hdl.mainfig,'Children')); end hdl.a0=axes('Units','normalized','Position',[0.02 0.5 0.25 0.4],'Parent',hdl.mainfig); hdl.diff=axes('Units','normalized','Position',[0.02 0.01 0.25 0.4],'Parent',hdl.mainfig); hdl.moving=axes('Units','normalized','Position',[0.3 0.5 0.25 0.4],'Parent',hdl.mainfig); hdl.pair=axes('Units','normalized','Position',[0.3 0.01 0.25 0.4],'Parent',hdl.mainfig); hdl.aAniso=axes('Units','normalized','Position',[0.6 0.5 0.25 0.4],'Parent',hdl.mainfig); hdl.aOrient=axes('Units','normalized','Position',[0.6 0.01 0.25 0.4],'Parent',hdl.mainfig); hdl.CmapTitle=uicontrol('Parent',hdl.mainfig,... 'Style', 'text',... 'String','Colormap',... 'Units','normalized',... 'Position',[0.86 0.88 0.05 0.02],... 'FontSize',10); hdl.popCmap=uicontrol('Parent',hdl.mainfig,... 'Style', 'popupmenu',... 'String', {'gray','hot','cool','bone','jet'},... 'Units','normalized',... 'Position', [0.86 0.84 0.06 0.04],... 'FontSize',10,... 'Callback', @setcmap); hdl.popImageTitle=uicontrol('Parent',hdl.mainfig,... 'Style', 'text',... 'String','Select Image',... 'Units','normalized',... 'Position',[0.92 0.88 0.07 0.02],... 'FontSize',10); % This control selects the image to be adjusted. ImageLabelList= {'I0','I45','I90','I135'}; % Titles to place on top of the axes. ImageTitleList={'Displaying I0',... 'Adjusting I45',... 'Adjusting I90',... 'Adjusting I135'}; hdl.popImage=uicontrol('Parent',hdl.mainfig,... 'Style', 'popupmenu',... 'String',ImageLabelList,... 'Units','normalized',... 'Position', [0.92 0.84 0.07 0.04],... 'FontSize',10,... 'Callback', @selectimage); [hdl.rControlS,hdl.rControlP,hdl.rControlE]=sliderPanel(... 'Parent',hdl.mainfig,... 'Title','Rotation',... 'Position',[0.86 0.7 0.12 0.12],... 'Min',optargs.RotationRange(1),... 'Max',optargs.RotationRange(2),... 'Value',mean(optargs.RotationRange),... 'SliderStep',[0.001 0.001],... 'FontSize',10,... 'Callback',@rControl); [hdl.sxControlS,hdl.sxControlP,hdl.sxControlE]=sliderPanel(... 'Parent',hdl.mainfig,... 'Title','Horizontal Scaling',... 'Position',[0.86 0.55 0.12 0.12],... 'Min',optargs.ScaleRange(1),... 'Max',optargs.ScaleRange(2),... 'Value',mean(optargs.ScaleRange),... 'SliderStep',[0.001 0.001],... 'FontSize',10,... 'Callback',@sxControl); [hdl.syControlS,hdl.syControlP,hdl.syControlE]=sliderPanel(... 'Parent',hdl.mainfig,... 'Title','Vertical Scaling',... 'Position',[0.86 0.4 0.12 0.12],... 'Min',optargs.ScaleRange(1),... 'Max',optargs.ScaleRange(2),... 'Value',mean(optargs.ScaleRange),... 'SliderStep',[0.001 0.001],... 'FontSize',10,... 'Callback',@syControl); [hdl.xControlS,hdl.xControlP,hdl.xControlE]=sliderPanel(... 'Parent',hdl.mainfig,... 'Title','Horizontal Shift',... 'Position',[0.86 0.25 0.12 0.12],... 'Min',optargs.ShiftRange(1),... 'Max',optargs.ShiftRange(2),... 'Value',mean(optargs.ShiftRange),... 'SliderStep',[0.001 0.001],... 'FontSize',10,... 'Callback',@xControl); [hdl.yControlS,hdl.yControlP,hdl.yControlE]=sliderPanel(... 'Parent',hdl.mainfig,... 'Title','Vertical Shift',... 'Position',[0.86 0.1 0.12 0.12],... 'Min',optargs.ShiftRange(1),... 'Max',optargs.ShiftRange(2),... 'Value',mean(optargs.ShiftRange),... 'SliderStep',[0.001 0.001],... 'FontSize',10,... 'Callback',@yControl); hdl.buttondone=uicontrol('Parent',hdl.mainfig,... 'Style','pushbutton',... 'String','Done',... 'Units','normalized',... 'Position',[0.86 0.02 0.04 0.04],... 'FontSize',10,... 'Callback',optargs.regEndCallBack); setcmap(); initializeimages(); %%%%%%%%% All callbacks are written as nested functions %%%%%% %% Initial computation and output. function initializeimages() [Orient,Aniso]=ComputeFluorAnisotropy(I0,I45reg,I90reg,I135reg,'anisotropy','ItoSMatrix',self.ItoSMatrix); Ivec=[I0(:); I45reg(:); I90reg(:); I135reg(:)]; Ilim=[min(Ivec) max(Ivec)]; I45Diff=abs(I0-I45reg); I90Diff=abs(I0-I90reg); I135Diff=abs(I0-I135reg); Diffvec=[I45Diff(:); I90Diff(:); I135Diff(:)]; Difflim=[min(Diffvec) max(Diffvec)]; axes(hdl.a0); hdl.I0=imagesc(I0); axis equal; set(hdl.a0,'Clim',Ilim); title('I0'); colorbar; axes(hdl.moving); hdl.Imoving=imagesc(I0); axis equal; set(hdl.moving,'Clim',Ilim); hdl.Tmoving=title(ImageTitleList{1}); colorbar; hidecontrols(); axes(hdl.diff); hdl.Idiff=imagesc(abs(I0-I0)); axis equal; % Fix the limits of difference. set(hdl.diff,'Clim',Difflim); title('Difference'); colorbar; axes(hdl.pair); hdl.Ipair=imagesc(imfuse(I0,I0)); axis equal; title('Fused image'); axes(hdl.aAniso); hdl.IAniso=imagesc(Aniso); axis equal; set(hdl.aAniso,'Clim',[0 1]); title('Anisotropy'); axes(hdl.aOrient); hdl.IOrient=imagesc(Orient,[0 pi]); axis equal; title('Orientation'); linkaxes([ hdl.a0 hdl.diff hdl.moving hdl.pair hdl.aAniso hdl.aOrient ]); end function updatecontrols() set([hdl.xControlS, hdl.yControlS, hdl.rControlS, hdl.sxControlS, hdl.syControlS,... hdl.xControlE, hdl.yControlE, hdl.rControlE, hdl.sxControlE, hdl.syControlE,... hdl.xControlP, hdl.yControlP, hdl.rControlP, hdl.sxControlP, hdl.syControlP],'Visible','on'); % Update controls with current statis settings for registration and % make them visible. set(hdl.xControlS,'Value',xshift); set(hdl.yControlS,'Value',yshift); set(hdl.rControlS,'Value',rotation); set(hdl.sxControlS,'Value',xscale); set(hdl.syControlS,'Value',yscale); set(hdl.xControlE,'String',num2str(xshift)); set(hdl.yControlE,'String',num2str(yshift)); set(hdl.rControlE,'String',num2str(rotation)); set(hdl.sxControlE,'String',num2str(xscale)); set(hdl.syControlE,'String',num2str(yscale)); end function hidecontrols() set([hdl.xControlS, hdl.yControlS, hdl.rControlS, hdl.sxControlS, hdl.syControlS,... hdl.xControlE, hdl.yControlE, hdl.rControlE, hdl.sxControlE, hdl.syControlE,... hdl.xControlP, hdl.yControlP, hdl.rControlP, hdl.sxControlP, hdl.syControlP],'Visible','off'); end %% updateimages displays updated images and also assigns the outputs. function updateimages() %update images is called by the callbacks for image selector and by %the callbacks for registration sliders. popImageValue=get(hdl.popImage,'value'); % Update the registration parameters based on chosen image. switch(popImageValue) case 1 % Don't do anything for I0. case 2 self.I45xShift=xshift; self.I45yShift=yshift; self.I45Rotation=rotation*(pi/180); % Angles are displayed in degree, stored in radians. self.I45xScale=xscale; self.I45yScale=yscale; self.tformI45=ShiftScaleRotToaffine(xshift,yshift,xscale,yscale,rotation*(pi/180)); case 3 self.I90xShift=xshift; self.I90yShift=yshift; self.I90Rotation=rotation*(pi/180); self.I90xScale=xscale; self.I90yScale=yscale; self.tformI90=ShiftScaleRotToaffine(xshift,yshift,xscale,yscale,rotation*(pi/180)); case 4 self.I135xShift=xshift; self.I135yShift=yshift; self.I135Rotation=rotation*(pi/180); self.I135xScale=xscale; self.I135yScale=yscale; self.tformI135=ShiftScaleRotToaffine(xshift,yshift,xscale,yscale,rotation*(pi/180)); end % calculate the transformed images. I45reg=imtransformAffineMat(I45,self.tformI45,'cubic','coordinates','centered'); I90reg=imtransformAffineMat(I90,self.tformI90,'cubic','coordinates','centered'); I135reg=imtransformAffineMat(I135,self.tformI135,'cubic','coordinates','centered'); % Calculate registered images. [Orient,Aniso]=ComputeFluorAnisotropy(I0,I45reg,I90reg,I135reg,'anisotropy','ItoSMatrix',self.ItoSMatrix); % Assign a moving image for display purpose. switch(popImageValue) case 1 MovingImage=I0; case 2 MovingImage=I45reg; case 3 MovingImage=I90reg; case 4 MovingImage=I135reg; end % I set Cdata instead of redrawing images so that any axes properties % set by the user are not reset. set(hdl.Idiff,'CData',abs(I0-MovingImage)); set(hdl.Imoving,'CData',MovingImage); set(hdl.Ipair,'CData',imfuse(I0,MovingImage)); set(hdl.IAniso,'CData',Aniso); set(hdl.IOrient,'CData',Orient); set(hdl.Tmoving,'String',ImageTitleList{popImageValue}); %Set the title on the moving image. end %% callbacks for controls. function xControl(~,~,~) xshift=get(hdl.xControlS,'Value'); updateimages(); end function yControl(~,~,~) yshift=get(hdl.yControlS,'Value'); updateimages(); end function rControl(~,~,~) rotation=get(hdl.rControlS,'Value'); updateimages(); end function sxControl(~,~,~) xscale=get(hdl.sxControlS,'Value'); updateimages(); end function syControl(~,~,~) yscale=get(hdl.syControlS,'Value'); updateimages(); end function setcmap(~,~,~) list=get(hdl.popCmap,'String'); value=get(hdl.popCmap,'value'); colormap(eval(list{value})); end %% selectimage assigns the values to controls based on the selected image. function selectimage(~,~,~) % restore the registration parameters based on chosen image and % refresh the display. popImageValue=get(hdl.popImage,'value'); switch(popImageValue) case 1 % For I0, do nothing and hide the registration controls. hidecontrols(); case 2 xshift=self.I45xShift; yshift=self.I45yShift; rotation=self.I45Rotation*(180/pi); % Angles are stored in radians inside the object, but displayed in degree in the GUI. xscale=self.I45xScale; yscale=self.I45yScale; updatecontrols(); case 3 xshift=self.I90xShift; yshift=self.I90yShift; rotation=self.I90Rotation*(180/pi); xscale=self.I90xScale; yscale=self.I90yScale; updatecontrols(); case 4 xshift=self.I135xShift; yshift=self.I135yShift; rotation=self.I135Rotation*(180/pi); xscale=self.I135xScale; yscale=self.I135yScale; updatecontrols(); end updateimages(); end % closefunction makes sure that the images are updated when figure is closed. function closefunction(~,~,~) % Executed only when no parent canvas is specified. % updateimages(); % Update the images. % close GUI delete(hdl.mainfig); end if optargs.WaitForClose waitfor(hdl.mainfig); end end
github
mehta-lab/Instantaneous-PolScope-master
screencapture.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/screencapture.m
34,159
utf_8
d79cc0eed8f03127f0825954b69cf72b
function imageData = screencapture(varargin) % screencapture - get a screen-capture of a figure frame, component handle, or screen area rectangle % % ScreenCapture gets a screen-capture of any Matlab GUI handle (including desktop, % figure, axes, image or uicontrol), or a specified area rectangle located relative to % the specified handle. Screen area capture is possible by specifying the root (desktop) % handle (=0). The output can be either to an image file or to a Matlab matrix (useful % for displaying via imshow() or for further processing) or to the system clipboard. % This utility also enables adding a toolbar button for easy interactive screen-capture. % % Syntax: % imageData = screencapture(handle, position, target, 'PropName',PropValue, ...) % % Input Parameters: % handle - optional handle to be used for screen-capture origin. % If empty/unsupplied then current figure (gcf) will be used. % position - optional position array in pixels: [x,y,width,height]. % If empty/unsupplied then the handle's position vector will be used. % If both handle and position are empty/unsupplied then the position % will be retrieved via interactive mouse-selection. % If handle is an image, then position is in data (not pixel) units, so the % captured region remains the same after figure/axes resize (like imcrop) % target - optional filename for storing the screen-capture, or the 'clipboard' string. % If empty/unsupplied then no output to file will be done. % The file format will be determined from the extension (JPG/PNG/...). % Supported formats are those supported by the imwrite function. % 'PropName',PropValue - % optional list of property pairs (e.g., 'target','myImage.png','pos',[10,20,30,40],'handle',gca) % PropNames may be abbreviated and are case-insensitive. % PropNames may also be given in whichever order. % Supported PropNames are: % - 'handle' (default: gcf handle) % - 'position' (default: gcf position array) % - 'target' (default: '') % - 'toolbar' (figure handle; default: gcf) % this adds a screen-capture button to the figure's toolbar % If this parameter is specified, then no screen-capture % will take place and the returned imageData will be []. % % Output parameters: % imageData - image data in a format acceptable by the imshow function % If neither target nor imageData were specified, the user will be % asked to interactively specify the output file. % % Examples: % imageData = screencapture; % interactively select screen-capture rectangle % imageData = screencapture(hListbox); % capture image of a uicontrol % imageData = screencapture(0, [20,30,40,50]); % capture a small desktop region % imageData = screencapture(gcf,[20,30,40,50]); % capture a small figure region % imageData = screencapture(gca,[10,20,30,40]); % capture a small axes region % imshow(imageData); % display the captured image in a matlab figure % imwrite(imageData,'myImage.png'); % save the captured image to file % img = imread('cameraman.tif'); % hImg = imshow(img); % screencapture(hImg,[60,35,140,80]); % capture a region of an image % screencapture(gcf,[],'myFigure.jpg'); % capture the entire figure into file % screencapture('handle',gcf,'target','myFigure.jpg'); % same as previous % screencapture('handle',gcf,'target','clipboard'); % copy to clipboard % screencapture('toolbar',gcf); % adds a screen-capture button to gcf's toolbar % screencapture('toolbar',[],'target','sc.bmp'); % same with default output filename % % Technical description: % http://UndocumentedMatlab.com/blog/screencapture-utility/ % % Bugs and suggestions: % Please send to Yair Altman (altmany at gmail dot com) % % See also: % imshow, imwrite, print % % Release history: % 1.7 2014-04-28: Fixed bug when capturing interactive selection % 1.6 2014-04-22: Only enable image formats when saving to an unspecified file via uiputfile % 1.5 2013-04-18: Fixed bug in capture of non-square image; fixes for Win64 % 1.4 2013-01-27: Fixed capture of Desktop (root); enabled rbbox anywhere on desktop (not necesarily in a Matlab figure); enabled output to clipboard (based on Jiro Doke's imclipboard utility); edge-case fixes; added Java compatibility check % 1.3 2012-07-23: Capture current object (uicontrol/axes/figure) if w=h=0 (e.g., by clicking a single point); extra input args sanity checks; fix for docked windows and image axes; include axes labels & ticks by default when capturing axes; use data-units position vector when capturing images; many edge-case fixes % 1.2 2011-01-16: another performance boost (thanks to Jan Simon); some compatibility fixes for Matlab 6.5 (untested) % 1.1 2009-06-03: Handle missing output format; performance boost (thanks to Urs); fix minor root-handle bug; added toolbar button option % 1.0 2009-06-02: First version posted on <a href="http://www.mathworks.com/matlabcentral/fileexchange/authors/27420">MathWorks File Exchange</a> % License to use and modify this code is granted freely to all interested, as long as the original author is % referenced and attributed as such. The original author maintains the right to be solely associated with this work. % Programmed and Copyright by Yair M. Altman: altmany(at)gmail.com % $Revision: 1.7 $ $Date: 2014/04/28 21:10:12 $ % Ensure that java awt is enabled... if ~usejava('awt') error('YMA:screencapture:NeedAwt','ScreenCapture requires Java to run.'); end % Ensure that our Java version supports the Robot class (requires JVM 1.3+) try robot = java.awt.Robot; %#ok<NASGU> catch uiwait(msgbox({['Your Matlab installation is so old that its Java engine (' version('-java') ... ') does not have a java.awt.Robot class. '], ' ', ... 'Without this class, taking a screen-capture is impossible.', ' ', ... 'So, either install JVM 1.3 or higher, or use a newer Matlab release.'}, ... 'ScreenCapture', 'warn')); if nargout, imageData = []; end return; end % Process optional arguments paramsStruct = processArgs(varargin{:}); % If toolbar button requested, add it and exit if ~isempty(paramsStruct.toolbar) % Add the toolbar button addToolbarButton(paramsStruct); % Return the figure to its pre-undocked state (when relevant) redockFigureIfRelevant(paramsStruct); % Exit immediately (do NOT take a screen-capture) if nargout, imageData = []; end return; end % Convert position from handle-relative to desktop Java-based pixels [paramsStruct, msgStr] = convertPos(paramsStruct); % Capture the requested screen rectangle using java.awt.Robot imgData = getScreenCaptureImageData(paramsStruct.position); % Return the figure to its pre-undocked state (when relevant) redockFigureIfRelevant(paramsStruct); % Save image data in file or clipboard, if specified if ~isempty(paramsStruct.target) if strcmpi(paramsStruct.target,'clipboard') if ~isempty(imgData) imclipboard(imgData); else msgbox('No image area selected - not copying image to clipboard','ScreenCapture','warn'); end else % real filename if ~isempty(imgData) imwrite(imgData,paramsStruct.target); else msgbox(['No image area selected - not saving image file ' paramsStruct.target],'ScreenCapture','warn'); end end end % Return image raster data to user, if requested if nargout imageData = imgData; % If neither output formats was specified (neither target nor output data) elseif isempty(paramsStruct.target) & ~isempty(imgData) %#ok ML6 % Ask the user to specify a file %error('YMA:screencapture:noOutput','No output specified for ScreenCapture: specify the output filename and/or output data'); %format = '*.*'; formats = imformats; for idx = 1 : numel(formats) ext = sprintf('*.%s;',formats(idx).ext{:}); format(idx,1:2) = {ext(1:end-1), formats(idx).description}; %#ok<AGROW> end [filename,pathname] = uiputfile(format,'Save screen capture as'); if ~isequal(filename,0) & ~isequal(pathname,0) %#ok Matlab6 compatibility imwrite(imgData,fullfile(pathname,filename)); else % TODO - copy to clipboard end end % Display msgStr, if relevant if ~isempty(msgStr) uiwait(msgbox(msgStr,'ScreenCapture')); drawnow; pause(0.05); % time for the msgbox to disappear end return; % debug breakpoint %% Process optional arguments function paramsStruct = processArgs(varargin) % Get the properties in either direct or P-V format [regParams, pvPairs] = parseparams(varargin); % Now process the optional P-V params try % Initialize paramName = []; paramsStruct = []; paramsStruct.handle = []; paramsStruct.position = []; paramsStruct.target = ''; paramsStruct.toolbar = []; paramsStruct.wasDocked = 0; % no false available in ML6 paramsStruct.wasInteractive = 0; % no false available in ML6 % Parse the regular (non-named) params in recption order if ~isempty(regParams) & (isempty(regParams{1}) | ishandle(regParams{1}(1))) %#ok ML6 paramsStruct.handle = regParams{1}; regParams(1) = []; end if ~isempty(regParams) & isnumeric(regParams{1}) & (length(regParams{1}) == 4) %#ok ML6 paramsStruct.position = regParams{1}; regParams(1) = []; end if ~isempty(regParams) & ischar(regParams{1}) %#ok ML6 paramsStruct.target = regParams{1}; end % Parse the optional param PV pairs supportedArgs = {'handle','position','target','toolbar'}; while ~isempty(pvPairs) % Disregard empty propNames (may be due to users mis-interpretting the syntax help) while ~isempty(pvPairs) & isempty(pvPairs{1}) %#ok ML6 pvPairs(1) = []; end if isempty(pvPairs) break; end % Ensure basic format is valid paramName = ''; if ~ischar(pvPairs{1}) error('YMA:screencapture:invalidProperty','Invalid property passed to ScreenCapture'); elseif length(pvPairs) == 1 if isempty(paramsStruct.target) paramsStruct.target = pvPairs{1}; break; else error('YMA:screencapture:noPropertyValue',['No value specified for property ''' pvPairs{1} '''']); end end % Process parameter values paramName = pvPairs{1}; if strcmpi(paramName,'filename') % backward compatibility paramName = 'target'; end paramValue = pvPairs{2}; pvPairs(1:2) = []; idx = find(strncmpi(paramName,supportedArgs,length(paramName))); if ~isempty(idx) %paramsStruct.(lower(supportedArgs{idx(1)})) = paramValue; % incompatible with ML6 paramsStruct = setfield(paramsStruct, lower(supportedArgs{idx(1)}), paramValue); %#ok ML6 % If 'toolbar' param specified, then it cannot be left empty - use gcf if strncmpi(paramName,'toolbar',length(paramName)) & isempty(paramsStruct.toolbar) %#ok ML6 paramsStruct.toolbar = getCurrentFig; end elseif isempty(paramsStruct.target) paramsStruct.target = paramName; pvPairs = {paramValue, pvPairs{:}}; %#ok (more readable this way, although a bit less efficient...) else supportedArgsStr = sprintf('''%s'',',supportedArgs{:}); error('YMA:screencapture:invalidProperty','%s \n%s', ... 'Invalid property passed to ScreenCapture', ... ['Supported property names are: ' supportedArgsStr(1:end-1)]); end end % loop pvPairs catch if ~isempty(paramName), paramName = [' ''' paramName '''']; end error('YMA:screencapture:invalidProperty','Error setting ScreenCapture property %s:\n%s',paramName,lasterr); %#ok<LERR> end %end % processArgs %% Convert position from handle-relative to desktop Java-based pixels function [paramsStruct, msgStr] = convertPos(paramsStruct) msgStr = ''; try % Get the screen-size for later use screenSize = get(0,'ScreenSize'); % Get the containing figure's handle hParent = paramsStruct.handle; if isempty(paramsStruct.handle) paramsStruct.hFigure = getCurrentFig; hParent = paramsStruct.hFigure; else paramsStruct.hFigure = ancestor(paramsStruct.handle,'figure'); end % To get the acurate pixel position, the figure window must be undocked try if strcmpi(get(paramsStruct.hFigure,'WindowStyle'),'docked') set(paramsStruct.hFigure,'WindowStyle','normal'); drawnow; pause(0.25); paramsStruct.wasDocked = 1; % no true available in ML6 end catch % never mind - ignore... end % The figure (if specified) must be in focus if ~isempty(paramsStruct.hFigure) & ishandle(paramsStruct.hFigure) %#ok ML6 isFigureValid = 1; % no true available in ML6 figure(paramsStruct.hFigure); else isFigureValid = 0; % no false available in ML6 end % Flush all graphic events to ensure correct rendering drawnow; pause(0.01); % No handle specified wasPositionGiven = 1; % no true available in ML6 if isempty(paramsStruct.handle) % Set default handle, if not supplied paramsStruct.handle = paramsStruct.hFigure; % If position was not specified, get it interactively using RBBOX if isempty(paramsStruct.position) [paramsStruct.position, jFrameUsed, msgStr] = getInteractivePosition(paramsStruct.hFigure); %#ok<ASGLU> jFrameUsed is unused paramsStruct.wasInteractive = 1; % no true available in ML6 wasPositionGiven = 0; % no false available in ML6 end elseif ~ishandle(paramsStruct.handle) % Handle was supplied - ensure it is a valid handle error('YMA:screencapture:invalidHandle','Invalid handle passed to ScreenCapture'); elseif isempty(paramsStruct.position) % Handle was supplied but position was not, so use the handle's position paramsStruct.position = getPixelPos(paramsStruct.handle); paramsStruct.position(1:2) = 0; wasPositionGiven = 0; % no false available in ML6 elseif ~isnumeric(paramsStruct.position) | (length(paramsStruct.position) ~= 4) %#ok ML6 % Both handle & position were supplied - ensure a valid pixel position vector error('YMA:screencapture:invalidPosition','Invalid position vector passed to ScreenCapture: \nMust be a [x,y,w,h] numeric pixel array'); end % Capture current object (uicontrol/axes/figure) if w=h=0 (single-click in interactive mode) if paramsStruct.position(3)<=0 | paramsStruct.position(4)<=0 %#ok ML6 %TODO - find a way to single-click another Matlab figure (the following does not work) %paramsStruct.position = getPixelPos(ancestor(hittest,'figure')); paramsStruct.position = getPixelPos(paramsStruct.handle); paramsStruct.position(1:2) = 0; paramsStruct.wasInteractive = 0; % no false available in ML6 wasPositionGiven = 0; % no false available in ML6 end % First get the parent handle's desktop-based Matlab pixel position parentPos = [0,0,0,0]; dX = 0; dY = 0; dW = 0; dH = 0; if ~isa(handle(hParent),'figure') % Get the reguested component's pixel position parentPos = getPixelPos(hParent, 1); % no true available in ML6 % Axes position inaccuracy estimation deltaX = 3; deltaY = -1; % Fix for images %isAxes = isa(handle(hParent),'axes'); isImage = isa(handle(hParent),'image'); if isImage % | (isAxes & strcmpi(get(hParent,'YDir'),'reverse')) %#ok ML6 % Compensate for resized image axes hAxes = get(hParent,'Parent'); if all(get(hAxes,'DataAspectRatio')==1) % sanity check: this is the normal behavior % Note 18/4/2013: the following fails for non-square images %actualImgSize = min(parentPos(3:4)); %dX = (parentPos(3) - actualImgSize) / 2; %dY = (parentPos(4) - actualImgSize) / 2; %parentPos(3:4) = actualImgSize; % The following should work for all types of images actualImgSize = size(get(hParent,'CData')); dX = (parentPos(3) - min(parentPos(3),actualImgSize(2))) / 2; dY = (parentPos(4) - min(parentPos(4),actualImgSize(1))) / 2; parentPos(3:4) = actualImgSize([2,1]); %parentPos(3) = max(parentPos(3),actualImgSize(2)); %parentPos(4) = max(parentPos(4),actualImgSize(1)); end % Fix user-specified img positions (but not auto-inferred ones) if wasPositionGiven % In images, use data units rather than pixel units % Reverse the YDir ymax = max(get(hParent,'YData')); paramsStruct.position(2) = ymax - paramsStruct.position(2) - paramsStruct.position(4); % Note: it would be best to use hgconvertunits, but: % ^^^^ (1) it fails on Matlab 6, and (2) it doesn't accept Data units %paramsStruct.position = hgconvertunits(hFig, paramsStruct.position, 'Data', 'pixel', hParent); % fails! xLims = get(hParent,'XData'); yLims = get(hParent,'YData'); xPixelsPerData = parentPos(3) / (diff(xLims) + 1); yPixelsPerData = parentPos(4) / (diff(yLims) + 1); paramsStruct.position(1) = round((paramsStruct.position(1)-xLims(1)) * xPixelsPerData); paramsStruct.position(2) = round((paramsStruct.position(2)-yLims(1)) * yPixelsPerData + 2*dY); paramsStruct.position(3) = round( paramsStruct.position(3) * xPixelsPerData); paramsStruct.position(4) = round( paramsStruct.position(4) * yPixelsPerData); % Axes position inaccuracy estimation if strcmpi(computer('arch'),'win64') deltaX = 7; deltaY = -7; else deltaX = 3; deltaY = -3; end else % axes/image position was auto-infered (entire image) % Axes position inaccuracy estimation if strcmpi(computer('arch'),'win64') deltaX = 6; deltaY = -6; else deltaX = 2; deltaY = -2; end dW = -2*dX; dH = -2*dY; end end %hFig = ancestor(hParent,'figure'); hParent = paramsStruct.hFigure; elseif paramsStruct.wasInteractive % interactive figure rectangle % Compensate for 1px rbbox inaccuracies deltaX = 2; deltaY = -2; else % non-interactive figure % Compensate 4px figure boundaries = difference betweeen OuterPosition and Position deltaX = -1; deltaY = 1; end %disp(paramsStruct.position) % for debugging % Now get the pixel position relative to the monitor figurePos = getPixelPos(hParent); desktopPos = figurePos + parentPos; % Now convert to Java-based pixels based on screen size % Note: multiple monitors are automatically handled correctly, since all % ^^^^ Java positions are relative to the main monitor's top-left corner javaX = desktopPos(1) + paramsStruct.position(1) + deltaX + dX; javaY = screenSize(4) - desktopPos(2) - paramsStruct.position(2) - paramsStruct.position(4) + deltaY + dY; width = paramsStruct.position(3) + dW; height = paramsStruct.position(4) + dH; paramsStruct.position = round([javaX, javaY, width, height]); %paramsStruct.position % Ensure the figure is at the front so it can be screen-captured if isFigureValid figure(hParent); drawnow; pause(0.02); end catch % Maybe root/desktop handle (root does not have a 'Position' prop so getPixelPos croaks if isequal(double(hParent),0) % =root/desktop handle; handles case of hParent=[] javaX = paramsStruct.position(1) - 1; javaY = screenSize(4) - paramsStruct.position(2) - paramsStruct.position(4) - 1; paramsStruct.position = [javaX, javaY, paramsStruct.position(3:4)]; end end %end % convertPos %% Interactively get the requested capture rectangle function [positionRect, jFrameUsed, msgStr] = getInteractivePosition(hFig) msgStr = ''; try % First try the invisible-figure approach, in order to % enable rbbox outside any existing figure boundaries f = figure('units','pixel','pos',[-100,-100,10,10],'HitTest','off'); drawnow; pause(0.01); jf = get(handle(f),'JavaFrame'); try jWindow = jf.fFigureClient.getWindow; catch try jWindow = jf.fHG1Client.getWindow; catch jWindow = jf.getFigurePanelContainer.getParent.getTopLevelAncestor; end end com.sun.awt.AWTUtilities.setWindowOpacity(jWindow,0.05); %=nearly transparent (not fully so that mouse clicks are captured) jWindow.setMaximized(1); % no true available in ML6 jFrameUsed = 1; % no true available in ML6 msg = {'Mouse-click and drag a bounding rectangle for screen-capture ' ... ... %'or single-click any Matlab figure to capture the entire figure.' ... }; catch % Something failed, so revert to a simple rbbox on a visible figure try delete(f); drawnow; catch, end %Cleanup... jFrameUsed = 0; % no false available in ML6 msg = {'Mouse-click within any Matlab figure and then', ... 'drag a bounding rectangle for screen-capture,', ... 'or single-click to capture the entire figure'}; end uiwait(msgbox(msg,'ScreenCapture')); k = waitforbuttonpress; %#ok k is unused %hFig = getCurrentFig; %p1 = get(hFig,'CurrentPoint'); positionRect = rbbox; %p2 = get(hFig,'CurrentPoint'); if jFrameUsed jFrameOrigin = getPixelPos(f); delete(f); drawnow; try figOrigin = getPixelPos(hFig); catch % empty/invalid hFig handle figOrigin = [0,0,0,0]; end else if isempty(hFig) jFrameOrigin = getPixelPos(gcf); else jFrameOrigin = [0,0,0,0]; end figOrigin = [0,0,0,0]; end positionRect(1:2) = positionRect(1:2) + jFrameOrigin(1:2) - figOrigin(1:2); if prod(positionRect(3:4)) > 0 msgStr = sprintf('%dx%d area captured',positionRect(3),positionRect(4)); end %end % getInteractivePosition %% Get current figure (even if its handle is hidden) function hFig = getCurrentFig oldState = get(0,'showHiddenHandles'); set(0,'showHiddenHandles','on'); hFig = get(0,'CurrentFigure'); set(0,'showHiddenHandles',oldState); %end % getCurrentFig %% Get ancestor figure - used for old Matlab versions that don't have a built-in ancestor() function hObj = ancestor(hObj,type) if ~isempty(hObj) & ishandle(hObj) %#ok for Matlab 6 compatibility try hObj = get(hObj,'Ancestor'); catch % never mind... end try %if ~isa(handle(hObj),type) % this is best but always returns 0 in Matlab 6! %if ~isprop(hObj,'type') | ~strcmpi(get(hObj,'type'),type) % no isprop() in ML6! try objType = get(hObj,'type'); catch objType = ''; end if ~strcmpi(objType,type) try parent = get(handle(hObj),'parent'); catch parent = hObj.getParent; % some objs have no 'Parent' prop, just this method... end if ~isempty(parent) % empty parent means root ancestor, so exit hObj = ancestor(parent,type); end end catch % never mind... end end %end % ancestor %% Get position of an HG object in specified units function pos = getPos(hObj,field,units) % Matlab 6 did not have hgconvertunits so use the old way... oldUnits = get(hObj,'units'); if strcmpi(oldUnits,units) % don't modify units unless we must! pos = get(hObj,field); else set(hObj,'units',units); pos = get(hObj,field); set(hObj,'units',oldUnits); end %end % getPos %% Get pixel position of an HG object - for Matlab 6 compatibility function pos = getPixelPos(hObj,varargin) persistent originalObj try stk = dbstack; if ~strcmp(stk(2).name,'getPixelPos') originalObj = hObj; end if isa(handle(hObj),'figure') %| isa(handle(hObj),'axes') %try pos = getPos(hObj,'OuterPosition','pixels'); else %catch % getpixelposition is unvectorized unfortunately! pos = getpixelposition(hObj,varargin{:}); % add the axes labels/ticks if relevant (plus a tiny margin to fix 2px label/title inconsistencies) if isa(handle(hObj),'axes') & ~isa(handle(originalObj),'image') %#ok ML6 tightInsets = getPos(hObj,'TightInset','pixel'); pos = pos + tightInsets.*[-1,-1,1,1] + [-1,1,1+tightInsets(1:2)]; end end catch try % Matlab 6 did not have getpixelposition nor hgconvertunits so use the old way... pos = getPos(hObj,'Position','pixels'); catch % Maybe the handle does not have a 'Position' prop (e.g., text/line/plot) - use its parent pos = getPixelPos(get(hObj,'parent'),varargin{:}); end end % Handle the case of missing/invalid/empty HG handle if isempty(pos) pos = [0,0,0,0]; end %end % getPixelPos %% Adds a ScreenCapture toolbar button function addToolbarButton(paramsStruct) % Ensure we have a valid toolbar handle hFig = ancestor(paramsStruct.toolbar,'figure'); if isempty(hFig) error('YMA:screencapture:badToolbar','the ''Toolbar'' parameter must contain a valid GUI handle'); end set(hFig,'ToolBar','figure'); hToolbar = findall(hFig,'type','uitoolbar'); if isempty(hToolbar) error('YMA:screencapture:noToolbar','the ''Toolbar'' parameter must contain a figure handle possessing a valid toolbar'); end hToolbar = hToolbar(1); % just in case there are several toolbars... - use only the first % Prepare the camera icon icon = ['3333333333333333'; ... '3333333333333333'; ... '3333300000333333'; ... '3333065556033333'; ... '3000000000000033'; ... '3022222222222033'; ... '3022220002222033'; ... '3022203110222033'; ... '3022201110222033'; ... '3022204440222033'; ... '3022220002222033'; ... '3022222222222033'; ... '3000000000000033'; ... '3333333333333333'; ... '3333333333333333'; ... '3333333333333333']; cm = [ 0 0 0; ... % black 0 0.60 1; ... % light blue 0.53 0.53 0.53; ... % light gray NaN NaN NaN; ... % transparent 0 0.73 0; ... % light green 0.27 0.27 0.27; ... % gray 0.13 0.13 0.13]; % dark gray cdata = ind2rgb(uint8(icon-'0'),cm); % If the button does not already exit hButton = findall(hToolbar,'Tag','ScreenCaptureButton'); tooltip = 'Screen capture'; if ~isempty(paramsStruct.target) tooltip = [tooltip ' to ' paramsStruct.target]; end if isempty(hButton) % Add the button with the icon to the figure's toolbar hButton = uipushtool(hToolbar, 'CData',cdata, 'Tag','ScreenCaptureButton', 'TooltipString',tooltip, 'ClickedCallback',['screencapture(''' paramsStruct.target ''')']); %#ok unused else % Otherwise, simply update the existing button set(hButton, 'CData',cdata, 'Tag','ScreenCaptureButton', 'TooltipString',tooltip, 'ClickedCallback',['screencapture(''' paramsStruct.target ''')']); end %end % addToolbarButton %% Java-get the actual screen-capture image data function imgData = getScreenCaptureImageData(positionRect) if isempty(positionRect) | all(positionRect==0) | positionRect(3)<=0 | positionRect(4)<=0 %#ok ML6 imgData = []; else % Use java.awt.Robot to take a screen-capture of the specified screen area rect = java.awt.Rectangle(positionRect(1), positionRect(2), positionRect(3), positionRect(4)); robot = java.awt.Robot; jImage = robot.createScreenCapture(rect); % Convert the resulting Java image to a Matlab image % Adapted for a much-improved performance from: % http://www.mathworks.com/support/solutions/data/1-2WPAYR.html h = jImage.getHeight; w = jImage.getWidth; %imgData = zeros([h,w,3],'uint8'); %pixelsData = uint8(jImage.getData.getPixels(0,0,w,h,[])); %for i = 1 : h % base = (i-1)*w*3+1; % imgData(i,1:w,:) = deal(reshape(pixelsData(base:(base+3*w-1)),3,w)'); %end % Performance further improved based on feedback from Urs Schwartz: %pixelsData = reshape(typecast(jImage.getData.getDataStorage,'uint32'),w,h).'; %imgData(:,:,3) = bitshift(bitand(pixelsData,256^1-1),-8*0); %imgData(:,:,2) = bitshift(bitand(pixelsData,256^2-1),-8*1); %imgData(:,:,1) = bitshift(bitand(pixelsData,256^3-1),-8*2); % Performance even further improved based on feedback from Jan Simon: pixelsData = reshape(typecast(jImage.getData.getDataStorage, 'uint8'), 4, w, h); imgData = cat(3, ... transpose(reshape(pixelsData(3, :, :), w, h)), ... transpose(reshape(pixelsData(2, :, :), w, h)), ... transpose(reshape(pixelsData(1, :, :), w, h))); end %end % getInteractivePosition %% Return the figure to its pre-undocked state (when relevant) function redockFigureIfRelevant(paramsStruct) if paramsStruct.wasDocked try set(paramsStruct.hFigure,'WindowStyle','docked'); %drawnow; catch % never mind - ignore... end end %end % redockFigureIfRelevant %% Copy screen-capture to the system clipboard % Adapted from http://www.mathworks.com/matlabcentral/fileexchange/28708-imclipboard/content/imclipboard.m function imclipboard(imgData) % Import necessary Java classes import java.awt.Toolkit.* import java.awt.image.BufferedImage import java.awt.datatransfer.DataFlavor % Add the necessary Java class (ImageSelection) to the Java classpath if ~exist('ImageSelection', 'class') javaaddpath(fileparts(which(mfilename)), '-end'); end % Get System Clipboard object (java.awt.Toolkit) cb = getDefaultToolkit.getSystemClipboard; % can't use () in ML6! % Get image size ht = size(imgData, 1); wd = size(imgData, 2); % Convert to Blue-Green-Red format imgData = imgData(:, :, [3 2 1]); % Convert to 3xWxH format imgData = permute(imgData, [3, 2, 1]); % Append Alpha data (not used) imgData = cat(1, imgData, 255*ones(1, wd, ht, 'uint8')); % Create image buffer imBuffer = BufferedImage(wd, ht, BufferedImage.TYPE_INT_RGB); imBuffer.setRGB(0, 0, wd, ht, typecast(imgData(:), 'int32'), 0, wd); % Create ImageSelection object % % custom java class imSelection = ImageSelection(imBuffer); % Set clipboard content to the image cb.setContents(imSelection, []); %end %imclipboard %%%%%%%%%%%%%%%%%%%%%%%%%% TODO %%%%%%%%%%%%%%%%%%%%%%%%% % find a way in interactive-mode to single-click another Matlab figure for screen-capture
github
mehta-lab/Instantaneous-PolScope-master
gridfit.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/gridfit.m
33,939
utf_8
a1f046d6cbc834284e6954d5a30dcaf4
function [zgrid,xgrid,ygrid] = gridfit(x,y,z,xnodes,ynodes,varargin) % gridfit: estimates a surface on a 2d grid, based on scattered data % Replicates are allowed. All methods extrapolate to the grid % boundaries. Gridfit uses a modified ridge estimator to % generate the surface, where the bias is toward smoothness. % % Gridfit is not an interpolant. Its goal is a smooth surface % that approximates your data, but allows you to control the % amount of smoothing. % % usage #1: zgrid = gridfit(x,y,z,xnodes,ynodes); % usage #2: [zgrid,xgrid,ygrid] = gridfit(x,y,z,xnodes,ynodes); % usage #3: zgrid = gridfit(x,y,z,xnodes,ynodes,prop,val,prop,val,...); % % Arguments: (input) % x,y,z - vectors of equal lengths, containing arbitrary scattered data % The only constraint on x and y is they cannot ALL fall on a % single line in the x-y plane. Replicate points will be treated % in a least squares sense. % % ANY points containing a NaN are ignored in the estimation % % xnodes - vector defining the nodes in the grid in the independent % variable (x). xnodes need not be equally spaced. xnodes % must completely span the data. If they do not, then the % 'extend' property is applied, adjusting the first and last % nodes to be extended as necessary. See below for a complete % description of the 'extend' property. % % If xnodes is a scalar integer, then it specifies the number % of equally spaced nodes between the min and max of the data. % % ynodes - vector defining the nodes in the grid in the independent % variable (y). ynodes need not be equally spaced. % % If ynodes is a scalar integer, then it specifies the number % of equally spaced nodes between the min and max of the data. % % Also see the extend property. % % Additional arguments follow in the form of property/value pairs. % Valid properties are: % 'smoothness', 'interp', 'regularizer', 'solver', 'maxiter' % 'extend', 'tilesize', 'overlap' % % Any UNAMBIGUOUS shortening (even down to a single letter) is % valid for property names. All properties have default values, % chosen (I hope) to give a reasonable result out of the box. % % 'smoothness' - scalar - determines the eventual smoothness of the % estimated surface. A larger value here means the surface % will be smoother. Smoothness must be a non-negative real % number. % % Note: the problem is normalized in advance so that a % smoothness of 1 MAY generate reasonable results. If you % find the result is too smooth, then use a smaller value % for this parameter. Likewise, bumpy surfaces suggest use % of a larger value. (Sometimes, use of an iterative solver % with too small a limit on the maximum number of iterations % will result in non-convergence.) % % DEFAULT: 1 % % % 'interp' - character, denotes the interpolation scheme used % to interpolate the data. % % DEFAULT: 'triangle' % % 'bilinear' - use bilinear interpolation within the grid % (also known as tensor product linear interpolation) % % 'triangle' - split each cell in the grid into a triangle, % then linear interpolation inside each triangle % % 'nearest' - nearest neighbor interpolation. This will % rarely be a good choice, but I included it % as an option for completeness. % % % 'regularizer' - character flag, denotes the regularization % paradignm to be used. There are currently three options. % % DEFAULT: 'gradient' % % 'diffusion' or 'laplacian' - uses a finite difference % approximation to the Laplacian operator (i.e, del^2). % % We can think of the surface as a plate, wherein the % bending rigidity of the plate is specified by the user % as a number relative to the importance of fidelity to % the data. A stiffer plate will result in a smoother % surface overall, but fit the data less well. I've % modeled a simple plate using the Laplacian, del^2. (A % projected enhancement is to do a better job with the % plate equations.) % % We can also view the regularizer as a diffusion problem, % where the relative thermal conductivity is supplied. % Here interpolation is seen as a problem of finding the % steady temperature profile in an object, given a set of % points held at a fixed temperature. Extrapolation will % be linear. Both paradigms are appropriate for a Laplacian % regularizer. % % 'gradient' - attempts to ensure the gradient is as smooth % as possible everywhere. Its subtly different from the % 'diffusion' option, in that here the directional % derivatives are biased to be smooth across cell % boundaries in the grid. % % The gradient option uncouples the terms in the Laplacian. % Think of it as two coupled PDEs instead of one PDE. Why % are they different at all? The terms in the Laplacian % can balance each other. % % 'springs' - uses a spring model connecting nodes to each % other, as well as connecting data points to the nodes % in the grid. This choice will cause any extrapolation % to be as constant as possible. % % Here the smoothing parameter is the relative stiffness % of the springs connecting the nodes to each other compared % to the stiffness of a spting connecting the lattice to % each data point. Since all springs have a rest length % (length at which the spring has zero potential energy) % of zero, any extrapolation will be minimized. % % Note: I don't terribly like the 'springs' strategy. % It tends to drag the surface towards the mean of all % the data. Its been left in only because the paradigm % interests me. % % % 'solver' - character flag - denotes the solver used for the % resulting linear system. Different solvers will have % different solution times depending upon the specific % problem to be solved. Up to a certain size grid, the % direct \ solver will often be speedy, until memory % swaps causes problems. % % What solver should you use? Problems with a significant % amount of extrapolation should avoid lsqr. \ may be % best numerically for small smoothnesss parameters and % high extents of extrapolation. % % Large numbers of points will slow down the direct % \, but when applied to the normal equations, \ can be % quite fast. Since the equations generated by these % methods will tend to be well conditioned, the normal % equations are not a bad choice of method to use. Beware % when a small smoothing parameter is used, since this will % make the equations less well conditioned. % % DEFAULT: 'normal' % % '\' - uses matlab's backslash operator to solve the sparse % system. 'backslash' is an alternate name. % % 'symmlq' - uses matlab's iterative symmlq solver % % 'lsqr' - uses matlab's iterative lsqr solver % % 'normal' - uses \ to solve the normal equations. % % % 'maxiter' - only applies to iterative solvers - defines the % maximum number of iterations for an iterative solver % % DEFAULT: min(10000,length(xnodes)*length(ynodes)) % % % 'extend' - character flag - controls whether the first and last % nodes in each dimension are allowed to be adjusted to % bound the data, and whether the user will be warned if % this was deemed necessary to happen. % % DEFAULT: 'warning' % % 'warning' - Adjust the first and/or last node in % x or y if the nodes do not FULLY contain % the data. Issue a warning message to this % effect, telling the amount of adjustment % applied. % % 'never' - Issue an error message when the nodes do % not absolutely contain the data. % % 'always' - automatically adjust the first and last % nodes in each dimension if necessary. % No warning is given when this option is set. % % % 'tilesize' - grids which are simply too large to solve for % in one single estimation step can be built as a set % of tiles. For example, a 1000x1000 grid will require % the estimation of 1e6 unknowns. This is likely to % require more memory (and time) than you have available. % But if your data is dense enough, then you can model % it locally using smaller tiles of the grid. % % My recommendation for a reasonable tilesize is % roughly 100 to 200. Tiles of this size take only % a few seconds to solve normally, so the entire grid % can be modeled in a finite amount of time. The minimum % tilesize can never be less than 3, although even this % size tile is so small as to be ridiculous. % % If your data is so sparse than some tiles contain % insufficient data to model, then those tiles will % be left as NaNs. % % DEFAULT: inf % % % 'overlap' - Tiles in a grid have some overlap, so they % can minimize any problems along the edge of a tile. % In this overlapped region, the grid is built using a % bi-linear combination of the overlapping tiles. % % The overlap is specified as a fraction of the tile % size, so an overlap of 0.20 means there will be a 20% % overlap of successive tiles. I do allow a zero overlap, % but it must be no more than 1/2. % % 0 <= overlap <= 0.5 % % Overlap is ignored if the tilesize is greater than the % number of nodes in both directions. % % DEFAULT: 0.20 % % % 'autoscale' - Some data may have widely different scales on % the respective x and y axes. If this happens, then % the regularization may experience difficulties. % % autoscale = 'on' will cause gridfit to scale the x % and y node intervals to a unit length. This should % improve the regularization procedure. The scaling is % purely internal. % % autoscale = 'off' will disable automatic scaling % % DEFAULT: 'on' % % % Arguments: (output) % zgrid - (nx,ny) array containing the fitted surface % % xgrid, ygrid - as returned by meshgrid(xnodes,ynodes) % % % Speed considerations: % Remember that gridfit must solve a LARGE system of linear % equations. There will be as many unknowns as the total % number of nodes in the final lattice. While these equations % may be sparse, solving a system of 10000 equations may take % a second or so. Very large problems may benefit from the % iterative solvers or from tiling. % % % Example usage: % % x = rand(100,1); % y = rand(100,1); % z = exp(x+2*y); % xnodes = 0:.1:1; % ynodes = 0:.1:1; % % g = gridfit(x,y,z,xnodes,ynodes); % % Note: this is equivalent to the following call: % % g = gridfit(x,y,z,xnodes,ynodes, ... % 'smooth',1, ... % 'interp','triangle', ... % 'solver','normal', ... % 'regularizer','gradient', ... % 'extend','warning', ... % 'tilesize',inf); % % % Author: John D'Errico % e-mail address: [email protected] % Release: 2.0 % Release date: 5/23/06 % set defaults params.smoothness = 1; params.interp = 'triangle'; params.regularizer = 'gradient'; params.solver = 'normal'; params.maxiter = []; params.extend = 'warning'; params.tilesize = inf; params.overlap = 0.20; params.mask = []; params.autoscale = 'on'; params.xscale = 1; params.yscale = 1; % was the params struct supplied? if ~isempty(varargin) if isstruct(varargin{1}) % params is only supplied if its a call from tiled_gridfit params = varargin{1}; if length(varargin)>1 % check for any overrides params = parse_pv_pairs(params,varargin{2:end}); end else % check for any overrides of the defaults params = parse_pv_pairs(params,varargin); end end % check the parameters for acceptability params = check_params(params); % ensure all of x,y,z,xnodes,ynodes are column vectors, % also drop any NaN data x=x(:); y=y(:); z=z(:); k = isnan(x) | isnan(y) | isnan(z); if any(k) x(k)=[]; y(k)=[]; z(k)=[]; end xmin = min(x); xmax = max(x); ymin = min(y); ymax = max(y); % did they supply a scalar for the nodes? if length(xnodes)==1 xnodes = linspace(xmin,xmax,xnodes)'; xnodes(end) = xmax; % make sure it hits the max end if length(ynodes)==1 ynodes = linspace(ymin,ymax,ynodes)'; ynodes(end) = ymax; % make sure it hits the max end xnodes=xnodes(:); ynodes=ynodes(:); dx = diff(xnodes); dy = diff(ynodes); nx = length(xnodes); ny = length(ynodes); ngrid = nx*ny; % set the scaling if autoscale was on if strcmpi(params.autoscale,'on') params.xscale = mean(dx); params.yscale = mean(dy); params.autoscale = 'off'; end % check to see if any tiling is necessary if (params.tilesize < max(nx,ny)) % split it into smaller tiles. compute zgrid and ygrid % at the very end if requested zgrid = tiled_gridfit(x,y,z,xnodes,ynodes,params); else % its a single tile. % mask must be either an empty array, or a boolean % aray of the same size as the final grid. nmask = size(params.mask); if ~isempty(params.mask) && ((nmask(2)~=nx) || (nmask(1)~=ny)) if ((nmask(2)==ny) || (nmask(1)==nx)) error 'Mask array is probably transposed from proper orientation.' else error 'Mask array must be the same size as the final grid.' end end if ~isempty(params.mask) params.maskflag = 1; else params.maskflag = 0; end % default for maxiter? if isempty(params.maxiter) params.maxiter = min(10000,nx*ny); end % check lengths of the data n = length(x); if (length(y)~=n) || (length(z)~=n) error 'Data vectors are incompatible in size.' end if n<3 error 'Insufficient data for surface estimation.' end % verify the nodes are distinct if any(diff(xnodes)<=0) || any(diff(ynodes)<=0) error 'xnodes and ynodes must be monotone increasing' end % do we need to tweak the first or last node in x or y? if xmin<xnodes(1) switch params.extend case 'always' xnodes(1) = xmin; case 'warning' warning(['xnodes(1) was decreased by: ',num2str(xnodes(1)-xmin),', new node = ',num2str(xmin)]) xnodes(1) = xmin; case 'never' error(['Some x (',num2str(xmin),') falls below xnodes(1) by: ',num2str(xnodes(1)-xmin)]) end end if xmax>xnodes(end) switch params.extend case 'always' xnodes(end) = xmax; case 'warning' warning(['xnodes(end) was increased by: ',num2str(xmax-xnodes(end)),', new node = ',num2str(xmax)]) xnodes(end) = xmax; case 'never' error(['Some x (',num2str(xmax),') falls above xnodes(end) by: ',num2str(xmax-xnodes(end))]) end end if ymin<ynodes(1) switch params.extend case 'always' ynodes(1) = ymin; case 'warning' warning(['ynodes(1) was decreased by: ',num2str(ynodes(1)-ymin),', new node = ',num2str(ymin)]) ynodes(1) = ymin; case 'never' error(['Some y (',num2str(ymin),') falls below ynodes(1) by: ',num2str(ynodes(1)-ymin)]) end end if ymax>ynodes(end) switch params.extend case 'always' ynodes(end) = ymax; case 'warning' warning(['ynodes(end) was increased by: ',num2str(ymax-ynodes(end)),', new node = ',num2str(ymax)]) ynodes(end) = ymax; case 'never' error(['Some y (',num2str(ymax),') falls above ynodes(end) by: ',num2str(ymax-ynodes(end))]) end end % determine which cell in the array each point lies in [junk,indx] = histc(x,xnodes); %#ok [junk,indy] = histc(y,ynodes); %#ok % any point falling at the last node is taken to be % inside the last cell in x or y. k=(indx==nx); indx(k)=indx(k)-1; k=(indy==ny); indy(k)=indy(k)-1; ind = indy + ny*(indx-1); % Do we have a mask to apply? if params.maskflag % if we do, then we need to ensure that every % cell with at least one data point also has at % least all of its corners unmasked. params.mask(ind) = 1; params.mask(ind+1) = 1; params.mask(ind+ny) = 1; params.mask(ind+ny+1) = 1; end % interpolation equations for each point tx = min(1,max(0,(x - xnodes(indx))./dx(indx))); ty = min(1,max(0,(y - ynodes(indy))./dy(indy))); % Future enhancement: add cubic interpolant switch params.interp case 'triangle' % linear interpolation inside each triangle k = (tx > ty); L = ones(n,1); L(k) = ny; t1 = min(tx,ty); t2 = max(tx,ty); A = sparse(repmat((1:n)',1,3),[ind,ind+ny+1,ind+L], ... [1-t2,t1,t2-t1],n,ngrid); case 'nearest' % nearest neighbor interpolation in a cell k = round(1-ty) + round(1-tx)*ny; A = sparse((1:n)',ind+k,ones(n,1),n,ngrid); case 'bilinear' % bilinear interpolation in a cell A = sparse(repmat((1:n)',1,4),[ind,ind+1,ind+ny,ind+ny+1], ... [(1-tx).*(1-ty), (1-tx).*ty, tx.*(1-ty), tx.*ty], ... n,ngrid); end rhs = z; % Build regularizer. Add del^4 regularizer one day. switch params.regularizer case 'springs' % zero "rest length" springs [i,j] = meshgrid(1:nx,1:(ny-1)); ind = j(:) + ny*(i(:)-1); m = nx*(ny-1); stiffness = 1./(dy/params.yscale); Areg = sparse(repmat((1:m)',1,2),[ind,ind+1], ... stiffness(j(:))*[-1 1],m,ngrid); [i,j] = meshgrid(1:(nx-1),1:ny); ind = j(:) + ny*(i(:)-1); m = (nx-1)*ny; stiffness = 1./(dx/params.xscale); Areg = [Areg;sparse(repmat((1:m)',1,2),[ind,ind+ny], ... stiffness(i(:))*[-1 1],m,ngrid)]; [i,j] = meshgrid(1:(nx-1),1:(ny-1)); ind = j(:) + ny*(i(:)-1); m = (nx-1)*(ny-1); stiffness = 1./sqrt((dx(i(:))/params.xscale).^2 + ... (dy(j(:))/params.yscale).^2); Areg = [Areg;sparse(repmat((1:m)',1,2),[ind,ind+ny+1], ... stiffness*[-1 1],m,ngrid)]; Areg = [Areg;sparse(repmat((1:m)',1,2),[ind+1,ind+ny], ... stiffness*[-1 1],m,ngrid)]; case {'diffusion' 'laplacian'} % thermal diffusion using Laplacian (del^2) [i,j] = meshgrid(1:nx,2:(ny-1)); ind = j(:) + ny*(i(:)-1); dy1 = dy(j(:)-1)/params.yscale; dy2 = dy(j(:))/params.yscale; Areg = sparse(repmat(ind,1,3),[ind-1,ind,ind+1], ... [-2./(dy1.*(dy1+dy2)), 2./(dy1.*dy2), ... -2./(dy2.*(dy1+dy2))],ngrid,ngrid); [i,j] = meshgrid(2:(nx-1),1:ny); ind = j(:) + ny*(i(:)-1); dx1 = dx(i(:)-1)/params.xscale; dx2 = dx(i(:))/params.xscale; Areg = Areg + sparse(repmat(ind,1,3),[ind-ny,ind,ind+ny], ... [-2./(dx1.*(dx1+dx2)), 2./(dx1.*dx2), ... -2./(dx2.*(dx1+dx2))],ngrid,ngrid); case 'gradient' % Subtly different from the Laplacian. A point for future % enhancement is to do it better for the triangle interpolation % case. [i,j] = meshgrid(1:nx,2:(ny-1)); ind = j(:) + ny*(i(:)-1); dy1 = dy(j(:)-1)/params.yscale; dy2 = dy(j(:))/params.yscale; Areg = sparse(repmat(ind,1,3),[ind-1,ind,ind+1], ... [-2./(dy1.*(dy1+dy2)), 2./(dy1.*dy2), ... -2./(dy2.*(dy1+dy2))],ngrid,ngrid); [i,j] = meshgrid(2:(nx-1),1:ny); ind = j(:) + ny*(i(:)-1); dx1 = dx(i(:)-1)/params.xscale; dx2 = dx(i(:))/params.xscale; Areg = [Areg;sparse(repmat(ind,1,3),[ind-ny,ind,ind+ny], ... [-2./(dx1.*(dx1+dx2)), 2./(dx1.*dx2), ... -2./(dx2.*(dx1+dx2))],ngrid,ngrid)]; end nreg = size(Areg,1); % Append the regularizer to the interpolation equations, % scaling the problem first. Use the 1-norm for speed. NA = norm(A,1); NR = norm(Areg,1); A = [A;Areg*(params.smoothness*NA/NR)]; rhs = [rhs;zeros(nreg,1)]; % do we have a mask to apply? if params.maskflag unmasked = find(params.mask); end % solve the full system, with regularizer attached switch params.solver case {'\' 'backslash'} if params.maskflag % there is a mask to use % permute for minimum fill in for R (in the QR) p = colamd(A(:,unmasked)); zgrid=nan(ny,nx); zgrid(unmasked(p)) = A(:,unmasked(p))\rhs; else % permute for minimum fill in for R (in the QR) p = colamd(A); zgrid=zeros(ny,nx); zgrid(p) = A(:,p)\rhs; end case 'normal' % The normal equations, solved with \. Can be fast % for huge numbers of data points. if params.maskflag % there is a mask to use % Permute for minimum fill-in for \ (in chol) APA = A(:,unmasked)'*A(:,unmasked); p = symamd(APA); zgrid=nan(ny,nx); zgrid(unmasked(p)) = APA(p,p)\(A(:,unmasked(p))'*rhs); else % Permute for minimum fill-in for \ (in chol) APA = A'*A; p = symamd(APA); zgrid=zeros(ny,nx); zgrid(p) = APA(p,p)\(A(:,p)'*rhs); end case 'symmlq' % iterative solver - symmlq - requires a symmetric matrix, % so use it to solve the normal equations. No preconditioner. tol = abs(max(z)-min(z))*1.e-13; if params.maskflag % there is a mask to use zgrid=nan(ny,nx); [zgrid(unmasked),flag] = symmlq(A(:,unmasked)'*A(:,unmasked), ... A(:,unmasked)'*rhs,tol,params.maxiter); else [zgrid,flag] = symmlq(A'*A,A'*rhs,tol,params.maxiter); zgrid = reshape(zgrid,ny,nx); end % display a warning if convergence problems switch flag case 0 % no problems with convergence case 1 % SYMMLQ iterated MAXIT times but did not converge. warning(['Symmlq performed ',num2str(params.maxiter), ... ' iterations but did not converge.']) case 3 % SYMMLQ stagnated, successive iterates were the same warning 'Symmlq stagnated without apparent convergence.' otherwise warning(['One of the scalar quantities calculated in',... ' symmlq was too small or too large to continue computing.']) end case 'lsqr' % iterative solver - lsqr. No preconditioner here. tol = abs(max(z)-min(z))*1.e-13; if params.maskflag % there is a mask to use zgrid=nan(ny,nx); [zgrid(unmasked),flag] = lsqr(A(:,unmasked),rhs,tol,params.maxiter); else [zgrid,flag] = lsqr(A,rhs,tol,params.maxiter); zgrid = reshape(zgrid,ny,nx); end % display a warning if convergence problems switch flag case 0 % no problems with convergence case 1 % lsqr iterated MAXIT times but did not converge. warning(['Lsqr performed ',num2str(params.maxiter), ... ' iterations but did not converge.']) case 3 % lsqr stagnated, successive iterates were the same warning 'Lsqr stagnated without apparent convergence.' case 4 warning(['One of the scalar quantities calculated in',... ' LSQR was too small or too large to continue computing.']) end end end % if params.tilesize... % only generate xgrid and ygrid if requested. if nargout>1 [xgrid,ygrid]=meshgrid(xnodes,ynodes); end % ============================================ % End of main function - gridfit % ============================================ % ============================================ % subfunction - parse_pv_pairs % ============================================ function params=parse_pv_pairs(params,pv_pairs) % parse_pv_pairs: parses sets of property value pairs, allows defaults % usage: params=parse_pv_pairs(default_params,pv_pairs) % % arguments: (input) % default_params - structure, with one field for every potential % property/value pair. Each field will contain the default % value for that property. If no default is supplied for a % given property, then that field must be empty. % % pv_array - cell array of property/value pairs. % Case is ignored when comparing properties to the list % of field names. Also, any unambiguous shortening of a % field/property name is allowed. % % arguments: (output) % params - parameter struct that reflects any updated property/value % pairs in the pv_array. % % Example usage: % First, set default values for the parameters. Assume we % have four parameters that we wish to use optionally in % the function examplefun. % % - 'viscosity', which will have a default value of 1 % - 'volume', which will default to 1 % - 'pie' - which will have default value 3.141592653589793 % - 'description' - a text field, left empty by default % % The first argument to examplefun is one which will always be % supplied. % % function examplefun(dummyarg1,varargin) % params.Viscosity = 1; % params.Volume = 1; % params.Pie = 3.141592653589793 % % params.Description = ''; % params=parse_pv_pairs(params,varargin); % params % % Use examplefun, overriding the defaults for 'pie', 'viscosity' % and 'description'. The 'volume' parameter is left at its default. % % examplefun(rand(10),'vis',10,'pie',3,'Description','Hello world') % % params = % Viscosity: 10 % Volume: 1 % Pie: 3 % Description: 'Hello world' % % Note that capitalization was ignored, and the property 'viscosity' % was truncated as supplied. Also note that the order the pairs were % supplied was arbitrary. npv = length(pv_pairs); n = npv/2; if n~=floor(n) error 'Property/value pairs must come in PAIRS.' end if n<=0 % just return the defaults return end if ~isstruct(params) error 'No structure for defaults was supplied' end % there was at least one pv pair. process any supplied propnames = fieldnames(params); lpropnames = lower(propnames); for i=1:n p_i = lower(pv_pairs{2*i-1}); v_i = pv_pairs{2*i}; ind = strmatch(p_i,lpropnames,'exact'); if isempty(ind) ind = find(strncmp(p_i,lpropnames,length(p_i))); if isempty(ind) error(['No matching property found for: ',pv_pairs{2*i-1}]) elseif length(ind)>1 error(['Ambiguous property name: ',pv_pairs{2*i-1}]) end end p_i = propnames{ind}; % override the corresponding default in params params = setfield(params,p_i,v_i); %#ok end % ============================================ % subfunction - check_params % ============================================ function params = check_params(params) % check the parameters for acceptability % smoothness == 1 by default if isempty(params.smoothness) params.smoothness = 1; else if (length(params.smoothness)>1) || (params.smoothness<=0) error 'Smoothness must be scalar, real, finite, and positive.' end end % regularizer - must be one of 4 options - the second and % third are actually synonyms. valid = {'springs', 'diffusion', 'laplacian', 'gradient'}; if isempty(params.regularizer) params.regularizer = 'diffusion'; end ind = find(strncmpi(params.regularizer,valid,length(params.regularizer))); if (length(ind)==1) params.regularizer = valid{ind}; else error(['Invalid regularization method: ',params.regularizer]) end % interp must be one of: % 'bilinear', 'nearest', or 'triangle' % but accept any shortening thereof. valid = {'bilinear', 'nearest', 'triangle'}; if isempty(params.interp) params.interp = 'triangle'; end ind = find(strncmpi(params.interp,valid,length(params.interp))); if (length(ind)==1) params.interp = valid{ind}; else error(['Invalid interpolation method: ',params.interp]) end % solver must be one of: % 'backslash', '\', 'symmlq', 'lsqr', or 'normal' % but accept any shortening thereof. valid = {'backslash', '\', 'symmlq', 'lsqr', 'normal'}; if isempty(params.solver) params.solver = '\'; end ind = find(strncmpi(params.solver,valid,length(params.solver))); if (length(ind)==1) params.solver = valid{ind}; else error(['Invalid solver option: ',params.solver]) end % extend must be one of: % 'never', 'warning', 'always' % but accept any shortening thereof. valid = {'never', 'warning', 'always'}; if isempty(params.extend) params.extend = 'warning'; end ind = find(strncmpi(params.extend,valid,length(params.extend))); if (length(ind)==1) params.extend = valid{ind}; else error(['Invalid extend option: ',params.extend]) end % tilesize == inf by default if isempty(params.tilesize) params.tilesize = inf; elseif (length(params.tilesize)>1) || (params.tilesize<3) error 'Tilesize must be scalar and > 0.' end % overlap == 0.20 by default if isempty(params.overlap) params.overlap = 0.20; elseif (length(params.overlap)>1) || (params.overlap<0) || (params.overlap>0.5) error 'Overlap must be scalar and 0 < overlap < 1.' end % ============================================ % subfunction - tiled_gridfit % ============================================ function zgrid=tiled_gridfit(x,y,z,xnodes,ynodes,params) % tiled_gridfit: a tiled version of gridfit, continuous across tile boundaries % usage: [zgrid,xgrid,ygrid]=tiled_gridfit(x,y,z,xnodes,ynodes,params) % % Tiled_gridfit is used when the total grid is far too large % to model using a single call to gridfit. While gridfit may take % only a second or so to build a 100x100 grid, a 2000x2000 grid % will probably not run at all due to memory problems. % % Tiles in the grid with insufficient data (<4 points) will be % filled with NaNs. Avoid use of too small tiles, especially % if your data has holes in it that may encompass an entire tile. % % A mask may also be applied, in which case tiled_gridfit will % subdivide the mask into tiles. Note that any boolean mask % provided is assumed to be the size of the complete grid. % % Tiled_gridfit may not be fast on huge grids, but it should run % as long as you use a reasonable tilesize. 8-) % Note that we have already verified all parameters in check_params % Matrix elements in a square tile tilesize = params.tilesize; % Size of overlap in terms of matrix elements. Overlaps % of purely zero cause problems, so force at least two % elements to overlap. overlap = max(2,floor(tilesize*params.overlap)); % reset the tilesize for each particular tile to be inf, so % we will never see a recursive call to tiled_gridfit Tparams = params; Tparams.tilesize = inf; nx = length(xnodes); ny = length(ynodes); zgrid = zeros(ny,nx); % linear ramp for the bilinear interpolation rampfun = inline('(t-t(1))/(t(end)-t(1))','t'); % loop over each tile in the grid h = waitbar(0,'Relax and have a cup of JAVA. Its my treat.'); warncount = 0; xtind = 1:min(nx,tilesize); while ~isempty(xtind) && (xtind(1)<=nx) xinterp = ones(1,length(xtind)); if (xtind(1) ~= 1) xinterp(1:overlap) = rampfun(xnodes(xtind(1:overlap))); end if (xtind(end) ~= nx) xinterp((end-overlap+1):end) = 1-rampfun(xnodes(xtind((end-overlap+1):end))); end ytind = 1:min(ny,tilesize); while ~isempty(ytind) && (ytind(1)<=ny) % update the waitbar waitbar((xtind(end)-tilesize)/nx + tilesize*ytind(end)/ny/nx) yinterp = ones(length(ytind),1); if (ytind(1) ~= 1) yinterp(1:overlap) = rampfun(ynodes(ytind(1:overlap))); end if (ytind(end) ~= ny) yinterp((end-overlap+1):end) = 1-rampfun(ynodes(ytind((end-overlap+1):end))); end % was a mask supplied? if ~isempty(params.mask) submask = params.mask(ytind,xtind); Tparams.mask = submask; end % extract data that lies in this grid tile k = (x>=xnodes(xtind(1))) & (x<=xnodes(xtind(end))) & ... (y>=ynodes(ytind(1))) & (y<=ynodes(ytind(end))); k = find(k); if length(k)<4 if warncount == 0 warning 'A tile was too underpopulated to model. Filled with NaNs.' end warncount = warncount + 1; % fill this part of the grid with NaNs zgrid(ytind,xtind) = NaN; else % build this tile zgtile = gridfit(x(k),y(k),z(k),xnodes(xtind),ynodes(ytind),Tparams); % bilinear interpolation (using an outer product) interp_coef = yinterp*xinterp; % accumulate the tile into the complete grid zgrid(ytind,xtind) = zgrid(ytind,xtind) + zgtile.*interp_coef; end % step to the next tile in y if ytind(end)<ny ytind = ytind + tilesize - overlap; % are we within overlap elements of the edge of the grid? if (ytind(end)+max(3,overlap))>=ny % extend this tile to the edge ytind = ytind(1):ny; end else ytind = ny+1; end end % while loop over y % step to the next tile in x if xtind(end)<nx xtind = xtind + tilesize - overlap; % are we within overlap elements of the edge of the grid? if (xtind(end)+max(3,overlap))>=nx % extend this tile to the edge xtind = xtind(1):nx; end else xtind = nx+1; end end % while loop over x % close down the waitbar close(h) if warncount>0 warning([num2str(warncount),' tiles were underpopulated & filled with NaNs']) end
github
mehta-lab/Instantaneous-PolScope-master
distance2curve.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/distance2curve.m
55,860
utf_8
eda95809c753c165dd4f72f49b652555
function [xy,distance,t_a] = distance2curve(curvexy,mapxy,interpmethod) % distance2curve: minimum distance from a point to a general curvilinear n-dimensional arc % usage: [xy,distance,t] = distance2curve(curvexy,mapxy) % uses linear curve segments % usage: [xy,distance,t] = distance2curve(curvexy,mapxy,interpmethod) % % Identifies the closest point along a general space curve (a 1-d path % in some space) to some new set of points. The curve may be piecewise % linear or a parametric spline or pchip model. % % arguments: (input) % curvexy - An nxp real numeric array containing the points of the % curve. For 2-dimensional curves, p == 2. This will be a list % of points (each row of the array is a new point) that % define the curve. The curve may cross itself in space. % Closed curves are acceptable, in which case the first % and last points would be identical. (Sorry, but periodic % end conditions are not an option for the spline at this time.) % % Since a curve makes no sense in less than 2 dimensions, % p >= 2 is required. % % mapxy - an mxp real numeric array, where m is the number of new points % to be mapped to the curve in term of their closest distance. % % These points which will be mapped to the existing curve % in terms of the minimium (euclidean, 2-norm) distance % to the curve. Each row of this array will be a different % point. % % interpmethod - (OPTIONAL) string flag - denotes the method % used to compute the arc length of the curve. % % method may be any of 'linear', 'spline', or 'pchip', % or any simple contraction thereof, such as 'lin', % 'sp', or even 'p'. % % interpmethod == 'linear' --> Uses a linear chordal % approximation to define the curve. % This method is the most efficient. % % interpmethod == 'pchip' --> Fits a parametric pchip % approximation. % % interpmethod == 'spline' --> Uses a parametric spline % approximation to fit the curves. Generally for % a smooth curve, this method may be most accurate. % % DEFAULT: 'linear' % % arguments: (output) % xy - an mxp array, contains the closest point identified along % the curve to each of the points provided in mapxy. % % distance - an mx1 vector, the actual distance to the curve, % in terms minimum Euclidean distance. % % t - fractional arc length along the interpolating curve to that % point. This is the same value that interparc would use to % produce the points in xy. % % % Example: % % Find the closest points and the distance to a polygonal line from % % several test points. % % curvexy = [0 0;1 0;2 1;0 .5;0 0]; % mapxy = [3 4;.5 .5;3 -1]; % [xy,distance,t] = distance2curve(curvexy,mapxy,'linear') % % xy = % % 2 1 % % 0.470588235294118 0.617647058823529 % % 1.5 0.5 % % distance = % % 3.16227766016838 % % 0.121267812518166 % % 2.12132034355964 % % t = % % 0.485194315877587 % % 0.802026225550702 % % 0.34308419095021 % % % plot(curvexy(:,1),curvexy(:,2),'k-o',mapxy(:,1),mapxy(:,2),'r*') % hold on % plot(xy(:,1),xy(:,2),'g*') % line([mapxy(:,1),xy(:,1)]',[mapxy(:,2),xy(:,2)]','color',[0 0 1]) % axis equal % % % Example: % % Solve for the nearest point on the curve of a 3-d quasi-elliptical % % arc (sampled and interpolated from 20 points) mapping a set of points % % along a surrounding circle onto the ellipse. This is the example % % used to generate the screenshot figure. % t = linspace(0,2*pi,20)'; % curvexy = [cos(t) - 1,3*sin(t) + cos(t) - 1.25,(t/2 + cos(t)).*sin(t)]; % % s = linspace(0,2*pi,100)'; % mapxy = 5*[cos(s),sin(s),sin(s)]; % xy = distance2curve(curvexy,mapxy,'spline'); % % plot3(curvexy(:,1),curvexy(:,2),curvexy(:,3),'ko') % line([mapxy(:,1),xy(:,1)]',[mapxy(:,2),xy(:,2)]',[mapxy(:,3),xy(:,3)]','color',[0 0 1]) % axis equal % axis square % box on % grid on % view(26,-6) % % % Example: % % distance2curve is fairly fast, at least for the linear case. % % Map 1e6 points onto a polygonal curve in 10 dimensions. % curvexy = cumsum(rand(10,10)); % mapxy = rand(1000000,10)*5; % tic,[xy,distance] = distance2curve(curvexy,mapxy,'linear');toc % % Elapsed time is 2.867453 seconds. % % % See also: interparc, spline, pchip, interp1, arclength % % Author: John D'Errico % e-mail: [email protected] % Release: 1.0 % Release date: 9/22/2010 % check for errors, defaults, etc... if (nargin < 2) error('DISTANCE2CURVE:insufficientarguments', ... 'at least curvexy and mapxy must be supplied') elseif nargin > 3 error('DISTANCE2CURVE:abundantarguments', ... 'Too many arguments were supplied') end % get the dimension of the space our points live in [n,p] = size(curvexy); if isempty(curvexy) || isempty(mapxy) % empty begets empty. you might say this was a pointless exercise. xy = zeros(0,p); distance = zeros(0,p); t_a = zeros(0,p); return end % do curvexy and mapxy live in the same space? if size(mapxy,2) ~= p error('DISTANCE2CURVE:improperpxorpy', ... 'curvexy and mapxy do not appear to live in the same dimension spaces') end % do the points live in at least 2 dimensions? if p < 2 error('DISTANCE2CURVE:improperpxorpy', ... 'The points MUST live in at least 2 dimensions for any curve to be defined.') end % how many points to be mapped to the curve? m = size(mapxy,1); % make sure that curvexy and mapxy are doubles, as uint8, etc % would cause problems down the line. curvexy = double(curvexy); mapxy = double(mapxy); % test for complex inputs if ~isreal(curvexy) || ~isreal(mapxy) error('DISTANCE2CURVE:complexinputs','curvexy and mapxy may not be complex') end % default for interpmethod if (nargin < 3) || isempty(interpmethod) interpmethod = 'linear'; elseif ~ischar(interpmethod) error('DISTANCE2CURVE:invalidinterpmethod', ... 'Invalid method indicated. Only ''linear'',''pchip'',''spline'' allowed') else validmethods = {'linear' 'pchip' 'spline'}; ind = strmatch(lower(interpmethod),validmethods); if isempty(ind) || (length(ind) > 1) error('DISTANCE2CURVE:invalidinterpmethod', ... 'Invalid method indicated. Only ''linear'',''pchip'',''spline'' allowed') end interpmethod = validmethods{ind}; end % if the curve is a single point, stop here if n == 1 % return the appropriate parameters xy = repmat(curvexy,m,1); t_a = zeros(m,1); % 2 norm distance, or sqrt of sum of squares of differences distance = sqrt(sum(bsxfun(@minus,curvexy,mapxy).^2,2)); % we can drop out here return end % compute the chordal linear arclengths, and scale to [0,1]. seglen = sqrt(sum(diff(curvexy,[],1).^2,2)); t0 = [0;cumsum(seglen)/sum(seglen)]; % We need to build some parametric splines. % compute the splines, storing the polynomials in one 3-d array ppsegs = cell(1,p); % the breaks for the splines will be t0, unless spline got fancy % on us here. breaks = t0; for i = 1:p switch interpmethod case 'linear' dt = diff(t0); ind = 1:(n-1); ppsegs{i} = [(curvexy(ind + 1,i) - curvexy(ind,i))./dt,curvexy(ind,i)]; case 'pchip' spl = pchip(t0,curvexy(:,i)); ppsegs{i} = spl.coefs; case 'spline' spl = spline(t0,curvexy(:,i)); breaks = spl.breaks'; nc = numel(spl.coefs); if nc < 4 % just pretend it has cubic segments spl.coefs = [zeros(1,4-nc),spl{i}.coefs]; spl.order = 4; end ppsegs{i} = spl.coefs; end end % how many breaks did we find in the spline? This is % only a thing to worry about for a spline based on few points, % when the function spline.m may choose to use only two breaks. nbr = numel(breaks); % for each point in mapxy, find the closest point to those % in curvexy. This part we can do in a vectorized form. pointdistances = ipdm(mapxy,curvexy,'metric',2, ... 'result','structure','subset','nearestneighbor'); % initialize the return variables, using the closest point % found in the set curvexy. xy = curvexy(pointdistances.columnindex,:); distance = pointdistances.distance; t = t0(pointdistances.columnindex); % we must now do at least some looping, still vectorized where possible. % the piecewise linear case is simpler though, so do it separately. if strcmp(interpmethod,'linear'); % loop over the individual points, vectorizing in the number of % segments, when there are many segments, but not many points to map. if n >= (5*m) % many segments, so loop over the points in mapxy for i = 1:m % the i'th point in mapxy xyi = mapxy(i,:); % Compute the location (in t) of the minimal distance % point to xyi, for all lines. tnum = zeros(nbr - 1,1); tden = tnum; for j = 1:p ppj = ppsegs{j}; tden = tden + ppj(:,1).^2; tnum = tnum + ppj(:,1).*(xyi(j) - ppj(:,2)); end tmin = tnum./tden; % toss out any element of tmin that is less than or equal to % zero, or or is greater than dt for that segment. tmin((tmin <= 0) | (tmin >= diff(t0))) = NaN; % for any segments with a valid minimum distance inside the % segment itself, compute that distance. dmin = zeros(nbr - 1,1); for j = 1:p ppi = ppsegs{j}; dmin = dmin + (ppi(:,1).*tmin + ppi(:,2) - xyi(j)).^2; end dmin = sqrt(dmin); % what is the minimum distance among these segments? [mindist,minind] = min(dmin); if ~isnan(mindist) && (distance(i) > mindist) % there is a best segment, better than the % closest point from curvexy. distance(i) = mindist; t(i) = tmin(minind) + t0(minind); for j = 1:p ppj = ppsegs{j}; xy(i,j) = ppj(minind,1).*tmin(minind) + ppj(minind,2); end end end else for i = 1:(n-1) % the i'th segment of the curve t1 = t0(i); t2 = t0(i+1); % Compute the location (in t) of the minimal distance % point to mapxy, for all points. tnum = zeros(m,1); tden = 0; for j = 1:p ppj = ppsegs{j}; tden = tden + ppj(i,1).^2; tnum = tnum + ppj(i,1).*(mapxy(:,j) - ppj(i,2)); end tmin = tnum./tden; % We only care about those points for this segment where there % is a minimal distance to the segment that is internal to the % segment. k = find((tmin > 0) & (tmin < (t2-t1))); nk = numel(k); if nk > 0 % for any points with a valid minimum distance inside the % segment itself, compute that distance. dmin = zeros(nk,1); xymin = zeros(nk,p); for j = 1:p ppj = ppsegs{j}; xymin(:,j) = ppj(i,1).*tmin(k) + ppj(i,2); dmin = dmin + (xymin(:,j) - mapxy(k,j)).^2; end dmin = sqrt(dmin); L = dmin < distance(k); % this segment has a closer point % closest point from curvexy. if any(L) distance(k(L)) = dmin(L); t(k(L)) = tmin(k(L)) + t0(i); xy(k(L),:) = xymin(L,:); end end end end % for the linear case, t is identical to the fractional arc length % along the curve. t_a = t; else % cubic segments. here it is simplest to loop over the % distinct curve segments. We need not test the endpoints % of the segments, since the call to ipdm did that part. xytrans = zeros(1,p); polydiff = @(dp) dp(1:6).*[6 5 4 3 2 1]; for j = 1:(n-1) % the j'th curve segment t1 = t0(j); t2 = t0(j+1); % for a polynomial in t that looks like % P(t) = a1*t^3 + a2*t^2 + a3*t + a4, in each dimension, % extract the polynomial pieces for the 6th degree polynomial % in t for the square of the Euclidean distance to the curve. % Thus, (P_x(t) - x0)^2 + (P_y(t) - y0)^2 + ... % % a1^2*t^6 % 2*a1*a2*t^5 % (2*a1*a3 + a2^2)*t^4 % (2*a2*a3 - 2*a1*x0 + 2*a1*a4)*t^3 % (a3^2 - 2*a2*x0 + 2*a2*a4)*t^2 % (-2*a3*x0 + 2*a3*a4)*t % x0^2 - 2*a4*x0 + a4^2 % % here, only the parts of this distance that are independent of % the point itself are computed. so the x0 terms are not built % yet. All of the terms with a4 in them will go away because % of the translation. distpoly0 = zeros(1,7); for i = 1:p ppi = ppsegs{i}; % this will allow us to translate each poly to pass through % (0,0) (i.e., at t = 0) xytrans(i) = ppi(j,4); distpoly0(1:2) = distpoly0(1:2) + ppi(j,1).*[ppi(j,1),2*ppi(j,2)]; distpoly0(3) = distpoly0(3) + 2.*ppi(j,1).*ppi(j,3) + ppi(j,2).^2; distpoly0(4) = distpoly0(4) + 2.*ppi(j,2).*ppi(j,3); distpoly0(5) = distpoly0(5) + ppi(j,3).^2; end for i = 1:m % the i'th point, translated by xytrans. The translation does % not change the distance to this segment, but it does make % the computations more robust to numerical problems. xyi = mapxy(i,:) - xytrans; % update the poly for this particular point % (-2*a1*x0)*t^3 % (-2*a2*x0)*t^2 % (-2*a3*x0)*t % x0^2 distpoly = distpoly0; for k = 1:p ppk = ppsegs{k}; distpoly(4:6) = distpoly(4:6) - 2.*ppk(j,1:3).*xyi(k); distpoly(7) = distpoly(7) + xyi(k).^2; end % find any minima of this polynomial in the interval (0,t2-t1). % we can ignore solutions that happen at the endpoints of the % interval, since those are already covered by ipdm. % % merely compute the zeros of the derivative polynomial diffpoly = polydiff(distpoly); tstationary = roots(diffpoly); % discard any with an imaginary part, those that are less % than 0, or greater than t2-t1. k = (imag(tstationary) ~= 0) | ... (real(tstationary) <= 0) | ... (real(tstationary) >= (t2 - t1)); tstationary(k) = []; % for any solutions that remain, compute the distance. if ~isempty(tstationary) mindist = zeros(size(tstationary)); xyij = zeros(numel(tstationary),p); for k = 1:p xyij(:,k) = polyval(ppsegs{k}(j,:),tstationary); mindist = mindist + (mapxy(i,k) - xyij(:,k)).^2; end mindist = sqrt(mindist); % just in case there is more than one stationary point [mindist,ind] = min(mindist); if mindist < distance(i) % we found a point on this segment that is better % than the endpoint values for that segment. distance(i) = mindist; xy(i,:) = xyij(ind,:); t(i) = tstationary(ind) + t0(j); end end % if ~isempty(tstationary) end % for i = 1:n end % for j = 1:(n-1) % do we need to return t_a? t_a is the same number that interparc % uses, whereas t as we have computed it so far is just the fractional % chordal arclength. % % Don't bother doing this last piece unless that argument is requested, % since it takes some additional work to do. if nargout >= 2 % build new piecewise polynomials for each segment that % represent (dx/dt)^2 + (dy/dt)^2 + ... % % Since each poly must be cubic at this point, the result will be % a 4th degree piecewise polynomial. kernelcoefs = zeros(nbr-1,5); for i = 1:p ppi = ppsegs{i}; kernelcoefs = kernelcoefs + [9*ppi(:,1).^2, ... 12*ppi(:,1).*ppi(:,2), ... 4*ppi(:,2).^2 + 6*ppi(:,1).*ppi(:,3), ... 4*ppi(:,2).*ppi(:,3), ppi(:,3).^2]; end % get the arc length for each segment. quadgk will suffice here % since we need to integrate the sqrt of each poly arclengths = zeros(nbr-1,1); for i = 1:(nbr - 1) lengthfun = @(t) sqrt(polyval(kernelcoefs(i,:),t)); arclengths(i) = quadgk(lengthfun,0,t0(i+1) - t0(i)); end % get the cumulative arclengths, then scale by the sum % this gives us fractional arc lengths. arclengths = cumsum(arclengths); totallength = arclengths(end); arclengths = [0;arclengths/totallength]; % where does each point fall in terms of fractional cumulative % chordal arclength? (i.e., t0?) [tbin,tbin] = histc(t,t0); tbin(tbin < 1) = 1; % being careful at the bottom end tbin(tbin >= nbr) = nbr - 1; % if the point fell at the very top... % the total length below the segment in question t_a = arclengths(tbin); % now get the piece in the tbin segment for i = 1:m lengthfun = @(t) sqrt(polyval(kernelcoefs(tbin(i),:),t)); t_a(i) = t_a(i) + quadgk(lengthfun,0,t(i) - t0(tbin(i)))/totallength; end end end % if strcmp(interpmethod,'linear'); % ========================================================== function d = ipdm(data1,varargin) % ipdm: Inter-Point Distance Matrix % usage: d = ipdm(data1) % usage: d = ipdm(data1,data2) % usage: d = ipdm(data1,prop,value) % usage: d = ipdm(data1,data2,prop,value) % % Arguments: (input) % data1 - array of data points, each point is one row. p dimensional % data will be represented by matrix with p columns. % If only data1 is provided, then the distance matrix % is computed between all pairs of rows of data1. % % If your data is one dimensional, it MUST form a column % vector. A row vector of length n will be interpreted as % an n-dimensional data set. % % data2 - second array, supplied only if distances are to be computed % between two sets of points. % % % Class support: data1 and data2 are assumed to be either % single or double precision. I have not tested this code to % verify its success on integer data of any class. % % % Additional parameters are expected to be property/value pairs. % Property/value pairs are pairs of arguments, the first of which % (properties) must always be a character string. These strings % may be shortened as long as the shortening is unambiguous. % Capitalization is ignored. Valid properties for ipdm are: % % 'Metric', 'Subset', 'Limit', 'Result' % % 'Metric' - numeric flag - defines the distance metric used % metric = 2 --> (DEFAULT) Euclidean distance = 2-norm % The standard distance metric. % % metric = 1 --> 1-norm = sum of absolute differences % Also sometimes known as the "city block % metric", since this is the sum of the % differences in each dimension. % % metric = inf --> infinity-norm = maximum difference % over all dimensions. The name refers % to the limit of the p-norm, as p % approaches infinity. % % metric = 0 --> minimum difference over all dimensions. % This is not really a useful norm in % practice. % % Note: while other distance metrics exist, IMHO, these % seemed to be the common ones. % % % 'Result' - A string variable that denotes the style of returned % result. Valid result types are 'Array', 'Structure'. % Capitalization is ignored, and the string may be % shortened if you wish. % % result = 'Array' --> (DEFAULT) A matrix of all % interpoint distances will be generated. % This array may be large. If this option % is specified along with a minimum or % maximum value, then those elements above % or below the limiting values will be % set as -inf or +inf, as appropriate. % % When any of 'LargestFew', 'SmallestFew', % or 'NearestNeighbor' are set, then the % resulting array will be a sparse matrix % if 'array' is specified as the result. % % result = 'Structure' --> A list of all computed distances, % defined as a structure. This structure % will have fields named 'rowindex', % 'columnindex', and 'distance'. % % This option will be useful when a subset % criterion for the distances has been % specified, since then the distance matrix % may be very sparsely populated. Distances % for pairs outside of the criterion will % not be returned. % % % 'Subset' - Character string, any of: % % 'All', 'Maximum', 'Minimum', 'LargestFew', 'SmallestFew', % 'NearestNeighbor', 'FarthestNeighbor', or empty % % Like properties, capitalization is ignored here, and % any unambiguous shortening of the word is acceptable. % % DEFAULT = 'All' % % Some interpoint distance matrices can be huge. Often % these matrices are too large to be fully retained in % memory, yet only the pair of points with the largest % or smallest distance may be needed. When only some % subset of the complete set of distances is of interest, % these options allow you to specify which distances will % be returned. % % If 'result' is defined to be an array, then a sparse % matrix will be returned for the 'LargestFew', 'SmallestFew', % 'NearestNeighbor', and 'FarthestNeighbor' subset classes. % 'Minimum' and 'Maximum' will yield full matrices by % default. If a structure is specified, then only those % elements which have been identified will be returned. % % Where a subset is specified, its limiting value is % specified by the 'Limit' property. Call that value k. % % % 'All' --> (DEFAULT) Return all interpoint distances % % 'Minimum' --> Only look for those distances above % the cutoff k. All other distances will % be returned as -inf. % % 'Maximum' --> Only look for those distances below % the cutoff k. All other distances will % be returned as +inf. % % 'SmallestFew' --> Only return the subset of the k % smallest distances. Where only one data % set is provided, only the upper triangle % of the inter-point distance matrix will % be generated since that matrix is symmetric. % % 'LargestFew' --> Only return the subset of the k % largest distances. Where only one data % set is provided, only the upper triangle % of the inter-point distance matrix will % be generated since that matrix is symmetric. % % 'NearestNeighbor' --> Only return the single nearest % neighbor in data2 to each point in data1. % No limiting value is required for this % option. If multiple points have the same % nearest distance, then return the first % such point found. With only one input set, % a point will not be its own nearest % neighbor. % % Note that exact replicates in a single set % will cause problems, since a sparse matrix % is returned by default. Since they will have % a zero distance, they will not show up in % the sparse matrix. A structure return will % show those points as having a zero distance % though. % % 'FarthestNeighbor' --> Only return the single farthest % neighbor to each point. No limiting value % is required for this option. If multiple % points have the same farthest distance, % then return the first such point found. % % % 'Limit' - scalar numeric value or []. Used only when some % Subset is specified. % % DEFAULT = [] % % % 'ChunkSize' - allows a user with lower RAM limits % to force the code to only grab smaller chunks of RAM % at a time (where possible). This parameter is specified % in bytes of RAM. The default is 32 megabytes, or 2^22 % elements in any piece of the distance matrix. Only some % options will break the problem into chunks, thus as long % as a full matrix is expected to be returned, there seems % no reason to break the problem up into pieces. % % DEFAULT = 2^25 % % % Arguments: (output) % d - array of interpoint distances, or a struct wth the % fields {'rowindex', 'columnindex', 'distance'}. % % d(i,j) represents the distance between point i % (from data1) and point j (from data2). % % If only one (n1 x p) array is supplied, then d will % be an array of size == [n1,n1]. % % If two arrays (of sizes n1 x p and n2 x p) then d % will be an array of size == [n1,n2]. % % % Efficiency considerations: % Where possible, this code will use bsxfun to compute its % distances. % % % Example: % Compute the interpoint distances between all pairs of points % in a list of 5 points, in 2 dimensions and using Euclidean % distance as the distance metric. % % A = randn(5,2); % d = ipdm(A,'metric',2) % d = % 0 2.3295 3.2263 2.0263 2.8244 % 2.3295 0 1.1485 0.31798 1.0086 % 3.2263 1.1485 0 1.4318 1.8479 % 2.0263 0.31798 1.4318 0 1.0716 % 2.8244 1.0086 1.8479 1.0716 0 % % (see the demo file for many other examples) % % See also: pdist % % Author: John D'Errico % e-mail: [email protected] % Release: 1.0 % Release date: 2/26/08 % Default property values params.Metric = 2; params.Result = 'array'; params.Subset = 'all'; params.Limit = []; params.ChunkSize = 2^25; % untangle the arguments if nargin<1 % if called with no arguments, then the user probably % needs help. Give it to them. help ipdm return end % were two sets of data provided? pvpairs = {}; if nargin==1 % only 1 set of data provided dataflag = 1; data2 = []; else if ischar(varargin{1}) dataflag = 1; data2 = []; pvpairs = varargin; else dataflag = 2; data2 = varargin{1}; if nargin>2 pvpairs = varargin(2:end); end end end % get data sizes for later [n1,dim] = size(data1); if dataflag == 2 n2 = size(data2,1); end % Test the class of the input variables if ~(isa(data1,'double') || isa(data1,'single')) || ... ((dataflag == 2) && ~(isa(data2,'double') || isa(data2,'single'))) error('data points must be either single or double precision variables.') end % do we need to process any property/value pairs? if nargin>2 params = parse_pv_pairs(params,pvpairs); % check for problems in the properties % was a legal Subset provided? if ~isempty(params.Subset) && ~ischar(params.Subset) error('If provided, ''Subset'' must be character') elseif isempty(params.Subset) params.Subset = 'all'; end valid = {'all','maximum','minimum','largestfew','smallestfew', ... 'nearestneighbor','farthestneighbor'}; ind = find(strncmpi(params.Subset,valid,length(params.Subset))); if (length(ind)==1) params.Subset = valid{ind}; else error(['Invalid Subset: ',params.Subset]) end % was a limit provided? if ~ismember(params.Subset,{'all','nearestneighbor','farthestneighbor'}) && ... isempty(params.Limit) error('No limit provided, but a Subset that requires a limit value was specified') end % check the limit values for validity if length(params.Limit)>1 error('Limit must be scalar or empty') end switch params.Subset case {'largestfew', 'smallestfew'} % must be at least 1, and an integer if (params.Limit<1) || (round(params.Limit)~=params.Limit) error('Limit must be a positive integer for LargestFew or NearestFew') end end % was a legal Result provided? if isempty(params.Result) params.result = 'Array'; elseif ~ischar(params.Result) error('If provided, ''Result'' must be character or empty') end valid = {'array','structure'}; ind = find(strncmpi(params.Result,valid,length(params.Result))); if (length(ind)==1) params.Result = valid{ind}; else error(['Invalid Result: ',params.Subset]) end % check for the metric if isempty(params.Metric) params.Metric = 2; elseif (length(params.Metric)~=1) || ~ismember(params.Metric,[0 1 2 inf]) error('If supplied, ''Metric'' must be a scalar, and one of [0 1 2 inf]') end end % if nargin>2 % If Metric was given as 2, but the dimension is only 1, then it will % be slightly faster (and equivalent) to use the 1-norm Metric. if (dim == 1) && (params.Metric == 2) params.Metric = 1; end % Can we use bsxfun to compute the interpoint distances? % Older Matlab releases will not have bsxfun, but if it is % around, it will ne both faster and less of a memory hog. params.usebsxfun = (5==exist('bsxfun','builtin')); % check for dimension mismatch if 2 sets if (dataflag==2) && (size(data2,2)~=dim) error('If 2 point sets provided, then both must have the same number of columns') end % Total number of distances to compute, in case I must do it in batches if dataflag==1 n2 = n1; end ntotal = n1*n2; % FINALLY!!! Compute inter-point distances switch params.Subset case 'all' % The complete set of interpoint distances. There is no need % to break this into chunks, since we must return all distances. % If that is too much to compute in memory, then it will fail % anyway when we try to store the result. bsxfun will at least % do the computation efficiently. % One set or two? if dataflag == 1 d = distcomp(data1,data1,params); else d = distcomp(data1,data2,params); end % Must we return it as a struct? if params.Result(1) == 's' [rind,cind] = ndgrid(1:size(d,1),1:size(d,2)); ds.rowindex = rind(:); ds.columnindex = cind(:); ds.distance = d(:); d = ds; end case {'minimum' 'maximum'} % There is no reason to break this into pieces if the result % sill be filled in the end with +/- inf. Only break it up % if the final result is a struct. if ((ntotal*8)<=params.ChunkSize) || (params.Result(1) == 'a') % its small enough to do it all at once % One set or two? if dataflag == 1 d = distcomp(data1,data1,params); else d = distcomp(data1,data2,params); end % Must we return it as a struct? if params.Result(1) == 'a' % its an array, fill the unwanted distances with +/- inf if params.Subset(2) == 'i' % minimum d(d<=params.Limit) = -inf; else % maximum d(d>=params.Limit) = +inf; end else % a struct will be returned if params.Subset(2) == 'i' % minimum [dist.rowindex,dist.columnindex] = find(d>=params.Limit); else % maximum [dist.rowindex,dist.columnindex] = find(d<=params.Limit); end dist.distance = d(dist.rowindex + n1*(dist.columnindex-1)); d = dist; end else % we need to break this into chunks. This branch % will always return a struct. % this is the number of rows of data1 that we will % process at a time. bs = floor(params.ChunkSize/(8*n2)); bs = min(n1,max(1,bs)); % Accumulate the result into a cell array. Do it this % way because we don't know in advance how many elements % that we will find satisfying the minimum or maximum % limit specified. accum = cell(0,1); % now loop over the chunks batch = 1:bs; while ~isempty(batch) % One set or two? if dataflag == 1 dist = distcomp(data1(batch,:),data1,params); else dist = distcomp(data1(batch,:),data2,params); end % big or small as requested if ('i'==params.Subset(2)) % minimum value specified [I,J,V] = find(dist>=params.Limit); else % maximum limit [I,J] = find(dist<=params.Limit); I = I(:); J = J(:); V = dist(I + (J-1)*length(batch)); I = I + (batch(1)-1); end % and stuff them into the cell structure if ~isempty(V) accum{end+1,1} = [I,J,V(:)]; %#ok end % increment the batch batch = batch + bs; if batch(end)>n1 batch(batch>n1) = []; end end % convert the cells into one flat array accum = cell2mat(accum); if isempty(accum) d.rowindex = []; d.columnindex = []; d.distance = []; else % we found something % sort on the second column, to put them in a reasonable order accum = sortrows(accum,[2 1]); d.rowindex = accum(:,1); d.columnindex = accum(:,2); d.distance = accum(:,3); end end case {'smallestfew' 'largestfew'} % find the k smallest/largest distances. k is % given by params.Limit % if only 1 set, params.Limit must be less than n*(n-1)/2 if dataflag == 1 params.Limit = min(params.Limit,n1*(n1-1)/2); end % is this a large problem? if ((ntotal*8) <= params.ChunkSize) % small potatoes % One set or two? if dataflag == 1 dist = distcomp(data1,data1,params); % if only one data set, set the diagonal and % below that to +/- inf so we don't find it. temp = find(tril(ones(n1,n1),0)); if params.Subset(1) == 's' dist(temp) = inf; else dist(temp) = -inf; end else dist = distcomp(data1,data2,params); end % sort the distances to find those we need if ('s'==params.Subset(1)) % smallestfew [val,tags] = sort(dist(:),'ascend'); else % largestfew [val,tags] = sort(dist(:),'descend'); end val = val(1:params.Limit); tags = tags(1:params.Limit); % recover the row and column index from the linear % index returned by sort in tags. [d.rowindex,d.columnindex] = ind2sub([n1,size(dist,2)],tags); % create the matrix as a sparse one or a struct? if params.Result(1)=='a' % its an array, so make the array sparse. d = sparse(d.rowindex,d.columnindex,val,n1,size(dist,2)); else % a structure d.distance = val; end else % chunks % this is the number of rows of data1 that we will % process at a time. bs = floor(params.ChunkSize/(8*n2)); bs = min(n1,max(1,bs)); % We need to find the extreme cases. There are two possible % algorithms, depending on how many total elements we will % search for. % 1. Only a very few total elements. % 2. A relatively large number of total elements, forming % a significant fraction of the total set. % % Case #1 would suggest to retain params.Limit numberr of % elements from each batch, then at the end, sort them all % to find the best few. Case #2 will result in too many % elements to retain, so we must distinguish between these % alternatives. if (8*params.Limit*n1/bs) <= params.ChunkSize % params.Limit is small enough to fall into case #1. % Accumulate the result into a cell array. Do it this % way because we don't know in advance how many elements % that we will find satisfying the minimum or maximum % limit specified. accum = cell(0,1); % now loop over the chunks batch = (1:bs)'; while ~isempty(batch) % One set or two? if dataflag == 1 dist = distcomp(data1(batch,:),data1,params); k = find(tril(ones(length(batch),n2),batch(1)-1)); if ('s'==params.Subset(1)) dist(k) = inf; else dist(k) = -inf; end else dist = distcomp(data1(batch,:),data2,params); end % big or small as requested, keeping only the best % params.Limit number of elements if ('s'==params.Subset(1)) % minimum value specified [tags,tags] = sort(dist(:),1,'ascend'); %#ok tags = tags(1:bs); [I,J] = ndgrid(batch,1:n2); ijv = [I(tags),J(tags),dist(tags)]; else % maximum limit [tags,tags] = sort(dist(:),1,'descend'); %#ok tags = tags(1:bs); [I,J] = ndgrid(batch,1:n2); ijv = [I(tags),J(tags),dist(tags)]; end % and stuff them into the cell structure accum{end+1,1} = ijv; %#ok % increment the batch batch = batch + bs; if batch(end)>n1 batch(batch>n1) = []; end end % convert the cells into one flat array accum = cell2mat(accum); % keep only the params.Limit best of those singled out accum = sortrows(accum,3); if ('s'==params.Subset(1)) % minimum value specified accum = accum(1:params.Limit,:); else % minimum value specified accum = accum(end + 1 - (1:params.Limit),:); end d.rowindex = accum(:,1); d.columnindex = accum(:,2); d.distance = accum(:,3); % create the matrix as a sparse one or a struct? if params.Result(1)=='a' % its an array, so make the array sparse. d = sparse(d.rowindex,d.columnindex,d.distance,n1,size(dist,2)); end else % params.Limit forces us into the domain of case #2. % Here we cannot retain params.Limit elements from each chunk. % so we will grab each chunk and append it to the best elements % found so far, then filter out the best after each chunk is % done. This may be slower than we want, but its the only way. ijv = zeros(0,3); % loop over the chunks batch = (1:bs)'; while ~isempty(batch) % One set or two? if dataflag == 1 dist = distcomp(data1(batch,:),data1,params); k = find(tril(ones(length(batch),n2),batch(1)-1)); if ('s'==params.Subset(1)) dist(k) = inf; else dist(k) = -inf; end else dist = distcomp(data1(batch,:),data2,params); end [I,J] = ndgrid(batch,1:n2); ijv = [ijv;[I(:),J(:),dist(:)]]; %#ok % big or small as requested, keeping only the best % params.Limit number of elements if size(ijv,1) > params.Limit if ('s'==params.Subset(1)) % minimum value specified [tags,tags] = sort(ijv(:,3),1,'ascend'); %#ok else [tags,tags] = sort(ijv(:,3),1,'ascend'); %#ok end ijv = ijv(tags(1:params.Limit),:); end % increment the batch batch = batch + bs; if batch(end)>n1 batch(batch>n1) = []; end end % They are fully trimmed down. stuff a structure d.rowindex = ijv(:,1); d.columnindex = ijv(:,2); d.distance = ijv(:,3); % create the matrix as a sparse one or a struct? if params.Result(1)=='a' % its an array, so make the array sparse. d = sparse(d.rowindex,d.columnindex,d.distance,n1,size(dist,2)); end end end case {'nearestneighbor' 'farthestneighbor'} % find the closest/farthest neighbor for every point % is this a large problem? Or a 1-d problem? if dim == 1 % its a 1-d nearest/farthest neighbor problem. we can % special case these easily enough, and all the distance % metric options are the same in 1-d. % first split it into the farthest versus nearest cases. if params.Subset(1) == 'f' % farthest away % One set or two? if dataflag == 1 [d2min,minind] = min(data1); [d2max,maxind] = max(data1); else [d2min,minind] = min(data2); [d2max,maxind] = max(data2); end d.rowindex = (1:n1)'; d.columnindex = repmat(maxind,n1,1); d.distance = repmat(d2max,n1,1); % which endpoint was further away? k = abs((data1 - d2min)) >= abs((data1 - d2max)); if any(k) d.columnindex(k) = minind; d.distance(k) = d2min; end else % nearest. this is mainly a sort and some fussing around. d.rowindex = (1:n1)'; d.columnindex = ones(n1,1); d.distance = zeros(n1,1); % One set or two? if dataflag == 1 % if only one data point, then we are done if n1 == 2 % if exactly two data points, its trivial d.columnindex = [2 1]; d.distance = repmat(abs(diff(data1)),2,1); elseif n1>2 % at least three points. do a sort. [sorted_data,tags] = sort(data1); % handle the first and last points separately d.columnindex(tags(1)) = tags(2); d.distance(tags(1)) = sorted_data(2) - sorted_data(1); d.columnindex(tags(end)) = tags(end-1); d.distance(tags(end)) = sorted_data(end) - sorted_data(end-1); ind = (2:(n1-1))'; d1 = sorted_data(ind) - sorted_data(ind-1); d2 = sorted_data(ind+1) - sorted_data(ind); k = d1 < d2; d.distance(tags(ind(k))) = d1(k); d.columnindex(tags(ind(k))) = tags(ind(k)-1); k = ~k; d.distance(tags(ind(k))) = d2(k); d.columnindex(tags(ind(k))) = tags(ind(k)+1); end % if n1 == 2 else % Two sets of data. still really a sort and some fuss. if n2 == 1 % there is only one point in data2 d.distance = abs(data1 - data2); % d.columnindex is already set correctly else % At least two points in data2 % We need to sort all the data points together, but also % know which points from each set went where. ind12 and % bool12 will help keep track. ind12 = [1:n1,1:n2]'; bool12 = [zeros(n1,1);ones(n2,1)]; [sorted_data,tags] = sort([data1;data2]); ind12 = ind12(tags); bool12 = bool12(tags); % where did each point end up after the sort? loc1 = find(~bool12); loc2 = find(bool12); % for each point in data1, what is the (sorted) data2 % element which appears most nearly to the left of it? cs = cumsum(bool12); leftelement = cs(loc1); % any points which fell below the minimum element in data2 % will have a zero for the index of the element on their % left. fix this. leftelement = max(1,leftelement); % likewise, any point greater than the max in data2 will % have an n2 in left element. this too will be a problem % later, so fix it. leftelement = min(n2-1,leftelement); % distance to the left hand element dleft = abs(sorted_data(loc1) - sorted_data(loc2(leftelement))); dright = abs(sorted_data(loc1) - sorted_data(loc2(leftelement+1))); % find the points which are closer to the left element in data2 k = (dleft < dright); d.distance(ind12(loc1(k))) = dleft(k); d.columnindex(ind12(loc1(k))) = ind12(loc2(leftelement(k))); k = ~k; d.distance(ind12(loc1(k))) = dright(k); d.columnindex(ind12(loc1(k))) = ind12(loc2(leftelement(k)+1)); end % if n2 == 1 end % if dataflag == 1 end % if params.Subset(1) == 'f' % create the matrix as a sparse one or a struct? if params.Result(1)=='a' % its an array, so make the array sparse. d = sparse(d.rowindex,d.columnindex,d.distance,n1,n2); end elseif (ntotal>1000) && (((params.Metric == 0) && (params.Subset(1) == 'n')) || ... ((params.Metric == inf) && (params.Subset(1) == 'f'))) % nearest/farthest neighbour in n>1 dimensions, but for an % infinity norm metric. Reduce this to a sequence of % 1-d problems, each of which will be faster in general. % do this only if the problem is moderately large, since % we must overcome the extra overhead of the recursive % calls to ipdm. % do the first dimension if dataflag == 1 d = ipdm(data1(:,1),data1(:,1),'subset',params.Subset,'metric',params.Metric,'result','struct'); else d = ipdm(data1(:,1),data2(:,1),'subset',params.Subset,'metric',params.Metric,'result','struct'); end % its slightly different for nearest versus farthest here % now, loop over dimensions for i = 2:dim if dataflag == 1 di = ipdm(data1(:,i),data1(:,i),'subset',params.Subset,'metric',params.Metric,'result','struct'); else di = ipdm(data1(:,i),data2(:,i),'subset',params.Subset,'metric',params.Metric,'result','struct'); end % did any of the distances change? if params.Metric == 0 % the 0 norm, with nearest neighbour, so take the % smallest distance in any dimension. k = d.distance > di.distance; else % inf norm. so take the largest distance across dimensions k = d.distance < di.distance; end if any(k) d.distance(k) = di.distance(k); d.columnindex(k) = di.columnindex(k); end end % create the matrix as a sparse one or a struct? if params.Result(1)=='a' % its an array, so make the array sparse. d = sparse(d.rowindex,d.columnindex,d.distance,n1,n2); end elseif ((ntotal*8) <= params.ChunkSize) % None of the other special cases apply, so do it using brute % force for the small potatoes problem. % One set or two? if dataflag == 1 dist = distcomp(data1,data1,params); else dist = distcomp(data1,data2,params); end % if only one data set and if a nearest neighbor % problem, set the diagonal to +inf so we don't find it. if (dataflag==1) && (n1>1) && ('n'==params.Subset(1)) diagind = (1:n1) + (0:n1:(n1^2-1)); dist(diagind) = +inf; end if ('n'==params.Subset(1)) % nearest [val,j] = min(dist,[],2); else % farthest [val,j] = max(dist,[],2); end % create the matrix as a sparse one or a struct? if params.Result(1)=='a' % its an array, so make the array sparse. d = sparse((1:n1)',j,val,n1,size(dist,2)); else % a structure d.rowindex = (1:n1)'; d.columnindex = j; d.distance = val; end else % break it into chunks bs = floor(params.ChunkSize/(8*n2)); bs = min(n1,max(1,bs)); % pre-allocate the result d.rowindex = (1:n1)'; d.columnindex = zeros(n1,1); d.distance = zeros(n1,1); % now loop over the chunks batch = 1:bs; while ~isempty(batch) % One set or two? if dataflag == 1 dist = distcomp(data1(batch,:),data1,params); else dist = distcomp(data1(batch,:),data2,params); end % if only one data set and if a nearest neighbor % problem, set the diagonal to +inf so we don't find it. if (dataflag==1) && (n1>1) && ('n'==params.Subset(1)) diagind = 1:length(batch); diagind = diagind + (diagind-2+batch(1))*length(batch); dist(diagind) = +inf; end % big or small as requested if ('n'==params.Subset(1)) % nearest [val,j] = min(dist,[],2); else % farthest [val,j] = max(dist,[],2); end % and stuff them into the result structure d.columnindex(batch) = j; d.distance(batch) = val; % increment the batch batch = batch + bs; if batch(end)>n1 batch(batch>n1) = []; end end % did we need to return a struct or an array? if params.Result(1) == 'a' % an array. make it a sparse one d = sparse(d.rowindex,d.columnindex,d.distance,n1,n2); end end % if dim == 1 end % switch params.Subset % End of mainline % ====================================================== % begin subfunctions % ====================================================== function d = distcomp(set1,set2,params) % Subfunction to compute all distances between two sets of points dim = size(set1,2); % can we take advantage of bsxfun? % Note: in theory, there is no need to loop over the dimensions. We % could Just let bsxfun do ALL the work, then wrap a sum around the % outside. In practice, this tends to create large intermediate % arrays, especially in higher numbers of dimensions. Its also when % we might gain here by use of a vectorized code. This will only be % a serious gain when the number of points is relatively small and % the dimension is large. if params.usebsxfun % its a recent enough version of matlab that we can % use bsxfun at all. n1 = size(set1,1); n2 = size(set2,1); if (dim>1) && ((n1*n2*dim)<=params.ChunkSize) % its a small enough problem that we might gain by full % use of bsxfun switch params.Metric case 2 d = sum(bsxfun(@minus,reshape(set1,[n1,1,dim]),reshape(set2,[1,n2,dim])).^2,3); case 1 d = sum(abs(bsxfun(@minus,reshape(set1,[n1,1,dim]),reshape(set2,[1,n2,dim]))),3); case inf d = max(abs(bsxfun(@minus,reshape(set1,[n1,1,dim]),reshape(set2,[1,n2,dim]))),[],3); case 0 d = min(abs(bsxfun(@minus,reshape(set1,[n1,1,dim]),reshape(set2,[1,n2,dim]))),[],3); end else % too big, so that the ChunkSize will have been exceeded, or just 1-d if params.Metric == 2 d = bsxfun(@minus,set1(:,1),set2(:,1)').^2; else d = abs(bsxfun(@minus,set1(:,1),set2(:,1)')); end for i=2:dim switch params.Metric case 2 d = d + bsxfun(@minus,set1(:,i),set2(:,i)').^2; case 1 d = d + abs(bsxfun(@minus,set1(:,i),set2(:,i)')); case inf d = max(d,abs(bsxfun(@minus,set1(:,i),set2(:,i)'))); case 0 d = min(d,abs(bsxfun(@minus,set1(:,i),set2(:,i)'))); end end end else % Cannot use bsxfun. Sigh. Do things the hard (and slower) way. n1 = size(set1,1); n2 = size(set2,1); if params.Metric == 2 % Note: While some people might use a different Euclidean % norm computation based on expanding the square of the % difference of two numbers, that computation is inherantly % inaccurate when implemented in floating point arithmetic. % While it might be faster, I won't use it here. Sorry. d = (repmat(set1(:,1),1,n2) - repmat(set2(:,1)',n1,1)).^2; else d = abs(repmat(set1(:,1),1,n2) - repmat(set2(:,1)',n1,1)); end for i=2:dim switch params.Metric case 2 d = d + (repmat(set1(:,i),1,n2) - repmat(set2(:,i)',n1,1)).^2; case 1 d = d + abs(repmat(set1(:,i),1,n2) - repmat(set2(:,i)',n1,1)); case inf d = max(d,abs(repmat(set1(:,i),1,n2) - repmat(set2(:,i)',n1,1))); case 0 d = min(d,abs(repmat(set1(:,i),1,n2) - repmat(set2(:,i)',n1,1))); end end end % if 2 norm, then we must sqrt at the end if params.Metric==2 d = sqrt(d); end % ============================================================== % end main ipdm % begin included function - parse_pv_pairs % ============================================================== function params=parse_pv_pairs(params,pv_pairs) % parse_pv_pairs: parses sets of property value pairs, allows defaults % usage: params=parse_pv_pairs(default_params,pv_pairs) % % arguments: (input) % default_params - structure, with one field for every potential % property/value pair. Each field will contain the default % value for that property. If no default is supplied for a % given property, then that field must be empty. % % pv_array - cell array of property/value pairs. % Case is ignored when comparing properties to the list % of field names. Also, any unambiguous shortening of a % field/property name is allowed. % % arguments: (output) % params - parameter struct that reflects any updated property/value % pairs in the pv_array. % % Example usage: % First, set default values for the parameters. Assume we % have four parameters that we wish to use optionally in % the function examplefun. % % - 'viscosity', which will have a default value of 1 % - 'volume', which will default to 1 % - 'pie' - which will have default value 3.141592653589793 % - 'description' - a text field, left empty by default % % The first argument to examplefun is one which will always be % supplied. % % function examplefun(dummyarg1,varargin) % params.Viscosity = 1; % params.Volume = 1; % params.Pie = 3.141592653589793 % % params.Description = ''; % params=parse_pv_pairs(params,varargin); % params % % Use examplefun, overriding the defaults for 'pie', 'viscosity' % and 'description'. The 'volume' parameter is left at its default. % % examplefun(rand(10),'vis',10,'pie',3,'Description','Hello world') % % params = % Viscosity: 10 % Volume: 1 % Pie: 3 % Description: 'Hello world' % % Note that capitalization was ignored, and the property 'viscosity' % was truncated as supplied. Also note that the order the pairs were % supplied was arbitrary. npv = length(pv_pairs); n = npv/2; if n~=floor(n) error 'Property/value pairs must come in PAIRS.' end if n<=0 % just return the defaults return end if ~isstruct(params) error 'No structure for defaults was supplied' end % there was at least one pv pair. process any supplied propnames = fieldnames(params); lpropnames = lower(propnames); for i=1:n p_i = lower(pv_pairs{2*i-1}); v_i = pv_pairs{2*i}; ind = strmatch(p_i,lpropnames,'exact'); if isempty(ind) ind = find(strncmp(p_i,lpropnames,length(p_i))); if isempty(ind) error(['No matching property found for: ',pv_pairs{2*i-1}]) elseif length(ind)>1 error(['Ambiguous property name: ',pv_pairs{2*i-1}]) end end p_i = propnames{ind}; % override the corresponding default in params. % Use setfield for comptability issues with older releases. params = setfield(params,p_i,v_i); %#ok end
github
mehta-lab/Instantaneous-PolScope-master
myginput.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/myginput.m
6,466
utf_8
cd9eb5958c608e8178bfbfdc400c1b9d
function [out1,out2,out3] = myginput(arg1,strpointertype) %MYGINPUT Graphical input from mouse with custum cursor pointer. % [X,Y] = MYGINPUT(N) gets N points from the current axes and returns % the X- and Y-coordinates in length N vectors X and Y. % % [X,Y] = MYGINPUT(N, POINTER) also specifies the cursor pointer, e.g. % 'crosshair', 'arrow', 'circle' etc. See "Specifying the Figure Pointer" % in Matlab's documentation to see the list of available pointers. % % MYGINPUT is strictly equivalent to Matlab's original GINPUT, except % that a second argument specifies the cursor pointer instead of the % default 'fullcrosshair' pointer. % % Example: % plot(1:2,1:2,'s'); % hold on % [x,y] = myginput(1,'crosshair'); % plot(x,y,'o'); % hold off % % MYGINPUT is copied from Matlab's GINPUT rev. 5.32.4.4. % % See also GINPUT. % F. Moisy, moisy_at_fast.u-psud.fr % Revision: 1.02, Date: 2006/10/24 % History: % 2005/10/31: v1.00, first version, from GINPUT rev. 5.32.4.4. % 2005/11/25: v1.01, line 'uisuspend' modified (for compatibility with % ML7.00) % 2006/10/24: v1.02, help text improved out1 = []; out2 = []; out3 = []; y = []; if nargin<1 % modified MYGINPUT strpointertype='fullcrosshair'; % default GINPUT pointer end c = computer; if ~strcmp(c(1:2),'PC') tp = get(0,'TerminalProtocol'); else tp = 'micro'; end if ~strcmp(tp,'none') & ~strcmp(tp,'x') & ~strcmp(tp,'micro'), if nargout == 1, if nargin == 1, out1 = trmginput(arg1); else out1 = trmginput; end elseif nargout == 2 | nargout == 0, if nargin == 1, [out1,out2] = trmginput(arg1); else [out1,out2] = trmginput; end if nargout == 0 out1 = [ out1 out2 ]; end elseif nargout == 3, if nargin == 1, [out1,out2,out3] = trmginput(arg1); else [out1,out2,out3] = trmginput; end end else fig = gcf; figure(gcf); if nargin == 0 how_many = -1; b = []; else how_many = arg1; b = []; if isstr(how_many) ... | size(how_many,1) ~= 1 | size(how_many,2) ~= 1 ... | ~(fix(how_many) == how_many) ... | how_many < 0 error('Requires a positive integer.') end if how_many == 0 ptr_fig = 0; while(ptr_fig ~= fig) ptr_fig = get(0,'PointerWindow'); end scrn_pt = get(0,'PointerLocation'); loc = get(fig,'Position'); pt = [scrn_pt(1) - loc(1), scrn_pt(2) - loc(2)]; out1 = pt(1); y = pt(2); elseif how_many < 0 error('Argument must be a positive integer.') end end % Suspend axes functions %haxes = findobj(fig,'type','axes'); state = uisuspend(fig); %haxes = findobj(fig,'type','axes'); %state = uisuspend(haxes); pointer = get(gcf,'pointer'); set(gcf,'pointer',strpointertype); % modified MYGINPUT fig_units = get(fig,'units'); char = 0; % We need to pump the event queue on unix % before calling WAITFORBUTTONPRESS drawnow while how_many ~= 0 % Use no-side effect WAITFORBUTTONPRESS waserr = 0; try keydown = wfbp; catch waserr = 1; end if(waserr == 1) if(ishandle(fig)) set(fig,'units',fig_units); uirestore(state); error('Interrupted'); else error('Interrupted by figure deletion'); end end ptr_fig = get(0,'CurrentFigure'); if(ptr_fig == fig) if keydown char = get(fig, 'CurrentCharacter'); button = abs(get(fig, 'CurrentCharacter')); scrn_pt = get(0, 'PointerLocation'); set(fig,'units','pixels') loc = get(fig, 'Position'); pt = [scrn_pt(1) - loc(1), scrn_pt(2) - loc(2)]; set(fig,'CurrentPoint',pt); else button = get(fig, 'SelectionType'); if strcmp(button,'open') button = 1; elseif strcmp(button,'normal') button = 1; elseif strcmp(button,'extend') button = 2; elseif strcmp(button,'alt') button = 3; else error('Invalid mouse selection.') end end pt = get(gca, 'CurrentPoint'); how_many = how_many - 1; if(char == 13) % & how_many ~= 0) % if the return key was pressed, char will == 13, % and that's our signal to break out of here whether % or not we have collected all the requested data % points. % If this was an early breakout, don't include % the <Return> key info in the return arrays. % We will no longer count it if it's the last input. break; end out1 = [out1;pt(1,1)]; y = [y;pt(1,2)]; b = [b;button]; end end uirestore(state); set(fig,'units',fig_units); if nargout > 1 out2 = y; if nargout > 2 out3 = b; end else out1 = [out1 y]; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function key = wfbp %WFBP Replacement for WAITFORBUTTONPRESS that has no side effects. fig = gcf; current_char = []; % Now wait for that buttonpress, and check for error conditions waserr = 0; try h=findall(fig,'type','uimenu','accel','C'); % Disabling ^C for edit menu so the only ^C is for set(h,'accel',''); % interrupting the function. keydown = waitforbuttonpress; current_char = double(get(fig,'CurrentCharacter')); % Capturing the character. if~isempty(current_char) & (keydown == 1) % If the character was generated by the if(current_char == 3) % current keypress AND is ^C, set 'waserr'to 1 waserr = 1; % so that it errors out. end end set(h,'accel','C'); % Set back the accelerator for edit menu. catch waserr = 1; end drawnow; if(waserr == 1) set(h,'accel','C'); % Set back the accelerator if it errored out. error('Interrupted'); end if nargout>0, key = keydown; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
mehta-lab/Instantaneous-PolScope-master
pdftops.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/export_fig/pdftops.m
3,574
utf_8
92ff676904575e16046dfff010b4e145
function varargout = pdftops(cmd) %PDFTOPS Calls a local pdftops executable with the input command % % Example: % [status result] = pdftops(cmd) % % Attempts to locate a pdftops executable, finally asking the user to % specify the directory pdftops was installed into. The resulting path is % stored for future reference. % % Once found, the executable is called with the input command string. % % This function requires that you have pdftops (from the Xpdf package) % installed on your system. You can download this from: % http://www.foolabs.com/xpdf % % IN: % cmd - Command string to be passed into pdftops. % % OUT: % status - 0 iff command ran without problem. % result - Output from pdftops. % Copyright: Oliver Woodford, 2009-2010 % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on % Mac OS. % Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path % under linux. % 23/01/2014 - Add full path to pdftops.txt in warning. % 27/05/2015 - Fixed alert in case of missing pdftops; fixed code indentation % Call pdftops [varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd)); end function path_ = xpdf_path % Return a valid path % Start with the currently set path path_ = user_string('pdftops'); % Check the path works if check_xpdf_path(path_) return end % Check whether the binary is on the path if ispc bin = 'pdftops.exe'; else bin = 'pdftops'; end if check_store_xpdf_path(bin) path_ = bin; return end % Search the obvious places if ispc path_ = 'C:\Program Files\xpdf\pdftops.exe'; else path_ = '/usr/local/bin/pdftops'; end if check_store_xpdf_path(path_) return end % Ask the user to enter the path while 1 errMsg = 'Pdftops not found. Please locate the program, or install xpdf-tools from '; url = 'http://foolabs.com/xpdf'; fprintf(2, '%s\n', [errMsg '<a href="matlab:web(''-browser'',''' url ''');">' url '</a>']); errMsg = [errMsg url]; %#ok<AGROW> if strncmp(computer,'MAC',3) % Is a Mac % Give separate warning as the MacOS uigetdir dialogue box doesn't have a title uiwait(warndlg(errMsg)) end base = uigetdir('/', errMsg); if isequal(base, 0) % User hit cancel or closed window break; end base = [base filesep]; %#ok<AGROW> bin_dir = {'', ['bin' filesep], ['lib' filesep]}; for a = 1:numel(bin_dir) path_ = [base bin_dir{a} bin]; if exist(path_, 'file') == 2 break; end end if check_store_xpdf_path(path_) return end end error('pdftops executable not found.'); end function good = check_store_xpdf_path(path_) % Check the path is valid good = check_xpdf_path(path_); if ~good return end % Update the current default path to the path found if ~user_string('pdftops', path_) warning('Path to pdftops executable could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'pdftops.txt')); return end end function good = check_xpdf_path(path_) % Check the path is valid [good, message] = system(sprintf('"%s" -h', path_)); %#ok<ASGLU> % system returns good = 1 even when the command runs % Look for something distinct in the help text good = ~isempty(strfind(message, 'PostScript')); end
github
mehta-lab/Instantaneous-PolScope-master
crop_borders.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/export_fig/crop_borders.m
3,666
utf_8
ebb9c61581b6f0d4a2db2fd1d9e30685
function [A, vA, vB, bb_rel] = crop_borders(A, bcol, padding) %CROP_BORDERS Crop the borders of an image or stack of images % % [B, vA, vB, bb_rel] = crop_borders(A, bcol, [padding]) % %IN: % A - HxWxCxN stack of images. % bcol - Cx1 background colour vector. % padding - scalar indicating how much padding to have in relation to % the cropped-image-size (0<=padding<=1). Default: 0 % %OUT: % B - JxKxCxN cropped stack of images. % vA - coordinates in A that contain the cropped image % vB - coordinates in B where the cropped version of A is placed % bb_rel - relative bounding box (used for eps-cropping) % 06/03/15: Improved image cropping thanks to Oscar Hartogensis % 08/06/15: Fixed issue #76: case of transparent figure bgcolor if nargin < 3 padding = 0; end [h, w, c, n] = size(A); if isempty(bcol) % case of transparent bgcolor bcol = A(ceil(end/2),1,:,1); end if isscalar(bcol) bcol = bcol(ones(c, 1)); end % Crop margin from left bail = false; for l = 1:w for a = 1:c if ~all(col(A(:,l,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end % Crop margin from right bcol = A(ceil(end/2),w,:,1); bail = false; for r = w:-1:l for a = 1:c if ~all(col(A(:,r,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end % Crop margin from top bcol = A(1,ceil(end/2),:,1); bail = false; for t = 1:h for a = 1:c if ~all(col(A(t,:,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end % Crop margin from bottom bcol = A(h,ceil(end/2),:,1); bail = false; for b = h:-1:t for a = 1:c if ~all(col(A(b,:,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end % Crop the background, leaving one boundary pixel to avoid bleeding on resize %v = [max(t-padding, 1) min(b+padding, h) max(l-padding, 1) min(r+padding, w)]; %A = A(v(1):v(2),v(3):v(4),:,:); if padding == 0 % no padding padding = 1; elseif abs(padding) < 1 % pad value is a relative fraction of image size padding = sign(padding)*round(mean([b-t r-l])*abs(padding)); % ADJUST PADDING else % pad value is in units of 1/72" points padding = round(padding); % fix cases of non-integer pad value end if padding > 0 % extra padding % Create an empty image, containing the background color, that has the % cropped image size plus the padded border B = repmat(bcol,(b-t)+1+padding*2,(r-l)+1+padding*2); % vA - coordinates in A that contain the cropped image vA = [t b l r]; % vB - coordinates in B where the cropped version of A will be placed vB = [padding+1, (b-t)+1+padding, padding+1, (r-l)+1+padding]; % Place the original image in the empty image B(vB(1):vB(2), vB(3):vB(4), :) = A(vA(1):vA(2), vA(3):vA(4), :); A = B; else % extra cropping vA = [t-padding b+padding l-padding r+padding]; A = A(vA(1):vA(2), vA(3):vA(4), :); vB = [NaN NaN NaN NaN]; end % For EPS cropping, determine the relative BoundingBox - bb_rel bb_rel = [l-1 h-b-1 r+1 h-t+1]./[w h w h]; end function A = col(A) A = A(:); end
github
mehta-lab/Instantaneous-PolScope-master
isolate_axes.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/export_fig/isolate_axes.m
4,721
utf_8
253cd7b7d8fc7cb00d0cc55926f32de5
function fh = isolate_axes(ah, vis) %ISOLATE_AXES Isolate the specified axes in a figure on their own % % Examples: % fh = isolate_axes(ah) % fh = isolate_axes(ah, vis) % % This function will create a new figure containing the axes/uipanels % specified, and also their associated legends and colorbars. The objects % specified must all be in the same figure, but they will generally only be % a subset of the objects in the figure. % % IN: % ah - An array of axes and uipanel handles, which must come from the % same figure. % vis - A boolean indicating whether the new figure should be visible. % Default: false. % % OUT: % fh - The handle of the created figure. % Copyright (C) Oliver Woodford 2011-2013 % Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs % 16/03/12: Moved copyfig to its own function. Thanks to Bob Fratantonio % for pointing out that the function is also used in export_fig.m % 12/12/12: Add support for isolating uipanels. Thanks to michael for suggesting it % 08/10/13: Bug fix to allchildren suggested by Will Grant (many thanks!) % 05/12/13: Bug fix to axes having different units. Thanks to Remington Reid for reporting % 21/04/15: Bug fix for exporting uipanels with legend/colorbar on HG1 (reported by Alvaro % on FEX page as a comment on 24-Apr-2014); standardized indentation & help section % 22/04/15: Bug fix: legends and colorbars were not exported when exporting axes handle in HG2 % Make sure we have an array of handles if ~all(ishandle(ah)) error('ah must be an array of handles'); end % Check that the handles are all for axes or uipanels, and are all in the same figure fh = ancestor(ah(1), 'figure'); nAx = numel(ah); for a = 1:nAx if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'}) error('All handles must be axes or uipanel handles.'); end if ~isequal(ancestor(ah(a), 'figure'), fh) error('Axes must all come from the same figure.'); end end % Tag the objects so we can find them in the copy old_tag = get(ah, 'Tag'); if nAx == 1 old_tag = {old_tag}; end set(ah, 'Tag', 'ObjectToCopy'); % Create a new figure exactly the same as the old one fh = copyfig(fh); %copyobj(fh, 0); if nargin < 2 || ~vis set(fh, 'Visible', 'off'); end % Reset the object tags for a = 1:nAx set(ah(a), 'Tag', old_tag{a}); end % Find the objects to save ah = findall(fh, 'Tag', 'ObjectToCopy'); if numel(ah) ~= nAx close(fh); error('Incorrect number of objects found.'); end % Set the axes tags to what they should be for a = 1:nAx set(ah(a), 'Tag', old_tag{a}); end % Keep any legends and colorbars which overlap the subplots % Note: in HG1 these are axes objects; in HG2 they are separate objects, therefore we % don't test for the type, only the tag (hopefully nobody but Matlab uses them!) lh = findall(fh, 'Tag', 'legend', '-or', 'Tag', 'Colorbar'); nLeg = numel(lh); if nLeg > 0 set([ah(:); lh(:)], 'Units', 'normalized'); try ax_pos = get(ah, 'OuterPosition'); % axes and figures have the OuterPosition property catch ax_pos = get(ah, 'Position'); % uipanels only have Position, not OuterPosition end if nAx > 1 ax_pos = cell2mat(ax_pos(:)); end ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2); try leg_pos = get(lh, 'OuterPosition'); catch leg_pos = get(lh, 'Position'); % No OuterPosition in HG2, only in HG1 end if nLeg > 1; leg_pos = cell2mat(leg_pos); end leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2); ax_pos = shiftdim(ax_pos, -1); % Overlap test M = bsxfun(@lt, leg_pos(:,1), ax_pos(:,:,3)) & ... bsxfun(@lt, leg_pos(:,2), ax_pos(:,:,4)) & ... bsxfun(@gt, leg_pos(:,3), ax_pos(:,:,1)) & ... bsxfun(@gt, leg_pos(:,4), ax_pos(:,:,2)); ah = [ah; lh(any(M, 2))]; end % Get all the objects in the figure axs = findall(fh); % Delete everything except for the input objects and associated items delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)]))); end function ah = allchildren(ah) ah = findall(ah); if iscell(ah) ah = cell2mat(ah); end ah = ah(:); end function ph = allancestors(ah) ph = []; for a = 1:numel(ah) h = get(ah(a), 'parent'); while h ~= 0 ph = [ph; h]; h = get(h, 'parent'); end end end
github
mehta-lab/Instantaneous-PolScope-master
im2gif.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/export_fig/im2gif.m
6,048
utf_8
5a7437140f8d013158a195de1e372737
%IM2GIF Convert a multiframe image to an animated GIF file % % Examples: % im2gif infile % im2gif infile outfile % im2gif(A, outfile) % im2gif(..., '-nocrop') % im2gif(..., '-nodither') % im2gif(..., '-ncolors', n) % im2gif(..., '-loops', n) % im2gif(..., '-delay', n) % % This function converts a multiframe image to an animated GIF. % % To create an animation from a series of figures, export to a multiframe % TIFF file using export_fig, then convert to a GIF, as follows: % % for a = 2 .^ (3:6) % peaks(a); % export_fig test.tif -nocrop -append % end % im2gif('test.tif', '-delay', 0.5); % %IN: % infile - string containing the name of the input image. % outfile - string containing the name of the output image (must have the % .gif extension). Default: infile, with .gif extension. % A - HxWxCxN array of input images, stacked along fourth dimension, to % be converted to gif. % -nocrop - option indicating that the borders of the output are not to % be cropped. % -nodither - option indicating that dithering is not to be used when % converting the image. % -ncolors - option pair, the value of which indicates the maximum number % of colors the GIF can have. This can also be a quantization % tolerance, between 0 and 1. Default/maximum: 256. % -loops - option pair, the value of which gives the number of times the % animation is to be looped. Default: 65535. % -delay - option pair, the value of which gives the time, in seconds, % between frames. Default: 1/15. % Copyright (C) Oliver Woodford 2011 function im2gif(A, varargin) % Parse the input arguments [A, options] = parse_args(A, varargin{:}); if options.crop ~= 0 % Crop A = crop_borders(A, A(ceil(end/2),1,:,1)); end % Convert to indexed image [h, w, c, n] = size(A); A = reshape(permute(A, [1 2 4 3]), h, w*n, c); map = unique(reshape(A, h*w*n, c), 'rows'); if size(map, 1) > 256 dither_str = {'dither', 'nodither'}; dither_str = dither_str{1+(options.dither==0)}; if options.ncolors <= 1 [B, map] = rgb2ind(A, options.ncolors, dither_str); if size(map, 1) > 256 [B, map] = rgb2ind(A, 256, dither_str); end else [B, map] = rgb2ind(A, min(round(options.ncolors), 256), dither_str); end else if max(map(:)) > 1 map = double(map) / 255; A = double(A) / 255; end B = rgb2ind(im2double(A), map); end B = reshape(B, h, w, 1, n); % Bug fix to rgb2ind map(B(1)+1,:) = im2double(A(1,1,:)); % Save as a gif imwrite(B, map, options.outfile, 'LoopCount', round(options.loops(1)), 'DelayTime', options.delay); end %% Parse the input arguments function [A, options] = parse_args(A, varargin) % Set the defaults options = struct('outfile', '', ... 'dither', true, ... 'crop', true, ... 'ncolors', 256, ... 'loops', 65535, ... 'delay', 1/15); % Go through the arguments a = 0; n = numel(varargin); while a < n a = a + 1; if ischar(varargin{a}) && ~isempty(varargin{a}) if varargin{a}(1) == '-' opt = lower(varargin{a}(2:end)); switch opt case 'nocrop' options.crop = false; case 'nodither' options.dither = false; otherwise if ~isfield(options, opt) error('Option %s not recognized', varargin{a}); end a = a + 1; if ischar(varargin{a}) && ~ischar(options.(opt)) options.(opt) = str2double(varargin{a}); else options.(opt) = varargin{a}; end end else options.outfile = varargin{a}; end end end if isempty(options.outfile) if ~ischar(A) error('No output filename given.'); end % Generate the output filename from the input filename [path, outfile] = fileparts(A); options.outfile = fullfile(path, [outfile '.gif']); end if ischar(A) % Read in the image A = imread_rgb(A); end end %% Read image to uint8 rgb array function [A, alpha] = imread_rgb(name) % Get file info info = imfinfo(name); % Special case formats switch lower(info(1).Format) case 'gif' [A, map] = imread(name, 'frames', 'all'); if ~isempty(map) map = uint8(map * 256 - 0.5); % Convert to uint8 for storage A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0 A = permute(A, [1 2 5 4 3]); end case {'tif', 'tiff'} A = cell(numel(info), 1); for a = 1:numel(A) [A{a}, map] = imread(name, 'Index', a, 'Info', info); if ~isempty(map) map = uint8(map * 256 - 0.5); % Convert to uint8 for storage A{a} = reshape(map(uint32(A{a})+1,:), [size(A) size(map, 2)]); % Assume indexed from 0 end if size(A{a}, 3) == 4 % TIFF in CMYK colourspace - convert to RGB if isfloat(A{a}) A{a} = A{a} * 255; else A{a} = single(A{a}); end A{a} = 255 - A{a}; A{a}(:,:,4) = A{a}(:,:,4) / 255; A{a} = uint8(A(:,:,1:3) .* A{a}(:,:,[4 4 4])); end end A = cat(4, A{:}); otherwise [A, map, alpha] = imread(name); A = A(:,:,:,1); % Keep only first frame of multi-frame files if ~isempty(map) map = uint8(map * 256 - 0.5); % Convert to uint8 for storage A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0 elseif size(A, 3) == 4 % Assume 4th channel is an alpha matte alpha = A(:,:,4); A = A(:,:,1:3); end end end
github
mehta-lab/Instantaneous-PolScope-master
read_write_entire_textfile.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/export_fig/read_write_entire_textfile.m
924
utf_8
779e56972f5d9778c40dee98ddbd677e
%READ_WRITE_ENTIRE_TEXTFILE Read or write a whole text file to/from memory % % Read or write an entire text file to/from memory, without leaving the % file open if an error occurs. % % Reading: % fstrm = read_write_entire_textfile(fname) % Writing: % read_write_entire_textfile(fname, fstrm) % %IN: % fname - Pathname of text file to be read in. % fstrm - String to be written to the file, including carriage returns. % %OUT: % fstrm - String read from the file. If an fstrm input is given the % output is the same as that input. function fstrm = read_write_entire_textfile(fname, fstrm) modes = {'rt', 'wt'}; writing = nargin > 1; fh = fopen(fname, modes{1+writing}); if fh == -1 error('Unable to open file %s.', fname); end try if writing fwrite(fh, fstrm, 'char*1'); else fstrm = fread(fh, '*char')'; end catch ex fclose(fh); rethrow(ex); end fclose(fh); end
github
mehta-lab/Instantaneous-PolScope-master
pdf2eps.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/export_fig/pdf2eps.m
1,471
utf_8
a1f41f0c7713c73886a2323e53ed982b
%PDF2EPS Convert a pdf file to eps format using pdftops % % Examples: % pdf2eps source dest % % This function converts a pdf file to eps format. % % This function requires that you have pdftops, from the Xpdf suite of % functions, installed on your system. This can be downloaded from: % http://www.foolabs.com/xpdf % %IN: % source - filename of the source pdf file to convert. The filename is % assumed to already have the extension ".pdf". % dest - filename of the destination eps file. The filename is assumed to % already have the extension ".eps". % Copyright (C) Oliver Woodford 2009-2010 % Thanks to Aldebaro Klautau for reporting a bug when saving to % non-existant directories. function pdf2eps(source, dest) % Construct the options string for pdftops options = ['-q -paper match -eps -level2 "' source '" "' dest '"']; % Convert to eps using pdftops [status, message] = pdftops(options); % Check for error if status % Report error if isempty(message) error('Unable to generate eps. Check destination directory is writable.'); else error(message); end end % Fix the DSC error created by pdftops fid = fopen(dest, 'r+'); if fid == -1 % Cannot open the file return end fgetl(fid); % Get the first line str = fgetl(fid); % Get the second line if strcmp(str(1:min(13, end)), '% Produced by') fseek(fid, -numel(str)-1, 'cof'); fwrite(fid, '%'); % Turn ' ' into '%' end fclose(fid); end
github
mehta-lab/Instantaneous-PolScope-master
print2array.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/export_fig/print2array.m
9,369
utf_8
ca18a1e6c5a944b591a0557bd69f1c2c
function [A, bcol] = print2array(fig, res, renderer, gs_options) %PRINT2ARRAY Exports a figure to an image array % % Examples: % A = print2array % A = print2array(figure_handle) % A = print2array(figure_handle, resolution) % A = print2array(figure_handle, resolution, renderer) % A = print2array(figure_handle, resolution, renderer, gs_options) % [A bcol] = print2array(...) % % This function outputs a bitmap image of the given figure, at the desired % resolution. % % If renderer is '-painters' then ghostcript needs to be installed. This % can be downloaded from: http://www.ghostscript.com % % IN: % figure_handle - The handle of the figure to be exported. Default: gcf. % resolution - Resolution of the output, as a factor of screen % resolution. Default: 1. % renderer - string containing the renderer paramater to be passed to % print. Default: '-opengl'. % gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If % multiple options are needed, enclose in call array: {'-a','-b'} % % OUT: % A - MxNx3 uint8 image of the figure. % bcol - 1x3 uint8 vector of the background color % Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015- %{ % 05/09/11: Set EraseModes to normal when using opengl or zbuffer % renderers. Thanks to Pawel Kocieniewski for reporting the issue. % 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting it. % 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure size % and erasemode settings. Makes it a bit slower, but more reliable. % Thanks to Phil Trinh and Meelis Lootus for reporting the issues. % 09/12/11: Pass font path to ghostscript. % 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to % Ken Campbell for reporting it. % 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting it. % 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for % reporting the issue. % 26/02/15: If temp dir is not writable, use the current folder for temp % EPS/TIF files (Javier Paredes) % 27/02/15: Display suggested workarounds to internal print() error (issue #16) % 28/02/15: Enable users to specify optional ghostscript options (issue #36) % 10/03/15: Fixed minor warning reported by Paul Soderlind; fixed code indentation % 28/05/15: Fixed issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() func) % 07/07/15: Fixed issue #83: use numeric handles in HG1 %} % Generate default input arguments, if needed if nargin < 2 res = 1; if nargin < 1 fig = gcf; end end % Warn if output is large old_mode = get(fig, 'Units'); set(fig, 'Units', 'pixels'); px = get(fig, 'Position'); set(fig, 'Units', old_mode); npx = prod(px(3:4)*res)/1e6; if npx > 30 % 30M pixels or larger! warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx); end % Retrieve the background colour bcol = get(fig, 'Color'); % Set the resolution parameter res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))]; % Generate temporary file name tmp_nam = [tempname '.tif']; try % Ensure that the temp dir is writable (Javier Paredes 26/2/15) fid = fopen(tmp_nam,'w'); fwrite(fid,1); fclose(fid); delete(tmp_nam); % cleanup isTempDirOk = true; catch % Temp dir is not writable, so use the current folder [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU> fpath = pwd; tmp_nam = fullfile(fpath,[fname fext]); isTempDirOk = false; end % Enable users to specify optional ghostscript options (issue #36) if nargin > 3 && ~isempty(gs_options) if iscell(gs_options) gs_options = sprintf(' %s',gs_options{:}); elseif ~ischar(gs_options) error('gs_options input argument must be a string or cell-array of strings'); else gs_options = [' ' gs_options]; end else gs_options = ''; end if nargin > 2 && strcmp(renderer, '-painters') % Print to eps file if isTempDirOk tmp_eps = [tempname '.eps']; else tmp_eps = fullfile(fpath,[fname '.eps']); end print2eps(tmp_eps, fig, 0, renderer, '-loose'); try % Initialize the command to export to tiff using ghostscript cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc']; % Set the font path fp = font_path(); if ~isempty(fp) cmd_str = [cmd_str ' -sFONTPATH="' fp '"']; end % Add the filenames cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"' gs_options]; % Execute the ghostscript command ghostscript(cmd_str); catch me % Delete the intermediate file delete(tmp_eps); rethrow(me); end % Delete the intermediate file delete(tmp_eps); % Read in the generated bitmap A = imread(tmp_nam); % Delete the temporary bitmap file delete(tmp_nam); % Set border pixels to the correct colour if isequal(bcol, 'none') bcol = []; elseif isequal(bcol, [1 1 1]) bcol = uint8([255 255 255]); else for l = 1:size(A, 2) if ~all(reshape(A(:,l,:) == 255, [], 1)) break; end end for r = size(A, 2):-1:l if ~all(reshape(A(:,r,:) == 255, [], 1)) break; end end for t = 1:size(A, 1) if ~all(reshape(A(t,:,:) == 255, [], 1)) break; end end for b = size(A, 1):-1:t if ~all(reshape(A(b,:,:) == 255, [], 1)) break; end end bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1)); for c = 1:size(A, 3) A(:,[1:l-1, r+1:end],c) = bcol(c); A([1:t-1, b+1:end],:,c) = bcol(c); end end else if nargin < 3 renderer = '-opengl'; end err = false; % Set paper size old_pos_mode = get(fig, 'PaperPositionMode'); old_orientation = get(fig, 'PaperOrientation'); set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait'); try % Workaround for issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() function) fp = []; % in case we get an error below fp = findall(fig, 'Type','patch', 'LineWidth',0.75); set(fp, 'LineWidth',0.5); % Fix issue #83: use numeric handles in HG1 if ~using_hg2(fig), fig = double(fig); end % Print to tiff file print(fig, renderer, res_str, '-dtiff', tmp_nam); % Read in the printed file A = imread(tmp_nam); % Delete the temporary file delete(tmp_nam); catch ex err = true; end set(fp, 'LineWidth',0.75); % restore original figure appearance % Reset paper size set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation); % Throw any error that occurred if err % Display suggested workarounds to internal print() error (issue #16) fprintf(2, 'An error occured with Matlab''s builtin print function.\nTry setting the figure Renderer to ''painters'' or use opengl(''software'').\n\n'); rethrow(ex); end % Set the background color if isequal(bcol, 'none') bcol = []; else bcol = bcol * 255; if isequal(bcol, round(bcol)) bcol = uint8(bcol); else bcol = squeeze(A(1,1,:)); end end end % Check the output size is correct if isequal(res, round(res)) px = round([px([4 3])*res 3]); % round() to avoid an indexing warning below if ~isequal(size(A), px) % Correct the output size A = A(1:min(end,px(1)),1:min(end,px(2)),:); end end end % Function to return (and create, where necessary) the font path function fp = font_path() fp = user_string('gs_font_path'); if ~isempty(fp) return end % Create the path % Start with the default path fp = getenv('GS_FONTPATH'); % Add on the typical directories for a given OS if ispc if ~isempty(fp) fp = [fp ';']; end fp = [fp getenv('WINDIR') filesep 'Fonts']; else if ~isempty(fp) fp = [fp ':']; end fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype']; end user_string('gs_font_path', fp); end
github
mehta-lab/Instantaneous-PolScope-master
append_pdfs.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/export_fig/append_pdfs.m
2,678
utf_8
949c7c4ec3f5af6ff23099f17b1dfd79
%APPEND_PDFS Appends/concatenates multiple PDF files % % Example: % append_pdfs(output, input1, input2, ...) % append_pdfs(output, input_list{:}) % append_pdfs test.pdf temp1.pdf temp2.pdf % % This function appends multiple PDF files to an existing PDF file, or % concatenates them into a PDF file if the output file doesn't yet exist. % % This function requires that you have ghostscript installed on your % system. Ghostscript can be downloaded from: http://www.ghostscript.com % % IN: % output - string of output file name (including the extension, .pdf). % If it exists it is appended to; if not, it is created. % input1 - string of an input file name (including the extension, .pdf). % All input files are appended in order. % input_list - cell array list of input file name strings. All input % files are appended in order. % Copyright: Oliver Woodford, 2011 % Thanks to Reinhard Knoll for pointing out that appending multiple pdfs in % one go is much faster than appending them one at a time. % Thanks to Michael Teo for reporting the issue of a too long command line. % Issue resolved on 5/5/2011, by passing gs a command file. % Thanks to Martin Wittmann for pointing out the quality issue when % appending multiple bitmaps. % Issue resolved (to best of my ability) 1/6/2011, using the prepress % setting % 26/02/15: If temp dir is not writable, use the output folder for temp % files when appending (Javier Paredes); sanity check of inputs function append_pdfs(varargin) if nargin < 2, return; end % sanity check % Are we appending or creating a new file append = exist(varargin{1}, 'file') == 2; output = [tempname '.pdf']; try % Ensure that the temp dir is writable (Javier Paredes 26/2/15) fid = fopen(output,'w'); fwrite(fid,1); fclose(fid); delete(output); isTempDirOk = true; catch % Temp dir is not writable, so use the output folder [dummy,fname,fext] = fileparts(output); %#ok<ASGLU> fpath = fileparts(varargin{1}); output = fullfile(fpath,[fname fext]); isTempDirOk = false; end if ~append output = varargin{1}; varargin = varargin(2:end); end % Create the command file if isTempDirOk cmdfile = [tempname '.txt']; else cmdfile = fullfile(fpath,[fname '.txt']); end fh = fopen(cmdfile, 'w'); fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output); fprintf(fh, ' "%s"', varargin{:}); fclose(fh); % Call ghostscript ghostscript(['@"' cmdfile '"']); % Delete the command file delete(cmdfile); % Rename the file if needed if append movefile(output, varargin{1}); end end
github
mehta-lab/Instantaneous-PolScope-master
using_hg2.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/export_fig/using_hg2.m
1,002
utf_8
b1620dd31f4d0b8acea2723e354a3518
%USING_HG2 Determine if the HG2 graphics engine is used % % tf = using_hg2(fig) % %IN: % fig - handle to the figure in question. % %OUT: % tf - boolean indicating whether the HG2 graphics engine is being used % (true) or not (false). % 19/06/2015 - Suppress warning in R2015b; cache result for improved performance function tf = using_hg2(fig) persistent tf_cached if isempty(tf_cached) try if nargin < 1, fig = figure('visible','off'); end oldWarn = warning('off','MATLAB:graphicsversion:GraphicsVersionRemoval'); try % This generates a [supressed] warning in R2015b: tf = ~graphicsversion(fig, 'handlegraphics'); catch tf = verLessThan('matlab','8.4'); % =R2014b end warning(oldWarn); catch tf = false; end if nargin < 1, delete(fig); end tf_cached = tf; else tf = tf_cached; end end
github
mehta-lab/Instantaneous-PolScope-master
eps2pdf.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/export_fig/eps2pdf.m
7,661
utf_8
ab0c84a2a57942e7e121faef8e0742df
function eps2pdf(source, dest, crop, append, gray, quality, gs_options) %EPS2PDF Convert an eps file to pdf format using ghostscript % % Examples: % eps2pdf source dest % eps2pdf(source, dest, crop) % eps2pdf(source, dest, crop, append) % eps2pdf(source, dest, crop, append, gray) % eps2pdf(source, dest, crop, append, gray, quality) % eps2pdf(source, dest, crop, append, gray, quality, gs_options) % % This function converts an eps file to pdf format. The output can be % optionally cropped and also converted to grayscale. If the output pdf % file already exists then the eps file can optionally be appended as a new % page on the end of the eps file. The level of bitmap compression can also % optionally be set. % % This function requires that you have ghostscript installed on your % system. Ghostscript can be downloaded from: http://www.ghostscript.com % % Inputs: % source - filename of the source eps file to convert. The filename is % assumed to already have the extension ".eps". % dest - filename of the destination pdf file. The filename is assumed % to already have the extension ".pdf". % crop - boolean indicating whether to crop the borders off the pdf. % Default: true. % append - boolean indicating whether the eps should be appended to the % end of the pdf as a new page (if the pdf exists already). % Default: false. % gray - boolean indicating whether the output pdf should be grayscale % or not. Default: false. % quality - scalar indicating the level of image bitmap quality to % output. A larger value gives a higher quality. quality > 100 % gives lossless output. Default: ghostscript prepress default. % gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If % multiple options are needed, enclose in call array: {'-a','-b'} % Copyright (C) Oliver Woodford 2009-2014, Yair Altman 2015- % Suggestion of appending pdf files provided by Matt C at: % http://www.mathworks.com/matlabcentral/fileexchange/23629 % Thank you to Fabio Viola for pointing out compression artifacts, leading % to the quality setting. % Thank you to Scott for pointing out the subsampling of very small images, % which was fixed for lossless compression settings. % 9/12/2011 Pass font path to ghostscript. % 26/02/15: If temp dir is not writable, use the dest folder for temp % destination files (Javier Paredes) % 28/02/15: Enable users to specify optional ghostscript options (issue #36) % 01/03/15: Upon GS error, retry without the -sFONTPATH= option (this might solve % some /findfont errors according to James Rankin, FEX Comment 23/01/15) % 23/06/15: Added extra debug info in case of ghostscript error; code indentation % Intialise the options string for ghostscript options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"']; % Set crop option if nargin < 3 || crop options = [options ' -dEPSCrop']; end % Set the font path fp = font_path(); if ~isempty(fp) options = [options ' -sFONTPATH="' fp '"']; end % Set the grayscale option if nargin > 4 && gray options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray']; end % Set the bitmap quality if nargin > 5 && ~isempty(quality) options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false']; if quality > 100 options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"']; else options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode']; v = 1 + (quality < 80); quality = 1 - quality / 100; s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v); options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s); end end % Enable users to specify optional ghostscript options (issue #36) if nargin > 6 && ~isempty(gs_options) if iscell(gs_options) gs_options = sprintf(' %s',gs_options{:}); elseif ~ischar(gs_options) error('gs_options input argument must be a string or cell-array of strings'); else gs_options = [' ' gs_options]; end options = [options gs_options]; end % Check if the output file exists if nargin > 3 && append && exist(dest, 'file') == 2 % File exists - append current figure to the end tmp_nam = tempname; try % Ensure that the temp dir is writable (Javier Paredes 26/2/15) fid = fopen(tmp_nam,'w'); fwrite(fid,1); fclose(fid); delete(tmp_nam); catch % Temp dir is not writable, so use the dest folder [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU> fpath = fileparts(dest); tmp_nam = fullfile(fpath,[fname fext]); end % Copy the file copyfile(dest, tmp_nam); % Add the output file names options = [options ' -f "' tmp_nam '" "' source '"']; try % Convert to pdf using ghostscript [status, message] = ghostscript(options); catch me % Delete the intermediate file delete(tmp_nam); rethrow(me); end % Delete the intermediate file delete(tmp_nam); else % File doesn't exist or should be over-written % Add the output file names options = [options ' -f "' source '"']; % Convert to pdf using ghostscript [status, message] = ghostscript(options); end % Check for error if status % Retry without the -sFONTPATH= option (this might solve some GS % /findfont errors according to James Rankin, FEX Comment 23/01/15) orig_options = options; if ~isempty(fp) options = regexprep(options, ' -sFONTPATH=[^ ]+ ',' '); status = ghostscript(options); if ~status, return; end % hurray! (no error) end % Report error if isempty(message) error('Unable to generate pdf. Check destination directory is writable.'); else fprintf(2, 'Ghostscript error: perhaps %s is open by another application\n', dest); if ~isempty(gs_options) fprintf(2, ' or maybe the%s option(s) are not accepted by your GS version\n', gs_options); end fprintf(2, 'Ghostscript options: %s\n\n', orig_options); error(message); end end end % Function to return (and create, where necessary) the font path function fp = font_path() fp = user_string('gs_font_path'); if ~isempty(fp) return end % Create the path % Start with the default path fp = getenv('GS_FONTPATH'); % Add on the typical directories for a given OS if ispc if ~isempty(fp) fp = [fp ';']; end fp = [fp getenv('WINDIR') filesep 'Fonts']; else if ~isempty(fp) fp = [fp ':']; end fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype']; end user_string('gs_font_path', fp); end
github
mehta-lab/Instantaneous-PolScope-master
export_fig.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/export_fig/export_fig.m
54,007
utf_8
32f46fe89fce17e6b2e57b732facbcf6
function [imageData, alpha] = export_fig(varargin) %EXPORT_FIG Exports figures in a publication-quality format % % Examples: % imageData = export_fig % [imageData, alpha] = export_fig % export_fig filename % export_fig filename -format1 -format2 % export_fig ... -nocrop % export_fig ... -transparent % export_fig ... -native % export_fig ... -m<val> % export_fig ... -r<val> % export_fig ... -a<val> % export_fig ... -q<val> % export_fig ... -p<val> % export_fig ... -d<gs_option> % export_fig ... -depsc % export_fig ... -<renderer> % export_fig ... -<colorspace> % export_fig ... -append % export_fig ... -bookmark % export_fig ... -clipboard % export_fig ... -update % export_fig ... -nofontswap % export_fig(..., handle) % % This function saves a figure or single axes to one or more vector and/or % bitmap file formats, and/or outputs a rasterized version to the workspace, % with the following properties: % - Figure/axes reproduced as it appears on screen % - Cropped borders (optional) % - Embedded fonts (vector formats) % - Improved line and grid line styles % - Anti-aliased graphics (bitmap formats) % - Render images at native resolution (optional for bitmap formats) % - Transparent background supported (pdf, eps, png) % - Semi-transparent patch objects supported (png only) % - RGB, CMYK or grayscale output (CMYK only with pdf, eps, tiff) % - Variable image compression, including lossless (pdf, eps, jpg) % - Optionally append to file (pdf, tiff) % - Vector formats: pdf, eps % - Bitmap formats: png, tiff, jpg, bmp, export to workspace % % This function is especially suited to exporting figures for use in % publications and presentations, because of the high quality and % portability of media produced. % % Note that the background color and figure dimensions are reproduced % (the latter approximately, and ignoring cropping & magnification) in the % output file. For transparent background (and semi-transparent patch % objects), use the -transparent option or set the figure 'Color' property % to 'none'. To make axes transparent set the axes 'Color' property to % 'none'. PDF, EPS and PNG are the only formats that support a transparent % background, while only PNG format supports transparency of patch objects. % % The choice of renderer (opengl, zbuffer or painters) has a large impact % on the quality of output. The default value (opengl for bitmaps, painters % for vector formats) generally gives good results, but if you aren't % satisfied then try another renderer. Notes: 1) For vector formats (EPS, % PDF), only painters generates vector graphics. 2) For bitmaps, only % opengl can render transparent patch objects correctly. 3) For bitmaps, % only painters will correctly scale line dash and dot lengths when % magnifying or anti-aliasing. 4) Fonts may be substitued with Courier when % using painters. % % When exporting to vector format (PDF & EPS) and bitmap format using the % painters renderer, this function requires that ghostscript is installed % on your system. You can download this from: % http://www.ghostscript.com % When exporting to eps it additionally requires pdftops, from the Xpdf % suite of functions. You can download this from: % http://www.foolabs.com/xpdf % % Inputs: % filename - string containing the name (optionally including full or % relative path) of the file the figure is to be saved as. If % a path is not specified, the figure is saved in the current % directory. If no name and no output arguments are specified, % the default name, 'export_fig_out', is used. If neither a % file extension nor a format are specified, a ".png" is added % and the figure saved in that format. % -format1, -format2, etc. - strings containing the extensions of the % file formats the figure is to be saved as. % Valid options are: '-pdf', '-eps', '-png', % '-tif', '-jpg' and '-bmp'. All combinations % of formats are valid. % -nocrop - option indicating that the borders of the output are not to % be cropped. % -transparent - option indicating that the figure background is to be % made transparent (png, pdf and eps output only). % -m<val> - option where val indicates the factor to magnify the % on-screen figure pixel dimensions by when generating bitmap % outputs (does not affect vector formats). Default: '-m1'. % -r<val> - option val indicates the resolution (in pixels per inch) to % export bitmap and vector outputs at, keeping the dimensions % of the on-screen figure. Default: '-r864' (for vector output % only). Note that the -m option overides the -r option for % bitmap outputs only. % -native - option indicating that the output resolution (when outputting % a bitmap format) should be such that the vertical resolution % of the first suitable image found in the figure is at the % native resolution of that image. To specify a particular % image to use, give it the tag 'export_fig_native'. Notes: % This overrides any value set with the -m and -r options. It % also assumes that the image is displayed front-to-parallel % with the screen. The output resolution is approximate and % should not be relied upon. Anti-aliasing can have adverse % effects on image quality (disable with the -a1 option). % -a1, -a2, -a3, -a4 - option indicating the amount of anti-aliasing to % use for bitmap outputs. '-a1' means no anti- % aliasing; '-a4' is the maximum amount (default). % -<renderer> - option to force a particular renderer (painters, opengl or % zbuffer). Default value: opengl for bitmap formats or % figures with patches and/or transparent annotations; % painters for vector formats without patches/transparencies. % -<colorspace> - option indicating which colorspace color figures should % be saved in: RGB (default), CMYK or gray. CMYK is only % supported in pdf, eps and tiff output. % -q<val> - option to vary bitmap image quality (in pdf, eps and jpg % files only). Larger val, in the range 0-100, gives higher % quality/lower compression. val > 100 gives lossless % compression. Default: '-q95' for jpg, ghostscript prepress % default for pdf & eps. Note: lossless compression can % sometimes give a smaller file size than the default lossy % compression, depending on the type of images. % -p<val> - option to pad a border of width val to exported files, where % val is either a relative size with respect to cropped image % size (i.e. p=0.01 adds a 1% border). For EPS & PDF formats, % val can also be integer in units of 1/72" points (abs(val)>1). % val can be positive (padding) or negative (extra cropping). % If used, the -nocrop flag will be ignored, i.e. the image will % always be cropped and then padded. Default: 0 (i.e. no padding). % -append - option indicating that if the file (pdfs only) already % exists, the figure is to be appended as a new page, instead % of being overwritten (default). % -bookmark - option to indicate that a bookmark with the name of the % figure is to be created in the output file (pdf only). % -clipboard - option to save output as an image on the system clipboard. % Note: background transparency is not preserved in clipboard % -d<gs_option> - option to indicate a ghostscript setting. For example, % -dMaxBitmap=0 or -dNoOutputFonts (Ghostscript 9.15+). % -depsc - option to use EPS level-3 rather than the default level-2 print % device. This solves some bugs with Matlab's default -depsc2 device % such as discolored subplot lines on images (vector formats only). % -update - option to download and install the latest version of export_fig % -nofontswap - option to avoid font swapping. Font swapping is automatically % done in vector formats (only): 11 standard Matlab fonts are % replaced by the original figure fonts. This option prevents this. % handle - The handle of the figure, axes or uipanels (can be an array of % handles, but the objects must be in the same figure) to be % saved. Default: gcf. % % Outputs: % imageData - MxNxC uint8 image array of the exported image. % alpha - MxN single array of alphamatte values in the range [0,1], % for the case when the background is transparent. % % Some helpful examples and tips can be found at: % https://github.com/altmany/export_fig % % See also PRINT, SAVEAS, ScreenCapture (on the Matlab File Exchange) %{ % Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015- % The idea of using ghostscript is inspired by Peder Axensten's SAVEFIG % (fex id: 10889) which is itself inspired by EPS2PDF (fex id: 5782). % The idea for using pdftops came from the MATLAB newsgroup (id: 168171). % The idea of editing the EPS file to change line styles comes from Jiro % Doke's FIXPSLINESTYLE (fex id: 17928). % The idea of changing dash length with line width came from comments on % fex id: 5743, but the implementation is mine :) % The idea of anti-aliasing bitmaps came from Anders Brun's MYAA (fex id: % 20979). % The idea of appending figures in pdfs came from Matt C in comments on the % FEX (id: 23629) % Thanks to Roland Martin for pointing out the colour MATLAB % bug/feature with colorbar axes and transparent backgrounds. % Thanks also to Andrew Matthews for describing a bug to do with the figure % size changing in -nodisplay mode. I couldn't reproduce it, but included a % fix anyway. % Thanks to Tammy Threadgill for reporting a bug where an axes is not % isolated from gui objects. %} %{ % 23/02/12: Ensure that axes limits don't change during printing % 14/03/12: Fix bug in fixing the axes limits (thanks to Tobias Lamour for reporting it). % 02/05/12: Incorporate patch of Petr Nechaev (many thanks), enabling bookmarking of figures in pdf files. % 09/05/12: Incorporate patch of Arcelia Arrieta (many thanks), to keep tick marks fixed. % 12/12/12: Add support for isolating uipanels. Thanks to michael for suggesting it. % 25/09/13: Add support for changing resolution in vector formats. Thanks to Jan Jaap Meijer for suggesting it. % 07/05/14: Add support for '~' at start of path. Thanks to Sally Warner for suggesting it. % 24/02/15: Fix Matlab R2014b bug (issue #34): plot markers are not displayed when ZLimMode='manual' % 25/02/15: Fix issue #4 (using HG2 on R2014a and earlier) % 25/02/15: Fix issue #21 (bold TeX axes labels/titles in R2014b) % 26/02/15: If temp dir is not writable, use the user-specified folder for temporary EPS/PDF files (Javier Paredes) % 27/02/15: Modified repository URL from github.com/ojwoodford to /altmany % Indented main function % Added top-level try-catch block to display useful workarounds % 28/02/15: Enable users to specify optional ghostscript options (issue #36) % 06/03/15: Improved image padding & cropping thanks to Oscar Hartogensis % 26/03/15: Fixed issue #49 (bug with transparent grayscale images); fixed out-of-memory issue % 26/03/15: Fixed issue #42: non-normalized annotations on HG1 % 26/03/15: Fixed issue #46: Ghostscript crash if figure units <> pixels % 27/03/15: Fixed issue #39: bad export of transparent annotations/patches % 28/03/15: Fixed issue #50: error on some Matlab versions with the fix for issue #42 % 29/03/15: Fixed issue #33: bugs in Matlab's print() function with -cmyk % 29/03/15: Improved processing of input args (accept space between param name & value, related to issue #51) % 30/03/15: When exporting *.fig files, then saveas *.fig if figure is open, otherwise export the specified fig file % 30/03/15: Fixed edge case bug introduced yesterday (commit #ae1755bd2e11dc4e99b95a7681f6e211b3fa9358) % 09/04/15: Consolidated header comment sections; initialize output vars only if requested (nargout>0) % 14/04/15: Workaround for issue #45: lines in image subplots are exported in invalid color % 15/04/15: Fixed edge-case in parsing input parameters; fixed help section to show the -depsc option (issue #45) % 21/04/15: Bug fix: Ghostscript croaks on % chars in output PDF file (reported by Sven on FEX page, 15-Jul-2014) % 22/04/15: Bug fix: Pdftops croaks on relative paths (reported by Tintin Milou on FEX page, 19-Jan-2015) % 04/05/15: Merged fix #63 (Kevin Mattheus Moerman): prevent tick-label changes during export % 07/05/15: Partial fix for issue #65: PDF export used painters rather than opengl renderer (thanks Nguyenr) % 08/05/15: Fixed issue #65: bad PDF append since commit #e9f3cdf 21/04/15 (thanks Robert Nguyen) % 12/05/15: Fixed issue #67: exponent labels cropped in export, since fix #63 (04/05/15) % 28/05/15: Fixed issue #69: set non-bold label font only if the string contains symbols (\beta etc.), followup to issue #21 % 29/05/15: Added informative error message in case user requested SVG output (issue #72) % 09/06/15: Fixed issue #58: -transparent removed anti-aliasing when exporting to PNG % 19/06/15: Added -update option to download and install the latest version of export_fig % 07/07/15: Added -nofontswap option to avoid font-swapping in EPS/PDF % 16/07/15: Fixed problem with anti-aliasing on old Matlab releases %} if nargout [imageData, alpha] = deal([]); end hadError = false; displaySuggestedWorkarounds = true; % Ensure the figure is rendered correctly _now_ so that properties like axes limits are up-to-date drawnow; pause(0.05); % this solves timing issues with Java Swing's EDT (http://undocumentedmatlab.com/blog/solving-a-matlab-hang-problem) % Parse the input arguments fig = get(0, 'CurrentFigure'); [fig, options] = parse_args(nargout, fig, varargin{:}); % Ensure that we have a figure handle if isequal(fig,-1) return; % silent bail-out elseif isempty(fig) error('No figure found'); end % Isolate the subplot, if it is one cls = all(ismember(get(fig, 'Type'), {'axes', 'uipanel'})); if cls % Given handles of one or more axes, so isolate them from the rest fig = isolate_axes(fig); else % Check we have a figure if ~isequal(get(fig, 'Type'), 'figure'); error('Handle must be that of a figure, axes or uipanel'); end % Get the old InvertHardcopy mode old_mode = get(fig, 'InvertHardcopy'); end % Hack the font units where necessary (due to a font rendering bug in print?). % This may not work perfectly in all cases. % Also it can change the figure layout if reverted, so use a copy. magnify = options.magnify * options.aa_factor; if isbitmap(options) && magnify ~= 1 fontu = findall(fig, 'FontUnits', 'normalized'); if ~isempty(fontu) % Some normalized font units found if ~cls fig = copyfig(fig); set(fig, 'Visible', 'off'); fontu = findall(fig, 'FontUnits', 'normalized'); cls = true; end set(fontu, 'FontUnits', 'points'); end end try % MATLAB "feature": axes limits and tick marks can change when printing Hlims = findall(fig, 'Type', 'axes'); if ~cls % Record the old axes limit and tick modes Xlims = make_cell(get(Hlims, 'XLimMode')); Ylims = make_cell(get(Hlims, 'YLimMode')); Zlims = make_cell(get(Hlims, 'ZLimMode')); Xtick = make_cell(get(Hlims, 'XTickMode')); Ytick = make_cell(get(Hlims, 'YTickMode')); Ztick = make_cell(get(Hlims, 'ZTickMode')); Xlabel = make_cell(get(Hlims, 'XTickLabelMode')); Ylabel = make_cell(get(Hlims, 'YTickLabelMode')); Zlabel = make_cell(get(Hlims, 'ZTickLabelMode')); end % Set all axes limit and tick modes to manual, so the limits and ticks can't change % Fix Matlab R2014b bug (issue #34): plot markers are not displayed when ZLimMode='manual' set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual'); set_tick_mode(Hlims, 'X'); set_tick_mode(Hlims, 'Y'); if ~using_hg2(fig) set(Hlims,'ZLimMode', 'manual'); set_tick_mode(Hlims, 'Z'); end catch % ignore - fix issue #4 (using HG2 on R2014a and earlier) end % Fix issue #21 (bold TeX axes labels/titles in R2014b when exporting to EPS/PDF) try if using_hg2(fig) && isvector(options) % Set the FontWeight of axes labels/titles to 'normal' % Fix issue #69: set non-bold font only if the string contains symbols (\beta etc.) texLabels = findall(fig, 'type','text', 'FontWeight','bold'); symbolIdx = ~cellfun('isempty',strfind({texLabels.String},'\')); set(texLabels(symbolIdx), 'FontWeight','normal'); end catch % ignore end % Fix issue #42: non-normalized annotations on HG1 (internal Matlab bug) annotationHandles = []; try if ~using_hg2(fig) annotationHandles = findall(fig,'Type','hggroup','-and','-property','Units','-and','-not','Units','norm'); originalUnits = get(annotationHandles,'Units'); set(annotationHandles,'Units','norm'); end catch % should never happen, but ignore in any case - issue #50 end % Fix issue #46: Ghostscript crash if figure units <> pixels oldFigUnits = get(fig,'Units'); set(fig,'Units','pixels'); % Set to print exactly what is there set(fig, 'InvertHardcopy', 'off'); % Set the renderer switch options.renderer case 1 renderer = '-opengl'; case 2 renderer = '-zbuffer'; case 3 renderer = '-painters'; otherwise renderer = '-opengl'; % Default for bitmaps end try % Do the bitmap formats first if isbitmap(options) if abs(options.bb_padding) > 1 displaySuggestedWorkarounds = false; error('For bitmap output (png,jpg,tif,bmp) the padding value (-p) must be between -1<p<1') end % Get the background colour if options.transparent && (options.png || options.alpha) % Get out an alpha channel % MATLAB "feature": black colorbar axes can change to white and vice versa! hCB = findall(fig, 'Type','axes', 'Tag','Colorbar'); if isempty(hCB) yCol = []; xCol = []; else yCol = get(hCB, 'YColor'); xCol = get(hCB, 'XColor'); if iscell(yCol) yCol = cell2mat(yCol); xCol = cell2mat(xCol); end yCol = sum(yCol, 2); xCol = sum(xCol, 2); end % MATLAB "feature": apparently figure size can change when changing % colour in -nodisplay mode pos = get(fig, 'Position'); % Set the background colour to black, and set size in case it was % changed internally tcol = get(fig, 'Color'); set(fig, 'Color', 'k', 'Position', pos); % Correct the colorbar axes colours set(hCB(yCol==0), 'YColor', [0 0 0]); set(hCB(xCol==0), 'XColor', [0 0 0]); % The following code might cause out-of-memory errors try % Print large version to array B = print2array(fig, magnify, renderer); % Downscale the image B = downsize(single(B), options.aa_factor); catch % This is more conservative in memory, but kills transparency (issue #58) B = single(print2array(fig, magnify/options.aa_factor, renderer)); end % Set background to white (and set size) set(fig, 'Color', 'w', 'Position', pos); % Correct the colorbar axes colours set(hCB(yCol==3), 'YColor', [1 1 1]); set(hCB(xCol==3), 'XColor', [1 1 1]); % The following code might cause out-of-memory errors try % Print large version to array A = print2array(fig, magnify, renderer); % Downscale the image A = downsize(single(A), options.aa_factor); catch % This is more conservative in memory, but kills transparency (issue #58) A = single(print2array(fig, magnify/options.aa_factor, renderer)); end % Set the background colour (and size) back to normal set(fig, 'Color', tcol, 'Position', pos); % Compute the alpha map alpha = round(sum(B - A, 3)) / (255 * 3) + 1; A = alpha; A(A==0) = 1; A = B ./ A(:,:,[1 1 1]); clear B % Convert to greyscale if options.colourspace == 2 A = rgb2grey(A); end A = uint8(A); % Crop the background if options.crop %[alpha, v] = crop_borders(alpha, 0, 1); %A = A(v(1):v(2),v(3):v(4),:); [alpha, vA, vB] = crop_borders(alpha, 0, options.bb_padding); if ~any(isnan(vB)) % positive padding B = repmat(uint8(zeros(1,1,size(A,3))),size(alpha)); B(vB(1):vB(2), vB(3):vB(4), :) = A(vA(1):vA(2), vA(3):vA(4), :); % ADDED BY OH A = B; else % negative padding A = A(vA(1):vA(2), vA(3):vA(4), :); end end if options.png % Compute the resolution res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3; % Save the png imwrite(A, [options.name '.png'], 'Alpha', double(alpha), 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res); % Clear the png bit options.png = false; end % Return only one channel for greyscale if isbitmap(options) A = check_greyscale(A); end if options.alpha % Store the image imageData = A; % Clear the alpha bit options.alpha = false; end % Get the non-alpha image if isbitmap(options) alph = alpha(:,:,ones(1, size(A, 3))); A = uint8(single(A) .* alph + 255 * (1 - alph)); clear alph end if options.im % Store the new image imageData = A; end else % Print large version to array if options.transparent % MATLAB "feature": apparently figure size can change when changing % colour in -nodisplay mode pos = get(fig, 'Position'); tcol = get(fig, 'Color'); set(fig, 'Color', 'w', 'Position', pos); A = print2array(fig, magnify, renderer); set(fig, 'Color', tcol, 'Position', pos); tcol = 255; else [A, tcol] = print2array(fig, magnify, renderer); end % Crop the background if options.crop A = crop_borders(A, tcol, options.bb_padding); end % Downscale the image A = downsize(A, options.aa_factor); if options.colourspace == 2 % Convert to greyscale A = rgb2grey(A); else % Return only one channel for greyscale A = check_greyscale(A); end % Outputs if options.im imageData = A; end if options.alpha imageData = A; alpha = zeros(size(A, 1), size(A, 2), 'single'); end end % Save the images if options.png res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3; imwrite(A, [options.name '.png'], 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res); end if options.bmp imwrite(A, [options.name '.bmp']); end % Save jpeg with given quality if options.jpg quality = options.quality; if isempty(quality) quality = 95; end if quality > 100 imwrite(A, [options.name '.jpg'], 'Mode', 'lossless'); else imwrite(A, [options.name '.jpg'], 'Quality', quality); end end % Save tif images in cmyk if wanted (and possible) if options.tif if options.colourspace == 1 && size(A, 3) == 3 A = double(255 - A); K = min(A, [], 3); K_ = 255 ./ max(255 - K, 1); C = (A(:,:,1) - K) .* K_; M = (A(:,:,2) - K) .* K_; Y = (A(:,:,3) - K) .* K_; A = uint8(cat(3, C, M, Y, K)); clear C M Y K K_ end append_mode = {'overwrite', 'append'}; imwrite(A, [options.name '.tif'], 'Resolution', options.magnify*get(0, 'ScreenPixelsPerInch'), 'WriteMode', append_mode{options.append+1}); end end % Now do the vector formats if isvector(options) % Set the default renderer to painters if ~options.renderer if isempty(findall(fig,'-property','FaceAlpha','-and','-not','FaceAlpha',1)) && ... isempty(findall(fig,'type','patch')) renderer = '-painters'; else % This is *MUCH* slower, but more accurate for patches and transparent annotations (issue #39) renderer = '-opengl'; end end % Generate some filenames tmp_nam = [tempname '.eps']; try % Ensure that the temp dir is writable (Javier Paredes 30/1/15) fid = fopen(tmp_nam,'w'); fwrite(fid,1); fclose(fid); delete(tmp_nam); isTempDirOk = true; catch % Temp dir is not writable, so use the user-specified folder [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU> fpath = fileparts(options.name); tmp_nam = fullfile(fpath,[fname fext]); isTempDirOk = false; end if isTempDirOk pdf_nam_tmp = [tempname '.pdf']; else pdf_nam_tmp = fullfile(fpath,[fname '.pdf']); end if options.pdf pdf_nam = [options.name '.pdf']; try copyfile(pdf_nam, pdf_nam_tmp, 'f'); catch, end % fix for issue #65 else pdf_nam = pdf_nam_tmp; end % Generate the options for print p2eArgs = {renderer, sprintf('-r%d', options.resolution)}; if options.colourspace == 1 % CMYK % Issue #33: due to internal bugs in Matlab's print() function, we can't use its -cmyk option %p2eArgs{end+1} = '-cmyk'; end if ~options.crop % Issue #56: due to internal bugs in Matlab's print() function, we can't use its internal cropping mechanism, % therefore we always use '-loose' (in print2eps.m) and do our own cropping (in crop_borders) %p2eArgs{end+1} = '-loose'; end if any(strcmpi(varargin,'-depsc')) % Issue #45: lines in image subplots are exported in invalid color. % The workaround is to use the -depsc parameter instead of the default -depsc2 p2eArgs{end+1} = '-depsc'; end try % Generate an eps print2eps(tmp_nam, fig, [options.bb_padding, options.crop, options.fontswap], p2eArgs{:}); % Remove the background, if desired if options.transparent && ~isequal(get(fig, 'Color'), 'none') eps_remove_background(tmp_nam, 1 + using_hg2(fig)); end % Fix colorspace to CMYK, if requested (workaround for issue #33) if options.colourspace == 1 % CMYK % Issue #33: due to internal bugs in Matlab's print() function, we can't use its -cmyk option change_rgb_to_cmyk(tmp_nam); end % Add a bookmark to the PDF if desired if options.bookmark fig_nam = get(fig, 'Name'); if isempty(fig_nam) warning('export_fig:EmptyBookmark', 'Bookmark requested for figure with no name. Bookmark will be empty.'); end add_bookmark(tmp_nam, fig_nam); end % Generate a pdf eps2pdf(tmp_nam, pdf_nam_tmp, 1, options.append, options.colourspace==2, options.quality, options.gs_options); % Ghostscript croaks on % chars in the output PDF file, so use tempname and then rename the file try movefile(pdf_nam_tmp, pdf_nam, 'f'); catch, end catch ex % Delete the eps delete(tmp_nam); rethrow(ex); end % Delete the eps delete(tmp_nam); if options.eps try % Generate an eps from the pdf % since pdftops can't handle relative paths (e.g., '..\'), use a temp file eps_nam_tmp = strrep(pdf_nam_tmp,'.pdf','.eps'); pdf2eps(pdf_nam, eps_nam_tmp); movefile(eps_nam_tmp, [options.name '.eps'], 'f'); catch ex if ~options.pdf % Delete the pdf delete(pdf_nam); end try delete(eps_nam_tmp); catch, end rethrow(ex); end if ~options.pdf % Delete the pdf delete(pdf_nam); end end end % Revert the figure or close it (if requested) if cls || options.closeFig % Close the created figure close(fig); else % Reset the hardcopy mode set(fig, 'InvertHardcopy', old_mode); % Reset the axes limit and tick modes for a = 1:numel(Hlims) try set(Hlims(a), 'XLimMode', Xlims{a}, 'YLimMode', Ylims{a}, 'ZLimMode', Zlims{a},... 'XTickMode', Xtick{a}, 'YTickMode', Ytick{a}, 'ZTickMode', Ztick{a},... 'XTickLabelMode', Xlabel{a}, 'YTickLabelMode', Ylabel{a}, 'ZTickLabelMode', Zlabel{a}); catch % ignore - fix issue #4 (using HG2 on R2014a and earlier) end end % Revert the tex-labels font weights try set(texLabels, 'FontWeight','bold'); catch, end % Revert annotation units for handleIdx = 1 : numel(annotationHandles) try oldUnits = originalUnits{handleIdx}; catch oldUnits = originalUnits; end try set(annotationHandles(handleIdx),'Units',oldUnits); catch, end end % Revert figure units set(fig,'Units',oldFigUnits); end % Output to clipboard (if requested) if options.clipboard % Delete the output file if unchanged from the default name ('export_fig_out.png') if strcmpi(options.name,'export_fig_out') try fileInfo = dir('export_fig_out.png'); if ~isempty(fileInfo) timediff = now - fileInfo.datenum; ONE_SEC = 1/24/60/60; if timediff < ONE_SEC delete('export_fig_out.png'); end end catch % never mind... end end % Save the image in the system clipboard % credit: Jiro Doke's IMCLIPBOARD: http://www.mathworks.com/matlabcentral/fileexchange/28708-imclipboard try error(javachk('awt', 'export_fig -clipboard output')); catch warning('export_fig -clipboard output failed: requires Java to work'); return; end try % Import necessary Java classes import java.awt.Toolkit.* import java.awt.image.BufferedImage import java.awt.datatransfer.DataFlavor % Get System Clipboard object (java.awt.Toolkit) cb = getDefaultToolkit.getSystemClipboard(); % Add java class (ImageSelection) to the path if ~exist('ImageSelection', 'class') javaaddpath(fileparts(which(mfilename)), '-end'); end % Get image size ht = size(imageData, 1); wd = size(imageData, 2); % Convert to Blue-Green-Red format try imageData2 = imageData(:, :, [3 2 1]); catch % Probably gray-scaled image (2D, without the 3rd [RGB] dimension) imageData2 = imageData(:, :, [1 1 1]); end % Convert to 3xWxH format imageData2 = permute(imageData2, [3, 2, 1]); % Append Alpha data (unused - transparency is not supported in clipboard copy) alphaData2 = uint8(permute(255*alpha,[3,2,1])); %=255*ones(1,wd,ht,'uint8') imageData2 = cat(1, imageData2, alphaData2); % Create image buffer imBuffer = BufferedImage(wd, ht, BufferedImage.TYPE_INT_RGB); imBuffer.setRGB(0, 0, wd, ht, typecast(imageData2(:), 'int32'), 0, wd); % Create ImageSelection object from the image buffer imSelection = ImageSelection(imBuffer); % Set clipboard content to the image cb.setContents(imSelection, []); catch warning('export_fig -clipboard output failed: %s', lasterr); %#ok<LERR> end end % Don't output the data to console unless requested if ~nargout clear imageData alpha end catch err % Display possible workarounds before the error message if displaySuggestedWorkarounds if ~hadError, fprintf(2, 'export_fig error. '); end fprintf(2, 'Please ensure:\n'); fprintf(2, ' that you are using the <a href="https://github.com/altmany/export_fig/archive/master.zip">latest version</a> of export_fig\n'); fprintf(2, ' and that you have <a href="http://www.ghostscript.com">Ghostscript</a> installed\n'); try if options.eps fprintf(2, ' and that you have <a href="http://www.foolabs.com/xpdf">pdftops</a> installed\n'); end catch % ignore - probably an error in parse_args end fprintf(2, ' and that you do not have <a href="matlab:which export_fig -all">multiple versions</a> of export_fig installed by mistake\n'); fprintf(2, ' and that you did not made a mistake in the <a href="matlab:help export_fig">expected input arguments</a>\n'); fprintf(2, '\nIf the problem persists, then please <a href="https://github.com/altmany/export_fig/issues">report a new issue</a>.\n\n'); end rethrow(err) end end function [fig, options] = parse_args(nout, fig, varargin) % Parse the input arguments % Set the defaults options = struct(... 'name', 'export_fig_out', ... 'crop', true, ... 'transparent', false, ... 'renderer', 0, ... % 0: default, 1: OpenGL, 2: ZBuffer, 3: Painters 'pdf', false, ... 'eps', false, ... 'png', false, ... 'tif', false, ... 'jpg', false, ... 'bmp', false, ... 'clipboard', false, ... 'colourspace', 0, ... % 0: RGB/gray, 1: CMYK, 2: gray 'append', false, ... 'im', nout == 1, ... 'alpha', nout == 2, ... 'aa_factor', 0, ... 'bb_padding', 0, ... 'magnify', [], ... 'resolution', [], ... 'bookmark', false, ... 'closeFig', false, ... 'quality', [], ... 'update', false, ... 'fontswap', true, ... 'gs_options', {{}}); native = false; % Set resolution to native of an image % Go through the other arguments skipNext = false; for a = 1:nargin-2 if skipNext skipNext = false; continue; end if all(ishandle(varargin{a})) fig = varargin{a}; elseif ischar(varargin{a}) && ~isempty(varargin{a}) if varargin{a}(1) == '-' switch lower(varargin{a}(2:end)) case 'nocrop' options.crop = false; case {'trans', 'transparent'} options.transparent = true; case 'opengl' options.renderer = 1; case 'zbuffer' options.renderer = 2; case 'painters' options.renderer = 3; case 'pdf' options.pdf = true; case 'eps' options.eps = true; case 'png' options.png = true; case {'tif', 'tiff'} options.tif = true; case {'jpg', 'jpeg'} options.jpg = true; case 'bmp' options.bmp = true; case 'rgb' options.colourspace = 0; case 'cmyk' options.colourspace = 1; case {'gray', 'grey'} options.colourspace = 2; case {'a1', 'a2', 'a3', 'a4'} options.aa_factor = str2double(varargin{a}(3)); case 'append' options.append = true; case 'bookmark' options.bookmark = true; case 'native' native = true; case 'clipboard' options.clipboard = true; options.im = true; options.alpha = true; case 'svg' msg = ['SVG output is not supported by export_fig. Use one of the following alternatives:\n' ... ' 1. saveas(gcf,''filename.svg'')\n' ... ' 2. plot2svg utility: http://github.com/jschwizer99/plot2svg\n' ... ' 3. export_fig to EPS/PDF, then convert to SVG using generic (non-Matlab) tools\n']; error(sprintf(msg)); %#ok<SPERR> case 'update' % Download the latest version of export_fig into the export_fig folder try zipFileName = 'https://github.com/altmany/export_fig/archive/master.zip'; folderName = fileparts(which(mfilename('fullpath'))); targetFileName = fullfile(folderName, datestr(now,'yyyy-mm-dd.zip')); urlwrite(zipFileName,targetFileName); catch error('Could not download %s into %s\n',zipFileName,targetFileName); end % Unzip the downloaded zip file in the export_fig folder try unzip(targetFileName,folderName); catch error('Could not unzip %s\n',targetFileName); end case 'nofontswap' options.fontswap = false; otherwise try if strcmpi(varargin{a}(1:2),'-d') varargin{a}(2) = 'd'; % ensure lowercase 'd' options.gs_options{end+1} = varargin{a}; else val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q|p|P))-?\d*.?\d+', 'match')); if isempty(val) || isnan(val) % Issue #51: improved processing of input args (accept space between param name & value) val = str2double(varargin{a+1}); if isscalar(val) && ~isnan(val) skipNext = true; end end if ~isscalar(val) || isnan(val) error('option %s is not recognised or cannot be parsed', varargin{a}); end switch lower(varargin{a}(2)) case 'm' options.magnify = val; case 'r' options.resolution = val; case 'q' options.quality = max(val, 0); case 'p' options.bb_padding = val; end end catch error(['Unrecognized export_fig input option: ''' varargin{a} '''']); end end else [p, options.name, ext] = fileparts(varargin{a}); if ~isempty(p) options.name = [p filesep options.name]; end switch lower(ext) case {'.tif', '.tiff'} options.tif = true; case {'.jpg', '.jpeg'} options.jpg = true; case '.png' options.png = true; case '.bmp' options.bmp = true; case '.eps' options.eps = true; case '.pdf' options.pdf = true; case '.fig' % If no open figure, then load the specified .fig file and continue if isempty(fig) fig = openfig(varargin{a},'invisible'); varargin{a} = fig; options.closeFig = true; else % save the current figure as the specified .fig file and exit saveas(fig(1),varargin{a}); fig = -1; return end case '.svg' msg = ['SVG output is not supported by export_fig. Use one of the following alternatives:\n' ... ' 1. saveas(gcf,''filename.svg'')\n' ... ' 2. plot2svg utility: http://github.com/jschwizer99/plot2svg\n' ... ' 3. export_fig to EPS/PDF, then convert to SVG using generic (non-Matlab) tools\n']; error(sprintf(msg)); %#ok<SPERR> otherwise options.name = varargin{a}; end end end end % Quick bail-out if no figure found if isempty(fig), return; end % Do border padding with repsect to a cropped image if options.bb_padding options.crop = true; end % Set default anti-aliasing now we know the renderer if options.aa_factor == 0 try isAA = strcmp(get(ancestor(fig, 'figure'), 'GraphicsSmoothing'), 'on'); catch, isAA = false; end options.aa_factor = 1 + 2 * (~(using_hg2(fig) && isAA) | (options.renderer == 3)); end % Convert user dir '~' to full path if numel(options.name) > 2 && options.name(1) == '~' && (options.name(2) == '/' || options.name(2) == '\') options.name = fullfile(char(java.lang.System.getProperty('user.home')), options.name(2:end)); end % Compute the magnification and resolution if isempty(options.magnify) if isempty(options.resolution) options.magnify = 1; options.resolution = 864; else options.magnify = options.resolution ./ get(0, 'ScreenPixelsPerInch'); end elseif isempty(options.resolution) options.resolution = 864; end % Set the default format if ~isvector(options) && ~isbitmap(options) options.png = true; end % Check whether transparent background is wanted (old way) if isequal(get(ancestor(fig(1), 'figure'), 'Color'), 'none') options.transparent = true; end % If requested, set the resolution to the native vertical resolution of the % first suitable image found if native && isbitmap(options) % Find a suitable image list = findall(fig, 'Type','image', 'Tag','export_fig_native'); if isempty(list) list = findall(fig, 'Type','image', 'Visible','on'); end for hIm = list(:)' % Check height is >= 2 height = size(get(hIm, 'CData'), 1); if height < 2 continue end % Account for the image filling only part of the axes, or vice % versa yl = get(hIm, 'YData'); if isscalar(yl) yl = [yl(1)-0.5 yl(1)+height+0.5]; else if ~diff(yl) continue end yl = yl + [-0.5 0.5] * (diff(yl) / (height - 1)); end hAx = get(hIm, 'Parent'); yl2 = get(hAx, 'YLim'); % Find the pixel height of the axes oldUnits = get(hAx, 'Units'); set(hAx, 'Units', 'pixels'); pos = get(hAx, 'Position'); set(hAx, 'Units', oldUnits); if ~pos(4) continue end % Found a suitable image % Account for stretch-to-fill being disabled pbar = get(hAx, 'PlotBoxAspectRatio'); pos = min(pos(4), pbar(2)*pos(3)/pbar(1)); % Set the magnification to give native resolution options.magnify = (height * diff(yl2)) / (pos * diff(yl)); break end end end function A = downsize(A, factor) % Downsample an image if factor == 1 % Nothing to do return end try % Faster, but requires image processing toolbox A = imresize(A, 1/factor, 'bilinear'); catch % No image processing toolbox - resize manually % Lowpass filter - use Gaussian as is separable, so faster % Compute the 1d Gaussian filter filt = (-factor-1:factor+1) / (factor * 0.6); filt = exp(-filt .* filt); % Normalize the filter filt = single(filt / sum(filt)); % Filter the image padding = floor(numel(filt) / 2); for a = 1:size(A, 3) A(:,:,a) = conv2(filt, filt', single(A([ones(1, padding) 1:end repmat(end, 1, padding)],[ones(1, padding) 1:end repmat(end, 1, padding)],a)), 'valid'); end % Subsample A = A(1+floor(mod(end-1, factor)/2):factor:end,1+floor(mod(end-1, factor)/2):factor:end,:); end end function A = rgb2grey(A) A = cast(reshape(reshape(single(A), [], 3) * single([0.299; 0.587; 0.114]), size(A, 1), size(A, 2)), class(A)); %#ok<ZEROLIKE> end function A = check_greyscale(A) % Check if the image is greyscale if size(A, 3) == 3 && ... all(reshape(A(:,:,1) == A(:,:,2), [], 1)) && ... all(reshape(A(:,:,2) == A(:,:,3), [], 1)) A = A(:,:,1); % Save only one channel for 8-bit output end end function eps_remove_background(fname, count) % Remove the background of an eps file % Open the file fh = fopen(fname, 'r+'); if fh == -1 error('Not able to open file %s.', fname); end % Read the file line by line while count % Get the next line l = fgets(fh); if isequal(l, -1) break; % Quit, no rectangle found end % Check if the line contains the background rectangle if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +r[fe] *[\n\r]+', 'start'), 1) % Set the line to whitespace and quit l(1:regexp(l, '[\n\r]', 'start', 'once')-1) = ' '; fseek(fh, -numel(l), 0); fprintf(fh, l); % Reduce the count count = count - 1; end end % Close the file fclose(fh); end function b = isvector(options) b = options.pdf || options.eps; end function b = isbitmap(options) b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha; end % Helper function function A = make_cell(A) if ~iscell(A) A = {A}; end end function add_bookmark(fname, bookmark_text) % Adds a bookmark to the temporary EPS file after %%EndPageSetup % Read in the file fh = fopen(fname, 'r'); if fh == -1 error('File %s not found.', fname); end try fstrm = fread(fh, '*char')'; catch ex fclose(fh); rethrow(ex); end fclose(fh); % Include standard pdfmark prolog to maximize compatibility fstrm = strrep(fstrm, '%%BeginProlog', sprintf('%%%%BeginProlog\n/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse')); % Add page bookmark fstrm = strrep(fstrm, '%%EndPageSetup', sprintf('%%%%EndPageSetup\n[ /Title (%s) /OUT pdfmark',bookmark_text)); % Write out the updated file fh = fopen(fname, 'w'); if fh == -1 error('Unable to open %s for writing.', fname); end try fwrite(fh, fstrm, 'char*1'); catch ex fclose(fh); rethrow(ex); end fclose(fh); end function set_tick_mode(Hlims, ax) % Set the tick mode of linear axes to manual % Leave log axes alone as these are tricky M = get(Hlims, [ax 'Scale']); if ~iscell(M) M = {M}; end M = cellfun(@(c) strcmp(c, 'linear'), M); set(Hlims(M), [ax 'TickMode'], 'manual'); %set(Hlims(M), [ax 'TickLabelMode'], 'manual'); % this hides exponent label in HG2! end function change_rgb_to_cmyk(fname) % convert RGB => CMYK within an EPS file % Do post-processing on the eps file try % Read the EPS file into memory fstrm = read_write_entire_textfile(fname); % Replace all gray-scale colors fstrm = regexprep(fstrm, '\n([\d.]+) +GC\n', '\n0 0 0 ${num2str(1-str2num($1))} CC\n'); % Replace all RGB colors fstrm = regexprep(fstrm, '\n[0.]+ +[0.]+ +[0.]+ +RC\n', '\n0 0 0 1 CC\n'); % pure black fstrm = regexprep(fstrm, '\n([\d.]+) +([\d.]+) +([\d.]+) +RC\n', '\n${sprintf(''%.4g '',[1-[str2num($1),str2num($2),str2num($3)]/max([str2num($1),str2num($2),str2num($3)]),1-max([str2num($1),str2num($2),str2num($3)])])} CC\n'); % Overwrite the file with the modified contents read_write_entire_textfile(fname, fstrm); catch % never mind - leave as is... end end
github
mehta-lab/Instantaneous-PolScope-master
ghostscript.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/export_fig/ghostscript.m
7,492
utf_8
7a1e094c8bf153e1b239765ff6fd43df
function varargout = ghostscript(cmd) %GHOSTSCRIPT Calls a local GhostScript executable with the input command % % Example: % [status result] = ghostscript(cmd) % % Attempts to locate a ghostscript executable, finally asking the user to % specify the directory ghostcript was installed into. The resulting path % is stored for future reference. % % Once found, the executable is called with the input command string. % % This function requires that you have Ghostscript installed on your % system. You can download this from: http://www.ghostscript.com % % IN: % cmd - Command string to be passed into ghostscript. % % OUT: % status - 0 iff command ran without problem. % result - Output from ghostscript. % Copyright: Oliver Woodford, 2009-2015, Yair Altman 2015- %{ % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS. % Thanks to Nathan Childress for the fix to default location on 64-bit Windows systems. % 27/04/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and % Shaun Kline for pointing out the issue % 04/05/11 - Thanks to David Chorlian for pointing out an alternative % location for gs on linux. % 12/12/12 - Add extra executable name on Windows. Thanks to Ratish % Punnoose for highlighting the issue. % 28/06/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick % Steinbring for proposing the fix. % 24/10/13 - Fix error using GS 9.07 in Linux. Many thanks to Johannes % for the fix. % 23/01/14 - Add full path to ghostscript.txt in warning. Thanks to Koen % Vermeer for raising the issue. % 27/02/15 - If Ghostscript croaks, display suggested workarounds % 30/03/15 - Improved performance by caching status of GS path check, if ok % 14/05/15 - Clarified warning message in case GS path could not be saved % 29/05/15 - Avoid cryptic error in case the ghostscipt path cannot be saved (issue #74) %} try % Call ghostscript [varargout{1:nargout}] = system([gs_command(gs_path()) cmd]); catch err % Display possible workarounds for Ghostscript croaks url1 = 'https://github.com/altmany/export_fig/issues/12#issuecomment-61467998'; % issue #12 url2 = 'https://github.com/altmany/export_fig/issues/20#issuecomment-63826270'; % issue #20 hg2_str = ''; if using_hg2, hg2_str = ' or Matlab R2014a'; end fprintf(2, 'Ghostscript error. Rolling back to GS 9.10%s may possibly solve this:\n * <a href="%s">%s</a> ',hg2_str,url1,url1); if using_hg2 fprintf(2, '(GS 9.10)\n * <a href="%s">%s</a> (R2014a)',url2,url2); end fprintf('\n\n'); if ismac || isunix url3 = 'https://github.com/altmany/export_fig/issues/27'; % issue #27 fprintf(2, 'Alternatively, this may possibly be due to a font path issue:\n * <a href="%s">%s</a>\n\n',url3,url3); % issue #20 fpath = which(mfilename); if isempty(fpath), fpath = [mfilename('fullpath') '.m']; end fprintf(2, 'Alternatively, if you are using csh, modify shell_cmd from "export..." to "setenv ..."\nat the bottom of <a href="matlab:opentoline(''%s'',174)">%s</a>\n\n',fpath,fpath); end rethrow(err); end end function path_ = gs_path % Return a valid path % Start with the currently set path path_ = user_string('ghostscript'); % Check the path works if check_gs_path(path_) return end % Check whether the binary is on the path if ispc bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'}; else bin = {'gs'}; end for a = 1:numel(bin) path_ = bin{a}; if check_store_gs_path(path_) return end end % Search the obvious places if ispc default_location = 'C:\Program Files\gs\'; dir_list = dir(default_location); if isempty(dir_list) default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems dir_list = dir(default_location); end executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'}; ver_num = 0; % If there are multiple versions, use the newest for a = 1:numel(dir_list) ver_num2 = sscanf(dir_list(a).name, 'gs%g'); if ~isempty(ver_num2) && ver_num2 > ver_num for b = 1:numel(executable) path2 = [default_location dir_list(a).name executable{b}]; if exist(path2, 'file') == 2 path_ = path2; ver_num = ver_num2; end end end end if check_store_gs_path(path_) return end else executable = {'/usr/bin/gs', '/usr/local/bin/gs'}; for a = 1:numel(executable) path_ = executable{a}; if check_store_gs_path(path_) return end end end % Ask the user to enter the path while true if strncmp(computer, 'MAC', 3) % Is a Mac % Give separate warning as the uigetdir dialogue box doesn't have a % title uiwait(warndlg('Ghostscript not found. Please locate the program.')) end base = uigetdir('/', 'Ghostcript not found. Please locate the program.'); if isequal(base, 0) % User hit cancel or closed window break; end base = [base filesep]; %#ok<AGROW> bin_dir = {'', ['bin' filesep], ['lib' filesep]}; for a = 1:numel(bin_dir) for b = 1:numel(bin) path_ = [base bin_dir{a} bin{b}]; if exist(path_, 'file') == 2 if check_store_gs_path(path_) return end end end end end error('Ghostscript not found. Have you installed it from www.ghostscript.com?'); end function good = check_store_gs_path(path_) % Check the path is valid good = check_gs_path(path_); if ~good return end % Update the current default path to the path found if ~user_string('ghostscript', path_) filename = fullfile(fileparts(which('user_string.m')), '.ignore', 'ghostscript.txt'); warning('Path to ghostscript installation could not be saved in %s (perhaps a permissions issue). You can manually create this file and set its contents to %s, to improve performance in future invocations (this warning is safe to ignore).', filename, path_); return end end function good = check_gs_path(path_) persistent isOk if isempty(path_) isOk = false; elseif ~isequal(isOk,true) % Check whether the path is valid [status, message] = system([gs_command(path_) '-h']); %#ok<ASGLU> isOk = status == 0; end good = isOk; end function cmd = gs_command(path_) % Initialize any required system calls before calling ghostscript % TODO: in Unix/Mac, find a way to determine whether to use "export" (bash) or "setenv" (csh/tcsh) shell_cmd = ''; if isunix shell_cmd = 'export LD_LIBRARY_PATH=""; '; % Avoids an error on Linux with GS 9.07 end if ismac shell_cmd = 'export DYLD_LIBRARY_PATH=""; '; % Avoids an error on Mac with GS 9.07 end % Construct the command string cmd = sprintf('%s"%s" ', shell_cmd, path_); end
github
mehta-lab/Instantaneous-PolScope-master
fix_lines.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/export_fig/fix_lines.m
6,290
utf_8
8437006b104957762090e3d875688cb6
%FIX_LINES Improves the line style of eps files generated by print % % Examples: % fix_lines fname % fix_lines fname fname2 % fstrm_out = fixlines(fstrm_in) % % This function improves the style of lines in eps files generated by % MATLAB's print function, making them more similar to those seen on % screen. Grid lines are also changed from a dashed style to a dotted % style, for greater differentiation from dashed lines. % % The function also places embedded fonts after the postscript header, in % versions of MATLAB which place the fonts first (R2006b and earlier), in % order to allow programs such as Ghostscript to find the bounding box % information. % %IN: % fname - Name or path of source eps file. % fname2 - Name or path of destination eps file. Default: same as fname. % fstrm_in - File contents of a MATLAB-generated eps file. % %OUT: % fstrm_out - Contents of the eps file with line styles fixed. % Copyright: (C) Oliver Woodford, 2008-2014 % The idea of editing the EPS file to change line styles comes from Jiro % Doke's FIXPSLINESTYLE (fex id: 17928) % The idea of changing dash length with line width came from comments on % fex id: 5743, but the implementation is mine :) % Thank you to Sylvain Favrot for bringing the embedded font/bounding box % interaction in older versions of MATLAB to my attention. % Thank you to D Ko for bringing an error with eps files with tiff previews % to my attention. % Thank you to Laurence K for suggesting the check to see if the file was % opened. % 01/03/15: Issue #20: warn users if using this function in HG2 (R2014b+) % 27/03/15: Fixed out of memory issue with enormous EPS files (generated by print() with OpenGL renderer), related to issue #39 function fstrm = fix_lines(fstrm, fname2) % Issue #20: warn users if using this function in HG2 (R2014b+) if using_hg2 warning('export_fig:hg2','The fix_lines function should not be used in this Matlab version.'); end if nargout == 0 || nargin > 1 if nargin < 2 % Overwrite the input file fname2 = fstrm; end % Read in the file fstrm = read_write_entire_textfile(fstrm); end % Move any embedded fonts after the postscript header if strcmp(fstrm(1:15), '%!PS-AdobeFont-') % Find the start and end of the header ind = regexp(fstrm, '[\n\r]%!PS-Adobe-'); [ind2, ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+'); % Put the header first if ~isempty(ind) && ~isempty(ind2) && ind(1) < ind2(1) fstrm = fstrm([ind(1)+1:ind2(1) 1:ind(1) ind2(1)+1:end]); end end % Make sure all line width commands come before the line style definitions, % so that dash lengths can be based on the correct widths % Find all line style sections ind = [regexp(fstrm, '[\n\r]SO[\n\r]'),... % This needs to be here even though it doesn't have dots/dashes! regexp(fstrm, '[\n\r]DO[\n\r]'),... regexp(fstrm, '[\n\r]DA[\n\r]'),... regexp(fstrm, '[\n\r]DD[\n\r]')]; ind = sort(ind); % Find line width commands [ind2, ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]'); % Go through each line style section and swap with any line width commands % near by b = 1; m = numel(ind); n = numel(ind2); for a = 1:m % Go forwards width commands until we pass the current line style while b <= n && ind2(b) < ind(a) b = b + 1; end if b > n % No more width commands break; end % Check we haven't gone past another line style (including SO!) if a < m && ind2(b) > ind(a+1) continue; end % Are the commands close enough to be confident we can swap them? if (ind2(b) - ind(a)) > 8 continue; end % Move the line style command below the line width command fstrm(ind(a)+1:ind3(b)) = [fstrm(ind(a)+4:ind3(b)) fstrm(ind(a)+1:ind(a)+3)]; b = b + 1; end % Find any grid line definitions and change to GR format % Find the DO sections again as they may have moved ind = int32(regexp(fstrm, '[\n\r]DO[\n\r]')); if ~isempty(ind) % Find all occurrences of what are believed to be axes and grid lines ind2 = int32(regexp(fstrm, '[\n\r] *\d* *\d* *mt *\d* *\d* *L[\n\r]')); if ~isempty(ind2) % Now see which DO sections come just before axes and grid lines ind2 = repmat(ind2', [1 numel(ind)]) - repmat(ind, [numel(ind2) 1]); ind2 = any(ind2 > 0 & ind2 < 12); % 12 chars seems about right ind = ind(ind2); % Change any regions we believe to be grid lines to GR fstrm(ind+1) = 'G'; fstrm(ind+2) = 'R'; end end % Define the new styles, including the new GR format % Dot and dash lengths have two parts: a constant amount plus a line width % variable amount. The constant amount comes after dpi2point, and the % variable amount comes after currentlinewidth. If you want to change % dot/dash lengths for a one particular line style only, edit the numbers % in the /DO (dotted lines), /DA (dashed lines), /DD (dot dash lines) and % /GR (grid lines) lines for the style you want to change. new_style = {'/dom { dpi2point 1 currentlinewidth 0.08 mul add mul mul } bdef',... % Dot length macro based on line width '/dam { dpi2point 2 currentlinewidth 0.04 mul add mul mul } bdef',... % Dash length macro based on line width '/SO { [] 0 setdash 0 setlinecap } bdef',... % Solid lines '/DO { [1 dom 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dotted lines '/DA { [4 dam 1.5 dam] 0 setdash 0 setlinecap } bdef',... % Dashed lines '/DD { [1 dom 1.2 dom 4 dam 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dot dash lines '/GR { [0 dpi2point mul 4 dpi2point mul] 0 setdash 1 setlinecap } bdef'}; % Grid lines - dot spacing remains constant % Construct the output % This is the original (memory-intensive) code: %first_sec = strfind(fstrm, '% line types:'); % Isolate line style definition section %[second_sec, remaining] = strtok(fstrm(first_sec+1:end), '/'); %[remaining, remaining] = strtok(remaining, '%'); %fstrm = [fstrm(1:first_sec) second_sec sprintf('%s\r', new_style{:}) remaining]; fstrm = regexprep(fstrm,'(% line types:.+?)/.+?%',['$1',sprintf('%s\r',new_style{:}),'%']); % Write the output file if nargout == 0 || nargin > 1 read_write_entire_textfile(fname2, fstrm); end end
github
mehta-lab/Instantaneous-PolScope-master
movieDataGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/movieDataGUI.m
14,080
utf_8
4dd1aefb597084a14d2c9a2ce779d250
function varargout = movieDataGUI(varargin) % MOVIEDATAGUI M-file for movieDataGUI.fig % MOVIEDATAGUI, by itself, creates a new MOVIEDATAGUI or raises the existing % singleton*. % % H = MOVIEDATAGUI returns the handle to a new MOVIEDATAGUI or the handle to % the existing singleton*. % % MOVIEDATAGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in MOVIEDATAGUI.M with the given input arguments. % % MOVIEDATAGUI('Property','Value',...) creates a new MOVIEDATAGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before movieDataGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to movieDataGUI_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 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help movieDataGUI % Last Modified by GUIDE v2.5 12-Mar-2012 14:01:36 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @movieDataGUI_OpeningFcn, ... 'gui_OutputFcn', @movieDataGUI_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 movieDataGUI is made visible. function movieDataGUI_OpeningFcn(hObject, eventdata, handles, varargin) % % movieDataGUI('mainFig', handles.figure1) - call from movieSelector % movieDataGUI(MD) - MovieData viewer % % Useful tools: % % User Data: % % userData.channels - array of Channel objects % userData.mainFig - handle of movie selector GUI % userData.handles_main - 'handles' of movie selector GUI % % userData.setChannelFig - handle of channel set-up figure % userData.iconHelpFig - handle of help dialog % % NOTE: If movieDataGUI is under the "Overview" mode, additionally, % % userData.MD - the handle of selected MovieData object % % % Input check ip = inputParser; ip.addRequired('hObject',@ishandle); ip.addRequired('eventdata',@(x) isstruct(x) || isempty(x)); ip.addRequired('handles',@isstruct); ip.addOptional('MD',[],@(x) isa(x,'MovieData')); ip.addParamValue('mainFig',-1,@ishandle); ip.parse(hObject,eventdata,handles,varargin{:}) % Store inpu userData = get(handles.figure1, 'UserData'); userData.MD=ip.Results.MD; userData.mainFig=ip.Results.mainFig; [copyright openHelpFile] = userfcn_softwareConfig(handles); set(handles.text_copyright, 'String', copyright) % Set channel object array userData.channels = []; % Load help icon from dialogicons.mat userData = loadLCCBIcons(userData); supermap(1,:) = get(hObject,'color'); userData.colormap = supermap; set(handles.figure1,'CurrentAxes',handles.axes_help); Img = image(userData.questIconData); set(hObject,'colormap',supermap); set(gca, 'XLim',get(Img,'XData'),'YLim',get(Img,'YData'),... 'visible','off'); set(Img,'ButtonDownFcn',@icon_ButtonDownFcn); if openHelpFile set(Img, 'UserData', struct('class', mfilename)) end if ~isempty(userData.MD), userData.channels = userData.MD.channels_; set(handles.listbox_channel, 'String', userData.MD.getChannelPaths) % GUI setting set(handles.pushbutton_delete, 'Enable', 'off') set(handles.pushbutton_add, 'Enable', 'off') set(handles.pushbutton_output, 'Enable', 'off') set(hObject, 'Name', 'Movie Detail') set(handles.edit_path,'String', userData.MD.getFullPath) set(handles.edit_output, 'String', userData.MD.outputDirectory_) set(handles.edit_notes, 'String', userData.MD.notes_) % GUI setting - parameters propNames={'pixelSize_','timeInterval_','numAperture_','camBitdepth_'}; validProps = ~cellfun(@(x) isempty(userData.MD.(x)),propNames); propNames=propNames(validProps); cellfun(@(x) set(handles.(['edit_' x(1:end-1)]),'Enable','off',... 'String',userData.MD.(x)),propNames) end % Choose default command line output for movieDataGUI handles.output = hObject; % Update handles structure set(handles.figure1,'UserData',userData) guidata(hObject, handles); % UIWAIT makes movieDataGUI wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = movieDataGUI_OutputFcn(~, ~, 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 pushbutton_cancel. function pushbutton_cancel_Callback(~, ~, handles) % hObject handle to pushbutton_cancel (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) delete(handles.figure1); % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) userData = get(handles.figure1,'UserData'); % Verify channels are given if ~isfield(userData, 'channels') || isempty(userData.channels) errordlg('Please provide at least one channel path.',... 'Empty Channel','modal'); return; end assert(isa(userData.channels(1), 'Channel'),'User-defined: userData.channels are not of class ''Channel''') % Check output path outputDir = get(handles.edit_output, 'String'); if isempty(outputDir) || ~exist(outputDir, 'dir') errordlg('Please provide a valid output path to save your results.', ... 'Empty Output Path', 'modal'); return; end % Concatenate numerical parameters as movie options propNames={'pixelSize_','timeInterval_','numAperture_','camBitdepth_'}; propHandles = cellfun(@(x) handles.(['edit_' x(1:end-1)]),propNames); propStrings =get(propHandles,'String'); validProps = ~cellfun(@isempty,propStrings); if ~isempty(userData.MD), validProps=validProps & cellfun(@(x)isempty(userData.MD.(x)),propNames'); end propNames=propNames(validProps); propValues=num2cell(str2double(propStrings(validProps)))'; movieOptions = vertcat(propNames,propValues); movieOptions = reshape(movieOptions,1,numel(propNames)*2); % If movieDataGUI is under "Overview" mode if ~isempty(get(handles.edit_notes, 'String')) movieOptions=horzcat(movieOptions,'notes_',get(handles.edit_notes, 'String')); end if ~isempty(userData.MD), % Overview mode - edit existing MovieDat if ~isempty(movieOptions) try set(userData.MD,movieOptions{:}); catch ME errormsg = sprintf([ME.message '.\n\nMovie edition failed.']); errordlg(errormsg, 'User Input Error','modal'); return; end end % Create a pointer to the MovieData object (to use the same % sanityCheck command later) MD=userData.MD; else % Create Movie Data try MD = MovieData(userData.channels, outputDir, movieOptions{:}); catch ME errormsg = sprintf([ME.message '.\n\nMovie creation failed.']); errordlg(errormsg, 'User Input Error','modal'); return; end end try MD.sanityCheck; catch ME delete(MD); errormsg = sprintf('%s.\n\nPlease check your movie data. Movie data is not saved.',ME.message); errordlg(errormsg,'Channel Error','modal'); return; end % If new MovieData was created (from movieSelectorGUI) if ishandle(userData.mainFig), % Retrieve main window userData userData_main = get(userData.mainFig, 'UserData'); % Check if files in movie list are saved in the same file handles_main = guidata(userData.mainFig); contentlist = get(handles_main.listbox_movie, 'String'); movieDataFullPath = MD.getFullPath; if any(strcmp(movieDataFullPath, contentlist)) errordlg('Cannot overwrite a movie data file which is already in the movie list. Please choose another file name or another path.','Error','modal'); return end % Append MovieData object to movie selector panel userData_main.MD = cat(2, reshape(userData_main.MD,1,[]), MD); set(userData.mainFig, 'UserData', userData_main) movieSelectorGUI('refreshDisplay',userData.mainFig,eventdata,guidata(userData.mainFig)); end % Delete current window delete(handles.figure1) function edit_property_Callback(hObject, eventdata, handles) set(hObject,'BackgroundColor',[1 1 1]) if isempty(get(hObject,'String')), return; end propTag = get(hObject,'Tag'); propName = [propTag(length('edit_')+1:end) '_']; propValue = str2double(get(hObject,'String')); if ~MovieData.checkValue(propName,propValue) warndlg('Invalid property value','Setting Error','modal'); set(hObject,'BackgroundColor',[1 .8 .8]); return end % --- Executes on button press in pushbutton_delete. function pushbutton_delete_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'Userdata'); contents = get(handles.listbox_channel,'String'); % Return if list is empty if isempty(contents), return; end iChan = get(handles.listbox_channel,'Value'); % Delete channel object delete(userData.channels(iChan)) userData.channels(iChan) = []; contents(iChan) = [ ]; set(handles.listbox_channel,'String',contents); % Point 'Value' to the second last item in the list once the % last item has been deleted set(handles.listbox_channel,'Value',max(1,min(iChan,length(contents)))); set(handles.figure1, 'Userdata', userData) guidata(hObject, handles); % --- Executes on button press in pushbutton_add. function pushbutton_add_Callback(hObject, eventdata, handles) set(handles.listbox_channel, 'Value', 1) userData = get(handles.figure1, 'UserData'); if ishandle(userData.mainFig), handles_main = guidata(userData.mainFig); userData_main = get(handles_main.figure1, 'UserData'); userDir =userData_main.userDir; else userDir=pwd; end path = uigetdir(userDir, 'Add Channels ...'); if path == 0, return; end % Get current list contents = get(handles.listbox_channel,'String'); if any(strcmp(contents,path)) warndlg('This directory has been selected! Please select a differenct directory.',... 'Warning','modal'); return; end % Create path object and save it to userData try newChannel= Channel(path); newChannel.sanityCheck(); catch ME errormsg = sprintf('%s.\n\nPlease check this is valid channel.',ME.message); errordlg(errormsg,'Channel Error','modal'); return end % Refresh listbox_channel userData.channels = cat(2, userData.channels, newChannel); contents{end+1} = path; set(handles.listbox_channel,'string',contents); if ishandle(userData.mainFig), userData_main.userDir = fileparts(path); set(handles_main.figure1, 'UserData', userData_main) end set(handles.figure1, 'Userdata', userData) guidata(hObject, handles); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); if isfield(userData, 'iconHelpFig') && ishandle(userData.iconHelpFig) delete(userData.iconHelpFig) end % --- Executes on button press in pushbutton_output. function pushbutton_output_Callback(hObject, eventdata, handles) pathname = uigetdir(pwd,'Select a directory to store the processes output'); if isnumeric(pathname), return; end set(handles.edit_output, 'String', pathname); % --- Executes on button press in pushbutton_setting_chan. function pushbutton_setting_chan_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); if isempty(userData.channels), return; end assert(isa(userData.channels(1), 'Channel'), 'User-defined: Not a valid ''Channel'' object'); userData.setChannelFig = channelGUI('mainFig', handles.figure1, 'modal'); set(handles.figure1,'UserData',userData); % --- Executes on button press in pushbutton_bfImport. function pushbutton_bfImport_Callback(hObject, eventdata, handles) assert(bfCheckJavaPath(), 'Could not load the Bio-Formats library'); % Note: list of supported formats could be retrieved using % loci.formats.tools.PrintFormatTable class [file path] = uigetfile('Select image file to import.'); if isequal(file,0) || isequal(path,0), return; end % Import data into movie using bioformats MD = bfImport([path file],logical(get(handles.checkbox_uncompress,'Value'))); % Update movie selector interface userData=get(handles.figure1,'UserData'); if ishandle(userData.mainFig), % Append MovieData object to movie selector panel userData_main = get(userData.mainFig, 'UserData'); userData_main.MD = cat(2, reshape(userData_main.MD,1,[]), MD); set(userData.mainFig, 'UserData', userData_main) movieSelectorGUI('refreshDisplay',userData.mainFig,eventdata,guidata(userData.mainFig)) end % Relaunch this interface in preview mode movieDataGUI(MD(end));
github
mehta-lab/Instantaneous-PolScope-master
speckleDetectionProcessGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/speckleDetectionProcessGUI.m
9,854
utf_8
d31a208bcf8ea2c7e83c1e42c2ec9bf5
function varargout = speckleDetectionProcessGUI(varargin) % speckleDetectionProcessGUI M-file for speckleDetectionProcessGUI.fig % speckleDetectionProcessGUI, by itself, creates a new speckleDetectionProcessGUI or raises the existing % singleton*. % % H = speckleDetectionProcessGUI returns the handle to a new speckleDetectionProcessGUI or the handle to % the existing singleton*. % % speckleDetectionProcessGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in speckleDetectionProcessGUI.M with the given input arguments. % % speckleDetectionProcessGUI('Property','Value',...) creates a new speckleDetectionProcessGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before speckleDetectionProcessGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to speckleDetectionProcessGUI_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 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help speckleDetectionProcessGUI % Last Modified by GUIDE v2.5 03-Oct-2011 16:14:54 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @speckleDetectionProcessGUI_OpeningFcn, ... 'gui_OutputFcn', @speckleDetectionProcessGUI_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 speckleDetectionProcessGUI is made visible. function speckleDetectionProcessGUI_OpeningFcn(hObject, eventdata, handles, varargin) processGUI_OpeningFcn(hObject, eventdata, handles, varargin{:},'initChannel',1); % Set-up parameters userData=get(handles.figure1,'UserData'); funParams = userData.crtProc.funParams_; % Set-up parameters set(handles.listbox_maskChannels,'Value',funParams.MaskChannelIndex); set(handles.edit_alpha,'String',funParams.alpha); set(handles.popupmenu_speckleOrder,'Value',funParams.paramSpeckles(1)); set(handles.edit_percEdit,'String',funParams.paramSpeckles(2)); % Set the same channels for the masks as for the detectable channels props=get(handles.listbox_selectedChannels,{'String','UserData'}); set(handles.listbox_maskChannels,'String',props{1},'UserData',props{1}); % Store the image directories and filterSigma values (for multi-channel) userData.filterSigma = funParams.filterSigma; % Update status of noise parameter fields userData.noiseParams={'I0','sDN','GaussRatio'}; if ~isempty(userData.crtPackage.processes_{1}) cellfun(@(x)set(handles.(['edit_' x]),'Enable','off'),userData.noiseParams); set(handles.pushbutton_loadNoiseParameters,'Enable','off'); else cellfun(@(x)set(handles.(['edit_' x]),'String',funParams.(x)),userData.noiseParams); end set(handles.figure1, 'UserData', userData); % Update values of filter sigma and noise parameters listbox_selectedChannels_Callback(hObject,eventdata,handles); % Update GUI user data handles.output = hObject; guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = speckleDetectionProcessGUI_OutputFcn(~, ~, 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 pushbutton_cancel. function pushbutton_cancel_Callback(~, ~, handles) % Delete figure delete(handles.figure1); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, ~, handles) % Notify the package GUI that the setting panel is closed userData = get(handles.figure1, 'UserData'); if isfield(userData, 'helpFig') && ishandle(userData.helpFig) delete(userData.helpFig) end set(handles.figure1, 'UserData', userData); guidata(hObject,handles); % --- Executes on key press with focus on pushbutton_done and none of its controls. function pushbutton_done_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) % -------- Check user input -------- if isempty(get(handles.listbox_selectedChannels, 'String')) errordlg('Please select at least one input channel from ''Available Channels''.','Setting Error','modal') return; end if isempty(get(handles.listbox_maskChannels, 'Value')) errordlg('Please select at least one mask channel from ''Mask Channels''.','Setting Error','modal') return; end % -------- Process Sanity check -------- % ( only check underlying data ) userData = get(handles.figure1, 'UserData'); try userData.crtProc.sanityCheck; catch ME errordlg([ME.message 'Please double check your data.'],... 'Setting Error','modal'); return; end % Retrieve GUI-defined parameters channelIndex = get(handles.listbox_selectedChannels, 'Userdata'); funParams.ChannelIndex = channelIndex; maskChannelIndex = get(handles.listbox_maskChannels, 'Value'); funParams.MaskChannelIndex = maskChannelIndex; funParams.alpha=str2double(get(handles.edit_alpha, 'String')); funParams.paramSpeckles=[get(handles.popupmenu_speckleOrder,'Value')... str2double(get(handles.edit_percEdit, 'String'))]; % Save the filterSigma if different from psfSigma % In order not to override filterSigma in batch movie set up if ~isequal(userData.filterSigma,[userData.MD.channels_.psfSigma_]) funParams.filterSigma = userData.filterSigma; end if isempty(userData.crtPackage.processes_{1}) for i=1:numel(userData.noiseParams) funParams.(userData.noiseParams{i}) = ... str2num(get(handles.(['edit_' userData.noiseParams{i}]),'String')); %#ok<ST2NM> end end processGUI_ApplyFcn(hObject, eventdata, handles,funParams); % --- Executes on selection change in popupmenu_speckleOrder. function popupmenu_speckleOrder_Callback(hObject, eventdata, handles) if get(hObject,'Value')==1 set(handles.edit_percEdit,'Enable','off'); else set(handles.edit_percEdit,'Enable','on'); end % --- Executes on selection change in listbox_selectedChannels. function listbox_selectedChannels_Callback(hObject, eventdata, handles) % Read channel index userData = get(handles.figure1, 'UserData'); props = get(handles.listbox_selectedChannels, {'UserData','Value'}); chanIndx = props{1}(props{2}); set(handles.edit_filterSigma,'String',userData.filterSigma(chanIndx)); if ~isempty(userData.crtPackage.processes_{1}) if userData.crtPackage.processes_{1}.checkChannelOutput() [I0,sDN,GaussRatio] =userData.crtPackage.processes_{1}.loadChannelOutput(chanIndx); set(handles.edit_I0,'String',I0); set(handles.edit_sDN,'String',sDN); set(handles.edit_GaussRatio,'String',GaussRatio); else cellfun(@(x)set(handles.(['edit_' x]),'String','NA'),userData.noiseParams); end end function edit_filterSigma_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); % Retrieve the channel index props=get(handles.listbox_selectedChannels,{'UserData','Value'}); chanIndx = props{1}(props{2}); value = str2double(get(hObject, 'String')); if ~(value>0), % Reset old value set(hObject,'String',userData.filterSigma(chanIndx)) else % Update the sigma value in the stored array- userData.filterSigma(chanIndx) = value; guidata(hObject, handles); end % --- Executes on button press in pushbutton_loadNoiseParameters. function pushbutton_loadNoiseParameters_Callback(hObject, eventdata, handles) [file path]=uigetfile({'*.mat;*.MAT','Mat files (*.mat)'},... 'Select the file containing the noise model parameters'); if ~isequal(file,0) && ~isequal(path,0) noiseParams={'I0','sDN','GaussRatio'}; vars=whos(noiseParams{:},'-file',[path file]); if numel(vars)~=numel(noiseParams), errordlg('Please select a file containing valid noise model parameters'); return end s=load([path file],noiseParams{:}); for i=1:numel(noiseParams) set(handles.(['edit_' noiseParams{i}]),'String',s.(noiseParams{i})); end end
github
mehta-lab/Instantaneous-PolScope-master
flowTrackingProcessGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/flowTrackingProcessGUI.m
9,499
utf_8
33dffc0df71fa3ab79a0a90c1c389e95
function varargout = flowTrackingProcessGUI(varargin) % flowTrackingProcessGUI M-file for flowTrackingProcessGUI.fig % flowTrackingProcessGUI, by itself, creates a new flowTrackingProcessGUI or raises the existing % singleton*. % % H = flowTrackingProcessGUI returns the handle to a new flowTrackingProcessGUI or the handle to % the existing singleton*. % % flowTrackingProcessGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in flowTrackingProcessGUI.M with the given input arguments. % % flowTrackingProcessGUI('Property','Value',...) creates a new flowTrackingProcessGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before flowTrackingProcessGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to flowTrackingProcessGUI_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 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help flowTrackingProcessGUI % Last Modified by GUIDE v2.5 29-Nov-2011 10:45:04 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @flowTrackingProcessGUI_OpeningFcn, ... 'gui_OutputFcn', @flowTrackingProcessGUI_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 flowTrackingProcessGUI is made visible. function flowTrackingProcessGUI_OpeningFcn(hObject, eventdata, handles, varargin) processGUI_OpeningFcn(hObject, eventdata, handles, varargin{:},'initChannel',1); % Choose default command line output for noiseEstimationProcessGUI handles.output = hObject; % Parameter Setup userData = get(handles.figure1, 'UserData'); funParams = userData.crtProc.funParams_; userData.numParams = {'firstImage','lastImage','timeWindow','timeStepSize',... 'minCorLength','maxCorLength','edgeErodeWidth','maxFlowSpeed'}; cellfun(@(x) set(handles.(['edit_' x]),'String',funParams.(x)),userData.numParams); set(handles.edit_maxFlowSpeedNmMin,'String',... funParams.maxFlowSpeed*userData.MD.pixelSize_/userData.MD.timeInterval_*60); % Stationary background parameters substractBackground = (funParams.numStBgForAvg~=0); set(handles.checkbox_substractBackground,'Value',substractBackground) if substractBackground if funParams.numStBgForAvg==-1 set(handles.checkbox_useAllStBgImages,'Value',1); set(handles.edit_numStBgForAvg,'String','','Enable','off'); else set(handles.checkbox_useAllStBgImages,'Value',0); set(handles.edit_numStBgForAvg,'String',funParams.numStBgForAvg,... 'Enable','on'); end else set(handles.checkbox_useAllStBgImages,'Value',0,'Enable','off'); set(handles.edit_numStBgForAvg,'String','','Enable','off'); end % Outlier parameters detectOutliers = ~isempty(funParams.outlierThreshold); set(handles.checkbox_filterOutliers,'Value',detectOutliers); if detectOutliers set(handles.edit_outlierThreshold,'String',funParams.outlierThreshold,... 'Enable','on'); else set(handles.edit_outlierThreshold,'String','','Enable','off'); end % Update user data and GUI data set(hObject, 'UserData', userData); guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = flowTrackingProcessGUI_OutputFcn(~, ~, 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 pushbutton_cancel. function pushbutton_cancel_Callback(~, ~, handles) % Delete figure delete(handles.figure1); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, ~, handles) % Notify the package GUI that the setting panel is closed userData = get(handles.figure1, 'UserData'); if isfield(userData, 'helpFig') && ishandle(userData.helpFig) delete(userData.helpFig) end if isfield(userData, 'previewFig') && ishandle(userData.previewFig) delete(userData.previewFig) end set(handles.figure1, 'UserData', userData); guidata(hObject,handles); % --- Executes on key press with focus on pushbutton_done and none of its controls. function pushbutton_done_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end function pushbutton_done_Callback(hObject, eventdata, handles) % Input check userData = get(handles.figure1, 'UserData'); if isempty(get(handles.listbox_selectedChannels, 'String')) errordlg('Please select at least one input channel from ''Available Channels''.','Setting Error','modal') return; end % Process Sanity check ( only check underlying data ) try userData.crtProc.sanityCheck; catch ME errordlg([ME.message 'Please double check your data.'],... 'Setting Error','modal'); return; end % Retrieve GUI-defined parameters channelIndex = get (handles.listbox_selectedChannels, 'Userdata'); funParams.ChannelIndex = channelIndex; % Retrieve numeric parameters for i = 1:numel(userData.numParams), value = str2double(get(handles.(['edit_' userData.numParams{i}]),'String')); if isnan(value) || value<0 errordlg(['Please enter a valid value for '... get(handles.(['text_' userData.numParams{i}]),'String') '.'],... 'Setting Error','modal') return; end funParams.(userData.numParams{i})=value; end % Retrieve stationary background parameters if ~get(handles.checkbox_substractBackground,'Value') funParams.numStBgForAvg=0; else if get(handles.checkbox_useAllStBgImages,'Value') funParams.numStBgForAvg=0-1; else numStBgForAvg= str2double(get(handles.edit_numStBgForAvg,'String')); if isnan(numStBgForAvg) || numStBgForAvg<=0 errordlg(['Please enter a valid value for the '... get(handles.text_numStBgForAvg,'String') '.'],'Setting Error','modal'); return; end funParams.numStBgForAvg=numStBgForAvg; end end % Retrieve outlier parameters if get(handles.checkbox_filterOutliers,'Value') funParams.outlierThreshold=str2double(get(handles.edit_outlierThreshold,... 'String')); else funParams.outlierThreshold=[]; end % Set parameters and update main window setLastImage =@(x) parseProcessParams(x,struct('lastImage',... min(x.funParams_.lastImageNum,x.owner_.nFrames_))); processGUI_ApplyFcn(hObject, eventdata, handles,funParams); % --- Executes on button press in checkbox_filterOutliers. function checkbox_filterOutliers_Callback(hObject, eventdata, handles) if get(hObject,'Value') set(handles.edit_outlierThreshold,'Enable','on') else set(handles.edit_outlierThreshold,'Enable','off') end function edit_maxFlowSpeed_Callback(hObject, eventdata, handles) userData=get(handles.figure1,'UserData'); value=str2double(get(handles.edit_maxFlowSpeed,'String')); set(handles.edit_maxFlowSpeedNmMin,'String',... value*userData.MD.pixelSize_/userData.MD.timeInterval_*60); % --- Executes on button press in checkbox_substractBackground. function checkbox_substractBackground_Callback(hObject, eventdata, handles) if get(hObject,'Value'), set(handles.checkbox_useAllStBgImages,'Enable','on'); set(handles.edit_numStBgForAvg,'Enable','on'); else set(handles.checkbox_useAllStBgImages,'Value',0,'Enable','off'); set(handles.edit_numStBgForAvg,'String','','Enable','off'); end % --- Executes on button press in checkbox_useAllStBgImages. function checkbox_useAllStBgImages_Callback(hObject, eventdata, handles) if get(hObject,'Value'), set(handles.edit_numStBgForAvg,'String','','Enable','off'); else set(handles.edit_numStBgForAvg,'Enable','on'); end
github
mehta-lab/Instantaneous-PolScope-master
channelGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/channelGUI.m
11,289
utf_8
97d5a872f8f89ea40a13945e3f1e05ca
function varargout = channelGUI(varargin) % CHANNELGUI M-file for channelGUI.fig % CHANNELGUI, by itself, creates a new CHANNELGUI or raises the existing % singleton*. % % H = CHANNELGUI returns the handle to a new CHANNELGUI or the handle to % the existing singleton*. % % CHANNELGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in CHANNELGUI.M with the given input arguments. % % CHANNELGUI('Property','Value',...) creates a new CHANNELGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before channelGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to channelGUI_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 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help channelGUI % Last Modified by GUIDE v2.5 30-Jun-2011 15:53:11 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @channelGUI_OpeningFcn, ... 'gui_OutputFcn', @channelGUI_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 channelGUI is made visible. function channelGUI_OpeningFcn(hObject, ~, handles, varargin) % % channelGUI('mainFig', handles.figure1) - call from movieDataGUI % channelGUI(channelArray) - call from command line % channelGUI(..., 'modal') - call channelGUI as a modal window % % User Data: % % userData.channels - array of channel object % userData.selectedChannel - index of current channel % userData.mainFig - handle of movieDataGUI % userData.properties - structure array of properties % userData.propNames - list of modifiable properties % % userData.helpFig - handle of help window % [copyright openHelpFile] = userfcn_softwareConfig(handles); set(handles.text_copyright, 'String', copyright) userData = get(handles.figure1, 'UserData'); % Choose default command line output for channelGUI handles.output = hObject; % Load help icon from dialogicons.mat userData = loadLCCBIcons(userData); supermap(1,:) = get(hObject,'color'); userData.colormap = supermap; set(handles.figure1,'CurrentAxes',handles.axes_help); Img = image(userData.questIconData); set(hObject,'colormap',supermap); set(gca, 'XLim',get(Img,'XData'),'YLim',get(Img,'YData'),... 'visible','off'); set(Img,'ButtonDownFcn',@icon_ButtonDownFcn); if openHelpFile set(Img, 'UserData', struct('class', mfilename)) end if nargin > 3 if any(strcmp(varargin, 'mainFig')) % Called from movieDataGUI % Get userData.mainFig t = find(strcmp(varargin, 'mainFig')); userData.mainFig = varargin{t(end)+1}; % Get userData.channels userData_main = get(userData.mainFig, 'UserData'); assert(isa(userData_main.channels(1), 'Channel'), 'User-defined: No Channel object found.') userData.channels = userData_main.channels; % Get userData.selectedChannel handles_main = guidata(userData.mainFig); userData.selectedChannel = get(handles_main.listbox_channel, 'Value'); elseif isa(varargin{1}(1), 'Channel') % Called from command line userData.channels = varargin{1}; userData.selectedChannel = 1; else error('User-defined: Input parameters are incorrect.') end % Set as modal window if any(strcmp(varargin, 'modal')) set(hObject, 'WindowStyle', 'modal') end else error('User-defined: No proper input.') end % Set up imaging mode and flurophore pop-up menu modeString = vertcat({''},Channel.getImagingModes()); set(handles.popupmenu_imageType,'String',modeString); fluorophoreString = horzcat({''},Channel.getFluorophores()); set(handles.popupmenu_fluorophore,'String',fluorophoreString); % Read channel initial properties and store them in a structure propNames={'excitationWavelength_','emissionWavelength_',... 'exposureTime_','imageType_','fluorophore_'}; userData.isNumProp = @(x) x<4; for i=1:numel(userData.channels) for j=1:numel(propNames) userData.properties(i).(propNames{j})=... userData.channels(i).(propNames{j}); end end % Set up pop-up menu set(handles.popupmenu_channel, 'String', ... arrayfun(@(x)(['Channel ' num2str(x)]), 1:length(userData.channels), 'UniformOutput', false) ) set(handles.popupmenu_channel, 'Value', userData.selectedChannel) % Set up channel path and properties set(handles.figure1,'Visible','on'); set(handles.text_path, 'String', userData.channels(userData.selectedChannel).channelPath_) for i=1:numel(propNames) propValue = userData.properties(userData.selectedChannel).(propNames{i}); if userData.isNumProp(i) propHandle = handles.(['edit_' propNames{i}(1:end-1)]); guiProp = 'String'; guiValue = propValue; else propHandle = handles.(['popupmenu_' propNames{i}(1:end-1)]); guiProp = 'Value'; guiValue = find(strcmpi(propValue,get(propHandle,'String'))); if isempty(guiValue), guiValue=1; end end if ~isempty(propValue), enableState='inactive'; else enableState='on'; end set(propHandle,guiProp,guiValue,'Enable',enableState); end % Update handles structure set(handles.figure1,'UserData',userData) guidata(hObject, handles); % UIWAIT makes channelGUI wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = channelGUI_OutputFcn(~, ~, handles) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on selection change in popupmenu_channel. function popupmenu_channel_Callback(hObject, ~, handles) userData = get(handles.figure1, 'UserData'); if get(hObject,'Value') == userData.selectedChannel, return; end % Retrieve handles and names and save them propNames = fieldnames(userData.properties(1)); for i=1:numel(propNames) if userData.isNumProp(i) propHandle = handles.(['edit_' propNames{i}(1:end-1)]); guiValue = str2num(get(propHandle,'String')); else propHandle = handles.(['popupmenu_' propNames{i}(1:end-1)]); choices = get(propHandle,'String'); guiValue = choices{get(propHandle,'Value')}; end userData.properties(userData.selectedChannel).(propNames{i})=... guiValue; end % Update the selected channel path and properties propNames = fieldnames(userData.properties(1)); userData.selectedChannel=get(hObject,'Value'); set(handles.text_path, 'String', userData.channels(userData.selectedChannel).channelPath_) for i=1:numel(propNames) channelValue = userData.channels(userData.selectedChannel).(propNames{i}); if ~isempty(channelValue) propValue = channelValue; enableState = 'inactive'; else propValue = userData.properties(userData.selectedChannel).(propNames{i}); enableState = 'on'; end if userData.isNumProp(i) propHandle = handles.(['edit_' propNames{i}(1:end-1)]); guiProp = 'String'; guiValue = propValue; else propHandle = handles.(['popupmenu_' propNames{i}(1:end-1)]); guiProp = 'Value'; guiValue = find(strcmpi(propValue,get(propHandle,'String'))); if isempty(guiValue), guiValue=1; end end set(propHandle,guiProp,guiValue,'Enable',enableState); end set(handles.figure1,'UserData',userData) % --- Executes when edit field is changed. function edit_property_Callback(hObject, ~, handles) if ~isempty(get(hObject,'String')) % Read property value propTag = get(hObject,'Tag'); propName = [propTag(length('edit_')+1:end) '_']; propValue = str2double(get(hObject,'String')); % Test property value using the class static method if ~Channel.checkValue(propName,propValue) warndlg('Invalid property value','Setting Error','modal'); set(hObject,'BackgroundColor',[1 .8 .8]); set(handles.popupmenu_channel, 'Enable','off'); return end end set(hObject,'BackgroundColor',[1 1 1]); set(handles.popupmenu_channel, 'Enable','on'); % --- Executes on button press in pushbutton_cancel. function pushbutton_cancel_Callback(~, ~, handles) delete(handles.figure1) % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); % Retrieve names and handles of non-empty fields propNames = fieldnames(userData.properties(1)); for i=1:numel(propNames) if userData.isNumProp(i) propHandle = handles.(['edit_' propNames{i}(1:end-1)]); guiValue = str2num(get(propHandle,'String')); else propHandle = handles.(['popupmenu_' propNames{i}(1:end-1)]); choices = get(propHandle,'String'); guiValue = choices{get(propHandle,'Value')}; end userData.properties(userData.selectedChannel).(propNames{i})=... guiValue; end % Set properties to channel objects for i=1:numel(userData.channels) set(userData.channels(i),userData.properties(i)); end set(handles.figure1,'UserData',userData) delete(handles.figure1) % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on selection change in popupmenu_fluorophore. function popupmenu_fluorophore_Callback(hObject, eventdata, handles) % Retrieve selected fluorophore name props=get(hObject,{'String','Value'}); fluorophore = props{1}{props{2}}; isFluorophoreValid = ~isempty(fluorophore); isLambdaEditable = strcmp(get(handles.edit_emissionWavelength,'Enable'),'on'); if ~isFluorophoreValid || ~isLambdaEditable,return; end % Set the value of the emission wavelength lambda = name2wavelength(fluorophore)*1e9; set(handles.edit_emissionWavelength,'String',lambda);
github
mehta-lab/Instantaneous-PolScope-master
MovieObject.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/MovieObject.m
19,558
utf_8
a2b7ca9100db285b63292955b45073f5
classdef MovieObject < hgsetget % Abstract interface defining the analyis tools for movie objects % (movies, movie lists...) % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Sebastien Besson, Jan 2012 properties (SetAccess = protected) createTime_ % Object creation time processes_ = {}; % Cell array of process objects packages_ = {}; % Cell array of process packaged end properties outputDirectory_ =''; % Default output directory for all processes notes_ % User's notes end methods %% Set/get methods function set.outputDirectory_(obj, path) % Set the ouput endingFilesepToken = [regexptranslate('escape',filesep) '$']; path = regexprep(path,endingFilesepToken,''); obj.checkPropertyValue('outputDirectory_',path); obj.outputDirectory_=path; end function checkPropertyValue(obj,property, value) % Check if a property/value pair can be set up % Test if the property is unchanged if isequal(obj.(property),value), return; end propName = regexprep(regexprep(property,'(_\>)',''),'([A-Z])',' ${lower($1)}'); % Test if the property is writable assert(obj.checkProperty(property),'lccb:set:readonly',... ['The ' propName ' has been set previously and cannot be changed!']); % Test if the supplied value is valid assert(obj.checkValue(property,value),'lccb:set:invalid',... ['The supplied ' propName ' is invalid!']); end function status = checkProperty(obj,property) % Returns true/false if the non-empty property is writable status = isempty(obj.(property)); if status, return; end % Allow user to rewrite on some properties (paths, outputDirectory, notes) switch property case {'notes_'}; status = true; case {'outputDirectory_',obj.getPathProperty,obj.getFilenameProperty}; stack = dbstack; if any(cellfun(@(x)strcmp(x,[class(obj) '.sanityCheck']),{stack.name})), status = true; end end end function set.notes_(obj, value) obj.checkPropertyValue('notes_',value); obj.notes_=value; end function value = getPath(obj) value = obj.(obj.getPathProperty); end function setPath(obj, value) obj.(obj.getPathProperty) = value; end function value = getFilename(obj) value = obj.(obj.getFilenameProperty); end function setFilename(obj, value) obj.(obj.getFilenameProperty) = value; end function fullPath = getFullPath(obj, askUser) % Return full path of the movie object if nargin < 2, askUser = true; end hasEmptyComponent = isempty(obj.getPath) || isempty(obj.getFilename); hasDisplay = feature('ShowFigureWindows'); if any(hasEmptyComponent) && askUser && hasDisplay if ~isempty(obj.getPath), defaultDir = obj.getPath; elseif ~isempty(obj.outputDirectory_) defaultDir = obj.outputDirectory_; else defaultDir = pwd; end % Open a dialog box asking where to save the movie object movieClass = class(obj); objName = regexprep(movieClass,'([A-Z])',' ${lower($1)}'); defaultName = regexprep(movieClass,'(^[A-Z])','${lower($1)}'); [filename,path] = uiputfile('*.mat',['Find a place to save your' objName],... [defaultDir filesep defaultName '.mat']); if ~any([filename,path]), fullPath=[]; else fullPath = [path, filename]; % Set new path and filename obj.setPath(path); obj.setFilename(filename); end else fullPath = fullfile(obj.getPath(), obj.getFilename()); end end %% Functions to manipulate process object array function addProcess(obj, newprocess) % Add new process in process list assert(isa(newprocess,'Process')); obj.processes_ = horzcat(obj.processes_, {newprocess}); end function proc = getProcess(obj, i) assert(isscalar(i) && ismember(i,1:numel(obj.processes_))); proc = obj.processes_{i}; end function deleteProcess(obj, process) % Delete given process object in process list % % Input: % process - Process object or index of process to be % deleted in movie data's process list % Check input if isa(process, 'Process') pid = obj.getProcessIndex(process,1,Inf,false); assert(~isempty(pid),'The given process is not in current movie processes list.') assert(length(pid)==1,'More than one process of this type exists in movie processes list.') elseif isscalar(process) && ismember(process,1:numel(obj.processes_)) pid = process; else error('Please provide a Process object or a valid process index of movie data processes list.') end % Check process validity process = obj.processes_{pid}; isValid = ~isempty(process) && process.isvalid; if isValid % Unassociate process from parent packages [packageID procID] = process.getPackage(); for i=1:numel(packageID) obj.packages_{packageID(i)}.setProcess(procID(i),[]); end end if isValid && isa(process.owner_, 'MovieData') % Remove process from list for owner and descendants for movie = [process.owner_ process.owner_.getDescendants()] id = find(cellfun(@(x) isequal(x,process), movie.processes_),1); if ~isempty(id), movie.processes_(id) = [ ]; end end else obj.processes_(pid) = [ ]; end % Delete process object if isValid, delete(process); end end function replaceProcess(obj, pid, newprocess) % Replace process object by another in the analysis list % Input check ip=inputParser; ip.addRequired('pid',@(x) isscalar(x) && ismember(x,1:numel(obj.processes_)) || isa(x,'Process')); ip.addRequired('newprocess',@(x) isa(x,'Process')); ip.parse(pid, newprocess); % Retrieve process index if input is of process type if isa(pid, 'Process') pid = find(cellfun(@(x)(isequal(x,pid)),obj.processes_)); assert(isscalar(pid)) end [packageID procID] = obj.processes_{pid}.getPackage; % Check new process is compatible with parent packages if ~isempty(packageID) for i=1:numel(packageID) isValid = isa(newprocess,... obj.packages_{packageID(i)}.getProcessClassNames{procID(i)}); assert(isValid, 'Package class compatibility prevents process process replacement'); end end % Delete old process and replace it by the new one oldprocess = obj.processes_{pid}; if isa(oldprocess.owner_, 'MovieData') % Remove process from list for owner and descendants for movie = [oldprocess.owner_ oldprocess.owner_.getDescendants()] id = find(cellfun(@(x) isequal(x, oldprocess), movie.processes_),1); if ~isempty(id), movie.processes_{id} = newprocess; end end else obj.processes_{pid} = newprocess; end delete(oldprocess); % Associate new process in parent packages if ~isempty(packageID), for i=1:numel(packageID) obj.packages_{packageID(i)}.setProcess(procID(i),newprocess); end end end function iProc = getProcessIndex(obj, type, varargin) if isa(type, 'Process'), type = class(type); end iProc = getIndex(obj.processes_, type, varargin{:}); end %% Functions to manipulate package object array function addPackage(obj, newpackage) % Add package object to the package list assert(isa(newpackage,'Package')); obj.packages_ = horzcat(obj.packages_ , {newpackage}); end function package = getPackage(obj, i) assert(isscalar(i) && ismember(i,1:numel(obj.packages_))); package = obj.packages_{i}; end function deletePackage(obj, package) % Remove package object from the package list % Check input if isa(package, 'Package') pid = find(cellfun(@(x)isequal(x, package), obj.packages_)); assert(~isempty(pid),'The given package is not in current movie packages list.') assert(length(pid)==1,'More than one package of this type exists in movie packages list.') elseif isscalar(package) && ismember(package,1:numel(obj.packages_)) pid = package; else error('Please provide a Package object or a valid package index of movie data processes list.') end % Check package validity package = obj.packages_{pid}; isValid = ~isempty(package) && package.isvalid; if isValid && isa(package.owner_, 'MovieData') % Remove package from list for owner and descendants for movie = [package.owner_ package.owner_.getDescendants()] id = find(cellfun(@(x) isequal(x,package), movie.packages_),1); if ~isempty(id), movie.packages_(id) = [ ]; end end else obj.packages_(pid) = [ ]; end % Delete package object if isValid, delete(package); end end function iPackage = getPackageIndex(obj, type, varargin) if isa(type, 'Package'), type = class(type); end iPackage = getIndex(obj.packages_, type, varargin{:}); end %% Miscellaneous functions function askUser = sanityCheck(obj, path, filename,askUser) % Check sanity of movie object % % Check if the path and filename stored in the movie object are % the same as the input if any. If they differ, call the % movie object relocation routine. Use a dialog interface to ask % for relocation if askUser is set as true and return askUser. if nargin < 4, askUser = true; end if nargin > 1 && ~isempty(path) % Remove ending file separators from paths endingFilesepToken = [regexptranslate('escape',filesep) '$']; oldPath = regexprep(obj.getPath(),endingFilesepToken,''); newPath = regexprep(path,endingFilesepToken,''); % If different path if ~strcmp(oldPath, newPath) confirmRelocate = 'Yes to all'; if askUser if isa(obj,'MovieData') type='movie'; components='channels'; elseif isa(obj,'MovieList') type='movie list'; components='movies'; else error('Non supported movie object'); end relocateMsg=sprintf(['The %s and its analysis will be relocated from \n%s to \n%s.\n'... 'Should I relocate its %s as well?'],type,oldPath,newPath,components); confirmRelocate = questdlg(relocateMsg,['Relocation - ' type],'Yes to all','Yes','No','Yes'); end full = ~strcmp(confirmRelocate,'No'); askUser = ~strcmp(confirmRelocate,'Yes to all'); % Get old and new relocation directories [oldRootDir newRootDir]=getRelocationDirs(oldPath,newPath); oldRootDir = regexprep(oldRootDir,endingFilesepToken,''); newRootDir = regexprep(newRootDir,endingFilesepToken,''); % Relocate the object fprintf(1,'Relocating analysis from %s to %s\n',oldRootDir,newRootDir); obj.relocate(oldRootDir,newRootDir,full); end end if nargin > 2 && ~isempty(filename), obj.setFilename(filename); end if isempty(obj.outputDirectory_), warning('lccb:MovieObject:sanityCheck',... 'Empty output directory!'); end end function relocate(obj,oldRootDir,newRootDir) % Relocate all analysis paths of the movie object % % The relocate method automatically relocates the output directory, % as well as the paths in each process and package of the movie % assuming the internal architecture of the project is conserved. % Relocate output directory and set the ne movie path obj.outputDirectory_=relocatePath(obj.outputDirectory_,oldRootDir,newRootDir); obj.setPath(relocatePath(obj.getPath,oldRootDir,newRootDir)); % Relocate the processes for i=1:numel(obj.processes_), obj.processes_{i}.relocate(oldRootDir,newRootDir); end % Relocate the packages for i=1:numel(obj.packages_), obj.packages_{i}.relocate(oldRootDir,newRootDir); end end function reset(obj) % Reset the analysis of the movie object obj.processes_={}; obj.packages_={}; end end methods(Static) function obj = load(moviepath,varargin) % Load a movie object from a path % Check the path is a valid file assert(~isempty(ls(moviepath)),'lccb:movieObject:load', 'File does not exist.'); % Retrieve the absolute path [~,f]= fileattrib(moviepath); moviepath=f.Name; if strcmpi(moviepath(end-3:end),'.mat') % Import movie object from MAT file try % List variables in the path vars = whos('-file',moviepath); catch whosException ME = MException('lccb:movieObject:load', 'Fail to open file. Make sure it is a MAT file.'); ME = ME.addCause(whosException); throw(ME); end % Check if a single movie object is in the variables isMovie = cellfun(@(x) any(strcmp(superclasses(x),'MovieObject')),{vars.class}); assert(any(isMovie),'lccb:movieObject:load', ... 'No movie object is found in selected MAT file.'); assert(sum(isMovie)==1,'lccb:movieObject:load', ... 'Multiple movie objects are found in selected MAT file.'); % Load movie object data = load(moviepath,'-mat',vars(isMovie).name); obj= data.(vars(isMovie).name); % Set session if nargin>1 && isa(varargin{1},'omero.api.ServiceFactoryPrxHelper') obj.setSession(varargin{1}); end % Perform sanityCheck using the input path [moviePath,movieName,movieExt]=fileparts(moviepath); obj.sanityCheck(moviePath,[movieName movieExt],varargin{:}); else % Assume proprietary file - use Bioformats library obj=bfImport(moviepath,varargin{:}); end end function validator = getPropertyValidator(property) validator=[]; if ismember(property,{'outputDirectory_','notes_'}) validator=@ischar; end end end methods (Static,Abstract) getPathProperty() getFilenameProperty() end end function iProc = getIndex(list, type, varargin) % Find the index of a object of given class % Input check ip = inputParser; ip.addRequired('list',@iscell); ip.addRequired('type',@ischar); ip.addOptional('nDesired',1,@isscalar); ip.addOptional('askUser',true,@isscalar); ip.parse(list, type, varargin{:}); nDesired = ip.Results.nDesired; askUser = ip.Results.askUser; iProc = find(cellfun(@(x) isa(x,type), list)); nProc = numel(iProc); %If there are only nDesired or less processes found, return if nProc <= nDesired, return; end % If more than nDesired processes if askUser isMultiple = nDesired > 1; names = cellfun(@(x) (x.getName()), list(iProc), 'UniformOutput', false); iSelected = listdlg('ListString', names,... 'SelectionMode', isMultiple, 'ListSize', [400,400],... 'PromptString', ['Select the desired ' type ':']); iProc = iProc(iSelected); assert(~isempty(iProc), 'You must select a process to continue!'); else warning('lccb:process', ['More than ' num2str(nDesired) ' objects '... 'of class ' type ' were found! Returning most recent!']) iProc = iProc(end:-1:(end-nDesired+1)); end end
github
mehta-lab/Instantaneous-PolScope-master
name2wavelength.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/name2wavelength.m
1,153
utf_8
0efaabaf9f7d5ef9e5e515d6108b4e87
% Francois Aguet, 06/30/2011 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % function lambda = name2wavelength(name) s = getFluorPropStruct(); lv = [s.lambda_em]; if ischar(name) name = {name}; end lambda = cellfun(@(x) lv(strcmpi(x, {s.name})), name, 'UniformOutput', false); invalid = cellfun(@isempty, lambda); if any(invalid) invalid = name(invalid); invalid = cellfun(@(x) [x ' '], invalid, 'UniformOutput', false); error(['Unsupported fluorophores: ' invalid{:}]); end lambda = [lambda{:}];
github
mehta-lab/Instantaneous-PolScope-master
buildSpeckleArray.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/buildSpeckleArray.m
25,002
utf_8
099861ab75967e7988a43815b3b12218
function speckleArray=buildSpeckleArray(cM,noiseParams,threshold,gapList,cands,img,varargin) % buildSpeckleArray fills the speckleArray structure containing all speckle information extracted from the analysis of an FSM stack % % SYNOPSIS speckleArray=buildSpeckleArray(cM,noiseParams,threshold) % % INPUT cM : magic position matrix (mpm) as returned by the tracker module % noiseParams : noise parameters for speckle significance test % threshold : radius of the region considered when looking for matching speckles % % % OUTPUT speckleArray : structure containing all speckle information extracted from an image stack % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Sebastien Besson, June 2011 % Adapted from fsmBuildSaveSpeckleArray ip =inputParser; ip.addRequired('cM',@isnumeric); ip.addRequired('noiseParams',@isnumeric); ip.addRequired('threshold',@isscalar); ip.addRequired('gapList',@iscell); ip.addRequired('cands',@iscell); ip.addRequired('img',@iscell); ip.addParamValue('waitbar',[],@ishandle); ip.parse(cM,noiseParams,threshold,gapList,cands,img,varargin{:}); nSpeckles=size(cM,1); % Number of speckle lines nFrames=size(cM,2)/2; % Number of time points nTemplates=size(cM,3); % Number of subwindows % Initialize waitbar if ~isempty(ip.Results.waitbar) wtBar=ip.Results.waitbar; waitbar(0,wtBar,'Indexing speckles...'); elseif feature('ShowFigureWindows') wtBar=waitbar(0,'Indexing speckles...'); end % Index speckles and non-speckles x=1:2:2*nFrames-1; % Allocate memory for 'table' table=zeros(nSpeckles*nFrames,4); pos4=0; % This marks a speckle still existing in the last time point cMPos=0; % Position in cM sAPos=0; % Position in speckleArray for iSpeckle=1:nSpeckles for iFrame=1:nFrames cMPos=cMPos+1; % Keep info of the position in cM currentSpeckle=cM(iSpeckle,x(iFrame)); % Read x coordinate of current speckle if currentSpeckle==0 pos1=-1; pos2=-1; pos3=-1; else % We are at the beginning of the movie if iFrame==1 pos4=1; % We have to mark this because we have a speckle already existing at the first time point if cM(iSpeckle,x(iFrame+1))~=0 % Also next one is speckle sAPos=sAPos+1; % Increase also the position in the struct by 1 pos1=0; pos2=sAPos; pos3=0; else % Next speckle is zero: here we have to introduce a post-death non-speckle sAPos=sAPos+1; % This is the position of current speckle pos1=0; pos2=sAPos; sAPos=sAPos+1; % This will be the position of the "post-death" non-speckle pos3=sAPos; end % % We are at the end of the movie % elseif iFrame==nFrames pos4=2; % We have to cut here because we are at the last time point with a still existing speckle if cM(iSpeckle,x(iFrame-1))==0 % Last one was a non-speckle sAPos=sAPos+1; pos1=sAPos; % This is the "pre-birth" non-speckle sAPos=sAPos+1; pos2=sAPos; % This is the speckle pos3=0; else % Last one was also a speckle sAPos=sAPos+1; % Increase also the position in the struct by 1 pos1=0; pos2=sAPos; pos3=0; end % % We are in the central time-points % else if cM(iSpeckle,x(iFrame-1))~=0 && cM(iSpeckle,x(iFrame+1))~=0 % Last and next ones are speckle pos1=0; sAPos=sAPos+1; % This is the speckle pos2=sAPos; pos3=0; end if cM(iSpeckle,x(iFrame-1))==0 && cM(iSpeckle,x(iFrame+1))~=0 % Last one was not a speckle; the next is sAPos=sAPos+1; pos1=sAPos; % This is the "pre-birth" non-speckle sAPos=sAPos+1; pos2=sAPos; % This is the speckle pos3=0; end if cM(iSpeckle,x(iFrame-1))~=0 && cM(iSpeckle,x(iFrame+1))==0 % Last one was a speckle; the next is not pos1=0; sAPos=sAPos+1; % This is the speckle pos2=sAPos; sAPos=sAPos+1; % This is the "post-death" non-speckle pos3=sAPos; end if cM(iSpeckle,x(iFrame-1))==0 && cM(iSpeckle,x(iFrame+1))==0 % Both are not speckles sAPos=sAPos+1; pos1=sAPos; % This is the "pre-birth" non-speckle sAPos=sAPos+1; pos2=sAPos; % This is the speckle sAPos=sAPos+1; pos3=sAPos; % This is the "post-death" non-speckle end end end % Write correspondence table(cMPos,1:4)=[pos1 pos2 pos3 pos4]; % Reset pos4; pos4=0; end end % Initialize empty speckle array lengthSpeckleArray=max(table(:)); speckleArray=struct(... 'timepoint', uint16(zeros(lengthSpeckleArray,1)),... % Unsigned integer 16: 1 - 65535 (2 bytes) 'spPos', uint16(zeros(lengthSpeckleArray,2)),... % Unsigned integer 16 'bgPos1', uint16(zeros(lengthSpeckleArray,2)),... % Unsigned integer 16 'bgPos2', uint16(zeros(lengthSpeckleArray,2)),... % Unsigned integer 16 'bgPos3', uint16(zeros(lengthSpeckleArray,2)),... % Unsigned integer 16 'intensity', zeros(lengthSpeckleArray,1),... % Double (8 bytes) 'background', zeros(lengthSpeckleArray,1),... % Double 'deltaI', zeros(lengthSpeckleArray,1),... % Double 'deltaICrit', zeros(lengthSpeckleArray,1),... % Double 'sigmaSp', zeros(lengthSpeckleArray,1),... % Double 'sigmaBg', zeros(lengthSpeckleArray,1),... % Double 'status', char(zeros(lengthSpeckleArray,1)),... % Char (1 byte) 'speckleType', uint8(zeros(lengthSpeckleArray,1)),... % Unsigned integer 8: 1 - 255 (1 byte) 'score', zeros(lengthSpeckleArray,1),... % Double 'activity', int8(zeros(lengthSpeckleArray,1)),... % Integer 8: -128 - 127 (1 byte) 'lmEvent', false(lengthSpeckleArray,1)); % Logical: 0 | 1 (1 byte) % For vectorization % speckleArray2=speckleArray; % Initialize waitbar if ishandle(wtBar), waitbar(0,wtBar,'Populating speckleArray structure...'); end nTot = nSpeckles*nFrames*nTemplates; for iFrame=1:nFrames % Cycle through timepoints % Current candsS=cands{iFrame}; % Structure as is % Previous if iFrame>1, insCandsB=cands{iFrame-1}([cands{iFrame-1}.status]==0); imgB =img{iFrame-1}; end % Next if iFrame<nFrames insCandsD=cands{iFrame+1}([cands{iFrame+1}.status]==0); imgD =img{iFrame+1}; end % %%%% Beginning of vectorization % tic % [iTemplate,iSpeckle] =meshgrid(1:nTemplates,1:nSpeckles); % counter=iSpeckle+(iSpeckle-1)*(nFrames-1)+(iTemplate-1)*(nSpeckles*nFrames)+(iFrame-1); % % Read indexes % b=table(counter,1); % s=table(counter,2); % d=table(counter,3); % e=table(counter,4); % % % Valid speckles % validIndx=(s~=-1); % validS=s(validIndx); % speckleArray2.timepoint(validS)=uint16(iFrame); % coords2(:,1) =arrayfun(@(x,y) cM(x,(iFrame-1)*2+1,y),... % iSpeckle(validIndx),iTemplate(validIndx)); % coords2(:,2) =arrayfun(@(x,y) cM(x,(iFrame-1)*2+2,y),... % iSpeckle(validIndx),iTemplate(validIndx)); % % coords2 = speckleArray2.spPos(validS,:); % speckleArray2.spPos(validS,:) =uint16(coords2); % % % FInd associated speckles candidates % allCandsSPos = vertcat(candsS.Lmax); % [~,icoords,icandsPos]=intersect(coords2,allCandsSPos,'rows'); % [sortedIcoords,indx] = sort(icoords); % if ~isequal(sortedIcoords',1:size(coords2,1)), % error('Loc max not univocally found in Delaunay Triangulation results'); % end % % % Read various speckle data % speckleArray2.intensity(validS) = [candsS(icandsPos(indx)).ILmax]; % speckleArray2.background(validS) = [candsS(icandsPos(indx)).IBkg]; % speckleArray2.bgPos1(validS,:) = uint16(vertcat(candsS(icandsPos(indx)).Bkg1)); % speckleArray2.bgPos2(validS,:) = uint16(vertcat(candsS(icandsPos(indx)).Bkg2)); % speckleArray2.bgPos3(validS,:) = uint16(vertcat(candsS(icandsPos(indx)).Bkg3)); % speckleArray2.deltaI(validS) = [candsS(icandsPos(indx)).deltaI]; % speckleArray2.deltaICrit(validS) = [candsS(icandsPos(indx)).deltaICrit]; % speckleArray2.sigmaSp(validS) = [candsS(icandsPos(indx)).sigmaLmax]; % speckleArray2.sigmaBg(validS) = [candsS(icandsPos(indx)).sigmaBkg]; % speckleArray2.speckleType(validS) = uint8([candsS(icandsPos(indx)).speckleType]); % speckleArray2.lmEvent(validS) = false; % % Set the status to 's' by default % speckleArray2.status(validS)='s'; % speckleArray2.status(s(e==1))='f'; % speckleArray2.status(s(e==2))='l'; % [~,icoords]=intersect(coords2,gapList{iFrame},'rows'); % speckleArray2.status(validS(icoords))='g'; % % % % Birth events % validB=b(validIndx); % birthEvents = (validB~=0); % if any(birthEvents) % speckleArray2.timepoint(validB(birthEvents))=... % speckleArray2.timepoint(validS(birthEvents))-1; % speckleArray2.status(validB(birthEvents))='b'; % % [intensity,background,bk1,bk2,bk3,deltaI,deltaICrit,sigmaMax,sigmaMin,lmEvent,spPos,speckleType]=... % associateSpeckles(coords2(birthEvents,:),insCandsB,imgB,noiseParams,threshold); % % % insCandsBPos=vertcat(insCandsB.Lmax); % % D=KDTreeBallQuery(insCandsBPos,coords2(birthEvents,:),threshold); % end % % % Death events % potentialD=d(validIndx); % deathEvents = (potentialD~=0); % validD=potentialD(deathEvents); % if any(deathEvents) % speckleArray2.timepoint(validD)=... % speckleArray2.timepoint(validS(deathEvents))+1; % speckleArray2.status(validD)='d'; % % % % % NOW LOOK FOR A WEAK LOCAL MAXIMUM FOR THE 'b' AND 'd' SPECKLE; OTHERWISE CALCULATE % % NOISE VALUES AS USUAL % % % candsEvPos=vertcat(insCandsD.Lmax); % [D dist]=KDTreeBallQuery(candsEvPos,coords2(deathEvents,:),threshold); % unassociatedD = cellfun(@isempty,D); % speckleArray2.lmEvent(validD(unassociatedD))=0; % This is not even a weak local maximum % speckleArray2.lmEvent(validD(~unassociatedD))=1; % % Read intensities at the coordinates of speckle 's' % % speckleArray2.speckleType(deathEvents&unassociatedD) =imgD(lmPos(1),lmPos(2)); % % % Before using the data of the speckle 's' to read the corresponding data for 'b' or 'd' % % % one has to check whether the loc max has been validated using Delaunay or the auxiliary % % % function % % % % % % bk1=cands(v).Bkg1; % % bk2=cands(v).Bkg2; % % bk3=cands(v).Bkg3; % % % SB: some background points can be outside the cell mask where % % % image is null. Call nonzeros to compute mean over non zeros % % % pixels. % % background=mean(nonzeros([img(bk1(1),bk1(2)) img(bk2(1),bk2(2)) ... % % img(bk3(1),bk3(2))])); % % lmEvent=0; % No insignificant local maximum found % % [Imin,deltaI,k,sigmaDiff,sigmaMax,sigmaMin,status]=testSpeckleSignificance(intensity,background,noiseParams(1),noiseParams(2),noiseParams(3),noiseParams(4)); % % deltaICrit=k*sigmaDiff; % % % [intensity,background,bk1,bk2,bk3,deltaI,deltaICrit,sigmaMax,sigmaMin,lmEvent,spPos,speckleType]=... % % associateSpeckles(coords2(deathEvents,:),insCandsD,imgD,noiseParams,threshold); % end % % % % coordsD = coords2(deathEvents,:); % % insCandsDPos=vertcat(insCandsD.Lmax); % % D=KDTreeBallQuery(insCandsDPos,coordsD,... % % threshold*ones(sum(deathEvents),1)); % % % % % Death events not-matching any insignificant local maxima % % umDEvents =cellfun(@isempty,D); % % validUmD=validD(umDEvents); % % speckleArray2.intensity(validUmD) = ... % % arrayfun(@(x)imgD(coordsD(x,1),coordsD(x,2)),find(umDEvents)); % % speckleArray2.speckleType(validUmD) = 0; % % % % [~,icoords,icandsPos]=intersect(coordsD(umDEvents,:),allCandsSPos,'rows'); % % speckleArray2.bgPos1(validUmD,:) = vertcat(candsS(icandsPos).Bkg1); % % speckleArray2.bgPos2(validUmD,:) = vertcat(candsS(icandsPos).Bkg2); % % speckleArray2.bgPos3(validUmD,:) = vertcat(candsS(icandsPos).Bkg3); % % speckleArray2.lmEvent(validUmD) = 0; % No insignificant local maximum found % % % SB: some background points can be outside the cell mask where % % % image is null. Call nonzeros to compute mean over non zeros % % % pixels. % % % speckleArray2.background(validD(umDEvents)) = arrayfun(@(x)... % % % mean(nonzeros([img(bk1(1),bk1(2)) img(bk2(1),bk2(2)) ... % % % % img(bk3(1),bk3(2))])); % % speckleArray2.background(validUmD) = arrayfun(@(x)... % % mean(nonzeros([imgD(candsS(x).Bkg1(1),candsS(x).Bkg1(2))... % % imgD(candsS(x).Bkg2(1),candsS(x).Bkg2(2))... % % imgD(candsS(x).Bkg3(1),candsS(x).Bkg3(2))])),icandsPos); % % % [Imin,deltaI,k,sigmaDiff,sigmaMax,sigmaMin,status]=testSpeckleSignificance(intensity,background,noiseParams(1),noiseParams(2),noiseParams(3),noiseParams(4)); % % % deltaICrit=k*sigmaDiff; % % % % % Death events matching insignificant local maxima % % validMD=validD(~umDEvents); % % speckleArray2.lmEvent(validMD) = 1; % % end % % toc % %%%% End of vectorization %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Fill speckleArray for current frame (iFrame) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for iTemplate=1:nTemplates % Cycle through templates for iSpeckle=1:nSpeckles % Cycle through speckles (per template and timepoint) % Calculate counter counter=iSpeckle+(iSpeckle-1)*(nFrames-1)+(iTemplate-1)*(nSpeckles*nFrames)+(iFrame-1); % Read indexes b=table(counter,1); s=table(counter,2); d=table(counter,3); e=table(counter,4); if s~=-1 % Start with actual speckle speckleArray.timepoint(s) = uint16(iFrame); coords(1,1:2)=[cM(iSpeckle,(iFrame-1)*2+1,iTemplate) cM(iSpeckle,(iFrame-1)*2+2,iTemplate)]; speckleArray.spPos(s,1:2) = uint16(coords'); [intensity,background,bk1,bk2,bk3,deltaI,deltaICrit,sigmaMax,sigmaMin,speckleType]=SSpeckleInfo(candsS,coords); speckleArray.intensity(s) = intensity; speckleArray.background(s) = background; speckleArray.bgPos1(s,1:2) = uint16(bk1'); speckleArray.bgPos2(s,1:2) = uint16(bk2'); speckleArray.bgPos3(s,1:2) = uint16(bk3'); speckleArray.deltaI(s) = deltaI; speckleArray.deltaICrit(s) = deltaICrit; speckleArray.sigmaSp(s) = sigmaMax; speckleArray.sigmaBg(s) = sigmaMin; if ismember(coords,gapList{iFrame},'rows','legacy') % This speckle is a closed gap speckleArray.status(s) = 'g'; else % This is an actual speckle speckleArray.status(s) = 's'; end if e==1 % This is a speckle in the last frame of the movie speckleArray.status(s) = 'f'; elseif e==2 % This is a speckle in the first frame of the movie speckleArray.status(s) = 'l'; end speckleArray.lmEvent(s) = false; speckleArray.speckleType(s) = uint8(speckleType); % SPECKLE HAVING PRE-BIRTH SPECKLE ASSOCIATED if b~=0 % Now with pre-birth non-speckle speckleArray.timepoint(b) = speckleArray.timepoint(s)-1; % This requires an overloaded operator for uint16 [intensity,background,bk1,bk2,bk3,deltaI,deltaICrit,sigmaMax,sigmaMin,lmEvent,spPos,speckleType]=BDSpeckleInfo(coords,candsS,insCandsB,imgB,noiseParams,threshold); speckleArray.spPos(b,1:2) = uint16(spPos'); speckleArray.intensity(b) = intensity; speckleArray.background(b) = background; speckleArray.bgPos1(b,1:2) = uint16(bk1'); speckleArray.bgPos2(b,1:2) = uint16(bk2'); speckleArray.bgPos3(b,1:2) = uint16(bk3'); speckleArray.deltaI(b) = deltaI; speckleArray.deltaICrit(b) = deltaICrit; speckleArray.sigmaSp(b) = sigmaMax; speckleArray.sigmaBg(b) = sigmaMin; speckleArray.status(b) = 'b'; speckleArray.lmEvent(b) = logical(lmEvent); speckleArray.speckleType(b) = uint8(speckleType); end % CASE 3: SPECKLE HAVING POST-DEATH SPECKLE ASSOCIATED if d % Now with post-death non-speckle speckleArray.timepoint(d) = speckleArray.timepoint(s)+1; % This requires an overloaded operator for uint16 [intensity,background,bk1,bk2,bk3,deltaI,deltaICrit,sigmaMax,sigmaMin,lmEvent,spPos,speckleType]=BDSpeckleInfo(coords,candsS,insCandsD,imgD,noiseParams,threshold); speckleArray.spPos(d,1:2) = uint16(spPos'); speckleArray.intensity(d) = intensity; speckleArray.background(d) = background; speckleArray.bgPos1(d,1:2) = uint16(bk1'); speckleArray.bgPos2(d,1:2) = uint16(bk2'); speckleArray.bgPos3(d,1:2) = uint16(bk3'); speckleArray.deltaI(d) = deltaI; speckleArray.deltaICrit(d) = deltaICrit; speckleArray.sigmaSp(d) = sigmaMax; speckleArray.sigmaBg(d) = sigmaMin; speckleArray.status(d) = 'd'; speckleArray.lmEvent(d) = logical(lmEvent); speckleArray.speckleType(d) = uint8(speckleType); end % end % Update waitbar if needed linInd = sub2ind([nSpeckles nFrames nTemplates],iSpeckle,iFrame,iTemplate); if mod(linInd,round(nTot/20))==1 && ishandle(wtBar) ti=linInd/nTot; waitbar(ti,wtBar); end end end % toc % isequal(speckleArray,speckleArray2) end % Close waitbar if not-delegated if isempty(ip.Results.waitbar) && ishandle(wtBar), close(wtBar); end function [intensity,background,bk1,bk2,bk3,deltaI,deltaICrit,sigmaMax,sigmaMin,speckleType]=SSpeckleInfo(cands,lmPos) allCandsPos=vertcat(cands.Lmax); % Look for 'coords' in the cands structure t=lmPos(1,1)==allCandsPos(:,1); u=lmPos(1,2)==allCandsPos(:,2); v=find(t & u); % Check for correct selection of the loc max if isempty(v) || length(v)>1 error('Loc max not univocally found in Delaunay Triangulation results'); end % This is a speckle of class 's' -> all information has been already stored in delaunay###.mat intensity=cands(v).ILmax; background=cands(v).IBkg; bk1=cands(v).Bkg1; bk2=cands(v).Bkg2; bk3=cands(v).Bkg3; deltaI=cands(v).deltaI; deltaICrit=cands(v).deltaICrit; sigmaMax=cands(v).sigmaLmax; sigmaMin=cands(v).sigmaBkg; speckleType=cands(v).speckleType; function [intensity,background,bk1,bk2,bk3,deltaI,deltaICrit,sigmaMax,sigmaMin,lmEvent,spPos,speckleType]=BDSpeckleInfo(lmPos,cands,candsEv,img,noiseParams,threshold) allCandsPos=vertcat(cands.Lmax); % Look for 'coords' in the cands structure (still for the 's' speckle) t=lmPos(1,1)==allCandsPos(:,1); u=lmPos(1,2)==allCandsPos(:,2); v=find(t & u); % Check for correct selection of the loc max if isempty(v) || length(v)>1 error('Loc max not univocally found in Delaunay Triangulation results'); end % % NOW LOOK FOR A WEAK LOCAL MAXIMUM FOR THE 'b' AND 'd' SPECKLE; OTHERWISE CALCULATE % NOISE VALUES AS USUAL % candsEvPos=vertcat(candsEv.Lmax); %SB: quick if isempty(candsEvPos), x=[]; else D=KDTreeBallQuery(candsEvPos,lmPos,threshold); % To be compatibile with the fsmBuildSaveSpeckleArray % index=(dist{1}==min(dist{1})); % x=D{1}(index); x=D{1}; end if length(x)>1 % Arbitrarily take the one with smaller deltaI intensity = img(sub2ind(size(img), candsEvPos(x(:), 1), ... candsEvPos(x(:), 2)))'; background = cell2mat({candsEv(x(:)).IBkg}); deltaI = intensity - background; index=find(deltaI==min(deltaI)); if length(index)>1 disp('Arbitrarily chosen one local maximum as a ''b'' or ''d'' event.'); index=index(1); end x=x(index); end if ~isempty(x) % Read intensities at the coordinates of the local maximum found intensity=candsEv(x).ILmax; background=candsEv(x).IBkg; bk1=candsEv(x).Bkg1; bk2=candsEv(x).Bkg2; bk3=candsEv(x).Bkg3; deltaI=candsEv(x).deltaI; deltaICrit=candsEv(x).deltaICrit; sigmaMax=candsEv(x).sigmaLmax; sigmaMin=candsEv(x).sigmaBkg; lmEvent=1; % Insignificant local maximum found speckleType=candsEv(x).speckleType; else % No matching discarded local maximum found speckleType=0; % This is not even a weak local maximum % Read intensities at the coordinates of speckle 's' intensity=img(lmPos(1),lmPos(2)); % Before using the data of the speckle 's' to read the corresponding data for 'b' or 'd' % one has to check whether the loc max has been validated using Delaunay or the auxiliary % function bk1=cands(v).Bkg1; bk2=cands(v).Bkg2; bk3=cands(v).Bkg3; % SB: some background points can be outside the cell mask where % image is null. Call nonzeros to compute mean over non zeros % pixels. background=mean(nonzeros([img(bk1(1),bk1(2)) img(bk2(1),bk2(2)) ... img(bk3(1),bk3(2))])); lmEvent=0; % No insignificant local maximum found [Imin,deltaI,k,sigmaDiff,sigmaMax,sigmaMin,status]=testSpeckleSignificance(intensity,background,noiseParams(1),noiseParams(2),noiseParams(3),noiseParams(4)); deltaICrit=k*sigmaDiff; end % Return also the position of the recovered local maximum if ~isempty(x) spPos=candsEvPos(x,1:2); else spPos=lmPos; % If nothing has been found, use the coordinates of the 's' speckle end
github
mehta-lab/Instantaneous-PolScope-master
FlowTrackingProcess.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/FlowTrackingProcess.m
6,583
utf_8
b9294d2d10e6b023c4400a274137942a
classdef FlowTrackingProcess < ImageAnalysisProcess % Concrete class for a flow tracking process % % Sebastien Besson, 5/2011 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % methods function obj = FlowTrackingProcess(owner,varargin) if nargin == 0 super_args = {}; else % Input check ip = inputParser; ip.addRequired('owner',@(x) isa(x,'MovieData')); ip.addOptional('outputDir',owner.outputDirectory_,@ischar); ip.addOptional('funParams',[],@isstruct); ip.parse(owner,varargin{:}); outputDir = ip.Results.outputDir; funParams = ip.Results.funParams; % Define arguments for superclass constructor super_args{1} = owner; super_args{2} = FlowTrackingProcess.getName; super_args{3} = @trackMovieFlow; if isempty(funParams) funParams=FlowTrackingProcess.getDefaultParams(owner,outputDir); end super_args{4} = funParams; end obj = obj@ImageAnalysisProcess(super_args{:}); end function OK = checkChannelOutput(obj,varargin) % Input check ip =inputParser; ip.addOptional('iChan',1:numel(obj.owner_.channels_),... @(x) all(ismember(x,1:numel(obj.owner_.channels_)))); ip.parse(varargin{:}); iChan=ip.Results.iChan; %Makes sure there's at least one output file per channel OK = arrayfun(@(x) exist(obj.outFilePaths_{1,x},'file'),iChan); end function varargout = loadChannelOutput(obj,iChan,varargin) % Input check outputList = {'flow','corLen'}; ip =inputParser; ip.addRequired('iChan',@(x) isscalar(x) && obj.checkChanNum(x)); ip.addOptional('iFrame',1:obj.owner_.nFrames_,@(x) all(obj.checkFrameNum(x))); ip.addParamValue('output',outputList,@(x) all(ismember(x,outputList))); ip.parse(iChan,varargin{:}) iFrame = ip.Results.iFrame; output = ip.Results.output; if ischar(output), output={output}; end % Initialize output for j=1:numel(output) if numel(iFrame)==1 varargout{j}=[]; else varargout{j} = cell(size(iFrame)); end end % Fill output for i=1:numel(iFrame) flowFile= [obj.outFilePaths_{1,iChan}... filesep 'flow' num2str(iFrame(i)) '.mat']; % Check existence of output file if ~exist(flowFile,'file'), continue; end % Read variables and dispatch them s = load(flowFile,output{:}); for j=1:numel(output) if numel(iFrame)==1, varargout{j}=s.(output{j}); else varargout{j}{i}=s.(output{j}); end end end end function checkValue=checkValue(obj,property,value) % Test the validity of a property value switch property case {'lastImage','timeWindow','timeStepSize'} checkTest=@(x) isnumeric(x) && x>0 && x<=obj.owner_.nFrames_; case {'firstImage','minCorLength', 'maxCorLength',... 'minFeatureSize','edgeErodeWidth',... 'numStBgForAvg','maxFlowSpeed'} checkTest=@(x) isnumeric(x) && x>0; end checkValue = checkTest(value); end function output = getDrawableOutput(obj) colors = hsv(numel(obj.owner_.channels_)); output(1).name='Flow vectors'; output(1).var='flow'; output(1).formatData=@formatFlow; output(1).type='overlay'; output(1).defaultDisplayMethod=@(x) VectorFieldDisplay('Color',colors(x,:)); end end methods (Static) function name =getName() name = 'Flow Tracking'; end function h = GUI() h= @flowTrackingProcessGUI; end function funParams = getDefaultParams(owner,varargin) % Input check ip=inputParser; ip.addRequired('owner',@(x) isa(x,'MovieData')); ip.addOptional('outputDir',owner.outputDirectory_,@ischar); ip.parse(owner, varargin{:}) outputDir=ip.Results.outputDir; % Set default parameters funParams.ChannelIndex = 1:numel(owner.channels_); funParams.OutputDirectory = [outputDir filesep 'flow']; funParams.firstImage = 1; funParams.lastImage = owner.nFrames_; funParams.timeWindow = 2; funParams.timeStepSize = 1; funParams.minCorLength = 11; funParams.maxCorLength = 11; funParams.numStBgForAvg = 0; funParams.minFeatureSize = 11; funParams.edgeErodeWidth =5; funParams.maxFlowSpeed =10; funParams.outlierThreshold = 2; funParams.ROI = [1 1;owner.imSize_]; end end end function flow = formatFlow(initFlow) if isempty(initFlow), flow=zeros(1,4); else flow=[initFlow(:,[2 1]) initFlow(:,[4 3])-initFlow(:,[2 1])]; end end function data = formatBoxes(initData) if isempty(initData), data=[]; else finiteLength = isfinite(initData(:,3)); data=[initData(finiteLength,1:2) repmat(initData(finiteLength,3)/2,1,2)]; end end
github
mehta-lab/Instantaneous-PolScope-master
thresholdProcessGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/thresholdProcessGUI.m
21,191
utf_8
d710bf7e77b09cc1171ba4987714f3a6
function varargout = thresholdProcessGUI(varargin) % thresholdProcessGUI M-file for thresholdProcessGUI.fig % thresholdProcessGUI, by itself, creates a new thresholdProcessGUI or raises the existing % singleton*. % % H = thresholdProcessGUI returns the handle to a new thresholdProcessGUI or the handle to % the existing singleton*. % % thresholdProcessGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in thresholdProcessGUI.M with the given input arguments. % % thresholdProcessGUI('Property','Value',...) creates a new thresholdProcessGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before thresholdProcessGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to thresholdProcessGUI_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 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help thresholdProcessGUI % Last Modified by GUIDE v2.5 12-Dec-2011 17:52:57 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @thresholdProcessGUI_OpeningFcn, ... 'gui_OutputFcn', @thresholdProcessGUI_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 thresholdProcessGUI is made visible. function thresholdProcessGUI_OpeningFcn(hObject, eventdata, handles, varargin) processGUI_OpeningFcn(hObject, eventdata, handles, varargin{:},'initChannel',0); % ---------------------- Channel Setup ------------------------- userData = get(handles.figure1, 'UserData'); funParams = userData.crtProc.funParams_; % Set up available input channels set(handles.listbox_availableChannels,'String',userData.MD.getChannelPaths(), ... 'UserData',1:numel(userData.MD.channels_)); channelIndex = funParams.ChannelIndex; % Find any parent process userData.parentProc = userData.crtPackage.getParent(userData.procID); if isempty(userData.crtPackage.processes_{userData.procID}) && ~isempty(userData.parentProc) % Check existence of all parent processes emptyParentProc = any(cellfun(@isempty,userData.crtPackage.processes_(userData.parentProc))); if ~emptyParentProc % Intersect channel index with channel index of parent processes parentChannelIndex = @(x) userData.crtPackage.processes_{x}.funParams_.ChannelIndex; for i = userData.parentProc channelIndex = intersect(channelIndex,parentChannelIndex(i)); end end end if ~isempty(channelIndex) channelString = userData.MD.getChannelPaths(channelIndex); else channelString = {}; end set(handles.listbox_selectedChannels,'String',channelString,... 'UserData',channelIndex); set(handles.edit_GaussFilterSigma,'String',funParams.GaussFilterSigma); threshMethods = userData.crtProc.getMethods(); set(handles.popupmenu_thresholdingMethod,'String',{threshMethods(:).name},... 'Value',funParams.MethodIndx); if isempty(funParams.ThresholdValue) set(handles.checkbox_auto, 'Value', 1); set(get(handles.uipanel_automaticThresholding,'Children'),'Enable','on'); set(get(handles.uipanel_fixedThreshold,'Children'),'Enable','off'); if funParams.MaxJump set(handles.checkbox_max, 'Value', 1); set(handles.edit_jump, 'Enable','on','String',funParams.MaxJump); else set(handles.edit_jump, 'Enable', 'off'); end nSelectedChannels = numel(get(handles.listbox_selectedChannels, 'String')); set(handles.listbox_thresholdValues, 'String',... num2cell(zeros(1,nSelectedChannels))); userData.thresholdValue=0; else set(handles.checkbox_auto, 'Value', 0); set(get(handles.uipanel_fixedThreshold,'Children'),'Enable','on'); set(get(handles.uipanel_automaticThresholding,'Children'),'Enable','off'); set(handles.listbox_thresholdValues, 'String', num2cell(funParams.ThresholdValue)); userData.thresholdValue=funParams.ThresholdValue(1); set(handles.slider_threshold, 'Value',funParams.ThresholdValue(1)) end % Initialize the frame number slider and eidt nFrames=userData.MD.nFrames_; if nFrames > 1 set(handles.slider_frameNumber,'Value',1,'Min',1,... 'Max',nFrames,'SliderStep',[1/double(nFrames) 10/double(nFrames)]); else set(handles.slider_frameNumber,'Enable','off'); end set(handles.text_nFrames,'String',['/ ' num2str(nFrames)]); set(handles.edit_frameNumber,'Value',1); % Initialize previewing constants userData.previewFig =-1; userData.chanIndx = 0; userData.imIndx=0; % Update user data and GUI data handles.output = hObject; set(hObject, 'UserData', userData); guidata(hObject, handles); update_data(hObject,eventdata,handles); % --- Outputs from this function are returned to the command line. function varargout = thresholdProcessGUI_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 pushbutton_cancel. function pushbutton_cancel_Callback(hObject, eventdata, handles) % Delete figure delete(handles.figure1); % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) % Call back function of 'Apply' button userData = get(handles.figure1, 'UserData'); % -------- Check user input -------- if isempty(get(handles.listbox_selectedChannels, 'String')) errordlg('Please select at least one input channel from ''Available Channels''.','Setting Error','modal') return; end channelIndex = get (handles.listbox_selectedChannels, 'Userdata'); funParams.ChannelIndex = channelIndex; gaussFilterSigma = str2double(get(handles.edit_GaussFilterSigma, 'String')); if isnan(gaussFilterSigma) || gaussFilterSigma < 0 errordlg(['Please provide a valid input for '''... get(handles.text_GaussFilterSigma,'String') '''.'],'Setting Error','modal'); return; end funParams.GaussFilterSigma=gaussFilterSigma; if get(handles.checkbox_auto, 'value') funParams.ThresholdValue = [ ]; funParams.MethodIndx=get(handles.popupmenu_thresholdingMethod,'Value'); if get(handles.checkbox_max, 'Value') % If both checkbox are checked maxJump=str2double(get(handles.edit_jump, 'String')); if isnan(maxJump) || maxJump < 1 errordlg('Please provide a valid input for ''Maximum threshold jump''.','Setting Error','modal'); return; end funParams.MaxJump = str2double(get(handles.edit_jump,'String')); end else threshold = get(handles.listbox_thresholdValues, 'String'); if isempty(threshold) errordlg('Please provide at least one threshold value.','Setting Error','modal') return elseif length(threshold) ~= 1 && length(threshold) ~= length(channelIndex) errordlg('Please provide the same number of threshold values as the input channels.','Setting Error','modal') return else threshold = str2double(threshold); if any(isnan(threshold)) || any(threshold < 0) errordlg('Please provide valid threshold values. Threshold cannot be a negative number.','Setting Error','modal') return end end funParams.ThresholdValue = threshold; end % -------- Process Sanity check -------- % ( only check underlying data ) try userData.crtProc.sanityCheck; catch ME errordlg([ME.message 'Please double check your data.'],... 'Setting Error','modal'); return; end processGUI_ApplyFcn(hObject, eventdata, handles,funParams); % --- Executes on button press in checkbox_all. function checkbox_all_Callback(hObject, eventdata, handles) % Hint: get(hObject,'Value') returns toggle state of checkbox_all contents1 = get(handles.listbox_availableChannels, 'String'); chanIndex1 = get(handles.listbox_availableChannels, 'Userdata'); chanIndex2 = get(handles.listbox_selectedChannels, 'Userdata'); % Return if listbox1 is empty if isempty(contents1) return; end switch get(hObject,'Value') case 1 set(handles.listbox_selectedChannels, 'String', contents1); chanIndex2 = chanIndex1; thresholdValues =zeros(1,numel(chanIndex1)); case 0 set(handles.listbox_selectedChannels, 'String', {}, 'Value',1); chanIndex2 = [ ]; thresholdValues = []; end set(handles.listbox_selectedChannels, 'UserData', chanIndex2); set(handles.listbox_thresholdValues,'String',num2cell(thresholdValues)) update_data(hObject,eventdata,handles); % --- Executes on button press in pushbutton_select. function pushbutton_select_Callback(hObject, eventdata, handles) % call back function of 'select' button contents1 = get(handles.listbox_availableChannels, 'String'); contents2 = get(handles.listbox_selectedChannels, 'String'); id = get(handles.listbox_availableChannels, 'Value'); % If channel has already been added, return; chanIndex1 = get(handles.listbox_availableChannels, 'Userdata'); chanIndex2 = get(handles.listbox_selectedChannels, 'Userdata'); thresholdValues = cellfun(@str2num,get(handles.listbox_thresholdValues,'String')); for i = id if any(strcmp(contents1{i}, contents2) ) continue; else contents2{end+1} = contents1{i}; thresholdValues(end+1) = 0; chanIndex2 = cat(2, chanIndex2, chanIndex1(i)); end end set(handles.listbox_selectedChannels, 'String', contents2, 'Userdata', chanIndex2); set(handles.listbox_thresholdValues,'String',num2cell(thresholdValues)) update_data(hObject,eventdata,handles); % --- Executes on button press in pushbutton_delete. function pushbutton_delete_Callback(hObject, eventdata, handles) % Call back function of 'delete' button contents = get(handles.listbox_selectedChannels,'String'); id = get(handles.listbox_selectedChannels,'Value'); % Return if list is empty if isempty(contents) || isempty(id) return; end % Delete selected item contents(id) = [ ]; % Delete userdata chanIndex2 = get(handles.listbox_selectedChannels, 'Userdata'); chanIndex2(id) = [ ]; set(handles.listbox_selectedChannels, 'Userdata', chanIndex2); % Update thresholdValues thresholdValues = cellfun(@str2num,get(handles.listbox_thresholdValues,'String')); thresholdValues(id) = []; set(handles.listbox_thresholdValues,'String',num2cell(thresholdValues)); % Point 'Value' to the second last item in the list once the % last item has been deleted if (id >length(contents) && id>1) set(handles.listbox_selectedChannels,'Value',length(contents)); set(handles.listbox_thresholdValues,'Value',length(contents)); end % Refresh listbox set(handles.listbox_selectedChannels,'String',contents); update_data(hObject,eventdata,handles); % --- Executes on button press in checkbox_auto. function checkbox_auto_Callback(hObject, eventdata, handles) % Hint: get(hObject,'Value') returns toggle state of checkbox_auto if get(hObject, 'Value') set(get(handles.uipanel_automaticThresholding,'Children'),'Enable','on'); set(get(handles.uipanel_fixedThreshold,'Children'),'Enable','off'); if ~get(handles.checkbox_max,'Value'), set(handles.edit_jump,'Enable','off'); end else set(get(handles.uipanel_automaticThresholding,'Children'),'Enable','off'); set(get(handles.uipanel_fixedThreshold,'Children'),'Enable','on') set(handles.checkbox_max, 'Value', 0); set(handles.checkbox_applytoall, 'Value',0); set(handles.checkbox_preview, 'Value',1); end update_data(hObject,eventdata,handles); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, eventdata, handles) % Notify the package GUI that the setting panel is closed userData = get(handles.figure1, 'UserData'); if ishandle(userData.helpFig), delete(userData.helpFig); end if ishandle(userData.previewFig), delete(userData.previewFig); end set(handles.figure1, 'UserData', userData); guidata(hObject,handles); % --- Executes on button press in checkbox_max. function checkbox_max_Callback(hObject, eventdata, handles) if get(hObject, 'value') set(handles.edit_jump, 'Enable', 'on'); else set(handles.edit_jump, 'Enable', 'off'); end % --- Executes on key press with focus on pushbutton_done and none of its controls. function pushbutton_done_KeyPressFcn(hObject, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(hObject, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on button press in pushbutton_set_threshold. function pushbutton_set_threshold_Callback(hObject, eventdata, handles) newThresholdValue = get(handles.slider_threshold,'Value'); indx = get(handles.listbox_selectedChannels,'Value'); thresholdValues = cellfun(@str2num,get(handles.listbox_thresholdValues,'String')); thresholdValues(indx) = newThresholdValue; set(handles.listbox_thresholdValues,'String',num2cell(thresholdValues)); % --- Executes on button press in checkbox_preview. function checkbox_preview_Callback(hObject, eventdata, handles) if get(handles.checkbox_preview,'Value'), update_data(hObject,eventdata,handles); else userData = get(handles.figure1, 'UserData'); if ishandle(userData.previewFig), delete(userData.previewFig); end % Save data and update graphics set(handles.figure1,'UserData',userData); guidata(hObject, handles); end function threshold_edition(hObject,eventdata, handles) userData = get(handles.figure1, 'UserData'); % Retrieve the valuye of the selected threshold if strcmp(get(hObject,'Tag'),'edit_threshold') thresholdValue = str2double(get(handles.edit_threshold, 'String')); else thresholdValue = get(handles.slider_threshold, 'Value'); end thresholdValue=round(thresholdValue); % Check the validity of the supplied threshold if isnan(thresholdValue) || thresholdValue < 0 || thresholdValue > get(handles.slider_threshold,'Max') warndlg('Please provide a valid coefficient.','Setting Error','modal'); thresholdValue=userData.thresholdValue; end set(handles.slider_threshold,'Value',thresholdValue); set(handles.edit_threshold,'String',thresholdValue); % Save data and update graphics set(handles.figure1,'UserData',userData); guidata(hObject, handles); update_data(hObject,eventdata,handles); function imageNumber_edition(hObject,eventdata, handles) % Retrieve the value of the selected image if strcmp(get(hObject,'Tag'),'edit_imageNumber') imageNumber = str2double(get(handles.edit_frameNumber, 'String')); else imageNumber = get(handles.slider_frameNumber, 'Value'); end imageNumber=round(imageNumber); % Check the validity of the supplied threshold if isnan(imageNumber) || imageNumber < 0 || imageNumber > get(handles.slider_frameNumber,'Max') warndlg('Please provide a valid coefficient.','Setting Error','modal'); end set(handles.slider_frameNumber,'Value',imageNumber); set(handles.edit_frameNumber,'String',imageNumber); % Save data and update graphics guidata(hObject, handles); update_data(hObject,eventdata,handles); function update_data(hObject,eventdata, handles) userData = get(handles.figure1, 'UserData'); if strcmp(get(get(hObject,'Parent'),'Tag'),'uipanel_channels') ||... strcmp(get(hObject,'Tag'),'listbox_thresholdValues') % Check if changes have been at the list box level linkedListBoxes = {'listbox_selectedChannels','listbox_thresholdValues'}; checkLinkBox = strcmp(get(hObject,'Tag'),linkedListBoxes); if any(checkLinkBox) value = get(handles.(linkedListBoxes{checkLinkBox}),'Value'); set(handles.(linkedListBoxes{~checkLinkBox}),'Value',value); else value = get(handles.listbox_selectedChannels,'Value'); end thresholdString = get(handles.listbox_thresholdValues,'String'); if ~isempty(thresholdString) thresholdValue = str2double(thresholdString{value}); else thresholdValue=0; end set(handles.edit_threshold,'String',thresholdValue); set(handles.slider_threshold,'Value',thresholdValue); if isempty(thresholdString), if isfield(userData, 'previewFig'), delete(userData.previewFig); end set(handles.figure1, 'UserData', userData); guidata(hObject,handles); return end end % Retrieve the channex index props=get(handles.listbox_selectedChannels,{'UserData','Value'}); if isempty(props{1}), return; end chanIndx = props{1}(props{2}); imIndx = get(handles.slider_frameNumber,'Value'); thresholdValue = get(handles.slider_threshold, 'Value'); % Load a new image in case the image number or channel has been changed if (chanIndx~=userData.chanIndx) || (imIndx~=userData.imIndx) if ~isempty(userData.parentProc) && ~isempty(userData.crtPackage.processes_{userData.parentProc}) &&... userData.crtPackage.processes_{userData.parentProc}.checkChannelOutput(chanIndx) userData.imData=userData.crtPackage.processes_{userData.parentProc}.loadOutImage(chanIndx,imIndx); else userData.imData=userData.MD.channels_(chanIndx).loadImage(imIndx); end % Get the value of the new maximum threshold maxThresholdValue=max(userData.imData(:)); % Update the threshold Value if above the new maximum thresholdValue=min(thresholdValue,maxThresholdValue); set(handles.slider_threshold,'Value',thresholdValue,'Max',maxThresholdValue,... 'SliderStep',[1/double(maxThresholdValue) 10/double(maxThresholdValue)]); set(handles.edit_threshold,'String',thresholdValue); userData.updateImage=1; userData.chanIndx=chanIndx; userData.imIndx=imIndx; else userData.updateImage=0; end % Save the data set(handles.figure1, 'UserData', userData); guidata(hObject,handles); % Update graphics if applicable if get(handles.checkbox_preview,'Value') % Create figure if non-existing or closed if ~ishandle(userData.previewFig) userData.previewFig = figure('NumberTitle','off','Name','Thresholding preview',... 'Position',[50 50 userData.MD.imSize_(2) userData.MD.imSize_(1)]); axes('Position',[0 0 1 1]); else figure(userData.previewFig); end % Retrieve the handle of the figures image imHandle = findobj(userData.previewFig,'Type','image'); if userData.updateImage || isempty(imHandle) if isempty(imHandle) imHandle=imagesc(userData.imData); axis off; else set(imHandle,'CData',userData.imData); end end % Preview the tresholding output using the alphaData mapping alphamask=ones(size(userData.imData)); gaussFilterSigma = str2double(get(handles.edit_GaussFilterSigma, 'String')); if ~isnan(gaussFilterSigma) && gaussFilterSigma >0 imData = filterGauss2D(userData.imData,gaussFilterSigma); else imData=userData.imData; end if get(handles.checkbox_auto,'Value') methodIndx=get(handles.popupmenu_thresholdingMethod,'Value'); threshMethod = userData.crtProc.getMethods(methodIndx).func; try %#ok<TRYNC> currThresh = threshMethod( imData); alphamask(imData<=currThresh)=.4; end else % Preview manual threshold thresholdValue = get(handles.slider_threshold, 'Value'); alphamask(imData<=thresholdValue)=.4; end set(imHandle,'AlphaData',alphamask,'AlphaDataMapping','none'); set(handles.figure1, 'UserData', userData); guidata(hObject,handles); end
github
mehta-lab/Instantaneous-PolScope-master
scaleContrast.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/scaleContrast.m
1,274
utf_8
70c0faf19d14ebc348658a403b510f03
%out = scaleContrast(in, rangeIn, rangeOut) adjusts the contrast of the input % % Inputs: % in : input signal % rangeIn : input range. If empty, [min(in(:)) max(in(:))] % rangeOut : output range % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Francois Aguet (Last modified: 03/22/2011) function out = scaleContrast(in, rangeIn, rangeOut) if nargin<2 || isempty(rangeIn) rangeIn = [min(in(:)) max(in(:))]; end if nargin<3 || isempty(rangeOut) rangeOut = [0 255]; end if rangeIn(2)-rangeIn(1) ~= 0 out = (double(in)-rangeIn(1)) / diff(rangeIn) * diff(rangeOut) + rangeOut(1); else out = zeros(size(in)); end
github
mehta-lab/Instantaneous-PolScope-master
bfImport.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/bfImport.m
7,619
utf_8
5581d593bf14dfe54fb8f3b97368d297
function MD = bfImport(dataPath,varargin) % BFIMPORT imports movie files into MovieData objects using Bioformats % % MD = bfimport(dataPath) % % Load proprietary files using the Bioformats library. Read the metadata % that is associated with the movie and the channels and set them into the % created movie objects. Optionally images can be extracted and saved as % individual TIFF files. % % Input: % % dataPath - A string containing the full path to the movie file. % % extractImages - Optional. If true, individual images will be extracted % and saved as TIF images. % % Output: % % MD - A MovieData object % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Sebastien Besson, Dec 2011 status = bfCheckJavaPath(); assert(status, 'Bioformats library missing'); % Input check ip=inputParser; ip.addRequired('dataPath',@ischar); ip.addOptional('extractImages',false,@islogical); ip.addParamValue('outputDirectory',[],@ischar); ip.parse(dataPath,varargin{:}); extractImages = ip.Results.extractImages; assert(exist(dataPath,'file')==2,'File does not exist'); % Check path try % Retrieve movie reader and metadata r=bfGetReader(dataPath); r.setSeries(0); catch bfException ME = MException('lccb:import:error','Import error'); ME = ME.addCause(bfException); throw(ME); end % Read number of series and initialize movies nSeries = r.getSeriesCount(); MD(1, nSeries) = MovieData(); % Set output directory (based on image extraction flag) [mainPath,movieName,movieExt]=fileparts(dataPath); token = regexp([movieName,movieExt],'(\w+)\.ome\.tiff','tokens'); if ~isempty(token), movieName = token{1}{1}; end if ~isempty(ip.Results.outputDirectory) mainOutputDir = ip.Results.outputDirectory; else mainOutputDir = fullfile(mainPath, movieName); end % Create movie channels nChan = r.getSizeC(); channelPath = cell(nSeries, nChan); movieChannels(nSeries, nChan) = Channel(); for i = 1:nSeries fprintf(1,'Creating movie %g/%g\n',i,nSeries); iSeries = i-1; movieArgs = getMovieMetadata(r, iSeries); % Read number of channels, frames and stacks nChan = r.getMetadataStore().getPixelsSizeC(iSeries).getValue; if nSeries>1 sString = num2str(i, ['_s%0' num2str(floor(log10(nSeries))+1) '.f']); outputDir = [mainOutputDir sString]; movieFileName = [movieName sString '.mat']; else outputDir = mainOutputDir; movieFileName = [movieName '.mat']; end % Create output directory if ~isdir(outputDir), mkdir(outputDir); end for iChan = 1:nChan channelArgs = getChannelMetadata(r, iSeries, iChan-1); % Create new channel if extractImages % Read channelName chanName=r.getMetadataStore().getChannelName(iSeries, iChan-1); if isempty(chanName), chanName = ['Channel_' num2str(iChan)]; else chanName = char(chanName.toString); end channelPath{i, iChan} = fullfile(outputDir, chanName); else channelPath{i, iChan} = dataPath; end movieChannels(i, iChan) = Channel(channelPath{i, iChan}, channelArgs{:}); end % Create movie object MD(i) = MovieData(movieChannels(i, :), outputDir, movieArgs{:}); MD(i).setPath(outputDir); MD(i).setFilename(movieFileName); if ~extractImages, MD(i).setSeries(iSeries); end if extractImages nFrames = r.getMetadataStore().getPixelsSizeT(iSeries).getValue; nZ = r.getMetadataStore().getPixelsSizeZ(iSeries).getValue; % Create anonymous functions for reading files tString=@(t)num2str(t, ['%0' num2str(floor(log10(nFrames))+1) '.f']); zString=@(z)num2str(z, ['%0' num2str(floor(log10(nZ))+1) '.f']); imageName = @(c,t,z) [movieName '_w' num2str(movieChannels(i, c).emissionWavelength_) ... '_z' zString(z),'_t' tString(t),'.tif']; % Clean channel directories and save images as TIF files for iChan = 1:nChan, mkClrDir(channelPath{i, iChan}); end for iPlane = 1:r.getImageCount() index = r.getZCTCoords(iPlane - 1); imwrite(bfGetPlane(r, iPlane),[channelPath{i, index(2) + 1} filesep ... imageName(index(2) + 1, index(3) + 1, index(1) + 1)],'tif'); end end % Close reader and check movie sanity MD(i).sanityCheck; end % Close reader r.close; function movieArgs = getMovieMetadata(r, iSeries) % Create movie metadata cell array using read metadata movieArgs={}; pixelSizeX = r.getMetadataStore().getPixelsPhysicalSizeX(iSeries); % Pixel size might be automatically set to 1.0 by @#$% Metamorph hasValidPixelSize = ~isempty(pixelSizeX) && pixelSizeX.getValue ~= 1; if hasValidPixelSize % Convert from microns to nm and check x and y values are equal pixelSizeX= pixelSizeX.getValue*10^3; pixelSizeY= r.getMetadataStore().getPixelsPhysicalSizeY(iSeries).getValue*10^3; assert(isequal(pixelSizeX,pixelSizeY),'Pixel size different in x and y'); movieArgs=horzcat(movieArgs,'pixelSize_',pixelSizeX); end % Camera bit depth camBitdepth = r.getBitsPerPixel(); hasValidCamBitDepth = ~isempty(camBitdepth) && mod(camBitdepth, 2) == 0; if hasValidCamBitDepth movieArgs=horzcat(movieArgs,'camBitdepth_',camBitdepth); end % Time interval timeInterval = r.getMetadataStore().getPixelsTimeIncrement(iSeries); if ~isempty(timeInterval) movieArgs=horzcat(movieArgs,'timeInterval_',double(timeInterval)); end % Lens numerical aperture try % Use a try-catch statement because property is not always defined lensNA=r.getMetadataStore().getObjectiveLensNA(0,0); if ~isempty(lensNA) movieArgs=horzcat(movieArgs,'numAperture_',double(lensNA)); elseif ~isempty(r.getMetadataStore().getObjectiveID(0,0)) % Hard-coded for deltavision files. Try to get the objective id and % read the objective na from a lookup table tokens=regexp(char(r.getMetadataStore().getObjectiveID(0,0).toString),... '^Objective\:= (\d+)$','once','tokens'); if ~isempty(tokens) [na,mag]=getLensProperties(str2double(tokens),{'na','magn'}); movieArgs=horzcat(movieArgs,'numAperture_',na,'magnification_',mag); end end end function channelArgs = getChannelMetadata(r, iSeries, iChan) channelArgs={}; % Read excitation wavelength exwlgth=r.getMetadataStore().getChannelExcitationWavelength(iSeries, iChan); if ~isempty(exwlgth) channelArgs=horzcat(channelArgs, 'excitationWavelength_', exwlgth.getValue); end % Fill emission wavelength emwlgth=r.getMetadataStore().getChannelEmissionWavelength(iSeries, iChan); if isempty(emwlgth) try emwlgth= r.getMetadataStore().getChannelLightSourceSettingsWavelength(iSeries, iChan); end end if ~isempty(emwlgth) channelArgs = horzcat(channelArgs, 'emissionWavelength_', emwlgth.getValue); end
github
mehta-lab/Instantaneous-PolScope-master
userfcn_saveCheckbox.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/userfcn_saveCheckbox.m
1,227
utf_8
b479fb471c7dc40b23b23dc1ff0f48d3
function checked = userfcn_saveCheckbox(handles) % GUI tool function - return the check/uncheck status of checkbox of % processes in package control panel % % Input: % % handles - the "handles" of package control panel movie % % Output: % % checked - array of check/unchecked status 1 - checked, 0 - unchecked % % % Chuangang Ren % 08/2010 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % userData = get(handles.figure1, 'UserData'); l = 1:size(userData.dependM, 1); checked = arrayfun( @(x)( eval(['get(handles.checkbox_' num2str(x) ', ''Value'')']) ), l, 'UniformOutput', true);
github
mehta-lab/Instantaneous-PolScope-master
msgboxGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/msgboxGUI.m
5,702
utf_8
a6b41c4b0e091b74b0b4568dbc79b336
function varargout = msgboxGUI(varargin) % MSGBOXGUI M-file for msgboxGUI.fig % MSGBOXGUI, by itself, creates a new MSGBOXGUI or raises the existing % singleton*. % % H = MSGBOXGUI returns the handle to a new MSGBOXGUI or the handle to % the existing singleton*. % % MSGBOXGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in MSGBOXGUI.M with the given input arguments. % % MSGBOXGUI('Property','Value',...) creates a new MSGBOXGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before msgboxGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to msgboxGUI_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 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help msgboxGUI % Last Modified by GUIDE v2.5 07-Sep-2011 11:43:10 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @msgboxGUI_OpeningFcn, ... 'gui_OutputFcn', @msgboxGUI_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 msgboxGUI is made visible. function msgboxGUI_OpeningFcn(hObject, eventdata, handles, varargin) % % fhandle = msgboxGUI % % fhandle = msgboxGUI(paramName, 'paramValue', ... ) % % Help dialog GUI % % Parameter Field Names: % 'text' -> Help text % 'title' -> Title of text box % 'name'-> Name of dialog box % % Choose default command line output for msgboxGUI handles.output = hObject; % Parse input ip = inputParser; ip.CaseSensitive=false; ip.addRequired('hObject',@ishandle); ip.addRequired('eventdata',@(x) isstruct(x) || isempty(x)); ip.addRequired('handles',@isstruct); ip.addParamValue('text','',@ischar); ip.addParamValue('extendedText','',@ischar); ip.addParamValue('name','',@ischar); ip.addParamValue('title','',@ischar); ip.parse(hObject,eventdata,handles,varargin{:}); % Apply input set(hObject, 'Name',ip.Results.name) set(handles.edit_text, 'String',ip.Results.text) set(handles.text_title, 'string',ip.Results.title) if ~isempty(ip.Results.extendedText), userData = get(handles.figure1,'UserData'); set(handles.pushbutton_extendedText,'Visible','on'); userData.text = ip.Results.text; userData.extendedText=ip.Results.extendedText; userData.type='basic'; set(handles.figure1,'UserData',userData); end % Update handles structure uicontrol(handles.pushbutton_done) guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = msgboxGUI_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 pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) delete(handles.figure1) % --- Executes on key press with focus on figure1 or any of its controls. function figure1_WindowKeyPressFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata structure with the following fields (see FIGURE) % Key: name of the key that was pressed, in lower case % Character: character interpretation of the key(s) that was pressed % Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed % handles structure with handles and user data (see GUIDATA) if strcmp(eventdata.Key, 'return'), delete(hObject); end % --- Executes on button press in pushbutton_extendedText. function pushbutton_extendedText_Callback(hObject, eventdata, handles) % hObject handle to pushbutton_extendedText (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) userData=get(handles.figure1,'UserData'); if strcmp(userData.type,'basic') userData.type='extended'; set(handles.edit_text, 'String',userData.extendedText); set(hObject,'String','See basic report...'); else userData.type='basic'; set(handles.edit_text, 'String',userData.text); set(hObject,'String','See extended report...'); end set(handles.figure1,'UserData',userData); guidata(hObject,handles);
github
mehta-lab/Instantaneous-PolScope-master
plotScaleBar.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/plotScaleBar.m
3,905
utf_8
d298498fbdcc4d3c5a5f154b781bcc02
%plotScaleBar(width, varargin) adds a scale bar to a figure. % % Inputs: width : width of the scale bar, in x-axis units. % h : axes handle. If empty, current axes ('gca') are used. % varargin : optional inputs, always in name/value pairs: % 'Location' : {'NorthEast', 'SouthEast', 'SouthWest', 'NorthWest'} % 'Label' : string % 'FontName' % 'FontSize' % % Ouput: hScalebar : handle to the patch graphic object and text graphic % object if applicable % % Example: plotScalebar(500, [], 'Label', '500 nm', 'Location', 'SouthEast'); % % % Note: there is a bug in '-depsc2' as of Matlab2010b, which misprints patches. % When printing, use 'depsc' instead. % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Francois Aguet, March 14 2011 (last modified 07/26/2011) function hScaleBar = plotScaleBar(width, varargin) ip = inputParser; ip.CaseSensitive = false; ip.addRequired('width', @isscalar); % same units as axes ip.addOptional('height', width/10, @isscalar); % height of the scale bar ip.addParamValue('Handle', gca, @ishandle) ip.addParamValue('Location', 'southwest', @(x) any(strcmpi(x, {'northeast', 'southeast', 'southwest', 'northwest'}))); ip.addParamValue('Label', [], @(x) ischar(x) || isempty(x)); ip.addParamValue('FontName', 'Helvetica', @ischar); ip.addParamValue('FontSize', [], @isscalar); ip.addParamValue('Color', [1 1 1], @(x) isvector(x) && numel(x)==3); ip.parse(width, varargin{:}); label = ip.Results.Label; fontName = ip.Results.FontName; fontSize = ip.Results.FontSize; color = ip.Results.Color; height = ip.Results.height; location = lower(ip.Results.Location); XLim = get(ip.Results.Handle, 'XLim'); YLim = get(ip.Results.Handle, 'YLim'); lx = diff(XLim); ly = diff(YLim); dx = ly/20; % distance from border if ~isempty(label) if isempty(fontSize) fontSize = 3*height/ly; % normalized units end % get height of default text bounding box h = text(0, 0, label, 'FontUnits', 'normalized', 'FontName', fontName, 'FontSize', fontSize); extent = get(h, 'extent'); % units: pixels textHeight = 1.2*extent(4); textWidth = extent(3); delete(h); else textHeight = dx; textWidth = 0; end hold(ip.Results.Handle, 'on'); set(gcf, 'InvertHardcopy', 'off'); if ~isempty(strfind(location, 'north')) y0 = dx; else y0 = ly-height-textHeight; end if ~isempty(strfind(location, 'east')) x0 = lx-width-dx; else x0 = dx; end x0 = x0+XLim(1); y0 = y0+YLim(1); % text alignment if > scalebar width if textWidth > width if ~isempty(strfind(ip.Results.Location, 'west')) halign = 'left'; tx = x0; else halign = 'right'; tx = x0+width; end else halign = 'center'; tx = x0+width/2; end textProps = {'Color', color, 'FontUnits', 'normalized',... 'FontName', fontName, 'FontSize', fontSize,... 'VerticalAlignment', 'Top',... 'HorizontalAlignment', halign}; hScaleBar(1) = fill([x0 x0+width x0+width x0], [y0+height y0+height y0 y0],... color, 'EdgeColor', 'none', 'Parent', ip.Results.Handle); if ~isempty(label) hScaleBar(2) = text(tx, y0+height, label, textProps{:}, 'Parent', ip.Results.Handle); end
github
mehta-lab/Instantaneous-PolScope-master
cropMovieGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/cropMovieGUI.m
13,292
utf_8
f1df0ac075f95cc1798e8c14dc2159f6
function varargout = cropMovieGUI(varargin) % cropMovieGUI M-file for cropMovieGUI.fig % cropMovieGUI, by itself, creates a new cropMovieGUI or raises the existing % singleton*. % % H = cropMovieGUI returns the handle to a new cropMovieGUI or the handle to % the existing singleton*. % % cropMovieGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in cropMovieGUI.M with the given input arguments. % % cropMovieGUI('Property','Value',...) creates a new cropMovieGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before cropMovieGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to cropMovieGUI_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 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help cropMovieGUI % Last Modified by GUIDE v2.5 30-Sep-2011 15:09:12 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @cropMovieGUI_OpeningFcn, ... 'gui_OutputFcn', @cropMovieGUI_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 cropMovieGUI is made visible. function cropMovieGUI_OpeningFcn(hObject,eventdata,handles,varargin) % Check input % The mainFig and procID should always be present % procCOnstr and procName should only be present if the concrete process % initation is delegated from an abstract class. Else the constructor will % be directly read from the package constructor list. ip = inputParser; ip.addRequired('hObject',@ishandle); ip.addRequired('eventdata',@(x) isstruct(x) || isempty(x)); ip.addRequired('handles',@isstruct); ip.addOptional('MD',[],@(x)isa(x,'MovieData')); ip.addParamValue('mainFig',-1,@ishandle); ip.parse(hObject,eventdata,handles,varargin{:}); userData.MD =ip.Results.MD; userData.mainFig =ip.Results.mainFig; % Set up copyright statement set(handles.text_copyright, 'String',userfcn_softwareConfig(handles)); % Set up available input channels set(handles.listbox_selectedChannels,'String',userData.MD.getChannelPaths(), ... 'UserData',1:numel(userData.MD.channels_)); % Save the image directories and names (for cropping preview) userData.nFrames = userData.MD.nFrames_; userData.imRectHandle.isvalid=0; userData.cropROI = [1 1 userData.MD.imSize_(end:-1:1)]; userData.previewFig=-1; % Read the first image and update the sliders max value and steps props = get(handles.listbox_selectedChannels, {'UserData','Value'}); userData.chanIndx = props{1}(props{2}); set(handles.edit_frameNumber,'String',1); set(handles.slider_frameNumber,'Min',1,'Value',1,'Max',userData.nFrames,... 'SliderStep',[1/max(1,double(userData.nFrames-1)) 10/max(1,double(userData.nFrames-1))]); userData.imIndx=1; userData.imData=mat2gray(userData.MD.channels_(userData.chanIndx).loadImage(userData.imIndx)); set(handles.listbox_selectedChannels,'Callback',@(h,event) update_data(h,event,guidata(h))); set(handles.edit_firstFrame,'String',1); set(handles.edit_lastFrame,'String',userData.nFrames); % Choose default command line output for cropMovieGUI handles.output = hObject; % Update user data and GUI data set(hObject, 'UserData', userData); guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = cropMovieGUI_OutputFcn(~, ~, 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 pushbutton_cancel. function pushbutton_cancel_Callback(~, ~, handles) % Delete figure delete(handles.figure1); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, ~, handles) % Notify the package GUI that the setting panel is closed userData = get(handles.figure1, 'UserData'); if isfield(userData, 'helpFig') && ishandle(userData.helpFig) delete(userData.helpFig) end if ishandle(userData.previewFig), delete(userData.previewFig); end set(handles.figure1, 'UserData', userData); guidata(hObject,handles); % --- Executes on key press with focus on pushbutton_crop and none of its controls. function pushbutton_crop_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_crop, [], handles); end % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_crop, [], handles); end % --- Executes on button press in checkbox_crop. function update_data(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); % Retrieve the channel index props=get(handles.listbox_selectedChannels,{'UserData','Value'}); chanIndx = props{1}(props{2}); imIndx = get(handles.slider_frameNumber,'Value'); % Load a new image if either the image number or the channel has been changed if (chanIndx~=userData.chanIndx) || (imIndx~=userData.imIndx) % Update image flag and dat userData.imData=mat2gray(userData.MD.channels_(chanIndx).loadImage(imIndx)); userData.updateImage=1; userData.chanIndx=chanIndx; userData.imIndx=imIndx; % Update roi if userData.imRectHandle.isvalid userData.cropROI=getPosition(userData.imRectHandle); end else userData.updateImage=0; end % In case of crop previewing mode if get(handles.checkbox_crop,'Value') % Create figure if non-existing or closed if ~isfield(userData, 'previewFig') || ~ishandle(userData.previewFig) userData.previewFig = figure('Name','Select the region to crop',... 'DeleteFcn',@close_previewFig,'UserData',handles.figure1); userData.newFigure = 1; else figure(userData.previewFig); userData.newFigure = 0; end % Retrieve the image object handle imHandle =findobj(userData.previewFig,'Type','image'); if userData.newFigure || userData.updateImage if isempty(imHandle) imHandle=imshow(userData.imData); axis off; else set(imHandle,'CData',userData.imData); end end if userData.imRectHandle.isvalid % Update the imrect position setPosition(userData.imRectHandle,userData.cropROI) else % Create a new imrect object and store the handle userData.imRectHandle = imrect(get(imHandle,'Parent'),userData.cropROI); fcn = makeConstrainToRectFcn('imrect',get(imHandle,'XData'),get(imHandle,'YData')); setPositionConstraintFcn(userData.imRectHandle,fcn); end else % Save the roi if applicable if userData.imRectHandle.isvalid, userData.cropROI=getPosition(userData.imRectHandle); end % Close the figure if applicable if ishandle(userData.previewFig), delete(userData.previewFig); end end set(handles.figure1, 'UserData', userData); guidata(hObject,handles); function close_previewFig(hObject, eventdata) handles = guidata(get(hObject,'UserData')); set(handles.checkbox_crop,'Value',0); update_data(handles.checkbox_crop, eventdata, handles); % --- Executes on slider movement. function frameNumberEdition_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); % Retrieve the value of the selected image if strcmp(get(hObject,'Tag'),'edit_frameNumber') frameNumber = str2double(get(handles.edit_frameNumber, 'String')); else frameNumber = get(handles.slider_frameNumber, 'Value'); end frameNumber=round(frameNumber); % Check the validity of the frame values if isnan(frameNumber) warndlg('Please provide a valid frame value.','Setting Error','modal'); end frameNumber = min(max(frameNumber,1),userData.nFrames); % Store value set(handles.slider_frameNumber,'Value',frameNumber); set(handles.edit_frameNumber,'String',frameNumber); % Save data and update graphics set(handles.figure1, 'UserData', userData); guidata(hObject, handles); update_data(hObject,eventdata,handles); % --- Executes on button press in pushbutton_outputDirectory. function pushbutton_outputDirectory_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); pathname = uigetdir(userData.MD.movieDataPath_,'Select output directory'); % Test uigetdir output and store its results if isequal(pathname,0), return; end set(handles.edit_outputDirectory,'String',pathname); % Save data set(handles.figure1,'UserData',userData); guidata(hObject, handles); % --- Executes on button press in pushbutton_addfile. function pushbutton_addfile_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); [filename, pathname]=uigetfile({'*.tif;*.TIF;*.stk;*.STK;*.bmp;*.BMP;*.jpg;*.JPG',... 'Image files (*.tif,*.stk,*.bmp,*.jpg)'},... 'Select the reference frame',userData.MD.movieDataPath_); % Test uigetdir output and store its results if isequal(pathname,0) || isequal(filename,0), return; end files = get(handles.listbox_additionalFiles,'String'); if any(strcmp([pathname filename],files)),return; end files{end+1} = [pathname filename]; set(handles.listbox_additionalFiles,'String',files,'Value',numel(files)); % --- Executes on button press in pushbutton_removeFile. function pushbutton_removeFile_Callback(hObject, eventdata, handles) props = get(handles.listbox_additionalFiles,{'String','Value'}); if isempty(props{1}), return; end files= props{1}; files(props{2})=[]; set(handles.listbox_additionalFiles,'String',files,'Value',max(1,props{2}-1)); % --- Executes on button press in pushbutton_crop. function pushbutton_crop_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); % Check valid output directory outputDirectory = get(handles.edit_outputDirectory,'String'); if isempty(outputDirectory), errordlg('Please select an output directory','Error','modal'); end % Read cropROI if crop window is still visible if userData.imRectHandle.isvalid userData.cropROI=getPosition(userData.imRectHandle); end % Read cropTOI firstFrame = str2double(get(handles.edit_firstFrame,'String')); lastFrame = str2double(get(handles.edit_lastFrame,'String')); cropTOI=firstFrame:lastFrame; additionalFiles= get(handles.listbox_additionalFiles,'String'); if isempty(additionalFiles) filesArgs={}; else filesArgs={'additionalFiles',additionalFiles}; end % Call the crop routine MD = cropMovie(userData.MD,outputDirectory,'cropROI',userData.cropROI,... 'cropTOI',cropTOI,filesArgs{:}); % If new MovieData was created (from movieSelectorGUI) if userData.mainFig ~=-1, % Retrieve main window userData userData_main = get(userData.mainFig, 'UserData'); % Append new ROI to movie selector panel userData_main.MD = cat(2, userData_main.MD, MD); set(userData.mainFig, 'UserData', userData_main) movieSelectorGUI('refreshDisplay',userData.mainFig,... eventdata,guidata(userData.mainFig)); end % Delete current window delete(handles.figure1) function edit_firstFrame_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); firstFrame = str2double(get(handles.edit_firstFrame,'String')); lastFrame = str2double(get(handles.edit_lastFrame,'String')); if ~ismember(firstFrame,1:userData.nFrames) || firstFrame>lastFrame set(handles.edit_firstFrame,'String',1) end function edit_lastFrame_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); firstFrame = str2double(get(handles.edit_firstFrame,'String')); lastFrame = str2double(get(handles.edit_lastFrame,'String')); if ~ismember(lastFrame,1:userData.nFrames) || firstFrame>lastFrame set(handles.edit_lastFrame,'String',userData.nFrames) end
github
mehta-lab/Instantaneous-PolScope-master
padarrayXT.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/padarrayXT.m
9,977
utf_8
b5dfc4e9473b41fe46216ba08a849299
function b = padarrayXT(varargin) %PADARRAYXT Modified version of built-in function 'padarray'. % Mirroring ('symmetric' option) does not duplicate the border pixel. % B = PADARRAYXT(A,PADSIZE) pads array A with PADSIZE(k) number of zeros % along the k-th dimension of A. PADSIZE should be a vector of % nonnegative integers. % % B = PADARRAYXT(A,PADSIZE,PADVAL) pads array A with PADVAL (a scalar) % instead of with zeros. % % B = PADARRAYXT(A,PADSIZE,PADVAL,DIRECTION) pads A in the direction % specified by the string DIRECTION. DIRECTION can be one of the % following strings. % % String values for DIRECTION % 'pre' Pads before the first array element along each % dimension . % 'post' Pads after the last array element along each % dimension. % 'both' Pads before the first array element and after the % last array element along each dimension. % % By default, DIRECTION is 'both'. % % B = PADARRAYXT(A,PADSIZE,METHOD,DIRECTION) pads array A using the % specified METHOD. METHOD can be one of these strings: % % String values for METHOD % 'circular' Pads with circular repetition of elements. % 'replicate' Repeats border elements of A. % 'symmetric' Pads array with mirror reflections of itself. % 'asymmetric' Pads array with odd-symmetric extensions of itself. % % Class Support % ------------- % When padding with a constant value, A can be numeric or logical. % When padding using the 'circular', 'replicate', or 'symmetric' % methods, A can be of any class. B is of the same class as A. % % Example % ------- % Add three elements of padding to the beginning of a vector. The % padding elements contain mirror copies of the array. % % b = padarrayxt([1 2 3 4],3,'symmetric','pre') % % Add three elements of padding to the end of the first dimension of % the array and two elements of padding to the end of the second % dimension. Use the value of the last array element as the padding % value. % % B = padarrayxt([1 2; 3 4],[3 2],'replicate','post') % % Add three elements of padding to each dimension of a % three-dimensional array. Each pad element contains the value 0. % % A = [1 2; 3 4]; % B = [5 6; 7 8]; % C = cat(3,A,B) % D = padarray(C,[3 3],0,'both') % % See also CIRCSHIFT, IMFILTER. % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Copyright 1993-2010 The MathWorks, Inc. % $Revision: 1.11.4.13 $ $Date: 2011/08/09 17:51:33 $ % Last modified on 04/14/2012 by Francois Aguet. [a, method, padSize, padVal, direction] = ParseInputs(varargin{:}); if isempty(a) % treat empty matrix similar for any method if strcmp(direction,'both') sizeB = size(a) + 2*padSize; else sizeB = size(a) + padSize; end b = mkconstarray(class(a), padVal, sizeB); elseif strcmpi(method,'constant') % constant value padding with padVal b = ConstantPad(a, padSize, padVal, direction); else % compute indices then index into input image aSize = size(a); aIdx = getPaddingIndices(aSize,padSize,method,direction); b = a(aIdx{:}); end if islogical(a) b = logical(b); end %%% %%% ConstantPad %%% function b = ConstantPad(a, padSize, padVal, direction) numDims = numel(padSize); % Form index vectors to subsasgn input array into output array. % Also compute the size of the output array. idx = cell(1,numDims); sizeB = zeros(1,numDims); for k = 1:numDims M = size(a,k); switch direction case 'pre' idx{k} = (1:M) + padSize(k); sizeB(k) = M + padSize(k); case 'post' idx{k} = 1:M; sizeB(k) = M + padSize(k); case 'both' idx{k} = (1:M) + padSize(k); sizeB(k) = M + 2*padSize(k); end end % Initialize output array with the padding value. Make sure the % output array is the same type as the input. b = mkconstarray(class(a), padVal, sizeB); b(idx{:}) = a; %%% %%% ParseInputs %%% function [a, method, padSize, padVal, direction] = ParseInputs(varargin) % narginchk(2,4); if nargin<2 || nargin>4 error('Incompatible number of input arguments.'); end % fixed syntax args a = varargin{1}; padSize = varargin{2}; % default values method = 'constant'; padVal = 0; direction = 'both'; validateattributes(padSize, {'double'}, {'real' 'vector' 'nonnan' 'nonnegative' ... 'integer'}, mfilename, 'PADSIZE', 2); % Preprocess the padding size if (numel(padSize) < ndims(a)) padSize = padSize(:); padSize(ndims(a)) = 0; end if nargin > 2 firstStringToProcess = 3; if ~ischar(varargin{3}) % Third input must be pad value. padVal = varargin{3}; validateattributes(padVal, {'numeric' 'logical'}, {'scalar'}, ... mfilename, 'PADVAL', 3); firstStringToProcess = 4; end for k = firstStringToProcess:nargin validStrings = {'circular' 'replicate' 'symmetric' 'pre' ... 'post' 'both'}; string = validatestring(varargin{k}, validStrings, mfilename, ... 'METHOD or DIRECTION', k); switch string case {'circular' 'replicate' 'symmetric'} method = string; case {'pre' 'post' 'both'} direction = string; otherwise error(message('images:padarray:unexpectedError')) end end end % Check the input array type if strcmp(method,'constant') && ~(isnumeric(a) || islogical(a)) error(message('images:padarray:badTypeForConstantPadding')) end % Internal functions called by padarray.m (modified) function aIdx = getPaddingIndices(aSize,padSize,method,direction) %getPaddingIndices is used by padarray and blockproc. % Computes padding indices of input image. This is function is used to % handle padding of in-memory images (via padarray) as well as % arbitrarily large images (via blockproc). % % aSize : result of size(I) where I is the image to be padded % padSize : padding amount in each dimension. % numel(padSize) can be greater than numel(aSize) % method : X or a 'string' padding method % direction : pre, post, or both. % % See the help for padarray for additional information. % Copyright 2010 The MathWorks, Inc. % $Revision: 1.1.6.1 $ $Date: 2010/04/15 15:18:15 $ % make sure we have enough image dims for the requested padding if numel(padSize) > numel(aSize) singleton_dims = numel(padSize) - numel(aSize); aSize = [aSize ones(1,singleton_dims)]; end switch method case 'circular' aIdx = CircularPad(aSize, padSize, direction); case 'symmetric' aIdx = SymmetricPad(aSize, padSize, direction); case 'replicate' aIdx = ReplicatePad(aSize, padSize, direction); end %%% %%% CircularPad %%% function idx = CircularPad(aSize, padSize, direction) numDims = numel(padSize); % Form index vectors to subsasgn input array into output array. % Also compute the size of the output array. idx = cell(1,numDims); for k = 1:numDims M = aSize(k); dimNums = uint32(1:M); p = padSize(k); switch direction case 'pre' idx{k} = dimNums(mod(-p:M-1, M) + 1); case 'post' idx{k} = dimNums(mod(0:M+p-1, M) + 1); case 'both' idx{k} = dimNums(mod(-p:M+p-1, M) + 1); end end %%% %%% SymmetricPad %%% function idx = SymmetricPad(aSize, padSize, direction) numDims = numel(padSize); % Form index vectors to subsasgn input array into output array. % Also compute the size of the output array. idx = cell(1,numDims); for k = 1:numDims M = aSize(k); if M>1 dimNums = uint32([1:M M-1:-1:2]); div = 2*M-2; else dimNums = [1 1]; div = 2; end p = padSize(k); switch direction case 'pre' idx{k} = dimNums(mod(-p:M-1, div) + 1); case 'post' idx{k} = dimNums(mod(0:M+p-1, div) + 1); case 'both' idx{k} = dimNums(mod(-p:M+p-1, div) + 1); end end %%% %%% ReplicatePad %%% function idx = ReplicatePad(aSize, padSize, direction) numDims = numel(padSize); % Form index vectors to subsasgn input array into output array. % Also compute the size of the output array. idx = cell(1,numDims); for k = 1:numDims M = aSize(k); p = padSize(k); onesVector = uint32(ones(1,p)); switch direction case 'pre' idx{k} = [onesVector 1:M]; case 'post' idx{k} = [1:M M*onesVector]; case 'both' idx{k} = [onesVector 1:M M*onesVector]; end end function out = mkconstarray(class, value, size) %MKCONSTARRAY creates a constant array of a specified numeric class. % A = MKCONSTARRAY(CLASS, VALUE, SIZE) creates a constant array % of value VALUE and of size SIZE. % Copyright 1993-2003 The MathWorks, Inc. % $Revision: 1.8.4.1 $ $Date: 2003/01/26 06:00:35 $ out = repmat(feval(class, value), size);
github
mehta-lab/Instantaneous-PolScope-master
getFluorPropStruct.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/getFluorPropStruct.m
2,135
utf_8
0c9e124473a898979cc7662fb1aed3af
% Values from http://www.olympusfluoview.com/applications/fpcolorpalette.html % Alexa Fluors: http://www.invitrogen.com/site/us/en/home/References/Molecular-Probes-The-Handbook/Technical-Notes-and-Product-Highlights/The-Alexa-Fluor-Dye-Series.html % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Francois Aguet, October 2010 function s = getFluorPropStruct() s(1).name = 'bfp'; s(1).lambda_em = 440e-9; s(2).name = 'ebfp'; s(2).lambda_em = 440e-9; s(3).name = 'cfp'; s(3).lambda_em = 475e-9; s(4).name = 'egfp'; s(4).lambda_em = 507e-9; s(5).name = 'gfp'; s(5).lambda_em = 509e-9; s(6).name = 'alexa488'; s(6).lambda_em = 519e-9; s(7).name = 'yfp'; s(7).lambda_em = 527e-9; s(8).name = 'alexa555'; s(8).lambda_em = 565e-9; s(9).name = 'dtomato'; s(9).lambda_em = 581e-9; s(10).name = 'tdtomato'; s(10).lambda_em = 581e-9; s(11).name = 'dsred'; s(11).lambda_em = 583e-9; s(12).name = 'tagrfp'; s(12).lambda_em = 584e-9; s(13).name = 'alexa568'; s(13).lambda_em = 603e-9; s(14).name = 'rfp'; s(14).lambda_em = 607e-9; s(15).name = 'mrfp'; s(15).lambda_em = 607e-9; s(16).name = 'mcherry'; s(16).lambda_em = 610e-9; s(17).name = 'texasred'; s(17).lambda_em = 615e-9; s(18).name = 'alexa647'; s(18).lambda_em = 665e-9; s(19).name = 'cy3'; s(19).lambda_em = 570e-9; s(20).name = 'cy5'; s(20).lambda_em = 670e-9; s(21).name = 'alexa594'; s(21).lambda_em = 617e-9; s(22).name = 'dapi'; s(22).lambda_em = 470e-9; s(23).name = 'fluosphere605'; s(23).lambda_em = 605e-9; [~,i]=sort([s.lambda_em]); s=s(i);
github
mehta-lab/Instantaneous-PolScope-master
trackStackFlow.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/trackStackFlow.m
27,283
utf_8
fe2a7c5655b0d3cfc4c4cfc2acdfe370
function [v,corLength,sigtVal] = trackStackFlow(stack,points,minCorL,varargin) %trackStackFlow: Calculate the flow velocity from a stack of movie images. % % SYNOPSIS : % v = trackStackFlow(stack,points,minCorL) % [v,corLen] = trackStackFlow(stack,points,minCorL,maxCorL,varargin) % [v,corLen,sigtVal] = trackStackFlow(stack,points,minCorL,maxCorL,varargin) % % INPUT : % stack : An image stack (i.e. of dimensions n x m x l) to be correlated % % points : A set of points (size nP x 2) expressed in the xy % coordinate system where the velocity is calculated. % % minCorL : The minimum side length of an image block (or band) % that is to be cross correlated over frames to detect flow % velocity. Optimal block size will be searched in the range % [minCorL maxCorL] for the detection of coherent flow pattern % behind noisy data. % % maxCorL : Optional - The maximum side length of an image block (or band) % that is to be cross correlated over frames to detect flow % velocity. Optimal block size will be searched in the range % [minCorL maxCorL] for the detection of coherent flow pattern % behind noisy data. % If not input, will be set to minCorL % % The following optional parameters can be set as parameter/value pairs: % % 'bgAvgImg': A stack of stationary background frames to be substracted % during image correlation. Default is zeros matrix. % % 'maxSpd' : A numerical value that specifies the maximum speed that can % be detected (in pixels/frame). The default is 10. % % 'bgMask': A stack of background masks which is used to remove % background pixels from being used in correlation. % % 'minFeatureSize': The minimum feature size in the image. This is % measured as the diameter of features. % Default, 11 pixels (typical speckle size). % % OUTPUT : % v : velocity vector of (size nP x2) expressed in the xy % coordinate system. % % corLen : The optimal block length in the sense that it is the minimum % block length in the range [minCorLen, maxCorLe] that gives a % stable coherent flow. % % sigtVal : The 1st, 2nd local maximum and the reference score for % significance test can also be output for use in % postprocessing. % % References: % J. Li & G. Danuser, J. of microscopy, 220 150-167, 2005. % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Lin Ji, 2005 % Sebastien Besson, May 2011 (last modified Nov 2011) % Adapted from imFlowTrack.m % Input check ip= inputParser; ip.addRequired('stack',@(x) isnumeric(x) && size(x,3)>=2); ip.addRequired('points',@(x) isnumeric(x) && size(x,2)==2); ip.addRequired('minCorL',@isscalar); ip.addOptional('maxCorL',minCorL,@isscalar); ip.addParamValue('maxSpd',10,@isscalar); ip.addParamValue('bgMask',true(size(stack)),@(x) isequal(size(x),size(stack))); ip.addParamValue('bgAvgImg', zeros(size(stack)),@isnumeric); ip.addParamValue('minFeatureSize',11,@isscalar); ip.parse(stack,points,minCorL,varargin{:}); maxCorL=ip.Results.maxCorL; maxSpd=ip.Results.maxSpd; minFeatureSize=ip.Results.minFeatureSize; bgMask=ip.Results.bgMask; bgAvgImg=ip.Results.bgAvgImg; %We automatically update the speed search radius until a high limit is % reached. If no significant maximum is detected, it means either the image % quality is bad or the flow velocity is even higher than this limit. maxSpdLimit = 2*maxSpd; [imgW imgL numFrames] = size(stack); x=points(:,1); y=points(:,2); %Initial maximum speed components in both direction. initMaxFlowSpd = 5; initMaxPerpSpd = 5; closenessThreshold = 0.25; %For isotropic correlation. maxSpdLimit = max(maxSpdLimit,initMaxFlowSpd); % Initialize output nPoints = size(points,1); v = zeros(nPoints,2); corLength = minCorL*ones(nPoints,1); sigtValues = NaN*ones(nPoints,3); %We calculate a score for each sampling velocity. The score is an average of % the normalized cross-correlation coefficient of an image block that moves % over consecutive frames at the sampling velocity. We sample the velocity % by sampling the components of the velocity in two orthogonal directions and % in the range [-maxSpd maxSpd]. The two orthogonal directions are parallel to % the two sides of the square block. bandDir = [1 0]; perpDir = [-bandDir(2) bandDir(1)]; %We only use odd correlation lengths greater than 3 pixels minCorL = max(3,minCorL+(1-mod(minCorL,2))); maxCorL = max(minCorL,maxCorL+(1-mod(maxCorL,2))); bAreaThreshold = min(0.95*minCorL^2,maxCorL^2*0.5); %Options for optimization. options = optimset('GradObj','on','Display','off'); % Creates the format string for the numerical indexes L=length(num2str(nPoints)); strg=sprintf('%%.%dd',L); backSpc =repmat('\b',1,L); %Calculate the correlation coefficient for each sampling velocity at % each point. startTime = cputime; fprintf(1,[' Start tracking (total: ' strg ' points): '],nPoints); for k = 1:nPoints fprintf(1,[strg ' ...'],k); sigtVal = [NaN NaN NaN]; %Always get back the initial max speed for the new point. maxFlowSpd = initMaxFlowSpd; maxPerpSpd = initMaxPerpSpd; %Alway start with 'minCorL' for each new point. corL = minCorL; pass = 0; while pass == 0 && corL <= maxCorL %Create kymograph around each point. 'bandDir' is used as the direction % of the kymographed line. xI = round(x(k)); yI = round(y(k)); if xI < 1 || xI > imgL || yI < 1 || yI > imgW %The point is outside the image. Mark it untrackable. pass = 0; corL = 2*maxCorL; continue; end %Always get back the initial max speed for new 'corL'. % We devide the max speed by 2 due the use of the while loop below. maxFlowSpd = initMaxFlowSpd/2; maxPerpSpd = initMaxPerpSpd/2; %Flag that indicates the quality of the score. pass = 0; while pass == 0 && maxFlowSpd < maxSpdLimit && maxPerpSpd < maxSpdLimit %If the quality of the score function is not good enough (pass == 0), % we increase the max sampling speed until the limit is reached. maxFlowSpd = min(maxSpdLimit,maxFlowSpd*2); maxPerpSpd = min(maxSpdLimit,maxPerpSpd*2); %Get sampling speed. Make sure it will not shift the template (block) outside of % the image area. We also use bigger stepsize for large speed. minSpdF = -min(floor(maxFlowSpd),max(0,xI-corL-1)); maxSpdF = min(floor(maxFlowSpd),imgL-min(xI+corL,imgL)); dv = max(1,ceil(abs(minSpdF)/10)); vF = minSpdF:dv:min(0,maxSpdF); if vF(end) ~= 0 vF(end+1) = 0; end dv = max(1,ceil(abs(maxSpdF)/10)); vF = [vF vF(end)+dv:dv:maxSpdF]; minSpdP = -min(floor(maxPerpSpd),max(0,yI-corL-1)); maxSpdP = min(floor(maxPerpSpd),imgW-min(yI+corL,imgW)); dv = max(1,ceil(abs(minSpdP)/10)); vP = minSpdP:dv:min(0,maxSpdP); if vP(end) ~= 0 vP(end+1) = 0; end dv = max(1,ceil(abs(maxSpdP)/10)); vP = [vP vP(end)+dv:dv:maxSpdP]; %Debugging vF = minSpdF:maxSpdF; vP = minSpdP:maxSpdP; %End of debugging hCLL = min(xI-1,corL)+max(-vF(1),0); hCLR = min(imgL-xI,corL)+max(vF(end),0); hCWL = min(yI-1,corL)+max(-vP(1),0); hCWR = min(imgW-yI,corL)+max(vP(end),0); cropL = hCLL+hCLR+1; cropW = hCWL+hCWR+1; kym = zeros(cropW,cropL,numFrames); for k2 = 1:numFrames kym(:,:,k2) = double(stack(yI-hCWL:yI+hCWR,xI-hCLL:xI+hCLR,k2)); end kymMask = squeeze(bgMask(yI-hCWL:yI+hCWR,xI-hCLL:xI+hCLR,:)); kymAvgImg = bgAvgImg(yI-hCWL:yI+hCWR,xI-hCLL:xI+hCLR,:); %The index of zero velocity. zeroI = [find(vP==0) find(vF==0)]; %The index of the center of image block in the kymographed or cropped % image. centerI = [hCWL+1,hCLL+1]; [score,blockIsTooSmall] = calScore(kym,centerI,corL,vP,vF, ... 'bAreaThreshold',bAreaThreshold,'kymMask',kymMask,'kymAvgImg',kymAvgImg); if blockIsTooSmall %Tell the program to increase block size. pass = 0; maxFlowSpd = Inf; maxPerpSpd = Inf; else %Test the quality of the score function and find the index of the % maximum score. [pass,locMaxI,sigtVal] = findMaxScoreI(score,zeroI,minFeatureSize); if pass == 0 || corL < maxCorL %Increase the block length and width by a factor of 5/4 to see if % the ambiguity can be resovled. Also by comparing the two % velocities returned from two block sizes, we identify the % optimal block size that gives a coherent flow. [score2] = calScore(kym,centerI,ceil(1.25*corL),... vP,vF,'bAreaThreshold',bAreaThreshold,... 'kymMask',kymMask,'kymAvgImg',kymAvgImg); [pass2,maxI2] = findMaxScoreI(score2,zeroI,minFeatureSize); if pass2 == 1 sp = csape({vP,vF},score2); dsp1 = fnder(sp,[1,0]); dsp2 = fnder(sp,[0,1]); % SB: here Jin Li was using a spline to refine the % velocity estimation. This creates a bottleneck in % terms of speed execution. % Maybe looking at the local neighborhood and % fitting a 2D parabola to extract sub-pixel % maximum woudl be a good idea in future % development of the function maxV2 = [vP(maxI2(1)) vF(maxI2(2))]; maxV2 = fmincon(@vFun,maxV2,[],[],[],[], ... [max(vP(1),maxV2(1)-2) max(vF(1),maxV2(2)-2)], ... [min(vP(end),maxV2(1)+2), min(vF(end),maxV2(2)+2)],[], ... options,sp,dsp1,dsp2); sp = csape({vP,vF},score); dsp1 = fnder(sp,[1,0]); dsp2 = fnder(sp,[0,1]); locMaxV = [vP(locMaxI(:,1)).' vF(locMaxI(:,2)).']; for j = 1:size(locMaxI,1) maxV1 = locMaxV(j,:); maxV = fmincon(@vFun,maxV1, [],[],[],[], ... [max(vP(1),maxV1(1)-2) max(vF(1),maxV1(2)-2)], ... [min(vP(end),maxV1(1)+2), min(vF(end),maxV1(2)+2)],[], ... options,sp,dsp1,dsp2); locMaxV(j,:) = maxV; end distToMaxV2 = sqrt(sum((locMaxV- ... ones(size(locMaxV,1),1)*maxV2).^2,2)); [minD,ind] = min(distToMaxV2); maxV = locMaxV(ind,:); maxVNorm = max(norm(maxV2),norm(maxV)); if maxVNorm == 0 || ... (pass == 1 && minD < 2*closenessThreshold*maxVNorm) || ... (pass == 1 && maxVNorm < 0.5) || ... (pass == 0 && minD < closenessThreshold*maxVNorm) pass = 2; else pass = 0; end else pass = 0; end else maxI = locMaxI; end end end if pass == 0 if corL == maxCorL corL = Inf; else corL = min(maxCorL,floor(corL*3/2)); end end end if pass == 0 maxV = [NaN NaN]; sigtVal = [NaN NaN NaN]; elseif pass == 1 sp = csape({vP,vF},score); dsp1 = fnder(sp,[1,0]); dsp2 = fnder(sp,[0,1]); maxV = [vP(maxI(1)) vF(maxI(2))]; maxV = fmincon(@vFun,maxV,[],[],[],[], ... [max(vP(1),maxV(1)-2) max(vF(1),maxV(2)-2)], ... [min(vP(end),maxV(1)+2), min(vF(end),maxV(2)+2)],[], ... options,sp,dsp1,dsp2); end if ~isnan(maxV(1)) && ~isnan(maxV(2)) rotv= maxV*[perpDir;bandDir]; v(k,:) = [rotv(1) rotv(2)]; else v(k,:) = [NaN NaN]; end corLength(k) = corL; sigtValues(k,:) = sigtVal; fprintf(1,[backSpc '\b\b\b\b']); end nanInd = find(isnan(v(:,1))); endTime = cputime; fprintf(1,[strg '.\n'],nPoints); fprintf(1,' Tracking is done in %f sec (%f sec per point).\n', ... endTime-startTime,(endTime-startTime)/nPoints); fprintf(1,' Total tracked points: %d (out of %d).\n', ... nPoints-length(nanInd),nPoints); function [f,df] = vFun(v,pp,dpp1,dpp2) f = -fnval(pp,v.'); df = -[fnval(dpp1,v.') fnval(dpp2,v.')]; function [score,blockIsTooSmall] = calScore(kym,centerI,corL,vP,vF,varargin) % centerI : The coordinate index of the image block center in the 'kym' image. % %For boundary points, the cutoff of background can make the effective image area too small for % stable correlation. We check this and report it back as output. blockIsTooSmall = 0; if mod(corL,2) == 0, corL = corL+1; end numFrames = size(kym,3); kymLen = size(kym,2); kymWidth = size(kym,1); %Check additional parameters ip =inputParser; ip.addParamValue('bAreaThreshold',0.5*corL^2,@isscalar); ip.addParamValue('kymMask',[],@islogical) ip.addParamValue('kymAvgImg',zeros(size(kym)),@isnumeric) ip.parse(varargin{:}); bAreaThreshold=ip.Results.bAreaThreshold; kymMask=ip.Results.kymMask; kymAvgImg=ip.Results.kymAvgImg; %The index of the correlating image block in the big cropped image. bI1 = centerI(1)-(corL-1)/2:centerI(1)+(corL-1)/2; bI2 = centerI(2)-(corL-1)/2:centerI(2)+(corL-1)/2; %Find the part of the image block that is outside the cropped image and cut it off from the template. bI1(bI1<1 | bI1>kymWidth) = []; bI2(bI2<1 | bI2>kymLen) = []; score = zeros(length(vP),length(vF)); if isempty(kymMask) %Background intensities are set to be zero. So, if there is no zero intensities, there is no % background. kymP2 = kym.*kym; %The norm of the kymographed image band at each frame. bNorm1 = sqrt(sum(sum(sum(kymP2(bI1,bI2,1:numFrames-1))))); for j1 = 1:length(vP) v1 = vP(j1); for j2 = 1:length(vF) v2 = vF(j2); corrM = kym(bI1,bI2,1:numFrames-1).* ... kym(bI1+v1,bI2+v2,2:numFrames); %The norm of the shifted image band at each frame. bNorm2 = sqrt(sum(sum(sum(kymP2(bI1+v1,bI2+v2,2:numFrames))))); %Normalize the correlation coefficients. score(j1,j2) = sum(corrM(:))/bNorm1/bNorm2; end end else kym = reshape(kym,kymLen*kymWidth,numFrames); kymMask = reshape(kymMask,kymLen*kymWidth,numFrames); numAvgImgs = size(kymAvgImg,3); kymAvgImg = reshape(kymAvgImg,kymLen*kymWidth,numAvgImgs); lastKymAvgImg = kymAvgImg(:,numAvgImgs); %Extend 'kymAvgImg' to have 'numFrames' columns by repeating 'lastKymAvgImg'. kymAvgImg = [kymAvgImg lastKymAvgImg*ones(1,numFrames-numAvgImgs)]; %kymAvgImg = kymAvgImg(:)*ones(1,numFrames); %%%%% Debugging %%%%%%%%%%%%%%% %kymAvgImg(:) = 0; %%%%% Debugging %%%%%%%%%%%%%%% kym0 = (kym-kymAvgImg).*kymMask; %kym0P2 = kym0.*kym0; %We only consider frames whose texture area (after cutting off background % area) is bigger than 'bAreaThreshold'. Note: Background pixel values are % zero. %First, Get the linear index of the image block in the big cropped image. [BI1,BI2] = ndgrid(bI1,bI2); bI = (BI2(:)-1)*kymWidth+BI1(:); allFrames = 1:numFrames-1; nzInd = arrayfun(@(x)sum(kymMask(bI,x)),allFrames); validFrames = allFrames(nzInd >= bAreaThreshold); %If the number of valid frames is less than half of the number of % correlating frames, we reject the tracking for this point with the default % zero score. if length(validFrames) < numFrames/2; blockIsTooSmall = 1; return; end %We consider template shift in both the positive (to next frame) flow direction and % negative (from previous frame) flow direction. kymValid = kym0(bI,validFrames); kymValidP2 = kymValid.*kymValid; bNorm = sqrt(sum(kymValidP2,1)); % SB:old score calculation function from imFlowTrack % for j1 = 1:length(vP) % v1 = vP(j1); % for j2 = 1:length(vF) % v2 = vF(j2); % v = v2*kymWidth+v1; % % kymShift = kym(bI+v,validFrames+1)-kymAvgImg(bI,validFrames); % bNormS = sqrt(sum(kymShift.^2.*kymMask(bI,validFrames),1)); % % corrM = -ones(1,length(validFrames)); % nzInd = find(bNorm~=0); % nzInd = nzInd(bNormS(nzInd)~=0); % zeroInd = find(bNorm==0); % zeroInd = zeroInd(bNormS(zeroInd)==0); % % corrM(zeroInd) = 1; % corrM(nzInd) = sum(kymValid(:,nzInd).*kymShift(:,nzInd),1); % % zeroInd = find(bNorm==0); % if ~isempty(zeroInd) % bNorm(zeroInd) = 1; % end % zeroInd = find(bNormS==0); % if ~isempty(zeroInd) % bNormS(zeroInd) = 1; % end % % score(j1,j2) = mean(corrM./bNorm./bNormS); % end % end % SB: beginning of vectorized score calculation [v1,v2]=ndgrid(vP,vF); v = v2*kymWidth+v1; [bI2,v2]=ndgrid(bI,v(:)); allbI=bI2+v2; % Create a matrix of size (size(bI,1)xsize(validFrames)xsize(v)) kymShiftMatrix= reshape(kym(allbI(:),validFrames+1),... length(bI),numel(v),length(validFrames))-... permute(repmat(kymAvgImg(bI,validFrames),[1 1 numel(v)]),[1 3 2]); kymShiftMatrix= permute(kymShiftMatrix,[2 3 1]); bNormS=squeeze(sqrt(sum(kymShiftMatrix.^2.*... permute(repmat(kymMask(bI,validFrames),[1 1 numel(v)]),[3 2 1]),3))); validCorrM = squeeze(sum(kymShiftMatrix.* ... permute(repmat(kym0(bI,validFrames),[1 1 numel(v)]),[3 2 1]),3)); % Initialize the correlation matrix corrM = -ones(numel(v),length(validFrames)); % Set the correlation value of zero correlation elements to 1 corrM(repmat(bNorm==0,numel(v),1) & bNormS==0)=1; nzInd = repmat(bNorm~=0,numel(v),1) & bNormS~=0; corrM(nzInd) = validCorrM(nzInd); % Set bNorm and bNormS null components to 1 (to avoid division by zero) bNorm(bNorm==0)=1; bNorm=repmat(bNorm,numel(v),1); bNormS(bNormS==0)=1; score = mean(corrM./bNorm./bNormS,2); score = reshape(score,size(v)); minusOnesI = find(score(:)==-1); nMOnesI = (score(:)~=-1); [minScore,minScoreI] = min(score(nMOnesI)); ind = 1:length(score(:)); ind([minusOnesI minScoreI]) = []; score([minusOnesI minScoreI]) = min(score(ind)); end function [pass,locMaxI,sigtVal] = findMaxScoreI(score,zeroI,minFeatureSize) % % INPUT: % score : The cross-correlation score function. % zeroI : The index of 'score' that corresponds to zero velocity. % OUTPUT: % pass : If an unambiguous global maximum is found, pass = 1 is returned. % Otherwise, pass = 0 is returned indicating that the quality of the % score function is not good. % locMaxI : Index of local maximum whose scores pass the significant test. % sigtVal : A 1x3 vector that contains the scores of the 1st, 2nd local % maximum and the reference score. [m,n] = size(score); numSamples = m*n; avg = sum(score(:))/numSamples; % dev = sum(abs(score(:)-avg))/numSamples; %Some threshold used for quality test. minFeatureRadius = max(1,ceil((minFeatureSize-1)/2)); %Unit: pixel. closenessThreshold = 0.2; maxNbDist = 0.5; sigThreshold = 0.5; %0.5; %We divide the score into 5x5 pixels blocks centered at 'zeroI' which is % the index for zero velocity and find the local maximum in each block % and then do a significant test on them in the sense that they have to be % significantly bigger than the average. If there are more than one % significant local maximums, return 0. To return 1, the unique significant % local maximum also needs to be close the center of the sample region. ind1 = 1:5:m; if ind1(end) < m if ind1(end) == m-1 ind1(end) = m; else ind1(end) = floor((ind1(end-1)+m)/2); ind1(end+1) = m; end end ind2 = 1:5:n; if ind2(end) < n if ind2(end) == n-1 ind2(end) = n; else ind2(end) = floor((ind2(end-1)+n)/2); ind2(end+1) = n; end end locMaxI = []; locMaxS = []; locAvgMinS = []; locCount = 0; for k = 1:length(ind1)-1 for j = 1:length(ind2)-1 locScore = score(ind1(k):ind1(k+1),ind2(j):ind2(j+1)); [tmp,index] = max(locScore,[],1); [maxS,i2] = max(tmp); i1 = index(i2); %maxI = [ind1(k,i1) ind2(j,i2)]; maxI = [ind1(k)+i1-1 ind2(j)+i2-1]; %Check if it is true local maximum in the sense that it is bigger than % its surrounding pixels or it is a boundary maximum. if maxI(1) == 1 yOffset = maxI(1):maxI(1)+2; elseif maxI(1) == m yOffset = maxI(1)-2:maxI(1); else yOffset = maxI(1)-1:maxI(1)+1; end if maxI(2) == 1 xOffset = maxI(2):maxI(2)+2; elseif maxI(2) == n xOffset = maxI(2)-2:maxI(2); else xOffset = maxI(2)-1:maxI(2)+1; end if maxS >= max(max(score(yOffset,xOffset))) maxS = sum(sum(score(yOffset,xOffset)))/9; %The following 'avgMinS' is used in the calibration of the % 'baseS' below. It is the averge of scores around the local % maximum (excluding the maximum). avgMinS = (sum(sum(score(yOffset,xOffset)))-score(maxI(1),maxI(2)))/8; %Further check if it is close to any previouse % local maximum. %Distance to previouse local maximum. dist = zeros(locCount,1); for jj = 1:locCount dist(jj) = norm(maxI-locMaxI(jj,:)); end [minD,minDI] = min(dist); if locCount == 0 || minD >= ... max(2,norm(locMaxI(minDI,:)-zeroI)*closenessThreshold) locCount = locCount+1; locMaxI(locCount,:) = maxI; locMaxS(locCount) = maxS; locAvgMinS(locCount) = avgMinS; elseif maxS > locMaxS(minDI) locMaxI(minDI,:) = maxI; locMaxS(minDI) = maxS; locAvgMinS(minDI) = avgMinS; end end end end [maxS,maxInd] = max(locMaxS); maxI = locMaxI(maxInd,:); [locMaxS,desI] = sort(locMaxS,'descend'); locMaxI = locMaxI(desI,:); maxI = locMaxI(1,:); locAvgMinS = locAvgMinS(desI); avgMinS = locAvgMinS(1); %Note: this is not global 'minS'. It is the % minimum score among the 9 elements around % 'maxI'. It is used in the calibartion of % 'baseS' below. maxINorm = norm(maxI-zeroI); if size(locMaxI,1) == 1 sigtVal = [maxS 0 maxS]; if maxI(1) < m/4 || maxI(1) > 3*m/4 || ... maxI(2) < n/4 || maxI(2) > 3*n/4 pass = 0; else pass = 1; end return; end %Calculate the distance from all local maximum to the global maximum. It %will be used to determine the neiborhood for calculating local average %around the global maximum point. dist = sqrt((locMaxI(2:end,1)-maxI(1)).^2+(locMaxI(2:end,2)-maxI(2)).^2); minD = min(dist); %Calculate the local averge around the maximun point. This local average % will be used to calculate 'baseS', the reference score. offset = max(minFeatureRadius,ceil(min(minD,maxINorm)*maxNbDist)); if maxI(1) > offset y0 = maxI(1)-offset; else y0 = 1; end yNeighbor = y0:min(m,y0+2*offset); if maxI(2) > offset x0 = maxI(2)-offset; else x0 = 1; end xNeighbor = x0:min(n,x0+2*offset); locAvg = sum(sum(score(yNeighbor,xNeighbor)))/ ... length(yNeighbor)/length(xNeighbor); baseS = locMaxS; for k = 2:length(locMaxS) %Anisotropically adapted reference score: % Calculate local minimum along the line between the two local maximums % for the testing of local maximum significance. %The distance between the two local maximum. xD = locMaxI(k,2)-maxI(2); yD = locMaxI(k,1)-maxI(1); if abs(xD) > abs(yD) xShift = 0:sign(xD):xD; yShift = floor(xShift*yD/xD+0.5); else yShift = 0:sign(yD):yD; xShift = floor(yShift*xD/yD+0.5); end lineMinS = min(score(m*(maxI(2)+xShift-1)+maxI(1)+yShift)); baseS(k) = max(lineMinS,locAvg); %In very rare cases, 'baseS' can be even bigger than 'maxS' since our % 'maxS' is the average of the 9 elements around 'maxI'. So, we need % the following control to make sure 'baseS' is always less than % 'maxS'. if baseS(k) > maxS baseS(k) = min(avgMinS,baseS(k)); end end if length(baseS) == 1 sigtVal = [maxS 0 maxS]; elseif baseS(2) == maxS sigtVal = [maxS locMaxS(2) maxS/2]; else sigtVal = [maxS locMaxS(2) baseS(2)]; end inSigI = find(maxS-baseS > 0 & locMaxS-baseS < (maxS-baseS)*sigThreshold); locMaxI(inSigI,:) = []; locMaxS(inSigI) = []; if isempty(locMaxS) pass = 0; return; elseif length(locMaxS) > 1 pass = 0; return; end if maxI(1) < m/4 || maxI(1) > 3*m/4 || ... maxI(2) < n/4 || maxI(2) > 3*n/4 pass = 0; return; end pass = 1;
github
mehta-lab/Instantaneous-PolScope-master
trackSpeckles.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/trackSpeckles.m
6,284
utf_8
10061247bfb8da2fca4fe503ec8c4fba
function [M vectors]=trackSpeckles(I,J,threshold, varargin) % trackSpeckles uses the interpolated vector field to refine the tracking % % SYNOPSIS M = trackSpeckles(I,J,threshold) % M = trackSpeckles(I,J,threshold,'initM',initM,'initCorLen',initCorLen) % % INPUT I : matrix [y x I]n of speckle coordinates and intensities for frame 1 % J : matrix [y x I]n of speckle coordinates and intensities for frame 2 % threshold : radius of the region searched by the tracker for matching speckles % gridSize : (optional, default = 0) distance between two interpolation points on the grid [gy gx] % if gridSize is set equal to zero, the field is interpolated onto % the original vector positions % % OUTPUT M : matrix of matches [y1(1) x1(1) y1(2) x1(2)]n % % References: % A. Ponti et al., Biophysical J., 84 336-3352, 2003. % A. Ponti et al., Biophysical J., 89 2459-3469, 2005. % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Aaron Ponti, September 8th, 2004 % Sebastien Besson, 5/2011 % Copied from fsmTrackTrackerMain % Input Check ip =inputParser; ip.addRequired('I',@(x) isnumeric(x) && size(x,2)==3); ip.addRequired('J',@(x) isnumeric(x) && size(x,2)==3); ip.addRequired('threshold',@isscalar); ip.addParamValue('initM',[],@isnumeric); ip.addParamValue('initCorLen',Inf,@isscalar); ip.addParamValue('enhanced',0,@isscalar); ip.addParamValue('corrLength',0,@isscalar); ip.parse(I,J,threshold, varargin{:}) initM = ip.Results.initM; initCorLen = ip.Results.initCorLen; enhanced = ip.Results.enhanced; corrLength = ip.Results.corrLength; % Track with initialization matrix initM as an initializer M=fsmTrackTrackerIterative(initM,I,J,threshold,initCorLen); % Returns if no hierarchical tracking if ~enhanced, return; end % Extract vector field from M (discard non-matched speckles) raw=M(M(:,1)~=0 & M(:,3)~=0,:); % In the very unlikely case that ALL particles are unmatched if isempty(raw), vectors=zeros(1,4); return; end % Extract vectors from M raw=M(M(:,1)~=0 & M(:,3)~=0,:); % Interpolate onto vector positions grid=raw(:,1:2); % Average returned M to be used to propagate I again vectors=vectorFieldAdaptInterp(raw,grid,corrLength,[],'strain'); % Track with vectors as an initializer M=fsmTrackTrackerIterative(vectors,I,J,threshold,initCorLen); function M=fsmTrackTrackerIterative(initM,I,J,threshold,initCorLen) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % If an initializer for the tracker exists, use it to propagate speckle positions at frame I % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(initM) % Sort I and make sure there are no empty lines I=sortrows(I(I(:,1)~=0,:)); % Propagate speckle positions spPos=I(:,1:2); % Extract only positions pSpPos=propagateSpecklePositions(spPos,initM,'FORWARD',initCorLen); % Now I is the propagated version of the original I I=cat(2,pSpPos,I(:,3)); % Add original intensities to the propagated positions clear Itmp; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Track with linear assignment code % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% NONLINK_MARKER = -1; % value to indicate that two points cannot be linked. extendedTesting = 0; augmentCC = 1; % automatically generate ghost marker to account for birth and deaths % Extract speckle coordinates posI(:,1)=I(:,1); posI(:,2)=I(:,2); posJ(:,1)=J(:,1); posJ(:,2)=J(:,2); % create cost matrix for the linear assignment code % in the most general case that is equal to the distance matrix cc = createSparseDistanceMatrix(posI, posJ, threshold); %cc = createDistanceMatrix(posI, posJ); [all_links_1, all_links_2] = lap(cc, NONLINK_MARKER, extendedTesting, augmentCC); I_N = length(posI); J_N = length(posJ); % first get points that are in frame 1 and have a link in frame 2 all_links_1_2 = all_links_1(1:I_N); frame_1_indices = find(all_links_1_2 <= J_N); frame_2_indices = all_links_1(frame_1_indices); Mone = [posI(frame_1_indices,1:2), posJ(frame_2_indices,1:2)]; % Add non-paired speckles from frame 1 frame_1_indices_noLink = find(all_links_1_2 > J_N); lenNPI=size(frame_1_indices_noLink,1); MNPI=zeros(lenNPI,4); MNPI(1:lenNPI,1:2)=posI(frame_1_indices_noLink,1:2); Mone=cat(1,Mone,MNPI); % Add non-paired speckles from frame 2 all_links_2_1 = all_links_2(1:J_N); frame_2_indices_noLink = find(all_links_2_1 > I_N); lenNPJ=size(frame_2_indices_noLink,1); MNPJ=zeros(lenNPJ,4); MNPJ(1:lenNPJ,3:4)=posJ(frame_2_indices_noLink,1:2); Mone=cat(1,Mone,MNPJ); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % If needed, correct back the propagated coordinates of the first frame % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(initM) % Create a copy of Mone copyMone=Mone; % Correct back the coordinates of the first frame (= currentM(:,1:2)) for i=1:size(spPos,1) indx=find(Mone(:,1)==pSpPos(i,1) & Mone(:,2)==pSpPos(i,2)); if length(indx)~=1 error('Propagated position not univocally found in Mone'); end copyMone(indx,1:2)=spPos(i,:); end M=copyMone; else % Return the result of the first tracking M=Mone; end
github
mehta-lab/Instantaneous-PolScope-master
maskRefinementProcessGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/maskRefinementProcessGUI.m
10,611
utf_8
65f2c327d142bed6240e167c2cbf915c
function varargout = maskRefinementProcessGUI(varargin) % MASKREFINEMENTPROCESSGUI M-file for maskRefinementProcessGUI.fig % MASKREFINEMENTPROCESSGUI, by itself, creates a new MASKREFINEMENTPROCESSGUI or raises the existing % singleton*. % % H = MASKREFINEMENTPROCESSGUI returns the handle to a new MASKREFINEMENTPROCESSGUI or the handle to % the existing singleton*. % % MASKREFINEMENTPROCESSGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in MASKREFINEMENTPROCESSGUI.M with the given input arguments. % % MASKREFINEMENTPROCESSGUI('Property','Value',...) creates a new MASKREFINEMENTPROCESSGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before maskRefinementProcessGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to maskRefinementProcessGUI_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 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help maskRefinementProcessGUI % Last Modified by GUIDE v2.5 01-Jun-2011 16:59:46 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @maskRefinementProcessGUI_OpeningFcn, ... 'gui_OutputFcn', @maskRefinementProcessGUI_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 maskRefinementProcessGUI is made visible. function maskRefinementProcessGUI_OpeningFcn(hObject, eventdata, handles, varargin) processGUI_OpeningFcn(hObject, eventdata, handles, varargin{:},'initChannel',1); % Parameters setup userData = get(handles.figure1, 'UserData'); funParams = userData.crtProc.funParams_; if funParams.MaskCleanUp if ~funParams.FillHoles set(handles.checkbox_fillholes, 'Value', 0) end set(handles.edit_1, 'String',num2str(funParams.MinimumSize)) set(handles.edit_2, 'String',num2str(funParams.ClosureRadius)) set(handles.edit_3, 'String',num2str(funParams.ObjectNumber)) else set([handles.checkbox_cleanup handles.checkbox_fillholes], 'Value', 0); set(get(handles.uipanel_cleanup,'Children'),'Enable','off'); end if funParams.EdgeRefinement set(handles.checkbox_edge, 'Value', 1) set(handles.text_para4, 'Enable', 'on'); set(handles.text_para5, 'Enable', 'on'); set(handles.text_para6, 'Enable', 'on'); set(handles.edit_4, 'Enable', 'on', 'String',num2str(funParams.MaxEdgeAdjust)); set(handles.edit_5, 'Enable', 'on', 'String',num2str(funParams.MaxEdgeGap)); set(handles.edit_6, 'Enable', 'on', 'String',num2str(funParams.PreEdgeGrow)); end % Update user data and GUI data handles.output = hObject; set(handles.figure1, 'UserData', userData); guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = maskRefinementProcessGUI_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 pushbutton_cancel. function pushbutton_cancel_Callback(hObject, eventdata, handles) % hObject handle to pushbutton_cancel (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) delete(handles.figure1); % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) % Call back function of 'Apply' button userData = get(handles.figure1, 'UserData'); % -------- Check user input -------- if isempty(get(handles.listbox_selectedChannels, 'String')) errordlg('Please select at least one input channel from ''Available Channels''.','Setting Error','modal') return; end if get(handles.checkbox_cleanup, 'value') if isnan(str2double(get(handles.edit_1, 'String'))) ... || str2double(get(handles.edit_1, 'String')) < 0 errordlg('Please provide a valid input for ''Minimus Size''.','Setting Error','modal'); return; end if isnan(str2double(get(handles.edit_2, 'String'))) ... || str2double(get(handles.edit_2, 'String')) < 0 errordlg('Please provide a valid input for ''Closure Radius''.','Setting Error','modal'); return; end if isnan(str2double(get(handles.edit_3, 'String'))) ... || str2double(get(handles.edit_3, 'String')) < 0 errordlg('Please provide a valid input for ''Object Number''.','Setting Error','modal'); return; end end if get(handles.checkbox_edge, 'value') if isnan(str2double(get(handles.edit_4, 'String'))) ... || str2double(get(handles.edit_4, 'String')) < 0 errordlg('Please provide a valid input for ''Maximum Adjust Distance''.','Setting Error','modal'); return; end if isnan(str2double(get(handles.edit_5, 'String'))) ... || str2double(get(handles.edit_5, 'String')) < 0 errordlg('Please provide a valid input for ''Maximum Edge Gap''.','Setting Error','modal'); return; end if isnan(str2double(get(handles.edit_6, 'String'))) ... || str2double(get(handles.edit_6, 'String')) < 0 errordlg('Please provide a valid input for ''Radius of Growth''.','Setting Error','modal'); return; end end if ~get(handles.checkbox_cleanup, 'value') && ~get(handles.checkbox_edge, 'value') errordlg('Please select at least one option for mask refinement processing.') return; end % -------- Process Sanity check -------- % ( only check underlying data ) try userData.crtProc.sanityCheck; catch ME errordlg([ME.message 'Please double check your data'],... 'Setting Error','modal'); return; end % Retrieve GUI-defined parameters channelIndex = get (handles.listbox_selectedChannels, 'Userdata'); funParams.ChannelIndex = channelIndex; if get(handles.checkbox_cleanup, 'Value') funParams.MaskCleanUp = true; funParams.MinimumSize = str2double(get(handles.edit_1, 'String')); funParams.ClosureRadius = str2double(get(handles.edit_2, 'String')); funParams.ObjectNumber = str2double(get(handles.edit_3, 'String')); if get(handles.checkbox_fillholes, 'Value') funParams.FillHoles = true; else funParams.FillHoles = false; end else funParams.MaskCleanUp = false; end if get(handles.checkbox_edge, 'Value') funParams.EdgeRefinement = true; funParams.MaxEdgeAdjust = str2double(get(handles.edit_4, 'String')); funParams.MaxEdgeGap = str2double(get(handles.edit_5, 'String')); funParams.PreEdgeGrow = str2double(get(handles.edit_6, 'String')); else funParams.EdgeRefinement = false; end % Set parameters and update main window processGUI_ApplyFcn(hObject, eventdata, handles,funParams); % --- Executes on button press in checkbox_cleanup. function checkbox_cleanup_Callback(hObject, eventdata, handles) % Hint: get(hObject,'Value') returns toggle state of checkbox_auto if get(hObject, 'Value') set(get(handles.uipanel_cleanup,'Children'),'Enable','on'); else set(get(handles.uipanel_cleanup,'Children'),'Enable','off'); end % --- Executes on button press in checkbox_edge. function checkbox_edge_Callback(hObject, eventdata, handles) % Hint: get(hObject,'Value') returns toggle state of checkbox_auto if get(hObject, 'Value') set(get(handles.uipanel_edge,'Children'),'Enable','on'); else set(get(handles.uipanel_edge,'Children'),'Enable','off'); end % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); if isfield(userData, 'helpFig') && ishandle(userData.helpFig) delete(userData.helpFig) end set(handles.figure1, 'UserData', userData); guidata(hObject,handles); % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata structure with the following fields (see FIGURE) % Key: name of the key that was pressed, in lower case % Character: character interpretation of the key(s) that was pressed % Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed % handles structure with handles and user data (see GUIDATA) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on key press with focus on pushbutton_done and none of its controls. function pushbutton_done_KeyPressFcn(hObject, eventdata, handles) % hObject handle to pushbutton_done (see GCBO) % eventdata structure with the following fields (see UICONTROL) % Key: name of the key that was pressed, in lower case % Character: character interpretation of the key(s) that was pressed % Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed % handles structure with handles and user data (see GUIDATA) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end
github
mehta-lab/Instantaneous-PolScope-master
MakeQTMovie.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/MakeQTMovie.m
29,830
utf_8
285b3b909f0c5edc95258c1daa5e3117
function MakeQTMovie(cmd,arg, arg2) % function MakeQTMovie(cmd, arg, arg2) % Create a QuickTime movie from a bunch of figures (and an optional sound). % % Syntax: MakeQTMovie cmd [arg] % The following commands are supported: % addfigure - Add snapshot of current figure to movie % addaxes - Add snapshot of current axes to movie % addmatrix data - Add a matrix to movie (convert to jpeg with imwrite) % addmatrixsc data - Add a matrix to movie (convert to jpeg with imwrite) % (automatically scales image data) % addsound data [sr] - Add sound to movie (only monaural for now) % (third argument is the sound's sample rate.) % cleanup - Remove the temporary files % demo - Create a demonstration movie % finish - Finish movie, write out QT file % framerate fps - Set movies frame rate [Default is 10 fps] % quality # - Set JPEG quality (between 0 and 1) % size [# #] - Set plot size to [width height] % start filename - Start creating a movie with this name % The start command must be called first to provide a movie name. % The finish command must be called last to write out the movie % data. All other commands can be called in any order. Only one % movie can be created at a time. % % This code is published as Interval Technical Report #1999-066 % The latest copy can be found at % http://web.interval.com/papers/1999-066/ % (c) Copyright Malcolm Slaney, Interval Research, March 1999. % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % This is experimental software and is being provided to Licensee % 'AS IS.' Although the software has been tested on Macintosh, SGI, % Linux, and Windows machines, Interval makes no warranties relating % to the software's performance on these or any other platforms. % % Disclaimer % THIS SOFTWARE IS BEING PROVIDED TO YOU 'AS IS.' INTERVAL MAKES % NO EXPRESS, IMPLIED OR STATUTORY WARRANTY OF ANY KIND FOR THE % SOFTWARE INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF % PERFORMANCE, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. % IN NO EVENT WILL INTERVAL BE LIABLE TO LICENSEE OR ANY THIRD % PARTY FOR ANY DAMAGES, INCLUDING LOST PROFITS OR OTHER INCIDENTAL % OR CONSEQUENTIAL DAMAGES, EVEN IF INTERVAL HAS BEEN ADVISED OF % THE POSSIBLITY THEREOF. % % This software program is owned by Interval Research % Corporation, but may be used, reproduced, modified and % distributed by Licensee. Licensee agrees that any copies of the % software program will contain the same proprietary notices and % warranty disclaimers which appear in this software program. % This program uses the Matlab imwrite routine to convert each image % frame into JPEG. After first reserving 8 bytes for a header that points % to the movie description, all the compressed images and the sound are % added to the movie file. When the 'finish' method is called then the % first 8 bytes of the header are rewritten to indicate the size of the % movie data, and then the movie header ('moov structure') is written % to the output file. % % This routine creates files according to the QuickTime file format as % described in the appendix of % "Quicktime (Inside MacIntosh)," Apple Computer Incorporated, % Addison-Wesley Pub Co; ISBN: 0201622017, April 1993. % I appreciate help that I received from Lee Fyock (MathWorks) and Aaron % Hertzmann (Interval) in debugging and testing this work. % Changes: % July 5, 1999 - Removed stss atom since it upset PC version of QuickTime % November 11, 1999 - Fixed quality bug in addmatrix. Added addmatrixsc. % March 7, 2000 - by Jordan Rosenthal ([email protected]), Added truecolor % capability when running in Matlab 5.3 changed some help comments, fixed % some bugs, vectorized some code. % April 7, 2000 - by Malcolm. Cleaned up axis/figure code and fixed(?) SGI % playback problems. Added user data atom to give version information. % Fixed sound format problems. % April 10, 2000 - by Malcolm. Fixed problem with SGI (at least) and B&W % addmatrix. % October 15, 2004 - by Andre Kerstens ([email protected]), implemented % a fix for two known bugs in Matlab 7 (R14) basically turning the % accelerator and javafigures off if nargin < 1 fprintf('Syntax: MakeQTMovie cmd [arg]\n') fprintf('The following commands are supported:\n'); fprintf(' addfigure - Add snapshot of current figure to movie\n') fprintf(' addaxes - Add snapshot of current axes to movie\n') fprintf(' addmatrix data - Add a matrix to movie '); fprintf('(convert to jpeg)\n') fprintf(' addmatrixsc data - Add a matrix to movie '); fprintf('(scale and convert to jpeg)\n') fprintf(' addsound data - Add sound samples '); fprintf('(with optional rate)\n') fprintf(' demo - Show this program in action\n'); fprintf(' finish - Finish movie, write out QT file\n'); fprintf(' framerate # - Set movie frame rate '); fprintf('(default is 10fps)\n'); fprintf(' quality # - Set JPEG quality (between 0 and 1)\n'); fprintf(' size [# #] - Set plot size to [width height]\n'); fprintf(' start filename - Start making a movie with '); fprintf('this name\n'); return; end % Since matlab 7 handles figures different from 6 (using java), we have to % set this feature to 0 when 7 is used. Also implements a workaround for % a known bug with global variables % matlabVersion = version; % if (matlabVersion(1) == '7') % if isempty(strfind(version,'R2008')) % oldJFValue = feature('javafigures'); % feature('javafigures',0); % oldAccelValue = feature('accel'); % feature('accel',0); % end % end global MakeQTMovieStatus MakeDefaultQTMovieStatus; % Needed first time, ignored otherwise switch lower(cmd) case {'addframe','addplot','addfigure','addaxes'} switch lower(cmd) case {'addframe','addfigure'} hObj = gcf; % Add the entire figure (with all axes) otherwise hObj = gca; % Add what's inside the current axis end frame = getframe(hObj); [I,map] = frame2im(frame); if ImageSizeChanged(size(I)) > 0 return; end if isempty(map) % RGB image imwrite(I,MakeQTMovieStatus.imageTmp, 'jpg', 'Quality', ... MakeQTMovieStatus.spatialQual*100); else % Indexed image writejpg_map(MakeQTMovieStatus.imageTmp, I, map); end [pos, len] = AddFileToMovie; n = MakeQTMovieStatus.frameNumber + 1; MakeQTMovieStatus.frameNumber = n; MakeQTMovieStatus.frameStarts(n) = pos; MakeQTMovieStatus.frameLengths(n) = len; %% Allow images to be added by doing: %% MakeQTMovie('addimage', '/path/to/file.jpg'); %% This case adapted from addmatrix. Thanks to %% Stephen Eglen <[email protected]> for this idea. case 'addimage' if nargin < 2 fprintf('MakeQTMovie error: Need to specify a filename with '); fprintf('the image command.\n'); return; end %% Check to see that the image is the correct size. Do %% this by reading in the image and then checking its size. %% tim - temporary image. tim = imread(arg); tim_size = size(tim); fprintf('Image %s size %d %d\n', arg, tim_size(1), tim_size(2)); if ImageSizeChanged(tim_size) > 0 return; end [pos, len] = AddFileToMovie(arg); n = MakeQTMovieStatus.frameNumber + 1; MakeQTMovieStatus.frameNumber = n; MakeQTMovieStatus.frameStarts(n) = pos; MakeQTMovieStatus.frameLengths(n) = len; case 'addmatrix' if nargin < 2 fprintf('MakeQTMovie error: Need to specify a matrix with '); fprintf('the addmatrix command.\n'); return; end if ImageSizeChanged(size(arg)) > 0 return; end % Work around a bug, at least on the % SGIs, which causes JPEGs to be % written which can't be read with the % SGI QT. Turn the B&W image into a % color matrix. if ndims(arg) < 3 arg(:,:,2) = arg; arg(:,:,3) = arg(:,:,1); end imwrite(arg, MakeQTMovieStatus.imageTmp, 'jpg', 'Quality', ... MakeQTMovieStatus.spatialQual*100); [pos, len] = AddFileToMovie; n = MakeQTMovieStatus.frameNumber + 1; MakeQTMovieStatus.frameNumber = n; MakeQTMovieStatus.frameStarts(n) = pos; MakeQTMovieStatus.frameLengths(n) = len; case 'addmatrixsc' if nargin < 2 fprintf('MakeQTMovie error: Need to specify a matrix with '); fprintf('the addmatrix command.\n'); return; end if ImageSizeChanged(size(arg)) > 0 return; end arg = arg - min(min(arg)); arg = arg / max(max(arg)); % Work around a bug, at least on the % SGIs, which causes JPEGs to be % written which can't be read with the % SGI QT. Turn the B&W image into a % color matrix. if ndims(arg) < 3 arg(:,:,2) = arg; arg(:,:,3) = arg(:,:,1); end imwrite(arg, MakeQTMovieStatus.imageTmp, 'jpg', 'Quality', ... MakeQTMovieStatus.spatialQual*100); [pos, len] = AddFileToMovie; n = MakeQTMovieStatus.frameNumber + 1; MakeQTMovieStatus.frameNumber = n; MakeQTMovieStatus.frameStarts(n) = pos; MakeQTMovieStatus.frameLengths(n) = len; case 'addsound' if nargin < 2 fprintf('MakeQTMovie error: Need to specify a sound array '); fprintf('with the addsound command.\n'); return; end % Do stereo someday??? OpenMovieFile MakeQTMovieStatus.soundLength = length(arg); arg = round(arg/max(max(abs(arg)))*32765); negs = find(arg<0); arg(negs) = arg(negs) + 65536; sound = mb16(arg); MakeQTMovieStatus.soundStart = ftell(MakeQTMovieStatus.movieFp); MakeQTMovieStatus.soundLen = length(sound); fwrite(MakeQTMovieStatus.movieFp, sound, 'uchar'); if nargin < 3 arg2 = 22050; end MakeQTMovieStatus.soundRate = arg2; case 'cleanup' if isstruct(MakeQTMovieStatus) if ~isempty(MakeQTMovieStatus.movieFp) fclose(MakeQTMovieStatus.movieFp); MakeQTMovieStatus.movieFp = []; end if ~isempty(MakeQTMovieStatus.imageTmp) & ... exist(MakeQTMovieStatus.imageTmp,'file') > 0 delete(MakeQTMovieStatus.imageTmp); MakeQTMovieStatus.imageTmp = []; end end MakeQTMovieStatus = []; case 'debug' fprintf('Current Movie Data:\n'); fprintf(' %d frames at %d fps\n', MakeQTMovieStatus.frameNumber, ... MakeQTMovieStatus.frameRate); starts = MakeQTMovieStatus.frameStarts; if length(starts) > 10, starts = starts(1:10);, end; lens = MakeQTMovieStatus.frameLengths; if length(lens) > 10, lens = lens(1:10);, end; fprintf(' Start: %6d Size: %6d\n', [starts; lens]); fprintf(' Movie Image Size: %dx%d\n', ... MakeQTMovieStatus.imageSize(2), ...); MakeQTMovieStatus.imageSize(1)); if length(MakeQTMovieStatus.soundStart) > 0 fprintf(' Sound: %d samples at %d Hz sampling rate ', ... MakeQTMovieStatus.soundLength, ... MakeQTMovieStatus.soundRate); fprintf('at %d.\n', MakeQTMovieStatus.soundStart); else fprintf(' Sound: No sound track\n'); end fprintf(' Temporary files for images: %s\n', ... MakeQTMovieStatus.imageTmp); fprintf(' Final movie name: %s\n', MakeQTMovieStatus.movieName); fprintf(' Compression Quality: %g\n', ... MakeQTMovieStatus.spatialQual); case 'demo' clf fps = 10; movieLength = 10; sr = 22050; fn = 'test.mov'; fprintf('Creating the movie %s.\n', fn); MakeQTMovie('start',fn); MakeQTMovie('size', [160 120]); MakeQTMovie('quality', 1.0); theSound = []; for i=1:movieLength plot(sin((1:100)/4+i)); MakeQTMovie('addaxes'); theSound = [theSound sin(440/sr*2*pi*(2^(i/12))*(1:sr/fps))]; end MakeQTMovie('framerate', fps); MakeQTMovie('addsound', theSound, sr); MakeQTMovie('finish'); case {'finish','close'} AddQTHeader; MakeQTMovie('cleanup') % Remove temporary files case 'framerate' if nargin < 2 fprintf('MakeQTMovie error: Need to specify the '); fprintf('frames/second with the framerate command.\n'); return; end MakeQTMovieStatus.frameRate = arg; case 'help' MakeQTMovie % To get help message. case 'size' % Size is off by one on the % Mac. if nargin < 2 fprintf('MakeQTMovie error: Need to specify a vector with '); fprintf('the size command.\n'); return; end if length(arg) ~= 2 error('MakeQTMovie: Error, must supply 2 element size.'); end oldUnits = get(gcf,'units'); set(gcf,'units','pixels'); cursize = get(gcf, 'position'); cursize(3) = arg(1); cursize(4) = arg(2); set(gcf, 'position', cursize); set(gcf,'units',oldUnits); case 'start' if nargin < 2 fprintf('MakeQTMovie error: Need to specify a file name '); fprintf('with start command.\n'); return; end MakeQTMovie('cleanup'); MakeDefaultQTMovieStatus; MakeQTMovieStatus.movieName = arg; case 'test' clf MakeQTMovieStatus = []; MakeQTMovie('start','test.mov'); MakeQTMovie('size', [320 240]); MakeQTMovie('quality', 1.0); subplot(2,2,1); for i=1:10 plot(sin((1:100)/4+i)); MakeQTMovie('addfigure'); end MakeQTMovie('framerate', 10); MakeQTMovie('addsound', sin(1:5000), 22050); MakeQTMovie('debug'); MakeQTMovie('finish'); case 'quality' if nargin < 2 fprintf('MakeQTMovie error: Need to specify a quality '); fprintf('(between 0-1) with the quality command.\n'); return; end MakeQTMovieStatus.spatialQual = arg; otherwise fprintf('MakeQTMovie: Unknown method %s.\n', cmd); end % Set the values back for the figuresize % matlabVersion = version; % if (matlabVersion(1) == '7') % if isempty(strfind(version,'R2008')) % feature('javafigures',oldJFValue); % feature('accel',oldAccelValue); % end % end %%%%%%%%%%%%%%% MakeDefaultQTMovieStatus %%%%%%%%%%%%%%%%% % Make the default movie status structure. function MakeDefaultQTMovieStatus global MakeQTMovieStatus if isempty(MakeQTMovieStatus) MakeQTMovieStatus = struct(... 'frameRate', 10, ... % frames per second 'frameStarts', [], ... % Starting byte position 'frameLengths', [], ... 'timeScale', 10, ... % How much faster does time run? 'soundRate', 22050, ... % Sound Sample Rate 'soundStart', [], ... % Starting byte position 'soundLength', 0, ... 'soundChannels', 1, ... % Number of channels 'frameNumber', 0, ... 'movieFp', [], ... % File pointer 'imageTmp', tempname, ... 'movieName', 'output.mov', ... 'imageSize', [0 0], ... 'trackNumber', 0, ... 'timeScaleExpansion', 100, ... 'spatialQual', 1.0); % Between 0.0 and 1.0 end %%%%%%%%%%%%%%% ImageSizeChanged %%%%%%%%%%%%%%%%% % Check to see if the image size has changed. This m-file can't % deal with that, so we'll return an error. function err = ImageSizeChanged(newsize) global MakeQTMovieStatus newsize = newsize(1:2); % Don't care about RGB info, if present oldsize = MakeQTMovieStatus.imageSize; err = 0; if sum(oldsize) == 0 MakeQTMovieStatus.imageSize = newsize; else if sum(newsize ~= oldsize) > 0 fprintf('MakeQTMovie Error: New image size'); fprintf('(%dx%d) doesn''t match old size (%dx%d)\n', ... newsize(1), newsize(2), oldsize(1), oldsize(2)); fprintf(' Can''t add this image to the movie.\n'); err = 1; end end %%%%%%%%%%%%%%% AddFileToMovie %%%%%%%%%%%%%%%%% % OK, we've saved out an image file. Now add it to the end of the movie % file we are creating. % We'll copy the JPEG file in 16kbyte chunks to the end of the movie file. % Keep track of the start and end byte position in the file so we can put % the right information into the QT header. function [pos, len] = AddFileToMovie(imageTmp) global MakeQTMovieStatus OpenMovieFile if nargin < 1 imageTmp = MakeQTMovieStatus.imageTmp; end fp = fopen(imageTmp, 'rb'); if fp < 0 error('Could not reopen QT image temporary file.'); end len = 0; pos = ftell(MakeQTMovieStatus.movieFp); while 1 data = fread(fp, 1024*16, 'uchar'); if isempty(data) break; end cnt = fwrite(MakeQTMovieStatus.movieFp, data, 'uchar'); len = len + cnt; end fclose(fp); %%%%%%%%%%%%%%% AddQTHeader %%%%%%%%%%%%%%%%% % Go back and write the atom information that allows % QuickTime to skip the image and sound data and find % its movie description information. function AddQTHeader() global MakeQTMovieStatus pos = ftell(MakeQTMovieStatus.movieFp); header = moov_atom; cnt = fwrite(MakeQTMovieStatus.movieFp, header, 'uchar'); fseek(MakeQTMovieStatus.movieFp, 0, -1); cnt = fwrite(MakeQTMovieStatus.movieFp, mb32(pos), 'uchar'); fclose(MakeQTMovieStatus.movieFp); MakeQTMovieStatus.movieFp = []; %%%%%%%%%%%%%%% OpenMovieFile %%%%%%%%%%%%%%%%% % Open a new movie file. Write out the initial QT header. We'll fill in % the correct length later. function OpenMovieFile global MakeQTMovieStatus if isempty(MakeQTMovieStatus.movieFp) fp = fopen(MakeQTMovieStatus.movieName, 'wb'); if fp < 0 error('Could not open QT movie output file.'); end MakeQTMovieStatus.movieFp = fp; cnt = fwrite(fp, [mb32(0) mbstring('mdat')], 'uchar'); end %%%%%%%%%%%%%%% writejpg_map %%%%%%%%%%%%%%%%% % Like the imwrite routine, but first pass the image data through the indicated % RGB map. function writejpg_map(name,I,map) global MakeQTMovieStatus [y,x] = size(I); % Force values to be valid indexes. This fixes a bug that occasionally % occurs in frame2im in Matlab 5.2 which incorrectly produces values of I % equal to zero. I = max(1,min(I,size(map,1))); rgb = zeros(y, x, 3); t = zeros(y,x); t(:) = map(I(:),1)*255; rgb(:,:,1) = t; t(:) = map(I(:),2)*255; rgb(:,:,2) = t; t(:) = map(I(:),3)*255; rgb(:,:,3) = t; imwrite(uint8(rgb),name,'jpeg','Quality',MakeQTMovieStatus.spatialQual*100); %%%%%%%%%%%%%%% SetAtomSize %%%%%%%%%%%%%%%%% % Fill in the size of the atom function y=SetAtomSize(x) y = x; y(1:4) = mb32(length(x)); %%%%%%%%%%%%%%% mb32 %%%%%%%%%%%%%%%%% % Make a vector from a 32 bit integer function y = mb32(x) if size(x,1) > size(x,2) x = x'; end y = [bitand(bitshift(x,-24),255); ... bitand(bitshift(x,-16),255); ... bitand(bitshift(x, -8),255); ... bitand(x, 255)]; y = y(:)'; %%%%%%%%%%%%%%% mb16 %%%%%%%%%%%%%%%%% % Make a vector from a 16 bit integer function y = mb16(x) if size(x,1) > size(x,2) x = x'; end y = [bitand(bitshift(x, -8),255); ... bitand(x, 255)]; y = y(:)'; %%%%%%%%%%%%%%% mb8 %%%%%%%%%%%%%%%%% % Make a vector from a 8 bit integer function y = mb8(x) if size(x,1) > size(x,2) x = x'; end y = [bitand(x, 255)]; y = y(:)'; % % The following routines all create atoms necessary % to describe a QuickTime Movie. The basic idea is to % fill in the necessary data, all converted to 8 bit % characters, then fix it up later with SetAtomSize so % that it has the correct header. (This is easier than % counting by hand.) %%%%%%%%%%%%%%% mbstring %%%%%%%%%%%%%%%%% % Make a vector from a character string function y = mbstring(s) y = double(s); %%%%%%%%%%%%%%% dinf_atom %%%%%%%%%%%%%%%%% function y = dinf_atom() y = SetAtomSize([mb32(0) mbstring('dinf') dref_atom]); %%%%%%%%%%%%%%% dref_atom %%%%%%%%%%%%%%%%% function y = dref_atom() y = SetAtomSize([mb32(0) mbstring('dref') mb32(0) mb32(1) ... mb32(12) mbstring('alis') mb32(1)]); %%%%%%%%%%%%%%% edts_atom %%%%%%%%%%%%%%%%% function y = edts_atom(add_sound_p) global MakeQTMovieStatus fixed1 = bitshift(1,16); % Fixed point 1 if add_sound_p > 0 duration = MakeQTMovieStatus.soundLength / ... MakeQTMovieStatus.soundRate * ... MakeQTMovieStatus.timeScale; else duration = MakeQTMovieStatus.frameNumber / ... MakeQTMovieStatus.frameRate * ... MakeQTMovieStatus.timeScale; end duration = ceil(duration); y = [mb32(0) ... % Atom Size mbstring('edts') ... % Atom Name SetAtomSize([mb32(0) ... % Atom Size mbstring('elst') ... % Atom Name mb32(0) ... % Version/Flags mb32(1) ... % Number of entries mb32(duration) ... % Length of this track mb32(0) ... % Time mb32(fixed1)])]; % Rate y = SetAtomSize(y); %%%%%%%%%%%%%%% hdlr_atom %%%%%%%%%%%%%%%%% function y = hdlr_atom(component_type, sub_type) if strcmp(sub_type, 'vide') type_string = 'Apple Video Media Handler'; elseif strcmp(sub_type, 'alis') type_string = 'Apple Alias Data Handler'; elseif strcmp(sub_type, 'soun') type_string = 'Apple Sound Media Handler'; end y = [mb32(0) ... % Atom Size mbstring('hdlr') ... % Atom Name mb32(0) ... % Version and Flags mbstring(component_type) ... % Component Name mbstring(sub_type) ... % Sub Type Name mbstring('appl') ... % Component manufacturer mb32(0) ... % Component flags mb32(0) ... % Component flag mask mb8(length(type_string)) ... % Type Name byte count mbstring(type_string)]; % Type Name y = SetAtomSize(y); %%%%%%%%%%%%%%% mdhd_atom %%%%%%%%%%%%%%%%% function y = mdhd_atom(add_sound_p) global MakeQTMovieStatus if add_sound_p data = [mb32(MakeQTMovieStatus.soundRate) ... mb32(MakeQTMovieStatus.soundLength)]; else data = [mb32(MakeQTMovieStatus.frameRate * ... MakeQTMovieStatus.timeScaleExpansion) ... mb32(MakeQTMovieStatus.frameNumber * ... MakeQTMovieStatus.timeScaleExpansion)]; end y = [mb32(0) mbstring('mdhd') ... % Atom Header mb32(0) ... mb32(round(now*3600*24)) ... % Creation time mb32(round(now*3600*24)) ... % Modification time data ... mb16(0) mb16(0)]; y = SetAtomSize(y); %%%%%%%%%%%%%%% mdia_atom %%%%%%%%%%%%%%%%% function y = mdia_atom(add_sound_p) global MakeQTMovieStatus if add_sound_p hdlr = hdlr_atom('mhlr', 'soun'); else hdlr = hdlr_atom('mhlr', 'vide'); end y = [mb32(0) mbstring('mdia') ... % Atom Header mdhd_atom(add_sound_p) ... hdlr ... % Handler Atom minf_atom(add_sound_p)]; y = SetAtomSize(y); %%%%%%%%%%%%%%% minf_atom %%%%%%%%%%%%%%%%% function y = minf_atom(add_sound_p) global MakeQTMovieStatus if add_sound_p data = smhd_atom; else data = vmhd_atom; end y = [mb32(0) mbstring('minf') ... % Atom Header data ... hdlr_atom('dhlr','alis') ... dinf_atom ... stbl_atom(add_sound_p)]; y = SetAtomSize(y); %%%%%%%%%%%%%%% moov_atom %%%%%%%%%%%%%%%%% function y=moov_atom global MakeQTMovieStatus MakeQTMovieStatus.timeScale = MakeQTMovieStatus.frameRate * ... MakeQTMovieStatus.timeScaleExpansion; if MakeQTMovieStatus.soundLength > 0 sound = trak_atom(1); else sound = []; end y = [mb32(0) mbstring('moov') ... mvhd_atom udat_atom sound trak_atom(0) ]; y = SetAtomSize(y); %%%%%%%%%%%%%%% mvhd_atom %%%%%%%%%%%%%%%%% function y=mvhd_atom global MakeQTMovieStatus fixed1 = bitshift(1,16); % Fixed point 1 frac1 = bitshift(1,30); % Fractional 1 if length(MakeQTMovieStatus.soundStart) > 0 NumberOfTracks = 2; else NumberOfTracks = 1; end % Need to make sure its longer % of movie and sound lengths MovieDuration = max(MakeQTMovieStatus.frameNumber / ... MakeQTMovieStatus.frameRate, ... MakeQTMovieStatus.soundLength / ... MakeQTMovieStatus.soundRate); MovieDuration = ceil(MovieDuration * MakeQTMovieStatus.timeScale); y = [mb32(0) ... % Size mbstring('mvhd') ... % Movie Data mb32(0) ... % Version and Flags mb32(0) ... % Creation Time (unknown) mb32(0) ... % Modification Time (unknown) mb32(MakeQTMovieStatus.timeScale) ... % Movie's Time Scale mb32(MovieDuration) ... % Movie Duration mb32(fixed1) ... % Preferred Rate mb16(255) ... % Preferred Volume mb16(0) ... % Fill mb32(0) ... % Fill mb32(0) ... % Fill mb32(fixed1) mb32(0) mb32(0) ... % Transformation matrix (identity) mb32(0) mb32(fixed1) mb32(0) ... mb32(0) mb32(0) mb32(frac1) ... mb32(0) ... % Preview Time mb32(0) ... % Preview Duration mb32(0) ... % Poster Time mb32(0) ... % Selection Time mb32(0) ... % Selection Duration mb32(0) ... % Current Time mb32(NumberOfTracks)]; % Video and/or Sound? y = SetAtomSize(y); %%%%%%%%%%%%%%% raw_image_description %%%%%%%%%%%%%%%%% function y = raw_image_description() global MakeQTMovieStatus fixed1 = bitshift(1,16); % Fixed point 1 codec = [12 'Photo - JPEG ']; y = [mb32(0) mbstring('jpeg') ... % Atom Header mb32(0) mb16(0) mb16(0) mb16(0) mb16(1) ... mbstring('appl') ... mb32(1023) ... % Temporal Quality (perfect) mb32(floor(1023*MakeQTMovieStatus.spatialQual)) ... mb16(MakeQTMovieStatus.imageSize(2)) ... mb16(MakeQTMovieStatus.imageSize(1)) ... mb32(fixed1 * 72) mb32(fixed1 * 72) ... mb32(0) ... mb16(0) ... mbstring(codec) ... mb16(24) mb16(65535)]; y = SetAtomSize(y); %%%%%%%%%%%%%%% raw_sound_description %%%%%%%%%%%%%%%%% function y = raw_sound_description() global MakeQTMovieStatus y = [mb32(0) mbstring('twos') ... % Atom Header mb32(0) mb16(0) mb16(0) mb16(0) mb16(0) ... mb32(0) ... mb16(MakeQTMovieStatus.soundChannels) ... mb16(16) ... % 16 bits per sample mb16(0) mb16(0) ... mb32(round(MakeQTMovieStatus.soundRate*65536))]; y = SetAtomSize(y); %%%%%%%%%%%%%%% smhd_atom %%%%%%%%%%%%%%%%% function y = smhd_atom() y = SetAtomSize([mb32(0) mbstring('smhd') mb32(0) mb16(0) mb16(0)]); %%%%%%%%%%%%%%% stbl_atom %%%%%%%%%%%%%%%%% % Removed the stss atom since it seems to upset the PC version of QT % and it is empty so it doesn't add anything. % Malcolm - July 5, 1999 function y = stbl_atom(add_sound_p) y = [mb32(0) mbstring('stbl') ... % Atom Header stsd_atom(add_sound_p) ... stts_atom(add_sound_p) ... stsc_atom(add_sound_p) ... stsz_atom(add_sound_p) ... stco_atom(add_sound_p)]; y = SetAtomSize(y); %%%%%%%%%%%%%%% stco_atom %%%%%%%%%%%%%%%%% function y = stco_atom(add_sound_p) global MakeQTMovieStatus if add_sound_p y = [mb32(0) mbstring('stco') mb32(0) mb32(1) ... mb32(MakeQTMovieStatus.soundStart)]; else y = [mb32(0) mbstring('stco') mb32(0) ... mb32(MakeQTMovieStatus.frameNumber) ... mb32(MakeQTMovieStatus.frameStarts)]; end y = SetAtomSize(y); %%%%%%%%%%%%%%% stsc_atom %%%%%%%%%%%%%%%%% function y = stsc_atom(add_sound_p) global MakeQTMovieStatus if add_sound_p samplesperchunk = MakeQTMovieStatus.soundLength; else samplesperchunk = 1; end y = [mb32(0) mbstring('stsc') mb32(0) mb32(1) ... mb32(1) mb32(samplesperchunk) mb32(1)]; y = SetAtomSize(y); %%%%%%%%%%%%%%% stsd_atom %%%%%%%%%%%%%%%%% function y = stsd_atom(add_sound_p) if add_sound_p desc = raw_sound_description; else desc = raw_image_description; end y = [mb32(0) mbstring('stsd') mb32(0) mb32(1) desc]; y = SetAtomSize(y); %%%%%%%%%%%%%%% stss_atom %%%%%%%%%%%%%%%%% function y = stss_atom() y = SetAtomSize([mb32(0) mbstring('stss') mb32(0) mb32(0)]); %%%%%%%%%%%%%%% stsz_atom %%%%%%%%%%%%%%%%% function y = stsz_atom(add_sound_p) global MakeQTMovieStatus if add_sound_p y = [mb32(0) mbstring('stsz') mb32(0) mb32(2) ... mb32(MakeQTMovieStatus.soundLength)]; else y = [mb32(0) mbstring('stsz') mb32(0) mb32(0) ... mb32(MakeQTMovieStatus.frameNumber) ... mb32(MakeQTMovieStatus.frameLengths)]; end y = SetAtomSize(y); %%%%%%%%%%%%%%% stts_atom %%%%%%%%%%%%%%%%% function y = stts_atom(add_sound_p) global MakeQTMovieStatus if add_sound_p count_duration = [mb32(MakeQTMovieStatus.soundLength) mb32(1)]; else count_duration = [mb32(MakeQTMovieStatus.frameNumber) ... mb32(MakeQTMovieStatus.timeScaleExpansion)]; end y = SetAtomSize([mb32(0) mbstring('stts') mb32(0) mb32(1) count_duration]); %%%%%%%%%%%%%%% trak_atom %%%%%%%%%%%%%%%%% function y = trak_atom(add_sound_p) global MakeQTMovieStatus y = [mb32(0) mbstring('trak') ... % Atom Header tkhd_atom(add_sound_p) ... % Track header edts_atom(add_sound_p) ... % Edit List mdia_atom(add_sound_p)]; y = SetAtomSize(y); %%%%%%%%%%%%%%% tkhd_atom %%%%%%%%%%%%%%%%% function y = tkhd_atom(add_sound_p) global MakeQTMovieStatus fixed1 = bitshift(1,16); % Fixed point 1 frac1 = bitshift(1,30); % Fractional 1 (CHECK THIS) if add_sound_p > 0 duration = MakeQTMovieStatus.soundLength / ... MakeQTMovieStatus.soundRate * ... MakeQTMovieStatus.timeScale; else duration = MakeQTMovieStatus.frameNumber / ... MakeQTMovieStatus.frameRate * ... MakeQTMovieStatus.timeScale; end duration = ceil(duration); y = [mb32(0) mbstring('tkhd') ... % Atom Header mb32(15) ... % Version and flags mb32(round(now*3600*24)) ... % Creation time mb32(round(now*3600*24)) ... % Modification time mb32(MakeQTMovieStatus.trackNumber) ... mb32(0) ... mb32(duration) ... % Track duration mb32(0) mb32(0) ... % Offset and priority mb16(0) mb16(0) mb16(255) mb16(0) ... % Layer, Group, Volume, fill mb32(fixed1) mb32(0) mb32(0) ... % Transformation matrix (identity) mb32(0) mb32(fixed1) mb32(0) ... mb32(0) mb32(0) mb32(frac1)]; if add_sound_p y = [y mb32(0) mb32(0)]; % Zeros for sound else y = [y mb32(fliplr(MakeQTMovieStatus.imageSize)*fixed1)]; end y= SetAtomSize(y); MakeQTMovieStatus.trackNumber = MakeQTMovieStatus.trackNumber + 1; %%%%%%%%%%%%%%% udat_atom %%%%%%%%%%%%%%%%% function y = udat_atom() atfmt = [64 double('fmt')]; atday = [64 double('day')]; VersionString = 'Matlab MakeQTMovie version April 7, 2000'; y = [mb32(0) mbstring('udta') ... SetAtomSize([mb32(0) atfmt mbstring(['Created ' VersionString])]) ... SetAtomSize([mb32(0) atday ' ' date])]; y = SetAtomSize(y); %%%%%%%%%%%%%%% vmhd_atom %%%%%%%%%%%%%%%%% function y = vmhd_atom() y = SetAtomSize([mb32(0) mbstring('vmhd') mb32(0) ... mb16(64) ... % Graphics Mode mb16(0) mb16(0) mb16(0)]); % Op Color
github
mehta-lab/Instantaneous-PolScope-master
recycleProcessGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/recycleProcessGUI.m
9,804
utf_8
a88bb2d4f5b018d7fb9eeabf2b2c51c9
function varargout = recycleProcessGUI(varargin) % RECYCLEPROCESSGUI M-file for recycleProcessGUI.fig % RECYCLEPROCESSGUI, by itself, creates a new RECYCLEPROCESSGUI or raises the existing % singleton*. % % H = RECYCLEPROCESSGUI returns the handle to a new RECYCLEPROCESSGUI or the handle to % the existing singleton*. % % RECYCLEPROCESSGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in RECYCLEPROCESSGUI.M with the given input arguments. % % RECYCLEPROCESSGUI('Property','Value',...) creates a new RECYCLEPROCESSGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before recycleProcessGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to recycleProcessGUI_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 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help recycleProcessGUI % Last Modified by GUIDE v2.5 27-Sep-2011 11:06:56 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @recycleProcessGUI_OpeningFcn, ... 'gui_OutputFcn', @recycleProcessGUI_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 recycleProcessGUI is made visible. function recycleProcessGUI_OpeningFcn(hObject, eventdata, handles, varargin) % % recycleProcessGUI(process, package, 'mainFig', handles.figure1) % % Input: % % process - the array of processes for recycle % package - the package where the processes would be attached to % % User Data: % % userData.recyclableProc - the array of processes for recycle % userData.package - the package where the processes would be attached to % % userData.mainFig - handle of movie selector GUI % % % Input check ip = inputParser; ip.addRequired('hObject',@ishandle); ip.addRequired('eventdata',@(x) isstruct(x) || isempty(x)); ip.addRequired('handles',@isstruct); ip.addRequired('process',@(x) all(cellfun(@(y) isa(y,'Process'),x))); ip.addRequired('package',@(x) isa(x,'Package')); ip.addParamValue('mainFig',-1,@ishandle); ip.parse(hObject,eventdata,handles,varargin{:}) % Store input userData = get(handles.figure1, 'UserData'); userData.recyclableProc =ip.Results.process ; userData.package = ip.Results.package; userData.mainFig=ip.Results.mainFig; userData.previewFig = -1; [copyright] = userfcn_softwareConfig(handles); set(handles.text_copyright, 'String', copyright) % Choose default command line output for recycleProcessGUI handles.output = hObject; % GUI set-up set(handles.text_package, 'String', userData.package.getName) set(handles.text_movie, 'String', [userData.package.owner_.getPath filesep userData.package.owner_.getFilename]) % Create recyclable processes list nProc = numel(userData.recyclableProc); string = cell(1,nProc); for i = 1:nProc string{i} = userData.recyclableProc{i}.getName; end set(handles.listbox_processes, 'String',string, 'UserData',1:nProc) % Create package processes list nProc = numel(userData.package.processes_); string = cell(1,nProc); for i = 1:nProc processClassName = userData.package.getProcessClassNames{i}; processName=eval([processClassName '.getName']); string{i} = [' Step ' num2str(i) ': ' processName]; end set(handles.listbox_package, 'String', string,'UserData',cell(1,nProc)); set(handles.figure1,'UserData',userData) uiwait(handles.figure1) guidata(hObject, handles); % UIWAIT makes recycleProcessGUI wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = recycleProcessGUI_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; delete(handles.figure1) % --- Executes on button press in pushbutton_cancel. function pushbutton_cancel_Callback(hObject, eventdata, handles) uiresume(handles.figure1) % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) % Add the processes to the new package userData = get(handles.figure1, 'UserData'); procIds = get(handles.listbox_package, 'UserData'); validPackageProc=~cellfun(@isempty,procIds); if isempty(find(validPackageProc,1)), uiresume(handles.figure1); end for i = find(validPackageProc) userData.package.setProcess(i,userData.recyclableProc{procIds{i}}); end uiresume(handles.figure1) % --- Executes on button press in pushbutton_add. function pushbutton_add_Callback(hObject, eventdata, handles) % Test if ther is any process to dispatch processString = get(handles.listbox_processes, 'String'); if isempty(processString), return; end % Load process list and get corresponding process id userData=get(handles.figure1,'UserData'); props = get(handles.listbox_processes, {'UserData','Value'}); procIds=props{1}; procIndex = props{2}; procId=procIds(procIndex); process= userData.recyclableProc(procId); % Find associated package process getPackId = @(proc)find(cellfun(@(x) isa(proc,x),userData.package.getProcessClassNames)); packProcIds = cellfun(getPackId,process); if any(packProcIds) % Update package process and pids props = get(handles.listbox_package, {'String','UserData'}); packageString = props{1}; for i = 1:numel(packProcIds) props{2}{packProcIds(i)}=procId(i); packageString{packProcIds(i)} = ['<html><b> ' packageString{packProcIds(i)} '</b></html>']; end set(handles.listbox_package, 'String',packageString','UserData',props{2}); % Remove process from the list processString(procIndex) = []; procIds(procIndex) = []; % Set the highlighted value if ~isscalar(procIndex) || (procIndex > length(processString) && procIndex > 1) set(handles.listbox_processes, 'Value', length(processString)); end set(handles.listbox_processes, 'String', processString, 'UserData', procIds) end % --- Executes on button press in pushbutton_remove. function pushbutton_remove_Callback(hObject, eventdata, handles) % Find package process id and return if empty props = get(handles.listbox_package,{'UserData','Value','String'}); procIds =props{1}; procId = procIds{props{2}}; if isempty(procId), return; end % Remove pid from the package id list and update package string userData=get(handles.figure1,'UserData'); packageString = props{3}; procIds(props{2})=[]; processClassName = userData.package.getProcessClassNames{props{2}}; processName=eval([processClassName '.getName']); packageString{props{2}} = [' Step ' num2str(props{2}) ': ' processName]; set(handles.listbox_package,'String',packageString,'UserData',procIds); % Add process to the process list props = get(handles.listbox_processes, {'UserData','String'}); procIds=props{1}; processString = props{2}; processString{end+1} = userData.recyclableProc{procId}.getName; set(handles.listbox_processes,'String',processString,'UserData',[procIds procId]); % --- Executes when user attempts to close figure1. function figure1_CloseRequestFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) if isequal(get(handles.figure1, 'waitstatus'), 'waiting') % The GUI is still in UIWAIT, us UIRESUME uiresume(handles.figure1); else % The GUI is no longer waiting, just close it delete(handles.figure1); end % --- Executes on button press in pushbutton_preview. function pushbutton_preview_Callback(hObject, eventdata, handles) % Test if ther is any process to preview processString = get(handles.listbox_processes, 'String'); if isempty(processString), return; end % Load process list and get corresponding process id userData=get(handles.figure1,'UserData'); props = get(handles.listbox_processes, {'UserData','Value'}); procIds=props{1}; procIndex = props{2}; procId=procIds(procIndex); userData.previewFig = userData.recyclableProc{procId}.resultDisplay(); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); if ishandle(userData.previewFig), delete(userData.detailFig); end
github
mehta-lab/Instantaneous-PolScope-master
flowAnalysisProcessGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/flowAnalysisProcessGUI.m
7,426
utf_8
940863cc8f0156d649fa7d33edb728b5
function varargout = flowAnalysisProcessGUI(varargin) % flowAnalysisProcessGUI M-file for flowAnalysisProcessGUI.fig % flowAnalysisProcessGUI, by itself, creates a new flowAnalysisProcessGUI or raises the existing % singleton*. % % H = flowAnalysisProcessGUI returns the handle to a new flowAnalysisProcessGUI or the handle to % the existing singleton*. % % flowAnalysisProcessGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in flowAnalysisProcessGUI.M with the given input arguments. % % flowAnalysisProcessGUI('Property','Value',...) creates a new flowAnalysisProcessGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before flowAnalysisProcessGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to flowAnalysisProcessGUI_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 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help flowAnalysisProcessGUI % Last Modified by GUIDE v2.5 30-Sep-2011 21:04:01 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @flowAnalysisProcessGUI_OpeningFcn, ... 'gui_OutputFcn', @flowAnalysisProcessGUI_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 flowAnalysisProcessGUI is made visible. function flowAnalysisProcessGUI_OpeningFcn(hObject, eventdata, handles, varargin) processGUI_OpeningFcn(hObject, eventdata, handles, varargin{:},... 'initChannel',1); % Set process parameters userData = get(handles.figure1, 'UserData'); funParams = userData.crtProc.funParams_; userData.numericParams ={'timeWindow','corrLength','gridSize'}; cellfun(@(x) set(handles.(['edit_' x]),'String',funParams.(x)),... userData.numericParams) set(handles.edit_corrLengthMicrons,'String',... funParams.corrLength*userData.MD.pixelSize_/1000); set(handles.edit_gridSizeMicrons,'String',... funParams.gridSize*userData.MD.pixelSize_/1000); % Set popup-menu flowProc = userData.crtProc.getFlowProcesses; validProc = cellfun(@(x) ~isempty(userData.MD.getProcessIndex(x,1)),flowProc); flowProc=flowProc(validProc); flowString = cellfun(@(x) eval([x '.getName']),flowProc,'Unif',false); flowValue = find(strcmp(funParams.FlowProcess,flowProc)); if isempty(flowValue), flowValue=1; end set(handles.popupmenu_FlowProcess,'String',flowString,'Value',flowValue,... 'UserData',flowProc); % Choose default command line output for speedMapsProcessGUI handles.output = hObject; % Update user data and GUI data set(hObject, 'UserData', userData); guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = flowAnalysisProcessGUI_OutputFcn(~, ~, 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 pushbutton_cancel. function pushbutton_cancel_Callback(~, ~, handles) % Delete figure delete(handles.figure1); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, ~, handles) % Notify the package GUI that the setting panel is closed userData = get(handles.figure1, 'UserData'); if isfield(userData, 'helpFig') && ishandle(userData.helpFig) delete(userData.helpFig) end if isfield(userData, 'previewFig') && ishandle(userData.previewFig) delete(userData.previewFig) end set(handles.figure1, 'UserData', userData); guidata(hObject,handles); % --- Executes on key press with focus on pushbutton_done and none of its controls. function pushbutton_done_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) % Check user input userData = get(handles.figure1, 'UserData'); if isempty(get(handles.listbox_selectedChannels, 'String')) errordlg('Please select at least one input channel from ''Available Channels''.','Setting Error','modal') return; end timeWindow = str2double(get(handles.edit_timeWindow,'String')); if isnan(timeWindow) || timeWindow<=0 || timeWindow > userData.MD.nFrames_ || mod(timeWindow,2)==0 errordlg(sprintf('The time window should be an odd number between 0 and %g.',... userData.MD.nFrames_),'Setting Error','modal') return; end % Process Sanity check ( only check underlying data ) try userData.crtProc.sanityCheck; catch ME errordlg([ME.message 'Please double check your data.'],... 'Setting Error','modal'); return; end % Set parameters channelIndex = get(handles.listbox_selectedChannels, 'Userdata'); funParams.ChannelIndex = channelIndex; for i=1:numel(userData.numericParams) funParams.(userData.numericParams{i})=... str2double(get(handles.(['edit_' userData.numericParams{i}]),'String')); end flowProps = get(handles.popupmenu_FlowProcess,{'UserData','Value'}); funParams.FlowProcess = flowProps{1}{flowProps{2}}; processGUI_ApplyFcn(hObject, eventdata, handles,funParams); function edit_corrLength_Callback(hObject, eventdata, handles) userData=get(handles.figure1,'UserData'); value = str2double(get(handles.edit_corrLength,'String')); set(handles.edit_corrLengthMicrons,'String',value*userData.MD.pixelSize_/1000); function edit_gridSize_Callback(hObject, eventdata, handles) userData=get(handles.figure1,'UserData'); value = str2double(get(handles.edit_gridSize,'String')); set(handles.edit_gridSizeMicrons,'String',value*userData.MD.pixelSize_/1000);
github
mehta-lab/Instantaneous-PolScope-master
userfcn_checkAllMovies.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/userfcn_checkAllMovies.m
2,862
utf_8
6a100db6360cdf72ed28a3fd31dece47
function userfcn_checkAllMovies(procID, value, handles) if get(handles.checkbox_all, 'Value') userData = get(handles.figure1, 'UserData'); for x = setdiff(1:length(userData.MD), userData.id) % Recalls the userData that may have been updated by the % checkAllMovies function % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % userData=get(handles.figure1, 'UserData'); userData.statusM(x).Checked(procID) = value; set(handles.figure1, 'UserData', userData) dfs_checkAllMovies(procID, value, handles, x) end end function dfs_checkAllMovies(procID, value, handles, x) userData = get(handles.figure1, 'UserData'); M = userData.dependM; if value % If check parentI = find(M(procID, :)==1); parentI = parentI(:)'; if isempty(parentI) return else for i = parentI if userData.statusM(x).Checked(i) || ... (~isempty(userData.package(x).processes_{i}) && ... userData.package(x).processes_{i}.success_ ) continue else userData.statusM(x).Checked(i) = 1; set(handles.figure1, 'UserData', userData) dfs_checkAllMovies(i, value, handles, x) end end end else % If uncheck childProcesses = find(M(:,procID)); childProcesses = childProcesses(:)'; if isempty(childProcesses) || ... (~isempty(userData.package(x).processes_{procID}) ... && userData.package(x).processes_{procID}.success_) return; else for i = childProcesses if userData.statusM(x).Checked(i) userData.statusM(x).Checked(i) = 0; set(handles.figure1, 'UserData', userData) dfs_checkAllMovies(i, value, handles, x) end end end end
github
mehta-lab/Instantaneous-PolScope-master
movieSelectorGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/movieSelectorGUI.m
17,862
utf_8
55b8091f6b801ba061cedf901dcdc2ef
function varargout = movieSelectorGUI(varargin) % MOVIESELECTORGUI M-file for movieSelectorGUI.fig % MOVIESELECTORGUI, by itself, creates a new MOVIESELECTORGUI or raises the existing % singleton*. % % H = MOVIESELECTORGUI returns the handle to a new MOVIESELECTORGUI or the handle to % the existing singleton*. % % MOVIESELECTORGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in MOVIESELECTORGUI.M with the given input arguments. % % MOVIESELECTORGUI('Property','Value',...) creates a new MOVIESELECTORGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before movieSelectorGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to movieSelectorGUI_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 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help movieSelectorGUI % Last Modified by GUIDE v2.5 07-Nov-2012 18:14:25 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @movieSelectorGUI_OpeningFcn, ... 'gui_OutputFcn', @movieSelectorGUI_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 movieSelectorGUI is made visible. function movieSelectorGUI_OpeningFcn(hObject, eventdata, handles, varargin) % % Useful tools: % % User Data: % % userData.MD - new or loaded MovieData object % userData.ML - newly saved or loaded MovieList object % % userData.userDir - default open directory % userData.colormap - color map (used for ) % userData.questIconData - image data of question icon % % userData.packageGUI - the name of package GUI % % userData.newFig - handle of new movie set-up GUI % userData.iconHelpFig - handle of help dialog % userData.msgboxGUI - handle of message box GUI ip = inputParser; ip.addRequired('hObject',@ishandle); ip.addRequired('eventdata',@(x) isstruct(x) || isempty(x)); ip.addRequired('handles',@isstruct); ip.addParamValue('packageName','',@ischar); ip.addParamValue('MD',[],@(x) isempty(x) || isa(x,'MovieData')); ip.addParamValue('ML',[],@(x) isempty(x) || isa(x,'MovieList')); ip.parse(hObject,eventdata,handles,varargin{:}); [copyright openHelpFile] = userfcn_softwareConfig(handles); set(handles.text_copyright, 'String', copyright) userData = get(handles.figure1, 'UserData'); % Choose default command line output for setupMovieDataGUI handles.output = hObject; % other user data set-up userData.MD = [ ]; userData.ML = [ ]; userData.userDir = pwd; userData.newFig=-1; userData.msgboxGUI=-1; userData.iconHelpFig =-1; % Load help icon from dialogicons.mat userData = loadLCCBIcons(userData); % Get concrete packages packageList = getPackageList(); if isempty(packageList), warndlg('No package found! Please make sure you properly added the installation directory to the path (see user''s manual).',... 'Movie Selector','modal'); end packageNames = cellfun(@(x) eval([x '.getName']),packageList,'Unif',0); [packageNames,index]=sort(packageNames); packageList=packageList(index); % Create radio controls for packages nPackages=numel(packageList); pos = get(handles.uipanel_packages,'Position'); for i=1:nPackages uicontrol(handles.uipanel_packages,'Style','radio',... 'Position',[30 pos(4)-20-30*i pos(3)-35 20],'Tag',['radiobutton_package' num2str(i)],... 'String',[' ' packageNames{i}],'UserData',packageList{i},... 'Value',strcmp(packageList{i},ip.Results.packageName)) axes('Units','pixels',... 'Position',[10 pos(4)-20-30*i 20 20],'Tag',['axes_help_package' num2str(i)],... 'Parent',handles.uipanel_packages) Img = image(userData.questIconData, 'UserData', struct('class', packageList{i})); set(gca, 'XLim',get(Img,'XData'),'YLim',get(Img,'YData'), 'Visible','off'); set(Img,'ButtonDownFcn',@icon_ButtonDownFcn); end set(handles.uipanel_packages,'SelectionChangeFcn',''); % Populate movie list to analyze if ~isempty(ip.Results.ML) userData.ML=ip.Results.ML; % Populate movies with the movie list components if no MD is passed if isempty(ip.Results.MD) MD = arrayfun(@(x) horzcat(x.getMovies{:}),userData.ML,'Unif',0); userData.MD = horzcat(MD{:}); else userData.MD = []; end end % Populate movies to analyze if ~isempty(ip.Results.MD) userData.MD = horzcat(userData.MD,ip.Results.MD); end % Filter movies to get a unique list [~,index] = unique(arrayfun(@getFullPath,userData.MD,'Unif',0)); userData.MD = userData.MD(sort(index)); % Filter movie lists to get a unique list [~,index] = unique(arrayfun(@getFullPath,userData.ML,'Unif',0)); userData.ML = userData.ML(sort(index)); supermap(1,:) = get(hObject,'color'); userData.colormap = supermap; set(handles.figure1,'CurrentAxes',handles.axes_help); Img = image(userData.questIconData); set(hObject,'colormap',supermap); set(gca, 'XLim',get(Img,'XData'),'YLim',get(Img,'YData'),... 'visible','off'); set(Img,'ButtonDownFcn',@icon_ButtonDownFcn); if openHelpFile, set(Img, 'UserData', struct('class',mfilename)); end set(handles.figure1,'UserData',userData); refreshDisplay(hObject,eventdata,handles); % Save userdata guidata(hObject, handles); function packageList = getPackageList() packageList = {'BiosensorsPackage';... 'FocalAdhesionPackage' 'IntegratorPackage' 'QFSMPackage' 'SegmentationPackage' 'TFMPackage' 'TrackingPackage' 'WindowingPackage'}; validPackage = cellfun(@(x) exist(x,'class')==8,packageList); packageList = packageList(validPackage); % --- Outputs from this function are returned to the command line. function varargout = movieSelectorGUI_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 pushbutton_cancel. function pushbutton_cancel_Callback(hObject, eventdata, handles) delete(handles.figure1) % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) % Check a package is selected if isempty(get(handles.uipanel_packages, 'SelectedObject')) warndlg('Please select a package to continue.', 'Movie Selector', 'modal') return end % Retrieve the ID of the selected button and call the appropriate userData = get(handles.figure1, 'UserData'); selectedPackage=get(get(handles.uipanel_packages, 'SelectedObject'),'UserData'); % Select movie or list depending on the package nature class = eval([selectedPackage '.getMovieClass()']); if strcmp(class, 'MovieList') type = 'movie list'; field = 'ML'; else type = 'movie'; field = 'MD'; end if isempty(userData.(field)) warndlg(['Please load at least one ' type ' to continue.'], 'Movie Selector', 'modal') return end close(handles.figure1); packageGUI(selectedPackage,userData.(field),... 'MD', userData.MD, 'ML', userData.ML); % --- Executes on selection change in listbox_movie. function listbox_movie_Callback(hObject, eventdata, handles) refreshDisplay(hObject, eventdata, handles) % --- Executes on button press in pushbutton_new. function pushbutton_new_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); % if movieDataGUI exist, delete it if ishandle(userData.newFig), delete(userData.newFig); end userData.newFig = movieDataGUI('mainFig',handles.figure1); set(handles.figure1,'UserData',userData); % --- Executes on button press in pushbutton_prepare. function pushbutton_prepare_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); % if preparation GUI exist, delete it if ishandle(userData.newFig), delete(userData.newFig); end userData.newFig = dataPreparationGUI('mainFig',handles.figure1); set(handles.figure1,'UserData',userData); % --- Executes on button press in pushbutton_delete. function pushbutton_delete_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'Userdata'); if isempty(userData.MD), return;end % Delete channel object num = get(handles.listbox_movie,'Value'); removedMovie=userData.MD(num); userData.MD(num) = []; % Test if movie does not share common ancestor checkCommonAncestor= arrayfun(@(x) any(isequal(removedMovie.getAncestor,x.getAncestor)),userData.MD); if ~any(checkCommonAncestor), delete(removedMovie); end % Refresh listbox_channel set(handles.figure1, 'Userdata', userData) refreshDisplay(hObject,eventdata,handles); guidata(hObject, handles); % --- Executes on button press in pushbutton_detail. function pushbutton_detail_Callback(hObject, eventdata, handles) % Return if no movie props=get(handles.listbox_movie, {'String','Value'}); if isempty(props{1}), return; end userData = get(handles.figure1, 'UserData'); % if movieDataGUI exist, delete it userData.newFig = movieDataGUI(userData.MD(props{2})); set(handles.figure1,'UserData',userData); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); if ishandle(userData.newFig), delete(userData.newFig); end if ishandle(userData.iconHelpFig), delete(userData.iconHelpFig); end if ishandle(userData.msgboxGUI), delete(userData.msgboxGUI); end % --- Executes on button press in pushbutton_open. function pushbutton_open_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); filespec = {'*.mat','MATLAB Files'}; [filename, pathname] = uigetfile(filespec,'Select a movie or a list of movies', ... userData.userDir); if ~any([filename pathname]), return; end userData.userDir = pathname; % Check if reselect the movie data that is already in the listbox moviePaths = get(handles.listbox_movie, 'String'); movieListPaths = get(handles.listbox_movieList, 'String'); if any(strcmp([pathname filename],vertcat(moviePaths,movieListPaths))) errordlg('This movie has already been selected.','Error','modal'); return end try M = MovieObject.load([pathname filename]); catch ME msg = sprintf('Movie: %s\n\nError: %s\n\nMovie is not successfully loaded. Please refer to movie detail and adjust your data.', [pathname filename],ME.message); errordlg(msg, 'Movie error','modal'); return end switch class(M) case 'MovieData' userData.MD = cat(2, reshape(userData.MD,1,[]), M); case 'MovieList' % Find duplicate movie data in list box movieDataFile = M.movieDataFile_; index = 1: length(movieDataFile); movieList=get(handles.listbox_movie,'String'); index = index(~ismember(movieDataFile,movieList)); if isempty(index) msg = sprintf('All movie data in movie list file %s has already been added to the movie list box.', M.movieListFileName_); warndlg(msg,'Warning','modal'); end % Healthy Movie Data userData.ML = horzcat(userData.ML, M); userData.MD = horzcat(userData.MD,M.getMovies{index}); otherwise error('User-defined: varable ''type'' does not have an approprate value.') end % Refresh movie list box in movie selector panel set(handles.figure1, 'UserData', userData); refreshDisplay(hObject,eventdata,handles); function menu_about_Callback(hObject, eventdata, handles) status = web(get(hObject,'UserData'), '-browser'); if status switch status case 1 msg = 'System default web browser is not found.'; case 2 msg = 'System default web browser is found but could not be launched.'; otherwise msg = 'Fail to open browser for unknown reason.'; end warndlg(msg,'Fail to open browser','modal'); end % -------------------------------------------------------------------- function menu_file_quit_Callback(hObject, eventdata, handles) delete(handles.figure1) % --- Executes on button press in pushbutton_deleteall. function pushbutton_deleteall_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'Userdata'); contentlist = get(handles.listbox_movie,'String'); % Return if list is empty if isempty(contentlist), return; end % Confirm deletion user_response = questdlg(['Are you sure to delete all the '... 'movies and movie lists?'], ... 'Movie Listbox', 'Yes','No','Yes'); if strcmpi('no', user_response), return; end % Delete movies and movie lists userData.MD = []; userData.ML = []; set(handles.figure1, 'Userdata', userData) refreshDisplay(hObject, eventdata, handles) guidata(hObject, handles); % --- Executes on button press in pushbutton_save. function pushbutton_save_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); contentList = get(handles.listbox_movie, 'String'); if isempty(contentList) warndlg('No movie selected. Please create new movie data or open existing movie data or movie list.', 'No Movie Selected', 'modal') return end if isempty(userData.ML) movieListPath = [userData.userDir filesep]; movieListFileName = 'movieList.mat'; else movieListPath = userData.ML(end).movieListPath_; movieListFileName = userData.ML(end).movieListFileName_; end % Ask user where to save the movie data file [filename,path] = uiputfile('*.mat','Find a place to save your movie list',... [movieListPath filesep movieListFileName]); if ~any([filename,path]), return; end % Ask user where to select the output directory of the outputDir = uigetdir(path,'Select a directory to store the list analysis output'); if isequal(outputDir,0), return; end try ML = MovieList(contentList, outputDir); ML.setPath(path); ML.setFilename(filename); ML.sanityCheck; catch ME msg = sprintf('%s\n\nMovie list is not saved.', ME.message); errordlg(msg, 'Movie List Error', 'modal') return end userData.ML=cat(2,userData.ML,ML); set(handles.figure1,'UserData',userData); refreshDisplay(hObject, eventdata, handles) % -------------------------------------------------------------------- function menu_tools_crop_Callback(hObject, eventdata, handles) % Return if no movie props=get(handles.listbox_movie, {'String','Value'}); if isempty(props{1}), return; end userData = get(handles.figure1, 'UserData'); if ishandle(userData.newFig), delete(userData.newFig); end userData.newFig = cropMovieGUI(userData.MD(props{2}),'mainFig',handles.figure1); set(handles.figure1,'UserData',userData); % -------------------------------------------------------------------- function menu_tools_addROI_Callback(hObject, eventdata, handles) % Return if no movie props=get(handles.listbox_movie, {'String','Value'}); if isempty(props{1}), return; end userData = get(handles.figure1, 'UserData'); if ishandle(userData.newFig), delete(userData.newFig); end userData.newFig = addMovieROIGUI(userData.MD(props{2}),'mainFig',handles.figure1); set(handles.figure1,'UserData',userData); % --- Executes on selection change in listbox_movie. function refreshDisplay(hObject, eventdata, handles) userData = get(handles.figure1,'UserData'); % Display Movie information moviePaths = arrayfun(@getFullPath,userData.MD,'Unif',false); nMovies= numel(userData.MD); iMovie = get(handles.listbox_movie, 'Value'); if isempty(userData.MD), iMovie=0; else iMovie=max(1,min(iMovie,nMovies)); end set(handles.listbox_movie,'String',moviePaths,'Value',iMovie); set(handles.text_movies, 'String', sprintf('%g/%g movie(s)',iMovie,nMovies)) % Display list information listPaths = arrayfun(@getFullPath,userData.ML,'Unif',false); nLists= numel(userData.ML); iList = get(handles.listbox_movieList, 'Value'); if isempty(userData.ML), iList=0; else iList=max(1,min(iList,nLists)); end set(handles.listbox_movieList,'String',listPaths); set(handles.text_movieList, 'String', sprintf('%g/%g movie list(s)',iList,nLists)) % --- Executes on button press in pushbutton_deletelist. function pushbutton_deletelist_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'Userdata'); if isempty(userData.MD), return;end % Delete channel object iList = get(handles.listbox_movie,'Value'); delete(userData.ML(iList)); userData.ML(iList) = []; % Refresh listbox_channel set(handles.figure1, 'Userdata', userData) refreshDisplay(hObject,eventdata,handles); guidata(hObject, handles);
github
mehta-lab/Instantaneous-PolScope-master
trackSpecklesGapCloser.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/trackSpecklesGapCloser.m
25,186
utf_8
ccb0557af7abf183da3707242a5dd994
function [M,gapList]=trackSpecklesGapCloser(M,threshold,invalidCands,varargin) % fsmTrackgapCloser closes gaps in speckles lifetimes by recovering weak % local maxima close (in space and time) to a birth and death event % % SYNOPSIS [M,gapClosed]=fsmTrackGapCloser(M,threshold,strg,userPath,firstIndex,frame) % % INPUT M : M stack as returned by the tracker functions % M = [y x y x] [y x y x] [y x y x] % ... , ... , ... % t1 t2 t2 t3 t3 t4 % 1 2 3 % threshold : radius of the considered neighborhood % invalidCands : String to correctly format the numeric suffix of saved files % userPath : Work path % firstIndex : index of the first corresponding image % frame : optional - by default, the gap closer goes % through the whole M stack and closes all gaps. % Alternatively, it can be used to close exclusively % the gaps at tn somewhere in the middle of the M matrix. % The user passes, for tn, M(:,:,n:n+1) to the gap % closer and must also set the variable frame=n. % This will be used to load the corresponding % cands###.mat file (see fsm PREPROCESSING module). % If size(M,3) is > 2 the input parameter frame is IGNORED. % % OUTPUT M : corrected M stack % gapClosed : number of gaps closed % % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Aaron Ponti, October 4th, 2002 % Sebastien Besson, June 2011 % Adapted from fsmTrackGapCloser % Check input ip = inputParser; ip.addRequired('M',@(x) size(x,3)>1); ip.addRequired('threshold',@isscalar); ip.addRequired('invalidCands',@iscell); ip.addParamValue('vectors',[],@iscell); ip.addParamValue('waitbar',[],@ishandle); ip.parse(M,threshold,invalidCands,varargin{:}); vectors = ip.Results.vectors; %Initialize counters matching=0; notMatching=0; % Initialize gapList gapList = cell(1,size(M,3)+1); gapList{1} = [0 0]; gapList{end} = [0 0]; if ~isempty(ip.Results.waitbar) h=ip.Results.waitbar; waitbar(0,h,'Closing gaps...'); else h=waitbar(0,'Closing gaps...'); end for i=1:size(M,3)-1 % Load cands structure cands = invalidCands{i+1}; % No insignificant local maxima, no need to try and close gaps if isempty(cands), gapList{i+1}=[0 0]; continue; end if ~isempty(vectors) % Extract source and target positions to be (back)propagated source=M(:,1:2,i); target=M(:,3:4,i+1); % Keep track of the row in source and target which contain the speckles fS=find(source(:,1)~=0); fT=find(target(:,1)~=0); % Forward propagate pSource=propagateSpecklePositions(source(fS,:),vectors{i},'forward'); % Backward propagate pTarget=propagateSpecklePositions(target(fT,:),vectors{i+1},'backward'); % Create the copy of M (only three time-points) Mcopy=M(:,:,i:i+1); Mcopy(fS,1:2,1)=pSource; Mcopy(fT,3:4,2)=pTarget; % Pass the copy to the gap closing subfunction [pMcopy,glist,match,notMatch] = closeGap(Mcopy,1,cands,threshold); % Replace propagated positions with original positions and write back % to M (with gap closed) M(:,:,i:i+1)=pMcopy; M(:,1:2,i)=source; M(:,3:4,i+1)=target; else [M,glist,match,notMatch] = closeGap(M,i,cands,threshold); end % Update counters and gapList cell array gapList{i+1} = glist; matching = matching+match; notMatching = notMatching+notMatch; waitbar(i/(size(M,3)-1),h); end % Display results tot=matching+notMatching; if tot~=0 fprintf(1,'Closed gaps: %d/%d (%d%%)\n',matching,tot,fix(matching/tot*100)); else fprintf(1,'No gaps found!!!\n'); end % Close waitbar if not-delegated if isempty(ip.Results.waitbar), close(h); end function [M,gapList,matching,notMatching] = closeGap(M,iFrame,cands,threshold) % Initialize counters matching=0; notMatching=0; gapList=[]; % Read current time-point (first = 2) P=M(:,1:2,iFrame); % previous time-point ( P ) C=M(:,3:4,iFrame); % current time-point ( C ) T=M(:,1:2,iFrame+1); % to be modified to close gaps ( T ) N=M(:,3:4,iFrame+1); % next time-point ( N ) % Positions of non-speckles (in C) posC=C(:,1)==0; posC=find(posC); % Check for existance of speckles at these positions in P % posP=P(posC,1)~=0; % posP=find(posP); posP=posC(P(posC,1)~=0); % Read the speckle coordinates in P pM=P(posP,:); % Positions of non-speckles (in T) posT=T(:,1)==0; posT=find(posT); % Check for existance of speckles at these positions in N posN=N(posT,1)~=0; posN=posT(posN); % Read the speckle coordinates in N nM=N(posN,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Check if some of the speckles in N at the positions given % by pos match those given by posP % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(pM) && ~isempty(nM) % There are candidate speckles % Create distance matrix D=createDistanceMatrix(pM,nM); % Row E=zeros(size(D)); for i=1:size(D,1) t=D(i,:); t=t==min(t); E(i,:)=t; end % Column F=zeros(size(D)); for i=1:size(D,2) t=D(:,i); t=t==min(t); F(:,i)=t; end % Thresholding H=D<=threshold; % Resulting selected distance matrix G=(E & F & H); % Now find matching pairs: y = speckle in pM, x = speckle in nM [y x]=find(G); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % If there exist some speckles from N matching some speckles from P, build a % matching matrix (PM) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(y) && ~isempty(x) % Speckles have to be paired % Sort y and x (preserving coupling!) to avoid future problems PM=[]; PM(1:length(y),1)=y; PM(1:length(x),2)=x; PM=sortrows(PM,1:2); y=PM(:,1); x=PM(:,2); PM=[]; % Now build matching pairs len=length(unique(sort(y))); % Must be sorted for unique, otherwise you will lose some of the speckles! counter=1; for i=1:len nY=y; % Create a copy of y for boolean testing posY=y(counter); nY=nY==posY; indx=find(nY); PM(i,1)=posY; PM(i,2:1+length(indx))=x(indx)'; counter=counter+length(x(indx)'); end clear counter; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Check whether a speckle in nM is bound to more than one speckle in pM % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% RepetitionList=[]; numberOfRepetitions=0; source=unique(sort(PM(:,2))); target=PM(:,2); if length(source)<length(target) counter=0; for cn=1:length(source) % ss=source(cn); ss=ss==target(:); ss=find(ss); if length(ss)>1 % Keep the first repeating speckle, mark all others to be deleted ss(1,:)=[]; counter=counter+1; RepetitionList(counter:counter+length(ss)-1,1)=ss; counter=counter+length(ss)-1; numberOfRepetitions=numberOfRepetitions+1; end end % Remove marked repeating speckles if RepetitionList~=0 PM(RepetitionList,:)=[]; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Start closing gaps % sD = [y x] : coordinates of the speckle to be written into M % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% clear D E F G H % % Go through PM % for c2=1:size(PM,1) % Initialize sD sD=[]; % Go through speckles t=PM(c2,2:end)>0; t=find(t); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MORE THAN TWO SPECKLES FROM nM MATCH THE SPECKLE FROM pM % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if length(t)>2 fprintf(1,'\nWarning -> gapCloser: one speckle death is matched by %d births.\n',length(t)); fprintf(1,'One will be selected without further analysis.\n'); % This problem is reduced to a 1 to 1 case PM(c2,3:end)=0; % Remove index of death events 2 and above t=1; % Set the number of death events found to 1 end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ONLY ONE SPECKLE FROM nM MATCHES THE SPECKLE FROM pM % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if length(t)==1 % Only one matching speckle st=pM(PM(c2,1),:); % Look for a loc max in the cands structure close to st tmp=[cands.Lmax]; tmp=reshape(tmp,2,length(tmp)/2)'; D=createDistanceMatrix(tmp,st); % Find minimum distance (which has also to be < a given threshold) E=(D<threshold & D==min(D)); E=find(E); if ~isempty(E) % Check that only one speckle is at minimum distance if length(E)>1 for i=1:length(E) sD(i,1:2)=cands(E(i)).Lmax; end % Use also the speckle from N to build a distance criterium sp=nM(PM(c2,2),:); % Select one of the speckles from the cands structure for i=1:length(E) D2(i,1)=sqrt((sD(i,1)-st(1))^2+(sD(i,2)-st(2))^2)*... % Distance to st sqrt((sD(i,1)-sp(1))^2+(sD(i,2)-sp(2))^2); % Distance to sp end % Select min distance D2=D2==min(D2); % Check that these speckles are not already coupled (in T) w=[]; for i=1:length(E) v2=[]; t2=sD(i,1)==T(:,1); u2=sD(i,2)==T(:,2); v2=find(t2 & u2); if isempty(v2) w(i,1)=1; end if length(v2)==1 w(i,1)=0; end if length(v2)>1 error('This SHOULDN''T OCCUR!'); end end % Insert this info into the criterion D2=w.*D2; % Get speckle D2=find(D2); % Pick out speckle if isempty(D2), sD=[]; end if length(D2)==1 sD=sD(D2,:); % "Remove" assigned speckle from the cands structure cands(E(D2)).Lmax=[Inf Inf]; end if length(D2)>1 D2=D2(1); sD=sD(D2,:); % "Remove" assigned speckle from the cands structure cands(E(D2)).Lmax=[Inf Inf]; end else % Valid match - Gap successfully closed sD=cands(E).Lmax; % "Remove" assigned speckle from the cands structure cands(E).Lmax=[Inf Inf]; end else %disp('No candidate speckle found in the cands structure'); sD=[]; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TWO SPECKLES FROM nM MATCH THE SPECKLE FROM pM % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if length(t)==2 % % SPECKLE 1 % % First matching speckle st=pM(PM(c2,1),:); % Look for a loc max in the cands structure close to st tmp=[cands.Lmax]; tmp=reshape(tmp,2,length(tmp)/2)'; D=createDistanceMatrix(tmp,st); % Find minimum distance (which has also to be < a given threshold) E=(D<threshold & D==min(D)); E=find(E); if ~isempty(E) % Check that only one speckle is at minimum distance if length(E)>1 for i=1:length(E) sD(i,1:2)=cands(E(i)).Lmax; end % Use also the speckle from N to build a distance criterium sp=nM(PM(c2,2),:); % Select one of the speckles from the cands structure for i=1:length(E) D2(i,1)=sqrt((sD(i,1)-st(1))^2+(sD(i,2)-st(2))^2)*... % Distance to st sqrt((sD(i,1)-sp(1))^2+(sD(i,2)-sp(2))^2); % Distance to sp end % Select min distance D2=D2==min(D2); % Check that these speckles are not already coupled (in T) w=[]; for i=1:length(E) v2=[]; t2=sD(i,1)==T(:,1); u2=sD(i,2)==T(:,2); v2=find(t2 & u2); if isempty(v2) w(i,1)=1; end if length(v2)==1 w(i,1)=0; end if length(v2)>1 error('This SHOULDN''T OCCUR!'); end end % Insert this info into the criterion D2=w.*D2; % Get speckle D2=find(D2); % Pick out speckle if length(D2)==0 sD1=[]; E1=[]; sD=[]; end if length(D2)==1 sD1=sD(D2,:); E1=E(D2); sD=[]; end if length(D2)>1 D2=D2(1); sD1=sD(D2,:); E1=E(1); sD=[]; end else % First candidate speckle (sD1) sD1=cands(E).Lmax; E1=E; end else % NO CANDIDATE SPECKLE FOUND sD1=[]; E1=E; end % % SPECKLE 2 % clear D D2 E F G H sD=[]; % First speckle is always the same st=pM(PM(c2,1),:); % Look for a loc max in the cands structure data close to st tmp=[cands.Lmax]; tmp=reshape(tmp,2,length(tmp)/2)'; D=createDistanceMatrix(tmp,st); % Find minimum distance (which has also to be < a given threshold) E=(D<threshold & D==min(D)); E=find(E); if ~isempty(E) % Check that only one speckle is at minimum distance if length(E)>1 for i=1:length(E) sD(i,1:2)=cands(E(i)).Lmax; end % Use also the speckle from N to build a distance criterium sp=nM(PM(c2,3),:); % Select one of the speckles from the cands structure for i=1:length(E) D2(i,1)=sqrt((sD(i,1)-st(1))^2+(sD(i,2)-st(2))^2)*... % Distance to st sqrt((sD(i,1)-sp(1))^2+(sD(i,2)-sp(2))^2); % Distance to sp end % Select min distance D2=D2==min(D2); % Check that these speckles are not already coupled (in T) w=[]; for i=1:length(E) v2=[]; t2=sD(i,1)==T(:,1); u2=sD(i,2)==T(:,2); v2=find(t2 & u2); if isempty(v2) w(i,1)=1; end if length(v2)==1 w(i,1)=0; end if length(v2)>1 error('This SHOULDN''T OCCUR!'); end end % Insert this info into the criterion D2=w.*D2; % Get speckle D2=find(D2); % Pick out speckle if isempty(D2) sD2=[]; E2=[]; sD=[]; end if length(D2)==1 sD2=sD(D2,:); E2=E(D2); sD=[]; end if length(D2)>1 D2=D2(1); sD2=sD(D2,:); E2=E(1); sD=[]; end else % Second candidate speckle (sD2) sD2=cands(E).Lmax; E2=E; end else % NO CANDIDATE SPECKLE FOUND sD2=[]; E2=E; end % % SELECT BETWEEN SPECKLE 1 AND 2 % % Check that speckle 1 is not already coupled (in T) if ~isempty(sD1) t1=sD1(1,1)==T(:,1); u1=sD1(1,2)==T(:,2); v1=(t1 & u1); if ~isempty(find(v1,1)), sD1=[]; end end % Check that speckle 2 is not already coupled (in T) if ~isempty(sD2) t2=sD2(1,1)==T(:,1); u2=sD2(1,2)==T(:,2); v2=(t2 & u2); if ~isempty(find(v2,1)), sD2=[]; end end % Select if isempty(sD1) && isempty(sD2) sD=[]; E=[]; end if isempty(sD1) && ~isempty(sD2) sD=sD2; E=E2; end if ~isempty(sD1) && isempty(sD2) sD=sD1; E=E1; end if ~isempty(sD1) && ~isempty(sD2) D12(1,1)=sqrt((sD1(1,1)-st(1))^2+(sD1(1,2)-st(2))^2); D12(2,1)=sqrt((sD2(1,1)-st(1))^2+(sD2(1,2)-st(2))^2); D12=D12==min(D12); D12=find(D12); if length(D12)==1 if D12==1 sD=sD1; E=E1; end if D12==2 sD=sD2; E=E2; end end if length(D12)==2 % Simply take one of them sD=sD1; E=E1; end end % Remove from the cands structure if ~isempty(E) cands(E).Lmax=[Inf Inf]; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SELECTED SPECKLE HAS NOW TO BE WRITTEN INTO M % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(sD) % Check that this speckle is not already coupled (in T) % (this is redundant in the case that more than one speckle were found in the cands structure) t=sD(1,1)==T(:,1); u=sD(1,2)==T(:,2); v=(t & u); if isempty(find(v,1)) % Another speckle to be added to the list of "closed gaps" matching=matching+1; % Valid match - write st to M (to close gap) M(posP(PM(c2,1)),3:4,iFrame)=sD; M(posN(PM(c2,2)),1:2,iFrame+1)=sD; % Write this speckle as 'gap' gapList(matching,1:2)=sD; else % Update counter notMatching=notMatching+1; end else % Update counter notMatching=notMatching+1; end end end end
github
mehta-lab/Instantaneous-PolScope-master
processGUI_OpeningFcn.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/processGUI_OpeningFcn.m
9,135
utf_8
3d6bce13e58298f8d84b38e07a0aebdc
function processGUI_OpeningFcn(hObject, eventdata, handles, string,varargin) % Common initialization of concrete process GUIs % % This function fills various fields of the userData % userData.mainFig - handle to the main figure % userData.handles_main - 'handles' of main figure % userData.procID - The ID of process in the current package % userData.MD - current MovieData array % userData.MD - current MovieList array % userData.crtProc - current process % userData.crtPackage - current package % userData.crtProcClassName - current process class % (as defined by the package: can be superclass) % userData.procConstr - constructor of current process % % userData.questIconData - help icon image information % userData.colormap - color map information % % Sebastien Besson May 2011 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Check input % The mainFig and procID should always be present % procCOnstr and procName should only be present if the concrete process % initation is delegated from an abstract class. Else the constructor will % be directly read from the package constructor list. ip = inputParser; ip.addRequired('hObject',@ishandle); ip.addRequired('eventdata',@(x) isstruct(x) || isempty(x)); ip.addRequired('handles',@isstruct); ip.addRequired('string',@(x) isequal(x,'mainFig')); ip.addOptional('mainFig',[],@ishandle); ip.addOptional('procID',[],@isscalar); ip.addParamValue('procConstr',[],@(x) isa(x,'function_handle')); ip.addParamValue('procClassName','',@ischar); ip.addParamValue('initChannel',0,@isscalar); ip.parse(hObject,eventdata,handles,string,varargin{:}); % Retrieve userData and read function input userData = get(handles.figure1, 'UserData'); userData.mainFig=ip.Results.mainFig; userData.procID = ip.Results.procID; userData.procConstr=ip.Results.procConstr; userData.crtProcClassName = ip.Results.procClassName; initChannel = ip.Results.initChannel; % Set up copyright statement [copyright openHelpFile] = userfcn_softwareConfig(handles); set(handles.text_copyright, 'String', copyright) % Get current package, movie data and process userData.handles_main = guidata(userData.mainFig); userData_main = get(userData.mainFig, 'UserData'); userData.crtPackage = userData_main.crtPackage; if strcmp(userData.crtPackage.getMovieClass(), 'MovieData') userData.MD = userData_main.MD(userData_main.id); else userData.ML = userData_main.ML(userData_main.id); end % If constructor is not inherited from abstract class, read it from package if isempty(userData.procConstr) userData.procConstr = userData.crtPackage.getDefaultProcessConstructors{userData.procID}; userData.crtProcClassName = userData.crtPackage.getProcessClassNames{userData.procID}; end % Retrieve crtProc if procID step of the package is set up AND is the same % class as the current process crtProcName = eval([userData.crtProcClassName '.getName']); if isa(userData.crtPackage.processes_{userData.procID},userData.crtProcClassName) userData.crtProc = userData.crtPackage.processes_{userData.procID}; else userData.crtProc =[]; end % Set process names in the text box and figure title procString = [' Step ' num2str(userData.procID) ': ' crtProcName]; set(handles.text_processName,'String',procString); figString = [' Setting - ' crtProcName]; set(handles.figure1,'Name',figString); % Initialize help, preview figure userData.helpFig=-1; userData.previewFig=-1; % Get icon infomation userData.questIconData = userData_main.questIconData; userData.colormap = userData_main.colormap; % If process does not exist, create a default one in user data. if isempty(userData.crtProc) try movieClass = userData.crtPackage.getMovieClass(); if strcmp(movieClass,'MovieData') userData.crtProc = userData.procConstr(userData.MD, ... userData.crtPackage.outputDirectory_); else userData.crtProc = userData.procConstr(userData.ML, ... userData.crtPackage.outputDirectory_); end catch ME if ~isequal(ME.identifier,'MATLAB:class:MethodRestricted') rethrow(ME); end end end % Check for multiple movies else if isfield(handles,'checkbox_applytoall') if numel(userData_main.MD) ==1 set(handles.checkbox_applytoall,'Value',0,'Visible','off'); else set(handles.checkbox_applytoall, 'Value',... userData_main.applytoall(userData.procID)); end uicontrol(handles.pushbutton_done); end % ----------------------Set up help icon------------------------ % Set up help icon set(hObject,'colormap',userData.colormap); % Set up package help. Package icon is tagged as '0' set(handles.figure1,'CurrentAxes',handles.axes_help); Img = image(userData.questIconData); set(gca, 'XLim',get(Img,'XData'),'YLim',get(Img,'YData'),... 'visible','off','YDir','reverse'); set(Img,'ButtonDownFcn',@icon_ButtonDownFcn); if openHelpFile set(Img, 'UserData', struct('class',userData.crtProcClassName)) end % Update user data and GUI data set(hObject, 'UserData', userData); % ---------------------------------------------------------------- if ~initChannel, return; end funParams = userData.crtProc.funParams_; % Set up available input channels set(handles.listbox_availableChannels,'String',userData.MD.getChannelPaths(), ... 'UserData',1:numel(userData.MD.channels_)); channelIndex = funParams.ChannelIndex; % Find any parent process parentProc = userData.crtPackage.getParent(userData.procID); if isempty(userData.crtPackage.processes_{userData.procID}) && ~isempty(parentProc) % Check existence of all parent processes emptyParentProc = any(cellfun(@isempty,userData.crtPackage.processes_(parentProc))); if ~emptyParentProc % Intersect channel index with channel index of parent processes parentChannelIndex = @(x) userData.crtPackage.processes_{x}.funParams_.ChannelIndex; for i = parentProc channelIndex = intersect(channelIndex,parentChannelIndex(i)); end end end if ~isempty(channelIndex) channelString = userData.MD.getChannelPaths(channelIndex); else channelString = {}; end set(handles.listbox_selectedChannels,'String',channelString,... 'UserData',channelIndex); % Set default channels callback function set(handles.checkbox_all,'Callback',@(hObject,eventdata)... checkallChannels(hObject,eventdata,guidata(hObject))); set(handles.pushbutton_select,'Callback',@(hObject,eventdata)... selectChannel(hObject,eventdata,guidata(hObject))); set(handles.pushbutton_delete,'Callback',@(hObject,eventdata)... deleteChannel(hObject,eventdata,guidata(hObject))); % --- Executes on button press in checkbox_all. function checkallChannels(hObject, eventdata, handles) % Retrieve available channels properties availableProps = get(handles.listbox_availableChannels, {'String','UserData'}); if isempty(availableProps{1}), return; end % Update selected channels if get(hObject,'Value') set(handles.listbox_selectedChannels, 'String', availableProps{1},... 'UserData',availableProps{2}); else set(handles.listbox_selectedChannels, 'String', {}, 'UserData',[], 'Value',1); end % --- Executes on button press in pushbutton_select. function selectChannel(hObject, eventdata, handles) % Retrieve channels properties availableProps = get(handles.listbox_availableChannels, {'String','UserData','Value'}); selectedProps = get(handles.listbox_selectedChannels, {'String','UserData'}); % Find new elements and set them to the selected listbox newID = availableProps{3}(~ismember(availableProps{1}(availableProps{3}),selectedProps{1})); selectedChannels = horzcat(selectedProps{1}',availableProps{1}(newID)'); selectedData = horzcat(selectedProps{2}, availableProps{2}(newID)); set(handles.listbox_selectedChannels, 'String', selectedChannels, 'UserData', selectedData); % --- Executes on button press in pushbutton_delete. function deleteChannel(hObject, eventdata, handles) % Get selected properties and returin if empty selectedProps = get(handles.listbox_selectedChannels, {'String','UserData','Value'}); if isempty(selectedProps{1}) || isempty(selectedProps{3}),return; end % Delete selected item selectedProps{1}(selectedProps{3}) = [ ]; selectedProps{2}(selectedProps{3}) = [ ]; set(handles.listbox_selectedChannels, 'String', selectedProps{1},'UserData',selectedProps{2},... 'Value',max(1,min(selectedProps{3},numel(selectedProps{1}))));
github
mehta-lab/Instantaneous-PolScope-master
detectSpeckles.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/detectSpeckles.m
17,854
utf_8
c6568f7101403d3a5d1728d5d68606e2
function [cands locMax]=detectSpeckles(I,noiseParam,specParam,varargin) % detectSpeckles detects speckles in a filtered image % % Plots PSFs on the positions of the primary speckles (found by locmax operator) and substructs % them from the filtered data. Appled again on the resulting image, the locmax-operator finds % new (secondary) speckles (intensity and distance significance tests applied) % % % SYNOPSIS cands=detectSpeckles(I,strg,counter,noiseParam,Speckles) % % INPUT I : filtered image % noiseParam : noise parameters for statistical speckle selection % specParam : (1) contains information for the hierarchical level % (2) minimal increase in (%) of new speckles % (before stopping) % % OUTPUT cands : augmented cands structure (see fsmPrepTestLocalMaxima.m) % locMax : image containing the significant local maxima % % References: % A. Ponti et al., Biophysical J., 84 336-3352, 2003. % A. Ponti et al., Biophysical J., 89 2459-3469, 2005. % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Aaron Ponti, October 4th, 2002 % Sylvain Berlemont, Jan 2010 % Sebastien Besson, May 2011 (last modified Nov 2011) % Adapted from fsmPrepMainSecondarySpeckles.m ip=inputParser; ip.addRequired('I',@isnumeric); ip.addRequired('noiseParam',@isnumeric) ip.addRequired('specParam',@isnumeric); ip.addOptional('psfSigma',1,@isscalar); ip.addParamValue('userROIbw',[],@isnumeric) ip.parse(I,noiseParam,specParam,varargin{:}); userROIbw = ip.Results.userROIbw; psfSigma = ip.Results.psfSigma; IG=I; % SB: What the hell is this constant!!! SIG=1.88; % for the twice convolved image (or 1.77) % local minima Imin=locmin2d(IG,[3,3]); % Add virtual points along the cell edge to make sure there will be a % triangle in the delaunay triangulation for each local maxima (cands). If % no cell mask is provided there is no additional point. % reconstruct the mask from the original image bwMask = I ~= 0; if ~all(bwMask) % Dilate the cell mask bwMaskExt = imdilate(bwMask, strel('disk', 1)); % Compute Distance transform bwDist = bwdist(1 - bwMaskExt); % Get first outline outline = contourc(double(bwDist), [0, 0]); X = []; Y = []; iChunk = 1; while iChunk < size(outline,2) n = outline(2,iChunk); X = [X, round(outline(1,iChunk+1:5:iChunk+n))]; Y = [Y, round(outline(2,iChunk+1:5:iChunk+n))]; iChunk = iChunk + n + 1; end % add these points to Imin ind = sub2ind(size(Imin), Y, X); Imin(ind) = -1000; end % intial (filtered) image [cands,triMin,pMin] = fsmPrepConfirmSpeckles(IG,Imin,noiseParam,userROIbw); [cands(:).speckleType] = deal(1); Inew=IG; candsS=cands; HierLevel=2; while HierLevel<=specParam(1) && ... length(candsS)>(specParam(2)*length(cands)) && ... any([candsS.status]) Inew=fsmPrepSubstructMaxima(Inew,SIG,candsS); candsS = fsmPrepConfirmLoopSpeckles(Inew,noiseParam,triMin,pMin,IG,userROIbw); [candsS(:).speckleType] = deal(HierLevel); candsS=fsmPrepCheckDistance(candsS,cands,psfSigma); HierLevel=HierLevel+1; if ~isempty(candsS) cands=cat(1,cands,candsS); end end % remove repetitions because of secondary speckles apearing on the same % positions as primary (because of floating background) cands=removeSpeckleRepetitions(cands); % obtain updated IM from candstTot locMax=zeros(size(IG)); validCands = [cands(:).status] == 1; if any(validCands) validLmax = vertcat(cands(validCands).Lmax); validILmax = [cands(validCands).ILmax]; validIdx = sub2ind(size(IG), validLmax(:,1), validLmax(:,2)); locMax(validIdx) = validILmax; end function candsTot=removeSpeckleRepetitions(candsTot) % removeSpeckleRepetitions checks for repetitions amongst the lists of the primary, % secondary and tertiary speckles and removes them from the cands structure % % Sebastien Besson, June 2011 % Adapted from fsmPrepCheckInfo % Construct kd-tree candsTotPos = vertcat(candsTot.Lmax); idx=KDTreeBallQuery(candsTotPos,candsTotPos,0); % Find replicates and return if no duplicate found isReplicate = cellfun(@(x) length(x)>1,idx); if isempty(find(isReplicate,1)), return; end % Check that no two candidates are significant checkCands = find(cellfun(@(x) sum([candsTot(x).status])>1, idx(isReplicate)),1); if ~isempty(checkCands), error('unusual speckles repetition: both speckles (at the same position) are significant'); end % Identify insignificant maxima and remove them ind =([candsTot.status]==0 & [candsTot.speckleType]>1 & isReplicate'); candsTot(ind)=[]; function newCands=fsmPrepCheckDistance(newCands,oldCands,psfSigma) % fsmPrepCheckDistance uses a look-up-table to verify if a new (secondary or tertiary) speckle are not closer than % theoretically possible to a primary (for tertiary also secondary) one; if a candidate is closer - it is discarded % % SYNOPSIS newCands=fsmPrepCheckDistance(newCands,oldCands) % % INPUT newCands : cands for the new/secondary speckles % oldCands : cands for the old/primary speckles % psfSigma : standard deciation of the Gaussian psf % % OUTPUT newCands : updated cands for the new/secondary speckles % % % DEPENDENCES fsmPrepCheckDistance uses { createDistanceMatrix } % fsmPrepCheckDistance is used by { fsmPrepMainSecondarySpeckles } % % Alexandre Matov, November 7th, 2002 % Modified by Sylvain Berlemont, 2010 % Modified by Sebastien Besson, Oct 2011 % Retrieve only statistically significant speckles validIdx1 = [oldCands(:).status] == 1; validIdx2 = [newCands(:).status] == 1; if ~(any(validIdx1) && any(validIdx2)),return; end % Get positions and intensities of i-th and i+1th order speckles pos1 = vertcat(oldCands(validIdx1).Lmax); pos2 = vertcat(newCands(validIdx2).Lmax); deltaI1 = [oldCands(validIdx1).deltaI]; deltaI2 = [newCands(validIdx2).deltaI]; % Old distance criterion from fsmCenter % D=createSparseDistanceMatrix(pos2,pos1,5.21); % toBeRemoved=false(size(D,1),1); % initialization % % for i=1:size(D,1) % rowI = D(i,:); % minDistRow=find(rowI); % % if ~isempty(minDistRow) % % SB: this criteria doesn't make sense to me: % RelInt = deltaI1(minDistRow) / deltaI2(i); % r=5.2-3.5.*exp(.5-RelInt(:)); % d = nonzeros(rowI) + eps; % % toBeRemoved(i) = any(d <= r); % end % end % Classify secondary speckles by their distance to the primary speckles rmax = 4*psfSigma; idx1= KDTreeBallQuery(pos1,pos2,2*psfSigma); [idx2 D2]= KDTreeBallQuery(pos1,pos2,rmax); % Intialize logical array for removing speckles r=false(sum(validIdx2),1); % Remove all points closer than 2*psfSigma to any existing speckle r(~cellfun(@isempty,idx1))=true; % Apply generalized Sparrow criterion to all speckles which distance is % between 2 psfSigma and 4 psfSigma of an existing speckle % See A. Ponti et al. 2005 (supplementary material) w = @(r) sqrt(r.^2-4*psfSigma^2); Acrit = @(r) (r-w(r))./(r+w(r)).*exp(w(r).*r/(2*psfSigma.^2)); A = @(x) deltaI1(idx2{x}) / deltaI2(x); applyGSC = @(x) all(A(x)<=Acrit(D2{x})'); for i=find(~cellfun(@isempty,idx2) & cellfun(@isempty,idx1))' r(i)=~applyGSC(i); end % Remove invalid speckles if any(r) ind2 = find(validIdx2); newCands(ind2(r)) = []; end function [cands,triMin,pMin]=fsmPrepConfirmSpeckles(IG,Imin,noiseParam,userROIbw) % fsmPrepConfirmSpeckles uses statistical tests to confirm the significance % of detected speckles % % SYNOPSIS [cands,triMin,pMin]=fsmPrepConfirmSpeckles(IG,Imin,noiseParam) % % INPUT IG : filtered image % Imin : local minima % noiseParam : noise parameters for statistical speckle selection % userROIbw : (optional) User-defined black-and-white mask to select speckles % % OUTPUT cands : cands structure (see fsmPrepTestLocalMaxima.m) % triMin : set of Delaunay triangles % pMin : attached dSet (vertex coordinates) to lMin % % % % DEPENDENCES fsmPrepConfirmSpeckles uses { fsmPrepBkgEstimationDelaunay, fsmPrepTestLocalMaxima, locmax2d } % fsmPrepConfirmSpeckles is used by { fsmPrepMainSecondarySpeckles } % % Alexandre Matov, November 7th, 2002 % Sylvain Berlemont, Jan 2010 % Find the local maxima Imax=locmax2d(IG,[5,5]); if nargin == 4 && ~isempty(userROIbw) Imax=Imax.*userROIbw; end % Finds 3 loc min around each loc max [cands,triMin,pMin]=fsmPrepBkgEstimationDelaunay(Imax,Imin); % analyze speckles - validate, locmax, locmin... cands = fsmPrepTestLocalMaxima(IG,cands,noiseParam,IG); function cands=fsmPrepConfirmLoopSpeckles(Inew,noiseParam,triMin,pMin,IG,userROIbw) % fsmPrepConfirmLoopSpeckles uses statistical tests to confirm the significance of detected speckles % of higher than one hierarchical level (in the main loop) % % SYNOPSIS cands=fsmPrepConfirmLoopSpeckles(Inew,noiseParam,triMin,pMin,IG) % % INPUT Inew : substracted image % noiseParam : noise parameters for statistical speckle selection % triMin : set of Delaunay triangles % pMin : attached dSet (vertex coordinates) to lMin % IG : original (filtered) image % % OUTPUT cands : cands structure (see fsmPrepTestLocalMaxima.m) % % % % DEPENDENCES fsmPrepConfirmLoopSpeckles uses { locmax2d, tsearch,fsmPrepTestLocalMaxima } % fsmPrepConfirmLoopSpeckles is used by { fsmPrepMainSecondarySpeckles } % % Alexandre Matov, April 2nd, 2003 % Sylvain Berlemont, Jan 2010 % find the local maxima Imax=locmax2d(Inew,[5,5]); if nargin == 6 && ~isempty(userROIbw) % Mask Imax Imax=Imax.*userROIbw; end % find the coordinates/positions of the initial local maxima before % significance test (for comparision) [yi,xi]=find(ne(Imax,0)); pMax=[yi,xi]; % Assign local maxima to local minimum triangles % triangles=tsearch(pMin(:,1),pMin(:,2),triMin,pMax(:,1),pMax(:,2)); triangles = triMin.pointLocation(pMax); % Store information into cands structure validTri = 1:numel(triangles); validTri = validTri(~isnan(triangles)); n = ones(numel(validTri), 1); cands = struct(... 'Lmax', mat2cell(pMax(validTri,:), n), ... 'Bkg1', mat2cell(pMin(triMin(triangles(validTri),1),:), n),... 'Bkg2', mat2cell(pMin(triMin(triangles(validTri),2),:), n),... 'Bkg3', mat2cell(pMin(triMin(triangles(validTri),3),:), n)); % analyze speckles - validate, locmax, locmin... cands = fsmPrepTestLocalMaxima(Inew,cands,noiseParam,IG); function [Inew,Imaxima]=fsmPrepSubstructMaxima(IG,SIG,cands) % fsmPrepSubstructMaxima takes the filtered image IG and substracts Gaussian % kernels at the positions of the local maxima % % % SYNOPSIS Inew=fsmPrepSubstructMaxima(IG,Imax,SIG,cands) % % INPUT IG : filtered image % SIG : sigma of the GKs % cands : cands strucure % % OUTPUT Inew : the resulting image after substaction % Imaxima : the synthetic image to be substracted from the % real % % Alexandre Matov, November 7th, 2002 % Modified by Sylvain Berlemont, 2010 Imax=zeros(size(IG)); % prepearing Imax for substraction validCands = ([cands(:).status] == 1) & ([cands(:).deltaI] > 0); if any(validCands) validLmax = vertcat(cands(validCands).Lmax); validDeltaI = [cands(validCands).deltaI]; validIdx = sub2ind(size(IG), validLmax(:,1), validLmax(:,2)); Imax(validIdx) = validDeltaI; end % the masked with a GK local maxima points with intensity delta.I for the % raw data image. Imaxima=filterGauss2D(Imax,SIG); % substruction Inew=IG-Imaxima; % In case Imaxima has value outside the cell footprint (IG is masked) due % to the filtering step, Inew may have negative value outside the cell % footprint. Make sure the cell mask is also applied on Inew. Inew(IG == 0) = 0; function [cands,triMin,pMin]=fsmPrepBkgEstimationDelaunay(lMax,lMin) % fsmPrepBkgEstimationDelaunay uses Delaunay triangulation to assign 3 local minima to every local maximum % % SYNOPSIS [cands,triMin,pMin]=fsmPrepBkgEstimationDelaunay(lMax,lMin) % % INPUT lMax : local max map (the output of the locMax2D function) % lMin : local min max (the output of the locMin2D function) % % OUTPUT triMin : Delaunay triangulation % pMin : attached dSet (vertex coordinates) to lMin % cands : structure containing statistical information for each local maximum % (see help for detail) - fsmPrepBkgEstimationDelaunay only stores % local maximum and local minimum coordinates % % DEPENDENCES % % Aaron Ponti, October 23th, 2002 % Sylvain Berlemont, Jan 2010 % Sebastien Besson, May 2011 % Collect lMax coordinates into matrics [y x]=find(lMax); pMax=[y x]; if isempty(pMax), return; end % Collect lMin coordinates into matrices [y x]=find(lMin); pMin=[y x]; % Delaunay triangulation triMin=DelaunayTri(pMin); triangles = triMin.pointLocation(pMax); % Store information validTri = 1:numel(triangles); validTri = validTri(~isnan(triangles)); n = ones(numel(validTri), 1); cands = struct(... 'Lmax', mat2cell(pMax(validTri,:), n), ... 'Bkg1', mat2cell(pMin(triMin(triangles(validTri),1),:), n),... 'Bkg2', mat2cell(pMin(triMin(triangles(validTri),2),:), n),... 'Bkg3', mat2cell(pMin(triMin(triangles(validTri),3),:), n)); function cands = fsmPrepTestLocalMaxima(img,cands,parameters,imgO) % fspPrepTestLocalMaxima selects statistically significant local maxima using loc max and background info from analyzeSpeckles % % SYNOPSIS cands=fsmPrepTestLocalMaxima(img,cands,parameters) % % INPUT img : image matrix % cands : Imax and Imin for every speckles obtained % from analyzeSpeckles (Delaunay triangulation) % parameters : [k sigmaD PoissonNoise I0] % k : gives the confidence interval Xavg+/-k*sigma % for normally distributed data % sigmaD, PoissonNoise, I0 : from the noise % calibration model % sigma=sqrt(sigmaD^2+PoissonNoise*(I-I0)) % I0 : mean intensity of the background images % imgO : the original (filtered) image % % OUTPUT cands : cands (input) augmented by additional (statistical) information % % cands.Lmax : Local maximum position - [y x] % .Bkg1 : First local minimum position - [y x] % .Bkg2 : Second local minimum position - [y x] % .Bkg3 : Third local minimum position - [y x] % .ILmax : Local maximum intensity % .IBkg : Mean background intensity % .deltaI : Intensity difference: ILmax-IBkg % .deltaICrit : Critical intensity difference as calculated with the noise model % .sigmaLmax : Error on local maximum intensity % .sigmaBkg : Error on background intensity % .status : Significance of the local maximum: 1, speckle; 0, weak local maximum % % Aaron Ponti, October 4th, 2002 % Sylvain Berlemont, Jan 2010 % Sebastien Besson, Aug 2011 % Parameters k=parameters(1); sigmaD=parameters(2); PoissonNoise=parameters(3); I0=parameters(4); Lmax = vertcat(cands(:).Lmax); Bkg1 = vertcat(cands(:).Bkg1); Bkg2 = vertcat(cands(:).Bkg2); Bkg3 = vertcat(cands(:).Bkg3); indLmax = sub2ind(size(img), Lmax(:, 1), Lmax(:, 2)); indBkg1 = sub2ind(size(img), Bkg1(:, 1), Bkg1(:, 2)); indBkg2 = sub2ind(size(img), Bkg2(:, 1), Bkg2(:, 2)); indBkg3 = sub2ind(size(img), Bkg3(:, 1), Bkg3(:, 2)); % Calculate difference Imax-Imin for every speckle for c1=1:length(cands) % Read values for Imax and Imin from the image at the coordinates % specified by info Imax = img(indLmax(c1)); % imgO is the original filtered image Imin = mean(nonzeros([imgO(indBkg1(c1)), imgO(indBkg2(c1)), imgO(indBkg3(c1))])); [Imin,deltaI,k,sigmaDiff,sigmaMax,sigmaMin,status]=... testSpeckleSignificance(Imax,Imin,k,sigmaD,PoissonNoise,I0); % Complete cands cands(c1).ILmax=Imax; % Local maximum intensity cands(c1).IBkg=Imin; % Mean background intensity cands(c1).deltaI=deltaI; % Intensity difference: ILmax-IBkg cands(c1).deltaICrit=k*sigmaDiff; % Critical intensity difference as calculated with the noise model cands(c1).sigmaLmax=sigmaMax; % Error on local maximum intensity cands(c1).sigmaBkg=sigmaMin; % Error on background intensity cands(c1).status=status; % Significance of the local maximum: 1, speckle; 0, weak local maximum end % Filter out cands with no local background cands(isnan([cands.IBkg]))=[];
github
mehta-lab/Instantaneous-PolScope-master
movieViewer.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/movieViewer.m
45,341
utf_8
32495b017b0dc3a8c372e825f97f74e2
function mainFig = movieViewer(MO,varargin) ip = inputParser; ip.addRequired('MO',@(x) isa(x,'MovieObject')); ip.addOptional('procId',[],@isnumeric); ip.addParamValue('movieIndex',0,@isscalar); ip.parse(MO,varargin{:}); % Check existence of viewer % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % h=findobj(0,'Name','Viewer'); if ~isempty(h), delete(h); end mainFig=figure('Name','Viewer','Position',[0 0 200 200],... 'NumberTitle','off','Tag','figure1','Toolbar','none','MenuBar','none',... 'Color',get(0,'defaultUicontrolBackgroundColor'),'Resize','off',... 'DeleteFcn', @(h,event) deleteViewer()); userData=get(mainFig,'UserData'); if isa(ip.Results.MO,'MovieList') userData.ML=ip.Results.MO; userData.movieIndex=ip.Results.movieIndex; if userData.movieIndex~=0 userData.MO=ip.Results.MO.getMovies{userData.movieIndex}; else userData.MO=ip.Results.MO; end userData.procId = ip.Results.procId; if ~isempty(ip.Results.procId) procId = userData.MO.getProcessIndex(class(userData.ML.processes_{ip.Results.procId})); else procId = ip.Results.procId; end else userData.MO=ip.Results.MO; % userData.MO=ip.Results.MO; procId=ip.Results.procId; end % Classify movieData processes by type (image, overlay, movie overlay or % graph) validProcId= find(cellfun(@(x) ismember('getDrawableOutput',methods(x)) &... x.success_,userData.MO.processes_)); validProc=userData.MO.processes_(validProcId); getOutputType = @(type) cellfun(@(x) any(~cellfun(@isempty,regexp({x.getDrawableOutput.type},type,'once','start'))),... validProc); isImageProc =getOutputType('image'); imageProc=validProc(isImageProc); imageProcId = validProcId(isImageProc); isOverlayProc =getOutputType('[oO]verlay'); overlayProc=validProc(isOverlayProc); overlayProcId = validProcId(isOverlayProc); isGraphProc =getOutputType('[gG]raph'); graphProc=validProc(isGraphProc); graphProcId = validProcId(isGraphProc); % Create series of anonymous function to generate process controls createProcText= @(panel,i,j,pos,name) uicontrol(panel,'Style','text',... 'Position',[10 pos 250 20],'Tag',['text_process' num2str(i)],... 'String',name,'HorizontalAlignment','left','FontWeight','bold'); createOutputText= @(panel,i,j,pos,text) uicontrol(panel,'Style','text',... 'Position',[40 pos 200 20],'Tag',['text_process' num2str(i) '_output'... num2str(j)],'String',text,'HorizontalAlignment','left'); createProcButton= @(panel,i,j,k,pos) uicontrol(panel,'Style','radio',... 'Position',[200+30*k pos 20 20],'Tag',['radiobutton_process' num2str(i) '_output'... num2str(j) '_channel' num2str(k)]); createChannelBox= @(panel,i,j,k,pos,varargin) uicontrol(panel,'Style','checkbox',... 'Position',[200+30*k pos 20 20],'Tag',['checkbox_process' num2str(i) '_output'... num2str(j) '_channel' num2str(k)],varargin{:}); createMovieBox= @(panel,i,j,pos,name,varargin) uicontrol(panel,'Style','checkbox',... 'Position',[40 pos 200 25],'Tag',['checkbox_process' num2str(i) '_output'... num2str(j)],'String',[' ' name],varargin{:}); createInputBox= @(panel,i,j,k,pos,name,varargin) uicontrol(panel,'Style','checkbox',... 'Position',[40 pos 200 25],'Tag',['checkbox_process' num2str(i) '_output'... num2str(j) '_input' num2str(k)],'String',[' ' name],varargin{:}); createInputInputBox= @(panel,i,j,k,l,pos,varargin) uicontrol(panel,'Style','checkbox',... 'Position',[200+30*l pos 20 20],'Tag',['checkbox_process' num2str(i) '_output'... num2str(j) '_input' num2str(k) '_input' num2str(l)],varargin{:}); panel1 = uipanel('Parent',mainFig,'BorderType','none'); panel2 = uipanel('Parent',panel1,'BorderType','none'); s=uicontrol('Style','Slider','Parent',mainFig,... 'Units','normalized','Position',[0.95 0 0.05 1],... 'Value',1,'SliderStep',[.02,.2],'Callback',{@slider_callback,panel2}); %% Image panel creation if isa(userData.MO,'MovieData') imagePanel = uibuttongroup(panel2,'Position',[0 0 1/2 1],... 'Title','Image','BackgroundColor',get(0,'defaultUicontrolBackgroundColor'),... 'Units','pixels','Tag','uipanel_image'); hPosition=createImageOptions(imagePanel,userData); % Create controls for switching between process image output hPosition=hPosition+50; nProc = numel(imageProc); for iProc=nProc:-1:1; output=imageProc{iProc}.getDrawableOutput; validChan = imageProc{iProc}.checkChannelOutput; validOutput = find(strcmp({output.type},'image')); for iOutput=validOutput(end:-1:1) createOutputText(imagePanel,imageProcId(iProc),iOutput,hPosition,output(iOutput).name); arrayfun(@(x) createProcButton(imagePanel,imageProcId(iProc),iOutput,x,hPosition),... find(validChan)); hPosition=hPosition+20; end createProcText(imagePanel,imageProcId(iProc),iOutput,hPosition,imageProc{iProc}.getName); hPosition=hPosition+20; end % Create controls for selecting channels (raw image) hPosition=hPosition+10; uicontrol(imagePanel,'Style','radio','Position',[10 hPosition 200 20],... 'Tag','radiobutton_channels','String',' Raw image','Value',1,... 'HorizontalAlignment','left','FontWeight','bold'); arrayfun(@(i) uicontrol(imagePanel,'Style','checkbox',... 'Position',[200+30*i hPosition 20 20],... 'Tag',['checkbox_channel' num2str(i)],'Value',i<4,... 'Callback',@(h,event) redrawChannel(h,guidata(h))),... 1:numel(userData.MO.channels_)); hPosition=hPosition+20; uicontrol(imagePanel,'Style','text','Position',[120 hPosition 100 20],... 'Tag','text_channels','String','Channels'); arrayfun(@(i) uicontrol(imagePanel,'Style','text',... 'Position',[200+30*i hPosition 20 20],... 'Tag',['text_channel' num2str(i)],'String',i),... 1:numel(userData.MO.channels_)); else imagePanel=-1; end %% Overlay panel creation if ~isempty(overlayProc) overlayPanel = uipanel(panel2,'Position',[1/2 0 1/2 1],... 'Title','Overlay','BackgroundColor',get(0,'defaultUicontrolBackgroundColor'),... 'Units','pixels','Tag','uipanel_overlay'); % Create overlay options hPosition=10; hPosition=createVectorFieldOptions(overlayPanel,userData,hPosition); hPosition=createTrackOptions(overlayPanel,userData,hPosition); hPosition=createWindowsOptions(overlayPanel,userData,hPosition); % Create controls for selecting overlays hPosition=hPosition+50; nProc = numel(overlayProc); for iProc=nProc:-1:1; output=overlayProc{iProc}.getDrawableOutput; % Create checkboxes for movie overlays validOutput = find(strcmp({output.type},'movieOverlay')); for iOutput=validOutput(end:-1:1) createMovieBox(overlayPanel,overlayProcId(iProc),iOutput,hPosition,output(iOutput).name,... 'Callback',@(h,event) redrawOverlay(h,guidata(h))); hPosition=hPosition+20; end % Create checkboxes for channel-specific overlays validOutput = find(strcmp({output.type},'overlay')); for iOutput=validOutput(end:-1:1) validChan = overlayProc{iProc}.checkChannelOutput; createOutputText(overlayPanel,overlayProcId(iProc),iOutput,hPosition,output(iOutput).name); arrayfun(@(x) createChannelBox(overlayPanel,overlayProcId(iProc),iOutput,x,hPosition,... 'Callback',@(h,event) redrawOverlay(h,guidata(h))),find(validChan)); hPosition=hPosition+20; end createProcText(overlayPanel,overlayProcId(iProc),iOutput,hPosition,overlayProc{iProc}.getName); hPosition=hPosition+20; end if ~isempty(overlayProc) uicontrol(overlayPanel,'Style','text','Position',[120 hPosition 100 20],... 'Tag','text_channels','String','Channels'); arrayfun(@(i) uicontrol(overlayPanel,'Style','text',... 'Position',[200+30*i hPosition 20 20],... 'Tag',['text_channel' num2str(i)],'String',i),... 1:numel(userData.MO.channels_)); end else overlayPanel=-1; end %% Add additional panel for independent graphs if ~isempty(graphProc) graphPanel = uipanel(panel2,'Position',[0 0 1 1],... 'Title','Graph','BackgroundColor',get(0,'defaultUicontrolBackgroundColor'),... 'Units','pixels','Tag','uipanel_graph'); hPosition3=10; hPosition3 = createScalarMapOptions(graphPanel,userData,hPosition3); hPosition3=hPosition3+50; % Create controls for selecting all other graphs nProc = numel(graphProc); for iProc=nProc:-1:1; output=graphProc{iProc}.getDrawableOutput; if isa(graphProc{iProc},'SignalProcessingProcess'); input=graphProc{iProc}.getInput; nInput=numel(input); % Create set of boxes for correlation graphs (input/input) validOutput = graphProc{iProc}.checkOutput; for iOutput=size(validOutput,3):-1:1 for iInput=nInput:-1:1 createOutputText(graphPanel,graphProcId(iProc),iInput,hPosition3,input(iInput).name); for jInput=1:iInput if validOutput(iInput,jInput,iOutput) createInputInputBox(graphPanel,graphProcId(iProc),iOutput,iInput,jInput,hPosition3,... 'Callback',@(h,event) redrawSignalGraph(h,guidata(h))); end end hPosition3=hPosition3+20; end createProcText(graphPanel,graphProcId(iProc),iInput,hPosition3,output(iOutput).name); hPosition3=hPosition3+20; end else % Create boxes for movie -specific graphs validOutput = find(strcmp({output.type},'movieGraph')); for iOutput=validOutput(end:-1:1) createMovieBox(graphPanel,graphProcId(iProc),iOutput,hPosition3,... output(iOutput).name,'Callback',@(h,event) redrawGraph(h,guidata(h))); hPosition3=hPosition3+20; end % Create boxes for channel-specific graphs validOutput = find(strcmp({output.type},'graph')); for iOutput=validOutput(end:-1:1) validChan = graphProc{iProc}.checkChannelOutput(); createOutputText(graphPanel,graphProcId(iProc),iOutput,hPosition3,output(iOutput).name); arrayfun(@(x) createChannelBox(graphPanel,graphProcId(iProc),iOutput,x,hPosition3,... 'Callback',@(h,event) redrawGraph(h,guidata(h))),find(validChan)); hPosition3=hPosition3+20; end % Create boxes for sampled graphs validOutput = find(strcmp({output.type},'sampledGraph')); for iOutput=validOutput(end:-1:1) validChan = graphProc{iProc}.checkChannelOutput(); createOutputText(graphPanel,graphProcId(iProc),iOutput,hPosition3,output(iOutput).name); arrayfun(@(x) createChannelBox(graphPanel,graphProcId(iProc),iOutput,x,hPosition3,... 'Callback',@(h,event) redrawGraph(h,guidata(h))),find(validChan(iOutput,:))); hPosition3=hPosition3+20; end % Create boxes for sampled graphs validOutput = find(strcmp({output.type},'signalGraph')); for iOutput=validOutput(end:-1:1) input=graphProc{iProc}.getInput; validInput = find(graphProc{iProc}.checkOutput()); % createOutputText(graphPanel,graphProcId(iProc),iOutput,hPosition3,output(iOutput).name); for iInput=fliplr(validInput) createInputBox(graphPanel,graphProcId(iProc),iOutput,iInput,hPosition3,... input(iInput).name,'Callback',@(h,event) redrawGraph(h,guidata(h))); hPosition3=hPosition3+20; end end createProcText(graphPanel,graphProcId(iProc),iOutput,hPosition3,graphProc{iProc}.getName); hPosition3=hPosition3+20; end end if ~isempty(graphProc) && isa(userData.MO,'MovieData') uicontrol(graphPanel,'Style','text','Position',[120 hPosition3 100 20],... 'Tag','text_channels','String','Channels'); arrayfun(@(i) uicontrol(graphPanel,'Style','text',... 'Position',[200+30*i hPosition3 20 20],... 'Tag',['text_channel' num2str(i)],'String',i),... 1:numel(userData.MO.channels_)); end else graphPanel=-1; end %% Get image/overlay panel size and resize them imagePanelSize = getPanelSize(imagePanel); overlayPanelSize = getPanelSize(overlayPanel); graphPanelSize = getPanelSize(graphPanel); panelsLength = max(500,imagePanelSize(1)+overlayPanelSize(1)+graphPanelSize(1)); panelsHeight = max([imagePanelSize(2),overlayPanelSize(2),graphPanelSize(2)]); % Resize panel if ishandle(imagePanel) set(imagePanel,'Position',[10 panelsHeight-imagePanelSize(2)+10 ... imagePanelSize(1) imagePanelSize(2)],... 'SelectionChangeFcn',@(h,event) redrawImage(guidata(h))) end if ishandle(overlayPanel) set(overlayPanel,'Position',[imagePanelSize(1)+10 panelsHeight-overlayPanelSize(2)+10 ... overlayPanelSize(1) overlayPanelSize(2)]); end if ishandle(graphPanel) set(graphPanel,'Position',[imagePanelSize(1)+overlayPanelSize(1)+10 ... panelsHeight-graphPanelSize(2)+10 ... graphPanelSize(1) graphPanelSize(2)]) end %% Create movie panel moviePanel = uipanel(panel2,... 'Title','','BackgroundColor',get(0,'defaultUicontrolBackgroundColor'),... 'Units','pixels','Tag','uipanel_movie','BorderType','none'); hPosition=10; if isa(userData.MO,'MovieData') % Create control button for exporting figures and movie (cf Francois' GUI) uicontrol(moviePanel, 'Style', 'togglebutton','String', 'Run movie',... 'Position', [10 hPosition 100 20],'Callback',@(h,event) runMovie(h,guidata(h))); uicontrol(moviePanel, 'Style', 'checkbox','Tag','checkbox_saveFrames',... 'Value',0,'String', 'Save frames','Position', [150 hPosition 100 20]); uicontrol(moviePanel, 'Style', 'checkbox','Tag','checkbox_saveMovie',... 'Value',0,'String', 'Save movie','Position', [250 hPosition 100 20]); uicontrol(moviePanel, 'Style', 'popupmenu','Tag','popupmenu_movieFormat',... 'Value',1,'String', {'MOV';'AVI'},'Position', [350 hPosition 100 20]); % Create controls for scrollling through the movie hPosition = hPosition+30; uicontrol(moviePanel,'Style','text','Position',[10 hPosition 50 15],... 'String','Frame','Tag','text_frame','HorizontalAlignment','left'); uicontrol(moviePanel,'Style','edit','Position',[70 hPosition 30 20],... 'String','1','Tag','edit_frame','BackgroundColor','white',... 'HorizontalAlignment','left',... 'Callback',@(h,event) redrawScene(h,guidata(h))); uicontrol(moviePanel,'Style','text','Position',[100 hPosition 40 15],... 'HorizontalAlignment','left',... 'String',['/' num2str(userData.MO.nFrames_)],'Tag','text_frameMax'); uicontrol(moviePanel,'Style','slider',... 'Position',[150 hPosition panelsLength-160 20],... 'Value',1,'Min',1,'Max',userData.MO.nFrames_,... 'SliderStep',[1/double(userData.MO.nFrames_) 5/double(userData.MO.nFrames_)],... 'Tag','slider_frame','BackgroundColor','white',... 'Callback',@(h,event) redrawScene(h,guidata(h))); end % Create movie location edit box hPosition = hPosition+30; uicontrol(moviePanel,'Style','text','Position',[10 hPosition 40 20],... 'String','Movie','Tag','text_movie'); if isa(ip.Results.MO,'MovieList') moviePaths = cellfun(@getDisplayPath,userData.ML.getMovies,'UniformOutput',false); movieIndex=0:numel(moviePaths); uicontrol(moviePanel,'Style','popupmenu','Position',[60 hPosition panelsLength-110 20],... 'String',vertcat(getDisplayPath(ip.Results.MO),moviePaths'),'UserData',movieIndex,... 'Value',find(userData.movieIndex==movieIndex),... 'HorizontalAlignment','left','BackgroundColor','white','Tag','popup_movie',... 'Callback',@(h,event) switchMovie(h,guidata(h))); if userData.movieIndex==0, set(findobj(moviePanel,'Tag','text_movie'),'String','List'); end else uicontrol(moviePanel,'Style','edit','Position',[60 hPosition panelsLength-110 20],... 'String',getDisplayPath(ip.Results.MO),... 'HorizontalAlignment','left','BackgroundColor','white','Tag','edit_movie'); end % Add help button hAxes = axes('Units','pixels','Position',[panelsLength-50 hPosition 48 48],... 'Tag','axes_help', 'Parent', moviePanel); icons = loadLCCBIcons(); Img = image(icons.questIconData); set(hAxes, 'XLim',get(Img,'XData'),'YLim',get(Img,'YData'), 'visible','off','YDir','reverse'); set(Img,'ButtonDownFcn',@icon_ButtonDownFcn, 'UserData', struct('class','movieViewer')); % Add copyrigth hPosition = hPosition+30; uicontrol(moviePanel,'Style','text','Position',[10 hPosition panelsLength-100 20],... 'String',userfcn_softwareConfig(),'Tag','text_copyright',... 'HorizontalAlignment','left'); % Get overlay panel size moviePanelSize = getPanelSize(moviePanel); moviePanelHeight =moviePanelSize(2); %% Resize panels and figure sz=get(0,'ScreenSize'); maxWidth = panelsLength+20; maxHeight = panelsHeight+moviePanelHeight; figWidth = min(maxWidth,.75*sz(3)); figHeight=min(maxHeight,.75*sz(4)); set(mainFig,'Position',[sz(3)/50 (sz(4)-maxHeight)/2 figWidth+20 figHeight]); set(panel1,'Units','Pixels','Position',[0 0 figWidth figHeight]); panelRatio=maxHeight/figHeight; set(moviePanel,'Position',[10 panelsHeight+10 panelsLength moviePanelHeight]); set(panel2,'Position',[0 1-panelRatio 1 panelRatio]); if panelRatio==1, set(s,'Enable','off'); end % Update handles structure and attach it to the main figure handles = guihandles(mainFig); guidata(handles.figure1, handles); set(handles.figure1,'UserData',userData); %% Set up default parameters % Auto check input process for i=intersect(procId,validProcId) h=findobj(mainFig,'-regexp','Tag',['(\w)_process' num2str(i) '_output1.*'],... '-not','Style','text'); set(h,'Value',1); for j=find(arrayfun(@(x)isequal(get(x,'Parent'),graphPanel),h))' callbackFcn = get(h(j),'Callback'); callbackFcn(h(j),[]); end end % Update the image and overlays if isa(userData.MO,'MovieData'), redrawScene(handles.figure1, handles); end function hPosition=createImageOptions(imagePanel,userData) % First create image option (timestamp, scalebar, image scaling) % Timestamp hPosition=10; if isempty(userData.MO.timeInterval_), timeStampStatus = 'off'; else timeStampStatus = 'on'; end uicontrol(imagePanel,'Style','checkbox',... 'Position',[10 hPosition 200 20],'Tag','checkbox_timeStamp',... 'String',' Time stamp','HorizontalAlignment','left',... 'Enable',timeStampStatus,'Callback',@(h,event) setTimeStamp(guidata(h))); uicontrol(imagePanel,'Style','popupmenu','Position',[130 hPosition 120 20],... 'String',{'NorthEast', 'SouthEast', 'SouthWest', 'NorthWest'},'Value',4,... 'Tag','popupmenu_timeStampLocation','Enable',timeStampStatus,... 'Callback',@(h,event) setTimeStamp(guidata(h))); % Scalebar hPosition=hPosition+30; if isempty(userData.MO.pixelSize_), scBarstatus = 'off'; else scBarstatus = 'on'; end uicontrol(imagePanel,'Style','edit','Position',[30 hPosition 50 20],... 'String','1','BackgroundColor','white','Tag','edit_imageScaleBar',... 'Enable',scBarstatus,... 'Callback',@(h,event) setScaleBar(guidata(h),'imageScaleBar')); uicontrol(imagePanel,'Style','text','Position',[85 hPosition-2 70 20],... 'String','microns','HorizontalAlignment','left'); uicontrol(imagePanel,'Style','checkbox',... 'Position',[150 hPosition 100 20],'Tag','checkbox_imageScaleBarLabel',... 'String',' Show label','HorizontalAlignment','left',... 'Enable',scBarstatus,... 'Callback',@(h,event) setScaleBar(guidata(h),'imageScaleBar')); hPosition=hPosition+30; uicontrol(imagePanel,'Style','checkbox',... 'Position',[10 hPosition 200 20],'Tag','checkbox_imageScaleBar',... 'String',' Scalebar','HorizontalAlignment','left',... 'Enable',scBarstatus,... 'Callback',@(h,event) setScaleBar(guidata(h),'imageScaleBar')); uicontrol(imagePanel,'Style','popupmenu','Position',[130 hPosition 120 20],... 'String',{'NorthEast', 'SouthEast', 'SouthWest', 'NorthWest'},'Value',3,... 'Tag','popupmenu_imageScaleBarLocation','Enable',scBarstatus,... 'Callback',@(h,event) setScaleBar(guidata(h),'imageScaleBar')); hPosition=hPosition+30; uicontrol(imagePanel,'Style','text',... 'Position',[20 hPosition 100 20],'Tag','text_imageScaleFactor',... 'String',' Scaling factor','HorizontalAlignment','left'); uicontrol(imagePanel,'Style','edit','Position',[120 hPosition 50 20],... 'String','1','BackgroundColor','white','Tag','edit_imageScaleFactor',... 'Callback',@(h,event) setScaleFactor(guidata(h))); % Colormap control hPosition=hPosition+30; uicontrol(imagePanel,'Style','text','Position',[20 hPosition-2 100 20],... 'String','Color limits','HorizontalAlignment','left'); uicontrol(imagePanel,'Style','edit','Position',[150 hPosition 50 20],... 'String','','BackgroundColor','white','Tag','edit_cmin',... 'Callback',@(h,event) setCLim(guidata(h))); uicontrol(imagePanel,'Style','edit','Position',[200 hPosition 50 20],... 'String','','BackgroundColor','white','Tag','edit_cmax',... 'Callback',@(h,event) setCLim(guidata(h))); hPosition=hPosition+30; uicontrol(imagePanel,'Style','text','Position',[20 hPosition-2 80 20],... 'String','Colormap','HorizontalAlignment','left'); uicontrol(imagePanel,'Style','popupmenu',... 'Position',[130 hPosition 120 20],'Tag','popupmenu_colormap',... 'String',{'Gray','Jet','HSV','Custom'},'Value',1,... 'HorizontalAlignment','left','Callback',@(h,event) setColormap(guidata(h))); % Colorbar hPosition=hPosition+30; uicontrol(imagePanel,'Style','checkbox',... 'Position',[10 hPosition 120 20],'Tag','checkbox_colorbar',... 'String',' Colorbar','HorizontalAlignment','left',... 'Callback',@(h,event) setColorbar(guidata(h))); findclass(findpackage('scribe'),'colorbar'); locations = findtype('ColorbarLocationPreset'); locations = locations.Strings; uicontrol(imagePanel,'Style','popupmenu','String',locations,... 'Position',[130 hPosition 120 20],'Tag','popupmenu_colorbarLocation',... 'HorizontalAlignment','left','Callback',@(h,event) setColorbar(guidata(h))); hPosition=hPosition+20; uicontrol(imagePanel,'Style','text','Position',[10 hPosition 200 20],... 'String','Image options','HorizontalAlignment','left','FontWeight','bold'); function hPosition=createVectorFieldOptions(overlayPanel,userData,hPosition) % First create overlay option (vectorField) if isempty(userData.MO.pixelSize_) || isempty(userData.MO.timeInterval_), scaleBarStatus = 'off'; else scaleBarStatus = 'on'; end uicontrol(overlayPanel,'Style','text','Position',[20 hPosition-2 100 20],... 'String','Color limits','HorizontalAlignment','left'); uicontrol(overlayPanel,'Style','edit','Position',[150 hPosition 50 20],... 'String','','BackgroundColor','white','Tag','edit_vectorCmin',... 'Callback',@(h,event) redrawOverlays(guidata(h))); uicontrol(overlayPanel,'Style','edit','Position',[200 hPosition 50 20],... 'String','','BackgroundColor','white','Tag','edit_vectorCmax',... 'Callback',@(h,event) redrawOverlays(guidata(h))); hPosition=hPosition+30; uicontrol(overlayPanel,'Style','edit','Position',[30 hPosition 50 20],... 'String','1000','BackgroundColor','white','Tag','edit_vectorFieldScaleBar',... 'Enable',scaleBarStatus,... 'Callback',@(h,event) setScaleBar(guidata(h),'vectorFieldScaleBar')); uicontrol(overlayPanel,'Style','text','Position',[85 hPosition-2 70 20],... 'String','nm/min','HorizontalAlignment','left'); uicontrol(overlayPanel,'Style','checkbox',... 'Position',[150 hPosition 100 20],'Tag','checkbox_vectorFieldScaleBarLabel',... 'String',' Show label','HorizontalAlignment','left',... 'Enable',scaleBarStatus,... 'Callback',@(h,event) setScaleBar(guidata(h),'vectorFieldScaleBar')); hPosition=hPosition+30; uicontrol(overlayPanel,'Style','checkbox',... 'Position',[20 hPosition 100 20],'Tag','checkbox_vectorFieldScaleBar',... 'String',' Scalebar','HorizontalAlignment','left',... 'Enable',scaleBarStatus,... 'Callback',@(h,event) setScaleBar(guidata(h),'vectorFieldScaleBar')); uicontrol(overlayPanel,'Style','popupmenu','Position',[130 hPosition 120 20],... 'String',{'NorthEast', 'SouthEast', 'SouthWest', 'NorthWest'},'Value',3,... 'Tag','popupmenu_vectorFieldScaleBarLocation','Enable',scaleBarStatus,... 'Callback',@(h,event) setScaleBar(guidata(h),'vectorFieldScaleBar')); hPosition=hPosition+30; uicontrol(overlayPanel,'Style','text',... 'Position',[20 hPosition 100 20],'Tag','text_vectorFieldScale',... 'String',' Display scale','HorizontalAlignment','left'); uicontrol(overlayPanel,'Style','edit','Position',[120 hPosition 50 20],... 'String','1','BackgroundColor','white','Tag','edit_vectorFieldScale',... 'Callback',@(h,event) redrawOverlays(guidata(h))); hPosition=hPosition+20; uicontrol(overlayPanel,'Style','text',... 'Position',[10 hPosition 200 20],'Tag','text_vectorFieldOptions',... 'String','Vector field options','HorizontalAlignment','left','FontWeight','bold'); function hPosition=createTrackOptions(overlayPanel,userData,hPosition) hPosition=hPosition+30; uicontrol(overlayPanel,'Style','text',... 'Position',[20 hPosition 100 20],'Tag','text_dragtailLength',... 'String',' Dragtail length','HorizontalAlignment','left'); uicontrol(overlayPanel,'Style','edit','Position',[120 hPosition 50 20],... 'String','10','BackgroundColor','white','Tag','edit_dragtailLength',... 'Callback',@(h,event) redrawOverlays(guidata(h))); hPosition=hPosition+20; uicontrol(overlayPanel,'Style','checkbox',... 'Position',[20 hPosition 150 20],'Tag','checkbox_showLabel',... 'String',' Show track number','HorizontalAlignment','left',... 'Callback',@(h,event) redrawOverlays(guidata(h))); hPosition=hPosition+20; uicontrol(overlayPanel,'Style','text',... 'Position',[10 hPosition 200 20],'Tag','text_trackOptions',... 'String','Track options','HorizontalAlignment','left','FontWeight','bold'); function hPosition=createWindowsOptions(overlayPanel,userData,hPosition) hPosition=hPosition+30; uicontrol(overlayPanel,'Style','text',... 'Position',[20 hPosition 100 20],'Tag','text_faceAlpha',... 'String',' Alpha value','HorizontalAlignment','left'); uicontrol(overlayPanel,'Style','edit','Position',[120 hPosition 50 20],... 'String','.3','BackgroundColor','white','Tag','edit_faceAlpha',... 'Callback',@(h,event) redrawOverlays(guidata(h))); hPosition=hPosition+20; uicontrol(overlayPanel,'Style','text',... 'Position',[10 hPosition 200 20],'Tag','text_windowsOptions',... 'String','Windows options','HorizontalAlignment','left','FontWeight','bold'); function hPosition=createScalarMapOptions(graphPanel,userData,hPosition) hPosition=hPosition+30; uicontrol(graphPanel,'Style','text',... 'Position',[20 hPosition 200 20],'Tag','text_UpSample',... 'String',' Upsampling Factor','HorizontalAlignment','left'); uicontrol(graphPanel,'Style','edit','Position',[220 hPosition 50 20],... 'String','1','BackgroundColor','white','Tag','edit_UpSample',... 'Callback',@(h,event) redrawGraphs(guidata(h))); hPosition=hPosition+20; uicontrol(graphPanel,'Style','text',... 'Position',[20 hPosition 200 20],'Tag','text_SmoothParam',... 'String',' Smoothing Parameter','HorizontalAlignment','left'); uicontrol(graphPanel,'Style','edit','Position',[220 hPosition 50 20],... 'String','.99','BackgroundColor','white','Tag','edit_SmoothParam',... 'Callback',@(h,event) redrawGraphs(guidata(h))); hPosition=hPosition+20; uicontrol(graphPanel,'Style','text',... 'Position',[10 hPosition 200 20],'Tag','text_scalarMapOptions',... 'String','Scalar Map options','HorizontalAlignment','left','FontWeight','bold'); function slider_callback(src,eventdata,panel) pos=get(panel,'Position'); pos(2)=(1-pos(4))*get(src,'Value'); set(panel,'Position',pos) uistack(panel,'top'); function displayPath= getDisplayPath(movie) [~,endPath] = fileparts(movie.getPath); displayPath = fullfile(endPath,movie.getFilename); function switchMovie(hObject,handles) userData=get(handles.figure1,'UserData'); props=get(hObject,{'UserData','Value'}); if isequal(props{1}(props{2}), userData.movieIndex),return;end movieViewer(userData.ML,userData.procId,'movieIndex',props{1}(props{2})); function size = getPanelSize(hPanel) if ~ishandle(hPanel), size=[0 0]; return; end a=get(get(hPanel,'Children'),'Position'); P=vertcat(a{:}); size = [max(P(:,1)+P(:,3))+10 max(P(:,2)+P(:,4))+20]; function runMovie(hObject,handles) userData = get(handles.figure1, 'UserData'); nFrames = userData.MO.nFrames_; startFrame = get(handles.slider_frame,'Value'); if startFrame == nFrames, startFrame =1; end; if get(hObject,'Value'), action = 'Stop'; else action = 'Run'; end set(hObject,'String',[action ' movie']); % Get frame/movies export status saveMovie = get(handles.checkbox_saveMovie,'Value'); saveFrames = get(handles.checkbox_saveFrames,'Value'); props = get(handles.popupmenu_movieFormat,{'String','Value'}); movieFormat = props{1}{props{2}}; if saveMovie, moviePath = fullfile(userData.MO.outputDirectory_,['Movie.' lower(movieFormat)]); end % Initialize movie output if saveMovie && strcmpi(movieFormat,'mov') MakeQTMovie('start',moviePath); MakeQTMovie('quality',.9) end if saveMovie && strcmpi(movieFormat,'avi') movieFrames(1:nFrames) = struct('cdata', [],'colormap', []); end % Initialize frame output if saveFrames; fmt = ['%0' num2str(ceil(log10(nFrames))) 'd']; frameName = @(frame) ['frame' num2str(frame, fmt) '.tif']; fpath = [userData.MO.outputDirectory_ filesep 'Frames']; mkClrDir(fpath); fprintf('Generating movie frames: '); end for iFrame = startFrame : nFrames if ~get(hObject,'Value'), return; end % Handle pushbutton press set(handles.slider_frame, 'Value',iFrame); redrawScene(hObject, handles); drawnow; % Get current frame for frame/movie export hFig = getFigure(handles,'Movie'); if saveMovie && strcmpi(movieFormat,'mov'), MakeQTMovie('addfigure'); end if saveMovie && strcmpi(movieFormat,'avi'), movieFrames(iFrame) = getframe(hFig); end if saveFrames print(hFig, '-dtiff', fullfile(fpath,frameName(iFrame))); fprintf('\b\b\b\b%3d%%', round(100*iFrame/(nFrames))); end end % Finish frame/movie creation if saveFrames; fprintf('\n'); end if saveMovie && strcmpi(movieFormat,'mov'), MakeQTMovie('finish'); end if saveMovie && strcmpi(movieFormat,'avi'), movie2avi(movieFrames,moviePath); end % Reset button set(hObject,'String', 'Run movie', 'Value', 0); function redrawScene(hObject, handles) userData = get(handles.figure1, 'UserData'); % Retrieve the value of the selected image if strcmp(get(hObject,'Tag'),'edit_frame') frameNumber = str2double(get(handles.edit_frame, 'String')); else frameNumber = get(handles.slider_frame, 'Value'); end frameNumber=round(frameNumber); frameNumber = min(max(frameNumber,1),userData.MO.nFrames_); % Set the slider and editboxes values set(handles.edit_frame,'String',frameNumber); set(handles.slider_frame,'Value',frameNumber); % Update the image and overlays redrawImage(handles); redrawOverlays(handles); function h= getFigure(handles,figName) h = findobj(0,'-regexp','Name',['^' figName '$']); if ~isempty(h), figure(h); return; end %Create a figure if strcmp(figName,'Movie') userData = get(handles.figure1,'UserData'); sz=get(0,'ScreenSize'); nx=userData.MO.imSize_(2); ny=userData.MO.imSize_(1); sc = max(1, max(nx/(.9*sz(3)), ny/(.9*sz(4)))); h = figure('Position',[sz(3)*.2 sz(4)*.2 nx/sc ny/sc],... 'Name',figName,'NumberTitle','off','Tag','viewerFig',... 'UserData',handles.figure1); % figure options for movie export iptsetpref('ImShowBorder','tight'); set(h, 'InvertHardcopy', 'off'); set(h, 'PaperUnits', 'Points'); set(h, 'PaperSize', [nx ny]); set(h, 'PaperPosition', [0 0 nx ny]); % very important set(h, 'PaperPositionMode', 'auto'); % set(h,'DefaultLineLineSmoothing','on'); % set(h,'DefaultPatchLineSmoothing','on'); axes('Parent',h,'XLim',[0 userData.MO.imSize_(2)],... 'YLim',[0 userData.MO.imSize_(1)],'Position',[0.05 0.05 .9 .9]); set(handles.figure1,'UserData',userData); % Set the zoom properties hZoom=zoom(h); hPan=pan(h); set(hZoom,'ActionPostCallback',@(h,event)panZoomCallback(h)); set(hPan,'ActionPostCallback',@(h,event)panZoomCallback(h)); else h = figure('Name',figName,'NumberTitle','off','Tag','viewerFig'); end function redrawChannel(hObject,handles) % Callback for channels checkboxes to avoid 0 or more than 4 channels channelBoxes = findobj(handles.figure1,'-regexp','Tag','checkbox_channel*'); nChan=numel(find(arrayfun(@(x)get(x,'Value'),channelBoxes))); if nChan==0, set(hObject,'Value',1); elseif nChan>3, set(hObject,'Value',0); end redrawImage(handles) function setScaleBar(handles,type) % Remove existing scalebar of given type h=findobj('Tag',type); if ~isempty(h), delete(h); end % If checked, adds a new scalebar using the width as a label input userData=get(handles.figure1,'UserData'); if ~get(handles.(['checkbox_' type]),'Value'), return; end getFigure(handles,'Movie'); scale = str2double(get(handles.(['edit_' type]),'String')); if strcmp(type,'imageScaleBar') width = scale *1000/userData.MO.pixelSize_; label = [num2str(scale) ' \mum']; else displayScale = str2double(get(handles.edit_vectorFieldScale,'String')); width = scale*displayScale/(userData.MO.pixelSize_/userData.MO.timeInterval_*60); label= [num2str(scale) ' nm/min']; end if ~get(handles.(['checkbox_' type 'Label']),'Value'), label=''; end props=get(handles.(['popupmenu_' type 'Location']),{'String','Value'}); location=props{1}{props{2}}; hScaleBar = plotScaleBar(width,'Label',label,'Location',location); set(hScaleBar,'Tag',type); function setTimeStamp(handles) % Remove existing timestamp of given type h=findobj('Tag','timeStamp'); if ~isempty(h), delete(h); end % If checked, adds a new scalebar using the width as a label input userData=get(handles.figure1,'UserData'); if ~get(handles.checkbox_timeStamp,'Value'), return; end getFigure(handles,'Movie'); frameNr=get(handles.slider_frame,'Value'); time= (frameNr-1)*userData.MO.timeInterval_; p=sec2struct(time); props=get(handles.popupmenu_timeStampLocation,{'String','Value'}); location=props{1}{props{2}}; hTimeStamp = plotTimeStamp(p.str,'Location',location); set(hTimeStamp,'Tag','timeStamp'); function setCLim(handles) clim=[str2double(get(handles.edit_cmin,'String')) ... str2double(get(handles.edit_cmax,'String'))]; redrawImage(handles,'CLim',clim) function setScaleFactor(handles) scaleFactor=str2double(get(handles.edit_imageScaleFactor,'String')); redrawImage(handles,'ScaleFactor',scaleFactor) function setColormap(handles) allCmap=get(handles.popupmenu_colormap,'String'); selectedCmap = get(handles.popupmenu_colormap,'Value'); redrawImage(handles,'Colormap',allCmap{selectedCmap}) function setColorbar(handles) cbar=get(handles.checkbox_colorbar,'Value'); props = get(handles.popupmenu_colorbarLocation,{'String','Value'}); if cbar, cbarStatus='on'; else cbarStatus='off'; end redrawImage(handles,'Colorbar',cbarStatus,'ColorbarLocation',props{1}{props{2}}) function redrawImage(handles,varargin) frameNr=get(handles.slider_frame,'Value'); imageTag = get(get(handles.uipanel_image,'SelectedObject'),'Tag'); % Get the figure handle drawFig = getFigure(handles,'Movie'); userData=get(handles.figure1,'UserData'); % Use corresponding method depending if input is channel or process output channelBoxes = findobj(handles.figure1,'-regexp','Tag','checkbox_channel*'); [~,index]=sort(arrayfun(@(x) get(x,'Tag'),channelBoxes,'UniformOutput',false)); channelBoxes =channelBoxes(index); if strcmp(imageTag,'radiobutton_channels') set(channelBoxes,'Enable','on'); chanList=find(arrayfun(@(x)get(x,'Value'),channelBoxes)); userData.MO.channels_(chanList).draw(frameNr,varargin{:}); displayMethod = userData.MO.channels_(chanList(1)).displayMethod_; else set(channelBoxes,'Enable','off'); % Retrieve the id, process nr and channel nr of the selected imageProc tokens = regexp(imageTag,'radiobutton_process(\d+)_output(\d+)_channel(\d+)','tokens'); procId=str2double(tokens{1}{1}); outputList = userData.MO.processes_{procId}.getDrawableOutput; iOutput = str2double(tokens{1}{2}); output = outputList(iOutput).var; iChan = str2double(tokens{1}{3}); userData.MO.processes_{procId}.draw(iChan,frameNr,'output',output,varargin{:}); displayMethod = userData.MO.processes_{procId}.displayMethod_{iOutput,iChan}; end % Set the color limits properties clim=displayMethod.CLim; if isempty(clim) hAxes=findobj(drawFig,'Type''axes','-not','Tag','Colorbar'); clim=get(hAxes,'Clim'); end if ~isempty(clim) set(handles.edit_cmin,'Enable','on','String',clim(1)); set(handles.edit_cmax,'Enable','on','String',clim(2)); end set(handles.edit_imageScaleFactor,'Enable','on','String',displayMethod.ScaleFactor); % Set the colorbar properties cbar=displayMethod.Colorbar; cbarLocation = find(strcmpi(displayMethod.ColorbarLocation,get(handles.popupmenu_colorbarLocation,'String'))); set(handles.checkbox_colorbar,'Value',strcmp(cbar,'on')); set(handles.popupmenu_colorbarLocation,'Enable',cbar,'Value',cbarLocation); % Set the colormap properties cmap=displayMethod.Colormap; allCmap=get(handles.popupmenu_colormap,'String'); iCmap = find(strcmpi(cmap,allCmap),1); if isempty(iCmap), iCmap= numel(allCmap); enableState = 'off'; else enableState = 'on'; end set(handles.popupmenu_colormap,'Value',iCmap,'Enable',enableState); % Reset the scaleBar setScaleBar(handles,'imageScaleBar'); setTimeStamp(handles); function panZoomCallback(h) % Reset the scaleBar handles=guidata(get(h,'UserData')); setScaleBar(handles,'imageScaleBar'); setTimeStamp(handles); function redrawOverlays(handles) if ~isfield(handles,'uipanel_overlay'), return; end overlayBoxes = findobj(handles.uipanel_overlay,'-regexp','Tag','checkbox_process*'); checkedBoxes = logical(arrayfun(@(x) get(x,'Value'),overlayBoxes)); overlayTags=arrayfun(@(x) get(x,'Tag'),overlayBoxes(checkedBoxes),... 'UniformOutput',false); for i=1:numel(overlayTags), redrawOverlay(handles.(overlayTags{i}),handles) end % Reset the scaleBar if get(handles.checkbox_vectorFieldScaleBar,'Value'), setScaleBar(handles,'vectorFieldScaleBar'); end function redrawOverlay(hObject,handles) userData=get(handles.figure1,'UserData'); frameNr=get(handles.slider_frame,'Value'); overlayTag = get(hObject,'Tag'); % Get figure handle or recreate figure movieFig = findobj(0,'Name','Movie'); if isempty(movieFig), redrawScene(hObject, handles); return; end figure(movieFig); % Retrieve the id, process nr and channel nr of the selected imageProc tokens = regexp(overlayTag,'^checkbox_process(\d+)_output(\d+)','tokens'); procId=str2double(tokens{1}{1}); outputList = userData.MO.processes_{procId}.getDrawableOutput; iOutput = str2double(tokens{1}{2}); output = outputList(iOutput).var; % Discriminate between channel-specific processes annd movie processes tokens = regexp(overlayTag,'_channel(\d+)$','tokens'); if ~isempty(tokens) iChan = str2double(tokens{1}{1}); inputArgs={iChan,frameNr}; graphicTag =['process' num2str(procId) '_channel'... num2str(iChan) '_output' num2str(iOutput)]; else iChan = []; inputArgs={frameNr}; graphicTag = ['process' num2str(procId) '_output' num2str(iOutput)]; end % Draw or delete the overlay depending on the checkbox value if get(hObject,'Value') vectorScale = str2double(get(handles.edit_vectorFieldScale,'String')); dragtailLength = str2double(get(handles.edit_dragtailLength,'String')); showLabel = get(handles.checkbox_showLabel,'Value'); faceAlpha = str2double(get(handles.edit_faceAlpha,'String')); clim=[str2double(get(handles.edit_vectorCmin,'String')) ... str2double(get(handles.edit_vectorCmax,'String'))]; if ~isempty(clim) && all(~isnan(clim)), cLimArgs={'CLim',clim}; else cLimArgs={}; end userData.MO.processes_{procId}.draw(inputArgs{:},'output',output,... 'vectorScale',vectorScale,'dragtailLength',dragtailLength,... 'faceAlpha',faceAlpha,'showLabel',showLabel,cLimArgs{:}); else h=findobj('Tag',graphicTag); if ~isempty(h), delete(h); end end % Get display method and update option status if isempty(iChan), displayMethod = userData.MO.processes_{procId}.displayMethod_{iOutput}; else displayMethod = userData.MO.processes_{procId}.displayMethod_{iOutput,iChan}; end if isa(displayMethod,'VectorFieldDisplay') && ~isempty(displayMethod.CLim) set(handles.edit_vectorCmin,'String',displayMethod.CLim(1)); set(handles.edit_vectorCmax,'String',displayMethod.CLim(2)); end function redrawGraphs(handles) if ~isfield(handles,'uipanel_graph'), return; end graphBoxes = findobj(handles.uipanel_graph,'-regexp','Tag','checkbox_process*'); checkedBoxes = logical(arrayfun(@(x) get(x,'Value'),graphBoxes)); graphTags=arrayfun(@(x) get(x,'Tag'),graphBoxes(checkedBoxes),... 'UniformOutput',false); for i=1:numel(graphTags), redrawGraph(handles.(graphTags{i}),handles) end function redrawGraph(hObject,handles) graphTag = get(hObject,'Tag'); userData=get(handles.figure1,'UserData'); % Retrieve the id, process nr and channel nr of the selected graphProc tokens = regexp(graphTag,'^checkbox_process(\d+)_output(\d+)','tokens'); procId=str2double(tokens{1}{1}); outputList = userData.MO.processes_{procId}.getDrawableOutput; iOutput = str2double(tokens{1}{2}); output = outputList(iOutput).var; % Discriminate between channel-specific and movie processes tokens = regexp(graphTag,'_channel(\d+)$','tokens'); if ~isempty(tokens) iChan = str2double(tokens{1}{1}); figName = [outputList(iOutput).name ' - Channel ' num2str(iChan)]; if strcmp({outputList(iOutput).type},'sampledGraph') inputArgs={iChan,iOutput}; else inputArgs={iChan}; end else tokens = regexp(graphTag,'_input(\d+)$','tokens'); if ~isempty(tokens) iInput = str2double(tokens{1}{1}); figName = [outputList(iOutput).name ' - ' ... userData.MO.processes_{procId}.getInput(iInput).name]; inputArgs={iInput}; else inputArgs={}; figName = outputList(iOutput).name; end end % Draw or delete the graph figure depending on the checkbox value h = getFigure(handles,figName); if ~get(hObject,'Value'),delete(h); return; end upSample = str2double(get(handles.edit_UpSample,'String')); smoothParam = str2double(get(handles.edit_SmoothParam,'String')); userData.MO.processes_{procId}.draw(inputArgs{:}, 'output', output,... 'UpSample', upSample,'SmoothParam', smoothParam); set(h,'DeleteFcn',@(h,event)closeGraphFigure(hObject)); function redrawSignalGraph(hObject,handles) graphTag = get(hObject,'Tag'); userData=get(handles.figure1,'UserData'); % Retrieve the id, process nr and channel nr of the selected graphProc tokens = regexp(graphTag,'^checkbox_process(\d+)_output(\d+)_input(\d+)_input(\d+)','tokens'); procId=str2double(tokens{1}{1}); iOutput = str2double(tokens{1}{2}); iInput1 = str2double(tokens{1}{3}); iInput2 = str2double(tokens{1}{4}); signalProc = userData.MO.processes_{procId}; figName = signalProc.getOutputTitle(iInput1,iInput2,iOutput); % Draw or delete the graph figure depending on the checkbox value h = getFigure(handles,figName); if ~get(hObject,'Value'),delete(h); return; end signalProc.draw(iInput1,iInput2,iOutput); set(h,'DeleteFcn',@(h,event)closeGraphFigure(hObject)); function closeGraphFigure(hObject) set(hObject,'Value',0); function deleteViewer() h = findobj(0,'-regexp','Tag','viewerFig'); if ~isempty(h), delete(h); end
github
mehta-lab/Instantaneous-PolScope-master
dataPreparationGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/dataPreparationGUI.m
29,435
utf_8
638addd5f5871857e30fecde23d77197
function varargout = dataPreparationGUI(varargin) % DATAPREPARATIONGUI M-file for dataPreparationGUI.fig % DATAPREPARATIONGUI, by itself, creates a new DATAPREPARATIONGUI or raises the existing % singleton*. % % H = DATAPREPARATIONGUI returns the handle to a new DATAPREPARATIONGUI or the handle to % the existing singleton*. % % DATAPREPARATIONGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in DATAPREPARATIONGUI.M with the given input arguments. % % DATAPREPARATIONGUI('Property','Value',...) creates a new DATAPREPARATIONGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before dataPreparationGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to dataPreparationGUI_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 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help dataPreparationGUI % Last Modified by GUIDE v2.5 23-Apr-2011 20:07:04 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @dataPreparationGUI_OpeningFcn, ... 'gui_OutputFcn', @dataPreparationGUI_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 dataPreparationGUI is made visible. function dataPreparationGUI_OpeningFcn(hObject, ~, handles, varargin) % % dataPreparationGUI('mainFig', handles.figure1) - call from movieSelector % % Useful tools: % % User Data: % % userData.channels - array of Channel objects % userData.mainFig - handle of movie selector GUI % userData.handles_main - 'handles' of movie selector GUI % % userData.setChannelFig - handle of channel set-up figure % userData.iconHelpFig - handle of help dialog % % % [copyright openHelpFile] = userfcn_softwareConfig(handles); set(handles.text_copyright, 'String', copyright) % Choose default command line output forfor i dataPreparationGUI handles.output = hObject; userData = get(handles.figure1, 'UserData'); % Initialize the userData userData.projectDir = pwd; userData.outputDir = []; userData.rawData =[]; userData.channels =[]; userData.movies=[]; % Load help icon from dialogicons.mat userData = loadLCCBIcons(userData); supermap(1,:) = get(hObject,'color'); userData.colormap = supermap; axes(handles.axes_help); Img = image(userData.questIconData); set(hObject,'colormap',supermap); set(gca, 'XLim',get(Img,'XData'),'YLim',get(Img,'YData'),... 'visible','off'); set(Img,'ButtonDownFcn',@icon_ButtonDownFcn); if openHelpFile set(Img, 'UserData', struct('class',mfilename)) end % TestIif the dataPreparationGUI ewas called from the movieSelctorGUI if nargin > 3 t = find(strcmp(varargin,'mainFig')); if isempty(t) error('User-defined: input error, correct statement: dataPreparationGUI(''mainFig'',handles.figure1)'); end set(handles.checkbox_createMD,'Value',1); % Save main figure handles userData.mainFig = varargin{t+1}; userData.handles_main = guidata(userData.mainFig); end % Save data and update graphics set(handles.figure1,'UserData',userData) guidata(hObject, handles); update_graphics(hObject,handles) % UIWAIT makes dataPreparationGUI wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = dataPreparationGUI_OutputFcn(~, ~, 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 pushbutton_cancel. function pushbutton_cancel_Callback(~, ~, handles) % handles structure with handles and user data (see GUIDATA) delete(handles.figure1); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(~, ~, handles) % handles structure with handles and user data (see GUIDATA) userData = get(handles.figure1, 'UserData'); % Delete help window if existing if isfield(userData, 'iconHelpFig') && ishandle(userData.iconHelpFig) delete(userData.iconHelpFig) end % --- Executes on button press in pushbutton_delete_channel. function pushbutton_delete_channel_Callback(hObject, ~, handles) % hObject handle to pushbutton_delete_channel (see GCBO) % handles structure with handles and user data (see GUIDATA) userData = get(handles.figure1, 'UserData'); % Retrieve the selected channel id, remove it and update the selected channel userData.selectedChannel=get(handles.listbox_channels,'Value'); userData.channels(userData.selectedChannel)=[]; userData.selectedChannel = max(userData.selectedChannel-1,1); % Save data and update graphics set(handles.figure1,'UserData',userData); guidata(hObject, handles); update_graphics(hObject,handles) % --- Executes on button press in pushbutton_edit_channel. function channelEdition_Callback(hObject, ~, handles) % hObject handle to pushbutton_edit_channel (see GCBO) % handles structure with handles and user data (see GUIDATA) userData = get(handles.figure1, 'UserData'); % Retrieve the channel index in the case of channel edition if strcmp(get(hObject,'Tag'),'pushbutton_edit_channel') userData.selectedChannel = get(handles.listbox_channels,'Value'); if userData.selectedChannel> numel(userData.channels), return; end newChannel=0; else newChannel=1; end % Launch a dialog window asking the user for the new channel directory name propNames = {'excitationWavelength_','emissionWavelength_','exposureTime_'}; prompt = {'Enter the channel as it is encoded in the image names',... 'Enter the channel directory name - optional',... 'Enter the excitation wavelength (in nm) - optional',... 'Enter the emission wavelength (in nm) - optional',... 'Enter the exposure time (in s) - optional'}; num_lines = 1; if newChannel inputData=inputdlg(prompt,'Create new channel',num_lines); else dlg_title = ['Rename channel ' num2str(userData.selectedChannel)]; defaultValues={userData.channels(userData.selectedChannel).string,... userData.channels(userData.selectedChannel).name,... num2str(userData.channels(userData.selectedChannel).properties.excitationWavelength_),... num2str(userData.channels(userData.selectedChannel).properties.emissionWavelength_),... num2str(userData.channels(userData.selectedChannel).properties.exposureTime_)}; inputData=inputdlg(prompt,dlg_title,num_lines,defaultValues); end if isempty(inputData), return; end % If no channel directory name is supplied, use the channel string name if isempty(inputData{2}), inputData{2}=inputData{1}; end % Update the channel string and if newChannel % Add a new channel structure and update the channel index userData.channels(end+1).name=inputData{2}; userData.channels(end).exportMD = 1; userData.channels(end).string=''; userData.channels(end).properties.excitationWavelength_=[]; userData.channels(end).properties.emissionWavelength_=[]; userData.channels(end).properties.exposureTime_=[]; userData.selectedChannel = numel(userData.channels); else userData.channels(userData.selectedChannel).name=inputData{2}; end userData.channels(userData.selectedChannel).string=inputData{1}; % Manage input properties propList=inputData(3:end); if ~isempty(propList), % Check for property values validity propValues = cellfun(@str2num,propList','Unif',false); validProperties = Channel.checkValue(propNames,propValues); % Affect valid, non-multiple properties values for i= find(validProperties) userData.channels(userData.selectedChannel).properties.(propNames{i})=propValues{i}; end end % Save data and update graphics set(handles.figure1,'UserData',userData); guidata(hObject, handles); update_graphics(hObject,handles) % --- Executes on button press in pushbutton_select_projectDir. function pushbutton_select_projectDir_Callback(hObject, ~, handles) % hObject handle to pushbutton_select_projectDir (see GCBO) % handles structure with handles and user data (see GUIDATA) userData = get(handles.figure1, 'UserData'); pathname = uigetdir(userData.projectDir,'Select project folder'); % Test uigetdir output, reinitalize the movies if any, store the project % directory and the output directory (project directory by default) if isequal(pathname,0), return; end userData.projectDir = pathname; userData.outputDir = pathname; userData.movies=[]; userData.rawData=[]; set(handles.edit_projectDir,'String',pathname); set(handles.edit_outputDir,'String',pathname); % List all subdirectories, including the project directory itself allSub = dir(userData.projectDir); allSub = allSub([allSub.isdir]' & ... arrayfun(@(x)(~any(strcmp(x.name,{'..'}))),allSub)); nSub = numel(allSub); for iSub = 1:nSub % List all images of any extension in this directory % Use the true returnAll option of imDir imageFiles = imDir([userData.projectDir filesep allSub(iSub).name],true); if ~isempty(imageFiles) % If some image files are found, there are two behaviours % 1- if the directory is the project directory, we will use it as % it to create channel folders % 2- for any other folder, add a new movie which name is set by the % folder name if ~strcmp(allSub(iSub).name,'.') % Add movie with empty properties userData.movies(end+1).name=allSub(iSub).name; userData.movies(end).properties.pixelSize_=[]; userData.movies(end).properties.timeInterval_=[]; userData.movies(end).properties.numAperture_=[]; userData.movies(end).properties.camBitdepth_=[]; rawData.movieIndx = numel(userData.movies); else rawData.movieIndx=[]; end % Get the unique bodyname of the image files [~, imageBodyNames,~,imageExt]=cellfun(@getFilenameBody,{imageFiles.name},'Unif',false); [imageBodyNames,uniqueIndx] = unique(imageBodyNames); for iRawData=1:numel(imageBodyNames) rawData.name = imageBodyNames{iRawData}; rawData.dir = allSub(iSub).name; rawData.chanIndx=[]; rawData.ext=imageExt{uniqueIndx(iRawData)}; userData.rawData=vertcat(userData.rawData,rawData); end end end if isempty(userData.rawData) errordlg('No images found in the main project folder or its sub-folders !!'); end % Save data and update graphics set(handles.figure1,'UserData',userData); guidata(hObject, handles); update_graphics(hObject,handles) % --- Executes on button press in pushbutton_guess. function pushbutton_guess_Callback(hObject, ~, handles) % hObject handle to pushbutton_guess (see GCBO) % handles structure with handles and user data (see GUIDATA) userData = get(handles.figure1, 'UserData'); % Check all raw data components have been affected to a channel checkChannels = any(cellfun(@isempty,{userData.rawData.chanIndx})); if checkChannels, errordlg('All components have not been affected to a channel','modal'); return; end % Guess the movie names from the raw data % Use the part of the string to the left of the channel string nRawData = numel(userData.rawData); movieNames=cell(1,nRawData); for i=1:nRawData chanIndx = userData.rawData(i).chanIndx; indx=regexp(userData.rawData(i).name,userData.channels(chanIndx).string,'start'); movieNames{i}=userData.rawData(i).name(1:indx-1); end % Find the unique movie names and store the correspondinx index for each % raw data component [uniqueMovieNames, ~, movieIndx]= unique(movieNames); userData.movies = cell2struct(uniqueMovieNames,'name')'; initProperties.pixelSize_=[]; initProperties.timeInterval_=[]; initProperties.numAperture_=[]; initProperties.camBitdepth_=[]; [userData.movies(:).properties]=deal(initProperties); for i=1:nRawData userData.rawData(i).movieIndx=movieIndx(i); end % Save data and update graphics set(handles.figure1,'UserData',userData); guidata(hObject, handles); update_graphics(hObject,handles) % --- Executes on button press in checkbox_createMD. function checkbox_createMD_Callback(hObject, ~, handles) update_graphics(hObject,handles) % --- Executes on button press in pushbutton_edit_movie. function pushbutton_edit_movie_Callback(hObject, ~, handles) % hObject handle to pushbutton_edit_movie (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) userData = get(handles.figure1, 'UserData'); if isempty(userData.movies), return; end % Retrieve the selected movie ID and launch a dialog box asking the user % for the new movie name selectedMovie = get(handles.listbox_movies,'Value'); propNames = {'pixelSize_','timeInterval_','numAperture_','camBitdepth_'}; % Input dialog common properties dlg_title = 'Movie edition'; num_lines = 1; prompt = {... 'Enter the movie directory name:',... 'Enter the pixel size (in nm) - optional',... 'Enter the time interval (in s) - optional',... 'Enter the numerical aperture - optional',... 'Enter the camera bit depth - optional',... }; % Test for single or multiple selection if numel(selectedMovie)==1 defaultValues={... userData.movies(selectedMovie).name,... num2str(userData.movies(selectedMovie).properties.pixelSize_),... num2str(userData.movies(selectedMovie).properties.timeInterval_),... num2str(userData.movies(selectedMovie).properties.numAperture_),... num2str(userData.movies(selectedMovie).properties.camBitdepth_)}; inputData=inputdlg(prompt,dlg_title,num_lines,defaultValues); % Update the movie name and store the list of properties in propList userData.movies(selectedMovie).name=inputData{1}; propList=inputData(2:end); else % Initialize default values nProps = numel(propNames); defaultValues=cellfun(@num2str,cell(1,nProps),'Unif',false); for i= 1:nProps allPropValues=arrayfun(@(x) x.properties.(propNames{i}),userData.movies(selectedMovie),... 'UniformOutput',false); uniquePropValues = unique([allPropValues{:}]); emptyPropValues = find(cellfun(@isempty,allPropValues),1); unicityTest = isempty(uniquePropValues) ||... (numel(uniquePropValues)==1 && isempty(emptyPropValues)); if unicityTest defaultValues{i} = num2str(uniquePropValues); else defaultValues{i}='(multiple)'; end end % Remove the movie name from the prompt list and store answer in % propList propList=inputdlg(prompt(2:end),dlg_title,num_lines,defaultValues); end if isempty(propList), return; end % Check multiple properties nonMultipleOutput=~strcmp(propList','(multiple)'); % Check for property values validity propValues = cellfun(@str2num,propList','Unif',false); validProperties = MovieData.checkValue(propNames,propValues); % Affect valid, non-multiple properties values for i= find(nonMultipleOutput & validProperties) for j=selectedMovie userData.movies(j).properties.(propNames{i})=propValues{i}; end end % Save data and update graphics set(handles.figure1,'UserData',userData); guidata(hObject, handles); update_graphics(hObject,handles) % --- Executes on selection change in listbox_channels. function listbox_channels_Callback(hObject, ~, handles) % hObject handle to listbox_channels (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Check if the user double clicked on the list box if strcmp(get(handles.figure1,'SelectionType'),'open') userData = get(handles.figure1, 'UserData'); % Modify the export status of the selected channel userData.selectedChannel=get(handles.listbox_channels,'Value'); userData.channels(userData.selectedChannel).exportMD=~userData.channels(userData.selectedChannel).exportMD; % Save data and update graphics set(handles.figure1,'UserData',userData); guidata(hObject, handles); update_graphics(hObject,handles) end function update_graphics(hObject, handles) userData = get(handles.figure1, 'UserData'); if ~isempty(userData.channels) % Generate the channel list, put the channels to be exported in the % MovieData in bold (using html block), update the channel listbox channelList =arrayfun(@(x)[x.name ' (' x.string ')'],userData.channels,'UniformOutput',false); if get(handles.checkbox_createMD,'Value') exportMDChannels = logical([userData.channels.exportMD]); channelList(exportMDChannels)=cellfun(@(x) ['<html><b>' x '</b></html>'],channelList(exportMDChannels),... 'UniformOutput',false); end set(handles.listbox_channels,'String',channelList,'Value',userData.selectedChannel); else set(handles.listbox_channels,'String',[]); end if ~isempty(userData.movies) % Generate the movie list, update the movies listbox set(handles.listbox_movies,'String',{userData.movies.name}); else set(handles.listbox_movies,'String',[]); end if isempty(userData.rawData), set(handles.listbox_rawData,'String',[]); return; end nRawData = numel(userData.rawData); % If raw data has been selected, find the match between each channel string % with all the raw data components nChannels = numel(userData.channels(:)); channelMatches=zeros(nChannels,nRawData); for i=1:nChannels findChannel = @(x) (~isempty(regexp(x,userData.channels(i).string,'ONCE'))); channelMatches(i,:) = cellfun(findChannel,{userData.rawData.name}); end % Test the unique correspondance between each raw data component and a % channel for i=1:nRawData chanIndx=find(channelMatches(:,i)); if numel(chanIndx)>1 errorMsg=sprintf('Multiple user-defined channels match the movie:\n %s',userData.rawData(i).name); errordlg(errorMsg); userData.rawData(i).chanIndx=[]; break else userData.rawData(i).chanIndx = chanIndx; end end % Update the number of found chanels and put the matched raw data components % associated with a channel in bold font. channelMatch = ~cellfun(@isempty,{userData.rawData.chanIndx}); channelMatchText=['Matching channels: ' num2str(sum(channelMatch)) '/' num2str(nRawData)]; set(handles.text_channelMatch,'String',channelMatchText); rawDataNames={userData.rawData.name}; rawDataNames(channelMatch)=cellfun(@(x) ['<html><b>' x '</b></html>'],rawDataNames(channelMatch),'UniformOutput',false); set(handles.listbox_rawData,'String',rawDataNames); % Update the number of found movies movieMatch = ~cellfun(@isempty,{userData.rawData.movieIndx}); movieMatchText=['Matching movies: ' num2str(sum(movieMatch)) '/' num2str(nRawData)]; set(handles.text_movieMatch,'String',movieMatchText); % Save data set(handles.figure1,'UserData',userData); guidata(hObject, handles); % --- Executes on button press in pushbutton_select_outputDir. function pushbutton_select_outputDir_Callback(hObject, ~, handles) % hObject handle to pushbutton_select_outputDir (see GCBO) % handles structure with handles and user data (see GUIDATA) userData = get(handles.figure1, 'UserData'); pathname = uigetdir('Select output directory', userData.projectDir); % Test uigetdir output and store its results if isequal(pathname,0), return; end userData.outputDir = pathname; set(handles.edit_outputDir,'String',pathname); % Save data set(handles.figure1,'UserData',userData); guidata(hObject, handles); % --- Executes on button press in pushbutton_exclude_component. function pushbutton_exclude_component_Callback(hObject, ~, handles) % hObject handle to pushbutton_exclude_component (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) userData = get(handles.figure1, 'UserData'); % Retrieve the selected component id, selectedComponents=get(handles.listbox_rawData,'Value'); % Find any movie associated with component to exclude uniqueMovieIndx =unique([userData.rawData(selectedComponents).movieIndx]); if ~isempty(uniqueMovieIndx), % Loop backwards on found movies (for index renumbering) for i=uniqueMovieIndx(end:-1:1) % Find movies to remove, i.e. movies where all components are to be % excluded nMovieComponentsToExclude = sum([userData.rawData(selectedComponents).movieIndx]==i); nMovieComponentsTotal = sum([userData.rawData(:).movieIndx]==i); if nMovieComponentsToExclude~=nMovieComponentsTotal, continue; end % Remove movie from the list userData.movies(i)=[]; % Renumber movie index of remaining components renumberIndx=([userData.rawData(:).movieIndx]>i); % Lame for loop as I didn't find a way to avoid it for rawDataIndx =find(renumberIndx) userData.rawData(rawDataIndx).movieIndx=userData.rawData(rawDataIndx).movieIndx -1; end end end % Remove component and update the selected value userData.rawData(selectedComponents)=[]; selectedComponents = max(min(selectedComponents)-1,1); set(handles.listbox_rawData,'Value',selectedComponents); % Save data and update graphics set(handles.figure1,'UserData',userData); guidata(hObject, handles); update_graphics(hObject,handles) % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(~, ~, handles) userData = get(handles.figure1, 'UserData'); % Check all movies and channels have been attributed checkMovies = any(cellfun(@isempty,{userData.rawData.movieIndx})); if checkMovies, errordlg('All components have not been affected to a movie','modal'); return; end checkChannels = any(cellfun(@isempty,{userData.rawData.chanIndx})); if checkChannels, errordlg('All components have not been affected to a channel','modal'); return; end wtBar = waitbar(0,'Please wait, ...'); % Read checkbox values createMD=get(handles.checkbox_createMD,'Value'); splitSTK=get(handles.checkbox_splitSTK,'Value'); % Retrieve main window userData if applicable if isfield(userData,'mainFig') userData_main = get(userData.mainFig, 'UserData'); contentlist = get(userData.handles_main.listbox_movie, 'String'); end nMovies=numel(userData.movies); for iMovie=1:nMovies % Create the movie folder movieFolder=[userData.outputDir filesep userData.movies(iMovie).name]; if ~isdir(movieFolder), mkdir(movieFolder); end waitbar(iMovie/nMovies,wtBar,['Please wait, setting up movie ' num2str(iMovie) ' ...']); % Initialize Channel array (to be fetched in the MovieData constructor) if createMD, MDChannels=[]; end % Find all raw data components associated with that movie rawDataList=find([userData.rawData.movieIndx]==iMovie); for nRawData=rawDataList % Retrieve the channel index and create the channel folder chanIndx = userData.rawData(nRawData).chanIndx; channelFolder = [movieFolder filesep userData.channels(chanIndx).name]; if ~isdir(channelFolder), mkdir(channelFolder); end % Retrieve original rawDatafolder and copy/move the file rawDataFolder = [userData.projectDir filesep userData.rawData(nRawData).dir]; rawDataBodyName = userData.rawData(nRawData).name; rawDataExt = userData.rawData(nRawData).ext; rawDataFiles=[rawDataFolder filesep rawDataBodyName '*' rawDataExt]; if strcmpi(rawDataExt,'.stk') && splitSTK % Split STK files stkFiles=dir(rawDataFiles); if numel(stkFiles)>1 errordlg('Found more than one STK file for the movie'); continue; end try currIm = stackRead([rawDataFolder filesep stkFiles(1).name]); catch errMess disp(['stackRead.m failed: ' errMess.message ' Trying tif3Dread.m instead...']) %Tif3Dread is slower, but can open some files which the %current stackRead version fails to open currIm = tif3Dread([rawDataFolder filesep stkFiles(1).name]); end nIm = size(currIm,3); %Check number of images %Get number of digits for writing file names nDig = floor(log10(nIm)+1); %Make the string for formatting fString = strcat('%0',num2str(nDig),'.f'); %Write them all to new dir disp(['Splitting "' stkFiles(1).name '" into ' num2str(nIm) ' seperate files...']) for k = 1:nIm imwrite(squeeze(currIm(:,:,k)),[channelFolder filesep stkFiles(1).name(1:end-4) '_' num2str(k,fString) '.tif']); end else if get(handles.checkbox_copy,'Value') copyfile(rawDataFiles,channelFolder); else movefile(rawDataFiles,channelFolder); end end % Create a Channel object, and append it to the existing Channel % array if applicable if createMD && userData.channels(chanIndx).exportMD try newChannel = Channel(channelFolder); set(newChannel, userData.channels(chanIndx).properties); catch ME throw(ME); end MDChannels = cat(2, MDChannels,newChannel); end end if createMD % Check all required channels have been set up nFoundChannels =numel(MDChannels); nExpectedChannels = sum([userData.channels.exportMD]); if nFoundChannels ~= nExpectedChannels errordlg('Not all channels were found. Skipped Movie Data creation!'); continue end % Save Movie Data to disk movieDataFile = 'movieData.mat'; % Launch the MovieData constructor try MD = MovieData(MDChannels, movieFolder); catch ME errormsg = sprintf([ME.message '.\n\nCreating movie data failed.']); errordlg(errormsg, 'User Input Error','modal'); continue; end % Check the movieData sanity try MD.movieDataPath_=movieFolder; MD.movieDataFileName_=movieDataFile; set(MD,userData.movies(iMovie).properties); MD.sanityCheck; catch ME delete(MD); errormsg = sprintf('%s.\n\nPlease check your movie data. Movie data is not saved.',ME.message); errordlg(errormsg,'Channel Error','modal'); continue; end % Save the movie data MD.save; % Update main window components and controls if applicable if isfield(userData,'mainFig') if any(strcmp([movieFolder filesep movieDataFile], contentlist)) errordlg('Cannot overwrite a movie data file which is already in the movie list. Please choose another file name or another path.','Error','modal'); return end % Update the main window components (list of MovieData, MovieData % listbox) userData_main.MD = cat(2, userData_main.MD, MD); contentlist{end+1} = [movieFolder filesep movieDataFile]; set(userData.handles_main.listbox_movie, 'String', contentlist, 'Value', length(contentlist)) title = sprintf('Movie List: %s/%s movie(s)', num2str(length(contentlist)), num2str(length(contentlist))); set(userData.handles_main.text_movie_1, 'String', title) end end end close(wtBar) % Update main window components and controls if applicable if isfield(userData,'mainFig')% Save the data set(userData.mainFig, 'UserData', userData_main) end % Delete current window delete(handles.figure1)
github
mehta-lab/Instantaneous-PolScope-master
SpeckleTrackingProcess.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/SpeckleTrackingProcess.m
7,543
utf_8
163e1c767e01d3fcf82d99c838c61985
classdef SpeckleTrackingProcess < DataProcessingProcess % Concrete class for a speckle tracking process % % Sebastien Besson, May 2011 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % methods function obj = SpeckleTrackingProcess(owner,varargin) if nargin == 0 super_args = {}; else % Input check ip = inputParser; ip.addRequired('owner',@(x) isa(x,'MovieData')); ip.addOptional('outputDir',owner.outputDirectory_,@ischar); ip.addOptional('funParams',[],@isstruct); ip.parse(owner,varargin{:}); outputDir = ip.Results.outputDir; funParams = ip.Results.funParams; % Define arguments for superclass constructor super_args{1} = owner; super_args{2} = SpeckleTrackingProcess.getName; super_args{3} = @trackMovieSpeckles; if isempty(funParams) funParams=SpeckleTrackingProcess.getDefaultParams(owner,outputDir); end super_args{4} = funParams; end obj = obj@DataProcessingProcess(super_args{:}); end function varargout = loadChannelOutput(obj,iChan,varargin) % Input check outputList={'MPM','M','gapList','flow'}; ip =inputParser; ip.addRequired('iChan',@(x) isscalar(x) && obj.checkChanNum(x)); ip.addOptional('iFrame',1:obj.owner_.nFrames_,@(x) all(obj.checkFrameNum(x))); ip.addParamValue('output',outputList,@(x) all(ismember(x,outputList))); ip.parse(iChan,varargin{:}) iFrame=ip.Results.iFrame; % Data loading output = ip.Results.output; if ischar(output), output = {output}; end s = load(obj.outFilePaths_{1,iChan},output{:}); for i=1:numel(output), varargout{i}=s.(output{i}); end % If single frame is selected if numel(iFrame)==1 for i=1:numel(output) switch output{i} case 'M' if size(varargout{i}, 3) < iFrame, varargout{i} = zeros(1,4); else varargout{i}=varargout{i}(:,:,iFrame); end case 'MPM' index = all(varargout{i}(:,2*iFrame-1:2*iFrame),2)~=0; varargout{i}=varargout{i}(index,1:2*iFrame); case {'flow','gapList'} varargout{i}=varargout{i}{iFrame}; end end end end function status = checkChannelOutput(obj,varargin) %Checks if the selected channels have valid output files ip =inputParser; ip.addRequired('obj',@(x) isa(x,'SpeckleTrackingProcess')); ip.addOptional('iChan',1:numel(obj.owner_.channels_),... @(x) all(obj.checkChanNum(x))); ip.parse(obj,varargin{:}); iChan=ip.Results.iChan; %Makes sure there's at least one .mat file in the speified %directory status = arrayfun(@(x) exist(obj.outFilePaths_{x},'file'),iChan); end function output = getDrawableOutput(obj) colors = hsv(numel(obj.owner_.channels_)); output(1).name='Tracks'; output(1).var='MPM'; output(1).formatData=@formatTracks; output(1).type='overlay'; output(1).defaultDisplayMethod=@(x)... TracksDisplay('Color',colors(x,:),'showLabel',false); output(2).name='Frame to frame displacement'; output(2).var='M'; output(2).formatData=@(x) [x(all(x(:,[1 3])~=0,2),[2 1])... x(all(x(:,[1 3])~=0,2),[4 3])-x(all(x(:,[1 3])~=0,2),[2 1])]; output(2).type='overlay'; output(2).defaultDisplayMethod=@(x)... VectorFieldDisplay('Color',colors(x,:)); output(3).name='Tracking initializers'; output(3).var='flow'; output(3).formatData=@formatFlow; output(3).type='overlay'; output(3).defaultDisplayMethod=@(x)... VectorFieldDisplay('Color',[0 1 0]); end end methods (Static) function name =getName() name = 'Speckle Tracking'; end function h = GUI() h= @speckleTrackingProcessGUI; end function methods = getInterpolationMethods(varargin) intMethods(1).name = 'none'; intMethods(1).description = ' Do not interpolate'; intMethods(2).name = 'nearest-neighbor'; intMethods(2).description = ' Use nearest-neighbor flow'; intMethods(3).name = 'gaussian'; intMethods(3).description = ' Use Gaussian weighted neighbors interpolation'; ip=inputParser; ip.addOptional('index',1:length(intMethods),@isvector); ip.parse(varargin{:}); methods=intMethods(ip.Results.index); end function funParams = getDefaultParams(owner,varargin) % Input check ip=inputParser; ip.addRequired('owner',@(x) isa(x,'MovieData')); ip.addOptional('outputDir',owner.outputDirectory_,@ischar); ip.parse(owner, varargin{:}) outputDir=ip.Results.outputDir; % Set default parameters funParams.ChannelIndex = 1 : numel(owner.channels_); funParams.OutputDirectory = [outputDir filesep 'speckleTracks']; funParams.enhanced = 0; funParams.threshold = 3; funParams.corrLength = 33; funParams.interpolationMethod = 1; end end end function flow = formatFlow(initFlow) if isempty(initFlow), flow=zeros(1,4); else flow=[initFlow(:,[2 1]) initFlow(:,[4 3])-initFlow(:,[2 1])]; end end function tracks=formatTracks(data) nTracks = size(data,1); % Find track starts trackStart=arrayfun(@(x) find(data(x,:)==0,1,'last')+1,1:nTracks,'UniformOutput',false); trackStart(cellfun(@isempty,trackStart))={1}; trackStart = [trackStart{:}]; % Create a tracks array of structures with 2 fields xCoord and yCoord tracks(nTracks, 1) =struct('xCoord',[],'yCoord',[]); for i=1:nTracks tracks(i).xCoord = data(i,trackStart(i)+1:2:end); tracks(i).yCoord = data(i,trackStart(i):2:end); end end
github
mehta-lab/Instantaneous-PolScope-master
packageGUI_RunFcn.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/packageGUI_RunFcn.m
13,383
utf_8
f9131d2eae6da6949f0b386c4646a0d1
function packageGUI_RunFcn(hObject,eventdata,handles) % Run the selected processes in the packageGUI interface % % This is a common section of code called by pushbutton_run_Callback % when user click the "Run" button on package control panels. % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Chuangang Ren 11/2010 % Sebastien Besson 5/2011 (last modified Oct 2011) ip = inputParser; ip.addRequired('hObject',@ishandle); ip.addRequired('eventdata',@(x) isstruct(x) || isempty(x)); ip.addRequired('handles',@isstruct); ip.parse(hObject,eventdata,handles); %% Initialization % Get check box status of current movie and update user data userData = get(handles.figure1,'UserData'); userData.statusM(userData.id).Checked = userfcn_saveCheckbox(handles); set(handles.figure1, 'UserData', userData) % Determine the movie(s) to be processed if ~isempty(userData.MD), field='MD'; else field = 'ML'; end nMovies = length(userData.(field)); % number of movies if get(handles.checkbox_runall, 'Value') movieList = circshift(1:nMovies,[0 -(userData.id-1)]); else movieList=userData.id; end % Get the list of valid movies (with processes to run) hasValidProc = arrayfun(@(x) any(userData.statusM(x).Checked),movieList); movieRun=movieList(hasValidProc); procCheck=cell(1,numel(nMovies)); procCheck(movieRun)=arrayfun(@(x) find(userData.statusM(x).Checked),movieRun,... 'UniformOutput',false); % Throw warning dialog if no movie if isempty(movieRun) warndlg('No step is selected, please select a step to process.',... 'No Step Selected','modal'); return end %% Pre-processing examination % movie exception (same length of movie data) movieException = cell(1, nMovies); procRun = cell(1, nMovies);% id of processes to run % Find unset processes isProcSet=@(x,y)~isempty(userData.package(x).processes_{y}); isMovieProcSet = @(x) all(arrayfun(@(y)isProcSet(x,y),procCheck{x})); invalidMovies=movieRun(~arrayfun(isMovieProcSet,movieRun)); for i = invalidMovies invalidProc = procCheck{i}(arrayfun(@(y)~isProcSet(i,y),procCheck{i})); for j=invalidProc ME = MException('lccb:run:setup', ['Step %d : %s is not set up yet.\n'... '\nTip: when step is set up successfully, the step name becomes bold.'],j,... eval([userData.package(i).getProcessClassNames{j} '.getName'])); movieException{i} = cat(2, movieException{i}, ME); end end validMovies=movieRun(arrayfun(isMovieProcSet,movieRun)); for iMovie = validMovies % Check if selected processes have alrady be successfully run % If force run, re-run every process that is checked if ~get(handles.checkbox_forcerun, 'Value') k = true; for i = procCheck{iMovie} if ~( userData.package(iMovie).processes_{i}.success_ && ... ~userData.package(iMovie).processes_{i}.procChanged_ ) || ... ~userData.package(iMovie).processes_{i}.updated_ k = false; procRun{iMovie} = cat(2, procRun{iMovie}, i); end end if k movieRun = setdiff(movieRun, iMovie); continue end else procRun{iMovie} = procCheck{iMovie}; end % Package full sanity check. Sanitycheck every checked process [status procEx] = userData.package(iMovie).sanityCheck(true, procRun{iMovie}); % Return user data !!! set(handles.figure1, 'UserData', userData) invalidProcEx = procRun{iMovie}(~cellfun(@isempty,procEx(procRun{iMovie}))); for i = invalidProcEx % Check if there is fatal error in exception array if strcmp(procEx{i}(1).identifier, 'lccb:set:fatal') || ... strcmp(procEx{i}(1).identifier, 'lccb:input:fatal') % Sanity check error - switch GUI to the x th movie if iMovie ~= userData.id set(handles.popupmenu_movie, 'Value', iMovie) % Update the movie pop-up menu in the main package GUI packageGUI('switchMovie_Callback',handles.popupmenu_movie, [], handles) end userfcn_drawIcon(handles,'error', i, procEx{i}(1).message, true); ME = MException('lccb:run:sanitycheck','Step %d %s: \n%s',... i,userData.package(iMovie).processes_{i}.getName, procEx{i}(1).message); movieException{iMovie} = cat(2, movieException{iMovie}, ME); end end % Refresh user data !!! userData = get(handles.figure1, 'UserData'); end %% Pre-processing exception report if isempty(movieRun) warndlg('All selected steps have been processed successfully. Please check the ''Force Run'' check box if you want to re-process the successful steps.','No Step Selected','modal'); return end status = generateReport(movieException,userData,'preprocessing'); if ~status, return; end %% Start processing if strcmp(get(handles.menu_debug_enter,'Checked'),'on'), dbstop if caught error; end for i=1:length(movieRun) iMovie = movieRun(i); if iMovie ~= userData.id % Update the movie pop-up menu in the main package GUI set(handles.figure1, 'UserData', userData) set(handles.popupmenu_movie, 'Value', iMovie) % Update the movie pop-up menu in the main package GUI packageGUI('switchMovie_Callback',handles.popupmenu_movie, [], handles) userData = get(handles.figure1, 'UserData'); end % Clear icons of selected processes % Return user data !!! set(handles.figure1, 'UserData', userData) userfcn_drawIcon(handles,'clear',procRun{iMovie},'',true); % user data is retrieved, updated and submitted % Refresh user data !!! userData = get(handles.figure1, 'UserData'); % Disable 'Run' button % set(handles.pushbutton_run, 'Enable', 'off') % set(handles.checkbox_forcerun, 'Enable', 'off') % set(handles.checkbox_runall, 'Enable', 'off') set(handles.text_status, 'Visible', 'on') % Run algorithms! try % Return user data !!! set(handles.figure1, 'UserData', userData) for procID = procRun{iMovie} set(handles.text_status, 'String', ... sprintf('Step %d - Processing %d of %d movies total ...', procID, i, length(movieRun)) ) userfcn_runProc_dfs(procID, procRun{iMovie}, handles); % user data is retrieved, updated and submitted end catch ME % Save the error into movie Exception cell array ME2 = MException('lccb:run:error','Step %d: %s',... procID,userData.package(iMovie).processes_{procID}.getName); movieException{iMovie} = cat(2, movieException{iMovie}, ME2); movieException{iMovie}=movieException{iMovie}.addCause(ME); procRun{iMovie} = procRun{iMovie}(procRun{iMovie} < procID); end % Refresh user data !!! userData = get(handles.figure1, 'UserData'); set(handles.pushbutton_run, 'Enable', 'on') set(handles.checkbox_forcerun, 'Enable', 'on') set(handles.checkbox_runall, 'Enable', 'on') set(handles.text_status, 'Visible', 'off') % Return user data !!! set(handles.figure1, 'UserData', userData) end if strcmp(get(handles.menu_debug_enter,'Checked'),'on'), dbclear if caught error; end %% Post-processing exception report status = generateReport(movieException,userData,'postprocessing'); if status successMsg = 'Your movie(s) have been processed successfully.'; userData.iconHelpFig = helpdlg(successMsg, [userData.crtPackage.getName]); set(handles.figure1, 'UserData', userData) end % Delete waitbars hWaitbar = findall(0,'type','figure','tag','TMWWaitbar'); delete(hWaitbar); end function userfcn_runProc_dfs (procID, procRun, handles) % throws exception % Set user Data userData = get(handles.figure1, 'UserData'); parentRun = []; parentID=userData.crtPackage.getParent(procID); % if current process procID have dependency processes for j = parentID % if parent process is one of the processes need to be run % if parent process has already run successfully if any(j == procRun) && ~userData.crtPackage.processes_{j}.success_ parentRun = horzcat(parentRun,j); %#ok<AGROW> end end % if above assumptions are yes, recursively run parent process' dfs fcn for j = parentRun userfcn_runProc_dfs (j, procRun, handles) end try userData.crtPackage.processes_{procID}.run(); % throws exception catch ME rethrow(ME) end % Refresh wall status packageGUI_RefreshFcn(handles,'initialize'); end function status = generateReport(movieException,userData,reportType) % Generate report from movie exception cell array % Check exception status errorMovies = find(~cellfun(@isempty, movieException, 'UniformOutput', true)); status =1; if isempty(errorMovies), return; end status = 0; % Create log message basicLogMsg = cell(size(movieException)); extendedLogMsg = cell(size(movieException)); for i = errorMovies % Format movie log message if ~isempty(userData.MD), field = 'MD'; type = 'Movie'; else field = 'ML'; type = 'Movie list'; end basicLogMsg{i} = sprintf('%s %d - %s:\n\n', type, i, userData.(field)(i).getFullPath); extendedLogMsg{i}=basicLogMsg{i}; % Read exception message and add causes message if any for j = 1:length(movieException{i}) basicLogMsg{i} = [basicLogMsg{i} '--' ... movieException{i}(j).getReport('basic','hyperlinks','off') sprintf('\n')]; extendedLogMsg{i} = [extendedLogMsg{i} sprintf('-- %s\n\n', movieException{i}(j).message)]; if ~isempty(movieException{i}(j).cause) basicLogMsg{i} = [basicLogMsg{i},sprintf('\nCaused by:\n%s\n',... movieException{i}(j).cause{1}.getReport('basic','hyperlinks','off'))]; extendedLogMsg{i} = [extendedLogMsg{i},... movieException{i}(j).cause{1}.getReport('extended','hyperlinks','off')]; end end basicLogMsg{i}=sprintf('%s\n',basicLogMsg{i}); extendedLogMsg{i}=sprintf('%s\n',extendedLogMsg{i}); end % Add report information if strcmpi(reportType,'preprocessing'), additionalText=['Please solve the above problems before continuing.'... '\n\nThe movie(s) could not be processed.']; elseif strcmpi(reportType,'postprocessing'), additionalText=... ['Please verify your settings are correct. '... 'Feel free to contact us if you have question regarding this error.'... '\n\nPlease help us improve the software by clearly reporting the '... 'scenario when this error occurs, and the above error information '... 'to us (error information is also displayed in Matlab command line).'... '\n\nFor contact information please refer to the following URL:'... '\nhttp://lccb.hms.harvard.edu/software.html']; end % Display general MATLAB installation information as a header % Copied from ver.m % find platform OS if ispc platform = [system_dependent('getos'),' ',system_dependent('getwinsys')]; elseif ismac [fail, input] = unix('sw_vers'); if ~fail platform = strrep(input, 'ProductName:', ''); platform = strrep(platform, sprintf('\t'), ''); platform = strrep(platform, sprintf('\n'), ' '); platform = strrep(platform, 'ProductVersion:', ' Version: '); platform = strrep(platform, 'BuildVersion:', 'Build: '); else platform = system_dependent('getos'); end else platform = system_dependent('getos'); end % display platform type matlabInfo = sprintf(['MATLAB Version %s\nMATLAB License Number: %s\n'... 'Operating System: %s\nJava VM Version: %s\n'],... version,license,platform,char(strread(version('-java'),'%s',1,'delimiter','\n'))); %#ok<REMFF1> basicReport = [basicLogMsg{:}, sprintf(additionalText)]; extendedReport =[matlabInfo, extendedLogMsg{:}, sprintf(additionalText)]; % Create title title='The processing of following movie(s)'; if strcmpi(type,'preprocessing'), title=[title ' could not be continued:']; elseif strcmpi(type,'postprocessing'), title=[title ' was terminated by run time error:']; end % Check messagebox existence and generate report using msgboxGUI if isfield(userData, 'msgboxGUI') && ishandle(userData.msgboxGUI) delete(userData.msgboxGUI) end if isequal(basicReport,extendedReport) userData.msgboxGUI = msgboxGUI('title',title,'text', basicReport,... 'name','Error report'); else userData.msgboxGUI = msgboxGUI('title',title,'text', basicReport,... 'extendedText',extendedReport,'name','Error report'); end end
github
mehta-lab/Instantaneous-PolScope-master
abstractProcessGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/abstractProcessGUI.m
6,409
utf_8
3a28b0e14f1fe7bd34e4ae1cd28a936c
function varargout = abstractProcessGUI(varargin) %ABSTRACTPROCESSGUI M-file for abstractProcessGUI.fig % ABSTRACTPROCESSGUI, by itself, creates a new ABSTRACTPROCESSGUI or raises the existing % singleton*. % % H = ABSTRACTPROCESSGUI returns the handle to a new ABSTRACTPROCESSGUI or the handle to % the existing singleton*. % % ABSTRACTPROCESSGUI('Property','Value',...) creates a new ABSTRACTPROCESSGUI using the % given property value pairs. Unrecognized properties are passed via % varargin to abstractProcessGUI_OpeningFcn. This calling syntax produces a % warning when there is an existing singleton*. % % ABSTRACTPROCESSGUI('CALLBACK') and ABSTRACTPROCESSGUI('CALLBACK',hObject,...) call the % local function named CALLBACK in ABSTRACTPROCESSGUI.M with the given input % arguments. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help abstractProcessGUI % Last Modified by GUIDE v2.5 09-Jul-2012 10:49:16 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @abstractProcessGUI_OpeningFcn, ... 'gui_OutputFcn', @abstractProcessGUI_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 abstractProcessGUI is made visible. function abstractProcessGUI_OpeningFcn(hObject, eventdata, handles, varargin) processGUI_OpeningFcn(hObject, eventdata, handles, varargin{:}) % Get current package and process userData = get(handles.figure1, 'UserData'); procName = eval([userData.crtProcClassName '.getName()']); set(handles.uipanel_methods, 'Title', [procName ' methods']); set(handles.text_methods, 'String', ['Choose a ' lower(procName) ' method']); % Get current process constructer, set-up GUIs and mask refinement process % constructor userData.subProcClassNames = eval([userData.crtProcClassName '.getConcreteClasses()']); validClasses = cellfun(@(x)exist(x,'class')==8,userData.subProcClassNames); userData.subProcClassNames = userData.subProcClassNames(validClasses); userData.subProcConstr = cellfun(@(x) str2func(x),userData.subProcClassNames,'Unif',0); userData.subProcGUI = cellfun(@(x) eval([x '.GUI']),userData.subProcClassNames,'Unif',0); subProcNames = cellfun(@(x) eval([x '.getName']),userData.subProcClassNames,'Unif',0); popupMenuProcName = vertcat(subProcNames,{['Choose a ' lower(procName) ' method']}); % Set up input channel list box if isempty(userData.crtProc) value = numel(userData.subProcClassNames)+1; set(handles.pushbutton_set, 'Enable', 'off'); else value = find(strcmp(userData.crtProc.getName,subProcNames)); end existSubProc = @(proc) any(cellfun(@(x) isa(x,proc),userData.MD.processes_)); for i=find(cellfun(existSubProc,userData.subProcClassNames')) popupMenuProcName{i} = ['<html><b>' popupMenuProcName{i} '</b></html>']; end set(handles.popupmenu_methods, 'String', popupMenuProcName,... 'Value',value) % Choose default command line output for abstractProcessGUI handles.output = hObject; % Update user data and GUI data set(hObject, 'UserData', userData); guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = abstractProcessGUI_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 pushbutton_cancel. function pushbutton_cancel_Callback(hObject, eventdata, handles) % Delete figure delete(handles.figure1); % --- Executes on selection change in popupmenu_methods. function popupmenu_methods_Callback(hObject, eventdata, handles) % hObject handle to popupmenu_methods (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_methods contents as cell array % contents{get(hObject,'Value')} returns selected item from popupmenu_methods content = get(hObject, 'string'); if get(hObject, 'Value') == length(content) set(handles.pushbutton_set, 'Enable', 'off') else set(handles.pushbutton_set, 'Enable', 'on') end % --- Executes on button press in pushbutton_set. function pushbutton_set_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); segProcID = get(handles.popupmenu_methods, 'Value'); subProcGUI =userData.subProcGUI{segProcID}; subProcGUI('mainFig',userData.mainFig,userData.procID,... 'procConstr',userData.subProcConstr{segProcID},... 'procClassName',userData.subProcClassNames{segProcID}); delete(handles.figure1); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); delete(userData.helpFig(ishandle(userData.helpFig))); set(handles.figure1, 'UserData', userData); guidata(hObject,handles);
github
mehta-lab/Instantaneous-PolScope-master
naFromLensID.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/naFromLensID.m
3,457
utf_8
f4c3286efd85be69065b29f69e0ffebc
function [NA,mag] = naFromLensID(lensID,ask) %NAFROMLENSID is a lookup table to find the NA for a given lensID % % SYNOPSIS [NA,mag] = naFromLensID(lensID,ask) % % INPUT lensID : ID of the lens according to deltaVision % ask : Whether or not to ask for lensID if not found in list % Default: 1 % % OUTPUT NA : numerical aperture of the specified lens % mag : magnification of the lens % % REMARKS After the program asks for a lensID, it will write it into the % .m-file. Alternatively, you can write it into the list at the % end of the code yourself. % % c: 8/05 jonas %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % TEST INPUT if nargin == 0 error('not enough input arguments') end if nargin < 2 || isempty(ask) ask = 1; end NA = NaN; mag = NaN; % LOOKUP LENSID lensIDList = lookupLensIDs; lensIdx = find(lensIDList(:,1) == lensID); % assign NA and mag if possible if ~isempty(lensIdx) % use most recent version NA = lensIDList(lensIdx(end),2); mag = lensIDList(lensIdx(end),3); end % check whether we have all the output we need if ~isnan(NA) && (~isnan(mag) || nargout < 2) % all is fine elseif ask % if not good, check whether we can ask for input. Use what we have for % defaults answ = inputdlg(... {sprintf('Please input NA of lens %i',lensID),... sprintf('Please input magnification of lens %i',lensID)},... 'Manual NA',1,... {num2str(NA),num2str(mag)}); if ~isempty(answ) NA = str2double(answ{1}); mag = str2double(answ{2}); end % write to file file = which('naFromLensID.m'); mFile = textread(file,'%s',... 'delimiter','\n','whitespace',''); % now add a line just befor the last line newLine = sprintf('%6i, %1.2f,%4i;...',lensID,NA,mag); mFile{end+1} = mFile{end}; mFile{end-1} = newLine; % finally, write the mFile fid = fopen(file,'w'); for i=1:length(mFile) fprintf(fid,'%s\n',mFile{i}); end fclose(fid); else % simply return the default (NaN) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function lensID = lookupLensIDs % add lensIDs, NAs and mags by adding a line like: % '9999, 1.25, 60;...' % into the table below. Do not add any lines after the % closing of the table '];' lensID = ... [10002, 1.40, 100;... 10006, 1.40, 100;... 10612, 1.42, 60;... 12003, 1.40, 100;... 0, 1.40, NaN;... 10005, 1.35, NaN;... 10105, 1.40, NaN;... 10403, 1.35, NaN;... 10003, 1.35, NaN;... 12005, NaN, NaN;... 10007, 1.40, 100;... 99999, 1.4, 100;... 10211, 1.40, 100;... 10602, 1.40, 60;... ];
github
mehta-lab/Instantaneous-PolScope-master
kineticAnalysisProcessGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/kineticAnalysisProcessGUI.m
6,620
utf_8
f2ebaf86cf423d3507559c4d3066c031
function varargout = kineticAnalysisProcessGUI(varargin) % kineticAnalysisProcessGUI M-file for kineticAnalysisProcessGUI.fig % kineticAnalysisProcessGUI, by itself, creates a new kineticAnalysisProcessGUI or raises the existing % singleton*. % % H = kineticAnalysisProcessGUI returns the handle to a new kineticAnalysisProcessGUI or the handle to % the existing singleton*. % % kineticAnalysisProcessGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in kineticAnalysisProcessGUI.M with the given input arguments. % % kineticAnalysisProcessGUI('Property','Value',...) creates a new kineticAnalysisProcessGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before kineticAnalysisProcessGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to kineticAnalysisProcessGUI_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 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help kineticAnalysisProcessGUI % Last Modified by GUIDE v2.5 19-Jul-2011 09:02:23 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @kineticAnalysisProcessGUI_OpeningFcn, ... 'gui_OutputFcn', @kineticAnalysisProcessGUI_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 kineticAnalysisProcessGUI is made visible. function kineticAnalysisProcessGUI_OpeningFcn(hObject, eventdata, handles, varargin) processGUI_OpeningFcn(hObject, eventdata, handles, varargin{:},... 'initChannel',1); % ---------------------- Parameter Setup ------------------------- userData = get(handles.figure1, 'UserData'); funParams = userData.crtProc.funParams_; try set(handles.edit_alpha,'String',userData.crtPackage.processes_{4}.funParams_.alpha); catch ME set(handles.edit_alpha,'String','NA'); end set(handles.popupmenu_bleachRed,'Value',... floor(funParams.bleachRed/7.2500e-05)+1); set(handles.edit_sigma,'String',funParams.sigma); set(handles.edit_timeWindow,'String',funParams.timeWindow); % ---------------------------------------------------------------- % Choose default command line output for kineticAnalysisProcessGUI handles.output = hObject; % Update user data and GUI data set(hObject, 'UserData', userData); guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = kineticAnalysisProcessGUI_OutputFcn(~, ~, 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 pushbutton_cancel. function pushbutton_cancel_Callback(~, ~, handles) % Delete figure delete(handles.figure1); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, ~, handles) % Notify the package GUI that the setting panel is closed userData = get(handles.figure1, 'UserData'); if isfield(userData, 'helpFig') && ishandle(userData.helpFig) delete(userData.helpFig) end if isfield(userData, 'previewFig') && ishandle(userData.previewFig) delete(userData.previewFig) end set(handles.figure1, 'UserData', userData); guidata(hObject,handles); % --- Executes on key press with focus on pushbutton_done and none of its controls. function pushbutton_done_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) % Call back function of 'Apply' button userData = get(handles.figure1, 'UserData'); % Check user input if isempty(get(handles.listbox_selectedChannels, 'String')) errordlg('Please select at least one input channel from ''Available Channels''.','Setting Error','modal') return; end timeWindow = str2double(get(handles.edit_timeWindow,'String')); if isnan(timeWindow) || timeWindow<=0 || timeWindow > userData.MD.nFrames_ || mod(timeWindow,2)==0 errordlg(sprintf('The time window should be an odd number between 0 and %g.',... userData.MD.nFrames_),'Setting Error','modal') return; end % Process Sanity check ( only check underlying data ) try userData.crtProc.sanityCheck; catch ME errordlg([ME.message 'Please double check your data.'],'Setting Error','modal'); return; end % Set parameter channelIndex = get(handles.listbox_selectedChannels, 'Userdata'); funParams.ChannelIndex = channelIndex; funParams.timeWindow = str2double(get(handles.edit_timeWindow,'String')); funParams.sigma = str2double(get(handles.edit_sigma,'String')); funParams.bleachRed = 7.2500e-05*(get(handles.popupmenu_bleachRed,'Value')-1); % Set parameters processGUI_ApplyFcn(hObject, eventdata, handles,funParams);
github
mehta-lab/Instantaneous-PolScope-master
packageGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/packageGUI.m
10,750
utf_8
42cfd7447b909a06314f77ffab3a1cdd
function varargout = packageGUI(varargin) % PACKAGEGUI M-file for packageGUI.fig % PACKAGEGUI, by itself, creates a new PACKAGEGUI or raises the existing % singleton*. % % H = PACKAGEGUI returns the handle to a new PACKAGEGUI or the handle to % the existing singleton*. % % PACKAGEGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in PACKAGEGUI.M with the given input arguments. % % PACKAGEGUI('Property','Value',...) creates a new PACKAGEGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before packageGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to packageGUI_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 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help packageGUI % Last Modified by GUIDE v2.5 03-Jun-2012 14:40:28 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @packageGUI_OpeningFcn, ... 'gui_OutputFcn', @packageGUI_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 % --- Outputs from this function are returned to the command line. function varargout = packageGUI_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; % In case the package GUI has been called without argument userData = get(handles.figure1, 'UserData'); if (isfield(userData,'startMovieSelectorGUI') && userData.startMovieSelectorGUI) movieSelectorGUI('packageName',userData.packageName,'MD',userData.MD,... 'ML', userData.ML); delete(handles.figure1) end % --- Executes on button press in pushbutton_status. function pushbutton_status_Callback(~, ~, handles) userData = get(handles.figure1, 'UserData'); % if movieDataGUI exist if isfield(userData, 'overviewFig') && ishandle(userData.overviewFig) delete(userData.overviewFig) end userData.overviewFig = movieDataGUI(userData.MD(userData.id)); set(handles.figure1, 'UserData', userData); % --- Executes on Save button press or File>Save function save_Callback(~, ~, handles) userData = get(handles.figure1, 'UserData'); set(handles.text_saveStatus, 'Visible', 'on') arrayfun(@save,userData.MD); pause(.3) set(handles.text_saveStatus, 'Visible', 'off') function switchMovie_Callback(hObject, ~, handles) userData = get(handles.figure1, 'UserData'); nMovies = length(userData.MD); switch get(hObject,'Tag') case 'pushbutton_left' newMovieId = userData.id - 1; case 'pushbutton_right' newMovieId = userData.id + 1; case 'popupmenu_movie' newMovieId = get(hObject, 'Value'); otherwise end if (newMovieId==userData.id), return; end % Save previous movie checkboxes userData.statusM(userData.id).Checked = userfcn_saveCheckbox(handles); % Set up new movie GUI parameters userData.id = mod(newMovieId-1,nMovies)+1; userData.crtPackage = userData.package(userData.id); set(handles.figure1, 'UserData', userData) set(handles.popupmenu_movie, 'Value', userData.id) % Set up GUI if userData.statusM(userData.id).Visited packageGUI_RefreshFcn(handles, 'refresh') else packageGUI_RefreshFcn(handles, 'initialize') end % --- Executes when user attempts to close figure1. function figure1_CloseRequestFcn(hObject, eventdata, handles) userData = get(handles.figure1,'Userdata'); if isfield(userData, 'MD') MD = userData.MD; else delete(handles.figure1); return; end saveRes = questdlg('Do you want to save the current progress?', ... 'Package Control Panel'); if strcmpi(saveRes,'yes'), arrayfun(@save,userData.MD); end if strcmpi(saveRes,'cancel'), return; end delete(handles.figure1); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); % Find all figures stored in userData and delete them if isempty(userData), return; end userDataFields=fieldnames(userData); isFig = ~cellfun(@isempty,regexp(userDataFields,'Fig$')); userDataFigs = userDataFields(isFig); for i=1:numel(userDataFigs) figHandles = userData.(userDataFigs{i}); validFigHandles = figHandles(ishandle(figHandles)&logical(figHandles)); delete(validFigHandles); end % msgboxGUI used for error reports if isfield(userData, 'msgboxGUI') && ishandle(userData.msgboxGUI) delete(userData.msgboxGUI) end % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(hObject, eventdata, handles) if strcmp(eventdata.Key, 'return') exit_Callback(handles.pushbutton_exit, [], handles); end if strcmp(eventdata.Key, 'leftarrow') switchMovie_Callback(handles.pushbutton_left, [], handles); end if strcmp(eventdata.Key, 'rightarrow') switchMovie_Callback(handles.pushbutton_right, [], handles); end % -------------------------------------------------------------------- function menu_about_Callback(hObject, eventdata, handles) status = web(get(hObject,'UserData'), '-browser'); if status switch status case 1 msg = 'System default web browser is not found.'; case 2 msg = 'System default web browser is found but could not be launched.'; otherwise msg = 'Fail to open browser for unknown reason.'; end warndlg(msg,'Fail to open browser','modal'); end % -------------------------------------------------------------------- function menu_file_open_Callback(~, ~, handles) % Call back function of 'New' in menu bar userData = get(handles.figure1,'Userdata'); % if ~isempty(userData.MD), field = 'MD'; else field = 'ML'; end % arrayfun(@(x) x.save,userData.(field)); movieSelectorGUI('packageName',userData.packageName,... 'MD', userData.MD, 'ML', userData.ML); delete(handles.figure1) % -------------------------------------------------------------------- function exit_Callback(~, ~, handles) delete(handles.figure1); % --- Executes on button press in pushbutton_show. function pushbutton_show_Callback(hObject, ~, handles) userData = get(handles.figure1, 'UserData'); prop=get(hObject,'Tag'); procID = str2double(prop(length('pushbutton_show_')+1:end)); if isfield(userData, 'resultFig') & ishandle(userData.resultFig) delete(userData.resultFig) end % Modifications should be added to the resultDisplay methods (should be % generic!!!!) if isa(userData.crtPackage,'UTrackPackage') % userData.resultFig = userData.crtPackage.processes_{procID}.resultDisplay(handles.figure1,procID); % Above line commented by Shalin Aug 16, 2015. userData.resultFig = userData.crtPackage.processes_{procID}.resultDisplay(); else userData.resultFig = userData.crtPackage.processes_{procID}.resultDisplay(); end set(handles.figure1, 'UserData', userData); % --- Executes on button press in pushbutton_set. function pushbutton_set_Callback(hObject, ~, handles) userData = get(handles.figure1, 'UserData'); prop=get(hObject,'Tag'); procID = str2double(prop(length('pushbutton_set_')+1:end)); % Read GUI handle from the associated process static method crtProc=userData.crtPackage.getProcessClassNames{procID}; crtProcGUI =eval([crtProc '.GUI']); userData.setFig(procID) = crtProcGUI('mainFig',handles.figure1,procID); set(handles.figure1, 'UserData', userData); guidata(hObject,handles); % --- Executes on button press in checkbox. function checkbox_Callback(hObject, eventdata, handles) props=get(hObject,{'Value','Tag'}); procStatus=props{1}; procID = str2double(props{2}(length('checkbox_')+1:end)); userData=get(handles.figure1, 'UserData'); userData.statusM(userData.id).Checked(procID) = procStatus; set(handles.figure1, 'UserData', userData) userfcn_checkAllMovies(procID, procStatus, handles); userfcn_lampSwitch(procID, procStatus, handles); % -------------------------------------------------------------------- function menu_debug_enter_Callback(hObject, eventdata, handles) status = get(hObject,'Checked'); if strcmp(status,'on'), newstatus = 'off'; dbclear if caught error; else newstatus='on'; end set(hObject,'Checked',newstatus); % -------------------------------------------------------------------- function menu_debug_batchMode_Callback(hObject, eventdata, handles) status = get(hObject,'Checked'); if strcmp(status,'on'), newstatus = 'off'; else newstatus='on'; end set(hObject,'Checked',newstatus); % --- Executes on button press in pushbutton_open. function pushbutton_open_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); prop=get(hObject,'Tag'); procID = str2double(prop(length('pushbutton_show_')+1:end)); % Use the OS-specific command to open result in exploration window outputDir = userData.crtPackage.processes_{procID}.funParams_.OutputDirectory; if ispc winopen(outputDir); elseif ismac system(sprintf('open %s',regexptranslate('escape',outputDir))); else msgbox(sprintf('Results can be found under %s',regexptranslate('escape',outputDir))); % SB: Following command not working under Ubuntu (as well as gnome-open % & nautilus) % system(sprintf('xdg-open %s',regexptranslate('escape',outputDir))); end
github
mehta-lab/Instantaneous-PolScope-master
getGaussianPSFsigma.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/getGaussianPSFsigma.m
2,763
utf_8
aebaaeedecd4b414ab7081ad95d1de1d
% getGaussianPSFsigma returns the standard deviation of the Gaussian % approximation of an ideal PSF in pixel % % INPUTS NA : numerical aperture of the objective % M : magnification of the objective % pixelSize : physical pixel size of the CCD in [m] % lambda : emission maximum wavelength of the fluorophore in [m] % -or- fluorophore name % {'Display'} : Display PSF and its Gaussian approximation. Optional, default 'off'. % % Alternative input: p : parameter structure for PSF calculations (see vectorialPSF.cpp). % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Francois Aguet, October 2010 (Last modified April 6 2011) function sigma = getGaussianPSFsigma(NA, M, pixelSize, lambda, varargin) ip = inputParser; ip.CaseSensitive = false; ip.addRequired('NA', @isscalar); ip.addRequired('M', @isscalar); ip.addRequired('pixelSize', @isscalar); ip.addRequired('lambda', @(x) ischar(x) | isscalar(x)) ip.addParamValue('Display', 'off', @(x) strcmpi(x, 'on') | strcmpi(x, 'off')); ip.parse(NA, M, pixelSize, lambda, varargin{:}); if ischar(lambda) lambda = name2wavelength(lambda); end % Defaults use values corresponding to optimal imaging conditions p.ti0 = 0; % working distance has no effect under ideal conditions p.ni0 = 1.518; p.ni = 1.518; p.tg0 = 0.17e-3; p.tg = 0.17e-3; p.ng0 = 1.515; p.ng = 1.515; p.ns = 1.33; p.lambda = lambda; p.M = M; p.NA = NA; p.alpha = asin(p.NA/p.ni); p.pixelSize = pixelSize; ru = 8; psf = vectorialPSF(0,0,0,0,ru,p); [pG, ~, ~, res] = fitGaussian2D(psf, [0 0 max(psf(:)) 1 0], 'As'); sigma = pG(4); %=============== % Display %=============== if strcmpi(ip.Results.Display, 'on') xa = (-ru+1:ru-1)*p.pixelSize/p.M*1e9; figure; subplot(1,2,1); imagesc(xa,xa,psf); colormap(gray(256)); axis image; colorbar; title('PSF'); xlabel('x [nm]'); ylabel('y [nm]'); subplot(1,2,2); imagesc(xa,xa, psf+res.data); colormap(gray(256)); axis image; colorbar; title('Gaussian approximation'); xlabel('x [nm]'); ylabel('y [nm]'); linkaxes; end
github
mehta-lab/Instantaneous-PolScope-master
addMovieROIGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/addMovieROIGUI.m
11,121
utf_8
3ee82ad3e76273b9b28c52ff1a12b064
function varargout = addMovieROIGUI(varargin) % addMovieROIGUI M-file for addMovieROIGUI.fig % addMovieROIGUI, by itself, creates a new addMovieROIGUI or raises the existing % singleton*. % % H = addMovieROIGUI returns the handle to a new addMovieROIGUI or the handle to % the existing singleton*. % % addMovieROIGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in addMovieROIGUI.M with the given input arguments. % % addMovieROIGUI('Property','Value',...) creates a new addMovieROIGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before addMovieROIGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to addMovieROIGUI_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 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help addMovieROIGUI % Last Modified by GUIDE v2.5 07-Feb-2012 15:54:14 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @addMovieROIGUI_OpeningFcn, ... 'gui_OutputFcn', @addMovieROIGUI_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 addMovieROIGUI is made visible. function addMovieROIGUI_OpeningFcn(hObject,eventdata,handles,varargin) % Check input % The mainFig and procID should always be present % procCOnstr and procName should only be present if the concrete process % initation is delegated from an abstract class. Else the constructor will % be directly read from the package constructor list. ip = inputParser; ip.addRequired('hObject',@ishandle); ip.addRequired('eventdata',@(x) isstruct(x) || isempty(x)); ip.addRequired('handles',@isstruct); ip.addOptional('MD',[],@(x)isa(x,'MovieData')); ip.addParamValue('mainFig',-1,@ishandle); ip.parse(hObject,eventdata,handles,varargin{:}); userData.MD =ip.Results.MD; userData.mainFig =ip.Results.mainFig; % Set up copyright statement set(handles.text_copyright, 'String',userfcn_softwareConfig(handles)); % Set up available input channels set(handles.listbox_selectedChannels,'String',userData.MD.getChannelPaths(), ... 'UserData',1:numel(userData.MD.channels_)); % Save the image directories and names (for cropping preview) userData.nFrames = userData.MD.nFrames_; userData.imPolyHandle.isvalid=0; m=userData.MD.imSize_(2); n=userData.MD.imSize_(1); userData.ROI = [1 1; m 1; m n; 1 n;]; userData.previewFig=-1; userData.helpFig=-1; % Read the first image and update the sliders max value and steps userData.chanIndex = 1; set(handles.edit_frameNumber,'String',1); set(handles.slider_frameNumber,'Min',1,'Value',1,'Max',userData.nFrames,... 'SliderStep',[1/max(1,double(userData.nFrames-1)) 10/max(1,double(userData.nFrames-1))]); userData.imIndx=1; userData.imData=mat2gray(userData.MD.channels_(userData.chanIndex).loadImage(userData.imIndx)); set(handles.listbox_selectedChannels,'Callback',@(h,event) update_data(h,event,guidata(h))); % Choose default command line output for addMovieROIGUI handles.output = hObject; % Update user data and GUI data set(hObject, 'UserData', userData); guidata(hObject, handles); update_data(hObject,eventdata,handles); % --- Outputs from this function are returned to the command line. function varargout = addMovieROIGUI_OutputFcn(~, ~, 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 pushbutton_cancel. function pushbutton_cancel_Callback(~, ~, handles) % Delete figure delete(handles.figure1); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, ~, handles) % Notify the package GUI that the setting panel is closed userData = get(handles.figure1, 'UserData'); if ishandle(userData.helpFig), delete(userData.helpFig); end if ishandle(userData.previewFig), delete(userData.previewFig); end set(handles.figure1, 'UserData', userData); guidata(hObject,handles); % --- Executes on key press with focus on pushbutton_addROI and none of its controls. function pushbutton_addROI_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_addROI, [], handles); end % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_addROI, [], handles); end % --- Executes on button press in checkbox_preview. function update_data(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); % Retrieve the channel index props=get(handles.listbox_selectedChannels,{'UserData','Value'}); chanIndex = props{1}(props{2}); imIndx = get(handles.slider_frameNumber,'Value'); % Load a new image if either the image number or the channel has been changed if (chanIndex~=userData.chanIndex) || (imIndx~=userData.imIndx) % Update image flag and dat userData.imData=mat2gray(userData.MD.channels_(chanIndex).loadImage(imIndx)); userData.updateImage=1; userData.chanIndex=chanIndex; userData.imIndx=imIndx; % Update roi if userData.imPolyHandle.isvalid userData.ROI=getPosition(userData.imPolyHandle); end else userData.updateImage=0; end % Create figure if non-existing or closed if ~isfield(userData, 'previewFig') || ~ishandle(userData.previewFig) userData.previewFig = figure('NumberTitle','off','Name',... 'Select the region of interest','DeleteFcn',@close_previewFig,... 'UserData',handles.figure1); axes('Position',[.05 .05 .9 .9]); userData.newFigure = 1; else figure(userData.previewFig); userData.newFigure = 0; end % Retrieve the image object handle imHandle =findobj(userData.previewFig,'Type','image'); if userData.newFigure || userData.updateImage if isempty(imHandle) imHandle=imshow(userData.imData); axis off; else set(imHandle,'CData',userData.imData); end end if userData.imPolyHandle.isvalid % Update the imPoly position setPosition(userData.imPolyHandle,userData.ROI) else % Create a new imPoly object and store the handle userData.imPolyHandle = impoly(get(imHandle,'Parent'),userData.ROI); fcn = makeConstrainToRectFcn('impoly',get(imHandle,'XData'),get(imHandle,'YData')); setPositionConstraintFcn(userData.imPolyHandle,fcn); end set(handles.figure1, 'UserData', userData); guidata(hObject,handles); function close_previewFig(hObject, eventdata) handles = guidata(get(hObject,'UserData')); userData=get(handles.figure1,'UserData'); userData.ROI=getPosition(userData.imPolyHandle); set(handles.figure1,'UserData',userData); update_data(hObject, eventdata, handles); % --- Executes on slider movement. function frameNumberEdition_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); % Retrieve the value of the selected image if strcmp(get(hObject,'Tag'),'edit_frameNumber') frameNumber = str2double(get(handles.edit_frameNumber, 'String')); else frameNumber = get(handles.slider_frameNumber, 'Value'); end frameNumber=round(frameNumber); % Check the validity of the frame values if isnan(frameNumber) warndlg('Please provide a valid frame value.','Setting Error','modal'); end frameNumber = min(max(frameNumber,1),userData.nFrames); % Store value set(handles.slider_frameNumber,'Value',frameNumber); set(handles.edit_frameNumber,'String',frameNumber); % Save data and update graphics set(handles.figure1, 'UserData', userData); guidata(hObject, handles); update_data(hObject,eventdata,handles); % --- Executes on button press in pushbutton_outputDirectory. function pushbutton_outputDirectory_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); pathname = uigetdir(userData.MD.movieDataPath_,'Select output directory'); % Test uigetdir output and store its results if isequal(pathname,0), return; end set(handles.edit_outputDirectory,'String',pathname); % Save data set(handles.figure1,'UserData',userData); guidata(hObject, handles); % --- Executes on button press in pushbutton_addROI. function pushbutton_addROI_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); % Check valid output directory outputDirectory = get(handles.edit_outputDirectory,'String'); if isempty(outputDirectory), errordlg('Please select an output directory','Error','modal'); return; end % Read ROI if crop window is still visible if userData.imPolyHandle.isvalid userData.ROI=getPosition(userData.imPolyHandle); set(handles.figure1,'UserData',userData); end update_data(hObject,eventdata,handles); % Create ROI mask and save it in the outputDirectory userData = get(handles.figure1, 'UserData'); mask=createMask(userData.imPolyHandle); maskPath = fullfile(outputDirectory,'roiMask.tif'); imwrite(mask,maskPath); % Create a new region of interest and save the object userData.MD.addROI(maskPath,outputDirectory); movieROI=userData.MD.rois_(end); movieROI.save; % If called from movieSelectorGUI if userData.mainFig ~=-1, % Retrieve main window userData userData_main = get(userData.mainFig, 'UserData'); % Append new ROI to movie selector panel userData_main.MD = cat(2, userData_main.MD, movieROI); set(userData.mainFig, 'UserData', userData_main) movieSelectorGUI('refreshDisplay',userData.mainFig,... eventdata,guidata(userData.mainFig)); end % Delete current window delete(handles.figure1)
github
mehta-lab/Instantaneous-PolScope-master
packageGUI_OpeningFcn.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/packageGUI_OpeningFcn.m
13,491
utf_8
fdc2c582da0d11e09581745185284f0d
function packageGUI_OpeningFcn(hObject,eventdata,handles,packageName,varargin) % Callback called at the opening of packageGUI % % packageGUI_OpeningFcn(packageName,MD) MD: MovieData object % % Useful tools % % User Data: % % userData.MD - array of MovieData object % userData.MD - array of MovieList object % userData.package - array of package (same length with userData.MD) % userData.crtPackage - the package of current MD % userData.id - the id of current MD on board % % userData.dependM - dependency matrix % userdata.statusM - GUI status matrix % userData.optProcID - optional process ID % userData.applytoall - array of boolean for batch movie set up % % userData.passIconData - pass icon image data % userData.errorIconData - error icon image data % userData.warnIconData - warning icon image data % userData.questIconData - help icon image data % userData.colormap - color map % % userData.setFig - array of handles of (multiple) setting figures (may not exist) % userData.resultFig - array of handles of (multiple) result figures (may not exist) % userData.packageHelpFig - handle of (single) help figure (may not exist) % userData.iconHelpFig - handle of (single) help figures (may not exist) % userData.statusFig - handle of (multiple) status figures (may not exist) % userData.processHelpFig - handle of (multiple) help figures (may not exist) % % % NOTE: % % userData.statusM - 1 x m stucture array, m is the number of Movie Data % this user data is used to save the status of movies % when GUI is switching between different movie(s) % % fields: IconType - the type of status icons, 'pass', 'warn', 'error' % Msg - the message displayed when clicking status icons % Checked - 1 x n logical array, n is the number of processes % used to save value of check box of each process % Visited - logical true or false, if the movie has been % loaded to GUI before % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Sebastien Besson May 2011 (last modified Sep 2011() % Input check ip = inputParser; ip.addRequired('hObject',@ishandle); ip.addRequired('eventdata',@(x) isstruct(x) || isempty(x)); ip.addRequired('handles',@isstruct); ip.addRequired('packageName',@ischar); ip.addOptional('MO',[],@(x) isa(x,'MovieObject')); ip.addParamValue('MD',[],@(x) isempty(x) || isa(x,'MovieData')); ip.addParamValue('ML',[],@(x) isempty(x) || isa(x,'MovieList')); ip.addParamValue('packageConstr','',@(x) isa(x,'function_handle')); ip.parse(hObject,eventdata,handles,packageName,varargin{:}); % Read the package name packageName = ip.Results.packageName; assert(any(strcmp(superclasses(packageName),'Package')),... sprintf('%s is not a valid Package',packageName)); handles.output = hObject; userData = get(handles.figure1,'UserData'); userData.packageName = packageName; userData.MD = ip.Results.MD; userData.ML = ip.Results.ML; %If package GUI supplied without argument, saves a boolean which will be %read by packageNameGUI_OutputFcn if isempty(ip.Results.MO) userData.startMovieSelectorGUI=true; set(handles.figure1,'UserData',userData); guidata(hObject, handles); return end if isa(ip.Results.MO,'MovieList') userData.ML = ip.Results.MO; set(handles.pushbutton_status,'Enable','off'); else userData.MD=ip.Results.MO; end % Call package GUI error [copyright openHelpFile] = userfcn_softwareConfig(handles); set(handles.text_copyright, 'String', copyright); % Singleton control try assert(~userData.init) catch ME if strcmpi(ME.identifier,'MATLAB:nonExistentField'); userData.init=true; else return end end % ----------------------------- Load MovieData ---------------------------- nMovies = numel(ip.Results.MO); packageIndx = cell(1, nMovies); % I. Before loading MovieData, firstly check if the current package exists for i = 1:nMovies % Check for existing packages and create them if false packageIndx{i} = ip.Results.MO(i).getPackageIndex(packageName,1,false); end for i = find(~cellfun(@isempty, packageIndx)) userData.package(i) = ip.Results.MO(i).packages_{packageIndx{i}}; end if any(cellfun(@isempty, packageIndx)) % Get the adapted constructor if ~isempty(ip.Results.packageConstr), packageConstr = ip.Results.packageConstr; elseif isConcreteClass(userData.packageName) packageConstr = str2func(userData.packageName); else % Launch interface to determine constructor concretePackages = eval([userData.packageName '.getConcretePackages()']); [selection, status] = listdlg('Name','',... 'PromptString',{'Select the type of object';'you want to track:'},... 'ListString', {concretePackages.name},'SelectionMode','single'); if ~status, userData.startMovieSelectorGUI=true; set(handles.figure1,'UserData',userData); guidata(hObject, handles); return end packageConstr = concretePackages(selection).packageConstr; end % Add package to movie for i = find(cellfun(@isempty, packageIndx)) ip.Results.MO(i).addPackage(packageConstr(ip.Results.MO(i),... ip.Results.MO(i).outputDirectory_)); userData.package(i) = ip.Results.MO(i).packages_{end}; end end % Run sanity check to check basic dependencies are satisfied for i = 1:nMovies try userData.package(i).sanityCheck(true,'all'); catch ME errordlg(ME.message,'Package initialization','modal'); userData.startMovieSelectorGUI=true; set(handles.figure1,'UserData',userData); guidata(hObject, handles); return end end % ------------- Check if existing processes can be recycled --------------- recyclableProc = cell(1, nMovies); processClassNames = userData.package(1).getProcessClassNames; % Multiple movies loop for i = 1:nMovies if isempty(packageIndx{i}) && ~isempty(ip.Results.MO(i).processes_) recyclableProcIndx = cellfun(@(x) cellfun(@(y)isa(y,x),... ip.Results.MO(i).processes_),processClassNames,'UniformOutput',false); recyclableProc{i}=ip.Results.MO(i).processes_(any(vertcat(recyclableProcIndx{:}),1)); end end recyclableProcMovie = find(~cellfun(@isempty, recyclableProc)); if ~isempty(recyclableProcMovie) % Ask user if to recycle msg = ['Record indicates that existing processes are recyclable for %s package:'... '\n\nDo you want to load and re-use these steps?']; user_response = questdlg(sprintf(msg,userData.package(1).getName),... 'Recycle Existing Steps','No','Yes','Yes'); if strcmpi(user_response,'Yes') for i = recyclableProcMovie recycleProcessGUI(recyclableProc{i}, userData.package(i),'mainFig', handles.figure1) end end end % Initialize userdata userData.id = 1; userData.crtPackage = userData.package(userData.id); userData.dependM = userData.package(userData.id).getDependencyMatrix; userData.optProcID =find(sum(userData.dependM==2,1)); nProc = size(userData.dependM, 1); userData.statusM = repmat( struct('IconType', {cell(1,nProc)}, 'Msg', {cell(1,nProc)}, 'Checked', zeros(1,nProc), 'Visited', false), 1, nMovies); % -----------------------Load and set up icons---------------------------- % Load icon images from dialogicons.mat userData = loadLCCBIcons(userData); % Set figure colormap supermap(1,:) = get(hObject,'color'); set(hObject,'colormap',supermap); userData.colormap = supermap; % Set up package help. set(handles.figure1,'CurrentAxes',handles.axes_help); Img = image(userData.questIconData); set(gca, 'XLim',get(Img,'XData'),'YLim',get(Img,'YData'),... 'visible','off','YDir','reverse'); set(Img,'ButtonDownFcn',@icon_ButtonDownFcn); if openHelpFile set(Img, 'UserData', struct('class', packageName)) end % --------------------------Set up processes------------------------------ % List of template process uicontrols to expand templateTag{1} = 'checkbox'; templateTag{2} = 'axes_icon'; templateTag{3} = 'pushbutton_show'; templateTag{4} = 'pushbutton_set'; templateTag{5} = 'axes_prochelp'; templateTag{6} = 'pushbutton_open'; set(handles.(templateTag{6}),'CData',userData.openIconData); % templateTag{6} = 'pushbutton_clear'; To be implemented someday? procTag=templateTag; set(handles.figure1,'Position',... get(handles.figure1,'Position')+(nProc-1)*[0 0 0 40]) set(handles.panel_movie,'Position',... get(handles.panel_movie,'Position')+(nProc-1)*[0 40 0 0]) set(handles.panel_proc,'Position',... get(handles.panel_proc,'Position')+(nProc-1)*[0 0 0 40]) set(handles.text_status, 'Position',... get(handles.text_status,'Position')+(nProc-1)*[0 40 0 0]) for i = 1:nProc for j=1:length(templateTag) procTag{j}=[templateTag{j} '_' num2str(i)]; handles.(procTag{j}) = copyobj(handles.(templateTag{j}),handles.panel_proc); set(handles.(procTag{j}),'Tag',procTag{j},'Position',... get(handles.(templateTag{j}),'Position')+(nProc-i)*[0 40 0 0]); end processClassName = userData.crtPackage.getProcessClassNames{i}; processName=eval([processClassName '.getName']); checkboxString = [' Step ' num2str(i) ': ' processName]; set(handles.(procTag{1}),'String',checkboxString) set(handles.figure1,'CurrentAxes',handles.(procTag{5})); Img = image(userData.smallquestIconData); set(gca, 'XLim',get(Img,'XData'),'YLim',get(Img,'YData'),... 'visible','off','YDir','reverse'); set(Img,'ButtonDownFcn',@icon_ButtonDownFcn); if openHelpFile set(Img, 'UserData', struct('class', processClassName)) end end cellfun(@(x)delete(handles.(x)),templateTag) handles = rmfield(handles,templateTag); optTag = 'text_optional'; for i = userData.optProcID procOptTag=[optTag '_' num2str(i)]; handles.(procOptTag) = copyobj(handles.(optTag),handles.panel_proc); set(handles.(procOptTag),'Tag',procOptTag,'Position',... get(handles.(optTag),'Position')+(nProc-i)*[0 40 0 0]); end delete(handles.(optTag)); handles = rmfield(handles,optTag); % --------------------------Create tools menu----------------------------- if ~isempty(userData.crtPackage.getTools) handles.menu_tools = uimenu(handles.figure1,'Label','Tools','Position',2); for i=1:length(userData.crtPackage.getTools) toolMenuTag=['menu_tools_' num2str(i)]; handles.(toolMenuTag) = uimenu(handles.menu_tools,... 'Label',userData.crtPackage.getTools(i).name,... 'Callback',@(h,event)menu_tools_Callback(h),'Tag',toolMenuTag); end end % --------------------------Other GUI settings----------------------------- % set titles set(handles.figure1, 'Name',['Control Panel - ' userData.crtPackage.getName]); set(handles.text_packageName,'String',userData.crtPackage.getName); % Set movie explorer msg = {}; if isa(ip.Results.MO,'MovieData'), movieType = 'Movie'; else movieType = 'Movie list'; end for i = 1: length(ip.Results.MO) msg = cat(2, msg, {sprintf(' %s %d of %d', movieType, i, length(ip.Results.MO))}); end set(handles.popupmenu_movie, 'String', msg, 'Value', userData.id); % Set option depen if length(ip.Results.MO) == 1 set(handles.checkbox_runall, 'Visible', 'off') set(handles.pushbutton_left, 'Enable', 'off') set(handles.pushbutton_right, 'Enable', 'off') set(handles.checkbox_all, 'Visible', 'off', 'Value', 0) userData.applytoall=zeros(nProc,1); else set(handles.checkbox_runall, 'Visible', 'on') userData.applytoall=ones(nProc,1); end set(handles.pushbutton_run, 'Callback', @(hObject,eventdata)packageGUI_RunFcn(hObject,eventdata,guidata(hObject))); % Set web links in menu set(handles.menu_about_gpl,'UserData','http://www.gnu.org/licenses/gpl.html') set(handles.menu_about_lccb,'UserData','http://lccb.hms.harvard.edu/') set(handles.menu_about_lccbsoftware,'UserData','http://lccb.hms.harvard.edu/software.html') % Update handles structure set(handles.figure1,'UserData',userData); guidata(hObject, handles); set(Img,'ButtonDownFcn',@icon_ButtonDownFcn); packageGUI_RefreshFcn(handles, 'initialize') end % -------------------------------------------------------------------- function menu_tools_Callback(hObject) handles =guidata(hObject); userData = get(handles.figure1, 'UserData'); prop=get(hObject,'Tag'); toolID = str2double(prop(length('menu_tools_')+1:end)); toolHandle=userData.crtPackage.getTools(toolID).funHandle; userData.toolFig(toolID) = toolHandle('mainFig',handles.figure1); set(handles.figure1, 'UserData', userData); end
github
mehta-lab/Instantaneous-PolScope-master
speckleTrackingProcessGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/speckleTrackingProcessGUI.m
7,441
utf_8
190b2d54085c54b30e00c5a6d5762040
function varargout = speckleTrackingProcessGUI(varargin) % speckleTrackingProcessGUI M-file for speckleTrackingProcessGUI.fig % speckleTrackingProcessGUI, by itself, creates a new speckleTrackingProcessGUI or raises the existing % singleton*. % % H = speckleTrackingProcessGUI returns the handle to a new speckleTrackingProcessGUI or the handle to % the existing singleton*. % % speckleTrackingProcessGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in speckleTrackingProcessGUI.M with the given input arguments. % % speckleTrackingProcessGUI('Property','Value',...) creates a new speckleTrackingProcessGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before speckleTrackingProcessGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to speckleTrackingProcessGUI_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 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help speckleTrackingProcessGUI % Last Modified by GUIDE v2.5 30-Sep-2011 21:01:04 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @speckleTrackingProcessGUI_OpeningFcn, ... 'gui_OutputFcn', @speckleTrackingProcessGUI_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 speckleTrackingProcessGUI is made visible. function speckleTrackingProcessGUI_OpeningFcn(hObject, eventdata, handles, varargin) processGUI_OpeningFcn(hObject, eventdata, handles, varargin{:},'initChannel',1); % ---------------------- Parameter Setup ------------------------- userData = get(handles.figure1, 'UserData'); funParams = userData.crtProc.funParams_; set(handles.edit_corrLength,'String',funParams.corrLength); set(handles.edit_corrLengthMicrons,'String',... funParams.corrLength*userData.MD.pixelSize_/1000); set(handles.edit_threshold,'String',funParams.threshold); set(handles.checkbox_enhanced,'Value',funParams.enhanced); % Enable interpolation methods only if flow tracking is set up if ~isempty(userData.crtPackage.processes_{5}); set(handles.popupmenu_interpolationMethod,'Enable','on'); else set(handles.popupmenu_interpolationMethod,'Enable','off'); % If neither flow tracking nor speckle tracking is set up if isempty(userData.crtPackage.processes_{6}); set(handles.checkbox_enhanced,'Value',1); end end % Load interpolation methods intMethods=SpeckleTrackingProcess.getInterpolationMethods; methodDescriptions = {intMethods(:).description}; methodNames = {intMethods(:).name}; try methodValue = find(strcmp(funParams.interpolationMethod,methodNames)); catch ME methodValue=1; end if isempty(methodValue), methodValue=1; end set(handles.popupmenu_interpolationMethod,'String',methodDescriptions,... 'UserData',methodNames,'Value',methodValue); % Choose default command line output for speckleTrackingProcessGUI handles.output = hObject; % Update user data and GUI data set(hObject, 'UserData', userData); guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = speckleTrackingProcessGUI_OutputFcn(~, ~, 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 pushbutton_cancel. function pushbutton_cancel_Callback(~, ~, handles) % Delete figure delete(handles.figure1); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, ~, handles) % Notify the package GUI that the setting panel is closed userData = get(handles.figure1, 'UserData'); if isfield(userData, 'helpFig') && ishandle(userData.helpFig) delete(userData.helpFig) end if isfield(userData, 'previewFig') && ishandle(userData.previewFig) delete(userData.previewFig) end set(handles.figure1, 'UserData', userData); guidata(hObject,handles); % --- Executes on key press with focus on pushbutton_done and none of its controls. function pushbutton_done_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) % Call back function of 'Apply' button % -------- Check user input -------- if isempty(get(handles.listbox_selectedChannels, 'String')) errordlg('Please select at least one input channel from ''Available Channels''.','Setting Error','modal') return; end % -------- Process Sanity check -------- % ( only check underlying data ) userData = get(handles.figure1, 'UserData'); try userData.crtProc.sanityCheck; catch ME errordlg([ME.message 'Please double check your data.'],... 'Setting Error','modal'); return; end % -------- Set parameter -------- channelIndex = get(handles.listbox_selectedChannels, 'Userdata'); funParams.ChannelIndex = channelIndex; funParams.corrLength =str2double(get(handles.edit_corrLength,'String')); funParams.threshold =str2double(get(handles.edit_threshold,'String')); funParams.enhanced =get(handles.checkbox_enhanced,'Value'); props = get(handles.popupmenu_interpolationMethod,{'UserData','Value'}); funParams.interpolationMethod = props{1}{props{2}}; processGUI_ApplyFcn(hObject, eventdata, handles,funParams); function edit_corrLength_Callback(hObject, eventdata, handles) userData=get(handles.figure1,'UserData'); value = str2double(get(handles.edit_corrLength,'String')); set(handles.edit_corrLengthMicrons,'String',value*userData.MD.pixelSize_/1000);
github
mehta-lab/Instantaneous-PolScope-master
noiseEstimationProcessGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/noiseEstimationProcessGUI.m
12,506
utf_8
6ef97ab21e7de79888eaa2a480673103
function varargout = noiseEstimationProcessGUI(varargin) % noiseEstimationProcessGUI M-file for noiseEstimationProcessGUI.fig % noiseEstimationProcessGUI, by itself, creates a new noiseEstimationProcessGUI or raises the existing % singleton*. % % H = noiseEstimationProcessGUI returns the handle to a new noiseEstimationProcessGUI or the handle to % the existing singleton*. % % noiseEstimationProcessGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in noiseEstimationProcessGUI.M with the given input arguments. % % noiseEstimationProcessGUI('Property','Value',...) creates a new noiseEstimationProcessGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before noiseEstimationProcessGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to noiseEstimationProcessGUI_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 % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help noiseEstimationProcessGUI % Last Modified by GUIDE v2.5 17-Jun-2011 11:12:38 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @noiseEstimationProcessGUI_OpeningFcn, ... 'gui_OutputFcn', @noiseEstimationProcessGUI_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 noiseEstimationProcessGUI is made visible. function noiseEstimationProcessGUI_OpeningFcn(hObject, eventdata, handles, varargin) processGUI_OpeningFcn(hObject, eventdata, handles, varargin{:},... 'initChannel',1); % Choose default command line output for noiseEstimationProcessGUI handles.output = hObject; % ---------------------- Channel Setup ------------------------- userData = get(handles.figure1, 'UserData'); funParams = userData.crtProc.funParams_; % Save the image directories and names (for cropping preview) userData.nFrames = userData.MD.nFrames_; userData.imRectHandle.isvalid=0; userData.firstImage = funParams.firstImage; userData.lastImage = funParams.lastImage; userData.cropROI = funParams.cropROI; userData.filterSigma = funParams.filterSigma; userData.previewFig=-1; % Read the first image and update the sliders max value and steps props = get(handles.listbox_selectedChannels, {'UserData','Value'}); userData.chanIndx = props{1}(props{2}); firstImage = userData.firstImage(userData.chanIndx); lastImage = userData.lastImage(userData.chanIndx); set(handles.edit_firstImage,'String',firstImage); set(handles.edit_lastImage,'String',lastImage); set(handles.edit_frameNumber,'String',firstImage); set(handles.slider_frameNumber,'Min',firstImage,'Value',firstImage,'Max',lastImage,... 'SliderStep',[1/double(lastImage-firstImage) 10/double(lastImage-firstImage)]); userData.imIndx=firstImage; userData.imData=userData.MD.channels_(userData.chanIndx).loadImage(userData.imIndx); set(handles.edit_filterSigma,'String',userData.filterSigma(userData.chanIndx)); % ---------------------------------------------------------------- % Update user data and GUI data set(hObject, 'UserData', userData); guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = noiseEstimationProcessGUI_OutputFcn(~, ~, 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 pushbutton_cancel. function pushbutton_cancel_Callback(~, ~, handles) % Delete figure delete(handles.figure1); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, ~, handles) % Notify the package GUI that the setting panel is closed userData = get(handles.figure1, 'UserData'); if isfield(userData, 'helpFig') && ishandle(userData.helpFig) delete(userData.helpFig) end if ishandle(userData.previewFig), delete(userData.previewFig); end set(handles.figure1, 'UserData', userData); guidata(hObject,handles); % --- Executes on key press with focus on pushbutton_done and none of its controls. function pushbutton_done_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end function close_previewFig(hObject, eventdata) handles = guidata(get(hObject,'UserData')); set(handles.checkbox_crop,'Value',0); update_data(handles.checkbox_crop, eventdata, handles); % --- Executes on button press in checkbox_crop. function update_data(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); % Retrieve the channel index props=get(handles.listbox_selectedChannels,{'UserData','Value'}); chanIndx = props{1}(props{2}); imIndx = get(handles.slider_frameNumber,'Value'); % If channel index has been modified, load new frame values if (chanIndx~=userData.chanIndx) set(handles.edit_filterSigma,'String',userData.filterSigma(userData.chanIndx)); firstImage = userData.firstImage(chanIndx); lastImage = userData.lastImage(chanIndx); set(handles.edit_firstImage,'String',firstImage); set(handles.edit_lastImage,'String',lastImage); set(handles.edit_frameNumber,'String',firstImage); set(handles.slider_frameNumber,'Min',firstImage,'Value',firstImage,'Max',lastImage,... 'SliderStep',[1/double(lastImage-firstImage) 10/double(lastImage-firstImage)]); end % Load a new image if either the image number or the channel has been changed if (chanIndx~=userData.chanIndx) || (imIndx~=userData.imIndx) userData.imData=userData.MD.channels_(chanIndx).loadImage(imIndx); userData.updateImage=1; userData.chanIndx=chanIndx; userData.imIndx=imIndx; % Update ROI if userData.imRectHandle.isvalid userData.cropROI=getPosition(userData.imRectHandle); end else userData.updateImage=0; end % In case of crop previewing mode if get(handles.checkbox_crop,'Value') % Create figure if non-existing or closed if ~isfield(userData, 'previewFig') || ~ishandle(userData.previewFig) userData.previewFig = figure('Name','Select the background region to crop',... 'DeleteFcn',@close_previewFig,'UserData',handles.figure1); axes('Position',[.05 .05 .9 .9]); userData.newFigure = 1; else figure(userData.previewFig); userData.newFigure = 0; end % Retrieve the image object handle imHandle = findobj(userData.previewFig,'Type','image'); if userData.newFigure || userData.updateImage if isempty(imHandle) imHandle=imshow(mat2gray(userData.imData)); axis off; else set(imHandle,'CData',mat2gray(userData.imData)); end end if userData.imRectHandle.isvalid % Update the imrect position setPosition(userData.imRectHandle,userData.cropROI) else % Create a new imrect object and store the handle userData.imRectHandle = imrect(get(imHandle,'Parent'),userData.cropROI); fcn = makeConstrainToRectFcn('imrect',get(imHandle,'XData'),get(imHandle,'YData')); setPositionConstraintFcn(userData.imRectHandle,fcn); end else if userData.imRectHandle.isvalid, userData.cropROI=getPosition(userData.imRectHandle); end % Close the figure if applicable if ishandle(userData.previewFig), delete(userData.previewFig); end end set(handles.figure1, 'UserData', userData); guidata(hObject,handles); % --- Executes on slider movement. function frameNumberEdition_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); % Retrieve the value of the selected image if strcmp(get(hObject,'Tag'),'edit_frameNumber') frameNumber = str2double(get(handles.edit_frameNumber, 'String')); else frameNumber = get(handles.slider_frameNumber, 'Value'); end frameNumber=round(frameNumber); firstImage = str2double(get(handles.edit_firstImage,'String')); lastImage = str2double(get(handles.edit_lastImage,'String')); % Check the validity of the frame values if isnan(firstImage) || isnan(lastImage) || isnan(frameNumber) warndlg('Please provide a valid frame value.','Setting Error','modal'); end if firstImage>lastImage, firstImage=lastImage; end firstImage = max(firstImage,1); lastImage = min(lastImage,userData.nFrames); frameNumber = min(max(frameNumber,firstImage),lastImage); % Store value userData.firstImage(userData.chanIndx) = firstImage; userData.lastImage(userData.chanIndx) = lastImage; set(handles.slider_frameNumber,'Min',firstImage,'Value',frameNumber,'Max',lastImage,... 'SliderStep',[1/double(lastImage-firstImage) 10/double(lastImage-firstImage)]); set(handles.edit_frameNumber,'String',frameNumber); set(handles.edit_firstImage,'String',firstImage); set(handles.edit_lastImage,'String',lastImage); % Save data and update graphics set(handles.figure1, 'UserData', userData); guidata(hObject, handles); update_data(hObject,eventdata,handles); function edit_filterSigma_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); % Retrieve the channel index props=get(handles.listbox_selectedChannels,{'UserData','Value'}); chanIndx = props{1}(props{2}); value = str2double(get(hObject, 'String')); if ~(value>0), % Reset old value set(hObject,'String',userData.filterSigma(chanIndx)) else % Update the sigma value in the stored array- userData.filterSigma(chanIndx) = value; guidata(hObject, handles); end % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) % Input check if isempty(get(handles.listbox_selectedChannels, 'String')) errordlg('Please select at least one input channel from ''Available Channels''.','Setting Error','modal') return; end channelIndex = get (handles.listbox_selectedChannels, 'Userdata'); funParams.ChannelIndex = channelIndex; % Process Sanity check ( only check underlying data ) userData = get(handles.figure1, 'UserData'); try userData.crtProc.sanityCheck; catch ME errordlg([ME.message 'Please double check your data.'],... 'Setting Error','modal'); return; end % Retrieve GUI-defined parameters if userData.imRectHandle.isvalid userData.cropROI=getPosition(userData.imRectHandle); end funParams.cropROI=userData.cropROI; funParams.firstImage=userData.firstImage; funParams.lastImage=userData.lastImage; % Save the filterSigma if different from psfSigma % In order not to override filterSigma in batch movie set up if ~isequal(userData.filterSigma,[userData.MD.channels_.psfSigma_]) funParams.filterSigma = userData.filterSigma; end % Set parameters and update main window processGUI_ApplyFcn(hObject, eventdata, handles,funParams);
github
mehta-lab/Instantaneous-PolScope-master
trackMovieSpeckles.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/trackMovieSpeckles.m
9,305
utf_8
7b6cd7625f476968da8367efc7d648ce
function trackMovieSpeckles(movieData,varargin) % trackMovieSpeckles tracks the speckles of a movie % % Copyright (C) 2012 LCCB % % This file is part of QFSM. % % QFSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % QFSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with QFSM. If not, see <http://www.gnu.org/licenses/>. % % % % SYNOPSIS detectMovieSpeckles(movieData,paramsIn) % % INPUT % movieData - A MovieData object describing the movie to be processed % % paramsIn - Structure with inputs for optional parameters. The % parameters should be stored as fields in the structure, with the field % names and possible values as described below % % OUTPUT % Sebastien Besson, May 2011 (last modified Sep 2011) %% ----------- Input ----------- %% %Check input ip = inputParser; ip.CaseSensitive = false; ip.addRequired('movieData', @(x) isa(x,'MovieData')); ip.addParamValue('paramsIn',[], @isstruct); ip.parse(movieData,varargin{:}); paramsIn=ip.Results.paramsIn; %Get the indices of any previous speckle detection processes iProc = movieData.getProcessIndex('SpeckleTrackingProcess',1,0); %If the process doesn't exist, create it if isempty(iProc) iProc = numel(movieData.processes_)+1; movieData.addProcess(SpeckleTrackingProcess(movieData,... movieData.outputDirectory_)); end specTrackProc = movieData.processes_{iProc}; %Parse input, store in parameter structure p = parseProcessParams(specTrackProc,paramsIn); %% --------------- Initialization ---------------%% if feature('ShowFigureWindows'), wtBar = waitbar(0,'Initializing...','Name',specTrackProc.getName()); wtBarArgs={'waitbar',wtBar}; else wtBarArgs={}; end % Reading various constants nFrames = movieData.nFrames_; nChan = numel(movieData.channels_); % Test the presence and output validity of the speckle detection process iSpecProc =movieData.getProcessIndex('SpeckleDetectionProcess',1,1); if isempty(iSpecProc) error(['Speckle detection has not yet been performed'... 'on this movie! Please run first!!']); end %Check that there is a valid output specDetProc = movieData.processes_{iSpecProc}; if ~specDetProc.checkChannelOutput(p.ChannelIndex) error(['Each channel must have speckles !' ... 'Please apply speckle detection to all needed channels before'... 'running speckle tracking!']) end % Set up the input directories inFilePaths = cell(1,nChan); for j = p.ChannelIndex inFilePaths{1,j} = specDetProc.outFilePaths_{1,j}; end % Check optional process Flow Tracking iFTProc =movieData.getProcessIndex('FlowTrackingProcess',1,1); if ~isempty(iFTProc) flowTrackProc=movieData.processes_{iFTProc}; if ~flowTrackProc.checkChannelOutput(p.ChannelIndex) error(['Each channel must have flow tracking output !' ... 'Please apply flow tracking to all needed channels before'... 'running speckle tracking!']) end for j = p.ChannelIndex inFilePaths{2,j} = flowTrackProc.outFilePaths_{1,j}; end initCorLen = flowTrackProc.funParams_.maxCorLength; else initCorLen = Inf; end specTrackProc.setInFilePaths(inFilePaths); % Set up the output directories outFilePaths_=cell(1,nChan); mkClrDir(p.OutputDirectory) channelName = @(x)movieData.getChannelPaths{x}(max(regexp(movieData.getChannelPaths{x},filesep))+1:end); for i = p.ChannelIndex; %Create string for current directory outFilePaths_{1,i} = [p.OutputDirectory filesep channelName(i) '_tracks.mat']; end specTrackProc.setOutFilePaths(outFilePaths_); %% --------------- Speckle detection ---------------%%% disp('Starting tracking speckles...') % Anonymous functions for reading input/output logMsg = @(chan) ['Please wait, tracking speckles for channel ' num2str(chan)]; timeMsg = @(t) ['\nEstimated time remaining: ' num2str(round(t)) 's']; tic; nTot = numel(p.ChannelIndex)*nFrames; for iChan = p.ChannelIndex % Log display disp(logMsg(iChan)) % Load all speckle candidates if ishandle(wtBar), waitbar(0,wtBar,'Loading speckles...'); end fprintf(1,'Loading speckles...\n'); cands = specDetProc.loadChannelOutput(iChan); % Generate Nx3 matrices with position (in image coordinate system) and % intensity of significant candidates % Replace fsmTrackFillSpeckleList validCands = cellfun(@(x) x([x.status]==1),cands,'UniformOutput',false); speckles = cellfun(@(x) horzcat([vertcat(x.Lmax) vertcat(x.ILmax)]),... validCands,'UniformOutput',false); % Retrieve insignificant candidates (for gap closing) invalidCands = cellfun(@(x) x([x.status]==0),cands,'UniformOutput',false); clear validCands % Initialize flow results to empty by default flow = cell(1,nFrames); if ~isempty(iFTProc) if ishandle(wtBar), waitbar(0,wtBar,'Loading flow field...'); end fprintf(1,'Loading flow field...'); % Load flow field and correlation length for all frames flow = flowTrackProc.loadChannelOutput(iChan,'output','flow'); % Interpolate non empty-flow for j=find(~cellfun(@isempty,flow)) flow{j} = interpolateFlow(flow{j},p.corrLength,p.interpolationMethod); end end M=zeros(4,4,nFrames-1); vectorField = cell(1,nFrames-1); for j=1:nFrames-1; % Track speckles between frame j and j+1; if p.enhanced % Generate match matrix in image coordinate system [matchM,vectors] = trackSpeckles(speckles{j},speckles{j+1},p.threshold,... 'initM',flow{j},'initCorLen',initCorLen,... 'enhanced',p.enhanced,'corrLength',p.corrLength); % Save interpolated vector field to disk for later use with gap closer vectorField{j}=vectors; else matchM = trackSpeckles(speckles{j},speckles{j+1},p.threshold,... 'initM',flow{j},'initCorLen',initCorLen,... 'enhanced',p.enhanced); end % If no flow tracked for frame j, use results of frame j if isempty(flow{j+1}) && ~isempty(iFTProc), % Extract vectors from M raw=matchM(matchM(:,1)~=0 & matchM(:,3)~=0,:); % Interpolate onto vector positions grid=raw(:,1:2); % Average returned M to be used to propagate I again interp_flow=vectorFieldAdaptInterp(raw,grid,p.corrLength,[],'strain'); flow{j+1} = interp_flow; end M(1:size(matchM,1),1:size(matchM,2),j,1)=matchM; if mod(j,5)==1 && ishandle(wtBar) tj=toc; nj = sum(nFrames(1:i-1))+ j; waitbar(nj/nTot,wtBar,sprintf([logMsg(iChan) timeMsg(tj*nTot/nj-tj)])); end end % Correct dimensions cM=M>0; [i,~,~]=find(cM); M=M(1:max(i),:,:,:); % In case only two frames have been tracked, no gaps can be closed if size(M,3)==1, MPM=M; end %#ok<NASGU> vector_arguments={}; vector_save={}; if p.enhanced, vector_arguments={'vectors',vectorField}; vector_save={'vectorField'}; end % Close gaps in M [M,gapList]=trackSpecklesGapCloser(M,p.threshold,invalidCands,... vector_arguments{:},wtBarArgs{:}); %#ok<NASGU> % Link gaps [MPM,M]=trackSpecklesLinker(M,wtBarArgs{:}); %#ok<NASGU,ASGLU> % Save output disp('Results will be saved as:') disp(specTrackProc.outFilePaths_{1,iChan}); save(specTrackProc.outFilePaths_{1,iChan},'MPM','M','gapList','flow',... vector_save{:}); end % Close waitbar if ishandle(wtBar), close(wtBar); end disp('Finished tracking speckles!'); function flow = interpolateFlow(flow,corLen, method) % Find points needed to be interpolated isnanIndx = isnan(flow(:,3)) | isnan(flow(:,4)); if isempty(isnanIndx), return; end switch method case 'none' % Use vectors of magnitude 0 flow(isnanIndx,3:4)=flow(isnanIndx,1:2); case 'nearest-neighbor' % Use magnitude of nearest neighbor realFlow = flow(~isnanIndx,:); % Contruct Delaunay triangulation and find nearest neighbor % delaunayTri=DelaunayTri(realFlow(:,1),realFlow(:,2)); % nnIdx = delaunayTri.nearestNeighbor(flow(isnanIndx,1),flow(isnanIndx,2)); nnIdx = KDTreeClosestPoint(realFlow(:,1:2),flow(isnanIndx,1:2)); flow(isnanIndx,3:4)=flow(isnanIndx,1:2)+... realFlow(nnIdx,3:4)-realFlow(nnIdx,1:2); case 'gaussian' % Use flow tracking correlation length flow(isnanIndx,:) = vectorFieldInterp(flow(~isnanIndx,:),... flow(isnanIndx,1:2),corLen,[]); end
github
mehta-lab/Instantaneous-PolScope-master
bfGetPlane.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/qFSM/bio-formats/bfGetPlane.m
3,316
utf_8
23879b4ca68d2da2bd94c99c43608811
function I = bfGetPlane(r, iPlane) % Get the plane data from a dataset reader using bioformats tools % % SYNOPSIS I = bfGetPlane(r, iPlane) % % Input % r - the reader object (e.g. the output bfGetReader) % % iPlane - a scalar giving the index of the plane to be retrieved. % % Output % % I - an array of size (width x height) containing the plane % % See also bfGetReader % Input check ip = inputParser; ip.addRequired('r', @(x) isa(x, 'loci.formats.ReaderWrapper')); ip.addRequired('iPlane', @isscalar); ip.parse(r, iPlane); % check MATLAB version, since typecast function requires MATLAB 7.1+ canTypecast = versionCheck(version, 7, 1); bioFormatsVersion = char(loci.formats.FormatTools.VERSION); isBioFormatsTrunk = versionCheck(bioFormatsVersion, 5, 0); width = r.getSizeX(); height = r.getSizeY(); pixelType = r.getPixelType(); bpp = loci.formats.FormatTools.getBytesPerPixel(pixelType); fp = loci.formats.FormatTools.isFloatingPoint(pixelType); sgn = loci.formats.FormatTools.isSigned(pixelType); bppMax = power(2, bpp * 8); little = r.isLittleEndian(); plane = r.openBytes(iPlane - 1); % convert byte array to MATLAB image if isBioFormatsTrunk && (sgn || ~canTypecast) % can get the data directly to a matrix arr = loci.common.DataTools.makeDataArray2D(plane, ... bpp, fp, little, height); else % get the data as a vector, either because makeDataArray2D % is not available, or we need a vector for typecast arr = loci.common.DataTools.makeDataArray(plane, ... bpp, fp, little); end % if ~strcmp(class(I),class(arr)), I= cast(I,['u' class(arr)]); end % Java does not have explicitly unsigned data types; % hence, we must inform MATLAB when the data is unsigned if ~sgn if canTypecast % TYPECAST requires at least MATLAB 7.1 % NB: arr will always be a vector here switch class(arr) case 'int8' arr = typecast(arr, 'uint8'); case 'int16' arr = typecast(arr, 'uint16'); case 'int32' arr = typecast(arr, 'uint32'); case 'int64' arr = typecast(arr, 'uint64'); end else % adjust apparent negative values to actual positive ones % NB: arr might be either a vector or a matrix here mask = arr < 0; adjusted = arr(mask) + bppMax / 2; switch class(arr) case 'int8' arr = uint8(arr); adjusted = uint8(adjusted); case 'int16' arr = uint16(arr); adjusted = uint16(adjusted); case 'int32' arr = uint32(arr); adjusted = uint32(adjusted); case 'int64' arr = uint64(arr); adjusted = uint64(adjusted); end adjusted = adjusted + bppMax / 2; arr(mask) = adjusted; end end if isvector(arr) % convert results from vector to matrix shape = [width height]; I = reshape(arr, shape)'; end function [result] = versionCheck(v, maj, min) tokens = regexp(v, '[^\d]*(\d+)[^\d]+(\d+).*', 'tokens'); majToken = tokens{1}(1); minToken = tokens{1}(2); major = str2double(majToken{1}); minor = str2double(minToken{1}); result = major > maj || (major == maj && minor >= min);
github
mehta-lab/Instantaneous-PolScope-master
bfCheckJavaPath.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/bioformats/bfCheckJavaPath.m
3,237
utf_8
a8204822a04672d090a16a10d4e3bf12
function [status, version] = bfCheckJavaPath(varargin) % bfCheckJavaPath check Bio-Formats is included in the Java class path % % SYNOPSIS bfCheckJavaPath() % status = bfCheckJavaPath(autoloadBioFormats) % [status, version] = bfCheckJavaPath() % % Input % % autoloadBioFormats - Optional. A boolean specifying the action to take % if no Bio-Formats JAR file is in the Java class path. If true, looks % for and adds a Bio-Formats JAR file to the dynamic Java path. % Default - true % % Output % % status - Boolean. True if a Bio-Formats JAR file is in the Java class % path. % % % version - String specifying the current version of Bio-Formats if % a Bio-Formats JAR file is in the Java class path. Empty string else. % OME Bio-Formats package for reading and converting biological file formats. % % Copyright (C) 2012 - 2014 Open Microscopy Environment: % - Board of Regents of the University of Wisconsin-Madison % - Glencoe Software, Inc. % - University of Dundee % % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as % published by the Free Software Foundation, either version 2 of the % License, or (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License along % with this program; if not, write to the Free Software Foundation, Inc., % 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. % Input check ip = inputParser; ip.addOptional('autoloadBioFormats', true, @isscalar); ip.parse(varargin{:}); % Check if a Bio-Formats JAR file is in the Java class path % Can be in either static or dynamic Java class path jPath = javaclasspath('-all'); bfJarFiles = {'bioformats_package.jar', 'loci_tools.jar'}; hasBFJar = false(numel(bfJarFiles), 1); for i = 1: numel(bfJarFiles); isBFJar = @(x) ~isempty(regexp(x, ['.*' bfJarFiles{i} '$'], 'once')); hasBFJar(i) = any(cellfun(isBFJar, jPath)); end % Check conflicting JARs are not loaded status = any(hasBFJar); if all(hasBFJar), warning('bf:jarConflict', ['Multiple Bio-Formats JAR files found'... 'in the Java class path. Please check.']) end if ~status && ip.Results.autoloadBioFormats, jarPath = getJarPath(bfJarFiles); assert(~isempty(jarPath), 'bf:jarNotFound',... 'Cannot automatically locate a Bio-Formats JAR file'); % Add the Bio-Formats JAR file to dynamic Java class path javaaddpath(jarPath); status = true; end if status % Read Bio-Formats version version = char(loci.formats.FormatTools.VERSION); else version = ''; end function path = getJarPath(files) % Assume the jar is either in the Matlab path or under the same folder as % this file for i = 1 : numel(files) path = which(files{i}); if isempty(path) path = fullfile(fileparts(mfilename('fullpath')), files{i}); end if ~isempty(path) && exist(path, 'file') == 2 return end end
github
mehta-lab/Instantaneous-PolScope-master
movieDataGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/movieDataGUI.m
15,141
utf_8
875ac3d79fa44477ad0f7d6595b6d6e7
function varargout = movieDataGUI(varargin) % MOVIEDATAGUI M-file for movieDataGUI.fig % MOVIEDATAGUI, by itself, creates a new MOVIEDATAGUI or raises the existing % singleton*. % % H = MOVIEDATAGUI returns the handle to a new MOVIEDATAGUI or the handle to % the existing singleton*. % % MOVIEDATAGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in MOVIEDATAGUI.M with the given input arguments. % % MOVIEDATAGUI('Property','Value',...) creates a new MOVIEDATAGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before movieDataGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to movieDataGUI_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 % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help movieDataGUI % Last Modified by GUIDE v2.5 20-Apr-2013 12:53:57 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @movieDataGUI_OpeningFcn, ... 'gui_OutputFcn', @movieDataGUI_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 movieDataGUI is made visible. function movieDataGUI_OpeningFcn(hObject, eventdata, handles, varargin) % % movieDataGUI('mainFig', handles.figure1) - call from movieSelector % movieDataGUI(MD) - MovieData viewer % % Useful tools: % % User Data: % % userData.channels - array of Channel objects % userData.mainFig - handle of movie selector GUI % userData.handles_main - 'handles' of movie selector GUI % % userData.setChannelFig - handle of channel set-up figure % userData.iconHelpFig - handle of help dialog % % NOTE: If movieDataGUI is under the "Overview" mode, additionally, % % userData.MD - the handle of selected MovieData object % % % Input check ip = inputParser; ip.addRequired('hObject',@ishandle); ip.addRequired('eventdata',@(x) isstruct(x) || isempty(x)); ip.addRequired('handles',@isstruct); ip.addOptional('MD',[],@(x) isa(x,'MovieData')); ip.addParamValue('mainFig',-1,@ishandle); ip.parse(hObject,eventdata,handles,varargin{:}) % Store inpu userData = get(handles.figure1, 'UserData'); if isempty(userData), userData = struct(); end userData.MD=ip.Results.MD; userData.mainFig=ip.Results.mainFig; set(handles.text_copyright, 'String', getLCCBCopyright()); % Set channel object array userData.channels = Channel.empty(1,0); % Load help icon from dialogicons.mat userData = loadLCCBIcons(userData); supermap(1,:) = get(hObject,'color'); userData.colormap = supermap; set(handles.figure1,'CurrentAxes',handles.axes_help); Img = image(userData.questIconData); set(hObject,'colormap',supermap); set(gca, 'XLim',get(Img,'XData'),'YLim',get(Img,'YData'),... 'visible','off'); set(Img,'ButtonDownFcn',@icon_ButtonDownFcn,... 'UserData', struct('class', mfilename)); if ~isempty(userData.MD), userData.channels = userData.MD.channels_; set(handles.listbox_channel, 'String', userData.MD.getChannelPaths) % GUI setting set(handles.pushbutton_delete, 'Enable', 'off') set(handles.pushbutton_add, 'Enable', 'off') set(handles.pushbutton_output, 'Enable', 'off') set(hObject, 'Name', 'Movie Detail') set(handles.edit_path,'String', userData.MD.getFullPath) set(handles.edit_output, 'String', userData.MD.outputDirectory_) set(handles.edit_notes, 'String', userData.MD.notes_) % GUI setting - parameters propNames={'pixelSize_','timeInterval_','numAperture_','camBitdepth_'}; validProps = ~cellfun(@(x) isempty(userData.MD.(x)),propNames); propNames=propNames(validProps); cellfun(@(x) set(handles.(['edit_' x(1:end-1)]),'Enable','off',... 'String',userData.MD.(x)),propNames) end % Choose default command line output for movieDataGUI handles.output = hObject; % Update handles structure set(handles.figure1,'UserData',userData) guidata(hObject, handles); % UIWAIT makes movieDataGUI wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = movieDataGUI_OutputFcn(~, ~, 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 pushbutton_cancel. function pushbutton_cancel_Callback(~, ~, handles) % hObject handle to pushbutton_cancel (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) delete(handles.figure1); % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) userData = get(handles.figure1,'UserData'); % Verify channels are given if ~isfield(userData, 'channels') || isempty(userData.channels) errordlg('Please provide at least one channel path.',... 'Empty Channel','modal'); return; end assert(isa(userData.channels(1), 'Channel'),'User-defined: userData.channels are not of class ''Channel''') % Check output path outputDir = get(handles.edit_output, 'String'); if isempty(outputDir) || ~exist(outputDir, 'dir') errordlg('Please provide a valid output path to save your results.', ... 'Empty Output Path', 'modal'); return; end % Concatenate numerical parameters as movie options propNames={'pixelSize_','timeInterval_','numAperture_','camBitdepth_'}; propStrings = cell(numel(propNames), 1); for i = 1 : numel(propNames) propStrings{i} =get(handles.(['edit_' propNames{i}(1:end-1)]), 'String'); end validProps = ~cellfun(@isempty,propStrings); if ~isempty(userData.MD), validProps=validProps & cellfun(@(x)isempty(userData.MD.(x)),propNames'); end propNames=propNames(validProps); propValues=num2cell(str2double(propStrings(validProps)))'; movieOptions = vertcat(propNames,propValues); movieOptions = reshape(movieOptions,1,numel(propNames)*2); % If movieDataGUI is under "Overview" mode if ~isempty(get(handles.edit_notes, 'String')) movieOptions=horzcat(movieOptions,'notes_',get(handles.edit_notes, 'String')); end if ~isempty(userData.MD), % Overview mode - edit existing MovieDat if ~isempty(movieOptions) try set(userData.MD,movieOptions{:}); catch ME errormsg = sprintf([ME.message '.\n\nMovie edition failed.']); errordlg(errormsg, 'User Input Error','modal'); return; end end else % Create Movie Data try userData.MD = MovieData(userData.channels, outputDir, movieOptions{:}); catch ME errormsg = sprintf([ME.message '.\n\nMovie creation failed.']); errordlg(errormsg, 'User Input Error','modal'); set(handles.figure1,'UserData',userData) return; end end try userData.MD.sanityCheck; catch ME errormsg = sprintf('%s.\n\nPlease check your movie data. Movie data is not saved.',ME.message); errordlg(errormsg,'Channel Error','modal'); set(handles.figure1,'UserData',userData) return; end % If new MovieData was created (from movieSelectorGUI) if ishandle(userData.mainFig), % Retrieve main window userData userData_main = get(userData.mainFig, 'UserData'); % Check if files in movie list are saved in the same file handles_main = guidata(userData.mainFig); contentlist = get(handles_main.listbox_movie, 'String'); movieDataFullPath = userData.MD.getFullPath; if any(strcmp(movieDataFullPath, contentlist)) errordlg('Cannot overwrite a movie data file which is already in the movie list. Please choose another file name or another path.','Error','modal'); return end % Append MovieData object to movie selector panel userData_main.MD = horzcat(userData_main.MD, userData.MD); set(userData.mainFig, 'UserData', userData_main) movieSelectorGUI('refreshDisplay',userData.mainFig,eventdata,guidata(userData.mainFig)); end % Delete current window delete(handles.figure1) function edit_property_Callback(hObject, eventdata, handles) set(hObject,'BackgroundColor',[1 1 1]) if isempty(get(hObject,'String')), return; end propTag = get(hObject,'Tag'); propName = [propTag(length('edit_')+1:end) '_']; propValue = str2double(get(hObject,'String')); if ~MovieData.checkValue(propName,propValue) warndlg('Invalid property value','Setting Error','modal'); set(hObject,'BackgroundColor',[1 .8 .8]); return end % --- Executes on button press in pushbutton_delete. function pushbutton_delete_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'Userdata'); contents = get(handles.listbox_channel,'String'); % Return if list is empty if isempty(contents), return; end iChan = get(handles.listbox_channel,'Value'); % Delete channel object delete(userData.channels(iChan)) userData.channels(iChan) = []; contents(iChan) = [ ]; set(handles.listbox_channel,'String',contents); % Point 'Value' to the second last item in the list once the % last item has been deleted set(handles.listbox_channel,'Value',max(1,min(iChan,length(contents)))); set(handles.figure1, 'Userdata', userData) guidata(hObject, handles); % --- Executes on button press in pushbutton_add. function pushbutton_add_Callback(hObject, eventdata, handles) set(handles.listbox_channel, 'Value', 1) userData = get(handles.figure1, 'UserData'); if ishandle(userData.mainFig), handles_main = guidata(userData.mainFig); userData_main = get(handles_main.figure1, 'UserData'); userDir =userData_main.userDir; else userDir=pwd; end path = uigetdir(userDir, 'Add Channels ...'); if path == 0, return; end % Get current list contents = get(handles.listbox_channel,'String'); if any(strcmp(contents,path)) warndlg('This directory has been selected! Please select a differenct directory.',... 'Warning','modal'); return; end % Create path object and save it to userData try hcstoggle = get(handles.checkbox4, 'Value'); if hcstoggle == 1 newChannel= Channel(path, 'hcsPlatestack_', 1); if max(size(newChannel))>1 for icn = 1:max(size(newChannel)) newChannel(icn).sanityCheck(); end end else newChannel = Channel(path); newChannel.sanityCheck(); end catch ME errormsg = sprintf('%s.\n\nPlease check this is valid channel.',ME.message); errordlg(errormsg,'Channel Error','modal'); return end % Refresh listbox_channel userData.channels = horzcat(userData.channels, newChannel); if hcstoggle == 1 for in = 1:length(userData.channels) ch_name = strcat(userData.channels(in).channelPath_, '-', userData.channels(in).hcsFlags_.wN); contents{end+1} = ch_name{1}; end else contents{end+1} = path; end set(handles.listbox_channel,'string',contents); if ishandle(userData.mainFig), userData_main.userDir = fileparts(path); set(handles_main.figure1, 'UserData', userData_main) end set(handles.figure1, 'Userdata', userData) guidata(hObject, handles); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); if isfield(userData, 'iconHelpFig') && ishandle(userData.iconHelpFig) delete(userData.iconHelpFig) end % --- Executes on button press in pushbutton_output. function pushbutton_output_Callback(hObject, eventdata, handles) pathname = uigetdir(pwd,'Select a directory to store the processes output'); if isnumeric(pathname), return; end set(handles.edit_output, 'String', pathname); % --- Executes on button press in pushbutton_setting_chan. function pushbutton_setting_chan_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); if isempty(userData.channels), return; end assert(isa(userData.channels(1), 'Channel'), 'User-defined: Not a valid ''Channel'' object'); userData.setChannelFig = channelGUI('mainFig', handles.figure1, 'modal'); set(handles.figure1,'UserData',userData); % --- Executes on button press in pushbutton_bfImport. function pushbutton_bfImport_Callback(hObject, eventdata, handles) assert(bfCheckJavaPath(), 'Could not load the Bio-Formats library'); % Note: list of supported formats could be retrieved using % loci.formats.tools.PrintFormatTable class [file, path] = uigetfile(bfGetFileExtensions(),... 'Select image file to import.'); if isequal(file,0) || isequal(path,0), return; end % Import data into movie using bioformats loci.common.DebugTools.enableLogging('INFO'); importMetadata = logical(get(handles.checkbox_importMetadata,'Value')); MD = MovieData([path file], importMetadata, 'askUser', true); % Update movie selector interface userData=get(handles.figure1,'UserData'); if ishandle(userData.mainFig), % Append MovieData object to movie selector panel userData_main = get(userData.mainFig, 'UserData'); userData_main.MD = horzcat(userData_main.MD, MD); set(userData.mainFig, 'UserData', userData_main) movieSelectorGUI('refreshDisplay',userData.mainFig,eventdata,guidata(userData.mainFig)) end % Relaunch this interface in preview mode movieDataGUI(MD(end)); % --- Executes on button press in checkbox4. function checkbox4_Callback(hObject, eventdata, handles) % hObject handle to checkbox4 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %set(handles.checkbox4, 'Value', 1); % Hint: get(hObject,'Value') returns toggle state of checkbox4
github
mehta-lab/Instantaneous-PolScope-master
trackCloseGapsKalmanSparse.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/trackCloseGapsKalmanSparse.m
36,873
utf_8
cb4935f9a7f8b4807975fa1681689161
function [tracksFinal,kalmanInfoLink,errFlag] = trackCloseGapsKalmanSparse(... movieInfo,costMatrices,gapCloseParam,kalmanFunctions,probDim,... saveResults,verbose,varargin) %TRACKCLOSEGAPSKALMANSPARSE (1) links features between frames, possibly using the Kalman Filter for motion propagation and (2) closes gaps, with merging and splitting % %SYNOPSIS [tracksFinal,kalmanInfoLink,errFlag] = trackCloseGapsKalmanSparse(... % movieInfo,costMatrices,gapCloseParam,kalmanFunctions,probDim,... % saveResults,verbose) % %INPUT movieInfo : Array of size equal to the number of frames in a % movie, containing at least the fields: % .xCoord : x-coordinates of detected features. % 1st column: value, 2nd column: standard % deviation (zeros if not available). % .yCoord : y-coordinates of detected features. % 1st column: value, 2nd column: standard % deviation (zeros if not available). % .zCoord : z-coordinates of detected features. % 1st column: value, 2nd column: standard % deviation (zeros if not available). % Optional. Skipped if problem is 2D. Default: zeros. % .amp : "Intensities" of detected features. % 1st column: values (ones if not available), % 2nd column: standard deviation (zeros if not % available). % ADDITIONAL FIELDS: % .kinType : Kinetochore type: 0 - inlier, 1 - % unaligned, 2 - lagging. Needed only when % using costMatHeLaKinsLink and costMatHeLaKinsCloseGaps. % costMatrices : 2-by-1 array indicating cost matrices and their % parameters. % -1st entry supplies the cost matrix for linking % between consecutive frames. % -2nd entry supplies the cost matrix for closing gaps % and merging and splitting. % Each entry is a structure with fields: % .funcName : Name of function used to calculate cost matrix. % .parameters : Structure containing parameters needed for cost matrix. % gapCloseParam: Structure containing variables needed for gap closing. % Contains the fields: % .timeWindow : Largest time gap between the end of a track and the % beginning of another that could be connected to it. % .mergeSplit : Logical variable with value 1 if the merging % and splitting of trajectories are to be consided; % and 0 if merging and splitting are not allowed. % .minTrackLen : Minimum length of tracks obtained from % linking to be used in gap closing. % .diagnostics : Logical variable with value 1 to plot a % histogram of gap lengths; 0 otherwise. % Optional. Default: 0. % kalmanFunctions: Names of Kalman filter functions for self-adaptive % tracking. Structure with fields: % .reserveMem : Reserves memory for kalmanFilterInfo. % .initialize : Initializes the Kalman filter for an appearing % feature. % .calcGain : Calculates the Kalman gain after linking. % .timeReverse : Reverses time (and associated variables) in % kalmanInfoLink between the different % frame-to-frame linking steps. % For non-self-adaptive tracking, enter []. % Optional. Default: []. % probDim : Problem dimensionality. 2 (for 2D) or 3 (for 3D). % Optional. If not input, dimensionality will be % derived from movieInfo. % saveResults : 0 if no saving is requested. % If saving is requested, structure with fields: % .dir : Directory where results should be saved. % Optional. Default: current directory. % .filename : Name of file where results should be saved. % Or []. Default: trackedFeatures in directory % where run is initiated. % Whole structure optional. % verbose : 1 to show calculation progress, 0 otherwise. % Optional. Default: 1. % % All optional variables can be entered as [] to use default values. % %OUTPUT tracksFinal : Structure array where each element corresponds to a % compound track. Each element contains the following % fields: % .tracksFeatIndxCG: Connectivity matrix of features between % frames, after gap closing. Number of rows % = number of track segments in compound % track. Number of columns = number of frames % the compound track spans. Zeros indicate % frames where track segments do not exist % (either because those frames are before the % segment starts or after it ends, or because % of losing parts of a segment. % .tracksCoordAmpCG: The positions and amplitudes of the tracked % features, after gap closing. Number of rows % = number of track segments in compound % track. Number of columns = 8 * number of % frames the compound track spans. Each row % consists of % [x1 y1 z1 a1 dx1 dy1 dz1 da1 x2 y2 z2 a2 dx2 dy2 dz2 da2 ...] % NaN indicates frames where track segments do % not exist, like the zeros above. % .seqOfEvents : Matrix with number of rows equal to number % of events happening in a compound track and 4 % columns: % 1st: Frame where event happens; % 2nd: 1 = start of track segment, 2 = end of track segment; % 3rd: Index of track segment that ends or starts; % 4th: NaN = start is a birth and end is a death, % number = start is due to a split, end % is due to a merge, number is the index % of track segment for the merge/split. % kalmanInfoLink: Structure array with number of entries equal to % number of frames in movie. Contains the fields % defined in kalmanFunctions.reserveMem (at % least stateVec, stateCov and noiseVar). % errFlag : 0 if function executes normally, 1 otherwise. % %Khuloud Jaqaman, April 2007 % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % %% Output tracksFinal = []; kalmanInfoLink = []; % numPotLinksPerFeature = []; % numPotLinksPerTrack = []; errFlag = 0; %% Input %check whether correct number of input arguments was used if nargin < 3 disp('--trackCloseGapsKalmanSparse: Incorrect number of input arguments!'); errFlag = 1; return end %check whether tracking is self-adaptive if nargin < 4 || isempty(kalmanFunctions) kalmanFunctions = []; selfAdaptive = 0; else selfAdaptive = 1; end %get number of frames in movie numFrames = length(movieInfo); %check whether z-coordinates were input, making problem potentially 3D if isfield(movieInfo,'zCoord') probDimT = 3; else probDimT = 2; end %assign problem dimensionality if not input if nargin < 5 || isempty(probDim) probDim = probDimT; else if probDim == 3 && probDimT == 2 disp('--trackCloseGapsKalmanSparse: Inconsistency in input. Problem 3D but no z-coordinates.'); errFlag = 1; end end %determine where to save results if nargin < 6 || isempty(saveResults) %if nothing was input saveResDir = pwd; saveResFile = 'trackedFeatures'; saveResults.dir = pwd; else if isstruct(saveResults) if ~isfield(saveResults,'dir') || isempty(saveResults.dir) saveResDir = pwd; else saveResDir = saveResults.dir; end if ~isfield(saveResults,'filename') || isempty(saveResults.filename) saveResFile = 'trackedFeatures'; else saveResFile = saveResults.filename; end else saveResults = 0; end end %check whether verbose if nargin < 7 || isempty(verbose) verbose = 1; end %exit if there are problems with input if errFlag disp('--trackCloseGapsKalmanSparse: Please fix input parameters.'); return end %% preamble %get gap closing parameters from input mergeSplit = gapCloseParam.mergeSplit; minTrackLen = gapCloseParam.minTrackLen; %make sure that gapCloseParam.timeWindow is not equal to 0 %set to 1 in this case, in order to not have any gap closing if gapCloseParam.timeWindow == 0 gapCloseParam.timeWindow = 1; end %get number of features in each frame if ~isfield(movieInfo,'num') for iFrame = 1 : numFrames movieInfo(iFrame).num = size(movieInfo(iFrame).xCoord,1); end end %collect coordinates and their std in one matrix in each frame if ~isfield(movieInfo,'allCoord') switch probDim case 2 for iFrame = 1 : numFrames movieInfo(iFrame).allCoord = [movieInfo(iFrame).xCoord ... movieInfo(iFrame).yCoord]; end case 3 for iFrame = 1 : numFrames movieInfo(iFrame).allCoord = [movieInfo(iFrame).xCoord ... movieInfo(iFrame).yCoord movieInfo(iFrame).zCoord]; end end end %calculate nearest neighbor distance for each feature in each frame if ~isfield(movieInfo,'nnDist') for iFrame = 1 : numFrames switch movieInfo(iFrame).num case 0 %if there are no features %there are no nearest neighbor distances nnDist = zeros(0,1); case 1 %if there is only 1 feature %assign nearest neighbor distance as 1000 pixels (a very big %number) nnDist = 1000; otherwise %if there is more than 1 feature %compute distance matrix nnDist = createDistanceMatrix(movieInfo(iFrame).allCoord(:,1:2:end),... movieInfo(iFrame).allCoord(:,1:2:end)); %sort distance matrix and find nearest neighbor distance nnDist = sort(nnDist,2); nnDist = nnDist(:,2); end %store nearest neighbor distance movieInfo(iFrame).nnDist = nnDist; end end %remove empty frames in the beginning and the end and keep the information %for later emptyStart = 0; numFeatures = vertcat(movieInfo.num); emptyFrames = find(numFeatures == 0); if ~isempty(emptyFrames) findEmpty = emptyFrames(1) == 1; else% findEmpty = 0; end while findEmpty emptyStart = emptyStart + 1; numFeatures = numFeatures(2:end); emptyFrames = find(numFeatures == 0); if ~isempty(emptyFrames) findEmpty = emptyFrames(1) == 1; else findEmpty = 0; end end emptyEnd = 0; numFeatures = vertcat(movieInfo.num); emptyFrames = find(numFeatures == 0); if ~isempty(emptyFrames) findEmpty = emptyFrames(end) == length(numFeatures); else findEmpty = 0; end while findEmpty emptyEnd = emptyEnd + 1; numFeatures = numFeatures(1:end-1); emptyFrames = find(numFeatures == 0); if ~isempty(emptyFrames) findEmpty = emptyFrames(end) == length(numFeatures); else findEmpty = 0; end end movieInfo = movieInfo(emptyStart+1:numFrames-emptyEnd); numFramesEff = length(movieInfo); if numFramesEff == 0 disp('Empty movie. Nothing to track.'); return end %% Link between frames % if self-adaptive, link in multiple rounds if selfAdaptive %get initial track segments by linking features between consecutive frames if verbose disp('Linking features forwards ...'); end [tmp,dummy,kalmanInfoLink,dummy,linkingCosts] = linkFeaturesKalmanSparse(... movieInfo,costMatrices(1).funcName,costMatrices(1).parameters,... kalmanFunctions,probDim,[],[],verbose); clear dummy %time-reverse Kalman filter information % -- USER DEFINED FUNCTION -- % eval(['kalmanInfoLink = ' kalmanFunctions.timeReverse ... '(kalmanInfoLink,probDim);']); %redo the linking by going backwards in the movie and using the %Kalman filter information from the first linking attempt %this will improve the linking and the state estimation if verbose disp('Linking features backwards ...'); end [dummy,dummy,kalmanInfoLink,dummy,linkingCosts] = linkFeaturesKalmanSparse(... movieInfo(end:-1:1),costMatrices(1).funcName,costMatrices(1).parameters,... kalmanFunctions,probDim,kalmanInfoLink,linkingCosts,verbose); clear dummy %time-reverse Kalman filter information % -- USER DEFINED FUNCTION -- % eval(['kalmanInfoLink = ' kalmanFunctions.timeReverse ... '(kalmanInfoLink,probDim);']); %go forward one more time to get the final estimate of the initial track %segments if verbose disp('Linking features forwards ...'); end [tracksFeatIndxLink,tracksCoordAmpLink,kalmanInfoLink,nnDistLinkedFeat,... dummy,errFlag] = linkFeaturesKalmanSparse(movieInfo,costMatrices(1).funcName,... costMatrices(1).parameters,kalmanFunctions,probDim,... kalmanInfoLink,linkingCosts,verbose); clear dummy else %if not self-adaptive, link in one round only %get initial track segments by linking features between consecutive frames if verbose disp('Linking features ...'); end [tracksFeatIndxLink,tracksCoordAmpLink,dummy,nnDistLinkedFeat,... dummy,errFlag] = linkFeaturesKalmanSparse(movieInfo,costMatrices(1).funcName,... costMatrices(1).parameters,kalmanFunctions,probDim,[],[],verbose); kalmanInfoLink = []; clear dummy end %% post-processing of linking results %this function now breaks up frame-to-frame linked tracks if they do not %follow a linear trajectory. it only runs with the EB3 cost matrix if isequal(costMatrices(2).funcName,'plusTipCostMatCloseGaps') tracksCoordAmpLink = full(tracksCoordAmpLink); tracksCoordAmpLink(tracksCoordAmpLink==0) = NaN; tracksCoordAmpLink(:,3:8:end) = 0; tracksCoordAmpLink(:,7:8:end) = 0; [tracksCoordAmpLink,tracksFeatIndxLink,nnDistLinkedFeat]=... plusTipBreakNonlinearTracks(tracksCoordAmpLink,tracksFeatIndxLink,nnDistLinkedFeat); end %get track start times, end times amd lifetimes trackSEL = getTrackSEL(tracksCoordAmpLink); %remove tracks whose length is less than minTrackLen indxKeep = find(trackSEL(:,3) >= minTrackLen); trackSEL = trackSEL(indxKeep,:); tracksFeatIndxLink = tracksFeatIndxLink(indxKeep,:); tracksCoordAmpLink = tracksCoordAmpLink(indxKeep,:); nnDistLinkedFeat = nnDistLinkedFeat(indxKeep,:); %calculate the new nearest-neighbor distance of each feature in each frame for iFrame = 1 : numFramesEff %get the coordinates of features in this frame coordFrame = tracksCoordAmpLink(:,(iFrame-1)*8+1:(iFrame-1)*8+3); if issparse(coordFrame) coordFrame = full(coordFrame(:,1:probDim)); coordFrame(coordFrame==0) = NaN; end coordFrame = coordFrame(~isnan(coordFrame(:,1)),:); if ~isempty(coordFrame) %compute distance matrix nnDist = createDistanceMatrix(coordFrame,coordFrame); %if there happens to be only one feature in this frame, give it a very %large nearest neighbor distance if length(nnDist(:)) == 1 nnDist = 1000; else %if there is more than 1 feature %sort distance matrix and find nearest neighbor distance nnDist = sort(nnDist,2); nnDist = nnDist(:,2); end %store nearest neighbor distances in matrix nnDistLinkedFeat(~isnan(nnDistLinkedFeat(:,iFrame)),iFrame) = nnDist; end end %save track start and end times trackStartTime = trackSEL(:,1); trackEndTime = trackSEL(:,2); clear trackSEL %get number of tracks numTracksLink = size(tracksFeatIndxLink,1); %% Close gaps with merging/splitting %if there are gaps to close (i.e. if there are tracks that start after the %first frame and tracks that end before the last frame) ... if any(trackStartTime > 1) && any(trackEndTime < numFramesEff) if verbose disp(sprintf('Closing gaps (%d starts and %d ends) ...',... length(find(trackStartTime>1)),length(find(trackEndTime<numFramesEff)))); end %initialize progress display if verbose progressText(0,'Gap closing'); end %calculate the cost matrix, which already includes the %costs of birth and death % -- USER DEFINED FUNCTION -- % eval(['[costMat,nonlinkMarker,indxMerge,numMerge,indxSplit,numSplit,'... 'errFlag] = ' costMatrices(2).funcName '(tracksCoordAmpLink,'... 'tracksFeatIndxLink,trackStartTime,trackEndTime,costMatrices(2).parameters,'... 'gapCloseParam,kalmanInfoLink,nnDistLinkedFeat,probDim,movieInfo);']) %if there are possible links ... if any(isfinite(nonzeros(costMat))) % % % %for paper - get number of potential links per track % % % numPotLinksPerTrack = full([sum(costMat(1:numTracksLink,1:numTracksLink+numMerge)... % % % ~=0,2); sum(costMat(1:numTracksLink+numSplit,1:numTracksLink)... % % % ~=0,1)']); %link tracks based on this cost matrix, allowing for birth and death [link12,link21] = lap(costMat,nonlinkMarker); link12 = double(link12); link21 = double(link21); %put the indices of all tracks from linking in one vector tracks2Link = (1:numTracksLink)'; tracksRemaining = tracks2Link; %reserve memory space for matrix showing track connectivity compoundTrack = zeros(numTracksLink,600); %initialize compTrackIndx compTrackIndx = 0; while ~isempty(tracksRemaining) %update compound track index by 1 compTrackIndx = compTrackIndx + 1; %take first track as a seed to build a compound track with %closed gaps and merges/splits trackSeed = tracksRemaining(1); seedLength = 1; seedLengthOld = 0; %dummy just to get into the while loop %while current seed contains more tracks than previous seed, i.e. %whie new track segments are still being added to the compound %track while seedLength > seedLengthOld %store current seed for later comparison seedLengthOld = seedLength; %find tracks connected to ends of seed tracks tmpTracks = link12(trackSeed); trackLink2End = tmpTracks(tmpTracks <= numTracksLink); %starts linked to ends trackMerge = []; if mergeSplit trackMerge = indxMerge(tmpTracks(tmpTracks > numTracksLink & ... tmpTracks <= numTracksLink+numMerge) - numTracksLink); %tracks that ends merge with end %find tracks connected to starts of seed tracks tmpTracks = link21(trackSeed); trackLink2Start = tmpTracks(tmpTracks <= numTracksLink); %ends linked to starts trackSplit = []; if mergeSplit trackSplit = indxSplit(tmpTracks(tmpTracks > numTracksLink & ... tmpTracks <= numTracksLink+numSplit) - numTracksLink); %tracks that starts split from end %put all tracks together as the new seed trackSeed = [trackSeed; trackLink2End; trackLink2Start; ... trackMerge; trackSplit]; %remove repetitions and arrange tracks in ascending order trackSeed = unique(trackSeed); %get number of tracks in new seed seedLength = length(trackSeed); %expand new seed if merging/splitting are allowed if mergeSplit %variables storing merge/split seed tracks mergeSeed = []; splitSeed = []; %go over all seed tracks for iSeed = 1 : seedLength %get the location(s) of this track in indxMerge mergeSeed = [mergeSeed; find(indxMerge == trackSeed(iSeed))]; %get the location(s) of this track in indxSplit splitSeed = [splitSeed; find(indxSplit == trackSeed(iSeed))]; end %add numTracksLink to mergeSeed and splitSeed to determine %their location in the cost matrix mergeSeed = mergeSeed + numTracksLink; splitSeed = splitSeed + numTracksLink; %find tracks merging with seed tracks trackMerge = []; for iSeed = 1 : length(mergeSeed) trackMerge = [trackMerge; find(link12(1:numTracksLink)==mergeSeed(iSeed))]; end %find tracks splitting from seed tracks trackSplit = []; for iSeed = 1 : length(splitSeed) trackSplit = [trackSplit; find(link21(1:numTracksLink)==splitSeed(iSeed))]; end %add these track to the seed trackSeed = [trackSeed; trackMerge; trackSplit]; %remove repetitions and arrange tracks in ascending order trackSeed = unique(trackSeed); %get number of tracks in new seed seedLength = length(trackSeed); end %(if mergeSplit) end %(while length(trackSeed) > length(trackSeedOld)) %expand trackSeed to reserve memory for connetivity information trackSeedConnect = [trackSeed zeros(seedLength,2)]; %store the tracks that the ends of the seed tracks are linked to, %and indicate whether it's an end-to-start link (+ve) or a merge (-ve) tmpTracks = link12(trackSeed); if mergeSplit tmpTracks(tmpTracks > numTracksLink & tmpTracks <= ... numTracksLink+numMerge) = -indxMerge(tmpTracks(tmpTracks > ... numTracksLink & tmpTracks <= numTracksLink+numMerge) - numTracksLink); end tmpTracks(tmpTracks > numTracksLink) = NaN; trackSeedConnect(:,2) = tmpTracks; %store the tracks that the starts of the seed tracks are linked to, %and indicate whether it's a start-to-end link (+ve) or a split (-ve) tmpTracks = link21(trackSeed); if mergeSplit tmpTracks(tmpTracks > numTracksLink & tmpTracks <= ... numTracksLink+numSplit) = -indxSplit(tmpTracks(tmpTracks > ... numTracksLink & tmpTracks <= numTracksLink+numSplit) - numTracksLink); end tmpTracks(tmpTracks > numTracksLink) = NaN; trackSeedConnect(:,3) = tmpTracks; %store tracks making up this compound track and their connectivity compoundTrack(compTrackIndx,1:3*seedLength) = reshape(... trackSeedConnect,3*seedLength,1)'; %in the list of all tracks, indicate that these tracks have %been taken care of by placing NaN instead of their number tracks2Link(trackSeed) = NaN; %retain only tracks that have not been linked to anything yet tracksRemaining = tracks2Link(~isnan(tracks2Link)); end %(while ~isempty(tracksRemaining)) %remove empty rows maxValue = max(compoundTrack,[],2); compoundTrack = compoundTrack(maxValue > 0,:); %determine number of tracks after gap closing (including merge/split if %specified) numTracksCG = size(compoundTrack,1); %reserve memory for structure storing tracks after gap closing tracksFinal = repmat(struct('tracksFeatIndxCG',[],... 'tracksCoordAmpCG',[],'seqOfEvents',[]),numTracksCG,1); %go over all compound tracks for iTrack = 1 : numTracksCG %get indices of tracks from linking making up current compound track %determine their number and connectivity trackSeedConnect = compoundTrack(iTrack,:)'; trackSeedConnect = trackSeedConnect(trackSeedConnect ~= 0); seedLength = length(trackSeedConnect)/3; %number of segments making current track trackSeedConnect = reshape(trackSeedConnect,seedLength,3); %get their start times segmentStartTime = trackStartTime(trackSeedConnect(:,1)); %arrange segments in ascending order of their start times [segmentStartTime,indxOrder] = sort(segmentStartTime); trackSeedConnect = trackSeedConnect(indxOrder,:); %get the segments' end times segmentEndTime = trackEndTime(trackSeedConnect(:,1)); %calculate the segments' positions in the matrix of coordinates and %amplitudes segmentStartTime8 = 8 * (segmentStartTime - 1) + 1; segmentEndTime8 = 8 * segmentEndTime; %instead of having the connectivity in terms of the original track %indices, have it in terms of the indices of this subset of tracks %(which are arranged in ascending order of their start times) for iSeed = 1 : seedLength value = trackSeedConnect(iSeed,2); if value > 0 trackSeedConnect(iSeed,2) = find(trackSeedConnect(:,1) == ... value); elseif value < 0 trackSeedConnect(iSeed,2) = -find(trackSeedConnect(:,1) == ... -value); end value = trackSeedConnect(iSeed,3); if value > 0 trackSeedConnect(iSeed,3) = find(trackSeedConnect(:,1) == ... value); elseif value < 0 trackSeedConnect(iSeed,3) = -find(trackSeedConnect(:,1) == ... -value); end end %get track information from the matrices storing linking information tracksFeatIndxCG = tracksFeatIndxLink(trackSeedConnect(:,1),:); tracksCoordAmpCG = tracksCoordAmpLink(trackSeedConnect(:,1),:); %convert zeros to NaNs where approriate for the case of sparse %matrices if issparse(tracksCoordAmpCG) %convert sparse to full tracksCoordAmpCG = full(tracksCoordAmpCG); %go over all the rows in this compound track for iRow = 1 : size(tracksCoordAmpCG,1) %find all the zero entries colZero = find(tracksCoordAmpCG(iRow,:)==0); colZero = colZero(:)'; %find the columns of the x-coordinates corresponding to %the zero columns xCoordCol = colZero - mod(colZero-1,8*ones(size(colZero))); %keep only the columns whose x-coordinate is zero as %well colZero = colZero(tracksCoordAmpCG(iRow,xCoordCol)==0); %replace zero with NaN in the surviving columns tracksCoordAmpCG(iRow,colZero) = NaN; end % tracksCoordAmpCG(tracksCoordAmpCG==0) = NaN; % if probDim == 2 % tracksCoordAmpCG(:,3:8:end) = 0; % tracksCoordAmpCG(:,7:8:end) = 0; % end end %perform all gap closing links and modify connectivity accordingly %go over all starts in reverse order for iSeed = seedLength : -1 : 2 %find the track this track might be connected to track2Append = trackSeedConnect(iSeed,3); %if there is a track (which is not a split) if track2Append > 0 %put track information in the relevant row tracksFeatIndxCG(track2Append,segmentStartTime(iSeed):... segmentEndTime(iSeed)) = tracksFeatIndxCG(iSeed,... segmentStartTime(iSeed):segmentEndTime(iSeed)); tracksFeatIndxCG(iSeed,:) = 0; tracksCoordAmpCG(track2Append,segmentStartTime8(iSeed):... segmentEndTime8(iSeed)) = tracksCoordAmpCG(iSeed,... segmentStartTime8(iSeed):segmentEndTime8(iSeed)); tracksCoordAmpCG(iSeed,:) = NaN; %update segment information segmentEndTime(track2Append) = segmentEndTime(iSeed); segmentEndTime8(track2Append) = segmentEndTime8(iSeed); segmentEndTime(iSeed) = NaN; segmentEndTime8(iSeed) = NaN; segmentStartTime(iSeed) = NaN; segmentStartTime8(iSeed) = NaN; %update connectivity trackSeedConnect(track2Append,2) = trackSeedConnect(iSeed,2); trackSeedConnect(trackSeedConnect(:,2) == iSeed,2) = track2Append; trackSeedConnect(trackSeedConnect(:,3) == iSeed,3) = track2Append; trackSeedConnect(trackSeedConnect(:,2) == -iSeed,2) = -track2Append; trackSeedConnect(trackSeedConnect(:,3) == -iSeed,3) = -track2Append; end %(if track2Append > 0) end %(for iSeed = seedLength : -1 : 2) %find rows that are not empty maxValue = max(tracksFeatIndxCG,[],2); rowsNotEmpty = find(maxValue > 0); %remove empty rows tracksFeatIndxCG = tracksFeatIndxCG(rowsNotEmpty,:); tracksCoordAmpCG = tracksCoordAmpCG(rowsNotEmpty,:); segmentEndTime = segmentEndTime(rowsNotEmpty); segmentStartTime = segmentStartTime(rowsNotEmpty); trackSeedConnect = trackSeedConnect(rowsNotEmpty,:); %update connectivity accordingly %by now, only merges and splits are left - thus no need for minus %sign to distinguish them from closed gaps for iSeed = 1 : length(rowsNotEmpty) trackSeedConnect(trackSeedConnect(:,2) == -rowsNotEmpty(... iSeed),2) = iSeed; trackSeedConnect(trackSeedConnect(:,3) == -rowsNotEmpty(... iSeed),3) = iSeed; end %determine new "seedLength" seedLength = length(rowsNotEmpty); %store the sequence of events of this track seqOfEvents = [segmentStartTime ones(seedLength,1) ... (1:seedLength)' trackSeedConnect(:,3); ... segmentEndTime 2*ones(seedLength,1) ... (1:seedLength)' trackSeedConnect(:,2)]; %sort sequence of events in ascending order of time [tmp,indxOrder] = sort(seqOfEvents(:,1)); seqOfEvents = seqOfEvents(indxOrder,:); %add 1 to the times of merges indx = find(~isnan(seqOfEvents(:,4)) & seqOfEvents(:,2) == 2); seqOfEvents(indx,1) = seqOfEvents(indx,1) + 1; %find the frame where the compound track starts and the frames %where it ends frameStart = seqOfEvents(1,1); frameEnd = seqOfEvents(end,1); %store final tracks, removing frames before anything happens and %after everything happens tracksFinal(iTrack).tracksFeatIndxCG = tracksFeatIndxCG(:,... frameStart:frameEnd); tracksFinal(iTrack).tracksCoordAmpCG = tracksCoordAmpCG(:,... 8*(frameStart-1)+1:8*frameEnd); tracksFinal(iTrack).seqOfEvents = seqOfEvents; end %(for iTrack = 1 : numTracksCG) else %if there are no possible links if verbose disp('No gaps to close!'); end %convert matrix of tracks into structure tracksFinal = convertMat2Struct(tracksCoordAmpLink,tracksFeatIndxLink); end %(if any(~isfinite(nonzeros(costMat)))) %display elapsed time if verbose progressText(1,'Gap closing'); end else %if there are no gaps to close if verbose disp('No gaps to close!'); end %convert matrix of tracks into structure tracksFinal = convertMat2Struct(tracksCoordAmpLink,tracksFeatIndxLink); end %(if any(trackStartTime > 1) && any(trackEndTime < numFramesEff) %shift time if any of the initial frames are empty for iTrack = 1 : length(tracksFinal) tracksFinal(iTrack).seqOfEvents(:,1) = tracksFinal(iTrack).seqOfEvents(:,1) + emptyStart; end %% Save results if isstruct(saveResults) save([saveResDir filesep saveResFile],'costMatrices','gapCloseParam',... 'kalmanFunctions','tracksFinal','kalmanInfoLink'); end %% Gap closing diagnostics %check whether to perform diagnostics if isfield(gapCloseParam,'diagnostics') diagnostics = gapCloseParam.diagnostics; else diagnostics = 0; end %if diagnostics are requested if ~isempty(diagnostics) && diagnostics == 1 %extract gap information from tracks gapInfo = findTrackGaps(tracksFinal); %plot the histogram of gap lengths if there are gaps if ~isempty(gapInfo) figure('Name','Gap length histogram','NumberTitle','off'); hist(gapInfo(:,4),(1:max(gapInfo(:,4)))); xlabel('Gap length'); ylabel('Counts'); else disp('No gaps to plot'); end end %% Subfunction1 function tracksFinal = convertMat2Struct(tracksCoordAmpLink,tracksFeatIndxLink) %get number of tracks numTracks = size(tracksCoordAmpLink,1); %reserve memory for structure storing tracks tracksFinal = repmat(struct('tracksFeatIndxCG',[],... 'tracksCoordAmpCG',[],'seqOfEvents',[]),numTracks,1); %get the start and end time of tracks trackSEL = getTrackSEL(tracksCoordAmpLink); %go over all tracks and store information for iTrack = 1 : numTracks %track start time and end time startTime = trackSEL(iTrack,1); endTime = trackSEL(iTrack,2); %feature indices tracksFinal(iTrack).tracksFeatIndxCG = tracksFeatIndxLink(iTrack,startTime:endTime); %feature coordinates and amplitudes tracksFinal(iTrack).tracksCoordAmpCG = full(tracksCoordAmpLink(iTrack,... (startTime-1)*8+1:endTime*8)); %sequence of events tracksFinal(iTrack).seqOfEvents = [startTime 1 1 NaN; endTime 2 1 NaN]; end %% %%%%% ~~ the end ~~ %%%%%
github
mehta-lab/Instantaneous-PolScope-master
anisoGaussianDetectionProcessGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/anisoGaussianDetectionProcessGUI.m
6,443
utf_8
b34bcd3e9886b156478d8f96eb21502c
function varargout = anisoGaussianDetectionProcessGUI(varargin) % anisoGaussianDetectionProcessGUI M-file for anisoGaussianDetectionProcessGUI.fig % anisoGaussianDetectionProcessGUI, by itself, creates a new anisoGaussianDetectionProcessGUI or raises the existing % singleton*. % % H = anisoGaussianDetectionProcessGUI returns the handle to a new anisoGaussianDetectionProcessGUI or the handle to % the existing singleton*. % % anisoGaussianDetectionProcessGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in anisoGaussianDetectionProcessGUI.M with the given input arguments. % % anisoGaussianDetectionProcessGUI('Property','Value',...) creates a new anisoGaussianDetectionProcessGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before anisoGaussianDetectionProcessGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to anisoGaussianDetectionProcessGUI_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 % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help anisoGaussianDetectionProcessGUI % Last Modified by GUIDE v2.5 18-Feb-2013 12:23:43 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @anisoGaussianDetectionProcessGUI_OpeningFcn, ... 'gui_OutputFcn', @anisoGaussianDetectionProcessGUI_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 anisoGaussianDetectionProcessGUI is made visible. function anisoGaussianDetectionProcessGUI_OpeningFcn(hObject, eventdata, handles, varargin) processGUI_OpeningFcn(hObject, eventdata, handles, varargin{:},'initChannel',1); % Set-up parameters userData=get(handles.figure1,'UserData'); funParams = userData.crtProc.funParams_; % Set-up parameters userData.numParams = {'psfSigma', 'alpha', 'kSigma', 'minDist'}; for i =1 : numel(userData.numParams) paramName = userData.numParams{i}; set(handles.(['edit_' paramName]), 'String', funParams.(paramName)); end % Update GUI user data set(handles.figure1, 'UserData', userData); handles.output = hObject; guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = anisoGaussianDetectionProcessGUI_OutputFcn(~, ~, 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 pushbutton_cancel. function pushbutton_cancel_Callback(~, ~, handles) % Delete figure delete(handles.figure1); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, ~, handles) % Notify the package GUI that the setting panel is closed userData = get(handles.figure1, 'UserData'); if(isempty(userData)), userData = struct(); end; if isfield(userData, 'helpFig') && ishandle(userData.helpFig) delete(userData.helpFig) end set(handles.figure1, 'UserData', userData); guidata(hObject,handles); % --- Executes on key press with focus on pushbutton_done and none of its controls. function pushbutton_done_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) % -------- Check user input -------- if isempty(get(handles.listbox_selectedChannels, 'String')) errordlg('Please select at least one input channel from ''Available Channels''.','Setting Error','modal') return; end % Retrieve GUI-defined parameters channelIndex = get(handles.listbox_selectedChannels, 'Userdata'); funParams.ChannelIndex = channelIndex; % Retrieve detection parameters userData = get(handles.figure1, 'UserData'); if(isempty(userData)), userData = struct(); end; for i = 1:numel(userData.numParams) paramName = userData.numParams{i}; value = str2double(get(handles.(['edit_' paramName]),'String')); if isnan(value) || value < 0 errordlg(['Please enter a valid value for '... get(handles.(['text_' paramName]),'String') '.'],... 'Setting Error','modal') return; end funParams.(paramName)=value; end % Add 64-bit warning is64bit = ~isempty(regexp(computer ,'64$', 'once')); if ~is64bit warndlg(['Your Matlab version is not detected as 64-bit. Please note '.... 'the anisotropic Gaussian detection uses compiled MEX files which '... 'are not provided for 32-bit.'],... 'Setting Error','modal'); end processGUI_ApplyFcn(hObject, eventdata, handles,funParams);
github
mehta-lab/Instantaneous-PolScope-master
plusTipWithinGroupComparison.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/plusTipWithinGroupComparison.m
4,350
utf_8
b4feab4eb44a303b3744a234858080f3
function plusTipWithinGroupComparison(groupData, iGroup, varargin) % plusTipPoolGroupData pools plus tip data from multiple projects in groups % % SYNOPSIS: plusTipWithinGroupComparison(groupData, saveDir, doPlot) % % INPUT: % groupList : output of plusTipExtractGroupData, nProj x 2 cell array % saveDir : path to output directory % doPlot : 1 to make histograms and boxplots for within and/or between % group data % % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Input check ip=inputParser; ip.addRequired('groupData', @(x) isstruct(x) || iscell(x) || isempty(x)); nGroups = numel(groupData.M); ip.addRequired('iGroup', @(x) isscalar(x) || ismember(x, 1 : nGroups)); ip.addOptional('saveDir', '', @ischar); ip.addOptional('doPlot', 1, @isscalar); ip.parse(groupData, iGroup, varargin{:}); saveDir = ip.Results.saveDir; doPlot = ip.Results.doPlot; % Call extract groupData function if empty or string input if isempty(groupData) || iscell(groupData) groupData = plusTipExtractGroupData(groupData); end % Launch interface if empty directory if isempty(saveDir) saveDir = uigetdir(pwd,'Select output directory.'); end % Set up output directory if isdir(saveDir), rmdir(saveDir, 's'); end mkdir(saveDir); % write out speed/lifetime/displacement distributions into a text file stackedM = vertcat(groupData.M{iGroup}{:}); dlmwrite([saveDir filesep 'gs_fs_bs_gl_fl_bl_gd_fd_bd_' ... groupData.names{iGroup} '.txt'], stackedM, 'precision', 3,... 'delimiter', '\t','newline', 'pc'); % Names for each movie in iGroup if ~isempty(groupData.movieNames{iGroup}) wtnGrpNames = groupData.movieNames{iGroup}; else wtnGrpNames = arrayfun(@(x) [groupData.names{iGroup} '_' num2str(x)],... 1:numel(groupData.dataMat{iGroup}),'Unif',0); end % Write stats results into a text file statsFile = [saveDir filesep 'Stats.txt']; statsNames = fieldnames(groupData.stats{iGroup}{1}); statsData= cellfun(@struct2cell,groupData.stats{iGroup},'Unif',false); statsData =horzcat(statsData{:}); pooledStatsNames = fieldnames(groupData.pooledStats{iGroup}); pooledStatsData = struct2cell(groupData.pooledStats{iGroup}); assert(all(ismember(pooledStatsNames, statsNames))); % Save pooled stats fid = fopen(statsFile,'w+'); fprintf(fid, '\t%s', wtnGrpNames{:}); fprintf(fid, '\tPooled Data'); for i=1:numel(pooledStatsNames) iStat = find(strcmp(pooledStatsNames{i},statsNames),1); fprintf(fid,'\n%s\t',statsNames{iStat}); fprintf(fid,'%g\t',statsData{iStat,:}); fprintf(fid,'%g',pooledStatsData{i}); end fclose(fid); if doPlot==1 % save histograms of pooled distributions from iGroup plusTipMakeHistograms(groupData.M{iGroup}, saveDir); % make within-group boxplots (show each movie in iGroup) plusTipMakeBoxplots(groupData.dataMat{iGroup}', wtnGrpNames', saveDir); % Plot comets as a function of time (Krek lab request) plotDetectedCometsNumber(groupData.detection{iGroup}, saveDir) end function plotDetectedCometsNumber(data,saveDir) maxFrame=max(cellfun(@numel,data)); nProjects = numel(data); colors=hsv(nProjects); % define small and large fonts sfont = {'FontName', 'Helvetica', 'FontSize', 18}; lfont = {'FontName', 'Helvetica', 'FontSize', 22}; % plot saveFig=figure('PaperPositionMode', 'auto'); % enable resizing hold on; arrayfun(@(i) plot(data{i},'-','Color',colors(i,:),'LineWidth',2),1:nProjects); % Set thickness of axes, ticks and assign tick labels set(gca, 'LineWidth', 1.5, sfont{:}, 'Layer', 'top','Xlim',[0 maxFrame]); xlabel('Frame number', lfont{:}); ylabel('Comet number', lfont{:}); % remove box around figure box off; saveas(saveFig,[saveDir filesep 'DetectedCometsCount.tif']); close(saveFig)
github
mehta-lab/Instantaneous-PolScope-master
omeroImport.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/omeroImport.m
5,645
utf_8
bb25155593f450c02de931d1e2a3b566
function movie = omeroImport(session,imageID,varargin) % OMEROIMPORT imports images from an OMERO server into MovieData objects % % movie = omeroImport(session) % % Load proprietary files using the Bioformats library. Read the metadata % that is associated with the movie and the channels and set them into the % created movie objects. Optionally images can be extracted and saved as % individual TIFF files. % % Input: % % session - an omero session % % imageID - The ID of the image to be associated with the movie Data. % % importMetadata - A flag specifying whether the movie metadata read by % Bio-Formats should be copied into the MovieData. Default: true. % % Optional Parameters : % ('FieldName' -> possible values) % % outputDirectory - A string giving the directory where to save the % created MovieData as well as the analysis output. In the case of % multi-series images, this string gives the basename of the output % folder and will be exanded as basename_sxxx for each movie % % Output: % % movie - A MovieData object % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Sebastien Besson, Dec 2011 (last modified May 2013) % Input check ip=inputParser; ip.addRequired('session', @MovieObject.isOmeroSession); ip.addRequired('imageID', @isscalar); ip.addOptional('importMetadata', true, @islogical); ip.addParamValue('outputDirectory', '', @ischar); ip.parse(session, imageID, varargin{:}); % Retrieve image and pixels image = getImages(session, imageID); assert(~isempty(image), 'No image of id %g found', imageID); pixels = image.getPrimaryPixels(); % Create metadata service metadataService = session.getMetadataService(); % Read Image metadata if ip.Results.importMetadata movieArgs = getMovieMetadata(metadataService, image); else movieArgs = {}; end % Set output directory (based on image extraction flag) if isempty(ip.Results.outputDirectory) [movieFileName, outputDir] = uiputfile('*.mat',... 'Find a place to save your analysis', 'movieData.mat'); if isequal(outputDir,0), return; end else outputDir = ip.Results.outputDirectory; if ~isdir(outputDir), mkdir(outputDir); end movieFileName = 'movie.mat'; end % Create movie channels nChan = pixels.getSizeC().getValue(); movieChannels(1,nChan) = Channel(); % Read OMERO channels pixels = session.getPixelsService().retrievePixDescription(pixels.getId.getValue); omeroChannels = toMatlabList(pixels.copyChannels); for i=1:nChan if ip.Results.importMetadata channelArgs = getChannelMetadata(omeroChannels(i)); else channelArgs = {}; end movieChannels(i)=Channel('',channelArgs{:}); end % Create movie object movie = MovieData(movieChannels, outputDir, movieArgs{:}); movie.setPath(outputDir); movie.setFilename(movieFileName); movie.setOmeroId(imageID); movie.setOmeroSession(session); movie.setOmeroSave(true); % Register single ROIs associated with the image roiResult = session.getRoiService().findByImage(imageID, []); rois = toMatlabList(roiResult.rois); if ~isempty(rois) && isscalar(rois), movie.roiOmeroId_ = rois.getId().getValue(); end % Save the movie movie.sanityCheck(); function movieArgs = getMovieMetadata(metadataService, image) movieArgs={}; pixels = image.getPrimaryPixels(); % Read pixel size pixelSize = pixels.getPhysicalSizeX(); if ~isempty(pixelSize) assert(isequal(pixelSize, pixels.getPhysicalSizeY),... 'Pixel size different in x and y'); if pixelSize.getValue() == 1, warning('Pixel size equal to 1.'); else movieArgs = horzcat(movieArgs, 'pixelSize_', pixelSize.getValue * 1e3); end end % Read camera bit depth camBitdepth = pixels.getPixelsType.getBitSize.getValue/2; if ~isempty(camBitdepth) movieArgs=horzcat(movieArgs,'camBitdepth_',camBitdepth); end % Read time interval timeInterval = pixels.getTimeIncrement(); if ~isempty(timeInterval) movieArgs=horzcat(movieArgs,'timeInterval_', timeInterval.getValue()); end % Read the lens numerical aperture instrument = image.getInstrument(); if ~isempty(instrument) instrument = metadataService.loadInstrument(instrument.getId.getValue); objectives = toMatlabList(instrument.copyObjective()); if ~isempty(objectives) && ~isempty(objectives(1).getLensNA()) lensNA = objectives(1).getLensNA().getValue(); movieArgs=horzcat(movieArgs,'numAperture_',double(lensNA)); end end function channelArgs = getChannelMetadata(omeroChannel) channelArgs = {}; % Read excitation wavelength exwlgth = omeroChannel.getLogicalChannel().getExcitationWave(); if ~isempty(exwlgth) && exwlgth.getValue() ~= -1 channelArgs=horzcat(channelArgs,... 'excitationWavelength_', exwlgth.getValue()); end % Read emission wavelength emwlgth=omeroChannel.getLogicalChannel().getEmissionWave(); if ~isempty(emwlgth) && emwlgth.getValue() ~= -1 % Bug channelArgs=horzcat(channelArgs,... 'emissionWavelength_', emwlgth.getValue()); end
github
mehta-lab/Instantaneous-PolScope-master
setErrorbarStyle.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/setErrorbarStyle.m
1,541
utf_8
eb7025ae7b73d5766e40031c35701343
%setErrorbarStyle(he, pos, de) modifies the width of the error bars % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Francois Aguet, Feb 22 2011 (last modif. 01/21/2012) function setErrorbarStyle(he, varargin) ip = inputParser; ip.CaseSensitive = false; ip.addRequired('he'); ip.addOptional('de', 0.2, @isscalar); ip.addParamValue('Position', 'both', @(x) any(strcmpi(x, {'both', 'top', 'bottom'}))); ip.parse(he, varargin{:}); de = ip.Results.de; he = get(he, 'Children'); xd = get(he(2), 'XData'); if strcmpi(ip.Results.Position, 'bottom') xd(4:9:end) = xd(1:9:end); xd(5:9:end) = xd(1:9:end); else xd(4:9:end) = xd(1:9:end) - de; xd(5:9:end) = xd(1:9:end) + de; end if strcmpi(ip.Results.Position, 'top') xd(7:9:end) = xd(1:9:end); xd(8:9:end) = xd(1:9:end); else xd(7:9:end) = xd(1:9:end) - de; xd(8:9:end) = xd(1:9:end) + de; end set(he(2), 'XData', xd);
github
mehta-lab/Instantaneous-PolScope-master
movieViewerOptions.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/movieViewerOptions.m
18,609
utf_8
6aa52eea4a33069fc3257a65c57f719d
function optionsFig = movieViewerOptions(mainFig) %GRAPHVIEWER creates a graphical interface to control the movie options % % This function creates a list of checkboxes for all graph processes which % output can be displayed in a standalone figure. It is called by % movieViewer. % % Input % % mainFig - the handle of the calling figure. % % Output: % % optionsFig - the handle of the movie options interface % % See also: graphViewer, movieViewerOptions % % Sebastien Besson, Nov 2012 % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Check existence of viewer h=findobj(0,'Name','Movie options'); if ~isempty(h), delete(h); end optionsFig=figure('Name','Movie options','Position',[0 0 200 200],... 'NumberTitle','off','Tag','figure1','Toolbar','none','MenuBar','none',... 'Color',get(0,'defaultUicontrolBackgroundColor'),'Resize','off'); userData = get(mainFig, 'UserData'); %% Image options panel creation imagePanel = uibuttongroup(gcf,'Position',[0 0 1/2 1],... 'Title','Image options','BackgroundColor',get(0,'defaultUicontrolBackgroundColor'),... 'Units','pixels','Tag','uipanel_image'); % Timestamp hPosition=10; if isempty(userData.MO.timeInterval_), timeStampStatus = 'off'; else timeStampStatus = 'on'; end uicontrol(imagePanel,'Style','checkbox',... 'Position',[10 hPosition 200 20],'Tag','checkbox_timeStamp',... 'String',' Time stamp','HorizontalAlignment','left',... 'Enable',timeStampStatus,'Callback',@(h,event) setTimeStamp(guidata(h))); uicontrol(imagePanel,'Style','popupmenu','Position',[130 hPosition 120 20],... 'String',{'NorthEast', 'SouthEast', 'SouthWest', 'NorthWest'},'Value',4,... 'Tag','popupmenu_timeStampLocation','Enable',timeStampStatus,... 'Callback',@(h,event) setTimeStamp(guidata(h))); % Scalebar hPosition=hPosition+30; if isempty(userData.MO.pixelSize_), scBarstatus = 'off'; else scBarstatus = 'on'; end uicontrol(imagePanel,'Style','edit','Position',[30 hPosition 50 20],... 'String','1','BackgroundColor','white','Tag','edit_imageScaleBar',... 'Enable',scBarstatus,... 'Callback',@(h,event) setScaleBar(guidata(h),'imageScaleBar')); uicontrol(imagePanel,'Style','text','Position',[85 hPosition-2 70 20],... 'String','microns','HorizontalAlignment','left'); uicontrol(imagePanel,'Style','checkbox',... 'Position',[150 hPosition 100 20],'Tag','checkbox_imageScaleBarLabel',... 'String',' Show label','HorizontalAlignment','left',... 'Enable',scBarstatus,... 'Callback',@(h,event) setScaleBar(guidata(h),'imageScaleBar')); hPosition=hPosition+30; uicontrol(imagePanel,'Style','checkbox',... 'Position',[20 hPosition 200 20],'Tag','checkbox_imageScaleBar',... 'String',' Show scalebar','HorizontalAlignment','left',... 'Enable',scBarstatus,... 'Callback',@(h,event) setScaleBar(guidata(h),'imageScaleBar')); uicontrol(imagePanel,'Style','popupmenu','Position',[130 hPosition 120 20],... 'String',{'NorthEast', 'SouthEast', 'SouthWest', 'NorthWest'},'Value',3,... 'Tag','popupmenu_imageScaleBarLocation','Enable',scBarstatus,... 'Callback',@(h,event) setScaleBar(guidata(h),'imageScaleBar')); hPosition=hPosition+20; uicontrol(imagePanel,'Style','text',... 'Position',[10 hPosition 200 20],'Tag','text_scalebar',... 'String','Scalebar','HorizontalAlignment','left','FontWeight','bold'); hPosition=hPosition+30; uicontrol(imagePanel,'Style','pushbutton',... 'Position',[20 hPosition 300 20],'Tag','pushbutton_scaleFactor',... 'String','Calibrate the ratio map unit','HorizontalAlignment','left',... 'Callback',@(h,event) calibrateRatio(guidata(h))); hPosition=hPosition+20; uicontrol(imagePanel,'Style','text',... 'Position',[20 hPosition 100 20],'Tag','text_imageScaleFactor',... 'String','Scaling factor','HorizontalAlignment','left'); uicontrol(imagePanel,'Style','edit','Position',[130 hPosition 70 20],... 'String','1','BackgroundColor','white','Tag','edit_imageScaleFactor',... 'Callback',@(h,event) setScaleFactor(guidata(h))); % Colormap control hPosition=hPosition+30; uicontrol(imagePanel,'Style','text','Position',[20 hPosition-2 100 20],... 'String','Color limits','HorizontalAlignment','left'); uicontrol(imagePanel,'Style','edit','Position',[130 hPosition 70 20],... 'String','','BackgroundColor','white','Tag','edit_cmin',... 'Callback',@(h,event) setCLim(guidata(h))); uicontrol(imagePanel,'Style','edit','Position',[200 hPosition 70 20],... 'String','','BackgroundColor','white','Tag','edit_cmax',... 'Callback',@(h,event) setCLim(guidata(h))); hPosition=hPosition+30; uicontrol(imagePanel,'Style','text','Position',[20 hPosition-2 80 20],... 'String','Colormap','HorizontalAlignment','left'); uicontrol(imagePanel,'Style','popupmenu',... 'Position',[130 hPosition 120 20],'Tag','popupmenu_colormap',... 'String',{'Gray','Jet','HSV'},'Value',1,... 'HorizontalAlignment','left','Callback',@(h,event) setColormap(guidata(h))); % Colorbar hPosition=hPosition+30; uicontrol(imagePanel,'Style','checkbox',... 'Position',[10 hPosition 120 20],'Tag','checkbox_colorbar',... 'String',' Colorbar','HorizontalAlignment','left',... 'Callback',@(h,event) setColorbar(guidata(h))); %findclass(findpackage('scribe'),'colorbar'); locations = ImageDisplay.getColorBarLocations(); uicontrol(imagePanel,'Style','popupmenu','String',locations,... 'Position',[130 hPosition 120 20],'Tag','popupmenu_colorbarLocation',... 'HorizontalAlignment','left','Callback',@(h,event) setColorbar(guidata(h))); %% Overlay options creation overlayPanel = uipanel(gcf,'Position',[1/2 0 1/2 1],... 'Title','Overlay options','BackgroundColor',get(0,'defaultUicontrolBackgroundColor'),... 'Units','pixels','Tag','uipanel_overlay'); hPosition=10; % First create overlay option (vectorField) if isempty(userData.MO.pixelSize_) || isempty(userData.MO.timeInterval_), scaleBarStatus = 'off'; else scaleBarStatus = 'on'; end uicontrol(overlayPanel,'Style','text','Position',[20 hPosition-2 100 20],... 'String','Color limits','HorizontalAlignment','left'); uicontrol(overlayPanel,'Style','edit','Position',[150 hPosition 50 20],... 'String','','BackgroundColor','white','Tag','edit_vectorCmin',... 'Callback',@(h,event) userData.redrawOverlaysFcn()); uicontrol(overlayPanel,'Style','edit','Position',[200 hPosition 50 20],... 'String','','BackgroundColor','white','Tag','edit_vectorCmax',... 'Callback',@(h,event) userData.redrawOverlaysFcn()); hPosition=hPosition+30; uicontrol(overlayPanel,'Style','edit','Position',[30 hPosition 50 20],... 'String','1000','BackgroundColor','white','Tag','edit_vectorFieldScaleBar',... 'Enable',scaleBarStatus,... 'Callback',@(h,event) setScaleBar(guidata(h),'vectorFieldScaleBar')); uicontrol(overlayPanel,'Style','text','Position',[85 hPosition-2 70 20],... 'String','nm/min','HorizontalAlignment','left'); uicontrol(overlayPanel,'Style','checkbox',... 'Position',[150 hPosition 100 20],'Tag','checkbox_vectorFieldScaleBarLabel',... 'String',' Show label','HorizontalAlignment','left',... 'Enable',scaleBarStatus,... 'Callback',@(h,event) setScaleBar(guidata(h),'vectorFieldScaleBar')); hPosition=hPosition+30; uicontrol(overlayPanel,'Style','checkbox',... 'Position',[20 hPosition 100 20],'Tag','checkbox_vectorFieldScaleBar',... 'String',' Scalebar','HorizontalAlignment','left',... 'Enable',scaleBarStatus,... 'Callback',@(h,event) setScaleBar(guidata(h),'vectorFieldScaleBar')); uicontrol(overlayPanel,'Style','popupmenu','Position',[130 hPosition 120 20],... 'String',{'NorthEast', 'SouthEast', 'SouthWest', 'NorthWest'},'Value',3,... 'Tag','popupmenu_vectorFieldScaleBarLocation','Enable',scaleBarStatus,... 'Callback',@(h,event) setScaleBar(guidata(h),'vectorFieldScaleBar')); hPosition=hPosition+30; uicontrol(overlayPanel,'Style','text',... 'Position',[20 hPosition 100 20],'Tag','text_vectorFieldScale',... 'String',' Display scale','HorizontalAlignment','left'); uicontrol(overlayPanel,'Style','edit','Position',[120 hPosition 50 20],... 'String','1','BackgroundColor','white','Tag','edit_vectorFieldScale',... 'Callback',@(h,event) setVectorScaleFactor(guidata(h))); hPosition=hPosition+20; uicontrol(overlayPanel,'Style','text',... 'Position',[10 hPosition 200 20],'Tag','text_vectorFieldOptions',... 'String','Vector field options','HorizontalAlignment','left','FontWeight','bold'); % Track options hPosition=hPosition+30; uicontrol(overlayPanel,'Style','text',... 'Position',[20 hPosition 100 20],'Tag','text_dragtailLength',... 'String',' Dragtail length','HorizontalAlignment','left'); uicontrol(overlayPanel,'Style','edit','Position',[120 hPosition 50 20],... 'String','10','BackgroundColor','white','Tag','edit_dragtailLength',... 'Callback',@(h,event) userData.redrawOverlaysFcn()); hPosition=hPosition+20; uicontrol(overlayPanel,'Style','checkbox',... 'Position',[20 hPosition 150 20],'Tag','checkbox_markMergeSplit',... 'String',' Mark merge/split','HorizontalAlignment','left',... 'Callback',@(h,event) userData.redrawOverlaysFcn()); hPosition=hPosition+20; uicontrol(overlayPanel,'Style','checkbox',... 'Position',[20 hPosition 150 20],'Tag','checkbox_showLabel',... 'String',' Show track number','HorizontalAlignment','left',... 'Callback',@(h,event) userData.redrawOverlaysFcn()); hPosition=hPosition+20; uicontrol(overlayPanel,'Style','text',... 'Position',[10 hPosition 200 20],'Tag','text_trackOptions',... 'String','Track options','HorizontalAlignment','left','FontWeight','bold'); % Windows options hPosition=hPosition+30; uicontrol(overlayPanel,'Style','text',... 'Position',[20 hPosition 100 20],'Tag','text_faceAlpha',... 'String',' Alpha value','HorizontalAlignment','left'); uicontrol(overlayPanel,'Style','edit','Position',[120 hPosition 50 20],... 'String','.3','BackgroundColor','white','Tag','edit_faceAlpha',... 'Callback',@(h,event) userData.redrawOverlaysFcn()); hPosition=hPosition+20; uicontrol(overlayPanel,'Style','text',... 'Position',[10 hPosition 200 20],'Tag','text_windowsOptions',... 'String','Windows options','HorizontalAlignment','left','FontWeight','bold'); %% Get image/overlay panel size and resize them imagePanelSize = getPanelSize(imagePanel); overlayPanelSize = getPanelSize(overlayPanel); panelsLength = max(500,imagePanelSize(1)+overlayPanelSize(1)); panelsHeight = max([imagePanelSize(2),overlayPanelSize(2)]); % Resize panel if ishandle(imagePanel) set(imagePanel,'Position',[10 panelsHeight-imagePanelSize(2)+10 ... imagePanelSize(1) imagePanelSize(2)]) end if ishandle(overlayPanel) set(overlayPanel,'Position',[imagePanelSize(1)+10 panelsHeight-overlayPanelSize(2)+10 ... overlayPanelSize(1) overlayPanelSize(2)]); end %% Resize panels and figure sz=get(0,'ScreenSize'); maxWidth = panelsLength+20; maxHeight = panelsHeight; figWidth = min(maxWidth,.75*sz(3)); figHeight=min(maxHeight,.75*sz(4)); set(optionsFig,'Position',[sz(3)/50 10 figWidth figHeight+20]); % Update handles structure and attach it to the main figure handles = guihandles(optionsFig); guidata(handles.figure1, handles); userData.mainFig = mainFig; userData.setImageOptions = @(h, method) setImageOptions(handles, h, method); userData.getOverlayOptions = @(h,event) getOverlayOptions(handles); userData.setOverlayOptions = @(method) setOverlayOptions(handles, method); set(handles.figure1,'UserData',userData); function size = getPanelSize(hPanel) if ~ishandle(hPanel), size=[0 0]; return; end a=get(get(hPanel,'Children'),'Position'); P=vertcat(a{:}); size = [max(P(:,1)+P(:,3))+10 max(P(:,2)+P(:,4))+20]; function setScaleBar(handles,type) % Remove existing scalebar of given type h=findobj('Tag',type); if ~isempty(h), delete(h); end % If checked, adds a new scalebar using the width as a label input userData=get(handles.figure1,'UserData'); if ~get(handles.(['checkbox_' type]),'Value'), return; end userData.getFigure('Movie'); scale = str2double(get(handles.(['edit_' type]),'String')); if strcmp(type,'imageScaleBar') width = scale *1000/userData.MO.pixelSize_; label = [num2str(scale) ' \mum']; else displayScale = str2double(get(handles.edit_vectorFieldScale,'String')); width = scale*displayScale/(userData.MO.pixelSize_/userData.MO.timeInterval_*60); label= [num2str(scale) ' nm/min']; end if ~get(handles.(['checkbox_' type 'Label']),'Value'), label=''; end props=get(handles.(['popupmenu_' type 'Location']),{'String','Value'}); location=props{1}{props{2}}; hScaleBar = plotScaleBar(width,'Label',label,'Location',location); set(hScaleBar,'Tag',type); function setTimeStamp(handles) % Remove existing timestamp of given type h=findobj('Tag','timeStamp'); if ~isempty(h), delete(h); end % If checked, adds a new scalebar using the width as a label input userData=get(handles.figure1,'UserData'); if ~get(handles.checkbox_timeStamp,'Value'), return; end userData.getFigure('Movie'); mainhandles = guidata(userData.mainFig); frameNr=get(mainhandles.slider_frame,'Value'); time= (frameNr-1)*userData.MO.timeInterval_; p=sec2struct(time); props=get(handles.popupmenu_timeStampLocation,{'String','Value'}); location=props{1}{props{2}}; hTimeStamp = plotTimeStamp(p.str,'Location',location); set(hTimeStamp,'Tag','timeStamp'); function setCLim(handles) clim=[str2double(get(handles.edit_cmin,'String')) ... str2double(get(handles.edit_cmax,'String'))]; userData = get(handles.figure1,'UserData'); userData.redrawImageFcn(handles,'CLim',clim) function setScaleFactor(handles) scaleFactor=str2double(get(handles.edit_imageScaleFactor,'String')); userData = get(handles.figure1,'UserData'); userData.redrawImageFcn(handles,'ScaleFactor',scaleFactor) function calibrateRatio(handles) % Make sure a movie is drawn userData = get(handles.figure1, 'UserData'); h = findobj(0, '-regexp', 'Name', '^Movie$'); if isempty(h), userData.redrawImageFcn(handles); end % Retrieve the handle of the axes containing the image hImage = findobj(h, 'Type', 'image', '-and', '-regexp', 'Tag', 'process','-or','Tag','channels'); hAxes = get(hImage, 'Parent'); % Allow use to draw polygon and retrieve mask once it is double-clicked p = impoly(hAxes); wait(p); mask = createMask(p); p.delete(); % Calculate mean value of unscaled image within the mask scaleFactor = str2double(get(handles.edit_imageScaleFactor, 'String')); imData = get(hImage, 'CData') * scaleFactor; ratio = nanmean(imData(mask)); % Set the color limit and scale factor of the image clim=[str2double(get(handles.edit_cmin, 'String')) ... str2double(get(handles.edit_cmax, 'String'))]; clim(1) = ratio; scaleFactor = ratio; userData.redrawImageFcn(handles, 'CLim', clim, 'ScaleFactor', scaleFactor); function setVectorScaleFactor(handles) userData = get(handles.figure1,'UserData'); userData.redrawOverlaysFcn(); % Reset the vector field scalebar if get(handles.checkbox_vectorFieldScaleBar,'Value'), setScaleBar(handles,'vectorFieldScaleBar'); end function setColormap(handles) allCmap=get(handles.popupmenu_colormap,'String'); selectedCmap = get(handles.popupmenu_colormap,'Value'); userData = get(handles.figure1,'UserData'); userData.redrawImageFcn('Colormap',allCmap{selectedCmap}) function setColorbar(handles) cbar=get(handles.checkbox_colorbar,'Value'); props = get(handles.popupmenu_colorbarLocation,{'String','Value'}); if cbar, cbarStatus='on'; else cbarStatus='off'; end userData = get(handles.figure1,'UserData'); userData.redrawImageFcn(handles,'Colorbar',cbarStatus,'ColorbarLocation',props{1}{props{2}}) function setImageOptions(handles, drawFig, displayMethod) % Set the color limits properties clim=displayMethod.CLim; if isempty(clim) hAxes=findobj(drawFig,'Type','axes','-not','Tag','Colorbar'); clim=get(hAxes,'Clim'); end if ~isempty(clim) set(handles.edit_cmin,'Enable','on','String',clim(1)); set(handles.edit_cmax,'Enable','on','String',clim(2)); end set(handles.edit_imageScaleFactor, 'Enable', 'on',... 'String',displayMethod.ScaleFactor); % Set the colorbar properties cbar=displayMethod.Colorbar; cbarLocation = find(strcmpi(displayMethod.ColorbarLocation,get(handles.popupmenu_colorbarLocation,'String'))); set(handles.checkbox_colorbar,'Value',strcmp(cbar,'on')); set(handles.popupmenu_colorbarLocation,'Enable',cbar,'Value',cbarLocation); % Set the colormap properties cmap=displayMethod.Colormap; colormaps = {'Gray','Jet','HSV'}; iCmap = find(strcmpi(cmap,colormaps),1); if isempty(iCmap), set(handles.popupmenu_colormap,'String','Custom',... 'Value',1,'Enable','off'); else set(handles.popupmenu_colormap,'String',colormaps,... 'Value',iCmap,'Enable','on'); end % Reset the scaleBar setScaleBar(handles,'imageScaleBar'); setTimeStamp(handles); function setOverlayOptions(handles, displayMethod) % Set the color limits properties if isa(displayMethod,'VectorFieldDisplay') && ~isempty(displayMethod.CLim) set(handles.edit_vectorCmin,'String',displayMethod.CLim(1)); set(handles.edit_vectorCmax,'String',displayMethod.CLim(2)); end function options = getOverlayOptions(handles) % Read various options vectorScale = str2double(get(handles.edit_vectorFieldScale,'String')); dragtailLength = str2double(get(handles.edit_dragtailLength,'String')); showLabel = get(handles.checkbox_showLabel,'Value'); markMergeSplit = get(handles.checkbox_markMergeSplit,'Value'); faceAlpha = str2double(get(handles.edit_faceAlpha,'String')); clim=[str2double(get(handles.edit_vectorCmin,'String')) ... str2double(get(handles.edit_vectorCmax,'String'))]; if ~isempty(clim) && all(~isnan(clim)), cLimArgs={'CLim',clim}; else cLimArgs={}; end options ={'vectorScale',vectorScale,'dragtailLength',dragtailLength,... 'faceAlpha',faceAlpha,'showLabel',showLabel, ... 'markMergeSplit',markMergeSplit,cLimArgs{:}};
github
mehta-lab/Instantaneous-PolScope-master
channelGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/channelGUI.m
11,799
utf_8
60e2117986c079fbd5c6ccd59665e855
function varargout = channelGUI(varargin) % CHANNELGUI M-file for channelGUI.fig % CHANNELGUI, by itself, creates a new CHANNELGUI or raises the existing % singleton*. % % H = CHANNELGUI returns the handle to a new CHANNELGUI or the handle to % the existing singleton*. % % CHANNELGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in CHANNELGUI.M with the given input arguments. % % CHANNELGUI('Property','Value',...) creates a new CHANNELGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before channelGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to channelGUI_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 % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help channelGUI % Last Modified by GUIDE v2.5 30-Jun-2011 15:53:11 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @channelGUI_OpeningFcn, ... 'gui_OutputFcn', @channelGUI_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 channelGUI is made visible. function channelGUI_OpeningFcn(hObject, ~, handles, varargin) % % channelGUI('mainFig', handles.figure1) - call from movieDataGUI % channelGUI(channelArray) - call from command line % channelGUI(..., 'modal') - call channelGUI as a modal window % % User Data: % % userData.channels - array of channel object % userData.selectedChannel - index of current channel % userData.mainFig - handle of movieDataGUI % userData.properties - structure array of properties % userData.propNames - list of modifiable properties % % userData.helpFig - handle of help window % set(handles.text_copyright, 'String', getLCCBCopyright()) userData = get(handles.figure1, 'UserData'); if isempty(userData), userData = struct(); end % Choose default command line output for channelGUI handles.output = hObject; % Load help icon from dialogicons.mat userData = loadLCCBIcons(userData); supermap(1,:) = get(hObject,'color'); userData.colormap = supermap; set(handles.figure1,'CurrentAxes',handles.axes_help); Img = image(userData.questIconData); set(hObject,'colormap',supermap); set(gca, 'XLim',get(Img,'XData'),'YLim',get(Img,'YData'),... 'visible','off'); set(Img,'ButtonDownFcn',@icon_ButtonDownFcn,... 'UserData', struct('class', mfilename)) if nargin > 3 if any(strcmp(varargin, 'mainFig')) % Called from movieDataGUI % Get userData.mainFig t = find(strcmp(varargin, 'mainFig')); userData.mainFig = varargin{t(end)+1}; % Get userData.channels userData_main = get(userData.mainFig, 'UserData'); assert(isa(userData_main.channels(1), 'Channel'), 'User-defined: No Channel object found.') userData.channels = userData_main.channels; % Get userData.selectedChannel handles_main = guidata(userData.mainFig); userData.selectedChannel = get(handles_main.listbox_channel, 'Value'); elseif isa(varargin{1}(1), 'Channel') % Called from command line userData.channels = varargin{1}; userData.selectedChannel = 1; else error('User-defined: Input parameters are incorrect.') end % Set as modal window if any(strcmp(varargin, 'modal')) set(hObject, 'WindowStyle', 'modal') end else error('User-defined: No proper input.') end % Set up imaging mode and flurophore pop-up menu modeString = vertcat({''},Channel.getImagingModes()); set(handles.popupmenu_imageType,'String',modeString); fluorophoreString = horzcat({''},Channel.getFluorophores()); set(handles.popupmenu_fluorophore,'String',fluorophoreString); % Read channel initial properties and store them in a structure propNames={'excitationWavelength_','emissionWavelength_',... 'exposureTime_','imageType_','fluorophore_'}; userData.isNumProp = @(x) x<4; for i=1:numel(userData.channels) for j=1:numel(propNames) userData.properties(i).(propNames{j})=... userData.channels(i).(propNames{j}); end end % Set up pop-up menu set(handles.popupmenu_channel, 'String', ... arrayfun(@(x)(['Channel ' num2str(x)]), 1:length(userData.channels), 'UniformOutput', false) ) set(handles.popupmenu_channel, 'Value', userData.selectedChannel) % Set up channel path and properties set(handles.figure1,'Visible','on'); set(handles.text_path, 'String', userData.channels(userData.selectedChannel).channelPath_) for i=1:numel(propNames) propValue = userData.properties(userData.selectedChannel).(propNames{i}); if userData.isNumProp(i) propHandle = handles.(['edit_' propNames{i}(1:end-1)]); guiProp = 'String'; guiValue = propValue; else propHandle = handles.(['popupmenu_' propNames{i}(1:end-1)]); guiProp = 'Value'; guiValue = find(strcmpi(propValue,get(propHandle,'String'))); if isempty(guiValue), guiValue=1; end end if ~isempty(propValue), enableState='inactive'; else enableState='on'; end set(propHandle,guiProp,guiValue,'Enable',enableState); end % Display psf sigma if computed if ~isempty(userData.channels(userData.selectedChannel).psfSigma_), set(handles.edit_psfSigma, 'String',... userData.channels(userData.selectedChannel).psfSigma_); else set(handles.edit_psfSigma, 'String', ''); end % Update handles structure set(handles.figure1,'UserData',userData) guidata(hObject, handles); % UIWAIT makes channelGUI wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = channelGUI_OutputFcn(~, ~, handles) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on selection change in popupmenu_channel. function popupmenu_channel_Callback(hObject, ~, handles) userData = get(handles.figure1, 'UserData'); if get(hObject,'Value') == userData.selectedChannel, return; end % Retrieve handles and names and save them propNames = fieldnames(userData.properties(1)); for i=1:numel(propNames) if userData.isNumProp(i) propHandle = handles.(['edit_' propNames{i}(1:end-1)]); guiValue = str2num(get(propHandle,'String')); else propHandle = handles.(['popupmenu_' propNames{i}(1:end-1)]); choices = get(propHandle,'String'); guiValue = choices{get(propHandle,'Value')}; end userData.properties(userData.selectedChannel).(propNames{i})=... guiValue; end % Update the selected channel path and properties propNames = fieldnames(userData.properties(1)); userData.selectedChannel=get(hObject,'Value'); set(handles.text_path, 'String', userData.channels(userData.selectedChannel).channelPath_) for i=1:numel(propNames) channelValue = userData.channels(userData.selectedChannel).(propNames{i}); if ~isempty(channelValue) propValue = channelValue; enableState = 'inactive'; else propValue = userData.properties(userData.selectedChannel).(propNames{i}); enableState = 'on'; end if userData.isNumProp(i) propHandle = handles.(['edit_' propNames{i}(1:end-1)]); guiProp = 'String'; guiValue = propValue; else propHandle = handles.(['popupmenu_' propNames{i}(1:end-1)]); guiProp = 'Value'; guiValue = find(strcmpi(propValue,get(propHandle,'String'))); if isempty(guiValue), guiValue=1; end end set(propHandle,guiProp,guiValue,'Enable',enableState); end % Display psf sigma if present if ~isempty(userData.channels(userData.selectedChannel).psfSigma_), set(handles.edit_psfSigma, 'String',... userData.channels(userData.selectedChannel).psfSigma_); else set(handles.edit_psfSigma, 'String', ''); end set(handles.figure1,'UserData',userData) % --- Executes when edit field is changed. function edit_property_Callback(hObject, ~, handles) if ~isempty(get(hObject,'String')) % Read property value propTag = get(hObject,'Tag'); propName = [propTag(length('edit_')+1:end) '_']; propValue = str2double(get(hObject,'String')); % Test property value using the class static method if ~Channel.checkValue(propName,propValue) warndlg('Invalid property value','Setting Error','modal'); set(hObject,'BackgroundColor',[1 .8 .8]); set(handles.popupmenu_channel, 'Enable','off'); return end end set(hObject,'BackgroundColor',[1 1 1]); set(handles.popupmenu_channel, 'Enable','on'); % --- Executes on button press in pushbutton_cancel. function pushbutton_cancel_Callback(~, ~, handles) delete(handles.figure1) % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); % Retrieve names and handles of non-empty fields propNames = fieldnames(userData.properties(1)); for i=1:numel(propNames) if userData.isNumProp(i) propHandle = handles.(['edit_' propNames{i}(1:end-1)]); guiValue = str2num(get(propHandle,'String')); else propHandle = handles.(['popupmenu_' propNames{i}(1:end-1)]); choices = get(propHandle,'String'); guiValue = choices{get(propHandle,'Value')}; end userData.properties(userData.selectedChannel).(propNames{i})=... guiValue; end % Set properties to channel objects for i=1:numel(userData.channels) set(userData.channels(i),userData.properties(i)); end set(handles.figure1,'UserData',userData) delete(handles.figure1) % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on selection change in popupmenu_fluorophore. function popupmenu_fluorophore_Callback(hObject, eventdata, handles) % Retrieve selected fluorophore name props=get(hObject,{'String','Value'}); fluorophore = props{1}{props{2}}; isFluorophoreValid = ~isempty(fluorophore); isLambdaEditable = strcmp(get(handles.edit_emissionWavelength,'Enable'),'on'); if ~isFluorophoreValid || ~isLambdaEditable,return; end % Set the value of the emission wavelength lambda = name2wavelength(fluorophore)*1e9; set(handles.edit_emissionWavelength,'String',lambda);
github
mehta-lab/Instantaneous-PolScope-master
readtiff.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/readtiff.m
3,515
utf_8
1a79d4a5da7da10b817709336b93042f
%[s] = readtiff(filepath) loads a tiff file or stack using libtiff % This function is ~1.5-2x faster than imread, useful for large stacks, % and supports a wider range of TIFF formats (see below) % % Inputs: % filepath : path to TIFF file to read from % % Optional inputs % range : range of pages to read from multi-page TIFF (stack) % info : output from imfinfo for filepath % % Options ('specifier', value) % 'ShowWaitbar' : true|{false} displays a progess bar while loading % % % Supported formats: unsigned integer, signed integer, single, and double TIFFs % as well as 8-bit/channel RGB stacks (returned as a cell array) % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Francois Aguet, 05/21/2013 function s = readtiff(filepath, varargin) ip = inputParser; ip.CaseSensitive = false; ip.KeepUnmatched = true; ip.addRequired('filepath'); ip.addOptional('range', []); ip.addOptional('info', [], @isstruct); ip.addParamValue('ShowWaitbar', false, @islogical); ip.parse(filepath, varargin{:}); info = ip.Results.info; range = ip.Results.range; if isempty(info) info = imfinfo(filepath); end if isempty(range) N = numel(info); range = 1:N; else N = numel(range); end w = warning('off', 'all'); % ignore unknown TIFF tags nx = info(1).Width; ny = info(1).Height; % Determine format and allocate arrays isRGB = false; if strcmpi(info(1).ColorType, 'grayscale') if isfield(info, 'SampleFormat') switch info(1).SampleFormat case 'Unsigned integer' cname = ['uint' num2str(info(1).BitDepth)]; case 'IEEE floating point' if info(1).BitDepth==32 cname = 'single'; else cname = 'double'; end case 'Two''s complement signed integer' cname = ['int' num2str(info(1).BitDepth)]; otherwise error('Unsupported format.'); end s = zeros(ny,nx,N,cname); else % assume uint s = zeros(ny,nx,N,['uint' num2str(info(1).BitDepth)]); end elseif strcmpi(info(1).ColorType, 'truecolor') && info(1).BitDepth==24 && ... all(info(1).BitsPerSample==[8 8 8]) s = cell(N,1); isRGB = true; else error('Unsupported format'); end t = Tiff(filepath, 'r'); if ~ip.Results.ShowWaitbar if ~isRGB for i = 1:numel(range) t.setDirectory(range(i)); s(:,:,i) = t.read(); end else for i = 1:numel(range) t.setDirectory(range(i)); s{i} = t.read(); end end else [~,fname] = fileparts(filepath); h = waitbar(0, ['Loading ' fname]); for i = 1:numel(range) t.setDirectory(range(i)); s(:,:,i) = t.read(); waitbar(i/numel(range)) end close(h); end t.close(); warning(w);
github
mehta-lab/Instantaneous-PolScope-master
MovieObject.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/MovieObject.m
22,005
utf_8
e063700a106112a9c5f638a15b120329
classdef MovieObject < hgsetget % Abstract interface defining the analyis tools for movie objects % (movies, movie lists...) % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Sebastien Besson, Jan 2012 properties (SetAccess = protected) createTime_ % Object creation time processes_ = {}; % List of analysis processes packages_ = {}; % List of analysis packages end properties outputDirectory_ = ''; % Default output directory for analysis notes_ % User notes omeroId_ % Identifier of an OMERO object omeroSave_ = false % Status of the saving to OMERO end properties (Transient =true) omeroSession_ % Active session to an OMERO server end methods %% Set/get methods function set.outputDirectory_(obj, path) % Set the ouput endingFilesepToken = [regexptranslate('escape',filesep) '$']; path = regexprep(path,endingFilesepToken,''); obj.checkPropertyValue('outputDirectory_',path); obj.outputDirectory_=path; end function checkPropertyValue(obj,property, value) % Check if a property/value pair can be set up % Test if the property is unchanged if isequal(obj.(property),value), return; end propName = regexprep(regexprep(property,'(_\>)',''),'([A-Z])',' ${lower($1)}'); % Test if the property is writable assert(obj.checkProperty(property),'lccb:set:readonly',... ['The ' propName ' has been set previously and cannot be changed!']); % Test if the supplied value is valid assert(obj.checkValue(property,value),'lccb:set:invalid',... ['The supplied ' propName ' is invalid!']); end function status = checkProperty(obj,property) % Returns true/false if the non-empty property is writable status = isempty(obj.(property)); if status, return; end % Allow user to rewrite on some properties (paths, outputDirectory, notes) switch property case {'notes_'}; status = true; case {'outputDirectory_',obj.getPathProperty,obj.getFilenameProperty}; stack = dbstack; if any(cellfun(@(x)strcmp(x,[class(obj) '.sanityCheck']),{stack.name})), status = true; end end end function set.notes_(obj, value) % Set the notes obj.checkPropertyValue('notes_',value); obj.notes_=value; end function value = getPath(obj) % Retrieve the folder path to save the object value = obj.(obj.getPathProperty); end function setPath(obj, value) % Set the folder path for saving the object obj.(obj.getPathProperty) = value; end function value = getFilename(obj) % Retrieve the filename for saving the object value = obj.(obj.getFilenameProperty); end function setFilename(obj, value) % Set the filename for saving the object obj.(obj.getFilenameProperty) = value; end function fullPath = getFullPath(obj, askUser) % Retrieve the full path for saving the object if nargin < 2, askUser = true; end hasEmptyComponent = isempty(obj.getPath) || isempty(obj.getFilename); hasDisplay = feature('ShowFigureWindows'); if any(hasEmptyComponent) && askUser && hasDisplay if ~isempty(obj.getPath), defaultDir = obj.getPath; elseif ~isempty(obj.outputDirectory_) defaultDir = obj.outputDirectory_; else defaultDir = pwd; end % Open a dialog box asking where to save the movie object movieClass = class(obj); objName = regexprep(movieClass,'([A-Z])',' ${lower($1)}'); defaultName = regexprep(movieClass,'(^[A-Z])','${lower($1)}'); [filename,path] = uiputfile('*.mat',['Find a place to save your' objName],... [defaultDir filesep defaultName '.mat']); if ~any([filename,path]), fullPath=[]; else fullPath = [path, filename]; % Set new path and filename obj.setPath(path); obj.setFilename(filename); end else if all(hasEmptyComponent), fullPath = ''; else fullPath = fullfile(obj.getPath(), obj.getFilename()); end end end %% Functions to manipulate process object array function addProcess(obj, newprocess) % Add new process to the processes list assert(isa(newprocess,'Process')); obj.processes_ = horzcat(obj.processes_, {newprocess}); end function proc = getProcess(obj, i) % Return process corresponding to the specified index assert(isscalar(i) && ismember(i,1:numel(obj.processes_))); proc = obj.processes_{i}; end function status = unlinkProcess(obj, process) % Unlink process from processes list id = []; status = false; if isa(process, 'Process') id = find(cellfun(@(x) isequal(x,process), obj.processes_), 1); elseif isscalar(process) && ismember(process, 1:numel(obj.processes_)) id = process; end if ~isempty(id), obj.processes_(id) = [ ]; status = true; end end function deleteProcess(obj, process) % Delete process from processes list and parent packages % % INPUT: % process - Process object or index % Check input if isa(process, 'Process') pid = find(cellfun(@(x) isequal(x,process), obj.processes_),1); assert(~isempty(pid),'The given process is not in current movie processes list.'); elseif isnumeric(process) pid = process; process = obj.getProcess(pid); else error('Please provide a Process object or a valid process index of movie data processes list.') end % Check process validity isValid = ~isempty(process) && process.isvalid; if isValid % Unassociate process from parent packages [packageID, procID] = process.getPackageIndex(); for i=1:numel(packageID) obj.getPackage(packageID(i)).setProcess(procID(i), []); end end if isValid && isa(process.owner_, 'MovieData') % Remove process from list for owner and descendants for movie = [process.owner_ process.owner_.getDescendants()] movie.unlinkProcess(process); end else obj.unlinkProcess(process); end % Delete process object if isValid, delete(process); end end function replaceProcess(obj, pid, newprocess) % Replace process object by another in the processes list % Input check ip=inputParser; ip.addRequired('pid', @(x) isa(x,'Process') || ... isnumeric(x) && ismember(x, 1:numel(obj.processes_))); ip.addRequired('newprocess', @(x) isa(x,'Process')); ip.parse(pid, newprocess); % Retrieve process index if input is of process type if isa(pid, 'Process') pid = find(cellfun(@(x)(isequal(x,pid)), obj.processes_)); assert(isscalar(pid)) end [packageID, procID] = obj.getProcess(pid).getPackageIndex(); % Check new process is compatible with parent packages if ~isempty(packageID) for i=1:numel(packageID) isValid = isa(newprocess,... obj.getPackage(packageID(i)).getProcessClassNames{procID(i)}); assert(isValid, 'Package class compatibility prevents process process replacement'); end end % Delete old process and replace it by the new one oldprocess = obj.getProcess(pid); if isa(oldprocess.owner_, 'MovieData') % Remove process from list for owner and descendants for movie = [oldprocess.owner_ oldprocess.owner_.getDescendants()] id = find(cellfun(@(x) isequal(x, oldprocess), movie.processes_),1); if ~isempty(id), movie.processes_{id} = newprocess; end end else obj.processes_{pid} = newprocess; end delete(oldprocess); % Associate new process in parent packages if ~isempty(packageID), for i=1:numel(packageID) obj.getPackage(packageID(i)).setProcess(procID(i),newprocess); end end end function iProc = getProcessIndex(obj, type, varargin) % Retrieve the existing process(es) of a given type if isa(type, 'Process'), type = class(type); end iProc = getIndex(obj.processes_, type, varargin{:}); end %% Functions to manipulate package object array function addPackage(obj, newpackage) % Add a package object to the package list assert(isa(newpackage,'Package')); obj.packages_ = horzcat(obj.packages_ , {newpackage}); end function package = getPackage(obj, i) % Return the package corresponding to the specified index assert(isscalar(i) && ismember(i,1:numel(obj.packages_))); package = obj.packages_{i}; end function status = unlinkPackage(obj, package) % Unlink a package from the packages list id = []; status = false; if isa(package, 'Package') id = find(cellfun(@(x) isequal(x,package), obj.packages_), 1); elseif isscalar(package) && ismember(package, 1:numel(obj.packages_)) id = package; end if ~isempty(id), obj.packages_(id) = [ ]; status = true; end end function deletePackage(obj, package) % Remove thepackage object from the packages list % Check input if isa(package, 'Package') pid = find(cellfun(@(x) isequal(x, package), obj.packages_),1); assert(~isempty(pid),'The given package is not in current movie packages list.'); elseif isnumeric(package) pid = package; package = obj.getPackage(pid); else error('Please provide a Package object or a valid package index of movie data processes list.') end % Check package validity isValid = ~isempty(package) && package.isvalid; if isValid && isa(package.owner_, 'MovieData') % Remove package from list for owner and descendants for movie = [package.owner_ package.owner_.getDescendants()] movie.unlinkPackage(package); end else obj.unlinkPackage(package); end % Delete package object if isValid, delete(package); end end function iPackage = getPackageIndex(obj, type, varargin) % Retrieve the existing package(s) of a given type if isa(type, 'Package'), type = class(type); end iPackage = getIndex(obj.packages_, type, varargin{:}); end %% Miscellaneous functions function askUser = sanityCheck(obj, path, filename,askUser) % Check sanity of movie object % % Check if the path and filename stored in the movie object are % the same as the input if any. If they differ, call the % movie object relocation routine. Use a dialog interface to ask % for relocation if askUser is set as true and return askUser. if nargin < 4, askUser = true; end if nargin > 1 && ~isempty(path) % Remove ending file separators from paths endingFilesepToken = [regexptranslate('escape',filesep) '$']; oldPath = regexprep(obj.getPath(),endingFilesepToken,''); newPath = regexprep(path,endingFilesepToken,''); % If different path hasDisplay = feature('ShowFigureWindows'); if ~strcmp(oldPath, newPath) confirmRelocate = 'Yes to all'; if askUser && hasDisplay if isa(obj,'MovieData') type='movie'; components='channels'; elseif isa(obj,'MovieList') type='movie list'; components='movies'; else error('Non supported movie object'); end relocateMsg=sprintf(['The %s and its analysis will be relocated from \n%s to \n%s.\n'... 'Should I relocate its %s as well?'],type,oldPath,newPath,components); confirmRelocate = questdlg(relocateMsg,['Relocation - ' type],'Yes to all','Yes','No','Yes'); end full = ~strcmp(confirmRelocate,'No'); askUser = ~strcmp(confirmRelocate,'Yes to all'); % Get old and new relocation directories [oldRootDir newRootDir]=getRelocationDirs(oldPath,newPath); oldRootDir = regexprep(oldRootDir,endingFilesepToken,''); newRootDir = regexprep(newRootDir,endingFilesepToken,''); % Relocate the object fprintf(1,'Relocating analysis from %s to %s\n',oldRootDir,newRootDir); obj.relocate(oldRootDir,newRootDir,full); end end if nargin > 2 && ~isempty(filename), obj.setFilename(filename); end if isempty(obj.outputDirectory_), warning('lccb:MovieObject:sanityCheck',... 'Empty output directory!'); end end function relocate(obj,oldRootDir,newRootDir) % Relocate the paths of all components of the movie object % % The relocate method automatically relocates the output directory, % as well as the paths in each process and package of the movie % assuming the internal architecture of the project is conserved. % Relocate output directory and set the ne movie path obj.outputDirectory_=relocatePath(obj.outputDirectory_,oldRootDir,newRootDir); obj.setPath(relocatePath(obj.getPath,oldRootDir,newRootDir)); % Relocate the processes for i=1:numel(obj.processes_), obj.processes_{i}.relocate(oldRootDir,newRootDir); end % Relocate the packages for i=1:numel(obj.packages_), obj.packages_{i}.relocate(oldRootDir,newRootDir); end end function reset(obj) % Reset the analysis of the movie object obj.processes_={}; obj.packages_={}; end %% OMERO functions function status = isOmero(obj) % Check if the movie object is linked to an OMERO object status = ~isempty(obj.omeroId_); end function setOmeroSession(obj,session) % Set the OMERO session linked to the object obj.omeroSession_ = session; end function session = getOmeroSession(obj) % Retrieve the OMERO session linked to the object session = obj.omeroSession_; end function setOmeroSave(obj, status) % Set the saving status onto the OMERO server obj.omeroSave_ = status; end function id = getOmeroId(obj) % Retrieve the identifier of the OMERO object id = obj.omeroId_; end function setOmeroId(obj, id) % Set the identifier of the OMERO object obj.checkPropertyValue('omeroId_', id); obj.omeroId_ = id; end function status = canUpload(obj) % Checks if the object can be uploaded to the OMERO server status = obj.omeroSave_ && ~isempty(obj.getOmeroSession()); end end methods(Static) function obj = loadMatFile(class, filepath) % Load a movie object saves as a MAT file on disk % Retrieve the absolute path [~, f] = fileattrib(filepath); filepath = f.Name; % Import movie object from MAT file try % List variables in the path vars = whos('-file', filepath); catch whosException ME = MException('lccb:movieObject:load', 'Fail to open file. Make sure it is a MAT file.'); ME = ME.addCause(whosException); throw(ME); end % Check if a single movie object is in the variables isMovie = cellfun(@(x) strcmp(x, class) || ... any(strcmp(superclasses(x), class)),{vars.class}); assert(any(isMovie),'lccb:movieObject:load', ... 'No object of type %s is found in selected MAT file.', class); assert(sum(isMovie)==1,'lccb:movieObject:load', ... 'Multiple objects are found in selected MAT file.'); assert(isequal(prod(vars(isMovie).size), 1),'lccb:movieObject:load', ... 'Multiple objects are found in selected MAT file.'); % Load movie object data = load(filepath, '-mat', vars(isMovie).name); obj= data.(vars(isMovie).name); end function validator = getPropertyValidator(property) % Retrieve the validator for the specified property validator=[]; if ismember(property,{'outputDirectory_','notes_'}) validator=@ischar; elseif strcmp(property, 'omeroId_') validator = @isposint; end end function status = isOmeroSession(session) % Check if the input is a valid OMERO session status = isa(session, 'omero.api.ServiceFactoryPrxHelper'); end end methods (Static,Abstract) getPathProperty() getFilenameProperty() end end function iProc = getIndex(list, type, varargin) % Find the index of a object of given class % Input check ip = inputParser; ip.addRequired('list',@iscell); ip.addRequired('type',@ischar); ip.addOptional('nDesired',1,@isscalar); ip.addOptional('askUser',true,@isscalar); ip.parse(list, type, varargin{:}); nDesired = ip.Results.nDesired; askUser = ip.Results.askUser; iProc = find(cellfun(@(x) isa(x,type), list)); nProc = numel(iProc); %If there are only nDesired or less processes found, return if nProc <= nDesired, return; end % If more than nDesired processes if askUser isMultiple = nDesired > 1; names = cellfun(@(x) (x.getName()), list(iProc), 'UniformOutput', false); iSelected = listdlg('ListString', names,... 'SelectionMode', isMultiple, 'ListSize', [400,400],... 'PromptString', ['Select the desired ' type ':']); iProc = iProc(iSelected); assert(~isempty(iProc), 'You must select a process to continue!'); else warning('lccb:process', ['More than ' num2str(nDesired) ' objects '... 'of class ' type ' were found! Returning most recent!']) iProc = iProc(end:-1:(end-nDesired+1)); end end
github
mehta-lab/Instantaneous-PolScope-master
name2wavelength.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/name2wavelength.m
1,165
utf_8
3a11bd3adb07963539c72a3afad159c5
% Francois Aguet, 06/30/2011 % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % function lambda = name2wavelength(name) s = getFluorPropStruct(); lv = [s.lambda_em]; if ischar(name) name = {name}; end lambda = cellfun(@(x) lv(strcmpi(x, {s.name})), name, 'UniformOutput', false); invalid = cellfun(@isempty, lambda); if any(invalid) invalid = name(invalid); invalid = cellfun(@(x) [x ' '], invalid, 'UniformOutput', false); error(['Unsupported fluorophores: ' invalid{:}]); end lambda = [lambda{:}];
github
mehta-lab/Instantaneous-PolScope-master
plusTipCostMatCloseGapsGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/plusTipCostMatCloseGapsGUI.m
5,937
utf_8
ba7fc8770c27a1ab83c384f0138f5f72
function varargout = plusTipCostMatCloseGapsGUI(varargin) % PLUSTIPCOSTMATCLOSEGAPSGUI M-file for plusTipCostMatCloseGapsGUI.fig % PLUSTIPCOSTMATCLOSEGAPSGUI, by itself, creates a new PLUSTIPCOSTMATCLOSEGAPSGUI or raises the existing % singleton*. % % H = PLUSTIPCOSTMATCLOSEGAPSGUI returns the handle to a new PLUSTIPCOSTMATCLOSEGAPSGUI or the handle to % the existing singleton*. % % PLUSTIPCOSTMATCLOSEGAPSGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in PLUSTIPCOSTMATCLOSEGAPSGUI.M with the given input arguments. % % PLUSTIPCOSTMATCLOSEGAPSGUI('Property','Value',...) creates a new PLUSTIPCOSTMATCLOSEGAPSGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before plusTipCostMatCloseGapsGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to plusTipCostMatCloseGapsGUI_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 % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help plusTipCostMatCloseGapsGUI % Last Modified by GUIDE v2.5 09-Feb-2012 16:27:04 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @plusTipCostMatCloseGapsGUI_OpeningFcn, ... 'gui_OutputFcn', @plusTipCostMatCloseGapsGUI_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 plusTipCostMatCloseGapsGUI is made visible. function plusTipCostMatCloseGapsGUI_OpeningFcn(hObject, eventdata, handles, varargin) costMat_OpeningFcn(hObject, eventdata, handles, varargin{:}) userData = get(handles.figure1, 'UserData'); if(isempty(userData)), userData = struct(); end; % 2014b Hackaton-fix PR parameters = userData.parameters; % Brownian motion parameters userData.numParams = {'maxFAngle','maxBAngle','backVelMultFactor','fluctRad'}; set(handles.checkbox_breakNonLinearTracks, 'Value', parameters.breakNonLinearTracks) for i=1:numel(userData.numParams) set(handles.(['edit_' userData.numParams{i}]), 'String', parameters.(userData.numParams{i})); end % Update handles structure set(handles.figure1, 'UserData', userData); handles.output = hObject; guidata(hObject, handles); % UIWAIT makes plusTipCostMatCloseGapsGUI wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = plusTipCostMatCloseGapsGUI_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 pushbutton_cancel. function pushbutton_cancel_Callback(hObject, eventdata, handles) % hObject handle to pushbutton_cancel (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) delete(handles.figure1) % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) % hObject handle to pushbutton_done (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) userData = get(handles.figure1, 'UserData'); if(isempty(userData)), userData = struct(); end; % 2014b Hackaton-fix PR parameters = userData.parameters; % Brownian motion parameters parameters.breakNonLinearTracks = get(handles.checkbox_breakNonLinearTracks, 'Value'); isPosScalar = @(x) isscalar(x) &&~isnan(x) && x>=0; for i=1:numel(userData.numParams) value = str2double(get(handles.(['edit_' userData.numParams{i}]), 'String')); if ~isPosScalar(value) errordlg(['Please provide a valid value to parameter '... get(handles.(['text_' userData.numParams{i}]), 'String') '.'],'Error','modal') return end parameters.(userData.numParams{i})=value; end u = get(userData.handles_main.popupmenu_gapclosing, 'UserData'); u{userData.procID} = parameters; set(userData.handles_main.popupmenu_gapclosing, 'UserData', u) set(handles.figure1, 'UserData', userData); guidata(hObject,handles); delete(handles.figure1); % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(hObject, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end
github
mehta-lab/Instantaneous-PolScope-master
pointSourceDetection.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/pointSourceDetection.m
8,294
utf_8
d5139d79def0a3261e4193b3ae572fe1
%[pstruct, mask, imgLM, imgLoG] = pointSourceDetection(img, sigma, mode) % % Inputs : % img : input image % sigma : standard deviation of the Gaussian PSF % % Options (as 'specifier'-value pairs): % % 'mode' : parameters to estimate. Default: 'xyAc'. % 'alpha' : alpha value used in the statistical tests. Default: 0.05. % 'mask' : mask of pixels (i.e., cell mask) to include in the detection. Default: all. % 'FitMixtures' : true|{false}. Toggles mixture-model fitting. % 'MaxMixtures' : maximum number of mixtures to fit. Default: 5. % 'RemoveRedundant' : {true}|false. Discard localizations that coincide within 'RedundancyRadius'. % 'RedundancyRadius' : Radius for filtering out redundant localizatios. Default: 0.25 % 'Prefilter' : {true}|false. Prefilter to calculate mask of significant pixels. % 'RefineMaskLoG' : {true}|false. Apply threshold to LoG-filtered img to refine mask of significant pixels. % 'RefineMaskValid' : {true}|false. Return only mask regions where a significant signal was localized. % 'ConfRadius' : Confidence radius for positions, beyond which the fit is rejected. Default: 2*sigma % 'WindowSize' : Window size for the fit. Default: 4*sigma, i.e., [-4*sigma ... 4*sigma]^2 % % Outputs: % pstruct : output structure with Gaussian parameters, standard deviations, p-values % mask : mask of significant (in amplitude) pixels % imgLM : image of local maxima % imgLoG : Laplacian of Gaussian-filtered image % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Francois Aguet, April 2011 (last modified: 09/30/2013) function [pstruct, mask, imgLM, imgLoG] = pointSourceDetection(img, sigma, varargin) % Parse inputs ip = inputParser; ip.CaseSensitive = false; ip.addRequired('img', @isnumeric); ip.addRequired('sigma', @isscalar); ip.addParamValue('Mode', 'xyAc', @ischar); ip.addParamValue('Alpha', 0.05, @isscalar); ip.addParamValue('Mask', [], @(x) isnumeric(x) || islogical(x)); ip.addParamValue('FitMixtures', false, @islogical); ip.addParamValue('MaxMixtures', 5, @isposint); ip.addParamValue('RemoveRedundant', true, @islogical); ip.addParamValue('RedundancyRadius', 0.25, @isscalar); ip.addParamValue('Prefilter', true, @islogical); ip.addParamValue('RefineMaskLoG', true, @islogical); ip.addParamValue('RefineMaskValid', true, @islogical); ip.addParamValue('ConfRadius', []); % Default: 2*sigma, see fitGaussians2D. ip.addParamValue('WindowSize', []); % Default: 4*sigma, see fitGaussians2D. ip.KeepUnmatched = true; ip.parse(img, sigma, varargin{:}); mode = ip.Results.Mode; alpha = ip.Results.Alpha; if ~isa(img, 'double') img = double(img); end % Gaussian kernel w = ceil(4*sigma); x = -w:w; g = exp(-x.^2/(2*sigma^2)); u = ones(1,length(x)); % convolutions imgXT = padarrayXT(img, [w w], 'symmetric'); fg = conv2(g', g, imgXT, 'valid'); fu = conv2(u', u, imgXT, 'valid'); fu2 = conv2(u', u, imgXT.^2, 'valid'); % Laplacian of Gaussian gx2 = g.*x.^2; imgLoG = 2*fg/sigma^2 - (conv2(g, gx2, imgXT, 'valid')+conv2(gx2, g, imgXT, 'valid'))/sigma^4; imgLoG = imgLoG / (2*pi*sigma^2); % 2-D kernel g = g'*g; n = numel(g); gsum = sum(g(:)); g2sum = sum(g(:).^2); % solution to linear system A_est = (fg - gsum*fu/n) / (g2sum - gsum^2/n); c_est = (fu - A_est*gsum)/n; if ip.Results.Prefilter J = [g(:) ones(n,1)]; % g_dA g_dc C = inv(J'*J); f_c = fu2 - 2*c_est.*fu + n*c_est.^2; % f-c RSS = A_est.^2*g2sum - 2*A_est.*(fg - c_est*gsum) + f_c; RSS(RSS<0) = 0; % negative numbers may result from machine epsilon/roundoff precision sigma_e2 = RSS/(n-3); sigma_A = sqrt(sigma_e2*C(1,1)); % standard deviation of residuals sigma_res = sqrt(RSS/(n-1)); kLevel = norminv(1-alpha/2.0, 0, 1); SE_sigma_c = sigma_res/sqrt(2*(n-1)) * kLevel; df2 = (n-1) * (sigma_A.^2 + SE_sigma_c.^2).^2 ./ (sigma_A.^4 + SE_sigma_c.^4); scomb = sqrt((sigma_A.^2 + SE_sigma_c.^2)/n); T = (A_est - sigma_res*kLevel) ./ scomb; pval = tcdf(-T, df2); % mask of admissible positions for local maxima mask = pval < 0.05; else mask = true(size(img)); end % all local max allMax = locmax2d(imgLoG, 2*ceil(sigma)+1); % local maxima above threshold in image domain imgLM = allMax .* mask; pstruct = []; if sum(imgLM(:))~=0 % no local maxima found, likely a background image if ip.Results.RefineMaskLoG % -> set threshold in LoG domain logThreshold = min(imgLoG(imgLM~=0)); logMask = imgLoG >= logThreshold; % combine masks mask = mask | logMask; end % re-select local maxima imgLM = allMax .* mask; % apply exclusion mask if ~isempty(ip.Results.Mask) imgLM(ip.Results.Mask==0) = 0; end [lmy, lmx] = find(imgLM~=0); lmIdx = sub2ind(size(img), lmy, lmx); if ~isempty(lmIdx) % run localization on local maxima if ~ip.Results.FitMixtures pstruct = fitGaussians2D(img, lmx, lmy, A_est(lmIdx), sigma*ones(1,length(lmIdx)),... c_est(lmIdx), mode, 'mask', mask, 'alpha', alpha,... 'ConfRadius', ip.Results.ConfRadius, 'WindowSize', ip.Results.WindowSize); else pstruct = fitGaussianMixtures2D(img, lmx, lmy, A_est(lmIdx), sigma*ones(1,length(lmIdx)),... c_est(lmIdx), 'mask', mask, 'alpha', alpha, 'maxM', ip.Results.MaxMixtures); end % remove NaN values idx = ~isnan([pstruct.x]); if sum(idx)~=0 fnames = fieldnames(pstruct); for k = 1:length(fnames) pstruct.(fnames{k}) = pstruct.(fnames{k})(idx); end % significant amplitudes idx = [pstruct.hval_Ar] == 1; % eliminate duplicate positions (resulting from localization) if ip.Results.RemoveRedundant pM = [pstruct.x' pstruct.y']; idxKD = KDTreeBallQuery(pM, pM, ip.Results.RedundancyRadius*ones(numel(pstruct.x),1)); idxKD = idxKD(cellfun(@numel, idxKD)>1); for k = 1:length(idxKD); RSS = pstruct.RSS(idxKD{k}); idx(idxKD{k}(RSS ~= min(RSS))) = 0; end end if sum(idx)>0 fnames = fieldnames(pstruct); for k = 1:length(fnames) pstruct.(fnames{k}) = pstruct.(fnames{k})(idx); end pstruct.hval_Ar = logical(pstruct.hval_Ar); pstruct.hval_AD = logical(pstruct.hval_AD); pstruct.isPSF = ~pstruct.hval_AD; % adjust mixture index if only a single component remains if ip.Results.FitMixtures mv = 0:max(pstruct.mixtureIndex); multiplicity = getMultiplicity(pstruct.mixtureIndex); pstruct.mixtureIndex(ismember(pstruct.mixtureIndex, mv(multiplicity==1))) = 0; end else pstruct = []; end else pstruct = []; end end end if ~isempty(pstruct) && ip.Results.RefineMaskValid CC = bwconncomp(mask); labels = labelmatrix(CC); loclabels = labels(sub2ind(size(img), pstruct.y_init, pstruct.x_init)); idx = setdiff(1:CC.NumObjects, loclabels); CC.PixelIdxList(idx) = []; CC.NumObjects = length(CC.PixelIdxList); mask = labelmatrix(CC)~=0; end
github
mehta-lab/Instantaneous-PolScope-master
bfImport.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/bfImport.m
9,330
utf_8
449a51086b2423d8452b4b5886cca6b3
function MD = bfImport(dataPath,varargin) % BFIMPORT imports movie files into MovieData objects using Bioformats % % MD = bfimport(dataPath) % MD = bfimport(dataPath, false) % MD = bfimport(dataPath, 'outputDirectory', outputDir) % % Load proprietary files using the Bioformats library. Read the metadata % that is associated with the movie and the channels and set them into the % created movie objects. % % Input: % % dataPath - A string containing the full path to the movie file. % % importMetadata - A flag specifying whether the movie metadata read by % Bio-Formats should be copied into the MovieData. Default: true. % % Optional Parameters : % ('FieldName' -> possible values) % % outputDirectory - A string giving the directory where to save the % created MovieData as well as the analysis output. In the case of % multi-series images, this string gives the basename of the output % folder and will be exanded as basename_sxxx for each movie % % Output: % % MD - A single MovieData object or an array of MovieData objects % depending on the number of series in the original images. % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Sebastien Besson, Dec 2011 (last modifier May 2014) % Input check ip=inputParser; ip.addRequired('dataPath',@ischar); ip.addOptional('importMetadata',true,@islogical); ip.addParamValue('outputDirectory',[],@ischar); ip.addParamValue('askUser', false, @isscalar); ip.parse(dataPath,varargin{:}); % Retrieve the absolute path of the image file [status, f] = fileattrib(dataPath); assert(status, '%s is not a valid path', dataPath); assert(~f.directory, '%s is a directory', dataPath); dataPath = f.Name; try % autoload java path and configure log4j bfInitLogging(); % Retrieve movie reader and metadata r = bfGetReader(dataPath); r.setSeries(0); catch bfException ME = MException('lccb:import:error','Import error'); ME = ME.addCause(bfException); throw(ME); end % Read number of series and initialize movies nSeries = r.getSeriesCount(); MD(1, nSeries) = MovieData(); % Set output directory (based on image extraction flag) [mainPath, movieName, movieExt] = fileparts(dataPath); token = regexp([movieName,movieExt], '^(.+)\.ome\.tiff{0,1}$', 'tokens'); if ~isempty(token), movieName = token{1}{1}; end if ~isempty(ip.Results.outputDirectory) mainOutputDir = ip.Results.outputDirectory; else mainOutputDir = fullfile(mainPath, movieName); end % Create movie channels nChan = r.getSizeC(); movieChannels(nSeries, nChan) = Channel(); for i = 1 : nSeries fprintf(1,'Creating movie %g/%g\n',i,nSeries); iSeries = i-1; % Read movie metadata using Bio-Formats if ip.Results.importMetadata movieArgs = getMovieMetadata(r, iSeries); else movieArgs = {}; end % Read number of channels, frames and stacks nChan = r.getMetadataStore().getPixelsSizeC(iSeries).getValue; % Generate movie filename out of the input name if nSeries>1 sString = num2str(i, ['_s%0' num2str(floor(log10(nSeries))+1) '.f']); outputDir = [mainOutputDir sString]; movieFileName = [movieName sString '.mat']; else outputDir = mainOutputDir; movieFileName = [movieName '.mat']; end % Create output directory if ~isdir(outputDir), mkdir(outputDir); end for iChan = 1:nChan if ip.Results.importMetadata channelArgs = getChannelMetadata(r, iSeries, iChan-1); else channelArgs = {}; end % Create new channel movieChannels(i, iChan) = Channel(dataPath, channelArgs{:}); end % Create movie object MD(i) = MovieData(movieChannels(i, :), outputDir, movieArgs{:}); MD(i).setPath(outputDir); MD(i).setFilename(movieFileName); MD(i).setSeries(iSeries); MD(i).setReader(BioFormatsReader(dataPath, iSeries, 'reader', r)); if ip.Results.askUser, status = exist(MD(i).getFullPath(), 'file'); if status msg = ['The output file %s already exist on disk. ' ... 'Do you want to overwrite?']; answer = questdlg(sprintf(msg, MD(i).getFullPath())); if ~strcmp(answer, 'Yes'), continue; end end end % Close reader and check movie sanity MD(i).sanityCheck; end function movieArgs = getMovieMetadata(r, iSeries) % Create movie metadata cell array using read metadata movieArgs={}; metadataStore = r.getMetadataStore(); pixelSizeX = metadataStore.getPixelsPhysicalSizeX(iSeries); % Pixel size might be automatically set to 1.0 by @#$% Metamorph hasValidPixelSizeX = ~isempty(pixelSizeX) && pixelSizeX.getValue() ~= 1; if hasValidPixelSizeX % Convert from microns to nm and check x and y values are equal pixelSizeY = metadataStore.getPixelsPhysicalSizeX(iSeries); if ~isempty(pixelSizeY), assert(isequal(pixelSizeX.getValue(), pixelSizeY.getValue()),... 'Pixel size different in x and y'); end pixelSizeX = pixelSizeX.getValue() *10^3; movieArgs = horzcat(movieArgs,'pixelSize_',pixelSizeX); end pixelSizeZ = metadataStore.getPixelsPhysicalSizeZ(iSeries); % Pixel size might be automatically set to 1.0 by @#$% Metamorph hasValidPixelSizeZ = ~isempty(pixelSizeZ) && pixelSizeZ.getValue() ~= 1; if hasValidPixelSizeZ % Convert from microns to nm and check x and y values are equal pixelSizeZ = pixelSizeZ.getValue() * 10^3; movieArgs = horzcat(movieArgs,'pixelSizeZ_',pixelSizeZ); end % Camera bit depth camBitdepth = r.getBitsPerPixel(); hasValidCamBitDepth = ~isempty(camBitdepth) && mod(camBitdepth, 2) == 0; if hasValidCamBitDepth movieArgs=horzcat(movieArgs,'camBitdepth_',camBitdepth); end % Time interval timeInterval = metadataStore.getPixelsTimeIncrement(iSeries); if ~isempty(timeInterval) movieArgs=horzcat(movieArgs,'timeInterval_',double(timeInterval)); end % Lens numerical aperture try % Use a try-catch statement because property is not always defined lensNA = metadataStore.getObjectiveLensNA(0,0); if ~isempty(lensNA) movieArgs=horzcat(movieArgs,'numAperture_',double(lensNA)); elseif ~isempty(metadataStore.getObjectiveID(0,0)) % Hard-coded for deltavision files. Try to get the objective id and % read the objective na from a lookup table tokens=regexp(char(metadataStore.getObjectiveID(0,0).toString),... '^Objective\:= (\d+)$','once','tokens'); if ~isempty(tokens) [na,mag]=getLensProperties(str2double(tokens),{'na','magn'}); movieArgs=horzcat(movieArgs,'numAperture_',na,'magnification_',mag); end end end function channelArgs = getChannelMetadata(r, iSeries, iChan) channelArgs={}; % Read channel name channelName = r.getMetadataStore().getChannelName(iSeries, iChan); if ~isempty(channelName) channelArgs=horzcat(channelArgs, 'name_', char(channelName)); end % Read excitation wavelength exwlgth=r.getMetadataStore().getChannelExcitationWavelength(iSeries, iChan); if ~isempty(exwlgth) channelArgs=horzcat(channelArgs, 'excitationWavelength_', exwlgth.getValue); end % Fill emission wavelength emwlgth=r.getMetadataStore().getChannelEmissionWavelength(iSeries, iChan); if isempty(emwlgth) try emwlgth= r.getMetadataStore().getChannelLightSourceSettingsWavelength(iSeries, iChan); end end if ~isempty(emwlgth) channelArgs = horzcat(channelArgs, 'emissionWavelength_', emwlgth.getValue); end % Read imaging mode acquisitionMode = r.getMetadataStore().getChannelAcquisitionMode(iSeries, iChan); if ~isempty(acquisitionMode), acquisitionMode = char(acquisitionMode.toString); switch acquisitionMode case {'TotalInternalReflection','TIRF'} channelArgs = horzcat(channelArgs, 'imageType_', 'TIRF'); case 'WideField' channelArgs = horzcat(channelArgs, 'imageType_', 'Widefield'); case {'SpinningDiskConfocal','SlitScanConfocal','LaserScanningConfocalMicroscopy'} channelArgs = horzcat(channelArgs, 'imageType_', 'Confocal'); otherwise disp('Acqusition mode not supported by the Channel object'); end end % Read fluorophore fluorophore = r.getMetadataStore().getChannelFluor(iSeries, iChan); if ~isempty(fluorophore), fluorophores = Channel.getFluorophores(); isFluorophore = strcmpi(fluorophore, fluorophores); if ~any(isFluorophore), disp('Fluorophore not supported by the Channel object'); else channelArgs = horzcat(channelArgs, 'fluorophore_',... fluorophores(find(isFluorophore, 1))); end end
github
mehta-lab/Instantaneous-PolScope-master
userfcn_saveCheckbox.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/userfcn_saveCheckbox.m
1,238
utf_8
e39588a918fae19c1fcec72fe9fa2ead
function checked = userfcn_saveCheckbox(handles) % GUI tool function - return the check/uncheck status of checkbox of % processes in package control panel % % Input: % % handles - the "handles" of package control panel movie % % Output: % % checked - array of check/unchecked status 1 - checked, 0 - unchecked % % % Chuangang Ren % 08/2010 % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % userData = get(handles.figure1, 'UserData'); l = 1:size(userData.dependM, 1); checked = arrayfun( @(x)( eval(['get(handles.checkbox_' num2str(x) ', ''Value'')']) ), l, 'UniformOutput', true);
github
mehta-lab/Instantaneous-PolScope-master
msgboxGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/msgboxGUI.m
5,815
utf_8
bb522a760915f439bbb09ed82ae26155
function varargout = msgboxGUI(varargin) % MSGBOXGUI M-file for msgboxGUI.fig % MSGBOXGUI, by itself, creates a new MSGBOXGUI or raises the existing % singleton*. % % H = MSGBOXGUI returns the handle to a new MSGBOXGUI or the handle to % the existing singleton*. % % MSGBOXGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in MSGBOXGUI.M with the given input arguments. % % MSGBOXGUI('Property','Value',...) creates a new MSGBOXGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before msgboxGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to msgboxGUI_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 % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help msgboxGUI % Last Modified by GUIDE v2.5 07-Sep-2011 11:43:10 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @msgboxGUI_OpeningFcn, ... 'gui_OutputFcn', @msgboxGUI_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 msgboxGUI is made visible. function msgboxGUI_OpeningFcn(hObject, eventdata, handles, varargin) % % fhandle = msgboxGUI % % fhandle = msgboxGUI(paramName, 'paramValue', ... ) % % Help dialog GUI % % Parameter Field Names: % 'text' -> Help text % 'title' -> Title of text box % 'name'-> Name of dialog box % % Choose default command line output for msgboxGUI handles.output = hObject; % Parse input ip = inputParser; ip.CaseSensitive=false; ip.addRequired('hObject',@ishandle); ip.addRequired('eventdata',@(x) isstruct(x) || isempty(x)); ip.addRequired('handles',@isstruct); ip.addParamValue('text','',@ischar); ip.addParamValue('extendedText','',@ischar); ip.addParamValue('name','',@ischar); ip.addParamValue('title','',@ischar); ip.parse(hObject,eventdata,handles,varargin{:}); % Apply input set(hObject, 'Name',ip.Results.name) set(handles.edit_text, 'String',ip.Results.text) set(handles.text_title, 'string',ip.Results.title) if ~isempty(ip.Results.extendedText), userData = get(handles.figure1,'UserData'); if isempty(userData), userData = struct(); end set(handles.pushbutton_extendedText,'Visible','on'); userData.text = ip.Results.text; userData.extendedText=ip.Results.extendedText; userData.type='basic'; set(handles.figure1,'UserData',userData); end % Update handles structure uicontrol(handles.pushbutton_done) guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = msgboxGUI_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 pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) delete(handles.figure1) % --- Executes on key press with focus on figure1 or any of its controls. function figure1_WindowKeyPressFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata structure with the following fields (see FIGURE) % Key: name of the key that was pressed, in lower case % Character: character interpretation of the key(s) that was pressed % Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed % handles structure with handles and user data (see GUIDATA) if strcmp(eventdata.Key, 'return'), delete(hObject); end % --- Executes on button press in pushbutton_extendedText. function pushbutton_extendedText_Callback(hObject, eventdata, handles) % hObject handle to pushbutton_extendedText (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) userData=get(handles.figure1,'UserData'); if isempty(userData), userData = struct(); end if strcmp(userData.type,'basic') userData.type='extended'; set(handles.edit_text, 'String',userData.extendedText); set(hObject,'String','See basic report...'); else userData.type='basic'; set(handles.edit_text, 'String',userData.text); set(hObject,'String','See extended report...'); end set(handles.figure1,'UserData',userData); guidata(hObject,handles);
github
mehta-lab/Instantaneous-PolScope-master
isSubclass.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/isSubclass.m
2,097
utf_8
3df6753cfcbfca84196cda5fc7a52ad9
function status = isSubclass(classname,parentname) %ISSUBCLASS check if a class inherits from a parent class % % Synopsis status = isSubclass(classname,parentname) % % Input: % classname - a string giving the name of the class (child) % % parentname - a string giving the name of the parent class % % Output % status - boolean. Return true if class is a child of parent. False % otherwise % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Sebastien Besson, Jan 2012 % Generalization of xunit.utils.isTestCaseSubClass from Steven L. Eddins % Input check ip =inputParser; ip.addRequired('classname',@ischar); ip.addRequired('parentname',@ischar); ip.parse(classname,parentname); % Check validity of child class class_meta = meta.class.fromName(classname); assert(~isempty(class_meta),' %s is not a valid class',classname); % Check validity of parent class assert(~isempty(meta.class.fromName(parentname)),' %s is not a valid parent class',parentname); % Call recursively class name status = isMetaSubclass(class_meta,parentname); function status = isMetaSubclass(class_meta,parentname) % Initialize output status = false; if strcmp(class_meta.Name, parentname), status = true; return; end % Call function recursively on parent classes (for multiple inheritance) super_classes = class_meta.SuperClasses; for k = 1:numel(super_classes) if isMetaSubclass(super_classes{k},parentname) status = true; break; end end
github
mehta-lab/Instantaneous-PolScope-master
plotScaleBar.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/plotScaleBar.m
4,008
utf_8
b7aeaf3895797ded1420a884739be339
%plotScaleBar(width, varargin) adds a scale bar to a figure. % % Inputs: width : width of the scale bar, in x-axis units. % h : axes handle. If empty, current axes ('gca') are used. % varargin : optional inputs, always in name/value pairs: % 'Location' : {'NorthEast', 'SouthEast', 'SouthWest', 'NorthWest'} % 'Label' : string % 'FontName' % 'FontSize' % % Ouput: hScalebar : handle to the patch graphic object and text graphic % object if applicable % % Example: plotScalebar(500, [], 'Label', '500 nm', 'Location', 'SouthEast'); % % % Note: there is a bug in '-depsc2' as of Matlab2010b, which misprints patches. % When printing, use 'depsc' instead. % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Francois Aguet, March 14 2011 (last modified 07/26/2011) function hScaleBar = plotScaleBar(width, varargin) ip = inputParser; ip.CaseSensitive = false; ip.addRequired('width', @isscalar); % same units as axes ip.addOptional('height', width/10, @isscalar); % height of the scale bar ip.addParamValue('Handle', gca, @ishandle) ip.addParamValue('Location', 'southwest', @(x) any(strcmpi(x, {'northeast', 'southeast', 'southwest', 'northwest'}))); ip.addParamValue('Label', [], @(x) ischar(x) || isempty(x)); ip.addParamValue('FontName', 'Helvetica', @ischar); ip.addParamValue('FontSize', [], @isscalar); ip.addParamValue('Color', [1 1 1], @(x) isvector(x) && numel(x)==3); ip.parse(width, varargin{:}); label = ip.Results.Label; fontName = ip.Results.FontName; fontSize = ip.Results.FontSize; color = ip.Results.Color; height = ip.Results.height; location = lower(ip.Results.Location); if ~isempty(fontSize) fontUnits = 'points'; else fontUnits = 'normalized'; end XLim = get(ip.Results.Handle, 'XLim'); YLim = get(ip.Results.Handle, 'YLim'); lx = diff(XLim); ly = diff(YLim); dx = ly/20; % distance from border if ~isempty(label) if isempty(fontSize) fontSize = 3*height/ly; % normalized units end % get height of default text bounding box h = text(0, 0, label, 'FontUnits', fontUnits, 'FontName', fontName, 'FontSize', fontSize); extent = get(h, 'extent'); % units: pixels textHeight = 1.2*extent(4); textWidth = extent(3); delete(h); else textHeight = dx; textWidth = 0; end hold(ip.Results.Handle, 'on'); set(gcf, 'InvertHardcopy', 'off'); if ~isempty(strfind(location, 'north')) y0 = dx; else y0 = ly-height-textHeight; end if ~isempty(strfind(location, 'east')) x0 = lx-width-dx; else x0 = dx; end x0 = x0+XLim(1); y0 = y0+YLim(1); % text alignment if > scalebar width if textWidth > width if ~isempty(strfind(ip.Results.Location, 'west')) halign = 'left'; tx = x0; else halign = 'right'; tx = x0+width; end else halign = 'center'; tx = x0+width/2; end textProps = {'Color', color, 'FontUnits', fontUnits,... 'FontName', fontName, 'FontSize', fontSize,... 'VerticalAlignment', 'Top',... 'HorizontalAlignment', halign}; hScaleBar(1) = fill([x0 x0+width x0+width x0], [y0+height y0+height y0 y0],... color, 'EdgeColor', 'none', 'Parent', ip.Results.Handle); if ~isempty(label) hScaleBar(2) = text(tx, y0+height, label, textProps{:}, 'Parent', ip.Results.Handle); end
github
mehta-lab/Instantaneous-PolScope-master
costMatRandomDirectedSwitchingMotionCloseGapsGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/costMatRandomDirectedSwitchingMotionCloseGapsGUI.m
14,630
utf_8
95fb6a930421a0f524720e7a557648f1
function varargout = costMatRandomDirectedSwitchingMotionCloseGapsGUI(varargin) % COSTMATRANDOMDIRECTEDSWITCHINGMOTIONCLOSEGAPSGUI M-file for costMatRandomDirectedSwitchingMotionCloseGapsGUI.fig % COSTMATRANDOMDIRECTEDSWITCHINGMOTIONCLOSEGAPSGUI, by itself, creates a new COSTMATRANDOMDIRECTEDSWITCHINGMOTIONCLOSEGAPSGUI or raises the existing % singleton*. % % H = COSTMATRANDOMDIRECTEDSWITCHINGMOTIONCLOSEGAPSGUI returns the handle to a new COSTMATRANDOMDIRECTEDSWITCHINGMOTIONCLOSEGAPSGUI or the handle to % the existing singleton*. % % COSTMATRANDOMDIRECTEDSWITCHINGMOTIONCLOSEGAPSGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in COSTMATRANDOMDIRECTEDSWITCHINGMOTIONCLOSEGAPSGUI.M with the given input arguments. % % COSTMATRANDOMDIRECTEDSWITCHINGMOTIONCLOSEGAPSGUI('Property','Value',...) creates a new COSTMATRANDOMDIRECTEDSWITCHINGMOTIONCLOSEGAPSGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before costMatRandomDirectedSwitchingMotionCloseGapsGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to costMatRandomDirectedSwitchingMotionCloseGapsGUI_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 % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help costMatRandomDirectedSwitchingMotionCloseGapsGUI % Last Modified by GUIDE v2.5 12-Dec-2011 15:51:50 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @costMatRandomDirectedSwitchingMotionCloseGapsGUI_OpeningFcn, ... 'gui_OutputFcn', @costMatRandomDirectedSwitchingMotionCloseGapsGUI_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 costMatRandomDirectedSwitchingMotionCloseGapsGUI is made visible. function costMatRandomDirectedSwitchingMotionCloseGapsGUI_OpeningFcn(hObject, eventdata, handles, varargin) costMat_OpeningFcn(hObject, eventdata, handles, varargin{:}) userData = get(handles.figure1, 'UserData'); if(isempty(userData)), userData = struct(); end; parameters = userData.parameters; % Brownian motion parameters set(handles.edit_lower, 'String', num2str(parameters.minSearchRadius)) set(handles.edit_upper, 'String', num2str(parameters.maxSearchRadius)) set(handles.edit_brownStdMult, 'String', num2str(parameters.brownStdMult(1))) set(handles.checkbox_useLocalDensity, 'Value', parameters.useLocalDensity) set(handles.edit_nnWindow, 'String', num2str(parameters.nnWindow)) set(handles.edit_before, 'String', num2str(parameters.brownScaling(1))) set(handles.edit_after, 'String', num2str(parameters.brownScaling(2))) set(handles.edit_gapLengthTransitionB, 'String', num2str(parameters.timeReachConfB-1)) set(handles.edit_gapPenalty, 'String', num2str(parameters.gapPenalty)); % Directed Motion parameters if parameters.linearMotion set(get(handles.uipanel_linearMotion,'Children'),'Enable','on'); set(handles.edit_lenForClassify, 'String', num2str(parameters.lenForClassify)) set(handles.edit_linStdMult, 'String', num2str(parameters.linStdMult(1))) set(handles.edit_before_2, 'String', num2str(parameters.linScaling(1))) set(handles.edit_after_2, 'String', num2str(parameters.linScaling(2))) set(handles.edit_gapLengthTransitionL, 'String', num2str(parameters.timeReachConfL-1)) set(handles.edit_maxAngleVV, 'String', num2str(parameters.maxAngleVV)) else set(get(handles.uipanel_linearMotion,'Children'),'Enable','off'); end set(handles.checkbox_linearMotion, 'Value', logical(parameters.linearMotion),'Enable','off'); set(handles.checkbox_immediateDirectionReversal, 'Value', parameters.linearMotion==2,'Enable','off'); % Merging/splitting parameters mergeSplitComponents = findobj(handles.uipanel_mergeSplit,'-not','Type','uipanel'); if get(userData.handles_main.checkbox_merging,'Value') || ... get(userData.handles_main.checkbox_splitting,'Value') set(mergeSplitComponents,'Enable','on'); if isempty(parameters.ampRatioLimit) || ... (length(parameters.ampRatioLimit) ==1 && parameters.ampRatioLimit == 0) set(handles.checkbox_ampRatioLimit, 'Value', 0) set(get(handles.uipanel_ampRatioLimit,'Children'),'Enable','off'); else set(get(handles.uipanel_ampRatioLimit,'Children'),'Enable','on'); set(handles.edit_min, 'String', num2str(parameters.ampRatioLimit(1))) set(handles.edit_max, 'String', num2str(parameters.ampRatioLimit(2))) end set(handles.edit_resLimit, 'String', num2str(parameters.resLimit)) else set(mergeSplitComponents,'Enable','off'); end % Update handles structure handles.output = hObject; guidata(hObject, handles); % UIWAIT makes costMatRandomDirectedSwitchingMotionCloseGapsGUI wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = costMatRandomDirectedSwitchingMotionCloseGapsGUI_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 pushbutton_cancel. function pushbutton_cancel_Callback(hObject, eventdata, handles) % hObject handle to pushbutton_cancel (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) delete(handles.figure1) % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) % hObject handle to pushbutton_done (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) userData = get(handles.figure1, 'UserData'); if(isempty(userData)), userData = struct(); end; parameters = userData.parameters; % Brownian motion parameters minSearchRadius = str2double(get(handles.edit_lower, 'String')); maxSearchRadius = str2double(get(handles.edit_upper, 'String')); brownStdMult = str2double(get(handles.edit_brownStdMult, 'String')); nnWindow = str2double(get(handles.edit_nnWindow, 'String')); brownScaling_1 = str2double(get(handles.edit_before, 'String')); brownScaling_2 = str2double(get(handles.edit_after, 'String')); gapLengthTransitionB = str2double(get(handles.edit_gapLengthTransitionB, 'String')); isPosScalar = @(x) isscalar(x) &&~isnan(x) && x>=0; % lower if ~isPosScalar(minSearchRadius) errordlg('Please provide a valid value to parameter "Lower Bound".','Error','modal') return end % Upper if ~isPosScalar(maxSearchRadius) errordlg('Please provide a valid value to parameter "Upper Bound".','Error','modal') return elseif maxSearchRadius < minSearchRadius errordlg('"Upper Bound" should be larger than "Lower Bound".','Error','modal') return end % brownStdMult if ~isPosScalar(brownStdMult) errordlg('Please provide a valid value to parameter "Multiplication Factor for Search Radius Calculation".','Error','modal') return end brownStdMult = brownStdMult*ones(userData.crtProc.funParams_.gapCloseParam.timeWindow,1); % nnWindow if ~isposint(nnWindow) errordlg('Please provide a valid value to parameter "Number of Frames for Nearest Neighbor Distance Calculation".','Error','modal') return end % brownScaling if ~isPosScalar(brownScaling_1) errordlg('Please provide a valid value to parameter "Scaling Power in Fast Expansion Phase".','Error','modal') return end % brownScaling if ~isPosScalar(brownScaling_2) errordlg('Please provide a valid value to parameter "Scaling Power in Slow Expansion Phase".','Error','modal') return end brownScaling = [brownScaling_1 brownScaling_2]; % gapLengthTransitionB if ~isPosScalar(gapLengthTransitionB) errordlg('Please provide a valid value to parameter "Gap length to transition from Fast to Slow Expansion".','Error','modal') return end % gapPenalty gapPenalty = get(handles.edit_gapPenalty, 'String'); if isempty(gapPenalty) gapPenalty = []; else gapPenalty = str2double(gapPenalty); if ~isPosScalar(gapPenalty) errordlg('Please provide a valid value to parameter "Time to Reach Confinement".','Error','modal') return end end parameters.minSearchRadius = minSearchRadius; parameters.maxSearchRadius = maxSearchRadius; parameters.brownStdMult = brownStdMult; parameters.useLocalDensity = get(handles.checkbox_useLocalDensity, 'Value'); parameters.nnWindow = nnWindow; parameters.brownScaling = brownScaling; parameters.timeReachConfB = gapLengthTransitionB+1; parameters.gapPenalty = gapPenalty; % Merging/splitting parameters if get(userData.handles_main.checkbox_merging,'Value') || ... get(userData.handles_main.checkbox_splitting,'Value') if ~get(handles.checkbox_ampRatioLimit, 'Value') ampRatioLimit = []; else ampRatioLimit_1 = str2double(get(handles.edit_min, 'String')); ampRatioLimit_2 = str2double(get(handles.edit_max, 'String')); % ampRatioLimit_1 if ~isPosScalar(ampRatioLimit_1) errordlg('Please provide a valid value to parameter "Min Allowed".','Error','modal') return end % ampRatioLimit_2 if ~isPosScalar(ampRatioLimit_2) errordlg('Please provide a valid value to parameter "Max Allowed".','Error','modal') return end if ampRatioLimit_2 <= ampRatioLimit_1 errordlg('"Max Allowed" should be larger than "Min Allowed".','Error','modal') return end ampRatioLimit = [ampRatioLimit_1 ampRatioLimit_2]; end % resLimit resLimit = get(handles.edit_resLimit, 'String'); if isempty( resLimit ) resLimit = []; else resLimit = str2double(resLimit); if ~isPosScalar(resLimit) errordlg('Please provide a valid value to parameter "Time to Reach Confinement".','Error','modal') return end end parameters.ampRatioLimit = ampRatioLimit; parameters.resLimit = resLimit; end % Linear motion parameters if parameters.linearMotion lenForClassify = str2double(get(handles.edit_lenForClassify, 'String')); linStdMult = str2double(get(handles.edit_linStdMult, 'String')); linScaling_1 = str2double(get(handles.edit_before_2, 'String')); linScaling_2 = str2double(get(handles.edit_after_2, 'String')); gapLengthTransitionL = str2double(get(handles.edit_gapLengthTransitionL, 'String')); maxAngleVV = str2double(get(handles.edit_maxAngleVV, 'String')); % lenForClassify if ~isPosScalar(lenForClassify) errordlg('Please provide a valid value to parameter "Minimum Track Segment Length to Classify it as Linear or Random".','Error','modal') return end % linStdMult if ~isPosScalar(linStdMult) errordlg('Please provide a valid value to parameter "Multiplication Factor for Linear Search Radius Calculation".','Error','modal') return end linStdMult = linStdMult*ones(userData.crtProc.funParams_.gapCloseParam.timeWindow,1); % linScaling_1 if ~isPosScalar(linScaling_1) errordlg('Please provide a valid value to parameter "Scaling Power in Fast Expansion Phase".','Error','modal') return end % linScaling_1 if ~isPosScalar(linScaling_2) errordlg('Please provide a valid value to parameter "Scaling Power in Slow Expansion Phase".','Error','modal') return end linScaling = [linScaling_1 linScaling_2]; % gapLengthTransitionL if ~isPosScalar(gapLengthTransitionL) errordlg('Please provide a valid value to parameter "Gap length to transition from Fast to Slow Expansion".','Error','modal') return end % maxAngleVV if ~isPosScalar(maxAngleVV) errordlg('Please provide a valid value to parameter "Maximum Angle Between Linear Track Segments".','Error','modal') return end parameters.lenForClassify = lenForClassify; parameters.linStdMult = linStdMult; parameters.linScaling = linScaling; parameters.timeReachConfL = gapLengthTransitionL+1; parameters.maxAngleVV = maxAngleVV; end u = get(userData.handles_main.popupmenu_gapclosing, 'UserData'); u{userData.procID} = parameters; set(userData.handles_main.popupmenu_gapclosing, 'UserData', u) set(handles.figure1, 'UserData', userData); guidata(hObject,handles); delete(handles.figure1); % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(hObject, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on button press in checkbox_ampRatioLimit. function checkbox_ampRatioLimit_Callback(hObject, eventdata, handles) if get(hObject, 'Value') set(get(handles.uipanel_ampRatioLimit,'Children'),'Enable','on'); else set(get(handles.uipanel_ampRatioLimit,'Children'),'Enable','off'); end
github
mehta-lab/Instantaneous-PolScope-master
cropMovieGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/cropMovieGUI.m
13,292
utf_8
632f4b6f0da5496d9638d67fbc8a79de
function varargout = cropMovieGUI(varargin) % cropMovieGUI M-file for cropMovieGUI.fig % cropMovieGUI, by itself, creates a new cropMovieGUI or raises the existing % singleton*. % % H = cropMovieGUI returns the handle to a new cropMovieGUI or the handle to % the existing singleton*. % % cropMovieGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in cropMovieGUI.M with the given input arguments. % % cropMovieGUI('Property','Value',...) creates a new cropMovieGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before cropMovieGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to cropMovieGUI_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 % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help cropMovieGUI % Last Modified by GUIDE v2.5 30-Sep-2011 15:09:12 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @cropMovieGUI_OpeningFcn, ... 'gui_OutputFcn', @cropMovieGUI_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 cropMovieGUI is made visible. function cropMovieGUI_OpeningFcn(hObject,eventdata,handles,varargin) % Check input % The mainFig and procID should always be present % procCOnstr and procName should only be present if the concrete process % initation is delegated from an abstract class. Else the constructor will % be directly read from the package constructor list. ip = inputParser; ip.addRequired('hObject',@ishandle); ip.addRequired('eventdata',@(x) isstruct(x) || isempty(x)); ip.addRequired('handles',@isstruct); ip.addOptional('MD',[],@(x)isa(x,'MovieData')); ip.addParamValue('mainFig',-1,@ishandle); ip.parse(hObject,eventdata,handles,varargin{:}); userData.MD =ip.Results.MD; userData.mainFig =ip.Results.mainFig; % Set up copyright statement set(handles.text_copyright, 'String', getLCCBCopyright()); % Set up available input channels set(handles.listbox_selectedChannels,'String',userData.MD.getChannelPaths(), ... 'UserData',1:numel(userData.MD.channels_)); % Save the image directories and names (for cropping preview) userData.nFrames = userData.MD.nFrames_; userData.imRectHandle.isvalid=0; userData.cropROI = [1 1 userData.MD.imSize_(end:-1:1)]; userData.previewFig=-1; % Read the first image and update the sliders max value and steps props = get(handles.listbox_selectedChannels, {'UserData','Value'}); userData.chanIndx = props{1}(props{2}); set(handles.edit_frameNumber,'String',1); set(handles.slider_frameNumber,'Min',1,'Value',1,'Max',userData.nFrames,... 'SliderStep',[1/max(1,double(userData.nFrames-1)) 10/max(1,double(userData.nFrames-1))]); userData.imIndx=1; userData.imData=mat2gray(userData.MD.channels_(userData.chanIndx).loadImage(userData.imIndx)); set(handles.listbox_selectedChannels,'Callback',@(h,event) update_data(h,event,guidata(h))); set(handles.edit_firstFrame,'String',1); set(handles.edit_lastFrame,'String',userData.nFrames); % Choose default command line output for cropMovieGUI handles.output = hObject; % Update user data and GUI data set(hObject, 'UserData', userData); guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = cropMovieGUI_OutputFcn(~, ~, 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 pushbutton_cancel. function pushbutton_cancel_Callback(~, ~, handles) % Delete figure delete(handles.figure1); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, ~, handles) % Notify the package GUI that the setting panel is closed userData = get(handles.figure1, 'UserData'); if isfield(userData, 'helpFig') && ishandle(userData.helpFig) delete(userData.helpFig) end if ishandle(userData.previewFig), delete(userData.previewFig); end set(handles.figure1, 'UserData', userData); guidata(hObject,handles); % --- Executes on key press with focus on pushbutton_crop and none of its controls. function pushbutton_crop_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_crop, [], handles); end % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_crop, [], handles); end % --- Executes on button press in checkbox_crop. function update_data(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); % Retrieve the channel index props=get(handles.listbox_selectedChannels,{'UserData','Value'}); chanIndx = props{1}(props{2}); imIndx = get(handles.slider_frameNumber,'Value'); % Load a new image if either the image number or the channel has been changed if (chanIndx~=userData.chanIndx) || (imIndx~=userData.imIndx) % Update image flag and dat userData.imData=mat2gray(userData.MD.channels_(chanIndx).loadImage(imIndx)); userData.updateImage=1; userData.chanIndx=chanIndx; userData.imIndx=imIndx; % Update roi if userData.imRectHandle.isvalid userData.cropROI=getPosition(userData.imRectHandle); end else userData.updateImage=0; end % In case of crop previewing mode if get(handles.checkbox_crop,'Value') % Create figure if non-existing or closed if ~isfield(userData, 'previewFig') || ~ishandle(userData.previewFig) userData.previewFig = figure('Name','Select the region to crop',... 'DeleteFcn',@close_previewFig,'UserData',handles.figure1); userData.newFigure = 1; else figure(userData.previewFig); userData.newFigure = 0; end % Retrieve the image object handle imHandle =findobj(userData.previewFig,'Type','image'); if userData.newFigure || userData.updateImage if isempty(imHandle) imHandle=imshow(userData.imData); axis off; else set(imHandle,'CData',userData.imData); end end if userData.imRectHandle.isvalid % Update the imrect position setPosition(userData.imRectHandle,userData.cropROI) else % Create a new imrect object and store the handle userData.imRectHandle = imrect(get(imHandle,'Parent'),userData.cropROI); fcn = makeConstrainToRectFcn('imrect',get(imHandle,'XData'),get(imHandle,'YData')); setPositionConstraintFcn(userData.imRectHandle,fcn); end else % Save the roi if applicable if userData.imRectHandle.isvalid, userData.cropROI=getPosition(userData.imRectHandle); end % Close the figure if applicable if ishandle(userData.previewFig), delete(userData.previewFig); end end set(handles.figure1, 'UserData', userData); guidata(hObject,handles); function close_previewFig(hObject, eventdata) handles = guidata(get(hObject,'UserData')); set(handles.checkbox_crop,'Value',0); update_data(handles.checkbox_crop, eventdata, handles); % --- Executes on slider movement. function frameNumberEdition_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); % Retrieve the value of the selected image if strcmp(get(hObject,'Tag'),'edit_frameNumber') frameNumber = str2double(get(handles.edit_frameNumber, 'String')); else frameNumber = get(handles.slider_frameNumber, 'Value'); end frameNumber=round(frameNumber); % Check the validity of the frame values if isnan(frameNumber) warndlg('Please provide a valid frame value.','Setting Error','modal'); end frameNumber = min(max(frameNumber,1),userData.nFrames); % Store value set(handles.slider_frameNumber,'Value',frameNumber); set(handles.edit_frameNumber,'String',frameNumber); % Save data and update graphics set(handles.figure1, 'UserData', userData); guidata(hObject, handles); update_data(hObject,eventdata,handles); % --- Executes on button press in pushbutton_outputDirectory. function pushbutton_outputDirectory_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); pathname = uigetdir(userData.MD.movieDataPath_,'Select output directory'); % Test uigetdir output and store its results if isequal(pathname,0), return; end set(handles.edit_outputDirectory,'String',pathname); % Save data set(handles.figure1,'UserData',userData); guidata(hObject, handles); % --- Executes on button press in pushbutton_addfile. function pushbutton_addfile_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); [filename, pathname]=uigetfile({'*.tif;*.TIF;*.stk;*.STK;*.bmp;*.BMP;*.jpg;*.JPG',... 'Image files (*.tif,*.stk,*.bmp,*.jpg)'},... 'Select the reference frame',userData.MD.movieDataPath_); % Test uigetdir output and store its results if isequal(pathname,0) || isequal(filename,0), return; end files = get(handles.listbox_additionalFiles,'String'); if any(strcmp([pathname filename],files)),return; end files{end+1} = [pathname filename]; set(handles.listbox_additionalFiles,'String',files,'Value',numel(files)); % --- Executes on button press in pushbutton_removeFile. function pushbutton_removeFile_Callback(hObject, eventdata, handles) props = get(handles.listbox_additionalFiles,{'String','Value'}); if isempty(props{1}), return; end files= props{1}; files(props{2})=[]; set(handles.listbox_additionalFiles,'String',files,'Value',max(1,props{2}-1)); % --- Executes on button press in pushbutton_crop. function pushbutton_crop_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); % Check valid output directory outputDirectory = get(handles.edit_outputDirectory,'String'); if isempty(outputDirectory), errordlg('Please select an output directory','Error','modal'); end % Read cropROI if crop window is still visible if userData.imRectHandle.isvalid userData.cropROI=getPosition(userData.imRectHandle); end % Read cropTOI firstFrame = str2double(get(handles.edit_firstFrame,'String')); lastFrame = str2double(get(handles.edit_lastFrame,'String')); cropTOI=firstFrame:lastFrame; additionalFiles= get(handles.listbox_additionalFiles,'String'); if isempty(additionalFiles) filesArgs={}; else filesArgs={'additionalFiles',additionalFiles}; end % Call the crop routine MD = cropMovie(userData.MD,outputDirectory,'cropROI',userData.cropROI,... 'cropTOI',cropTOI,filesArgs{:}); % If new MovieData was created (from movieSelectorGUI) if userData.mainFig ~=-1, % Retrieve main window userData userData_main = get(userData.mainFig, 'UserData'); % Append new ROI to movie selector panel userData_main.MD = horzcat(userData_main.MD, MD); set(userData.mainFig, 'UserData', userData_main) movieSelectorGUI('refreshDisplay',userData.mainFig,... eventdata,guidata(userData.mainFig)); end % Delete current window delete(handles.figure1) function edit_firstFrame_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); firstFrame = str2double(get(handles.edit_firstFrame,'String')); lastFrame = str2double(get(handles.edit_lastFrame,'String')); if ~ismember(firstFrame,1:userData.nFrames) || firstFrame>lastFrame set(handles.edit_firstFrame,'String',1) end function edit_lastFrame_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); firstFrame = str2double(get(handles.edit_firstFrame,'String')); lastFrame = str2double(get(handles.edit_lastFrame,'String')); if ~ismember(lastFrame,1:userData.nFrames) || firstFrame>lastFrame set(handles.edit_lastFrame,'String',userData.nFrames) end
github
mehta-lab/Instantaneous-PolScope-master
padarrayXT.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/padarrayXT.m
9,989
utf_8
022c2f55f7cc19443f657a7222e4b65c
function b = padarrayXT(varargin) %PADARRAYXT Modified version of built-in function 'padarray'. % Mirroring ('symmetric' option) does not duplicate the border pixel. % B = PADARRAYXT(A,PADSIZE) pads array A with PADSIZE(k) number of zeros % along the k-th dimension of A. PADSIZE should be a vector of % nonnegative integers. % % B = PADARRAYXT(A,PADSIZE,PADVAL) pads array A with PADVAL (a scalar) % instead of with zeros. % % B = PADARRAYXT(A,PADSIZE,PADVAL,DIRECTION) pads A in the direction % specified by the string DIRECTION. DIRECTION can be one of the % following strings. % % String values for DIRECTION % 'pre' Pads before the first array element along each % dimension . % 'post' Pads after the last array element along each % dimension. % 'both' Pads before the first array element and after the % last array element along each dimension. % % By default, DIRECTION is 'both'. % % B = PADARRAYXT(A,PADSIZE,METHOD,DIRECTION) pads array A using the % specified METHOD. METHOD can be one of these strings: % % String values for METHOD % 'circular' Pads with circular repetition of elements. % 'replicate' Repeats border elements of A. % 'symmetric' Pads array with mirror reflections of itself. % 'asymmetric' Pads array with odd-symmetric extensions of itself. % % Class Support % ------------- % When padding with a constant value, A can be numeric or logical. % When padding using the 'circular', 'replicate', or 'symmetric' % methods, A can be of any class. B is of the same class as A. % % Example % ------- % Add three elements of padding to the beginning of a vector. The % padding elements contain mirror copies of the array. % % b = padarrayxt([1 2 3 4],3,'symmetric','pre') % % Add three elements of padding to the end of the first dimension of % the array and two elements of padding to the end of the second % dimension. Use the value of the last array element as the padding % value. % % B = padarrayxt([1 2; 3 4],[3 2],'replicate','post') % % Add three elements of padding to each dimension of a % three-dimensional array. Each pad element contains the value 0. % % A = [1 2; 3 4]; % B = [5 6; 7 8]; % C = cat(3,A,B) % D = padarray(C,[3 3],0,'both') % % See also CIRCSHIFT, IMFILTER. % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Copyright 1993-2010 The MathWorks, Inc. % $Revision: 1.11.4.13 $ $Date: 2011/08/09 17:51:33 $ % Last modified on 04/14/2012 by Francois Aguet. [a, method, padSize, padVal, direction] = ParseInputs(varargin{:}); if isempty(a) % treat empty matrix similar for any method if strcmp(direction,'both') sizeB = size(a) + 2*padSize; else sizeB = size(a) + padSize; end b = mkconstarray(class(a), padVal, sizeB); elseif strcmpi(method,'constant') % constant value padding with padVal b = ConstantPad(a, padSize, padVal, direction); else % compute indices then index into input image aSize = size(a); aIdx = getPaddingIndices(aSize,padSize,method,direction); b = a(aIdx{:}); end if islogical(a) b = logical(b); end %%% %%% ConstantPad %%% function b = ConstantPad(a, padSize, padVal, direction) numDims = numel(padSize); % Form index vectors to subsasgn input array into output array. % Also compute the size of the output array. idx = cell(1,numDims); sizeB = zeros(1,numDims); for k = 1:numDims M = size(a,k); switch direction case 'pre' idx{k} = (1:M) + padSize(k); sizeB(k) = M + padSize(k); case 'post' idx{k} = 1:M; sizeB(k) = M + padSize(k); case 'both' idx{k} = (1:M) + padSize(k); sizeB(k) = M + 2*padSize(k); end end % Initialize output array with the padding value. Make sure the % output array is the same type as the input. b = mkconstarray(class(a), padVal, sizeB); b(idx{:}) = a; %%% %%% ParseInputs %%% function [a, method, padSize, padVal, direction] = ParseInputs(varargin) % narginchk(2,4); if nargin<2 || nargin>4 error('Incompatible number of input arguments.'); end % fixed syntax args a = varargin{1}; padSize = varargin{2}; % default values method = 'constant'; padVal = 0; direction = 'both'; validateattributes(padSize, {'double'}, {'real' 'vector' 'nonnan' 'nonnegative' ... 'integer'}, mfilename, 'PADSIZE', 2); % Preprocess the padding size if (numel(padSize) < ndims(a)) padSize = padSize(:); padSize(ndims(a)) = 0; end if nargin > 2 firstStringToProcess = 3; if ~ischar(varargin{3}) % Third input must be pad value. padVal = varargin{3}; validateattributes(padVal, {'numeric' 'logical'}, {'scalar'}, ... mfilename, 'PADVAL', 3); firstStringToProcess = 4; end for k = firstStringToProcess:nargin validStrings = {'circular' 'replicate' 'symmetric' 'pre' ... 'post' 'both'}; string = validatestring(varargin{k}, validStrings, mfilename, ... 'METHOD or DIRECTION', k); switch string case {'circular' 'replicate' 'symmetric'} method = string; case {'pre' 'post' 'both'} direction = string; otherwise error(message('images:padarray:unexpectedError')) end end end % Check the input array type if strcmp(method,'constant') && ~(isnumeric(a) || islogical(a)) error(message('images:padarray:badTypeForConstantPadding')) end % Internal functions called by padarray.m (modified) function aIdx = getPaddingIndices(aSize,padSize,method,direction) %getPaddingIndices is used by padarray and blockproc. % Computes padding indices of input image. This is function is used to % handle padding of in-memory images (via padarray) as well as % arbitrarily large images (via blockproc). % % aSize : result of size(I) where I is the image to be padded % padSize : padding amount in each dimension. % numel(padSize) can be greater than numel(aSize) % method : X or a 'string' padding method % direction : pre, post, or both. % % See the help for padarray for additional information. % Copyright 2010 The MathWorks, Inc. % $Revision: 1.1.6.1 $ $Date: 2010/04/15 15:18:15 $ % make sure we have enough image dims for the requested padding if numel(padSize) > numel(aSize) singleton_dims = numel(padSize) - numel(aSize); aSize = [aSize ones(1,singleton_dims)]; end switch method case 'circular' aIdx = CircularPad(aSize, padSize, direction); case 'symmetric' aIdx = SymmetricPad(aSize, padSize, direction); case 'replicate' aIdx = ReplicatePad(aSize, padSize, direction); end %%% %%% CircularPad %%% function idx = CircularPad(aSize, padSize, direction) numDims = numel(padSize); % Form index vectors to subsasgn input array into output array. % Also compute the size of the output array. idx = cell(1,numDims); for k = 1:numDims M = aSize(k); dimNums = uint32(1:M); p = padSize(k); switch direction case 'pre' idx{k} = dimNums(mod(-p:M-1, M) + 1); case 'post' idx{k} = dimNums(mod(0:M+p-1, M) + 1); case 'both' idx{k} = dimNums(mod(-p:M+p-1, M) + 1); end end %%% %%% SymmetricPad %%% function idx = SymmetricPad(aSize, padSize, direction) numDims = numel(padSize); % Form index vectors to subsasgn input array into output array. % Also compute the size of the output array. idx = cell(1,numDims); for k = 1:numDims M = aSize(k); if M>1 dimNums = uint32([1:M M-1:-1:2]); div = 2*M-2; else dimNums = [1 1]; div = 2; end p = padSize(k); switch direction case 'pre' idx{k} = dimNums(mod(-p:M-1, div) + 1); case 'post' idx{k} = dimNums(mod(0:M+p-1, div) + 1); case 'both' idx{k} = dimNums(mod(-p:M+p-1, div) + 1); end end %%% %%% ReplicatePad %%% function idx = ReplicatePad(aSize, padSize, direction) numDims = numel(padSize); % Form index vectors to subsasgn input array into output array. % Also compute the size of the output array. idx = cell(1,numDims); for k = 1:numDims M = aSize(k); p = padSize(k); onesVector = uint32(ones(1,p)); switch direction case 'pre' idx{k} = [onesVector 1:M]; case 'post' idx{k} = [1:M M*onesVector]; case 'both' idx{k} = [onesVector 1:M M*onesVector]; end end function out = mkconstarray(class, value, size) %MKCONSTARRAY creates a constant array of a specified numeric class. % A = MKCONSTARRAY(CLASS, VALUE, SIZE) creates a constant array % of value VALUE and of size SIZE. % Copyright 1993-2003 The MathWorks, Inc. % $Revision: 1.8.4.1 $ $Date: 2003/01/26 06:00:35 $ out = repmat(feval(class, value), size);
github
mehta-lab/Instantaneous-PolScope-master
getFluorPropStruct.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/getFluorPropStruct.m
2,343
utf_8
73fa811827f9f106a7b9a1508776eab0
% Values from http://www.olympusfluoview.com/applications/fpcolorpalette.html % Alexa Fluors: http://www.invitrogen.com/site/us/en/home/References/Molecular-Probes-The-Handbook/Technical-Notes-and-Product-Highlights/The-Alexa-Fluor-Dye-Series.html % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Francois Aguet, October 2010 function s = getFluorPropStruct() s(1).name = 'bfp'; s(1).lambda_em = 440e-9; s(2).name = 'ebfp'; s(2).lambda_em = 440e-9; s(3).name = 'cfp'; s(3).lambda_em = 475e-9; s(4).name = 'egfp'; s(4).lambda_em = 507e-9; s(5).name = 'gfp'; s(5).lambda_em = 509e-9; s(6).name = 'alexa488'; s(6).lambda_em = 519e-9; s(7).name = 'yfp'; s(7).lambda_em = 527e-9; s(8).name = 'alexa555'; s(8).lambda_em = 565e-9; s(9).name = 'dtomato'; s(9).lambda_em = 581e-9; s(10).name = 'tdtomato'; s(10).lambda_em = 581e-9; s(11).name = 'dsred'; s(11).lambda_em = 583e-9; s(12).name = 'tagrfp'; s(12).lambda_em = 584e-9; s(13).name = 'alexa568'; s(13).lambda_em = 603e-9; s(14).name = 'rfp'; s(14).lambda_em = 607e-9; s(15).name = 'mrfp'; s(15).lambda_em = 607e-9; s(16).name = 'mcherry'; s(16).lambda_em = 610e-9; s(17).name = 'texasred'; s(17).lambda_em = 615e-9; s(18).name = 'alexa647'; s(18).lambda_em = 665e-9; s(19).name = 'cy3'; s(19).lambda_em = 570e-9; s(20).name = 'cy5'; s(20).lambda_em = 670e-9; s(21).name = 'alexa594'; s(21).lambda_em = 617e-9; s(22).name = 'dapi'; s(22).lambda_em = 470e-9; s(23).name = 'fluosphere605'; s(23).lambda_em = 605e-9; s(24).name = 'meos'; s(24).lambda_em = 563e-9; s(25).name = 'turborfp'; s(25).lambda_em = 574e-9; s(26).name = 'mruby2'; s(26).lambda_em = 600e-9; s(27).name = 'tmr'; s(27).lambda_em = 578e-9; [~,i] = sort([s.lambda_em]); s = s(i);
github
mehta-lab/Instantaneous-PolScope-master
barplot2.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/barplot2.m
8,680
utf_8
da27be83188b815676132adcd89ea62b
%BARPLOT2 Bar plot grouping multiple sets/categories of data, with error bars. % % Inputs: prm : cell array of matrices that contain the box properties: % row 1: height % row 2: optional, error bars % errorbars : cell array colors, each containing a Nx3 matrix. Colors cycle through matrix. % % Options : see function content % % Examples: % % 1) Simple bar plot % figure; barplot2(rand(1,6), 0.1*rand(1,6), 'BarWidth', 0.8, 'XLabel', 'x label', 'YLabel', 'y label', ... % 'XTickLabel', arrayfun(@(k) ['S' num2str(k)], 1:6, 'unif', 0),... % 'Angle', 0, 'YLim', [0 1]); % % 2) Multiple groups % figure; barplot2(rand(6,3), 0.1*rand(6,3), 'BarWidth', 1, 'GroupDistance', 1, 'XLabel', 'x label', 'YLabel', 'y label', ... % 'XTickLabel', arrayfun(@(k) ['group ' num2str(k)], 1:6, 'unif', 0),... % 'Angle', 45, 'YLim', [0 1.2]); % % 3) Multiple groups, asymmetric error bars % figure; % eb = 0.5*ones(2,4); % barplot2([-2 1 -3 2; -2 1 -4 2], eb, eb/2, 'ErrorBarPosition', 'both',... % 'BarWidth', 1, 'GroupDistance', 1, 'XLabel', 'x label', 'YLabel', 'y label'); % % % Note: this function uses patch() since colors can't be controlled with bar() % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Francois Aguet, 18 March 2011 (Last modified: 1 Mar 2013) function [h, he] = barplot2(prm, varargin) ng = size(prm,1); % #groups nb = size(prm,2); % #bars in each group ip = inputParser; ip.CaseSensitive = false; ip.addRequired('prm'); ip.addOptional('errorbars', [], @(x) isempty(x) || all(size(x)==size(prm))); ip.addOptional('BottomErrorbars', [], @(x) isempty(x) || all(size(x)==size(prm))); ip.addOptional('Annotations', [], @(x) isempty(x) || size(x,2)==2); ip.addParamValue('FaceColor', jet(nb), @(x) any(size(x,1)==[1 nb ng])); ip.addParamValue('EdgeColor', []); ip.addParamValue('BorderWidth', [], @isscalar); ip.addParamValue('XLabel', ' ', @ischar); ip.addParamValue('YLabel', ' ', @ischar); ip.addParamValue('YLim', [], @(x) numel(x)==2); ip.addParamValue('YTick', []); ip.addParamValue('XTickLabel', [], @(x) isempty(x) || any(numel(x)==[nb ng]) || (iscell(x) && (numel(x)==sum(nb) || numel(x)==ng))); ip.addParamValue('BarWidth', 0.8, @isscalar); ip.addParamValue('GroupDistance', 0.8, @isscalar); ip.addParamValue('LineWidth', 1, @isscalar); ip.addParamValue('Angle', 45, @(x) isscalar(x) && (0<=x && x<=90)); ip.addParamValue('ErrorBarPosition', 'top', @(x) strcmpi(x, 'top') | strcmpi(x, 'both')); ip.addParamValue('ErrorBarWidth', 0.2, @(x) 0<x && x<=1); ip.addParamValue('Handle', gca, @ishandle); ip.addParamValue('Interpreter', 'tex', @(x) any(strcmpi(x, {'tex', 'latex', 'none'}))); ip.addParamValue('X', [], @(x) numel(x)==ng); % cell array of x-coordinates (groups only) ip.addParamValue('AdjustFigure', true, @islogical); ip.addParamValue('ErrorbarColor', []); % not yet implemented ip.parse(prm, varargin{:}); topErrorbars = ip.Results.errorbars; if isempty(ip.Results.BottomErrorbars) bottomErrorbars = topErrorbars; else bottomErrorbars = ip.Results.BottomErrorbars; end faceColor = ip.Results.FaceColor; if size(faceColor,1)==1 faceColor = repmat(faceColor, [nb 1]); end edgeColor = ip.Results.EdgeColor; if size(edgeColor,1)==1 edgeColor = repmat(edgeColor, [nb 1]); elseif isempty(edgeColor) edgeColor = zeros(size(faceColor)); end ha = ip.Results.Handle; bw = ip.Results.BarWidth; dg = ip.Results.GroupDistance; % distance between groups, in bar widths % x-coords for groups xa = cell(1,ng); if isempty(ip.Results.X) xa{1} = 1:nb; for g = 2:ng xa{g} = xa{1} + xa{g-1}(end) + dg; end else dx = min(diff(ip.Results.X)); for g = 1:ng w = (nb-1)/2; xa{g} = ip.Results.X(g) + (g-1)*dg + (-w:w)*dx/nb; end end if isempty(ip.Results.BorderWidth) if ng>1 border = bw/2+dg/2; else border = 1-bw/2; end else border = ip.Results.BorderWidth; end hold on; h = zeros(1,nb); topval = zeros(1,ng*nb); for g = 1:ng height = prm(g,:); % errorbars, if top only if ~isempty(topErrorbars)% && strcmpi(ip.Results.ErrorBarPosition, 'top') posIdx = height>=0; if sum(posIdx)>0 he = errorbar(xa{g}(posIdx), height(posIdx), zeros(1,sum(posIdx)), topErrorbars(g,posIdx),... 'k', 'LineStyle', 'none', 'LineWidth', ip.Results.LineWidth, 'HandleVisibility', 'off', 'Parent', ha); setErrorbarStyle(he, ip.Results.ErrorBarWidth, 'Position', 'top'); topval((g-1)*nb+find(posIdx)) = height(posIdx)+topErrorbars(g,posIdx); end posIdx = height<0; % negative values if sum(posIdx)>0 he = errorbar(xa{g}(posIdx), height(posIdx), bottomErrorbars(g,posIdx), zeros(1,sum(posIdx)),... 'k', 'LineStyle', 'none', 'LineWidth', ip.Results.LineWidth, 'HandleVisibility', 'off', 'Parent', ha); setErrorbarStyle(he, ip.Results.ErrorBarWidth, 'Position', 'bottom'); end %topval((g-1)*nb+find(posIdx) end % bars lb = xa{g} - bw/2; rb = xa{g} + bw/2; xv = [lb; rb; rb; lb; lb; rb]; yv = [height; height; zeros(1,nb); zeros(1,nb); height; height]; for b = 1:nb if size(faceColor,1)==nb ci = b; else ci = g; end hp = patch(xv(:,b), yv(:,b), faceColor(ci,:), 'EdgeColor', edgeColor(ci,:),... 'LineWidth', ip.Results.LineWidth, 'Parent', ha); if g==1 h(b) = hp; end end % errorbars, if two-sided if ~isempty(bottomErrorbars) && strcmpi(ip.Results.ErrorBarPosition, 'both') posIdx = height>=0; if sum(posIdx)>0 he = errorbar(xa{g}(posIdx), height(posIdx), bottomErrorbars(g,posIdx), zeros(1,sum(posIdx)),... 'k', 'LineStyle', 'none', 'LineWidth', ip.Results.LineWidth, 'HandleVisibility', 'off', 'Parent', ha); setErrorbarStyle(he, ip.Results.ErrorBarWidth, 'Position', 'bottom'); end posIdx = height<0; % negative values if sum(posIdx)>0 he = errorbar(xa{g}(posIdx), height(posIdx), zeros(1,sum(posIdx)), topErrorbars(g,posIdx),... 'k', 'LineStyle', 'none', 'LineWidth', ip.Results.LineWidth, 'HandleVisibility', 'off', 'Parent', ha); setErrorbarStyle(he, ip.Results.ErrorBarWidth, 'Position', 'top'); end end end % if there are negative values, plot axis if min(prm(:)) < 0 xAll = [xa{:}]; plot([xAll(1)-border xAll(end)+border], [0 0], 'k-'); end XTickLabel = ip.Results.XTickLabel; if numel(XTickLabel)==ng XTick = arrayfun(@(k) (xa{k}(1) + xa{k}(end))/2, 1:ng); else XTick = [xa{:}]; end % position of the bars xa = [xa{:}]; if isempty(XTickLabel) if ng>1 XTickLabel = 1:ng; else XTickLabel = 1:nb; end end XLim = [xa(1)-border xa(end)+border]; set(ha, 'XLim', XLim, 'XTick', XTick); if ~isempty(get(ha, 'XTickLabel')) set(ha, 'XTickLabel', XTickLabel); end if ~isempty(ip.Results.YLim) YLim = ip.Results.YLim; set(ha, 'YLim', YLim); else YLim = get(gca, 'YLim'); end if ~isempty(ip.Results.YTick) set(ha, 'YTick', ip.Results.YTick); end % add annotation links (for significance etc.) av = ip.Results.Annotations; if ~isempty(av) && ~isempty(topErrorbars) pos = get(gca, 'Position'); dy = 0.25/diff(XLim)*diff(YLim)/pos(4)*pos(3); maxposCount = zeros(numel(prm),1); for k = 1:size(av,1) y0 = max(topval(av(k,1):av(k,2))); maxpos = find(topval==y0, 1, 'first'); maxposCount(maxpos) = maxposCount(maxpos)+1; plot(xa(av(k,[1 1 2 2])), y0+dy+1.75*dy*(maxposCount(maxpos)-1)+[0 dy dy 0], 'k',... 'LineWidth', 0.75*ip.Results.LineWidth); end end % x labels if ip.Results.Angle~=0 && ~isempty(ip.Results.XTickLabel) && ~isempty(get(ha, 'XTickLabel')) rotateXTickLabels(ha, 'Angle', ip.Results.Angle, 'Interpreter', ip.Results.Interpreter,... 'AdjustFigure', ip.Results.AdjustFigure); end
github
mehta-lab/Instantaneous-PolScope-master
cometDetection.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/cometDetection.m
6,755
utf_8
3aca3d6e6edfd49b3d8f8cf3af52dcc6
% featuresInfo = cometDetection(img, mask, psfSigma, mode) % % Inputs : img : input image % mask : cell mask % psfSigma : standard deviation of the Gaussian PSF % {mode} : parameters to estimate, default 'xyArtc' % {alpha} : alpha-values for statistical test % {kSigma} : alpha-values for statistical test % {minDist} : minimum distance betwen detected features % {filterSigma} : sigma for the steerable filter % % Outputs: featuresInfo : output structure with anisotropic Gaussian % parameters, standard deviations (compatible with % Khuloud's tracker. % % Sylvain Berlemont, April 2011 % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % function featuresInfo = cometDetection(img, mask, psfSigma, varargin) % Parse inputs ip = inputParser; ip.CaseSensitive = false; ip.addRequired('img', @isnumeric); ip.addRequired('mask', @islogical); ip.addRequired('psfSigma', @isscalar); ip.addParamValue('mode', 'xyArtc', @ischar); ip.addParamValue('alpha', 0.05, @isscalar); ip.addParamValue('kSigma', 4, @isscalar); ip.addParamValue('minDist', .25, @isscalar); ip.addParamValue('filterSigma',psfSigma*sqrt(2), @isscalar); ip.parse(img, mask, psfSigma, varargin{:}); mode = ip.Results.mode; alpha = ip.Results.alpha; kSigma = ip.Results.kSigma; minDist = ip.Results.minDist; filterSigma =ip.Results.filterSigma; img = double(img); [nrows ncols] = size(img); % Filter image with laplacian bandPassIso = filterLoG(img,psfSigma); bandPassIso(bandPassIso < 0) = 0; bandPassIso(~mask) = 0; % Filter image with steerable filter [R,T] = steerableDetector(img,2,filterSigma); % Compute the local maxima of the bandpass filtered images locMaxIso = locmax2d(R, [5 5]); bw = blobSegmentThreshold(bandPassIso,0,0,mask); labels=bwlabel(bw); locMaxIso(~bw) = 0; indMax = find(locMaxIso); [y x] = ind2sub(size(img), indMax); P = zeros(size(y, 1), 7); P(:,1) = x; P(:,2) = y; P(:,3) = img(indMax); P(:,4) = 2*psfSigma; % sigmaX P(:,5) = psfSigma; % sigmaY P(:,6) = T(indMax)+pi/2; % % Subresolution detection % hside = ceil(kSigma * psfSigma); % npx = (2 * hside + 1)^2; % xmin = x - hside; % xmax = x + hside; % ymin = y - hside; % ymax = y + hside; PP =num2cell(P,1); [xRange,yRange,nzIdx] = arrayfun(@(x0,y0,sigmaX,sigmaY,theta)... anisoGaussian2DSupport(x0,y0,sigmaX,sigmaY,theta,kSigma,[ncols nrows]),... PP{[1 2 4 5 6]},'UniformOutput',false); % hside = ceil(kSigma * psfSigma); % npx = (2 * hside + 1)^2; xmin = cellfun(@min,xRange); xmax = cellfun(@max,xRange); ymin = cellfun(@min,yRange); ymax = cellfun(@max,yRange); npx = cellfun(@numel,nzIdx); isValid = find(xmin >= 1 & xmax <= ncols & ymin >= 1 & ymax <= nrows); xmin = xmin(isValid); xmax = xmax(isValid); ymin = ymin(isValid); ymax = ymax(isValid); P = P(isValid,:); stdP = zeros(size(P)); stdR = zeros(size(P,1),1); kLevel = norminv(1 - alpha / 2.0, 0, 1); % ~2 std above background success = false(numel(xmin),1); for iFeature = 1:numel(xmin) mask =labels(ymin(iFeature):ymax(iFeature), xmin(iFeature):xmax(iFeature)); mask(mask==labels(yRange{iFeature}(fix(end/2)),xRange{iFeature}(fix(end/2)))) = 0; anisoMask = false(length(yRange{iFeature}),length(xRange{iFeature})); anisoMask(nzIdx{iFeature})=true; anisoMask(mask~=0)=false; npx(iFeature)=nnz(anisoMask); crop = img(ymin(iFeature):ymax(iFeature), xmin(iFeature):xmax(iFeature)); crop(~anisoMask)=NaN; P(iFeature,7) = min(crop(:)); % background P(iFeature,3) = P(iFeature,3) - P(iFeature,7); % amplitude above background [params, stdParams, ~, res] = fitAnisoGaussian2D(crop, ... [0, 0, P(iFeature,3), 3 * P(iFeature,4), P(iFeature,5), ... P(iFeature,6), P(iFeature,7)], mode); % TEST: position must remain in a confined area px = floor(floor(size(crop)/2)+1+params(1:2)); isValid = all(px>=1) & all(px<=size(crop)); if isValid isValid = anisoMask(px(1),px(2)); end % TEST: sigmaX > 1 isValid = isValid & params(4) > 1; % TEST: goodness-of-fit % stdRes = std(res.data(~isnan(res.data))); % [~, pval] = kstest(res.data(~isnan(res.data)) ./ stdRes, [], alpha); isValid = isValid & res.pval > alpha; % TEST: amplitude SE_psfSigma_r = (res.std / sqrt(2*(npx(iFeature)-1))) * kLevel; psfSigma_A = stdParams(3); A_est = params(3); df2 = (npx(iFeature) - 1) * (psfSigma_A.^2 + SE_psfSigma_r.^2).^2 ./ (psfSigma_A.^4 + SE_psfSigma_r.^4); scomb = sqrt((psfSigma_A.^2 + SE_psfSigma_r.^2) / npx(iFeature)); T = (A_est - res.std * kLevel) ./ scomb; isValid = isValid & (1 - tcdf(T, df2)) < alpha; % TEST: extreme value of isValid = isValid & params(4) < 10 * psfSigma; success(iFeature) = isValid; P(iFeature,1) = P(iFeature,1) + params(1); P(iFeature,2) = P(iFeature,2) + params(2); P(iFeature,3) = params(3); P(iFeature,4) = params(4); P(iFeature,5) = params(5); P(iFeature,6) = params(6); P(iFeature,7) = params(7); stdP(iFeature,1) = stdParams(1); stdP(iFeature,2) = stdParams(2); stdP(iFeature,3) = stdParams(3); stdP(iFeature,4) = stdParams(4); stdP(iFeature,6) = stdParams(5); stdP(iFeature,7) = stdParams(6); stdR(iFeature) = res.std; end P = P(success,:); stdP = stdP(success,:); % Remove any detection which has been localised at the same position isValid = true(size(P,1),1); idxKD = KDTreeBallQuery(P(:,1:2), P(:,1:2), repmat(minDist, size(P,1), 1)); idxKD = idxKD(cellfun(@(x) length(x)>1, idxKD)); for k = 1:length(idxKD); stdRes = stdR(idxKD{k}); isValid(idxKD{k}(stdRes ~= min(stdRes))) = false; end P = P(isValid,:); stdP = stdP(isValid,:); featuresInfo.xCoord = [P(:,1), stdP(:,1)]; featuresInfo.yCoord = [P(:,2), stdP(:,2)]; featuresInfo.amp = [P(:,3), stdP(:,3)]; featuresInfo.sigmaX = [P(:,4), stdP(:,4)]; featuresInfo.sigmaY = [P(:,5), stdP(:,5)]; featuresInfo.theta = [P(:,6), stdP(:,6)]; featuresInfo.bkg = [P(:,7), stdP(:,7)];
github
mehta-lab/Instantaneous-PolScope-master
motionAnalysisProcessGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/motionAnalysisProcessGUI.m
6,511
utf_8
b871bab1808e1cb74cf3eef8463fa479
function varargout = motionAnalysisProcessGUI(varargin) % motionAnalysisProcessGUI M-file for motionAnalysisProcessGUI.fig % motionAnalysisProcessGUI, by itself, creates a new motionAnalysisProcessGUI or raises the existing % singleton*. % % H = motionAnalysisProcessGUI returns the handle to a new motionAnalysisProcessGUI or the handle to % the existing singleton*. % % motionAnalysisProcessGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in motionAnalysisProcessGUI.M with the given input arguments. % % motionAnalysisProcessGUI('Property','Value',...) creates a new motionAnalysisProcessGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before motionAnalysisProcessGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to motionAnalysisProcessGUI_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 % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help motionAnalysisProcessGUI % Last Modified by GUIDE v2.5 03-Apr-2012 18:20:06 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @motionAnalysisProcessGUI_OpeningFcn, ... 'gui_OutputFcn', @motionAnalysisProcessGUI_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 motionAnalysisProcessGUI is made visible. function motionAnalysisProcessGUI_OpeningFcn(hObject, eventdata, handles, varargin) processGUI_OpeningFcn(hObject, eventdata, handles, varargin{:},'initChannel',1); % Set default parameters userData = get(handles.figure1, 'UserData'); if(isempty(userData)), userData = struct(); end; funParams = userData.crtProc.funParams_; set(handles.popupmenu_probDim,'String',{'2','3'},'UserData',[2 3],... 'Value',find(funParams.probDim==[2 3])); set(handles.checkbox_checkAsym,'Value',funParams.checkAsym); % Set confinement radius methods confRadMethods = MotionAnalysisProcess.getConfinementRadiusMethods; set(handles.popupmenu_confRadMin,'String',{confRadMethods.name},... 'Value',find(funParams.confRadMin==[confRadMethods.type]),... 'UserData',[confRadMethods.type]); % Set alpha values alphaValues = MotionAnalysisProcess.getAlphaValues; set(handles.popupmenu_alphaValueMSS,'String',num2cell(alphaValues),... 'Value',find(funParams.alphaValues(1)==alphaValues),... 'UserData',alphaValues); set(handles.popupmenu_alphaValueAsym,'String',num2cell(alphaValues),... 'Value',find(funParams.alphaValues(2)==alphaValues),... 'UserData',alphaValues); % Update GUI user data handles.output = hObject; set(hObject, 'UserData', userData); guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = motionAnalysisProcessGUI_OutputFcn(~, ~, 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 pushbutton_cancel. function pushbutton_cancel_Callback(~, ~, handles) % Delete figure delete(handles.figure1); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, ~, handles) % Notify the package GUI that the setting panel is closed userData = get(handles.figure1, 'UserData'); if(isempty(userData)), userData = struct(); end; delete(userData.helpFig(ishandle(userData.helpFig))); set(handles.figure1, 'UserData', userData); guidata(hObject,handles); % --- Executes on key press with focus on pushbutton_done and none of its controls. function pushbutton_done_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) % Check user input if isempty(get(handles.listbox_selectedChannels, 'String')) errordlg('Please select at least one input channel from ''Available Channels''.','Setting Error','modal') return; end funParams.ChannelIndex = get(handles.listbox_selectedChannels, 'Userdata'); % Get frame range props = get(handles.popupmenu_probDim, {'UserData','Value'}); funParams.probDim=props{1}(props{2}); funParams.checkAsym=get(handles.checkbox_checkAsym,'Value'); % Get alpha values props = get(handles.popupmenu_alphaValueMSS, {'UserData','Value'}); funParams.alphaValues(1) =props{1}(props{2}); props = get(handles.popupmenu_alphaValueAsym, {'UserData','Value'}); funParams.alphaValues(2) =props{1}(props{2}); props = get(handles.popupmenu_confRadMin, {'UserData','Value'}); funParams.confRadMin=props{1}(props{2}); processGUI_ApplyFcn(hObject, eventdata, handles,funParams);
github
mehta-lab/Instantaneous-PolScope-master
HCSplatestack.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/HCSplatestack.m
2,492
utf_8
1c4f1b9bdb81b8abde6df30edef6e8d1
function [chplatestack, starti, startsw] = HCSplatestack(varagin) chplatestack = []; dirurl = varagin; file_lists = dir(fullfile(dirurl, '*.TIF')); ct = 0; lenf = zeros(1, 10); for i2 = 1:10 lenf(i2) = length(file_lists(i2).name); % see if there is inconsistent double digit naming end % if lenf(10) ~= mean(lenf) % renameSingledigitfiles(dirurl, file_lists, max(lenf)); % end %file_lists = dir(fullfile(dirurl, '*.TIF')); ct = 0; %[starti, startsw] = getindexstart(file_lists(1).name); % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % h = waitbar(0, 'Loading HCS Images'); for i1 = 1:length(file_lists) waitbar(i1/length(file_lists)); [starti, startsw] = getindexstart(file_lists(i1).name); wp = file_lists(i1,1).name(starti:max(startsw)+1); %well position wpv = double(wp(1))-64; %get numericle order from alphabetic sequence wph = str2double(wp(2:3)); if min(abs(str2double(wp(min(startsw)-starti+3))-(0:9))) == 0 %see if site number is double digit. shp = str2double([wp(min(startsw)-starti+2),wp(min(startsw)-starti+3)]); chn = str2double(wp(max(startsw)-starti+2)); else shp = str2double(wp(min(startsw)-starti+2)); chn = str2double(wp(max(startsw)-starti+2)); end ct = ct + 1; if ct == 1 wpvr = wpv; wphr = wph; end chplatestack{chn}{wpv-wpvr+1, wph-wphr+1}{shp} = [file_lists(i1,1).name]; end close(h) function renameSingledigitfiles(dirurl, file_lists, maxlength) [starti, startsw] = getindexstart(file_lists(1).name); ss = startsw(1); for i3 = 1:length(file_lists) if length(file_lists(i3).name) ~= maxlength movefile(strcat(dirurl, file_lists(i3).name), strcat(dirurl, file_lists(i3).name(1:ss), '0', file_lists(i3).name(ss+1:end))); end end
github
mehta-lab/Instantaneous-PolScope-master
MakeQTMovie.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/MakeQTMovie.m
29,841
utf_8
28412bad79f01471d852bd2dcda56185
function MakeQTMovie(cmd,arg, arg2) % function MakeQTMovie(cmd, arg, arg2) % Create a QuickTime movie from a bunch of figures (and an optional sound). % % Syntax: MakeQTMovie cmd [arg] % The following commands are supported: % addfigure - Add snapshot of current figure to movie % addaxes - Add snapshot of current axes to movie % addmatrix data - Add a matrix to movie (convert to jpeg with imwrite) % addmatrixsc data - Add a matrix to movie (convert to jpeg with imwrite) % (automatically scales image data) % addsound data [sr] - Add sound to movie (only monaural for now) % (third argument is the sound's sample rate.) % cleanup - Remove the temporary files % demo - Create a demonstration movie % finish - Finish movie, write out QT file % framerate fps - Set movies frame rate [Default is 10 fps] % quality # - Set JPEG quality (between 0 and 1) % size [# #] - Set plot size to [width height] % start filename - Start creating a movie with this name % The start command must be called first to provide a movie name. % The finish command must be called last to write out the movie % data. All other commands can be called in any order. Only one % movie can be created at a time. % % This code is published as Interval Technical Report #1999-066 % The latest copy can be found at % http://web.interval.com/papers/1999-066/ % (c) Copyright Malcolm Slaney, Interval Research, March 1999. % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % This is experimental software and is being provided to Licensee % 'AS IS.' Although the software has been tested on Macintosh, SGI, % Linux, and Windows machines, Interval makes no warranties relating % to the software's performance on these or any other platforms. % % Disclaimer % THIS SOFTWARE IS BEING PROVIDED TO YOU 'AS IS.' INTERVAL MAKES % NO EXPRESS, IMPLIED OR STATUTORY WARRANTY OF ANY KIND FOR THE % SOFTWARE INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF % PERFORMANCE, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. % IN NO EVENT WILL INTERVAL BE LIABLE TO LICENSEE OR ANY THIRD % PARTY FOR ANY DAMAGES, INCLUDING LOST PROFITS OR OTHER INCIDENTAL % OR CONSEQUENTIAL DAMAGES, EVEN IF INTERVAL HAS BEEN ADVISED OF % THE POSSIBLITY THEREOF. % % This software program is owned by Interval Research % Corporation, but may be used, reproduced, modified and % distributed by Licensee. Licensee agrees that any copies of the % software program will contain the same proprietary notices and % warranty disclaimers which appear in this software program. % This program uses the Matlab imwrite routine to convert each image % frame into JPEG. After first reserving 8 bytes for a header that points % to the movie description, all the compressed images and the sound are % added to the movie file. When the 'finish' method is called then the % first 8 bytes of the header are rewritten to indicate the size of the % movie data, and then the movie header ('moov structure') is written % to the output file. % % This routine creates files according to the QuickTime file format as % described in the appendix of % "Quicktime (Inside MacIntosh)," Apple Computer Incorporated, % Addison-Wesley Pub Co; ISBN: 0201622017, April 1993. % I appreciate help that I received from Lee Fyock (MathWorks) and Aaron % Hertzmann (Interval) in debugging and testing this work. % Changes: % July 5, 1999 - Removed stss atom since it upset PC version of QuickTime % November 11, 1999 - Fixed quality bug in addmatrix. Added addmatrixsc. % March 7, 2000 - by Jordan Rosenthal ([email protected]), Added truecolor % capability when running in Matlab 5.3 changed some help comments, fixed % some bugs, vectorized some code. % April 7, 2000 - by Malcolm. Cleaned up axis/figure code and fixed(?) SGI % playback problems. Added user data atom to give version information. % Fixed sound format problems. % April 10, 2000 - by Malcolm. Fixed problem with SGI (at least) and B&W % addmatrix. % October 15, 2004 - by Andre Kerstens ([email protected]), implemented % a fix for two known bugs in Matlab 7 (R14) basically turning the % accelerator and javafigures off if nargin < 1 fprintf('Syntax: MakeQTMovie cmd [arg]\n') fprintf('The following commands are supported:\n'); fprintf(' addfigure - Add snapshot of current figure to movie\n') fprintf(' addaxes - Add snapshot of current axes to movie\n') fprintf(' addmatrix data - Add a matrix to movie '); fprintf('(convert to jpeg)\n') fprintf(' addmatrixsc data - Add a matrix to movie '); fprintf('(scale and convert to jpeg)\n') fprintf(' addsound data - Add sound samples '); fprintf('(with optional rate)\n') fprintf(' demo - Show this program in action\n'); fprintf(' finish - Finish movie, write out QT file\n'); fprintf(' framerate # - Set movie frame rate '); fprintf('(default is 10fps)\n'); fprintf(' quality # - Set JPEG quality (between 0 and 1)\n'); fprintf(' size [# #] - Set plot size to [width height]\n'); fprintf(' start filename - Start making a movie with '); fprintf('this name\n'); return; end % Since matlab 7 handles figures different from 6 (using java), we have to % set this feature to 0 when 7 is used. Also implements a workaround for % a known bug with global variables % matlabVersion = version; % if (matlabVersion(1) == '7') % if isempty(strfind(version,'R2008')) % oldJFValue = feature('javafigures'); % feature('javafigures',0); % oldAccelValue = feature('accel'); % feature('accel',0); % end % end global MakeQTMovieStatus MakeDefaultQTMovieStatus; % Needed first time, ignored otherwise switch lower(cmd) case {'addframe','addplot','addfigure','addaxes'} switch lower(cmd) case {'addframe','addfigure'} hObj = gcf; % Add the entire figure (with all axes) otherwise hObj = gca; % Add what's inside the current axis end frame = getframe(hObj); [I,map] = frame2im(frame); if ImageSizeChanged(size(I)) > 0 return; end if isempty(map) % RGB image imwrite(I,MakeQTMovieStatus.imageTmp, 'jpg', 'Quality', ... MakeQTMovieStatus.spatialQual*100); else % Indexed image writejpg_map(MakeQTMovieStatus.imageTmp, I, map); end [pos, len] = AddFileToMovie; n = MakeQTMovieStatus.frameNumber + 1; MakeQTMovieStatus.frameNumber = n; MakeQTMovieStatus.frameStarts(n) = pos; MakeQTMovieStatus.frameLengths(n) = len; %% Allow images to be added by doing: %% MakeQTMovie('addimage', '/path/to/file.jpg'); %% This case adapted from addmatrix. Thanks to %% Stephen Eglen <[email protected]> for this idea. case 'addimage' if nargin < 2 fprintf('MakeQTMovie error: Need to specify a filename with '); fprintf('the image command.\n'); return; end %% Check to see that the image is the correct size. Do %% this by reading in the image and then checking its size. %% tim - temporary image. tim = imread(arg); tim_size = size(tim); fprintf('Image %s size %d %d\n', arg, tim_size(1), tim_size(2)); if ImageSizeChanged(tim_size) > 0 return; end [pos, len] = AddFileToMovie(arg); n = MakeQTMovieStatus.frameNumber + 1; MakeQTMovieStatus.frameNumber = n; MakeQTMovieStatus.frameStarts(n) = pos; MakeQTMovieStatus.frameLengths(n) = len; case 'addmatrix' if nargin < 2 fprintf('MakeQTMovie error: Need to specify a matrix with '); fprintf('the addmatrix command.\n'); return; end if ImageSizeChanged(size(arg)) > 0 return; end % Work around a bug, at least on the % SGIs, which causes JPEGs to be % written which can't be read with the % SGI QT. Turn the B&W image into a % color matrix. if ndims(arg) < 3 arg(:,:,2) = arg; arg(:,:,3) = arg(:,:,1); end imwrite(arg, MakeQTMovieStatus.imageTmp, 'jpg', 'Quality', ... MakeQTMovieStatus.spatialQual*100); [pos, len] = AddFileToMovie; n = MakeQTMovieStatus.frameNumber + 1; MakeQTMovieStatus.frameNumber = n; MakeQTMovieStatus.frameStarts(n) = pos; MakeQTMovieStatus.frameLengths(n) = len; case 'addmatrixsc' if nargin < 2 fprintf('MakeQTMovie error: Need to specify a matrix with '); fprintf('the addmatrix command.\n'); return; end if ImageSizeChanged(size(arg)) > 0 return; end arg = arg - min(min(arg)); arg = arg / max(max(arg)); % Work around a bug, at least on the % SGIs, which causes JPEGs to be % written which can't be read with the % SGI QT. Turn the B&W image into a % color matrix. if ndims(arg) < 3 arg(:,:,2) = arg; arg(:,:,3) = arg(:,:,1); end imwrite(arg, MakeQTMovieStatus.imageTmp, 'jpg', 'Quality', ... MakeQTMovieStatus.spatialQual*100); [pos, len] = AddFileToMovie; n = MakeQTMovieStatus.frameNumber + 1; MakeQTMovieStatus.frameNumber = n; MakeQTMovieStatus.frameStarts(n) = pos; MakeQTMovieStatus.frameLengths(n) = len; case 'addsound' if nargin < 2 fprintf('MakeQTMovie error: Need to specify a sound array '); fprintf('with the addsound command.\n'); return; end % Do stereo someday??? OpenMovieFile MakeQTMovieStatus.soundLength = length(arg); arg = round(arg/max(max(abs(arg)))*32765); negs = find(arg<0); arg(negs) = arg(negs) + 65536; sound = mb16(arg); MakeQTMovieStatus.soundStart = ftell(MakeQTMovieStatus.movieFp); MakeQTMovieStatus.soundLen = length(sound); fwrite(MakeQTMovieStatus.movieFp, sound, 'uchar'); if nargin < 3 arg2 = 22050; end MakeQTMovieStatus.soundRate = arg2; case 'cleanup' if isstruct(MakeQTMovieStatus) if ~isempty(MakeQTMovieStatus.movieFp) fclose(MakeQTMovieStatus.movieFp); MakeQTMovieStatus.movieFp = []; end if ~isempty(MakeQTMovieStatus.imageTmp) & ... exist(MakeQTMovieStatus.imageTmp,'file') > 0 delete(MakeQTMovieStatus.imageTmp); MakeQTMovieStatus.imageTmp = []; end end MakeQTMovieStatus = []; case 'debug' fprintf('Current Movie Data:\n'); fprintf(' %d frames at %d fps\n', MakeQTMovieStatus.frameNumber, ... MakeQTMovieStatus.frameRate); starts = MakeQTMovieStatus.frameStarts; if length(starts) > 10, starts = starts(1:10);, end; lens = MakeQTMovieStatus.frameLengths; if length(lens) > 10, lens = lens(1:10);, end; fprintf(' Start: %6d Size: %6d\n', [starts; lens]); fprintf(' Movie Image Size: %dx%d\n', ... MakeQTMovieStatus.imageSize(2), ...); MakeQTMovieStatus.imageSize(1)); if length(MakeQTMovieStatus.soundStart) > 0 fprintf(' Sound: %d samples at %d Hz sampling rate ', ... MakeQTMovieStatus.soundLength, ... MakeQTMovieStatus.soundRate); fprintf('at %d.\n', MakeQTMovieStatus.soundStart); else fprintf(' Sound: No sound track\n'); end fprintf(' Temporary files for images: %s\n', ... MakeQTMovieStatus.imageTmp); fprintf(' Final movie name: %s\n', MakeQTMovieStatus.movieName); fprintf(' Compression Quality: %g\n', ... MakeQTMovieStatus.spatialQual); case 'demo' clf fps = 10; movieLength = 10; sr = 22050; fn = 'test.mov'; fprintf('Creating the movie %s.\n', fn); MakeQTMovie('start',fn); MakeQTMovie('size', [160 120]); MakeQTMovie('quality', 1.0); theSound = []; for i=1:movieLength plot(sin((1:100)/4+i)); MakeQTMovie('addaxes'); theSound = [theSound sin(440/sr*2*pi*(2^(i/12))*(1:sr/fps))]; end MakeQTMovie('framerate', fps); MakeQTMovie('addsound', theSound, sr); MakeQTMovie('finish'); case {'finish','close'} AddQTHeader; MakeQTMovie('cleanup') % Remove temporary files case 'framerate' if nargin < 2 fprintf('MakeQTMovie error: Need to specify the '); fprintf('frames/second with the framerate command.\n'); return; end MakeQTMovieStatus.frameRate = arg; case 'help' MakeQTMovie % To get help message. case 'size' % Size is off by one on the % Mac. if nargin < 2 fprintf('MakeQTMovie error: Need to specify a vector with '); fprintf('the size command.\n'); return; end if length(arg) ~= 2 error('MakeQTMovie: Error, must supply 2 element size.'); end oldUnits = get(gcf,'units'); set(gcf,'units','pixels'); cursize = get(gcf, 'position'); cursize(3) = arg(1); cursize(4) = arg(2); set(gcf, 'position', cursize); set(gcf,'units',oldUnits); case 'start' if nargin < 2 fprintf('MakeQTMovie error: Need to specify a file name '); fprintf('with start command.\n'); return; end MakeQTMovie('cleanup'); MakeDefaultQTMovieStatus; MakeQTMovieStatus.movieName = arg; case 'test' clf MakeQTMovieStatus = []; MakeQTMovie('start','test.mov'); MakeQTMovie('size', [320 240]); MakeQTMovie('quality', 1.0); subplot(2,2,1); for i=1:10 plot(sin((1:100)/4+i)); MakeQTMovie('addfigure'); end MakeQTMovie('framerate', 10); MakeQTMovie('addsound', sin(1:5000), 22050); MakeQTMovie('debug'); MakeQTMovie('finish'); case 'quality' if nargin < 2 fprintf('MakeQTMovie error: Need to specify a quality '); fprintf('(between 0-1) with the quality command.\n'); return; end MakeQTMovieStatus.spatialQual = arg; otherwise fprintf('MakeQTMovie: Unknown method %s.\n', cmd); end % Set the values back for the figuresize % matlabVersion = version; % if (matlabVersion(1) == '7') % if isempty(strfind(version,'R2008')) % feature('javafigures',oldJFValue); % feature('accel',oldAccelValue); % end % end %%%%%%%%%%%%%%% MakeDefaultQTMovieStatus %%%%%%%%%%%%%%%%% % Make the default movie status structure. function MakeDefaultQTMovieStatus global MakeQTMovieStatus if isempty(MakeQTMovieStatus) MakeQTMovieStatus = struct(... 'frameRate', 10, ... % frames per second 'frameStarts', [], ... % Starting byte position 'frameLengths', [], ... 'timeScale', 10, ... % How much faster does time run? 'soundRate', 22050, ... % Sound Sample Rate 'soundStart', [], ... % Starting byte position 'soundLength', 0, ... 'soundChannels', 1, ... % Number of channels 'frameNumber', 0, ... 'movieFp', [], ... % File pointer 'imageTmp', tempname, ... 'movieName', 'output.mov', ... 'imageSize', [0 0], ... 'trackNumber', 0, ... 'timeScaleExpansion', 100, ... 'spatialQual', 1.0); % Between 0.0 and 1.0 end %%%%%%%%%%%%%%% ImageSizeChanged %%%%%%%%%%%%%%%%% % Check to see if the image size has changed. This m-file can't % deal with that, so we'll return an error. function err = ImageSizeChanged(newsize) global MakeQTMovieStatus newsize = newsize(1:2); % Don't care about RGB info, if present oldsize = MakeQTMovieStatus.imageSize; err = 0; if sum(oldsize) == 0 MakeQTMovieStatus.imageSize = newsize; else if sum(newsize ~= oldsize) > 0 fprintf('MakeQTMovie Error: New image size'); fprintf('(%dx%d) doesn''t match old size (%dx%d)\n', ... newsize(1), newsize(2), oldsize(1), oldsize(2)); fprintf(' Can''t add this image to the movie.\n'); err = 1; end end %%%%%%%%%%%%%%% AddFileToMovie %%%%%%%%%%%%%%%%% % OK, we've saved out an image file. Now add it to the end of the movie % file we are creating. % We'll copy the JPEG file in 16kbyte chunks to the end of the movie file. % Keep track of the start and end byte position in the file so we can put % the right information into the QT header. function [pos, len] = AddFileToMovie(imageTmp) global MakeQTMovieStatus OpenMovieFile if nargin < 1 imageTmp = MakeQTMovieStatus.imageTmp; end fp = fopen(imageTmp, 'rb'); if fp < 0 error('Could not reopen QT image temporary file.'); end len = 0; pos = ftell(MakeQTMovieStatus.movieFp); while 1 data = fread(fp, 1024*16, 'uchar'); if isempty(data) break; end cnt = fwrite(MakeQTMovieStatus.movieFp, data, 'uchar'); len = len + cnt; end fclose(fp); %%%%%%%%%%%%%%% AddQTHeader %%%%%%%%%%%%%%%%% % Go back and write the atom information that allows % QuickTime to skip the image and sound data and find % its movie description information. function AddQTHeader() global MakeQTMovieStatus pos = ftell(MakeQTMovieStatus.movieFp); header = moov_atom; cnt = fwrite(MakeQTMovieStatus.movieFp, header, 'uchar'); fseek(MakeQTMovieStatus.movieFp, 0, -1); cnt = fwrite(MakeQTMovieStatus.movieFp, mb32(pos), 'uchar'); fclose(MakeQTMovieStatus.movieFp); MakeQTMovieStatus.movieFp = []; %%%%%%%%%%%%%%% OpenMovieFile %%%%%%%%%%%%%%%%% % Open a new movie file. Write out the initial QT header. We'll fill in % the correct length later. function OpenMovieFile global MakeQTMovieStatus if isempty(MakeQTMovieStatus.movieFp) fp = fopen(MakeQTMovieStatus.movieName, 'wb'); if fp < 0 error('Could not open QT movie output file.'); end MakeQTMovieStatus.movieFp = fp; cnt = fwrite(fp, [mb32(0) mbstring('mdat')], 'uchar'); end %%%%%%%%%%%%%%% writejpg_map %%%%%%%%%%%%%%%%% % Like the imwrite routine, but first pass the image data through the indicated % RGB map. function writejpg_map(name,I,map) global MakeQTMovieStatus [y,x] = size(I); % Force values to be valid indexes. This fixes a bug that occasionally % occurs in frame2im in Matlab 5.2 which incorrectly produces values of I % equal to zero. I = max(1,min(I,size(map,1))); rgb = zeros(y, x, 3); t = zeros(y,x); t(:) = map(I(:),1)*255; rgb(:,:,1) = t; t(:) = map(I(:),2)*255; rgb(:,:,2) = t; t(:) = map(I(:),3)*255; rgb(:,:,3) = t; imwrite(uint8(rgb),name,'jpeg','Quality',MakeQTMovieStatus.spatialQual*100); %%%%%%%%%%%%%%% SetAtomSize %%%%%%%%%%%%%%%%% % Fill in the size of the atom function y=SetAtomSize(x) y = x; y(1:4) = mb32(length(x)); %%%%%%%%%%%%%%% mb32 %%%%%%%%%%%%%%%%% % Make a vector from a 32 bit integer function y = mb32(x) if size(x,1) > size(x,2) x = x'; end y = [bitand(bitshift(x,-24),255); ... bitand(bitshift(x,-16),255); ... bitand(bitshift(x, -8),255); ... bitand(x, 255)]; y = y(:)'; %%%%%%%%%%%%%%% mb16 %%%%%%%%%%%%%%%%% % Make a vector from a 16 bit integer function y = mb16(x) if size(x,1) > size(x,2) x = x'; end y = [bitand(bitshift(x, -8),255); ... bitand(x, 255)]; y = y(:)'; %%%%%%%%%%%%%%% mb8 %%%%%%%%%%%%%%%%% % Make a vector from a 8 bit integer function y = mb8(x) if size(x,1) > size(x,2) x = x'; end y = [bitand(x, 255)]; y = y(:)'; % % The following routines all create atoms necessary % to describe a QuickTime Movie. The basic idea is to % fill in the necessary data, all converted to 8 bit % characters, then fix it up later with SetAtomSize so % that it has the correct header. (This is easier than % counting by hand.) %%%%%%%%%%%%%%% mbstring %%%%%%%%%%%%%%%%% % Make a vector from a character string function y = mbstring(s) y = double(s); %%%%%%%%%%%%%%% dinf_atom %%%%%%%%%%%%%%%%% function y = dinf_atom() y = SetAtomSize([mb32(0) mbstring('dinf') dref_atom]); %%%%%%%%%%%%%%% dref_atom %%%%%%%%%%%%%%%%% function y = dref_atom() y = SetAtomSize([mb32(0) mbstring('dref') mb32(0) mb32(1) ... mb32(12) mbstring('alis') mb32(1)]); %%%%%%%%%%%%%%% edts_atom %%%%%%%%%%%%%%%%% function y = edts_atom(add_sound_p) global MakeQTMovieStatus fixed1 = bitshift(1,16); % Fixed point 1 if add_sound_p > 0 duration = MakeQTMovieStatus.soundLength / ... MakeQTMovieStatus.soundRate * ... MakeQTMovieStatus.timeScale; else duration = MakeQTMovieStatus.frameNumber / ... MakeQTMovieStatus.frameRate * ... MakeQTMovieStatus.timeScale; end duration = ceil(duration); y = [mb32(0) ... % Atom Size mbstring('edts') ... % Atom Name SetAtomSize([mb32(0) ... % Atom Size mbstring('elst') ... % Atom Name mb32(0) ... % Version/Flags mb32(1) ... % Number of entries mb32(duration) ... % Length of this track mb32(0) ... % Time mb32(fixed1)])]; % Rate y = SetAtomSize(y); %%%%%%%%%%%%%%% hdlr_atom %%%%%%%%%%%%%%%%% function y = hdlr_atom(component_type, sub_type) if strcmp(sub_type, 'vide') type_string = 'Apple Video Media Handler'; elseif strcmp(sub_type, 'alis') type_string = 'Apple Alias Data Handler'; elseif strcmp(sub_type, 'soun') type_string = 'Apple Sound Media Handler'; end y = [mb32(0) ... % Atom Size mbstring('hdlr') ... % Atom Name mb32(0) ... % Version and Flags mbstring(component_type) ... % Component Name mbstring(sub_type) ... % Sub Type Name mbstring('appl') ... % Component manufacturer mb32(0) ... % Component flags mb32(0) ... % Component flag mask mb8(length(type_string)) ... % Type Name byte count mbstring(type_string)]; % Type Name y = SetAtomSize(y); %%%%%%%%%%%%%%% mdhd_atom %%%%%%%%%%%%%%%%% function y = mdhd_atom(add_sound_p) global MakeQTMovieStatus if add_sound_p data = [mb32(MakeQTMovieStatus.soundRate) ... mb32(MakeQTMovieStatus.soundLength)]; else data = [mb32(MakeQTMovieStatus.frameRate * ... MakeQTMovieStatus.timeScaleExpansion) ... mb32(MakeQTMovieStatus.frameNumber * ... MakeQTMovieStatus.timeScaleExpansion)]; end y = [mb32(0) mbstring('mdhd') ... % Atom Header mb32(0) ... mb32(round(now*3600*24)) ... % Creation time mb32(round(now*3600*24)) ... % Modification time data ... mb16(0) mb16(0)]; y = SetAtomSize(y); %%%%%%%%%%%%%%% mdia_atom %%%%%%%%%%%%%%%%% function y = mdia_atom(add_sound_p) global MakeQTMovieStatus if add_sound_p hdlr = hdlr_atom('mhlr', 'soun'); else hdlr = hdlr_atom('mhlr', 'vide'); end y = [mb32(0) mbstring('mdia') ... % Atom Header mdhd_atom(add_sound_p) ... hdlr ... % Handler Atom minf_atom(add_sound_p)]; y = SetAtomSize(y); %%%%%%%%%%%%%%% minf_atom %%%%%%%%%%%%%%%%% function y = minf_atom(add_sound_p) global MakeQTMovieStatus if add_sound_p data = smhd_atom; else data = vmhd_atom; end y = [mb32(0) mbstring('minf') ... % Atom Header data ... hdlr_atom('dhlr','alis') ... dinf_atom ... stbl_atom(add_sound_p)]; y = SetAtomSize(y); %%%%%%%%%%%%%%% moov_atom %%%%%%%%%%%%%%%%% function y=moov_atom global MakeQTMovieStatus MakeQTMovieStatus.timeScale = MakeQTMovieStatus.frameRate * ... MakeQTMovieStatus.timeScaleExpansion; if MakeQTMovieStatus.soundLength > 0 sound = trak_atom(1); else sound = []; end y = [mb32(0) mbstring('moov') ... mvhd_atom udat_atom sound trak_atom(0) ]; y = SetAtomSize(y); %%%%%%%%%%%%%%% mvhd_atom %%%%%%%%%%%%%%%%% function y=mvhd_atom global MakeQTMovieStatus fixed1 = bitshift(1,16); % Fixed point 1 frac1 = bitshift(1,30); % Fractional 1 if length(MakeQTMovieStatus.soundStart) > 0 NumberOfTracks = 2; else NumberOfTracks = 1; end % Need to make sure its longer % of movie and sound lengths MovieDuration = max(MakeQTMovieStatus.frameNumber / ... MakeQTMovieStatus.frameRate, ... MakeQTMovieStatus.soundLength / ... MakeQTMovieStatus.soundRate); MovieDuration = ceil(MovieDuration * MakeQTMovieStatus.timeScale); y = [mb32(0) ... % Size mbstring('mvhd') ... % Movie Data mb32(0) ... % Version and Flags mb32(0) ... % Creation Time (unknown) mb32(0) ... % Modification Time (unknown) mb32(MakeQTMovieStatus.timeScale) ... % Movie's Time Scale mb32(MovieDuration) ... % Movie Duration mb32(fixed1) ... % Preferred Rate mb16(255) ... % Preferred Volume mb16(0) ... % Fill mb32(0) ... % Fill mb32(0) ... % Fill mb32(fixed1) mb32(0) mb32(0) ... % Transformation matrix (identity) mb32(0) mb32(fixed1) mb32(0) ... mb32(0) mb32(0) mb32(frac1) ... mb32(0) ... % Preview Time mb32(0) ... % Preview Duration mb32(0) ... % Poster Time mb32(0) ... % Selection Time mb32(0) ... % Selection Duration mb32(0) ... % Current Time mb32(NumberOfTracks)]; % Video and/or Sound? y = SetAtomSize(y); %%%%%%%%%%%%%%% raw_image_description %%%%%%%%%%%%%%%%% function y = raw_image_description() global MakeQTMovieStatus fixed1 = bitshift(1,16); % Fixed point 1 codec = [12 'Photo - JPEG ']; y = [mb32(0) mbstring('jpeg') ... % Atom Header mb32(0) mb16(0) mb16(0) mb16(0) mb16(1) ... mbstring('appl') ... mb32(1023) ... % Temporal Quality (perfect) mb32(floor(1023*MakeQTMovieStatus.spatialQual)) ... mb16(MakeQTMovieStatus.imageSize(2)) ... mb16(MakeQTMovieStatus.imageSize(1)) ... mb32(fixed1 * 72) mb32(fixed1 * 72) ... mb32(0) ... mb16(0) ... mbstring(codec) ... mb16(24) mb16(65535)]; y = SetAtomSize(y); %%%%%%%%%%%%%%% raw_sound_description %%%%%%%%%%%%%%%%% function y = raw_sound_description() global MakeQTMovieStatus y = [mb32(0) mbstring('twos') ... % Atom Header mb32(0) mb16(0) mb16(0) mb16(0) mb16(0) ... mb32(0) ... mb16(MakeQTMovieStatus.soundChannels) ... mb16(16) ... % 16 bits per sample mb16(0) mb16(0) ... mb32(round(MakeQTMovieStatus.soundRate*65536))]; y = SetAtomSize(y); %%%%%%%%%%%%%%% smhd_atom %%%%%%%%%%%%%%%%% function y = smhd_atom() y = SetAtomSize([mb32(0) mbstring('smhd') mb32(0) mb16(0) mb16(0)]); %%%%%%%%%%%%%%% stbl_atom %%%%%%%%%%%%%%%%% % Removed the stss atom since it seems to upset the PC version of QT % and it is empty so it doesn't add anything. % Malcolm - July 5, 1999 function y = stbl_atom(add_sound_p) y = [mb32(0) mbstring('stbl') ... % Atom Header stsd_atom(add_sound_p) ... stts_atom(add_sound_p) ... stsc_atom(add_sound_p) ... stsz_atom(add_sound_p) ... stco_atom(add_sound_p)]; y = SetAtomSize(y); %%%%%%%%%%%%%%% stco_atom %%%%%%%%%%%%%%%%% function y = stco_atom(add_sound_p) global MakeQTMovieStatus if add_sound_p y = [mb32(0) mbstring('stco') mb32(0) mb32(1) ... mb32(MakeQTMovieStatus.soundStart)]; else y = [mb32(0) mbstring('stco') mb32(0) ... mb32(MakeQTMovieStatus.frameNumber) ... mb32(MakeQTMovieStatus.frameStarts)]; end y = SetAtomSize(y); %%%%%%%%%%%%%%% stsc_atom %%%%%%%%%%%%%%%%% function y = stsc_atom(add_sound_p) global MakeQTMovieStatus if add_sound_p samplesperchunk = MakeQTMovieStatus.soundLength; else samplesperchunk = 1; end y = [mb32(0) mbstring('stsc') mb32(0) mb32(1) ... mb32(1) mb32(samplesperchunk) mb32(1)]; y = SetAtomSize(y); %%%%%%%%%%%%%%% stsd_atom %%%%%%%%%%%%%%%%% function y = stsd_atom(add_sound_p) if add_sound_p desc = raw_sound_description; else desc = raw_image_description; end y = [mb32(0) mbstring('stsd') mb32(0) mb32(1) desc]; y = SetAtomSize(y); %%%%%%%%%%%%%%% stss_atom %%%%%%%%%%%%%%%%% function y = stss_atom() y = SetAtomSize([mb32(0) mbstring('stss') mb32(0) mb32(0)]); %%%%%%%%%%%%%%% stsz_atom %%%%%%%%%%%%%%%%% function y = stsz_atom(add_sound_p) global MakeQTMovieStatus if add_sound_p y = [mb32(0) mbstring('stsz') mb32(0) mb32(2) ... mb32(MakeQTMovieStatus.soundLength)]; else y = [mb32(0) mbstring('stsz') mb32(0) mb32(0) ... mb32(MakeQTMovieStatus.frameNumber) ... mb32(MakeQTMovieStatus.frameLengths)]; end y = SetAtomSize(y); %%%%%%%%%%%%%%% stts_atom %%%%%%%%%%%%%%%%% function y = stts_atom(add_sound_p) global MakeQTMovieStatus if add_sound_p count_duration = [mb32(MakeQTMovieStatus.soundLength) mb32(1)]; else count_duration = [mb32(MakeQTMovieStatus.frameNumber) ... mb32(MakeQTMovieStatus.timeScaleExpansion)]; end y = SetAtomSize([mb32(0) mbstring('stts') mb32(0) mb32(1) count_duration]); %%%%%%%%%%%%%%% trak_atom %%%%%%%%%%%%%%%%% function y = trak_atom(add_sound_p) global MakeQTMovieStatus y = [mb32(0) mbstring('trak') ... % Atom Header tkhd_atom(add_sound_p) ... % Track header edts_atom(add_sound_p) ... % Edit List mdia_atom(add_sound_p)]; y = SetAtomSize(y); %%%%%%%%%%%%%%% tkhd_atom %%%%%%%%%%%%%%%%% function y = tkhd_atom(add_sound_p) global MakeQTMovieStatus fixed1 = bitshift(1,16); % Fixed point 1 frac1 = bitshift(1,30); % Fractional 1 (CHECK THIS) if add_sound_p > 0 duration = MakeQTMovieStatus.soundLength / ... MakeQTMovieStatus.soundRate * ... MakeQTMovieStatus.timeScale; else duration = MakeQTMovieStatus.frameNumber / ... MakeQTMovieStatus.frameRate * ... MakeQTMovieStatus.timeScale; end duration = ceil(duration); y = [mb32(0) mbstring('tkhd') ... % Atom Header mb32(15) ... % Version and flags mb32(round(now*3600*24)) ... % Creation time mb32(round(now*3600*24)) ... % Modification time mb32(MakeQTMovieStatus.trackNumber) ... mb32(0) ... mb32(duration) ... % Track duration mb32(0) mb32(0) ... % Offset and priority mb16(0) mb16(0) mb16(255) mb16(0) ... % Layer, Group, Volume, fill mb32(fixed1) mb32(0) mb32(0) ... % Transformation matrix (identity) mb32(0) mb32(fixed1) mb32(0) ... mb32(0) mb32(0) mb32(frac1)]; if add_sound_p y = [y mb32(0) mb32(0)]; % Zeros for sound else y = [y mb32(fliplr(MakeQTMovieStatus.imageSize)*fixed1)]; end y= SetAtomSize(y); MakeQTMovieStatus.trackNumber = MakeQTMovieStatus.trackNumber + 1; %%%%%%%%%%%%%%% udat_atom %%%%%%%%%%%%%%%%% function y = udat_atom() atfmt = [64 double('fmt')]; atday = [64 double('day')]; VersionString = 'Matlab MakeQTMovie version April 7, 2000'; y = [mb32(0) mbstring('udta') ... SetAtomSize([mb32(0) atfmt mbstring(['Created ' VersionString])]) ... SetAtomSize([mb32(0) atday ' ' date])]; y = SetAtomSize(y); %%%%%%%%%%%%%%% vmhd_atom %%%%%%%%%%%%%%%%% function y = vmhd_atom() y = SetAtomSize([mb32(0) mbstring('vmhd') mb32(0) ... mb16(64) ... % Graphics Mode mb16(0) mb16(0) mb16(0)]); % Op Color
github
mehta-lab/Instantaneous-PolScope-master
cometPostTrackingProcessGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/cometPostTrackingProcessGUI.m
6,077
utf_8
1adf2297da70584ca18a58d0f599e739
function varargout = cometPostTrackingProcessGUI(varargin) % cometPostTrackingProcessGUI M-file for cometPostTrackingProcessGUI.fig % cometPostTrackingProcessGUI, by itself, creates a new cometPostTrackingProcessGUI or raises the existing % singleton*. % % H = cometPostTrackingProcessGUI returns the handle to a new cometPostTrackingProcessGUI or the handle to % the existing singleton*. % % cometPostTrackingProcessGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in cometPostTrackingProcessGUI.M with the given input arguments. % % cometPostTrackingProcessGUI('Property','Value',...) creates a new cometPostTrackingProcessGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before cometPostTrackingProcessGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to cometPostTrackingProcessGUI_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 % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help cometPostTrackingProcessGUI % Last Modified by GUIDE v2.5 16-Jul-2012 12:30:38 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @cometPostTrackingProcessGUI_OpeningFcn, ... 'gui_OutputFcn', @cometPostTrackingProcessGUI_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 cometPostTrackingProcessGUI is made visible. function cometPostTrackingProcessGUI_OpeningFcn(hObject,eventdata,handles,varargin) processGUI_OpeningFcn(hObject, eventdata, handles, varargin{:},'initChannel',1); userData=get(handles.figure1,'UserData'); if(isempty(userData)), userData = struct(); end; % 2014b Hackaton-fix PR funParams = userData.crtProc.funParams_; set(handles.checkbox_makeHist,'Value',funParams.makeHist); set(handles.checkbox_remBegEnd,'Value',funParams.remBegEnd); % Initialize pop-up menus for reclassification schemes set(handles.popupmenu_fgapReclassScheme,'String',... CometPostTrackingProcess.getFgapReclassificationSchemes, 'Value',... funParams.fgapReclassScheme); set(handles.popupmenu_bgapReclassScheme,'String',... CometPostTrackingProcess.getBgapReclassificationSchemes, 'Value',... funParams.bgapReclassScheme); % Choose default command line output for cometPostTrackingProcessGUI handles.output = hObject; % Update user data and GUI data set(hObject, 'UserData', userData); guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = cometPostTrackingProcessGUI_OutputFcn(~, ~, 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 pushbutton_cancel. function pushbutton_cancel_Callback(~, ~, handles) % Delete figure delete(handles.figure1); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, ~, handles) % Notify the package GUI that the setting panel is closed userData = get(handles.figure1, 'UserData'); if(isempty(userData)), userData = struct(); end; % 2014b Hackaton-fix PR if ishandle(userData.helpFig), delete(userData.helpFig); end set(handles.figure1, 'UserData', userData); guidata(hObject,handles); % --- Executes on key press with focus on pushbutton_done and none of its controls. function pushbutton_done_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(~, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) % Check user input if isempty(get(handles.listbox_selectedChannels, 'String')) errordlg('Please select at least one input process from ''Available Movies''.','Setting Error','modal') return; end funParams.ChannelIndex = get(handles.listbox_selectedChannels,'UserData'); funParams.makeHist=get(handles.checkbox_makeHist,'Value'); funParams.remBegEnd=get(handles.checkbox_remBegEnd,'Value'); funParams.fgapReclassScheme=get(handles.popupmenu_fgapReclassScheme,'Value'); funParams.bgapReclassScheme=get(handles.popupmenu_bgapReclassScheme,'Value'); % Set parameters processGUI_ApplyFcn(hObject, eventdata, handles,funParams);
github
mehta-lab/Instantaneous-PolScope-master
recycleProcessGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/recycleProcessGUI.m
9,825
utf_8
43449c3b28eb23b0d486c92d733b1342
function varargout = recycleProcessGUI(varargin) % RECYCLEPROCESSGUI M-file for recycleProcessGUI.fig % RECYCLEPROCESSGUI, by itself, creates a new RECYCLEPROCESSGUI or raises the existing % singleton*. % % H = RECYCLEPROCESSGUI returns the handle to a new RECYCLEPROCESSGUI or the handle to % the existing singleton*. % % RECYCLEPROCESSGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in RECYCLEPROCESSGUI.M with the given input arguments. % % RECYCLEPROCESSGUI('Property','Value',...) creates a new RECYCLEPROCESSGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before recycleProcessGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to recycleProcessGUI_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 % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help recycleProcessGUI % Last Modified by GUIDE v2.5 27-Sep-2011 11:06:56 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @recycleProcessGUI_OpeningFcn, ... 'gui_OutputFcn', @recycleProcessGUI_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 recycleProcessGUI is made visible. function recycleProcessGUI_OpeningFcn(hObject, eventdata, handles, varargin) % % recycleProcessGUI(process, package, 'mainFig', handles.figure1) % % Input: % % process - the array of processes for recycle % package - the package where the processes would be attached to % % User Data: % % userData.recyclableProc - the array of processes for recycle % userData.package - the package where the processes would be attached to % % userData.mainFig - handle of movie selector GUI % % % Input check ip = inputParser; ip.addRequired('hObject',@ishandle); ip.addRequired('eventdata',@(x) isstruct(x) || isempty(x)); ip.addRequired('handles',@isstruct); ip.addRequired('process',@(x) all(cellfun(@(y) isa(y,'Process'),x))); ip.addRequired('package',@(x) isa(x,'Package')); ip.addParamValue('mainFig',-1,@ishandle); ip.parse(hObject,eventdata,handles,varargin{:}) % Store input userData = get(handles.figure1, 'UserData'); if isempty(userData), userData = struct(); end userData.recyclableProc =ip.Results.process ; userData.package = ip.Results.package; userData.mainFig=ip.Results.mainFig; userData.previewFig = -1; set(handles.text_copyright, 'String', getLCCBCopyright()) % Choose default command line output for recycleProcessGUI handles.output = hObject; % GUI set-up set(handles.text_package, 'String', userData.package.getName) set(handles.text_movie, 'String', [userData.package.owner_.getPath filesep userData.package.owner_.getFilename]) % Create recyclable processes list nProc = numel(userData.recyclableProc); string = cell(1,nProc); for i = 1:nProc string{i} = userData.recyclableProc{i}.getName; end set(handles.listbox_processes, 'String',string, 'UserData',1:nProc) % Create package processes list nProc = numel(userData.package.processes_); string = cell(1,nProc); for i = 1:nProc processClassName = userData.package.getProcessClassNames{i}; processName=eval([processClassName '.getName']); string{i} = [' Step ' num2str(i) ': ' processName]; end set(handles.listbox_package, 'String', string,'UserData',cell(1,nProc)); set(handles.figure1,'UserData',userData) uiwait(handles.figure1) guidata(hObject, handles); % UIWAIT makes recycleProcessGUI wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = recycleProcessGUI_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; delete(handles.figure1) % --- Executes on button press in pushbutton_cancel. function pushbutton_cancel_Callback(hObject, eventdata, handles) uiresume(handles.figure1) % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) % Add the processes to the new package userData = get(handles.figure1, 'UserData'); procIds = get(handles.listbox_package, 'UserData'); validPackageProc=~cellfun(@isempty,procIds); if isempty(find(validPackageProc,1)), uiresume(handles.figure1); end for i = find(validPackageProc) userData.package.setProcess(i,userData.recyclableProc{procIds{i}}); end uiresume(handles.figure1) % --- Executes on button press in pushbutton_add. function pushbutton_add_Callback(hObject, eventdata, handles) % Test if ther is any process to dispatch processString = get(handles.listbox_processes, 'String'); if isempty(processString), return; end % Load process list and get corresponding process id userData=get(handles.figure1,'UserData'); props = get(handles.listbox_processes, {'UserData','Value'}); procIds=props{1}; procIndex = props{2}; procId=procIds(procIndex); process= userData.recyclableProc(procId); % Find associated package process getPackId = @(proc)find(cellfun(@(x) isa(proc,x),userData.package.getProcessClassNames)); packProcIds = cellfun(getPackId,process); if any(packProcIds) % Update package process and pids props = get(handles.listbox_package, {'String','UserData'}); packageString = props{1}; for i = 1:numel(packProcIds) props{2}{packProcIds(i)}=procId(i); packageString{packProcIds(i)} = ['<html><b> ' packageString{packProcIds(i)} '</b></html>']; end set(handles.listbox_package, 'String',packageString','UserData',props{2}); % Remove process from the list processString(procIndex) = []; procIds(procIndex) = []; % Set the highlighted value if ~isscalar(procIndex) || (procIndex > length(processString) && procIndex > 1) set(handles.listbox_processes, 'Value', length(processString)); end set(handles.listbox_processes, 'String', processString, 'UserData', procIds) end % --- Executes on button press in pushbutton_remove. function pushbutton_remove_Callback(hObject, eventdata, handles) % Find package process id and return if empty props = get(handles.listbox_package,{'UserData','Value','String'}); procIds =props{1}; procId = procIds{props{2}}; if isempty(procId), return; end % Remove pid from the package id list and update package string userData=get(handles.figure1,'UserData'); packageString = props{3}; procIds(props{2})=[]; processClassName = userData.package.getProcessClassNames{props{2}}; processName=eval([processClassName '.getName']); packageString{props{2}} = [' Step ' num2str(props{2}) ': ' processName]; set(handles.listbox_package,'String',packageString,'UserData',procIds); % Add process to the process list props = get(handles.listbox_processes, {'UserData','String'}); procIds=props{1}; processString = props{2}; processString{end+1} = userData.recyclableProc{procId}.getName; set(handles.listbox_processes,'String',processString,'UserData',[procIds procId]); % --- Executes when user attempts to close figure1. function figure1_CloseRequestFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) if isequal(get(handles.figure1, 'waitstatus'), 'waiting') % The GUI is still in UIWAIT, us UIRESUME uiresume(handles.figure1); else % The GUI is no longer waiting, just close it delete(handles.figure1); end % --- Executes on button press in pushbutton_preview. function pushbutton_preview_Callback(hObject, eventdata, handles) % Test if ther is any process to preview processString = get(handles.listbox_processes, 'String'); if isempty(processString), return; end % Load process list and get corresponding process id userData=get(handles.figure1,'UserData'); props = get(handles.listbox_processes, {'UserData','Value'}); procIds=props{1}; procIndex = props{2}; procId=procIds(procIndex); userData.previewFig = userData.recyclableProc{procId}.resultDisplay(); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); if ishandle(userData.previewFig), delete(userData.detailFig); end
github
mehta-lab/Instantaneous-PolScope-master
filterLoG.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/filterLoG.m
2,255
utf_8
51664e4425e439e9812813f363b0391f
% filterLoG : filters a signal with a Laplacian of Gaussian filter. Unlike % the built-in Matlab function fspecial('Laplacian'), this function computes % the exact convolution, using FFTs. % % out = filterLoG(signal, sigma); % % INPUT: signal: input (1-3 dimensional) % sigma : standard deviation of the Gaussian kernel % % OUTPUT: y : LoG filtered signal % % Francois Aguet, last modified: 11/11/2010 % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % function y = filterLoG(signal, sigma) dims = ndims(signal); if numel(signal)==max(size(signal)) dims = 1; end switch dims case 1 nx = length(signal); w1 = -nx/2:nx/2-1; w1 = fftshift(w1); w1 = w1*2*pi/nx; I = fft(signal); LoG = w1.^2 .* exp(-0.5*sigma^2.*w1.^2); y = real(ifft(I.*LoG)); case 2 [ny,nx] = size(signal); [w1,w2] = meshgrid(-nx/2:nx/2-1, -ny/2:ny/2-1); w1 = fftshift(w1); w2 = fftshift(w2); w1 = w1*2*pi/nx; w2 = w2*2*pi/ny; I = fft2(signal); LoG = (w1.^2 + w2.^2) .* exp(-0.5*sigma^2*(w1.^2 + w2.^2)); y = real(ifft2(I.*LoG)); case 3 [ny,nx,nz] = size(signal); [w1,w2,w3] = meshgrid(-nx/2:nx/2-1, -ny/2:ny/2-1, -nz/2:nz/2-1); w1 = fftshift(w1); w2 = fftshift(w2); w3 = fftshift(w3); w1 = w1*2*pi/nx; w2 = w2*2*pi/ny; w3 = w3*2*pi/nz; I = fftn(signal); LoG = (w1.^2 + w2.^2 + w3.^2) .* exp(-0.5*sigma^2*(w1.^2 + w2.^2 + w3.^2)); y = real(ifftn(I.*LoG)); end
github
mehta-lab/Instantaneous-PolScope-master
subResolutionProcessGUI.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/subResolutionProcessGUI.m
17,501
utf_8
d8fdbd388e2db5d6d9da2032b35ed30e
function varargout = subResolutionProcessGUI(varargin) % SUBRESOLUTIONPROCESSGUI M-file for subResolutionProcessGUI.fig % SUBRESOLUTIONPROCESSGUI, by itself, creates a new SUBRESOLUTIONPROCESSGUI or raises the existing % singleton*. % % H = SUBRESOLUTIONPROCESSGUI returns the handle to a new SUBRESOLUTIONPROCESSGUI or the handle to % the existing singleton*. % % SUBRESOLUTIONPROCESSGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in SUBRESOLUTIONPROCESSGUI.M with the given input arguments. % % SUBRESOLUTIONPROCESSGUI('Property','Value',...) creates a new SUBRESOLUTIONPROCESSGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before subResolutionProcessGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to subResolutionProcessGUI_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 % % Copyright (C) 2014 LCCB % % This file is part of u-track. % % u-track is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % u-track is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with u-track. If not, see <http://www.gnu.org/licenses/>. % % % Edit the above text to modify the response to help subResolutionProcessGUI % Last Modified by GUIDE v2.5 16-Dec-2011 15:04:12 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @subResolutionProcessGUI_OpeningFcn, ... 'gui_OutputFcn', @subResolutionProcessGUI_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 subResolutionProcessGUI is made visible. function subResolutionProcessGUI_OpeningFcn(hObject, eventdata, handles, varargin) processGUI_OpeningFcn(hObject, eventdata, handles, varargin{:},'initChannel',1) % Parameter Setup userData = get(handles.figure1, 'UserData'); if(isempty(userData)), userData = struct(); end; funParams = userData.crtProc.funParams_; set(handles.edit_camBitDepth,'String',funParams.detectionParam.bitDepth); set(handles.edit_psfSigma,'String',funParams.detectionParam.psfSigma) arrayfun(@(x)set(handles.(['edit_alphaLocMax' num2str(x)]), 'String', funParams.detectionParam.alphaLocMax(x)), ... 1:length(funParams.detectionParam.alphaLocMax)) if length(funParams.detectionParam.integWindow)>1 || funParams.detectionParam.integWindow set(handles.checkbox_rollingwindow, 'Value', 1) set(handles.text_windowSize, 'Enable', 'on') arrayfun(@(x)set(handles.(['edit_integWindow' num2str(x)]), 'Enable', 'on'), 1:3) arrayfun(@(x)set(handles.(['edit_integWindow' num2str(x)]), ... 'String', num2str(funParams.detectionParam.integWindow(x)*2+1)), ... 1:length(funParams.detectionParam.integWindow)) end % Mixture model fitting set(handles.checkbox_mmf, 'Value', funParams.detectionParam.doMMF) checkbox_mmf_Callback(hObject, eventdata, handles) set(handles.edit_alphaR, 'String', num2str(funParams.detectionParam.testAlpha.alphaR)) set(handles.edit_alphaA, 'String', num2str(funParams.detectionParam.testAlpha.alphaA)) set(handles.edit_alphaD, 'String', num2str(funParams.detectionParam.testAlpha.alphaD)) set(handles.edit_alphaF, 'String', num2str(funParams.detectionParam.testAlpha.alphaF)) if funParams.detectionParam.numSigmaIter set(handles.checkbox_iteration, 'Value', 1) set(handles.text_numSigmaIter, 'Enable', 'on') set(handles.edit_numSigmaIter, 'Enable', 'on', 'String',num2str(funParams.detectionParam.numSigmaIter) ) end set(handles.checkbox_visual, 'Value', funParams.detectionParam.visual) if ~isempty(funParams.detectionParam.background) set(handles.checkbox_background, 'Value', 1) set(handles.edit_av_background, 'String', num2str(funParams.detectionParam.background.alphaLocMaxAbs)) set(handles.edit_path, 'String', funParams.detectionParam.background.imageDir) else set(handles.checkbox_background, 'Value', 0) end checkbox_background_Callback(hObject, eventdata, handles) % funParams.movieParam set(handles.edit_min, 'String', num2str(funParams.firstImageNum)) set(handles.edit_max, 'String', num2str(funParams.lastImageNum)) set(handles.text_framenum, 'String', ['(Totally ' num2str(userData.MD.nFrames_) ' frames in the movie)']) % Choose default command line output for subResolutionProcessGUI handles.output = hObject; % Update user data and GUI data); set(hObject, 'UserData', userData); uicontrol(handles.pushbutton_done); guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = subResolutionProcessGUI_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 checkbox_iteration. function checkbox_mmf_Callback(hObject, eventdata, handles) if get(handles.checkbox_mmf,'Value'), state='on'; else state='off'; end set([handles.text_alphaR handles.edit_alphaR], 'Enable',state) % --- Executes on button press in checkbox_iteration. function checkbox_iteration_Callback(hObject, eventdata, handles) if get(hObject, 'Value') state='on'; % If no maximum number of iterations, use default number 10 value = str2double(get(handles.edit_numSigmaIter, 'String')); if isnan(value), set(handles.edit_numSigmaIter, 'String', '10'); end else state='off'; end set([handles.text_numSigmaIter handles.edit_numSigmaIter], 'Enable',state) % --- Executes on button press in checkbox_rollingwindow. function checkbox_rollingwindow_Callback(hObject, eventdata, handles) if get(hObject, 'Value') state='on'; % If no input, use default number 1 for i=1:3 value = str2double(get(handles.(['edit_integWindow' num2str(i)]), 'String')); if ~isempty(get(handles.(['edit_alphaLocMax' num2str(i)]), 'String')) && isnan(value) set(handles.(['edit_integWindow' num2str(i)]), 'String', '1') end end else state='off'; end set([handles.text_windowSize handles.edit_integWindow1 handles.edit_integWindow2... handles.edit_integWindow3], 'Enable',state) % --- Executes on button press in pushbutton_new. function pushbutton_new_Callback(hObject, eventdata, handles) % hObject handle to pushbutton_new (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) [coor pathname] = cropStack([]); if ~isempty(pathname) && ischar(pathname) set(handles.edit_path, 'String', pathname) end % --- Executes on button press in pushbutton_open. function pushbutton_open_Callback(hObject, eventdata, handles) pathname = uigetdir(pwd); if isequal(pathname,0), return; end set(handles.edit_path, 'String', pathname) % --- Executes on button press in checkbox_background. function checkbox_background_Callback(hObject, eventdata, handles) if get(handles.checkbox_background, 'Value'), state= 'on'; else state='off'; end set(get(handles.uipanel_background,'Children'),'Enable',state); % --- Executes on button press in pushbutton_cancel. function pushbutton_cancel_Callback(hObject, eventdata, handles) userData = get(handles.figure1, 'UserData'); if(isempty(userData)), userData = struct(); end; delete(handles.figure1); % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) % Call back function of 'Apply' button userData = get(handles.figure1, 'UserData'); if(isempty(userData)), userData = struct(); end; if isempty(get(handles.listbox_selectedChannels, 'String')) errordlg('Please select at least one input channel from ''Available Channels''.','Setting Error','modal') return; end channelIndex = get (handles.listbox_selectedChannels, 'Userdata'); funParams.ChannelIndex = channelIndex; % ------------------------- Check user input ----------------------------- missPara = []; %% Required Fields alphaLocMax{1} = get(handles.edit_alphaLocMax1, 'String'); alphaLocMax{2} = get(handles.edit_alphaLocMax2, 'String'); alphaLocMax{3} = get(handles.edit_alphaLocMax3, 'String'); integWindow{1} = get(handles.edit_integWindow1, 'String'); integWindow{2} = get(handles.edit_integWindow2, 'String'); integWindow{3} = get(handles.edit_integWindow3, 'String'); alphaR = get(handles.edit_alphaR, 'String'); alphaA = get(handles.edit_alphaA, 'String'); alphaD = get(handles.edit_alphaD, 'String'); alphaF = get(handles.edit_alphaF, 'String'); alphaLocMaxAbs = get(handles.edit_av_background, 'String'); %% Gaussian Standard Deviation: psfSigma psfSigma = str2double(get(handles.edit_psfSigma, 'String')); if isnan(psfSigma) || psfSigma < 0 errordlg('Please provide a valid value to parameter "Gaussian Standard Deviation".','Error','modal') return end bitDepth = str2double(get(handles.edit_camBitDepth, 'String')); if isnan(bitDepth) || bitDepth < 0 errordlg('Please provide a valid value to parameter "Camera Bit Depth".','Error','modal') return end %% Alpha-value for Local Maxima Detection: alphaLoc validAlphaLocMax = ~cellfun(@isempty, alphaLocMax); if all(~validAlphaLocMax) missPara = horzcat(missPara, sprintf('Alpha-value for Local Maxima Detection\n')); alphaLoc = 0.05; % default elseif any(cellfun(@(x)isnan(str2double(x)), alphaLocMax(validAlphaLocMax))) || any(cellfun(@(x)(str2double(x) < 0), alphaLocMax(validAlphaLocMax))) errordlg('Please provide a valid value to parameter "Alpha-value for Local Maxima Detection".','Error','modal') return else alphaLoc = cellfun(@(x)str2double(x), alphaLocMax(validAlphaLocMax), 'UniformOutput', true); end %% Window Size: integWin temp = cellfun(@(x)~isempty(x), integWindow); if get(handles.checkbox_rollingwindow, 'Value') if isempty(alphaLoc) missPara = horzcat(missPara, sprintf('Window Size\n')); integWin = (1-1)/2; % default elseif length(find(temp)) ~= length(alphaLoc) errordlg('The length of parameter "Camera Bit Depth" must be the same with parameter "Alpha-value for Local Maxima Detection".','Error','modal') return elseif any(cellfun(@(x)isnan(str2double(x)), integWindow(temp))) || any(cellfun(@(x)(str2double(x) < 0), integWindow(temp))) errordlg('Please provide a valid value to parameter "Camera Bit Depth".','Error','modal') return else integWin = cellfun(@(x)str2double(x), integWindow(temp), 'UniformOutput', true); if ~all(mod(integWin, 2) == 1) errordlg('Parameter "Window Size" must be an odd number.','Error','modal') return end integWin = (integWin-1)/2; end else integWin = 0; end %% AlphaR if get(handles.checkbox_mmf, 'Value') if isempty( alphaR ) missPara = horzcat(missPara, sprintf('Alpha Residual\n')); alphaR = 0.05; % default elseif isnan(str2double(alphaR)) || str2double(alphaR) < 0 errordlg('Please provide a valid value to parameter "Alpha Residuals".','Error','modal') return else alphaR = str2double(alphaR); end else alphaR = .05; end %% AlphaA if isempty( alphaA ) missPara = horzcat(missPara, sprintf('Alpha Amplitude\n')); alphaA = 0.05; % default elseif isnan(str2double(alphaA)) || str2double(alphaA) < 0 errordlg('Please provide a valid value to parameter "Alpha Amplitude".','Error','modal') return else alphaA = str2double(alphaA); end %% AlphaD if isempty( alphaD ) missPara = horzcat(missPara, sprintf('Alpha Distance\n')); alphaD = 0.05; % default elseif isnan(str2double(alphaD)) || str2double(alphaD) < 0 errordlg('Please provide a valid value to parameter "Alpha Distance".','Error','modal') return else alphaD = str2double(alphaD); end %% AlphaF if isempty( alphaF ) missPara = horzcat(missPara, sprintf('Alpha Final\n')); alphaF = 0; % default elseif isnan(str2double(alphaF)) || str2double(alphaF) < 0 errordlg('Please provide a valid value to parameter "Alpha Final".','Error','modal') return else alphaF = str2double(alphaF); end %% Maximum Number of Interations: numSigmaIter if get(handles.checkbox_iteration, 'Value') numSigmaIter = str2double(get(handles.edit_numSigmaIter, 'String')); if isnan(numSigmaIter) || numSigmaIter < 0 || floor(numSigmaIter) ~= ceil(numSigmaIter) errordlg('Please provide a valid value to parameter "Maximum Number of Interations".','Error','modal') return end else numSigmaIter = 0; end %% Alpha-value for Local Maxima Detection if get(handles.checkbox_background, 'Value') if isempty( alphaLocMaxAbs ) missPara = horzcat(missPara, sprintf('Background Alpha-value \n')); alphaLocMaxAbs = 0.001; % default elseif isnan(str2double(alphaLocMaxAbs)) || str2double(alphaLocMaxAbs) < 0 errordlg('Please provide a valid value to parameter "Background Alpha-value".','Error','modal') return else alphaLocMaxAbs = str2double(alphaLocMaxAbs); end else alphaLocMaxAbs = []; end %% Background directory: bg_dir if get(handles.checkbox_background, 'Value') bg_dir = get(handles.edit_path, 'String'); if isempty( bg_dir ) errordlg('Please specify a background image directory.','Error','modal') return end if ~strcmp(bg_dir(end), filesep), bg_dir = [bg_dir filesep]; end end %% Frame Index: minid, maxid minid = str2double(get(handles.edit_min, 'String')); if isnan(minid) || minid <= 0 || floor(minid) ~= ceil(minid) errordlg('Please provide a valid value to parameter "Minimum Frame Index".','Error','modal') return end maxid = str2double(get(handles.edit_max, 'String')); if isnan(maxid) || maxid <= 0 || floor(maxid) ~= ceil(maxid) errordlg('Please provide a valid value to parameter "Maximum Frame Index".','Error','modal') return end if minid > maxid errordlg('Minimum frame index is larger than maximum frame index.','Error','modal') return elseif maxid > userData.MD.nFrames_ errordlg('Frame index exceeds the number of frames.', 'Error', 'modal') return end %% TO-DO check validation of output dir and background image dir % Check background image directory if get(handles.checkbox_background, 'Value') fileNames = imDir(bg_dir); if isempty(fileNames) errordlg(sprintf('No valid image file found in the background image directory: %s.', bg_dir),'Error','modal') return end [x1 filenameBase x3 x4] = getFilenameBody(fileNames(1).name); end funParams.firstImageNum = minid; funParams.lastImageNum = maxid; %% funParams.detectionParam funParams.detectionParam.psfSigma = psfSigma; funParams.detectionParam.bitDepth = bitDepth; funParams.detectionParam.alphaLocMax = alphaLoc; funParams.detectionParam.integWindow = integWin; funParams.detectionParam.doMMF = get(handles.checkbox_mmf, 'Value'); funParams.detectionParam.testAlpha.alphaR = alphaR; funParams.detectionParam.testAlpha.alphaA = alphaA; funParams.detectionParam.testAlpha.alphaD = alphaD; funParams.detectionParam.testAlpha.alphaF = alphaF; funParams.detectionParam.numSigmaIter = numSigmaIter; funParams.detectionParam.visual = get(handles.checkbox_visual, 'Value'); if get(handles.checkbox_background, 'Value') funParams.detectionParam.background.imageDir = bg_dir; funParams.detectionParam.background.alphaLocMaxAbs = alphaLocMaxAbs; funParams.detectionParam.background.filenameBase = filenameBase; else funParams.detectionParam.background = []; end % Apply parameters setLastImageNum =@(x) parseProcessParams(x,struct('lastImageNum',... min(x.funParams_.lastImageNum,x.owner_.nFrames_))); processGUI_ApplyFcn(hObject,eventdata,handles,funParams,{setLastImageNum}); % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(hObject, eventdata, handles) if strcmp(eventdata.Key, 'return') pushbutton_done_Callback(handles.pushbutton_done, [], handles); end