├── help └── LAND_manual.pdf ├── utilities ├── simulation │ ├── simCluster.m │ └── sim3Dclusters.m ├── multiWaitbar │ ├── license.txt │ └── multiWaitbar.m ├── visualization │ └── visModuleCluster.m └── cropImage.m ├── coreAlgorithm ├── @ClusterAnalysis │ ├── DBSCAN.m │ ├── ClusterAnalysis.m │ ├── scatterPlot.m │ ├── parameterEstimation.m │ ├── ripley.m │ ├── radialDensityFunction.m │ ├── kNNDistance.m │ └── distanceAnalysis.m ├── batchProcessing │ ├── visDBSCAN.m │ ├── visRDF.m │ ├── visRipley.m │ ├── vis_Distances.m │ ├── clusterBatchProcessing.m │ └── visKNN_Distances.m └── gui │ ├── startClusterAnalysis.fig │ └── startClusterAnalysis.m ├── README.md └── LICENSE /help/LAND_manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wikunia/LAND/master/help/LAND_manual.pdf -------------------------------------------------------------------------------- /utilities/simulation/simCluster.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wikunia/LAND/master/utilities/simulation/simCluster.m -------------------------------------------------------------------------------- /utilities/simulation/sim3Dclusters.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wikunia/LAND/master/utilities/simulation/sim3Dclusters.m -------------------------------------------------------------------------------- /coreAlgorithm/@ClusterAnalysis/DBSCAN.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wikunia/LAND/master/coreAlgorithm/@ClusterAnalysis/DBSCAN.m -------------------------------------------------------------------------------- /coreAlgorithm/batchProcessing/visDBSCAN.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wikunia/LAND/master/coreAlgorithm/batchProcessing/visDBSCAN.m -------------------------------------------------------------------------------- /coreAlgorithm/gui/startClusterAnalysis.fig: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wikunia/LAND/master/coreAlgorithm/gui/startClusterAnalysis.fig -------------------------------------------------------------------------------- /coreAlgorithm/@ClusterAnalysis/ClusterAnalysis.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wikunia/LAND/master/coreAlgorithm/@ClusterAnalysis/ClusterAnalysis.m -------------------------------------------------------------------------------- /coreAlgorithm/@ClusterAnalysis/scatterPlot.m: -------------------------------------------------------------------------------- 1 | function [] = scatterPlot(obj) 2 | %scatterPlot creates scatterplot of experimental and random data 3 | % 4 | % Jan Neumann, 18.04.18 5 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 6 | % random data 7 | figure( 'Name', num2str(obj.sampleID) ); 8 | if obj.dimension == 3 9 | scatter3(obj.randomTable(:, 2), obj.randomTable(:, 1), obj.randomTable(:, 3), '.'); 10 | axis equal vis3d 11 | zlabel('z [nm]') 12 | else 13 | scatter(obj.randomTable(:, 2), obj.randomTable(:, 1), '.'); 14 | axis equal 15 | end 16 | title('Random data') 17 | set(gca,'Ydir','reverse') 18 | xlabel('x [nm]') 19 | ylabel('y [nm]') 20 | %% experimental data 21 | figure( 'Name', num2str(obj.sampleID) ); 22 | if obj.dimension == 3 23 | scatter3(obj.positionTable(:, 2), obj.positionTable(:, 1), obj.positionTable(:, 3), '.'); 24 | axis equal vis3d 25 | zlabel('z [nm]') 26 | else 27 | scatter(obj.positionTable(:, 2), obj.positionTable(:, 1), '.'); 28 | axis equal 29 | end 30 | title('Experimental data') 31 | set(gca,'Ydir','reverse') 32 | xlabel('x [nm]') 33 | ylabel('y [nm]') 34 | end -------------------------------------------------------------------------------- /utilities/multiWaitbar/license.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016, The MathWorks, Inc. 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | * In all cases, the software is, and all modifications and derivatives of the 14 | software shall be, licensed to you solely for use in conjunction with 15 | MathWorks products and service offerings. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 18 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 20 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 21 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 22 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 23 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 24 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 25 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 26 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /coreAlgorithm/batchProcessing/visRDF.m: -------------------------------------------------------------------------------- 1 | function visRDF(Clusterparamstruct, clusterData) 2 | %visRDF Summary of this function goes here 3 | % Detailed explanation goes here 4 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 5 | if Clusterparamstruct.RDF.algorithm == true 6 | % get bin size - should be the same for all samples 7 | binSize = clusterData(1).Analysis.clusterStruct(2).RDF; 8 | binValues = []; 9 | for kk=1:size(clusterData, 2) 10 | binValues = cat(2, clusterData(kk).Analysis.clusterStruct(1).RDF, binValues); 11 | end 12 | binValues = mean(binValues, 2); 13 | % random data 14 | binValuesRandom = []; 15 | if Clusterparamstruct.compareRandomData == true 16 | binSizeRandom = clusterData(1).Analysis.randomClusterStruct(2).RDF; 17 | for kk=1:size(clusterData, 2) 18 | binValuesRandom = cat(2, clusterData(kk).Analysis.randomClusterStruct(1).RDF, binValuesRandom); 19 | end 20 | binValuesRandom = mean(binValuesRandom, 2); 21 | end 22 | %% plotting 23 | h = figure( 'Name', 'Radial Density Function' ); 24 | plot( binSize, binValues); 25 | hold on 26 | if Clusterparamstruct.compareRandomData == true 27 | plot( binSizeRandom, binValuesRandom); 28 | end 29 | grid on; 30 | title('radial density function'); 31 | xlabel('distance [nm]'); 32 | ylabel('g(r)'); 33 | if Clusterparamstruct.compareRandomData == true 34 | legend('experimental data', 'random data'); 35 | else 36 | legend('experimental data'); 37 | end 38 | hold off 39 | savefig(h, [Clusterparamstruct.DIR_output filesep 'RDF.fig']); 40 | end 41 | end -------------------------------------------------------------------------------- /coreAlgorithm/batchProcessing/visRipley.m: -------------------------------------------------------------------------------- 1 | function visRipley(Clusterparamstruct, clusterData) 2 | %visRipley Summary of this function goes here 3 | % Detailed explanation goes here 4 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 5 | if Clusterparamstruct.ripley.algorithm == true 6 | % get bin size - should be the same for all samples 7 | binSize = clusterData(1).Analysis.clusterStruct(2).ripley; 8 | binValues = []; 9 | for kk=1:size(clusterData, 2) 10 | binValues = cat(2, clusterData(kk).Analysis.clusterStruct(1).ripley, binValues); 11 | end 12 | binValues = mean(binValues, 2); 13 | % random data 14 | binValuesRandom = []; 15 | if Clusterparamstruct.compareRandomData == true 16 | binSizeRandom = clusterData(1).Analysis.randomClusterStruct(2).ripley; 17 | for kk=1:size(clusterData, 2) 18 | binValuesRandom = cat(2, clusterData(kk).Analysis.randomClusterStruct(1).ripley, binValuesRandom); 19 | end 20 | binValuesRandom = mean(binValuesRandom, 2); 21 | end 22 | %% plotting 23 | h = figure( 'Name', 'Ripley Function' ); 24 | plot( binSize, binValues); 25 | hold on 26 | if Clusterparamstruct.compareRandomData == true 27 | plot( binSizeRandom, binValuesRandom); 28 | end 29 | grid on; 30 | title('ripley function'); 31 | xlabel('distance [nm]'); 32 | ylabel('L(r)-r'); 33 | if Clusterparamstruct.compareRandomData == true 34 | legend('experimental data', 'random data'); 35 | else 36 | legend('experimental data'); 37 | end 38 | hold off 39 | savefig(h, [Clusterparamstruct.DIR_output filesep 'ripley.fig']); 40 | end 41 | end 42 | 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Localization Analyzer for Nanoscale Distributions (LAND) 2 | 3 | LAND is a software package for Matlab that enables quantitative 2D and 3D analysis of single molecule localization microscopy (SMLM) data. The package includes density-based clustering algorithms like DBSCAN and algorithms used in spatial statistics like the radial density function or Ripley's function. In addition, it contains algorithms for quantifying the conformation and texture of the nuclear nanostructure. LAND has been specifically designed for the evaluation of large sample sizes and data with high emitter densities. 4 | 5 | ## Getting Started 6 | 7 | The follwong sections describe how to get a copy of the software and how to install it on your local machine. Detailed instructions on how to use the software including examples can be found in the manual [LAND_manual.pdf](help/LAND_manual.pdf). 8 | 9 | ### Requirements 10 | 11 | * Matlab R2014b or newer 12 | * Statistics and Machine Learning Toolbox 13 | * Image Processing Toolbox 14 | 15 | * *(optional, but highly recommended for a much faster computation)* [Andrea Tagliasacchi's kdtree](https://github.com/ataiya/kdtree) 16 | 17 | * [multiWaitbar](https://de.mathworks.com/matlabcentral/fileexchange/26589-multiwaitbar-label-varargin) (a copy is included in this distribution) 18 | 19 | At least 8 GByte RAM are recommended. 20 | 21 | ### Installing 22 | 23 | * download the software package from https://github.com/Jan-NM/LAND 24 | * extract **LAND-master.zip** 25 | * copy the generated **LAND-master** directory into your local Matlab working directory (on Windows machines, usually C:\Users\ "user name"\Documents\MATLAB) 26 | 27 | To use Andrea Tagliasacchi's kdtree, download the following files from https://github.com/ataiya/kdtree/tree/master/toolbox: 28 | * KDTree.h 29 | * kdtree_ball_query.cpp 30 | * kdtree_ball_query.m 31 | * kdtree_build.cpp 32 | * kdtree_build.m 33 | * kdtree_delete.cpp 34 | * kdtree_delete.m 35 | * MyHeaps.h 36 | 37 | These files must now be compiled. 38 | * create a folder named "*kdtree*" in the directory "*...\LAND-master\utilities\...*" 39 | * configure the [MEX environment](https://de.mathworks.com/help/matlab/matlab_external/what-you-need-to-build-mex-files.html) 40 | * download and install a Matlab-supported C++ compiler 41 | 42 | The following description is for Windows machines: 43 | 44 | * type "*mex -setup C++*" in Matlab's command window to setup the mex environment 45 | * open "...\LAND-master\utilities\ataiya_kdtree\..." in Matlab's current folder panel 46 | * type "*mex kdtree_build.cpp*" in Matlab's command window 47 | * type "*mex kdtree_ball_query.cpp*" in Matlab's command window 48 | * type "*mex kdtree_delete.cpp*" in Matlab's command window 49 | 50 | * to use LAND, right click on ILAND-master in Matlab's current folder panel, go to "*Add to Path*" and click on "*Selected Folders and Subfolders*" 51 | 52 | LAND can be used via the command window or by opening the user interface. To open the user interface type "*startClusterAnalysis*" in the command window. Detailed instructions on how to use the software including examples can be found in the manual [LAND_manual.pdf](help/ILAND_manual.pdf). 53 | 54 | ## License 55 | 56 | LAND is licensed under the GNU GPL - see the [LICENSE](LICENSE) file for details. LAND includes [multiWaitbar](https://de.mathworks.com/matlabcentral/fileexchange/26589-multiwaitbar-label-varargin), which comes with a separate license. 57 | 58 | ## Notes 59 | 60 | DBSCAN is based on the paper: Ester at al., "A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise", (1996). 61 | -------------------------------------------------------------------------------- /coreAlgorithm/@ClusterAnalysis/parameterEstimation.m: -------------------------------------------------------------------------------- 1 | function [] = parameterEstimation( obj, method) 2 | %parameterEstimation helps to estimate appropriate parameters for DBSCAN 3 | % Jan Neumann, 27.06.17 4 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 5 | switch method 6 | case 'DBSCAN' 7 | figure('Name', 'DBSCAN parameter estimation'); 8 | set(gcf,'units', 'normalized', 'outerposition', [0 0 1 1]) 9 | subplot(2,2,1) 10 | %% calculate nearest neighbor distance (k = 2) 11 | positions = obj.positionTable; 12 | treeData = obj.queryData; 13 | switch obj.flagSearchTree 14 | case 'cTree' % for knn search, use Matlab's internal function 15 | [~, nnDistance] = knnsearch(positions(:, 1:obj.dimension), positions(:, 1:obj.dimension), 'K', 2); 16 | case 'matlabTree' 17 | [~, nnDistance] = knnsearch(treeData.X, treeData.X, 'K', 2); 18 | end 19 | nnDistances = mean(nnDistance(:, 2:end), 2); 20 | % plot histogram 21 | histogram(nnDistances, 'Normalization', 'probability'); 22 | grid on 23 | xlabel('distance [nm]'); 24 | ylabel('normalized frequency'); 25 | title('Nearest neighbor distances'); 26 | %% enter radius and do rangesearch with corresponding radius 27 | prompt = {'Enter radius value [nm]:'}; 28 | dlg_title = 'Input'; 29 | num_lines = 1; 30 | defaultans = {'2'}; 31 | radius = inputdlg(prompt,dlg_title,num_lines,defaultans); 32 | radius = str2double(radius{1}); 33 | switch obj.flagSearchTree % should be done on a cropped dataset for large position tables 34 | case 'cTree' 35 | [~, distance] = rangesearch(positions(:, 1:obj.dimension), positions(:, 1:obj.dimension), radius); 36 | case 'matlabTree' 37 | [~, distance] = rangesearch(positions(:, 1:obj.dimension), treeData.X, radius); 38 | end 39 | minPoints = cellfun('length', distance); 40 | subplot(2,2,2) 41 | histogram(minPoints) 42 | title(['Frequency of number of neighbors for radius ' num2str(radius)]); 43 | xlabel('Number of neighbors'); 44 | ylabel('frequency'); 45 | grid on 46 | %% second method according to DBSCAN paper 47 | % enter k value 48 | prompt = {'Enter k value:'}; 49 | dlg_title = 'Input'; 50 | num_lines = 1; 51 | defaultans = {'4'}; 52 | k = inputdlg(prompt,dlg_title,num_lines,defaultans); 53 | k = str2double(k{1}); 54 | % calculate k-NN distance 55 | switch obj.flagSearchTree 56 | case 'cTree' % for knn search, use Matlab's internal function 57 | [~, nnDistance] = knnsearch(positions(:, 1:obj.dimension), positions(:, 1:obj.dimension), 'K', k); 58 | case 'matlabTree' 59 | [~, nnDistance] = knnsearch(treeData.X, treeData.X, 'K', k); 60 | end 61 | % mean over NN distance 62 | nnDistances = mean(nnDistance(:, 2:end), 2); 63 | %% create k-distance graph 64 | % sort k-distances in ascending order 65 | nnDistances = sortrows(nnDistances, 'ascend'); 66 | % plot figures for estimation of radius parameter 67 | subplot(2,2,3) 68 | histogram(nnDistances, 'Normalization', 'probability'); 69 | title([num2str(k), '-nearest neighbor distance']); 70 | grid on 71 | xlabel('distance [nm]'); 72 | ylabel('normalized frequency'); 73 | subplot(2,2,4) 74 | plot(nnDistances); 75 | title([num2str(k), '-distance graph']); 76 | grid on; 77 | xlabel('points'); 78 | ylabel('radius [nm]'); 79 | otherwise 80 | disp('Choose DBSCAN as method!') 81 | end 82 | end -------------------------------------------------------------------------------- /utilities/visualization/visModuleCluster.m: -------------------------------------------------------------------------------- 1 | function [varargout] = visModuleCluster(locTable, visMethod, pixelSize) 2 | %visModuleCluster visualization for cluster algorithm 3 | % 4 | % Following visualization methods are supported 5 | % histogramBinning [2D only] 6 | % gaussianBlur [2D only] 7 | % 8 | % input parameters 9 | % locTable Matrix that contains point coordinates. Rows should 10 | % correspond to detected signals. Columns should be 11 | % arranged in the follwing order (column 1 - x coordiante, column 2 - y coordiante, , column 4 - x loc. prec., column 5 - y loc. prec.) 12 | % visMethod any of the specified visualization methods as string 13 | % for example 'histogramBinning' 14 | % pixelSize final super-resolution pixel size 15 | % 16 | % requires Image Processing Toolbox, Statistics and Machine Learning 17 | % Toolbox 18 | % 19 | % by Jan Neumann, IMB Mainz, 12.02.2018 20 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 21 | nSteps = 100; % needed in gaussian blur if individual blurring method is used, specifies binning for loc. prec. 22 | 23 | if nargin < 3 24 | multiWaitbar('CloseAll'); 25 | error('Please specify at least visualization method and pixel size!'); 26 | end 27 | %% start with visualization method 28 | switch visMethod 29 | case 'histogramBinning' 30 | x1 = double(ceil(locTable(:, 1)./pixelSize)); 31 | y1 = double(ceil(locTable(:, 2)./pixelSize)); 32 | % generate histogram binned image 33 | SRimage = sparse(x1-min(x1)+1, y1-min(y1)+1, 1); 34 | SRimage = full(SRimage); 35 | case 'gaussianBlur' 36 | minPrecision = floor(min(min(locTable(:, 4:5)))); 37 | maxPrecision = ceil(max(max(locTable(:, 4:5)))); 38 | % get dimension of image 39 | x1 = double(round(locTable(:, 1)./pixelSize)); 40 | y1 = double(round(locTable(:, 2)./pixelSize)); 41 | % generate histogram binned image 42 | [xSize, ySize] = size(full(sparse(x1-min(x1)+1, y1-min(y1)+1, 1))); 43 | minX = min(x1); 44 | minY = min(y1); 45 | SRimage = zeros(xSize, ySize, 'single'); 46 | prevStep = minPrecision; 47 | steps = linspace(minPrecision, maxPrecision, nSteps); 48 | if steps == 0 49 | steps = 2 * pixelSize; % in case data does not contain localization precision 50 | end 51 | steps(1) = []; 52 | for ii = steps 53 | % find points with specific loc prec. 54 | idx = (mean(locTable(:, 4:5), 2) <= ii) & (mean(locTable(:, 4:5), 2) > prevStep); 55 | tempPoints = locTable(idx, :); 56 | globalBlur = ((0.5*(ii - prevStep)) + prevStep) / pixelSize; 57 | % generate histogram binned with current selection of points 58 | x1 = double(round(tempPoints(:, 1)./pixelSize)); 59 | y1 = double(round(tempPoints(:, 2)./pixelSize)); 60 | tempImage = sparse(x1-minX+1, y1-minY+1, 1, xSize, ySize); % check if x and y are correct 61 | tempImage = full(tempImage); 62 | % images should have fixed size to be abble to be added 63 | % check version of matlab 64 | if verLessThan('matlab', '8.5') 65 | h = fspecial('gaussian', 2*ceil(2*globalBlur) + 1, globalBlur); 66 | SRimage = SRimage + imfilter(tempImage, h, 'conv'); 67 | % alternative implement own filter 68 | % maskSize = 2*ceil(2*globalBlur) + 1; 69 | % ind = -floor(maskSize/2) : floor(maskSize/2); 70 | % [X, Y] = meshgrid(ind, ind); 71 | % h = exp(-(X.^2 + Y.^2)/(2*globalBlur*globalBlur)); 72 | % h = h / sum(h(:)); 73 | % SRimage = SRimage + conv2(tempImage ,h); 74 | else 75 | SRimage = SRimage + imgaussfilt(tempImage, globalBlur); 76 | end 77 | prevStep = ii; 78 | end 79 | end 80 | varargout{1} = SRimage; 81 | end -------------------------------------------------------------------------------- /utilities/cropImage.m: -------------------------------------------------------------------------------- 1 | function [] = cropImage() 2 | %cropImage crops SMLM image 3 | % 4 | % partially based on cropOrte.m by Martin Hagmann 5 | % crops several ROIs from batch of images 6 | % 7 | % Jan Neumann, 06.03.18 8 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 9 | pixelSize = 10; % default SR pixel size for histogram binning 10 | [FileName, PathName] = uigetfile('*.mat', 'Select the localization data file(s).', 'MultiSelect', 'on'); 11 | if isequal(FileName, 0) 12 | errorMessage = sprintf('Error no file selected'); 13 | uiwait(warndlg(errorMessage)); 14 | return; 15 | end 16 | 17 | FileName = cellstr(FileName); % convert to cell if only one file is selected 18 | 19 | for ii = 1:numel(FileName) 20 | figure('units','normalized','outerposition',[0 0 1 1]); 21 | subplot(1, 2, 1); 22 | % load list of localizations 23 | locFile = load(fullfile(PathName, FileName{ii})); 24 | oldField = char(fieldnames(locFile)); 25 | if ~(strcmp(oldField, 'Orte')) 26 | newField = 'Orte'; 27 | [locFile.(newField)] = locFile.(oldField); 28 | locFile = rmfield(locFile, oldField); 29 | end 30 | % reconstruct histogram binned image for cropping 31 | x1 = round(locFile.Orte(:, 2)./pixelSize); 32 | y1 = round(locFile.Orte(:, 3)./pixelSize); 33 | SRimage = sparse(x1-min(x1)+1, y1-min(y1)+1, 1); 34 | % transform to 8 bit 35 | SRimage = full(SRimage); 36 | SRimage = SRimage > 0; 37 | imagesc(SRimage); 38 | axis image; 39 | k = waitforbuttonpress; 40 | point1 = get(gca, 'CurrentPoint'); % button down detected 41 | finalRect = rbbox; % return figure units 42 | point2 = get(gca, 'CurrentPoint'); % button up detected 43 | point1 = point1(1, 1:2); % extract x and y 44 | point2 = point2(1, 1:2); 45 | p1 = min(point1, point2); % calculate locations 46 | offset = abs(point1-point2); % and dimensions 47 | % Find the coordinates of the box. 48 | xCoords = [p1(1) p1(1)+offset(1) p1(1)+offset(1) p1(1) p1(1)]; 49 | yCoords = [p1(2) p1(2) p1(2)+offset(2) p1(2)+offset(2) p1(2)]; 50 | x1Cropped = round(xCoords(1)); 51 | x2Cropped = round(xCoords(2)); 52 | y1Cropped = round(yCoords(5)); 53 | y2Cropped = round(yCoords(3)); 54 | hold on 55 | axis manual 56 | plot(xCoords, yCoords, 'r-'); % redraw in dataspace units 57 | % Display the cropped image. 58 | % figure 59 | % croppedImage = SRimage(y1Cropped:y2Cropped, x1Cropped:x2Cropped); 60 | % imshow(croppedImage); 61 | % axis on; 62 | % title('Region that you defined', 'FontSize', 30); 63 | % transform to Orte coordinates 64 | minX = x1Cropped * pixelSize; 65 | minY = y1Cropped * pixelSize; 66 | maxX = x2Cropped * pixelSize; 67 | maxY = y2Cropped * pixelSize; 68 | % work first with min / max and floor / ceil then multiply with pixelsize 69 | 70 | % rectangle('Position',[imRect(1), imRect(2), imRect(3), imRect(4)],... 71 | % 'Curvature',[0.0, 0.0], 'EdgeColor', 'r', 'LineWidth', 3,... 72 | % 'LineStyle','-'); 73 | OrteCropped = locFile.Orte(locFile.Orte(:, 3) > minX & locFile.Orte(:, 3) < maxX, :); 74 | OrteCropped = OrteCropped(OrteCropped(:, 2) > minY & OrteCropped(:, 2) < maxY, :); 75 | % shift list of localization 76 | mincroppedX = min(OrteCropped(:, 3)); 77 | mincroppedY = min(OrteCropped(:, 2)); 78 | OrteCropped(:, 3) = OrteCropped(:, 3) - mincroppedX + 1; 79 | OrteCropped(:, 2) = OrteCropped(:, 2) - mincroppedY + 1; 80 | x1 = round(OrteCropped(:, 2)./pixelSize); 81 | y1 = round(OrteCropped(:, 3)./pixelSize); 82 | SRimage = sparse(x1-min(x1)+1, y1-min(y1)+1, 1); 83 | % transform to 8 bit 84 | SRimage = full(SRimage); 85 | SRimage = SRimage > 0; 86 | subplot(1, 2, 2); 87 | imagesc(SRimage); 88 | axis image; 89 | Orte = OrteCropped; 90 | save([PathName FileName{ii}(1:end-4) '_cropped.mat'], 'Orte'); 91 | end 92 | end -------------------------------------------------------------------------------- /coreAlgorithm/@ClusterAnalysis/ripley.m: -------------------------------------------------------------------------------- 1 | function [] = ripley( obj, samplingDistance, maxRadius, isRandom, showPlot) 2 | %ripley computes Ripley's function using the point 3 | % coordinates 4 | % 5 | % Input: 6 | % samplingDistance: step size for the radius, in nm 7 | % maxRadius: maximum distance up to which the ripley function is calculated 8 | % (only points with this minimum distance to the image boundary 9 | % are considered), in nm 10 | % isRandom: true if random positions should be used 11 | % showPlot: plot ripley finction 12 | % 13 | % Output: 14 | % (1) L(r)-r values for each bin 15 | % (2) center of each bin, in nm 16 | % 17 | % Jan Neumann, 02.06.2018 18 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 19 | %% init 20 | multiWaitbar('computing Ripley''s H-function...', 0); 21 | switch nargin 22 | case 3 23 | isRandom = 0; 24 | showPlot = 0; 25 | case 4 26 | showPlot = 0; 27 | case 5 28 | 29 | otherwise 30 | error('Wrong number of input arguments!') 31 | end 32 | if isRandom == true 33 | positions = obj.randomTable; 34 | dataMat = obj.randomClusterStruct; 35 | nPoints = obj.randomNoOfPoints; 36 | treeData = obj.randomQueryData; 37 | flagSearchTree = obj.flagSearchTreeRandomData; 38 | physicalDimension(1, :) = obj.randomPhysicalDimension(1, :); 39 | physicalDimension(2, :) = obj.randomPhysicalDimension(2, :); 40 | if obj.dimension == 3 41 | physicalDimension(3, :) = obj.randomPhysicalDimension(3, :); 42 | end 43 | else 44 | positions = obj.positionTable; 45 | dataMat = obj.clusterStruct; 46 | nPoints = obj.NoOfPoints; 47 | treeData = obj.queryData; 48 | flagSearchTree = obj.flagSearchTree; 49 | physicalDimension(1, :) = obj.physicalDimension(1, :); 50 | physicalDimension(2, :) = obj.physicalDimension(2, :); 51 | if obj.dimension == 3 52 | physicalDimension(3, :) = obj.physicalDimension(3, :); 53 | end 54 | end 55 | % initialize output fields of dataMat 56 | dataMat(1).ripley = []; 57 | dataMat(2).ripley = []; 58 | %% compute Ripley's function 59 | % create bins for Ripley histogram 60 | nbins = ceil(maxRadius/samplingDistance); 61 | [binArray, edges] = histcounts([0 maxRadius], nbins); 62 | binArray = zeros(size(binArray, 2), 1); 63 | 64 | % to avoid edge effects only points within a minimum distance of 65 | % maxDiameter to the image boundaries are considered 66 | if obj.dimension == 3 67 | mapSize = ceil(max(positions(:, 1:3))); 68 | currentPositions = positions(positions(:, 1) > maxRadius & positions(:, 1) < mapSize(1) - maxRadius... 69 | & positions(:, 2) > maxRadius & positions(:, 2) < mapSize(2) - maxRadius... 70 | & positions(:, 3) > maxRadius & positions(:, 3) < mapSize(3) - maxRadius, :); 71 | else 72 | mapSize = ceil(max(positions(:, 1:2))); 73 | currentPositions = positions(positions(:, 1) > maxRadius & positions(:, 1) < mapSize(1)-maxRadius... 74 | & positions(:, 2) > maxRadius & positions(:, 2) < mapSize(2)-maxRadius, :); 75 | end 76 | % check of currentPositions is empty 77 | if isempty(currentPositions) 78 | error('Image size is to small or maxRadius is to big! Can not find any points which have maxRadius distance from the image borders! Try to decrease maxRadius or increase image region.'); 79 | end 80 | nPointsFinal = size(currentPositions, 1); 81 | 82 | % for waitbar 83 | prevPercent = 0; 84 | counter = 1; 85 | % loop through all points 86 | for ii = 1:size(currentPositions, 1) 87 | % loop through all radii 88 | for ll = 1:size(binArray, 1) 89 | % get number of points within radii 90 | switch flagSearchTree 91 | case 'cTree' 92 | radDistances = kdtree_ball_query(treeData, currentPositions(ii, 1:obj.dimension), edges(ll + 1)); 93 | case 'matlabTree' 94 | distance = rangesearch(currentPositions(ii, 1:obj.dimension), treeData.X, edges(ll + 1)); 95 | radDistances = (find(~cellfun('isempty', distance))).'; 96 | end 97 | binArray(ll, 1) = binArray(ll, 1) + numel(radDistances) - 1; % sum up points within r, ignore current point 98 | end 99 | % waitbar 100 | currentPercent = fix(100*counter/nPointsFinal); 101 | if currentPercent > prevPercent 102 | multiWaitbar( 'computing Ripley''s H-function...', 'Value', counter/nPointsFinal); 103 | prevPercent = currentPercent; 104 | end 105 | counter = counter + 1; 106 | end 107 | 108 | %% normalize data 109 | if obj.dimension == 3 110 | density = nPoints / (physicalDimension(1, :) * physicalDimension(2, :) * physicalDimension(3, :)); 111 | else 112 | density = nPoints / (physicalDimension(1, :) * physicalDimension(2, :)); 113 | end 114 | binArray = binArray ./ nPointsFinal ./density; 115 | for ll = 1:size(binArray, 1) 116 | if obj.dimension == 3 117 | binArray(ll) = nthroot(binArray(ll, 1) / pi * 3/4, 3) - (edges(1, ll) + samplingDistance); 118 | else 119 | binArray(ll) = sqrt(binArray(ll, 1) / pi) - (edges(1, ll) + samplingDistance); 120 | end 121 | end 122 | multiWaitbar( 'computing Ripley''s H-function...', 'Close'); 123 | %% visualization 124 | if showPlot == true 125 | figure( 'Name', num2str(obj.sampleID) ); 126 | plot(edges(1 ,1:end-1) + samplingDistance/2, binArray); 127 | grid on; 128 | title('Ripleys function'); 129 | xlabel('distance [nm]'); 130 | ylabel('L(r)-r'); 131 | xlim([min(edges) max(edges)]); 132 | end 133 | %% output 134 | dataMat(1).ripley = binArray; 135 | dataMat(2).ripley = (edges(1, 1:end-1) + samplingDistance/2).'; 136 | if isRandom == true 137 | obj.randomClusterStruct = dataMat; 138 | else 139 | obj.clusterStruct = dataMat; 140 | end 141 | end -------------------------------------------------------------------------------- /coreAlgorithm/@ClusterAnalysis/radialDensityFunction.m: -------------------------------------------------------------------------------- 1 | function [] = radialDensityFunction( obj, binSize, maxRadius, isRandom, showPlot ) 2 | %radialDensityFunction computes radial density function function using the point 3 | % coordinates 4 | % 5 | % Input: 6 | % binSize: size of the shell (dr), in nm 7 | % maxRadius: maximum distance up to which the radial density function is calculated 8 | % (only points with this minimum distance to the image boundary 9 | % are considered), in nm 10 | % isRandom: true if random positions should be used 11 | % showPlot: plot pair correlation function 12 | % 13 | % Output: 14 | % (1) g(r) values for each bin 15 | % (2) center of each bin, in nm 16 | % 17 | % Jan Neumann, 27.06.2017 18 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 19 | %% init 20 | multiWaitbar('computing radial density function...', 0); 21 | switch nargin 22 | case 3 23 | isRandom = 0; 24 | showPlot = 0; 25 | case 4 26 | showPlot = 0; 27 | case 5 28 | 29 | otherwise 30 | error('Wrong number of input arguments!') 31 | end 32 | if isRandom == true 33 | positions = obj.randomTable; 34 | dataMat = obj.randomClusterStruct; 35 | nPoints = obj.randomNoOfPoints; 36 | treeData = obj.randomQueryData; 37 | flagSearchTree = obj.flagSearchTreeRandomData; 38 | physicalDimension(1, :) = obj.randomPhysicalDimension(1, :); 39 | physicalDimension(2, :) = obj.randomPhysicalDimension(2, :); 40 | if obj.dimension == 3 41 | physicalDimension(3, :) = obj.randomPhysicalDimension(3, :); 42 | end 43 | else 44 | positions = obj.positionTable; 45 | dataMat = obj.clusterStruct; 46 | nPoints = obj.NoOfPoints; 47 | treeData = obj.queryData; 48 | flagSearchTree = obj.flagSearchTree; 49 | physicalDimension(1, :) = obj.physicalDimension(1, :); 50 | physicalDimension(2, :) = obj.physicalDimension(2, :); 51 | if obj.dimension == 3 52 | physicalDimension(3, :) = obj.physicalDimension(3, :); 53 | end 54 | end 55 | % initialize output fields of dataMat 56 | dataMat(1).RDF = []; 57 | dataMat(2).RDF = []; 58 | %% radial density function algorithm 59 | % create bins for radial density function 60 | nbins = ceil(maxRadius/binSize); 61 | [binArray, edges] = histcounts([0 maxRadius], nbins); 62 | binArray = zeros(size(binArray, 2), 1); 63 | 64 | % to avoid edge effects only points within a minimum distance of 65 | % maxDiameter to the image boundaries are considered 66 | if obj.dimension == 3 67 | mapSize = ceil(max(positions(:, 1:3))); 68 | currentPositions = positions(positions(:, 1) > maxRadius & positions(:, 1) < mapSize(1) - maxRadius... 69 | & positions(:, 2) > maxRadius & positions(:, 2) < mapSize(2) - maxRadius... 70 | & positions(:, 3) > maxRadius & positions(:, 3) < mapSize(3) - maxRadius, :); 71 | else 72 | mapSize = ceil(max(positions(:, 1:2))); 73 | currentPositions = positions(positions(:, 1) > maxRadius & positions(:, 1) < mapSize(1)-maxRadius... 74 | & positions(:, 2) > maxRadius & positions(:, 2) < mapSize(2)-maxRadius, :); 75 | end 76 | % check if currentPositions is empty 77 | if isempty(currentPositions) 78 | error(['Image size is too small or maxRadius is too big! Can not find any points which have ', num2str(maxRadius), ' nm distance from the image borders! Try to decrease maxRadius or increase image region.']); 79 | end 80 | nPointsFinal = size(currentPositions, 1); 81 | 82 | % for waitbar 83 | prevPercent = 0; 84 | counter = 1; 85 | % loop through all points 86 | for ii = 1:size(currentPositions, 1) 87 | % loop through all radii 88 | for ll = 1:size(binArray, 1) 89 | % get number of points within radii 90 | switch flagSearchTree 91 | case 'cTree' 92 | radInDistances = kdtree_ball_query(treeData, currentPositions(ii, 1:obj.dimension), edges(ll)); % get number of points within r 93 | radOutDistances = kdtree_ball_query(treeData, currentPositions(ii, 1:obj.dimension), edges(ll + 1)); % get number of points within r + dr 94 | case 'matlabTree' 95 | radInDistances = rangesearch(currentPositions(ii, 1:obj.dimension), treeData.X, edges(ll)); 96 | radOutDistances = rangesearch(currentPositions(ii, 1:obj.dimension), treeData.X, edges(ll + 1)); 97 | radInDistances = (find(~cellfun('isempty', radInDistances))).'; 98 | radOutDistances = (find(~cellfun('isempty', radOutDistances))).'; 99 | end 100 | binArray(ll, 1) = binArray(ll, 1) + numel(radOutDistances) - numel(radInDistances); % number of points within shell dr 101 | end 102 | % waitbar 103 | currentPercent = fix(100*counter/nPointsFinal ); 104 | if currentPercent > prevPercent 105 | multiWaitbar( 'computing radial density function...', 'Value', counter/nPointsFinal ); 106 | prevPercent = currentPercent; 107 | end 108 | counter = counter + 1; 109 | end 110 | %% normalize data (g(r) = binArray(ii) / (binArea*density*nPoints)) - center of each bin is taken as r 111 | if obj.dimension == 3 112 | density = nPoints / (physicalDimension(1, :) * physicalDimension(2, :) * physicalDimension(3, :)); 113 | else 114 | density = nPoints / (physicalDimension(1, :) * physicalDimension(2, :)); 115 | end 116 | for ii = 1 : nbins 117 | innerPart = edges(1, ii) + binSize/2; 118 | outerPart = innerPart + binSize; 119 | if obj.dimension == 3 120 | binArray(ii) = binArray(ii) / (4/3*pi*outerPart^3 - 4/3*pi*innerPart^3); 121 | else 122 | binArray(ii) = binArray(ii) / (pi*outerPart^2 - pi*innerPart^2); 123 | end 124 | end 125 | binArray = binArray ./ nPointsFinal ./ density ; 126 | multiWaitbar( 'computing radial density function...', 'Close'); 127 | %% visualization 128 | if showPlot == true 129 | figure( 'Name', num2str(obj.sampleID) ); 130 | plot(edges(1 ,1:end-1) + binSize/2, binArray); 131 | grid on; 132 | title('radial density function'); 133 | xlabel('distance [nm]'); 134 | ylabel('g(r)'); 135 | xlim([min(edges) max(edges)]); 136 | end 137 | %% output 138 | dataMat(1).RDF = binArray; 139 | dataMat(2).RDF = (edges(1, 1:end-1) + binSize/2).'; 140 | if isRandom == true 141 | obj.randomClusterStruct = dataMat; 142 | else 143 | obj.clusterStruct = dataMat; 144 | end 145 | end -------------------------------------------------------------------------------- /coreAlgorithm/batchProcessing/vis_Distances.m: -------------------------------------------------------------------------------- 1 | function vis_Distances(Clusterparamstruct, clusterData) 2 | %vis_Distances Summary of this function goes here 3 | % Detailed explanation goes here 4 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 5 | if Clusterparamstruct.Distance.algorithm == true 6 | nSamples = size(clusterData, 2); 7 | totalDistance = cell(1, nSamples); 8 | totalDistanceRandom = cell(1, nSamples); 9 | totalInnerDistance = cell(1, nSamples); 10 | totalOuterDistance = cell(1, nSamples); 11 | totalInnerDistanceRandom = cell(1, nSamples); 12 | totalOuterDistanceRandom = cell(1, nSamples); 13 | for kk=1:nSamples 14 | if isfield(clusterData(kk).Analysis.clusterStruct, 'allDistances') 15 | totalDistance{kk} = clusterData(kk).Analysis.clusterStruct(1).allDistances; 16 | else 17 | totalDistance{kk} = 0; 18 | end 19 | end 20 | totalDistance = cell2mat(totalDistance.'); 21 | % if DBSCAN was done before 22 | if isfield(clusterData(kk).Analysis.clusterStruct, 'clusterDBSCAN') 23 | for kk=1:nSamples 24 | if isfield(clusterData(kk).Analysis.clusterStruct, 'allDistances') 25 | totalInnerDistance{kk} = clusterData(kk).Analysis.clusterStruct(2).allDistances; 26 | totalOuterDistance{kk} = clusterData(kk).Analysis.clusterStruct(3).allDistances; 27 | else 28 | totalInnerDistance{kk} = 0; 29 | totalOuterDistance{kk} = 0; 30 | end 31 | end 32 | end 33 | totalInnerDistance = cell2mat(totalInnerDistance.'); 34 | totalOuterDistance = cell2mat(totalOuterDistance.'); 35 | %% for random data 36 | if Clusterparamstruct.compareRandomData == true 37 | for kk=1:nSamples 38 | if isfield(clusterData(kk).Analysis.randomClusterStruct, 'allDistances') 39 | totalDistanceRandom{kk} = clusterData(kk).Analysis.randomClusterStruct(1).allDistances; 40 | end 41 | end 42 | totalDistanceRandom = cell2mat(totalDistanceRandom.'); 43 | end 44 | % if DBSCAN was done before 45 | if isfield(clusterData(kk).Analysis.randomClusterStruct, 'clusterDBSCAN') 46 | if ~isempty(clusterData(kk).Analysis.randomClusterStruct(2).clusterDBSCAN) 47 | for kk=1:nSamples 48 | if isfield(clusterData(kk).Analysis.randomClusterStruct, 'allDistances') 49 | totalInnerDistanceRandom{kk} = clusterData(kk).Analysis.randomClusterStruct(2).allDistances; 50 | totalOuterDistanceRandom{kk} = clusterData(kk).Analysis.randomClusterStruct(3).allDistances; 51 | end 52 | end 53 | totalInnerDistanceRandom = cell2mat(totalInnerDistanceRandom.'); 54 | totalOuterDistanceRandom = cell2mat(totalOuterDistanceRandom.'); 55 | end 56 | end 57 | %% plotting 58 | h = figure( 'Name', 'Distance' ); 59 | histogram(totalDistance, ceil(max(totalDistance(:, 1))), 'Normalization', 'probability'); 60 | hold on 61 | if Clusterparamstruct.compareRandomData == true && isfield(clusterData(kk).Analysis.randomClusterStruct, 'allDistances') 62 | histogram(totalDistanceRandom, ceil(max(totalDistanceRandom(:, 1))), 'Normalization', 'probability'); 63 | end 64 | grid on; 65 | title('Distance Analysis'); 66 | xlabel('distance [nm]'); 67 | ylabel('normalized frequency'); 68 | if Clusterparamstruct.compareRandomData == true 69 | legend(['mean distance = ' num2str(mean(totalDistance)) ' nm \pm ' num2str(std(totalDistance)) ' nm'],... 70 | ['mean distance = ' num2str(mean(totalDistanceRandom)) ' nm \pm ' num2str(std(totalDistanceRandom)) ' nm']); 71 | else 72 | legend(['mean distance = ' num2str(mean(totalDistance)) ' nm \pm ' num2str(std(totalDistance)) ' nm']); 73 | end 74 | ax = gca; 75 | ax.XLim = [0 Clusterparamstruct.Distance.maxDistance]; 76 | hold off 77 | savefig(h, [Clusterparamstruct.DIR_output filesep 'distance.fig']); 78 | 79 | % inner distances 80 | if isfield(clusterData(kk).Analysis.clusterStruct, 'clusterDBSCAN') 81 | if ~isempty(clusterData(kk).Analysis.clusterStruct(2).clusterDBSCAN) 82 | h = figure( 'Name', 'Distances of points within a cluster' ); 83 | histogram(totalInnerDistance, ceil(max(totalInnerDistance(:, 1))), 'Normalization', 'probability'); 84 | hold on 85 | if Clusterparamstruct.compareRandomData == true && isfield(clusterData(kk).Analysis.randomClusterStruct, 'allDistances') 86 | histogram(totalInnerDistanceRandom, ceil(max(totalInnerDistanceRandom(:, 1))), 'Normalization', 'probability'); 87 | end 88 | grid on; 89 | title('Distance Analysis of points within a cluster'); 90 | xlabel('distance [nm]'); 91 | ylabel('normalized frequency'); 92 | if Clusterparamstruct.compareRandomData == true && isfield(clusterData(kk).Analysis.randomClusterStruct, 'allDistances') 93 | legend(['mean distance = ' num2str(mean(totalInnerDistance)) ' nm \pm ' num2str(std(totalInnerDistance)) ' nm'],... 94 | ['mean distance = ' num2str(mean(totalInnerDistanceRandom)) ' nm \pm ' num2str(std(totalInnerDistanceRandom)) ' nm']); 95 | else 96 | legend(['mean distance = ' num2str(mean(totalInnerDistance)) ' nm \pm ' num2str(std(totalInnerDistance)) ' nm']); 97 | end 98 | ax = gca; 99 | ax.XLim = [0 Clusterparamstruct.Distance.maxDistance]; 100 | hold off 101 | savefig(h, [Clusterparamstruct.DIR_output filesep 'innerDistance.fig']); 102 | end 103 | end 104 | % outer distances 105 | if isfield(clusterData(kk).Analysis.clusterStruct, 'clusterDBSCAN') 106 | if ~isempty(clusterData(kk).Analysis.clusterStruct(2).clusterDBSCAN) 107 | h = figure( 'Name', 'Distances of points outside a cluster' ); 108 | histogram(totalOuterDistance, ceil(max(totalOuterDistance(:, 1))), 'Normalization', 'probability'); 109 | hold on 110 | if Clusterparamstruct.compareRandomData == true && isfield(clusterData(kk).Analysis.randomClusterStruct, 'clusterDBSCAN') 111 | histogram(totalOuterDistanceRandom, ceil(max(totalOuterDistanceRandom(:, 1))), 'Normalization', 'probability'); 112 | end 113 | grid on; 114 | title('Distance Analysis of points outside a cluster'); 115 | xlabel('distance [nm]'); 116 | ylabel('normalized frequency'); 117 | if Clusterparamstruct.compareRandomData == true && isfield(clusterData(kk).Analysis.randomClusterStruct, 'clusterDBSCAN') 118 | legend(['mean distance = ' num2str(mean(totalOuterDistance)) ' nm \pm ' num2str(std(totalOuterDistance)) ' nm'],... 119 | ['mean distance = ' num2str(mean(totalOuterDistanceRandom)) ' nm \pm ' num2str(std(totalOuterDistanceRandom)) ' nm']); 120 | else 121 | legend(['mean distance = ' num2str(mean(totalOuterDistance)) ' nm \pm ' num2str(std(totalOuterDistance)) ' nm']); 122 | end 123 | ax = gca; 124 | ax.XLim = [0 Clusterparamstruct.Distance.maxDistance]; 125 | hold off 126 | savefig(h, [Clusterparamstruct.DIR_output filesep 'outerDistance.fig']); 127 | end 128 | end 129 | end -------------------------------------------------------------------------------- /coreAlgorithm/batchProcessing/clusterBatchProcessing.m: -------------------------------------------------------------------------------- 1 | function [] = clusterBatchProcessing(Clusterparamstruct) 2 | %clusterBatchProcessing batch processes multiple localization files for 3 | %cluster analysis 4 | % 5 | % 6 | % Jan Neumann, 23.07.17 7 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 8 | %% init parameters 9 | global files 10 | % file and sampleID handling 11 | [~, FILESmax] = size(files); 12 | if FILESmax < 10 13 | jm = ['0' num2str(FILESmax)]; 14 | else 15 | jm = num2str(FILESmax); 16 | end 17 | pathname = [Clusterparamstruct.DIR_input,filesep]; 18 | %% start batch processing 19 | clusterData = struct([]); 20 | % loop through files 21 | for ii = 1:FILESmax 22 | if ii < 10 23 | js = ['0' num2str(ii)]; 24 | else 25 | js = num2str(ii); 26 | end 27 | Clusterparamstruct.displayStatus(['running Evaluation of File No. ' js ' of ' jm '...']); 28 | filename = char(files(ii)); 29 | sampleID = filename(1:end-4); 30 | if isequal(filename,0)||isequal(pathname,0) 31 | Clusterparamstruct.displayStatus('Error - Evaluation not successful'); 32 | Clusterparamstruct.displayError('No File Selected'); 33 | Clusterparamstruct.enableStartButton(); 34 | error('No File Selected'); 35 | end 36 | % load file for evaluation 37 | localizationFile = load([pathname filename]); 38 | oldField = char(fieldnames(localizationFile)); 39 | if ~(strcmp(oldField, 'Orte')) 40 | newField = 'Orte'; 41 | [localizationFile.(newField)] = localizationFile.(oldField); 42 | localizationFile = rmfield(localizationFile, oldField); 43 | end 44 | failedFiles = []; % for error handling 45 | try 46 | clusterData(ii).sampleID = sampleID; 47 | clusterData(ii).Analysis = ClusterAnalysis(localizationFile.Orte, sampleID,... 48 | Clusterparamstruct.dimension, Clusterparamstruct.densityAlgorithm, ... 49 | Clusterparamstruct.randomAlgorithmValue, Clusterparamstruct.randomAlgorithm); 50 | % process corresponding analysis programs, always run DBSCAN before 51 | % distance calculations 52 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 53 | % DBSCAN 54 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 55 | if Clusterparamstruct.DBSCAN.algorithm == true 56 | clusterData(ii).Analysis.DBSCAN(Clusterparamstruct.DBSCAN.radius, Clusterparamstruct.DBSCAN.minPoint,... 57 | 0, Clusterparamstruct.DBSCAN.maxDiameter, Clusterparamstruct.showPlots); 58 | if Clusterparamstruct.compareRandomData == true 59 | clusterData(ii).Analysis.DBSCAN(Clusterparamstruct.DBSCAN.radius, Clusterparamstruct.DBSCAN.minPoint,... 60 | 1, Clusterparamstruct.DBSCAN.maxDiameter, Clusterparamstruct.showPlots); 61 | end 62 | end 63 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 64 | % Nearest Neighbor Analysis 65 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 66 | if Clusterparamstruct.kNNDistance.algorithm == true 67 | clusterData(ii).Analysis.kNNDistance(Clusterparamstruct.kNNDistance.k, 0,... 68 | Clusterparamstruct.kNNDistance.maxDistance, Clusterparamstruct.showPlots); 69 | if Clusterparamstruct.compareRandomData == true 70 | clusterData(ii).Analysis.kNNDistance(Clusterparamstruct.kNNDistance.k, 1,... 71 | Clusterparamstruct.kNNDistance.maxDistance, Clusterparamstruct.showPlots); 72 | end 73 | end 74 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 75 | % Distance Analysis 76 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 77 | if Clusterparamstruct.Distance.algorithm == true 78 | clusterData(ii).Analysis.distanceAnalysis(Clusterparamstruct.Distance.maxDistance, 0,... 79 | Clusterparamstruct.showPlots); 80 | if Clusterparamstruct.compareRandomData == true 81 | clusterData(ii).Analysis.distanceAnalysis(Clusterparamstruct.Distance.maxDistance, 1,... 82 | Clusterparamstruct.showPlots); 83 | end 84 | end 85 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 86 | % Radial Density Function 87 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 88 | if Clusterparamstruct.RDF.algorithm == true 89 | clusterData(ii).Analysis.radialDensityFunction(Clusterparamstruct.RDF.binSize,... 90 | Clusterparamstruct.RDF.maxDistance, 0, Clusterparamstruct.showPlots); 91 | if Clusterparamstruct.compareRandomData == true 92 | clusterData(ii).Analysis.radialDensityFunction(Clusterparamstruct.RDF.binSize,... 93 | Clusterparamstruct.RDF.maxDistance, 1, Clusterparamstruct.showPlots); 94 | end 95 | end 96 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 97 | % Ripley's Function 98 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 99 | if Clusterparamstruct.ripley.algorithm == true 100 | clusterData(ii).Analysis.ripley(Clusterparamstruct.ripley.radius,... 101 | Clusterparamstruct.ripley.maxDistance, 0, Clusterparamstruct.showPlots); 102 | if Clusterparamstruct.compareRandomData == true 103 | clusterData(ii).Analysis.ripley(Clusterparamstruct.ripley.radius,... 104 | Clusterparamstruct.ripley.maxDistance, 1, Clusterparamstruct.showPlots); 105 | end 106 | end 107 | catch ME 108 | disp(['An error occured during evaluation of file: ' sampleID'.']); 109 | disp(getReport(ME,'extended')); 110 | fprintf('\n'); 111 | disp('Continue execution...'); 112 | failedFiles = [failedFiles sampleID ', ' ]; 113 | Clusterparamstruct.displayError(['Could not evaluate files: ' failedFiles]); 114 | end 115 | end 116 | % remove entries which are empty 117 | keep = []; 118 | for ii = 1:FILESmax 119 | if ~isfield(clusterData(ii),'Analysis') || isempty(clusterData(ii).Analysis) 120 | continue 121 | else 122 | keep = [keep ii]; 123 | end 124 | end 125 | if isempty(keep) 126 | disp('Data is empty. Can not proceed.') 127 | return 128 | end 129 | clusterData = clusterData(keep); 130 | %% create results report and plots 131 | multiWaitbar( 'Finishing computation! Please wait a few mintues.', 'Busy'); 132 | % Nearest Neighbor analysis 133 | visKNN_Distances(Clusterparamstruct, clusterData) 134 | % DBSCAN algorithm 135 | visDBSCAN(Clusterparamstruct, clusterData) 136 | % distance analysis 137 | vis_Distances(Clusterparamstruct, clusterData) 138 | % radial density function 139 | visRDF(Clusterparamstruct, clusterData) 140 | % Ripley's function 141 | visRipley(Clusterparamstruct, clusterData) 142 | %% save data 143 | Clusterparamstruct.ClusterPathname = [Clusterparamstruct.DIR_output filesep]; 144 | Clusterparamstruct.ClusterFilename = [Clusterparamstruct.treatmentName, '.mat']; 145 | treatmentName.(Clusterparamstruct.treatmentName) = clusterData; 146 | save([Clusterparamstruct.ClusterPathname Clusterparamstruct.ClusterFilename], '-struct', 'treatmentName'); 147 | savefig(Clusterparamstruct.handles.figure1, [Clusterparamstruct.ClusterPathname 'settings']) 148 | multiWaitbar('CLOSEALL'); 149 | end -------------------------------------------------------------------------------- /coreAlgorithm/@ClusterAnalysis/kNNDistance.m: -------------------------------------------------------------------------------- 1 | function [] = kNNDistance(obj, k, isRandom, maxDistance, showPlot) 2 | %kNNDistance calculates distances to k-th nearest neighbor 3 | % 4 | % k = 2 calculates distance to next neighbor 5 | % 6 | % Input: 7 | % k: number of next neigbor to calculate distance (default: 2) 8 | % isRandom: true if random positons should be used 9 | % maxDistance: maximum allowed distance for nearest neighbor in nm (default = size of image) 10 | % showPlot: show histogram of NN distribution (default = true) 11 | % Output: 12 | % (1) k-value 13 | % (2) nearest neighbor distances of all points 14 | % 15 | % Note: If clustering with DBSCAN was done before, the function 16 | % automatically calculates the NN-distances of all points, of points 17 | % within clusters and of the points outside of the clusters. 18 | % Additional output: 19 | % (3) k-nearest neighbor distances of points within clusters 20 | % (4) k-nearest neighbor distances of points outside of clusters 21 | % 22 | % Matlab 2014b or newer and Statistics and Machine Learning Toolbox 23 | % 24 | % Jan Neumann, 27.06.2017 25 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 26 | %% init 27 | isDBSCAN = false; % remembers if DBSCAN data already exist 28 | switch nargin 29 | case 1 30 | k = 2; 31 | isRandom = 0; 32 | if isRandom == true 33 | maxDistance = max(obj.randomPhysicalDimension); 34 | else 35 | maxDistance = max(obj.physicalDimension); 36 | end 37 | showPlot = 0; 38 | case 2 39 | isRandom = 0; 40 | if isRandom == true 41 | maxDistance = max(obj.randomPhysicalDimension); 42 | else 43 | maxDistance = max(obj.physicalDimension); 44 | end 45 | showPlot = 0; 46 | case 3 47 | if isRandom == true 48 | maxDistance = max(obj.randomPhysicalDimension); 49 | else 50 | maxDistance = max(obj.physicalDimension); 51 | end 52 | showPlot = 0; 53 | case 4 54 | showPlot = 0; 55 | case 5 56 | 57 | otherwise 58 | error('Wrong number of input arguments!') 59 | end 60 | if maxDistance <= 0 61 | error('maxDistance must be larger than zero!') 62 | end 63 | if isRandom == true 64 | positions = obj.randomTable; 65 | dataMat = obj.randomClusterStruct; 66 | treeData = obj.randomQueryData; 67 | flagSearchTree = obj.flagSearchTreeRandomData; 68 | if isfield(obj.randomClusterStruct, 'clusterDBSCAN') 69 | clusterAssignment = obj.randomClusterStruct(3).clusterDBSCAN; 70 | isDBSCAN = true; 71 | end 72 | else 73 | positions = obj.positionTable; 74 | dataMat = obj.clusterStruct; 75 | treeData = obj.queryData; 76 | flagSearchTree = obj.flagSearchTree; 77 | if isfield(obj.clusterStruct, 'clusterDBSCAN') 78 | clusterAssignment = obj.clusterStruct(3).clusterDBSCAN; 79 | isDBSCAN = true; 80 | end 81 | end 82 | if k == 1 || k > obj.NoOfPoints 83 | error('k must be greater than 1 and less than the maximum number of points within the data set!') 84 | end 85 | % initialize output fields of dataMat 86 | dataMat(1).kNNDistance = []; 87 | dataMat(2).kNNDistance = []; 88 | if isDBSCAN == true 89 | dataMat(3).kNNDistance = []; 90 | dataMat(4).kNNDistance = []; 91 | end 92 | %% k-NN-calculation for all distances 93 | switch flagSearchTree 94 | case 'cTree' % for knn search, use Matlab's internal function 95 | [~, nnDistance] = knnsearch(positions(:, 1:obj.dimension), positions(:, 1:obj.dimension), 'K', k); 96 | case 'matlabTree' 97 | [~, nnDistance] = knnsearch(treeData.X, treeData.X, 'K', k); 98 | end 99 | % mean over NN distance 100 | nnDistances = mean(nnDistance(:, 2:end), 2); 101 | nnDistances = nnDistances(nnDistances(:, 1) <= maxDistance, :); 102 | %% k-NN-calculation for points inside and outside of clusters 103 | if isDBSCAN == true 104 | % for points of clusters the clusterAssignment equals 0 105 | tempCluster = clusterAssignment(:, 1) == 0; % calculate NN distance outside of clusters 106 | outerPoints = positions(tempCluster, 1:obj.dimension); 107 | [~, outerNNDistance] = knnsearch(outerPoints(:, 1:obj.dimension), outerPoints(:, 1:obj.dimension), 'K', k); 108 | outerNNDistance = mean(outerNNDistance(:, 2:end), 2); 109 | outerNNDistance = outerNNDistance(outerNNDistance(:, 1) <= maxDistance, :); 110 | innerNNDistance = []; % calculate NN distance within clusters 111 | if any(clusterAssignment) 112 | for kk = 1:max(clusterAssignment) 113 | tempCluster = clusterAssignment(:, 1) == kk; 114 | innerPoints = positions(tempCluster, 1:obj.dimension); 115 | [~, tempInnerNNDistance] = knnsearch(innerPoints(:, 1:obj.dimension), innerPoints(:, 1:obj.dimension), 'K', k); 116 | currentInnerNNDistance = mean(tempInnerNNDistance(:, 2:end), 2); 117 | currentInnerNNDistance = currentInnerNNDistance(currentInnerNNDistance(:, 1) <= maxDistance, :); 118 | innerNNDistance = cat(1, innerNNDistance, currentInnerNNDistance); 119 | end 120 | end 121 | end 122 | %% visualization 123 | if showPlot == true 124 | figure('Name', [num2str(k), '-Nearest Neighbor Distances: ',num2str(obj.sampleID)] ); 125 | if isDBSCAN == true 126 | plotCounter = 3; % check if outer or inner k-NN distances exist 127 | if isempty(innerNNDistance) 128 | plotCounter = plotCounter - 1; 129 | end 130 | if isempty(outerNNDistance) 131 | plotCounter = plotCounter - 1; 132 | end 133 | subplot(1, plotCounter, 1) 134 | histogram(nnDistances, ceil(max(nnDistances(:, 1))), 'Normalization', 'probability'); 135 | grid on; 136 | title('all points'); 137 | xlabel('distance [nm]'); 138 | ylabel('normalized frequency'); 139 | ax = gca; 140 | ax.XLim = [0 maxDistance]; 141 | if ~isempty(innerNNDistance) 142 | subplot(1, plotCounter, 2) 143 | histogram(innerNNDistance, ceil(max(innerNNDistance(:, 1))), 'Normalization', 'probability'); 144 | grid on; 145 | title('points inside of clusters'); 146 | xlabel('distance [nm]'); 147 | ylabel('normalized frequency'); 148 | ax = gca; 149 | ax.XLim = [0 maxDistance]; 150 | end 151 | if ~isempty(outerNNDistance) 152 | subplot(1, plotCounter, 3) 153 | histogram(outerNNDistance, ceil(max(outerNNDistance(:, 1))), 'Normalization', 'probability'); 154 | grid on; 155 | title('points outside of clusters'); 156 | xlabel('distance [nm]'); 157 | ylabel('normalized frequency'); 158 | ax = gca; 159 | ax.XLim = [0 maxDistance]; 160 | end 161 | else 162 | histogram(nnDistances, ceil(max(nnDistances(:, 1))), 'Normalization', 'probability'); 163 | grid on; 164 | title('all points'); 165 | xlabel('distance [nm]'); 166 | ylabel('normalized frequency'); 167 | ax = gca; 168 | ax.XLim = [0 maxDistance]; 169 | end 170 | end 171 | %% output 172 | dataMat(1).kNNDistance = k; 173 | dataMat(2).kNNDistance = nnDistances; % all points 174 | if isDBSCAN == true 175 | dataMat(3).kNNDistance = innerNNDistance; % points inside of clusters 176 | dataMat(4).kNNDistance = outerNNDistance; % points outside of clusters 177 | end 178 | if isRandom == true 179 | obj.randomClusterStruct = dataMat; 180 | else 181 | obj.clusterStruct = dataMat; 182 | end 183 | end -------------------------------------------------------------------------------- /coreAlgorithm/batchProcessing/visKNN_Distances.m: -------------------------------------------------------------------------------- 1 | function visKNN_Distances(Clusterparamstruct, clusterData) 2 | %visKNN_Distances Summary of this function goes here 3 | % Detailed explanation goes here 4 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 5 | if Clusterparamstruct.kNNDistance.algorithm == true 6 | nSamples = size(clusterData, 2); 7 | totalkNNDistance = cell(1, nSamples); 8 | totalkNNDistanceRandom = cell(1, nSamples); 9 | totalInnerkNNDistance = cell(1, nSamples); 10 | totalOuterkNNDistance = cell(1, nSamples); 11 | totalInnerkNNDistanceRandom = cell(1, nSamples); 12 | totalOuterkNNDistanceRandom = cell(1, nSamples); 13 | for kk=1:nSamples 14 | if isfield(clusterData(kk).Analysis.clusterStruct, 'kNNDistance') 15 | totalkNNDistance{kk} = clusterData(kk).Analysis.clusterStruct(2).kNNDistance; 16 | else 17 | totalkNNDistance{kk} = 0; 18 | end 19 | end 20 | totalkNNDistance = cell2mat(totalkNNDistance.'); 21 | % if DBSCAN was done before 22 | if isfield(clusterData(kk).Analysis.clusterStruct, 'clusterDBSCAN') 23 | for kk=1:nSamples 24 | if isfield(clusterData(kk).Analysis.clusterStruct, 'kNNDistance') 25 | totalInnerkNNDistance{kk} = clusterData(kk).Analysis.clusterStruct(3).kNNDistance; 26 | totalOuterkNNDistance{kk} = clusterData(kk).Analysis.clusterStruct(4).kNNDistance; 27 | else 28 | totalInnerkNNDistance{kk} = 0; 29 | totalOuterkNNDistance{kk} = 0; 30 | end 31 | end 32 | end 33 | totalInnerkNNDistance = cell2mat(totalInnerkNNDistance.'); 34 | totalOuterkNNDistance = cell2mat(totalOuterkNNDistance.'); 35 | %% for random data 36 | if Clusterparamstruct.compareRandomData == true 37 | for kk=1:nSamples 38 | if isfield(clusterData(kk).Analysis.randomClusterStruct, 'kNNDistance') 39 | totalkNNDistanceRandom{kk} = clusterData(kk).Analysis.randomClusterStruct(2).kNNDistance; 40 | end 41 | end 42 | totalkNNDistanceRandom = cell2mat(totalkNNDistanceRandom.'); 43 | end 44 | % if DBSCAN was done before 45 | if isfield(clusterData(kk).Analysis.randomClusterStruct, 'clusterDBSCAN') 46 | if ~isempty(clusterData(kk).Analysis.randomClusterStruct(2).clusterDBSCAN) 47 | for kk=1:nSamples 48 | if isfield(clusterData(kk).Analysis.randomClusterStruct, 'kNNDistance') 49 | totalInnerkNNDistanceRandom{kk} = clusterData(kk).Analysis.randomClusterStruct(3).kNNDistance; 50 | totalOuterkNNDistanceRandom{kk} = clusterData(kk).Analysis.randomClusterStruct(4).kNNDistance; 51 | end 52 | end 53 | totalInnerkNNDistanceRandom = cell2mat(totalInnerkNNDistanceRandom.'); 54 | totalOuterkNNDistanceRandom = cell2mat(totalOuterkNNDistanceRandom.'); 55 | end 56 | end 57 | %% plotting 58 | h = figure( 'Name', 'kNN-Distance' ); 59 | histogram(totalkNNDistance, ceil(max(totalkNNDistance(:, 1))), 'Normalization', 'probability'); 60 | hold on 61 | if Clusterparamstruct.compareRandomData == true && isfield(clusterData(kk).Analysis.randomClusterStruct, 'kNNDistance') 62 | histogram(totalkNNDistanceRandom, ceil(max(totalkNNDistanceRandom(:, 1))), 'Normalization', 'probability'); 63 | end 64 | grid on; 65 | title([num2str(Clusterparamstruct.kNNDistance.k) '-Nearest Neighbor Distance']); 66 | xlabel('distance [nm]'); 67 | ylabel('normalized frequency'); 68 | if Clusterparamstruct.compareRandomData == true 69 | legend(['mean k-NN-Distance = ' num2str(mean(totalkNNDistance)) ' nm \pm ' num2str(std(totalkNNDistance)) ' nm'],... 70 | ['mean k-NN-Distance = ' num2str(mean(totalkNNDistanceRandom)) ' nm \pm ' num2str(std(totalkNNDistanceRandom)) ' nm']); 71 | else 72 | legend(['mean k-NN-Distance = ' num2str(mean(totalkNNDistance)) ' nm \pm ' num2str(std(totalkNNDistance)) ' nm']); 73 | end 74 | ax = gca; 75 | ax.XLim = [0 Clusterparamstruct.kNNDistance.maxDistance]; 76 | hold off 77 | savefig(h, [Clusterparamstruct.DIR_output filesep 'kNNDistance.fig']); 78 | 79 | % inner kNN distances 80 | if isfield(clusterData(kk).Analysis.clusterStruct, 'clusterDBSCAN') 81 | if ~isempty(clusterData(kk).Analysis.clusterStruct(2).clusterDBSCAN) 82 | h = figure( 'Name', 'kNN-Distance of points within a cluster' ); 83 | histogram(totalInnerkNNDistance, ceil(max(totalInnerkNNDistance(:, 1))), 'Normalization', 'probability'); 84 | hold on 85 | if Clusterparamstruct.compareRandomData == true && isfield(clusterData(kk).Analysis.randomClusterStruct, 'kNNDistance') 86 | histogram(totalInnerkNNDistanceRandom, ceil(max(totalInnerkNNDistanceRandom(:, 1))), 'Normalization', 'probability'); 87 | end 88 | grid on; 89 | title([num2str(Clusterparamstruct.kNNDistance.k) '-Nearest Neighbor Distance of points within a cluster']); 90 | xlabel('distance [nm]'); 91 | ylabel('normalized frequency'); 92 | if Clusterparamstruct.compareRandomData == true && isfield(clusterData(kk).Analysis.randomClusterStruct, 'kNNDistance') 93 | legend(['mean k-NN-Distance = ' num2str(mean(totalInnerkNNDistance)) ' nm \pm ' num2str(std(totalInnerkNNDistance)) ' nm'],... 94 | ['mean k-NN-Distance = ' num2str(mean(totalInnerkNNDistanceRandom)) ' nm \pm ' num2str(std(totalInnerkNNDistanceRandom)) ' nm']); 95 | else 96 | legend(['mean k-NN-Distance = ' num2str(mean(totalInnerkNNDistance)) ' nm \pm ' num2str(std(totalInnerkNNDistance)) ' nm']); 97 | end 98 | ax = gca; 99 | ax.XLim = [0 Clusterparamstruct.kNNDistance.maxDistance]; 100 | hold off 101 | savefig(h, [Clusterparamstruct.DIR_output filesep 'innerkNNDistance.fig']); 102 | end 103 | end 104 | % outer kNNdistances 105 | if isfield(clusterData(kk).Analysis.clusterStruct, 'clusterDBSCAN') 106 | if ~isempty(clusterData(kk).Analysis.clusterStruct(2).clusterDBSCAN) 107 | h = figure( 'Name', 'kNN-Distance of points outside a cluster' ); 108 | histogram(totalOuterkNNDistance, ceil(max(totalOuterkNNDistance(:, 1))), 'Normalization', 'probability'); 109 | hold on 110 | if Clusterparamstruct.compareRandomData == true && isfield(clusterData(kk).Analysis.randomClusterStruct, 'kNNDistance') 111 | histogram(totalOuterkNNDistanceRandom, ceil(max(totalOuterkNNDistanceRandom(:, 1))), 'Normalization', 'probability'); 112 | end 113 | grid on; 114 | title([num2str(Clusterparamstruct.kNNDistance.k) '-Nearest Neighbor Distance of points outside a cluster']); 115 | xlabel('distance [nm]'); 116 | ylabel('normalized frequency'); 117 | if Clusterparamstruct.compareRandomData == true && isfield(clusterData(kk).Analysis.randomClusterStruct, 'kNNDistance') 118 | legend(['mean k-NN-Distance = ' num2str(mean(totalOuterkNNDistance)) ' nm \pm ' num2str(std(totalOuterkNNDistance)) ' nm'],... 119 | ['mean k-NN-Distance = ' num2str(mean(totalOuterkNNDistanceRandom)) ' nm \pm ' num2str(std(totalOuterkNNDistanceRandom)) ' nm']); 120 | else 121 | legend(['mean k-NN-Distance = ' num2str(mean(totalOuterkNNDistance)) ' nm \pm ' num2str(std(totalOuterkNNDistance)) ' nm']); 122 | end 123 | ax = gca; 124 | ax.XLim = [0 Clusterparamstruct.kNNDistance.maxDistance]; 125 | hold off 126 | savefig(h, [Clusterparamstruct.DIR_output filesep 'outerkNNDistance.fig']); 127 | end 128 | end 129 | end -------------------------------------------------------------------------------- /coreAlgorithm/@ClusterAnalysis/distanceAnalysis.m: -------------------------------------------------------------------------------- 1 | function [] = distanceAnalysis(obj, maxDistance, isRandom, showPlot) 2 | %distanceAnalyses calculates pairwise distances 3 | % 4 | % Calculates pairwise distances between detected signals. To 5 | % avoid edge effects, distances from points that are located within 6 | % maxDistance from the image border are not caluclated . 7 | % 8 | % Input: 9 | % maxDistance: maximum allowed distance to which distances are calculated in nm (default = 200) 10 | % isRandom: true if random positons should be used (default = false) 11 | % showPlot: show histogram of distance distribution (default = false) 12 | % Output: 13 | % (1) distances of all points 14 | % 15 | % Note: If computations have already been carried out using DBSCAN, the function 16 | % automatically calculates the distances of all the points, of points 17 | % within the clusters and of the points outside of the clusters. 18 | % Additional output: 19 | % (2) pairwise distances of points within clusters 20 | % (3) pairwise distances of points outside of clusters 21 | % 22 | % Matlab 2014b or newer and Statistics and Machine Learning Toolbox 23 | % 24 | % Note: 25 | % Histograms are normalized (according to all distances measured from zero to maxDistance). 26 | % 27 | % Jan Neumann, 13.07.2017 28 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 29 | %% init 30 | isDBSCAN = false; % flag, DBSCAN was carried out before 31 | supressWaitbar = false; % flag for waitbar 32 | switch nargin 33 | case 1 34 | maxDistance = 200; 35 | isRandom = 0; 36 | showPlot = 0; 37 | case 2 38 | isRandom = 0; 39 | showPlot = 0; 40 | case 3 41 | showPlot = 0; 42 | case 4 43 | 44 | otherwise 45 | error('Wrong number of input arguments!') 46 | end 47 | if isRandom == true 48 | positions = obj.randomTable; 49 | dataMat = obj.randomClusterStruct; 50 | dataSize = min(obj.randomPhysicalDimension(1:obj.dimension)); 51 | if isfield(obj.randomClusterStruct, 'clusterDBSCAN') 52 | clusterAssignment = obj.randomClusterStruct(3).clusterDBSCAN; 53 | isDBSCAN = true; 54 | end 55 | else 56 | positions = obj.positionTable; 57 | dataMat = obj.clusterStruct; 58 | dataSize = min(obj.physicalDimension(1:obj.dimension)); 59 | if isfield(obj.clusterStruct, 'clusterDBSCAN') 60 | clusterAssignment = obj.clusterStruct(3).clusterDBSCAN; 61 | isDBSCAN = true; 62 | end 63 | end 64 | if dataSize < 3*maxDistance 65 | disp('Image size is smaller then 3 times the cut-off distance! Try to decrease cut-off distance or increase image region.'); 66 | return 67 | end 68 | %% perform distance calculation 69 | imageSize = ceil(max(positions(:, 1:obj.dimension))); 70 | distances = distanceCalculation(positions, obj.dimension, imageSize, maxDistance, supressWaitbar); 71 | % distance calculation for points inside and outside of clusters 72 | if isDBSCAN == true 73 | % for outside points clusterAssignment is 0 74 | tempCluster = clusterAssignment(:, 1) == 0; 75 | outerPositions = positions(tempCluster, 1:obj.dimension); 76 | outerDistances = distanceCalculation(outerPositions, obj.dimension, imageSize, maxDistance, supressWaitbar); 77 | % for points within clusters 78 | if any(clusterAssignment) 79 | supressWaitbar = true; 80 | innerDistances = cell(1, max(clusterAssignment)); 81 | multiWaitbar('calculating distances...', 0); 82 | % for waitbar 83 | prevPercent = 0; 84 | counter = 1; 85 | for kk = 1:max(clusterAssignment) 86 | tempCluster = clusterAssignment(:, 1) == kk; 87 | innerPositions = positions(tempCluster, 1:obj.dimension); 88 | innerDistances{kk} = distanceCalculation(innerPositions, obj.dimension, imageSize, maxDistance, supressWaitbar); 89 | % waitbar 90 | currentPercent = fix(100*counter/max(clusterAssignment)); 91 | if currentPercent > prevPercent 92 | multiWaitbar( 'calculating distances...', 'Value', counter/double(max(clusterAssignment))); 93 | prevPercent = currentPercent; 94 | end 95 | counter = counter + 1; 96 | end 97 | % remove empty cell arrays -> cluster had been outside the 98 | % boundary 99 | innerDistances = innerDistances(~cellfun('isempty',innerDistances)); 100 | innerDistances = (cell2mat(innerDistances.')); 101 | multiWaitbar('calculating distances...', 'Close'); 102 | else 103 | innerDistances = 0; 104 | end 105 | end 106 | %% visualization 107 | if showPlot == true 108 | figure( 'Name', num2str(obj.sampleID) ); 109 | if isDBSCAN == true 110 | subplot(1, 3, 1) 111 | h = histogram(distances, ceil(max(distances(:, 1))), 'Normalization', 'probability'); 112 | grid on; 113 | title('Distance Analysis - all points'); 114 | xlabel('distance [nm]'); 115 | ylabel('normalized frequency'); 116 | ax = gca; 117 | ax.XLim = [0 maxDistance]; 118 | subplot(1, 3, 2) 119 | h = histogram(innerDistances, ceil(max(innerDistances(:, 1))), 'Normalization', 'probability'); 120 | grid on; 121 | title('Distance Analysis - points inside of clusters'); 122 | xlabel('distance [nm]'); 123 | ylabel('normalized frequency'); 124 | ax = gca; 125 | ax.XLim = [0 maxDistance]; 126 | subplot(1, 3, 3) 127 | h = histogram(outerDistances, ceil(max(outerDistances(:, 1))), 'Normalization', 'probability'); 128 | grid on; 129 | title('Distance Analysis - points outside of clusters'); 130 | xlabel('distance [nm]'); 131 | ylabel('normalized frequency'); 132 | ax = gca; 133 | ax.XLim = [0 maxDistance]; 134 | else 135 | histogram(distances, maxDistance, 'Normalization', 'probability'); % data are normalized to all distances with 0 and maxDistance 136 | grid on; 137 | title('Distance Analysis - all points'); 138 | xlabel('distance [nm]'); 139 | ylabel('normalized frequency'); 140 | ax = gca; 141 | ax.XLim = [0 maxDistance]; 142 | end 143 | end 144 | %% output 145 | dataMat(1).allDistances = distances; 146 | if isDBSCAN == true 147 | dataMat(2).allDistances = innerDistances; % points inside of clusters 148 | dataMat(3).allDistances = outerDistances; % points outside of clusters 149 | end 150 | if isRandom == true 151 | obj.randomClusterStruct = dataMat; 152 | else 153 | obj.clusterStruct = dataMat; 154 | end 155 | end 156 | 157 | 158 | function dist = distanceCalculation(positions, dim, mapSize, maxDistance, supressWaitbar) 159 | % re-sort points in such a way that boundary points are at the end of the 160 | % list 161 | if dim == 3 162 | currentPositions = positions(positions(:, 1) > maxDistance & positions(:, 1) < mapSize(1)-maxDistance... 163 | & positions(:, 2) > maxDistance & positions(:, 2) < mapSize(2)-maxDistance... 164 | & positions(:, 3) > maxDistance & positions(:, 3) < mapSize(3) - maxDistance, :); 165 | outsidePositions = positions( (positions(:, 1) <= maxDistance | positions(:, 1) >= mapSize(1)-maxDistance)... 166 | | (positions(:, 2) <= maxDistance | positions(:, 2) >= mapSize(2)-maxDistance)... 167 | | positions(:, 3) <= maxDistance | positions(:, 3) >= mapSize(3) - maxDistance, :); 168 | positions = cat(1, currentPositions, outsidePositions); 169 | else 170 | currentPositions = positions(positions(:, 1) > maxDistance & positions(:, 1) < mapSize(1)-maxDistance... 171 | & positions(:, 2) > maxDistance & positions(:, 2) < mapSize(2)-maxDistance, :); 172 | outsidePositions = positions( (positions(:, 1) <= maxDistance | positions(:, 1) >= mapSize(1)-maxDistance)... 173 | | (positions(:, 2) <= maxDistance | positions(:, 2) >= mapSize(2)-maxDistance), :); 174 | positions = cat(1, currentPositions, outsidePositions); 175 | end 176 | % cell array for saving distances 177 | distanceCell = cell(1, size(currentPositions, 1)); 178 | nDistanceCell = 1; 179 | if supressWaitbar == false 180 | multiWaitbar('calculating distances...', 0); 181 | % for waitbar 182 | prevPercent = 0; 183 | counter = 1; 184 | end 185 | 186 | for ii = 1 : size(currentPositions, 1) 187 | % calculate distance of current point to all other points that have 188 | % not yet been visited 189 | currentDistance = single(pdist2(positions(ii:end, 1:dim), positions(ii, 1:dim))); 190 | % removes distances larger then maxDistance 191 | currentIdx = (currentDistance <= maxDistance & currentDistance > 0); 192 | currentDistance = currentDistance(currentIdx); 193 | distanceCell{nDistanceCell} = reshape(currentDistance, [], 1); 194 | nDistanceCell = nDistanceCell + 1; 195 | if supressWaitbar == false 196 | % waitbar 197 | currentPercent = fix(100*counter/size(currentPositions, 1)); 198 | if currentPercent > prevPercent 199 | multiWaitbar( 'calculating distances...', 'Value', counter/size(currentPositions, 1)); 200 | prevPercent = currentPercent; 201 | end 202 | counter = counter + 1; 203 | end 204 | end 205 | dist = (cell2mat(distanceCell.')); 206 | if supressWaitbar == false 207 | multiWaitbar('calculating distances...', 'Close'); 208 | end 209 | end -------------------------------------------------------------------------------- /utilities/multiWaitbar/multiWaitbar.m: -------------------------------------------------------------------------------- 1 | function cancel = multiWaitbar( label, varargin ) 2 | %multiWaitbar: add, remove or update an entry on the multi waitbar 3 | % 4 | % multiWaitbar(LABEL,VALUE) adds a waitbar for the specified label, or 5 | % if it already exists updates the value. LABEL must be a string and 6 | % VALUE a number between zero and one or the string 'Close' to remove the 7 | % entry Setting value equal to 0 or 'Reset' will cause the progress bar 8 | % to reset and the time estimate to be re-initialized. 9 | % 10 | % multiWaitbar(LABEL,COMMAND,VALUE,...) or 11 | % multiWaitbar(LABEL,VALUE,COMMAND,VALUE,...) 12 | % passes one or more command/value pairs for changing the named waitbar 13 | % entry. Possible commands include: 14 | % 'Value' Set the value of the named waitbar entry. The 15 | % corresponding value must be a number between 0 and 1. 16 | % 'Increment' Increment the value of the named waitbar entry. The 17 | % corresponding value must be a number between 0 and 1. 18 | % 'Color' Change the color of the named waitbar entry. The 19 | % value must be an RGB triple, e.g. [0.1 0.2 0.3], or a 20 | % single-character color name, e.g. 'r', 'b', 'm'. 21 | % 'Relabel' Change the label of the named waitbar entry. The 22 | % value must be the new name. 23 | % 'Reset' Set the named waitbar entry back to zero and reset its 24 | % timer. No value need be specified. 25 | % 'CanCancel' [on|off] should a "cancel" button be shown for this bar 26 | % (default 'off'). 27 | % 'CancelFcn' Function to call in the event that the user cancels. 28 | % 'ResetCancel' Reset the "cancelled" flag for an entry (ie. if you 29 | % decide not to cancel). 30 | % 'Close' Remove the named waitbar entry. 31 | % 'Busy' Puts this waitbar in "busy mode" where a small bar 32 | % bounces back and forth. Return to normal progress display 33 | % using the 'Reset' command. 34 | % 35 | % cancel = multiWaitbar(LABEL,VALUE) also returns whether the user has 36 | % clicked the "cancel" button for this entry (true or false). Two 37 | % mechanisms are provided for cancelling an entry if the 'CanCancel' 38 | % setting is 'on'. The first is just to check the return argument and if 39 | % it is true abort the task. The second is to set a 'CancelFcn' that is 40 | % called when the user clicks the cancel button, much as is done for 41 | % MATLAB's built-in WAITBAR. In either case, you can use the 42 | % 'ResetCancel' command if you don't want to cancel after all. 43 | % 44 | % multiWaitbar('CLOSEALL') closes the waitbar window. 45 | % 46 | % Example: 47 | % multiWaitbar( 'CloseAll' ); 48 | % multiWaitbar( 'Task 1', 0 ); 49 | % multiWaitbar( 'Task 2', 0.5, 'Color', 'b' ); 50 | % multiWaitbar( 'Task 3', 'Busy'); 51 | % multiWaitbar( 'Task 1', 'Value', 0.1 ); 52 | % multiWaitbar( 'Task 2', 'Increment', 0.2 ); 53 | % multiWaitbar( 'Task 3', 'Reset' ); % Disables "busy" mode 54 | % multiWaitbar( 'Task 3', 'Value', 0.3 ); 55 | % multiWaitbar( 'Task 2', 'Close' ); 56 | % multiWaitbar( 'Task 3', 'Close' ); 57 | % multiWaitbar( 'Task 1', 'Close' ); 58 | % 59 | % Example: 60 | % multiWaitbar( 'Task 1', 0, 'CancelFcn', @(a,b) disp( ['Cancel ',a] ) ); 61 | % for ii=1:100 62 | % abort = multiWaitbar( 'Task 1', ii/100 ); 63 | % if abort 64 | % % Here we would normally ask the user if they're sure 65 | % break 66 | % else 67 | % pause( 1 ) 68 | % end 69 | % end 70 | % multiWaitbar( 'Task 1', 'Close' ) 71 | % 72 | % Example: 73 | % multiWaitbar( 'CloseAll' ); 74 | % multiWaitbar( 'Red...', 7/7, 'Color', [0.8 0.0 0.1] ); 75 | % multiWaitbar( 'Orange...', 6/7, 'Color', [1.0 0.4 0.0] ); 76 | % multiWaitbar( 'Yellow...', 5/7, 'Color', [0.9 0.8 0.2] ); 77 | % multiWaitbar( 'Green...', 4/7, 'Color', [0.2 0.9 0.3] ); 78 | % multiWaitbar( 'Blue...', 3/7, 'Color', [0.1 0.5 0.8] ); 79 | % multiWaitbar( 'Indigo...', 2/7, 'Color', [0.4 0.1 0.5] ); 80 | % multiWaitbar( 'Violet...', 1/7, 'Color', [0.8 0.4 0.9] ); 81 | % 82 | % Thanks to Jesse Hopkins for suggesting the "busy" mode. 83 | 84 | % Author: Ben Tordoff 85 | % Copyright 2007-2014 The MathWorks, Inc. 86 | 87 | persistent FIGH; 88 | cancel = false; 89 | 90 | % Check basic inputs 91 | error( nargchk( 1, inf, nargin ) ); %#ok - kept for backwards compatibility 92 | if ~ischar( label ) 93 | error( 'multiWaitbar:BadArg', 'LABEL must be the name of the progress entry (i.e. a string)' ); 94 | end 95 | 96 | % Try to get hold of the figure 97 | if isempty( FIGH ) || ~ishandle( FIGH ) 98 | FIGH = findall( 0, 'Type', 'figure', 'Tag', 'multiWaitbar:Figure' ); 99 | if isempty(FIGH) 100 | FIGH = iCreateFig(); 101 | else 102 | FIGH = handle( FIGH(1) ); 103 | end 104 | end 105 | 106 | % Check for close all and stop early 107 | if any( strcmpi( label, {'CLOSEALL','CLOSE ALL'} ) ) 108 | iDeleteFigure(FIGH); 109 | return; 110 | end 111 | 112 | % Make sure we're on-screen 113 | if ~strcmpi( FIGH.Visible, 'on' ) 114 | FIGH.Visible = 'on'; 115 | end 116 | 117 | % Get the list of entries and see if this one already exists 118 | entries = getappdata( FIGH, 'ProgressEntries' ); 119 | if isempty(entries) 120 | idx = []; 121 | else 122 | idx = find( strcmp( label, {entries.Label} ), 1, 'first' ); 123 | end 124 | bgcol = getappdata( FIGH, 'DefaultProgressBarBackgroundColor' ); 125 | 126 | % If it doesn't exist, create it 127 | needs_redraw = false; 128 | entry_added = isempty(idx); 129 | if entry_added 130 | % Create a new entry 131 | defbarcolor = getappdata( FIGH, 'DefaultProgressBarColor' ); 132 | entries = iAddEntry( FIGH, entries, label, 0, defbarcolor, bgcol ); 133 | idx = numel( entries ); 134 | end 135 | 136 | % Check if the user requested a cancel 137 | if nargout 138 | cancel = entries(idx).Cancel; 139 | end 140 | 141 | % Parse the inputs. We shortcut the most common case as an efficiency 142 | force_update = false; 143 | if nargin==2 && isnumeric( varargin{1} ) 144 | entries(idx).LastValue = entries(idx).Value; 145 | entries(idx).Value = max( 0, min( 1, varargin{1} ) ); 146 | entries(idx).Busy = false; 147 | needs_update = true; 148 | else 149 | [params,values] = iParseInputs( varargin{:} ); 150 | 151 | needs_update = false; 152 | for ii=1:numel( params ) 153 | switch upper( params{ii} ) 154 | case 'BUSY' 155 | entries(idx).Busy = true; 156 | needs_update = true; 157 | 158 | case 'VALUE' 159 | entries(idx).LastValue = entries(idx).Value; 160 | entries(idx).Value = max( 0, min( 1, values{ii} ) ); 161 | entries(idx).Busy = false; 162 | needs_update = true; 163 | 164 | case {'INC','INCREMENT'} 165 | entries(idx).LastValue = entries(idx).Value; 166 | entries(idx).Value = max( 0, min( 1, entries(idx).Value + values{ii} ) ); 167 | entries(idx).Busy = false; 168 | needs_update = true; 169 | 170 | case {'COLOR','COLOUR'} 171 | entries(idx).CData = iMakeColors( values{ii}, 16 ); 172 | needs_update = true; 173 | force_update = true; 174 | 175 | case {'RELABEL', 'UPDATELABEL'} 176 | % Make sure we have a string as the value and that it 177 | % doesn't already appear 178 | if ~ischar( values{ii} ) 179 | error( 'multiWaitbar:BadString', 'Value for ''Relabel'' must be a string.' ); 180 | end 181 | if ismember( values{ii}, {entries.Label} ) 182 | error( 'multiWaitbar:NameAlreadyExists', 'Cannot relabel an entry to a label that already exists.' ); 183 | end 184 | entries(idx).Label = values{ii}; 185 | needs_update = true; 186 | force_update = true; 187 | 188 | case {'CANCANCEL'} 189 | if ~ischar( values{ii} ) || ~any( strcmpi( values{ii}, {'on','off'} ) ) 190 | error( 'multiWaitbar:BadString', 'Parameter ''CanCancel'' must be a ''on'' or ''off''.' ); 191 | end 192 | entries(idx).CanCancel = strcmpi( values{ii}, 'on' ); 193 | entries(idx).Cancel = false; 194 | needs_redraw = true; 195 | 196 | case {'RESETCANCEL'} 197 | entries(idx).Cancel = false; 198 | needs_redraw = true; 199 | 200 | case {'CANCELFCN'} 201 | if ~isa( values{ii}, 'function_handle' ) 202 | error( 'multiWaitbar:BadFunction', 'Parameter ''CancelFcn'' must be a valid function handle.' ); 203 | end 204 | entries(idx).CancelFcn = values{ii}; 205 | if ~entries(idx).CanCancel 206 | entries(idx).CanCancel = true; 207 | end 208 | needs_redraw = true; 209 | 210 | case {'CLOSE','DONE'} 211 | if ~isempty(idx) 212 | % Remove the selected entry 213 | entries = iDeleteEntry( entries, idx ); 214 | end 215 | if isempty( entries ) 216 | iDeleteFigure( FIGH ); 217 | % With the window closed, there's nothing else to do 218 | return; 219 | else 220 | needs_redraw = true; 221 | end 222 | % We can't continue after clearing the entry, so jump out 223 | break; 224 | 225 | otherwise 226 | error( 'multiWaitbar:BadArg', 'Unrecognized command: ''%s''', params{ii} ); 227 | 228 | end 229 | end 230 | end 231 | 232 | % Now work out what to update/redraw 233 | if needs_redraw 234 | setappdata( FIGH, 'ProgressEntries', entries ); 235 | iRedraw( FIGH ); 236 | % NB: Redraw includes updating all bars, so never need to do both 237 | elseif needs_update 238 | [entries(idx),needs_redraw] = iUpdateEntry( entries(idx), force_update ); 239 | setappdata( FIGH, 'ProgressEntries', entries ); 240 | % NB: if anything was updated onscreen, "needs_redraw" is now true. 241 | end 242 | if entry_added || needs_redraw 243 | % If the shape or size has changed, do a full redraw, including events 244 | drawnow(); 245 | end 246 | 247 | % If we have any "busy" entries, start the timer, otherwise stop it. 248 | myTimer = getappdata( FIGH, 'BusyTimer' ); 249 | if any([entries.Busy]) 250 | if strcmpi(myTimer.Running,'off') 251 | start(myTimer); 252 | end 253 | else 254 | if strcmpi(myTimer.Running,'on') 255 | stop(myTimer); 256 | end 257 | end 258 | 259 | end % multiWaitbar 260 | 261 | 262 | %-------------------------------------------------------------------------% 263 | function [params, values] = iParseInputs( varargin ) 264 | % Parse the input arguments, extracting a list of commands and values 265 | idx = 1; 266 | params = {}; 267 | values = {}; 268 | if nargin==0 269 | return; 270 | end 271 | if isnumeric( varargin{1} ) 272 | params{idx} = 'Value'; 273 | values{idx} = varargin{1}; 274 | idx = idx + 1; 275 | end 276 | 277 | while idx <= nargin 278 | param = varargin{idx}; 279 | if ~ischar( param ) 280 | error( 'multiWaitbar:BadSyntax', 'Additional properties must be supplied as property-value pairs' ); 281 | end 282 | params{end+1,1} = param; %#ok 283 | values{end+1,1} = []; %#ok 284 | switch upper( param ) 285 | case {'DONE','CLOSE','RESETCANCEL'} 286 | % No value needed, and stop 287 | break; 288 | case {'BUSY'} 289 | % No value needed but parsing should continue 290 | idx = idx + 1; 291 | case {'RESET','ZERO','SHOW'} 292 | % All equivalent to saying ('Value', 0) 293 | params{end} = 'Value'; 294 | values{end} = 0; 295 | idx = idx + 1; 296 | otherwise 297 | if idx==nargin 298 | error( 'multiWaitbar:BadSyntax', 'Additional properties must be supplied as property-value pairs' ); 299 | end 300 | values{end,1} = varargin{idx+1}; 301 | idx = idx + 2; 302 | end 303 | end 304 | if isempty( params ) 305 | error( 'multiWaitbar:BadSyntax', 'Must specify a value or a command' ); 306 | end 307 | end % iParseInputs 308 | 309 | %-------------------------------------------------------------------------% 310 | function fobj = iCreateFig() 311 | % Create the progress bar group window 312 | bgcol = get(0,'DefaultUIControlBackgroundColor'); 313 | f = figure( ... 314 | 'Name', 'Progress', ... 315 | 'Tag', 'multiWaitbar:Figure', ... 316 | 'Color', bgcol, ... 317 | 'MenuBar', 'none', ... 318 | 'ToolBar', 'none', ... 319 | 'WindowStyle', 'normal', ... % We don't want to be docked! 320 | 'HandleVisibility', 'off', ... 321 | 'IntegerHandle', 'off', ... 322 | 'Visible', 'off', ... 323 | 'NumberTitle', 'off' ); 324 | % Resize and centre on the first screen 325 | screenSize = get(0,'ScreenSize'); 326 | figSz = [360 42]; 327 | figPos = ceil((screenSize(1,3:4)-figSz)/2); 328 | fobj = handle( f ); 329 | fobj.Position = [figPos, figSz]; 330 | setappdata( fobj, 'ProgressEntries', [] ); 331 | % Make sure we have the image 332 | defbarcolor = [0.8 0.0 0.1]; 333 | barbgcol = uint8( 255*0.75*bgcol ); 334 | setappdata( fobj, 'DefaultProgressBarBackgroundColor', barbgcol ); 335 | setappdata( fobj, 'DefaultProgressBarColor', defbarcolor ); 336 | setappdata( fobj, 'DefaultProgressBarSize', [350 16] ); 337 | % Create the timer to use for "Busy" mode, being sure to delete any 338 | % existing ones 339 | delete( timerfind('Tag', 'MultiWaitbarTimer') ); 340 | myTimer = timer( ... 341 | 'TimerFcn', @(src,evt) iTimerFcn(f), ... 342 | 'Period', 0.02, ... 343 | 'ExecutionMode', 'FixedRate', ... 344 | 'Tag', 'MultiWaitbarTimer' ); 345 | setappdata( fobj, 'BusyTimer', myTimer ); 346 | 347 | % Setup the resize function after we've finished setting up the figure to 348 | % avoid excessive redraws 349 | fobj.ResizeFcn = @iRedraw; 350 | fobj.CloseRequestFcn = @iCloseFigure; 351 | end % iCreateFig 352 | 353 | %-------------------------------------------------------------------------% 354 | function cdata = iMakeColors( baseColor, height ) 355 | % Creates a shiny bar from a single base color 356 | lightColor = [1 1 1]; 357 | badColorErrorID = 'multiWaitbar:BadColor'; 358 | badColorErrorMsg = 'Colors must be a three element vector [R G B] or a single character (''r'', ''g'' etc.)'; 359 | 360 | if ischar(baseColor) 361 | switch upper(baseColor) 362 | case 'K' 363 | baseColor = [0.1 0.1 0.1]; 364 | case 'R' 365 | baseColor = [0.8 0 0]; 366 | case 'G' 367 | baseColor = [0 0.6 0]; 368 | case 'B' 369 | baseColor = [0 0 0.8]; 370 | case 'C' 371 | baseColor = [0.2 0.8 0.9]; 372 | case 'M' 373 | baseColor = [0.6 0 0.6]; 374 | case 'Y' 375 | baseColor = [0.9 0.8 0.2]; 376 | case 'W' 377 | baseColor = [0.9 0.9 0.9]; 378 | otherwise 379 | error( badColorErrorID, badColorErrorMsg ); 380 | end 381 | else 382 | if numel(baseColor) ~= 3 383 | error( badColorErrorID, badColorErrorMsg ); 384 | end 385 | if isa( baseColor, 'uint8' ) 386 | baseColor = double( baseColor ) / 255; 387 | elseif isa( baseColor, 'double' ) 388 | if any(baseColor>1) || any(baseColor<0) 389 | error( 'multiWaitbar:BadColorValue', 'Color values must be in the range 0 to 1 inclusive.' ); 390 | end 391 | else 392 | error( badColorErrorID, badColorErrorMsg ); 393 | end 394 | end 395 | 396 | % By this point we should have a double precision 3-element vector. 397 | cols = repmat( baseColor, [height, 1] ); 398 | 399 | breaks = max( 1, round( height * [1 25 50 75 88 100] / 100 ) ); 400 | cols(breaks(1),:) = 0.6*baseColor; 401 | cols(breaks(2),:) = lightColor - 0.4*(lightColor-baseColor); 402 | cols(breaks(3),:) = baseColor; 403 | cols(breaks(4),:) = min( baseColor*1.2, 1.0 ); 404 | cols(breaks(5),:) = min( baseColor*1.4, 0.95 ) + 0.05; 405 | cols(breaks(6),:) = min( baseColor*1.6, 0.9 ) + 0.1; 406 | 407 | y = 1:height; 408 | cols(:,1) = max( 0, min( 1, interp1( breaks, cols(breaks,1), y, 'pchip' ) ) ); 409 | cols(:,2) = max( 0, min( 1, interp1( breaks, cols(breaks,2), y, 'pchip' ) ) ); 410 | cols(:,3) = max( 0, min( 1, interp1( breaks, cols(breaks,3), y, 'pchip' ) ) ); 411 | cdata = uint8( 255 * cat( 3, cols(:,1), cols(:,2), cols(:,3) ) ); 412 | end % iMakeColors 413 | 414 | 415 | %-------------------------------------------------------------------------% 416 | function cdata = iMakeBackground( baseColor, height ) 417 | % Creates a shaded background 418 | if isa( baseColor, 'uint8' ) 419 | baseColor = double( baseColor ) / 255; 420 | end 421 | 422 | ratio = 1 - exp( -0.5-2*(1:height)/height )'; 423 | cdata = uint8( 255 * cat( 3, baseColor(1)*ratio, baseColor(2)*ratio, baseColor(3)*ratio ) ); 424 | end % iMakeBackground 425 | 426 | %-------------------------------------------------------------------------% 427 | function entries = iAddEntry( parent, entries, label, value, color, bgcolor ) 428 | % Add a new entry to the progress bar 429 | 430 | % Create bar coloring 431 | psize = getappdata( parent, 'DefaultProgressBarSize' ); 432 | cdata = iMakeColors( color, 16 ); 433 | % Create background image 434 | barcdata = iMakeBackground( bgcolor, psize(2) ); 435 | 436 | % Work out the size in advance 437 | labeltext = uicontrol( 'Style', 'Text', ... 438 | 'String', label, ... 439 | 'Parent', parent, ... 440 | 'HorizontalAlignment', 'Left' ); 441 | etatext = uicontrol( 'Style', 'Text', ... 442 | 'String', '', ... 443 | 'Parent', parent, ... 444 | 'HorizontalAlignment', 'Right' ); 445 | progresswidget = uicontrol( 'Style', 'Checkbox', ... 446 | 'String', '', ... 447 | 'Parent', parent, ... 448 | 'Position', [5 5 psize], ... 449 | 'CData', barcdata ); 450 | cancelwidget = uicontrol( 'Style', 'PushButton', ... 451 | 'String', '', ... 452 | 'FontWeight', 'Bold', ... 453 | 'Parent', parent, ... 454 | 'Position', [5 5 16 16], ... 455 | 'CData', iMakeCross( 8 ), ... 456 | 'Callback', @(src,evt) iCancelEntry( src, label ), ... 457 | 'Visible', 'off' ); 458 | mypanel = uipanel( 'Parent', parent, 'Units', 'Pixels' ); 459 | 460 | newentry = struct( ... 461 | 'Label', label, ... 462 | 'Value', value, ... 463 | 'LastValue', inf, ... 464 | 'Created', tic(), ... 465 | 'LabelText', labeltext, ... 466 | 'ETAText', etatext, ... 467 | 'ETAString', '', ... 468 | 'Progress', progresswidget, ... 469 | 'ProgressSize', psize, ... 470 | 'Panel', mypanel, ... 471 | 'BarCData', barcdata, ... 472 | 'CData', cdata, ... 473 | 'BackgroundCData', barcdata, ... 474 | 'CanCancel', false, ... 475 | 'CancelFcn', [], ... 476 | 'CancelButton', cancelwidget, ... 477 | 'Cancel', false, ... 478 | 'Busy', false ); 479 | if isempty( entries ) 480 | entries = newentry; 481 | else 482 | entries = [entries;newentry]; 483 | end 484 | % Store in figure before the redraw 485 | setappdata( parent, 'ProgressEntries', entries ); 486 | if strcmpi( get( parent, 'Visible' ), 'on' ) 487 | iRedraw( parent, [] ); 488 | else 489 | set( parent, 'Visible', 'on' ); 490 | end 491 | end % iAddEntry 492 | 493 | %-------------------------------------------------------------------------% 494 | function entries = iDeleteEntry( entries, idx ) 495 | delete( entries(idx).LabelText ); 496 | delete( entries(idx).ETAText ); 497 | delete( entries(idx).CancelButton ); 498 | delete( entries(idx).Progress ); 499 | delete( entries(idx).Panel ); 500 | entries(idx,:) = []; 501 | end % iDeleteEntry 502 | 503 | %-------------------------------------------------------------------------% 504 | function entries = iCancelEntry( src, name ) 505 | figh = ancestor( src, 'figure' ); 506 | entries = getappdata( figh, 'ProgressEntries' ); 507 | if isempty(entries) 508 | % The entries have been lost - nothing can be done. 509 | return 510 | end 511 | idx = find( strcmp( name, {entries.Label} ), 1, 'first' ); 512 | 513 | % Set the cancel flag so that the user is told on next update 514 | entries(idx).Cancel = true; 515 | setappdata( figh, 'ProgressEntries', entries ); 516 | 517 | % If a user function is supplied, call it 518 | if ~isempty( entries(idx).CancelFcn ) 519 | feval( entries(idx).CancelFcn, name, 'Cancelled' ); 520 | end 521 | 522 | end % iCancelEntry 523 | 524 | 525 | %-------------------------------------------------------------------------% 526 | function [entry,updated] = iUpdateEntry( entry, force ) 527 | % Update one progress bar 528 | 529 | % Deal with busy entries separately 530 | if entry.Busy 531 | entry = iUpdateBusyEntry(entry); 532 | updated = true; 533 | return; 534 | end 535 | 536 | % Some constants 537 | marker_weight = 0.8; 538 | 539 | % Check if the label needs updating 540 | updated = force; 541 | val = entry.Value; 542 | lastval = entry.LastValue; 543 | 544 | % Now update the bar 545 | psize = entry.ProgressSize; 546 | filled = max( 1, round( val*psize(1) ) ); 547 | lastfilled = max( 1, round( lastval*psize(1) ) ); 548 | 549 | % We do some careful checking so that we only redraw what we have to. This 550 | % makes a small speed difference, but every little helps! 551 | if force || (filled(filled-2)) = []; 561 | highlight = [marker_weight*entry.CData, 255 - marker_weight*(255-entry.CData)]; 562 | for ii=1:numel( markers ) 563 | progresscdata(:,markers(ii)+[-1,0],:) = highlight; 564 | end 565 | 566 | % Set the image into the checkbox 567 | entry.BarCData = progresscdata; 568 | set( entry.Progress, 'cdata', progresscdata ); 569 | updated = true; 570 | 571 | elseif filled > lastfilled 572 | % Just need to update the existing data 573 | progresscdata = entry.BarCData; 574 | startIdx = max(1,lastfilled-1); 575 | % Repmat is the obvious way to fill the bar, but BSXFUN is often 576 | % faster. Indexing is obscure but faster still. 577 | progresscdata(:,startIdx:filled,:) = iMakeBarImage(entry.CData, startIdx, filled); 578 | 579 | % Add light/shadow around the markers 580 | markers = round( (0.1:0.1:val)*psize(1) ); 581 | markers(markers(filled-2)) = []; 582 | highlight = [marker_weight*entry.CData, 255 - marker_weight*(255-entry.CData)]; 583 | for ii=1:numel( markers ) 584 | progresscdata(:,markers(ii)+[-1,0],:) = highlight; 585 | end 586 | 587 | entry.BarCData = progresscdata; 588 | set( entry.Progress, 'CData', progresscdata ); 589 | updated = true; 590 | end 591 | 592 | % As an optimization, don't update any text if the bar didn't move and the 593 | % percentage hasn't changed 594 | decval = round( val*100 ); 595 | lastdecval = round( lastval*100 ); 596 | 597 | if ~updated && (decval == lastdecval) 598 | return 599 | end 600 | 601 | % Now work out the remaining time 602 | minTime = 3; % secs 603 | if val <= 0 604 | % Zero value, so clear the eta 605 | entry.Created = tic(); 606 | elapsedtime = 0; 607 | etaString = ''; 608 | else 609 | elapsedtime = round(toc( entry.Created )); % in seconds 610 | 611 | % Only show the remaining time if we've had time to estimate 612 | if elapsedtime < minTime 613 | % Not enough time has passed since starting, so leave blank 614 | etaString = ''; 615 | else 616 | % Calculate a rough ETA 617 | eta = elapsedtime * (1-val) / val; 618 | etaString = iGetTimeString( eta ); 619 | end 620 | end 621 | 622 | if ~isequal( etaString, entry.ETAString ) 623 | set( entry.ETAText, 'String', etaString ); 624 | entry.ETAString = etaString; 625 | updated = true; 626 | end 627 | 628 | % Update the label too 629 | if force || elapsedtime > minTime 630 | if force || (decval ~= lastdecval) 631 | labelstr = [entry.Label, sprintf( ' (%d%%)', decval )]; 632 | set( entry.LabelText, 'String', labelstr ); 633 | updated = true; 634 | end 635 | end 636 | 637 | end % iUpdateEntry 638 | 639 | function eta = iGetTimeString( remainingtime ) 640 | if remainingtime > 172800 % 2 days 641 | eta = sprintf( '%d days', round(remainingtime/86400) ); 642 | else 643 | if remainingtime > 7200 % 2 hours 644 | eta = sprintf( '%d hours', round(remainingtime/3600) ); 645 | else 646 | if remainingtime > 120 % 2 mins 647 | eta = sprintf( '%d mins', round(remainingtime/60) ); 648 | else 649 | % Seconds 650 | remainingtime = round( remainingtime ); 651 | if remainingtime > 1 652 | eta = sprintf( '%d secs', remainingtime ); 653 | elseif remainingtime == 1 654 | eta = '1 sec'; 655 | else 656 | eta = ''; % Nearly done (<1sec) 657 | end 658 | end 659 | end 660 | end 661 | end % iGetTimeString 662 | 663 | 664 | %-------------------------------------------------------------------------% 665 | function entry = iUpdateBusyEntry( entry ) 666 | % Update a "busy" progress bar 667 | % Make sure the widget is still OK 668 | if ~ishandle(entry.Progress) 669 | return 670 | end 671 | % Work out the new position. Since the bar is 0.1 long and needs to bounce, 672 | % the position varies from 0 up to 0.9 then back down again. We achieve 673 | % this with judicious use of "mod" with 1.8. 674 | entry.Value = mod(entry.Value+0.01,1.8); 675 | val = entry.Value; 676 | if val>0.9 677 | % Moving backwards 678 | val = 1.8-val; 679 | end 680 | psize = entry.ProgressSize; 681 | startIdx = max( 1, round( val*psize(1) ) ); 682 | endIdx = max( 1, round( (val+0.1)*psize(1) ) ); 683 | barLength = endIdx - startIdx + 1; 684 | 685 | % Create the image 686 | bgim = entry.BackgroundCData(:,ones( 1, psize(1) ),:); 687 | barim = iMakeBarImage(entry.CData, 1, barLength); 688 | bgim(:,startIdx:endIdx,:) = barim; 689 | 690 | % Put it into the widget 691 | entry.BarCData = bgim; 692 | set( entry.Progress, 'CData', bgim ); 693 | end % iUpdateBusyEntry 694 | 695 | 696 | %-------------------------------------------------------------------------% 697 | function barim = iMakeBarImage(strip, startIdx, endIdx) 698 | shadow1_weight = 0.4; 699 | shadow2_weight = 0.7; 700 | barLength = endIdx - startIdx + 1; 701 | % Repmat is the obvious way to fill the bar, but BSXFUN is often 702 | % faster. Indexing is obscure but faster still. 703 | barim = strip(:,ones(1, barLength),:); 704 | % Add highlight to the start of the bar 705 | if startIdx <= 2 && barLength>=2 706 | barim(:,1,:) = 255 - shadow1_weight*(255-strip); 707 | barim(:,2,:) = 255 - shadow2_weight*(255-strip); 708 | end 709 | % Add shadow to the end of the bar 710 | if endIdx>=4 && barLength>=2 711 | barim(:,end,:) = shadow1_weight*strip; 712 | barim(:,end-1,:) = shadow2_weight*strip; 713 | end 714 | end % iMakeBarImage 715 | 716 | %-------------------------------------------------------------------------% 717 | function iCloseFigure( fig, evt ) %#ok 718 | % Closing the figure just makes it invisible 719 | set( fig, 'Visible', 'off' ); 720 | end % iCloseFigure 721 | 722 | %-------------------------------------------------------------------------% 723 | function iDeleteFigure( fig ) 724 | % Actually destroy the figure 725 | busyTimer = getappdata( fig, 'BusyTimer' ); 726 | stop( busyTimer ); 727 | delete( busyTimer ); 728 | delete( fig ); 729 | end % iDeleteFigure 730 | 731 | %-------------------------------------------------------------------------% 732 | function iRedraw( fig, evt ) %#ok 733 | entries = getappdata( fig, 'ProgressEntries' ); 734 | fobj = handle( fig ); 735 | p = fobj.Position; 736 | % p = get( fig, 'Position' ); 737 | border = 5; 738 | textheight = 16; 739 | barheight = 16; 740 | panelheight = 10; 741 | N = max( 1, numel( entries ) ); 742 | 743 | % Check the height is correct 744 | heightperentry = textheight+barheight+panelheight; 745 | requiredheight = 2*border + N*heightperentry - panelheight; 746 | if ~isequal( p(4), requiredheight ) 747 | p(2) = p(2) + p(4) - requiredheight; 748 | p(4) = requiredheight; 749 | % In theory setting the position should re-trigger this callback, but 750 | % in practice it doesn't, probably because we aren't calling "drawnow". 751 | set( fig, 'Position', p ) 752 | end 753 | ypos = p(4) - border; 754 | width = p(3) - 2*border; 755 | setappdata( fig, 'DefaultProgressBarSize', [width barheight] ); 756 | 757 | for ii=1:numel( entries ) 758 | set( entries(ii).LabelText, 'Position', [border ypos-textheight width*0.75 textheight] ); 759 | set( entries(ii).ETAText, 'Position', [border+width*0.75 ypos-textheight width*0.25 textheight] ); 760 | ypos = ypos - textheight; 761 | if entries(ii).CanCancel 762 | set( entries(ii).Progress, 'Position', [border ypos-barheight width-barheight+1 barheight] ); 763 | entries(ii).ProgressSize = [width-barheight barheight]; 764 | set( entries(ii).CancelButton, 'Visible', 'on', 'Position', [p(3)-border-barheight ypos-barheight barheight barheight] ); 765 | else 766 | set( entries(ii).Progress, 'Position', [border ypos-barheight width+1 barheight] ); 767 | entries(ii).ProgressSize = [width barheight]; 768 | set( entries(ii).CancelButton, 'Visible', 'off' ); 769 | end 770 | ypos = ypos - barheight; 771 | set( entries(ii).Panel, 'Position', [-500 ypos-500-panelheight/2 p(3)+1000 500] ); 772 | ypos = ypos - panelheight; 773 | entries(ii) = iUpdateEntry( entries(ii), true ); 774 | end 775 | setappdata( fig, 'ProgressEntries', entries ); 776 | end % iRedraw 777 | 778 | function cdata = iMakeCross( sz ) 779 | % Create a cross-shape icon of size sz*sz*3 780 | 781 | cdata = diag(ones(sz,1),0) + diag(ones(sz-1,1),1) + diag(ones(sz-1,1),-1); 782 | cdata = cdata + flip(cdata,2); 783 | 784 | % Convert zeros to nans (transparent) and non-zeros to zero (black) 785 | cdata(cdata == 0) = nan; 786 | cdata(~isnan(cdata)) = 0; 787 | 788 | % Convert to RGB 789 | cdata = cat( 3, cdata, cdata, cdata ); 790 | end % iMakeCross 791 | 792 | 793 | function iTimerFcn(fig) 794 | % Timer callback for updating stuff every so often 795 | entries = getappdata( fig, 'ProgressEntries' ); 796 | for ii=1:numel(entries) 797 | if entries(ii).Busy 798 | entries(ii) = iUpdateBusyEntry(entries(ii)); 799 | end 800 | end 801 | setappdata( fig, 'ProgressEntries', entries ); 802 | end % iTimerFcn 803 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /coreAlgorithm/gui/startClusterAnalysis.m: -------------------------------------------------------------------------------- 1 | function varargout = startClusterAnalysis(varargin) 2 | % STARTCLUSTERANALYSIS GUI script for ClusterAnalysis evaluation. 3 | % 4 | % 5 | % Cremer Group, Institute of Molecular Biology (IMB), Mainz 6 | 7 | % Last Modified by GUIDE v2.5 30-Apr-2019 11:27:15 8 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 9 | %% Begin initialization code - DO NOT EDIT 10 | gui_Singleton = 1; 11 | gui_State = struct('gui_Name', mfilename, ... 12 | 'gui_Singleton', gui_Singleton, ... 13 | 'gui_OpeningFcn', @startClusterAnalysis_OpeningFcn, ... 14 | 'gui_OutputFcn', @startClusterAnalysis_OutputFcn, ... 15 | 'gui_LayoutFcn', [] , ... 16 | 'gui_Callback', []); 17 | if nargin && ischar(varargin{1}) 18 | gui_State.gui_Callback = str2func(varargin{1}); 19 | end 20 | 21 | if nargout 22 | [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); 23 | else 24 | gui_mainfcn(gui_State, varargin{:}); 25 | end 26 | % End initialization code - DO NOT EDIT 27 | 28 | 29 | %% Function to load content into the listbox 'filebox' 30 | function load_filebox(dir_path, handles) 31 | 32 | filter_str = get(handles.fn,'String'); 33 | dir_struct= dir([dir_path '/' filter_str]); 34 | [sorted_names,sorted_index] = sortrows({dir_struct.name}'); 35 | 36 | handles.file_names = sorted_names; 37 | handles.is_dir = [dir_struct.isdir]; 38 | handles.sorted_index = sorted_index; 39 | guidata(handles.figure1,handles) 40 | set(handles.filebox,'String',handles.file_names,... 41 | 'Value',1) 42 | 43 | 44 | %% Function to load content into the listbox 'selbox' from the 'filebox' 45 | function load_selbox(fnames, handles) 46 | 47 | [~, x] = size(fnames); 48 | [sorted_names,sorted_index] = sortrows(fnames); 49 | handles.file_names = sorted_names; 50 | handles.sorted_index = sorted_index; 51 | guidata(handles.figure1,handles) 52 | set(handles.filenum,'String',[num2str(x) ' files selected']) 53 | set(handles.selbox,'String',handles.file_names,... 54 | 'Value',1) 55 | 56 | 57 | %% Callback: openingFcn 58 | % --- Executes just before startClusterAnalysis is made visible. 59 | function startClusterAnalysis_OpeningFcn(hObject, eventdata, handles, varargin) 60 | % This function has no output args, see OutputFcn. 61 | % hObject handle to figure 62 | % eventdata reserved - to be defined in a future version of MATLAB 63 | % handles structure with handles and user data (see GUIDATA) 64 | % varargin command line arguments to startClusterAnalysis (see VARARGIN) 65 | 66 | % Choose default command line output for startClusterAnalysis 67 | global files; 68 | 69 | DIR_input = pwd; 70 | DIR_output = [pwd filesep 'out']; 71 | 72 | files ={}; 73 | set(handles.displayDIR_input,'String',DIR_input); 74 | set(handles.displayDIR_output,'String',DIR_output); 75 | load_filebox(DIR_input,handles); 76 | 77 | handles.output = hObject; 78 | 79 | guidata(hObject, handles); 80 | 81 | 82 | % --- Outputs from this function are returned to the command line. 83 | function varargout = startClusterAnalysis_OutputFcn(hObject, eventdata, handles) 84 | % varargout cell array for returning output args (see VARARGOUT); 85 | % hObject handle to figure 86 | % eventdata reserved - to be defined in a future version of MATLAB 87 | % handles structure with handles and user data (see GUIDATA) 88 | 89 | % Get default command line output from handles structure 90 | varargout{1} = handles.output; 91 | 92 | 93 | % --- Executes on button press in selDIR_input. 94 | function selDIR_input_Callback(hObject, eventdata, handles) 95 | DIR_input = get(handles.displayDIR_input,'String'); 96 | if(isempty(DIR_input)) 97 | startdir = pwd; 98 | else 99 | startdir = DIR_input; 100 | end 101 | newDIR_input = uigetdir(startdir,'Select Input Directory'); 102 | if(newDIR_input == 0) % user pressed cancel 103 | return; 104 | else 105 | DIR_input = newDIR_input; 106 | end 107 | DIR_output = [DIR_input filesep 'out']; 108 | set(handles.filebox,'String',DIR_input); 109 | guidata(hObject, handles); 110 | set(handles.displayDIR_input,'String',DIR_input); 111 | set(handles.displayDIR_output,'String',DIR_output); 112 | load_filebox(DIR_input,handles); 113 | 114 | 115 | % --- Executes on selection change in filebox. 116 | function filebox_Callback(hObject, eventdata, handles) 117 | global files; 118 | contents = cellstr(get(hObject,'String')); 119 | if(isempty(contents)) 120 | return; 121 | end 122 | newfilename = contents{get(hObject,'Value')}; 123 | myfiles = get(handles.selbox,'String'); 124 | x = strmatch(newfilename, myfiles); %% check if file is already selected 125 | if(isempty(x)) 126 | files(end+1) ={newfilename}; 127 | load_selbox(files, handles) 128 | end 129 | 130 | 131 | % --- Executes during object creation, after setting all properties. 132 | function filebox_CreateFcn(hObject, eventdata, handles) 133 | 134 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 135 | set(hObject,'BackgroundColor','white'); 136 | end 137 | 138 | 139 | % --- Executes on selection change in selbox. 140 | function selbox_Callback(hObject, eventdata, handles) 141 | global files; 142 | [a b ]= size(files); 143 | 144 | contents = cellstr(get(hObject,'String')); 145 | if(isempty(contents)) 146 | return; 147 | end 148 | filenames = contents{get(hObject,'Value')}; 149 | newfiles = {}; 150 | j=1; 151 | for i = 1:b 152 | if (strcmp(files(i),filenames)==0) 153 | newfiles(j) = files(i); 154 | j=j+1; 155 | end 156 | end 157 | files = newfiles; 158 | load_selbox(files, handles) 159 | 160 | 161 | % --- Executes during object creation, after setting all properties. 162 | function selbox_CreateFcn(hObject, eventdata, handles) 163 | 164 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 165 | set(hObject,'BackgroundColor','white'); 166 | end 167 | 168 | 169 | function fn_Callback(hObject, eventdata, handles) 170 | DIR_input = get(handles.displayDIR_input,'String'); 171 | load_filebox(DIR_input,handles); 172 | guidata(hObject, handles); 173 | 174 | 175 | % --- Executes during object creation, after setting all properties. 176 | function fn_CreateFcn(hObject, eventdata, handles) 177 | 178 | % Hint: edit controls usually have a white background on Windows. 179 | % See ISPC and COMPUTER. 180 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 181 | set(hObject,'BackgroundColor','white'); 182 | end 183 | 184 | 185 | % --- Executes on button press in refresh. 186 | function refresh_Callback(hObject, eventdata, handles) 187 | DIR_input = get(handles.displayDIR_input,'String'); 188 | load_filebox(DIR_input,handles); 189 | 190 | 191 | % --- Executes on button press in loadall. 192 | function loadall_Callback(hObject, eventdata, handles) 193 | global files; 194 | files = cellstr(get(handles.filebox,'String'))'; 195 | load_selbox(files, handles); 196 | 197 | 198 | % --- Executes on button press in selDIR_output. 199 | function selDIR_output_Callback(hObject, eventdata, handles) 200 | % global DIR_output 201 | DIR_output = get(handles.displayDIR_output,'String'); 202 | newDIR_output = uigetdir('','Select Output Directory'); 203 | if(newDIR_output == 0) 204 | return; 205 | else 206 | DIR_output = newDIR_output; 207 | end 208 | set(handles.displayDIR_output,'String',DIR_output); 209 | % hObject handle to selDIR_output (see GCBO) 210 | % eventdata reserved - to be defined in a future version of MATLAB 211 | % handles structure with handles and user data (see GUIDATA) 212 | 213 | 214 | %% Main routine: START BUTTON PRESSED 215 | % ####################################################### 216 | % ### start main evaluation routine #### 217 | % ####################################################### 218 | % --- Executes on button press in startbut. 219 | function startbut_Callback(hObject, eventdata, handles) 220 | 221 | global files 222 | 223 | set(handles.startbut,'Enable','off'); 224 | drawnow; 225 | set(handles.errors,'String','no Problems so far...'); 226 | %-------------------------------------------------------------------------- 227 | % initialize callbacks 228 | Clusterparamstruct.displayStatus = @(text) displayStatus(handles.displaystatus,text); 229 | Clusterparamstruct.displayError = @(text) displayStatus(handles.errors,text); 230 | Clusterparamstruct.enableStartButton = @() enableStartButton(handles.startbut); 231 | 232 | % init general parameters 233 | if get(handles.twoDim, 'Value') == 1 234 | Clusterparamstruct.dimension = 2; 235 | elseif get(handles.threeDim, 'Value') == 1 236 | Clusterparamstruct.dimension = 3; 237 | end 238 | Clusterparamstruct.compareRandomData = get(handles.compareRandom, 'Value'); 239 | if Clusterparamstruct.compareRandomData == 1 240 | Clusterparamstruct.randomAlgorithm = get(handles.CSR, 'Value'); 241 | if get(handles.avgDensity, 'Value') == 1 242 | Clusterparamstruct.densityAlgorithm = 'averageDensity'; 243 | Clusterparamstruct.randomAlgorithmValue = []; % should stey empty - parameter is not needed 244 | end 245 | if get(handles.kernelDensity, 'Value') == 1 246 | Clusterparamstruct.densityAlgorithm = 'kernelDensity'; 247 | Clusterparamstruct.randomAlgorithmValue(1) = str2double(get(handles.sampDist, 'String')); 248 | Clusterparamstruct.randomAlgorithmValue(2) = str2double(get(handles.gridSpacing, 'String')); 249 | end 250 | if get(handles.specValue, 'Value') == 1 251 | Clusterparamstruct.densityAlgorithm = 'specificValue'; 252 | Clusterparamstruct.randomAlgorithmValue = str2double(get(handles.randomValue, 'String')); 253 | end 254 | else 255 | Clusterparamstruct.randomAlgorithm = 1; % create random data for object construction even if not requested 256 | Clusterparamstruct.densityAlgorithm = 'averageDensity'; 257 | Clusterparamstruct.randomAlgorithmValue = []; 258 | end 259 | Clusterparamstruct.showPlots = get(handles.showPlots, 'Value'); 260 | 261 | % parameter for kNN distance algortihm 262 | Clusterparamstruct.kNNDistance.algorithm = get(handles.kNNDistance, 'Value'); 263 | Clusterparamstruct.kNNDistance.k = str2double(get(handles.kValue, 'String')); 264 | Clusterparamstruct.kNNDistance.maxDistance = str2double(get(handles.maxNNDist, 'String')); % in nm 265 | 266 | % parameter for DBSCAN algorithm 267 | Clusterparamstruct.DBSCAN.algorithm = get(handles.DBSCANalgo, 'Value'); 268 | Clusterparamstruct.DBSCAN.radius = str2double(get(handles.DBSCANradius, 'String')); 269 | Clusterparamstruct.DBSCAN.minPoint = str2double(get(handles.DBSCANpoints, 'String')); 270 | Clusterparamstruct.DBSCAN.maxDiameter = str2double(get(handles.DBSCANdelete, 'String')); 271 | 272 | % parameter for distance analysis 273 | Clusterparamstruct.Distance.algorithm = get(handles.distanceAlgo, 'Value'); 274 | Clusterparamstruct.Distance.maxDistance = str2double(get(handles.maxDist, 'String')); % in nm 275 | 276 | % parameter for RDF 277 | Clusterparamstruct.RDF.algorithm = get(handles.RDF, 'Value'); 278 | Clusterparamstruct.RDF.binSize = str2double(get(handles.binSize, 'String')); % in nm 279 | Clusterparamstruct.RDF.maxDistance = str2double(get(handles.maxDistRDF, 'String')); % in nm 280 | 281 | % parameter for Ripley's function 282 | Clusterparamstruct.ripley.algorithm = get(handles.ripley, 'Value'); 283 | Clusterparamstruct.ripley.radius = str2double(get(handles.ripleyRadius, 'String')); % in nm 284 | Clusterparamstruct.ripley.maxDistance = str2double(get(handles.ripleyDistance, 'String')); % in nm 285 | 286 | % get name of sample 287 | if isempty(get(handles.treatmentName, 'String')) 288 | Clusterparamstruct.treatmentName = 'clusterData'; 289 | else 290 | Clusterparamstruct.treatmentName = get(handles.treatmentName, 'String'); 291 | end 292 | 293 | set(handles.displaystatus,'String','Evaluation running...'); 294 | %-------------------------------------------------------------------------- 295 | %% - create outputfolder if not existing 296 | Clusterparamstruct.DIR_input = get(handles.displayDIR_input,'String'); 297 | Clusterparamstruct.DIR_output = get(handles.displayDIR_output,'String'); 298 | files = cellstr(get(handles.selbox,'String'))'; 299 | if(strcmp(get(handles.filenum,'String'),'no files selected')) 300 | files = {}; 301 | end 302 | if(isempty(files)) 303 | set(handles.displaystatus,'String','Error - Evaluation not successful'); 304 | set(handles.errors,'String','No File Selected'); 305 | set(handles.startbut,'Enable','on'); 306 | error('No files selected'); 307 | end 308 | 309 | if(~isdir(Clusterparamstruct.DIR_output)) 310 | mkdir(Clusterparamstruct.DIR_output); 311 | disp('output folder created') 312 | end 313 | %% - start evaluation - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 314 | Clusterparamstruct.handles = handles; 315 | Clusterparamstruct.outputmode = 'gui'; 316 | 317 | clusterBatchProcessing(Clusterparamstruct); 318 | 319 | set(handles.displaystatus,'String','Evaluation finished!'); 320 | set(handles.startbut,'Enable','on'); 321 | 322 | 323 | % --- Executes when selected object is changed in filetypegroup. 324 | function filetypegroup_SelectionChangeFcn(hObject, eventdata, handles) 325 | switch get(eventdata.NewValue,'Tag') 326 | case 'ortesel' 327 | set(handles.fn,'String','*.mat'); 328 | end 329 | DIR_input = get(handles.displayDIR_input,'String'); 330 | load_filebox(DIR_input,handles); 331 | % hObject handle to the selected object in filetypegroup 332 | % eventdata structure with the following fields (see UIBUTTONGROUP) 333 | % EventName: string 'SelectionChanged' (read only) 334 | % OldValue: handle of the previously selected object or empty if none was selected 335 | % NewValue: handle of the currently selected object 336 | % handles structure with handles and user data (see GUIDATA) 337 | 338 | 339 | % -------------------------------------------------------------------- 340 | function filetypegroup_ButtonDownFcn(hObject, eventdata, handles) 341 | % hObject handle to filetypegroup (see GCBO) 342 | % eventdata reserved - to be defined in a future version of MATLAB 343 | % handles structure with handles and user data (see GUIDATA) 344 | 345 | 346 | % --- Executes during object creation, after setting all properties. 347 | function filetypegroup_CreateFcn(hObject, eventdata, handles) 348 | % hObject handle to filetypegroup (see GCBO) 349 | % eventdata reserved - to be defined in a future version of MATLAB 350 | % handles empty - handles not created until after all CreateFcns called 351 | 352 | 353 | % -------------------------------------------------------------------- 354 | function uimenuEnableStartButton_Callback(hObject, eventdata, handles) 355 | % hObject handle to uimenuEnableStartButton (see GCBO) 356 | % eventdata reserved - to be defined in a future version of MATLAB 357 | % handles structure with handles and user data (see GUIDATA) 358 | set(handles.startbut,'Enable','on'); 359 | 360 | 361 | % --- Executes on button press in debugbutton. 362 | function debugbutton_Callback(hObject, eventdata, handles) 363 | % hObject handle to debugbutton (see GCBO) 364 | % eventdata reserved - to be defined in a future version of MATLAB 365 | % handles structure with handles and user data (see GUIDATA) 366 | keyboard 367 | 368 | 369 | function displayStatus(hObject,text) 370 | % call this function with hObject = handles.displaystatus 371 | set(hObject,'String',text); 372 | 373 | 374 | function enableStartButton(hObject) 375 | % call this function with hObject = handles.startbut 376 | set(hObject,'Enable','on'); 377 | 378 | 379 | function edit22_Callback(hObject, eventdata, handles) 380 | % hObject handle to edit22 (see GCBO) 381 | % eventdata reserved - to be defined in a future version of MATLAB 382 | % handles structure with handles and user data (see GUIDATA) 383 | 384 | % Hints: get(hObject,'String') returns contents of edit22 as text 385 | % str2double(get(hObject,'String')) returns contents of edit22 as a double 386 | 387 | 388 | % --- Executes during object creation, after setting all properties. 389 | function edit22_CreateFcn(hObject, eventdata, handles) 390 | % hObject handle to edit22 (see GCBO) 391 | % eventdata reserved - to be defined in a future version of MATLAB 392 | % handles empty - handles not created until after all CreateFcns called 393 | 394 | % Hint: edit controls usually have a white background on Windows. 395 | % See ISPC and COMPUTER. 396 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 397 | set(hObject,'BackgroundColor','white'); 398 | end 399 | 400 | 401 | function edit23_Callback(hObject, eventdata, handles) 402 | % hObject handle to edit23 (see GCBO) 403 | % eventdata reserved - to be defined in a future version of MATLAB 404 | % handles structure with handles and user data (see GUIDATA) 405 | 406 | % Hints: get(hObject,'String') returns contents of edit23 as text 407 | % str2double(get(hObject,'String')) returns contents of edit23 as a double 408 | 409 | 410 | % --- Executes during object creation, after setting all properties. 411 | function edit23_CreateFcn(hObject, eventdata, handles) 412 | % hObject handle to edit23 (see GCBO) 413 | % eventdata reserved - to be defined in a future version of MATLAB 414 | % handles empty - handles not created until after all CreateFcns called 415 | 416 | % Hint: edit controls usually have a white background on Windows. 417 | % See ISPC and COMPUTER. 418 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 419 | set(hObject,'BackgroundColor','white'); 420 | end 421 | 422 | 423 | % --- Executes on selection change in listbox10. 424 | function listbox10_Callback(hObject, eventdata, handles) 425 | % hObject handle to listbox10 (see GCBO) 426 | % eventdata reserved - to be defined in a future version of MATLAB 427 | % handles structure with handles and user data (see GUIDATA) 428 | 429 | % Hints: contents = cellstr(get(hObject,'String')) returns listbox10 contents as cell array 430 | % contents{get(hObject,'Value')} returns selected item from listbox10 431 | 432 | 433 | % --- Executes during object creation, after setting all properties. 434 | function listbox10_CreateFcn(hObject, eventdata, handles) 435 | % hObject handle to listbox10 (see GCBO) 436 | % eventdata reserved - to be defined in a future version of MATLAB 437 | % handles empty - handles not created until after all CreateFcns called 438 | 439 | % Hint: listbox controls usually have a white background on Windows. 440 | % See ISPC and COMPUTER. 441 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 442 | set(hObject,'BackgroundColor','white'); 443 | end 444 | 445 | 446 | function order_Callback(hObject, eventdata, handles) 447 | % hObject handle to order (see GCBO) 448 | % eventdata reserved - to be defined in a future version of MATLAB 449 | % handles structure with handles and user data (see GUIDATA) 450 | 451 | % Hints: get(hObject,'String') returns contents of order as text 452 | % str2double(get(hObject,'String')) returns contents of order as a double 453 | 454 | 455 | % --- Executes during object creation, after setting all properties. 456 | function order_CreateFcn(hObject, eventdata, handles) 457 | % hObject handle to order (see GCBO) 458 | % eventdata reserved - to be defined in a future version of MATLAB 459 | % handles empty - handles not created until after all CreateFcns called 460 | 461 | % Hint: edit controls usually have a white background on Windows. 462 | % See ISPC and COMPUTER. 463 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 464 | set(hObject,'BackgroundColor','white'); 465 | end 466 | 467 | % --- Executes on button press in cropOrte. 468 | function cropOrte_Callback(hObject, eventdata, handles) 469 | % hObject handle to cropOrte (see GCBO) 470 | % eventdata reserved - to be defined in a future version of MATLAB 471 | % handles structure with handles and user data (see GUIDATA) 472 | cropImage; 473 | 474 | 475 | % --- Executes on button press in helpbutton. 476 | function helpbutton_Callback(hObject, eventdata, handles) 477 | % hObject handle to helpbutton (see GCBO) 478 | % eventdata reserved - to be defined in a future version of MATLAB 479 | % handles structure with handles and user data (see GUIDATA) 480 | winopen('help/LAND_manual.pdf'); 481 | 482 | 483 | % --- Executes on button press in twoDim. 484 | function twoDim_Callback(hObject, eventdata, handles) 485 | % hObject handle to twoDim (see GCBO) 486 | % eventdata reserved - to be defined in a future version of MATLAB 487 | % handles structure with handles and user data (see GUIDATA) 488 | set(handles.threeDim, 'Value', 0); 489 | 490 | % Hint: get(hObject,'Value') returns toggle state of twoDim 491 | 492 | 493 | % --- Executes on button press in threeDim. 494 | function threeDim_Callback(hObject, eventdata, handles) 495 | % hObject handle to threeDim (see GCBO) 496 | % eventdata reserved - to be defined in a future version of MATLAB 497 | % handles structure with handles and user data (see GUIDATA) 498 | set(handles.twoDim, 'Value', 0); 499 | 500 | % Hint: get(hObject,'Value') returns toggle state of threeDim 501 | 502 | 503 | % --- Executes on button press in compareRandom. 504 | function compareRandom_Callback(hObject, eventdata, handles) 505 | % hObject handle to compareRandom (see GCBO) 506 | % eventdata reserved - to be defined in a future version of MATLAB 507 | % handles structure with handles and user data (see GUIDATA) 508 | if(get(hObject,'Value')) 509 | set(handles.CSR, 'Enable', 'on'); 510 | set(handles.avgDensity, 'Enable', 'on'); 511 | set(handles.kernelDensity, 'Enable', 'on'); 512 | set(handles.specValue, 'Enable', 'on'); 513 | set(handles.sampDist, 'Enable', 'on'); 514 | set(handles.randomValue, 'Enable', 'on'); 515 | set(handles.gridSpacing, 'Enable', 'on'); 516 | set(handles.text80, 'Enable', 'on'); 517 | set(handles.text81, 'Enable', 'on'); 518 | else 519 | set(handles.CSR, 'Enable', 'off'); 520 | set(handles.avgDensity, 'Enable', 'off'); 521 | set(handles.kernelDensity, 'Enable', 'off'); 522 | set(handles.specValue, 'Enable', 'off'); 523 | set(handles.sampDist, 'Enable', 'off'); 524 | set(handles.randomValue, 'Enable', 'off'); 525 | set(handles.gridSpacing, 'Enable', 'off') 526 | set(handles.text80, 'Enable', 'off'); 527 | set(handles.text81, 'Enable', 'off'); 528 | end 529 | % Hint: get(hObject,'Value') returns toggle state of compareRandom 530 | 531 | 532 | % --- Executes on button press in showPlots. 533 | function showPlots_Callback(hObject, eventdata, handles) 534 | % hObject handle to showPlots (see GCBO) 535 | % eventdata reserved - to be defined in a future version of MATLAB 536 | % handles structure with handles and user data (see GUIDATA) 537 | 538 | % Hint: get(hObject,'Value') returns toggle state of showPlots 539 | 540 | 541 | 542 | function kValue_Callback(hObject, eventdata, handles) 543 | % hObject handle to kValue (see GCBO) 544 | % eventdata reserved - to be defined in a future version of MATLAB 545 | % handles structure with handles and user data (see GUIDATA) 546 | 547 | % Hints: get(hObject,'String') returns contents of kValue as text 548 | % str2double(get(hObject,'String')) returns contents of kValue as a double 549 | 550 | 551 | % --- Executes during object creation, after setting all properties. 552 | function kValue_CreateFcn(hObject, eventdata, handles) 553 | % hObject handle to kValue (see GCBO) 554 | % eventdata reserved - to be defined in a future version of MATLAB 555 | % handles empty - handles not created until after all CreateFcns called 556 | 557 | % Hint: edit controls usually have a white background on Windows. 558 | % See ISPC and COMPUTER. 559 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 560 | set(hObject,'BackgroundColor','white'); 561 | end 562 | 563 | 564 | % --- Executes on button press in kNNDistance. 565 | function kNNDistance_Callback(hObject, eventdata, handles) 566 | % hObject handle to kNNDistance (see GCBO) 567 | % eventdata reserved - to be defined in a future version of MATLAB 568 | % handles structure with handles and user data (see GUIDATA) 569 | 570 | % Hint: get(hObject,'Value') returns toggle state of kNNDistance 571 | 572 | 573 | 574 | function maxNNDist_Callback(hObject, eventdata, handles) 575 | % hObject handle to maxNNDist (see GCBO) 576 | % eventdata reserved - to be defined in a future version of MATLAB 577 | % handles structure with handles and user data (see GUIDATA) 578 | 579 | % Hints: get(hObject,'String') returns contents of maxNNDist as text 580 | % str2double(get(hObject,'String')) returns contents of maxNNDist as a double 581 | 582 | 583 | % --- Executes during object creation, after setting all properties. 584 | function maxNNDist_CreateFcn(hObject, eventdata, handles) 585 | % hObject handle to maxNNDist (see GCBO) 586 | % eventdata reserved - to be defined in a future version of MATLAB 587 | % handles empty - handles not created until after all CreateFcns called 588 | 589 | % Hint: edit controls usually have a white background on Windows. 590 | % See ISPC and COMPUTER. 591 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 592 | set(hObject,'BackgroundColor','white'); 593 | end 594 | 595 | function DBSCANradius_Callback(hObject, eventdata, handles) 596 | % hObject handle to DBSCANradius (see GCBO) 597 | % eventdata reserved - to be defined in a future version of MATLAB 598 | % handles structure with handles and user data (see GUIDATA) 599 | 600 | % Hints: get(hObject,'String') returns contents of DBSCANradius as text 601 | % str2double(get(hObject,'String')) returns contents of DBSCANradius as a double 602 | 603 | 604 | % --- Executes during object creation, after setting all properties. 605 | function DBSCANradius_CreateFcn(hObject, eventdata, handles) 606 | % hObject handle to DBSCANradius (see GCBO) 607 | % eventdata reserved - to be defined in a future version of MATLAB 608 | % handles empty - handles not created until after all CreateFcns called 609 | 610 | % Hint: edit controls usually have a white background on Windows. 611 | % See ISPC and COMPUTER. 612 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 613 | set(hObject,'BackgroundColor','white'); 614 | end 615 | 616 | 617 | 618 | function DBSCANpoints_Callback(hObject, eventdata, handles) 619 | % hObject handle to DBSCANpoints (see GCBO) 620 | % eventdata reserved - to be defined in a future version of MATLAB 621 | % handles structure with handles and user data (see GUIDATA) 622 | 623 | % Hints: get(hObject,'String') returns contents of DBSCANpoints as text 624 | % str2double(get(hObject,'String')) returns contents of DBSCANpoints as a double 625 | 626 | 627 | % --- Executes during object creation, after setting all properties. 628 | function DBSCANpoints_CreateFcn(hObject, eventdata, handles) 629 | % hObject handle to DBSCANpoints (see GCBO) 630 | % eventdata reserved - to be defined in a future version of MATLAB 631 | % handles empty - handles not created until after all CreateFcns called 632 | 633 | % Hint: edit controls usually have a white background on Windows. 634 | % See ISPC and COMPUTER. 635 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 636 | set(hObject,'BackgroundColor','white'); 637 | end 638 | 639 | 640 | 641 | function DBSCANdelete_Callback(hObject, eventdata, handles) 642 | % hObject handle to DBSCANdelete (see GCBO) 643 | % eventdata reserved - to be defined in a future version of MATLAB 644 | % handles structure with handles and user data (see GUIDATA) 645 | 646 | % Hints: get(hObject,'String') returns contents of DBSCANdelete as text 647 | % str2double(get(hObject,'String')) returns contents of DBSCANdelete as a double 648 | 649 | 650 | % --- Executes during object creation, after setting all properties. 651 | function DBSCANdelete_CreateFcn(hObject, eventdata, handles) 652 | % hObject handle to DBSCANdelete (see GCBO) 653 | % eventdata reserved - to be defined in a future version of MATLAB 654 | % handles empty - handles not created until after all CreateFcns called 655 | 656 | % Hint: edit controls usually have a white background on Windows. 657 | % See ISPC and COMPUTER. 658 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 659 | set(hObject,'BackgroundColor','white'); 660 | end 661 | 662 | 663 | % --- Executes on button press in DBSCANalgo. 664 | function DBSCANalgo_Callback(hObject, eventdata, handles) 665 | % hObject handle to DBSCANalgo (see GCBO) 666 | % eventdata reserved - to be defined in a future version of MATLAB 667 | % handles structure with handles and user data (see GUIDATA) 668 | 669 | % Hint: get(hObject,'Value') returns toggle state of DBSCANalgo 670 | 671 | 672 | % --- Executes on button press in distanceAlgo. 673 | function distanceAlgo_Callback(hObject, eventdata, handles) 674 | % hObject handle to distanceAlgo (see GCBO) 675 | % eventdata reserved - to be defined in a future version of MATLAB 676 | % handles structure with handles and user data (see GUIDATA) 677 | 678 | % Hint: get(hObject,'Value') returns toggle state of distanceAlgo 679 | 680 | 681 | 682 | function maxDist_Callback(hObject, eventdata, handles) 683 | % hObject handle to maxDist (see GCBO) 684 | % eventdata reserved - to be defined in a future version of MATLAB 685 | % handles structure with handles and user data (see GUIDATA) 686 | 687 | % Hints: get(hObject,'String') returns contents of maxDist as text 688 | % str2double(get(hObject,'String')) returns contents of maxDist as a double 689 | 690 | 691 | % --- Executes during object creation, after setting all properties. 692 | function maxDist_CreateFcn(hObject, eventdata, handles) 693 | % hObject handle to maxDist (see GCBO) 694 | % eventdata reserved - to be defined in a future version of MATLAB 695 | % handles empty - handles not created until after all CreateFcns called 696 | 697 | % Hint: edit controls usually have a white background on Windows. 698 | % See ISPC and COMPUTER. 699 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 700 | set(hObject,'BackgroundColor','white'); 701 | end 702 | 703 | 704 | % --- Executes on button press in parameterEstimation. 705 | function parameterEstimation_Callback(hObject, eventdata, handles) 706 | % hObject handle to parameterEstimation (see GCBO) 707 | % eventdata reserved - to be defined in a future version of MATLAB 708 | % handles structure with handles and user data (see GUIDATA) 709 | [filename, pathname] = uigetfile('*.mat', 'Select an Orte file to test DBSCAN parameter'); 710 | if isequal(filename, 0) 711 | disp('No Orte file selected') 712 | else 713 | estimationFile = load([pathname filename]); 714 | oldField = char(fieldnames(estimationFile)); 715 | if ~(strcmp(oldField, 'Orte')) 716 | newField = 'Orte'; 717 | [estimationFile.(newField)] = estimationFile.(oldField); 718 | estimationFile = rmfield(estimationFile, oldField); 719 | end 720 | parameterObject = ClusterAnalysis(estimationFile.Orte); 721 | parameterObject.parameterEstimation('DBSCAN'); 722 | parameterObject.delete; 723 | clear('Orte', 'parameterObject', 'filename', 'pathname'); 724 | end 725 | 726 | 727 | % --- Executes on button press in avgDensity. 728 | function avgDensity_Callback(hObject, eventdata, handles) 729 | % hObject handle to avgDensity (see GCBO) 730 | % eventdata reserved - to be defined in a future version of MATLAB 731 | % handles structure with handles and user data (see GUIDATA) 732 | set(handles.kernelDensity, 'Value', 0); 733 | set(handles.specValue, 'Value', 0); 734 | % Hint: get(hObject,'Value') returns toggle state of avgDensity 735 | 736 | 737 | % --- Executes on button press in kernelDensity. 738 | function kernelDensity_Callback(hObject, eventdata, handles) 739 | % hObject handle to kernelDensity (see GCBO) 740 | % eventdata reserved - to be defined in a future version of MATLAB 741 | % handles structure with handles and user data (see GUIDATA) 742 | set(handles.avgDensity, 'Value', 0); 743 | set(handles.specValue, 'Value', 0); 744 | % Hint: get(hObject,'Value') returns toggle state of kernelDensity 745 | 746 | 747 | % --- Executes on button press in specValue. 748 | function specValue_Callback(hObject, eventdata, handles) 749 | % hObject handle to specValue (see GCBO) 750 | % eventdata reserved - to be defined in a future version of MATLAB 751 | % handles structure with handles and user data (see GUIDATA) 752 | set(handles.avgDensity, 'Value', 0); 753 | set(handles.kernelDensity, 'Value', 0); 754 | % Hint: get(hObject,'Value') returns toggle state of specValue 755 | 756 | 757 | function sampDist_Callback(hObject, eventdata, handles) 758 | % hObject handle to sampDist (see GCBO) 759 | % eventdata reserved - to be defined in a future version of MATLAB 760 | % handles structure with handles and user data (see GUIDATA) 761 | 762 | % Hints: get(hObject,'String') returns contents of sampDist as text 763 | % str2double(get(hObject,'String')) returns contents of sampDist as a double 764 | 765 | 766 | % --- Executes during object creation, after setting all properties. 767 | function sampDist_CreateFcn(hObject, eventdata, handles) 768 | % hObject handle to sampDist (see GCBO) 769 | % eventdata reserved - to be defined in a future version of MATLAB 770 | % handles empty - handles not created until after all CreateFcns called 771 | 772 | % Hint: edit controls usually have a white background on Windows. 773 | % See ISPC and COMPUTER. 774 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 775 | set(hObject,'BackgroundColor','white'); 776 | end 777 | 778 | 779 | 780 | function randomValue_Callback(hObject, eventdata, handles) 781 | % hObject handle to randomValue (see GCBO) 782 | % eventdata reserved - to be defined in a future version of MATLAB 783 | % handles structure with handles and user data (see GUIDATA) 784 | 785 | % Hints: get(hObject,'String') returns contents of randomValue as text 786 | % str2double(get(hObject,'String')) returns contents of randomValue as a double 787 | 788 | 789 | % --- Executes during object creation, after setting all properties. 790 | function randomValue_CreateFcn(hObject, eventdata, handles) 791 | % hObject handle to randomValue (see GCBO) 792 | % eventdata reserved - to be defined in a future version of MATLAB 793 | % handles empty - handles not created until after all CreateFcns called 794 | 795 | % Hint: edit controls usually have a white background on Windows. 796 | % See ISPC and COMPUTER. 797 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 798 | set(hObject,'BackgroundColor','white'); 799 | end 800 | 801 | 802 | % --- Executes on button press in CSR. 803 | function CSR_Callback(hObject, eventdata, handles) 804 | % hObject handle to CSR (see GCBO) 805 | % eventdata reserved - to be defined in a future version of MATLAB 806 | % handles structure with handles and user data (see GUIDATA) 807 | 808 | % Hint: get(hObject,'Value') returns toggle state of CSR 809 | 810 | 811 | 812 | function treatmentName_Callback(hObject, eventdata, handles) 813 | % hObject handle to treatmentName (see GCBO) 814 | % eventdata reserved - to be defined in a future version of MATLAB 815 | % handles structure with handles and user data (see GUIDATA) 816 | 817 | % Hints: get(hObject,'String') returns contents of treatmentName as text 818 | % str2double(get(hObject,'String')) returns contents of treatmentName as a double 819 | 820 | 821 | % --- Executes during object creation, after setting all properties. 822 | function treatmentName_CreateFcn(hObject, eventdata, handles) 823 | % hObject handle to treatmentName (see GCBO) 824 | % eventdata reserved - to be defined in a future version of MATLAB 825 | % handles empty - handles not created until after all CreateFcns called 826 | 827 | % Hint: edit controls usually have a white background on Windows. 828 | % See ISPC and COMPUTER. 829 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 830 | set(hObject,'BackgroundColor','white'); 831 | end 832 | 833 | 834 | 835 | function binSize_Callback(hObject, eventdata, handles) 836 | % hObject handle to binSize (see GCBO) 837 | % eventdata reserved - to be defined in a future version of MATLAB 838 | % handles structure with handles and user data (see GUIDATA) 839 | 840 | % Hints: get(hObject,'String') returns contents of binSize as text 841 | % str2double(get(hObject,'String')) returns contents of binSize as a double 842 | 843 | 844 | % --- Executes during object creation, after setting all properties. 845 | function binSize_CreateFcn(hObject, eventdata, handles) 846 | % hObject handle to binSize (see GCBO) 847 | % eventdata reserved - to be defined in a future version of MATLAB 848 | % handles empty - handles not created until after all CreateFcns called 849 | 850 | % Hint: edit controls usually have a white background on Windows. 851 | % See ISPC and COMPUTER. 852 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 853 | set(hObject,'BackgroundColor','white'); 854 | end 855 | 856 | 857 | % --- Executes on button press in RDF. 858 | function RDF_Callback(hObject, eventdata, handles) 859 | % hObject handle to RDF (see GCBO) 860 | % eventdata reserved - to be defined in a future version of MATLAB 861 | % handles structure with handles and user data (see GUIDATA) 862 | 863 | % Hint: get(hObject,'Value') returns toggle state of RDF 864 | 865 | 866 | 867 | function maxDistRDF_Callback(hObject, eventdata, handles) 868 | % hObject handle to maxDistRDF (see GCBO) 869 | % eventdata reserved - to be defined in a future version of MATLAB 870 | % handles structure with handles and user data (see GUIDATA) 871 | 872 | % Hints: get(hObject,'String') returns contents of maxDistRDF as text 873 | % str2double(get(hObject,'String')) returns contents of maxDistRDF as a double 874 | 875 | 876 | % --- Executes during object creation, after setting all properties. 877 | function maxDistRDF_CreateFcn(hObject, eventdata, handles) 878 | % hObject handle to maxDistRDF (see GCBO) 879 | % eventdata reserved - to be defined in a future version of MATLAB 880 | % handles empty - handles not created until after all CreateFcns called 881 | 882 | % Hint: edit controls usually have a white background on Windows. 883 | % See ISPC and COMPUTER. 884 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 885 | set(hObject,'BackgroundColor','white'); 886 | end 887 | 888 | 889 | 890 | function ripleyRadius_Callback(hObject, eventdata, handles) 891 | % hObject handle to ripleyRadius (see GCBO) 892 | % eventdata reserved - to be defined in a future version of MATLAB 893 | % handles structure with handles and user data (see GUIDATA) 894 | 895 | % Hints: get(hObject,'String') returns contents of ripleyRadius as text 896 | % str2double(get(hObject,'String')) returns contents of ripleyRadius as a double 897 | 898 | 899 | % --- Executes during object creation, after setting all properties. 900 | function ripleyRadius_CreateFcn(hObject, eventdata, handles) 901 | % hObject handle to ripleyRadius (see GCBO) 902 | % eventdata reserved - to be defined in a future version of MATLAB 903 | % handles empty - handles not created until after all CreateFcns called 904 | 905 | % Hint: edit controls usually have a white background on Windows. 906 | % See ISPC and COMPUTER. 907 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 908 | set(hObject,'BackgroundColor','white'); 909 | end 910 | 911 | 912 | 913 | function ripleyDistance_Callback(hObject, eventdata, handles) 914 | % hObject handle to ripleyDistance (see GCBO) 915 | % eventdata reserved - to be defined in a future version of MATLAB 916 | % handles structure with handles and user data (see GUIDATA) 917 | 918 | % Hints: get(hObject,'String') returns contents of ripleyDistance as text 919 | % str2double(get(hObject,'String')) returns contents of ripleyDistance as a double 920 | 921 | 922 | % --- Executes during object creation, after setting all properties. 923 | function ripleyDistance_CreateFcn(hObject, eventdata, handles) 924 | % hObject handle to ripleyDistance (see GCBO) 925 | % eventdata reserved - to be defined in a future version of MATLAB 926 | % handles empty - handles not created until after all CreateFcns called 927 | 928 | % Hint: edit controls usually have a white background on Windows. 929 | % See ISPC and COMPUTER. 930 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 931 | set(hObject,'BackgroundColor','white'); 932 | end 933 | 934 | 935 | % --- Executes on button press in ripley. 936 | function ripley_Callback(hObject, eventdata, handles) 937 | % hObject handle to ripley (see GCBO) 938 | % eventdata reserved - to be defined in a future version of MATLAB 939 | % handles structure with handles and user data (see GUIDATA) 940 | 941 | % Hint: get(hObject,'Value') returns toggle state of ripley 942 | 943 | 944 | 945 | function gridSpacing_Callback(hObject, eventdata, handles) 946 | % hObject handle to gridSpacing (see GCBO) 947 | % eventdata reserved - to be defined in a future version of MATLAB 948 | % handles structure with handles and user data (see GUIDATA) 949 | 950 | % Hints: get(hObject,'String') returns contents of gridSpacing as text 951 | % str2double(get(hObject,'String')) returns contents of gridSpacing as a double 952 | 953 | 954 | % --- Executes during object creation, after setting all properties. 955 | function gridSpacing_CreateFcn(hObject, eventdata, handles) 956 | % hObject handle to gridSpacing (see GCBO) 957 | % eventdata reserved - to be defined in a future version of MATLAB 958 | % handles empty - handles not created until after all CreateFcns called 959 | 960 | % Hint: edit controls usually have a white background on Windows. 961 | % See ISPC and COMPUTER. 962 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 963 | set(hObject,'BackgroundColor','white'); 964 | end 965 | --------------------------------------------------------------------------------