starting som prediction fine-tuned class-performance visualisation
Christoph Budziszewski

Christoph Budziszewski commited on 2009-01-21 16:34:25
Zeige 147 geänderte Dateien mit 46482 Einfügungen und 15 Löschungen.


git-svn-id: https://svn.discofish.de/MATLAB/spmtoolbox/SVMCrossVal@112 83ab2cfd-5345-466c-8aeb-2b2739fb922d
... ...
@@ -0,0 +1,100 @@
1
+function classify(varargin)
2
+
3
+
4
+
5
+switch nargin
6
+    case 1
7
+        paramModel = varargin{1};
8
+        % PROJECT_BASE_PATH = 'D:\Analyze\Stimolos';
9
+        PROJECT_BASE_PATH = 'D:\Analyze\Choice\24pilot';
10
+        PROJECT_RESULT_PATH = 'results\SPM.mat';
11
+    otherwise
12
+        error('spmtoolbox:SVMCrossVal:arginError','Please Specify action and parameter model');
13
+end
14
+
15
+        
16
+        % common params
17
+        calculateParams  = struct;
18
+        calculateParams.smoothed        = getDouble(paramModel.txtSmoothed);
19
+
20
+        calculateParams.frameShiftStart = getDouble(paramModel.txtFrameShiftStart);  % -20;
21
+        calculateParams.frameShiftEnd   = getDouble(paramModel.txtFrameShiftEnd); %15;
22
+        calculateParams.decodeDuration  = getDouble(paramModel.txtFrameShiftDur);
23
+        calculateParams.psthStart       = getDouble(paramModel.txtPSTHStart); % -25;
24
+        calculateParams.psthEnd         = getDouble(paramModel.txtPSTHEnd); % 20;
25
+        calculateParams.baselineStart   = getDouble(paramModel.txtBaselineStart); % -22;
26
+        calculateParams.baselineEnd     = getDouble(paramModel.txtBaselineEnd); % -20;
27
+
28
+        calculateParams.svmargs         = get(paramModel.txtSVMopts,'String');
29
+        calculateParams.sessionList     = 1:3;
30
+
31
+        classStruct = parseClassDef(paramModel);
32
+        
33
+        
34
+        calculateParams.labelMap        = LabelMap(classStruct.labelCells , classStruct.conditionCells, 'auto'); % LabelMap({'<','>','<+<','>+>','<+>','>+<'},{-2,-1,1,2,3,4}); 0 is autolabel
35
+        calculateParams.classList       = getClasses(calculateParams.labelMap);
36
+        calculateParams.eventList       = classStruct.eventMatrix; %[9,11,13; 10,12,14];
37
+%         calculateParams.eventList       = getPSTEventMatrix(calculateParams.labelMap);
38
+        
39
+        subjectSelection = getSubjectIDString(paramModel);
40
+        decode = struct;
41
+        decode.decodePerformance = [];
42
+        decode.rawTimeCourse     = [];
43
+        
44
+        for subjectCell = subjectSelection
45
+            SubjectID = cell2mat(subjectCell);
46
+            namehelper = strcat('s',SubjectID); %Vars can not start with numbers.
47
+
48
+            display('loading SPM.mat ...');
49
+            spm = load(fullfile(PROJECT_BASE_PATH,SubjectID,PROJECT_RESULT_PATH));
50
+            display('... done.');
51
+
52
+            %% calculate
53
+            calculateParams.(namehelper).des             = spm.SPM;
54
+            calculateParams.(namehelper).voxelList       = parseVoxelList(paramModel,SubjectID);
55
+            assignin('base','calculateParams',calculateParams);
56
+
57
+            display(sprintf('calculating cross-validation performance time-shift for Subject %s. Please Wait. ...',SubjectID));
58
+            display('switching off all warnings');
59
+            warning_state               = warning('off','all');
60
+            display('calculating ...');
61
+            decode.(namehelper)         = calculateDecodePerformance(calculateParams,SubjectID);
62
+            display('... done');
63
+            display('restoring warnings');
64
+            warning(warning_state);
65
+            
66
+            decode.decodePerformance    = [decode.decodePerformance decode.(namehelper).decodePerformance];
67
+            decode.rawTimeCourse        = [decode.rawTimeCourse decode.(namehelper).rawTimeCourse];
68
+
69
+            assignin('base','decode',decode);
70
+        end
71
+
72
+        display('Finished calculations.');
73
+        display('Plotting...');
74
+
75
+        plotParams                  = struct;
76
+        plotParams.psthStart        = calculateParams.psthStart;
77
+        plotParams.psthEnd   =  calculateParams.psthEnd;
78
+        plotParams.nClasses  = length(calculateParams.classList);
79
+        
80
+        plotParams.frameShiftStart   = calculateParams.frameShiftStart;
81
+        plotParams.frameShiftEnd     = calculateParams.frameShiftEnd;
82
+        plotParams.decodePerformance = decode.decodePerformance;
83
+        plotParams.rawTimeCourse     = decode.rawTimeCourse;
84
+        
85
+        if numel(subjectSelection) == 1
86
+          plotParams.SubjectID         = SubjectID;
87
+        else
88
+          plotParams.SubjectID         = 'Multiple';
89
+        end
90
+
91
+        plotParams.smoothed          = boolToYesNoString(calculateParams.smoothed);
92
+         
93
+
94
+        assignin('base','plotParams',plotParams);
95
+%         plotDecodePerformance(params.psthStart,params.psthEnd,params.nClasses,decode.decodeTable,params.frameShiftStart,params.frameShiftEnd,decode.rawTimeCourse);
96
+        plotDecodePerformance(plotParams);
97
+            
98
+        display('all done.');
99
+
100
+    end
0 101
\ No newline at end of file
... ...
@@ -0,0 +1,103 @@
1
+function plotDecodePerformance(varargin)
2
+% plotDecodePerformance(timeline,decodePerformance,nClasses,rawData)
3
+
4
+PSTH_AXIS_MIN = -1;
5
+PSTH_AXIS_MAX = 1;
6
+
7
+switch nargin
8
+    
9
+    case 1
10
+        inputStruct       = cell2mat(varargin(1));
11
+
12
+        psthStart         = inputStruct.psthStart;
13
+        psthEnd           = inputStruct.psthEnd;
14
+        nClasses          = inputStruct.nClasses;
15
+        decodePerformance = inputStruct.decodePerformance;
16
+        frameStart        = inputStruct.frameShiftStart;
17
+        frameEnd          = inputStruct.frameShiftEnd;
18
+        psth              = inputStruct.rawTimeCourse;
19
+        SubjectID         = inputStruct.SubjectID;
20
+        smoothed          = inputStruct.smoothed;
21
+
22
+    otherwise
23
+        error('spmtoolbox:SVMCrossVal:plotDecodePerformance:WrongArgument','Wrong Arguments');
24
+end
25
+
26
+    f = figure;
27
+    subplot(2,1,1);
28
+    hold on;
29
+      for voxel = 1:size(psth,2)
30
+          for label = 1:size(psth{voxel},2)
31
+              psthData = [];
32
+              for timepoint = 1:size(psth{voxel}{label},2)
33
+                  psthData = nanmean(psth{voxel}{label});
34
+              end
35
+              plot(psthStart:psthEnd,psthData,[colorChooser(voxel), lineStyleChooser(label)]);
36
+          end
37
+      end
38
+    axis([psthStart psthEnd PSTH_AXIS_MIN PSTH_AXIS_MAX])
39
+    hold off
40
+    
41
+    subplot(2,1,2)    
42
+    hold on;
43
+    
44
+    chanceLevel = 100/nClasses;
45
+    goodPredictionLevel = chanceLevel*1.5;
46
+    plot([psthStart psthEnd],[chanceLevel chanceLevel],'r');
47
+    plot([psthStart psthEnd],[goodPredictionLevel goodPredictionLevel],'g');
48
+    axis([psthStart psthEnd 0 100])
49
+    
50
+    plot(frameStart:frameEnd, mean(decodePerformance,2) ,'b');
51
+    PLOT_STD_ERR = 1;
52
+    PLOT_CLASS_PERFORMANCE = 1;
53
+    if PLOT_STD_ERR 
54
+        se = myStdErr(decodePerformance,2);
55
+        plot(frameStart:frameEnd, mean(decodePerformance,2)+se ,'b:');
56
+        plot(frameStart:frameEnd, mean(decodePerformance,2)-se ,'b:');
57
+    end
58
+    if PLOT_CLASS_PERFORMANCE
59
+        for c = 1:nClasses
60
+            plot(frameStart:frameEnd, decodePerformance() ,[colorChooser(c+2) '-']);
61
+        end
62
+    end
63
+    
64
+    
65
+    hold off;
66
+
67
+    title = sprintf('Subject %s, over %g voxel, smoothed %s',SubjectID,size(psth,2),smoothed);
68
+    set(f,'Name',title);
69
+    display(sprintf('%s',title));
70
+
71
+
72
+
73
+end
74
+
75
+
76
+function color = colorChooser(n)
77
+    switch (mod(n,8))
78
+    case 0
79
+        color = 'y';
80
+    case 1
81
+        color = 'r';
82
+    case 2
83
+        color = 'b';
84
+    case 3
85
+        color = 'g';
86
+    otherwise
87
+        color = 'k';
88
+    end
89
+end
90
+
91
+function style = lineStyleChooser(n)
92
+switch(mod(n,4))
93
+    case 0
94
+      style = '--';
95
+    case 1
96
+        style = '-';
97
+    case 2 
98
+        style = ':';
99
+    case 3
100
+        style = '-.';
101
+end
102
+end
103
+
... ...
@@ -43,14 +43,28 @@ end
43 43
     
44 44
     chanceLevel = 100/nClasses;
45 45
     goodPredictionLevel = chanceLevel*1.5;
46
-    plot([psthStart psthEnd],[chanceLevel chanceLevel],'r');
47
-    plot([psthStart psthEnd],[goodPredictionLevel goodPredictionLevel],'g');
46
+    plot([psthStart psthEnd],[chanceLevel chanceLevel],'k:');
47
+    plot([psthStart psthEnd],[goodPredictionLevel goodPredictionLevel],'k:');
48 48
     axis([psthStart psthEnd 0 100])
49 49
     
50
+    
51
+    PLOT_EXTRAS = 'class performance'
52
+    
53
+    switch PLOT_EXTRAS
54
+        case 'stderr'
50 55
             plot(frameStart:frameEnd, mean(decodePerformance,2) ,'b');
56
+
51 57
             se = myStdErr(decodePerformance,2);
52 58
             plot(frameStart:frameEnd, mean(decodePerformance,2)+se ,'b:');
53 59
             plot(frameStart:frameEnd, mean(decodePerformance,2)-se ,'b:');
60
+        case 'class performance'
61
+            for c = 1:size(decodePerformance,2)
62
+                plot(frameStart:frameEnd, decodePerformance(:,c) ,[colorChooser(mod(c,nClasses)+3) '-']);
63
+            end
64
+
65
+            plot(frameStart:frameEnd, mean(decodePerformance,2) ,'b','LineWidth',2);
66
+
67
+    end
54 68
     
55 69
     
56 70
     hold off;
... ...
@@ -67,13 +81,17 @@ end
67 81
 function color = colorChooser(n)
68 82
     switch (mod(n,8))
69 83
     case 0
70
-        color = 'y';
71
-    case 1
72 84
         color = 'r';
85
+    case 1
86
+        color = 'g';
73 87
     case 2
74 88
         color = 'b';
75 89
     case 3
76
-        color = 'g';
90
+        color = 'c';
91
+    case 4
92
+        color = 'm';
93
+    case 5
94
+        color = 'y';
77 95
     otherwise
78 96
         color = 'k';
79 97
     end
... ...
@@ -59,33 +59,38 @@ maxPerformance = -inf;
59 59
                 svmlabel  = svmlabel(rndindex);
60 60
             end
61 61
 
62
-            SVM_METHOD = 2;
62
+            SVM_METHOD = 'class performance'
63 63
             switch SVM_METHOD;
64
-                case 1
64
+                case 'libsvm crossval'
65 65
                     performance  = svmtrain(svmlabel, svmdata, svmargs);
66 66
 
67 67
                     minPerformance = min(minPerformance,performance);
68 68
                     maxPerformance = max(maxPerformance,performance);
69 69
 
70 70
                     decodePerformance = [decodePerformance; performance];
71
-                case 2
71
+                case 'class performance'
72 72
                     newsvmopt = killCrossvalOpt(svmargs);
73 73
                     
74 74
                     model = svmtrain(svmlabel,svmdata,newsvmopt);
75 75
                     classperformance = [];
76 76
                     for class = unique(svmlabel)';
77
-%                         assignin('base','uniquelabel',unique(svmlabel));
78
-%                         assignin('base','class',class);
79
-%                         assignin('base','svmlabel',svmlabel);
77
+
80 78
                         filterindex = find(class == svmlabel);
81
-                        testing_label = svmlabel(filterindex)
82
-                        testing_data  = svmdata(filterindex)
83
-                        [plabel accuracy dvalue] = svmpredict(testing_label,testing_data,model,'')
84
-%                         assignin('base','accuracy',accuracy);
79
+                        testing_label = svmlabel(filterindex);
80
+                        testing_data  = svmdata(filterindex);
81
+                        [plabel accuracy dvalue] = svmpredict(testing_label,testing_data,model,'');
82
+
85 83
                         classperformance = [classperformance accuracy(1)];
86 84
                     end
87 85
                     decodePerformance = [decodePerformance; classperformance];
88 86
                     
87
+                case 'som training'
88
+                    display('SOM TRAINING');
89
+                    addpath 'somtoolbox2';
90
+                    sD = som_data_struct(svmdata);
91
+                    assignin('base','sD',sD);
92
+                    sM = som_make(sD,'msize', [3 4],'lattice', 'rect');
93
+                    
89 94
             end
90 95
             
91 96
         end
... ...
@@ -0,0 +1,196 @@
1
+% SOM Toolbox
2
+% Version 2.0beta, May 30 2002
3
+% 
4
+% Copyright 1997-2000 by
5
+% Esa Alhoniemi, Johan Himberg, Juha Parhankangas and Juha Vesanto
6
+% Contributed files may contain copyrights of their own.
7
+% 
8
+% SOM Toolbox comes with ABSOLUTELY NO WARRANTY; for details
9
+% see License.txt in the program package. This is free software,
10
+% and you are welcome to redistribute it under certain conditions;
11
+% see License.txt for details.
12
+% 
13
+% 
14
+% Demos
15
+% 
16
+%            som_demo1   SOM Toolbox demo 1: basic properties
17
+%            som_demo2   SOM Toolbox demo 2: basic usage
18
+%            som_demo3   SOM Toolbox demo 3: visualization
19
+%            som_demo4   SOM Toolbox demo 4: data analysis
20
+% 
21
+% Creation of structs
22
+% 
23
+%              som_set   create & set (& check) values to structs
24
+%             som_info   print out information on a given struct  
25
+%      som_data_struct   create & initialize a data struct 
26
+%       som_map_struct   create & initialize a map struct 
27
+%     som_topol_struct   create & initialize a topology struct 
28
+%     som_train_struct   create & initialize a train struct 
29
+%         som_clstruct   create a cluster struct
30
+%            som_clset   set properties in a cluster struct
31
+%            som_clget   get stuff from a cluster struct
32
+% 
33
+% Struct conversion and file I/O
34
+% 
35
+%           som_vs1to2   converts a version 1.0 struct to version 2.0 struct
36
+%           som_vs2to1   converts a version 2.0 struct to version 1.0 struct
37
+%        som_read_data   reads a (SOM_PAK format) ASCII data file
38
+%       som_write_data   writes a SOM_PAK format codebook file
39
+%        som_write_cod   writes a SOM_PAK format data file
40
+%         som_read_cod   reads a SOM_PAK format codebook file
41
+% 
42
+% Data preprocessing
43
+% 
44
+%        som_normalize   normalize data set
45
+%      som_denormalize   denormalize data set 
46
+%    som_norm_variable   (de)normalize one variable
47
+%           preprocess   preprocessing GUI
48
+% 
49
+% Initialization and training functions
50
+% 
51
+%             som_make   create, initialize and train a SOM
52
+%         som_randinit   random initialization algorithm
53
+%          som_lininit   linear initialization algorithm
54
+%         som_seqtrain   sequential training algorithm
55
+%       som_batchtrain   batch training algorithm
56
+%              som_gui   SOM initialization and training GUI
57
+%       som_prototrain   a simple version of sequential training: easy to modify
58
+% 
59
+% Clustering algorithms
60
+% 
61
+%           som_kmeans   k-means algorithm (was earlier kmeans)
62
+%      kmeans_clusters   try and evaluate several k-means clusterings
63
+%           neural_gas   neural gas vector quantization algorithm
64
+%          som_linkage   hierarchical clustering algorithms
65
+%        som_cllinkage   hierarchical clustering of SOM
66
+%       som_dmatminima   local minima from distance (or U-) matrix
67
+%     som_dmatclusters   distance (or U-) matrix based clustering
68
+%         som_clspread   spreads clusters to unassinged map units
69
+%           som_cldist   calculate distances between clusters
70
+%         som_gapindex   gap validity index of clustering
71
+%             db_index   Davies-Bouldin validity index of clustering  
72
+% 
73
+% Supervised/classification algorithms
74
+% 
75
+%       som_supervised   supervised SOM algorithm
76
+%                 lvq1   LVQ1 algorithm
77
+%                 lvq3   LVQ3 algorithm
78
+%                  knn   k-NN classification algorithm 
79
+%              knn_old   k-NN classification algorithm (old version)
80
+% 
81
+% SOM error measures
82
+% 
83
+%          som_quality   quantization and topographic error of SOM
84
+%       som_distortion   SOM distortion measure
85
+%      som_distortion3   elements of the SOM distortion measure
86
+% 
87
+% Auxiliary functions
88
+% 
89
+%             som_bmus   calculates BMUs for given data vectors
90
+%         som_eucdist2   pairwise squared euclidian distances between vectors
91
+%            som_mdist   calculates pairwise distances between vectors 
92
+%           som_divide   extract subsets of data based on map
93
+%            som_label   give labels to map units
94
+%        som_label2num   rcodes string data labels to interger class labels 
95
+%        som_autolabel   automatically labels the SOM based on given data
96
+%      som_unit_coords   calculates coordinates in output space for map units
97
+%       som_unit_dists   distances in output space between map units
98
+%      som_unit_neighs   units in 1-neighborhood for each map unit
99
+%     som_neighborhood   calculates neighborhood matrix for the given map
100
+%        som_neighbors   calculates different kinds of neighborhoods 
101
+%           som_neighf   calculates neighborhood function values
102
+%           som_select   GUI for manual selection of map units
103
+%     som_estimate_gmm   create Gaussian mixture model on top of SOM
104
+%  som_probability_gmm   evaluate Gaussian mixture model
105
+%          som_ind2sub   from linear index to subscript index 
106
+%          som_sub2ind   from subscript index to linear index
107
+%          som_ind2cod   from linear index to SOM_PAK linear index 
108
+%          som_cod2ind   from SOM_linear index to SOM_PAK linear index 
109
+%             nanstats   mean, std and median which ignore NaNs
110
+%   som_modify_dataset   add, remove, or extract samples and components
111
+%         som_fillnans   fill NaNs in a data set based on given SOM
112
+%            som_stats   statistics of a data set
113
+%           som_drmake   calculate descriptive rules for a cluster
114
+%           som_dreval   evaluate descriptive rules for a cluster
115
+%         som_drsignif   rule significance measures
116
+% 
117
+% Using SOM_PAK from Matlab
118
+% 
119
+%      som_sompaktrain   uses SOM_PAK to train a map
120
+%           sompak_gui   GUI for using SOM_PAK from Matlab
121
+%          sompak_init   call SOM_PAK's initialization programs from Matlab
122
+%      sompak_init_gui   GUI for using SOM_PAK's initialization from Matlab
123
+%    sompak_rb_control   an auxiliary function for sompak_*_gui functions.
124
+%        sompak_sammon   call SOM_PAK's Sammon program from Matlab
125
+%    sompak_sammon_gui   GUI for using SOM_PAK's Sammon program from Matlab
126
+%         sompak_train   call SOM_PAK's training program from Matlab
127
+%     sompak_train_gui   GUI for using SOM_PAK's training program from Matlab 
128
+% 
129
+% Visualization
130
+% 
131
+%             som_show   basic visualization
132
+%         som_show_add   add labels, hits and trajectories
133
+%       som_show_clear   remove extra markers
134
+%       som_recolorbar   refresh/reconfigure colorbars
135
+%         som_show_gui   GUI for using som_show and associated functions
136
+%             som_grid   visualization of SOM grid
137
+%           som_cplane   component planes and U-matrices
138
+%         som_barplane   bar chart visualization of map
139
+%         som_pieplane   pie chart visualization of map
140
+%        som_plotplane   plot chart visualization of map
141
+%       som_trajectory   launches a GUI for presenting comet-trajectories 
142
+%       som_dendrogram   visualization of clustering tree
143
+%       som_plotmatrix   pairwise scatter plots and histograms
144
+%    som_order_cplanes   order and visualize the component planes
145
+%           som_clplot   plots of clusters (based on cluster struct)
146
+% som_projections_plot   projections plots (see som_projections)
147
+%       som_stats_plot   plots of statistics (see som_stats)
148
+% 
149
+% Auxiliary functions for visualization
150
+% 
151
+%                 hits   calculates hits, or sum of values for each map unit
152
+%             som_hits   calculates the response of data on the map
153
+%             som_umat   calculates the U-matrix
154
+%                  cca   curvilinear component analysis projection algorithm
155
+%              pcaproj   principal component projection algorithm
156
+%               sammon   Sammon's mapping projection algorithm
157
+%       som_connection   connection matrix for map 
158
+%       som_vis_coords   map unit coordinates used in visualizations
159
+%        som_colorcode   create color coding for map/2D data
160
+%         som_bmucolor   colors of the BMUs from a given map color code
161
+%        som_normcolor   simulate indexed colormap
162
+%     som_clustercolor   color coding which depends on clustering structure
163
+%      som_kmeanscolor   color coding according to k-means clustering
164
+%     som_kmeanscolor2   a newer version of the som_kmeanscolor function
165
+%       som_fuzzycolor   a fuzzy color coding 
166
+%         som_coloring   a SOM-based color coding 
167
+%      som_projections   calculates a default set of projections
168
+% 
169
+% Report generation stuff
170
+% 
171
+%     som_table_struct   creates a table struct
172
+%     som_table_modify   modifies a table struct
173
+%      som_table_print   print a table in various formats
174
+%            rep_utils   various utilities for printing report elements
175
+%      som_stats_table   a table of data set statistics
176
+%     som_stats_report   report on data set statistics
177
+% 
178
+% Low level routines used by visualization functions
179
+% 
180
+%            vis_patch   defines hexagonal and rectangular patches
181
+%    vis_som_show_data   returns UserData and subplot handles stored by som_show.m
182
+%        vis_valuetype   used for type checks 
183
+%         vis_footnote   adds a movable text to the current figure 
184
+%          vis_trajgui   the actual GUI started by som_trajectory.m 
185
+% vis_PlaneAxisProperties   set axis properties in visualization functions
186
+% vis_footnoteButtonDownFcn   callback function for vis_footnote.m
187
+%     vis_planeGetArgs   converts topol struct to lattice, msize argument pair
188
+%    vis_show_gui_comp   internal function used by som_show_gui.m
189
+%    vis_show_gui_tool   internal function used by som_show_gui.m
190
+% 
191
+% Other
192
+% 
193
+%           somtoolbox   this file
194
+%            iris.data   IRIS data set (used in demos)
195
+%          License.txt   GNU General Public License 
196
+%        Copyright.txt   Copyright notice
... ...
@@ -0,0 +1,55 @@
1
+COPYRIGHT
2
+---------
3
+
4
+SOM Toolbox 2.0, a software library for Matlab 5 implementing the
5
+Self-Organizing Map algorithm is Copyright (C) 1999 by Esa Alhoniemi,
6
+Johan Himberg, Jukka Parviainen and Juha Vesanto.
7
+
8
+This package is free software; you can redistribute it and/or
9
+modify it under the terms of the GNU General Public License
10
+as published by the Free Software Foundation; either version 2
11
+of the License, or any later version.
12
+
13
+Note: only part of the files distributed in the package belong to the
14
+SOM Toolbox. The package also contains contributed files, which may
15
+have their own copyright notices. If not, the GNU General Public
16
+License holds for them, too, but so that the author(s) of the file
17
+have the Copyright.
18
+
19
+This package is distributed in the hope that it will be useful,
20
+but WITHOUT ANY WARRANTY; without even the implied warranty of
21
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
+GNU General Public License for more details.
23
+
24
+You should have received a copy of the GNU General Public License
25
+along with this package (file License.txt); if not, write to the Free
26
+Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27
+02111-1307, USA.
28
+
29
+
30
+LICENSING THE LIBRARY FOR PROPRIETARY PROGRAMS
31
+----------------------------------------------
32
+
33
+As stated in the GNU General Public License (see License.txt) it is
34
+not possible to include this software library in a commercial
35
+proprietary program without written permission from the owners of the
36
+copyright. If you wish to obtain such permission, you can reach us by
37
+paper mail:
38
+
39
+  SOM Toolbox team
40
+  Laboratory of Computer and Information Science
41
+  P.O.Box 5400
42
+  FIN-02015 HUT 
43
+  Finland
44
+  Europe 
45
+
46
+and by email:
47
+
48
+  somtlbx@mail.cis.hut.fi
49
+
50
+
51
+
52
+
53
+
54
+
55
+
... ...
@@ -0,0 +1,386 @@
1
+GNU GENERAL PUBLIC LICENSE
2
+
3
+Version 2, June 1991
4
+
5
+Copyright (C) 1989, 1991 Free Software Foundation, Inc.  
6
+59 Temple Place - Suite 330, Boston, MA  02111-1307, USA
7
+
8
+Everyone is permitted to copy and distribute verbatim copies
9
+of this license document, but changing it is not allowed.
10
+
11
+------------------------------------------------------------------------
12
+
13
+Preamble
14
+
15
+  The licenses for most software are designed to take away your
16
+freedom to share and change it.  By contrast, the GNU General Public
17
+License is intended to guarantee your freedom to share and change free
18
+software--to make sure the software is free for all its users.  This
19
+General Public License applies to most of the Free Software
20
+Foundation's software and to any other program whose authors commit to
21
+using it.  (Some other Free Software Foundation software is covered by
22
+the GNU Library General Public License instead.)  You can apply it to
23
+your programs, too.
24
+
25
+  When we speak of free software, we are referring to freedom, not
26
+price.  Our General Public Licenses are designed to make sure that you
27
+have the freedom to distribute copies of free software (and charge for
28
+this service if you wish), that you receive source code or can get it
29
+if you want it, that you can change the software or use pieces of it
30
+in new free programs; and that you know you can do these things.
31
+
32
+  To protect your rights, we need to make restrictions that forbid
33
+anyone to deny you these rights or to ask you to surrender the rights.
34
+These restrictions translate to certain responsibilities for you if you
35
+distribute copies of the software, or if you modify it.
36
+
37
+  For example, if you distribute copies of such a program, whether
38
+gratis or for a fee, you must give the recipients all the rights that
39
+you have.  You must make sure that they, too, receive or can get the
40
+source code.  And you must show them these terms so they know their
41
+rights.
42
+
43
+  We protect your rights with two steps: (1) copyright the software, and
44
+(2) offer you this license which gives you legal permission to copy,
45
+distribute and/or modify the software.
46
+
47
+  Also, for each author's protection and ours, we want to make certain
48
+that everyone understands that there is no warranty for this free
49
+software.  If the software is modified by someone else and passed on, we
50
+want its recipients to know that what they have is not the original, so
51
+that any problems introduced by others will not reflect on the original
52
+authors' reputations.
53
+
54
+  Finally, any free program is threatened constantly by software
55
+patents.  We wish to avoid the danger that redistributors of a free
56
+program will individually obtain patent licenses, in effect making the
57
+program proprietary.  To prevent this, we have made it clear that any
58
+patent must be licensed for everyone's free use or not licensed at all.
59
+
60
+  The precise terms and conditions for copying, distribution and
61
+modification follow.
62
+
63
+---------------------------------------------------------------------
64
+
65
+TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
66
+
67
+0.
68
+
69
+This License applies to any program or other work which contains a
70
+notice placed by the copyright holder saying it may be distributed
71
+under the terms of this General Public License.  The "Program", below,
72
+refers to any such program or work, and a "work based on the Program"
73
+means either the Program or any derivative work under copyright law:
74
+that is to say, a work containing the Program or a portion of it,
75
+either verbatim or with modifications and/or translated into another
76
+language.  (Hereinafter, translation is included without limitation in
77
+the term "modification".)  Each licensee is addressed as "you".
78
+
79
+Activities other than copying, distribution and modification are not
80
+covered by this License; they are outside its scope.  The act of
81
+running the Program is not restricted, and the output from the Program
82
+is covered only if its contents constitute a work based on the
83
+Program (independent of having been made by running the Program).
84
+Whether that is true depends on what the Program does.
85
+
86
+1.
87
+
88
+You may copy and distribute verbatim copies of the Program's source
89
+code as you receive it, in any medium, provided that you conspicuously
90
+and appropriately publish on each copy an appropriate copyright notice
91
+and disclaimer of warranty; keep intact all the notices that refer to
92
+this License and to the absence of any warranty; and give any other
93
+recipients of the Program a copy of this License along with the
94
+Program.
95
+
96
+You may charge a fee for the physical act of transferring a copy, and
97
+you may at your option offer warranty protection in exchange for a fee.
98
+
99
+2.
100
+
101
+You may modify your copy or copies of the Program or any portion of
102
+it, thus forming a work based on the Program, and copy and distribute
103
+such modifications or work under the terms of Section 1 above,
104
+provided that you also meet all of these conditions:
105
+
106
+a) You must cause the modified files to carry prominent notices
107
+   stating that you changed the files and the date of any change.
108
+
109
+b) You must cause any work that you distribute or publish, that in
110
+   whole or in part contains or is derived from the Program or any part
111
+   thereof, to be licensed as a whole at no charge to all third parties
112
+   under the terms of this License.
113
+
114
+c) If the modified program normally reads commands interactively when
115
+   run, you must cause it, when started running for such interactive use
116
+   in the most ordinary way, to print or display an announcement
117
+   including an appropriate copyright notice and a notice that there is
118
+   no warranty (or else, saying that you provide a warranty) and that
119
+   users may redistribute the program under these conditions, and telling
120
+   the user how to view a copy of this License.  (Exception: if the
121
+   Program itself is interactive but does not normally print such an
122
+   announcement, your work based on the Program is not required to print
123
+   an announcement.)
124
+
125
+These requirements apply to the modified work as a whole.  If
126
+identifiable sections of that work are not derived from the Program,
127
+and can be reasonably considered independent and separate works in
128
+themselves, then this License, and its terms, do not apply to those
129
+sections when you distribute them as separate works.  But when you
130
+distribute the same sections as part of a whole which is a work based
131
+on the Program, the distribution of the whole must be on the terms of
132
+this License, whose permissions for other licensees extend to the
133
+entire whole, and thus to each and every part regardless of who wrote
134
+it.
135
+
136
+Thus, it is not the intent of this section to claim rights or contest
137
+your rights to work written entirely by you; rather, the intent is to
138
+exercise the right to control the distribution of derivative or
139
+collective works based on the Program.
140
+
141
+In addition, mere aggregation of another work not based on the Program
142
+with the Program (or with a work based on the Program) on a volume of
143
+a storage or distribution medium does not bring the other work under
144
+the scope of this License.
145
+
146
+3.
147
+
148
+You may copy and distribute the Program (or a work based on it, under
149
+Section 2) in object code or executable form under the terms of
150
+Sections 1 and 2 above provided that you also do one of the following:
151
+
152
+a) Accompany it with the complete corresponding machine-readable
153
+   source code, which must be distributed under the terms of Sections 1
154
+   and 2 above on a medium customarily used for software interchange; or,
155
+
156
+b) Accompany it with a written offer, valid for at least three years,
157
+   to give any third party, for a charge no more than your cost of
158
+   physically performing source distribution, a complete machine-readable
159
+   copy of the corresponding source code, to be distributed under the
160
+   terms of Sections 1 and 2 above on a medium customarily used for
161
+   software interchange; or,
162
+
163
+c) Accompany it with the information you received as to the offer to
164
+   distribute corresponding source code.  (This alternative is allowed
165
+   only for noncommercial distribution and only if you received the
166
+   program in object code or executable form with such an offer, in
167
+   accord with Subsection b above.)
168
+
169
+The source code for a work means the preferred form of the work for
170
+making modifications to it.  For an executable work, complete source
171
+code means all the source code for all modules it contains, plus any
172
+associated interface definition files, plus the scripts used to
173
+control compilation and installation of the executable.  However, as a
174
+special exception, the source code distributed need not include
175
+anything that is normally distributed (in either source or binary
176
+form) with the major components (compiler, kernel, and so on) of the
177
+operating system on which the executable runs, unless that component
178
+itself accompanies the executable.
179
+
180
+If distribution of executable or object code is made by offering
181
+access to copy from a designated place, then offering equivalent
182
+access to copy the source code from the same place counts as
183
+distribution of the source code, even though third parties are not
184
+compelled to copy the source along with the object code.
185
+
186
+4.
187
+
188
+You may not copy, modify, sublicense, or distribute the Program except
189
+as expressly provided under this License.  Any attempt otherwise to
190
+copy, modify, sublicense or distribute the Program is void, and will
191
+automatically terminate your rights under this License.  However,
192
+parties who have received copies, or rights, from you under this
193
+License will not have their licenses terminated so long as such
194
+parties remain in full compliance.
195
+
196
+5.
197
+
198
+You are not required to accept this License, since you have not signed
199
+it.  However, nothing else grants you permission to modify or
200
+distribute the Program or its derivative works.  These actions are
201
+prohibited by law if you do not accept this License.  Therefore, by
202
+modifying or distributing the Program (or any work based on the
203
+Program), you indicate your acceptance of this License to do so, and
204
+all its terms and conditions for copying, distributing or modifying
205
+the Program or works based on it.
206
+
207
+6.
208
+
209
+Each time you redistribute the Program (or any work based on the
210
+Program), the recipient automatically receives a license from the
211
+original licensor to copy, distribute or modify the Program subject to
212
+these terms and conditions.  You may not impose any further
213
+restrictions on the recipients' exercise of the rights granted herein.
214
+You are not responsible for enforcing compliance by third parties to
215
+this License.
216
+
217
+7.
218
+
219
+If, as a consequence of a court judgment or allegation of patent
220
+infringement or for any other reason (not limited to patent issues),
221
+conditions are imposed on you (whether by court order, agreement or
222
+otherwise) that contradict the conditions of this License, they do not
223
+excuse you from the conditions of this License.  If you cannot
224
+distribute so as to satisfy simultaneously your obligations under this
225
+License and any other pertinent obligations, then as a consequence you
226
+may not distribute the Program at all.  For example, if a patent
227
+license would not permit royalty-free redistribution of the Program by
228
+all those who receive copies directly or indirectly through you, then
229
+the only way you could satisfy both it and this License would be to
230
+refrain entirely from distribution of the Program.
231
+
232
+If any portion of this section is held invalid or unenforceable under
233
+any particular circumstance, the balance of the section is intended to
234
+apply and the section as a whole is intended to apply in other
235
+circumstances.
236
+
237
+It is not the purpose of this section to induce you to infringe any
238
+patents or other property right claims or to contest validity of any
239
+such claims; this section has the sole purpose of protecting the
240
+integrity of the free software distribution system, which is
241
+implemented by public license practices.  Many people have made
242
+generous contributions to the wide range of software distributed
243
+through that system in reliance on consistent application of that
244
+system; it is up to the author/donor to decide if he or she is willing
245
+to distribute software through any other system and a licensee cannot
246
+impose that choice.
247
+
248
+This section is intended to make thoroughly clear what is believed to
249
+be a consequence of the rest of this License.
250
+
251
+8.
252
+
253
+If the distribution and/or use of the Program is restricted in certain
254
+countries either by patents or by copyrighted interfaces, the original
255
+copyright holder who places the Program under this License may add an
256
+explicit geographical distribution limitation excluding those
257
+countries, so that distribution is permitted only in or among
258
+countries not thus excluded.  In such case, this License incorporates
259
+the limitation as if written in the body of this License.
260
+
261
+9.
262
+
263
+The Free Software Foundation may publish revised and/or new versions
264
+of the General Public License from time to time.  Such new versions
265
+will be similar in spirit to the present version, but may differ in
266
+detail to address new problems or concerns.
267
+
268
+Each version is given a distinguishing version number.  If the Program
269
+specifies a version number of this License which applies to it and
270
+"any later version", you have the option of following the terms and
271
+conditions either of that version or of any later version published by
272
+the Free Software Foundation.  If the Program does not specify a
273
+version number of this License, you may choose any version ever
274
+published by the Free Software Foundation.
275
+
276
+10.
277
+
278
+If you wish to incorporate parts of the Program into other free
279
+programs whose distribution conditions are different, write to the
280
+author to ask for permission.  For software which is copyrighted by
281
+the Free Software Foundation, write to the Free Software Foundation;
282
+we sometimes make exceptions for this.  Our decision will be guided by
283
+the two goals of preserving the free status of all derivatives of our
284
+free software and of promoting the sharing and reuse of software
285
+generally.
286
+
287
+NO WARRANTY
288
+
289
+11.
290
+ 
291
+BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
292
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT
293
+WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER
294
+PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND,
295
+EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
296
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
297
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
298
+PROGRAM IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME
299
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
300
+
301
+12.
302
+
303
+IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
304
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
305
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR
306
+DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL
307
+DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM
308
+(INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED
309
+INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF
310
+THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER
311
+OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
312
+
313
+END OF TERMS AND CONDITIONS
314
+
315
+-----------------------------------------------------------------------
316
+
317
+How to Apply These Terms to Your New Programs 
318
+
319
+If you develop a new program, and you want it to be of the greatest
320
+possible use to the public, the best way to achieve this is to make it
321
+free software which everyone can redistribute and change under these
322
+terms.
323
+
324
+To do so, attach the following notices to the program.  It is safest
325
+to attach them to the start of each source file to most effectively
326
+convey the exclusion of warranty; and each file should have at least
327
+the "copyright" line and a pointer to where the full notice is found.
328
+
329
+one line to give the program's name and an idea of what it does.
330
+Copyright (C) 20<yy>  <name of author>
331
+
332
+This program is free software; you can redistribute it and/or modify
333
+it under the terms of the GNU General Public License as published by
334
+the Free Software Foundation; either version 2 of the License, or (at
335
+your option) any later version.
336
+
337
+This program is distributed in the hope that it will be useful, but
338
+WITHOUT ANY WARRANTY; without even the implied warranty of
339
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
340
+General Public License for more details.
341
+
342
+You should have received a copy of the GNU General Public License
343
+along with this program; if not, write to the Free Software
344
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
345
+USA. 
346
+
347
+Also add information on how to contact you by electronic and paper mail.
348
+
349
+If the program is interactive, make it output a short notice like this
350
+when it starts in an interactive mode:
351
+
352
+ Gnomovision version 69, Copyright (C) 20<yy> <name of author> 
353
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show
354
+ w'.  This is free software, and you are welcome to redistribute it
355
+ under certain conditions; type `show c' for details.  
356
+
357
+The hypothetical commands `show w' and `show c' should show the
358
+appropriate parts of the General Public License.  Of course, the
359
+commands you use may be called something other than `show w' and `show
360
+c'; they could even be mouse-clicks or menu items--whatever suits your
361
+program.
362
+
363
+You should also get your employer (if you work as a programmer) or
364
+your school, if any, to sign a "copyright disclaimer" for the program,
365
+if necessary.  Here is a sample; alter the names:
366
+
367
+ Yoyodyne, Inc., hereby disclaims all copyright
368
+ interest in the program `Gnomovision'
369
+ (which makes passes at compilers) written 
370
+ by James Hacker.
371
+
372
+ <signature of Ty Coon>, 1 April 1989
373
+ Ty Coon, President of Vice
374
+
375
+This General Public License does not permit incorporating your program
376
+into proprietary programs.  If your program is a subroutine library,
377
+you may consider it more useful to permit linking proprietary
378
+applications with the library.  If this is what you want to do, use
379
+the GNU Library General Public License instead of this License.
380
+
381
+FSF & GNU inquiries & questions to gnu@prep.ai.mit.edu.
382
+
383
+Copyright notice above.
384
+Free Software Foundation, Inc.,
385
+59 Temple Place - Suite 330, Boston, MA  02111,  USA
386
+
... ...
@@ -0,0 +1,282 @@
1
+function [P] = cca(D, P, epochs, Mdist, alpha0, lambda0)
2
+
3
+%CCA Projects data vectors using Curvilinear Component Analysis.
4
+%
5
+% P = cca(D, P, epochs, [Dist], [alpha0], [lambda0])
6
+%
7
+%  P = cca(D,2,10);           % projects the given data to a plane
8
+%  P = cca(D,pcaproj(D,2),5); % same, but with PCA initialization
9
+%  P = cca(D, 2, 10, Dist);   % same, but the given distance matrix is used
10
+%  
11
+%  Input and output arguments ([]'s are optional):
12
+%   D          (matrix) the data matrix, size dlen x dim
13
+%              (struct) data or map struct            
14
+%   P          (scalar) output dimension
15
+%              (matrix) size dlen x odim, the initial projection
16
+%   epochs     (scalar) training length
17
+%   [Dist]     (matrix) pairwise distance matrix, size dlen x dlen.
18
+%                       If the distances in the input space should
19
+%                       be calculated otherwise than as euclidian
20
+%                       distances, the distance from each vector
21
+%                       to each other vector can be given here,
22
+%                       size dlen x dlen. For example PDIST
23
+%                       function can be used to calculate the
24
+%                       distances: Dist = squareform(pdist(D,'mahal'));
25
+%   [alpha0]   (scalar) initial step size, 0.5 by default
26
+%   [lambda0]  (scalar) initial radius of influence, 3*max(std(D)) by default
27
+%  
28
+%   P          (matrix) size dlen x odim, the projections
29
+%
30
+% Unknown values (NaN's) in the data: projections of vectors with
31
+% unknown components tend to drift towards the center of the
32
+% projection distribution. Projections of totally unknown vectors are
33
+% set to unknown (NaN).
34
+%
35
+% See also SAMMON, PCAPROJ. 
36
+
37
+% Reference: Demartines, P., Herault, J., "Curvilinear Component
38
+%   Analysis: a Self-Organizing Neural Network for Nonlinear
39
+%   Mapping of Data Sets", IEEE Transactions on Neural Networks, 
40
+%   vol 8, no 1, 1997, pp. 148-154.
41
+
42
+% Contributed to SOM Toolbox 2.0, February 2nd, 2000 by Juha Vesanto
43
+% Copyright (c) by Juha Vesanto
44
+% http://www.cis.hut.fi/projects/somtoolbox/
45
+
46
+% juuso 171297 040100
47
+
48
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
49
+%% Check arguments 
50
+
51
+error(nargchk(3, 6, nargin)); % check the number of input arguments
52
+
53
+% input data
54
+if isstruct(D), 
55
+  if strcmp(D.type,'som_map'), D = D.codebook; else D = D.data; end
56
+end
57
+[noc dim] = size(D);
58
+noc_x_1  = ones(noc, 1); % used frequently
59
+me = zeros(1,dim); st = zeros(1,dim);
60
+for i=1:dim,
61
+  me(i) = mean(D(find(isfinite(D(:,i))),i));
62
+  st(i) = std(D(find(isfinite(D(:,i))),i));
63
+end
64
+
65
+% initial projection
66
+if prod(size(P))==1, 
67
+  P = (2*rand(noc,P)-1).*st(noc_x_1,1:P) + me(noc_x_1,1:P); 
68
+else
69
+  % replace unknown projections with known values
70
+  inds = find(isnan(P)); P(inds) = rand(size(inds));
71
+end
72
+[dummy odim] = size(P);
73
+odim_x_1  = ones(odim, 1); % this is used frequently
74
+
75
+% training length
76
+train_len = epochs*noc;
77
+
78
+% random sample order
79
+rand('state',sum(100*clock));
80
+sample_inds = ceil(noc*rand(train_len,1));
81
+
82
+% mutual distances
83
+if nargin<4 | isempty(Mdist) | all(isnan(Mdist(:))),
84
+  fprintf(2, 'computing mutual distances\r');
85
+  dim_x_1 = ones(dim,1);
86
+  for i = 1:noc,
87
+    x = D(i,:); 
88
+    Diff = D - x(noc_x_1,:);
89
+    N = isnan(Diff);
90
+    Diff(find(N)) = 0; 
91
+    Mdist(:,i) = sqrt((Diff.^2)*dim_x_1);
92
+    N = find(sum(N')==dim); %mutual distance unknown
93
+    if ~isempty(N), Mdist(N,i) = NaN; end
94
+  end
95
+else
96
+  % if the distance matrix is output from PDIST function
97
+  if size(Mdist,1)==1, Mdist = squareform(Mdist); end
98
+  if size(Mdist,1)~=noc, 
99
+    error('Mutual distance matrix size and data set size do not match'); 
100
+  end
101
+end
102
+
103
+% alpha and lambda
104
+if nargin<5 | isempty(alpha0) | isnan(alpha0), alpha0 = 0.5; end
105
+alpha = potency_curve(alpha0,alpha0/100,train_len);
106
+
107
+if nargin<6 | isempty(lambda0) | isnan(lambda0), lambda0 = max(st)*3; end
108
+lambda = potency_curve(lambda0,0.01,train_len);
109
+
110
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
111
+%% Action
112
+
113
+k=0; fprintf(2, 'iterating: %d / %d epochs\r',k,epochs);
114
+
115
+for i=1:train_len, 
116
+  
117
+  ind = sample_inds(i);     % sample index
118
+  dx = Mdist(:,ind);        % mutual distances in input space
119
+  known = find(~isnan(dx)); % known distances
120
+
121
+  if ~isempty(known),
122
+    % sample vector's projection
123
+    y = P(ind,:);                 
124
+
125
+    % distances in output space
126
+    Dy = P(known,:) - y(noc_x_1(known),:); 
127
+    dy = sqrt((Dy.^2)*odim_x_1);           
128
+  
129
+    % relative effect
130
+    dy(find(dy==0)) = 1;        % to get rid of div-by-zero's
131
+    fy = exp(-dy/lambda(i)) .* (dx(known) ./ dy - 1);
132
+
133
+    % Note that the function F here is e^(-dy/lambda)) 
134
+    % instead of the bubble function 1(lambda-dy) used in the 
135
+    % paper.
136
+    
137
+    % Note that here a simplification has been made: the derivatives of the
138
+    % F function have been ignored in calculating the gradient of error
139
+    % function w.r.t. to changes in dy.
140
+    
141
+    % update
142
+    P(known,:) = P(known,:) + alpha(i)*fy(:,odim_x_1).*Dy;
143
+  end
144
+
145
+  % track
146
+  if rem(i,noc)==0, 
147
+    k=k+1; fprintf(2, 'iterating: %d / %d epochs\r',k,epochs);
148
+  end
149
+
150
+end
151
+
152
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
153
+%% clear up
154
+
155
+% calculate error
156
+error = cca_error(P,Mdist,lambda(train_len));
157
+fprintf(2,'%d iterations, error %f          \n', epochs, error);
158
+
159
+% set projections of totally unknown vectors as unknown
160
+unknown = find(sum(isnan(D)')==dim);
161
+P(unknown,:) = NaN;
162
+
163
+return;
164
+
165
+
166
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
167
+%% tips
168
+
169
+% to plot the results, use the code below
170
+
171
+%subplot(2,1,1), 
172
+%switch(odim), 
173
+%  case 1, plot(P(:,1),ones(dlen,1),'x')
174
+%  case 2, plot(P(:,1),P(:,2),'x'); 
175
+%  otherwise, plot3(P(:,1),P(:,2),P(:,3),'x'); rotate3d on
176
+%end
177
+%subplot(2,1,2), dydxplot(P,Mdist);
178
+
179
+% to a project a new point x in the input space to the output space
180
+% do the following:
181
+
182
+% Diff = D - x(noc_x_1,:); Diff(find(isnan(Diff))) = 0; 
183
+% dx = sqrt((Diff.^2)*dim_x_1);
184
+% p = project_point(P,x,dx); % this function can be found from below
185
+% tlen = size(p,1);
186
+% plot(P(:,1),P(:,2),'bx',p(tlen,1),p(tlen,2),'ro',p(:,1),p(:,2),'r-')
187
+
188
+% similar trick can be made to the other direction
189
+
190
+
191
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
192
+%% subfunctions
193
+
194
+function vals = potency_curve(v0,vn,l)
195
+
196
+  % curve that decreases from v0 to vn with a rate that is 
197
+  % somewhere between linear and 1/t
198
+  vals = v0 * (vn/v0).^([0:(l-1)]/(l-1));
199
+
200
+
201
+function error = cca_error(P,Mdist,lambda)
202
+
203
+  [noc odim] = size(P);
204
+  noc_x_1 = ones(noc,1);
205
+  odim_x_1 = ones(odim,1);
206
+
207
+  error = 0;
208
+  for i=1:noc,
209
+    known = find(~isnan(Mdist(:,i)));
210
+    if ~isempty(known),   
211
+      y = P(i,:);                 
212
+      Dy = P(known,:) - y(noc_x_1(known),:);
213
+      dy = sqrt((Dy.^2)*odim_x_1);
214
+      fy = exp(-dy/lambda);
215
+      error = error + sum(((Mdist(known,i) - dy).^2).*fy);
216
+    end
217
+  end
218
+  error = error/2;
219
+
220
+
221
+function [] = dydxplot(P,Mdist)
222
+
223
+  [noc odim] = size(P);
224
+  noc_x_1 = ones(noc,1);
225
+  odim_x_1 = ones(odim,1);
226
+  Pdist = zeros(noc,noc);
227
+    
228
+  for i=1:noc,
229
+    y = P(i,:);                 
230
+    Dy = P - y(noc_x_1,:);
231
+    Pdist(:,i) = sqrt((Dy.^2)*odim_x_1);
232
+  end
233
+
234
+  Pdist = tril(Pdist,-1); 
235
+  inds = find(Pdist > 0); 
236
+  n = length(inds);
237
+  plot(Pdist(inds),Mdist(inds),'.');
238
+  xlabel('dy'), ylabel('dx')
239
+
240
+
241
+function p = project_point(P,x,dx)
242
+
243
+  [noc odim] = size(P);
244
+  noc_x_1 = ones(noc,1);
245
+  odim_x_1 = ones(odim,1);
246
+
247
+  % initial projection
248
+  [dummy,i] = min(dx);
249
+  y = P(i,:)+rand(1,odim)*norm(P(i,:))/20;
250
+ 
251
+  % lambda 
252
+  lambda = norm(std(P));
253
+
254
+  % termination
255
+  eps = 1e-3; i_max = noc*10;
256
+  
257
+  i=1; p(i,:) = y; 
258
+  ready = 0;
259
+  while ~ready,
260
+
261
+    % mutual distances
262
+    Dy = P - y(noc_x_1,:);        % differences in output space
263
+    dy = sqrt((Dy.^2)*odim_x_1);  % distances in output space
264
+    f = exp(-dy/lambda);
265
+  
266
+    fprintf(2,'iteration %d, error %g \r',i,sum(((dx - dy).^2).*f));
267
+
268
+    % all the other vectors push the projected one
269
+    fy = f .* (dx ./ dy - 1) / sum(f);
270
+  
271
+    % update    
272
+    step = - sum(fy(:,odim_x_1).*Dy);
273
+    y = y + step;
274
+  
275
+    i=i+1;
276
+    p(i,:) = y;   
277
+    ready = (norm(step)/norm(y) < eps | i > i_max);
278
+
279
+  end
280
+  fprintf(2,'\n');
281
+     
282
+  
0 283
\ No newline at end of file
... ...
@@ -0,0 +1,83 @@
1
+function [t,r] = db_index(D, cl, C, p, q)
2
+ 
3
+% DB_INDEX Davies-Bouldin clustering evaluation index.
4
+%
5
+% [t,r] = db_index(D, cl, C, p, q)
6
+%
7
+%  Input and output arguments ([]'s are optional):  
8
+%    D     (matrix) data (n x dim)
9
+%          (struct) map or data struct
10
+%    cl    (vector) cluster numbers corresponding to data samples (n x 1)
11
+%    [C]   (matrix) prototype vectors (c x dim) (default = cluster means)
12
+%    [p]   (scalar) norm used in the computation (default == 2)
13
+%    [q]   (scalar) moment used to calculate cluster dispersions (default = 2)
14
+% 
15
+%    t     (scalar) Davies-Bouldin index for the clustering (=mean(r))
16
+%    r     (vector) maximum DB index for each cluster (size c x 1)    
17
+% 
18
+% See also  KMEANS, KMEANS_CLUSTERS, SOM_GAPINDEX.
19
+
20
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
21
+%% input arguments
22
+
23
+if isstruct(D), 
24
+    switch D.type,
25
+    case 'som_map', D = D.codebook; 
26
+    case 'som_data', D = D.data; 
27
+    end
28
+end
29
+
30
+% cluster centroids
31
+[l dim] = size(D);
32
+u = unique(cl); 
33
+c = length(u); 
34
+if nargin <3, 
35
+  C = zeros(c,dim); 
36
+  for i=1:c, 
37
+      me = nanstats(D(find(cl==u(i)),:));
38
+      C(i,:) = me';
39
+  end 
40
+end
41
+
42
+u2i = zeros(max(u),1); u2i(u) = 1:c; 
43
+D = som_fillnans(D,C,u2i(cl)); % replace NaN's with cluster centroid values
44
+
45
+if nargin <4, p = 2; end % euclidian distance between cluster centers
46
+if nargin <5, q = 2; end % dispersion = standard deviation
47
+ 
48
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
49
+%% action
50
+
51
+% dispersion in each cluster 
52
+for i = 1:c
53
+  ind = find(cl==u(i)); % points in this cluster
54
+  l   = length(ind);
55
+  if l > 0
56
+    S(i) = (mean(sqrt(sum((D(ind,:) - ones(l,1) * C(i,:)).^2,2)).^q))^(1/q);
57
+  else
58
+    S(i) = NaN;
59
+  end
60
+end
61
+ 
62
+% distances between clusters
63
+%for i = 1:c
64
+%  for j = i+1:c
65
+%    M(i,j) = sum(abs(C(i,:) - C(j,:)).^p)^(1/p);
66
+%  end
67
+%end
68
+M = som_mdist(C,p); 
69
+
70
+% Davies-Bouldin index
71
+R = NaN * zeros(c);
72
+r = NaN * zeros(c,1);
73
+for i = 1:c
74
+  for j = i+1:c
75
+    R(i,j) = (S(i) + S(j))/M(i,j);
76
+  end
77
+  r(i) = max(R(i,:));
78
+end
79
+ 
80
+t = mean(r(isfinite(r)));
81
+ 
82
+return;                                                                                                     
83
+
... ...
@@ -0,0 +1,53 @@
1
+function [hits,ninvalid] = hits(bmus, mmax, values)
2
+
3
+%HITS Calculate number of occurances of each value.
4
+%
5
+% hits = hits(bmus,[mmax],[values])
6
+%
7
+%   h = hits(bmus);
8
+%   h = hits(bmus,length(sM.codebook)); 
9
+%
10
+%  Input and output arguments ([]'s are optional): 
11
+%   bmus     (vector) BMU indeces (or other similar) 
12
+%   [mmax]   (scalar) maximum index, default value max(bmus)
13
+%            (struct) map or topology struct from where the maximum
14
+%                     index is acquired
15
+%   [values] (vector) values associated with the data (default = 1)
16
+%
17
+%   hits     (vector) the number of occurances of each index
18
+%                     (or if values are given, their sum for each index)
19
+%   ninvalid (scalar) number of invalid indeces (NaN, Inf or 
20
+%                     <=0 or > mmax)
21
+%
22
+% See also SOM_HITS, SOM_BMUS.    
23
+
24
+% Copyright (c) 2002 by the SOM toolbox programming team.
25
+% Contributed to SOM Toolbox by Juha Vesanto, April 24th, 2002
26
+% http://www.cis.hut.fi/projects/somtoolbox/
27
+
28
+% Version 2.0beta juuso 240402
29
+
30
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
31
+
32
+if nargin<2 | isempty(mmax), 
33
+  mmax = max(bmus);
34
+elseif isstruct(mmax), 
35
+  switch mmax.type, 
36
+   case 'som_map',   mmax = prod(mmax.topol.msize);
37
+   case 'som_topol', mmax = prod(mmax.msize);
38
+   otherwise, 
39
+    error('Illegal struct for 2nd argument.')
40
+  end
41
+end
42
+
43
+if nargin<3, values = 1; end
44
+
45
+valid_bmus = find(isfinite(bmus) & bmus>0 & bmus<=mmax); 
46
+ninvalid = length(bmus)-length(valid_bmus); 
47
+
48
+bmus = bmus(valid_bmus); 
49
+if length(values)>length(bmus), values = values(valid_bmus); end
50
+hits = full(sum(sparse(bmus,1:length(bmus),values,mmax,length(bmus)),2));
51
+
52
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
53
+
... ...
@@ -0,0 +1,120 @@
1
+function [centers,clusters,errors,ind] = kmeans_clusters(sD, n_max, c_max, verbose)
2
+
3
+% KMEANS_CLUSTERS Clustering with k-means with different values for k.
4
+%
5
+% [c, p, err, ind] = kmeans_clusters(sD, [n_max], [c_max], [verbose])
6
+%
7
+%   [c, p, err, ind] = kmeans_clusters(sD);
8
+%  
9
+%  Input and output arguments ([]'s are optional):
10
+%   D         (struct) map or data struct
11
+%             (matrix) size dlen x dim, the data 
12
+%   [n_max]   (scalar) maximum number of clusters, default is sqrt(dlen)
13
+%   [c_max]   (scalar) maximum number of k-means runs, default is 5
14
+%   [verbose] (scalar) verbose level, 0 by default
15
+%
16
+%   c         (cell array) c{i} contains cluster centroids for k=i
17
+%   p         (cell array) p{i} contains cluster indeces for k=i
18
+%   err       (vector) squared sum of errors for each value of k
19
+%   ind       (vector) Davies-Bouldin index value for each clustering
20
+%
21
+% Makes a k-means to the given data set with different values of
22
+% k. The k-means is run multiple times for each k, and the best of
23
+% these is selected based on sum of squared errors. Finally, the
24
+% Davies-Bouldin index is calculated for each clustering. 
25
+%
26
+% For example to cluster a SOM: 
27
+%    [c, p, err, ind] = kmeans_clusters(sM); % find clusterings
28
+%    [dummy,i] = min(ind); % select the one with smallest index
29
+%    som_show(sM,'color',{p{i},sprintf('%d clusters',i)}); % visualize
30
+%    colormap(jet(i)), som_recolorbar % change colormap
31
+%  
32
+% See also SOM_KMEANS.
33
+
34
+% References: 
35
+%   Jain, A.K., Dubes, R.C., "Algorithms for Clustering Data", 
36
+%   Prentice Hall, 1988, pp. 96-101.
37
+%
38
+%   Davies, D.L., Bouldin, D.W., "A Cluster Separation Measure", 
39
+%   IEEE Transactions on Pattern Analysis and Machine Intelligence, 
40
+%   vol. PAMI-1, no. 2, 1979, pp. 224-227.
41
+%
42
+%   Vesanto, J., Alhoniemi, E., "Clustering of the Self-Organizing
43
+%   Map", IEEE Transactions on Neural Networks, 2000.
44
+
45
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Esa Alhoniemi
46
+% Copyright (c) by Esa Alhoniemi
47
+% http://www.cis.hut.fi/projects/somtoolbox/
48
+
49
+% ecco 301299 juuso 020200 211201
50
+
51
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
52
+%% input arguments and initialization
53
+
54
+if isstruct(sD), 
55
+  if isfield(sD,'data'), D = sD.data; 
56
+  else D = sD.codebook; 
57
+  end
58
+else D = sD; 
59
+end
60
+[dlen dim] = size(D);
61
+
62
+if nargin < 2 | isempty(n_max) | isnan(n_max), n_max = ceil(sqrt(dlen)); end
63
+if nargin < 3 | isempty(c_max) | isnan(c_max), c_max = 5; end
64
+if nargin < 4 | isempty(verbose) | isnan(verbose), verbose = 0; end
65
+
66
+centers   = cell(n_max,1); 
67
+clusters  = cell(n_max,1);
68
+ind       = zeros(1,n_max)+NaN;
69
+errors    = zeros(1,n_max)+NaN;
70
+
71
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
72
+%% action
73
+
74
+% the case k=1 is trivial, but Davies-Boulding index cannot be evaluated
75
+m = zeros(1,dim);
76
+for i=1:dim, m(i)=mean(D(isfinite(D(:,i)),i)); end
77
+centers{1} = m;
78
+clusters{1} = ones(dlen,1);
79
+[dummy qerr] = som_bmus(m,D);
80
+errors(1) = sum(qerr.^2);
81
+ind(1) = NaN; 
82
+
83
+if verbose, fprintf(2,'Doing k-means for 2-%d clusters\n',n_max); end
84
+
85
+for i = 2:n_max, % number of clusters
86
+
87
+  % make k-means with k=i for c_max times and select the best based
88
+  % on sum-of-squared errors (SSE)
89
+  best = realmax;  
90
+  for j = 1:c_max     % run number j for cluster i      
91
+    if verbose,
92
+      fprintf('%d/%d clusters, k-means run %d/%d\r', i, n_max,j, c_max);
93
+    end      
94
+    [c, k, err] = som_kmeans('batch', D, i, 100, 0);
95
+    if err < best, k_best = k'; c_best = c; best = err; end
96
+    % ' added in k_best = k'; by kr 1.10.02
97
+  end
98
+  if verbose, fprintf(1, '\n');  end
99
+
100
+  % store the results  
101
+  centers{i}  = c_best;
102
+  clusters{i} = k_best;
103
+  errors(i)   = best;
104
+%  ind(i)      = db_index(D, c_best, k_best, 2); wrong version in somtbx ??
105
+  ind(i)      = db_index(D, k_best, c_best, 2); % modified by kr 1.10.02
106
+
107
+  % if verbose mode, plot the index & SSE
108
+  if verbose
109
+    subplot(2,1,1), plot(ind), grid
110
+    title('Davies-Bouldin''s index')
111
+    subplot(2,1,2), plot(errors), grid
112
+    title('SSE')
113
+    drawnow
114
+  end
115
+end
116
+
117
+return; 
118
+
119
+
120
+
... ...
@@ -0,0 +1,158 @@
1
+function [C,P]=knn(d, Cp, K)
2
+
3
+%KNN K-Nearest Neighbor classifier using an arbitrary distance matrix
4
+%
5
+%  [C,P]=knn(d, Cp, [K])
6
+%
7
+%  Input and output arguments ([]'s are optional): 
8
+%   d     (matrix) of size NxP: This is a precalculated dissimilarity (distance matrix).
9
+%           P is the number of prototype vectors and N is the number of data vectors
10
+%           That is, d(i,j) is the distance between data item i and prototype j.
11
+%   Cp    (vector) of size Px1 that contains integer class labels. Cp(j) is the class of 
12
+%            jth prototype.
13
+%   [K]   (scalar) the maximum K in K-NN classifier, default is 1
14
+%   C     (matrix) of size NxK: integers indicating the class 
15
+%           decision for data items according to the K-NN rule for each K.
16
+%           C(i,K) is the classification for data item i using the K-NN rule
17
+%   P     (matrix) of size NxkxK: the relative amount of prototypes of 
18
+%           each class among the K closest prototypes for each classifiee. 
19
+%           That is, P(i,j,K) is the relative amount of prototypes of class j 
20
+%           among K nearest prototypes for data item i.
21
+%
22
+% If there is a tie between representatives of two or more classes
23
+% among the K closest neighbors to the classifiee, the class i selected randomly 
24
+% among these candidates.
25
+%
26
+% IMPORTANT  If K>1 this function uses 'sort' which is considerably slower than 
27
+%            'max' which is used for K=1. If K>1 the knn always calculates 
28
+%            results for all K-NN models from 1-NN up to K-NN.   
29
+%
30
+% EXAMPLE 1 
31
+%
32
+% sP;                           % a SOM Toolbox data struct containing labeled prototype vectors
33
+% [Cp,label]=som_label2num(sP); % get integer class labels for prototype vectors                 
34
+% sD;                           % a SOM Toolbox data struct containing vectors to be classified
35
+% d=som_eucdist2(sD,sP);        % calculate euclidean distance matrix
36
+% class=knn(d,Cp,10);           % classify using 1,2,...,10-rules
37
+% class(:,5);                   % includes results for 5NN 
38
+% label(class(:,5))             % original class labels for 5NN
39
+%
40
+% EXAMPLE 2 (leave-one-out-crossvalidate KNN for selection of proper K)
41
+%
42
+% P;                          % a data matrix of prototype vectors (rows)
43
+% Cp;                         % column vector of integer class labels for vectors in P 
44
+% d=som_eucdist2(P,P);        % calculate euclidean distance matrix PxP
45
+% d(eye(size(d))==1)=NaN;     % set self-dissimilarity to NaN:
46
+%                             % this drops the prototype itself away from its neighborhood 
47
+%                             % leave-one-out-crossvalidation (LOOCV)
48
+% class=knn(d,Cp,size(P,1));  % classify using all possible K
49
+%                             % calculate and plot LOOC-validated errors for all K
50
+% failratep = ...
51
+%  100*sum((class~=repmat(Cp,1,size(P,1))))./size(P,1); plot(1:size(P,1),failratep) 
52
+
53
+% See also SOM_LABEL2NUM, SOM_EUCDIST2, PDIST. 
54
+%
55
+% Contributed to SOM Toolbox 2.0, October 29th, 2000 by Johan Himberg
56
+% Copyright (c) by Johan Himberg
57
+% http://www.cis.hut.fi/projects/somtoolbox/
58
+
59
+% Version 2.0beta Johan 291000
60
+
61
+%% Init %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
62
+
63
+% Check K 
64
+if nargin<3 | isempty(K),
65
+  K=1;
66
+end
67
+
68
+if ~vis_valuetype(K,{'1x1'})
69
+  error('Value for K must be a scalar');
70
+end
71
+
72
+% Check that dist is a matrix
73
+if ~vis_valuetype(d,{'nxm'}),
74
+  error('Distance matrix not valid.')
75
+end
76
+
77
+[N_data N_proto]=size(d);
78
+
79
+% Check class label vector: must be numerical and of integers
80
+if ~vis_valuetype(Cp,{[N_proto 1]});
81
+  error(['Class vector is invalid: has to be a N-of-data_rows x 1' ...
82
+	 ' vector of integers']);
83
+elseif sum(fix(Cp)-Cp)~=0
84
+  error('Class labels in vector ''Cp'' must be integers.');
85
+end
86
+
87
+if size(d,2) ~= length(Cp),
88
+  error('Distance matrix and prototype class vector dimensions do not match.');
89
+end
90
+
91
+% Check if the classes are given as labels (no class input arg.)
92
+% if they are take them from prototype struct
93
+
94
+% Find all class labels
95
+ClassIndex=unique(Cp);
96
+N_class=length(ClassIndex); % number of different classes  
97
+
98
+
99
+%%%% Classification %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
100
+
101
+if K==1,   % sort distances only if K>1
102
+  
103
+  % 1NN
104
+  % Select the closest prototype
105
+  [tmp,proto_index]=min(d,[],2); 
106
+  C=Cp(proto_index);
107
+
108
+else 
109
+  
110
+  % Sort the prototypes for each classifiee according to distance
111
+  [tmp, proto_index]=sort(d');
112
+  
113
+  %% Select up to K closest prototypes
114
+  proto_index=proto_index(1:K,:);
115
+  knn_class=Cp(proto_index);
116
+  for i=1:N_class,
117
+    classcounter(:,:,i)=cumsum(knn_class==ClassIndex(i));
118
+  end
119
+  
120
+  %% Vote between classes of K neighbors 
121
+  [winner,vote_index]=max(classcounter,[],3);
122
+  
123
+  %%% Handle ties
124
+  
125
+  % Set index to classes that got as much votes as winner
126
+  
127
+  equal_to_winner=(repmat(winner,[1 1 N_class])==classcounter);
128
+ 
129
+  % set index to ties
130
+  [tie_indexi,tie_indexj]=find(sum(equal_to_winner,3)>1); % drop the winner from counter 
131
+  
132
+  % Go through tie cases and reset vote_index randomly to one
133
+  % of them 
134
+  
135
+  for i=1:length(tie_indexi),
136
+    tie_class_index=find(squeeze(equal_to_winner(tie_indexi(i),tie_indexj(i),:)));
137
+    fortuna=randperm(length(tie_class_index));
138
+    vote_index(tie_indexi(i),tie_indexj(i))=tie_class_index(fortuna(1));
139
+  end
140
+  
141
+  C=ClassIndex(vote_index)';
142
+end
143
+
144
+%% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
145
+
146
+% Relative amount of classes in K neighbors for each classifiee
147
+
148
+if K==1,
149
+  P=zeros(N_data,N_class);
150
+  if nargout>1,
151
+    for i=1:N_data,
152
+      P(i,ClassIndex==C(i))=1;
153
+    end
154
+  end
155
+else
156
+  P=shiftdim(classcounter,1)./repmat(shiftdim(1:K,-1), [N_data N_class 1]);
157
+end
158
+
... ...
@@ -0,0 +1,251 @@
1
+function [Class,P]=knn_old(Data, Proto, proto_class, K)
2
+
3
+%KNN_OLD A K-nearest neighbor classifier using Euclidean distance 
4
+%
5
+% [Class,P]=knn_old(Data, Proto, proto_class, K)
6
+%
7
+%  [sM_class,P]=knn_old(sM, sData, [], 3);
8
+%  [sD_class,P]=knn_old(sD, sM, class);
9
+%  [class,P]=knn_old(data, proto, class);
10
+%  [class,P]=knn_old(sData, sM, class,5);
11
+%
12
+%  Input and output arguments ([]'s are optional): 
13
+%   Data   (matrix) size Nxd, vectors to be classified (=classifiees)
14
+%          (struct) map or data struct: map codebook vectors or
15
+%                   data vectors are considered as classifiees.
16
+%   Proto  (matrix) size Mxd, prototype vector matrix (=prototypes)
17
+%          (struct) map or data struct: map codebook vectors or
18
+%                   data vectors are considered as prototypes.
19
+%   [proto_class] (vector) size Nx1, integers 1,2,...,k indicating the
20
+%                   classes of corresponding protoptypes, default: see the 
21
+%                   explanation below. 
22
+%   [K]    (scalar) the K in KNN classifier, default is 1
23
+% 
24
+%   Class  (matrix) size Nx1, vector of 1,2, ..., k indicating the class 
25
+%                   desicion according to the KNN rule
26
+%   P      (matrix) size Nxk, the relative amount of prototypes of 
27
+%                   each class among the K closest prototypes for
28
+%                   each classifiee.
29
+%
30
+% If 'proto_class' is _not_ given, 'Proto' _must_ be a labeled SOM
31
+% Toolbox struct. The label of the data vector or the first label of
32
+% the map model vector is considered as class label for th prototype
33
+% vector. In this case the output 'Class' is a copy of 'Data' (map or
34
+% data struct) relabeled according to the classification.  If input
35
+% argument 'proto_class' _is_ given, the output argument 'Class' is
36
+% _always_ a vector of integers 1,2,...,k indiacating the class.
37
+%
38
+% If there is a tie between representatives of two or more classes
39
+% among the K closest neighbors to the classifiee, the class is
40
+% selected randomly among these candidates.
41
+%
42
+% IMPORTANT
43
+% 
44
+% ** Even if prototype vectors are given in a map struct the mask _is not 
45
+%    taken into account_ when calculating Euclidean distance
46
+% ** The function calculates the total distance matrix between all
47
+%    classifiees and prototype vectors. This results to an MxN matrix; 
48
+%    if N is high it is recommended to divide the matrix 'Data'
49
+%    (the classifiees) into smaller sets in order to avoid memory
50
+%    overflow or swapping. Also, if K>1 this function uses 'sort' which is
51
+%    considerably slower than 'max' which is used for K==1.
52
+%
53
+% See also KNN, SOM_LABEL, SOM_AUTOLABEL
54
+
55
+% Contributed to SOM Toolbox 2.0, February 11th, 2000 by Johan Himberg
56
+% Copyright (c) by Johan Himberg
57
+% http://www.cis.hut.fi/projects/somtoolbox/
58
+
59
+% Version 2.0beta Johan 040200
60
+
61
+%% Init %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
62
+% This must exist later
63
+classnames='';
64
+
65
+% Check K 
66
+if nargin<4 | isempty(K),
67
+  K=1;
68
+end
69
+
70
+if ~vis_valuetype(K,{'1x1'})
71
+  error('Value for K must be a scalar.');
72
+end
73
+
74
+% Take data from data or map struct
75
+
76
+if isstruct(Data);
77
+  if isfield(Data,'type') & ischar(Data.type),
78
+    ;
79
+  else
80
+    error('Invalid map/data struct?');
81
+  end
82
+  switch Data.type
83
+   case 'som_map'
84
+    data=Data.codebook;
85
+   case 'som_data'
86
+    data=Data.data;
87
+  end
88
+else
89
+  % is already a matrix
90
+  data=Data;
91
+end
92
+
93
+% Take prototype vectors from prototype struct
94
+
95
+if isstruct(Proto),
96
+  
97
+  if isfield(Proto,'type') & ischar(Proto.type),
98
+    ;
99
+  else
100
+    error('Invalid map/data struct?');
101
+  end
102
+  switch Proto.type
103
+   case 'som_map'
104
+    proto=Proto.codebook;
105
+   case 'som_data'
106
+    proto=Proto.data;
107
+  end
108
+else
109
+  % is already a matrix
110
+  proto=Proto; 
111
+end
112
+
113
+% Check that inputs are matrices
114
+if ~vis_valuetype(proto,{'nxm'}) | ~vis_valuetype(data,{'nxm'}),
115
+  error('Prototype or data input not valid.')
116
+end
117
+
118
+% Record data&proto sizes and check their dims 
119
+[N_data dim_data]=size(data); 
120
+[N_proto dim_proto]=size(proto);
121
+if dim_proto ~= dim_data,
122
+  error('Data and prototype vector dimension does not match.');
123
+end
124
+
125
+% Check if the classes are given as labels (no class input arg.)
126
+% if they are take them from prototype struct
127
+
128
+if nargin<3 | isempty(proto_class)
129
+  if ~isstruct(Proto)
130
+    error(['If prototypes are not in labeled map or data struct' ...
131
+	   'class must be given.']);  
132
+    % transform to interger (numerical) class labels
133
+  else
134
+    [proto_class,classnames]=class2num(Proto.labels); 
135
+  end
136
+end
137
+
138
+% Check class label vector: must be numerical and of integers
139
+if ~vis_valuetype(proto_class,{[N_proto 1]});
140
+  error(['Class vector is invalid: has to be a N-of-data_rows x 1' ...
141
+	 ' vector of integers']);
142
+elseif sum(fix(proto_class)-proto_class)~=0
143
+  error('Class labels in vector ''Class'' must be integers.');
144
+end
145
+
146
+% Find all class labels
147
+ClassIndex=unique(proto_class);
148
+N_class=length(ClassIndex); % number of different classes  
149
+
150
+% Calculate euclidean distances between classifiees and prototypes
151
+d=distance(proto,data);
152
+
153
+%%%% Classification %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
154
+
155
+if K==1,   % sort distances only if K>1
156
+  
157
+  % 1NN
158
+  % Select the closest prototype
159
+  [tmp,proto_index]=min(d);
160
+  class=proto_class(proto_index);
161
+
162
+else 
163
+  
164
+  % Sort the prototypes for each classifiee according to distance
165
+  [tmp,proto_index]=sort(d);
166
+  
167
+  %% Select K closest prototypes
168
+  proto_index=proto_index(1:K,:);
169
+  knn_class=proto_class(proto_index);
170
+  for i=1:N_class,
171
+    classcounter(i,:)=sum(knn_class==ClassIndex(i));
172
+  end
173
+  
174
+  %% Vote between classes of K neighbors 
175
+  [winner,vote_index]=max(classcounter);
176
+  
177
+  %% Handle ties
178
+  
179
+  % set index to clases that got as amuch votes as winner
180
+  
181
+  equal_to_winner=(repmat(winner,N_class,1)==classcounter);
182
+  
183
+  % set index to ties
184
+  tie_index=find(sum(equal_to_winner)>1); % drop the winner from counter 
185
+  
186
+  % Go through equal classes and reset vote_index randomly to one
187
+  % of them 
188
+  
189
+  for i=1:length(tie_index),
190
+    tie_class_index=find(equal_to_winner(:,tie_index(i)));
191
+    fortuna=randperm(length(tie_class_index));
192
+    vote_index(tie_index(i))=tie_class_index(fortuna(1));
193
+  end
194
+  
195
+  class=ClassIndex(vote_index);
196
+end
197
+
198
+%% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
199
+
200
+% Relative amount of classes in K neighbors for each classifiee
201
+
202
+if K==1,
203
+  P=zeros(N_data,N_class);
204
+  if nargout>1,
205
+    for i=1:N_data,
206
+      P(i,ClassIndex==class(i))=1;
207
+    end
208
+  end
209
+else
210
+  P=classcounter'./K;
211
+end
212
+
213
+% xMake class names to struct if they exist
214
+if ~isempty(classnames),
215
+  Class=Data;
216
+  for i=1:N_data,
217
+    Class.labels{i,1}=classnames{class(i)};
218
+  end
219
+else
220
+  Class=class;
221
+end
222
+
223
+
224
+%%% Subfunctions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
225
+
226
+function [nos,names] = class2num(class)
227
+
228
+% Change string labels in map/data struct to integer numbers
229
+
230
+names = {};
231
+nos = zeros(length(class),1);
232
+for i=1:length(class)
233
+  if ~isempty(class{i}) & ~any(strcmp(class{i},names))
234
+    names=cat(1,names,class(i));
235
+  end
236
+end
237
+
238
+tmp_nos = (1:length(names))';
239
+for i=1:length(class)
240
+  if ~isempty(class{i})
241
+    nos(i,1) = find(strcmp(class{i},names));    
242
+  end
243
+end
244
+
245
+function d=distance(X,Y);
246
+
247
+% Euclidean distance matrix between row vectors in X and Y
248
+
249
+U=~isnan(Y); Y(~U)=0;
250
+V=~isnan(X); X(~V)=0;
251
+d=X.^2*U'+V*Y'.^2-2*X*Y';
... ...
@@ -0,0 +1,180 @@
1
+function codebook=lvq1(codebook, data, rlen, alpha);
2
+
3
+%LVQ1 Trains a codebook with the LVQ1 -algorithm.
4
+%
5
+%  sM = lvq1(sM, D, rlen, alpha)
6
+%
7
+%   sM = lvq1(sM,sD,30*length(sM.codebook),0.08);
8
+%
9
+%  Input and output arguments: 
10
+%   sM    (struct) map struct, the class information must be 
11
+%                  present on the first column of .labels field
12
+%   D     (struct) data struct, the class information must
13
+%                  be present on the first column of .labels field
14
+%   rlen  (scalar) running length
15
+%   alpha (scalar) learning parameter
16
+%
17
+%   sM    (struct) map struct, the trained codebook
18
+%
19
+% NOTE: does not take mask into account.
20
+% 
21
+% For more help, try 'type lvq1', or check out online documentation. 
22
+% See also LVQ3, SOM_SUPERVISED, SOM_SEQTRAIN.
23
+
24
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
25
+%
26
+% lvq1
27
+%
28
+% PURPOSE
29
+%
30
+% Trains codebook with the LVQ1 -algorithm (described below).
31
+%
32
+% SYNTAX
33
+%
34
+%  sM = lvq1(sM, D, rlen, alpha)
35
+%
36
+% DESCRIPTION
37
+%
38
+% Trains codebook with the LVQ1 -algorithm. Codebook contains a number
39
+% of vectors (mi, i=1,2,...,n) and so does data (vectors xj,
40
+% j=1,2,...,k).  Both vector sets are classified: vectors may have a
41
+% class (classes are set to the first column of data or map -structs'
42
+% .labels -field). For each xj there is defined the nearest codebook
43
+% -vector index c by searching the minimum of the euclidean distances
44
+% between the current xj and codebook -vectors:
45
+%
46
+%    c = min{ ||xj - mi|| },  i=[1,..,n], for fixed xj
47
+%         i
48
+% If xj and mc belong to the same class, mc is updated as follows:
49
+%    mc(t+1) = mc(t) + alpha * (xj(t) - mc(t))
50
+% If xj and mc belong to different classes, mc is updated as follows:
51
+%    mc(t+1) = mc(t) - alpha * (xj(t) - mc(t))
52
+% Otherwise updating is not performed.
53
+% 
54
+% Argument 'rlen' tells how many times training sequence is performed.
55
+% LVQ1 -algorithm may be stopped after a number of steps, that is
56
+% 30-50 times the number of codebook vectors.
57
+%
58
+% Argument 'alpha' is the learning rate, recommended to be smaller
59
+% than 0.1.
60
+%
61
+% NOTE: does not take mask into account.
62
+%
63
+% REFERENCES
64
+%
65
+% Kohonen, T., "Self-Organizing Map", 2nd ed., Springer-Verlag, 
66
+%    Berlin, 1995, pp. 176-179.
67
+%
68
+% See also LVQ_PAK from http://www.cis.hut.fi/research/som_lvq_pak.shtml
69
+%   
70
+% REQUIRED INPUT ARGUMENTS
71
+%
72
+%  sM                The data to be trained.
73
+%          (struct)  A map struct.
74
+%
75
+%  D                 The data to use in training.
76
+%          (struct)  A data struct.
77
+%
78
+%  rlen    (integer) Running length of LVQ1 -algorithm.
79
+%                    
80
+%  alpha   (float)   Learning rate used in training.
81
+%
82
+% OUTPUT ARGUMENTS
83
+%
84
+%  codebook          Trained data.
85
+%          (struct)  A map struct.
86
+%
87
+% EXAMPLE
88
+%
89
+%   lab = unique(sD.labels(:,1));         % different classes
90
+%   mu = length(lab)*5;                   % 5 prototypes for each    
91
+%   sM = som_randinit(sD,'msize',[mu 1]); % initial prototypes
92
+%   sM.labels = [lab;lab;lab;lab;lab];    % their classes
93
+%   sM = lvq1(sM,sD,50*mu,0.05);          % use LVQ1 to adjust
94
+%                                         % the prototypes      
95
+%   sM = lvq3(sM,sD,50*mu,0.05,0.2,0.3);  % then use LVQ3 
96
+%
97
+% SEE ALSO
98
+% 
99
+%  lvq3             Use LVQ3 algorithm for training.
100
+%  som_supervised   Train SOM using supervised training.
101
+%  som_seqtrain     Train SOM with sequential algorithm.
102
+
103
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Parhankangas
104
+% Copyright (c) Juha Parhankangas
105
+% http://www.cis.hut.fi/projects/somtoolbox/
106
+
107
+% Juha Parhankangas 310100 juuso 020200
108
+
109
+cod = codebook.codebook;
110
+c_class = class2num(codebook.labels(:,1));
111
+
112
+dat = data.data;
113
+d_class = class2num(data.labels(:,1));
114
+
115
+x=size(dat,1);
116
+y=size(cod,2);
117
+
118
+ONES=ones(size(cod,1),1);
119
+
120
+for t=1:rlen
121
+
122
+  fprintf(1,'\rTraining round: %d',t);
123
+  tmp=NaN*ones(x,y);
124
+
125
+  for j=1:x
126
+    no_NaN=find(~isnan(dat(j,:)));
127
+    di = sqrt(sum([cod(:,no_NaN)  - ONES*dat(j,no_NaN)].^2,2));
128
+
129
+    [foo,ind] = min(di);
130
+
131
+    if d_class(j) & d_class(j) == c_class(ind) % 0 is for unclassified vectors
132
+      tmp(ind,:) = cod(ind,:) + alpha * (dat(j,:) - cod(ind,:));
133
+    elseif d_class(j)
134
+      tmp(ind,:) = cod(ind,:) - alpha*(dat(j,:) - cod(ind,:));
135
+    end
136
+  end
137
+
138
+  inds = find(~isnan(sum(tmp,2)));
139
+  cod(inds,:) = tmp(inds,:);
140
+end
141
+
142
+codebook.codebook = cod;
143
+
144
+sTrain = som_set('som_train','algorithm','lvq1',...
145
+		 'data_name',data.name,...
146
+		 'neigh','',...
147
+		 'mask',ones(y,1),...
148
+		 'radius_ini',NaN,...
149
+		 'radius_fin',NaN,...
150
+		 'alpha_ini',alpha,...
151
+		 'alpha_type','constant',...
152
+		 'trainlen',rlen,...
153
+		 'time',datestr(now,0));
154
+codebook.trainhist(end+1) = sTrain;
155
+
156
+return;
157
+
158
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
159
+
160
+function nos = class2num(class)
161
+
162
+names = {};
163
+nos = zeros(length(class),1);
164
+
165
+for i=1:length(class)
166
+  if ~isempty(class{i}) & ~any(strcmp(class{i},names))
167
+    names=cat(1,names,class(i));
168
+  end
169
+end
170
+
171
+tmp_nos = (1:length(names))';
172
+
173
+for i=1:length(class)
174
+  if ~isempty(class{i})
175
+    nos(i,1) = find(strcmp(class{i},names));    
176
+  end
177
+end
178
+
179
+
180
+
... ...
@@ -0,0 +1,215 @@
1
+function codebook = lvq3(codebook,data,rlen,alpha,win,epsilon)
2
+
3
+%LVQ3 trains codebook with LVQ3 -algorithm
4
+%
5
+% sM = lvq3(sM,D,rlen,alpha,win,epsilon)
6
+%
7
+%   sM = lvq3(sM,sD,50*length(sM.codebook),0.05,0.2,0.3);
8
+%
9
+%  Input and output arguments: 
10
+%   sM      (struct) map struct, the class information must be 
11
+%                    present on the first column of .labels field
12
+%   D       (struct) data struct, the class information must
13
+%                    be present on the first column of .labels field
14
+%   rlen    (scalar) running length
15
+%   alpha   (scalar) learning parameter, e.g. 0.05
16
+%   win     (scalar) window width parameter, e.g. 0.25
17
+%   epsilon (scalar) relative learning parameter, e.g. 0.3
18
+%
19
+%   sM      (struct) map struct, the trained codebook
20
+%
21
+% NOTE: does not take mask into account.
22
+%
23
+% For more help, try 'type lvq3', or check out online documentation.
24
+% See also LVQ1, SOM_SUPERVISED, SOM_SEQTRAIN.
25
+
26
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
27
+%
28
+% lvq3
29
+%
30
+% PURPOSE
31
+%
32
+% Trains codebook with the LVQ3 -algorithm (described below).
33
+%
34
+% SYNTAX
35
+%
36
+% sM = lvq3(sM, data, rlen, alpha, win, epsilon)
37
+%
38
+% DESCRIPTION
39
+%
40
+% Trains codebook with the LVQ3 -algorithm. Codebook contains a number
41
+% of vectors (mi, i=1,2,...,n) and so does data (vectors xj, j=1,2,...k).
42
+% Both vector sets are classified: vectors may have a class (classes are
43
+% set to data- or map -structure's 'labels' -field. For each xj the two 
44
+% closest codebookvectors mc1 and mc2 are searched (euclidean distances
45
+% d1 and d2). xj must fall into the zone of window. That happens if:
46
+%
47
+%    min(d1/d2, d2/d1) > s, where s = (1-win) / (1+win).
48
+%
49
+% If xj belongs to the same class of one of the mc1 and mc1, codebook
50
+% is updated as follows (let mc1 belong to the same class as xj):
51
+%    mc1(t+1) = mc1(t) + alpha * (xj(t) - mc1(t))
52
+%    mc2(t+1) = mc2(t) - alpha * (xj(t) - mc2(t))
53
+% If both mc1 and mc2 belong to the same class as xj, codebook is
54
+% updated as follows:
55
+%    mc1(t+1) = mc1(t) + epsilon * alpha * (xj(t) - mc1(t))
56
+%    mc2(t+1) = mc2(t) + epsilon * alpha * (xj(t) - mc2(t))
57
+% Otherwise updating is not performed.
58
+%
59
+% Argument 'rlen' tells how many times training -sequence is performed.
60
+%
61
+% Argument 'alpha' is recommended to be smaller than 0.1 and argument
62
+% 'epsilon' should be between 0.1 and 0.5.
63
+%
64
+% NOTE: does not take mask into account.
65
+%
66
+% REFERENCES
67
+%
68
+% Kohonen, T., "Self-Organizing Map", 2nd ed., Springer-Verlag, 
69
+%    Berlin, 1995, pp. 181-182.
70
+%
71
+% See also LVQ_PAK from http://www.cis.hut.fi/research/som_lvq_pak.shtml
72
+% 
73
+% REQUIRED INPUT ARGUMENTS
74
+%
75
+%  sM                The data to be trained.
76
+%          (struct)  A map struct.
77
+%
78
+%  data              The data to use in training.
79
+%          (struct)  A data struct.
80
+%
81
+%  rlen    (integer) Running length of LVQ3 -algorithm.
82
+%                    
83
+%  alpha   (float)   Learning rate used in training, e.g. 0.05
84
+%
85
+%  win     (float)   Window length, e.g. 0.25
86
+%  
87
+%  epsilon (float)   Relative learning parameter, e.g. 0.3
88
+%
89
+% OUTPUT ARGUMENTS
90
+%
91
+%  sM          Trained data.
92
+%          (struct)  A map struct.
93
+%
94
+% EXAMPLE
95
+%
96
+%   lab = unique(sD.labels(:,1));         % different classes
97
+%   mu = length(lab)*5;                   % 5 prototypes for each    
98
+%   sM = som_randinit(sD,'msize',[mu 1]); % initial prototypes
99
+%   sM.labels = [lab;lab;lab;lab;lab];    % their classes
100
+%   sM = lvq1(sM,sD,50*mu,0.05);          % use LVQ1 to adjust
101
+%                                         % the prototypes      
102
+%   sM = lvq3(sM,sD,50*mu,0.05,0.2,0.3);  % then use LVQ3 
103
+% 
104
+% SEE ALSO
105
+% 
106
+%  lvq1             Use LVQ1 algorithm for training.
107
+%  som_supervised   Train SOM using supervised training.
108
+%  som_seqtrain     Train SOM with sequential algorithm.
109
+
110
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Parhankangas
111
+% Copyright (c) by Juha Parhankangas
112
+% http://www.cis.hut.fi/projects/somtoolbox/
113
+
114
+% Juha Parhankangas 310100 juuso 020200
115
+
116
+NOTFOUND = 1;
117
+
118
+cod = codebook.codebook;
119
+dat = data.data;
120
+
121
+c_class = codebook.labels(:,1);
122
+d_class = data.labels(:,1);
123
+
124
+s = (1-win)/(1+win);
125
+
126
+x = size(dat,1);
127
+y = size(cod,2);
128
+
129
+c_class=class2num(c_class);
130
+d_class=class2num(d_class);
131
+
132
+ONES=ones(size(cod,1),1);
133
+
134
+for t=1:rlen
135
+  fprintf('\rTraining round: %d/%d',t,rlen);
136
+  tmp = NaN*ones(x,y);
137
+ 
138
+  for j=1:x
139
+    flag = 0;
140
+    mj = 0;
141
+    mi = 0;
142
+    no_NaN=find(~isnan(dat(j,:)));
143
+    di=sqrt(sum([cod(:,no_NaN) - ONES*dat(j,no_NaN)].^2,2));
144
+    [foo, ind1] = min(di);
145
+    di(ind1)=Inf;
146
+    [foo,ind2] =  min(di);    
147
+  
148
+    %ind2=ind2+1;
149
+
150
+    if d_class(j) & d_class(j)==c_class(ind1)
151
+      mj = ind1;
152
+      mi = ind2;
153
+      if d_class(j)==c_class(ind2)
154
+        flag = 1;
155
+      end
156
+    elseif d_class(j) & d_class(j)==c_class(ind2)
157
+      mj = ind2;
158
+      mi = ind1;
159
+      if d_class(j)==c_class(ind1)
160
+        flag = 1;
161
+      end
162
+    end
163
+
164
+    if mj & mi
165
+      if flag
166
+        tmp([mj mi],:) = cod([mj mi],:) + epsilon*alpha*...
167
+                       (dat([j j],:) - cod([mj mi],:));
168
+      else
169
+        tmp(mj,:) = cod(mj,:) + alpha * (dat(j,:)-cod(mj,:));
170
+        tmp(mi,:) = cod(mi,:) - alpha * (dat(j,:)-cod(mj,:));
171
+      end
172
+    end  
173
+  end    
174
+  inds = find(~isnan(sum(tmp,2)));
175
+  cod(inds,:) = tmp(inds,:);
176
+end
177
+fprintf(1,'\n');
178
+
179
+sTrain = som_set('som_train','algorithm','lvq3',...
180
+		 'data_name',data.name,...
181
+		 'neigh','',...
182
+		 'mask',ones(y,1),...
183
+		 'radius_ini',NaN,...
184
+		 'radius_fin',NaN,...
185
+		 'alpha_ini',alpha,...
186
+		 'alpha_type','constant',...
187
+		 'trainlen',rlen,...
188
+		 'time',datestr(now,0));
189
+codebook.trainhist(end+1) = sTrain;
190
+
191
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
192
+
193
+function nos = class2num(class)
194
+
195
+names = {};
196
+nos = zeros(length(class),1);
197
+
198
+for i=1:length(class)
199
+  if ~isempty(class{i}) & ~any(strcmp(class{i},names))
200
+    names=cat(1,names,class(i));
201
+  end
202
+end
203
+
204
+tmp_nos = (1:length(names))';
205
+
206
+for i=1:length(class)
207
+  if ~isempty(class{i})
208
+    nos(i,1) = find(strcmp(class{i},names));    
209
+  end
210
+end
211
+
212
+
213
+
214
+
215
+
... ...
@@ -0,0 +1,65 @@
1
+function [me, st, md, no] = nanstats(D)
2
+
3
+%NANSTATS Statistical operations that ignore NaNs and Infs.
4
+%
5
+% [mean, std, median, nans] = nanstats(D)
6
+%
7
+%  Input and output arguments: 
8
+%   D   (struct) data or map struct
9
+%       (matrix) size dlen x dim
10
+%
11
+%   me  (double) columnwise mean
12
+%   st  (double) columnwise standard deviation
13
+%   md  (double) columnwise median
14
+%   no  (vector) columnwise number of samples (finite, not-NaN)
15
+
16
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Vesanto
17
+% http://www.cis.hut.fi/projects/somtoolbox/
18
+
19
+% Version 2.0beta juuso 300798 200900
20
+
21
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
22
+%% check arguments
23
+
24
+(nargchk(1, 1, nargin));  % check no. of input args is correct
25
+
26
+if isstruct(D), 
27
+  if strcmp(D.type,'som_map'), D = D.codebook;
28
+  else D = D.data;
29
+  end
30
+end
31
+[dlen dim] = size(D);
32
+me = zeros(dim,1)+NaN;
33
+md = me;
34
+st = me;
35
+no = me;
36
+
37
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
38
+%% computation
39
+
40
+for i = 1:dim,
41
+  ind = find(isfinite(D(:, i))); % indices of non-NaN/Inf elements
42
+  n   = length(ind);             % no of non-NaN/Inf elements
43
+
44
+  me(i) = sum(D(ind, i)); % compute average
45
+  if n == 0, me(i) = NaN; else me(i) = me(i) / n; end
46
+
47
+  if nargout>1, 
48
+    md(i) = median(D(ind, i)); % compute median
49
+
50
+    if nargout>2, 
51
+      st(i) = sum((me(i) - D(ind, i)).^2); % compute standard deviation
52
+      if n == 0,     st(i) = NaN;
53
+      elseif n == 1, st(i) = 0;
54
+      else st(i) = sqrt(st(i) / (n - 1));
55
+      end
56
+
57
+      if nargout>3, 
58
+	no(i) = n; % number of samples (finite, not-NaN)
59
+      end
60
+    end
61
+  end
62
+end
63
+
64
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
65
+
... ...
@@ -0,0 +1,89 @@
1
+function [Neurons] = neural_gas(D,n,epochs,alpha0,lambda0)
2
+
3
+%NEURAL_GAS Quantizes the data space using the neural gas algorithm.
4
+%
5
+% Neurons = neural_gas(D, n, epochs, [alpha0], [lambda0])
6
+%
7
+%   C = neural_gas(D,50,10);
8
+%   sM = som_map_struct(sD); 
9
+%   sM.codebook = neural_gas(sD,size(sM.codebook,1),10);
10
+%
11
+%  Input and output arguments ([]'s are optional):
12
+%   D          (matrix) the data matrix, size dlen x dim
13
+%              (struct) a data struct
14
+%   n          (scalar) the number of neurons
15
+%   epochs     (scalar) the number of training epochs (the number of
16
+%                       training steps is dlen*epochs)
17
+%   [alpha0]   (scalar) initial step size, 0.5 by default
18
+%   [lambda0]  (scalar) initial decay constant, n/2 by default
19
+%
20
+%   Neurons    (matrix) the neuron matrix, size n x dim
21
+%
22
+% See also SOM_MAKE, KMEANS.
23
+
24
+% References: 
25
+%  T.M.Martinetz, S.G.Berkovich, and K.J.Schulten. "Neural-gas" network
26
+%  for vector quantization and its application to time-series prediction. 
27
+%  IEEE Transactions on Neural Networks, 4(4):558-569, 1993.
28
+
29
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Vesanto
30
+% Copyright (c) by Juha Vesanto
31
+% http://www.cis.hut.fi/projects/somtoolbox/
32
+
33
+% juuso 101297 020200
34
+
35
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
36
+%% Check arguments and initialize
37
+
38
+error(nargchk(3, 5, nargin));  % check the number of input arguments
39
+
40
+if isstruct(D), D = D.data; end
41
+[dlen,dim] = size(D);
42
+Neurons = (rand(n,dim)-0.5)*10e-5; % small initial values
43
+train_len = epochs*dlen;
44
+
45
+if nargin<4 | isempty(alpha0) | isnan(alpha0), alpha0 = 0.5; end
46
+if nargin<5 | isempty(lambda0) | isnan(lambda0), lambda0 = n/2; end
47
+
48
+% random sample order
49
+rand('state',sum(100*clock));
50
+sample_inds = ceil(dlen*rand(train_len,1));
51
+
52
+% lambda
53
+lambda = lambda0 * (0.01/lambda0).^([0:(train_len-1)]/train_len);
54
+
55
+% alpha
56
+alpha = alpha0 * (0.005/alpha0).^([0:(train_len-1)]/train_len);
57
+
58
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
59
+%% Action
60
+
61
+for i=1:train_len,
62
+
63
+  % sample vector
64
+  x = D(sample_inds(i),:); % sample vector
65
+  known = ~isnan(x);       % its known components
66
+  X = x(ones(n,1),known);  % we'll need this 
67
+
68
+  % neighborhood ranking
69
+  Dx = Neurons(:,known) - X;  % difference between vector and all map units
70
+  [qerrs, inds] = sort((Dx.^2)*known'); % 1-BMU, 2-BMU, etc.
71
+  ranking(inds) = [0:(n-1)];             
72
+  h = exp(-ranking/lambda(i));
73
+  H = h(ones(length(known),1),:)';
74
+
75
+  % update 
76
+  Neurons = Neurons + alpha(i)*H.*(x(ones(n,1),known) - Neurons(:,known));
77
+
78
+  % track
79
+  fprintf(1,'%d / %d \r',i,train_len);
80
+  if 0 & mod(i,50) == 0, 
81
+    hold off, plot3(D(:,1),D(:,2),D(:,3),'bo')
82
+    hold on, plot3(Neurons(:,1),Neurons(:,2),Neurons(:,3),'r+')
83
+    drawnow
84
+  end
85
+end
86
+
87
+fprintf(1,'\n');
88
+
89
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
0 90
\ No newline at end of file
... ...
@@ -0,0 +1,80 @@
1
+function [P,V,me,l] = pcaproj(D,arg1,arg2)
2
+
3
+%PCAPROJ Projects data vectors using Principal Component Analysis.
4
+%
5
+% [P,V,me,l] = pcaproj(D, odim)
6
+% P =          pcaproj(D, V, me)
7
+%
8
+%  Input and output arguments ([]'s are optional)
9
+%   D      (matrix) size dlen x dim, the data matrix
10
+%          (struct) data or map struct            
11
+%   odim   (scalar) how many principal vectors are used
12
+%  
13
+%   P      (matrix) size dlen x odim, the projections
14
+%   V      (matrix) size dim x odim, principal eigenvectors (unit length)
15
+%   me     (vector) size 1 x dim, center point of D
16
+%   l      (vector) size 1 x odim, the corresponding eigenvalues, 
17
+%                   relative to total sum of eigenvalues
18
+%                   
19
+% See also SAMMON, CCA.
20
+
21
+% Contributed to SOM Toolbox 2.0, February 2nd, 2000 by Juha Vesanto
22
+% Copyright (c) by Juha Vesanto
23
+% http://www.cis.hut.fi/projects/somtoolbox/
24
+
25
+% juuso 191297 070200
26
+
27
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
28
+
29
+error(nargchk(2, 3, nargin)); % check the number of input arguments
30
+
31
+% the data
32
+if isstruct(D), 
33
+  if strcmp(D.type,'som_map'), D=D.codebook; else D=D.data; end
34
+end
35
+[dlen dim] = size(D);
36
+
37
+if nargin==2, 
38
+
39
+  odim = arg1;
40
+    
41
+  % autocorrelation matrix
42
+  A = zeros(dim);
43
+  me = zeros(1,dim);
44
+  for i=1:dim, 
45
+    me(i) = mean(D(isfinite(D(:,i)),i)); 
46
+    D(:,i) = D(:,i) - me(i); 
47
+  end  
48
+  for i=1:dim, 
49
+    for j=i:dim, 
50
+      c = D(:,i).*D(:,j); c = c(isfinite(c));
51
+      A(i,j) = sum(c)/length(c); A(j,i) = A(i,j); 
52
+    end
53
+  end
54
+  
55
+  % eigenvectors, sort them according to eigenvalues, and normalize
56
+  [V,S]   = eig(A);
57
+  eigval  = diag(S);
58
+  [y,ind] = sort(abs(eigval)); 
59
+  eigval  = eigval(flipud(ind));
60
+  V       = V(:,flipud(ind)); 
61
+  for i=1:odim, V(:,i) = (V(:,i) / norm(V(:,i))); end
62
+  
63
+  % take only odim first eigenvectors
64
+  V = V(:,1:odim);
65
+  l = abs(eigval)/sum(abs(eigval));
66
+  l = l(1:odim); 
67
+
68
+else % nargin==3, 
69
+
70
+  V = arg1;
71
+  me = arg2;
72
+  odim = size(V,2);    
73
+  D = D-me(ones(dlen,1),:);
74
+  
75
+end
76
+  
77
+% project the data using odim first eigenvectors
78
+P = D*V;
79
+
80
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,6642 @@
1
+function preprocess(sData,arg2)
2
+
3
+%PREPROCESS  A GUI for data preprocessing.
4
+%
5
+%  preprocess(sData)
6
+%
7
+%    preprocess(sData)
8
+%
9
+% Launches a preprocessing GUI. The optional input argument can be
10
+% either a data struct or a struct array of such. However, primarily
11
+% the processed data sets are loaded to the application using the
12
+% tools in the GUI. Also, the only way to get the preprocessed data
13
+% sets back into the workspace is to use the tools in the GUI (press
14
+% the button DATA SET MANAGEMENT).
15
+%  
16
+% For a more throughout description, see online documentation.
17
+% See also SOM_GUI. 
18
+
19
+%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
20
+%
21
+% IN FILES: preprocess.html,preproc.jpg,sDman.jpg,clip.jpg,delay.jpg,window.jpg,selVect.jpg
22
+
23
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Parhankangas
24
+% Copyright (c) by Juha Parhankangas and the SOM Toolbox team
25
+
26
+% http://www.cis.hut.fi/projects/somtoolbox/
27
+
28
+% Juha Parhankangas 050100
29
+
30
+global no_of_sc  % every Nth component in 'relative values' is drawn stronger.
31
+no_of_sc=5;
32
+
33
+if nargin < 1 | nargin > 2 
34
+  error('Invalid number of input arguments');
35
+  return;
36
+end
37
+  
38
+if nargin == 1, arg2=[]; end
39
+
40
+if ~isstr(sData)   %%% Preprocess is started...
41
+data.LOG{1}='% Starting the ''Preprocess'' -window...';
42
+data.LOG{2}=cat(2,'preprocess(',...
43
+                     sprintf('%s);',inputname(1)));
44
+
45
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
46
+if ~isempty(pre_h)
47
+  figure(pre_h);
48
+  msgbox('''Preprocess''-figure already exists.');
49
+  return;
50
+end
51
+
52
+h0 = figure('Color',[0.8 0.8 0.8], ...
53
+	'PaperPosition',[18 180 576 432], ...
54
+	'PaperUnits','points', ...
55
+	'Position',[595 216 600 775], ...
56
+	'Tag','Preprocess');
57
+	
58
+h1 = uicontrol('Parent',h0, ...
59
+	'Units','normalized', ...
60
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
61
+	'FontWeight','demi', ...
62
+	'HorizontalAlignment','left', ...
63
+	'ListboxTop',0, ...
64
+	'Position',[0.015 0.06064516129032258 0.9550000000000001 0.1458064516129032], ...
65
+	'Style','text', ...
66
+	'Tag','StaticText1');
67
+
68
+data.results_h = h1;
69
+
70
+h1 = uicontrol('Parent',h0, ...
71
+	'Units','normalized', ...
72
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
73
+	'Callback','preprocess close', ...
74
+	'FontWeight','demi', ...
75
+	'ListboxTop',0, ...
76
+	'Position',[0.8067 0.0142 0.1667 0.0348],...
77
+	'String','CLOSE', ...
78
+	'Tag','Pushbutton1');
79
+
80
+h1 = uicontrol('Parent',h0, ...
81
+	'Units','normalized', ...
82
+	'BackgroundColor',[0.8 0.8 0.8], ...
83
+	'FontWeight','demi', ...
84
+	'HorizontalAlignment','left', ...
85
+	'ListboxTop',0, ...
86
+	'Position',[0.01833333333333333 0.2141935483870968 0.07000000000000001 0.01806451612903226], ...
87
+	'String','LOG', ...
88
+	'Style','text', ...
89
+	'Tag','StaticText2');
90
+
91
+h1 = uicontrol('Parent',h0, ...
92
+	'Units','normalized', ...
93
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
94
+	'Callback','preprocess sel_comp',...
95
+	'FontWeight','demi', ...
96
+	'ListboxTop',0, ...
97
+	'Position',[0.7983333333333333 0.2090322580645161 0.1666666666666667 0.03483870967741935], ...
98
+	'String',' ', ...
99
+	'Style','popupmenu', ...
100
+	'Tag','sel_comp_h', ...
101
+	'Value',1);
102
+
103
+data.sel_comp_h=h1;
104
+
105
+h1 = uicontrol('Parent',h0, ...
106
+	'Units','normalized', ...
107
+	'BackgroundColor',[1 1 1], ...
108
+	'ListboxTop',0, ...
109
+	'Position',[0.0183 0.2568 0.2133 0.1290], ...
110
+	'Style','text', ...
111
+	'Tag','StaticText3');
112
+
113
+data.sel_cdata_h=h1;
114
+
115
+h1 = axes('Parent',h0, ...
116
+	'CameraUpVector',[0 1 0], ...
117
+	'CameraUpVectorMode','manual', ...
118
+	'Color',[1 1 1], ...
119
+	'Position',[0.2583 0.2568 0.2133 0.1290], ...
120
+	'Tag','Axes1', ...
121
+	'XColor',[0 0 0], ...
122
+	'XTickLabel',['0  ';'0.5';'1  '], ...
123
+	'XTickLabelMode','manual', ...
124
+	'XTickMode','manual', ...
125
+	'YColor',[0 0 0], ...
126
+	'YTickMode','manual', ...
127
+	'ZColor',[0 0 0]);
128
+
129
+data.sel_chist_h=h1;
130
+
131
+h2 = text('Parent',h1, ...
132
+	'Color',[0 0 0], ...
133
+	'HandleVisibility','off', ...
134
+	'HorizontalAlignment','center', ...
135
+	'Position',[0.4960629921259843 -0.08080808080808044 9.160254037844386], ...
136
+	'Tag','Axes1Text4', ...
137
+	'VerticalAlignment','cap');
138
+set(get(h2,'Parent'),'XLabel',h2);
139
+h2 = text('Parent',h1, ...
140
+	'Color',[0 0 0], ...
141
+	'HandleVisibility','off', ...
142
+	'HorizontalAlignment','center', ...
143
+	'Position',[-0.0551181102362206 0.4848484848484853 9.160254037844386], ...
144
+	'Rotation',90, ...
145
+	'Tag','Axes1Text3', ...
146
+	'VerticalAlignment','baseline');
147
+set(get(h2,'Parent'),'YLabel',h2);
148
+h2 = text('Parent',h1, ...
149
+	'Color',[0 0 0], ...
150
+	'HandleVisibility','off', ...
151
+	'HorizontalAlignment','right', ...
152
+	'Position',[-1.2283    5.7980    9.1603], ...
153
+	'Tag','Axes1Text2', ...
154
+	'Visible','off');
155
+set(get(h2,'Parent'),'ZLabel',h2);
156
+h2 = text('Parent',h1, ...
157
+	'Color',[0 0 0], ...
158
+	'HandleVisibility','off', ...
159
+	'HorizontalAlignment','center', ...
160
+	'Position',[0.4960629921259843 1.070707070707071 9.160254037844386], ...
161
+	'Tag','Axes1Text1', ...
162
+	'VerticalAlignment','bottom');
163
+set(get(h2,'Parent'),'Title',h2);
164
+
165
+h1 = axes('Parent',h0, ...
166
+	'CameraUpVector',[0 1 0], ...
167
+	'CameraUpVectorMode','manual', ...
168
+	'Color',[0.7529 0.7529 0.7529], ...
169
+	'Position',[0.4950000000000001 0.2567741935483871 0.4766666666666667 0.1290322580645161], ...
170
+	'Tag','Axes2', ...
171
+	'XColor',[0 0 0], ...
172
+	'XTickMode','manual', ...
173
+	'YColor',[0 0 0], ...
174
+	'YTick',[0 0.5 1], ...
175
+	'YTickMode','manual', ...
176
+	'ZColor',[0 0 0]);
177
+
178
+data.vector_h=h1;
179
+
180
+h2 = text('Parent',h1, ...
181
+	'Color',[0 0 0], ...
182
+	'HandleVisibility','off', ...
183
+	'HorizontalAlignment','center', ...
184
+	'Position',[0.4982456140350879 -0.08080808080808044 9.160254037844386], ...
185
+	'Tag','Axes2Text4', ...
186
+	'VerticalAlignment','cap');
187
+set(get(h2,'Parent'),'XLabel',h2);
188
+h2 = text('Parent',h1, ...
189
+	'Color',[0 0 0], ...
190
+	'HandleVisibility','off', ...
191
+	'HorizontalAlignment','center', ...
192
+	'Position',[-0.1018    0.4848    9.1603], ...
193
+	'Rotation',90, ...
194
+	'Tag','Axes2Text3', ...
195
+	'VerticalAlignment','baseline');
196
+set(get(h2,'Parent'),'YLabel',h2);
197
+h2 = text('Parent',h1, ...
198
+	'Color',[0 0 0], ...
199
+	'HandleVisibility','off', ...
200
+	'HorizontalAlignment','right', ...
201
+	'Position',[-1.045614035087719 5.797979797979799 9.160254037844386], ...
202
+	'Tag','Axes2Text2', ...
203
+	'Visible','off');
204
+set(get(h2,'Parent'),'ZLabel',h2);
205
+h2 = text('Parent',h1, ...
206
+	'Color',[0 0 0], ...
207
+	'HandleVisibility','off', ...
208
+	'HorizontalAlignment','center', ...
209
+	'Position',[0.4982456140350879 1.070707070707071 9.160254037844386], ...
210
+	'Tag','Axes2Text1', ...
211
+	'VerticalAlignment','bottom');
212
+set(get(h2,'Parent'),'Title',h2);
213
+
214
+h1 = uicontrol('Parent',h0, ...
215
+	'Units','normalized', ...
216
+	'BackgroundColor',[0.8 0.8 0.8], ...
217
+	'FontWeight','demi', ...
218
+	'HorizontalAlignment','left', ...
219
+	'ListboxTop',0, ...
220
+	'Position',[0.01833333333333333 0.3922580645161291 0.17 0.01806451612903226], ...
221
+	'String','STATISTICS', ...
222
+	'Style','text', ...
223
+	'Tag','StaticText4');
224
+
225
+h1 = uicontrol('Parent',h0, ...
226
+	'Units','normalized', ...
227
+	'BackgroundColor',[0.8 0.8 0.8], ...
228
+	'FontWeight','demi', ...
229
+	'HorizontalAlignment','left', ...
230
+	'ListboxTop',0, ...
231
+	'Position',[0.2583333333333334 0.3922580645161291 0.1633333333333333 0.01806451612903226], ...
232
+	'String','HISTOGRAM', ...
233
+	'Style','text', ...
234
+	'Tag','StaticText5');
235
+
236
+h1 = uicontrol('Parent',h0, ...
237
+	'Units','normalized', ...
238
+	'BackgroundColor',[0.8 0.8 0.8], ...
239
+	'FontWeight','demi',...
240
+	'FontSize',6,...
241
+	'HorizontalAlignment','left',...
242
+	'String',{'LEFT: NEW SELECTION';'RIGHT: ADD TO SELECTION'}, ...
243
+	'ListboxTop',0, ...
244
+	'Position',[0.5016666666666667 0.38 0.235 0.03741935483870968], ...
245
+	'Style','text', ...
246
+	'Tag','StaticText6', ...
247
+	'UserData','[ ]');
248
+
249
+h1 = uicontrol('Parent',h0, ...
250
+	'Units','normalized', ...
251
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
252
+	'Callback','preprocess selall', ...
253
+	'FontWeight','demi', ...
254
+	'ListboxTop',0, ...
255
+	'Position',[0.8066666666666668 0.3922580645161291 0.1666666666666667 0.03483870967741935], ...
256
+	'String','SELECT ALL', ...
257
+	'Tag','Pushbutton2', ...
258
+	'UserData','[ ]');
259
+
260
+h1 = uicontrol('Parent',h0, ...
261
+	'Units','normalized', ...
262
+	'BackgroundColor',[0.7529 0.7529 0.7529], ...
263
+	'Position',[0.01833333333333333 0.4503225806451613 0.23 0.3225806451612903], ...
264
+	'String',' ', ...
265
+	'Style','listbox', ...
266
+	'Tag','Listbox1', ...
267
+	'Value',1);
268
+
269
+data.comp_names_h=h1;
270
+
271
+h1 = uicontrol('Parent',h0, ...
272
+	'Units','normalized', ...
273
+	'BackgroundColor',[1 1 1], ...
274
+	'Position',[0.4950000000000001 0.4503225806451613 0.2333333333333333 0.3225806451612903], ...
275
+	'String',' ', ...
276
+	'Style','listbox', ...
277
+	'Tag','Listbox2', ...
278
+	'Value',1);
279
+
280
+data.vect_mean_h = h1;
281
+
282
+h1 = axes('Parent',h0, ...
283
+	'CameraUpVector',[0 1 0], ...
284
+	'CameraUpVectorMode','manual', ...
285
+	'Color',[1 1 1], ...
286
+	'Position',[0.7383333333333334 0.4503225806451613 0.2333333333333333 0.3225806451612903], ...
287
+	'Tag','Axes3', ...
288
+	'XColor',[0 0 0], ...
289
+	'XTickMode','manual', ...
290
+	'YColor',[0 0 0], ...
291
+	'YTickMode','manual', ...
292
+	'ZColor',[0 0 0]);
293
+
294
+data.sel_cplot_h = h1;
295
+
296
+h2 = text('Parent',h1, ...
297
+	'Color',[0 0 0], ...
298
+	'HandleVisibility','off', ...
299
+	'HorizontalAlignment','center', ...
300
+	'Position',[0.4964028776978418 -0.03212851405622486 9.160254037844386], ...
301
+	'Tag','Axes3Text4', ...
302
+	'VerticalAlignment','cap');
303
+set(get(h2,'Parent'),'XLabel',h2);
304
+h2 = text('Parent',h1, ...
305
+	'Color',[0 0 0], ...
306
+	'HandleVisibility','off', ...
307
+	'HorizontalAlignment','center', ...
308
+	'Position',[-0.05035971223021596 0.493975903614458 9.160254037844386], ...
309
+	'Rotation',90, ...
310
+	'Tag','Axes3Text3', ...
311
+	'VerticalAlignment','baseline');
312
+set(get(h2,'Parent'),'YLabel',h2);
313
+h2 = text('Parent',h1, ...
314
+	'Color',[0 0 0], ...
315
+	'HandleVisibility','off', ...
316
+	'HorizontalAlignment','right', ...
317
+	'Position',[-3.1942    1.7028    9.1603], ...
318
+	'Tag','Axes3Text2', ...
319
+	'Visible','off');
320
+set(get(h2,'Parent'),'ZLabel',h2);
321
+h2 = text('Parent',h1, ...
322
+	'Color',[0 0 0], ...
323
+	'HandleVisibility','off', ...
324
+	'HorizontalAlignment','center', ...
325
+	'Position',[0.4964028776978418 1.028112449799197 9.160254037844386], ...
326
+	'Tag','Axes3Text1', ...
327
+	'VerticalAlignment','bottom');
328
+set(get(h2,'Parent'),'Title',h2);
329
+
330
+h1 = uicontrol('Parent',h0, ...
331
+	'Units','normalized', ...
332
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
333
+	'Callback','preprocess plxy', ...
334
+	'FontWeight','demi', ...
335
+	'ListboxTop',0, ...
336
+	'Position',[0.265 0.4683870967741936 0.125 0.03483870967741935], ...
337
+	'String','XY-PLOT', ...
338
+	'Tag','Pushbutton3');
339
+
340
+h1 = uicontrol('Parent',h0, ...
341
+	'Units','normalized', ...
342
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
343
+	'Callback','preprocess hist', ...
344
+	'FontWeight','demi', ...
345
+	'ListboxTop',0, ...
346
+	'Position',[0.265 0.5303225806451613 0.125 0.03483870967741935], ...
347
+	'String','HISTOGRAM', ...
348
+	'Tag','Pushbutton4');
349
+
350
+h1 = uicontrol('Parent',h0, ...
351
+	'Units','normalized', ...
352
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
353
+	'Callback','preprocess bplo', ...
354
+	'FontWeight','demi', ...
355
+	'ListboxTop',0, ...
356
+	'Position',[0.265 0.5922580645161291 0.125 0.03483870967741935], ...
357
+	'String','BOX PLOT', ...
358
+	'Tag','Pushbutton5');
359
+
360
+h1 = uicontrol('Parent',h0, ...
361
+	'Units','normalized', ...
362
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
363
+	'Callback','preprocess plot', ...
364
+	'FontWeight','demi', ...
365
+	'ListboxTop',0, ...
366
+	'Position',[0.265 0.654195483870968 0.125 0.03483870967741935], ...
367
+	'String','PLOT', ...
368
+	'Tag','Pushbutton6');
369
+
370
+h1 = uicontrol('Parent',h0, ...
371
+	'Units','normalized', ...
372
+	'BackgroundColor',[1 1 1], ...
373
+	'ListboxTop',0, ...
374
+	'Position',[0.4088888888888889 0.5333333333333333 0.06 0.03268817204301075], ...
375
+	'String','30', ...
376
+	'Style','edit', ...
377
+	'Tag','EditText1');
378
+
379
+data.no_of_bins_h = h1;
380
+
381
+
382
+h1 = uicontrol('Parent',h0, ...
383
+	'Units','normalized', ...
384
+	'BackgroundColor',[0.8 0.8 0.8], ...
385
+	'FontWeight','demi', ...
386
+	'HorizontalAlignment','left', ...
387
+	'ListboxTop',0, ...
388
+	'Position',[0.01833333333333333 0.775483870967742 0.2016666666666667 0.01806451612903226], ...
389
+	'String','COMPONENT LIST', ...
390
+	'Style','text', ...
391
+	'Tag','StaticText7');
392
+
393
+h1 = uicontrol('Parent',h0, ...
394
+	'Units','normalized', ...
395
+	'BackgroundColor',[0.8 0.8 0.8], ...
396
+	'FontWeight','demi', ...
397
+	'HorizontalAlignment','left', ...
398
+	'ListboxTop',0, ...
399
+	'Position',[0.4950000000000001 0.775483870967742 0.1966666666666667 0.01806451612903226], ...
400
+	'String','AVERAGE', ...
401
+	'Style','text', ...
402
+	'Tag','StaticText8');
403
+
404
+h1 = uicontrol('Parent',h0, ...
405
+	'Units','normalized', ...
406
+	'BackgroundColor',[0.8 0.8 0.8], ...
407
+	'FontWeight','demi', ...
408
+	'HorizontalAlignment','left', ...
409
+	'ListboxTop',0, ...
410
+	'Position',[0.7383333333333334 0.775483870967742 0.225 0.01806451612903226], ...
411
+	'String','RELATIVE VALUES', ...
412
+	'Style','text', ...
413
+	'Tag','StaticText9');
414
+
415
+h1 = uicontrol('Parent',h0, ...
416
+	'Units','normalized', ...
417
+	'BackgroundColor',[0.8 0.8 0.8], ...
418
+	'FontSize',10, ...
419
+	'FontWeight','demi', ...
420
+	'HorizontalAlignment','left', ...
421
+	'ListboxTop',0, ...
422
+	'Position',[0.01833333333333333 0.8154838709677419 0.2033333333333333 0.0232258064516129], ...
423
+	'String','COMPONENTS', ...
424
+	'Style','text', ...
425
+	'Tag','StaticText10');
426
+
427
+h1 = uicontrol('Parent',h0, ...
428
+	'Units','normalized', ...
429
+	'BackgroundColor',[0.8 0.8 0.8], ...
430
+	'FontSize',10, ...
431
+	'FontWeight','demi', ...
432
+	'HorizontalAlignment','left', ...
433
+	'ListboxTop',0, ...
434
+	'Position',[0.4950000000000001 0.8154838709677419 0.2 0.0232258064516129], ...
435
+	'String','VECTORS', ...
436
+	'Style','text', ...
437
+	'Tag','StaticText11');
438
+
439
+h1 = uicontrol('Parent',h0, ...
440
+	'Units','normalized', ...
441
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
442
+	'Callback','preprocess sD_management', ...
443
+	'FontSize',5, ...
444
+	'FontWeight','demi', ...
445
+	'ListboxTop',0, ...
446
+	'Position',[0.01833333333333333 0.8503225806451613 0.1666666666666667 0.03483870967741935], ...
447
+	'String','DATA SET MANAGEMENT', ...
448
+	'Tag','Pushbutton7');
449
+
450
+h1 = uicontrol('Parent',h0, ...
451
+	'Units','normalized', ...
452
+	'Callback','preprocess sel_sD', ...
453
+	'ListboxTop',0, ...
454
+	'Position',[0.01833333333333333 0.8890322580645161 0.1666666666666667 0.03483870967741935], ...
455
+	'String',' ', ...
456
+	'Style','popupmenu', ...
457
+	'Tag','PopupMenu2', ...
458
+	'Value',1);
459
+
460
+data.sD_set_h = h1;
461
+
462
+h1 = uicontrol('Parent',h0, ...
463
+	'Units','normalized', ...
464
+	'BackgroundColor',[1 1 1], ...
465
+	'ListboxTop',0, ...
466
+	'Position',[0.2516666666666667 0.8503225806451613 0.7216666666666667 0.07354838709677419], ...
467
+	'Style','text', ...
468
+	'Tag','StaticText12');
469
+
470
+data.sD_name_h = h1;
471
+
472
+h1 = uicontrol('Parent',h0, ...
473
+	'Units','normalized', ...
474
+	'BackgroundColor',[0.8 0.8 0.8], ...
475
+	'FontSize',10, ...
476
+	'FontWeight','demi', ...
477
+	'HorizontalAlignment','left', ...
478
+	'ListboxTop',0, ...
479
+	'Position',[0.01833333333333333 0.9341935483870968 0.1616666666666667 0.02064516129032258], ...
480
+	'String','DATA SETS', ...
481
+	'Style','text', ...
482
+	'Tag','StaticText13');
483
+
484
+h1 = uicontrol('Parent',h0, ...
485
+	'Units','normalized', ...
486
+	'BackgroundColor',[0.8 0.8 0.8], ...
487
+	'FontSize',10, ...
488
+	'FontWeight','demi', ...
489
+	'HorizontalAlignment','left', ...
490
+	'ListboxTop',0, ...
491
+	'Position',[0.2516666666666667 0.9341935483870968 0.2833333333333333 0.02064516129032258], ...
492
+	'String','SELECTED DATA SET', ...
493
+	'Style','text', ...
494
+	'Tag','StaticText14');
495
+
496
+if ~isstruct(sData), 
497
+  sData=som_data_struct(sData);
498
+end
499
+
500
+ui_h=uimenu('Label','&Normalization');
501
+uimenu(ui_h,'Label','Scale [0,1]','Callback','preprocess zscale');
502
+uimenu(ui_h,'Label','Scale var=1','Callback','preprocess vscale');
503
+uimenu(ui_h,'Label','HistD','Callback','preprocess histeq');
504
+uimenu(ui_h,'Label','HistC','Callback','preprocess histeq2');
505
+uimenu(ui_h,'Label','Log','Callback','preprocess log');
506
+uimenu(ui_h,'Label','Eval (1-comp)','Callback','preprocess eval1');
507
+
508
+ui_h=uimenu('Label','&Components');
509
+uimenu(ui_h,'Label','Move component','Callback','preprocess move');
510
+uimenu(ui_h,'Label','Copy component','Callback','preprocess copy');
511
+uimenu(ui_h,'Label','Add: N binary types','Callback','preprocess oneo');
512
+uimenu(ui_h,'Label','Add: zeros','Callback','preprocess zero');
513
+uimenu(ui_h,'Label','Remove component','Callback','preprocess remove');
514
+uimenu(ui_h,'Label','Remove selected vectors',...
515
+            'Callback','preprocess remove_vects');
516
+uimenu(ui_h,'Label','Select all components',...
517
+            'Callback','preprocess sel_all_comps');
518
+
519
+ui_h=uimenu('Label','&Misc');
520
+ui_h1=uimenu(ui_h,'Label','Calculate');
521
+ui_h2=uimenu(ui_h,'Label','Process');
522
+
523
+uimenu(ui_h,'Label','Get LOG-file','Callback','preprocess LOG');
524
+uimenu(ui_h,'Label','Indices of the selected vectors',...
525
+            'Callback','preprocess get_inds');
526
+uimenu(ui_h,'Label','Undo','Callback','preprocess undo');
527
+uimenu(ui_h1,'Label','Number of values','Callback','preprocess noof');
528
+uimenu(ui_h1,'Label','Number of selected vectors',...
529
+             'Callback','preprocess no_of_sel');
530
+uimenu(ui_h1,'Label','Correlation','Callback','preprocess corr');
531
+uimenu(ui_h2,'Label','Unit length','Callback','preprocess unit');
532
+uimenu(ui_h2,'Label','Eval','Callback','preprocess eval2');
533
+uimenu(ui_h2,'Label','Clipping','Callback','preprocess clipping');
534
+uimenu(ui_h2,'Label','Delay','Callback','preprocess delay');
535
+uimenu(ui_h2,'Label','Windowed','Callback','preprocess window');
536
+uimenu(ui_h2,'Label','Select vectors','Callback','preprocess select');
537
+
538
+len=getfield(size(sData(1).data),{1});
539
+data.selected_vects=find(ones(1,len));
540
+data.sD_set=sData;
541
+set(data.vector_h,'ButtonDownFcn','preprocess(''vector_bdf'',''down'')');
542
+set(gcf,'UserData',data);
543
+if ~set_sD_stats;
544
+  return;
545
+end
546
+sel_sD;
547
+return;    %%% Preprocess-window is ready.
548
+
549
+else
550
+ arg=sData;
551
+ if strcmp(arg,'rename')
552
+   rename(arg2);
553
+ elseif strcmp(arg,'sel_sD')
554
+   if isempty(arg2)
555
+     sel_sD;
556
+   else
557
+     sel_sD(arg2);
558
+   end
559
+ elseif strcmp(arg,'zscale')
560
+   if isempty(arg2)
561
+      zero2one_scale;
562
+   else
563
+      zero2one_scale(arg2);
564
+   end
565
+ elseif strcmp(arg,'vscale');
566
+   if isempty(arg2)
567
+      var_scale;
568
+   else
569
+      var_scale(arg2);
570
+   end
571
+ elseif strcmp(arg,'histeq2')
572
+   if isempty(arg2)
573
+     hist_eq2;
574
+   else
575
+     hist_eq2(arg2);
576
+   end
577
+ elseif strcmp(arg,'log')
578
+   if isempty(arg2)
579
+     logarithm;
580
+   else
581
+     logarithm(arg2);
582
+   end
583
+ elseif strcmp(arg,'eval1')
584
+   if isempty(arg2)
585
+     eval1;
586
+   else
587
+     eval1(arg2);
588
+   end
589
+ elseif strcmp(arg,'eval2')
590
+   if isempty(arg2)
591
+     eval2;
592
+   else
593
+     eval2(arg2);
594
+   end
595
+ elseif strcmp(arg,'histeq');
596
+   if isempty(arg2)
597
+     hist_eq;
598
+   else
599
+      hist_eq(arg2);
600
+   end
601
+ elseif strcmp(arg,'selall')
602
+   if isempty(arg2)
603
+     select_all;
604
+   else
605
+     select_all(arg2);
606
+   end
607
+ elseif strcmp(arg,'sel_button');
608
+   if isempty(arg2)
609
+     sel_button;
610
+   else
611
+     sel_button(arg2);
612
+   end
613
+ elseif strcmp(arg,'clear_button')
614
+   if isempty(arg2)
615
+     clear_button;
616
+   else
617
+     clear_button(arg2)
618
+   end
619
+ elseif(strcmp(arg,'move'))
620
+   if isempty(arg2)
621
+     move_component;
622
+   else
623
+     move_component(arg2);
624
+   end
625
+ elseif(strcmp(arg,'copy'))
626
+   if isempty(arg2)
627
+     copy_component;
628
+   else
629
+     copy_component(arg2);
630
+   end
631
+ elseif strcmp(arg,'oneo')
632
+   if isempty(arg2)
633
+     one_of_n;
634
+   else
635
+     one_of_n(arg2);
636
+   end
637
+ elseif strcmp(arg,'zero')
638
+   if isempty(arg2)
639
+     add_zeros;
640
+   else
641
+     add_zeros(arg2);
642
+   end
643
+ elseif strcmp(arg,'remove')
644
+   if isempty(arg2)
645
+     remove_component;
646
+   else
647
+     remove_component(arg2);
648
+   end
649
+ elseif strcmp(arg,'remove_vects')
650
+   if isempty(arg2)
651
+     remove_vects;
652
+   else
653
+     remove_vects(arg2);
654
+   end
655
+ elseif strcmp(arg,'noof')
656
+   if isempty(arg2)
657
+     no_of_values;
658
+   else
659
+     no_of_values(arg2);
660
+   end
661
+ elseif strcmp(arg,'corr');
662
+   if isempty(arg2)
663
+     correlation;
664
+   else
665
+     correlation(arg2);
666
+   end
667
+ elseif strcmp(arg,'unit')
668
+   if isempty(arg2)
669
+     unit_length;
670
+   else
671
+     unit_length(arg2);
672
+   end
673
+ elseif strcmp(arg,'clip_data')
674
+   clip_data(arg2);
675
+ elseif strcmp(arg,'copy_delete')
676
+   copy_delete(arg2);
677
+ elseif strcmp(arg,'and_or_cb')
678
+   and_or_cb(arg2);
679
+ elseif strcmp(arg,'all_sel_cb')
680
+   all_sel_cb(arg2);
681
+ elseif strcmp(arg,'clip_exp_cb')
682
+   clip_exp_cb(arg2);
683
+ elseif strcmp(arg,'window_cb')
684
+   window_cb(arg2);
685
+ elseif strcmp(arg,'set_state_vals')
686
+   set_state_vals(arg2);
687
+ elseif strcmp(arg,'vector_bdf')
688
+   vector_bdf(arg2);
689
+ elseif strcmp(arg,'sD_management');
690
+   if isempty(arg2)
691
+     sD_management;
692
+   else
693
+     sD_management(arg2);
694
+   end
695
+ elseif strcmp(arg,'clipping')
696
+   if isempty(arg2)
697
+     clipping;
698
+   else
699
+     clipping(arg2);
700
+   end
701
+ elseif strcmp(arg,'delay')
702
+   if isempty(arg2)
703
+     delay;
704
+   else
705
+     delay(arg2);
706
+   end
707
+ elseif strcmp(arg,'window');
708
+   if isempty(arg2)
709
+     window;
710
+   else
711
+     window(arg2);
712
+   end
713
+ elseif strcmp(arg,'select');
714
+   if isempty(arg2)
715
+     select;
716
+   else
717
+     select(arg2);
718
+   end
719
+ elseif strcmp(arg,'import')
720
+   if isempty(arg2)
721
+     import;
722
+   else
723
+     import(arg2);
724
+   end
725
+ elseif strcmp(arg,'export')
726
+   if isempty(arg2)
727
+     export;
728
+   else
729
+     export(arg2);
730
+   end
731
+ elseif strcmp(arg,'undo');
732
+   if isempty(arg2)
733
+     undo;
734
+   else
735
+     undo(arg2);
736
+   end
737
+ elseif strcmp(arg,'delay_data')
738
+   if isempty(arg2)
739
+     delay_data;
740
+   else
741
+     delay_data(arg2);
742
+   end
743
+ elseif strcmp(arg,'eval_windowed')
744
+   if isempty(arg2)
745
+     eval_windowed;
746
+   else
747
+     eval_windowed(arg2);
748
+   end 
749
+ elseif strcmp(arg,'get_inds')
750
+   if isempty(arg2)
751
+     get_selected_inds;
752
+   else
753
+     get_selected_inds(arg2);
754
+   end
755
+ elseif strcmp(arg,'no_of_sel')
756
+   if isempty(arg2)
757
+     no_of_selected;
758
+   else
759
+     no_of_selected(arg2);
760
+   end
761
+ elseif strcmp(arg,'sel_comp');
762
+   if isempty(arg2)
763
+     sel_comp;
764
+   else
765
+     sel_comp(arg2);
766
+   end
767
+ elseif strcmp(arg,'sel_all_comps')
768
+   if isempty(arg2)
769
+     select_all_comps;
770
+   else
771
+     select_all_comps(arg2);
772
+   end 
773
+ elseif strcmp(arg,'refresh')
774
+   set_var_names;  
775
+ elseif any(strcmp(arg,{'close_c','close_d','close_s','close_w','close_sD'}))
776
+   if isempty(arg2)
777
+     close_func(arg)
778
+   else
779
+     close_func(arg,arg2);
780
+   end 
781
+ end
782
+ 
783
+
784
+ switch arg
785
+   case 'sD_stats'
786
+     sD_stats;
787
+   case 'LOG'
788
+     log_file;
789
+   otherwise
790
+     pro_tools(arg);
791
+ end
792
+end
793
+
794
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
795
+
796
+function set_compnames(sData,h)
797
+
798
+%SET_COMPNAMES
799
+%
800
+% set_compnames(sData,h)
801
+%
802
+% ARGUMENTS
803
+%
804
+%  sData     (struct)  som_data_struct
805
+%  h         (scalar)  handle to a list box object
806
+%
807
+%
808
+% This function sets the component names of sData to the list box
809
+% indicated by 'h'. 
810
+%
811
+
812
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
813
+
814
+if isempty(pre_h)
815
+  error('Figure ''Preprocess'' does not exist. Closing program...');
816
+  close_preprocess;
817
+end
818
+
819
+udata=get(pre_h,'UserData');
820
+
821
+set(h,'Value',[]);
822
+for i=1:length(sData.comp_names)	
823
+  tmp=sprintf('#%d: ',i);
824
+  names{i,1}=cat(2,tmp, sData.comp_names{i});
825
+end
826
+
827
+
828
+set(h,'String',names,'Max',2);
829
+set(udata.sel_comp_h,'String',names);
830
+
831
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
832
+
833
+function draw_vectors(vectors,h)
834
+
835
+%DRAW_VECTORS
836
+%
837
+% draw_vectors(vectors,h)
838
+%
839
+% ARGUMENTS
840
+%
841
+%  vectors  (vector) vector of 0's and 1's
842
+%  h        (scalar) handle to an axis object
843
+%
844
+%
845
+%  This function draws an horizontal bar of 'vectors' in the axis
846
+%  indicated by 'h'.
847
+%
848
+%
849
+
850
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
851
+subplot(h);
852
+hold off;
853
+cla;
854
+
855
+set(h,'YLim',[0 1]);
856
+set(h,'YTick',[]);
857
+set(h,'XLim',[0 length(vectors)+1]);
858
+hold on;
859
+
860
+comp_no=get(getfield(get(pre_h,'UserData'),'sel_comp_h'),'Value');
861
+comp=getfield(get(pre_h,'UserData'),'sData');
862
+comp=comp.data(:,comp_no);
863
+Max = max(comp);
864
+Min = min(comp);
865
+lims=get(gca,'YLim');
866
+lims(1)=Min;
867
+h=abs(0.1*Max);
868
+lims(2)=Max;
869
+if Max - Min <= eps
870
+  tmp=Max;
871
+  lims(1)=tmp-1;
872
+  lims(2)=tmp+1;
873
+end
874
+lims(2)=lims(2)+h;
875
+if ~all(isnan(lims))
876
+  set(gca,'YLim',lims);
877
+end
878
+h=(lims(2)-lims(1))/4;
879
+set(gca,'YTickMode','auto'); 
880
+t=1:length(vectors);
881
+h=plot(t,comp);
882
+set(h,'ButtonDownFcn','preprocess(''vector_bdf'',''down'')');
883
+indices =find(vectors);
884
+vectors(indices)=0.1*(getfield(get(gca,'YLim'),...
885
+                      {2})-getfield(get(gca,'YLim'),{1}));
886
+plot(indices,vectors(indices)+getfield(get(gca,'YLim'),{1}),...
887
+     'ored','MarkerSize',4);
888
+
889
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
890
+
891
+function vect_means(sData,handle,indices)
892
+
893
+%VECT_MEANS
894
+%
895
+% vect_means(sData,handle,indices)
896
+%
897
+% ARGUMENTS
898
+% 
899
+%  sData    (struct)    som_data_struct
900
+%  handle   (scalar)    handle to the static text box object
901
+%  indices  (vector)    indices of selected vectors
902
+%
903
+%
904
+% This function calculates means of selected vectors' components
905
+% and writes them in the static text box indicated by 'handle'.
906
+%
907
+%
908
+
909
+sData= sData.data(indices,:);
910
+
911
+for i=1:length(sData(1,:))
912
+  names{i}=sprintf('#%d: ',i);
913
+end
914
+
915
+
916
+for i=1:length(sData(1,:))
917
+  tmp=sData(:,i);
918
+  tmp=cat(2,names{i},sprintf('%-10.3g',mean(tmp(find(~isnan(tmp))))));
919
+  string{i}=tmp;
920
+end
921
+
922
+set(handle,'String',string);
923
+set(handle,'HorizontalAlignment','left');
924
+
925
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
926
+
927
+function vector_bdf(arg)
928
+
929
+%VECTOR_BDF   A button down function.
930
+%
931
+% vector_bdf(arg)
932
+%
933
+% ARGUMENTS
934
+%
935
+%  arg      (string)  'down' or 'up',  tells the mouse button's state.
936
+%                     
937
+%
938
+%  This function selects vectors in the vector-window and plots maxima,
939
+%  minima and means of the selected vectors. It also writes means of the
940
+%  selected vectors' components in a static text box and takes care of
941
+%  changes of the chosen component's data.
942
+%
943
+%  See also VECTOR_MEANS, SEL_COMP
944
+%
945
+%
946
+ 
947
+
948
+arg2=arg(6:length(arg));
949
+if ~isempty(arg2)
950
+  LOG=1;
951
+else
952
+  LOG=0;
953
+end
954
+arg=arg(1:4);
955
+
956
+%%% arg's first "word" is 4 letters long and it can be:
957
+%%%
958
+%%% 'key '
959
+%%% 'down'
960
+%%% 'drag'
961
+%%% 'up  '
962
+
963
+if strcmp(arg,'key ') %string is 'key' + 1 space!!!
964
+  if ~LOG
965
+    key=get(gcf,'CurrentCharacter');
966
+   else 
967
+    key=arg2
968
+  end
969
+  if ~strcmp(key,'<') & ~strcmp(key,'>')
970
+    return;
971
+  end
972
+  data=get(gcf,'UserData');
973
+  sel=data.selected_vects;
974
+  if length(sel) == 1
975
+    if strcmp(key,'<') & sel ~= 1 
976
+      data.selected_vects=sel-1;
977
+      set(gcf,'UserData',data);
978
+     elseif strcmp(key,'>') & sel ~= length(data.sData.data(:,1))
979
+      data.selected_vects = sel + 1;
980
+      set(gcf,'UserData',data);
981
+     end
982
+  else
983
+    if strcmp(key,'<') & sel(1) ~= 1
984
+      data.selected_vects=cat(2,sel(1)-1,sel);
985
+      set(gcf,'UserData',data);
986
+     elseif strcmp(key,'>') & sel(length(sel)) ~= length(sel)
987
+      data.selected_vects=cat(2,sel,sel(length(sel))+1);
988
+      set(gcf,'UserData',data);
989
+     end
990
+  end
991
+  cplot_mimema;
992
+  pro_tools('plot_hist');
993
+  pro_tools('c_stat');
994
+  vects=zeros(1,length(data.sData.data(:,1)));
995
+  vects(data.selected_vects)=1;
996
+  draw_vectors(vects,data.vector_h);
997
+ 
998
+  if ~LOG
999
+    data=get(gcf,'UserData');
1000
+    data.LOG{length(data.LOG)+1}=...
1001
+    sprintf('preprocess(''vector_bdf'',''key  %s'');',key);
1002
+                                                %string is 'key'+2spaces+%s
1003
+    set(gcf,'UserData',data);
1004
+  end
1005
+  return;
1006
+end
1007
+
1008
+switch arg
1009
+  case 'down'
1010
+   set(gcf,'WindowButtonUpFcn','preprocess(''vector_bdf'',''up  '')');
1011
+   set(gcf,'WindowButtonMotionFcn','preprocess(''vector_bdf'',''drag'')');
1012
+   switch get(gcf,'SelectionType')
1013
+     case 'normal'
1014
+      data.lims1=round(getfield(get(gca,'CurrentPoint'),{1,1}));
1015
+      data.lims2=[];
1016
+     case 'alt'
1017
+      tmp=round(getfield(get(gca,'CurrentPoint'),{1,1}));
1018
+      if isempty(get(gca,'UserData'))
1019
+        data.lims1=tmp;
1020
+        data.lims2=[];
1021
+      else
1022
+        data.lims1=cat(2,getfield(get(gca,'UserData'),'lims1'),tmp);
1023
+        data.lims2=getfield(get(gca,'UserData'),'lims2');
1024
+      end
1025
+   end
1026
+   coords=get(gca,'CurrentPoint');
1027
+   h=line([coords(1),coords(1)],get(gca,'YLim'),'EraseMode','xor');
1028
+   set(h,'Color','red');
1029
+   h2=line([coords(1),coords(1)],get(gca,'YLim'),'EraseMode','xor');
1030
+   set(h2,'Color','red');
1031
+   data.h=h;
1032
+   data.h2=h2;
1033
+   set(gca,'UserData',data);
1034
+
1035
+  case 'drag'
1036
+   coords=get(gca,'CurrentPoint');
1037
+   lim=get(gca,'XLim');
1038
+   h2=getfield(get(gca,'UserData'),'h2');
1039
+   if lim(1) >= coords(1)
1040
+     set(h2,'XData',[lim(1) lim(1)]);
1041
+   elseif lim(2) <= coords(2)
1042
+     set(h2,'XData',[lim(2) lim(2)]);
1043
+   else
1044
+     set(h2,'XData',[coords(1) coords(1)]);
1045
+   end
1046
+  case 'up  '   % string is 'up' + 2 spaces!!! 
1047
+   set(gcf,'WindowButtonUpFcn','');
1048
+   set(gcf,'WindowButtonMotionFcn','');
1049
+   if ~LOG
1050
+     data=get(gca,'UserData');
1051
+     delete(data.h);
1052
+     delete(data.h2);
1053
+     tmp=round(getfield(get(gca,'CurrentPoint'),{1,1}));
1054
+     data.lims2=cat(2,data.lims2,tmp);
1055
+     tmp_data=sort(cat(1,data.lims1,data.lims2));
1056
+     high=getfield(get(gca,'XLim'),{2})-1;
1057
+     vectors=zeros(1,high);
1058
+     tmp_data(find(tmp_data<1))=1;
1059
+     tmp_data(find(tmp_data>high))=high;
1060
+
1061
+     for i=1:getfield(size(tmp_data),{2})
1062
+       vectors(tmp_data(1,i):tmp_data(2,i))=1;
1063
+     end
1064
+     selected_vects=find(vectors);
1065
+   else
1066
+     pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
1067
+     len=size(getfield(getfield(get(pre_h,'UserData'),'sData'),'data'));
1068
+     vectors=zeros(1,len(1));
1069
+     i=1;
1070
+     while i <= length(arg2) & (isspace(arg2(i)) | ~isletter(arg2(i)))
1071
+      i=i+1;
1072
+     end
1073
+     arg3=arg2(i:length(arg2));
1074
+     selected_vects=str2num(arg2(1:i-1));
1075
+     if ~isempty(arg3) & ~all(isspace(arg3))
1076
+       selected_vects=unique(cat(2,selected_vects,...
1077
+                            getfield(get(pre_h,'UserData'),'selected_vects')));
1078
+     end           
1079
+     vectors(selected_vects)=1;  
1080
+     set(pre_h,'CurrentAxes',getfield(get(pre_h,'UserData'),'vector_h'));
1081
+     set(0,'CurrentFigure',pre_h);
1082
+   end
1083
+   draw_vectors(vectors,gca);
1084
+   sData=getfield(get(gcf,'UserData'),'sData');
1085
+   h=getfield(get(gcf,'UserData'),'vect_mean_h');
1086
+   vect_means(sData,h,selected_vects);
1087
+   if ~LOG
1088
+     set(gca,'UserData',data);
1089
+   end
1090
+   data=get(gcf,'UserData');  
1091
+   data.undo.sData=data.sData;
1092
+   data.undo.selected=data.selected_vects;
1093
+   data.selected_vects=selected_vects;
1094
+   if ~LOG
1095
+     data.LOG{length(data.LOG)+1}='% Vector selection by using the mouse...';
1096
+     tmp=sprintf('preprocess(''vector_bdf'',''up   %s'');',...
1097
+                num2str(data.selected_vects));
1098
+     if length(tmp) > 500
1099
+       tmp=textwrap({tmp},500);
1100
+       data.LOG{length(data.LOG)+1}=cat(2,tmp{1},''');');
1101
+       for i=2:length(tmp)-1
1102
+         data.LOG{length(data.LOG)+1}=...
1103
+               cat(2,sprintf('preprocess(''vector_bdf'',''up   %s',...
1104
+                     tmp{i}),'add'');');
1105
+       end
1106
+       data.LOG{length(data.LOG)+1}=...
1107
+             cat(2,sprintf('preprocess(''vector_bdf'',''up   %s',...
1108
+                   tmp{length(tmp)}(1:length(tmp{length(tmp)})-3)),' add'');');
1109
+     else
1110
+       data.LOG{length(data.LOG)+1}=tmp;
1111
+     end
1112
+   end   
1113
+   set(gcf,'UserData',data);
1114
+   cplot_mimema;
1115
+   sel_comp;
1116
+end
1117
+
1118
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1119
+
1120
+function sel_button(varargin) 
1121
+
1122
+%SEL_BUTTON     A Callback function. It performs the operations needed
1123
+%               when vector components are selected.
1124
+%
1125
+% See also SEL_COMP
1126
+%
1127
+
1128
+if nargin == 1
1129
+  LOG=1;
1130
+  pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
1131
+  string=getfield(get(pre_h,'UserData'),'comp_names_h');
1132
+  string=getfield(get(string,'String'),{str2num(varargin{1})});
1133
+  set(0,'CurrentFigure',pre_h);
1134
+else
1135
+  LOG=0;
1136
+  val=get(getfield(get(gcf,'UserData'),'comp_names_h'),'Value');
1137
+end
1138
+
1139
+sel_button_h=getfield(get(gcf,'UserData'),'sel_button_h');
1140
+sel_comps_h=getfield(get(gcf,'UserData'),'sel_comps_h');
1141
+comp_names_h=getfield(get(gcf,'UserData'),'comp_names_h');
1142
+if ~LOG
1143
+  string=getfield(get(comp_names_h,'String'),{get(comp_names_h,'Value')});
1144
+end
1145
+tmp_string=get(sel_comps_h,'String');
1146
+
1147
+if iscell(tmp_string)
1148
+
1149
+  for i=1:length(string)
1150
+    if ~any(strcmp(string{i},tmp_string))
1151
+      tmp_string=cat(1,tmp_string,string(i));
1152
+    end
1153
+  end
1154
+  string=tmp_string;
1155
+end
1156
+
1157
+set(sel_comps_h,'String',string);
1158
+set(comp_names_h,'Value',[]);
1159
+sel_comp;
1160
+if ~LOG
1161
+  data=get(gcf,'UserData');
1162
+  data.LOG{length(data.LOG)+1}='% Select components';
1163
+  data.LOG{length(data.LOG)+1}=sprintf('preprocess(''sel_button'',''%s'');',...
1164
+                                        num2str(val));
1165
+  set(gcf,'UserData',data);
1166
+end
1167
+ 
1168
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1169
+
1170
+function clear_button(varargin)
1171
+
1172
+%CLEAR_BUTTON  Function callback evaluated when a 'Clear'-button is
1173
+%              pressed. It removes texts from the 'selected components' 
1174
+%              -window and the 'selected component data' -window and
1175
+%              clears the 'histogram' -axis.
1176
+%
1177
+%
1178
+
1179
+if nargin==1
1180
+  LOG=1;
1181
+  pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
1182
+  set(0,'CurrentFigure',pre_h);
1183
+else
1184
+  LOG=0;
1185
+end
1186
+
1187
+sel_comp_h=getfield(get(gcf,'UserData'),'sel_comp_h');
1188
+sel_cdata_h=getfield(get(gcf,'UserData'),'sel_cdata_h');
1189
+sel_cplot_h=getfield(get(gcf,'UserData'),'sel_cplot_h');
1190
+sel_chist_h=getfield(get(gcf,'UserData'),'sel_chist_h');
1191
+vector_h=getfield(get(gcf,'UserData'),'vector_h');
1192
+
1193
+set(sel_comp_h,'Value',1);
1194
+set(sel_cdata_h,'String',' ');
1195
+subplot(sel_chist_h);
1196
+hold off;
1197
+cla;
1198
+
1199
+selected=getfield(get(gcf,'UserData'),'selected_vects');
1200
+dims=size(getfield(getfield(get(gcf,'UserData'),'sData'),'data'));
1201
+vectors=zeros(1,dims(1));
1202
+vectors(selected)=1;
1203
+subplot(vector_h);
1204
+draw_vectors(vectors,vector_h);
1205
+if ~LOG
1206
+  data=get(gcf,'UserData');
1207
+  data.LOG{length(data.LOG)+1}='% Remove components from the selected list.';
1208
+  data.LOG{length(data.LOG)+1}='preprocess(''clear_button'',''foo'');';
1209
+  set(gcf,'UserData',data);
1210
+end
1211
+
1212
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1213
+
1214
+function sel_comp(varargin)
1215
+
1216
+%SEL_COMP  performs the operations needed when vector components are
1217
+%          chosen. It writes maxima, minima, mean and standard deviation
1218
+%          of the chosen component to a text box window and draws a
1219
+%          histogram of the chosen component of selected vectors' 
1220
+%
1221
+%
1222
+
1223
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
1224
+set(0,'CurrentFigure',pre_h);
1225
+sel_comp_h=getfield(get(pre_h,'UserData'),'sel_comp_h');
1226
+
1227
+if nargin == 1
1228
+  set(sel_comp_h,'Value',str2num(varargin{1}));
1229
+elseif ~isempty(gcbo)
1230
+  no=get(sel_comp_h,'Value');
1231
+  data=get(gcf,'UserData');
1232
+  data.LOG{length(data.LOG)+1}='% Select one component';
1233
+  data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''sel_comp'',''',...
1234
+                                      num2str(no),''');');
1235
+  set(gcf,'UserData',data);
1236
+end
1237
+
1238
+pro_tools('c_stat');
1239
+pro_tools('plot_hist');
1240
+data=get(gcf,'UserData');
1241
+sData=data.sData;  
1242
+vector_h=data.vector_h;
1243
+len=length(sData.data(:,1));
1244
+vects=zeros(1,len);
1245
+vects(data.selected_vects)=1;
1246
+draw_vectors(vects,vector_h);
1247
+
1248
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1249
+
1250
+function cplot_mimema
1251
+
1252
+global no_of_sc
1253
+
1254
+sData=getfield(get(gcf,'UserData'),'sData');
1255
+sel_cplot_h=getfield(get(gcf,'UserData'),'sel_cplot_h');
1256
+selected=getfield(get(gcf,'UserData'),'selected_vects');
1257
+
1258
+set(sel_cplot_h,'YLim',[0 length(sData.data(1,:))+1]);
1259
+
1260
+subplot(sel_cplot_h);
1261
+hold off;
1262
+cla;
1263
+hold on;
1264
+
1265
+for i=1:length(sData.data(1,:))
1266
+  Max=max(sData.data(:,i));
1267
+  Min=min(sData.data(:,i));
1268
+  tmp=sData.data(selected,i);
1269
+
1270
+  selMax=max(tmp);
1271
+  selMin=min(tmp);
1272
+  Mean=abs(mean(tmp(find(~isnan(tmp)))));
1273
+  Median=abs(median(tmp(find(~isnan(tmp)))));
1274
+  
1275
+  if Max ~= Min & ~all(isnan(sData.data(:,i)))
1276
+
1277
+    if rem(i,no_of_sc)   % no_of_sc is defined in the beginning of this file...
1278
+
1279
+      line([abs(selMin-Min)/(Max-Min) (selMax-Min)/(Max-Min)],...
1280
+           [i i],'Color','black');
1281
+      plot(abs(Mean-Min)/(Max-Min),i,'oblack');
1282
+      plot(abs(Median-Min)/(Max-Min),i,'xblack');
1283
+    else
1284
+      line([abs(selMin-Min)/(Max-Min) (selMax-Min)/(Max-Min)],...
1285
+           [i i],'Color','black','LineWidth',2);
1286
+      plot(abs(Mean-Min)/(Max-Min),i,'oblack','LineWidth',2);
1287
+      plot(abs(Median-Min)/(Max-Min),i,'xblack','LineWidth',2);
1288
+    end
1289
+  else
1290
+
1291
+    if rem(i,no_of_sc)     % N is defined in the beginning of this file.
1292
+
1293
+      plot(mean(get(gca,'XLim')),i,'oblack');
1294
+      plot(mean(get(gca,'XLim')),i,'xblack');
1295
+    else
1296
+      plot(mean(get(gca,'XLim')),i,'oblack','LineWidth',2);
1297
+      plot(mean(get(gca,'XLim')),i,'xblack','LineWidth',2);
1298
+    end
1299
+  end
1300
+end
1301
+
1302
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1303
+
1304
+
1305
+function bool=set_sD_stats
1306
+
1307
+%SET_SD_STATS Writes the data set names to popup menu.
1308
+%
1309
+%
1310
+
1311
+bool=1;
1312
+data=get(gcf,'UserData');
1313
+
1314
+for i=1:length(data.sD_set)
1315
+ % if ~isvalid_var_name({data.sD_set(i).name})
1316
+ %   close_preprocess;
1317
+ %   bool=0;
1318
+ %   return;
1319
+ % end
1320
+  string{i}=cat(2,sprintf('#%d: ',i),data.sD_set(i).name);
1321
+end
1322
+
1323
+set(data.sD_set_h,'String',string);
1324
+data.sData=data.sD_set(get(data.sD_set_h,'Value'));
1325
+data.sData.MODIFIED=0;
1326
+data.sData.INDEX=1;
1327
+set(gcf,'UserData',data);
1328
+write_sD_stats;
1329
+
1330
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1331
+
1332
+function write_sD_stats
1333
+
1334
+%WRITE_SD_STATS  writes data's name, length and dimension to text box.
1335
+%
1336
+%
1337
+
1338
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
1339
+
1340
+
1341
+sD_name_h=getfield(get(pre_h,'UserData'),'sD_name_h');
1342
+sData=getfield(get(pre_h,'UserData'),'sData');
1343
+dims=size(sData.data);
1344
+string{1}=cat(2,'Name:   ',sData.name);
1345
+string{2}=cat(2,'Length: ',sprintf('%d',dims(1)));
1346
+string{3}=cat(2,'Dim:     ',sprintf('%d',dims(2)));
1347
+
1348
+set(sD_name_h,'String',string);
1349
+set(sD_name_h,'HorizontalAlignment','left');
1350
+
1351
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1352
+
1353
+
1354
+
1355
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1356
+
1357
+function sel_sD(varargin)
1358
+
1359
+%SEL_SD  sets new data to UserData's 'sData'.
1360
+%        
1361
+%
1362
+
1363
+if nargin==1
1364
+  LOG=1;
1365
+  index=str2num(varargin{1});
1366
+  pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
1367
+  set(0,'CurrentFigure',pre_h);
1368
+else
1369
+  LOG=0;
1370
+end
1371
+
1372
+sD_set_h=getfield(get(gcf,'UserData'),'sD_set_h');
1373
+comp_names_h=getfield(get(gcf,'UserData'),'comp_names_h');
1374
+vector_h=getfield(get(gcf,'UserData'),'vector_h');
1375
+vect_mean_h=getfield(get(gcf,'UserData'),'vect_mean_h');
1376
+
1377
+if ~LOG
1378
+  index=get(sD_set_h,'Value');
1379
+end
1380
+data=get(gcf,'UserData');
1381
+data.undo = [];
1382
+INDEX=data.sData.INDEX;
1383
+data.sData=rmfield(data.sData,'MODIFIED'); 
1384
+data.sData=rmfield(data.sData,'INDEX');
1385
+
1386
+tmp=data.sD_set(index);
1387
+tmp.MODIFIED=0;
1388
+tmp.INDEX=index;
1389
+data.sD_set(INDEX)=data.sData;
1390
+data.sData=tmp;
1391
+
1392
+len=getfield(size(tmp.data),{1});
1393
+
1394
+data.selected_vects=find(ones(1,len));
1395
+if ~LOG
1396
+  data.LOG{length(data.LOG)+1}='% Select a new data set.';
1397
+  data.LOG{length(data.LOG)+1}=sprintf('preprocess(''sel_sD'',''%s'');',...
1398
+                                        num2str(index));
1399
+end
1400
+set(gcf,'UserData',data);
1401
+write_sD_stats;
1402
+set_compnames(tmp,comp_names_h);
1403
+draw_vectors(ones(1,len),vector_h);
1404
+vect_means(tmp,vect_mean_h,data.selected_vects);
1405
+clear_button;
1406
+sel_comp;
1407
+cplot_mimema;
1408
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1409
+
1410
+function indices=get_indices
1411
+
1412
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
1413
+
1414
+comp_names_h=getfield(get(pre_h,'UserData'),'comp_names_h');
1415
+indices = get(comp_names_h,'Value');
1416
+
1417
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1418
+
1419
+
1420
+
1421
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1422
+
1423
+function sD_management(varargin)
1424
+
1425
+if nargin ~= 1
1426
+  pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
1427
+  preh_udata=get(pre_h,'UserData');
1428
+  preh_udata.LOG{length(preh_udata.LOG)+1}=...
1429
+           '% Starting the ''Data Set Management'' -window...';
1430
+  preh_udata.LOG{length(preh_udata.LOG)+1}=...
1431
+                 'preprocess(''sD_management'',''foo'');';
1432
+  set(pre_h,'UserData',preh_udata);
1433
+end 
1434
+
1435
+man_h=findobj(get(0,'Children'),'Tag','Management');
1436
+if ~isempty(man_h)
1437
+  figure(man_h);
1438
+  return;
1439
+end
1440
+
1441
+h0 = figure('BackingStore','off', ...
1442
+	'Color',[0.8 0.8 0.8], ...
1443
+	'Name','Data Set Management', ...
1444
+	'PaperPosition',[18 180 576 432], ...
1445
+	'PaperUnits','points', ...
1446
+	'Position',[753 523 324 470], ...
1447
+	'RendererMode','manual', ...
1448
+	'Tag','Management');
1449
+h1 = uicontrol('Parent',h0, ...
1450
+	'Units','normalized', ...
1451
+	'BackgroundColor',[1 1 1], ...
1452
+	'FontWeight','demi', ...
1453
+	'HorizontalAlignment','left', ...
1454
+	'ListboxTop',0, ...
1455
+	'Max',2, ...
1456
+	'Position',[0.02777777777777778 0.0723404255319149 0.7716049382716049 0.1914893617021277], ...
1457
+	'String',' ', ...
1458
+	'Style','edit', ...
1459
+	'Tag','EditText1');
1460
+
1461
+data.new_c_name_h = h1;
1462
+
1463
+h1 = uicontrol('Parent',h0, ...
1464
+	'Callback','preprocess rename comp',...
1465
+	'Units','normalized', ...
1466
+	'FontSize',6, ...
1467
+	'FontWeight','demi', ...
1468
+	'ListboxTop',0, ...
1469
+	'Position',[0.8240740740740741 0.2106382978723404 0.154320987654321 0.05319148936170213], ...
1470
+	'String','RENAME', ...
1471
+	'Tag','Pushbutton1');
1472
+
1473
+h1 = uicontrol('Parent',h0, ...
1474
+	'Callback','preprocess close_sD',...
1475
+	'Units','normalized', ...
1476
+	'FontWeight','demi', ...
1477
+	'ListboxTop',0, ...
1478
+	'Position',[0.8240740740740741 0.01914893617021277 0.154320987654321 0.05319148936170213], ...
1479
+	'String','CLOSE', ...
1480
+	'Tag','Pushbutton2');
1481
+h1 = uicontrol('Parent',h0, ...
1482
+	'Units','normalized', ...
1483
+	'BackgroundColor',[0.8 0.8 0.8], ...
1484
+	'FontWeight','demi', ...
1485
+	'HorizontalAlignment','left', ...
1486
+	'ListboxTop',0, ...
1487
+	'Position',[0.02777777777777778 0.2680851063829787 0.345679012345679 0.02978723404255319], ...
1488
+	'String','COMPONENTS:', ...
1489
+	'Style','text', ...
1490
+	'Tag','StaticText1');
1491
+h1 = uicontrol('Parent',h0, ...
1492
+	'Units','normalized', ...
1493
+	'BackgroundColor',[1 1 1], ...
1494
+	'HorizontalAlignment','left', ...
1495
+	'Position',[0.02777777777777778 0.3170212765957447 0.3549382716049382 0.5319148936170213], ...
1496
+	'String',' ', ...
1497
+	'Style','listbox', ...
1498
+	'Tag','Listbox1', ...
1499
+	'Value',1);
1500
+
1501
+data.sets_h=h1;
1502
+
1503
+h1 = uicontrol('Parent',h0, ...
1504
+	'Units','normalized', ...
1505
+	'BackgroundColor',[1 1 1], ...
1506
+	'HorizontalAlignment','left', ...
1507
+	'Position',[0.6234567901234568 0.3170212765957447 0.3549382716049382 0.5319148936170213], ...
1508
+	'String',' ', ...
1509
+	'Style','listbox', ...
1510
+	'Tag','Listbox2', ...
1511
+	'Value',1);
1512
+
1513
+
1514
+data.variables_h = h1;
1515
+
1516
+h1 = uicontrol('Parent',h0, ...
1517
+	'Callback','preprocess export',...
1518
+	'Units','normalized', ...
1519
+	'FontWeight','demi', ...
1520
+	'ListboxTop',0, ...
1521
+	'Position',[0.4259259259259259 0.551063829787234 0.154320987654321 0.0425531914893617], ...
1522
+	'String','->', ...
1523
+	'Tag','Pushbutton4');
1524
+
1525
+h1 = uicontrol('Parent',h0, ...
1526
+	'Callback','preprocess import',...
1527
+	'Units','normalized', ...
1528
+	'FontWeight','demi', ...
1529
+	'ListboxTop',0, ...
1530
+	'Position',[0.4259259259259259 0.625531914893617 0.154320987654321 0.0425531914893617], ...
1531
+	'String','<-', ...
1532
+	'Tag','Pushbutton3');
1533
+
1534
+
1535
+
1536
+h1 = uicontrol('Parent',h0, ...
1537
+	'Units','normalized', ...
1538
+	'BackgroundColor',[0.8 0.8 0.8], ...
1539
+	'FontWeight','demi', ...
1540
+	'HorizontalAlignment','left', ...
1541
+	'ListboxTop',0, ...
1542
+	'Position',[0.02777777777777778 0.8531914893617022 0.2993827160493827 0.02978723404255319], ...
1543
+	'String','DATA SETS', ...
1544
+	'Style','text', ...
1545
+	'Tag','StaticText2');
1546
+
1547
+h1 = uicontrol('Parent',h0, ...
1548
+	'Units','normalized', ...
1549
+	'BackgroundColor',[0.8 0.8 0.8], ...
1550
+	'FontWeight','demi', ...
1551
+	'HorizontalAlignment','left', ...
1552
+	'ListboxTop',0, ...
1553
+	'Position',[0.6234567901234568 0.8531914893617022 0.2561728395061728 0.02978723404255319], ...
1554
+	'String','WORKSPACE', ...
1555
+	'Style','text', ...
1556
+	'Tag','StaticText3');
1557
+
1558
+h1 = uicontrol('Parent',h0, ...
1559
+	'Callback','preprocess rename set',...
1560
+	'Units','normalized', ...
1561
+	'BackgroundColor',[1 1 1], ...
1562
+	'HorizontalAlignment','left', ...
1563
+	'ListboxTop',0, ...
1564
+	'Position',[0.1820987654320987 0.9127659574468086 0.7808641975308641 0.0425531914893617], ...
1565
+	'Style','edit', ...
1566
+	'Tag','EditText2');
1567
+
1568
+data.new_name_h = h1;
1569
+
1570
+
1571
+h1 = uicontrol('Parent',h0, ...
1572
+	'Units','normalized', ...
1573
+	'BackgroundColor',[0.8 0.8 0.8], ...
1574
+	'FontWeight','demi', ...
1575
+	'HorizontalAlignment','left', ...
1576
+	'ListboxTop',0, ...
1577
+	'Position',[0.02777777777777778 0.9127659574468086 0.1388888888888889 0.02978723404255319], ...
1578
+	'String','NAME:', ...
1579
+	'Style','text', ...
1580
+	'Tag','StaticText4');
1581
+
1582
+
1583
+ui_h=uimenu('Label','&Tools');
1584
+uimenu(ui_h,'Label','Copy','Callback','preprocess copy_delete copy');
1585
+uimenu(ui_h,'Label','Delete','Callback','preprocess copy_delete delete');
1586
+uimenu(ui_h,'Label','Refresh','Callback','preprocess refresh');
1587
+
1588
+set(gcf,'UserData',data);
1589
+set_var_names;
1590
+sD_names;
1591
+sD_stats;
1592
+
1593
+
1594
+
1595
+%%% Subfunction: set_var_names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1596
+
1597
+function set_var_names
1598
+
1599
+
1600
+variables_h=getfield(get(gcf,'UserData'),'variables_h');
1601
+value=get(variables_h,'Value');
1602
+len=evalin('base','length(who)');
1603
+
1604
+names=cell(len,1);
1605
+
1606
+for i=1:len
1607
+  string=cat(2,'getfield(who,{',num2str(i),'})');
1608
+  names(i)=evalin('base',string);
1609
+end
1610
+
1611
+set(variables_h,'String',names);
1612
+if(value > length(names))
1613
+  set(variables_h,'Value',1);
1614
+end
1615
+
1616
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1617
+
1618
+%%% Subfunction: sD_names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1619
+
1620
+function sD_names
1621
+
1622
+sets_h=getfield(get(gcf,'UserData'),'sets_h');
1623
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
1624
+
1625
+sD_set = getfield(get(pre_h,'UserData'),'sD_set');
1626
+
1627
+for i=1:length(sD_set)
1628
+  names{i,1}=cat(2,sprintf('#%d: ',i),sD_set(i).name);
1629
+end
1630
+
1631
+set(sets_h,'String',names);
1632
+
1633
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1634
+
1635
+%%% Subfunction: sD_stats %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1636
+
1637
+function sD_stats
1638
+
1639
+man_h=findobj(get(0,'Children'),'Tag','Management');
1640
+c_names_h=getfield(get(man_h,'UserData'),'new_c_name_h');
1641
+sD_name_h=getfield(get(man_h,'UserData'),'new_name_h');
1642
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
1643
+INDEX=getfield(getfield(get(pre_h,'UserData'),'sData'),'INDEX');
1644
+MODIFIED=getfield(getfield(get(pre_h,'UserData'),'sData'),'MODIFIED');
1645
+value=get(getfield(get(man_h,'UserData'),'sets_h'),'Value');
1646
+ 
1647
+if value==INDEX
1648
+  data=get(pre_h,'UserData');
1649
+  sData=rmfield(data.sData,[{'INDEX'};{'MODIFIED'}]);
1650
+  data.sD_set(INDEX)=sData;
1651
+  data.sData.MODIFIED=0;
1652
+  set(pre_h,'UserData',data);
1653
+end      
1654
+
1655
+sData=getfield(getfield(get(pre_h,'UserData'),'sD_set'),{value});
1656
+string1=[{sData.name}];
1657
+
1658
+
1659
+set(sD_name_h,'String',string1);
1660
+set(c_names_h,'String',sData.comp_names);
1661
+
1662
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1663
+
1664
+%%% Subfunction: import %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1665
+
1666
+function import(varargin)
1667
+
1668
+if nargin==1
1669
+  LOG=1;
1670
+  man_h=findobj(get(0,'Children'),'Tag','Management');
1671
+  set(0,'CurrentFigure',man_h);
1672
+  name=varargin;
1673
+else 
1674
+  LOG=0;
1675
+end
1676
+
1677
+variables_h=getfield(get(gcf,'UserData'),'variables_h');
1678
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
1679
+if ~LOG
1680
+  name=getfield(get(variables_h,'String'),{get(variables_h,'Value')});
1681
+end
1682
+errstr='Data to be imported must be real matrix or ''som_data_struct''.';
1683
+new_sD=evalin('base',name{1});
1684
+
1685
+if isempty(pre_h)
1686
+  errordlg('''Preprocess'' -figure does not exist. Terminating program...');
1687
+  close_preprocess;
1688
+  return;
1689
+end
1690
+
1691
+if isstr(new_sD) | (~isstruct(new_sD) & ~isreal(new_sD))
1692
+  errordlg(errstr);
1693
+  return;
1694
+elseif isstruct(new_sD) & length(new_sD) > 1
1695
+  errordlg(errstr)
1696
+  return;
1697
+elseif ~isstruct(new_sD)
1698
+  new_sD=som_data_struct(new_sD);
1699
+  new_sD.name=name{1};
1700
+end
1701
+
1702
+new_sD_names=fieldnames(new_sD);
1703
+right_names=fieldnames(som_data_struct(1));
1704
+for i=1:length(new_sD_names)
1705
+  if ~any(strcmp(new_sD_names(i),right_names));
1706
+    errordlg(errstr);
1707
+    return;
1708
+  end
1709
+end
1710
+
1711
+data=get(pre_h,'UserData');
1712
+data.sD_set(length(data.sD_set) + 1)=new_sD;
1713
+if ~LOG
1714
+  data.LOG{length(data.LOG)+1}='% Import a data set from the workspace.';
1715
+  data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''import'',''',...
1716
+                                    name{1},''');');
1717
+end
1718
+set(pre_h,'UserData',data);
1719
+sD_names;
1720
+sD_stats;
1721
+old =gcf;
1722
+set(0,'CurrentFigure',pre_h);
1723
+set_sD_stats;
1724
+set(0,'CurrentFigure',old);
1725
+
1726
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1727
+
1728
+%%% Subfunction: export %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1729
+
1730
+function export(varargin)
1731
+
1732
+if nargin == 1
1733
+  LOG=1;
1734
+  man_h=findobj(get(0,'Children'),'Tag','Management');
1735
+  set(0,'CurrentFigure',man_h);
1736
+  index=str2num(varargin{1});  
1737
+else
1738
+  LOG=0;
1739
+end
1740
+
1741
+sets_h=getfield(get(gcf,'UserData'),'sets_h');
1742
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
1743
+
1744
+if ~LOG
1745
+  index=get(sets_h,'Value');
1746
+end
1747
+
1748
+if isempty(pre_h)
1749
+  errordlg('''Preprocess''-figure does not exist. Terminating program...');
1750
+  close(findobj(get(0,'Children'),'Tag','Management'));
1751
+  close(findobj(get(0,'Children'),'Tag','PlotWin'));
1752
+  return;
1753
+end
1754
+
1755
+sData=getfield(getfield(get(pre_h,'UserData'),'sD_set'),{index});
1756
+
1757
+if ~isvalid_var_name({sData.name})
1758
+  return;
1759
+end
1760
+
1761
+assignin('base',sData.name,sData);
1762
+disp(sprintf('Data set ''%s'' is set to the workspace.',sData.name));
1763
+if ~LOG
1764
+  data=get(pre_h,'UserData');
1765
+  data.LOG{length(data.LOG)+1}='% Export a data set to the workspace.';
1766
+  data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''export'',''',...
1767
+                                   num2str(index),''');');
1768
+  set(pre_h,'UserData',data);
1769
+end
1770
+set_var_names;
1771
+
1772
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1773
+
1774
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1775
+%%% Subfunction: rename %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1776
+
1777
+function rename(arg)
1778
+
1779
+i=1;
1780
+while i <= length(arg) & arg(i) ~= ' '
1781
+  i=i+1;
1782
+end
1783
+
1784
+arg2=arg(i+1:length(arg));
1785
+arg=arg(1:i-1);
1786
+if ~isempty(arg2)
1787
+  LOG=1;
1788
+  i=1;
1789
+  if arg2(1) ~= '{'
1790
+    while i <= length(arg2) & arg2(i) ~= ' '
1791
+      i=i+1;
1792
+    end
1793
+    index=str2num(arg2(i+1:length(arg2)));
1794
+    arg2=arg2(1:i-1);
1795
+  else
1796
+    while i <= length(arg2) & arg2(i) ~= '}'
1797
+      i=i+1;
1798
+    end
1799
+    index=str2num(arg2(i+1:length(arg2)));
1800
+    arg2=arg2(1:i);
1801
+  end
1802
+else
1803
+  LOG=0;
1804
+end
1805
+
1806
+new_name_h=getfield(get(gcf,'UserData'),'new_name_h');
1807
+new_c_name_h=getfield(get(gcf,'UserData'),'new_c_name_h');
1808
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
1809
+
1810
+if isempty(pre_h)
1811
+  errordlg('''Preprocess'' -figure does not exist. Terminating program...');
1812
+  close_preprocess;
1813
+  return;
1814
+end
1815
+
1816
+switch arg
1817
+  case 'set'
1818
+   if LOG
1819
+     name={arg2};
1820
+   else
1821
+     name=get(new_name_h,'String');
1822
+   end
1823
+   if ~isempty(name{1}) & ~any(isspace(name{1}))
1824
+     if ~isvalid_var_name(name)
1825
+       sD_stats;
1826
+       return;
1827
+     end
1828
+     if ~LOG
1829
+       index=get(getfield(get(gcf,'UserData'),'sets_h'),'Value');
1830
+     end
1831
+     data=get(pre_h,'UserData');
1832
+     tmp_set.name=name{1};        
1833
+     data.sD_set(index).name=name{1};
1834
+     if data.sData.INDEX == index
1835
+       data.sData.name=name{1};
1836
+     end
1837
+     if ~LOG
1838
+       data.LOG{length(data.LOG)+1}='% Rename a data set.';
1839
+       data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''rename'',''set ',...
1840
+                                                       name{1},' ',...
1841
+                                                       num2str(index),...
1842
+                                                       ''');');
1843
+     end 
1844
+
1845
+     set(pre_h,'UserData',data);
1846
+     sD_names;
1847
+     string=get(data.sD_set_h,'String');
1848
+     string{index}=cat(2,sprintf('#%d: ',index),name{1});
1849
+     set(data.sD_set_h,'String',string);
1850
+     string=get(data.sD_name_h,'String');
1851
+     string{1}=cat(2,'Name:   ',name{1});
1852
+     if index==data.sData.INDEX
1853
+       set(data.sD_name_h,'String',string);
1854
+     end
1855
+   else
1856
+     sD_stats;
1857
+   end
1858
+  case 'comp'
1859
+   if ~LOG
1860
+     names=get(new_c_name_h,'String');
1861
+     index=get(getfield(get(gcf,'UserData'),'sets_h'),'Value');
1862
+   else
1863
+     names=eval(arg2);
1864
+   end
1865
+   if check_cell_names(names)
1866
+     data=get(pre_h,'UserData');
1867
+     sData=data.sD_set(index);
1868
+     if length(sData.comp_names)==length(names)
1869
+       data.sD_set(index).comp_names=names;
1870
+       if index == data.sData.INDEX
1871
+         for i=1:length(names)
1872
+           names{i}=cat(2,sprintf('#%d: ',i),names{i});
1873
+         end
1874
+         set(data.comp_names_h,'String',names);
1875
+         set(data.sel_comp_h,'String',names);
1876
+       end
1877
+       if ~LOG
1878
+         data.LOG{length(data.LOG)+1}='% Rename components.';
1879
+         str='preprocess(''rename'',''comp {';
1880
+         for i=1:length(names)-1
1881
+           str=cat(2,str,'''''',names{i},''''',');
1882
+         end
1883
+         str=cat(2,str,'''''',names{length(names)},'''''} ',...
1884
+                 num2str(index),''');');
1885
+         data.LOG{length(data.LOG)+1}=str;
1886
+       else
1887
+         set(new_c_name_h,'String',names);
1888
+       end
1889
+       set(pre_h,'UserData',data);          
1890
+     else
1891
+       errordlg('There are less components in data.');
1892
+       sD_stats;
1893
+       return;
1894
+     end
1895
+   else
1896
+     sD_stats;  
1897
+   end
1898
+end
1899
+
1900
+%%% Subfunction: check_cell_names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1901
+
1902
+function bool=check_cell_names(names)
1903
+
1904
+bool = 1;
1905
+
1906
+if isempty(names)
1907
+  bool= 0;
1908
+  return;
1909
+end
1910
+for i=1:length(names)
1911
+  if isempty(names{i}) | isspace(names{i})
1912
+    bool = 0;
1913
+    return;
1914
+  end
1915
+end
1916
+
1917
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1918
+
1919
+%%% Subfunction: isvalid_var_name %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1920
+
1921
+function bool=isvalid_var_name(name)
1922
+
1923
+bool=1;
1924
+
1925
+tmp=name{1};
1926
+if ~((tmp(1)>='a' & tmp(1)<='z') | (tmp(1)>='A' & tmp(1)<='Z'))
1927
+  errordlg('Invalid name.');
1928
+  bool=0;
1929
+  return;
1930
+end
1931
+for j=1:length(tmp)
1932
+  if ~((tmp(j)>='a' & tmp(j)<='z') | ...
1933
+       (tmp(j)>='A' & tmp(j)<='Z') | ...
1934
+       (j>1 & tmp(j) == '_') | ...
1935
+       (tmp(j)>='0' & tmp(j) <= '9')) | tmp(j) == '.'
1936
+    errordlg('Invalid name.');
1937
+    bool=0;
1938
+    return;
1939
+  end
1940
+  if j == length(tmp) & tmp(j) == '_'
1941
+    errordlg('Invalid name.');
1942
+    bool=0;
1943
+    return;
1944
+  end
1945
+end 
1946
+
1947
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1948
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1949
+
1950
+%%% Subfunction: copy_delete %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1951
+
1952
+function copy_delete(arg)
1953
+
1954
+i=1;
1955
+while i <= length(arg) & arg(i) ~= ' '
1956
+  i=i+1;
1957
+end
1958
+
1959
+arg2=arg(i+1:length(arg));
1960
+arg=arg(1:i-1);
1961
+
1962
+if ~isempty(arg2)
1963
+  index=str2num(arg2);
1964
+  LOG=1;
1965
+else
1966
+  LOG=0;
1967
+end
1968
+
1969
+sets_h=getfield(get(gcf,'UserData'),'sets_h');
1970
+if ~LOG
1971
+  index=get(sets_h,'Value');
1972
+end
1973
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
1974
+
1975
+if isempty(pre_h)
1976
+  errordlg('''Preprocess'' -figure does not exist. Terminating program.');
1977
+  close_preprocess;
1978
+  return;
1979
+end
1980
+
1981
+switch arg
1982
+  case 'copy'
1983
+   data=get(pre_h,'UserData');
1984
+   data.sD_set(length(data.sD_set)+1)=data.sD_set(index);
1985
+   if ~LOG
1986
+     data.LOG{length(data.LOG)+1}='% Copy a data set.';
1987
+     data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''copy_delete'',''',...
1988
+                                      'copy ',num2str(index),''');');
1989
+   end
1990
+   set(pre_h,'UserData',data);
1991
+   sD_names;   
1992
+   old=gcf;
1993
+   set(0,'CurrentFigure',pre_h);
1994
+   set_sD_stats;
1995
+   set(0,'CurrentFigure',old);
1996
+  case 'delete'
1997
+   if length(get(sets_h,'String')) == 1
1998
+     msgbox('No data left. Closing program...')
1999
+     close_preprocess;
2000
+     return;
2001
+   end
2002
+   data=get(pre_h,'UserData');
2003
+   if ~isempty(data.undo) &  any(strcmp('index',fieldnames(data.undo)))
2004
+     if data.undo.index > index
2005
+       data.undo.index = data.undo.index-1;
2006
+     elseif data.undo.index==index;
2007
+       data.undo=[];
2008
+     end
2009
+   end
2010
+   set1=data.sD_set(1:index-1);
2011
+   set2=data.sD_set(index+1:length(data.sD_set));
2012
+
2013
+   if ~isempty(set1)
2014
+     data.sD_set=[set1 set2];
2015
+   else
2016
+     data.sD_set=set2;
2017
+   end
2018
+   if ~LOG
2019
+     data.LOG{length(data.LOG)+1}='% Delete a data set.';
2020
+     data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''copy_delete'',''',...
2021
+                                      'delete ',num2str(index),''');');
2022
+   end
2023
+   set(pre_h,'UserData',data);
2024
+
2025
+   set(sets_h,'Value',1);
2026
+   sD_names;
2027
+   sD_stats;
2028
+   old = gcf;
2029
+   set(0,'CurrentFigure',pre_h);
2030
+
2031
+   for i=1:length(data.sD_set)
2032
+     string{i}=cat(2,sprintf('#%d: ',i),data.sD_set(i).name);
2033
+   end
2034
+
2035
+   set(data.sD_set_h,'String',string);
2036
+   data.sData=data.sD_set(get(data.sD_set_h,'Value'));
2037
+   data.sData.MODIFIED=0;
2038
+   data.sData.INDEX=1;
2039
+   set(gcf,'UserData',data);
2040
+   write_sD_stats;
2041
+
2042
+   sData=getfield(get(gcf,'UserData'),'sData');
2043
+   if sData.INDEX > index
2044
+     value=get(getfield(get(gcf,'UserData'),'sD_set_h'),'Value');
2045
+     set(getfield(get(gcf,'UserData'),'sD_set_h'),'Value',value-1);
2046
+     sData.INDEX = sData.INDEX -1;
2047
+   elseif sData.INDEX == index
2048
+     set(getfield(get(gcf,'UserData'),'sD_set_h'),'Value',1);
2049
+   end
2050
+ 
2051
+   sel_sD;
2052
+   set(0,'CurrentFigure',old);
2053
+end
2054
+
2055
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2056
+
2057
+function clipping(varargin)
2058
+
2059
+if nargin ~= 1
2060
+  pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
2061
+  preh_udata=get(pre_h,'UserData');
2062
+  preh_udata.LOG{length(preh_udata.LOG)+1}=...
2063
+        '% Starting the ''Clipping'' -window...';
2064
+  preh_udata.LOG{length(preh_udata.LOG)+1}='preprocess(''clipping'',''foo'');';
2065
+  set(pre_h,'UserData',preh_udata);
2066
+end
2067
+
2068
+clip_h=findobj(get(0,'Children'),'Tag','Clipping');
2069
+
2070
+if ~isempty(clip_h)
2071
+  figure(clip_h);
2072
+  return;
2073
+end
2074
+
2075
+h0 = figure('Color',[0.8 0.8 0.8], ...
2076
+	'PaperPosition',[18 180 575 432], ...
2077
+	'PaperUnits','points', ...
2078
+	'Position',[718 389 300 249], ...
2079
+	'Tag','Clipping');
2080
+
2081
+h1 = uicontrol('Parent',h0, ...
2082
+	'Units','normalized', ...
2083
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
2084
+	'ListboxTop',0, ...
2085
+	'Position',[0.03 0.03614457831325301 0.4666666666666667 0.9236947791164658], ...
2086
+	'Style','frame', ...
2087
+	'Tag','Frame1');
2088
+
2089
+h1 = uicontrol('Parent',h0, ...
2090
+	'Units','normalized', ...
2091
+	'BackgroundColor',[0.8 0.8 0.8], ...
2092
+	'ListboxTop',0, ...
2093
+	'Position',[0.05333333333333334 0.5983935742971887 0.42 0.3333333333333333], ...
2094
+	'Style','frame', ...
2095
+	'Tag','Frame2');
2096
+
2097
+h1 = uicontrol('Parent',h0, ...
2098
+	'Units','normalized', ...
2099
+	'BackgroundColor',[0.8 0.8 0.8], ...
2100
+	'ListboxTop',0, ...
2101
+	'Style','frame', ...
2102
+	'Position',[0.05333333333333334 0.33 0.42 0.24], ...
2103
+	'Tag','Frame3');
2104
+
2105
+h1 = uicontrol('Parent',h0, ...
2106
+	'Units','normalized', ...
2107
+	'BackgroundColor',[0.8 0.8 0.8], ...
2108
+	'ListboxTop',0, ...
2109
+	'Style','frame', ...
2110
+	'Position',[0.05333333333333334 0.06 0.42 0.24],...
2111
+	'Tag','Frame4');
2112
+
2113
+h1 = uicontrol('Parent',h0, ...
2114
+	'Units','normalized', ...
2115
+	'ListboxTop',0, ...
2116
+	'Position',[0.5133333333333334 0.6385542168674698 0.4666666666666667 0.321285140562249], ...
2117
+	'Style','frame', ...
2118
+	'Tag','Frame5');
2119
+
2120
+h1 = uicontrol('Parent',h0, ...
2121
+	'Units','normalized', ...
2122
+	'BackgroundColor',[0.8 0.8 0.8], ...
2123
+	'ListboxTop',0, ...
2124
+	'Position',[0.5366666666666667 0.6666666666666666 0.42 0.2650602409638554], ...
2125
+	'Style','frame', ...
2126
+	'Tag','Frame6');
2127
+
2128
+h1 = uicontrol('Parent',h0, ...
2129
+	'Units','normalized', ...
2130
+	'BackgroundColor',[1 1 1], ...
2131
+	'ListboxTop',0, ...
2132
+	'Position',[0.31 0.823293172690763 0.15 0.09638554216867469], ...
2133
+	'Style','edit', ...
2134
+	'Tag','EditText1');
2135
+
2136
+data.big_val_h = h1;
2137
+
2138
+h1 = uicontrol('Parent',h0, ...
2139
+	'Units','normalized', ...
2140
+	'BackgroundColor',[1 1 1], ...
2141
+	'ListboxTop',0, ...
2142
+	'Position',[0.31 0.7148594377510039 0.15 0.09638554216867469], ...
2143
+	'Style','edit', ...
2144
+	'Tag','EditText2');
2145
+
2146
+data.small_val_h = h1;
2147
+
2148
+h1 = uicontrol('Parent',h0, ...
2149
+	'Units','normalized', ...
2150
+	'BackgroundColor',[1 1 1], ...
2151
+	'ListboxTop',0, ...
2152
+	'Position',[0.31 0.606425702811245 0.15 0.09638554216867469], ...
2153
+	'Style','edit', ...
2154
+	'Tag','EditText3');
2155
+
2156
+data.equal_val_h=h1;
2157
+
2158
+h1 = uicontrol('Parent',h0, ...
2159
+	'Units','normalized', ...
2160
+	'BackgroundColor',[0.8 0.8 0.8], ...
2161
+	'FontSize',6, ...
2162
+	'FontWeight','demi', ...
2163
+	'HorizontalAlignment','left', ...
2164
+	'ListboxTop',0, ...
2165
+	'Position',[0.06000000000000001 0.8473895582329316 0.22 0.05622489959839357], ...
2166
+	'String','Bigger than', ...
2167
+	'Style','text', ...
2168
+	'Tag','StaticText1');
2169
+h1 = uicontrol('Parent',h0, ...
2170
+	'Units','normalized', ...
2171
+	'BackgroundColor',[0.8 0.8 0.8], ...
2172
+	'FontSize',6, ...
2173
+	'FontWeight','demi', ...
2174
+	'HorizontalAlignment','left', ...
2175
+	'ListboxTop',0, ...
2176
+	'Position',[0.06000000000000001 0.7389558232931727 0.24 0.04819277108433735], ...
2177
+	'String','Smaller than', ...
2178
+	'Style','text', ...
2179
+	'Tag','StaticText2');
2180
+h1 = uicontrol('Parent',h0, ...
2181
+	'Units','normalized', ...
2182
+	'BackgroundColor',[0.8 0.8 0.8], ...
2183
+	'FontSize',6, ...
2184
+	'FontWeight','demi', ...
2185
+	'HorizontalAlignment','left', ...
2186
+	'ListboxTop',0, ...
2187
+	'Position',[0.06000000000000001 0.610441767068273 0.22 0.07228915662650602], ...
2188
+	'String','Equal to', ...
2189
+	'Style','text', ...
2190
+	'Tag','StaticText3');
2191
+
2192
+h1 = uicontrol('Parent',h0, ...
2193
+	'Units','normalized', ...
2194
+	'BackgroundColor',[0.8 0.8 0.8], ...
2195
+	'ListboxTop',0, ...
2196
+	'Position',[0.07000000000000001 0.465863453815261 0.06333333333333334 0.07228915662650602], ...
2197
+	'Style','radiobutton', ...
2198
+	'Value',1,...
2199
+	'Tag','Radiobutton1');
2200
+
2201
+data.and_button_h=h1;
2202
+
2203
+h1 = uicontrol('Parent',h0, ...
2204
+	'Units','normalized', ...
2205
+	'BackgroundColor',[0.8 0.8 0.8], ...
2206
+	'ListboxTop',0, ...
2207
+	'Position',[0.07000000000000001 0.3734939759036144 0.06333333333333334 0.07228915662650602], ...
2208
+	'Style','radiobutton', ...
2209
+	'Tag','Radiobutton2');
2210
+
2211
+data.or_button_h=h1;
2212
+
2213
+h1 = uicontrol('Parent',h0, ...
2214
+	'Units','normalized', ...
2215
+	'BackgroundColor',[0.8 0.8 0.8], ...
2216
+	'FontSize',6, ...
2217
+	'FontWeight','demi', ...
2218
+	'HorizontalAlignment','left', ...
2219
+	'Position',[0.1466666666666667 0.45 0.2333333333333333 0.07228915662650602], ...
2220
+	'String','AND', ...
2221
+	'Style','text', ...
2222
+	'Tag','StaticText4');
2223
+
2224
+h1 = uicontrol('Parent',h0, ...
2225
+	'Units','normalized', ...
2226
+	'BackgroundColor',[0.8 0.8 0.8], ...
2227
+	'FontSize',6, ...
2228
+	'FontWeight','demi', ...
2229
+	'HorizontalAlignment','left', ...
2230
+	'ListboxTop',0, ...
2231
+	'String','OR', ...
2232
+	'Position',[0.1466666666666667 0.35 0.2333333333333333 0.07228915662650602], ...
2233
+	'Style','text', ...
2234
+	'Tag','StaticText5');
2235
+
2236
+h1 = uicontrol('Parent',h0, ...
2237
+	'Units','normalized', ...
2238
+	'BackgroundColor',[0.8 0.8 0.8], ...
2239
+	'ListboxTop',0, ...
2240
+	'Position',[0.07000000000000001 0.1967871485943775 0.06333333333333334 0.07228915662650602], ...
2241
+	'Style','radiobutton', ...
2242
+	'Value',1,...
2243
+	'Tag','Radiobutton3');
2244
+
2245
+data.all_button_h=h1;
2246
+
2247
+h1 = uicontrol('Parent',h0, ...
2248
+	'Units','normalized', ...
2249
+	'BackgroundColor',[0.8 0.8 0.8], ...
2250
+	'ListboxTop',0, ...
2251
+	'Position',[0.07000000000000001 0.09236947791164658 0.06333333333333334 0.07228915662650602], ...
2252
+	'Style','radiobutton', ...
2253
+	'Tag','Radiobutton4');
2254
+
2255
+data.sel_vects_button_h=h1;
2256
+
2257
+h1 = uicontrol('Parent',h0, ...
2258
+	'Units','normalized', ...
2259
+	'BackgroundColor',[0.8 0.8 0.8], ...
2260
+	'FontSize',6, ...
2261
+	'FontWeight','demi', ...
2262
+	'HorizontalAlignment','left', ...
2263
+	'ListboxTop',0, ...
2264
+	'Position',[0.1466666666666667 0.1927710843373494 0.2333333333333333 0.07228915662650602], ...
2265
+	'String','All vectors', ...
2266
+	'Style','text', ...
2267
+	'Tag','StaticText6');
2268
+h1 = uicontrol('Parent',h0, ...
2269
+	'Units','normalized', ...
2270
+	'BackgroundColor',[0.8 0.8 0.8], ...
2271
+	'FontSize',6, ...
2272
+	'FontWeight','demi', ...
2273
+	'HorizontalAlignment','left', ...
2274
+	'ListboxTop',0, ...
2275
+	'Position',[0.1466666666666667 0.09638554216867469 0.3133333333333334 0.05622489959839357], ...
2276
+	'String','Among selected', ...
2277
+	'Style','text', ...
2278
+	'Tag','StaticText7');
2279
+h1 = uicontrol('Parent',h0, ...
2280
+	'Units','normalized', ...
2281
+	'BackgroundColor',[1 1 1], ...
2282
+	'ListboxTop',0, ...
2283
+	'Position',[0.7866666666666667 0.823293172690763 0.1366666666666667 0.09236947791164658], ...
2284
+	'Style','edit', ...
2285
+	'Tag','EditText4');
2286
+
2287
+data.replace_val_h=h1;
2288
+
2289
+h1 = uicontrol('Parent',h0, ...
2290
+	'Units','normalized', ...
2291
+	'BackgroundColor',[0.8 0.8 0.8], ...
2292
+	'FontSize',6, ...
2293
+	'FontWeight','demi', ...
2294
+	'HorizontalAlignment','left', ...
2295
+	'ListboxTop',0, ...
2296
+	'Position',[0.5633333333333334 0.8273092369477911 0.2066666666666667 0.07630522088353413], ...
2297
+	'String','Replace', ...
2298
+	'Style','text', ...
2299
+	'Tag','StaticText8');
2300
+h1 = uicontrol('Parent',h0, ...
2301
+	'Units','normalized', ...
2302
+	'FontWeight','demi', ...
2303
+	'ListboxTop',0, ...
2304
+	'Position',[0.5700000000000001 0.6827309236947791 0.3566666666666667 0.08032128514056225], ...
2305
+	'String','Replace', ...
2306
+	'Tag','Pushbutton1');
2307
+
2308
+data.OK_button_h=h1;
2309
+
2310
+h1 = uicontrol('Parent',h0, ...
2311
+	'Units','normalized', ...
2312
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
2313
+	'Callback','preprocess close_c',...
2314
+	'FontWeight','demi', ...
2315
+	'ListboxTop',0, ...
2316
+	'Position',[0.6633333333333333 0.07228915662650602 0.2833333333333333 0.09638554216867469], ...
2317
+	'String','Close', ...
2318
+	'Tag','Pushbutton2');
2319
+
2320
+
2321
+data.state.and=1;
2322
+data.state.all=1;
2323
+data.state.big=[];
2324
+data.state.small=[];
2325
+data.state.equal=[];
2326
+data.state.replace=[];
2327
+
2328
+set(data.or_button_h,'Callback','preprocess and_or_cb or');
2329
+set(data.and_button_h,'Callback','preprocess and_or_cb and');
2330
+set(data.and_button_h,'Value',1);
2331
+set(data.all_button_h,'Callback','preprocess all_sel_cb all');
2332
+set(data.sel_vects_button_h,'Callback','preprocess all_sel_cb sel');
2333
+set(data.big_val_h,'Callback','preprocess set_state_vals big');
2334
+set(data.small_val_h,'Callback','preprocess set_state_vals small');
2335
+set(data.equal_val_h,'Callback','preprocess set_state_vals equal');
2336
+set(data.replace_val_h,'Callback','preprocess set_state_vals replace');
2337
+set(data.OK_button_h,'Callback','preprocess clip_data clip');
2338
+set(h0,'UserData',data);
2339
+
2340
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2341
+
2342
+function select(varargin)
2343
+
2344
+if nargin ~= 1
2345
+  pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
2346
+  preh_udata=get(pre_h,'UserData');
2347
+  preh_udata.LOG{length(preh_udata.LOG)+1}=...
2348
+      '% Starting the ''Select'' -window...';
2349
+  preh_udata.LOG{length(preh_udata.LOG)+1}='preprocess(''select'',''foo'');';
2350
+  set(pre_h,'UserData',preh_udata);
2351
+end
2352
+
2353
+sel_h=findobj(get(0,'Children'),'Tag','Select');
2354
+
2355
+if ~isempty(sel_h)
2356
+  figure(sel_h);
2357
+  return;
2358
+end
2359
+
2360
+h0 = figure('Color',[0.8 0.8 0.8], ...
2361
+	'PaperPosition',[18 180 576 432], ...
2362
+	'PaperUnits','points', ...
2363
+	'Position',[750 431 168 365], ...
2364
+	'Tag','Select');
2365
+h1 = uicontrol('Parent',h0, ...
2366
+	'Units','normalized', ...
2367
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
2368
+	'ListboxTop',0, ...
2369
+	'Position',[0.05357142857142857 0.2712328767123288 0.8333333333333333 0.6301369863013698], ...
2370
+	'Style','frame', ...
2371
+	'Tag','Frame1');
2372
+
2373
+h1 = uicontrol('Parent',h0, ...
2374
+	'Units','normalized', ...
2375
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
2376
+	'ListboxTop',0, ...
2377
+	'Position',[0.05357142857142857 0.1041095890410959 0.8333333333333333 0.1397260273972603], ...
2378
+	'Style','frame', ...
2379
+	'Tag','Frame2');
2380
+
2381
+h1 = uicontrol('Parent',h0,...
2382
+	'Units','normalized', ...
2383
+	'BackgroundColor',[0.8 0.8 0.8], ...
2384
+	'ListboxTop',0, ...
2385
+	'Position',[0.09523809523809523 0.6547945205479452 0.75 0.2273972602739726], ...
2386
+	'Style','frame', ...
2387
+	'Tag','Frame3');
2388
+
2389
+h1 = uicontrol('Parent',h0, ...
2390
+	'Units','normalized', ...
2391
+	'BackgroundColor',[0.8 0.8 0.8], ...
2392
+	'ListboxTop',0, ...
2393
+	'Position',[0.09523809523809523 0.4794520547945206 0.75 0.1506849315068493], ...
2394
+	'Style','frame', ...
2395
+	'Tag','Frame4');
2396
+
2397
+h1 = uicontrol('Parent',h0, ...
2398
+	'Units','normalized', ...
2399
+	'BackgroundColor',[0.8 0.8 0.8], ...
2400
+	'ListboxTop',0, ...
2401
+	'Position',[0.09523809523809523 0.2986301369863014 0.75 0.1506849315068493], ...
2402
+	'Style','frame', ...
2403
+	'Tag','Frame5');
2404
+
2405
+h1 = uicontrol('Parent',h0, ...
2406
+	'Units','normalized', ...
2407
+	'BackgroundColor',[1 1 1], ...
2408
+	'ListboxTop',0, ...
2409
+	'Position',[0.5535714285714285 0.8082191780821918 0.2678571428571429 0.06575342465753425], ...
2410
+	'Style','edit', ...
2411
+	'Tag','EditText1');
2412
+
2413
+data.big_val_h=h1;
2414
+
2415
+h1 = uicontrol('Parent',h0, ...
2416
+	'Units','normalized', ...
2417
+	'BackgroundColor',[1 1 1], ...
2418
+	'ListboxTop',0, ...
2419
+	'Position',[0.5535714285714285 0.7342465753424657 0.2678571428571429 0.06575342465753425], ...
2420
+	'Style','edit', ...
2421
+	'Tag','EditText2');
2422
+
2423
+data.small_val_h = h1;
2424
+
2425
+h1 = uicontrol('Parent',h0, ...
2426
+	'Units','normalized', ...
2427
+	'BackgroundColor',[1 1 1], ...
2428
+	'ListboxTop',0, ...
2429
+	'Position',[0.5535714285714285 0.6602739726027397 0.2678571428571429 0.06575342465753425], ...
2430
+	'Style','edit', ...
2431
+	'Tag','EditText3');
2432
+
2433
+data.equal_val_h=h1;
2434
+
2435
+h1 = uicontrol('Parent',h0, ...
2436
+	'BackgroundColor',[0.8 0.8 0.8], ...
2437
+	'Units','normalized', ...
2438
+	'FontWeight','demi', ...
2439
+	'FontSize',8,...
2440
+	'HorizontalAlignment','left', ...
2441
+	'ListboxTop',0, ...
2442
+	'Position',[0.1071 0.8247 0.3929 0.0384], ...
2443
+	'String','Bigger than', ...
2444
+	'Style','text', ...
2445
+	'Tag','StaticText1');
2446
+
2447
+h1 = uicontrol('Parent',h0, ...
2448
+	'BackgroundColor',[0.8 0.8 0.8], ...
2449
+	'Units','normalized', ...
2450
+	'FontWeight','demi', ...
2451
+	'FontSize',8,...
2452
+	'HorizontalAlignment','left', ...
2453
+	'ListboxTop',0, ...
2454
+	'Position',[0.1071 0.7507 0.4286 0.0329], ...
2455
+	'String','Smaller than', ...
2456
+	'Style','text', ...
2457
+	'Tag','StaticText2');
2458
+
2459
+h1 = uicontrol('Parent',h0, ...
2460
+	'Units','normalized', ...
2461
+	'BackgroundColor',[0.8 0.8 0.8], ...
2462
+	'FontWeight','demi', ...
2463
+	'FontSize',8,...
2464
+	'HorizontalAlignment','left', ...
2465
+	'ListboxTop',0, ...
2466
+	'Position',[0.1071 0.6630 0.3929 0.0493], ...
2467
+	'String','Equal to', ...
2468
+	'Style','text', ...
2469
+	'Tag','StaticText3');
2470
+
2471
+h1 = uicontrol('Parent',h0, ...
2472
+	'Units','normalized', ...
2473
+	'BackgroundColor',[0.8 0.8 0.8], ...
2474
+	'ListboxTop',0, ...
2475
+	'Position',[0.125 0.5643835616438356 0.1130952380952381 0.04931506849315068], ...
2476
+	'Style','radiobutton', ...
2477
+	'Tag','Radiobutton1');
2478
+
2479
+data.and_button_h = h1;
2480
+
2481
+h1 = uicontrol('Parent',h0, ...
2482
+	'Units','normalized', ...
2483
+	'BackgroundColor',[0.8 0.8 0.8], ...
2484
+	'ListboxTop',0, ...
2485
+	'Position',[0.125 0.5013698630136987 0.1130952380952381 0.04931506849315068], ...
2486
+	'Style','radiobutton', ...
2487
+	'Tag','Radiobutton2');
2488
+
2489
+data.or_button_h = h1;
2490
+
2491
+h1 = uicontrol('Parent',h0, ...
2492
+	'Units','normalized', ...
2493
+	'BackgroundColor',[0.8 0.8 0.8], ...
2494
+	'FontWeight','demi', ...
2495
+	'FontSize',8,...
2496
+	'HorizontalAlignment','left', ...
2497
+	'ListboxTop',0, ...
2498
+	'Position',[0.2619047619047619 0.5561643835616439 0.3809523809523809 0.05205479452054795], ...
2499
+	'String','AND', ...
2500
+	'Style','text', ...
2501
+	'Tag','StaticText4');
2502
+
2503
+h1 = uicontrol('Parent',h0, ...
2504
+	'Units','normalized', ...
2505
+	'BackgroundColor',[0.8 0.8 0.8], ...
2506
+	'FontWeight','demi', ...
2507
+	'FontSize',8,...
2508
+	'HorizontalAlignment','left', ...
2509
+	'ListboxTop',0, ...
2510
+	'Position',[0.2619047619047619 0.4986301369863014 0.3809523809523809 0.04657534246575343], ...
2511
+	'String','OR', ...
2512
+	'Style','text', ...
2513
+	'Tag','StaticText5');
2514
+
2515
+h1 = uicontrol('Parent',h0, ...
2516
+	'Units','normalized', ...
2517
+	'BackgroundColor',[0.8 0.8 0.8], ...
2518
+	'ListboxTop',0, ...
2519
+	'Position',[0.125 0.3808219178082192 0.1130952380952381 0.04931506849315068], ...
2520
+	'Style','radiobutton', ...
2521
+	'Tag','Radiobutton3');
2522
+
2523
+data.all_button_h = h1;
2524
+
2525
+h1 = uicontrol('Parent',h0, ...
2526
+	'Units','normalized', ...
2527
+	'BackgroundColor',[0.8 0.8 0.8], ...
2528
+	'ListboxTop',0, ...
2529
+	'Position',[0.125 0.3095890410958904 0.1130952380952381 0.04931506849315068], ...
2530
+	'Style','radiobutton', ...
2531
+	'Tag','Radiobutton4');
2532
+
2533
+data.sel_vects_button_h = h1;
2534
+
2535
+h1 = uicontrol('Parent',h0, ...
2536
+	'Units','normalized', ...
2537
+	'BackgroundColor',[0.8 0.8 0.8], ...
2538
+	'FontWeight','demi', ...
2539
+	'FontSize',8,...
2540
+	'HorizontalAlignment','left', ...
2541
+	'ListboxTop',0, ...
2542
+	'Position',[0.2619047619047619 0.3780821917808219 0.4166666666666666 0.04931506849315068], ...
2543
+	'String','All vectors', ...
2544
+	'Style','text', ...
2545
+	'Tag','StaticText6');
2546
+
2547
+h1 = uicontrol('Parent',h0, ...
2548
+	'Units','normalized', ...
2549
+	'BackgroundColor',[0.8 0.8 0.8], ...
2550
+	'FontWeight','demi', ...
2551
+	'FontSize',8,...
2552
+	'HorizontalAlignment','left', ...
2553
+	'ListboxTop',0, ...
2554
+	'Position',[0.2619047619047619 0.3123287671232877 0.5595238095238095 0.03835616438356165], ...
2555
+	'String','Among selected', ...
2556
+	'Style','text', ...
2557
+	'Tag','StaticText7');
2558
+
2559
+h1 = uicontrol('Parent',h0, ...
2560
+	'Units','normalized', ...
2561
+	'BackgroundColor',[0.8 0.8 0.8], ...
2562
+	'ListboxTop',0, ...
2563
+	'Position',[0.0952    0.1178    0.7500    0.1068], ...
2564
+	'Style','frame', ...
2565
+	'Tag','Frame6');
2566
+
2567
+h1 = uicontrol('Parent',h0, ...
2568
+	'Units','normalized', ...
2569
+	'BackgroundColor',[1 1 1], ...
2570
+	'ListboxTop',0, ...
2571
+	'Position',[0.5298    0.1342    0.2738    0.0712], ...
2572
+	'Style','edit', ...
2573
+	'Tag','EditText4');
2574
+
2575
+data.replace_val_h = h1;
2576
+
2577
+h1 = uicontrol('Parent',h0, ...
2578
+	'Units','normalized', ...
2579
+	'BackgroundColor',[0.8 0.8 0.8], ...
2580
+	'FontSize',8,...
2581
+	'FontWeight','demi', ...
2582
+	'HorizontalAlignment','left', ...
2583
+	'ListboxTop',0, ...
2584
+	'Position',[0.1369047619047619 0.136986301369863 0.3214285714285714 0.06027397260273973], ...
2585
+	'String','Vectors', ...
2586
+	'Style','text', ...
2587
+	'Tag','StaticText8');
2588
+
2589
+h1 = uicontrol('Parent',h0, ...
2590
+	'Units','normalized', ...
2591
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
2592
+	'FontWeight','demi', ...
2593
+	'ListboxTop',0, ...
2594
+	'Position',[0.05357142857142857 0.01917808219178082 0.3869047619047619 0.0684931506849315], ...
2595
+	'String','OK', ...
2596
+	'Tag','Pushbutton1');
2597
+
2598
+data.OK_button_h = h1;
2599
+
2600
+h1 = uicontrol('Parent',h0, ...
2601
+	'Units','normalized', ...
2602
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
2603
+	'Callback','preprocess close_s',...
2604
+	'FontWeight','demi', ...
2605
+	'ListboxTop',0, ...
2606
+	'Position',[0.5 0.01917808219178082 0.3869047619047619 0.0684931506849315], ...
2607
+	'String','Close', ...
2608
+	'Tag','Pushbutton2');
2609
+
2610
+
2611
+
2612
+data.state.and=1;
2613
+data.state.all=1;
2614
+data.state.big=[];
2615
+data.state.small=[];
2616
+data.state.equal=[];
2617
+data.state.replace=[];
2618
+
2619
+set(data.or_button_h,'Callback','preprocess and_or_cb or');
2620
+set(data.and_button_h,'Callback','preprocess and_or_cb and');
2621
+set(data.and_button_h,'Value',1);
2622
+set(data.all_button_h,'Callback','preprocess all_sel_cb all');
2623
+set(data.sel_vects_button_h,'Callback','preprocess all_sel_cb sel');
2624
+set(data.big_val_h,'Callback','preprocess set_state_vals big');
2625
+set(data.small_val_h,'Callback','preprocess set_state_vals small');
2626
+set(data.equal_val_h,'Callback','preprocess set_state_vals equal');
2627
+set(data.replace_val_h,'Callback','preprocess set_state_vals replace');
2628
+set(data.OK_button_h,'Callback','preprocess clip_data sel');
2629
+set(h0,'UserData',data);
2630
+
2631
+
2632
+
2633
+%%% Subfunction: and_or_cb %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2634
+
2635
+function and_or_cb(arg)
2636
+
2637
+%AND_OR_CB  A callback function. Checks that only one of the radiobox
2638
+%           buttons 'AND' and 'OR' is pressed down.
2639
+%
2640
+%
2641
+
2642
+and_button_h=getfield(get(gcf,'UserData'),'and_button_h');
2643
+or_button_h=getfield(get(gcf,'UserData'),'or_button_h');
2644
+data=get(gcf,'UserData');
2645
+
2646
+switch arg
2647
+  case 'or'
2648
+   set(and_button_h,'Value',0);
2649
+   set(or_button_h,'Value',1);
2650
+   data.state.and=0;
2651
+  case 'and'
2652
+   set(or_button_h,'Value',0);
2653
+   set(and_button_h,'Value',1);
2654
+   data.state.and=1;
2655
+end
2656
+
2657
+set(gcf,'UserData',data);
2658
+
2659
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2660
+
2661
+%%% Subfunction: all_sel_cb %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2662
+
2663
+function all_sel_cb(arg)
2664
+
2665
+all_button_h=getfield(get(gcf,'UserData'),'all_button_h');
2666
+sel_vects_button_h=getfield(get(gcf,'UserData'),'sel_vects_button_h');
2667
+data=get(gcf,'UserData');
2668
+
2669
+switch arg
2670
+ case 'all'
2671
+  set(sel_vects_button_h,'Value',0);
2672
+  set(all_button_h,'Value',1);
2673
+  data.state.all=1;
2674
+ case 'sel'
2675
+  set(all_button_h,'Value',0);
2676
+  set(sel_vects_button_h,'Value',1);
2677
+  data.state.all=0;
2678
+end
2679
+
2680
+set(gcf,'UserData',data);
2681
+
2682
+%%% Subfunction: set_state_vals %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2683
+
2684
+function set_state_vals(arg)
2685
+
2686
+%SET_STATE_VALS  sets the values to the UserData's state-struct.
2687
+%
2688
+%
2689
+
2690
+
2691
+data=get(gcf,'UserData');
2692
+
2693
+switch arg
2694
+  case 'big'
2695
+   big_val_h=getfield(get(gcf,'UserData'),'big_val_h');
2696
+   val =str2num(get(big_val_h,'String'));
2697
+   dims=size(val);
2698
+   if dims(1) ~= 1 | dims(2) ~= 1
2699
+     errordlg('Argument of the operation must be scalar.');
2700
+     set(big_val_h,'String','');
2701
+     return;
2702
+   end 
2703
+   if isreal(val) 
2704
+     data.state.big=val;
2705
+   else
2706
+     errordlg('Limits of the operation must be real.');
2707
+     set(big_val_h,'String','');
2708
+     return;
2709
+   end
2710
+  case 'small'
2711
+   small_val_h=getfield(get(gcf,'UserData'),'small_val_h');
2712
+   val=str2num(get(small_val_h,'String'));
2713
+   dims=size(val);
2714
+   if dims(1) ~= 1 | dims(2) ~= 1
2715
+     errordlg('Argument of the operation must be scalar.')
2716
+     set(small_val_h,'String','');
2717
+     return;
2718
+   end 
2719
+   if isreal(val)
2720
+     data.state.small=val;
2721
+   else
2722
+     errordlg('Limits of the operation must be real.');
2723
+     set(small_val_h,'String','');
2724
+     return;
2725
+   end 
2726
+  case 'equal'
2727
+   equal_val_h=getfield(get(gcf,'UserData'),'equal_val_h');
2728
+   val = str2num(get(equal_val_h,'String'));
2729
+   dims=size(val);
2730
+   if dims(1) ~= 1 | dims(2) ~= 1
2731
+     errordlg('Argument of the operation must be scalar.');
2732
+     set(equal_val_h,'String','');
2733
+     return;
2734
+   end
2735
+   if isreal(val)
2736
+     data.state.equal=val;
2737
+   else
2738
+     errordlg('Limits of the operation must be real.');
2739
+     set(equal_val_h,'String','');
2740
+     return;
2741
+   end
2742
+  case 'replace'
2743
+   replace_val_h=getfield(get(gcf,'UserData'),'replace_val_h');
2744
+   val=str2num(get(replace_val_h,'String'));
2745
+   dims=size(val);
2746
+   if (dims(1) ~= 1 | dims(2) ~= 1) & ~strcmp(get(gcf,'Tag'),'Select')
2747
+     errordlg('Argument of the operation must be scalar.');
2748
+     set(replace_val_h,'String','');
2749
+     return;
2750
+   end
2751
+   if isreal(val)
2752
+     data.state.replace=val;
2753
+   else
2754
+     errordlg('Limits of the operation must be real.');
2755
+     set(replace_val_h,'String','');
2756
+     return;
2757
+   end
2758
+end
2759
+
2760
+set(gcf,'UserData',data);   
2761
+
2762
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2763
+
2764
+%%% Subfunction: clip_data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2765
+
2766
+function clip_data(arg)
2767
+
2768
+%CLIP_DATA  A callback function. Filters the data.
2769
+%
2770
+%
2771
+
2772
+i=1;
2773
+while i <= length(arg) & arg(i) ~= ' '
2774
+  i=i+1;
2775
+end
2776
+
2777
+arg2=arg(i+1:length(arg));
2778
+arg=arg(1:i-1);
2779
+
2780
+if ~isempty(arg2)
2781
+  LOG=1;
2782
+  if strcmp(arg,'sel')
2783
+    c_h=findobj(get(0,'Children'),'Tag','Select');
2784
+  else
2785
+    c_h=findobj(get(0,'Children'),'Tag','Clipping');
2786
+  end
2787
+  set(0,'CurrentFigure',c_h);
2788
+  i=1;
2789
+  while i <= length(arg2) & arg2(i) ~= ' '
2790
+    i=i+1;
2791
+  end
2792
+  BT=str2num(arg2(1:i-1));
2793
+  i=i+1;
2794
+  j=i;
2795
+  while i <= length(arg2) & arg2(i) ~= ' '
2796
+    i=i+1;
2797
+  end
2798
+  ST=str2num(arg2(j:i-1));
2799
+  i=i+1;
2800
+  j=i;
2801
+  while i <= length(arg2) & arg2(i) ~= ' '
2802
+    i=i+1;
2803
+  end
2804
+  EQ=str2num(arg2(j:i-1));
2805
+  i=i+1;
2806
+  j=i;
2807
+  while i <= length(arg2) & arg2(i) ~= ' '
2808
+    i=i+1;
2809
+  end
2810
+  AND_OR=str2num(arg2(j:i-1));
2811
+  i=i+1;
2812
+  j=i;
2813
+  while i <= length(arg2) & arg2(i) ~= ' '
2814
+    i=i+1;
2815
+  end
2816
+  ALL_AMONG=str2num(arg2(j:i-1));
2817
+  i=i+1;
2818
+  j=i;
2819
+  while i <= length(arg2)
2820
+    i=i+1;
2821
+  end
2822
+  VECT_REPL=str2num(arg2(j:i-1));
2823
+else
2824
+  LOG=0;
2825
+end
2826
+
2827
+if ~LOG
2828
+  big_val_h=getfield(get(gcf,'UserData'),'big_val_h');
2829
+  small_val_h=getfield(get(gcf,'UserData'),'small_val_h');
2830
+  equal_val_h=getfield(get(gcf,'UserData'),'equal_val_h');
2831
+  replace_val_h=getfield(get(gcf,'UserData'),'replace_val_h');
2832
+end
2833
+
2834
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
2835
+
2836
+if isempty(pre_h)
2837
+  errordlg('''Preprocess'' -figure does not exist. Terminating program...');
2838
+  pro_tools('close');
2839
+  return;
2840
+end
2841
+
2842
+comp_names_h=getfield(get(pre_h,'UserData'),'comp_names_h');
2843
+selected=getfield(get(pre_h,'UserData'),'selected_vects');
2844
+sData=getfield(get(pre_h,'UserData'),'sData');
2845
+undo = sData;
2846
+state=getfield(get(gcf,'UserData'),'state');
2847
+
2848
+if LOG
2849
+  state.big=BT;
2850
+  state.small=ST;
2851
+  state.equal=EQ;
2852
+  state.replace=VECT_REPL;
2853
+  state.and=AND_OR;
2854
+  state.all=ALL_AMONG;
2855
+end
2856
+
2857
+if isempty(pre_h)
2858
+  pro_tools('close');
2859
+end
2860
+
2861
+if isempty(get(comp_names_h,'Value'))
2862
+  clear_state_vals;
2863
+  errordlg('There must be one component chosen for the operation.');
2864
+  return;
2865
+end
2866
+
2867
+n_th_comp=getfield(get_indices,{1});
2868
+
2869
+if isempty(state.big) & isempty(state.small) & isempty(state.equal) & ...
2870
+   strcmp(arg,'clip')
2871
+  clear_state_vals;
2872
+  errordlg('At least one limit must be chosen for the-operation.');
2873
+  return;
2874
+end
2875
+
2876
+if ~isempty(state.replace) & strcmp(arg,'sel')
2877
+  if ~all(state.replace == round(state.replace)) | any(state.replace < 1)
2878
+    errordlg('Indices of vectors must be positive integers.');
2879
+    return;
2880
+  elseif any(state.replace > length(sData.data(:,1)))
2881
+    errordlg('Indices of the vectors to be selected are too big.');
2882
+    return;
2883
+  end
2884
+end
2885
+
2886
+if isempty(state.replace) & strcmp(arg,'clip')
2887
+  clear_state_vals;
2888
+  errordlg('Replace value must be determined for Clipping-operation.');
2889
+  return;
2890
+end
2891
+
2892
+if isempty(state.big) & isempty(state.small) & isempty(state.equal) & ...
2893
+   isempty(state.replace)
2894
+   clear_state_vals;
2895
+   return;
2896
+end
2897
+
2898
+bt_indices=[];
2899
+lt_indices=[];
2900
+equal_indices=[];
2901
+
2902
+
2903
+if ~isempty(state.big)
2904
+  if state.all
2905
+    bt_indices=find(sData.data(:,n_th_comp) > state.big); 
2906
+  else
2907
+    bt_indices=selected(find(sData.data(selected,n_th_comp) > state.big));
2908
+  end
2909
+end
2910
+
2911
+if ~isempty(state.small)
2912
+  if state.all
2913
+    lt_indices=find(sData.data(:,n_th_comp) < state.small);
2914
+  else
2915
+    lt_indices=selected(find(sData.data(selected,n_th_comp) < state.small)); 
2916
+  end
2917
+end
2918
+
2919
+if ~isempty(state.equal)
2920
+  if isnan(state.equal)
2921
+    if state.all
2922
+      equal_indices=find(isnan(sData.data(:,n_th_comp)));
2923
+    else
2924
+      equal_indices=selected(find(isnan(sData.data(selected,n_th_comp))));
2925
+    end
2926
+  elseif state.all
2927
+    equal_indices=find(sData.data(:,n_th_comp)==state.equal);
2928
+  else
2929
+    equal_indices=selected(find(sData.data(selected,n_th_comp)==state.equal));
2930
+  end
2931
+end
2932
+
2933
+if state.and
2934
+
2935
+  if ~isempty(bt_indices) | ~isempty(lt_indices) | ~isempty(equal_indices)...
2936
+     | strcmp(arg,'sel')
2937
+
2938
+    if isempty(bt_indices) & isempty(lt_indices) & isempty(equal_indices) &...
2939
+       isempty(state.replace)
2940
+      clear_state_vals;
2941
+      return;
2942
+    end
2943
+    if isempty(bt_indices)
2944
+      if ~state.all
2945
+        bt_indices=selected;
2946
+      else
2947
+        bt_indices=1:getfield(size(sData.data),{1});
2948
+      end
2949
+    end
2950
+    if isempty(lt_indices)
2951
+      if ~state.all
2952
+        lt_indices=selected;
2953
+      else
2954
+        lt_indices=1:getfield(size(sData.data),{1});
2955
+      end
2956
+    end
2957
+    if isempty(equal_indices)
2958
+      if ~state.all
2959
+        equal_indices=selected;
2960
+      else
2961
+        equal_indices=1:getfield(size(sData.data),{1});
2962
+      end
2963
+    end
2964
+    
2965
+    indices=intersect(intersect(bt_indices,lt_indices),equal_indices);
2966
+    if strcmp(arg,'sel')
2967
+      if ~isempty(indices) | ~isempty(state.replace)
2968
+        if isempty(state.replace)
2969
+          NOTEMPTY=0;
2970
+          if ~state.all
2971
+            state.replace=selected;
2972
+          else
2973
+            state.replace=1:getfield(size(sData.data),{1});
2974
+          end
2975
+        else
2976
+          NOTEMPTY=1;
2977
+        end
2978
+        if isempty(indices)
2979
+          indices=selected;
2980
+        end
2981
+        indices=intersect(indices,state.replace);
2982
+        if isempty(indices)
2983
+          indices=selected;
2984
+        end
2985
+        data=get(pre_h,'UserData');
2986
+        data.undo.sData=sData;
2987
+        data.undo.selected=data.selected_vects;
2988
+        data.selected_vects=indices;
2989
+        if ~LOG
2990
+         if ~NOTEMPTY
2991
+           data.LOG{length(data.LOG)+1}='% Select vectors.';
2992
+           data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''clip_data'',''',...
2993
+                                                 arg,...
2994
+                                                 ' ',num2str(state.big),...
2995
+                                                 ' ',num2str(state.small),...
2996
+                                                 ' ',num2str(state.equal),...
2997
+                                                 ' ',num2str(state.and),...
2998
+                                                 ' ',num2str(state.all),...
2999
+                                                 ''');');
3000
+         else
3001
+           code=write_log_code(state.replace,...
3002
+                               arg,...
3003
+                               state.big,...
3004
+                               state.small,...
3005
+                               state.equal,...
3006
+                               state.and,...
3007
+                               state.all);
3008
+           data.LOG(length(data.LOG)+1:length(data.LOG)+length(code))=code;
3009
+         end 
3010
+        end 
3011
+        set(pre_h,'UserData',data);
3012
+        old=gcf;
3013
+        set(0,'CurrentFigure',pre_h);
3014
+        sel_comp;
3015
+        cplot_mimema;
3016
+        vect_means(data.sData,data.vect_mean_h,data.selected_vects);
3017
+        set(0,'CurrentFigure',old);
3018
+      end
3019
+      clear_state_vals;
3020
+      return;
3021
+    end
3022
+    sData.data(indices,n_th_comp) = state.replace;
3023
+    sData.MODIFIED=1;
3024
+  end
3025
+else
3026
+  indices=union(union(bt_indices,lt_indices),equal_indices);
3027
+  if ~isempty(indices) | strcmp(arg,'sel')
3028
+    if strcmp(arg,'sel')
3029
+      if ~isempty(indices) | ~isempty(state.replace')
3030
+        data=get(pre_h,'UserData');
3031
+        data.undo.sData=sData;
3032
+        data.undo.selected=data.selected_vects;
3033
+        data.selected_vects=union(indices,state.replace);
3034
+        if ~LOG
3035
+         if isempty(state.replace);
3036
+           data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''clip_data'',''',...
3037
+                                                 arg,...
3038
+                                                 ' ',num2str(state.big),...
3039
+                                                 ' ',num2str(state.small),...
3040
+                                                 ' ',num2str(state.equal),...
3041
+                                                 ' ',num2str(state.and),...
3042
+                                                 ' ',num2str(state.all),...
3043
+                                                 ''');');
3044
+         else
3045
+           code=write_log_code(state.replace,...
3046
+                               arg,...
3047
+                               state.big,...
3048
+                               state.small,...
3049
+                               state.equal,...
3050
+                               state.and,...
3051
+                               state.all);
3052
+           data.LOG(length(data.LOG)+1:length(data.LOG)+length(code))=code;
3053
+         end
3054
+        end 
3055
+        set(pre_h,'UserData',data);
3056
+        old=gcf;
3057
+        set(0,'CurrentFigure',pre_h);
3058
+        sel_comp;
3059
+	vect_means(data.sData,data.vect_mean_h,data.selected_vects);
3060
+        cplot_mimema;
3061
+        set(0,'CurrentFigure',old);
3062
+      end
3063
+      clear_state_vals;
3064
+      return;
3065
+    end
3066
+    sData.data(indices,n_th_comp)=state.replace;
3067
+    sData.MODIFIED=1;
3068
+  end
3069
+end
3070
+
3071
+if sData.MODIFIED
3072
+  data=get(pre_h,'UserData');
3073
+  data.sData=sData;
3074
+  data.undo.sData=undo;
3075
+  if ~LOG
3076
+    if strcmp(arg,'sel')
3077
+      data.LOG{length(data.LOG)+1}='% Select vectors';
3078
+    else
3079
+      data.LOG{length(data.LOG)+1}='% Clip values.';
3080
+    end
3081
+    if strcmp(arg,'clip') | isempty(state.replace)
3082
+     data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''clip_data'',''',arg,...
3083
+                                                 ' ',num2str(state.big),...
3084
+                                                 ' ',num2str(state.small),...
3085
+                                                 ' ',num2str(state.equal),...
3086
+                                                 ' ',num2str(state.and),...
3087
+                                                 ' ',num2str(state.all),...
3088
+                                                 ' ',num2str(state.replace),...
3089
+                                                 ''');');
3090
+    else
3091
+      code=write_log_code(state.replace,...
3092
+                          arg,...
3093
+                          state.big,...
3094
+                          state.small,...
3095
+                          state.equal,...
3096
+                          state.and,...
3097
+                          state.all);
3098
+      data.LOG(length(data.LOG)+1:length(data.LOG)+length(code))=code;
3099
+    end
3100
+  end 
3101
+  set(pre_h,'UserData',data);
3102
+  old=gcf;
3103
+  set(0,'CurrentFigure',pre_h)
3104
+
3105
+  vector_h=getfield(get(gcf,'UserData'),'vector_h');
3106
+  vect_mean_h=getfield(get(gcf,'UserData'),'vect_mean_h');
3107
+  set(gcf,'CurrentAxes',vector_h);
3108
+  vect_means(sData,vect_mean_h,selected);
3109
+  cplot_mimema;
3110
+  sel_comp;
3111
+
3112
+  set(0,'CurrentFigure',old);
3113
+end
3114
+
3115
+clear_state_vals;
3116
+
3117
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3118
+
3119
+%%% Subfunction: clear_state_vals %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3120
+
3121
+function clear_state_vals
3122
+
3123
+%CLEAR_STATE_VALS  Sets the fields of the UserData's state-struct empty.
3124
+%
3125
+%
3126
+
3127
+
3128
+data=get(gcf,'UserData');
3129
+set(data.big_val_h,'String','');
3130
+set(data.small_val_h,'String','');
3131
+set(data.equal_val_h,'String','');
3132
+set(data.replace_val_h,'String','');
3133
+data.state.big=[];
3134
+data.state.small=[];
3135
+data.state.equal=[];
3136
+data.state.replace=[];
3137
+set(gcf,'UserData',data);
3138
+
3139
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3140
+
3141
+function delay(varargin)
3142
+
3143
+delay_h=findobj(get(0,'Children'),'Tag','Delay');
3144
+
3145
+if nargin ~= 1
3146
+  pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
3147
+  preh_udata=get(pre_h,'UserData');
3148
+  preh_udata.LOG{length(preh_udata.LOG)+1}=...
3149
+      '% Starting the ''Delay'' -window...';
3150
+  preh_udata.LOG{length(preh_udata.LOG)+1}='preprocess(''delay'',''foo'');';
3151
+  set(pre_h,'UserData',preh_udata);
3152
+end
3153
+
3154
+if ~isempty(delay_h)
3155
+  figure(delay_h);
3156
+  return;
3157
+end
3158
+
3159
+h0 = figure('Color',[0.8 0.8 0.8], ...
3160
+	'PaperPosition',[18 180 576 432], ...
3161
+	'PaperUnits','points', ...
3162
+	'Position',[759 664 162 215], ...
3163
+	'Tag','Delay');
3164
+
3165
+h1 = uicontrol('Parent',h0, ...
3166
+	'Units','normalized', ...
3167
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
3168
+	'ListboxTop',0, ...
3169
+	'Position',[0.05555555555555555 0.2046511627906977 0.8950617283950617 0.7441860465116279], ...
3170
+	'Style','frame', ...
3171
+	'Tag','Frame1');
3172
+
3173
+h1 = uicontrol('Parent',h0, ...
3174
+	'Units','normalized', ...
3175
+	'BackgroundColor',[0.8 0.8 0.8], ...
3176
+	'ListboxTop',0, ...
3177
+	'Position',[0.08641975308641975 0.6976744186046512 0.8333333333333333 0.2232558139534884], ...
3178
+	'Style','frame', ...
3179
+	'Tag','Frame2');
3180
+
3181
+h1 = uicontrol('Parent',h0, ...
3182
+	'Units','normalized', ...
3183
+	'BackgroundColor',[0.8 0.8 0.8], ...
3184
+	'ListboxTop',0, ...
3185
+	'Position',[0.08641975308641975 0.227906976744186 0.8333333333333333 0.4418604651162791], ...
3186
+	'Style','frame', ...
3187
+	'Tag','Frame3');
3188
+
3189
+h1 = uicontrol('Parent',h0, ...
3190
+	'Units','normalized', ...
3191
+	'Callback','preprocess delay_data',...
3192
+	'FontWeight','demi', ...
3193
+	'ListboxTop',0, ...
3194
+	'Position',[0.0556 0.0326 0.4012 0.1163], ...
3195
+	'String','OK', ...
3196
+	'Tag','Pushbutton1');
3197
+
3198
+h1 = uicontrol('Parent',h0, ...
3199
+	'Units','normalized', ...
3200
+	'Callback','preprocess close_d',...
3201
+	'FontWeight','demi', ...
3202
+	'ListboxTop',0, ...
3203
+	'Position',[0.5494 0.0326 0.4012 0.1163], ...
3204
+	'String','Close', ...
3205
+	'Tag','Pushbutton2');
3206
+
3207
+h1 = uicontrol('Parent',h0, ...
3208
+	'Units','normalized', ...
3209
+	'BackgroundColor',[1 1 1], ...
3210
+	'ListboxTop',0, ...
3211
+	'Position',[0.4876543209876543 0.7534883720930232 0.3518518518518519 0.1255813953488372], ...
3212
+	'Style','edit', ...
3213
+	'Tag','EditText1');
3214
+
3215
+data.delay_val_h = h1;
3216
+
3217
+h1 = uicontrol('Parent',h0, ...
3218
+	'Units','normalized', ...
3219
+	'BackgroundColor',[0.8 0.8 0.8], ...
3220
+	'FontWeight','demi', ...
3221
+	'HorizontalAlignment','left', ...
3222
+	'ListboxTop',0, ...
3223
+	'Position',[0.1173 0.7860 0.3086 0.0651], ...
3224
+	'String','Delay', ...
3225
+	'Style','text', ...
3226
+	'Tag','StaticText1');
3227
+
3228
+h1 = uicontrol('Parent',h0, ...
3229
+	'Units','normalized', ...
3230
+	'Callback','preprocess clip_exp_cb c_this',...
3231
+	'BackgroundColor',[0.8 0.8 0.8], ...
3232
+	'ListboxTop',0, ...
3233
+	'Position',[0.1173 0.5349 0.1173 0.0837], ...
3234
+	'Style','radiobutton', ...
3235
+	'Tag','Radiobutton1');
3236
+
3237
+data.c_this_button_h=h1;
3238
+data.mode='c_this';
3239
+
3240
+h1 = uicontrol('Parent',h0, ...
3241
+	'Units','normalized', ...
3242
+	'BackgroundColor',[0.8 0.8 0.8], ...
3243
+	'Callback','preprocess clip_exp_cb c_all',...
3244
+	'ListboxTop',0, ...
3245
+	'Position',[0.1173 0.4047 0.1173 0.0837], ...
3246
+	'Style','radiobutton', ...
3247
+	'Tag','Radiobutton2');
3248
+
3249
+data.c_all_button_h=h1;
3250
+
3251
+h1 = uicontrol('Parent',h0, ...
3252
+	'Units','normalized', ...
3253
+	'BackgroundColor',[0.8 0.8 0.8], ...
3254
+	'Callback','preprocess clip_exp_cb e_all',...
3255
+	'ListboxTop',0, ...
3256
+	'Position',[0.1173    0.2651    0.1173    0.0837], ...
3257
+	'Style','radiobutton', ...
3258
+	'Tag','Radiobutton3');
3259
+
3260
+data.e_all_button_h=h1;
3261
+
3262
+
3263
+h1 = uicontrol('Parent',h0, ...
3264
+	'Units','normalized', ...
3265
+	'BackgroundColor',[0.8 0.8 0.8], ...
3266
+	'FontWeight','demi', ...
3267
+	'FontSize',8,...
3268
+	'HorizontalAlignment','left', ...
3269
+	'ListboxTop',0, ...
3270
+	'Position',[0.26 0.5534883720930233 0.4135802469135802 0.06511627906976744], ...
3271
+	'String','Clip this', ...
3272
+	'Style','text', ...
3273
+	'Tag','StaticText2');
3274
+h1 = uicontrol('Parent',h0, ...
3275
+	'Units','normalized', ...
3276
+	'BackgroundColor',[0.8 0.8 0.8], ...
3277
+	'FontWeight','demi', ...
3278
+	'FontSize',8,...
3279
+	'HorizontalAlignment','left', ...
3280
+	'ListboxTop',0, ...
3281
+	'Position',[0.26 0.413953488372093 0.3765432098765432 0.06511627906976744], ...
3282
+	'String','Clip all', ...
3283
+	'Style','text', ...
3284
+	'Tag','StaticText3');
3285
+h1 = uicontrol('Parent',h0, ...
3286
+	'Units','normalized', ...
3287
+	'BackgroundColor',[0.8 0.8 0.8], ...
3288
+	'FontWeight','demi', ...
3289
+	'FontSize',8,...
3290
+	'HorizontalAlignment','left', ...
3291
+	'ListboxTop',0, ...
3292
+	'Position',[0.26 0.2744186046511628 0.4197530864197531 0.06511627906976744], ...
3293
+	'String','Expand all', ...
3294
+	'Style','text', ...
3295
+	'Tag','StaticText4');
3296
+
3297
+
3298
+set(gcf,'UserData',data);
3299
+
3300
+%%% Subfunction clip_exp_cb %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3301
+
3302
+function clip_exp_cb(arg)
3303
+
3304
+c_this_button_h=getfield(get(gcf,'UserData'),'c_this_button_h');
3305
+c_all_button_h=getfield(get(gcf,'UserData'),'c_all_button_h');
3306
+e_all_button_h=getfield(get(gcf,'UserData'),'e_all_button_h');
3307
+data=get(gcf,'UserData');
3308
+
3309
+
3310
+switch arg    
3311
+  case 'c_this'
3312
+   set(c_all_button_h,'Value',0);
3313
+   set(e_all_button_h,'Value',0);
3314
+   set(c_this_button_h,'Value',1);
3315
+   data.mode='c_this';
3316
+  case 'c_all'
3317
+   set(c_this_button_h,'Value',0);
3318
+   set(e_all_button_h,'Value',0);
3319
+   set(c_all_button_h,'Value',1);
3320
+   data.mode='c_all';
3321
+  case 'e_all'
3322
+   set(c_this_button_h,'Value',0);
3323
+   set(c_all_button_h,'Value',0);
3324
+   set(e_all_button_h,'Value',1);
3325
+   data.mode='e_all';
3326
+end
3327
+
3328
+set(gcf,'UserData',data);
3329
+
3330
+%%% Subfunction: delay_data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3331
+
3332
+function delay_data(varargin)
3333
+
3334
+if nargin == 1
3335
+  del_h=findobj(get(0,'Children'),'Tag','Delay');
3336
+  set(0,'CurrentFigure',del_h);
3337
+  LOG=1;
3338
+  arg=varargin{1};
3339
+  i=1;
3340
+  while i <= length(arg) & arg(i) ~= ' ' 
3341
+    i=i+1;
3342
+  end
3343
+  delay=str2num(arg(1:i-1));
3344
+  no=str2num(arg(i+1:length(arg)));
3345
+else
3346
+  LOG=0;
3347
+end
3348
+
3349
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
3350
+q='Delay operation is not evaluated.';
3351
+t='Warning';
3352
+if isempty(pre_h)
3353
+  errordlg('''Preprocess'' -figure does not exist. Terminating program...');
3354
+  pro_tools('close');
3355
+  return;
3356
+end
3357
+
3358
+sData=getfield(get(pre_h,'UserData'),'sData');
3359
+undo = sData;
3360
+data=get(gcf,'UserData');
3361
+if ~LOG
3362
+  delay=str2num(get(data.delay_val_h,'String'));
3363
+  if isempty(delay)
3364
+    errordlg('Value of ''Delay'' must be defined.');
3365
+    return
3366
+  end
3367
+  set(data.delay_val_h,'String','');
3368
+  if round(delay) ~= delay
3369
+    errordlg('Value of ''Delay'' must be integer.');
3370
+    return;
3371
+  end
3372
+end
3373
+comp_names_h=getfield(get(pre_h,'UserData'),'comp_names_h');
3374
+if isempty(get(comp_names_h,'Value'))
3375
+  errordlg('There are not components chosen.');
3376
+  return;
3377
+end
3378
+n_th_comp=getfield(get_indices,{1});
3379
+len=length(sData.data(:,1));
3380
+
3381
+if LOG
3382
+  switch no
3383
+    case 1
3384
+     data.mode='c_this';
3385
+     preprocess('clip_exp_cb','c_this');
3386
+    case 2
3387
+     data.mode='c_all';
3388
+     preprocess('clip_exp_cb','c_all');
3389
+    case 3
3390
+     data.mode='e_all';
3391
+     preprocess('clip_exp_cb','e_all');
3392
+  end
3393
+end
3394
+
3395
+switch data.mode
3396
+  case 'c_this'
3397
+   MODE='1';
3398
+   if delay > 0
3399
+     sData.data(delay+1:len,n_th_comp)=sData.data(1:len-delay);
3400
+     if delay >= len
3401
+       errordlg(q,t);
3402
+       return;
3403
+     else
3404
+       sData.data(1:delay,n_th_comp)=NaN;
3405
+     end
3406
+   elseif delay < 0
3407
+     sData.data(1:len+delay,n_th_comp)=...
3408
+              sData.data(abs(delay)+1:len,n_th_comp);    
3409
+     if abs(delay) >= len
3410
+       errordlg(q,t);
3411
+       return;
3412
+     else
3413
+       sData.data(len+delay+1:len,n_th_comp)=NaN;
3414
+     end
3415
+   end
3416
+   if delay ~= 0
3417
+     data=get(pre_h,'UserData');
3418
+     sData.MODIFIED=1;
3419
+     sData.comp_norm(n_th_comp)=[];
3420
+     data.sData=sData;
3421
+     data.undo.sData=undo;
3422
+     set(pre_h,'UserData',data);
3423
+     old = gcf;
3424
+     set(0,'CurrentFigure',pre_h);
3425
+     sel_comp;
3426
+     cplot_mimema;
3427
+     set(0,'CurrentFigure',old);
3428
+   end
3429
+  case 'c_all'
3430
+   MODE='2';
3431
+   if delay > 0
3432
+     sData.data(delay+1:len,n_th_comp)=sData.data(1:len-delay,n_th_comp);
3433
+     if delay >= len
3434
+       errordlg(q,t);
3435
+       return;
3436
+     else
3437
+       sData.data=sData.data(delay+1:len,:);
3438
+     end
3439
+   elseif delay < 0
3440
+    sData.data(1:len+delay,n_th_comp)=sData.data(abs(delay)+1:len,n_th_comp);
3441
+    if abs(delay) >= len
3442
+      errordlg(q,t);
3443
+      return;
3444
+    else
3445
+      sData.data=sData.data(1:len+delay,:);
3446
+    end
3447
+   end
3448
+   if delay ~= 0
3449
+     data=get(pre_h,'UserData');
3450
+     sData.MODIFIED=1;
3451
+     sData.comp_norm(:,:)={[]};
3452
+     data.sData=sData;
3453
+     data.undo.sData=undo;
3454
+     data.undo.selected=data.selected_vects;
3455
+     if delay > 0
3456
+       data.selected_vects=...
3457
+                        data.selected_vects(find(data.selected_vects>delay));
3458
+       data.selected_vects=data.selected_vects-delay;
3459
+     elseif nargin == 1
3460
+       data.selected_vects=...
3461
+         data.selected_vects(find(data.selected_vects<=len-abs(delay)));
3462
+     end
3463
+     set(pre_h,'UserData',data);
3464
+     old=gcf;
3465
+     set(0,'CurrentFigure',pre_h);
3466
+     vects=zeros(1,length(sData.data(:,1)));
3467
+     vects(data.selected_vects)=1;
3468
+     write_sD_stats;
3469
+     draw_vectors(vects,data.vector_h);
3470
+     sel_comp;
3471
+     cplot_mimema;
3472
+     set(0,'CurrentFigure',old);
3473
+   end
3474
+  case 'e_all'
3475
+   MODE='3';
3476
+   if delay > 0
3477
+     sData.data(len+1:len+delay,:)=NaN;
3478
+     sData.data(1+delay:delay+len,n_th_comp)=sData.data(1:len,n_th_comp);
3479
+     sData.data(1:delay,n_th_comp)=NaN;
3480
+   elseif delay < 0
3481
+     delay=abs(delay);
3482
+     sData.data(delay+1:len+delay,:)=sData.data;
3483
+     sData.data(1:delay,:)=NaN;
3484
+     sData.data(1:len,n_th_comp)=sData.data(delay+1:len+delay,n_th_comp);
3485
+     sData.data(len+1:len+delay,n_th_comp)=NaN;
3486
+   end 
3487
+   if delay ~= 0
3488
+     data=get(pre_h,'UserData');
3489
+     sData.MODIFIED=1;
3490
+     sData.comp_norm(:,:)={[]};
3491
+     data.sData=sData;
3492
+     data.undo.sData=undo;
3493
+     data.undo.selected=data.selected_vects;
3494
+     set(pre_h,'UserData',data);
3495
+     old=gcf;
3496
+     set(0,'CurrentFigure',pre_h);
3497
+     write_sD_stats;
3498
+     pro_tools('selall');
3499
+     set(0,'CurrentFigure',old);
3500
+   end
3501
+end
3502
+ 
3503
+if ~LOG
3504
+  data=get(pre_h,'UserData');
3505
+  data.LOG{length(data.LOG)+1}='% Delay a component.';
3506
+  data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''delay_data'',''',...
3507
+                                      num2str(delay),' ',MODE,''');');
3508
+  set(pre_h,'UserData',data);
3509
+end
3510
+
3511
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3512
+
3513
+function window(varargin)
3514
+
3515
+if nargin ~= 1
3516
+  pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
3517
+  preh_udata=get(pre_h,'UserData');
3518
+  preh_udata.LOG{length(preh_udata.LOG)+1}=...
3519
+    '% Starting the ''Windowed'' -window...';
3520
+  preh_udata.LOG{length(preh_udata.LOG)+1}='preprocess(''window'',''foo'');';
3521
+  set(pre_h,'UserData',preh_udata);
3522
+end
3523
+
3524
+win_h=findobj(get(0,'Children'),'Tag','Window');
3525
+
3526
+if ~isempty(win_h)
3527
+  figure(win_h);
3528
+  return;
3529
+end
3530
+
3531
+h0 = figure('Color',[0.8 0.8 0.8], ...
3532
+	'PaperPosition',[18 180 576 432], ...
3533
+	'PaperUnits','points', ...
3534
+	'Position',[513 703 288 219], ...
3535
+	'Tag','Window');
3536
+
3537
+h1 = uicontrol('Parent',h0, ...
3538
+	'Units','normalized', ...
3539
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
3540
+	'ListboxTop',0, ...
3541
+	'Position',[0.03125 0.1552511415525114 0.9375 0.7990867579908676], ...
3542
+	'Style','frame', ...
3543
+	'Tag','Frame1');
3544
+h1 = uicontrol('Parent',h0, ...
3545
+	'Units','normalized', ...
3546
+	'BackgroundColor',[0.8 0.8 0.8], ...
3547
+	'ListboxTop',0, ...
3548
+	'Position',[0.04861111111111111 0.7214611872146118 0.9027777777777777 0.2009132420091324], ...
3549
+	'Style','frame', ...
3550
+	'Tag','Frame2');
3551
+h1 = uicontrol('Parent',h0, ...
3552
+	'Units','normalized', ...
3553
+	'BackgroundColor',[0.8 0.8 0.8], ...
3554
+	'ListboxTop',0, ...
3555
+	'Position',[0.04861111111111111 0.1780821917808219 0.2777777777777778 0.5251141552511416], ...
3556
+	'Style','frame', ...
3557
+	'Tag','Frame3');
3558
+h1 = uicontrol('Parent',h0, ...
3559
+	'Units','normalized', ...
3560
+	'BackgroundColor',[0.8 0.8 0.8], ...
3561
+	'ListboxTop',0, ...
3562
+	'Position',[0.3611111111111111 0.1780821917808219 0.2777777777777778 0.5251141552511416], ...
3563
+	'Style','frame', ...
3564
+	'Tag','Frame4');
3565
+h1 = uicontrol('Parent',h0, ...
3566
+	'Units','normalized', ...
3567
+	'BackgroundColor',[0.8 0.8 0.8], ...
3568
+	'ListboxTop',0, ...
3569
+	'Position',[0.6736111111111111 0.1780821917808219 0.2777777777777778 0.5251141552511416], ...
3570
+	'Style','frame', ...
3571
+	'Tag','Frame5');
3572
+
3573
+h1 = uicontrol('Parent',h0, ...
3574
+	'Callback','preprocess eval_windowed',...	
3575
+	'Units','normalized', ...
3576
+	'FontWeight','demi', ...
3577
+	'ListboxTop',0, ...
3578
+	'Position',[0.03125 0.0319634703196347 0.2256944444444444 0.091324200913242], ...
3579
+	'String','OK', ...
3580
+	'Tag','Pushbutton1');
3581
+
3582
+h1 = uicontrol('Parent',h0, ...
3583
+	'Callback','preprocess close_w', ...
3584
+	'Units','normalized', ...
3585
+	'FontWeight','demi', ...
3586
+	'ListboxTop',0, ...
3587
+	'Position',[0.7430555555555555 0.0319634703196347 0.2256944444444444 0.091324200913242], ...
3588
+	'String','Close', ...
3589
+	'Tag','Pushbutton2');
3590
+
3591
+h1 = uicontrol('Parent',h0, ...
3592
+	'Units','normalized', ...
3593
+	'BackgroundColor',[1 1 1], ...
3594
+	'ListboxTop',0, ...
3595
+	'Position',[0.7083333333333333 0.7625570776255708 0.2083333333333333 0.1232876712328767], ...
3596
+	'Style','edit', ...
3597
+	'Tag','EditText1');
3598
+
3599
+data.win_len_h=h1;
3600
+
3601
+h1 = uicontrol('Parent',h0, ...
3602
+	'Units','normalized', ...
3603
+	'BackgroundColor',[0.8 0.8 0.8], ...
3604
+	'FontWeight','demi', ...
3605
+	'HorizontalAlignment','left', ...
3606
+	'ListboxTop',0, ...
3607
+	'Position',[0.07638888888888888 0.8036529680365296 0.3784722222222222 0.0547945205479452], ...
3608
+	'String','Window length', ...
3609
+	'Style','text', ...
3610
+	'Tag','StaticText1');
3611
+
3612
+h1 = uicontrol('Parent',h0, ...
3613
+	'Units','normalized', ...
3614
+	'BackgroundColor',[0.8 0.8 0.8], ...
3615
+	'Callback','preprocess window_cb centered',...
3616
+	'ListboxTop',0, ...
3617
+	'Position',[0.06597222222222222 0.5616438356164384 0.06597222222222222 0.0821917808219178], ...
3618
+	'Style','radiobutton', ...
3619
+	'Tag','Radiobutton1');
3620
+
3621
+data.centered_h=h1;
3622
+data.position='center';
3623
+
3624
+h1 = uicontrol('Parent',h0, ...
3625
+	'Units','normalized', ...
3626
+	'BackgroundColor',[0.8 0.8 0.8], ...
3627
+	'Callback','preprocess window_cb previous',...
3628
+	'ListboxTop',0, ...
3629
+	'Position',[0.06597222222222222 0.4018264840182648 0.06597222222222222 0.0821917808219178], ...
3630
+	'Style','radiobutton', ...
3631
+	'Tag','Radiobutton2');
3632
+
3633
+data.previous_h=h1;
3634
+
3635
+h1 = uicontrol('Parent',h0, ...
3636
+	'Units','normalized', ...
3637
+	'BackgroundColor',[0.8 0.8 0.8], ...
3638
+	'Callback','preprocess window_cb next',...
3639
+	'ListboxTop',0, ...
3640
+	'Position',[0.06597222222222222 0.2465753424657534 0.06597222222222222 0.0821917808219178], ...
3641
+	'Style','radiobutton', ...
3642
+	'Tag','Radiobutton3');
3643
+
3644
+data.next_h=h1;
3645
+
3646
+h1 = uicontrol('Parent',h0, ...
3647
+	'Units','normalized', ...
3648
+	'BackgroundColor',[0.8 0.8 0.8], ...
3649
+	 'Callback','preprocess window_cb mean',...
3650
+	'ListboxTop',0, ...
3651
+	'Position',[0.3784722222222222 0.5799086757990868 0.06597222222222222 0.0821917808219178], ...
3652
+	'Style','radiobutton', ...
3653
+	'Tag','Radiobutton4');
3654
+
3655
+data.mean_h=h1;
3656
+data.mode='mean';
3657
+
3658
+
3659
+h1 = uicontrol('Parent',h0, ...
3660
+	'Units','normalized', ...
3661
+	'BackgroundColor',[0.8 0.8 0.8], ...
3662
+	'Callback','preprocess window_cb median',...
3663
+	'ListboxTop',0, ...
3664
+	'Position',[0.3784722222222222 0.4611872146118721 0.06597222222222222 0.0821917808219178], ...
3665
+	'Style','radiobutton', ...
3666
+	'Tag','Radiobutton5');
3667
+
3668
+
3669
+data.median_h=h1;
3670
+
3671
+h1 = uicontrol('Parent',h0, ...
3672
+	'Units','normalized', ...
3673
+	'BackgroundColor',[0.8 0.8 0.8], ...
3674
+	'Callback','preprocess window_cb max',...
3675
+	'ListboxTop',0, ...
3676
+	'Position',[0.3784722222222222 0.3515981735159817 0.06597222222222222 0.0821917808219178], ...
3677
+	'Style','radiobutton', ...
3678
+	'Tag','Radiobutton6');
3679
+
3680
+data.max_h=h1;
3681
+
3682
+h1 = uicontrol('Parent',h0, ...
3683
+	'Units','normalized', ...
3684
+	'Callback','preprocess window_cb min',...
3685
+	'BackgroundColor',[0.8 0.8 0.8], ...	
3686
+	'ListboxTop',0, ...
3687
+	'Position',[0.3784722222222222 0.2374429223744292 0.06597222222222222 0.0821917808219178], ...
3688
+	'Style','radiobutton', ...
3689
+	'Tag','Radiobutton7');
3690
+
3691
+data.min_h = h1;
3692
+
3693
+h1 = uicontrol('Parent',h0, ...
3694
+	'Units','normalized', ...
3695
+	'BackgroundColor',[0.8 0.8 0.8], ...
3696
+	'Callback','preprocess window_cb clip',...
3697
+	'ListboxTop',0, ...
3698
+	'Position',[0.6909722222222222 0.5525114155251141 0.06597222222222222 0.0821917808219178], ...
3699
+	'Style','radiobutton', ...
3700
+	'Tag','Radiobutton8');
3701
+
3702
+data.clip_h=h1;
3703
+data.eval_mode='clip';
3704
+
3705
+h1 = uicontrol('Parent',h0, ...
3706
+	'Units','normalized', ...
3707
+	'BackgroundColor',[0.8 0.8 0.8], ...
3708
+	'Callback','preprocess window_cb expand',...
3709
+	'ListboxTop',0, ...
3710
+	'Position',[0.6909722222222222 0.2922374429223744 0.06597222222222222 0.0821917808219178], ...
3711
+	'Style','radiobutton', ...
3712
+	'Tag','Radiobutton9');
3713
+
3714
+data.expand_h=h1;
3715
+
3716
+h1 = uicontrol('Parent',h0, ...
3717
+	'Units','normalized', ...
3718
+	'BackgroundColor',[0.8 0.8 0.8], ...
3719
+	'FontWeight','demi', ...
3720
+	'FontSize',8,...
3721
+	'HorizontalAlignment','left', ...
3722
+	'ListboxTop',0, ...
3723
+	'Position',[0.132 0.5799 0.19 0.0548], ...
3724
+	'String','Centered', ...
3725
+	'Style','text', ...
3726
+	'Tag','StaticText2');
3727
+h1 = uicontrol('Parent',h0, ...
3728
+	'Units','normalized', ...
3729
+	'BackgroundColor',[0.8 0.8 0.8], ...
3730
+	'FontWeight','demi', ...
3731
+	'FontSize',8,...
3732
+	'HorizontalAlignment','left', ...
3733
+	'ListboxTop',0, ...
3734
+	'Position',[0.132 0.4247 0.1667 0.0548], ...
3735
+	'String','Previous', ...
3736
+	'Style','text', ...
3737
+	'Tag','StaticText3');
3738
+h1 = uicontrol('Parent',h0, ...
3739
+	'Units','normalized', ...
3740
+	'BackgroundColor',[0.8 0.8 0.8], ...
3741
+	'FontWeight','demi', ...
3742
+	'FontSize',8,...
3743
+	'HorizontalAlignment','left', ...
3744
+	'ListboxTop',0, ...
3745
+	'Position',[0.132 0.2648 0.1632 0.0548], ...
3746
+	'String','Next', ...
3747
+	'Style','text', ...
3748
+	'Tag','StaticText4');
3749
+h1 = uicontrol('Parent',h0, ...,
3750
+	'Units','normalized', ...
3751
+	'BackgroundColor',[0.8 0.8 0.8], ...
3752
+	'FontWeight','demi', ...
3753
+	'FontSize',8,...
3754
+	'HorizontalAlignment','left', ...
3755
+	'ListboxTop',0, ...
3756
+	'Position',[0.445 0.6027397260273972 0.19 0.0547945205479452], ...
3757
+	'String','Mean', ...
3758
+	'Style','text', ...
3759
+	'Tag','StaticText5');
3760
+h1 = uicontrol('Parent',h0, ...
3761
+	'Units','normalized', ...
3762
+	'BackgroundColor',[0.8 0.8 0.8], ...
3763
+	'FontWeight','demi', ...
3764
+	'FontSize',8,...
3765
+	'HorizontalAlignment','left', ...
3766
+	'ListboxTop',0, ...
3767
+	'Position',[0.445 0.4795 0.1806 0.0548], ...
3768
+	'String','Median', ...
3769
+	'Style','text', ...
3770
+	'Tag','StaticText6');
3771
+
3772
+h1 = uicontrol('Parent',h0, ...
3773
+	'Units','normalized', ...
3774
+	'BackgroundColor',[0.8 0.8 0.8], ...
3775
+	'FontWeight','demi', ...
3776
+	'FontSize',8,...
3777
+	'HorizontalAlignment','left', ...
3778
+	'ListboxTop',0, ...
3779
+	'Position',[0.445 0.3699 0.1667 0.0548], ...
3780
+	'String','Max', ...
3781
+	'Style','text', ...
3782
+	'Tag','StaticText7');
3783
+h1 = uicontrol('Parent',h0, ...
3784
+	'Units','normalized', ...
3785
+	'BackgroundColor',[0.8 0.8 0.8], ...
3786
+	'FontWeight','demi', ...
3787
+	'FontSize',8,...
3788
+	'HorizontalAlignment','left', ...
3789
+	'ListboxTop',0, ...
3790
+	'Position',[0.445 0.2557077625570776 0.1597222222222222 0.0547945205479452], ...
3791
+	'String','Min', ...
3792
+	'Style','text', ...
3793
+	'Tag','StaticText8');
3794
+h1 = uicontrol('Parent',h0, ...
3795
+	'Units','normalized', ...
3796
+	'BackgroundColor',[0.8 0.8 0.8], ...
3797
+	'FontWeight','demi', ...
3798
+	'FontSize',8,...
3799
+	'HorizontalAlignment','left', ...
3800
+	'ListboxTop',0, ...
3801
+	'Position',[0.7535 0.5753 0.1354 0.054], ...
3802
+	'String','Clip', ...
3803
+	'Style','text', ...
3804
+	'Tag','StaticText9');
3805
+h1 = uicontrol('Parent',h0, ...
3806
+	'Units','normalized', ...
3807
+	'BackgroundColor',[0.8 0.8 0.8], ...
3808
+	'FontWeight','demi', ...
3809
+	'FontSize',8,...
3810
+	'HorizontalAlignment','left', ...
3811
+	'ListboxTop',0, ...
3812
+	'Position',[0.7534722222222222 0.3150684931506849 0.1527777777777778 0.0547945205479452], ...
3813
+	'String','Expand', ...
3814
+	'Style','text', ...
3815
+	'Tag','StaticText10');
3816
+
3817
+
3818
+
3819
+set(gcf,'UserData',data);
3820
+
3821
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3822
+
3823
+function window_cb(arg)
3824
+
3825
+data=get(gcf,'UserData');
3826
+
3827
+if any(strcmp(arg,[{'centered'},{'previous'},{'next'}]))
3828
+  switch arg
3829
+    case 'centered'
3830
+     data.position='center';
3831
+     set(data.previous_h,'Value',0);
3832
+     set(data.next_h,'Value',0);
3833
+     set(data.centered_h,'Value',1);
3834
+    case 'previous'
3835
+     data.position='previous';
3836
+     set(data.centered_h,'Value',0);
3837
+     set(data.next_h,'Value',0);
3838
+     set(data.previous_h,'Value',1);
3839
+    case 'next'
3840
+     data.position='next';
3841
+     set(data.centered_h,'Value',0);
3842
+     set(data.previous_h,'Value',0);
3843
+     set(data.next_h,'Value',1);
3844
+  end
3845
+elseif any(strcmp(arg,[{'mean'},{'median'},{'min'},{'max'}]))
3846
+  switch arg
3847
+    case 'mean'
3848
+     data.mode='mean';
3849
+     set(data.median_h,'Value',0);
3850
+     set(data.min_h,'Value',0);
3851
+     set(data.max_h,'Value',0);
3852
+     set(data.mean_h,'Value',1);
3853
+    case 'median'
3854
+     data.mode='median';
3855
+     set(data.mean_h,'Value',0);
3856
+     set(data.max_h,'Value',0);
3857
+     set(data.min_h,'Value',0);
3858
+     set(data.median_h,'Value',1);
3859
+    case 'max'
3860
+     data.mode='max';
3861
+     set(data.mean_h,'Value',0);
3862
+     set(data.median_h,'Value',0);
3863
+     set(data.min_h,'Value',0);
3864
+     set(data.max_h,'Value',1);
3865
+    case 'min'
3866
+     data.mode='min';
3867
+     set(data.mean_h,'Value',0);
3868
+     set(data.median_h,'Value',0);
3869
+     set(data.max_h,'Value',0);
3870
+     set(data.min_h,'Value',1);
3871
+  end
3872
+elseif any(strcmp(arg,[{'clip','expand'}]))
3873
+  switch arg
3874
+    case 'clip'
3875
+     data.eval_mode='clip';
3876
+     set(data.expand_h,'Value',0);
3877
+     set(data.clip_h,'Value',1);
3878
+    case 'expand'
3879
+     data.eval_mode='expand';
3880
+     set(data.clip_h,'Value',0);
3881
+     set(data.expand_h,'Value',1); 
3882
+  end
3883
+end
3884
+
3885
+set(gcf,'UserData',data);
3886
+
3887
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3888
+
3889
+function eval_windowed(varargin)
3890
+
3891
+if nargin == 1
3892
+  LOG=1;
3893
+  i=1;
3894
+  arg=varargin{1};
3895
+  while i <= length(arg) & arg(i) ~= ' '
3896
+    i=i+1;
3897
+  end
3898
+  value=str2num(arg(1:i-1));
3899
+  i=i+1;
3900
+  j=i;
3901
+  while i <= length(arg) & arg(i) ~= ' '
3902
+    i=i+1;
3903
+  end
3904
+  position=arg(j:i-1);
3905
+  i=i+1;
3906
+  j=i;
3907
+  while i <= length(arg) & arg(i) ~= ' '
3908
+    i=i+1;
3909
+  end
3910
+  mode=arg(j:i-1);
3911
+  i=i+1;
3912
+  j=i;
3913
+  while i <= length(arg) & arg(i) ~= ' '
3914
+    i=i+1;
3915
+  end
3916
+  eval_mode=arg(j:i-1);
3917
+else
3918
+  LOG=0;
3919
+end
3920
+
3921
+data=get(gcf,'UserData');
3922
+if LOG
3923
+  data.position=position;
3924
+  data.eval_mode=eval_mode;
3925
+  data.mode=mode;
3926
+end
3927
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
3928
+
3929
+if isempty(pre_h)
3930
+  errordlg('''Preprocess''-window does not exist. Terminating program...');
3931
+  pro_tools('close');
3932
+  return;
3933
+end
3934
+
3935
+comp_names_h=getfield(get(pre_h,'UserData'),'comp_names_h');
3936
+sData=getfield(get(pre_h,'UserData'),'sData');
3937
+undo=sData;
3938
+
3939
+if isempty(get(comp_names_h,'Value'))
3940
+ errordlg('There are not components chosen.');
3941
+ return;
3942
+end
3943
+
3944
+if ~LOG
3945
+  if isempty(get(data.win_len_h,'String'))
3946
+    errordlg('Window length must be defined');
3947
+    return;
3948
+  end
3949
+
3950
+  value=str2num(get(data.win_len_h,'String'));
3951
+end
3952
+
3953
+set(data.win_len_h,'String','');
3954
+
3955
+if ~LOG
3956
+  if isempty(value) | value < 0 | value ~= round(value)
3957
+    errordlg('Window length must be positive integer.');
3958
+    return;
3959
+  end
3960
+
3961
+  if value > length(sData.data(:,1))
3962
+    errordlg('Length of window is too big.');
3963
+    return;
3964
+  end
3965
+end
3966
+
3967
+index=getfield(get_indices,{1});
3968
+
3969
+sData=eval_operation(sData,value,data.mode,data.eval_mode,data.position,index);
3970
+sData.comp_norm(index)={[]};
3971
+u_data=get(pre_h,'UserData');
3972
+u_data.sData=sData;
3973
+u_data.undo.sData=undo;
3974
+u_data.undo.selected=u_data.selected_vects;
3975
+
3976
+if ~LOG
3977
+  u_data.LOG{length(u_data.LOG)+1}=...
3978
+    '% Evaluating the wanted ''windowed'' -operation.';
3979
+  u_data.LOG{length(u_data.LOG)+1}=cat(2,'preprocess(''eval_windowed'',',...
3980
+                                        '''',num2str(value),...
3981
+                                       ' ',data.position,' ',data.mode,...
3982
+                                       ' ',data.eval_mode,''');');
3983
+end
3984
+ 
3985
+set(pre_h,'UserData',u_data);
3986
+old=gcf;
3987
+set(0,'CurrentFigure',pre_h);
3988
+
3989
+if strcmp(data.eval_mode,'expand');
3990
+  write_sD_stats;
3991
+  pro_tools('selall');
3992
+else
3993
+  sel_comp;
3994
+  cplot_mimema;
3995
+end
3996
+
3997
+set(0,'CurrentFigure',old);
3998
+
3999
+
4000
+
4001
+%%% Subfunction: eval_operation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4002
+
4003
+
4004
+function sData=eval_operation(sData,winlen,mode,evalmode,position,n)
4005
+
4006
+
4007
+len=length(sData.data(:,1));
4008
+dim=length(sData.data(1,:));
4009
+
4010
+switch(position)
4011
+  case 'center'
4012
+   prev=round(winlen/2)-1;
4013
+   next=winlen-round(winlen/2);
4014
+  case 'previous'
4015
+   prev=winlen-1;
4016
+   next=0;
4017
+  case 'next'
4018
+   prev=0;
4019
+   next=winlen-1;
4020
+end
4021
+
4022
+switch(evalmode)
4023
+  case 'clip'
4024
+   for center=1:len
4025
+     win=center-prev:center-prev+winlen-1;
4026
+     win=win(find(win > 0 & win <= len));
4027
+     str=cat(2,mode,'(sData.data(win(find(~isnan(sData.data(win,n)))),n))');
4028
+     tmp(center)=eval(str);
4029
+   end
4030
+   sData.data(:,n)=tmp;
4031
+  case 'expand'   
4032
+   for i=1:len+winlen-1  
4033
+     win=i-(winlen-1):i;
4034
+     win=win(find(win > 0 & win <= len));
4035
+     str=cat(2,mode,'(sData.data(win(find(~isnan(sData.data(win,n)))),n))');
4036
+     tmp(i)=eval(str);
4037
+   end  
4038
+  sData.data=cat(1,repmat(NaN,next,dim),sData.data,repmat(NaN,prev,dim));
4039
+  sData.data(:,n)=tmp;
4040
+end
4041
+
4042
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4043
+
4044
+
4045
+
4046
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4047
+
4048
+function pro_tools(arg)
4049
+
4050
+switch arg
4051
+  case 'close'
4052
+   close_preprocess;
4053
+  case 'c_stat'
4054
+   write_c_stats;
4055
+  case 'plot_hist'
4056
+   plot_hist;
4057
+  case 'plot'
4058
+   plot_button;
4059
+  case 'plxy'
4060
+   plxy_button;
4061
+  case 'bplo'
4062
+   bplo_button;
4063
+  case 'hist'
4064
+   hist_button;
4065
+end
4066
+
4067
+
4068
+%%% Subfunction close_preprocess %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4069
+
4070
+function close_preprocess
4071
+
4072
+ 
4073
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
4074
+man_h=findobj(get(0,'Children'),'Tag','Management');
4075
+clip_h=findobj(get(0,'Children'),'Tag','Clipping');
4076
+plot_h=findobj(get(0,'Children'),'Tag','PlotWin');
4077
+delay_h=findobj(get(0,'Children'),'Tag','Delay');
4078
+window_h=findobj(get(0,'Children'),'Tag','Window');
4079
+sel_h=findobj(get(0,'Children'),'Tag','Select');
4080
+
4081
+if ~isempty(man_h)
4082
+  close(man_h);
4083
+end
4084
+if ~isempty(clip_h)
4085
+  close(clip_h);
4086
+end
4087
+if ~isempty(plot_h)
4088
+  close(plot_h);
4089
+end
4090
+if ~isempty(delay_h)
4091
+  close(delay_h);
4092
+end
4093
+if ~isempty(window_h)
4094
+  close(window_h);
4095
+end
4096
+if ~isempty(sel_h)
4097
+  close(sel_h);
4098
+end
4099
+if ~isempty(pre_h)
4100
+  close(pre_h);
4101
+end
4102
+
4103
+
4104
+
4105
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4106
+
4107
+%%% Subfunction: undo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4108
+
4109
+function undo(varargin)
4110
+
4111
+if nargin == 1
4112
+  pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
4113
+  set(0,'CurrentFigure',pre_h);
4114
+  LOG=1;
4115
+else
4116
+  LOG=0;
4117
+end
4118
+
4119
+data=get(gcf,'UserData');
4120
+if ~isempty(data.undo)
4121
+  if any(strcmp('selected',fieldnames(data.undo)))
4122
+    data.selected_vects=data.undo.selected;
4123
+  end
4124
+  if ~any(strcmp('index',fieldnames(data.undo)))
4125
+    data.sData=data.undo.sData;
4126
+    data.undo=[];
4127
+    if ~LOG
4128
+      data.LOG{length(data.LOG)+1}='% Undo the most recent operation.';
4129
+      data.LOG{length(data.LOG)+1}='preprocess(''undo'',''foo'');';
4130
+    end
4131
+    set(gcf,'UserData',data);
4132
+    set_compnames(data.sData,data.comp_names_h);
4133
+    write_sD_stats;
4134
+    vect_means(data.sData,data.vect_mean_h,data.selected_vects);
4135
+    sel_comp;
4136
+    cplot_mimema;
4137
+    return;
4138
+  end
4139
+  
4140
+  % 'undo.sData' does not exist in sD_set - array
4141
+
4142
+  index=data.undo.index; 
4143
+  data.undo.sData=rmfield(data.undo.sData,[{'INDEX'};{'MODIFIED'}]);
4144
+  if index<=length(data.sD_set)
4145
+    rest=data.sD_set(index:length(data.sD_set));        
4146
+  else
4147
+    rest=[];
4148
+  end
4149
+  data.sD_set=cat(2,data.sD_set(1:index-1),data.undo.sData,rest);
4150
+  data.undo=[];
4151
+  if ~LOG
4152
+    data.LOG{length(data.LOG)+1}='% Undo the most recent operation.';
4153
+    data.LOG{length(data.LOG)+1}='preprocess(''undo'',''foo'');';
4154
+  end
4155
+  set(gcf,'UserData',data);
4156
+  set(getfield(get(gcf,'UserData'),'sD_set_h'),'Value',index);
4157
+  set_sD_stats;
4158
+  sel_sD;
4159
+else
4160
+  msgbox('Can''t do...');
4161
+end
4162
+
4163
+%%% Subfunction: write_c_stats %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4164
+
4165
+function write_c_stats(varargin)
4166
+
4167
+
4168
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
4169
+comp_names_h=getfield(get(pre_h,'UserData'),'comp_names_h');
4170
+sel_comp_h=getfield(get(pre_h,'UserData'),'sel_comp_h');
4171
+sel_chist_h=getfield(get(pre_h,'UserData'),'sel_chist_h');
4172
+
4173
+if nargin==1
4174
+  val1=varargin(1);
4175
+else
4176
+  val1=get(sel_comp_h,'String');
4177
+end
4178
+   
4179
+if ~isempty(val1) & iscell(val1)
4180
+  selected_vects=getfield(get(pre_h,'UserData'),'selected_vects');
4181
+  sData=getfield(get(pre_h,'UserData'),'sData');
4182
+  sel_cdata_h=getfield(get(pre_h,'UserData'),'sel_cdata_h');
4183
+  name=getfield(get(sel_comp_h,'String'),{get(sel_comp_h,'Value')});
4184
+  name=name{1};
4185
+  i=2;
4186
+
4187
+  while ~isempty(str2num(name(i)))
4188
+   value(i-1)=name(i);
4189
+   i=i+1;
4190
+  end
4191
+
4192
+  value=str2num(value);
4193
+
4194
+
4195
+  data=sData.data(selected_vects,value);
4196
+
4197
+  string{1} = cat(2,'Min: ',sprintf('%-10.3g',min(data)));
4198
+  string{2} = cat(2,'Mean: ',sprintf('%-10.3g',mean(data(find(~isnan(data))))));
4199
+  string{3} = cat(2,'Max: ',sprintf('%-10.3g',max(data)));
4200
+  string{4} = cat(2,'Std: ',sprintf('%-10.3g',std(data(find(~isnan(data)))))); 
4201
+  string{5} = cat(2,'Number of NaNs: ',sprintf('%-10.3g',sum(isnan(data))));
4202
+  string{6} = cat(2,'NaN (%):',...
4203
+                    sprintf('%-10.3g',100*sum(isnan(data))/length(data)));
4204
+  string{7} = cat(2,'Number of values: ',sprintf('%-10.3g',...
4205
+                    length(find(~isnan(unique(data))))));
4206
+  set(sel_cdata_h,'String',string);
4207
+  set(sel_cdata_h,'HorizontalAlignment','left');  
4208
+end
4209
+
4210
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4211
+
4212
+%%% Subfunction plot_hist %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4213
+
4214
+function plot_hist
4215
+
4216
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
4217
+sel_chist_h=getfield(get(pre_h,'UserData'),'sel_chist_h');
4218
+sData=getfield(get(pre_h,'UserData'),'sData');
4219
+selected=getfield(get(pre_h,'UserData'),'selected_vects');
4220
+
4221
+value=get(getfield(get(pre_h,'UserData'),'sel_comp_h'),'Value');
4222
+subplot(sel_chist_h);
4223
+hold off;
4224
+cla;
4225
+if all(isnan(sData.data(:,value)));
4226
+  return;
4227
+end
4228
+hold on;
4229
+lim1=min(sData.data(:,value));
4230
+lim2=max(sData.data(:,value));
4231
+if lim2 - lim1 >= eps
4232
+  x=lim1:(lim2-lim1)/(30-1):lim2;
4233
+  set(sel_chist_h,'XLim',[lim1 lim2]);
4234
+elseif lim1 ~= 0
4235
+  x=(lim1)/2:lim1/(30-1):lim1+(lim1)/2;
4236
+  set(sel_chist_h,'Xlim',[lim1-abs(lim1/2) lim1+abs(lim1/2)]);
4237
+else
4238
+  x=-1:2/(30-1):1;
4239
+  set(sel_chist_h,'XLim',[-1 1]);
4240
+end
4241
+
4242
+hist(sData.data(selected,value),x);
4243
+
4244
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4245
+
4246
+%%% Subfunction: select_all %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4247
+
4248
+function select_all(varargin)
4249
+
4250
+if nargin == 1
4251
+  LOG=1;
4252
+else
4253
+  LOG=0;
4254
+end
4255
+
4256
+data=get(gcf,'UserData');
4257
+data.selected_vects=(1:length(data.sData.data(:,1)));
4258
+if ~LOG
4259
+  data.LOG{length(data.LOG)+1}='% Select all vectors.';
4260
+  data.LOG{length(data.LOG)+1}='selall(''foo'');';
4261
+end
4262
+set(gcf,'UserData',data);
4263
+tmp=zeros(1,length(data.sData.data(:,1)));
4264
+tmp(data.selected_vects)=1;
4265
+draw_vectors(tmp,data.vector_h);
4266
+cplot_mimema;
4267
+vect_means(data.sData,data.vect_mean_h,data.selected_vects);
4268
+sel_comp;
4269
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4270
+
4271
+%%% Subfunction: plot_button %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4272
+
4273
+function plot_button
4274
+
4275
+%PLOT_BUTTON  A callback function. Plots all the components and marks
4276
+%             the chosen components.
4277
+%
4278
+%
4279
+
4280
+sData=getfield(get(gcf,'UserData'),'sData');
4281
+selected=getfield(get(gcf,'UserData'),'selected_vects');
4282
+
4283
+indices=get_indices;
4284
+if isempty(indices)
4285
+  return;
4286
+end
4287
+h=findobj(get(0,'Children'),'Tag','PlotWin');
4288
+if isempty(h)
4289
+  h= figure;
4290
+  set(h,'Tag','PlotWin');
4291
+end
4292
+
4293
+names=sData.comp_names(indices);  
4294
+data=sData.data(:,indices);
4295
+
4296
+set(0,'CurrentFigure',h);
4297
+hold off;
4298
+clf;
4299
+t=0:1/(getfield(size(data),{1})-1):1;
4300
+tmp=setdiff(1:length(data(:,1)),selected);
4301
+for i=1:length(names)
4302
+  subplot(length(names),1,i);
4303
+  hold on;
4304
+  if max(data(:,i))- min(data(:,i)) <= eps
4305
+    set(gca,'YLim',[max(data(:,i))-1 max(data(:,i))+1]);
4306
+  end
4307
+  plot(t,data(:,i));
4308
+  if ~isempty(tmp);
4309
+    data(tmp,i)=NaN;
4310
+  end
4311
+  plot(t,data(:,i),'red');
4312
+  ylabel(names{i});
4313
+  set(gca,'XTick',[]);
4314
+end
4315
+set(gcf,'Name','Plotted Data Components');    
4316
+
4317
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4318
+
4319
+%%% Subfunction: plxy_button %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4320
+
4321
+function plxy_button
4322
+
4323
+%PLXY_BUTTON  A callback function. XY-plots the first and the second
4324
+%             components chosen.
4325
+%
4326
+%
4327
+
4328
+
4329
+sData=getfield(get(gcf,'UserData'),'sData');
4330
+selected=getfield(get(gcf,'UserData'),'selected_vects');
4331
+
4332
+inds = get_indices;
4333
+if length(inds) < 2
4334
+  errordlg('There must be two components chosen for XY-plot.');
4335
+  return;
4336
+end
4337
+
4338
+inds=inds(1:2);
4339
+names=getfield(sData,'comp_names',{inds});
4340
+
4341
+h=findobj(get(0,'Children'),'Tag','PlotWin');
4342
+
4343
+if isempty(h)
4344
+  h= figure;
4345
+  set(h,'Tag','PlotWin');
4346
+end
4347
+
4348
+set(0,'CurrentFigure',h);
4349
+clf;
4350
+axes;
4351
+if max(sData.data(:,inds(1))) - min(sData.data(:,inds(1))) <= eps
4352
+  set(gca,'XLim',[max(sData.data(:,inds(1)))-1 max(sData.data(:,inds(1)))+1]);
4353
+end
4354
+if max(sData.data(:,inds(2))) - min(sData.data(:,inds(2))) <= eps
4355
+  set(gca,'YLim',[max(sData.data(:,inds(2)))-1 max(sData.data(:,inds(2)))+1]);
4356
+end
4357
+hold on;
4358
+plot(sData.data(:,inds(1)),sData.data(:,inds(2)),'o');
4359
+x=sData.data(selected,inds(1));
4360
+y=sData.data(selected,inds(2));
4361
+
4362
+plot(x,y,'ored','MarkerSize',4);
4363
+xlabel(names(1));
4364
+ylabel(names(2));
4365
+set(h,'Name','Plotted Data Components');
4366
+
4367
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4368
+
4369
+%%% Sub_function: bplo_button %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4370
+
4371
+function bplo_button
4372
+
4373
+%BPLO_BUTTON  A callback function. Box-plots the first component chosen.
4374
+
4375
+
4376
+sData=getfield(get(gcf,'UserData'),'sData');
4377
+selected=getfield(get(gcf,'UserData'),'selected_vects');
4378
+
4379
+if length(selected) == 1
4380
+  errordlg('There are too few vectors chosen for box-plotting.');
4381
+else
4382
+  indices=get_indices;
4383
+  if isempty(indices)
4384
+    return;
4385
+  end
4386
+  for i=1:length(indices)
4387
+    if length(unique(sData.data(selected,indices(i))))==1
4388
+      errordlg('All the values are the same. Operation can''t be evaluated.');
4389
+      return;
4390
+    end
4391
+  end 
4392
+  names=getfield(sData,'comp_names',{indices});
4393
+  h= findobj(get(0,'Children'),'Tag','PlotWin');
4394
+  if isempty(h)
4395
+    h= figure;
4396
+    set(h,'Tag','PlotWin');
4397
+  end
4398
+
4399
+  data=sData.data(selected,indices);
4400
+
4401
+  set(0,'CurrentFigure',h);
4402
+  hold off;
4403
+  clf;
4404
+  hold on;
4405
+  for i=1:getfield(size(data),{2})
4406
+    subplot(getfield(size(data),{2}),1,i);
4407
+    if ~all(isnan(data(:,i)))
4408
+      boxplot(data(:,i));
4409
+    end
4410
+    name=names{i};
4411
+    tmp=get(get(gca,'YLabel'),'String');
4412
+    ylabel(cat(2,sprintf('[%s]    ',name),tmp));
4413
+  end
4414
+  set(h,'Name','Box-plot');
4415
+end
4416
+
4417
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4418
+
4419
+%%% Subfunction: hist_button %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4420
+
4421
+function hist_button
4422
+
4423
+no_of_bins_h=getfield(get(gcf,'UserData'),'no_of_bins_h');
4424
+selected=getfield(get(gcf,'UserData'),'selected_vects');
4425
+sData=getfield(get(gcf,'UserData'),'sData');
4426
+n=str2num(get(no_of_bins_h,'String'));
4427
+s1='Invalid number of bins.';
4428
+s2=sprintf('\nSet new value to the box under the ''Histogram''-button.');
4429
+
4430
+if isempty(n)
4431
+  errordlg(cat(2,s1,s2));
4432
+else
4433
+  indices=get_indices;
4434
+  if isempty(indices)
4435
+    return;
4436
+  end
4437
+  n=round(n);
4438
+  if n < 1
4439
+    errordlg('Number of bins must be positive integer.');
4440
+  else
4441
+    h= findobj(get(0,'Children'),'Tag','PlotWin');
4442
+    if isempty(h)
4443
+      h= figure;
4444
+      set(h,'Tag','PlotWin');
4445
+    end
4446
+
4447
+    set(0,'CurrentFigure',h);
4448
+    hold off;
4449
+    clf;
4450
+    data=sData.data(selected,indices);
4451
+    names=sData.comp_names(indices);
4452
+    for i=1:length(names)
4453
+      subplot(length(names),1,i);
4454
+      hold on;
4455
+      lim1=min(sData.data(:,indices(i)));
4456
+      lim2=max(sData.data(:,indices(i)));
4457
+      if n > 1
4458
+        if lim2 - lim1 >= eps
4459
+          x=lim1:(lim2-lim1)/(n-1):lim2;
4460
+          set(gca,'XLim',[lim1 lim2]);
4461
+        elseif lim1 ~= 0
4462
+          x=lim1/2:lim1/(n-1):lim1/2+lim1;
4463
+          if ~all(isnan([lim1 lim2]))
4464
+            set(gca,'XLim',[lim1-abs(lim1/2) lim1+abs(lim1/2)]);
4465
+          end
4466
+        else
4467
+          x=-1:2/(n-1):1;
4468
+          set(gca,'XLim',[-1 1]);
4469
+        end
4470
+      else 
4471
+        x=1;
4472
+        if lim2 ~= lim1
4473
+          set(gca,'XLim',[lim1 lim2]);
4474
+        else
4475
+          set(gca,'XLim',[lim1/2 lim1/2+lim1]);
4476
+        end
4477
+      end
4478
+      if ~all(isnan(data(:,i)))
4479
+        hist(data(:,i),x);
4480
+      end
4481
+      name=names{i};
4482
+      xlabel(name);     
4483
+    end
4484
+    set(h,'Name','Histogram');      
4485
+  end
4486
+end
4487
+
4488
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4489
+
4490
+%%% Subfunction: no_of_values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4491
+
4492
+function no_of_values(varargin); 
4493
+
4494
+%NO_OF_VALUES  A callback function. Calculates the number of different
4495
+%              values of the chosen components.
4496
+%
4497
+%
4498
+
4499
+if nargin==1;
4500
+  LOG=1;
4501
+else
4502
+  LOG=0;
4503
+end
4504
+
4505
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
4506
+results_h=getfield(get(pre_h,'UserData'),'results_h');
4507
+sData=getfield(get(pre_h,'UserData'),'sData');
4508
+selected=getfield(get(pre_h,'UserData'),'selected_vects');
4509
+str1='There must be one component chosen for ''Number of Values''-operation';
4510
+
4511
+
4512
+if ~LOG & isempty(get_indices) 
4513
+  errordlg(str1);
4514
+else
4515
+  indices=get_indices;
4516
+  data=sData.data(selected,indices);
4517
+
4518
+  string{1} = 'Number of different values:';
4519
+
4520
+  for i=1:getfield(size(data),{2})
4521
+
4522
+    tmp=data(:,i);
4523
+    string{i+1}=cat(2,sprintf('#%d:',indices(i)),... 
4524
+                      sprintf('%d',length(find(~isnan(unique(data(:,i)))))));
4525
+  end
4526
+
4527
+  set(results_h,'String',string);
4528
+  set(results_h,'HorizontalAlignment','left');
4529
+  if ~LOG
4530
+    data=get(pre_h,'UserData');
4531
+    data.LOG{length(data.LOG)+1}='% Number of values';
4532
+    data.LOG{length(data.LOG)+1}='preprocess(''noof'',''foo'');';
4533
+    set(pre_h,'UserData',data);
4534
+  end
4535
+end
4536
+
4537
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4538
+
4539
+%%% Subfunction: correlation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4540
+
4541
+function correlation(varargin)
4542
+
4543
+if nargin == 1
4544
+  LOG=1;
4545
+else
4546
+  LOG=0;
4547
+end
4548
+
4549
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
4550
+results_h=getfield(get(pre_h,'UserData'),'results_h');
4551
+selected=getfield(get(pre_h,'UserData'),'selected_vects');
4552
+sData=getfield(get(pre_h,'UserData'),'sData');
4553
+
4554
+if length(get_indices) < 2
4555
+  errordlg('There must be two components chosen for Correlation');
4556
+else
4557
+  indices=getfield(get_indices,{1:2});
4558
+  data=sData.data(selected,indices);
4559
+  inds=find(~isnan(data(:,1)) & ~isnan(data(:,2)));
4560
+  value=getfield(corrcoef(data(inds,1),data(inds,2)),{1,2});
4561
+  names=sData.comp_names(indices);
4562
+  string{1}='Correlation between';
4563
+  string{2}=cat(2,names{1},' and ',names{2},':');
4564
+  string{3}=sprintf('%-10.3g',value);
4565
+
4566
+  set(results_h,'String',string);
4567
+  set(results_h,'HorizontalAlignment','left');
4568
+  if ~LOG
4569
+    data=get(pre_h,'UserData');
4570
+    data.LOG{length(data.LOG)+1}='% Correlation';
4571
+    data.LOG{length(data.LOG)+1}='preprocess(''corr'',''foo'');';
4572
+    set(pre_h,'UserData',data);
4573
+  end
4574
+end
4575
+
4576
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4577
+
4578
+%%% Subfunction: unit_length %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4579
+
4580
+function unit_length(varargin) 
4581
+
4582
+%UNIT_LENGTH  A callback function Scales all the vectors to the unit
4583
+%             length.
4584
+%
4585
+% 
4586
+
4587
+if nargin==1
4588
+  LOG=1;
4589
+else
4590
+  LOG=0;
4591
+end
4592
+
4593
+vect_mean_h=getfield(get(gcf,'UserData'),'vect_mean_h');
4594
+sData=getfield(get(gcf,'UserData'),'sData');
4595
+sData.MODIFIED=1;
4596
+scaled=sData.data;
4597
+comp_names_h=getfield(get(gcf,'UserData'),'comp_names_h');
4598
+
4599
+if ~LOG & isempty(get(comp_names_h,'Value'))
4600
+  errordlg('There must be components chosen for the ''unit length''- operation');
4601
+  return;
4602
+end
4603
+inds=get_indices;
4604
+for i=1:length(scaled(:,1));
4605
+  x=find(~isnan(scaled(i,inds)));
4606
+  scaled(i,inds(x))=(1/sqrt(sum(scaled(i,inds(x)).^2)))*scaled(i,inds(x));
4607
+end
4608
+
4609
+data=get(gcf,'UserData');
4610
+
4611
+
4612
+data.undo.sData = sData;
4613
+data.sData.data=scaled;
4614
+
4615
+for i=1:length(inds)
4616
+  data.sData.comp_norm{inds(i)}=[];
4617
+end
4618
+
4619
+if ~LOG
4620
+  data.LOG{length(data.LOG)+1}='% Unit length';
4621
+  data.LOG{length(data.LOG)+1}='preprocess(''unit'',''foo'');';
4622
+end
4623
+set(gcf,'UserData',data);
4624
+
4625
+vects=zeros(1,length(sData.data(:,1)));
4626
+vects(data.selected_vects)=1;
4627
+
4628
+draw_vectors(vects,data.vector_h);
4629
+vect_means(sData,vect_mean_h,data.selected_vects);
4630
+cplot_mimema;
4631
+plot_hist;
4632
+
4633
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4634
+
4635
+%%% Subfunction: one_of_n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4636
+
4637
+function one_of_n(varargin)
4638
+
4639
+if nargin==1
4640
+  LOG=1;
4641
+else
4642
+  LOG=0;
4643
+end
4644
+
4645
+data=get(gcf,'UserData');
4646
+vector_h=getfield(get(gcf,'Userdata'),'vector_h');
4647
+comp_names_h=getfield(get(gcf,'Userdata'),'comp_names_h');
4648
+vect_mean_h=getfield(get(gcf,'UserData'),'vect_mean_h');
4649
+sData=data.sData;
4650
+undo=data.sData;
4651
+selected=getfield(get(gcf,'UserData'),'selected_vects');
4652
+msg='Creating over 10 new components. Stop operation?';
4653
+
4654
+if ~LOG
4655
+  if isempty(get(data.comp_names_h,'Value'))
4656
+    errordlg('There must be one component chosen for ''Add: N binary types'' -operation');
4657
+    return;
4658
+  end
4659
+end
4660
+
4661
+index=getfield(get_indices,{1});
4662
+
4663
+tmp=unique(sData.data(:,index)); 
4664
+n=length(tmp);
4665
+
4666
+if ~LOG
4667
+  if n>10
4668
+    answer=questdlg(msg,'Question','Yes','No','Yes');
4669
+
4670
+    if strcmp(answer,'Yes')
4671
+      msgbox('Operation stopped.');
4672
+      return;
4673
+    end
4674
+
4675
+  end
4676
+end
4677
+
4678
+dim1=getfield(size(sData.data),{1});
4679
+dim2=getfield(size(sData.data),{2});
4680
+sData.data=cat(2,sData.data,zeros(dim1,n));
4681
+
4682
+dim=dim2+n;
4683
+for i=1:n
4684
+  sData.data(:,dim-(n-i))=(sData.data(:,index) == tmp(i));
4685
+end
4686
+
4687
+INDEX=sData.INDEX;
4688
+for i=1:n
4689
+  sData.comp_names{dim2+i}=sprintf('%dNewVar',dim2+i);
4690
+end
4691
+tmp_norm=cat(1,sData.comp_norm,cell(n,1));
4692
+sData=som_data_struct(sData.data,...
4693
+                      'name',sData.name,...
4694
+                      'labels',sData.labels,...
4695
+                      'comp_names',sData.comp_names);
4696
+                
4697
+sData.MODIFIED=1;
4698
+sData.INDEX=INDEX;
4699
+sData.comp_norm=tmp_norm;
4700
+data.undo.sData=undo;
4701
+data.sData=sData;
4702
+data.selected_vects=1:length(sData.data(:,1));
4703
+if ~LOG
4704
+  data.LOG{length(data.LOG)+1}='% Add: N binary types';
4705
+  data.LOG{length(data.LOG)+1}='preprocess(''oneo'',''foo'');';
4706
+end
4707
+set(gcf,'UserData',data);
4708
+clear_button;
4709
+write_sD_stats;
4710
+set_compnames(sData,comp_names_h);
4711
+tmp=ones(1,length(sData.data(:,1)));
4712
+draw_vectors(tmp,vector_h);
4713
+vect_means(sData,vect_mean_h,1:length(sData.data(:,1)));
4714
+cplot_mimema;
4715
+sel_comp;
4716
+
4717
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4718
+
4719
+%%% Subfunction: add_zeros %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4720
+
4721
+function add_zeros(varargin)
4722
+
4723
+if nargin == 1
4724
+  LOG=1;
4725
+else
4726
+  LOG=0;
4727
+end
4728
+
4729
+data=get(gcf,'UserData');
4730
+vector_h=getfield(get(gcf,'Userdata'),'vector_h');
4731
+comp_names_h=getfield(get(gcf,'Userdata'),'comp_names_h');
4732
+vect_mean_h=getfield(get(gcf,'UserData'),'vect_mean_h');
4733
+sData=data.sData;
4734
+undo=sData;
4735
+
4736
+dim1=getfield(size(sData.data),{1});
4737
+dim2=getfield(size(sData.data),{2});
4738
+sData.data=cat(2,sData.data,zeros(dim1,1));
4739
+
4740
+INDEX=sData.INDEX;
4741
+
4742
+sData.comp_names{dim2+1}=sprintf('%dNewVar',dim2+1);
4743
+tmp_norm=cat(1,sData.comp_norm,cell(1,1));
4744
+sData=som_data_struct(sData.data,...
4745
+                      'name',sData.name,...
4746
+                      'labels',sData.labels,...
4747
+                      'comp_names',sData.comp_names);
4748
+         
4749
+sData.MODIFIED=1;
4750
+sData.INDEX=INDEX;
4751
+sData.comp_norm=tmp_norm;
4752
+data.sData=sData;
4753
+data.undo.sData=undo;
4754
+data.selected_vects=1:length(sData.data(:,1));
4755
+if ~LOG
4756
+  data.LOG{length(data.LOG)+1}='% Add: zeros';
4757
+  data.LOG{length(data.LOG)+1}='preprocess(''zero'',''foo'');';
4758
+end
4759
+set(gcf,'UserData',data);
4760
+clear_button;
4761
+write_sD_stats;
4762
+set_compnames(sData,comp_names_h);
4763
+tmp=ones(1,length(sData.data(:,1)));
4764
+draw_vectors(tmp,vector_h);
4765
+vect_means(sData,vect_mean_h,1:length(sData.data(:,1)));
4766
+cplot_mimema;
4767
+sel_comp;
4768
+
4769
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4770
+
4771
+%%% Subfunction: move_component %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4772
+
4773
+function move_component(varargin)
4774
+
4775
+%MOVE_COMPONENT  A callback function. Moves one component of vectors to
4776
+%                the position wanted.
4777
+%
4778
+%
4779
+
4780
+if nargin == 1
4781
+  LOG=1;
4782
+  i=1;
4783
+  while varargin{1}(i) ~= ' ' 
4784
+    value(i)=varargin{1}(i);
4785
+    i=i+1;
4786
+  end
4787
+  value=str2num(value);                                 % the new place
4788
+  index=str2num(varargin{1}(i:length(varargin{1})));    % index of the chosen
4789
+                                                        % component
4790
+else
4791
+  LOG=0;
4792
+end
4793
+
4794
+data=get(gcf,'UserData');
4795
+sData=data.sData;
4796
+undo=sData;
4797
+prompt='Enter the number of the new component place:';
4798
+
4799
+
4800
+if isempty(get(data.comp_names_h,'Value'))
4801
+  errordlg('There must be one component chosen for ''Move Component''-operation');
4802
+  return;
4803
+end
4804
+
4805
+if ~LOG
4806
+  index=getfield(get_indices,{1});
4807
+  answer=inputdlg(prompt);
4808
+
4809
+  if isempty(answer) | (iscell(answer) & isempty(answer{1}))
4810
+    msgbox('No components moved');
4811
+    return;
4812
+  end
4813
+
4814
+  value=str2num(answer{1});
4815
+
4816
+
4817
+  dims=size(value);
4818
+
4819
+  if dims(1) ~= 1 | dims(2) ~= 1 | ~isreal(value)
4820
+    errordlg('The new component place must be positive integer.')
4821
+    return;
4822
+  end
4823
+
4824
+  if value <= 0 | round(value) ~= value
4825
+    errordlg('The new component place must be positive integer.');
4826
+    return;
4827
+  end
4828
+
4829
+  if value > getfield(size(sData.data),{2})
4830
+    errordlg('Too big value for the new component place.');
4831
+    return;
4832
+  end
4833
+end
4834
+
4835
+sData.MODIFIED=1;
4836
+if index < value
4837
+  indices1=setdiff(1:value,index);
4838
+  indices2=setdiff(value+1:length(sData.data(1,:)),index);
4839
+elseif index > value
4840
+  indices1=setdiff(1:value-1,index);
4841
+  indices2=setdiff(value:length(sData.data(1,:)),index);
4842
+else
4843
+  data.sData=sData;
4844
+  data.undo.sData=undo;
4845
+  set(gcf,'UserData',data);
4846
+  return;
4847
+end
4848
+
4849
+tmp1=sData.data(:,indices1);
4850
+tmp2=sData.data(:,indices2);
4851
+sData.data=cat(2,tmp1,sData.data(:,index),tmp2);
4852
+
4853
+tmp1=sData.comp_names(indices1);
4854
+tmp2=sData.comp_names(indices2);
4855
+sData.comp_names=cat(1,tmp1,sData.comp_names(index),tmp2);
4856
+
4857
+tmp1=sData.comp_norm(indices1);
4858
+tmp2=sData.comp_norm(indices2);
4859
+sData.comp_norm=cat(1,tmp1,sData.comp_norm(index),tmp2);
4860
+
4861
+data.sData=sData;
4862
+data.undo.sData=undo;
4863
+if ~LOG
4864
+  data.LOG{length(data.LOG)+1}='% Move component.';
4865
+  data.LOG{length(data.LOG)+1}=sprintf('preprocess(''move'',''%s %s'');',...
4866
+           num2str(value),num2str(index));
4867
+end
4868
+comp_names_h=getfield(get(gcf,'UserData'),'comp_names_h');
4869
+vect_mean_h=getfield(get(gcf,'UserData'),'vect_mean_h');
4870
+vector_h=getfield(get(gcf,'UserData'),'vector_h');
4871
+data.selected_vects=1:length(sData.data(:,1));
4872
+set(gcf,'UserData',data);
4873
+clear_button;
4874
+set_compnames(sData,comp_names_h);
4875
+draw_vectors(ones(1,length(sData.data(:,1))),vector_h);
4876
+vect_means(sData,vect_mean_h,data.selected_vects);
4877
+cplot_mimema;
4878
+sel_comp;
4879
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4880
+
4881
+%%% Subfunction: copy_component %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4882
+
4883
+function copy_component(varargin)
4884
+
4885
+%COPY_COMPONENT  Copies one component of vectors to the position wanted.
4886
+%
4887
+%
4888
+
4889
+if nargin == 1
4890
+  LOG=1;
4891
+  i=1;
4892
+  while varargin{1}(i) ~= ' ' 
4893
+    value(i)=varargin{1}(i);
4894
+    i=i+1;
4895
+  end
4896
+  value=str2num(value);                                 % the new place
4897
+  index=str2num(varargin{1}(i:length(varargin{1})));    % index of the chosen
4898
+                                                        % component
4899
+else
4900
+  LOG=0;
4901
+end
4902
+
4903
+
4904
+data=get(gcf,'UserData');
4905
+sData=data.sData;
4906
+undo=sData;
4907
+if ~LOG
4908
+  prompt='Enter the number of the new component place:';
4909
+
4910
+
4911
+  if isempty(get(data.comp_names_h,'Value'))
4912
+    errordlg('There must be one component chosen for ''Copy Component''-operation');
4913
+    return;
4914
+  end
4915
+
4916
+  index=getfield(get_indices,{1});
4917
+  answer=inputdlg(prompt);
4918
+
4919
+  if isempty(answer) | (iscell(answer) & isempty(answer{1}))
4920
+    msgbox('No components moved');
4921
+    return
4922
+  end
4923
+
4924
+
4925
+  value=str2num(answer{1});
4926
+  dims=size(value);
4927
+
4928
+  if dims(1) ~= 1 | dims(2) ~= 1 | ~isreal(value)
4929
+    errordlg('The new component place must be positive integer.')
4930
+    return;
4931
+  end
4932
+
4933
+  if value <= 0 | round(value) ~= value
4934
+    errordlg('The new component place must be positive integer.');
4935
+    return;
4936
+  end
4937
+
4938
+  if value > getfield(size(sData.data),{2}) + 1
4939
+    errordlg('Too big value for the new component place.');
4940
+    return;
4941
+  end
4942
+end
4943
+
4944
+sData.MODIFIED=1;
4945
+
4946
+indices1=1:value-1;
4947
+indices2=value:length(sData.data(1,:));
4948
+tmp1=sData.data(:,indices1);
4949
+tmp2=sData.data(:,indices2);
4950
+sData.data=cat(2,tmp1,sData.data(:,index),tmp2);
4951
+
4952
+tmp1=sData.comp_names(indices1);
4953
+tmp2=sData.comp_names(indices2);
4954
+name=cell(1,1);
4955
+name{1}=cat(2,'Copied',sData.comp_names{index});
4956
+sData.comp_names=cat(1,tmp1,name,tmp2);
4957
+
4958
+tmp1=sData.comp_norm(indices1);
4959
+tmp2=sData.comp_norm(indices2);
4960
+norm=cell(1,1);
4961
+norm{1}=sData.comp_norm{index};
4962
+sData.comp_norm=cat(1,tmp1,norm,tmp2);
4963
+
4964
+data.sData=sData;
4965
+data.undo.sData=undo;
4966
+if ~LOG
4967
+  data.LOG{length(data.LOG)+1}='% Copy component';
4968
+  data.LOG{length(data.LOG)+1}=sprintf('preprocess(''copy'',''%s %s'');',...
4969
+           num2str(value),num2str(index));
4970
+end
4971
+
4972
+
4973
+comp_names_h=getfield(get(gcf,'UserData'),'comp_names_h');
4974
+vect_mean_h=getfield(get(gcf,'UserData'),'vect_mean_h');
4975
+vector_h=getfield(get(gcf,'UserData'),'vector_h');
4976
+data.selected_vects=1:length(sData.data(:,1));
4977
+set(gcf,'UserData',data);
4978
+clear_button;
4979
+write_sD_stats;
4980
+set_compnames(sData,comp_names_h);
4981
+draw_vectors(ones(1,length(sData.data(:,1))),vector_h);
4982
+vect_means(sData,vect_mean_h,data.selected_vects);
4983
+cplot_mimema;
4984
+sel_comp;
4985
+
4986
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4987
+
4988
+%%% Subfunction: remove_component %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4989
+
4990
+function remove_component(varargin)
4991
+
4992
+if nargin == 1
4993
+  LOG=1;
4994
+  value=str2num(varargin{1});
4995
+else
4996
+  LOG=0;
4997
+end
4998
+
4999
+data=get(gcf,'UserData');
5000
+vect_mean_h=getfield(get(gcf,'UserData'),'vect_mean_h');
5001
+vector_h=getfield(get(gcf,'UserData'),'vector_h');
5002
+comp_names_h=getfield(get(gcf,'UserData'),'comp_names_h');
5003
+sData=data.sData;
5004
+undo=sData;
5005
+prompt='Enter the number of component to be removed.';
5006
+dim=length(sData.data(1,:));
5007
+
5008
+if ~LOG
5009
+  answer=inputdlg(prompt);
5010
+
5011
+  if isempty(answer) | (iscell(answer) & isempty(answer{1}))
5012
+    msgbox('Components not removed.');
5013
+    return;
5014
+  end
5015
+
5016
+  value=str2num(answer{1});
5017
+  dims=size(value);
5018
+
5019
+  if dims(1) ~= 1 | dims(2) ~= 1 | ~isreal(value)
5020
+    errordlg('Number of the component to be removed must be positive integer.')
5021
+    return;
5022
+  end
5023
+
5024
+  if value <= 0 | round(value) ~= value
5025
+    errordlg('Number of the component to be removed must be positive integer.');
5026
+    return;
5027
+  end
5028
+
5029
+  if value > getfield(size(sData.data),{2})
5030
+    errordlg('There are less components.');
5031
+    return;
5032
+  end
5033
+end
5034
+
5035
+sD_set_h=getfield(get(gcf,'UserData'),'sD_set_h');
5036
+index=get(sD_set_h,'Value');
5037
+if value == 1 & getfield(size(sData.data),{2}) == 1
5038
+   if length(get(sD_set_h,'String')) == 1
5039
+    msgbox('No data left. Closing program...')
5040
+    pro_tools('close');
5041
+    return;
5042
+  end
5043
+ 
5044
+  set1=data.sD_set(1:index-1);
5045
+  set2=data.sD_set(index+1:length(data.sD_set));
5046
+  data.sD_set=[set1 set2];
5047
+   set(gcf,'UserData',data);
5048
+  
5049
+  set_sD_stats;
5050
+  sel_sD;
5051
+  data=get(gcf,'UserData');
5052
+  data.undo.sData=undo;
5053
+  data.undo.index=index;
5054
+  set(gcf,'UserData',data);
5055
+  return;
5056
+end
5057
+dims=size(sData.data);
5058
+tmp_data=cat(2,sData.data(:,1:value-1),sData.data(:,value+1:dims(2)));
5059
+tmp_norm=cat(1,sData.comp_norm(1:value-1),sData.comp_norm(value+1:dims(2)));
5060
+names=cat(1,sData.comp_names(1:value-1),sData.comp_names(value+1:dims(2)));
5061
+INDEX=sData.INDEX;
5062
+comp_norm=sData.comp_norm;
5063
+sData=som_data_struct(tmp_data,...
5064
+                      'name',sData.name,...
5065
+                      'labels',sData.labels,...
5066
+                      'comp_names',names);
5067
+sData.comp_norm=tmp_norm;
5068
+sData.MODIFIED=1;
5069
+sData.INDEX=INDEX;
5070
+data=get(gcf,'UserData');
5071
+data.sData=sData;
5072
+data.undo.sData=undo;
5073
+data.selected_vects=1:length(sData.data(:,1));
5074
+if ~LOG
5075
+  data.LOG{length(data.LOG)+1}='% Remove component';
5076
+  data.LOG{length(data.LOG)+1}=sprintf('preprocess(''remove'',''%s'');',...
5077
+                                        answer{1});
5078
+end
5079
+set(gcf,'UserData',data);
5080
+clear_button;
5081
+write_sD_stats;
5082
+set_compnames(sData,comp_names_h);
5083
+tmp=ones(1,length(sData.data(:,1)));
5084
+draw_vectors(tmp,vector_h);
5085
+vect_means(sData,vect_mean_h,1:length(sData.data(:,1)));
5086
+cplot_mimema;
5087
+sel_comp;
5088
+
5089
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5090
+
5091
+%%% Subfunction: remove_vects %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5092
+
5093
+function remove_vects(varargin)
5094
+
5095
+if nargin==1
5096
+  LOG=1;
5097
+  tmp_str=varargin{1};
5098
+else
5099
+  LOG=0;
5100
+  tmp_str='_foo';
5101
+end
5102
+data=get(gcf,'UserData');
5103
+vect_mean_h=data.vect_mean_h;
5104
+vector_h=data.vector_h;
5105
+sData=data.sData;
5106
+undo=sData;
5107
+
5108
+if length(data.selected_vects) == getfield(size(sData.data),{1})
5109
+  if LOG
5110
+    answer='Yes';
5111
+  else
5112
+    answer=questdlg('Do you want to delete this data set?');
5113
+  end
5114
+  if strcmp(answer,'No')
5115
+    return;
5116
+  else
5117
+    index=get(data.sD_set_h,'Value');
5118
+    if length(get(data.sD_set_h,'String')) == 1
5119
+      msgbox('No data left. Closing program...')
5120
+      pro_tools('close');
5121
+      return;
5122
+    end
5123
+     
5124
+    set1=data.sD_set(1:index-1);
5125
+    set2=data.sD_set(index+1:length(data.sD_set));
5126
+    data.sD_set=[set1 set2];
5127
+    set(gcf,'UserData',data);
5128
+  
5129
+    set(data.sD_set_h,'Value',1);
5130
+    set_sD_stats;
5131
+    sel_sD;
5132
+    data=get(gcf,'UserData');
5133
+    data.undo.sData=undo;
5134
+    data.undo.index=index;
5135
+    if ~LOG
5136
+      data.LOG{length(data.LOG)+1}='% Remove selected vectors';
5137
+      data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''remove_vects'',''',...
5138
+                                          tmp_str,''');');
5139
+    end
5140
+    set(gcf,'UserData',data);
5141
+    return;
5142
+  end
5143
+end
5144
+
5145
+tmp=sData.data(data.selected_vects,:);
5146
+if ~LOG
5147
+  answer=questdlg('Do you want to save removed values to workspace?');
5148
+else
5149
+  if ~strcmp(tmp_str,'_foo')
5150
+    answer='Yes';
5151
+  else
5152
+    answer='No';
5153
+  end
5154
+end
5155
+old=gcf;
5156
+if strcmp(answer,'Yes')
5157
+  if ~LOG
5158
+    answer=inputdlg('Give the name of the output -variable.');
5159
+  else
5160
+    answer={tmp_str};
5161
+  end
5162
+  if isvalid_var_name(answer)
5163
+    assignin('base',answer{1},tmp);
5164
+    disp(sprintf('Removed values are set to workspace as''%s''.',answer{1}));
5165
+    tmp_str=answer{1};
5166
+  end
5167
+end
5168
+set(0,'CurrentFigure',old);
5169
+sData.data(data.selected_vects,:)=[];
5170
+sData.labels(data.selected_vects,:)=[];
5171
+sData.MODIFIED=1;
5172
+data.sData=sData;
5173
+data.selected=1:length(sData.data(:,1));
5174
+data.undo.sData=undo;
5175
+if ~LOG
5176
+  data.LOG{length(data.LOG)}='% Remove selected vectors';
5177
+  data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''remove_vects'',''',...
5178
+                                      tmp_str,''');');
5179
+end
5180
+set(gcf,'UserData',data);
5181
+
5182
+
5183
+draw_vectors(ones(1,length(data.selected)),data.vector_h);
5184
+write_sD_stats;
5185
+select_all('foo');
5186
+
5187
+
5188
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5189
+
5190
+
5191
+
5192
+
5193
+%%% Subfunction: eval1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5194
+
5195
+function eval1(varargin);
5196
+
5197
+if nargin == 1
5198
+  answer=varargin
5199
+  LOG=1;
5200
+else
5201
+  LOG=0;
5202
+end
5203
+
5204
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
5205
+if isempty(pre_h)
5206
+  errordlg('''Preprocess''-figure does not exist. Terminating program...');
5207
+  pro_tools('close');
5208
+  return;
5209
+end  
5210
+
5211
+undo=getfield(get(pre_h,'UserData'),'sData');
5212
+
5213
+if ~LOG
5214
+  prompt={'Enter the expression to be evaluated.',...
5215
+          'Enter the inverse normalization method (optional).'};
5216
+  title='Single component eval.';
5217
+  answer= inputdlg(prompt,title,1);
5218
+end
5219
+
5220
+if ~isempty(answer)
5221
+  tmp=[];
5222
+  if ~isempty(answer{1})
5223
+    [tmp,method]=build_expr(answer{1},'single');
5224
+    if ~isstr(tmp)
5225
+      sData=getfield(get(gcf,'UserData'),'sData');
5226
+      tmp='Done.';
5227
+      %if ~isempty(answer{2})
5228
+      %  sN=som_norm_struct('eval',{method,answer{2}});
5229
+      %else
5230
+      %  sN=som_norm_struct('eval',{method});
5231
+      %end
5232
+      %sN=som_set(sN,'status','done');
5233
+      params={answer{1};answer{2}};
5234
+      ind=getfield(get_indices,{1});
5235
+      x.type='';
5236
+      x.method='eval';
5237
+      x.params={answer{1};answer{2}};
5238
+      x.status='';
5239
+      sData.comp_norm{ind}=x;
5240
+      data=get(gcf,'UserData');
5241
+      data.undo.sData=undo;
5242
+      data.sData=sData;
5243
+      if ~LOG
5244
+        data.LOG{length(data.LOG)+1}='% Eval (1-comp)';
5245
+        data.LOG{length(data.LOG)+1}=cat(2,'preprocess eval1 ',...
5246
+                 sprintf('{''%s''  ''%s''};',answer{1},answer{2}));
5247
+      end 
5248
+      set(pre_h,'UserData',data);
5249
+
5250
+    end
5251
+  end    
5252
+  set(getfield(get(pre_h,'UserData'),'results_h'),'String',tmp);
5253
+end
5254
+
5255
+
5256
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5257
+
5258
+%%% Subfunction: eval2
5259
+
5260
+function eval2(varargin)
5261
+
5262
+if nargin == 1
5263
+  answer=varargin{1};
5264
+  LOG=1;
5265
+else
5266
+  LOG=0;
5267
+end
5268
+
5269
+undo=getfield(get(gcf,'UserData'),'sData');
5270
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
5271
+
5272
+if isempty(pre_h)
5273
+  errordlg('''Preprocess''-figure does not exist. Terminating program.');
5274
+  pro_tools('close');
5275
+  return;
5276
+end
5277
+
5278
+if ~LOG
5279
+  prompt='Enter the expression to be evaluated.';
5280
+  title ='Eval';
5281
+  answer=inputdlg(prompt,title,1);
5282
+end
5283
+
5284
+if ~isempty(answer) & ~isempty(answer{1})
5285
+   str=answer{1};
5286
+   [answer,foo]=build_expr(answer{1},'multiple');
5287
+   if ~isstr(answer)
5288
+     
5289
+     answer='Done.';
5290
+     data=get(gcf,'UserData');
5291
+     data.undo.sData=undo;
5292
+     if ~LOG
5293
+        data.LOG{length(data.LOG)+1}='% Eval';
5294
+        data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''eval2'',',...
5295
+                 sprintf('{''%s''});',str));
5296
+      end 
5297
+     set(gcf,'UserData',data);
5298
+   end
5299
+end
5300
+
5301
+set(getfield(get(pre_h,'UserData'),'results_h'),'String',answer);
5302
+
5303
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5304
+
5305
+%%% Subfunction: zero2one_scale %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5306
+
5307
+function zero2one_scale(varargin)
5308
+
5309
+if nargin == 1
5310
+  LOG=1;
5311
+else
5312
+  LOG=0;
5313
+end
5314
+
5315
+
5316
+data=get(gcf,'UserData');
5317
+sData=data.sData;
5318
+undo=sData;
5319
+INDEX=sData.INDEX;
5320
+sData=rmfield(sData,[{'INDEX'};{'MODIFIED'}]);
5321
+
5322
+if isempty(get(data.comp_names_h,'Value'))
5323
+  errordlg('There must be components chosen for scaling.');
5324
+  return;
5325
+end
5326
+
5327
+sData=som_normalize(sData,'range',get_indices);
5328
+sData.MODIFIED=1;
5329
+sData.INDEX=INDEX;
5330
+
5331
+data.sData=sData;
5332
+data.undo.sData=undo;
5333
+if ~LOG
5334
+  data.LOG{length(data.LOG)+1}='% Scale [0,1]';
5335
+  data.LOG{length(data.LOG)+1}='preprocess(''zscale'', ''foo'');';
5336
+end 
5337
+set(gcf,'UserData',data);
5338
+
5339
+vects=zeros(1,length(sData.data(:,1)));
5340
+vects(data.selected_vects)=1;
5341
+
5342
+cplot_mimema;
5343
+plot_hist;
5344
+vect_means(sData,data.vect_mean_h,data.selected_vects);
5345
+draw_vectors(vects,data.vector_h);
5346
+
5347
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5348
+
5349
+%%% Subfunction: var_scale %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5350
+
5351
+function var_scale(varargin)
5352
+
5353
+if nargin == 1
5354
+  LOG=1;
5355
+else
5356
+  LOG=0;
5357
+end
5358
+
5359
+data=get(gcf,'UserData');
5360
+sData=data.sData;
5361
+undo=sData;
5362
+INDEX=sData.INDEX;
5363
+sData=rmfield(sData,[{'INDEX'};{'MODIFIED'}]);
5364
+
5365
+if isempty(get(data.comp_names_h,'Value'))
5366
+  errordlg('There must be components chosen for scaling.');
5367
+  return;
5368
+end  
5369
+
5370
+sData=som_normalize(sData,'var',get_indices);
5371
+
5372
+sData.INDEX=INDEX;
5373
+sData.MODIFIED=1;
5374
+
5375
+data.sData=sData;
5376
+data.undo.sData=undo;
5377
+if ~LOG
5378
+  data.LOG{length(data.LOG)+1}='% Scale var=1';
5379
+  data.LOG{length(data.LOG)+1}='preprocess(''vscale'', ''foo'');';
5380
+end 
5381
+set(gcf,'UserData',data);
5382
+
5383
+vects=zeros(1,length(sData.data(:,1)));
5384
+vects(data.selected_vects)=1;
5385
+
5386
+cplot_mimema;
5387
+plot_hist;
5388
+vect_means(sData,data.vect_mean_h,data.selected_vects);
5389
+draw_vectors(vects,data.vector_h);
5390
+
5391
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5392
+
5393
+%%% Subfunction: hist_eq %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5394
+
5395
+function hist_eq(varargin)
5396
+
5397
+if nargin == 1
5398
+  LOG=1;
5399
+else
5400
+  LOG=0;
5401
+end
5402
+
5403
+data=get(gcf,'UserData');
5404
+sData=data.sData;
5405
+undo=sData;
5406
+INDEX=sData.INDEX;
5407
+sData=rmfield(sData,[{'INDEX'},{'MODIFIED'}]);
5408
+
5409
+if isempty(get(data.comp_names_h,'Value'))
5410
+  errordlg('There must be components chosen for ''Histogram eq''.');
5411
+  return;
5412
+end
5413
+
5414
+sData=som_normalize(sData,'histD',get_indices);
5415
+
5416
+sData.INDEX=INDEX;
5417
+sData.MODIFIED=1;
5418
+
5419
+data.sData=sData;
5420
+data.undo.sData=undo;
5421
+if ~LOG
5422
+  data.LOG{length(data.LOG)+1}='% Histogram eq';
5423
+  data.LOG{length(data.LOG)+1}='preprocess(''histeq'', ''foo'');';
5424
+end 
5425
+set(gcf,'UserData',data);
5426
+
5427
+vects=zeros(1,length(sData.data(:,1)));
5428
+vects(data.selected_vects)=1;
5429
+
5430
+cplot_mimema;
5431
+plot_hist;
5432
+vect_means(sData,data.vect_mean_h,data.selected_vects);
5433
+draw_vectors(vects,data.vector_h);
5434
+
5435
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5436
+
5437
+%%% Subfunction: hist_eq2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5438
+
5439
+function hist_eq2(varargin)
5440
+
5441
+if nargin == 1
5442
+  LOG=1;
5443
+else
5444
+  LOG=0;
5445
+end
5446
+
5447
+
5448
+data=get(gcf,'UserData');
5449
+sData=data.sData;
5450
+undo=sData;
5451
+
5452
+INDEX=sData.INDEX;
5453
+sData=rmfield(sData,[{'INDEX'};{'MODIFIED'}]);
5454
+
5455
+if isempty(get(data.comp_names_h,'Value'))
5456
+  errordlg('There must be components chosen for ''Histogram eq2''.');
5457
+  return;
5458
+end
5459
+
5460
+inds=get_indices;
5461
+%%%[sData,ok]=som_normalize(sData,inds,'histC');
5462
+sData=som_normalize(sData,'histC',inds);
5463
+sData.INDEX=INDEX;
5464
+sData.MODIFIED=1;
5465
+
5466
+data.sData=sData;
5467
+data.undo.sData=undo;
5468
+if ~LOG
5469
+  data.LOG{length(data.LOG)+1}='% Histogram eq2';
5470
+  data.LOG{length(data.LOG)+1}='preprocess(''histeq2'', ''foo'');';
5471
+end 
5472
+set(gcf,'UserData',data);
5473
+
5474
+vects=zeros(1,length(sData.data(:,1)));
5475
+vects(data.selected_vects)=1;
5476
+
5477
+cplot_mimema;
5478
+plot_hist;
5479
+vect_means(sData,data.vect_mean_h,data.selected_vects);
5480
+draw_vectors(vects,data.vector_h);
5481
+
5482
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5483
+
5484
+%%% Subfunction: logarithm %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5485
+
5486
+function logarithm(varargin)
5487
+
5488
+if nargin == 1
5489
+  LOG=1;
5490
+else
5491
+  LOG=0;
5492
+end
5493
+
5494
+data=get(gcf,'UserData');
5495
+sData=data.sData;
5496
+undo=sData;
5497
+
5498
+INDEX=sData.INDEX;
5499
+sData=rmfield(sData,[{'INDEX'},{'MODIFIED'}]);
5500
+
5501
+if isempty(get(data.comp_names_h,'Value'))
5502
+  errordlg('There must be components chosen for ''Log''.');
5503
+  return;
5504
+end
5505
+
5506
+Data=som_normalize(sData,'log',get_indices);
5507
+
5508
+sData.INDEX=INDEX;
5509
+sData.MODIFIED=1;
5510
+
5511
+data.sData=sData;
5512
+data.undo.sData=undo;
5513
+if ~LOG
5514
+  data.LOG{length(data.LOG)+1}='% Log';
5515
+  data.LOG{length(data.LOG)+1}='preprocess(''log'', ''foo'');';
5516
+end 
5517
+set(gcf,'UserData',data);
5518
+
5519
+vects=zeros(1,length(sData.data(:,1)));
5520
+vects(data.selected_vects)=1;
5521
+
5522
+cplot_mimema;
5523
+plot_hist;
5524
+vect_means(sData,data.vect_mean_h,data.selected_vects);
5525
+draw_vectors(vects,data.vector_h);
5526
+
5527
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5528
+
5529
+function [answer,method]=build_expr(string,evaltype)
5530
+
5531
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
5532
+
5533
+method=[];
5534
+if isempty(pre_h)
5535
+  close_preprocess;
5536
+  errordlg('''Preprocess'' -figure does not exist. Terminating program...'); 
5537
+  return;
5538
+
5539
+end
5540
+
5541
+if isempty(string)
5542
+  str = '[]';
5543
+  return;
5544
+end
5545
+
5546
+tmp=[];
5547
+[name,assign,skip]=check_assign(string,evaltype);
5548
+
5549
+if ~strcmp(assign,'NOTASSIGN') & ~strcmp(assign,'error')
5550
+  string=string(skip:length(string));
5551
+end
5552
+
5553
+if ~strcmp(assign,'error')
5554
+  if isempty(string)
5555
+    answer='Illegal expression.';
5556
+    return;
5557
+  end
5558
+  [str,skip]=check_token(string,evaltype);
5559
+  method=string;
5560
+  while ~strcmp(str,'error') & ~strcmp(tmp,'error') & skip < length(string)
5561
+    if ~strcmp(tmp,')')
5562
+      str=cat(2,str,tmp);
5563
+    end
5564
+    [tmp,skip2]=check_token(string(skip+1:length(string)),evaltype);
5565
+    skip=skip+skip2;
5566
+               
5567
+  end
5568
+   if ~strcmp(tmp,')') & ~strcmp(tmp,'error')
5569
+     str=cat(2,str,tmp);
5570
+   elseif strcmp(tmp,'error')
5571
+     str='error';
5572
+   end
5573
+end
5574
+
5575
+if ~strcmp(assign,'error') & ~strcmp(str,'error');
5576
+  answer=evalin('caller',str,'lasterr');
5577
+else
5578
+  answer='??? Illegal expression.';
5579
+end
5580
+
5581
+
5582
+data=get(pre_h,'UserData');
5583
+sData=data.sData;
5584
+if strcmp(assign,'NOTASSIGN') & strcmp(evaltype,'single') & ~isstr(answer)
5585
+  if isempty(get(getfield(get(pre_h,'UserData'),'comp_names_h'),'Value'))
5586
+    errordlg('There are not components chosen.');
5587
+    answer='??? Illegal expression.';
5588
+    return;
5589
+  end
5590
+  index=getfield(get_indices,{1});
5591
+  if strcmp(assign,'NOTASSIGN')
5592
+    if length(sData.data(:,index)) ~=length(answer) & ~isscalar(answer)
5593
+      answer='??? Illegal assignment.';
5594
+    else
5595
+      sData.data(:,index)=answer;
5596
+      sData.MODIFIED=1;
5597
+      data.sData=sData;
5598
+      set(pre_h,'UserData',data);
5599
+    end
5600
+  else
5601
+    if length(sData.data(str2num(assign),index)) ~=length(answer) & ~isscalar(answer)
5602
+      answer='??? Illegal assignment.';
5603
+    else
5604
+      sData.data(str2num(assign),index)=answer;
5605
+      sData.MODIFIED=1;
5606
+      data.sData=sData;
5607
+      set(pre_h,'UserData',data);
5608
+    end
5609
+  end
5610
+elseif ~strcmp(assign,'error') & ~isstr(answer) & ~strcmp(assign,'NOTASSIGN')  
5611
+  switch name
5612
+    case 'x'
5613
+     if isempty(get(data.comp_names_h,'Value'))
5614
+       return;
5615
+     end
5616
+     index = getfield(get_indices,{1});
5617
+     if isempty(assign)
5618
+       if length(sData.data(:,index)) ~= length(answer) & ~isscalar(answer)
5619
+         answer='??? Illegal assignment.';
5620
+       else
5621
+         sData.data(:,index)=answer;
5622
+         sData.MODIFIED=1;
5623
+         data.sData=sData;
5624
+         if strcmp(evaltype,'multiple')
5625
+           data.sData.comp_norm(index)={[]};
5626
+         end
5627
+         set(pre_h,'UserData',data);
5628
+       end
5629
+     else
5630
+       args=create_args(assign,'x');
5631
+       if length(args) == 1
5632
+         len=max(str2num(args{1}));
5633
+         if ~isscalar(len)
5634
+           answer='??? Illegal assignment.';
5635
+           return;
5636
+         elseif len > length(sData.data(:,1)) | min(str2num(args{1})) < 1
5637
+           answer='??? Illegal assignment.';
5638
+           return;
5639
+         elseif ~all(size(sData.data(str2num(args{1}),index))) == size(answer) & ~isscalar(answer)
5640
+           answer='??? Illegal assignment.';
5641
+           return;
5642
+         else            
5643
+           sData.data(str2num(args{1}),index)=answer;
5644
+           sData.MODIFIED=1;
5645
+           data.sData=sData;
5646
+           if strcmp(evaltype,'multiple')
5647
+             data.sData.comp_norm(index)={[]};
5648
+           end
5649
+           set(pre_h,'UserData',data);
5650
+         end
5651
+       else
5652
+         len=max(str2num(args{1}));
5653
+         dim=max(str2num(args{2}));
5654
+         asize=size(answer);
5655
+         msize=size(sData.data);
5656
+         if ~isscalar(len) | ~isscalar(dim) 
5657
+           answer='??? Illegal assignment.';
5658
+           return;
5659
+         elseif len > length(sData.data(:,1)) | len < 1
5660
+           answer='??? Illegal assignment.';
5661
+           return;
5662
+         elseif dim > 1 | dim > msize(2) | min(str2num(args{2})) < 1
5663
+           answer='??? Illegal assignment.';
5664
+           return;
5665
+         end 
5666
+         len=length(str2num(args{1}));
5667
+         dim=length(str2num(args{1}));
5668
+         if ~all([len dim] == asize) & ~isscalar(answer) 
5669
+           answer='??? Illegal assignment.';
5670
+           return;
5671
+         else
5672
+           tmp=sData.data(:,index);
5673
+           tmp([str2num(args{1})],[str2num(args{2})])=answer;
5674
+           sData.data(:,index)=tmp;
5675
+           sData.MODIFIED=1;
5676
+           data.sData=sData;
5677
+           if strcmp(evaltype,'multiple')
5678
+             data.sData.comp_norm(index)={[]};
5679
+           end
5680
+           set(pre_h,'UserData',data);
5681
+         end
5682
+       end
5683
+     end
5684
+
5685
+    case 'xs'
5686
+     if isempty(get(data.comp_names_h,'Value'))
5687
+       return;
5688
+     end
5689
+     indices=get_indices;
5690
+     if isempty(assign)
5691
+       if ~all(size(answer) == size(sData.data(:,indices))) & ~isscalar(answer)
5692
+         answer='??? Illegal assignment.';
5693
+       else       
5694
+         sData.data(:,indices) = answer;
5695
+         sData.MODIFIED=1;
5696
+         data.sData=sData;
5697
+         data.sData.comp_norm(indices)={[]};
5698
+         set(pre_h,'UserData',data);
5699
+       end
5700
+     else
5701
+       args=create_args(assign,'xs');
5702
+       if length(args) == 1
5703
+         len=max(str2num(args{1}));
5704
+         if ~isscalar(len)
5705
+           answer='??? Illegal assignment.';
5706
+           return;
5707
+         elseif len > length(sData.data(:,1)) | min(str2num(args{1})) < 1
5708
+           answer='??? Illegal assignment.';
5709
+           return;
5710
+         end
5711
+         if ~all(size(answer) == size(sData.data(str2num(args{1})))) &...
5712
+            ~isscalar(answer)
5713
+           answer='??? Illegal assignment.';
5714
+           return;
5715
+         else
5716
+           tmp=sData.data(:,indices);
5717
+           tmp(str2num(args{1}))=answer;
5718
+           sData.data(:,indices)=tmp;
5719
+           sData.MODIFIED=1;
5720
+           sData.comp_norm{indices}={[]};
5721
+           data.sData=sData;
5722
+           set(pre_h,'UserData',data);
5723
+         end
5724
+       else
5725
+         len=max(str2num(args{1}));
5726
+         dim=max(str2num(args{2}));
5727
+         asize=size(answer);
5728
+         msize=size(sData.data(:,indices));
5729
+         if ~isscalar(len) | ~isscalar(dim)
5730
+           answer='??? Illegal assignment.';
5731
+           return;
5732
+         elseif len > msize(1) | min(str2num(args{1})) < 1
5733
+           answer='??? Illegal assignment.';
5734
+           return;
5735
+         elseif dim > msize(2) | min(str2num(args{2})) < 1
5736
+           answer='??? Illegal assignment.';
5737
+           return;
5738
+         end
5739
+         len=length(str2num(args{1}));
5740
+         dim=length(str2num(args{2}));
5741
+         if ~all([len dim] == asize) & ~isscalar(answer)
5742
+           answer='??? Illegal assignment';
5743
+           return;
5744
+         else
5745
+           tmp=sData.data(:,indices);
5746
+           tmp([str2num(args{1})],[str2num(args{2})])=answer;
5747
+           sData.MODIFIED=1;
5748
+           sData.data(:,indices)=tmp;
5749
+           data.sData=sData;
5750
+           data.sData.comp_norm(indices)={[]};
5751
+           set(pre_h,'UserData',data); 
5752
+         end
5753
+        
5754
+       end
5755
+     end
5756
+
5757
+    case 'D'
5758
+     if isempty(assign)
5759
+       if ~all(size(answer) == size(sData.data)) & ~isscalar(answer)
5760
+         answer='??? Illegal assignment.';
5761
+       else
5762
+         if isscalar(answer)
5763
+           sData.data(:,:)=answer;
5764
+         else
5765
+           sData.data=answer;
5766
+         end
5767
+         sData.MODIFIED=1;
5768
+         data.sData=sData;
5769
+         data.sData.comp_norm(1:length(sData.data(1,:)))={[]};
5770
+         set(pre_h,'UserData',data);
5771
+       end
5772
+     else
5773
+       args=create_args(assign,'D');
5774
+       if length(args) == 1
5775
+         len=max(str2num(args{1}));
5776
+         if ~isscalar(len)
5777
+           answer='??? Illegal assignment.';
5778
+           return;
5779
+         elseif len > length(sData.data(:,1)) | min(str2num(args{1})) < 1
5780
+           answer='??? Illegal assignment.';
5781
+           return;
5782
+         end 
5783
+         if ~all(size(answer) == size(sData.data(str2num(args{1})))) &...
5784
+            ~isscalar(answer)
5785
+           answer='??? Illegal assignment.';
5786
+         else
5787
+           sData.data(str2num(args{1}))=answer;
5788
+           sData.MODIFIED=1;
5789
+           data.sData=sData;
5790
+           [i,j]=ind2sub(size(sData.data),str2num(args{1}));
5791
+           data.sData.comp_norm(j)={[]};
5792
+           set(pre_h,'UserData',data);
5793
+         end
5794
+       else
5795
+         len=max(str2num(args{1}));
5796
+         dim=max(str2num(args{2}));
5797
+         asize=size(answer);
5798
+         msize=size(sData.data);
5799
+         if ~isscalar(len) | ~isscalar(dim)
5800
+           answer='??? Illegal assignment.';
5801
+           return;
5802
+         elseif len > msize(1) | min(str2num(args{1})) < 1
5803
+           answer='??? Illegal assignment.';
5804
+           return;
5805
+         elseif dim > msize(2) | min(str2num(args{2})) < 1
5806
+           answer= '??? Illegal assignment.';
5807
+           return;
5808
+         end
5809
+         len = length(str2num(args{1}));
5810
+         dim = length(str2num(args{2}));
5811
+         if ~all([len dim] == asize) & ~isscalar(answer)
5812
+           answer='??? Illegal assignment.';
5813
+           return;
5814
+         else
5815
+           sData.data([str2num(args{1})],[str2num(args{2})])=answer;
5816
+           sData.MODIFIED=1;
5817
+           data.sData=sData;
5818
+           data.sData.comp_norm(str2num(args{2}))={[]};
5819
+           set(pre_h,'UserData',data);
5820
+         end
5821
+       end
5822
+     end
5823
+  end
5824
+end
5825
+if sData.MODIFIED
5826
+  selected=getfield(get(pre_h,'UserData'),'selected_vects');
5827
+  vector_h=getfield(get(pre_h,'UserData'),'vector_h');
5828
+  vect_mean_h=getfield(get(pre_h,'UserData'),'vect_mean_h');
5829
+  vects=zeros(length(sData.data(:,1)));
5830
+  vects(selected)=1;
5831
+  draw_vectors(vects,vector_h);
5832
+  vect_means(sData,vect_mean_h,selected);
5833
+  pro_tools('plot_hist');
5834
+  pro_tools('c_stat');
5835
+  cplot_mimema;
5836
+end
5837
+
5838
+ 
5839
+%%% Subfunction: check_assign %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5840
+
5841
+function [name,string,skip]=check_assign(string,evaltype)
5842
+
5843
+
5844
+reswords=[{'D'};{'x'};{'xs'}];
5845
+flag=0;
5846
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
5847
+
5848
+if isempty(pre_h)
5849
+  man_h=findobj(get(0,'Children'),'Tag','Management');
5850
+  clip_h=findobj(get(0,'Children'),'Tag','Clipping');
5851
+  errordlg('''Preprocess'' -window does not exist. Terminating program.');
5852
+  if ~isempty(man_h)
5853
+    close man_h;
5854
+  end
5855
+  if ~isempty(clip_h)
5856
+    close clip_h;
5857
+  end
5858
+  return;
5859
+end
5860
+
5861
+EMPTY=isempty(get(getfield(get(pre_h,'UserData'),'comp_names_h'),'Value'));
5862
+
5863
+[name,s]=give_token(string,evaltype);
5864
+skip=length(s);
5865
+
5866
+if strcmp(evaltype,'single') & ~strcmp(name,'x')
5867
+  string='NOTASSIGN';
5868
+  return;
5869
+end
5870
+
5871
+if strcmp(name,'other') & ~strcmp(s,'x') 
5872
+  string = 'error';
5873
+  return;
5874
+end
5875
+
5876
+if strcmp(name,[{'x'};{'xs'}])
5877
+  comp_names_h=getfield(get(gcf,'UserData'),'comp_names_h');
5878
+  if isempty(get(comp_names_h,'Value'))
5879
+    errordlg('There are not components chosen.');
5880
+    string='error';
5881
+    return;
5882
+  end
5883
+end
5884
+
5885
+
5886
+if skip == length(string) | ~strcmp(name,reswords)
5887
+  string = 'NOTASSIGN';
5888
+  return;
5889
+end
5890
+
5891
+if (strcmp(name,'x') | strcmp(name,'xs')) & EMPTY
5892
+  errordlg('There are not components chosen.');
5893
+  string = 'error';
5894
+  return;
5895
+end
5896
+
5897
+[t,s]=give_token(string(length(name)+1),evaltype);
5898
+
5899
+if strcmp(t,'(')
5900
+  flag=1;
5901
+end
5902
+
5903
+[foo,skip]=check_token(string,evaltype);
5904
+if length(name) ~= skip-1
5905
+  skip=skip-1;
5906
+  tmp=string(length(name)+1:skip);
5907
+else 
5908
+  tmp = [];
5909
+end
5910
+
5911
+if flag & tmp(length(tmp)) ~= ')'
5912
+  tmp(length(tmp)+1)=')';
5913
+end
5914
+
5915
+if skip==length(string)
5916
+  return;
5917
+end
5918
+
5919
+skip=skip+1;
5920
+if length(string) ~= skip
5921
+  [t,s]=give_token(string(skip+1:length(string)),evaltype);
5922
+else
5923
+  string='NOTASSIGN';
5924
+  return;
5925
+end
5926
+
5927
+if ~strcmp(t,'=')
5928
+  string = 'NOTASSIGN';
5929
+  return;
5930
+end
5931
+string=tmp;
5932
+skip = skip+2;
5933
+
5934
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5935
+
5936
+%%% Subfunction: isscalar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5937
+
5938
+function bool = isscalar(x)
5939
+
5940
+  m= size(x);
5941
+  
5942
+  bool = m(1) == 1 & m(2) == 1;
5943
+
5944
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5945
+
5946
+%%% Subfunction: create_args %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5947
+
5948
+function args=create_args(string,type)
5949
+
5950
+arg2='';
5951
+i=2;
5952
+j=1;
5953
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
5954
+msize=size(getfield(getfield(get(pre_h,'UserData'),'sData'),'data'));
5955
+
5956
+
5957
+if string(i) == ':'
5958
+  arg1=num2str(cat(2,'1:',num2str(msize(1))));
5959
+  i=i+1;
5960
+  j=j+length(arg1);
5961
+end
5962
+
5963
+while string(i) ~=',' & string(i) ~=')'
5964
+  arg1(j)=string(i);
5965
+  i=i+1;
5966
+  j=j+1;
5967
+end
5968
+
5969
+
5970
+
5971
+if string(i) ==','
5972
+  j=1;
5973
+  i=i+1;
5974
+  if string(i)==':'
5975
+    switch type
5976
+      case 'x'
5977
+       arg2='1';
5978
+      case 'cs'
5979
+       arg2=num2str(get_indices);
5980
+      case 'D'
5981
+       arg2=num2str(cat(2,'1:',num2str(msize(2))));
5982
+    end
5983
+    i=i+1;
5984
+    j=j+length(arg2);
5985
+  end
5986
+
5987
+  while string(i) ~= ')'
5988
+    arg2(j)=string(i);
5989
+    j=j+1;
5990
+    i=i+1;
5991
+  end
5992
+end
5993
+
5994
+
5995
+args{1}=arg1;
5996
+if ~isempty(arg2)
5997
+  args{2} = arg2;
5998
+end
5999
+
6000
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6001
+
6002
+function [str,skip] = check_token(string,evaltype)
6003
+
6004
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
6005
+
6006
+tmp_string=string;
6007
+[t,s]=give_token(tmp_string,evaltype);
6008
+skip=length(s);
6009
+
6010
+if strcmp(t,'c')
6011
+  if isempty(get(getfield(get(pre_h,'UserData'),'comp_names_h'),'Value'))
6012
+    errordlg('There are no components chosen.');
6013
+    str='error';
6014
+    return;
6015
+  end
6016
+  index=getfield(get_indices,{1});
6017
+  str=cat(2,'[',num2str(index),']');
6018
+  if skip == length(tmp_string)
6019
+    return;
6020
+  end
6021
+  tmp_string=tmp_string(skip+1:length(tmp_string));  
6022
+  [t,s] = give_token(tmp_string,evaltype);
6023
+  if ~strcmp(t,'(')
6024
+    return;
6025
+  end
6026
+  [args,skip2] = get_args(tmp_string(length(s)+1:length(tmp_string)),'c',...
6027
+                          evaltype);
6028
+  skip=skip+skip2+2;
6029
+  if strcmp(args,'error')
6030
+    str = 'error'
6031
+    return;
6032
+  elseif ~strcmp(args,'all')
6033
+    str=cat(2,'getfield(',str,',',args,')');
6034
+  else
6035
+    str=cat(2,'getfield(',str,',{[1]})'); 
6036
+  end
6037
+elseif strcmp(t,'cs')
6038
+  if isempty(get(getfield(get(pre_h,'UserData'),'comp_names_h'),'Value'))
6039
+    errordlg('There are no components chosen.');
6040
+    str='error';
6041
+    return;
6042
+  end
6043
+  str =cat(2,'[',num2str(get_indices),']');
6044
+  if length(s) == length(string)
6045
+    return;
6046
+  end
6047
+  tmp_string=tmp_string(1+length(s):length(string));
6048
+  [t,s]=give_token(tmp_string,evaltype);
6049
+  if ~strcmp(t,'(')
6050
+    return;
6051
+  else
6052
+    [args,skip2]=get_args(tmp_string(1+length(s):length(tmp_string)),'cs',...
6053
+                          evaltype);
6054
+    skip=2+skip+skip2;
6055
+    if strcmp(args,'error')
6056
+      str='error';
6057
+      return;
6058
+    elseif ~strcmp(args,'all')
6059
+      str = cat(2,'getfield(',str,',',args,')');
6060
+    else
6061
+      tmp_str=str;
6062
+      str=cat(2,'[getfield(',str,',','{1})');
6063
+      for i=2:length(get_indices)
6064
+        str=cat(2,str,';getfield(',tmp_str,',',sprintf('{%d})',i));
6065
+      end
6066
+      str=cat(2,str,']');
6067
+    end
6068
+  end
6069
+elseif strcmp(t,'dim')
6070
+  ind1=getfield(size(getfield(getfield(get(pre_h,'UserData'),'sData'),'data')),{2});
6071
+  str=cat(2,'[',num2str(ind1),']');
6072
+  if length(s)==length(string)
6073
+    return;
6074
+  end
6075
+  tmp_string=string(1+length(s):length(string));
6076
+  [t,s]=give_token(tmp_string,evaltype);
6077
+  if ~strcmp(t,'(')
6078
+    return;
6079
+  end
6080
+  skip=1+skip+length(s);
6081
+  [args,skip2]=get_args(tmp_string(1+length(s):length(tmp_string)),'dim',...
6082
+                        evaltype);
6083
+  if strcmp(args,'error')
6084
+    str = 'error';
6085
+    return;
6086
+  else
6087
+    skip=skip+skip2;
6088
+    if ~strcmp(args,'all')
6089
+      str=cat(2,'getfield(',str,',',args,')');
6090
+    end
6091
+  end
6092
+
6093
+elseif strcmp(t,'dlen') 
6094
+  ind1=getfield(size(getfield(getfield(get(pre_h,'UserData'),'sData'),'data')),{1});
6095
+  str=cat(2,'[',num2str(ind1),']');
6096
+  if length(s)==length(string)
6097
+    return;
6098
+  end
6099
+  tmp_string=string(1+length(s):length(string));
6100
+  [t,s]=give_token(tmp_string,evaltype);
6101
+  if ~strcmp(t,'(')
6102
+    return;
6103
+  end
6104
+  skip=skip+length(s);
6105
+  [args,skip2]=get_args(tmp_string(1+length(s):length(tmp_string)),'dlen',...
6106
+                        evaltype);
6107
+  if strcmp(args,'error')
6108
+    str='error';
6109
+    return;
6110
+  else
6111
+    skip=1+skip+skip2;
6112
+    if ~strcmp(args,'all')
6113
+      str=cat(2,'getfield(',str,',',args,')');
6114
+    end
6115
+  end
6116
+
6117
+elseif strcmp(t,'x')
6118
+  if isempty(get(getfield(get(pre_h,'UserData'),'comp_names_h'),'Value'))
6119
+    errordlg('There are not components chosen.');
6120
+    str='error';
6121
+    return;
6122
+  end
6123
+  len=getfield(size(getfield(getfield(get(pre_h,'UserData'),...
6124
+               'sData'),'data')),{1});
6125
+  index=num2str(getfield(get_indices,{1}));
6126
+  h_str='findobj(get(0,''Children''),''Tag'',''Preprocess'')';
6127
+  get_str=cat(2,'getfield(get(',h_str,',''UserData''),''sData'')');
6128
+  get_str=cat(2,'getfield(',get_str,',''data'')');
6129
+  str=cat(2,'getfield(',get_str,',{[1:',num2str(len),'],',index,'})');
6130
+  if length(s) == length(string)
6131
+    return;
6132
+  end
6133
+  tmp_string=string(1+length(s):length(string));
6134
+  [t,s]=give_token(tmp_string,evaltype);
6135
+  if ~strcmp(t,'(');
6136
+    return;
6137
+  end
6138
+  skip=skip+length(s);
6139
+  [args,skip2]=get_args(tmp_string(1+length(s):length(tmp_string)),'x',...
6140
+                        evaltype);
6141
+  if strcmp(args,'error')
6142
+    str = 'error';
6143
+    return;
6144
+  else
6145
+    skip=1+skip+skip2;
6146
+    if ~strcmp(args,'all')
6147
+      str=cat(2,'getfield(',str,',',args,')');
6148
+    end
6149
+  end
6150
+
6151
+elseif strcmp(t,'xs')
6152
+  if isempty(get(getfield(get(pre_h,'UserData'),'comp_names_h'),'Value'))
6153
+    errordlg('There are not components chosen.');
6154
+    str='error';
6155
+    return;
6156
+  end
6157
+  len=getfield(size(getfield(getfield(get(pre_h,'UserData'),...
6158
+               'sData'),'data')),{1});
6159
+  index=get_indices;
6160
+  index=cat(2,'[',num2str(index),']');
6161
+  h_str='findobj(get(0,''Children''),''Tag'',''Preprocess'')';
6162
+  get_str=cat(2,'getfield(get(',h_str,',''UserData''),''sData'')');
6163
+  get_str=cat(2,'getfield(',get_str,',''data'')');
6164
+  str=cat(2,'getfield(',get_str,',{[1:',num2str(len),'],',index,'})');
6165
+  if length(s) == length(string)
6166
+    return;
6167
+  end
6168
+  tmp_string=string(1+length(s):length(string));
6169
+  [t,s]=give_token(tmp_string,evaltype);
6170
+  if ~strcmp(t,'(')
6171
+    return;
6172
+  end
6173
+  skip=1+skip+length(s);
6174
+
6175
+  [args,skip2]=get_args(tmp_string(1+length(s):length(tmp_string)),'xs',...
6176
+                        evaltype);
6177
+  if strcmp(args,'error')
6178
+    str = 'error';
6179
+    return;
6180
+  elseif ~strcmp(args,'all')  
6181
+    str=cat(2,'getfield(',str,',',args,')');
6182
+    skip=skip+skip2;
6183
+  else
6184
+    skip=skip+skip2;
6185
+    [dlen,dim]=size(eval(str));
6186
+    tmp_str=str;
6187
+    str=cat(2,'[','getfield(',tmp_str,sprintf(',{1:%d,1})',dlen));
6188
+    for i=2:dim
6189
+      tmp=sprintf(',{1:%d,%d})',dlen,dim);
6190
+      str=cat(2,str,';','getfield(',tmp_str,tmp);
6191
+    end
6192
+    str=cat(2,str,']');
6193
+  end
6194
+elseif strcmp(t,'D')
6195
+  get_h='findobj(get(0,''Children''),''Tag'',''Preprocess'')';
6196
+  str=cat(2,'getfield(getfield(get(',get_h,',''UserData''),''sData''),''data'')');
6197
+
6198
+  if length(s) >= length(tmp_string)
6199
+    return;
6200
+  end
6201
+
6202
+  tmp_string=tmp_string(1+length(s):length(tmp_string));
6203
+  [t,s]=give_token(tmp_string,evaltype);
6204
+  if ~strcmp(t,'(')
6205
+    return;
6206
+  else
6207
+    tmp_string=tmp_string(1+length(s):length(tmp_string));
6208
+    skip = skip+length(s);
6209
+    [args, skip2]=get_args(tmp_string,'D',evaltype);
6210
+    if strcmp(args,'error')
6211
+      str='error';
6212
+      return;
6213
+    elseif ~strcmp(args,'all')
6214
+      str=cat(2,'getfield(',str,',',args,')');
6215
+      skip=1+skip+skip2;
6216
+    else
6217
+      skip=1+skip+skip2;
6218
+      [dlen,dim]=size(eval(str));
6219
+      tmp_str=str;
6220
+      str=cat(2,'[getfield(',str,sprintf(',{1:%d,1})',dlen));
6221
+      for i=2:dim
6222
+        tmp=sprintf(',{1:%d,%d}',dlen,i);
6223
+        str=cat(2,str,';getfield(',tmp_str,tmp,')');
6224
+      end
6225
+      str=cat(2,str,']');
6226
+    end
6227
+  end  
6228
+else
6229
+  if strcmp(t,'(')
6230
+    str = t;
6231
+    str2='';
6232
+    tmp_string=tmp_string(1+length(s):length(tmp_string));
6233
+    while ~strcmp(str2,')') & ~isempty(tmp_string)
6234
+      [str2,skip2]=check_token(tmp_string,evaltype);
6235
+      if strcmp(str2,'error')
6236
+        str='error';
6237
+        return;
6238
+      end
6239
+      skip=skip+skip2;
6240
+      tmp_string=tmp_string(skip2+1:length(tmp_string));
6241
+      str=cat(2,str,str2);
6242
+    end
6243
+    if ~strcmp(str2,')')
6244
+      str = 'error';
6245
+    end
6246
+  else
6247
+    str = s;
6248
+  end
6249
+end
6250
+
6251
+%%% Subfunction: get_args %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6252
+
6253
+function [str,skip] = get_args(string,flag,evaltype)
6254
+
6255
+res_words=[{'D'};{'c'};{'cs'};{'dim'};{'dlen'};{'x'};{'xs'}];
6256
+NOTALL=1;
6257
+if isempty(string)
6258
+  str='error'
6259
+  skip=[];
6260
+  return;
6261
+end
6262
+[t,s] = give_token(string,evaltype);
6263
+
6264
+
6265
+skip=length(s);
6266
+if any(strcmp(t,res_words));
6267
+  [str,skip2] = check_token(string,evaltype);
6268
+  string=string(1+length(s):length(string)); 
6269
+  str=cat(2,'{[',str);
6270
+  [t,s]=give_token(string,evaltype);
6271
+elseif t==')' | t==','
6272
+  str = 'error';
6273
+  return;
6274
+elseif strcmp(t,':');
6275
+  if length(s) == length(string)
6276
+    str='error';
6277
+    return;
6278
+  end
6279
+  [t,s]=give_token(string(1+length(s):length(string)),evaltype);
6280
+  if t == ')'
6281
+    str = 'all';
6282
+    return;
6283
+  end
6284
+  switch flag
6285
+    case {'c','cs','dim','dlen'}
6286
+     str= '{[1';
6287
+    otherwise
6288
+     str=cat(2,'{[',get_all('vect'));
6289
+  end
6290
+  NOTALL=0;
6291
+  string=string(1+length(s):length(string));
6292
+  [t,s]=give_token(string,evaltype);
6293
+  skip=skip+1;
6294
+else 
6295
+  str = cat(2,'{[',s);
6296
+end
6297
+str2 =[];
6298
+
6299
+
6300
+if ~strcmp(t,',') & ~strcmp(t,')')
6301
+  skip=skip-length(s);
6302
+end
6303
+
6304
+
6305
+
6306
+while ~strcmp(t,',') & ~strcmp(t,')') & NOTALL;
6307
+  str=cat(2,str,str2);
6308
+  [t,s] = give_token(string,evaltype);
6309
+  if length(s) == length(string)
6310
+    str = 'error';
6311
+    return;
6312
+  end
6313
+  string=string(1+length(s):length(string));
6314
+  skip=skip+length(s);
6315
+  [t,s]=give_token(string,evaltype);
6316
+  if length(s) == length(string) & ~strcmp(t,')')
6317
+    str = 'error';
6318
+    return;
6319
+  end
6320
+
6321
+  [str2,foo]=check_token(string,evaltype);  
6322
+end 
6323
+
6324
+if NOTALL & ~strcmp(t,')')
6325
+ skip=skip+1;
6326
+end
6327
+
6328
+if strcmp(t,')')
6329
+  str=cat(2,str,']}');
6330
+  return
6331
+end
6332
+
6333
+str=cat(2,str,']',',','[');
6334
+str2 = [];
6335
+
6336
+
6337
+[t,s] = give_token(string,evaltype);
6338
+if strcmp(t,')')
6339
+  str = 'error'
6340
+  return;
6341
+end
6342
+NOTALL=1;
6343
+string=string(1+length(s):length(string));
6344
+[t,s]=give_token(string,evaltype);
6345
+if strcmp(t,':');
6346
+   switch flag
6347
+     case {'c','dim','dlen','x'}
6348
+      str=cat(2,str,'1');
6349
+     case 'D'
6350
+      str=cat(2,str,get_all('comp'));
6351
+     case {'cs','xs'}
6352
+      str=cat(2,str,'1:',num2str(length(get_indices)));
6353
+   end
6354
+   NOTALL=0;
6355
+   if length(s) == length(string)
6356
+    str='error';
6357
+    return;
6358
+   end
6359
+   string=string(1+length(s):length(string));
6360
+   [t,s]=give_token(string,evaltype);
6361
+end
6362
+
6363
+if ~strcmp(t,')') & NOTALL
6364
+  skip=skip-1;
6365
+end
6366
+
6367
+while ~strcmp(t,')') & NOTALL
6368
+  str=cat(2,str,str2);
6369
+  skip=skip+length(s);
6370
+  if length(s) == length(string) & ~strcmp(t,')')
6371
+    str='error';
6372
+    return;
6373
+  end
6374
+  [str2,foo]=check_token(string,evaltype);
6375
+  string=string(1+length(s):length(string));
6376
+  [t,s]=give_token(string,evaltype);
6377
+end
6378
+if ~strcmp(t,')')
6379
+  str='error';
6380
+  return;
6381
+end
6382
+
6383
+
6384
+str=cat(2,str,str2,']}');
6385
+skip=skip+length(s);
6386
+
6387
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6388
+
6389
+%%% Subfunction: get_all %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6390
+
6391
+function str=get_all(vect_or_comp)
6392
+
6393
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
6394
+
6395
+switch vect_or_comp
6396
+  case 'vect'
6397
+   dim=getfield(size(getfield(getfield(get(pre_h,'UserData'),...
6398
+                'sData'),'data')),{1});
6399
+   str=cat(2,'1:',num2str(dim));
6400
+  case 'comp'
6401
+   dim=getfield(size(getfield(getfield(get(pre_h,'UserData'),...
6402
+                'sData'),'data')),{2});
6403
+   str=cat(2,'1:',num2str(dim));
6404
+end
6405
+
6406
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6407
+
6408
+function [token,str]=give_token(string,evaltype)
6409
+
6410
+n=length(string);
6411
+i=1;
6412
+char=string(i);
6413
+
6414
+switch analyze_char(string(i));
6415
+  case 'num'
6416
+   token='num';
6417
+   while i <= n & strcmp('num',analyze_char(string(i)))
6418
+     str(i)=string(i);
6419
+     i=i+1;
6420
+   end
6421
+  case 'other'
6422
+   switch string(i)
6423
+     case ':'
6424
+      token = ':';
6425
+     case ','
6426
+      token = ',';
6427
+     case '('
6428
+      token = '(';
6429
+     case ')'
6430
+      token = ')';
6431
+     case '='
6432
+      token = '=';
6433
+     otherwise
6434
+      token='other';
6435
+   end
6436
+   str=string(i);
6437
+  case 'alpha'
6438
+   while i <= n & strcmp('alpha',analyze_char(string(i)))
6439
+    str(i)=string(i);
6440
+    i=i+1;
6441
+   end
6442
+   token = find_res_word(str,evaltype);
6443
+end
6444
+
6445
+%%% Subfunction: analyze_char %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6446
+
6447
+function type=analyze_char(char)
6448
+
6449
+
6450
+if ((char-0) >= ('0'-0) &  (char-0) <= ('9'-0))
6451
+  type='num';
6452
+elseif   ((char-0) >= ('a'-0) & (char-0) <= ('z'-0)) ...
6453
+       | ((char-0) >= ('A'-0) & (char-0) <= ('Z'-0))  
6454
+  type='alpha';
6455
+else
6456
+  type='other';
6457
+end
6458
+
6459
+
6460
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6461
+
6462
+%%% Subfunction: find_res_word %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6463
+
6464
+function token = find_res_word(string,evaltype)
6465
+
6466
+reswords=[{'D'};{'c'};{'cs'};{'dim'};{'dlen'};{'x'};{'xs'};{'other'}];
6467
+
6468
+for i=1:length(reswords);
6469
+  token=reswords{i};
6470
+  if strcmp(string,reswords{i})
6471
+    if strcmp(evaltype,'single') & ~strcmp(string,'x')
6472
+      token = 'other';
6473
+    end
6474
+    return;
6475
+  end
6476
+end
6477
+
6478
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6479
+
6480
+function close_func(varargin)
6481
+
6482
+switch varargin{1}
6483
+  case 'close_c'
6484
+   str='% Closing the ''Clipping'' -window...';
6485
+   clip_h=findobj(get(0,'Children'),'Tag','Clipping');
6486
+   close(clip_h);
6487
+  case 'close_sD'
6488
+   str='% Closing the ''Data Set Management'' -window...';
6489
+   sD_h=findobj(get(0,'Children'),'Tag','Management');
6490
+   close(sD_h);
6491
+  case 'close_w'
6492
+   str='% Closing the ''Windowed'' -window...';
6493
+   win_h=findobj(get(0,'Children'),'Tag','Window');
6494
+   close(win_h);
6495
+  case 'close_s'
6496
+   str='% Closing the ''Select'' -window...';
6497
+   sel_h=findobj(get(0,'Children'),'Tag','Select');
6498
+   close(sel_h);
6499
+  case 'close_d'
6500
+   str='% Closing the ''Delay'' -window...';
6501
+   del_h=findobj(get(0,'Children'),'Tag','Delay');
6502
+   close(del_h);
6503
+end
6504
+
6505
+if nargin ~= 2
6506
+  pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
6507
+  preh_udata=get(pre_h,'UserData');
6508
+  str2=cat(2,'preprocess(''',varargin{1},''',''foo'');');
6509
+  preh_udata.LOG{length(preh_udata.LOG)+1}=str;
6510
+  preh_udata.LOG{length(preh_udata.LOG)+1}=str2;
6511
+  set(pre_h,'UserData',preh_udata);
6512
+end
6513
+
6514
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6515
+
6516
+function log_file
6517
+
6518
+answer=inputdlg('Give the name of the outputfile:','LOG function',1,...
6519
+                {'log_function'});
6520
+
6521
+if isempty(answer)
6522
+  return;
6523
+end
6524
+
6525
+
6526
+tmp=clock;
6527
+str =cat(2,'% Created: ',...
6528
+           date,...
6529
+           ' ',sprintf('%d:%d\n%\n\n',tmp(4),tmp(5)));
6530
+pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
6531
+LOG=getfield(get(pre_h,'UserData'),'LOG');
6532
+file=cat(2,pwd,'/',answer{1},'.m');
6533
+fid =fopen(file,'w');
6534
+
6535
+arg=LOG{2}(12:length(LOG{2})-2);
6536
+fprintf(fid,'%s\n \n',cat(2,'function ',answer{1},'(',arg,')'));
6537
+fprintf(fid,'%s\n',str);
6538
+for i=1:length(LOG)
6539
+  fprintf(fid,'%s\n',LOG{i});
6540
+end
6541
+fclose(fid);
6542
+disp(sprintf('LOG-file ''%s'' is done.',file));
6543
+
6544
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6545
+
6546
+function get_selected_inds(varargin)
6547
+
6548
+if nargin == 1
6549
+  LOG=1;
6550
+  answer = {varargin{1}};
6551
+else
6552
+  LOG=0;
6553
+end
6554
+
6555
+selected=getfield(get(gcf,'UserData'),'selected_vects');
6556
+if ~LOG
6557
+  answer=inputdlg('Give the name of the output variable:',...
6558
+                '',1,{'indices'});
6559
+end
6560
+
6561
+if isempty(answer) | isempty(answer{1})
6562
+  return;
6563
+else
6564
+  assignin('base',answer{1},selected);
6565
+  disp(cat(2,'Indices of the selected vectors are set to the workspace ',...  
6566
+           sprintf(' as ''%s''.',answer{1})));
6567
+  if ~LOG
6568
+    data=get(gcf,'UserData');
6569
+    data.LOG{length(data.LOG)+1}=...
6570
+    '% Saving indices of the selected vectors to the workspace.';
6571
+    data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''get_inds'',',...
6572
+                                        '''',answer{1},''');');
6573
+    set(gcf,'UserData',data);
6574
+  end
6575
+end
6576
+
6577
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6578
+
6579
+function no_of_selected(varargin)
6580
+
6581
+if nargin == 1
6582
+  pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
6583
+  set(0,'CurrentFigure',pre_h);
6584
+  LOG = 1;
6585
+else
6586
+  LOG = 0;
6587
+end
6588
+
6589
+results_h=getfield(get(gcf,'UserData'),'results_h');
6590
+no=length(getfield(get(gcf,'UserData'),'selected_vects'));
6591
+str={sprintf('Number of selected vectors: %d\n', no)};
6592
+set(results_h,'String',str,'HorizontalAlignment','left');
6593
+
6594
+if ~LOG
6595
+  data=get(gcf,'UserData');
6596
+  data.LOG{length(data.LOG)+1}='% Number of selected vectors';
6597
+  data.LOG{length(data.LOG)+1}='preprocess(''no_of_sel'',''foo'');';
6598
+  set(gcf,'UserData',data);
6599
+end
6600
+
6601
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6602
+
6603
+function select_all_comps(varargin)
6604
+
6605
+if nargin == 1
6606
+  pre_h=findobj(get(0,'Children'),'Tag','Preprocess');
6607
+  set(0,'CurrentFigure',pre_h);
6608
+  LOG=1;
6609
+else
6610
+  LOG=0;
6611
+end
6612
+
6613
+comp_names_h=getfield(get(gcf,'UserData'),'comp_names_h');
6614
+
6615
+set(comp_names_h,'Value',[1:length(get(comp_names_h,'String'))]);
6616
+sel_comp;
6617
+
6618
+if ~LOG
6619
+  data=get(gcf,'UserData');
6620
+  data.LOG{length(data.LOG)+1}='% Select all components';          
6621
+  data.LOG{length(data.LOG)+1}='preprocess(''sel_all_comps'',''foo'');';
6622
+  set(gcf,'UserData',data);
6623
+end
6624
+
6625
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
6626
+
6627
+function code=write_log_code(indices,arg1,arg2,arg3,arg4,arg5,arg6);
6628
+
6629
+str=textwrap({num2str(indices)},500);
6630
+
6631
+code{1}=sprintf('inds=[];');
6632
+for i=1:length(str);
6633
+  code{i+1}=sprintf('  inds=cat(2,inds,[%s]);',str{i});
6634
+end
6635
+str=cat(2,'preprocess(''''clip_data'''',''''',arg1,' ',num2str(arg2),' ',...
6636
+                      num2str(arg3),' ',num2str(arg4),...
6637
+                      ' ',num2str(arg5),' ',num2str(arg6),' ');
6638
+code{length(code)+1}=cat(2,'eval(cat(2,',...
6639
+                            '''',str,'''',...
6640
+                            ',num2str(inds),'''''');''));');
6641
+
6642
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,572 @@
1
+function aout = rep_utils(action,fmt,fid)
2
+
3
+%REP_UTILS Utilities for print reports and report elements.
4
+%  
5
+% aout = rep_utils(action,fmt,[fid])
6
+% 
7
+%  Input and output arguments ([]'s are optional): 
8
+%   action      (string)     action identifier
9
+%               (cell array) {action,par1,par2,...}
10
+%                            the action identifier, followed by action 
11
+%                            parameters
12
+%   [fmt]       (string)     format of output, 'txt' by default
13
+%   [fid]       (scalar)     output file id, by default NaN in which
14
+%                            case output is not written, only returned
15
+%                            in aout
16
+%   
17
+%   aout        (varies)     output of the action
18
+%
19
+%  Here are the actions and their arguments: 
20
+%  'printlines'   par1 (cellstr)   print par1, each cell on a new line
21
+%  'header'       par1 (string)    print document header using par1 as title
22
+%  'footer'                        print document footer
23
+%  'compile'      par1 (string)    compile the named document (only 'ps' and 'pdf')
24
+%  'inserttable'  par1 (struct)    print given table
25
+%                 par2 (scalar)    print lines between rows if par2=1
26
+%                 par3 (scalar)    use longtable format (only 'ps' and 'pdf')
27
+%  'printfigure'  par1 (string)    print current figure to file, par1 = filename
28
+%                 par2 (scalar)    used resolution (150 dpi by default)
29
+%                 par3 (scalar)    if par3=1, insert figure in minipage
30
+%  'insertfigure' par1 (string)    insert figure to report, par1 = filename of figure
31
+%                 par2 (vector)    size 2 x 1, size of figure relative to page size 
32
+%                                  NaN = automatic scaling
33
+%                 par3 (scalar)    if par3=1, insert figure in minipage (only 'ps' and 'pdf')
34
+%  'insertbreak'                   insert paragraph break into report 
35
+%
36
+% See also  REP_STATS.
37
+
38
+% Contributed to SOM Toolbox 2.0, January 2nd, 2002 by Juha Vesanto
39
+% Copyright (c) by Juha Vesanto
40
+% http://www.cis.hut.fi/projects/somtoolbox/
41
+
42
+% Version 2.0beta juuso 020102
43
+
44
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
45
+%% input arguments
46
+
47
+pars = {''}; 
48
+if iscell(action), 
49
+    if length(action)>1, pars = action(2:end); end
50
+    action = action{1}; 
51
+end
52
+
53
+if nargin<2 | isempty(fmt), fmt = 'txt'; end
54
+global REPORT_OUTPUT_FMT
55
+REPORT_OUTPUT_FMT = fmt;
56
+
57
+if nargin<3 | isempty(fid), fid = NaN; end
58
+
59
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
60
+%% action
61
+
62
+aout = []; 
63
+printable = 0; 
64
+
65
+switch action,
66
+case 'printlines',
67
+    aout = pars{1}; 
68
+case 'header',     
69
+    switch fmt, 
70
+    case {'ps','pdf'}, aout = tex_startdocument(pars{1}); 
71
+    case 'html',       aout = html_startpage(pars{1});
72
+    case 'txt',        aout = cell(0);
73
+    end 
74
+    printable = 1; 
75
+case 'footer', 
76
+    switch fmt, 
77
+    case {'ps','pdf'}, aout = tex_enddocument; 
78
+    case 'html',       aout = html_endpage;
79
+    case 'txt',        aout = cell(0);
80
+    end 
81
+    printable = 1; 
82
+case 'compile',      aout = compiledocument(pars{1});
83
+case 'inserttable',  aout = inserttable(pars{:}); printable = 1; 
84
+case 'printfigure',  printfigure(pars{:});
85
+case 'insertfigure', aout = insertfigure(pars{:}); printable = 1;
86
+case 'insertbreak',  aout = insertbreak; printable = 1; 
87
+case 'joinstr',      aout = joinstr(pars{:}); printable = 1; 
88
+case 'rulestr',      aout = rulestr(pars{:}); printable = 1; 
89
+case 'c_and_p_str',  aout = c_and_p_str(pars{:}); printable = 1; 
90
+case 'p_str',        aout = p_str(pars{:}); printable = 1; 
91
+end 
92
+
93
+% if output file is given, print lines
94
+if ~isnan(fid) & printable,
95
+    if ~iscell(aout), aout = {aout}; end
96
+    for i = 1:length(aout), fprintf(fid,'%s\n',fmtline(aout{i})); end
97
+end
98
+
99
+return;
100
+
101
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
102
+%% subfunctions
103
+
104
+%% simple formatter strings
105
+
106
+function s = joinstr(cs, sep1, sep2)
107
+  if nargin==1, sep1 = ', '; sep2 = ' and '; end
108
+  if nargin<3, sep2 = sep1; end
109
+  if isempty(cs), 
110
+    s = '';     
111
+  elseif strcmp(sep1,'\n'), 
112
+    if size(cs,1)==1, cs = cs'; end
113
+    s = char(cs); 
114
+  else
115
+    s = cs{1}; 
116
+    for i=2:length(cs)-1, s = [s sep1 cs{i}]; end
117
+    if length(cs)>1, s = [s sep2 cs{end}]; end
118
+  end
119
+  return; 
120
+
121
+function str = c_and_p_str(n,m)
122
+
123
+  % return a string of form # (%), e.g. '23 (12%)'
124
+  if n==m, p = '100'; 
125
+  elseif n==0, p = '0';
126
+  else p = sprintf('%.2g',100*n/m);
127
+  end
128
+  str = sprintf('%d (%s%%)',round(n),p); 
129
+  return;
130
+  
131
+function str = p_str(p)
132
+  % return a string of form %, e.g. '12%'
133
+  if round(p*100)>=100, p = sprintf('%3g',100*p); 
134
+  elseif abs(p)<eps, p = '0';
135
+  else p = sprintf('%.2g',100*p);
136
+  end
137
+  str = sprintf('%s%%',p); 
138
+  return;
139
+
140
+function cs = rulestr(sR,cnames)
141
+  global REPORT_OUTPUT_FMT
142
+  switch REPORT_OUTPUT_FMT
143
+   case {'ps','pdf'}, [leq,geq,infi,m,less,in] = deal('\leq','\geq','\inf','$','<','\in'); 
144
+   case 'html',  [leq,geq,infi,m,less,in]  = deal('&lt;=','&gt;=','Inf',' ','&lt;',' '); 
145
+   case 'txt', [leq,geq,infi,m,less,in]  = deal('<=','>=','inf',' ','<',''); 
146
+  end
147
+  nr = length(sR); 
148
+  cs = cell(nr,1); 
149
+  fmt = '%.2g'; 
150
+  if nargin<2, cnames = {sR.name}; end
151
+  if isempty(cnames), cnames = cell(nr,1); cnames(:) = {''}; end 
152
+  for i=1:nr,       
153
+    low  = sR(i).low; 
154
+    high = sR(i).high; 
155
+    switch isfinite(low) + 2*isfinite(high), 
156
+     case 0, cs{i} = [cnames{i} ' ' 'any']; 
157
+     case 1, cs{i} = [cnames{i} ' ' m geq sprintf(fmt,low) m];
158
+     case 2, cs{i} = [cnames{i} ' ' m less sprintf(fmt,high) m]; 
159
+     case 3, cs{i} = [cnames{i} ' ' m in '[' sprintf(fmt,low) ',' sprintf(fmt,high) ']' m];
160
+    end
161
+  end
162
+  return; 
163
+
164
+%% print figure
165
+
166
+function imgfmt = fmt2imgfmt
167
+  global REPORT_OUTPUT_FMT
168
+  switch REPORT_OUTPUT_FMT, 
169
+  case 'ps',   imgfmt = 'ps'; 
170
+  case 'pdf',  imgfmt = 'pdf'; 
171
+  case 'html', imgfmt = 'png'; 
172
+  case 'txt',  imgfmt = ''; 
173
+  end
174
+  return; 
175
+
176
+function printfigure(fname,resolution)
177
+  if nargin<2, resolution = 150; end
178
+  fnameps = [fname '.ps']; 
179
+  switch fmt2imgfmt,
180
+  case 'ps',  
181
+      print('-dpsc2',fnameps); 
182
+  case 'pdf', 
183
+      print('-dpsc2',fnameps);       
184
+      eval(sprintf('!ps2pdf %s',fnameps));  
185
+  case 'gif',       
186
+      print('-dpsc2',fnameps);              
187
+      cmd = 'pstogif'; 
188
+      opt = sprintf('-depth 1 -density %d',resolution); 
189
+      unix(sprintf('%s %s -out %s %s',cmd,opt,[fname '.gif'],fnameps));
190
+  case 'png',
191
+      opt = sprintf('-r%d',resolution); 
192
+      print('-dpng',opt,[fname '.png']);
193
+  end
194
+  return; 
195
+
196
+%% headers and footers, and compilation
197
+
198
+function cs = tex_startdocument(title)
199
+  % tex document headers
200
+  global REPORT_OUTPUT_FMT
201
+  cs = cell(0); 
202
+  cs{end+1} = '\documentclass[10pt,a4paper]{article}'; 
203
+  cs{end+1} = '\usepackage[dvips]{epsfig,graphicx,color}'; 
204
+  cs{end+1} = '\usepackage{float,graphics,subfigure}'; 
205
+  cs{end+1} = '\usepackage{multirow,rotating,portland,lscape,longtable,pifont}'; 
206
+  cs{end+1} = '\usepackage[T1]{fontenc}'; 
207
+  if strcmp(REPORT_OUTPUT_FMT,'pdf'), cs{end+1} = '\usepackage{pslatex}'; end
208
+  cs{end+1} = '\usepackage[english]{babel}'; 
209
+
210
+  cs{end+1} = '\oddsidemargin 0 mm';
211
+  cs{end+1} = '\evensidemargin 0 mm';
212
+  cs{end+1} = '\textwidth 17 cm';
213
+  cs{end+1} = '\topmargin 0 mm';
214
+  cs{end+1} = '\textheight 21 cm';
215
+  cs{end+1} = '\voffset 0 mm';
216
+
217
+  cs{end+1} = '\begin{document}'; 
218
+  cs{end+1} = ['\title{' title '}']; 
219
+  cs{end+1} = '\maketitle'; 
220
+  %cs{end+1} = '\tableofcontents'; 
221
+  %cs{end+1} = '\clearpage'; 
222
+  return;
223
+
224
+function cs = tex_enddocument
225
+  cs = cell(0);
226
+  cs{end+1} = '\end{document}';
227
+  return; 
228
+
229
+function cs = html_startpage(title)
230
+  % print HTML document headers
231
+  cs = cell(0);
232
+  cs{end+1} = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">';
233
+  cs{end+1} = '<HTML>';
234
+  cs{end+1} = '<HEAD>';
235
+  cs{end+1} = sprintf('  <TITLE>%s</TITLE>',title);
236
+  cs{end+1} = '</HEAD>';
237
+  cs{end+1} = '<BODY bgcolor=white vlink="#000033" link="#0000ff" text="#000000">';
238
+  if ~isempty(title), cs{end+1} = sprintf('<H1>%s</H1>',title); end
239
+  return;
240
+
241
+function cs = html_endpage
242
+  % print HTML document footers
243
+  cs = cell(0);
244
+  cs{end+1} = '<P><HR>';
245
+  cs{end+1} = '</BODY>';
246
+  cs{end+1} = '</HTML>';
247
+  return;
248
+
249
+function files = compiledocument(filename)
250
+  global REPORT_OUTPUT_FMT
251
+  switch REPORT_OUTPUT_FMT, 
252
+   case 'pdf', 
253
+    eval(sprintf('!pdflatex --interaction batchmode %s.tex',filename));
254
+    eval(sprintf('!pdflatex --interaction batchmode %s.tex',filename));
255
+    %eval(sprintf('!acroread %s.pdf &',filename)); 
256
+    files = {[filename '.aux'],[filename '.log'],[filename '.out'],[filename '.pdf']}; 
257
+   case 'ps', 
258
+    eval(sprintf('!latex --interaction batchmode %s.tex',filename));
259
+    eval(sprintf('!latex --interaction batchmode %s.tex',filename));
260
+    eval(sprintf('!dvips %s.dvi',filename)); 
261
+    eval(sprintf('!ps2pdf %s.ps',filename));
262
+    %eval(sprintf('!ghostview %s.ps &',filename)); 
263
+    files = {[filename '.aux'],[filename '.log'],[filename '.out'],[filename '.dvi'],[filename '.pdf']}; 
264
+   case 'html',   
265
+   case 'txt',
266
+  end
267
+  return; 
268
+
269
+
270
+function vstr = defaultformat(val)  
271
+  global REPORT_OUTPUT_FMT
272
+  if ischar(val),        vstr = val; 
273
+  elseif iscellstr(val), vstr = char(val); 
274
+  elseif isempty(val),   vstr = ''; 
275
+  elseif isnumeric(val), 
276
+    if val==round(val), fmt = '%d'; else fmt = '%.3g'; end 
277
+    if abs(val)<=eps, vstr = '0'; else vstr = sprintf(fmt,val); end
278
+  elseif isstruct(val) & isfield(val,'values') & isfield(val,'headers'), 
279
+    % a table
280
+    vstr = joinstr(inserttable(val,0),'\n');
281
+    if any(strcmp(REPORT_OUTPUT_FMT,{'ps','pdf'})), 
282
+      vstr= inserttominipage(vstr); 
283
+    end
284
+  else
285
+    vstr = ''; fprintf(1,'defaultformat unable to handle input\n');     
286
+    whos val
287
+  end
288
+  return; 
289
+
290
+%% report elements (list, table, image, link)
291
+
292
+function str = fmtline(str)
293
+  % replace some formatting elements depeding on output format
294
+  global REPORT_OUTPUT_FMT
295
+  if isempty(str), str = ''; return; end
296
+  switch REPORT_OUTPUT_FMT, 
297
+   case {'ps','pdf'}, 
298
+     str = strrep(str,'<B>',  '{\bf ');
299
+     str = strrep(str,'<I>',  '{\em ');
300
+     str = strrep(str,'<TT>', '{\tt ');
301
+     str = strrep(str,'</B>', '}');
302
+     str = strrep(str,'</I>', '}');
303
+     str = strrep(str,'</TT>','}');
304
+     str = strrep(str,'#','\#'); 
305
+     str = strrep(str,'%','\%');
306
+   case 'html', % nil
307
+   case 'txt', 
308
+     str = strrep(str,'<B>',  '*');
309
+     str = strrep(str,'<I>',  '*');
310
+     str = strrep(str,'<TT>', '');
311
+     str = strrep(str,'</B>', '*');
312
+     str = strrep(str,'</I>', '*');
313
+     str = strrep(str,'</TT>','');
314
+  end
315
+  return;
316
+
317
+function cs = insertbreak
318
+    global REPORT_OUTPUT_FMT
319
+    cs = cell(0); 
320
+    switch REPORT_OUTPUT_FMT
321
+    case {'ps','pdf'}, cs{end+1} = '';
322
+    case 'html', cs{end+1} = '<P>';
323
+    case 'txt', cs{end+1} = ''; 
324
+    end   
325
+    return;
326
+    
327
+function insertlist(list,enum)
328
+  % make list
329
+  global REPORT_OUTPUT_FMT
330
+  if nargin<2, enum = 0; end
331
+  cs = cell(0);
332
+  switch REPORT_OUTPUT_FMT
333
+   case {'ps','pdf'}, 
334
+    if enum, tag = 'enumerate'; else tag = 'itemize'; end
335
+    starttag = ['\begin{' tag '}'];
336
+    listtag = '\item ';
337
+    endtag = ['\end{' tag '}'];
338
+   case 'html', 
339
+    if enum, tag = 'OL'; else tag = 'UL'; end
340
+    starttag = ['<' tag '>'];
341
+    listtag = '<LI>';
342
+    endtag = ['</' tag '>'];   
343
+   case 'txt',
344
+    starttag = ''; 
345
+    listtag = '- ';
346
+    endtag = ''; 
347
+  end
348
+  cs{end+1} = starttag;
349
+  for i=1:length(list), cs{end+1} = sprintf('%s %s',listtag,list{i}); end
350
+  cs{end+1} = endtag; 
351
+  return;
352
+
353
+function csout = tablerow(cs,emp,span)
354
+  % construct one table row
355
+  global REPORT_OUTPUT_FMT
356
+  if nargin<2 | isempty(emp), emp = 'none'; end
357
+  if nargin<3 | isempty(span), span = ones(length(cs),2); end
358
+  rowspan = span(:,1); colspan = span(:,2);
359
+  switch emp,
360
+   case 'bold',   emp1 = '<B>';  emp2 = '</B>'; 
361
+   case 'italic', emp1 = '<I>';  emp2 = '</I>'; 
362
+   case 'fixed',  emp1 = '<TT>'; emp2 = '</TT>';           
363
+   case 'none',   emp1 = '';     emp2 = ''; 
364
+   case 'header', emp1 = '';     emp2 = ''; tag = 'TH';
365
+  end      
366
+  csout = cell(0); 
367
+  switch REPORT_OUTPUT_FMT, 
368
+   case {'pdf','ps'}, 
369
+    %switch emp,
370
+    % case 'bold',   emp1 = '{\bf '; emp2 = '}'; 
371
+    % case 'italic', emp1 = '{\em '; emp2 = '}'; 
372
+    % case 'fixed',  emp1 = '{\tt '; emp2 = '}';       
373
+    % case 'none',   emp1 = '';      emp2 = ''; 
374
+    %end    
375
+    s0 = ''; 
376
+    for i=1:length(cs), 
377
+      if rowspan(i) & colspan(i), 
378
+	 sp1 = ''; sp2 = '';
379
+         if colspan(i)>1, sp1 = [sp1 ' \multicolumn{' num2str(colspan(i)) '}{|c|}{']; sp2 = [sp2 '}']; end
380
+         if rowspan(i)>1, sp1 = [sp1 ' \multirow{' num2str(rowspan(i)) '}{2cm}{']; sp2 = [sp2 '}']; end
381
+	 s = s0; 
382
+	 content = cellstr(defaultformat(cs{i})); 
383
+	 csout{end+1} = [s sp1 emp1 content{1}]; 
384
+	 for j=2:length(content), csout{end+1} = content{j}; end
385
+	 csout{end} = [csout{end} emp2 sp2]; 
386
+	 s0 = ' & '; 
387
+      end
388
+    end
389
+    csout{end} = [csout{end} ' \\']; 
390
+   case 'html', 
391
+    tag = 'TD';
392
+    csout{end+1} = '<TR>';     
393
+    for i=1:length(cs),
394
+      if rowspan(i) & colspan(i), 
395
+         sp = '';
396
+         if rowspan(i)>1, sp = [sp ' ROWSPAN=' num2str(rowspan(i))]; end
397
+         if colspan(i)>1, sp = [sp ' COLSPAN=' num2str(colspan(i))]; end
398
+         s = sprintf('<%s%s>%s',tag,sp,emp1);
399
+	     content = cellstr(defaultformat(cs{i})); 
400
+	     csout{end+1} = [s content{1}]; 
401
+	     for j=2:length(content), csout{end+1} = content{j}; end
402
+	     csout{end} = [csout{end} emp2 '</' tag '>']; 
403
+      end
404
+    end
405
+    csout{end+1} = '</TR>'; 
406
+   case 'txt',
407
+    for i=1:length(cs), csout{end+1} = defaultformat(cs{i}); end
408
+  end
409
+  return;  
410
+
411
+function cs = inserttable(sTable,rowlines,long)
412
+  % put table contents to cellstr
413
+  global REPORT_OUTPUT_FMT  
414
+  if nargin<2, rowlines = 1; end
415
+  if nargin<3, long = 0; end
416
+  [rows cols] = size(sTable.values);
417
+  cs = cell(0); 
418
+  if isempty(sTable.colfmt), cf = 'c'; sTable.colfmt = cf(ones(1,cols)); end
419
+  if isempty(sTable.span), sTable.span = ones([rows cols 2]); end  
420
+  switch REPORT_OUTPUT_FMT
421
+   case {'ps','pdf','tex','latex'}
422
+    li1 = ' \hline';  
423
+    if rowlines>0, li2 = li1; li3 = li1; 
424
+    elseif rowlines==0, li2 = ''; li3 = li1; 
425
+    else li1 = ''; li2 = ''; li3 = '';  
426
+    end
427
+    if long, tbl = 'longtable'; else tbl = 'tabular'; end
428
+    cs{end+1} = ['\begin{' tbl '}{' sTable.colfmt '}' li1];
429
+    if ~isempty(sTable.headers), 
430
+      row = tablerow(sTable.headers,'bold'); 
431
+      for i=1:length(row), cs{end+1} = row{i}; end
432
+      cs{end} = [cs{end} li1 li2]; 
433
+    end
434
+    for i=1:rows, 
435
+      row = tablerow(sTable.values(i,:),'',squeeze(sTable.span(i,:,:))); 
436
+      for i=1:length(row), cs{end+1} = row{i}; end
437
+      cs{end} = [cs{end} li2]; 
438
+    end 
439
+    if ~rowlines, cs{end} = [cs{end} li3]; end
440
+    cs{end+1} = ['\end{' tbl '}'];
441
+   case 'html'
442
+    cs{end+1} = ['<TABLE BORDER=' num2str(rowlines>0) '>'];
443
+    if ~isempty(sTable.headers), 
444
+      row = tablerow(sTable.headers,'header'); 
445
+      for i=1:length(row), cs{end+1} = row{i}; end
446
+    end
447
+    for i=1:rows, 
448
+      row = tablerow(sTable.values(i,:),'',squeeze(sTable.span(i,:,:))); 
449
+      for i=1:length(row), cs{end+1} = row{i}; end
450
+    end
451
+    cs{end+1} = '</TABLE>';
452
+   case 'txt'
453
+    cT = [sTable.headers(:)'; sTable.values]; 
454
+    A = cell2char(cT); 
455
+    for i=1:size(A,1), cs{end+1} = A(i,:); end        
456
+  end  
457
+  return;
458
+
459
+function A = cell2char(T)
460
+
461
+  [nrow,ncol] = size(T); 
462
+  rowsep = 0; 
463
+  colsep = 1;
464
+
465
+  % change to strings
466
+  for i=1:nrow, 
467
+    for j=1:ncol, 
468
+      t = T{i,j};
469
+      if ischar(t),        % ok
470
+      elseif isempty(t),   T{i,j} = ''; 
471
+      elseif isstruct(t),  % ??
472
+      elseif iscell(t),    T{i,j} = cell2char(t); 
473
+      elseif isnumeric(t), T{i,j} = num2str(t,3); 
474
+      end
475
+    end
476
+  end
477
+
478
+  % widths of columns and heights of rows 
479
+  HW = ones(nrow,ncol,2);
480
+  for i=1:nrow, for j=1:ncol, HW(i,j,:) = size(T{i,j}); end, end
481
+  colw = max(HW(:,:,2),[],1); 
482
+  rowh = max(HW(:,:,1),[],2); 
483
+
484
+  % the table itself
485
+  A = char(32*ones(sum(rowh)+rowsep*(nrow-1),sum(colw)+colsep*(ncol-1)));
486
+  for i=1:nrow, 
487
+    for j=1:ncol,
488
+      i0 = (i-1)*rowsep+sum(rowh(1:i-1));
489
+      j0 = (j-1)*colsep+sum(colw(1:j-1)); 
490
+      S = char(32*ones(rowh(i),colw(j))); 
491
+      si = size(T{i,j}); S(1:si(1),1:si(2)) = T{i,j}; 
492
+      A(i0+[1:rowh(i)],j0+[1:colw(j)]) = S; 
493
+    end
494
+  end
495
+  return; 
496
+  
497
+
498
+function s = inserttominipage(s,width)
499
+  if nargin<2 | isempty(width) | isnan(width), width = 1; end
500
+  width = ['{' num2str(width) '\columnwidth}'];
501
+  mp1 = '\begin{minipage}[t]'; mp2 = '\end{minipage}';   
502
+  if size(s,1)==1, s = [mp1 width s mp2];
503
+  else s = char({[mp1 width]; s; mp2});
504
+  end
505
+  return; 
506
+  
507
+function cs = insertfigure(fname,boxsize,inminipage)
508
+  global REPORT_OUTPUT_FMT
509
+  if nargin<2, boxsize = [NaN 1]; end
510
+  if nargin<3, inminipage = 0; end
511
+  htmlpagewidth = 800;
512
+  si = cell(0); 
513
+  switch REPORT_OUTPUT_FMT,     
514
+   case {'ps','pdf'}, 
515
+    if ~isnan(boxsize(1)), si{end+1} = ['height=' num2str(boxsize(1)) '\textheight']; end
516
+    if ~isnan(boxsize(2)), si{end+1} = ['width=' num2str(boxsize(2)) '\columnwidth']; end
517
+    if length(si), si = [', ' joinstr(si, ', ', ', ')]; end
518
+   case 'html', 
519
+    if ~isnan(boxsize(1)), si{end+1} = ['HEIGHT=' num2str(htmlpagewidth*boxsize(1))]; end
520
+    if ~isnan(boxsize(2)), si{end+1} = ['WIDTH=' num2str(htmlpagewidth*boxsize(2))]; end   
521
+    if length(si), si = [' ' joinstr(si, ' ', ' ')]; end
522
+   case 'txt', 
523
+    % nil 
524
+  end    
525
+  switch REPORT_OUTPUT_FMT,     
526
+   case 'ps',   s = ['\epsfig{file=./' fname '.ps ' si '}']; 
527
+   case 'pdf',  s = ['\includegraphics[' si ']{./' fname '.pdf}'];
528
+   case 'html', 
529
+    fn = [fname '.' fmt2imgfmt]; 
530
+    s = ['<IMG SRC="' fn '" ALIGN="center" ALT="' fname '"' si '>'];
531
+    s = makelinkfrom(fn,s); 
532
+   case 'txt', 
533
+    s = ['[image:' fname ']'];
534
+  end
535
+  switch REPORT_OUTPUT_FMT, 
536
+   case {'ps','pdf'},
537
+    if inminipage, s = inserttominipage(s,boxsize(2)); end
538
+   case 'html', 
539
+    s = ['<CENTER>' s '</CENTER>']; 
540
+   case 'txt', 
541
+    % nil
542
+  end
543
+  cs = {s};
544
+  return;
545
+
546
+function str = makelinkfrom(linkto,anchor)  
547
+  global REPORT_OUTPUT_FMT
548
+  if iscell(linkto), 
549
+    if strcmp(REPORT_OUTPUT_FMT,'html'), linkto = joinstr(linkto,'','#'); 
550
+    else linkto = joinstr(linkto,'',''); 
551
+    end
552
+  end
553
+  switch REPORT_OUTPUT_FMT,  
554
+   case 'pdf',  str = ['\hyperlink{' linkto '}{' anchor '}'];
555
+   case 'ps',   str = [anchor ' (p.\pageref{' linkto '})']; 
556
+   case 'html', str = ['<a href="' linkto '">' anchor '</a>']; 
557
+   case 'txt', str = ''; 
558
+  end
559
+  return; 
560
+      
561
+function str = makelinkto(linkname)
562
+  global REPORT_OUTPUT_FMT
563
+  switch REPORT_OUTPUT_FMT,  
564
+   case 'pdf', 
565
+    fmt = '\pdfdest name {%s} fit \pdfoutline goto name {%s} {%s}'; 
566
+    str = sprintf(fmt,linkname,linkname,linkname);
567
+   case 'ps',   str = ['\label{' linkname '}']; 
568
+   case 'html', str = ['<a name="' linkname '"> </a>']; 
569
+   case 'txt', str = ''; 
570
+  end
571
+  return;
572
+
... ...
@@ -0,0 +1,249 @@
1
+function P = sammon(D, P, varargin)
2
+
3
+%SAMMON Computes Sammon's mapping of a data set.
4
+%
5
+% P = sammon(D, P, [value], [mode], [alpha], [Mdist])
6
+%
7
+%  P = sammon(D,2);            % projection to 2-dim space
8
+%  P = sammon(sMap,3);         % projects the codebook vectors
9
+%  P = sammon(sMap,3,[],[],[],Md) % uses distance matrix Md
10
+%  som_grid(sMap,'Coord',P)    % visualization of map projection
11
+%
12
+%  Input and output arguments ([]'s are optional):
13
+%   D        (matrix) size dlen x dim, data to be projected
14
+%            (struct) data or map struct            
15
+%   P        (scalar) output dimension
16
+%            (matrix) size dlen x odim, initial projection matrix
17
+%   [value]  (scalar) all different modes (the next argument) require 
18
+%                     a value, default = 100
19
+%   [mode]   (string) 'steps' or 'errlimit' or 'errchange' or 'seconds',
20
+%                     see below, default is 'steps'
21
+%   [alpha]  (scalar) iteration step size, default = 0.2
22
+%   [Dist]   (matrix) pairwise distance matrix, size dlen x dlen.
23
+%                     If the distances in the input space should
24
+%                     be calculated otherwise than as euclidian
25
+%                     distances, the distance from each vector
26
+%                     to each other vector can be given here,
27
+%                     size dlen x dlen. For example PDIST
28
+%                     function can be used to calculate the
29
+%                     distances: Dist = squareform(pdist(D,'mahal'));
30
+%
31
+%   P        (matrix) size dlen x odim, the projections
32
+%
33
+% The output dimension must be 2 or higher but (naturally) lower 
34
+% than data set dimension.
35
+%
36
+% The mode argument determines the end condition for iteration. If 
37
+% the mode argument is used, also the value argument has to be 
38
+% specified. Different mode possibilities are:
39
+% 'steps'      the iteration is terminated when it is run <value> 
40
+% 'errlimit'   steps, the iteration is terminated when projection error 
41
+%              is lower than <value>,
42
+% 'errchange'  the iteration is terminated when change between 
43
+%              projection error on two successive iteration rounds
44
+%	       is less than <value> percent of total error, and
45
+% 'seconds'    the iteration is terminated after <value> seconds 
46
+%              of iteration.
47
+%
48
+% See also CCA, PCAPROJ, SOM_GRID.
49
+
50
+% Reference: Sammon, J.W. Jr., "A nonlinear mapping for data
51
+%   structure analysis", IEEE Transactions on Computers, vol. C-18,
52
+%   no. 5, 1969, pp. 401-409.
53
+
54
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Vesanto
55
+% Copyright (c) by Juha Vesanto
56
+% http://www.cis.hut.fi/projects/somtoolbox/
57
+
58
+% juuso 040100 
59
+
60
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
61
+%% check arguments
62
+
63
+error(nargchk(2, 6, nargin));  % check no. of input arguments is correct
64
+
65
+% input data
66
+if isstruct(D),
67
+  if isfield(D, 'data'),         D = D.data; % data struct
68
+  elseif isfield(D, 'codebook'), D = D.codebook; % map struct
69
+  else error('Invalid structure');
70
+  end
71
+end
72
+if any(isnan(D(:))), 
73
+  error('Cannot make Sammon''s projection for data with unknown components')
74
+end 
75
+
76
+% compute data dimensions
77
+orig_si = size(D); 
78
+dim = orig_si(end); 
79
+noc = prod(orig_si)/dim;
80
+if length(orig_si)>2, D = reshape(D,[noc dim]); end
81
+
82
+% output dimension / initial projection matrix
83
+if prod(size(P))==1, 
84
+  odim = P; 
85
+  P = rand(noc,odim)-0.5; 
86
+else 
87
+  si = size(P);
88
+  odim = si(end);
89
+  if prod(si) ~= noc*odim, 
90
+    error('Initial projection matrix size does not match data size');
91
+  end
92
+  if length(si)>2, P = reshape(P,[noc odim]); end
93
+  inds = find(isnan(P)); 
94
+  if length(inds), P(inds) = rand(size(inds)); end
95
+end
96
+if odim > dim | odim < 2, 
97
+  error('Output dimension must be within [2, dimension of data]');
98
+end
99
+
100
+% determine operating mode
101
+if nargin < 3 | isempty(varargin{1}) | isnan(varargin{1}), value=100;
102
+else value = varargin{1}; 
103
+end
104
+  
105
+if nargin < 4 | isempty(varargin{2}) | isnan(varargin{2}), mode='steps';
106
+else mode = varargin{2}; 
107
+end  
108
+switch mode,
109
+case 'steps',     runlen = value;
110
+case 'errlimit',  errlimit = value;
111
+case 'errchange', errchange = value; e_prev = 0;
112
+case 'seconds',   endtime = value;
113
+otherwise, error(['Illegal mode: ' mode]);
114
+end
115
+
116
+% iteration step size
117
+if nargin > 4, alpha = varargin{3}; else alpha = NaN; end
118
+if isempty(alpha) | isnan(alpha), alpha = 0.2; end
119
+
120
+% mutual distances
121
+if nargin > 5, Mdist = varargin{4}; else Mdist = []; end
122
+
123
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
124
+%% initialization
125
+
126
+% these are used quite frequently
127
+noc_x_1  = ones(noc, 1); 
128
+odim_x_1 = ones(odim,1); 
129
+
130
+% compute mutual distances between vectors
131
+if isempty(Mdist) | all(isnan(Mdist(:))),  
132
+  fprintf(2, 'computing mutual distances\r');
133
+  dim_x_1 = ones(dim,1);
134
+  for i = 1:noc,
135
+    x = D(i,:); 
136
+    Diff = D - x(noc_x_1,:);
137
+    N = isnan(Diff);
138
+    Diff(find(N)) = 0; 
139
+    Mdist(:,i) = sqrt((Diff.^2)*dim_x_1);
140
+    N = find(sum(N')==dim); %mutual distance unknown
141
+    if ~isempty(N), Mdist(N,i) = NaN; end
142
+  end
143
+else
144
+  % if the distance matrix is output from PDIST function
145
+  if size(Mdist,1)==1, Mdist = squareform(Mdist); end
146
+  if size(Mdist,1)~=noc, 
147
+    error('Mutual distance matrix size and data set size do not match'); 
148
+  end
149
+end
150
+
151
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
152
+%% action
153
+
154
+if strcmp(mode, 'seconds'), tic; end;
155
+fprintf(2, 'iterating                    \r');
156
+
157
+% sammon iteration   
158
+
159
+x  = P ;
160
+xu = zeros(noc, odim);
161
+xd = zeros(noc, odim);
162
+dq = zeros(noc, 1);
163
+dr = zeros(noc, 1);
164
+
165
+i = 0;
166
+ready = 0;
167
+while ~ready
168
+  for j = 1:noc,
169
+    xd      = -x + x(j*noc_x_1,:);
170
+    xd2     = xd.^2;
171
+    dpj     = sqrt(sum(xd2'))';
172
+    dq      = Mdist(:,j) - dpj;
173
+    dr      = Mdist(:,j) .* dpj;
174
+    ind     = find(dr ~= 0);
175
+    term    = dq(ind) ./ dr(ind);
176
+    e1      = sum(xd(ind,:) .* term(:,odim_x_1));
177
+    term2   = ((1.0 + dq(ind) ./ dpj(ind)) ./ dpj(ind)) ./ dr(ind);
178
+    e2      = sum(term) - sum(xd2(ind,:) .* term2(:,odim_x_1));
179
+    xu(j,:) = x(j,:) + alpha * e1 ./ abs(e2);
180
+  end
181
+
182
+  % move the center of mass to the center 
183
+
184
+  c = sum(xu) / noc;
185
+  x = xu - c(noc_x_1, :);
186
+
187
+  i = i + 1;
188
+
189
+  % compute mapping error
190
+  % doing this adds about 25% to computing time  
191
+  if 0,
192
+    e = 0; tot = 0;
193
+    for j = 2:noc, 
194
+      d   = Mdist(1:(j - 1), j);
195
+      tot = tot + sum(d);
196
+      ind = find(d ~= 0);
197
+      xd  = -x(1:(j - 1), :) + x(j * ones(j - 1, 1), :);
198
+      ee  = d - sqrt(sum(xd'.^2))';
199
+      e   = e + sum(ee(ind).^2 ./ d(ind));
200
+    end
201
+    e = e/tot; 
202
+    fprintf(2, '\r%d iterations, error %f', i, e);
203
+  else
204
+    fprintf(2, '\r%d iterations', i);
205
+  end
206
+  
207
+  % determine is the iteration ready
208
+  
209
+  switch mode
210
+    case 'steps', 
211
+      if i == runlen, ready = 1; end;
212
+    case 'errlimit',
213
+      if e < errlimit, ready = 1; end;
214
+    case 'errchange',
215
+      if i > 1
216
+	change = 100 * abs(e - e_prev) / e_prev;
217
+	if change < errchange, ready = 1; end;
218
+	fprintf(2, ', change of error %f %%    ', change);
219
+      end
220
+      e_prev = e;
221
+    case 'seconds'
222
+      if toc > endtime, ready = 1; end;
223
+      fprintf(2, ', elapsed time %f seconds  ', toc);
224
+  end
225
+  fprintf(2, '        ');
226
+  
227
+  % If you want to see the Sammon's projection plotted (in 2-D and 3-D case),
228
+  % execute the code below; it is not in use by default to speed up 
229
+  % computation.  
230
+  if 0, 
231
+    clf
232
+    if odim == 1,     plot(x(:,1), noc_x_1, 'o');
233
+    elseif odim == 2, plot(x(:,1), x(:,2), 'o');
234
+    else              plot3(x(:,1), x(:,2), x(:,3), 'o')
235
+    end
236
+    drawnow
237
+  end
238
+end
239
+
240
+fprintf(2, '\n');
241
+
242
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
243
+%% clean up
244
+
245
+% reshape
246
+orig_si(end) = odim; 
247
+P = reshape(x, orig_si);
248
+
249
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
0 250
\ No newline at end of file
... ...
@@ -0,0 +1,237 @@
1
+function [sTo] = som_autolabel(sTo, sFrom, mode, inds)
2
+
3
+%SOM_AUTOLABEL Automatical labeling, or clearing of labels.
4
+%
5
+% sTo = som_autolabel(sTo, sFrom, [mode], [inds])
6
+%
7
+%   sM = som_autolabel(sM,sD);      
8
+%   sD = som_autolabel(sD,sM);   
9
+%   sM = som_autolabel(sM,sD,'vote',[5]);
10
+%
11
+%  Input and output arguments ([]'s are optional): 
12
+%   sTo      (struct) data or map struct to which the labels are put,
13
+%                     the modified struct is returned
14
+%   sFrom    (struct) data or map struct from which the labels are taken
15
+%   [mode]   (string) labeling algorithm: 'add' (the default), 'freq' 
16
+%                     or 'vote'
17
+%   [inds]   (vector) the column-indexes of the labels that are to be
18
+%                     used in the operation (e.g. [2] would mean to use
19
+%                     only the second column of labels array in sFrom) 
20
+% 
21
+% The modes:
22
+%  'add':   all labels from sFrom are added to sTo (even multiple
23
+%           copies of same)  
24
+%  'add1':  only one instance of each label is kept
25
+%  'freq':  only one instance of each label is kept and '(#)', where 
26
+%           # is the frequency of the label, is added to the end of 
27
+%           the label. Labels are ordered according to frequency. 
28
+%  'vote':  only the label with most instances is kept
29
+%
30
+% NOTE: The operations are only performed for the new labels. 
31
+%       The old labels in sTo are left as they are.
32
+% NOTE: all empty labels ('') are ignored.
33
+%
34
+% For more help, try 'type som_autolabel' or check out online documentation.
35
+% See also SOM_LABEL, SOM_BMUS, SOM_SHOW_ADD, SOM_SHOW.
36
+
37
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
38
+%
39
+% som_autolabel
40
+%
41
+% PURPOSE
42
+%
43
+% Automatically label to map/data structs based on given data/map.
44
+%
45
+% SYNTAX
46
+%
47
+%  sTo = som_autolabel(sTo, sFrom)
48
+%  sTo = som_autolabel(sTo, sFrom, 'add')
49
+%  sTo = som_autolabel(sTo, sFrom, 'freq')
50
+%  sTo = som_autolabel(sTo, sFrom, 'vote')
51
+%  sTo = som_autolabel(..., inds)
52
+%
53
+% DESCRIPTION
54
+%
55
+% This function automatically labels given map/data struct based on an
56
+% already labelled data/map struct. Basically, the BMU of each vector in the
57
+% sFrom struct is found from among the vectors in sTo, and the vectors in
58
+% sFrom are added to the corresponding vector in the sTo struct. The actual
59
+% labels to add are selected based on the mode ('add', 'freq' or 'vote').
60
+%
61
+%  'add'  :  all labels from sFrom are added to sTo - even if there would 
62
+%            be multiple instances of the same label
63
+%  'add1' :  only one instance of each label is kept
64
+%  'freq' :  only one instance of each label is kept and '(#)', where 
65
+%            # is the frequency of the label, is added to the end of 
66
+%            the label. Labels are ordered according to frequency. 
67
+%  'vote' :  only the label with most instances is added
68
+%
69
+% Note that these operations do not effect the old labels of sTo: they 
70
+% are left as they were.  
71
+% 
72
+% NOTE: empty labels ('') are ignored.
73
+%
74
+% REQUIRED INPUT ARGUMENTS
75
+%
76
+%   sTo    (struct) data or map struct to which the labels are put 
77
+%   sFrom  (struct) data or map struct from which the labels are taken
78
+%
79
+% OPTIONAL INPUT ARGUMENTS 
80
+%
81
+%   mode   (string) The mode of operation: 'add' (default), 
82
+%                   'add1', 'freq' or 'vote'
83
+%   inds   (vector) The columns of the '.labels' field in sFrom to be 
84
+%                   used in operation
85
+%
86
+% OUTPUT ARGUMENTS
87
+% 
88
+%   sTo    (struct) the given data/map struct with modified labels
89
+% 
90
+% EXAMPLES
91
+%
92
+% To label a trained map based on (labelled) training data, just do
93
+%
94
+%  sM = som_autolabel(sM,sD);      
95
+%
96
+% This operation is sometimes called "calibration" in the literature.
97
+% You can also do this the other way around: use a labelled map to 
98
+% label a data set: 
99
+%
100
+%  sD = som_autolabel(sD,sM);   
101
+%
102
+% If you only want a single instance of each label, use the 'freq' mode: 
103
+%
104
+%  sM = som_autolabel(sM,sD,'freq');
105
+%
106
+% If you already have labels in the struct, and want to perform 'freq' on 
107
+% them, do the following: 
108
+%
109
+%  sMtemp = som_label(sM,'clear','all'); % make a map struct with no labels
110
+%  sM = som_autolabel(sMtemp,sM,'freq'); % add labels to it
111
+%
112
+% The third mode 'vote' votes between the labels and only adds the one
113
+% which is most frequent. If two labels are equally frequent, one or the
114
+% other is chosen based on which appears first in the list.
115
+%
116
+%  sM = som_autolabel(sM,sD,'vote');
117
+%
118
+% The lat argument is useful if you have specific labels in each column
119
+% of the '.labels' field. For example, the first column might be an
120
+% identifier, the next a typecode and the last a year. In this case, you
121
+% might want to label the map based only on the typecode: 
122
+% 
123
+%  sM  = som_autolabel(sM,sD,'vote',2);
124
+%
125
+% SEE ALSO
126
+% 
127
+%  som_label     Give/remove labels from a map/data set.
128
+%  som_bmus      Find BMUs from the map for the given set of data vectors.
129
+%  som_show      Show map planes.
130
+%  som_show_add  Add for example labels to the SOM_SHOW visualization.
131
+
132
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
133
+% http://www.cis.hut.fi/projects/somtoolbox/
134
+
135
+% Version 1.0beta juuso 101297 
136
+% Version 2.0beta juuso 101199
137
+
138
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
139
+%% check arguments
140
+
141
+error(nargchk(2, 4, nargin));  % check no. of input args is correct
142
+
143
+% sTo
144
+todata = strcmp(sTo.type,'som_data');
145
+
146
+% sFrom 
147
+[dummy m] = size(sFrom.labels);
148
+
149
+% mode
150
+if nargin<3 | isempty(mode), mode = 'add'; end
151
+
152
+% inds
153
+if nargin<4, inds = 1:m; end
154
+inds = inds(find(inds>0 & inds<=m));
155
+  
156
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
157
+%% get a list of the labels to be added to each vector
158
+
159
+% calculate BMUs
160
+if todata, bmus = som_bmus(sFrom,sTo,1);
161
+else bmus = som_bmus(sTo,sFrom,1); end
162
+
163
+% for each vector in sTo, make a list of all new labels
164
+Labels = cell(size(sTo.labels,1),1);
165
+for d=1:length(bmus), 
166
+  m = bmus(d); 
167
+  if todata, t = d; f = m; else t = m; f = d; end
168
+  if ~isnan(m), 
169
+    % add the labels
170
+    for j=1:length(inds), 
171
+      if ~isempty(sFrom.labels{f,inds(j)}), 
172
+        Labels{t}{length(Labels{t})+1} = sFrom.labels{f,inds(j)}; 
173
+      end
174
+    end 
175
+  end
176
+end
177
+
178
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
179
+%% insert the labels to sTo
180
+
181
+
182
+if strcmp(mode,'add1') | strcmp(mode,'freq') | strcmp(mode,'vote'),
183
+
184
+  % modify the Labels array apprpriately
185
+  
186
+  for i=1:length(Labels),
187
+    
188
+    % calculate frequency of each label in each node
189
+    new_labels = {};
190
+    new_freq = [];
191
+    for j=1:length(Labels{i}),
192
+      if isempty(Labels{i}{j}), % ignore
193
+      elseif ~any(strcmp(Labels{i}{j},new_labels)), % a new one!
194
+	k = length(new_labels) + 1;
195
+	new_labels{k} = Labels{i}{j};
196
+	new_freq(k) = sum(strcmp(new_labels{k},Labels{i}));
197
+      else, % an old one, ignore       
198
+      end
199
+    end
200
+    
201
+    % based on frequency, select label(s) to be added 
202
+    if length(new_labels) > 0,
203
+      if strcmp(mode,'add1'), 
204
+	Labels{i} = new_labels;
205
+      else
206
+      
207
+	% sort labels according to frequency
208
+	[dummy order] = sort(1./(1+new_freq));
209
+	new_labels = new_labels(order);
210
+	new_freq = new_freq(order);
211
+	
212
+	switch mode,
213
+	 case 'freq', 
214
+	  % replace each label with 'label(#)' where # is the frequency
215
+	  for j=1:length(new_labels), 
216
+	    labf = sprintf('%s(%d)',new_labels{j},new_freq(j));
217
+	    new_labels{j} = labf;
218
+	  end
219
+	  Labels{i} = new_labels;
220
+	 case 'vote',
221
+	  % place only the one with most votes 
222
+	  Labels{i} = {new_labels{1}};
223
+	end 
224
+      end 
225
+    end
226
+    
227
+  end
228
+
229
+end
230
+
231
+sTo = som_label(sTo,'add',[1:length(Labels)]',Labels);
232
+
233
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
234
+
235
+
236
+
237
+
... ...
@@ -0,0 +1,444 @@
1
+function h = som_barplane(varargin)
2
+
3
+%SOM_BARPLANE Visualize the map prototype vectors as bar charts
4
+%
5
+% h = som_barplane(lattice, msize, data, [color], [scaling], [gap], [pos])
6
+% h = som_barplane(topol, data, [color], [scaling], [gap], [pos])
7
+%
8
+%  som_barplane('hexa',[5 5], rand(25,4), jet(4)) 
9
+%  som_barplane(sM, sM.codebook,'none')
10
+% 
11
+%  Input and output argumetns ([]'s are optional):
12
+%   lattice   (string) grid 'hexa' or 'rect'
13
+%   msize     (vector) size 1x2, defines the map grid size msize, M=prod(msize)
14
+%             (matrix) size Mx2, gives explicit coordinates for each node:
15
+%                      in this case the first argument does not matter.
16
+%   topol     (struct) map or topology struct
17
+%   data      (matrix) size Mxd, each row defines heights of the bars
18
+%   [color]   (matrix) size dx3, of RGB triples. The rows define colors 
19
+%                      for each bar in a node. Default is hsv(d). A ColorSpec or
20
+%             (string) A ColorSpec or 'none' gives each bar the same color.       
21
+%   [scaling] (string) 'none', 'unitwise' or 'varwise'. The scaling
22
+%                      mode for the values. Default is 'varwise'.
23
+%   [gap]     (scalar) Defines the gap between bars, limits: 0 <= gap <= 1 
24
+%                      where 0=no gap, 1=bars are thin lines. Default is 0.25.
25
+%   [pos]     (vector) 1x2 vector defines the position of origin.
26
+%                      Default is [1 1].
27
+%
28
+%   h         (scalar) the object handle to the PATCH object
29
+% 
30
+% Axis are set as in SOM_CPLANE.
31
+%
32
+% For more help, try 'type som_barplane' or check out online documentation.
33
+% See also SOM_CPLANE, SOM_PLOTPLANE, SOM_PIEPLANE.
34
+
35
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
36
+%
37
+% som_barplane
38
+%
39
+% PURPOSE
40
+% 
41
+% Visualizes the map prototype vectors as bar charts.
42
+%
43
+% SYNTAX
44
+%
45
+%  h = som_barplane(topol, data)
46
+%  h = som_barplane(lattice, msize, data)
47
+%  h = som_barplane(..., color)
48
+%  h = som_barplane(..., color, scaling)
49
+%  h = som_barplane(..., color, scaling, gap)
50
+%  h = som_barplane(..., color, scaling, gap, pos)
51
+%
52
+% DESCRIPTION
53
+%
54
+% Visualizes the map prototype vectors as bar charts.
55
+%
56
+% REQUIRED INPUT ARGUMENTS
57
+% 
58
+% lattice     The basic shape of the map units 
59
+%    (string) 'hexa' or 'rect' positions the bar charts according to
60
+%             hexagonal or rectangular map lattice
61
+%
62
+% msize       The size of the map grid     
63
+%    (vector) [n1 n2] vector defines the map size (height: n1 units widht: n2
64
+%             units, total: M=n1xn2 units). The units will be placed to their
65
+%             topological locations in order to form a uniform hexagonal or 
66
+%             rectangular grid.
67
+%    (matrix) Mx2 matrix defines arbitary coordinates for the N units. In 
68
+%             this case the argument 'lattice' has no effect
69
+%
70
+% topol    Topology of the map grid
71
+%
72
+%   (struct) map or topology struct from which the topology is taken
73
+%
74
+% data        The data to use when constructing the bar charts.
75
+%             Typically, the map codebook or some of its components.
76
+%    (matrix) Mxd matrix. A row defines heights of the bars.
77
+%
78
+% OPTIONAL INPUT ARGUMENTS
79
+%
80
+% Note: if unspecified or given an empty value ('' or []), default
81
+% values are used for optional input arguments.
82
+%
83
+% color       The color of the bars in each pie
84
+%    (ColorSpec) or (string) 'none' gives the same color for each slice.
85
+%    (matrix) dx3 matrix assigns an RGB color determined by the dth row of
86
+%             the matrix to the dth bar (variable) in each bar plot. 
87
+%             Default value is hsv(d).
88
+%
89
+% scaling     How to scale the values  
90
+%    (string) 'none', 'unitwise' or 'varwise'. This determines the 
91
+%             scaling of codebook values when drawing the bars.  
92
+%
93
+%             'none' don't scale at all. The bars are not limited
94
+%              to remain inside he units' area: That is, if value of
95
+%              some variable exceeds [-.625,.625] for 'rect' (and
96
+%              in "worst case" [-.5,-.5] for 'hexa') the bars may
97
+%              overlap other units. 
98
+%             
99
+%              Base line (zero value line) 
100
+%              - is in the middle of the unit if data (codebook) contains both 
101
+%                negative and positive values (or is completely zero).
102
+%              - is in the top the unit if data (codebook) contains only
103
+%                non-positive values (everything <=0).
104
+%              - is in the bottom the unit if data (codebook) contains only
105
+%                non-negative values (everything >=0).
106
+% 
107
+%             'varwise' scales values so that each variable is scaled separately 
108
+%              so that when it gets its overall maximum value, the
109
+%              corresponding bar gets maximum range and for minimum value
110
+%              it gets the minimum range. Baseline: see scaling 'none' 
111
+%              This is the default.
112
+%             
113
+%             'unitwise' scales values in each unit individually so that the 
114
+%              bars for variables having minimum and maximum values have minimum 
115
+%              and maximum range inside each unit, respectively. 
116
+%              In this case the zero value line may move depending on the values. 
117
+% 
118
+
119
+% gap         The gap between bars        
120
+%    (scalar) 0: no gap: bars are glued together 
121
+%             ... default value is 0.25       
122
+%             1: maximum gap: bars are thin lines 
123
+% 
124
+% pos         Position of origin          
125
+%    (vector) size 1x2. This is meant for drawing the plane in arbitrary 
126
+%             location in a figure. Note the operation: if this argument is
127
+%             given, the axis limits setting part in the routine is skipped and 
128
+%             the limits setting will be left to be done by MATLAB's defaults. 
129
+%             Default is [1 1].
130
+%
131
+% OUTPUT ARGUMENTS
132
+%
133
+%  h (scalar) handle to the created patch object
134
+%
135
+% OBJECT TAGS     
136
+%
137
+%  One object handle is returned: field Tag is set to 'planeBar'       
138
+%
139
+% FEATURES
140
+%
141
+%  - The colors are fixed: changing colormap in the figure (see help
142
+%    colormap) will not change the coloring of the bars.
143
+%
144
+% EXAMPLES
145
+%
146
+% %%% Create the data and make a map 
147
+%    
148
+% data=rand(100,5); map=som_make(data);
149
+% 
150
+% %%% Create a 'jet' colormap that has as many rows as the data has variables
151
+%    
152
+% colors=jet(5);
153
+% 
154
+% %%% Draw bars
155
+%    
156
+% som_barplane(map.topol.lattice, map.topol.msize, map.codebook, colors);
157
+% or som_barplane(map.topol, map.codebook, colors);
158
+% or som_barplane(map, map.codebook, colors);
159
+% 
160
+% %%% Draw the bars so that the gap between the bars is bigger and all 
161
+%     bars are black
162
+%
163
+% som_barplane(map, map.codebook, 'k', '', 0.6);
164
+% 
165
+% SEE ALSO
166
+%
167
+% som_cplane     Visualize a 2D component plane, u-matrix or color plane
168
+% som_plotplane  Visualize the map prototype vectors as line graphs
169
+% som_pieplane   Visualize the map prototype vectors as pie charts
170
+
171
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
172
+% http://www.cis.hut.fi/projects/somtoolbox/             
173
+
174
+% Version 2.0beta Juha P 110599, Johan 140799, juuso 151199 140300 070600
175
+
176
+%%% Check & Init arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
177
+
178
+[nargin, lattice, msize, data, color, scaling, gap, pos] = vis_planeGetArgs(varargin{:});
179
+error(nargchk(3, 7, nargin))   % check that no. of input args is correct
180
+
181
+% Check pos
182
+
183
+if nargin < 7 | isempty(pos)
184
+  pos=NaN;                            % default value for pos (no translation) 
185
+elseif ~vis_valuetype(pos,{'1x2'})
186
+  error('Position of origin has to be given as an 1x2 vector');
187
+end
188
+
189
+% Check gap
190
+
191
+if nargin < 6 | isempty(gap),  
192
+  gap=0.25;                           % default value for gap
193
+elseif ~vis_valuetype(gap, {'1x1'}),
194
+  error('Gap value must be scalar.');
195
+elseif ~(gap >= 0 & gap<=1) 
196
+  error('Gap value must be in interval [0,1].')
197
+end
198
+
199
+% Check scaling
200
+
201
+if nargin < 5 | isempty(scaling),
202
+  scaling='varwise';
203
+elseif ~vis_valuetype(scaling,{'string'}) | ... 
204
+      ~any(strcmp(scaling,{'none','unitwise','varwise'})),
205
+  error('scaling sholud be ''none'', ''unitwise'' or ''varwise''.');
206
+end
207
+  
208
+% Check msize
209
+
210
+if ~vis_valuetype(msize,{'1x2','nx2'}),
211
+  error('msize has to be 1x2 grid size vector or a Nx2 coordinate matrix.');
212
+end
213
+
214
+% Check data
215
+
216
+if ~isnumeric(data),
217
+  error('Data matrix has to be numeric.');
218
+elseif length(size((data)))>2
219
+  error('Data matrix has too many dimensions!');
220
+else
221
+  d=size(data,2);
222
+  N=size(data,1);
223
+end
224
+
225
+s=.8;                                 % patch size scaling factor
226
+
227
+switch scaling,
228
+case 'none'  
229
+  % no scaling: don't scale
230
+  % Check data max and min values
231
+  positive=any(data(:)>0); negative=any(data(:)<0);
232
+  if (positive & negative) | (~positive & ~negative),
233
+    % Data contains both negative and positive values (or is
234
+    % completely zero) baseline to centre
235
+    zeroline='zero';
236
+  elseif positive & ~negative
237
+    % Data contains only positive values: baseline to bottom
238
+    zeroline='bottom';
239
+  elseif ~positive & negative
240
+    % Data contains only negative values: baseline to top
241
+    zeroline='top';
242
+  end
243
+case 'unitwise'
244
+  % scale the variables so that the bar for variable with the maximum 
245
+  % value in the unit spans to the upper edge of the unit
246
+  % and the bar for the variable with minimum value spans to the lower edge,
247
+  % respectively.
248
+  zeroline='moving';
249
+ case 'varwise'
250
+  % Check data max and min values
251
+  positive=any(data(:)>0); negative=any(data(:)<0);
252
+  if (positive & negative) | (~positive & ~negative),
253
+    % Data contains both negative and positive values (or is
254
+    % completely zero) baseline to
255
+    % centre, scale data so that it doesn't overflow
256
+    data=data./repmat(max(abs([max(data); min(data)])),N,1)*.5;
257
+    zeroline='zero';
258
+  elseif positive & ~negative
259
+    % Data contains only positive values: baseline to
260
+    % bottom, scale data so that it doesn't overflow
261
+    data=data./repmat(max(abs([max(data); min(data)])),N,1)*.5;
262
+    zeroline='bottom';
263
+  elseif ~positive & negative
264
+    % Data contains only negative values: baseline to
265
+    % top, scale data so that it doesn't overflow
266
+    zeroline='top';
267
+    data=data./repmat(max(abs([max(data); min(data)])),N,1)*.5;
268
+  end
269
+otherwise
270
+  error('Unknown scaling mode?');
271
+end
272
+
273
+for i=1:N,                            % calculate patch coordinates for
274
+  v=data(i,:);
275
+  [nx,ny]=vis_barpatch(v,gap,zeroline); % bars
276
+  barx(:,(1+(i-1)*d):(i*d))=s*nx;
277
+  bary(:,(1+(i-1)*d):(i*d))=s*ny;        
278
+end
279
+l=size(barx,1);
280
+
281
+if size(msize,1) == 1,
282
+  xdim=msize(2);
283
+  ydim=msize(1);
284
+  if xdim*ydim~=N 
285
+    error('Data matrix has wrong size.');
286
+  else
287
+    y=reshape(repmat(1:ydim,d,1),1,d*ydim); y=repmat(repmat(y,l,1),1,xdim);
288
+    x=reshape(repmat(1:xdim,l*ydim*d,1),l,N*d);  
289
+  end
290
+else
291
+  x=reshape(repmat(msize(:,1),1,l*d)',l,d*N);
292
+  y=reshape(repmat(msize(:,2),1,l*d)',l,d*N);
293
+  if N ~= size(msize,1),
294
+    error('Data matrix has wrong size.');
295
+  else
296
+    lattice='rect'; 
297
+    if isnan(pos),
298
+      pos=[0 0];
299
+    end
300
+  end
301
+end
302
+
303
+% Check lattice
304
+
305
+if ~ischar(lattice)
306
+  error('Invalid lattice.');
307
+end
308
+
309
+switch lattice                      
310
+case {'hexa','rect'}
311
+  pos=pos-1;
312
+otherwise
313
+  error([ 'Lattice' lattice ' not implemented!']);
314
+end  
315
+
316
+% Check color
317
+% C_FLAG is for color 'none'
318
+
319
+if nargin < 4 | isempty(color)
320
+  color=hsv(d);                       % default n hsv colors
321
+end
322
+if ~vis_valuetype(color, {[d 3],'nx3rgb'},'all') & ...
323
+  ~vis_valuetype(color,{'colorstyle','1x3rgb'})
324
+error('The color matrix has wrong size or has invalid values.');
325
+elseif ischar(color) & strcmp(color,'none')
326
+  C_FLAG=1;
327
+  color='w';
328
+else
329
+  C_FLAG=0;
330
+end
331
+
332
+%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
333
+
334
+% Making lattice.
335
+% Command view([0 90]) shows the map in 2D properly oriented
336
+
337
+switch lattice
338
+  case 'hexa'
339
+   t=find(rem(y(1,:),2));                        % move even rows by .5
340
+   x(:,t)=x(:,t)-.5; 
341
+   x=x+barx+.5; 
342
+   y=y+bary;   
343
+  case 'rect' 
344
+   x=x+barx; 
345
+   y=y+bary;         
346
+end
347
+
348
+% NB: The coordinates in hexa are not uniform in order to get even  
349
+% y-coordinates for the nodes. This is handled by setting _axis scaling_ 
350
+% so that the hexa-nodes look like uniform hexagonals. See 
351
+% vis_PlaneAxisProperties
352
+
353
+if ~isnan(pos)
354
+  x=x+pos(1);y=y+pos(2);               % move upper left corner 
355
+end                                    % to pos
356
+
357
+%% Set axes properties  
358
+
359
+ax=newplot;                            % get current axis
360
+vis_PlaneAxisProperties(ax,lattice, msize, pos);                         
361
+
362
+%% Rearrange dx3 color matrix
363
+
364
+if ~isstr(color) & size(color,1)~=1,
365
+  color=reshape(repmat(color,N,1),[1 N*d 3]);
366
+end
367
+
368
+%% Draw the plane! 
369
+
370
+if isnumeric(color), 
371
+  % explicit color settings by RGB-triplets won't work with 
372
+  % patch in 'painters' mode, unless there only a single triplet
373
+  si = size(color); 
374
+  if length(si)~=2 | any(si==[1 3]), set(gcf,'renderer','zbuffer'); end
375
+end
376
+
377
+h_=patch(x,y,color);
378
+
379
+if C_FLAG
380
+  set(h_,'FaceColor','none');
381
+end
382
+
383
+set(h_,'Tag','planeBar');              % tag the object 
384
+
385
+%%% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
386
+
387
+if nargout>0, h=h_; end                % Set h only if 
388
+                                       % there really is output
389
+
390
+%%% Subfunctions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
391
+
392
+function [xcoord,ycoord]=vis_barpatch(y,gap,zeroline)
393
+
394
+x = length(y);
395
+d = gap/(2*(x-1)+2);
396
+step= -.5:1/x:.5;
397
+
398
+miny=min(y);
399
+maxy=max(y);
400
+
401
+switch(zeroline)
402
+ case 'moving'
403
+  if miny < 0 
404
+    if maxy > 0
405
+      zl = .5 - (abs(miny)/(maxy-miny));    %reverse mode
406
+      y= .5 - ((y-miny*ones(1,x))./(maxy-miny));
407
+    else
408
+      zl = -.5;
409
+      y=-.5+abs(y./miny);
410
+    end
411
+  else
412
+    zl = .5;    %reverse mode
413
+    y=.5-y./maxy;
414
+  end
415
+ case 'moveNotScale'
416
+  if miny < 0
417
+    if maxy > 0
418
+      zl = 0.5+miny;
419
+      y = zl - y; 
420
+    else
421
+      zl=-.5;
422
+      y=-.5+abs(y);
423
+    end
424
+  else
425
+    zl=.5;
426
+    y =.5-y;
427
+  end
428
+ case 'zero'
429
+  zl=0; y=zl-y; 
430
+ case 'top'
431
+  zl=-.5; y=zl-2*y; 
432
+ case 'bottom'
433
+  zl=.5; y=zl-2*y; 
434
+end
435
+
436
+for i=1:x
437
+  xcoord(:,i) = [d+step(i);d+step(i);step(i+1)-d;step(i+1)-d;d+step(i)];
438
+  ycoord(:,i) = [zl;y(i);y(i);zl;zl];
439
+end
440
+
441
+
442
+
443
+
444
+
... ...
@@ -0,0 +1,539 @@
1
+function [sMap,sTrain] = som_batchtrain(sMap, D, varargin)
2
+
3
+%SOM_BATCHTRAIN  Use batch algorithm to train the Self-Organizing Map.
4
+%
5
+% [sM,sT] = som_batchtrain(sM, D, [argID, value, ...])
6
+% 
7
+%  sM     = som_batchtrain(sM,D);
8
+%  sM     = som_batchtrain(sM,sD,'radius',[10 3 2 1 0.1],'tracking',3);
9
+%  [M,sT] = som_batchtrain(M,D,'ep','msize',[10 3],'hexa');
10
+%
11
+%  Input and output arguments ([]'s are optional): 
12
+%   sM      (struct) map struct, the trained and updated map is returned
13
+%           (matrix) codebook matrix of a self-organizing map
14
+%                    size munits x dim or  msize(1) x ... x msize(k) x dim
15
+%                    The trained map codebook is returned.
16
+%   D       (struct) training data; data struct
17
+%           (matrix) training data, size dlen x dim
18
+%   [argID, (string) See below. The values which are unambiguous can 
19
+%    value] (varies) be given without the preceeding argID.
20
+%
21
+%   sT      (struct) learning parameters used during the training
22
+%
23
+% Here are the valid argument IDs and corresponding values. The values which
24
+% are unambiguous (marked with '*') can be given without the preceeding argID.
25
+%   'mask'       (vector) BMU search mask, size dim x 1
26
+%   'msize'      (vector) map size
27
+%   'radius'     (vector) neighborhood radiuses, length 1, 2 or trainlen
28
+%   'radius_ini' (scalar) initial training radius
29
+%   'radius_fin' (scalar) final training radius
30
+%   'tracking'   (scalar) tracking level, 0-3 
31
+%   'trainlen'   (scalar) training length in epochs
32
+%   'train'     *(struct) train struct, parameters for training
33
+%   'sTrain','som_train'  = 'train'
34
+%   'neigh'     *(string) neighborhood function, 'gaussian', 'cutgauss',
35
+%                         'ep' or 'bubble'
36
+%   'topol'     *(struct) topology struct
37
+%   'som_topol','sTopol'  = 'topol'
38
+%   'lattice'   *(string) map lattice, 'hexa' or 'rect'
39
+%   'shape'     *(string) map shape, 'sheet', 'cyl' or 'toroid'
40
+%   'weights'    (vector) sample weights: each sample is weighted 
41
+%
42
+% For more help, try 'type som_batchtrain' or check out online documentation.
43
+% See also  SOM_MAKE, SOM_SEQTRAIN, SOM_TRAIN_STRUCT.
44
+
45
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
46
+%
47
+% som_batchtrain
48
+%
49
+% PURPOSE
50
+%
51
+% Trains a Self-Organizing Map using the batch algorithm. 
52
+%
53
+% SYNTAX
54
+%
55
+%  sM = som_batchtrain(sM,D);
56
+%  sM = som_batchtrain(sM,sD);
57
+%  sM = som_batchtrain(...,'argID',value,...);
58
+%  sM = som_batchtrain(...,value,...);
59
+%  [sM,sT] = som_batchtrain(M,D,...);
60
+%
61
+% DESCRIPTION
62
+%
63
+% Trains the given SOM (sM or M above) with the given training data
64
+% (sD or D) using batch training algorithm.  If no optional arguments
65
+% (argID, value) are given, a default training is done. Using optional
66
+% arguments the training parameters can be specified. Returns the
67
+% trained and updated SOM and a train struct which contains
68
+% information on the training.
69
+%
70
+% REFERENCES
71
+%
72
+% Kohonen, T., "Self-Organizing Map", 2nd ed., Springer-Verlag, 
73
+%    Berlin, 1995, pp. 127-128.
74
+% Kohonen, T., "Things you haven't heard about the Self-Organizing
75
+%    Map", In proceedings of International Conference
76
+%    on Neural Networks (ICNN), San Francisco, 1993, pp. 1147-1156.
77
+%
78
+% KNOWN BUGS
79
+%
80
+% Batchtrain does not work correctly for a map with a single unit. 
81
+% This is because of the way 'min'-function works. 
82
+%
83
+% REQUIRED INPUT ARGUMENTS
84
+%
85
+%  sM          The map to be trained. 
86
+%     (struct) map struct
87
+%     (matrix) codebook matrix (field .data of map struct)
88
+%              Size is either [munits dim], in which case the map grid 
89
+%              dimensions (msize) should be specified with optional arguments,
90
+%              or [msize(1) ... msize(k) dim] in which case the map 
91
+%              grid dimensions are taken from the size of the matrix. 
92
+%              Lattice, by default, is 'rect' and shape 'sheet'.
93
+%  D           Training data.
94
+%     (struct) data struct
95
+%     (matrix) data matrix, size [dlen dim]
96
+%  
97
+% OPTIONAL INPUT ARGUMENTS 
98
+%
99
+%  argID (string) Argument identifier string (see below).
100
+%  value (varies) Value for the argument (see below).
101
+%
102
+%  The optional arguments can be given as 'argID',value -pairs. If an
103
+%  argument is given value multiple times, the last one is
104
+%  used. The valid IDs and corresponding values are listed below. The values 
105
+%  which are unambiguous (marked with '*') can be given without the 
106
+%  preceeding argID.
107
+%
108
+%  Below is the list of valid arguments: 
109
+%   'mask'       (vector) BMU search mask, size dim x 1. Default is 
110
+%                         the one in sM (field '.mask') or a vector of
111
+%                         ones if only a codebook matrix was given.
112
+%   'msize'      (vector) map grid dimensions. Default is the one
113
+%                         in sM (field sM.topol.msize) or 
114
+%                         'si = size(sM); msize = si(1:end-1);' 
115
+%                         if only a codebook matrix was given. 
116
+%   'radius'     (vector) neighborhood radius 
117
+%                         length = 1: radius_ini = radius
118
+%                         length = 2: [radius_ini radius_fin] = radius
119
+%                         length > 2: the vector given neighborhood
120
+%                                     radius for each step separately
121
+%                                     trainlen = length(radius)
122
+%   'radius_ini' (scalar) initial training radius
123
+%   'radius_fin' (scalar) final training radius
124
+%   'tracking'   (scalar) tracking level: 0, 1 (default), 2 or 3
125
+%                         0 - estimate time 
126
+%                         1 - track time and quantization error 
127
+%                         2 - plot quantization error
128
+%                         3 - plot quantization error and two first 
129
+%                             components 
130
+%   'trainlen'   (scalar) training length in epochs
131
+%   'train'     *(struct) train struct, parameters for training. 
132
+%                         Default parameters, unless specified, 
133
+%                         are acquired using SOM_TRAIN_STRUCT (this 
134
+%                         also applies for 'trainlen', 'radius_ini' 
135
+%                         and 'radius_fin').
136
+%   'sTrain', 'som_topol' (struct) = 'train'
137
+%   'neigh'     *(string) The used neighborhood function. Default is 
138
+%                         the one in sM (field '.neigh') or 'gaussian'
139
+%                         if only a codebook matrix was given. Other 
140
+%                         possible values is 'cutgauss', 'ep' and 'bubble'.
141
+%   'topol'     *(struct) topology of the map. Default is the one
142
+%                         in sM (field '.topol').
143
+%   'sTopol', 'som_topol' (struct) = 'topol'
144
+%   'lattice'   *(string) map lattice. Default is the one in sM
145
+%                         (field sM.topol.lattice) or 'rect' 
146
+%                         if only a codebook matrix was given. 
147
+%   'shape'     *(string) map shape. Default is the one in sM
148
+%                         (field sM.topol.shape) or 'sheet' 
149
+%                         if only a codebook matrix was given. 
150
+%   'weights'    (vector) weight for each data vector: during training, 
151
+%                         each data sample is weighted with the corresponding
152
+%                         value, for example giving weights = [1 1 2 1] 
153
+%                         would have the same result as having third sample
154
+%                         appear 2 times in the data
155
+%
156
+% OUTPUT ARGUMENTS
157
+% 
158
+%  sM          the trained map
159
+%     (struct) if a map struct was given as input argument, a 
160
+%              map struct is also returned. The current training 
161
+%              is added to the training history (sM.trainhist).
162
+%              The 'neigh' and 'mask' fields of the map struct
163
+%              are updated to match those of the training.
164
+%     (matrix) if a matrix was given as input argument, a matrix
165
+%              is also returned with the same size as the input 
166
+%              argument.
167
+%  sT (struct) train struct; information of the accomplished training
168
+%
169
+% EXAMPLES
170
+%
171
+% Simplest case:
172
+%  sM = som_batchtrain(sM,D);  
173
+%  sM = som_batchtrain(sM,sD);  
174
+%
175
+% To change the tracking level, 'tracking' argument is specified:
176
+%  sM = som_batchtrain(sM,D,'tracking',3);
177
+%
178
+% The change training parameters, the optional arguments 'train','neigh',
179
+% 'mask','trainlen','radius','radius_ini' and 'radius_fin' are used. 
180
+%  sM = som_batchtrain(sM,D,'neigh','cutgauss','trainlen',10,'radius_fin',0);
181
+%
182
+% Another way to specify training parameters is to create a train struct:
183
+%  sTrain = som_train_struct(sM,'dlen',size(D,1));
184
+%  sTrain = som_set(sTrain,'neigh','cutgauss');
185
+%  sM = som_batchtrain(sM,D,sTrain);
186
+%
187
+% By default the neighborhood radius goes linearly from radius_ini to
188
+% radius_fin. If you want to change this, you can use the 'radius' argument
189
+% to specify the neighborhood radius for each step separately:
190
+%  sM = som_batchtrain(sM,D,'radius',[5 3 1 1 1 1 0.5 0.5 0.5]);
191
+%
192
+% You don't necessarily have to use the map struct, but you can operate
193
+% directly with codebook matrices. However, in this case you have to
194
+% specify the topology of the map in the optional arguments. The
195
+% following commads are identical (M is originally a 200 x dim sized matrix):
196
+%  M = som_batchtrain(M,D,'msize',[20 10],'lattice','hexa','shape','cyl');
197
+%   or
198
+%  M = som_batchtrain(M,D,'msize',[20 10],'hexa','cyl');
199
+%   or
200
+%  sT= som_set('som_topol','msize',[20 10],'lattice','hexa','shape','cyl');
201
+%  M = som_batchtrain(M,D,sT);
202
+%   or
203
+%  M = reshape(M,[20 10 dim]);
204
+%  M = som_batchtrain(M,D,'hexa','cyl');
205
+%
206
+% The som_batchtrain also returns a train struct with information on the 
207
+% accomplished training. This struct is also added to the end of the 
208
+% trainhist field of map struct, in case a map struct was given.
209
+%  [M,sTrain] = som_batchtrain(M,D,'msize',[20 10]);
210
+%  [sM,sTrain] = som_batchtrain(sM,D); % sM.trainhist{end}==sTrain
211
+%
212
+% SEE ALSO
213
+% 
214
+%  som_make         Initialize and train a SOM using default parameters.
215
+%  som_seqtrain     Train SOM with sequential algorithm.
216
+%  som_train_struct Determine default training parameters.
217
+
218
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
219
+% http://www.cis.hut.fi/projects/somtoolbox/
220
+
221
+% Version 1.0beta juuso 071197 041297
222
+% Version 2.0beta juuso 101199
223
+
224
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
225
+%% Check arguments 
226
+
227
+error(nargchk(2, Inf, nargin));  % check the number of input arguments
228
+
229
+% map 
230
+struct_mode = isstruct(sMap);
231
+if struct_mode, 
232
+  sTopol = sMap.topol;
233
+else  
234
+  orig_size = size(sMap);
235
+  if ndims(sMap) > 2, 
236
+    si = size(sMap); dim = si(end); msize = si(1:end-1);
237
+    M = reshape(sMap,[prod(msize) dim]);
238
+  else
239
+    msize = [orig_size(1) 1]; 
240
+    dim = orig_size(2);    
241
+  end
242
+  sMap   = som_map_struct(dim,'msize',msize);
243
+  sTopol = sMap.topol;
244
+end
245
+[munits dim] = size(sMap.codebook);
246
+
247
+% data
248
+if isstruct(D), 
249
+  data_name = D.name; 
250
+  D = D.data;
251
+else 
252
+  data_name = inputname(2); 
253
+end
254
+nonempty = find(sum(isnan(D),2) < dim);
255
+D = D(nonempty,:);                    % remove empty vectors from the data
256
+[dlen ddim] = size(D);                % check input dimension
257
+if dim ~= ddim, 
258
+  error('Map and data input space dimensions disagree.'); 
259
+end
260
+
261
+% varargin
262
+sTrain = som_set('som_train','algorithm','batch','neigh', ...
263
+		 sMap.neigh,'mask',sMap.mask,'data_name',data_name);
264
+radius     = [];
265
+tracking   = 1;
266
+weights    = 1; 
267
+
268
+i=1; 
269
+while i<=length(varargin), 
270
+  argok = 1; 
271
+  if ischar(varargin{i}), 
272
+    switch varargin{i}, 
273
+     % argument IDs
274
+     case 'msize', i=i+1; sTopol.msize = varargin{i}; 
275
+     case 'lattice', i=i+1; sTopol.lattice = varargin{i};
276
+     case 'shape', i=i+1; sTopol.shape = varargin{i};
277
+     case 'mask', i=i+1; sTrain.mask = varargin{i};
278
+     case 'neigh', i=i+1; sTrain.neigh = varargin{i};
279
+     case 'trainlen', i=i+1; sTrain.trainlen = varargin{i};
280
+     case 'tracking', i=i+1; tracking = varargin{i};
281
+     case 'weights', i=i+1; weights = varargin{i}; 
282
+     case 'radius_ini', i=i+1; sTrain.radius_ini = varargin{i};
283
+     case 'radius_fin', i=i+1; sTrain.radius_fin = varargin{i};
284
+     case 'radius', 
285
+      i=i+1; 
286
+      l = length(varargin{i}); 
287
+      if l==1, 
288
+        sTrain.radius_ini = varargin{i}; 
289
+      else 
290
+        sTrain.radius_ini = varargin{i}(1); 
291
+        sTrain.radius_fin = varargin{i}(end);
292
+        if l>2, radius = varargin{i}; end
293
+      end 
294
+     case {'sTrain','train','som_train'}, i=i+1; sTrain = varargin{i};
295
+     case {'topol','sTopol','som_topol'}, 
296
+      i=i+1; 
297
+      sTopol = varargin{i};
298
+      if prod(sTopol.msize) ~= munits, 
299
+        error('Given map grid size does not match the codebook size.');
300
+      end
301
+      % unambiguous values
302
+     case {'hexa','rect'}, sTopol.lattice = varargin{i};
303
+     case {'sheet','cyl','toroid'}, sTopol.shape = varargin{i}; 
304
+     case {'gaussian','cutgauss','ep','bubble'}, sTrain.neigh = varargin{i};
305
+     otherwise argok=0; 
306
+    end
307
+  elseif isstruct(varargin{i}) & isfield(varargin{i},'type'), 
308
+    switch varargin{i}(1).type, 
309
+     case 'som_topol', 
310
+      sTopol = varargin{i}; 
311
+      if prod(sTopol.msize) ~= munits, 
312
+        error('Given map grid size does not match the codebook size.');
313
+      end
314
+     case 'som_train', sTrain = varargin{i};
315
+     otherwise argok=0; 
316
+    end
317
+  else
318
+    argok = 0; 
319
+  end
320
+  if ~argok, 
321
+    disp(['(som_batchtrain) Ignoring invalid argument #' num2str(i+2)]); 
322
+  end
323
+  i = i+1; 
324
+end
325
+
326
+% take only weights of non-empty vectors
327
+if length(weights)>dlen, weights = weights(nonempty); end
328
+
329
+% trainlen
330
+if ~isempty(radius), sTrain.trainlen = length(radius); end
331
+
332
+% check topology
333
+if struct_mode, 
334
+  if ~strcmp(sTopol.lattice,sMap.topol.lattice) | ...
335
+	~strcmp(sTopol.shape,sMap.topol.shape) | ...
336
+	any(sTopol.msize ~= sMap.topol.msize), 
337
+    warning('Changing the original map topology.');
338
+  end
339
+end
340
+sMap.topol = sTopol; 
341
+
342
+% complement the training struct
343
+sTrain = som_train_struct(sTrain,sMap,'dlen',dlen);
344
+if isempty(sTrain.mask), sTrain.mask = ones(dim,1); end
345
+
346
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
347
+%% initialize
348
+
349
+M        = sMap.codebook;
350
+mask     = sTrain.mask;
351
+trainlen = sTrain.trainlen;
352
+
353
+% neighborhood radius
354
+if trainlen==1, 
355
+  radius = sTrain.radius_ini; 
356
+elseif length(radius)<=2,  
357
+  r0 = sTrain.radius_ini; r1 = sTrain.radius_fin;
358
+  radius = r1 + fliplr((0:(trainlen-1))/(trainlen-1)) * (r0 - r1);
359
+else
360
+  % nil
361
+end
362
+                                   
363
+% distance between map units in the output space
364
+%  Since in the case of gaussian and ep neighborhood functions, the 
365
+%  equations utilize squares of the unit distances and in bubble case
366
+%  it doesn't matter which is used, the unitdistances and neighborhood
367
+%  radiuses are squared.
368
+Ud = som_unit_dists(sTopol);
369
+Ud = Ud.^2;
370
+radius = radius.^2;
371
+% zero neighborhood radius may cause div-by-zero error
372
+radius(find(radius==0)) = eps; 
373
+
374
+% The training algorithm involves calculating weighted Euclidian distances 
375
+% to all map units for each data vector. Basically this is done as
376
+%   for i=1:dlen, 
377
+%     for j=1:munits, 
378
+%       for k=1:dim
379
+%         Dist(j,i) = Dist(j,i) + mask(k) * (D(i,k) - M(j,k))^2;
380
+%       end
381
+%     end
382
+%   end
383
+% where mask is the weighting vector for distance calculation. However, taking 
384
+% into account that distance between vectors m and v can be expressed as
385
+%   |m - v|^2 = sum_i ((m_i - v_i)^2) = sum_i (m_i^2 + v_i^2 - 2*m_i*v_i)
386
+% this can be made much faster by transforming it to a matrix operation:
387
+%   Dist = (M.^2)*mask*ones(1,d) + ones(m,1)*mask'*(D'.^2) - 2*M*diag(mask)*D'
388
+% Of the involved matrices, several are constant, as the mask and data do 
389
+% not change during training. Therefore they are calculated beforehand.
390
+
391
+% For the case where there are unknown components in the data, each data
392
+% vector will have an individual mask vector so that for that unit, the 
393
+% unknown components are not taken into account in distance calculation.
394
+% In addition all NaN's are changed to zeros so that they don't screw up 
395
+% the matrix multiplications and behave correctly in updating step.
396
+Known = ~isnan(D);
397
+W1 = (mask*ones(1,dlen)) .* Known'; 
398
+D(find(~Known)) = 0;  
399
+
400
+% constant matrices
401
+WD = 2*diag(mask)*D';    % constant matrix
402
+dconst = ((D.^2)*mask)'; % constant in distance calculation for each data sample 
403
+                         % W2 = ones(munits,1)*mask'; D2 = (D'.^2); 		      
404
+
405
+% initialize tracking
406
+start = clock;
407
+qe = zeros(trainlen,1); 
408
+  
409
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
410
+%% Action
411
+
412
+% With the 'blen' parameter you can control the memory consumption 
413
+% of the algorithm, which is in practive directly proportional
414
+% to munits*blen. If you're having problems with memory, try to 
415
+% set the value of blen lower. 
416
+blen = min(munits,dlen);
417
+
418
+% reserve some space
419
+bmus = zeros(1,dlen); 
420
+ddists = zeros(1,dlen); 
421
+
422
+for t = 1:trainlen,  
423
+
424
+  % batchy train - this is done a block of data (inds) at a time
425
+  % rather than in a single sweep to save memory consumption. 
426
+  % The 'Dist' and 'Hw' matrices have size munits*blen
427
+  % which - if you have a lot of data - would be HUGE if you 
428
+  % calculated it all at once. A single-sweep version would 
429
+  % look like this: 
430
+  %  Dist = (M.^2)*W1 - M*WD; %+ W2*D2 
431
+  %  [ddists, bmus] = min(Dist);
432
+  % (notice that the W2*D2 term can be ignored since it is constant)
433
+  % This "batchy" version is the same as single-sweep if blen=dlen. 
434
+  i0 = 0;     
435
+  while i0+1<=dlen, 
436
+    inds = [(i0+1):min(dlen,i0+blen)]; i0 = i0+blen;      
437
+    Dist = (M.^2)*W1(:,inds) - M*WD(:,inds);
438
+    [ddists(inds), bmus(inds)] = min(Dist);
439
+  end  
440
+  
441
+  % tracking
442
+  if tracking > 0,
443
+    ddists = ddists+dconst; % add the constant term
444
+    ddists(ddists<0) = 0;   % rounding errors...
445
+    qe(t) = mean(sqrt(ddists));
446
+    trackplot(M,D,tracking,start,t,qe);
447
+  end
448
+  
449
+  % neighborhood 
450
+  % notice that the elements Ud and radius have been squared!
451
+  % note: 'bubble' matches the original "Batch Map" algorithm
452
+  switch sTrain.neigh, 
453
+   case 'bubble',   H = (Ud<=radius(t)); 
454
+   case 'gaussian', H = exp(-Ud/(2*radius(t))); 
455
+   case 'cutgauss', H = exp(-Ud/(2*radius(t))) .* (Ud<=radius(t));
456
+   case 'ep',       H = (1-Ud/radius(t)) .* (Ud<=radius(t));
457
+  end  
458
+  
459
+  % update 
460
+
461
+  % In principle the updating step goes like this: replace each map unit 
462
+  % by the average of the data vectors that were in its neighborhood.
463
+  % The contribution, or activation, of data vectors in the mean can 
464
+  % be varied with the neighborhood function. This activation is given 
465
+  % by matrix H. So, for each map unit the new weight vector is
466
+  %
467
+  %      m = sum_i (h_i * d_i) / sum_i (h_i), 
468
+  % 
469
+  % where i denotes the index of data vector.  Since the values of
470
+  % neighborhood function h_i are the same for all data vectors belonging to
471
+  % the Voronoi set of the same map unit, the calculation is actually done
472
+  % by first calculating a partition matrix P with elements p_ij=1 if the
473
+  % BMU of data vector j is i.
474
+
475
+  P = sparse(bmus,[1:dlen],weights,munits,dlen);
476
+       
477
+  % Then the sum of vectors in each Voronoi set are calculated (P*D) and the
478
+  % neighborhood is taken into account by calculating a weighted sum of the
479
+  % Voronoi sum (H*). The "activation" matrix A is the denominator of the 
480
+  % equation above.
481
+  
482
+  S = H*(P*D); 
483
+  A = H*(P*Known);
484
+  
485
+  % If you'd rather make this without using the Voronoi sets try the following: 
486
+  %   Hi = H(:,bmus); 
487
+  %   S = Hi * D;            % "sum_i (h_i * d_i)"
488
+  %   A = Hi * Known;        % "sum_i (h_i)"
489
+  % The bad news is that the matrix Hi has size [munits x dlen]... 
490
+    
491
+  % only update units for which the "activation" is nonzero
492
+  nonzero = find(A > 0); 
493
+  M(nonzero) = S(nonzero) ./ A(nonzero); 
494
+
495
+end; % for t = 1:trainlen
496
+
497
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
498
+%% Build / clean up the return arguments
499
+
500
+% tracking
501
+if tracking > 0, fprintf(1,'\n'); end
502
+
503
+% update structures
504
+sTrain = som_set(sTrain,'time',datestr(now,0));
505
+if struct_mode, 
506
+  sMap = som_set(sMap,'codebook',M,'mask',sTrain.mask,'neigh',sTrain.neigh);
507
+  tl = length(sMap.trainhist);
508
+  sMap.trainhist(tl+1) = sTrain;
509
+else
510
+  sMap = reshape(M,orig_size);
511
+end
512
+
513
+return;
514
+
515
+
516
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
517
+%% subfunctions
518
+
519
+%%%%%%%%
520
+function [] = trackplot(M,D,tracking,start,n,qe)
521
+
522
+  l = length(qe);
523
+  elap_t = etime(clock,start); 
524
+  tot_t = elap_t*l/n;
525
+  fprintf(1,'\rTraining: %3.0f/ %3.0f s',elap_t,tot_t)  
526
+  switch tracking
527
+   case 1, 
528
+   case 2,   
529
+    plot(1:n,qe(1:n),(n+1):l,qe((n+1):l))
530
+    title('Quantization error after each epoch');
531
+    drawnow
532
+   otherwise,
533
+    subplot(2,1,1), plot(1:n,qe(1:n),(n+1):l,qe((n+1):l))
534
+    title('Quantization error after each epoch');
535
+    subplot(2,1,2), plot(M(:,1),M(:,2),'ro',D(:,1),D(:,2),'b+'); 
536
+    title('First two components of map units (o) and data vectors (+)');
537
+    drawnow
538
+  end
539
+  % end of trackplot
... ...
@@ -0,0 +1,93 @@
1
+function bmu_colors=som_bmucolor(bmus, m, colors);
2
+
3
+% SOM_BMUCOLOR Returns the colors of the bmus according to a map colorcode
4
+%
5
+% bmu_colors=som_bmucolor(bmus, msize, colors);
6
+%
7
+% INPUT ARGUMENTS ([]'s are optional)
8
+%
9
+% bmus   (matrix) Nx1 vector of BMU indexes
10
+% msize  (map struct, topol struct or 1x2 vector) 
11
+%          gives the map grid size 
12
+% colors (matrix) colormap(s): munits x 3 x d matrix of RGB vectors
13
+%
14
+% OUTPUT ARGUMENTS 
15
+%
16
+% bmu_colors (Nx3xd matrix) color of the data point according to its BMU's 
17
+%              color(s).
18
+%
19
+% Idea is to get a color for each data point that links it to its BMU. 
20
+%
21
+% EXAMPLE
22
+%
23
+% We want to show how an time series is projected  to a map. Instead of 
24
+% a trajectory, we use 'color linking'
25
+%
26
+% map=som_make(multi_dim_signal); 
27
+% bmus=som_bmu(map,multi_dim_signal);
28
+% Colors=som_bmucolor(bmus, map, som_colorcode(map,'rgb1'));
29
+% colorsignal(Colors, multi_dim_signal);
30
+%
31
+% See also SOM_COLORCODE.
32
+
33
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
34
+% http://www.cis.hut.fi/projects/somtoolbox/             
35
+
36
+% Version 2.0alpha Johan 170699
37
+
38
+%% Check arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
39
+
40
+error(nargchk(3, 3, nargin))   % check no. of input args is correct
41
+
42
+% Check map grid size
43
+
44
+if vis_valuetype(m,{'1x2'}),
45
+  msize=m;  
46
+else
47
+  [tmp,ok,tmp]=som_set(m);
48
+  if isstruct(m) & all(ok)        % check m type
49
+    switch m.type
50
+    case 'som_topol'
51
+      msize=m.msize;
52
+      lattice=m.lattice;
53
+    case 'som_map'
54
+      msize=m.topol.msize;
55
+      lattice=m.topol.lattice;
56
+    otherwise
57
+      error('Invalid map or topol struct.');
58
+    end
59
+  end
60
+end  
61
+
62
+if length(msize)>2
63
+  error('Only 2D maps allowed!');
64
+end
65
+
66
+n=prod(msize)
67
+
68
+% Check colorcode size
69
+
70
+if ~vis_valuetype(colors,{'nx3xdimrgb','nx3rgb'})
71
+  error('Colorcode matrix not valid!');
72
+end
73
+
74
+% Check bmu vector
75
+
76
+if ~vis_valuetype(bmus,{'nx1'}),
77
+  error('Need a column vector of BMU indexes!');
78
+else
79
+  bmus=round(bmus);
80
+  if max(bmus) > n | min(bmus) < 1
81
+    error('BMU indexes exeed the map size!')
82
+  end
83
+end
84
+
85
+%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
86
+
87
+bmu_c=colors(bmus,:,:);
88
+
89
+%% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
90
+
91
+
92
+bmu_colors=squeeze(bmu_c);
93
+
... ...
@@ -0,0 +1,253 @@
1
+function [Bmus,Qerrors] = som_bmus(sMap, sData, which_bmus, mask)
2
+
3
+%SOM_BMUS Find the best-matching units from the map for the given vectors.
4
+%
5
+% [Bmus, Qerrors] = som_bmus(sMap, sData, [which], [mask])
6
+% 
7
+%   bmus = som_bmus(sM,sD);
8
+%   [bmus,qerrs] = som_bmus(sM,D,[1 2 3]);
9
+%   bmus = som_bmus(sM,D,1,[1 1 0 0 1]);
10
+%
11
+%  Input and output arguments ([]'s are optional): 
12
+%   sMap     (struct) map struct
13
+%            (matrix) codebook matrix, size munits x dim
14
+%   sData    (struct) data struct
15
+%            (matrix) data matrix, size dlen x dim
16
+%   [which]  (vector) which BMUs are returned, [1] by default 
17
+%            (string) 'all', 'best' or 'worst' meaning [1:munits],
18
+%                     [1] and [munits] respectively  
19
+%   [mask]   (vector) mask vector, length=dim, sMap.mask by default
20
+%
21
+%   Bmus     (matrix) the requested BMUs for each data vector, 
22
+%                     size dlen x length(which)
23
+%   Qerrors  (matrix) the corresponding quantization errors, size as Bmus
24
+%
25
+% NOTE: for a vector with all components NaN's, bmu=NaN and qerror=NaN
26
+% NOTE: the mask also effects the quantization errors
27
+%
28
+% For more help, try 'type som_bmus' or check out online documentation.
29
+% See also  SOM_QUALITY.
30
+
31
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
32
+%
33
+% som_bmus
34
+%
35
+% PURPOSE
36
+%
37
+% Finds Best-Matching Units (BMUs) for given data vector from a given map.
38
+%
39
+% SYNTAX
40
+%
41
+%  Bmus = som_bmus(sMap, sData)
42
+%  Bmus = som_bmus(..., which)
43
+%  Bmus = som_bmus(..., which, mask)
44
+%  [Bmus, Qerrs] = som_bmus(...)
45
+%
46
+% DESCRIPTION
47
+%
48
+% Returns the indexes and corresponding quantization errors of the
49
+% vectors in sMap that best matched the vectors in sData.
50
+%
51
+% By default only the index of the best matching unit (/vector) is
52
+% returned, but the 'which' argument can be used to get others as
53
+% well. For example it might be desirable to get also second- and
54
+% third-best matching units as well (which = [1:3]). 
55
+%
56
+% A mask can be used to weight the search process. The mask is used to
57
+% weight the influence of components in the distance calculation, as
58
+% follows: 
59
+%
60
+%   distance(x,y) = (x-y)' diag(mask) (x-y)
61
+%
62
+% where x and y are two vectors, and diag(mask) is a diagonal matrix with 
63
+% the elements of mask vector on the diagonal. 
64
+%
65
+% The vectors in the data set (sData) can contain unknown components
66
+% (NaNs), but the map (sMap) cannot. If there are completely empty
67
+% vectors (all NaNs), the returned BMUs and quantization errors for those 
68
+% vectors are NaNs.
69
+%
70
+% REQUIRED INPUT ARGUMENTS
71
+%
72
+%   sMap              The vectors from among which the BMUs are searched
73
+%                     for. These must not have any unknown components (NaNs).
74
+%            (struct) map struct
75
+%            (matrix) codebook matrix, size munits x dim
76
+%                     
77
+%   sData             The data vector(s) for which the BMUs are searched.
78
+%            (struct) data struct
79
+%            (matrix) data matrix, size dlen x dim
80
+%
81
+% OPTIONAL INPUT ARGUMENTS 
82
+%
83
+%   which    (vector) which BMUs are returned, 
84
+%                     by default only the best (ie. which = [1])
85
+%            (string) 'all', 'best' or 'worst' meaning [1:munits],
86
+%                     [1] and [munits] respectively  
87
+%   mask     (vector) mask vector to be used in BMU search, 
88
+%                     by default sMap.mask, or ones(dim,1) in case
89
+%                     a matrix was given
90
+%
91
+% OUTPUT ARGUMENTS
92
+% 
93
+%   Bmus     (matrix) the requested BMUs for each data vector, 
94
+%                     size dlen x length(which)
95
+%   Qerrors  (matrix) the corresponding quantization errors, 
96
+%                     size equal to that of Bmus
97
+%
98
+% EXAMPLES
99
+%
100
+% Simplest case:
101
+%  bmu = som_bmus(sM, [0.3 -0.4 1.0]);
102
+%           % 3-dimensional data, returns BMU for vector [0.3 -0.4 1]
103
+%  bmu = som_bmus(sM, [0.3 -0.4 1.0], [3 5]);
104
+%           % as above, except returns the 3rd and 5th BMUs
105
+%  bmu = som_bmus(sM, [0.3 -0.4 1.0], [], [1 0 1]);
106
+%           % as above, except ignores second component in searching
107
+%  [bmus qerrs] = som_bmus(sM, D);
108
+%           % returns BMUs and corresponding quantization errors 
109
+%           % for each vector in D
110
+%  bmus = som_bmus(sM, sD);
111
+%           % returns BMUs for each vector in sD using the mask in sM
112
+%
113
+% SEE ALSO
114
+% 
115
+%  som_quality      Measure the quantization and topographic error of a SOM.
116
+
117
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
118
+% http://www.cis.hut.fi/projects/somtoolbox/
119
+
120
+% Version 1.0beta juuso 071197, 101297 
121
+% Version 2.0alpha juuso 201198 080200
122
+
123
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
124
+%% check arguments and initialize
125
+
126
+error(nargchk(1, 4, nargin));  % check no. of input args is correct
127
+
128
+% sMap
129
+if isstruct(sMap), 
130
+  switch sMap.type, 
131
+   case 'som_map', M = sMap.codebook; 
132
+   case 'som_data', M = sMap.data;
133
+   otherwise, error('Invalid 1st argument.');
134
+  end
135
+else 
136
+  M = sMap; 
137
+end
138
+[munits dim] = size(M);
139
+if any(any(isnan(M))), 
140
+  error ('Map codebook must not have missing components.');
141
+end
142
+
143
+% data
144
+if isstruct(sData), 
145
+  switch sData.type, 
146
+   case 'som_map', D = sData.codebook;
147
+   case 'som_data', D = sData.data;
148
+   otherwise, error('Invalid 2nd argument.');
149
+  end
150
+else 
151
+  D = sData;
152
+end
153
+[dlen ddim] = size(D);
154
+if dim ~= ddim, 
155
+  error('Data and map dimensions do not match.')
156
+end
157
+
158
+% which_bmus
159
+if nargin < 3 | isempty(which_bmus) | any(isnan(which_bmus)), 
160
+  which_bmus = 1; 
161
+else
162
+  if ischar(which_bmus), 
163
+    switch which_bmus,
164
+     case 'best', which_bmus = 1; 
165
+     case 'worst', which_bmus = munits; 
166
+     case 'all', which_bmus = [1:munits];
167
+    end
168
+  end
169
+end
170
+
171
+% mask
172
+if nargin < 4 | isempty(mask) | any(isnan(mask)), 
173
+  if isstruct(sMap) & strcmp(sMap.type,'som_map'), 
174
+    mask = sMap.mask; 
175
+  elseif isstruct(sData) & strcmp(sData.type,'som_map'), 
176
+    mask = sData.mask; 
177
+  else
178
+    mask = ones(dim,1); 
179
+  end
180
+end
181
+if size(mask,1)==1, mask = mask'; end
182
+if all(mask == 0), 
183
+  error('All components masked off. BMU search cannot be done.');
184
+end
185
+
186
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
187
+%% action
188
+
189
+Bmus = zeros(dlen,length(which_bmus));
190
+Qerrors = Bmus;
191
+
192
+% The BMU search involves calculating weighted Euclidian distances 
193
+% to all map units for each data vector. Basically this is done as
194
+%   for i=1:dlen, 
195
+%     for j=1:munits, 
196
+%       for k=1:dim,
197
+%         Dist(j,i) = Dist(j,i) + mask(k) * (D(i,k) - M(j,k))^2;
198
+%       end
199
+%     end
200
+%   end
201
+% where mask is the weighting vector for distance calculation. However, taking 
202
+% into account that distance between vectors m and v can be expressed as
203
+%   |m - v|^2 = sum_i ((m_i - v_i)^2) = sum_i (m_i^2 + v_i^2 - 2*m_i*v_i)
204
+% this can be made much faster by transforming it to a matrix operation:
205
+%   Dist = (M.^2)*mask*ones(1,d) + ones(m,1)*mask'*(D'.^2) - 2*M*diag(mask)*D'
206
+%
207
+% In the case where there are unknown components in the data, each data
208
+% vector will have an individual mask vector so that for that unit, the 
209
+% unknown components are not taken into account in distance calculation.
210
+% In addition all NaN's are changed to zeros so that they don't screw up 
211
+% the matrix multiplications.
212
+
213
+% calculate distances & bmus
214
+
215
+% This is done a block of data at a time rather than in a
216
+% single sweep to save memory consumption. The 'Dist' matrix has 
217
+% size munits*blen which would be HUGE if you did it in a single-sweep
218
+% operation. If you _want_ to use the single-sweep version, just 
219
+% set blen = dlen. If you're having problems with memory, try to 
220
+% set the value of blen lower. 
221
+blen = min(munits,dlen);
222
+
223
+% handle unknown components
224
+Known = ~isnan(D);
225
+W1 = (mask*ones(1,dlen)) .* Known'; 
226
+D(find(~Known)) = 0;  
227
+unknown = find(sum(Known')==0); % completely unknown vectors 
228
+
229
+% constant matrices
230
+WD = 2*diag(mask)*D';   % constant matrix
231
+dconst = ((D.^2)*mask); % constant term in the distances
232
+
233
+i0 = 0; 
234
+while i0+1<=dlen, 
235
+  % calculate distances 
236
+  inds = [(i0+1):min(dlen,i0+blen)]; i0 = i0+blen;      
237
+  Dist = (M.^2)*W1(:,inds) - M*WD(:,inds); % plus dconst for each sample
238
+  
239
+  % find the bmus and the corresponding quantization errors
240
+  if all(which_bmus==1), [Q B] = min(Dist); else [Q B] = sort(Dist); end
241
+  if munits==1, Bmus(inds,:) = 1; else Bmus(inds,:) = B(which_bmus,:)'; end
242
+  Qerrors(inds,:) = Q(which_bmus,:)' + dconst(inds,ones(length(which_bmus),1));
243
+end  
244
+
245
+% completely unknown vectors
246
+if ~isempty(unknown), 
247
+  Bmus(unknown,:) = NaN;
248
+  Qerrors(unknown,:) = NaN;
249
+end
250
+
251
+Qerrors = sqrt(Qerrors);
252
+
253
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,227 @@
1
+function Cd = som_cldist(D,clinds1,clinds2,cldist,q,mask)
2
+
3
+% SOM_CLDIST Distances between two clusters.
4
+% 
5
+%   Cd = som_cldist(Md,c1,c2,'single')
6
+%   Cd = som_cldist(Md,c1,c2,'average')
7
+%   Cd = som_cldist(Md,c1,c2,'complete')
8
+%   Cd = som_cldist(Md,c1,c2,'neighf',H)
9
+%   Cd = som_cldist(Md,c1,[],...)
10
+%   Cd = som_cldist(D,c1,c2,'centroid',q,mask)
11
+%   Cd = som_cldist(D,c1,c2,'ward',q,mask)
12
+%   Cd = som_cldist(D,c1,[],...)
13
+%
14
+%  Input and output arguments ([]'s are optional):
15
+%   D        (matrix) size dlen x dim, the data set
16
+%            (struct) map or data struct
17
+%   Md       (matrix) size dlen x dlen, mutual distance matrix, see SOM_MDIST
18
+%   c1       (cell array) size n1 x 1, indices of clusters from which 
19
+%                     the distances should be calculated, each cell
20
+%                     contains indices of vectors that belong to that
21
+%                     cluster (indices are between 1...dlen)
22
+%   c2       (cell array) size n2 x 1, same as c1 but have the clusters
23
+%                     to which the distances should be calculated
24
+%            (empty)  c1 is used in place of c2
25
+%   [q]      (scalar) distance norm, default = 2
26
+%   [mask]   (vector) size dim x 1, the weighting mask, a vector of ones
27
+%                     by default
28
+%   H        (matrix) size dlen x dlen, neighborhood function values
29
+%
30
+%   Cd       (matrix) size n1 x n2, distances between the clusters
31
+%
32
+% See also SOM_MDIST. 
33
+
34
+% Copyright (c) 2000 by Juha Vesanto
35
+% Contributed to SOM Toolbox on XXX by Juha Vesanto
36
+% http://www.cis.hut.fi/projects/somtoolbox/
37
+ 
38
+% Version 2.0beta juuso 250800
39
+
40
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
41
+
42
+[dlen dim] = size(D); 
43
+if nargin<5, q = 2; end
44
+if nargin<6, mask = ones(dim,1); end
45
+if ~iscell(clinds1), clinds1 = {clinds1}; end
46
+if ~isempty(clinds2) & ~iscell(clinds2), clinds2 = {clinds2}; end
47
+
48
+n1 = length(clinds1); 
49
+n2 = length(clinds2); 
50
+if n2>0, Cd = zeros(n1,n2); else Cd = zeros(n1); end
51
+if n1==0, return; end
52
+
53
+switch cldist, 
54
+  
55
+ % centroid distance %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
56
+ case 'centroid',  
57
+
58
+  C1 = zeros(n1,dim); for i=1:n1, C1(i,:) = mean(D(clinds1{i},:),1); end
59
+  C2 = zeros(n2,dim); for i=1:n2, C2(i,:) = mean(D(clinds2{i},:),1); end
60
+  if n2==0, 
61
+    for i=1:n1-1, 
62
+      for j=i+1:n1, 
63
+	diff = C1(i,:)-C1(j,:); 
64
+	switch q, 
65
+	 case 1,    Cd(i,j)=abs(diff)*mask;
66
+	 case 2,    Cd(i,j)=sqrt((diff.^2)*mask);  
67
+	 case Inf,  Cd(i,j)=max(diag(mask)*abs(diff),[],2);
68
+	 otherwise, Cd(i,j)=((abs(diff).^q)*mask).^(1/q);
69
+	end   
70
+      end
71
+      Cd([(i+1):n1],i) = Cd(i,[(i+1):n1])';
72
+    end
73
+  else
74
+    for i=1:n1, 
75
+      for j=1:n2, 
76
+	diff = C1(i,:)-C2(j,:); 
77
+	switch q, 
78
+	 case 1,    Cd(i,j)=abs(diff)*mask;
79
+	 case 2,    Cd(i,j)=sqrt((diff.^2)*mask);  
80
+	 case Inf,  Cd(i,j)=max(diag(mask)*abs(diff),[],2);
81
+	 otherwise, Cd(i,j)=((abs(diff).^q)*mask).^(1/q);
82
+	end   
83
+      end
84
+    end
85
+  end
86
+
87
+ % ward distance %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
88
+ case 'ward',
89
+
90
+  C1 = zeros(n1,dim); nn1 = zeros(n1,dim); 
91
+  for i=1:n1, C1(i,:) = mean(D(clinds1{i},:),1); nn1(i) = length(clinds1{i}); end
92
+  C2 = zeros(n2,dim); nn2 = zeros(n2,dim); 
93
+  for i=1:n2, C2(i,:) = mean(D(clinds2{i},:),1); nn2(i) = length(clinds2{i}); end
94
+  if n2==0, 
95
+    for i=1:n1-1, 
96
+      for j=i+1:n1, 
97
+	diff = C1(i,:) - C1(j,:); 
98
+	f = 2*nn1(i)*nn1(j) / (nn1(i)+nn1(j)); 
99
+	switch q, 
100
+	 case 1,    Cd(i,j)=f*abs(diff)*mask;
101
+	 case 2,    Cd(i,j)=f*sqrt((diff.^2)*mask);  
102
+	 case Inf,  Cd(i,j)=f*max(diag(mask)*abs(diff),[],2);
103
+	 otherwise, Cd(i,j)=f*((abs(diff).^q)*mask).^(1/q);
104
+	end   
105
+      end
106
+      Cd([(i+1):n1],i) = Cd(i,[(i+1):n1])';
107
+    end
108
+  else
109
+    for i=1:n1, 
110
+      for j=1:n2, 
111
+	diff = C1(i,:) - C2(j,:); 
112
+	f = 2*nn1(i)*nn2(j) / (nn1(i)+nn2(j)); 
113
+	switch q, 
114
+	 case 1,    Cd(i,j)=f*abs(diff)*mask;
115
+	 case 2,    Cd(i,j)=f*sqrt((diff.^2)*mask);  
116
+	 case Inf,  Cd(i,j)=f*max(diag(mask)*abs(diff),[],2);
117
+	 otherwise, Cd(i,j)=f*((abs(diff).^q)*mask).^(1/q);
118
+	end   
119
+      end
120
+    end
121
+  end  
122
+
123
+ % single linkage distance %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
124
+ case 'single',
125
+
126
+  if n2==0, 
127
+    for i=1:n1-1, 
128
+      for j=i+1:n1, 
129
+	vd = D(clinds1{i},clinds1{j}); 
130
+	fi = isfinite(vd(:));
131
+	if any(fi), Cd(i,j) = min(vd(fi)); else Cd(i,j) = Inf; end
132
+      end
133
+      Cd([(i+1):n1],i) = Cd(i,[(i+1):n1])';
134
+    end
135
+  else
136
+    for i=1:n1, 
137
+      for j=1:n2, 
138
+	vd = D(clinds1{i},clinds2{j}); 
139
+	fi = isfinite(vd(:));
140
+	if any(fi), Cd(i,j) = min(vd(fi)); else Cd(i,j) = Inf; end
141
+      end
142
+    end
143
+  end
144
+
145
+ % average linkage distance %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
146
+ case 'average',
147
+  
148
+  if n2==0, 
149
+    for i=1:n1-1, 
150
+      for j=i+1:n1, 
151
+	vd = D(clinds1{i},clinds1{j}); 
152
+	fi = isfinite(vd(:));
153
+	if any(fi), Cd(i,j) = mean(vd(fi)); else Cd(i,j) = Inf; end
154
+      end
155
+      Cd([(i+1):n1],i) = Cd(i,[(i+1):n1])';
156
+    end
157
+  else
158
+    for i=1:n1, 
159
+      for j=1:n2, 
160
+	vd = D(clinds1{i},clinds2{j}); 
161
+	fi = isfinite(vd(:));
162
+	if any(fi), Cd(i,j) = mean(vd(fi)); else Cd(i,j) = Inf; end
163
+      end
164
+    end
165
+  end
166
+    
167
+ % complete linkage distance %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
168
+ case 'complete',
169
+ 
170
+   if n2==0, 
171
+    for i=1:n1-1, 
172
+      for j=i+1:n1, 
173
+	vd = D(clinds1{i},clinds1{j}); 
174
+	fi = isfinite(vd(:));
175
+	if any(fi), Cd(i,j) = max(vd(fi)); else Cd(i,j) = Inf; end
176
+      end
177
+      Cd([(i+1):n1],i) = Cd(i,[(i+1):n1])';
178
+    end
179
+  else
180
+    for i=1:n1, 
181
+      for j=1:n2, 
182
+	vd = D(clinds1{i},clinds2{j}); 
183
+	fi = isfinite(vd(:));
184
+	if any(fi), Cd(i,j) = max(vd(fi)); else Cd(i,j) = Inf; end
185
+      end
186
+    end
187
+  end
188
+ 
189
+ % neighborhood function linkage distance %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
190
+ case 'neighf',
191
+  
192
+  if n2==0, 
193
+    for i=1:n1-1, 
194
+      for j=i+1:n1, 
195
+	vd = D(clinds1{i},clinds1{j}); 
196
+	fi = isfinite(vd(:));
197
+	if any(fi), 
198
+	  hd = q(clinds1{i},clinds1{j}); 
199
+	  hd = hd(fi); 
200
+	  Cd(i,j) = sum(hd.*vd(fi))/sum(hd); 	  
201
+	else Cd(i,j) = Inf; 
202
+	end
203
+      end
204
+      Cd([(i+1):n1],i) = Cd(i,[(i+1):n1])';
205
+    end
206
+  else
207
+    for i=1:n1, 
208
+      for j=1:n2, 
209
+	vd = D(clinds1{i},clinds2{j}); 
210
+	fi = isfinite(vd(:));
211
+	if any(fi), 
212
+	  hd = q(clinds1{i},clinds2{j}); 
213
+	  hd = hd(fi); 
214
+	  Cd(i,j) = sum(hd.*vd(fi))/sum(hd); 	  
215
+	else Cd(i,j) = Inf; 
216
+	end
217
+      end
218
+    end
219
+  end
220
+
221
+ otherwise, error(['Unknown cluster distance metric: ' cldist]); 
222
+end
223
+  
224
+return;
225
+  
226
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
227
+
... ...
@@ -0,0 +1,115 @@
1
+function a = som_clget(sC, mode, ind)
2
+
3
+%SOM_CLGET Get properties of specified clusters.
4
+%
5
+%  a = som_clget(sC, mode, ind)
6
+% 
7
+%     inds = som_clget(sC,'dinds',20); 
8
+%     col  = som_clget(sC,'depth',[1 2 3 20 54]); 
9
+%
10
+%  Input and output arguments: 
11
+%    sC     (struct) clustering struct
12
+%    mode   (string) what kind of property is requested
13
+%                    'binds' (a union over) indeces of base clusters 
14
+%                            belonging to the specified cluster(s)
15
+%                    'dinds' (a union over) indeces of the data vectors 
16
+%                            belonging to the specified cluster(s)
17
+%                    'dlen'  number of data vectors belonging 
18
+%                            to each of the specified cluster(s)
19
+%                    'depth' depths of the specified clusters
20
+%                            (depth of the root cluster is 0, 
21
+%                             depth of its children are 1, etc.)
22
+%                    'child' (a union over) children clusters 
23
+%                             of specified cluster(s), including
24
+%                             the clusters themselves
25
+%                    'base'  base partitioning based on given 
26
+%                            clusters
27
+%    ind    (vector) indeces of the clusters
28
+%    
29
+%    a      (vector) the answer
30
+%
31
+% See also  SOM_CLSTRUCT, SOM_CLPLOT.
32
+
33
+% Copyright (c) 2000 by the SOM toolbox programming team.
34
+% Contributed to SOM Toolbox on XXX by Juha Vesanto
35
+% http://www.cis.hut.fi/projects/somtoolbox/
36
+
37
+% Version 2.0beta juuso 180800
38
+
39
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
40
+
41
+clen = size(sC.tree,1)+1; 
42
+
43
+switch mode, 
44
+ case 'binds', 
45
+  a = []; 
46
+  for i=1:length(ind), a = [a, getbaseinds(sC.tree,ind(i))]; end
47
+  a = unique(a);
48
+ case 'dinds', 
49
+  b = []; 
50
+  for i=1:length(ind), b = [b, getbaseinds(sC.tree,ind(i))]; end
51
+  b = unique(b);
52
+  a = zeros(length(sC.base),1); 
53
+  for i=1:length(b), a(find(sC.base==b(i)))=1; end
54
+  a = find(a); 
55
+ case 'dlen', 
56
+  a = zeros(length(ind),1); 
57
+  for i=1:length(ind), 
58
+    b = getbaseinds(sC.tree,ind(i)); 
59
+    for j=1:length(b), a(i) = a(i) + sum(sC.base==b(j)); end
60
+  end
61
+ case 'depth', 
62
+  a = getdepth(sC.tree); 
63
+  a = a(ind);
64
+ case 'child', 
65
+  a = getchildren(sC.tree,ind); 
66
+ case 'base',
67
+  a = sC.base*0; 
68
+  ind = -sort(-ind);
69
+  for i=1:length(ind), a(som_clget(sC,'dinds',ind(i))) = ind(i); end
70
+end
71
+
72
+return; 
73
+
74
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
75
+
76
+function ch = getchildren(Z,ind)
77
+
78
+  clen = size(Z,1)+1; 
79
+  ch = ind; cho = ind; 
80
+  while any(cho), 
81
+    i = cho(1); cho = cho(2:end); 
82
+    j = Z(i-clen,1); k = Z(i-clen,2); 
83
+    if j>clen, cho(end+1) = j; end
84
+    if k>clen, cho(end+1) = k; end
85
+    ch(end+1) = j; ch(end+1) = k; 
86
+  end
87
+  return;
88
+
89
+function binds = getbaseinds(Z,ind)
90
+
91
+  clen = size(Z,1)+1; 
92
+  binds = ind; 
93
+  while binds(1)>clen,   
94
+    i = binds(1); 
95
+    binds = binds(2:end); 
96
+    j = Z(i-clen,1); k = Z(i-clen,2);  
97
+    if j>clen, binds = [j binds]; else binds(end+1) = j; end
98
+    if k>clen, binds = [k binds]; else binds(end+1) = k; end
99
+  end
100
+  return;
101
+
102
+function depth = getdepth(Z)
103
+
104
+  clen = size(Z,1)+1; 
105
+  depth = zeros(2*clen-1,1); 
106
+  ch = 2*clen-1; % active nodes
107
+  while any(ch), 
108
+    c  = ch(1); ch = ch(2:end);
109
+    if c>clen & isfinite(Z(c-clen,3)), 
110
+      chc = Z(c-clen,1:2); % children of c
111
+      depth(chc) = depth(c) + 1; % or +(ind==chc(1))
112
+      ch = [ch, chc]; 
113
+    end
114
+  end
115
+  return; 
... ...
@@ -0,0 +1,272 @@
1
+function sC = som_cllinkage(sM,varargin)
2
+
3
+%SOM_CLLINKAGE Make a hierarchical linkage of the SOM map units.
4
+%
5
+% sC = som_cllinkage(sM, [[argID,] value, ...])
6
+%  
7
+%  sC = som_cllinkage(sM);
8
+%  sC = som_cllinkage(D,'complete');
9
+%  sC = som_cllinkage(sM,'single','ignore',find(~som_hits(sM,D)));
10
+%  sC = som_cllinkage(sM,pdist(sM.codebook,'mahal'));
11
+%  som_clplot(sC); 
12
+%
13
+%  Input and output arguments ([]'s are optional):
14
+%   sM       (struct) map or data struct to be clustered
15
+%            (matrix) size dlen x dim, a data set: the matrix must not
16
+%                     contain any NaN's!
17
+%   [argID,  (string) See below. The values which are unambiguous can 
18
+%    value]  (varies) be given without the preceeding argID.
19
+%
20
+%   sC       (struct) a clustering struct with e.g. the following fields
21
+%                     (for more information see SOMCL_STRUCT)
22
+%     .base  (vector) if base partitioning is given, this is a newly 
23
+%                     coded version of it so that the cluster indices
24
+%                     go from 1 to the number of clusters. 
25
+%     .tree  (matrix) size clen-1 x 3, the linkage info
26
+%                     Z(i,1) and Z(i,2) hold the indeces of clusters 
27
+%                     combined on level i (starting from bottom). The new
28
+%                     cluster has index dlen+i. The initial cluster 
29
+%                     index of each unit is its linear index in the 
30
+%                     original data matrix. Z(i,3) is the distance
31
+%                     between the combined clusters. See LINKAGE
32
+%                     function in the Statistics Toolbox.
33
+%     
34
+% Here are the valid argument IDs and corresponding values. The values 
35
+% which are unambiguous (marked with '*') can be given without the
36
+% preceeding argID.
37
+%   'topol'   *(struct) topology struct
38
+%   'connect' *(string) 'neighbors' or 'any' (default), whether the
39
+%                       connections should be allowed only between 
40
+%                       neighbors or between any vectors
41
+%              (matrix) size dlen x dlen indicating the connections
42
+%                       between vectors
43
+%   'linkage' *(string) the linkage criteria to use: 'single' (the
44
+%                       default), 'average', 'complete', 'centroid', or 'ward' 
45
+%   'dist'     (matrix) size dlen x dlen, pairwise distance matrix to 
46
+%                       be used instead of euclidian distances
47
+%              (vector) as the output of PDIST function
48
+%              (scalar) distance norm to use (default is euclidian = 2)
49
+%   'mask'     (vector) size dim x 1, the search mask used to 
50
+%                       weight distance calculation. By default 
51
+%                       sM.mask or a vector of ones is used.
52
+%   'base'     (vector) giving the base partitioning of the data: 
53
+%                       base(i) = j denotes that vector i belongs to
54
+%                       base cluster j, and base(i) = NaN that vector
55
+%                       i does not belong to any cluster, but should be
56
+%                       ignored. At the beginning of the clustering, the 
57
+%                       vector of each cluster are averaged, and these
58
+%                       averaged vectors are then clustered using 
59
+%                       hierarchical clustering.
60
+%   'ignore'   (vector) units to be ignored (in addition to those listed
61
+%                       in base argument)
62
+%   'tracking' (scalar) 1 or 0: whether to show tracking bar or not (default = 0)
63
+%
64
+% Note that if 'connect'='neighbors' and some vector are ignored (as denoted
65
+% by NaNs in the base vector), there may be areas on the map which will
66
+% never be connected: connections across the ignored map units simply do not
67
+% exist. In such a case, the neighborhood is gradually increased until 
68
+% the areas can be connected.
69
+%
70
+% See also KMEANS_CLUSTERS, LINKAGE, PDIST, DENDROGRAM. 
71
+
72
+% Copyright (c) 2000 by Juha Vesanto
73
+% Contributed to SOM Toolbox on XXX by Juha Vesanto
74
+% http://www.cis.hut.fi/projects/somtoolbox/
75
+ 
76
+% Version 2.0beta juuso 160600 250800
77
+
78
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
79
+%% input arguments
80
+
81
+% the data
82
+if isstruct(sM), 
83
+  switch sM.type, 
84
+   case 'som_map', M = sM.codebook; sT = sM.topol; mask = sM.mask; data_name = sM.name; sTr = sM.trainhist(end); 
85
+   case 'som_data', M = sM.data; sT = []; mask = []; data_name = sM.name; sTr = [];
86
+   case 'som_topol', M = []; sT = sM; mask = []; data_name = inputname(1); 
87
+                     sTr = som_set('som_train','neigh','gaussian','radius_fin',1);
88
+   otherwise, error('Bad first argument');
89
+  end
90
+else M = sM; sT = []; mask = []; data_name = inputname(1); sTr = []; 
91
+end
92
+[dlen dim] = size(M);
93
+if isempty(mask), mask = ones(dim,1); end
94
+if any(isnan(M(:))), error('Data matrix must not have any NaNs.'); end
95
+
96
+% varargin
97
+q = 2; 
98
+Md = []; 
99
+linkage = 'single';
100
+ignore = []; 
101
+Ne = 'any';
102
+base = []; 
103
+tracking = 0; 
104
+i=1; 
105
+while i<=length(varargin), 
106
+  argok = 1; 
107
+  if ischar(varargin{i}), 
108
+    switch varargin{i}, 
109
+      % argument IDs
110
+     case {'topol','som_topol','sTopol'}, i=i+1; sT = varargin{i};
111
+     case 'connect', i=i+1; Ne = varargin{i};
112
+     case 'ignore',  i=i+1; ignore = varargin{i}; 
113
+     case 'dist',    i=i+1; Md = varargin{i};
114
+     case 'linkage', i=i+1; linkage = varargin{i};
115
+     case 'mask',    i=i+1; mask = varargin{i};
116
+     case 'tracking',i=i+1; tracking = varargin{i}; 
117
+     case 'base',    i=i+1; base = varargin{i};
118
+      % unambiguous values
119
+     case 'neighbors', Ne = varargin{i};
120
+     case 'any',       Ne = varargin{i};
121
+     case {'single','average','complete','neighf','centroid','ward'}, linkage = varargin{i};
122
+     otherwise argok=0; 
123
+    end
124
+  elseif isstruct(varargin{i}) & isfield(varargin{i},'type'), 
125
+    switch varargin{i}(1).type, 
126
+     case 'som_topol', sT = varargin{i}; 
127
+     otherwise argok=0; 
128
+    end
129
+  else
130
+    argok = 0; 
131
+  end
132
+  if ~argok, disp(['(som_cllinkage) Ignoring invalid argument #' num2str(i+1)]); end
133
+  i = i+1; 
134
+end
135
+
136
+% check distance metric
137
+if prod(size(Md))==1, q = Md; Md = []; end
138
+if ~isempty(Md) & prod(size(Md))<dlen^2, Md = squareform(Md); end    
139
+if prod(size(Md))>0 & any(strcmp(linkage,{'ward','centroid'})),
140
+  warning(['The linkage method ' linkage ' cannot be performed with precalculated distance matrix.']);
141
+end
142
+
143
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
144
+%% distance matrix and connections between units
145
+
146
+% base partition 
147
+if isempty(base), base = 1:dlen; end
148
+if ~isempty(ignore), base(ignore) = NaN; end
149
+cid = unique(base(isfinite(base))); 
150
+nc = length(cid); 
151
+if max(cid)>nc | min(cid)<1, 
152
+  b = base; for i=1:nc, base(find(b==cid(i))) = i; end
153
+end
154
+
155
+% initial clusters
156
+clinds = cell(nc,1); 
157
+for i=1:nc, clinds{i} = find(base==i); end
158
+
159
+% neighborhood constraint (calculate connection matrix Ne)
160
+if ischar(Ne),
161
+  switch Ne, 
162
+   case 'any', Ne = []; 
163
+   case 'neighbors', if ischar(Ne), Ne = som_unit_neighs(sT); end  
164
+   otherwise, error(['Unrecognized connection mode ' Ne]);
165
+  end
166
+end
167
+if ~isempty(Ne), l = size(Ne,1); Ne([0:l-1]*l+[1:l]) = 1; end % diagonal=1
168
+if all(Ne(:)>0), Ne = []; end
169
+
170
+% neighborhood function values
171
+if strcmp(linkage,'neighf') 
172
+  if isempty(sTr), error('Cannot use neighf linkage.'); end
173
+  q = som_unit_dists(sT).^2; 
174
+  r = sTr.radius_fin^2; 
175
+  if isnan(r) | isempty(r), r = 1; end 
176
+  switch sTr.neigh,
177
+   case 'bubble',   q = (q <= r);
178
+   case 'gaussian', q = exp(-q/(2*r));
179
+   case 'cutgauss', q = exp(-q/(2*r)) .* (q <= r);
180
+   case 'ep',       q = (1-q/r) .* (q <= r);
181
+  end
182
+end
183
+
184
+% mutual distances and initial cluster distances
185
+Cd = []; 
186
+if any(strcmp(linkage,{'single','average','complete','neighf'})), 
187
+  M = som_mdist(M,2,mask,Ne); 
188
+  if (nc == dlen & all(base==[1:dlen])), Cd = M; end
189
+end 
190
+if isempty(Cd), Cd = som_cldist(M,clinds,[],linkage,q,mask); end
191
+Cd([0:nc-1]*nc+[1:nc]) = NaN; % NaNs on the diagonal
192
+			      
193
+% check out from Ne which of the clusters are not connected
194
+if ~isempty(Ne) & any(strcmp(linkage,{'centroid','ward'})),
195
+  Clconn = sparse(nc); 
196
+  for i=1:nc-1, 
197
+    for j=i+1:nc, Clconn(i,j) = any(any(Ne(clinds{i},clinds{j}))); end
198
+    Clconn(i+1:nc,i) = Clconn(i,i+1:nc)'; 
199
+  end
200
+  Cd(Clconn==0) = Inf; 
201
+else
202
+  Clconn = []; 
203
+end
204
+
205
+
206
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
207
+%% construct dendrogram
208
+
209
+clen = nc; 
210
+cid = 1:clen; 
211
+Z = zeros(nc-1,3)+NaN;     % merged clusters and distance for each step
212
+if tracking, h = waitbar(0,'Making hierarchical clustering'); end
213
+
214
+for i=1:clen-1,
215
+  if tracking, waitbar(i/clen,h); end
216
+  
217
+  % find two closest clusters and combine them
218
+  [d,c1] = min(min(Cd));          % cluster1
219
+  [d,c2] = min(Cd(:,c1));         % cluster2
220
+  i1 = clinds{c1};                % vectors belonging to c1
221
+  i2 = clinds{c2};                % vectors belonging to c2
222
+  clinds{c1} = [i1; i2];          % insert clusters to c1 
223
+  Z(i,:) = [cid(c1), cid(c2), d]; % update tree info   
224
+  
225
+  % remove cluster c2
226
+  notc2 = [1:c2-1,c2+1:nc]; 
227
+  nc = nc-1; if nc<=1, break; end
228
+  if c1>c2, c1=c1-1; end 
229
+  clinds = clinds(notc2); 
230
+  Cd = Cd(notc2,notc2);
231
+  cid = cid(notc2);
232
+  if ~isempty(Clconn), Clconn = Clconn(notc2,notc2); end
233
+  
234
+  % update cluster distances
235
+  notc1 = [1:c1-1,c1+1:nc];   
236
+  Cd(c1,notc1) = som_cldist(M,clinds(c1),clinds(notc1),linkage,q,mask); 
237
+  Cd(notc1,c1) = Cd(c1,notc1)'; 
238
+  if ~isempty(Clconn), 
239
+    for j=notc1, Clconn(c1,j) = any(any(Ne(clinds{c1},clinds{j}))); end
240
+    Clconn(notc1,c1) = Clconn(c1,notc1)'; 
241
+    Cd(Clconn==0) = Inf; 
242
+  end
243
+  
244
+end
245
+
246
+if tracking, close(h); end
247
+
248
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
249
+%% return values
250
+
251
+% to maintain compatibility with Statistics Toolbox, the values in 
252
+% Z must be yet transformed so that they are similar to the output
253
+% of LINKAGE function
254
+
255
+clen = size(Z,1)+1; 
256
+Zs = Z;
257
+current_cluster = 1:clen;
258
+for i=1:size(Z,1),
259
+  Zs(i,1) = current_cluster(Z(i,1));
260
+  Zs(i,2) = current_cluster(Z(i,2));
261
+  current_cluster(Z(i,[1 2])) = clen+i;  
262
+end
263
+Z = Zs;
264
+
265
+% make a clustering struct
266
+name = sprintf('Clustering of %s at %s',data_name,datestr(datenum(now),0)); 
267
+sC = som_clstruct(Z,'base',base,'name',name); 
268
+
269
+return;
270
+
271
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
272
+
... ...
@@ -0,0 +1,238 @@
1
+function h = som_clplot(sC,varargin)
2
+
3
+%SOM_CLPLOT Visualize clustering.
4
+% 
5
+% h = som_clplot(sC, [[argID,] value, ...])
6
+% som_clplot(sM, part)
7
+% 
8
+%   som_clplot(sC);
9
+%   som_clplot(som_clstruct(Z))
10
+%   som_clplot(sC,sM);
11
+%   som_clplot(sC,'coord',P);
12
+%   som_clplot(sC,'dendrogram',[1 1 1 1 0 0 1 1 0 0 1]);
13
+%   som_clplot(sC,'linewidth',10);
14
+%   som_clplot(sC,'size',10);
15
+%   som_clplot(sM,part);
16
+%    
17
+%  Input and output arguments ([]'s are optional):    
18
+%   sC        (struct) clustering struct, as produced by SOM_CLSTRUCT
19
+%   [argID,   (string) See below. Each pair is the fieldname and 
20
+%    value]   (varies) the value to be given to that field.
21
+%   sM        (struct) map struct
22
+%   part      (vector) length = munits, partitioning for the map
23
+%
24
+%   h         (vector) handles to the arcs between 
25
+%   
26
+% Here are the valid argument IDs and corresponding values. The values 
27
+% which are unambiguous (marked with '*') can be given without the
28
+% preceeding argID.
29
+%   'linecolor' (string) color of the arc lines, 'k' by default
30
+%               (vector) size 1 x 3
31
+%   'linewidth' (scalar) width of the arc lines
32
+%   'size'      (vector) length 2*clen-1, sizes for each of the 
33
+%                        cluster markers
34
+%               (scalar) this size is used for all cluster markers
35
+%   'dendrogram'(vector) size 2*clen-1, indicates which clusters 
36
+%                        are shown in the dendrogram
37
+%              *(string) 'on' or 'off' ('on' by default)
38
+%   'coord'     (matrix) size dlen x odim, the coordinates
39
+%                        for the data. If odim<=2, these are used as is.
40
+%                        Otherwise a 2-dimensional PCA-projection is
41
+%                        first made (see function PCAPROJ). These
42
+%                        coordinates are applied also to the clusters.
43
+%              *(struct) data struct: as above
44
+%                        map or topology struct: the coordinates given 
45
+%                        by SOM_VIS_COORDS are used for the data 
46
+%   'color'     (matrix) size dlen x 3, color for each data. By
47
+%                        default the colors defined for base 
48
+%                        clusters are used (sC.color(sC.base,:)).
49
+%                        For ignored data figure background color is used. 
50
+%               (vector) size dlen x 1, indexed colors are used
51
+%
52
+% See also SOM_CLSTRUCT, SOM_LINKAGE, SOM_CLPRUNE, LINKAGE, DENDROGRAM.
53
+
54
+% Copyright (c) 2000 by Juha Vesanto
55
+% Contributed to SOM Toolbox on XXX by Juha Vesanto
56
+% http://www.cis.hut.fi/projects/somtoolbox/
57
+ 
58
+% Version 2.0beta juuso 180600
59
+
60
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
61
+%% read the arguments
62
+
63
+% sC
64
+if strcmp(sC.type,'som_map'), 
65
+  base = varargin{1}; 
66
+  clen = length(unique(base(isfinite(base)))); 
67
+  Z = ones(clen-1,3); 
68
+  Z(:,1) = randperm(clen-1)'; 
69
+  Z(:,2) = [clen:2*clen-2]'; 
70
+  Z(:,3) = [1:clen-1]'; 
71
+  sT = sC;
72
+  sC = som_clstruct(Z,'base',varargin{1}); 
73
+  h = som_clplot(sC,'coord',sT,'dendrogram','off',varargin{2:end}); 
74
+  return; 
75
+end
76
+clen = size(sC.tree,1)+1; 
77
+
78
+% varargin
79
+show = 'on'; 
80
+markersize = 10; 
81
+linecolor = 'k'; 
82
+linewidth = 1; 
83
+datacoord = []; 
84
+datacolor = []; 
85
+
86
+i=1; 
87
+while i<=length(varargin), 
88
+  argok = 1; 
89
+  if ischar(varargin{i}), 
90
+    switch varargin{i}, 
91
+     case 'dendrogram', i=i+1; show = varargin{i}; 
92
+     case 'size',       i=i+1; markersize = varargin{i}; 
93
+     case 'linecolor',  i=i+1; linecolor = varargin{i}; 
94
+     case 'linewidth',  i=i+1; linewidth = varargin{i};
95
+     case 'color',      i=i+1; datacolor = varargin{i};
96
+     case 'coord',      i=i+1; datacoord = varargin{i};
97
+     case {'on','off'}, show = varargin{i}; 
98
+     otherwise argok=0; 
99
+    end
100
+  elseif isstruct(varargin{i}), datacoord = varargin{i}; 
101
+  else argok = 0; 
102
+  end
103
+  if ~argok, disp(['(som_clplot) Ignoring invalid argument #' num2str(i+1)]); end
104
+  i=i+1;
105
+end
106
+
107
+% markersize
108
+if length(markersize)==1, markersize = ones(2*clen-1,1)*markersize; end
109
+
110
+% datacoord
111
+if ~isempty(datacoord),
112
+  if isstruct(datacoord), 
113
+    switch datacoord.type, 
114
+     case 'som_map',   datacoord = datacoord.topol;
115
+     case 'som_topol', %nil 
116
+     case 'som_data',  datacoord = datacoord.data;
117
+     otherwise,        datacoord = []; 
118
+    end  
119
+  end
120
+  if isstruct(datacoord), 
121
+    sC = som_clstruct(sC,'coord',som_vis_coords(datacoord.lattice,datacoord.msize));
122
+  else
123
+    [dlen dim] = size(datacoord);
124
+    if dim>2, datacoord = pcaproj(datacoord,2); end
125
+    sC = som_clstruct(sC,'coord',datacoord);
126
+  end
127
+end
128
+
129
+% show
130
+if ischar(show), show = strcmp(show,'on'); end
131
+if prod(size(show)) == 1, show = ones(2*clen-1,1)*show; end
132
+
133
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
134
+%% initialize values
135
+
136
+% find the children to show for each cluster
137
+sTree0 = struct('parent',0,'children',[]); 
138
+sTree = sTree0; 
139
+for i=2:(2*clen-1), sTree(i) = sTree0; end
140
+for i=(clen+1):(2*clen-1), 
141
+  if isfinite(sC.tree(i-clen,3)), 
142
+    ch = sC.tree(i-clen,1:2);
143
+    sTree(i).children = ch; 
144
+    for j=1:length(ch), sTree(ch(j)).parent = i; end
145
+  end  
146
+end
147
+if any(show==0), % some clusters are not shown
148
+  for i=(clen+1):(2*clen-1), 
149
+    if ~show(i),
150
+      p = sTree(i).parent;
151
+      ch = sTree(i).children;
152
+      if p, 
153
+	j = find(sTree(p).children == i);
154
+	sTree(p).children = [sTree(p).children([1:(j-1),(j+1):end]), ch]; 
155
+	for j=1:length(ch), sTree(ch(j)).parent = p; end
156
+      end
157
+    end    
158
+  end  
159
+end
160
+
161
+% the arcs
162
+lfrom = []; lto = []; ladd = [];
163
+for i=(clen+1):(2*clen-1),   
164
+  if show(i), 
165
+    ch = sTree(i).children'; 
166
+    %ch = ch(find(show(ch)==1)); 
167
+    lfrom = [lfrom; i*ones(length(ch),1)]; 
168
+    lto = [lto; ch];     
169
+  end
170
+end
171
+
172
+% infinite height
173
+%isinf = ~isfinite(sC.height); 
174
+%sC.height(isinf) = 2*max(sC.height(~isinf)); 
175
+
176
+% the coordinates of the arcs
177
+Co = [sC.coord, sC.height];
178
+if size(Co,2)==2, 
179
+  Lx = [Co(lfrom,1),   Co(lto,1),     Co(lto,1)];
180
+  Ly = [Co(lfrom,end), Co(lfrom,end), Co(lto,end)];
181
+  Lz = []; 
182
+else
183
+  Lx = [Co(lfrom,1),   Co(lto,1),     Co(lto,1)];
184
+  Ly = [Co(lfrom,2),   Co(lto,2),     Co(lto,2)];
185
+  Lz = [Co(lfrom,end), Co(lfrom,end), Co(lto,end)];
186
+end
187
+
188
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
189
+%% plot
190
+
191
+washold = ishold; 
192
+if ~washold, cla; hold on; end
193
+
194
+% plot data
195
+if ~isempty(datacoord), 
196
+  if isempty(datacolor),
197
+    nancolor = get(gcf,'Color'); 
198
+    Col = nancolor(ones(length(sC.base),1),:);
199
+    ind = find(isfinite(sC.base)); 
200
+    Col(ind,:) = sC.color(sC.base(ind),:); 
201
+  elseif size(datacolor,2)==1, Col = som_normcolor(datacolor,jet); 
202
+  else Col = datacolor;     
203
+  end    
204
+  if isstruct(datacoord), som_cplane(datacoord,Col);
205
+  else som_grid('rect',[length(sC.base) 1],'line','none',...
206
+		'Coord',datacoord,'Markercolor',Col); 
207
+  end
208
+end
209
+
210
+h = []; 
211
+if any(show), 
212
+
213
+  % plot the lines
214
+  if isempty(Lz), 
215
+    h = line(Lx',Ly','color',linecolor,'linewidth',linewidth); 
216
+  else 
217
+    h = line(Lx',Ly',Lz','color',linecolor,'linewidth',linewidth); 
218
+    if ~washold, view(3); end
219
+    rotate3d on
220
+  end
221
+  
222
+  % plot the nodes
223
+  inds = find(show); 
224
+  som_grid('rect',[length(inds) 1],'line','none',...
225
+	   'Coord',Co(inds,:),...
226
+	   'Markercolor',sC.color(inds,:),...
227
+	   'Markersize',markersize(inds));
228
+end
229
+
230
+if ~washold, hold off, end
231
+
232
+return;
233
+
234
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
235
+
236
+
237
+
238
+  
0 239
\ No newline at end of file
... ...
@@ -0,0 +1,278 @@
1
+function [sC,old2new,newi] = som_clset(sC,action,par1,par2)
2
+
3
+% SOM_CLSET Create and/or set values in the som_clustering struct.
4
+%
5
+%   first argument
6
+%     sC       (struct) a som_clustering struct
7
+%     Z        (matrix) size nb-1 x 3, as given by LINKAGE function
8
+%     base     (vector) size dlen x 1, a partitioning of the data
9
+%
10
+%   actions    
11
+%     'remove'           removes the indicated clusters (par1: vector)
12
+%     'add'              add a cluster by making a combination of the indicated
13
+%                        clusters (par1: vector)
14
+%     %'move'             moves a child cluster (par1: scalar) from a parent to another
15
+%     %                   (par2: vector 1 x 2)
16
+%     'merge'            like 'add', followed by removing the indicated clusters (par1: vector)
17
+%     %'split'            the indicated cluster (par1: scalar) is partitioned into indicated
18
+%     %                   parts (par2: vector), which are then added, while the indicated cluster
19
+%     %                   (par1) is removed
20
+%     'coord'            sets the coordinates of base clusters (par1: matrix nb x *), and 
21
+%                        recalculates coordinates of the derived clusters (by averaging base cluster
22
+%                        coordinates)
23
+%     'color'            sets the colors of base clusters (par1: matrix nb x 3), and recalculates
24
+%                        colors of the derived clusters (as averages of base cluster colors)
25
+%                        
26
+%   sC
27
+%     .type     (string) 'som_clustering'
28
+%     .name     (string) Identifier for the clustering.
29
+%     .nb       (scalar) Number of base clusters in the clustering.
30
+%     .base     (vector) Size dlen x 1, the basic groups of data 
31
+%                        forming the base clusters, e.g. as a result 
32
+%                        of partitive clustering. Allowed values are 
33
+%                         1:nb   indicating the base cluster
34
+%                                to which the data belongs to. 
35
+%                         NaN    indicating that the data has
36
+%                                been ignored in the clustering                        
37
+%     .nc       (scalar) Number of clusters in the clustering (nb + derived clusters).
38
+%     .children (cellarray) size nc x 1, each cell gives the list of indeces
39
+%                        of child clusters for the cluster
40
+%     .parent   (vector) size nc x 1, the index of parent of each cluster 
41
+%                        (or zero if the cluster does not have a parent)
42
+%     .coord    (matrix) size nc x *, visualization coordinates for each cluster
43
+%                        By default the coordinates are set so that 
44
+%                        the base clusters are ordered on a line, and the
45
+%                        position of each combined cluster is average of 
46
+%                        the base clusters that constitute it.
47
+%     .color    (matrix) size nc x 3, color for each cluster. 
48
+%                        By default the colors are set so that the 
49
+%                        base clusters are ordered on a line,
50
+%                        and then colors are assigned from the 'hsv' 
51
+%                        colormap to the base clusters. The color
52
+%                        of each combined cluster is average as above.
53
+%     .cldist   (string) Default cluster distance function.
54
+
55
+inew = []; 
56
+if isstruct(sC), 
57
+    % it should be a som_clustering struct
58
+    old2new = [1:sC.nc];
59
+elseif size(sC,2)==3, 
60
+    % assume it is a cluster hierarchy matrix Z 
61
+    sC = Z2sC(sC); 
62
+    old2new = [1:sC.nc];
63
+else
64
+    % assume it is a partitioning vector
65
+    base = sC; 
66
+    u = unique(base(isfinite(base)));
67
+    old2new = sparse(u,1,1:length(u));
68
+    base = old2new(base);
69
+    sC = part2sC(base); 
70
+end 
71
+
72
+switch action, 
73
+case 'remove',        
74
+    for i=1:length(par1),         
75
+        [sC,o2n] = removecluster(sC,old2new(par1(i)));
76
+        old2new = o2n(old2new);
77
+    end 
78
+case 'add', 
79
+    [sC,old2new,inew] = addmergedcluster(sC,par1);    
80
+case 'move',
81
+    % not implemented yet
82
+case 'split', 
83
+    % not implemented yet
84
+case 'merge', 
85
+    [sC,old2new,inew] = addmergedcluster(sC,par1);
86
+    for i=1:length(par1), 
87
+        [sC,o2n] = removecluster(sC,old2new(par1(i)));
88
+        old2new = o2n(old2new);
89
+    end 
90
+case 'color', 
91
+    sC.color = derivative_average(sC,par1);
92
+case 'coord',
93
+    sC.coord = derivative_average(sC,par1);
94
+end 
95
+
96
+return;
97
+
98
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
99
+%% subfunctions
100
+
101
+function sC = clstruct(nb,nc)
102
+
103
+    sC = struct('type','som_clustering',...
104
+                'name','','base',[],'nb',nb,'nc',nc,...
105
+                'parent',[],'children',[],'coord',[],'color',[],'cldist','centroid');
106
+    sC.base = [1:nb]; 
107
+    sC.parent = zeros(nc,1);
108
+    sC.children = cell(nc,1); sC.children(:) = {[]}; 
109
+    sC.coord = zeros(nc,2);
110
+    sC.color = zeros(nc,3);
111
+    return;
112
+
113
+function Z = sC2Z(sC,height)
114
+
115
+    if nargin<2, height = 'level'; end
116
+
117
+    root   = find(sC.parent==0); 
118
+    order  = [root]; 
119
+    ch     = sC.children(root); 
120
+    while any(ch), i = ch(1); order = [ch(1), order]; ch = [ch(2:end), sC.children{i}]; end 
121
+
122
+    he = zeros(sC.nc,1); 
123
+    if strcmp(height,'level'), 
124
+        ch = sC.children{root}; 
125
+        while any(ch),
126
+            i = ch(1); he(i) = he(sC.parent(i))+1; 
127
+            ch = [ch(2:end), sC.children{i}]; 
128
+        end 
129
+        he = max(he)-he; 
130
+    elseif strcmp(height,'level2'), 
131
+        for i=order, if any(sC.children{i}), he(i) = max(he(sC.children{i}))+1; end, end
132
+    else
133
+        %he = som_cldist ( between children )
134
+    end 
135
+    
136
+    Z = zeros(sC.nb-1,3);    
137
+    i = sC.nb-1; 
138
+    inds = root; 
139
+    while i>0, 
140
+        ch = sC.children{inds(1)}; h = he(inds(1)); inds = [inds(2:end), ch]; 
141
+        if length(ch)>=2,
142
+            for k=1:length(ch)-2, Z(i,:) = [i-1, ch(k), h]; i = i - 1; end
143
+            Z(i,:) = [ch(end-1) ch(end) h]; i = i - 1;             
144
+        end 
145
+    end 
146
+    return;
147
+
148
+function sC = Z2sC(Z)
149
+
150
+    nb        = size(Z,1)+1;
151
+    nc        = 2*nb-1;
152
+    sC        = clstruct(nb,nc);
153
+    sC.base   = [1:nb];
154
+    for i=1:nc, 
155
+        j = find(Z(:,1)==i | Z(:,2)==i); 
156
+        sC.parent(i) = nb+j;
157
+        sC.children{sC.parent(i)}(end+1) = i; 
158
+    end 
159
+    % coords and color
160
+    order = nc; 
161
+    nonleaves = 1; 
162
+    while any(nonleaves), 
163
+        j = nonleaves(1); 
164
+        ch = sC.children{order(j)};
165
+        if j==1, oleft = []; else oleft = order(1:(j-1)); end
166
+        if j==length(order), oright = []; else oright = order((j+1):length(order)); end
167
+        order = [oleft, ch, oright];
168
+        nonleaves = find(order>nb); 
169
+    end
170
+    [dummy,co] = sort(order);     
171
+    sC.coord   = derivative_average(sC,co');
172
+    H          = hsv(nb+1);
173
+    sC.color   = derivative_average(sC,H(co,:));    
174
+    return;
175
+    
176
+function sC = part2sC(part)
177
+
178
+    nb      = max(part); 
179
+    nc      = nb+1; 
180
+    sC      = clstruct(nb,nc);
181
+    sC.base = part; 
182
+    sC.parent(1:nb) = nc; 
183
+    sC.children{nc} = [1:nb]; 
184
+    co       = [1:nb]'; 
185
+    sC.coord = derivative_average(sC,co);
186
+    H        = hsv(nb+1);
187
+    sC.color = derivative_average(sC,H(1:nb,:));
188
+    return;
189
+
190
+function [sC,old2new] = removecluster(sC,ind)
191
+  
192
+    old2new = [1:sC.nc]; 
193
+    parent_ind = sC.parent(ind);
194
+    ch = sC.children{ind};
195
+    if ~parent_ind, 
196
+        % trying to remove root cluster - no go
197
+        return; 
198
+    elseif ~any(ch), 
199
+        % trying to remove a base cluster - no go
200
+        return;
201
+    else
202
+        % ok, proceed
203
+        old2new = [1:ind-1 0 ind:sC.nc-1];
204
+        % update parent and child fields
205
+        sC.parent(ch) = parent_ind;
206
+        sC.children{parent_ind} = setdiff([sC.children{parent_ind}, ch],ind);
207
+        % remove old cluster
208
+        j = [1:ind-1, ind+1:sC.nc]; 
209
+        sC.parent   = sC.parent(j);
210
+        sC.children = sC.children(j);
211
+        sC.color    = sC.color(j,:);
212
+        sC.coord    = sC.coord(j,:);
213
+        sC.nc       = sC.nc-1; 
214
+        % update old indeces to new indices
215
+        sC.parent = old2new(sC.parent);
216
+        for i=1:sC.nc, sC.children{i} = old2new(sC.children{i}); end
217
+    end     
218
+    return;
219
+
220
+function [sC,old2new,inew] = addmergedcluster(sC,inds)
221
+
222
+    old2new    = [1:sC.nc]; 
223
+    inew       = 0; 
224
+    p_inds     = sC.parent(inds); 
225
+    if ~all(p_inds(1)==p_inds),  
226
+        % clusters are not siblings - no go
227
+        return;
228
+    end
229
+    parent_ind = p_inds(1); 
230
+    if isempty(setdiff(sC.children{parent_ind},inds)),  
231
+        % such a merged cluster exists already
232
+        return;     
233
+    else
234
+        % ok, proceed
235
+        inew = parent_ind;
236
+        old2new = [1:inew-1,inew+1:sC.nc+1];
237
+        % add the new cluster (=copy of parent_ind) 
238
+        j = [1:inew,inew:sC.nc];
239
+        sC.parent   = sC.parent(j);
240
+        sC.children = sC.children(j);
241
+        sC.color    = sC.color(j,:);
242
+        sC.coord    = sC.coord(j,:);
243
+        sC.nc       = sC.nc+1;
244
+        % update old indeces to new indices
245
+        sC.parent = old2new(sC.parent);
246
+        for i=1:sC.nc, sC.children{i} = old2new(sC.children{i}); end
247
+        inds = old2new(inds);
248
+        parent_ind = old2new(parent_ind);
249
+        % update parent, child, color and coord fields
250
+        sC.parent(inds)         = inew; 
251
+        sC.parent(inew)         = parent_ind;
252
+        sC.children{inew}       = inds; 
253
+        sC.children{parent_ind} = [setdiff(sC.children{parent_ind}, inds), inew];
254
+        b = baseind(sC,inew); 
255
+        sC.color(inew,:)        = mean(sC.color(b,:));
256
+        sC.coord(inew,:)        = mean(sC.coord(b,:));
257
+    end    
258
+    return;
259
+    
260
+function C = derivative_average(sC,Cbase)
261
+
262
+    [n dim] = size(Cbase);
263
+    if n ~= sC.nb, error('Color / Coord matrix should have nb rows'); end
264
+    C = zeros(sC.nc,dim);     
265
+    for i=1:sC.nc, C(i,:) = mean(Cbase(baseind(sC,i),:)); end   
266
+    return;
267
+    
268
+function bi = baseind(sC,ind)
269
+
270
+    bi = [ind]; 
271
+    i = 1; 
272
+    while i<=length(bi), bi = [bi, sC.children{bi(i)}]; end 
273
+    bi = bi(bi<=sC.nb);
274
+    return;
275
+  
276
+
277
+      
278
+      
... ...
@@ -0,0 +1,161 @@
1
+function base = som_clspread(sM,base,cldist,Ne,verbosity)
2
+
3
+% SOM_CLSPREAD Partition the given data by flooding.
4
+%
5
+%  part = som_clspread(sM,part,cldist,[Ne],[verbos])
6
+%
7
+%  Input and output arguments ([]'s are optional):
8
+%   sM       (struct) map or data struct
9
+%            (matrix) size dlen x dim, the data set            
10
+%   base     (vector) initial partition, where if base(i) is
11
+%                      0         i should be assigned to some cluster
12
+%                      NaN       i should not be assigned to any cluster
13
+%                      otherwise i belongs to cluster base(i)
14
+%   cldist   (string) cluster distance measure: 'single', 'average',
15
+%                     'complete', 'neighf', 'ward', 'centroid', 'BMU'  
16
+%   [Ne]     (scalar) 0 = not constrined to neighborhood
17
+%                     1 = constrained   
18
+%            (matrix) size dlen x dlen, indicating possible connections
19
+%   [verbos] (scalar) 1 (default) = show status bar
20
+%                     0  = don't
21
+%
22
+% See also SOM_CLDIST. 
23
+
24
+% Copyright (c) 2000 by Juha Vesanto
25
+% Contributed to SOM Toolbox on XXX by Juha Vesanto
26
+% http://www.cis.hut.fi/projects/somtoolbox/
27
+ 
28
+% Version 2.0beta juuso 220800
29
+
30
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
31
+%% input arguments
32
+
33
+q = 2; 
34
+
35
+% map/data
36
+if isstruct(sM), 
37
+  switch sM.type, 
38
+   case 'som_map',  M = sM.codebook; mask = sM.mask; sT = sM.topol; 
39
+   case 'som_data', M = sM.data; mask = []; sT = []; 
40
+  end
41
+else M = sM; mask = []; sT = []; 
42
+end
43
+[dlen dim] = size(M); 
44
+if isempty(mask), mask = ones(dim,1); end
45
+
46
+% simple option
47
+if any(strcmp(cldist,{'closest','BMU'})), 
48
+  i0 = find(base==0);
49
+  i1 = find(base>0);
50
+  bmus = som_bmus(M(i1,:),M(i0,:));
51
+  base(i0) = base(i1(bmus));
52
+  return; 
53
+end
54
+
55
+% constrained clustering
56
+if nargin<4, Ne = []; end
57
+if prod(size(Ne))==1,  
58
+  if Ne & isempty(sT),
59
+    warning('Cannot use constrained clustering.'); Ne = 0; 
60
+  end
61
+  if Ne, Ne = som_unit_neighs(sT); else Ne = []; end
62
+end
63
+if ~isempty(Ne), 
64
+  Ne([0:dlen-1]*dlen+[1:dlen]) = 1; % set diagonal elements = 1
65
+  if all(Ne(:)>0), Ne = []; end
66
+end
67
+
68
+if nargin<5, verbosity = 1; end
69
+
70
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
71
+%% initialize
72
+
73
+if size(base,1)==1, base = base'; end
74
+
75
+cid = unique(base(isfinite(base) & base~=0)); % cluster IDs
76
+nc = length(cid);    
77
+uind = find(base==0); % unclustered points
78
+nu = length(uind); 
79
+if nu==0, return; end
80
+
81
+% initial clusters
82
+clinds = cell(nc,1); for i=1:nc, clinds{i} = find(base==i); end
83
+clinds2 = cell(nu,1); for i=1:nu, clinds2{i} = uind(i); end
84
+
85
+% neighborhood function values
86
+if strcmp(cldist,'neighf')   
87
+  if isempty(sT), error('Cannot use neighf linkage.'); end
88
+  q = som_unit_dists(sT).^2; 
89
+  r = sM.trainhist(end).radius_fin^2; 
90
+  if isnan(r) | isempty(r), r = 1; end 
91
+  switch sM.neigh,
92
+   case 'bubble',   q = (q <= r);
93
+   case 'gaussian', q = exp(-q/(2*r));
94
+   case 'cutgauss', q = exp(-q/(2*r)) .* (q <= r);
95
+   case 'ep',       q = (1-q/r) .* (q <= r);
96
+  end
97
+end
98
+
99
+% distance of each cluster to the unclustered points
100
+if any(strcmp(cldist,{'single','average','complete','neighf'})), 
101
+  M = som_mdist(M,2,mask,Ne); 
102
+end 
103
+Cd = som_cldist(M,clinds,clinds2,cldist,q,mask); 
104
+			      
105
+% check out from Ne which of the clusters are not connected
106
+if ~isempty(Ne) & any(strcmp(cldist,{'centroid','ward'})),
107
+  Clconn = sparse(nc,nu);   
108
+  for i=1:nc, for j=1:nu, Clconn(i,j) = any(any(Ne(clinds{i},uind(j)))); end, end
109
+  Cd(Clconn==0) = Inf; 
110
+else
111
+  Clconn = []; 
112
+end
113
+
114
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
115
+%% action
116
+
117
+if verbosity,
118
+  nu0 = nu; 
119
+  h = waitbar(1-nu/nu0,'Assigning unclustered points'); % tracking
120
+end
121
+
122
+while 1, 
123
+
124
+  % find closest unclustered point
125
+  [dk,k] = min(Cd,[],2);  % min distance from each unclustered point
126
+  [d,c]  = min(dk);       % cluster to which it is assigned  
127
+  k = k(c); 
128
+
129
+  if ~isfinite(d), 
130
+    break; 
131
+  end
132
+
133
+  % add k to cluster c
134
+  base(uind(k)) = cid(c);   
135
+  clinds{c} = [clinds{c}; uind(k)];
136
+  
137
+  % remove point k
138
+  notk = [1:k-1,k+1:nu]; 
139
+  nu = nu-1; if nu<=0, break; end  
140
+  Cd = Cd(:,notk); 
141
+  uind = uind(notk); 
142
+  clinds2 = clinds2(notk); 
143
+  if ~isempty(Clconn), Clconn = Clconn(:,notk); end
144
+
145
+  % update cluster distances to c
146
+  Cd(c,:) = som_cldist(M,clinds(c),clinds2,cldist,q,mask); 
147
+  if ~isempty(Clconn), 
148
+    for j=1:nu, Clconn(c,j) = any(any(Ne(clinds{c},uind(j)))); end
149
+    Cd(c,find(Clconn(c,:)==0)) = Inf; 
150
+  end
151
+  
152
+  if verbosity, waitbar(1-nu/nu0,h); end % tracking
153
+
154
+end
155
+if verbosity, close(h); end
156
+
157
+return; 
158
+
159
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
160
+
161
+
... ...
@@ -0,0 +1,206 @@
1
+function sC = som_clstruct(Z,varargin)
2
+
3
+%SOM_CLSTRUCT Create a clustering struct or set its field values.
4
+%
5
+%  sC = som_clstruct(Z, [argID, value, ...]) 
6
+%
7
+%    Z  = linkage(pdist(sM.codebook));
8
+%    sC = som_clstruct(Z); 
9
+%    sC = som_clstruct(sC,'coord',som_vis_coords(lattice,msize));
10
+%    sC = som_clstruct(sC,'color',som_colorcode(sM));
11
+%    sC = som_clstruct(sC,'base',sC.base(som_bmus(sM,sD)));
12
+%
13
+%  Input and output arguments ([]'s are optional): 
14
+%   Z         (matrix) size clen-1 x 3, where clen is the number of 
15
+%                      base clusters. This is a clustering matrix 
16
+%                      similar to that produced by LINKAGE in 
17
+%                      Statistical Toolbox. See SOM_LINKAGE.
18
+%             (struct) clustering struct (as produced by this function)
19
+%   [argID,   (string) See below. Each pair is the fieldname and 
20
+%    value]   (varies) the value to be given to that field.
21
+%
22
+%   sC        (struct) clustering struct
23
+% 
24
+%   The clustering struct is based on the assumption that there 
25
+%   is a base partitioning of the SOM (or data) which is saved in 
26
+%   the .base field of the struct. Then a hierarchical clustering
27
+%   is applied to this base partitioning. The results are saved to 
28
+%   .tree field of the struct. Each cluster (base and combined)
29
+%   has also three properties: height, coordinate and color, which 
30
+%   are used in the visualizations. The fields of the struct are:
31
+%     .type   (string) 'som_clustering'
32
+%     .name   (string) Identifier for the clustering.
33
+%     .tree   (matrix) Size clen-1 x 3, as argument Z above. 
34
+%     .base   (vector) Size dlen x 1, the basic groups of data 
35
+%                      forming the base clusters, e.g. as a result 
36
+%                      of partitive clustering. Allowed values are 
37
+%                       1:clen indicating the base cluster
38
+%                              to which the data belongs to. 
39
+%                       NaN    indicating that the data has
40
+%                              been ignored in the clustering
41
+%                      By default [1:clen]. 
42
+%     .height (vector) Size 2*clen-1 x 1, (clustering) height for each 
43
+%                      cluster. By default 0 for each base cluster and
44
+%                      .tree(:,3) for the others.
45
+%     .coord  (matrix) Size 2*clen-1 x *, coordinate for each cluster, 
46
+%                      By default the coordinates are set so that 
47
+%                      the base clusters are ordered on a line, and the
48
+%                      position of each combined cluster is average of 
49
+%                      the base clusters that constitute it.
50
+%     .color  (matrix) Size 2*clen-1 x 3, color for each cluster. 
51
+%                      By default the colors are set so that the 
52
+%                      base clusters are ordered on a line, like above,
53
+%                      and then colors are assigned from the 'hsv' 
54
+%                      colormap to the base clusters. The color
55
+%                      of each combined cluster is average as above.
56
+%
57
+% Height, coord and color can also be specified in alternate forms:
58
+%   'height' (vector) size 2*clen-1 x 1, if given explicitly
59
+%                     size clen-1 x 1, specified heights of the 
60
+%                          combined clusters (the base cluster heights
61
+%                          are all = 0)
62
+%                     size 0 x 0, default value is used
63
+%   'coord'  (matrix) size 2*clen-1 x *, if given explicitly
64
+%                     size clen x *, to give coordinates for base 
65
+%                          clusters; the coordinate of combined clusters
66
+%                          are averaged from these
67
+%                     size dlen x *, to give coordinates of the 
68
+%                          original data: the cluster coordinates are
69
+%                          averaged from these based on base clusters
70
+%                     size 0 x 0, default value is used
71
+%   'color'  (matrix) as 'coord'
72
+%
73
+% See also  SOM_CLPLOT, SOM_CLVALIDITY, SOM_CLGET, SOM_CLLINKAGE.
74
+
75
+% Copyright (c) 2000 by the SOM toolbox programming team.
76
+% Contributed to SOM Toolbox on XXX by Juha Vesanto
77
+% http://www.cis.hut.fi/projects/somtoolbox/
78
+
79
+% Version 2.0beta juuso 180800
80
+
81
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
82
+
83
+if isstruct(Z), 
84
+  base = Z.base; 
85
+  color = Z.color; 
86
+  coord = Z.coord; 
87
+  height = Z.height; 
88
+  name = Z.name; 
89
+  Z = Z.tree; 
90
+else
91
+  base  = []; 
92
+  color = []; 
93
+  coord = []; 
94
+  height = []; 
95
+  name = ''; 
96
+end    
97
+clen  = size(Z,1)+1; 
98
+
99
+i=1; 
100
+while i<=length(varargin), 
101
+  argok = 1; 
102
+  if ischar(varargin{i}), 
103
+    switch varargin{i}, 
104
+     case 'tree',   i=i+1; Z = varargin{i}; clen = size(Z,1)+1;
105
+     case 'base',   i=i+1; base = varargin{i}; 
106
+     case 'color',  i=i+1; color = varargin{i}; 
107
+     case 'coord',  i=i+1; coord = varargin{i}; 
108
+     case 'height', i=i+1; height = varargin{i}; 
109
+     case 'name',   i=i+1; name = varargin{i}; 
110
+     otherwise argok=0; 
111
+    end
112
+  else argok = 0; 
113
+  end
114
+  if ~argok, disp(['(som_clstruct) Ignoring invalid argument #' num2str(i+1)]); end
115
+  i = i+1; 
116
+end
117
+
118
+if isempty(base), 
119
+  dlen = clen; 
120
+  base = 1:dlen; 
121
+else
122
+  dlen = length(base); 
123
+  if any(base)>clen | any(base)<1, error('Incorrect base partition vector.'); end
124
+end
125
+
126
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
127
+%% analysis of hierarchy
128
+
129
+% order of base clusters
130
+order = 2*clen-1; 
131
+nonleaves = 1; 
132
+while any(nonleaves), 
133
+  j = nonleaves(1); 
134
+  ch = Z(order(j)-clen,1:2);
135
+  if j==1, oleft = []; else oleft = order(1:(j-1)); end
136
+  if j==length(order), oright = []; else oright = order((j+1):length(order)); end
137
+  order = [oleft, ch, oright];
138
+  nonleaves = find(order>clen); 
139
+end
140
+
141
+% base cluster indeces for each non-base cluster
142
+basecl = cell(clen-1,1); 
143
+for i=1:clen-1, 
144
+  c1 = Z(i,1); if c1>clen, c1 = basecl{c1-clen}; end
145
+  c2 = Z(i,2); if c2>clen, c2 = basecl{c2-clen}; end
146
+  basecl{i} = [c1 c2];   
147
+end
148
+
149
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
150
+%% set coordinates, color and height and make the struct
151
+
152
+% coordinates
153
+if size(coord,1)==2*clen-1, % this is ok already
154
+else
155
+  if size(coord,1)==0, % the default    
156
+    [dummy,coord] = sort(order); 
157
+    coord = coord'; 
158
+  elseif size(coord,1)==dlen & dlen>clen, % coordinates given for original data
159
+    codata = coord; 
160
+    coord = zeros(clen,size(coord,2)); 
161
+    for i=1:clen, coord(i,:) = mean(codata(find(base==i),:),1); end  
162
+  end
163
+  if size(coord,1)==clen, % average from base clusters
164
+    coord = [coord; zeros(clen-1,size(coord,2))]; 
165
+    for i=1:clen-1, coord(i+clen,:) = mean(coord(basecl{i},:),1); end
166
+  else
167
+    error('Incorrect coordinate matrix.'); 
168
+  end
169
+end
170
+
171
+% color
172
+if size(color,1)==2*clen-1, % this is ok already
173
+else
174
+  if size(color,1)==0, % the default
175
+    color(order,:) = hsv(length(order)); 
176
+  elseif size(color,1)==dlen & dlen>clen, % colors given for original data
177
+    codata = color; 
178
+    color = zeros(clen,3); 
179
+    for i=1:clen, color(i,:) = mean(codata(find(base==i),:),1); end  
180
+  end
181
+  if size(color,1)==clen, % average from base clusters
182
+    color = [color; zeros(clen-1,3)]; 
183
+    for i=1:clen-1, color(i+clen,:) = mean(color(basecl{i},:),1); end
184
+  else
185
+    error('Incorrect color matrix.'); 
186
+  end
187
+end
188
+
189
+% height 
190
+if isempty(height), 
191
+  height = [zeros(clen,1); Z(:,3)]; 
192
+elseif length(height)==clen-1, 
193
+  if size(height,2)==clen-1, height = height'; end
194
+  height = [zeros(clen,1); height]; 
195
+elseif length(height)~=2*clen-1, 
196
+  error('Incorrect height vector.'); 
197
+end
198
+
199
+% make the struct
200
+sC = struct('type','som_clustering',...
201
+	    'name',name,'base',base,'tree',Z,...
202
+	    'color',color,'coord',coord,'height',height); 
203
+return; 
204
+
205
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
206
+  
... ...
@@ -0,0 +1,152 @@
1
+function color=som_clustercolor(m, class, colorcode)
2
+
3
+% SOM_CLUSTERCOLOR Sets map unit coloring according to classification
4
+%
5
+% syntax 1: color = som_clustercolor(m, class, [colorcode]) 
6
+% syntax 2: color = som_clustercolor(class, colormatrix)
7
+%
8
+%  Input and output arguments ([]'s are optional):
9
+%   m           (struct) map or topol struct
10
+%               (cell array) of form {str,[m1 m2]} where str = 'hexa'
11
+%                  or 'rect' and [m1 m2] = msize.
12
+%   class       (matrix) Mxn matrix of integers (class labels)
13
+%                  where M is the number of map units and each
14
+%                  column gives some classification for the units. 
15
+%   colorcode   (string) 'rgb1', 'rgb2' (default), 'rgb3', 'rgb4', 'hsv'.
16
+%   colormatrix (matrix) Mx3 matrix of RGB triplets giving the
17
+%                  initial color code for each unit.
18
+%   color       (matrix) size Mx3xn of RGB triplets giving the
19
+%                  resulting color code for each unit 
20
+%    
21
+% The function gives a color coding by class and location for the
22
+% map units. The color is determined by calculating the mean of the 
23
+% initial RGB values of units belonging to the same class. 
24
+% 
25
+% Function has two syntaxes: 
26
+% 
27
+% * If first argument gives the map topology, i.e. is map or topol struct
28
+% or cell indicating the topology, the initial color coding of the
29
+% units may be given by a string ('rgb1','rgb2','rgb3','rgb4', or 'hsv')
30
+% which describe a predefined coloring scheme. (see SOM_COLORCODE).
31
+% or an initial color matrix of size Mx3 with RGB triplets as rows.  
32
+% * Another possibility is to give just the classification vector
33
+% of size Mx1 and an initial color matrix of size Mx3 with RGB 
34
+% triplets as rows.  
35
+%
36
+% EXAMPLE (requires Matlab Statistics Toolbox)
37
+%
38
+% % Do a 10-cluster single linkage hierachical clustering for SOM units
39
+%    class=cluster(linkage(pdist(sM.codebook),'single'),10);
40
+% % Color code the clusters 
41
+%    C=som_clustercolor(sM, class, 'rgb2');
42
+% % Visualize
43
+%    som_show(sM,'color',C);
44
+%
45
+% See also SOM_COLORCODE, SOM_KMEANSCOLOR, SOM_CPLANE, SOM_SHOW
46
+
47
+% Contributed to SOM Toolbox 2.0, February 11th, 2000 by Johan Himberg
48
+% Copyright (c) by Johan Himberg
49
+% http://www.cis.hut.fi/projects/somtoolbox/
50
+
51
+% Version 2.0beta Johan 100200 
52
+
53
+%%% Check arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
54
+
55
+error(nargchk(2, 3, nargin));   % check no. of input args is correct
56
+
57
+% Check 1s argument 
58
+
59
+% Class matrix?
60
+if vis_valuetype(m, {'nxm'});
61
+   colorcode=class; 
62
+   class=m;
63
+   if ~vis_valuetype(colorcode,{'nx3rgb',[size(class,1) 3]},'all'),
64
+      error(['If map or topol is not specified the colorcode must be a' ...
65
+            ' [size(class,1) 3] sized RGB matrix.']);
66
+   end
67
+else
68
+   [tmp,ok,tmp]=som_set(m);
69
+   if isstruct(m) & all(ok)
70
+      switch m.type
71
+      case 'som_topol'              % topol? 
72
+         msize=m.msize;
73
+         lattice=m.lattice;
74
+      case 'som_map'   
75
+         msize=m.topol.msize;         % map?
76
+         lattice=m.topol.lattice;
77
+      otherwise
78
+         error('Invalid map or topol struct.');
79
+      end
80
+      % cell?  
81
+   elseif iscell(m) & vis_valuetype(size(m),{[1 2]}),
82
+      if vis_valuetype(m{2},{[1 2]}) & vis_valuetype(m{1},{'string'}),
83
+         lattice=m{1};    
84
+         msize=m{2}; 
85
+      else
86
+         error('Invalid map size information.');
87
+      end
88
+   else
89
+      % not known type
90
+      error('Invalid first argument!');
91
+   end
92
+   % Check map parameters
93
+   switch lattice                   % lattice  
94
+   case 'hexa' 
95
+      ;
96
+   case 'rect'
97
+      ;
98
+   otherwise
99
+      error('Unknown lattice type');
100
+   end
101
+   if length(msize)>2               % dimension
102
+      error('Only 2D maps allowed!');
103
+   end
104
+   % Check colorcode
105
+   if nargin<3 | isempty(colorcode)
106
+      colorcode='rgb2';
107
+   end
108
+end
109
+
110
+% Check class
111
+if any(class~=round(class))
112
+   error('Class labels must be integer numbers.');
113
+end
114
+
115
+if min(class)<=0 
116
+   error('Class numbers should be greater than 0');
117
+end
118
+
119
+if ischar(colorcode),
120
+   switch colorcode
121
+   case{'rgb1','rgb2','rgb3','rgb4','hsv'}
122
+      colorcode=som_colorcode(m, colorcode);
123
+   otherwise
124
+      error(['Color code not known: should be ''rgb1'',''rgb2'',' ...
125
+            ' ''rgb3'',''rgb4'' or ''hsv''.']);
126
+   end
127
+elseif ~vis_valuetype(colorcode,{'nx3rgb',[size(class,1) 3]},'all');
128
+   error(['Invalid colorcode matrix: should be a ' ...
129
+         '[length(class) 3] sized RGB matrix.']);
130
+end
131
+
132
+%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
133
+
134
+% Go through all i classifications (columns)
135
+for i=1:size(class,2), 
136
+   % Get unique class labels in ith classification
137
+   c=unique(class(:,i))'; % row vector for loop indexing
138
+   % Go through all class in ith classification    
139
+   for j=c;             
140
+      index=(class(:,i)==j); 
141
+      N=sum(index);
142
+      colors=colorcode(index,:);
143
+      % Calculate the mean color
144
+      meancolor=repmat(mean(colors,1),N,1);
145
+      % Select the original color that is closest to this mean
146
+      dist=sum((meancolor-colors).^2,2);
147
+      [tmp,min_dist_index]=min(dist);
148
+      best_color=repmat(colors(min_dist_index,:),N,1);
149
+      % Set the color to output variable
150
+      color(index,:,i)=best_color;
151
+   end
152
+end
... ...
@@ -0,0 +1,43 @@
1
+function ind = som_cod2ind(msize,cind)
2
+
3
+%SOM_COD2IND Matlab linear index from SOM_PAK style linear indeces.
4
+%
5
+% ind = som_cod2ind(msize,cind)
6
+%
7
+%  ind = som_cod2ind([10 15],44);
8
+%  ind = som_cod2ind(sMap,44);
9
+%  ind = som_cod2ind(sMap.msize,44);
10
+%  ind = som_cod2ind([10 15],[44 13 91]');
11
+%
12
+%  Input and output arguments: 
13
+%   msize  (struct) map or topology struct
14
+%          (vector) size 1 x m, specifies the map grid size
15
+%   cind   (vector) size n x 1, SOM_PAK style linear indeces for n map units
16
+%                   (row first, then column)
17
+% 
18
+%   ind    (vector) size n x 1, Matlab linear indeces
19
+%
20
+% See also SOM_IND2COD.
21
+
22
+% Contributed to SOM Toolbox vs2, January 14th, 2002 by Juha Vesanto
23
+% http://www.cis.hut.fi/projects/somtoolbox/
24
+
25
+% Version 2.0beta juuso 140102
26
+
27
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
28
+
29
+if isstruct(msize), 
30
+  if strcmp(msize.type,'som_map'), msize = msize.topol.msize; 
31
+  elseif strcmp(msize.type,'som_topol'), msize = msize.msize;
32
+  else error('Invalid first argument.'); end
33
+end
34
+
35
+if nargin<2, cind = 1:prod(msize); end
36
+
37
+I2C = som_ind2cod(msize,[1:prod(msize)]); 
38
+[dummy,C2I] = sort(I2C); 
39
+ind = C2I(cind); 
40
+
41
+return; 
42
+
43
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,333 @@
1
+function colors=som_colorcode(m, colorcode, scaling)
2
+
3
+%SOM_COLORCODE Calculates a heuristic color coding for the SOM grid
4
+%
5
+% colors = som_colorcode(m, colorcode, scaling) 
6
+%
7
+%  Input and output arguments ([]'s are optional):
8
+%   m           (struct) map or topol struct
9
+%               (cell array) of form {str,[m1 m2]} where 
10
+%                        str = 'hexa' or 'rect' and [m1 m2] = msize
11
+%               (matrix) size N x 2, unit coordinates 
12
+%   [colorcode] (string) 'rgb1' (default),'rgb2','rgb3','rgb4','hsv'  
13
+%   [scaling]   (scalar) 1=on (default), 0=off. Has effect only
14
+%                        if m is a Nx2 matrix of coordinates: 
15
+%                        controls whether these are scaled to 
16
+%                        range [0,1] or not.
17
+%
18
+%   colors      (matrix) size N x 3, RGB colors for each unit (or point)
19
+%
20
+% The function gives a color coding by location for the map grid 
21
+% (or arbitrary set of points). Map grid coordinates are always linearly 
22
+% normalized to a unit square (x and y coordinates between [0,1]), except
23
+% if m is a Nx2 matrix and scaling=0. In that case too, the coordinates
24
+% must be in range [0,1].
25
+% 
26
+% Following heuristic color codings are available:
27
+%
28
+%  'rgb1' slice of RGB-cube so that       green - yellow
29
+%         the corners have colors:          |       |
30
+%                                         blue  - magenta
31
+%
32
+%  'rgb2' slice of RGB-cube so that       red   - yellow
33
+%         the corners have colors:          |       |
34
+%                                         blue  - cyan   
35
+%
36
+%  'rgb3' slice of RGB-cube so that   mixed_green - orange
37
+%         the corners have colors:          |        |
38
+%                                     light_blue  - pink 
39
+%
40
+%  'rgb4' has 'rgb1' on the diagonal + additional colors in corners
41
+%         (more resolution but visually strongly discontinuous) 
42
+%
43
+%  'hsv'  angle and radius from map centre are coded by hue and 
44
+%         intensity (more resoluton but visually discontinuous)
45
+%
46
+% See also SOM_CPLANE, SOM_SHOW, SOM_CLUSTERCOLOR, SOM_KMEANSCOLOR, 
47
+%          SOM_BMUCOLOR.
48
+
49
+% Contributed to SOM Toolbox 2.0, February 11th, 2000 by Johan Himberg
50
+% Copyright (c) by Johan Himberg
51
+% http://www.cis.hut.fi/projects/somtoolbox/
52
+
53
+% Version 2.0 Johan 140799 
54
+
55
+%%% Check arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
56
+
57
+error(nargchk(1, 3, nargin));   % check no. of input args is correct
58
+
59
+%% Check m: map, topol, cell or data?
60
+
61
+if vis_valuetype(m,{'nx2'}),
62
+  p=m;  % explicit coordinates
63
+  
64
+else
65
+  
66
+  % map, topol, cell
67
+  
68
+  [tmp,ok,tmp]=som_set(m);
69
+  if isstruct(m) & all(ok)
70
+    switch m.type
71
+    case 'som_topol'              % topol 
72
+      msize=m.msize;
73
+      lattice=m.lattice;
74
+    case 'som_map'   
75
+      msize=m.topol.msize;        % map
76
+      lattice=m.topol.lattice;
77
+    otherwise
78
+      error('Invalid map or topol struct.');
79
+    end
80
+
81
+  % cell  
82
+    
83
+  elseif iscell(m) & vis_valuetype(size(m),{[1 2]}),
84
+    if vis_valuetype(m{2},{[1 2]}) & vis_valuetype(m{1},{'string'}),
85
+      lattice=m{1};    
86
+      msize=m{2}; 
87
+    else
88
+      error('Invalid map size information.');
89
+    end
90
+  end
91
+
92
+  %% Check map parameters
93
+ 
94
+  switch lattice                   % lattice  
95
+  case 'hexa' 
96
+    ;
97
+  case 'rect'
98
+    ;
99
+  otherwise
100
+    error('Unknown lattice type');
101
+  end
102
+  
103
+  if length(msize)>2                % dimension
104
+    error('Only 2D maps allowed!');
105
+  end
106
+  
107
+                                     
108
+  % Calculate coordinates 
109
+  p=som_unit_coords(msize,lattice,'sheet');
110
+
111
+  % Set scaling to 1 as it is done always in this case
112
+  scaling=1;   
113
+end
114
+
115
+% Check colorcode
116
+
117
+if nargin < 2 | isempty(colorcode),
118
+  colorcode='rgb1';
119
+end
120
+if ~ischar(colorcode)
121
+  error('String value for colorcode mode expected.');
122
+else
123
+ switch colorcode
124
+ case { 'rgb1', 'rgb2', 'rgb3' , 'rgb4' ,'hsv'}
125
+  otherwise
126
+    error([ 'Colorcode mode ' colorcode ' not implemented.']);
127
+  end
128
+end
129
+
130
+% Check scaling
131
+
132
+if nargin < 3 | isempty(scaling) 
133
+  scaling=1;
134
+end
135
+
136
+if ~vis_valuetype(scaling,{'1x1'})
137
+  error('Scaling should be 0 (off) or 1 (on).');
138
+end
139
+
140
+%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
141
+
142
+% scale coordintes between [0,1]
143
+
144
+if scaling  
145
+  n=size(p,1);
146
+  mn=min(p);
147
+  e=max(p)-mn;
148
+  p=(p-repmat(mn,n,1))./repmat(e,n,1);
149
+elseif sum(p(:,1)>1+p(:,1)<0+p(:,2)>1+p(:,2)<0),  
150
+  error('Coordinates out of range [0,1].');
151
+end
152
+
153
+switch colorcode 
154
+case 'rgb1'
155
+  h(:,1)=p(:,1);
156
+  h(:,2)=1-p(:,2);
157
+  h(:,3)=p(:,2);
158
+case 'rgb2'
159
+  h(:,1)=p(:,1);
160
+  h(:,2)=1-p(:,2);
161
+  h(:,3)=1-p(:,1);
162
+case 'rgb3'
163
+  h(:,1)=p(:,1);
164
+  h(:,2)=.5;
165
+  h(:,3)=p(:,2);
166
+case 'rgb4'  
167
+ p=rgb4(p);
168
+ h(:,1)=p(:,1);
169
+ h(:,2)=1-p(:,2);
170
+ h(:,3)=p(:,3);
171
+case 'hsv'
172
+  munits = n;
173
+  Hsv = zeros(munits,3);
174
+  for i=1:n, 
175
+    dx = .5-p(i,1);
176
+    dy = .5-p(i,2);
177
+    r = sqrt(dx^2+dy^2);
178
+    if r==0, 
179
+      h=1; 
180
+    elseif dx==0, 
181
+      h=.5; %h=ay; 
182
+    elseif dy==0, 
183
+      h=.5; %h=ax; 
184
+    else 
185
+      h = min(abs(.5/(dx/r)),abs(.5/(dy/r))); 
186
+    end
187
+    
188
+    if r==0, 
189
+      angle = 0; 
190
+    else 
191
+      angle = acos(dx/r); 
192
+      if dy<0, 
193
+	angle = 2*pi-angle; 
194
+      end
195
+    end
196
+    
197
+    Hsv(i,1) = 1-sin(angle/4);
198
+    Hsv(i,2) = 1;
199
+    Hsv(i,3) = r/h; 
200
+    h = hsv2rgb(Hsv);
201
+  end
202
+end
203
+
204
+
205
+%% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
206
+
207
+colors=h;
208
+
209
+%% Subfunctions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% juha %%%%
210
+
211
+function p=rgb4(coord)
212
+
213
+for i=1:size(coord,1);
214
+ p(i,:)=get_coords(coord(i,:))';
215
+end
216
+
217
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
218
+
219
+function coords=get_coords(coords)
220
+
221
+%GET_COORDS
222
+%
223
+% get_coords(coords)
224
+%
225
+% ARGUMENTS
226
+%
227
+% coords (1x2 or 2x1 vector) coords(1) is an x-coordinate and coords(2)
228
+%                            y-coordinate.
229
+%
230
+%
231
+% RETURNS
232
+%
233
+% coords (3x1 vector) x,y and z-coordinates.
234
+%
235
+
236
+if ~(all(size(coords) == [1 2]) | all(size(coords) == [2 1]))
237
+  error('Argument ''coords'' must be an 2x1 or 1x2 vector.');
238
+end
239
+
240
+if all(size(coords) == [1 2])
241
+  coords=coords';
242
+end
243
+
244
+if any(coords > 1) any(coords < 0)
245
+  error('Coordinates must lay inside the interval [0,1].');
246
+end
247
+
248
+if coords(1) <= 1/(sqrt(2)+1),
249
+  if coords(2) <= line3(coords(1))
250
+    coords=coords_in_base(4,coords);
251
+  elseif coords(2) <= line2(coords(1))
252
+    coords=coords_in_base(1,coords);
253
+  else
254
+    coords=coords_in_base(2,coords);
255
+  end
256
+elseif coords(1) <= sqrt(2)/(sqrt(2)+1)
257
+  if coords(2) <= line1(coords(1))
258
+    coords=coords_in_base(3,coords);
259
+  elseif coords(2) <= line2(coords(1))
260
+    coords=coords_in_base(1,coords);
261
+  else
262
+    coords=coords_in_base(2,coords);
263
+  end
264
+else
265
+  if coords(2) <= line1(coords(1)),
266
+    coords=coords_in_base(3,coords);
267
+  elseif coords(2) <= line4(coords(1))
268
+    coords=coords_in_base(1,coords);
269
+  else
270
+    coords=coords_in_base(5,coords);
271
+  end
272
+end
273
+
274
+
275
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
276
+
277
+function coords=coords_in_base(base_no,coords)
278
+
279
+A=[0;1/(sqrt(2)+1)];
280
+E=[1;1];
281
+F=[0;0];
282
+G=[1;0];
283
+H=[0;1];
284
+
285
+const=1+1/sqrt(2);
286
+
287
+switch base_no
288
+  case 1
289
+    x=(coords-A)*const;
290
+    coords=[(1/sqrt(2))*(x(1)-x(2));0.5*(x(1)+x(2));0.5*(x(1)+x(2))];
291
+  case 2
292
+    x=(coords-H)*const;
293
+    coords=[0;x(1);1+x(2)];
294
+  case 3
295
+    x=(coords-G)*const;
296
+    coords=[1;1+x(1);x(2)];
297
+  case 4
298
+    x=(coords-F)*const;
299
+    coords=[0.5+(1/sqrt(2))*(x(1)-x(2));...
300
+            0.5-(1/sqrt(2))*(x(1)+x(2));... 
301
+            0];
302
+  case 5
303
+    x=(coords-E)*const;
304
+    coords=[0.5+(1/sqrt(2))*(x(1)-x(2));...
305
+            0.5-(1/sqrt(2))*(x(1)+x(2));...      
306
+            1];
307
+end
308
+
309
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
310
+
311
+function y=line1(x)
312
+  
313
+y = x-1/(sqrt(2)+1);
314
+
315
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
316
+
317
+function y=line2(x)
318
+
319
+y = x+1/(sqrt(2)+1);
320
+ 
321
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
322
+
323
+function y=line3(x)
324
+
325
+y = -x+1/(sqrt(2)+1);
326
+
327
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
328
+
329
+function y= line4(x)
330
+
331
+y = -x+(2*sqrt(2)+1)/(sqrt(2)+1);
332
+
333
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
... ...
@@ -0,0 +1,98 @@
1
+function Col = som_coloring(sM,ncol,chaingap,dw)
2
+
3
+% SOM_COLORING Make a SOM-based coloring for given data/map.
4
+%
5
+% Col = som_coloring(sM,[ncol],[chaingap],[dw])
6
+% 
7
+%  Col = som_coloring(sM,5);
8
+%  som_show(sM,'color',Col); 
9
+%
10
+% Input and output arguments ([]'s are optional):
11
+%  sM          (struct) map or data struct
12
+%              (matrix) data matrix
13
+%  [ncol]      (scalar) number of colors to use
14
+%  [chaingap]  (scalar) size of gap in the color circle (see below), 
15
+%                       0.1 by default
16
+%  [dw]        (scalar) 1 = use input space distances to stretch
17
+%                           the color circle (default) 
18
+%                       0 = don't use
19
+%
20
+%  Col         (matrix) color for each data/codebook vector
21
+%
22
+% This function trains a 1-dimensional SOM using the input data
23
+% (codebook of a SOM, or a set of data vectors). A color from the 
24
+% color circle (see HSV function) is associated with each map unit, 
25
+% and each data/codebook vector of the input data picks its color
26
+% from its BMU on the 1-dimensional SOM. 
27
+%
28
+% If the chaingap argument == 0, the 1-dimensional map has a cylinder
29
+% (in effect, a ring) topology. Otherwise, the topology is rectangular
30
+% (in effect, a chain). 
31
+%
32
+% The colors are mapped to the 1-dimensional SOM simply by picking colors
33
+% from the color circle. If chaingap>0, a slice of the color circle is
34
+% removed before map units pick their colors from it. This creates a
35
+% discontiuity in the coloring at the ends of the 1-dimensional SOM.
36
+%
37
+% If the dw argument == 0, the colors are picked from the color circle
38
+% equidistantly. If not, the distances between the prototype vectors
39
+% in the 1-dimensional SOM are taken into account.
40
+%
41
+% See also SOM_KMEANSCOLOR, SOM_KMEANSCOLOR2, SOM_FUZZYCOLOR.
42
+
43
+% Contributed to SOM Toolbox 2.0, December 21st, 2001 by Juha Vesanto 
44
+% http://www.cis.hut.fi/projects/somtoolbox/             
45
+
46
+% Version 2.0beta juuso 211201
47
+
48
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
49
+
50
+if isstruct(sM), 
51
+  if strcmp(sM.type,'som_map'), ismap = 1; D = sM.codebook; 
52
+  else ismap = 0; D = sM.data; 
53
+  end
54
+else ismap = 0; D = sM; 
55
+end
56
+
57
+if nargin<2 | isempty(ncol) | isnan(ncol), ncol = min(64,size(D,1)); end
58
+if nargin<3 | isempty(chaingap) | isnan(chaingap), chaingap = 0.1; end
59
+if nargin<4 | isempty(dw) | isnan(dw), dw = 1; end
60
+
61
+if chaingap == 0, lattice = 'sheet'; else lattice = 'cyl'; end
62
+sMring = som_make(D,'msize',[1,ncol],lattice,'tracking',0);
63
+b = som_bmus(sMring,D);
64
+
65
+Colmap = hsv(ceil(ncol*(1+chaingap))); 
66
+Colmap = Colmap(1:ncol,:);
67
+
68
+if dw, % take distances in input space into account
69
+  dist = sqrt(sum((sMring.codebook-sMring.codebook([2:end 1],:)).^2,2));  
70
+  ind  = round([0; cumsum(dist)/sum(dist)]*(ncol-1)) + 1;
71
+  Colmap = Colmap(ind,:);
72
+end  
73
+Col = Colmap(b,:); 
74
+
75
+return; 
76
+
77
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
78
+
79
+% visualization
80
+  if ismap, 
81
+    a = som_bmus(sM.codebook,sMring.codebook); 
82
+    if chaingap==0, a(end+1) = a(1); end
83
+    som_show(sM,'color',Col); 
84
+    som_show_add('traj',a) 
85
+  else
86
+    i = find(sum(isnan(D),2)==0); 
87
+    [P,V,me] = pcaproj(D(i,:),2); 
88
+    Pr = pcaproj(sMring.codebook,V,me);
89
+    a = som_bmus(D(i,:),sMring.codebook); % Pr = P(a,:);
90
+    som_grid({'rect',[length(i) 1]},'line','none',...
91
+             'coord',P,'markercolor',Col(i,:));
92
+    hold on
93
+    if chaingap==0, Pr(end+1,:) = Pr(1,:); end
94
+    som_grid({'rect',[size(Pr,1) 1]},'linecolor','k',...
95
+             'linewidth',2,'markercolor','k','coord',Pr);
96
+  end
97
+
98
+
... ...
@@ -0,0 +1,173 @@
1
+function C=som_connection(S)
2
+
3
+%SOM_CONNECTION Connection matrix for 'hexa' and 'rect' lattices
4
+%
5
+% C=som_connection(S)
6
+%
7
+%  C=som_connection(sMap);
8
+%  C=som_connection(sTopol);
9
+%  C=som_connection({'hexa', [6 5], 'sheet'});
10
+%
11
+% Input and output arguments:
12
+%  S    (struct) map or topol struct
13
+%       (cell array) a cell array of form {lattice, msize, shape}, where
14
+%                lattice: 'hexa' or 'rect'
15
+%                msize  : 1x2 vector
16
+%                shape  : 'sheet', 'cyl or 'toroid' 
17
+%
18
+%  C    (sparse) An NxN connection matrix, N=prod(msize)
19
+%
20
+% The function returns a connection matrix, e.g., for drawing
21
+% connections between map units in the function som_grid. Note that
22
+% the connections are defined only in the upper triangular part to
23
+% save some memory!! Function SOM_UNIT_NEIGHS does the same thing, 
24
+% but also has values in the lower triangular. It is also slower.
25
+%
26
+% For more help, try 'type som_connection' or check out online documentation.
27
+% See also SOM_GRID, SOM_UNIT_NEIGHS.
28
+
29
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
30
+%
31
+% som_connection
32
+%
33
+% PURPOSE
34
+% 
35
+%  To create a connection matrix of SOM 'hexa' and 'rect' negihborhoods
36
+%
37
+% SYNTAX
38
+%
39
+%  C = som_connection(S)
40
+%
41
+% DESCRIPTION
42
+%
43
+%  Creates a connection matrix of SOM 'hexa' and 'rect'
44
+%  neighborhoods. The connections are defined only in the upper
45
+%  triangular part to save some memory.
46
+%  
47
+%  Function SOM_UNIT_NEIGHS does the same thing, but also has values
48
+%  in the lower triangular. It is also slower, except for 
49
+%  'toroid' shape because in that case this function calls 
50
+%  SOM_UNIT_NEIGHS...
51
+%
52
+% REQUIRED INPUT ARGUMENTS
53
+%  
54
+%  S                 map topology 
55
+%    (map struct)    S.topol is used to build the matrix
56
+%    (topol struct)  topology information is used to build the matrix
57
+%    (cell array)    of form {lattice, msize, shape}, where
58
+%                     lattice: 'hexa' or 'rect'
59
+%                     msize  : 1x2 vector
60
+%                     shape  : 'sheet', 'cyl or 'toroid' 
61
+%
62
+% OUTPUT ARGUMENTS
63
+%
64
+%  C (sparse)        munits x munits sparse matrix which describes 
65
+%                    nearest neighbor connections between units
66
+%
67
+% EXAMPLE 
68
+%
69
+% C = som_connection('hexa',[3 4],'sheet');
70
+% full(C)
71
+% ans =
72
+%
73
+%      0     1     0     1     0     0     0     0     0     0     0     0
74
+%      0     0     1     1     1     1     0     0     0     0     0     0
75
+%      0     0     0     0     0     1     0     0     0     0     0     0
76
+%      0     0     0     0     1     0     1     0     0     0     0     0
77
+%      0     0     0     0     0     1     1     1     1     0     0     0
78
+%      0     0     0     0     0     0     0     0     1     0     0     0
79
+%      0     0     0     0     0     0     0     1     0     1     0     0
80
+%      0     0     0     0     0     0     0     0     1     1     1     1
81
+%      0     0     0     0     0     0     0     0     0     0     0     1
82
+%      0     0     0     0     0     0     0     0     0     0     1     0
83
+%      0     0     0     0     0     0     0     0     0     0     0     1
84
+%      0     0     0     0     0     0     0     0     0     0     0     0
85
+%
86
+% SEE ALSO
87
+% 
88
+% som_grid         Visualization of a SOM grid
89
+% som_unit_neighs  Units in 1-neighborhood for all map units.
90
+
91
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
92
+% http://www.cis.hut.fi/projects/somtoolbox/             
93
+
94
+% Version 2.0alpha Johan 061099 juuso 151199 170400
95
+
96
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
97
+% Check arguments
98
+
99
+error(nargchk(1, 1, nargin));   % check number of input arguments
100
+
101
+[tmp,ok,tmp]=som_set(S);
102
+if isstruct(S) & all(ok),       % check m type
103
+  switch S.type
104
+  case 'som_topol' 
105
+    msize=S.msize;
106
+    lattice=S.lattice;
107
+    shape=S.shape;
108
+  case 'som_map'  
109
+    msize=S.topol.msize;
110
+    lattice=S.topol.lattice;
111
+    shape=S.topol.shape;
112
+  otherwise
113
+    error('Invalid map or topol struct.');
114
+  end
115
+elseif iscell(S),
116
+  if vis_valuetype(S,{'topol_cell'}),
117
+    lattice=S{1};
118
+    msize=S{2}; 
119
+    shape=S{3}; 
120
+  else
121
+    error('{lattice, msize, shape} expected for cell input.')
122
+  end
123
+else
124
+  error('{lattice, msize, shape}, or map or topol struct expected.')
125
+end
126
+
127
+if ~vis_valuetype(msize,{'1x2'})
128
+  error('Invalid map size: only 2D maps allowed.')
129
+end  
130
+
131
+%% Init %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
132
+
133
+N=msize(1)*msize(2);
134
+
135
+%% Action & Build output arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
136
+
137
+switch lattice
138
+case 'hexa'
139
+  l1=ones(N,1); l1((msize(1)+1):msize(1):end)=0;
140
+  l2=zeros(msize(1),1); l3=l2;
141
+  l2(1:2:end-1)=1; l3(3:2:end)=1;
142
+  l2=repmat(l2,msize(2),1); 
143
+  l3=repmat(l3,msize(2),1);
144
+  C= ...
145
+    spdiags([l1 l2 ones(N,1) l3], [1 msize(1)-1:msize(1)+1],N,N);
146
+case 'rect'
147
+  l1=ones(N,1);l1((msize(1)+1):msize(1):end)=0;
148
+  C=spdiags([l1 ones(N,1)],[1 msize(1)],N,N);
149
+otherwise
150
+  error('Unknown lattice.')
151
+end
152
+
153
+switch shape
154
+case 'sheet'
155
+  ;
156
+case 'cyl'
157
+  C=spdiags(ones(N,1),msize(1)*(msize(2)-1),C);
158
+case 'toroid'
159
+  %warning('Toroid not yet implemented: using ''cyl''.');
160
+  %C=spdiags(ones(N,1),msize(1)*(msize(2)-1),C);
161
+  %l=zeros(N,1); l(1:msize(2):end)=1;
162
+  %C=spdiags(l,msize(1),C);
163
+
164
+  % use som_unit_neighs to calculate these
165
+  C = som_unit_neighs(msize,lattice,'toroid');
166
+  % to be consistent, set the lower triangular values to zero
167
+  munits = prod(msize);
168
+  for i=1:(munits-1), C((i+1):munits,i) = 0; end
169
+otherwise
170
+  error('Unknown shape.');
171
+end
172
+
173
+
... ...
@@ -0,0 +1,470 @@
1
+function h=som_cplane(varargin) 
2
+
3
+%SOM_CPLANE Visualize one 2D component plane, U-matrix or color plane.
4
+%
5
+% h=som_cplane(lattice, msize, color, [s], [pos]) 
6
+% h=som_cplane(topol, color, [s], [pos]) 
7
+%
8
+%  som_cplane('hexa', [10 5], 'none');
9
+%  som_cplane('rect', [10 5], 'r');
10
+%  som_cplane(sM.topol, sM.codebook(:,1));
11
+%  U = som_umat(sM); som_cplane('hexaU',sM.topol.msize,U(:));
12
+%
13
+%  Input and output arguments ([]'s are optional): 
14
+%   lattice   (string) 'hexa', 'rect' (component planes)
15
+%                      'hexaU', 'rectU' (corresponding U-matrices)
16
+%             (matrix) defines the patch (see function VIS_PATCH).
17
+%   msize     (vector) 1x2 vector defines grid size (M=prod(msize))
18
+%             (matrix) Mx2 matrix gives explicit coordinates for each node
19
+%   topol     (struct) map or topology struct
20
+%   color              color for the nodes
21
+%             (matrix) Mx1 matrix gives indexed colors for the units
22
+%                      Mx3 matrix of RGB triples gives explicit
23
+%                      color for each unit
24
+%                      (Note: in case of U-matrix, the number of color
25
+%                      values is 4*prod(msize)-2*sum(msize)+1, not prod(msize))
26
+%             (string) ColorSpec gives the same color for each node
27
+%                      'none' draws black edges only.              
28
+%   [s]       (matrix) size Mx1, gives individual size scaling for each node 
29
+%             (scalar) gives the same size for each node, default=1.
30
+%                      Additional features: see 'type som_cplane' 
31
+%                      This argument is ignored if the lattice is 'rectU' or 'hexaU'.
32
+%   [pos]     (vector) a 1x2 vector that determines position of origin, 
33
+%                      default is [1 1].
34
+%
35
+%   h         (scalar) the object handle for the PATCH object
36
+%
37
+% Axis are set to the 'ij' mode with equal spacing and turned off if
38
+% 'pos' is not given. If 'lattice' is 'rect', 'hexa', 'rectU' or
39
+% 'hexaU' the node (a,b) has coordinates (a,b) (+pos), except on the
40
+% even numbered rows on the 'hexa' and 'hexaU' grids where the
41
+% coordinates are (a,b+0.5) (+pos).
42
+%
43
+% For more help, try 'type som_cplane' or check out online documentation.
44
+% See also SOM_PIEPLANE, SOM_PLOTPLANE, SOM_BARPLANE, VIS_PATCH,
45
+%          SOM_VIS_COORDS
46
+
47
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
48
+%
49
+% som_cplane
50
+%
51
+% PURPOSE
52
+% 
53
+% Visualizes a 2D component plane or u-matrix
54
+%
55
+% SYNTAX
56
+%
57
+%  h = som_cplane(topol, color)
58
+%  h = som_cplane(lattice, msize, color)
59
+%  h = som_cplane(lattice, msize, color)
60
+%  h = som_cplane(..., size) 
61
+%  h = som_cplane(..., size, pos) 
62
+%
63
+% DESCRIPTION
64
+%
65
+% Creates some basic visualizations of the SOM grid: the component plane and
66
+% the unified distance matrix. The routine draws the SOM grid as a patch
67
+% object according to the specifications given in the input arguments and
68
+% returns its object handle.
69
+% 
70
+% Each unit of the map is presented by a polygon whose color, size, shape
71
+% and location can be specified in various ways. The usual procedure 
72
+% is to choose the lattice and map size used in the map training. Then
73
+% the function creates the standard sheet shaped topological 
74
+% representation of the map grid with hexagonal or rectangular units.
75
+% When the values from a map codebook component (or from SOM_UMAT) 
76
+% are given to the function it produces an indexed coloring for the 
77
+% units (as in SURF command). Another possibility is to give a fixed 
78
+% RGB color for each unit explicitly.
79
+% 
80
+% Special effects (variable unit size, location or shape) can be produced
81
+% giving different types of input variables.
82
+%
83
+% KNOWN BUGS
84
+%
85
+% Using 1x3 or 3x1 grids causes problem, as the MATLAB will treat the color 
86
+% information vector 1x3 or 3x1 as a single RGB triple. So, using indexed 
87
+% colors is not possible for this particular map size.
88
+%
89
+% It is not possible to specify explicit coordinates for map
90
+% consistig of just one unit as then the msize is interpreted as
91
+% map size.
92
+%
93
+% REQUIRED INPUT ARGUMENTS
94
+% 
95
+% Note: M is the number of map units
96
+%
97
+% lattice  The basic shape of the map units 
98
+%
99
+%   (string) 'hexa' or 'rect' creates standard component plane; 
100
+%            'hexaU' or 'rectU' creates standard u-matrix.
101
+%   (matrix) Lx2 matrix defines the cornes of an arbitary polygon to be used
102
+%            as the unit marker. (L is the number of patch vertex: L=6 for 
103
+%            'hexa' and L=4 for 'rect') 
104
+%
105
+% msize    The size of the map grid     
106
+%         
107
+%   (vector) [n1 n2] vector defines the map size (height n1 units, width 
108
+%            n2 units, total M=n1 x n2 units). The units will be placed to their 
109
+%            topological locations to form a uniform hexagonal or rectangular grid.
110
+%   (matrix) Mx2 matrix defines arbitrary coordinates for the M units
111
+%            In this case the argument 'lattice' defines the unit form only. 
112
+%
113
+% topol    Topology of the map grid
114
+%
115
+%   (struct) map or topology struct from which the topology is taken
116
+% 
117
+% color    Unit colors
118
+%           
119
+%   (string) (ColorSpec) gives the same color for each unit, 'none'
120
+%            draws black unit edges only.
121
+%   (vector) Mx1 column vector gives indexed color for each unit using the 
122
+%            current colormap (see help colormap).   
123
+%   (matrix) Mx3 matrix of RGB triples as rows gives each unit a fixed color.
124
+%
125
+% OPTIONAL INPUT ARGUMENTS
126
+%
127
+% Note: M is the number of map units. 
128
+% Note: if unspecified or given empty values ('' or []) default
129
+% values are used for optional input arguments.
130
+% 
131
+% s        The size scaling factors for the units
132
+% 
133
+%   (scalar) scalar gives each unit the same size scaling: 
134
+%            0   unit disappears (edges can be seen as a dot).
135
+%            1   by default unit has its normal size (ie. no scaling)
136
+%            >1  unit overlaps others      
137
+%   (matrix) Mx1 double: each unit gets individual size scaling
138
+%
139
+% pos      Position of origin          
140
+% 
141
+%   (vector) This argument exists to be able drawing component planes
142
+%            in arbitrary locations in a figure. Note the operation:
143
+%            if this argument is given, the axis limits setting
144
+%            part in the routine is skipped and the limits setting
145
+%            will be left to be done by MATLAB's default
146
+%            operation. 
147
+%
148
+% OUTPUT ARGUMENTS
149
+%
150
+% h (scalar) handle to the created patch object
151
+% 
152
+% OBJECT TAGS     
153
+%
154
+% One object handle is returned: field Tag is set to
155
+%  'planeC'  for component plane     
156
+%  'planeU'  for U-matrix
157
+%
158
+% FEATURES
159
+%
160
+% There are some extra features in following arguments
161
+%
162
+% size
163
+%  - MxL matrix: radial scaling: the distance between 
164
+%    the center of node m and its kth vertex is scaled by
165
+%    s(m,k).
166
+%  - Mx1x2 matrix: the uniform scaling is done separately for
167
+%    x- and y-directions
168
+%  - MxLx2 matrix: the scaling is done separately to x- and y-
169
+%    directions for each vertex.
170
+%
171
+% color
172
+%    Each vertex may be given individual color. 
173
+%    The PATCH object interpolates the colors on the 
174
+%    face if shading is turned to interp. 
175
+%  - 1xMxL matrix: colormap index for each vertex
176
+%  - LxMx3 matrix: RGB color for each vertex
177
+%
178
+% Note: In both cases (size and color) the ordering of the patch
179
+% vertices in the "built-in" patches is the following
180
+%
181
+%          'rect'      'hexa'
182
+%            1 3          1 
183
+%            2 4         5 2
184
+%                        6 3
185
+%                         4
186
+%
187
+% The color interpolation result seem to depend on the order 
188
+% in which the patch vertices are defined. Anyway, it gives 
189
+% unfavourable results in our case especially with hexa grid: 
190
+% this is a MATLAB feature.
191
+%
192
+% EXAMPLES
193
+%
194
+% m=som_make(rand(100,4),'msize',[6 5])         % make a map
195
+% 
196
+% % show the first variable plane using indexed color coding
197
+%          
198
+% som_cplane(m.topol.lattice,m.topol.msize,m.codebook(:,1));  
199
+% or som_cplane(m.topol,m.codebook(:,1));  
200
+% or som_cplane(m,m.codebook(:,1));  
201
+%
202
+% % show the first variable using different sized black units
203
+%  
204
+% som_cplane(m,'k',m.codebook(:,1));
205
+% 
206
+% % Show the u-matrix. First we have to calculate it. 
207
+% % Note: som_umat returns a matrix therefore we write u(:) to get 
208
+% % a vector which contains the values in the proper order.
209
+% 
210
+% u=som_umat(m); 
211
+% som_cplane('hexaU', m.topol.msize, u(:)); 
212
+%
213
+% % Show three first variables coded as RGB colors
214
+% % and turn the unit edges off
215
+% 
216
+% h=som_cplane(m, m.codebook(:,1:3),1)
217
+% set(h,'edgecolor','none');
218
+%
219
+% % Try this! (see section FEATURES)
220
+% 
221
+% som_cplane('rect',[5 5],'none',rand(25,4));
222
+% som_cplane('rect',[5 5],rand(1,25,4));
223
+%
224
+% SEE ALSO
225
+%
226
+% som_barplane   Visualize the map prototype vectors as bar diagrams
227
+% som_plotplane  Visualize the map prototype vectors as line graphs
228
+% som_pieplane   Visualize the map prototype vectors as pie charts
229
+% som_umat       Compute unified distance matrix of self-organizing map
230
+% vis_patch      Define the basic patches used in som_cplane
231
+% som_vis_coords The default 'hexa' and 'rect' coordinates in visualizations
232
+
233
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
234
+% http://www.cis.hut.fi/projects/somtoolbox/             
235
+
236
+% Version 2.0beta Johan 061099 juuso 151199 juuso 070600
237
+
238
+%%% Check & Init  arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
239
+
240
+[nargin, lattice, msize, color, s, pos]=vis_planeGetArgs(varargin{:});
241
+error(nargchk(3, 5, nargin));  % check no. of input args is correct
242
+
243
+%% Translation?
244
+
245
+if nargin < 5 | isempty(pos)
246
+  pos=NaN;              % "no translation" flag
247
+elseif ~vis_valuetype(pos,{'1x2'}),
248
+  error('Position of origin has to be given as an 1x2 vector.');
249
+end
250
+
251
+%% Patchform %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
252
+
253
+switch class(lattice)
254
+case 'char'             % built-in patchforms
255
+  pos=pos-1;
256
+  switch lattice
257
+  case {'hexa', 'hexaU'}
258
+    patchform=vis_patch('hexa');
259
+  case {'rect', 'rectU'}
260
+    patchform=vis_patch('rect');
261
+  otherwise
262
+    error([ 'Lattice ' lattice ' not implemented!']);
263
+  end
264
+case { 'double', 'sparse'}
265
+  if vis_valuetype(lattice,{'nx2'}),
266
+    patchform=lattice; % users patchform
267
+    lattice='rect';    
268
+  else
269
+    error('Patchform matrix has wrong size');
270
+  end
271
+otherwise
272
+  error('String or matrix expected for lattice.');
273
+end
274
+
275
+l=size(patchform,1);     % number of vertices    
276
+planeType=lattice(end);  % 'U' if umatrix otherwise something else
277
+
278
+if ~vis_valuetype(msize,{ '1x2', 'nx2'}),
279
+  error('msize has to be given as 1x2 or nx2 vectors.');
280
+end
281
+
282
+%% msize or coordinates %%%%%%%%%%%%%%%%%%%%%%%
283
+
284
+if size(msize,1)>1 
285
+  % msize is coordinate matrix Nx2?
286
+  
287
+  if planeType == 'U',  % don't accept u-matrix
288
+    error('U-matrix visualization doesn''t work with free coordinates.');
289
+  end
290
+  
291
+  % set number of map unit and unit coordinates 
292
+  munits=size(msize,1);
293
+  unit_coords=msize; msize=[munits 1];
294
+  
295
+  if isnan(pos),         % no translation is done here 
296
+    pos=[0 0];           % using [0 0] in order to prevent 
297
+  end	                 % axis tightening in
298
+                         % vis_PlaneAxisProperties (arbitary coords!) 
299
+else
300
+  % msize is built-in lattice
301
+  
302
+  unit_coords=som_vis_coords(lattice,msize);
303
+  
304
+  % Calculate matrices x and y which 'moves' nodes 
305
+  % to the correct positions:
306
+  % For U-matrix, the size has to be recalculated
307
+  if planeType == 'U',
308
+    xdim=2*msize(1)-1;ydim=2*msize(2)-1;
309
+  else
310
+    xdim=msize(1);ydim=msize(2);
311
+  end
312
+  munits=xdim*ydim;
313
+  
314
+  % Feature warning
315
+  if munits == 3  
316
+    warning('Problems with 1x3 and 3x1 maps. See documentation.');
317
+  end
318
+end
319
+
320
+%% Color matrix %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
321
+
322
+if ~isnumeric(color) & ~ischar(color),
323
+  error('Color matrix is invalid.');
324
+else
325
+  d=size(color);           
326
+  switch length(d)       
327
+  case 2   %% Flat colors
328
+    if ischar(color) % Check for string 'none'
329
+      if strcmp(color,'none'), 
330
+	color=NaN;
331
+      end
332
+    else               
333
+      if ~(d(1)== 1 & d(2) == 3) & ...
334
+	    ~(d(1) == munits & (d(2)==1 | d(2)==3))
335
+	error('Color data matrix has wrong size.');
336
+      elseif d(1)~=1 & d(2)==3 
337
+	if any(color>1 | color<0)
338
+	  error('Color data matrix has invalid RGB values.');
339
+	end
340
+	color=reshape(color,[1 munits 3]);  % RGB colors
341
+      elseif d(2)==1
342
+	color=color';                       % indexed
343
+      end
344
+    end
345
+  case 3   %% Interpolated colors
346
+    if d(1) == 1 & d(2) == munits & d(3) == l,  
347
+      color=reshape(color, l, munits);
348
+    elseif ~(d(1) == l & d(2) == munits & d(3) == 3) 
349
+      error('Color data matrix has wrong size.');
350
+    end
351
+  otherwise
352
+    error('Color data matrix has too many dimensions.');
353
+  end
354
+end
355
+
356
+%% Size matrix? %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
357
+
358
+if nargin < 4 | isempty(s),  
359
+   s=1;      % default value for s (no scaling)
360
+elseif ~isnumeric(s)
361
+  error('Size matrix is not numeric.');
362
+end
363
+
364
+%%Determine the type of size matrix
365
+d=size(s);                  
366
+switch length(d)
367
+case 2  
368
+  if (d(1)==1 & d(2)==1),
369
+    % Each node gets the same, uniform scaling.
370
+    s=s'; sx=s; sy=s;	
371
+  elseif (d(1)==munits & d(2)==l),
372
+    % Each vertex is scaled radially respetc to the 
373
+    % node center.
374
+    s=s'; sx=s; sy=s;          
375
+  elseif d(1)==munits & d(2)==1  
376
+    % Each node gets an individual uniform scaling.
377
+    sx=repmat(s',l,1); sy=sx;
378
+  else
379
+    error('Size matrix has wrong size.');
380
+  end
381
+case 3  
382
+  if d(1)==munits & d(2)==1 & d(3)==2,     
383
+    % Each node is individually and uniformly 
384
+    % scaled separately to x- and y-directions.
385
+    sx=repmat(shiftdim(s(:,:,1))',l,1);   
386
+    sy=repmat(shiftdim(s(:,:,2))',l,1);   
387
+  elseif d(1)==munits & d(2)==l & d(3)==2,
388
+    % Each vertex is scaled separately to x- and y-directions
389
+    % with respect to the node center.
390
+    sx=shiftdim(s(:,:,1))';                
391
+    sy=shiftdim(s(:,:,2))';              
392
+  else
393
+    error('Size matrix has wrong size.');
394
+  end
395
+otherwise 
396
+  error('Size matrix has too many dimensions.');
397
+end
398
+
399
+% Size zero would cause division by zero. eps is as good (node disappears)
400
+% I tried first NaN, it works well otherwise, but the node is 
401
+% then not on the axis and some commands may the work oddly. 
402
+% The edge may be visible, though.
403
+
404
+sx(sx==0)=eps;                    
405
+sy(sy==0)=eps;                
406
+
407
+% Rescale sizes for u-matrix
408
+if planeType=='U', 
409
+   sx=sx/2;sy=sy/2; 
410
+end
411
+
412
+%%%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
413
+
414
+% Making grid. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
415
+
416
+% Translation for each patch
417
+
418
+x=repmat(unit_coords(:,1)',l,1);
419
+y=repmat(unit_coords(:,2)',l,1);
420
+
421
+% patch vertex coordiantes 
422
+
423
+nx=repmat(patchform(:,1),1,munits); 
424
+ny=repmat(patchform(:,2),1,munits); 
425
+
426
+% NB: The hexagons are not uniform in order to get even  
427
+% y-coordinates for the nodes. This is handled by setting _axis scaling_ 
428
+% so that the hexa-nodes look like uniform hexagonals. See 
429
+% vis_PlaneAxisProperties
430
+
431
+%% Make and scale the final input for PATCH:
432
+
433
+% 1: combine translation and scaling of each patch 
434
+x=(x./sx+nx).*sx; y=(y./sy+ny).*sy;  
435
+
436
+%% 2: translation of origin (pos)
437
+if ~isnan(pos)
438
+   x=x+pos(1);y=y+pos(2);    % move upper left corner 
439
+end                         % to pos
440
+
441
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
442
+
443
+%% Set axes properties  
444
+%% Command view([0 90]) shows the map in 2D properly oriented
445
+
446
+ax=newplot;                               % set new plot
447
+vis_PlaneAxisProperties(ax,lattice,msize,pos);
448
+
449
+%% Draw the map! 
450
+
451
+if ~isnan(color)
452
+   h_=patch(x,y,color);         
453
+else
454
+   h_=patch(x,y,'k');                     % empty grid 
455
+   set(h_,'FaceColor','none');
456
+end
457
+
458
+%% Set object tag
459
+
460
+if planeType=='U'
461
+   set(h_,'Tag','planeU');                      
462
+else
463
+   set(h_,'Tag','planeC');
464
+end	
465
+
466
+%%% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
467
+
468
+if nargout>0, h=h_; end                   % Set h only, 
469
+                                          % if there really is output
470
+
... ...
@@ -0,0 +1,173 @@
1
+function sData = som_data_struct(D, varargin)
2
+
3
+%SOM_DATA_STRUCT Create a data struct.
4
+%
5
+% sData = som_data_struct(D, [argID, value, ...])
6
+%
7
+%  sData  = som_data_struct(D); 
8
+%  sData  = som_data_struct(D,'name','my_data','labels',labs);
9
+%
10
+%  Input and output arguments ([]'s are optional): 
11
+%   D        (matrix) data matrix, size dlen x dim
12
+%   [argID,  (string) See below. These are given as argID, value pairs.
13
+%    value]  (varies) 
14
+%
15
+%   sData    (struct) created data struct
16
+%
17
+%  Here are the argument IDs and corresponding values: 
18
+%   'labels'     (string array / cellstr) labels for each data vector,
19
+%                 length=dlen
20
+%   'name'       (string) data name
21
+%   'comp_names' (string array / cellstr) component names, size dim x 1
22
+%   'comp_norm'  (cell array) normalization operations for each
23
+%                 component, size dim x 1. Each cell is either empty, 
24
+%                 or a cell array of normalization structs.
25
+%
26
+% For more help, try 'type som_data_struct' or check out online documentation.
27
+% See also SOM_SET, SOM_INFO, SOM_MAP_STRUCT.
28
+
29
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
30
+%
31
+% som_data_struct   
32
+%
33
+% PURPOSE
34
+%
35
+% Creates a data structure. 
36
+%
37
+% SYNTAX
38
+%
39
+%  sD = som_data_struct(D);
40
+%  sD = som_data_struct(...,'argID',value,...);
41
+%
42
+% DESCRIPTION
43
+%
44
+% Creates a data struct. The struct contains, in addition to the data
45
+% matrix, component names, normalization operations for the components,
46
+% labels for each vector, and a name for the whole data set. All of these
47
+% can be given in the optional arguments of the function. If left
48
+% unspecified, they are given default values. 
49
+%
50
+%  Field         Type         Size / default value    
51
+%  ------------------------------------------------------------------------
52
+%   .type        (string)     'som_data'               
53
+%   .data        (matrix)     size dlen x dim             
54
+%   .name        (string)     'unnamed'
55
+%   .labels      (cellstr)    size dlen x m, {''; ''; ... ''}
56
+%   .comp_names  (cellstr)    size dim x 1, {'Variable1', 'Variable2', ...}
57
+%   .comp_norm   (cell array) size dim x 1, {[], [], ... []}
58
+%   .label_names (cellstr)    size m x 1, []
59
+%                          
60
+% '.type' field is the struct identifier. Do not change it.
61
+% '.data' field is the data matrix, each row is one data vector
62
+% '.name' field is the identifier for the whole data struct
63
+% '.labels' field contains the labels for each of the vectors. The ith
64
+%         of '.labels' contains the labels for ith data vector. Note that 
65
+%         if some vectors have more labels than others, the others are
66
+%         are given empty labels ('') to pad the '.labels' array up.
67
+% '.comp_names' field contains the names of the vector components
68
+% '.comp_norm' field contains normalization information for each
69
+%         component. Each cell of '.comp_norm' is itself a cell array of
70
+%         normalization structs. If no normalizations are performed for 
71
+%         the particular component, the cell is empty ([]).
72
+% '.label_names' is similar to .comp_names field holding the names for
73
+%         each data label column
74
+%
75
+% REQUIRED INPUT ARGUMENTS
76
+%
77
+%  D  (matrix) The data matrix, size dlen x dim. The data matrix may 
78
+%              contain unknown values, indicated by NaNs. 
79
+%  
80
+% OPTIONAL INPUT ARGUMENTS 
81
+%
82
+%  argID (string) Argument identifier string (see below).
83
+%  value (varies) Value for the argument (see below).
84
+%
85
+%  The optional arguments can be given as 'argID',value -pairs as
86
+%  listed below. If an argument is given value multiple times, the
87
+%  last one is used.
88
+%
89
+%   'labels'     (string array / cellstr) labels for each data vector,
90
+%                 size dlen x m
91
+%   'name'       (string) data name
92
+%   'comp_names' (string array / cellstr) component names, size dim x 1
93
+%   'comp_norm'  (cell array) normalization operations for each
94
+%                 component, size dim x 1. Each cell is either empty, 
95
+%                 or a cell array of normalization structs.
96
+%   'label_names'(string array / cellstr) label names, size m x 1
97
+%
98
+% OUTPUT ARGUMENTS
99
+% 
100
+%  sD (struct) the data struct
101
+%
102
+% EXAMPLES
103
+%
104
+% Simplest case:
105
+%  D  = rand(8, 3); % 8 3-dimensional vectors
106
+%  sD = som_data_struct(D);
107
+%  
108
+% With optional arguments, the other fields can be given values:
109
+%  labs   = cell(8, 1); labs{1, 1} = 'first_label';
110
+%  cnames = {'first'; 'second'; 'third'};
111
+%  
112
+%  sD = som_data_struct(D,'labels',labs,'name','a data struct');
113
+%  sD = som_data_struct(D,'comp_names',cnames);
114
+%
115
+% SEE ALSO
116
+% 
117
+%  som_set          Set values and create SOM Toolbox structs.
118
+%  som_map_struct   Create a map struct.
119
+
120
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
121
+% http://www.cis.hut.fi/projects/somtoolbox/
122
+
123
+% Version 1.0beta ecco 071197
124
+% Version 2.0beta juuso 101199
125
+
126
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
127
+
128
+% data
129
+[dlen dim] = size(D);
130
+
131
+% default values
132
+if ~isempty(inputname(1)), name = inputname(1); 
133
+else name = 'unnamed'; end
134
+labels = cell(dlen,1);
135
+labels(1:dlen) = {''};
136
+%for i=1:dlen, labels{i} = ''; end
137
+comp_names = cell(dim,1);
138
+for i = 1:dim, comp_names{i} = sprintf('Variable%d', i); end
139
+comp_norm = cell(dim,1);
140
+label_names = []; 
141
+
142
+% varargin
143
+i=1; 
144
+while i<=length(varargin), 
145
+  argok = 1; 
146
+  if ischar(varargin{i}), 
147
+    switch varargin{i}, 
148
+      % argument IDs
149
+     case 'comp_names', i=i+1; comp_names = varargin{i}; 
150
+     case 'labels',     i=i+1; labels = varargin{i};
151
+     case 'name',       i=i+1; name = varargin{i};
152
+     case 'comp_norm',  i=i+1; comp_norm = varargin{i};
153
+     case 'label_names',i=i+1; label_names = varargin{i};
154
+     otherwise argok=0; 
155
+    end
156
+  else
157
+    argok = 0; 
158
+  end
159
+  if ~argok, 
160
+    disp(['(som_data_struct) Ignoring invalid argument #' num2str(i+1)]); 
161
+  end
162
+  i = i+1; 
163
+end
164
+
165
+% create struct
166
+sData = som_set('som_data','data',D,'labels',labels,...
167
+                          'name',name,'comp_names',comp_names,...
168
+                          'comp_norm',comp_norm,'label_names',label_names);
169
+
170
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
171
+
172
+
173
+
... ...
@@ -0,0 +1,294 @@
1
+
2
+%SOM_DEMO1 Basic properties and behaviour of the Self-Organizing Map.
3
+
4
+% Contributed to SOM Toolbox 2.0, February 11th, 2000 by Juha Vesanto
5
+% http://www.cis.hut.fi/projects/somtoolbox/
6
+
7
+% Version 1.0beta juuso 071197
8
+% Version 2.0beta juuso 030200 
9
+
10
+clf reset;
11
+figure(gcf)
12
+echo on
13
+
14
+
15
+
16
+clc
17
+%    ==========================================================
18
+%    SOM_DEMO1 - BEHAVIOUR AND PROPERTIES OF SOM
19
+%    ==========================================================
20
+
21
+%    som_make        - Create, initialize and train a SOM.
22
+%     som_randinit   - Create and initialize a SOM.
23
+%     som_lininit    - Create and initialize a SOM.
24
+%     som_seqtrain   - Train a SOM.
25
+%     som_batchtrain - Train a SOM.
26
+%    som_bmus        - Find best-matching units (BMUs).
27
+%    som_quality     - Measure quality of SOM.
28
+
29
+%    SELF-ORGANIZING MAP (SOM):
30
+
31
+%    A self-organized map (SOM) is a "map" of the training data, 
32
+%    dense where there is a lot of data and thin where the data 
33
+%    density is low. 
34
+
35
+%    The map constitutes of neurons located on a regular map grid. 
36
+%    The lattice of the grid can be either hexagonal or rectangular.
37
+
38
+subplot(1,2,1)
39
+som_cplane('hexa',[10 15],'none')
40
+title('Hexagonal SOM grid')
41
+
42
+subplot(1,2,2)
43
+som_cplane('rect',[10 15],'none')
44
+title('Rectangular SOM grid')
45
+
46
+%    Each neuron (hexagon on the left, rectangle on the right) has an
47
+%    associated prototype vector. After training, neighboring neurons
48
+%    have similar prototype vectors.
49
+
50
+%    The SOM can be used for data visualization, clustering (or 
51
+%    classification), estimation and a variety of other purposes.
52
+
53
+pause % Strike any key to continue...
54
+
55
+clf
56
+clc
57
+%    INITIALIZE AND TRAIN THE SELF-ORGANIZING MAP
58
+%    ============================================
59
+
60
+%    Here are 300 data points sampled from the unit square:
61
+
62
+D = rand(300,2);
63
+
64
+%    The map will be a 2-dimensional grid of size 10 x 10.
65
+
66
+msize = [10 10];
67
+
68
+%    SOM_RANDINIT and SOM_LININIT can be used to initialize the
69
+%    prototype vectors in the map. The map size is actually an
70
+%    optional argument. If omitted, it is determined automatically
71
+%    based on the amount of data vectors and the principal
72
+%    eigenvectors of the data set. Below, the random initialization
73
+%    algorithm is used.
74
+
75
+sMap  = som_randinit(D, 'msize', msize);
76
+
77
+%    Actually, each map unit can be thought as having two sets
78
+%    of coordinates: 
79
+%      (1) in the input space:  the prototype vectors
80
+%      (2) in the output space: the position on the map
81
+%    In the two spaces, the map looks like this: 
82
+
83
+subplot(1,3,1) 
84
+som_grid(sMap)
85
+axis([0 11 0 11]), view(0,-90), title('Map in output space')
86
+
87
+subplot(1,3,2) 
88
+plot(D(:,1),D(:,2),'+r'), hold on
89
+som_grid(sMap,'Coord',sMap.codebook)
90
+title('Map in input space')
91
+
92
+%    The black dots show positions of map units, and the gray lines
93
+%    show connections between neighboring map units.  Since the map
94
+%    was initialized randomly, the positions in in the input space are
95
+%    completely disorganized. The red crosses are training data.
96
+
97
+pause % Strike any key to train the SOM...
98
+
99
+%    During training, the map organizes and folds to the training
100
+%    data. Here, the sequential training algorithm is used:
101
+
102
+sMap  = som_seqtrain(sMap,D,'radius',[5 1],'trainlen',10);
103
+
104
+subplot(1,3,3)
105
+som_grid(sMap,'Coord',sMap.codebook)
106
+hold on, plot(D(:,1),D(:,2),'+r')
107
+title('Trained map')
108
+
109
+pause % Strike any key to view more closely the training process...
110
+
111
+
112
+clf
113
+
114
+clc
115
+%    TRAINING THE SELF-ORGANIZING MAP
116
+%    ================================
117
+
118
+%    To get a better idea of what happens during training, let's look
119
+%    at how the map gradually unfolds and organizes itself. To make it
120
+%    even more clear, the map is now initialized so that it is away
121
+%    from the data.
122
+
123
+sMap = som_randinit(D,'msize',msize);
124
+sMap.codebook = sMap.codebook + 1;
125
+
126
+subplot(1,2,1)
127
+som_grid(sMap,'Coord',sMap.codebook)
128
+hold on, plot(D(:,1),D(:,2),'+r'), hold off
129
+title('Data and original map')
130
+
131
+%    The training is based on two principles: 
132
+%     
133
+%      Competitive learning: the prototype vector most similar to a
134
+%      data vector is modified so that it it is even more similar to
135
+%      it. This way the map learns the position of the data cloud.
136
+%
137
+%      Cooperative learning: not only the most similar prototype
138
+%      vector, but also its neighbors on the map are moved towards the
139
+%      data vector. This way the map self-organizes.
140
+
141
+pause % Strike any key to train the map...
142
+
143
+echo off
144
+subplot(1,2,2)
145
+o = ones(5,1);
146
+r = (1-[1:60]/60);
147
+for i=1:60,
148
+  sMap = som_seqtrain(sMap,D,'tracking',0,...
149
+		      'trainlen',5,'samples',...
150
+		      'alpha',0.1*o,'radius',(4*r(i)+1)*o);
151
+  som_grid(sMap,'Coord',sMap.codebook)
152
+  hold on, plot(D(:,1),D(:,2),'+r'), hold off
153
+  title(sprintf('%d/300 training steps',5*i))
154
+  drawnow
155
+end
156
+title('Sequential training after 300 steps')
157
+echo on
158
+
159
+pause % Strike any key to continue with 3D data...
160
+
161
+clf
162
+
163
+clc
164
+%    TRAINING DATA: THE UNIT CUBE
165
+%    ============================
166
+
167
+%    Above, the map dimension was equal to input space dimension: both
168
+%    were 2-dimensional. Typically, the input space dimension is much
169
+%    higher than the 2-dimensional map. In this case the map cannot
170
+%    follow perfectly the data set any more but must find a balance
171
+%    between two goals:
172
+
173
+%      - data representation accuracy
174
+%      - data set topology representation accuracy    
175
+
176
+%    Here are 500 data points sampled from the unit cube:
177
+
178
+D = rand(500,3);
179
+
180
+subplot(1,3,1), plot3(D(:,1),D(:,2),D(:,3),'+r')
181
+view(3), axis on, rotate3d on
182
+title('Data')
183
+
184
+%    The ROTATE3D command enables you to rotate the picture by
185
+%    dragging the pointer above the picture with the leftmost mouse
186
+%    button pressed down.
187
+
188
+pause % Strike any key to train the SOM...
189
+
190
+
191
+
192
+
193
+clc
194
+%    DEFAULT TRAINING PROCEDURE
195
+%    ==========================
196
+
197
+%    Above, the initialization was done randomly and training was done
198
+%    with sequential training function (SOM_SEQTRAIN). By default, the
199
+%    initialization is linear, and batch training algorithm is
200
+%    used. In addition, the training is done in two phases: first with
201
+%    large neighborhood radius, and then finetuning with small radius.
202
+
203
+%    The function SOM_MAKE can be used to both initialize and train
204
+%    the map using default parameters:
205
+
206
+pause % Strike any key to use SOM_MAKE...
207
+
208
+sMap = som_make(D);
209
+
210
+%    Here, the linear initialization is done again, so that 
211
+%    the results can be compared.
212
+
213
+sMap0 = som_lininit(D); 
214
+
215
+subplot(1,3,2)
216
+som_grid(sMap0,'Coord',sMap0.codebook,...
217
+	 'Markersize',2,'Linecolor','k','Surf',sMap0.codebook(:,3)) 
218
+axis([0 1 0 1 0 1]), view(-120,-25), title('After initialization')
219
+
220
+subplot(1,3,3)
221
+som_grid(sMap,'Coord',sMap.codebook,...
222
+	 'Markersize',2,'Linecolor','k','Surf',sMap.codebook(:,3)) 
223
+axis([0 1 0 1 0 1]), view(3), title('After training'), hold on
224
+
225
+%    Here you can see that the 2-dimensional map has folded into the
226
+%    3-dimensional space in order to be able to capture the whole data
227
+%    space. 
228
+
229
+pause % Strike any key to evaluate the quality of maps...
230
+
231
+
232
+
233
+clc
234
+%    BEST-MATCHING UNITS (BMU)
235
+%    =========================
236
+
237
+%    Before going to the quality, an important concept needs to be
238
+%    introduced: the Best-Matching Unit (BMU). The BMU of a data
239
+%    vector is the unit on the map whose model vector best resembles
240
+%    the data vector. In practise the similarity is measured as the
241
+%    minimum distance between data vector and each model vector on the
242
+%    map. The BMUs can be calculated using function SOM_BMUS. This
243
+%    function gives the index of the unit.
244
+
245
+%    Here the BMU is searched for the origin point (from the
246
+%    trained map):
247
+
248
+bmu = som_bmus(sMap,[0 0 0]);
249
+
250
+%    Here the corresponding unit is shown in the figure. You can
251
+%    rotate the figure to see better where the BMU is.
252
+
253
+co = sMap.codebook(bmu,:);
254
+text(co(1),co(2),co(3),'BMU','Fontsize',20)
255
+plot3([0 co(1)],[0 co(2)],[0 co(3)],'ro-')
256
+
257
+pause % Strike any key to analyze map quality...
258
+
259
+
260
+
261
+
262
+clc
263
+%    SELF-ORGANIZING MAP QUALITY
264
+%    ===========================
265
+
266
+%    The maps have two primary quality properties:
267
+%      - data representation accuracy
268
+%      - data set topology representation accuracy
269
+
270
+%    The former is usually measured using average quantization error
271
+%    between data vectors and their BMUs on the map.  For the latter
272
+%    several measures have been proposed, e.g. the topographic error
273
+%    measure: percentage of data vectors for which the first- and
274
+%    second-BMUs are not adjacent units.
275
+
276
+%    Both measures have been implemented in the SOM_QUALITY function.
277
+%    Here are the quality measures for the trained map: 
278
+
279
+[q,t] = som_quality(sMap,D)
280
+
281
+%    And here for the initial map:
282
+
283
+[q0,t0] = som_quality(sMap0,D)
284
+
285
+%    As can be seen, by folding the SOM has reduced the average
286
+%    quantization error, but on the other hand the topology
287
+%    representation capability has suffered.  By using a larger final
288
+%    neighborhood radius in the training, the map becomes stiffer and
289
+%    preserves the topology of the data set better.
290
+
291
+
292
+echo off
293
+
294
+
... ...
@@ -0,0 +1,406 @@
1
+
2
+%SOM_DEMO2 Basic usage of the SOM Toolbox.
3
+
4
+% Contributed to SOM Toolbox 2.0, February 11th, 2000 by Juha Vesanto
5
+% http://www.cis.hut.fi/projects/somtoolbox/
6
+
7
+% Version 1.0beta juuso 071197 
8
+% Version 2.0beta juuso 070200
9
+
10
+clf reset;
11
+figure(gcf)
12
+echo on
13
+
14
+
15
+
16
+clc
17
+%    ==========================================================
18
+%    SOM_DEMO2 - BASIC USAGE OF SOM TOOLBOX
19
+%    ==========================================================
20
+
21
+%    som_data_struct    - Create a data struct.
22
+%    som_read_data      - Read data from file.
23
+%
24
+%    som_normalize      - Normalize data.
25
+%    som_denormalize    - Denormalize data.
26
+%
27
+%    som_make           - Initialize and train the map. 
28
+%
29
+%    som_show           - Visualize map.
30
+%    som_show_add       - Add markers on som_show visualization.
31
+%    som_grid           - Visualization with free coordinates.
32
+%
33
+%    som_autolabel      - Give labels to map.
34
+%    som_hits           - Calculate hit histogram for the map.
35
+
36
+%    BASIC USAGE OF THE SOM TOOLBOX
37
+
38
+%    The basic usage of the SOM Toolbox proceeds like this: 
39
+%      1. construct data set
40
+%      2. normalize it
41
+%      3. train the map
42
+%      4. visualize map
43
+%      5. analyse results
44
+
45
+%    The four first items are - if default options are used - very
46
+%    simple operations, each executable with a single command.  For
47
+%    the last, several different kinds of functions are provided in
48
+%    the Toolbox, but as the needs of analysis vary, a general default
49
+%    function or procedure does not exist. 
50
+
51
+pause % Strike any key to construct data...
52
+
53
+
54
+
55
+clc
56
+%    STEP 1: CONSTRUCT DATA
57
+%    ======================
58
+
59
+%    The SOM Toolbox has a special struct, called data struct, which
60
+%    is used to group information regarding the data set in one
61
+%    place.
62
+
63
+%    Here, a data struct is created using function SOM_DATA_STRUCT.
64
+%    First argument is the data matrix itself, then is the name 
65
+%    given to the data set, and the names of the components
66
+%    (variables) in the data matrix.
67
+
68
+D = rand(1000,3); % 1000 samples from unit cube
69
+sData = som_data_struct(D,'name','unit cube','comp_names',{'x','y','z'});
70
+			
71
+%    Another option is to read the data directly from an ASCII file.
72
+%    Here, the IRIS data set is loaded from a file (please make sure
73
+%    the file can be found from the current path):
74
+
75
+try, 
76
+  sDiris = som_read_data('iris.data');
77
+catch
78
+  echo off
79
+
80
+  warning('File ''iris.data'' not found. Using simulated data instead.')
81
+  
82
+  D = randn(50,4); 
83
+  D(:,1) = D(:,1)+5;     D(:,2) = D(:,2)+3.5; 
84
+  D(:,3) = D(:,3)/2+1.5; D(:,4) = D(:,4)/2+0.3;
85
+  D(find(D(:)<=0)) = 0.01; 
86
+  
87
+  D2 = randn(100,4); D2(:,2) = sort(D2(:,2));
88
+  D2(:,1) = D2(:,1)+6.5; D2(:,2) = D2(:,2)+2.8; 
89
+  D2(:,3) = D2(:,3)+5;   D2(:,4) = D2(:,4)/2+1.5;
90
+  D2(find(D2(:)<=0)) = 0.01; 
91
+  
92
+  sDiris = som_data_struct([D; D2],'name','iris (simulated)',...
93
+			  'comp_names',{'SepalL','SepalW','PetalL','PetalW'});
94
+  sDiris = som_label(sDiris,'add',[1:50]','Setosa');
95
+  sDiris = som_label(sDiris,'add',[51:100]','Versicolor');
96
+  sDiris = som_label(sDiris,'add',[101:150]','Virginica');
97
+  
98
+  echo on
99
+end
100
+
101
+%     Here are the histograms and scatter plots of the four variables.
102
+
103
+echo off 
104
+k=1;
105
+for i=1:4, 
106
+  for j=1:4, 
107
+    if i==j, 
108
+      subplot(4,4,k); 
109
+      hist(sDiris.data(:,i)); title(sDiris.comp_names{i})
110
+    elseif i<j, 
111
+      subplot(4,4,k); 
112
+      plot(sDiris.data(:,i),sDiris.data(:,j),'k.')
113
+      xlabel(sDiris.comp_names{i})
114
+      ylabel(sDiris.comp_names{j})
115
+    end
116
+    k=k+1;
117
+  end
118
+end
119
+echo on
120
+
121
+%     Actually, as you saw in SOM_DEMO1, most SOM Toolbox functions
122
+%     can also handle plain data matrices, but then one is without the
123
+%     convenience offered by component names, labels and
124
+%     denormalization operations.
125
+
126
+
127
+pause % Strike any key to normalize the data...
128
+
129
+
130
+
131
+
132
+
133
+clc
134
+%    STEP 2: DATA NORMALIZATION
135
+%    ==========================
136
+
137
+%    Since SOM algorithm is based on Euclidian distances, the scale of
138
+%    the variables is very important in determining what the map will
139
+%    be like. If the range of values of some variable is much bigger
140
+%    than of the other variables, that variable will probably dominate
141
+%    the map organization completely. 
142
+
143
+%    For this reason, the components of the data set are usually
144
+%    normalized, for example so that each component has unit
145
+%    variance. This can be done with function SOM_NORMALIZE:
146
+
147
+sDiris = som_normalize(sDiris,'var');
148
+
149
+%    The function has also other normalization methods.
150
+
151
+%    However, interpreting the values may be harder when they have
152
+%    been normalized. Therefore, the normalization operations can be
153
+%    reversed with function SOM_DENORMALIZE:
154
+
155
+x = sDiris.data(1,:)
156
+
157
+orig_x = som_denormalize(x,sDiris)
158
+
159
+pause % Strike any key to to train the map...
160
+
161
+
162
+
163
+
164
+
165
+clc
166
+%    STEP 3: MAP TRAINING
167
+%    ====================
168
+
169
+%    The function SOM_MAKE is used to train the SOM. By default, it
170
+%    first determines the map size, then initializes the map using
171
+%    linear initialization, and finally uses batch algorithm to train
172
+%    the map.  Function SOM_DEMO1 has a more detailed description of
173
+%    the training process.
174
+
175
+sMap = som_make(sDiris);
176
+
177
+
178
+pause % Strike any key to continues...
179
+
180
+%    The IRIS data set also has labels associated with the data
181
+%    samples. Actually, the data set consists of 50 samples of three
182
+%    species of Iris-flowers (a total of 150 samples) such that the
183
+%    measurements are width and height of sepal and petal leaves. The
184
+%    label associated with each sample is the species information:
185
+%    'Setosa', 'Versicolor' or 'Virginica'.
186
+
187
+%    Now, the map can be labelled with these labels. The best
188
+%    matching unit of each sample is found from the map, and the
189
+%    species label is given to the map unit. Function SOM_AUTOLABEL 
190
+%    can be used to do this: 
191
+
192
+sMap = som_autolabel(sMap,sDiris,'vote');
193
+
194
+pause % Strike any key to visualize the map...
195
+
196
+
197
+
198
+
199
+
200
+clc
201
+%    STEP 4: VISUALIZING THE SELF-ORGANIZING MAP: SOM_SHOW
202
+%    =====================================================
203
+
204
+%    The basic visualization of the SOM is done with function SOM_SHOW.
205
+
206
+colormap(1-gray)
207
+som_show(sMap,'norm','d')
208
+
209
+%    Notice that the names of the components are included as the
210
+%    titles of the subplots. Notice also that the variable values
211
+%    have been denormalized to the original range and scale.
212
+
213
+%    The component planes ('PetalL', 'PetalW', 'SepalL' and 'SepalW')
214
+%    show what kind of values the prototype vectors of the map units
215
+%    have. The value is indicated with color, and the colorbar on the
216
+%    right shows what the colors mean.
217
+
218
+%    The 'U-matrix' shows distances between neighboring units and thus
219
+%    visualizes the cluster structure of the map. Note that the
220
+%    U-matrix visualization has much more hexagons that the
221
+%    component planes. This is because distances *between* map units
222
+%    are shown, and not only the distance values *at* the map units. 
223
+
224
+%    High values on the U-matrix mean large distance between
225
+%    neighboring map units, and thus indicate cluster
226
+%    borders. Clusters are typically uniform areas of low
227
+%    values. Refer to colorbar to see which colors mean high
228
+%    values. In the IRIS map, there appear to be two clusters.
229
+
230
+pause % Strike any key to continue...
231
+
232
+%    The subplots are linked together through similar position. In
233
+%    each axis, a particular map unit is always in the same place. For
234
+%    example:
235
+
236
+h=zeros(sMap.topol.msize); h(1,2) = 1;
237
+som_show_add('hit',h(:),'markercolor','r','markersize',0.5,'subplot','all')
238
+
239
+%    the red marker is on top of the same unit on each axis. 
240
+
241
+pause % Strike any key to continue...
242
+
243
+
244
+
245
+clf
246
+
247
+clc
248
+
249
+%    STEP 4: VISUALIZING THE SELF-ORGANIZING MAP: SOM_SHOW_ADD
250
+%    =========================================================
251
+
252
+%    The SOM_SHOW_ADD function can be used to add markers, labels and
253
+%    trajectories on top of SOM_SHOW created figures. The function
254
+%    SOM_SHOW_CLEAR can be used to clear them away.
255
+
256
+%    Here, the U-matrix is shown on the left, and an empty grid
257
+%    named 'Labels' is shown on the right.
258
+
259
+som_show(sMap,'umat','all','empty','Labels')
260
+
261
+pause % Strike any key to add labels...
262
+
263
+%    Here, the labels added to the map with SOM_AUTOLABEL function
264
+%    are shown on the empty grid.
265
+
266
+som_show_add('label',sMap,'Textsize',8,'TextColor','r','Subplot',2)
267
+
268
+pause % Strike any key to add hits...
269
+
270
+%    An important tool in data analysis using SOM are so called hit
271
+%    histograms. They are formed by taking a data set, finding the BMU
272
+%    of each data sample from the map, and increasing a counter in a
273
+%    map unit each time it is the BMU. The hit histogram shows the
274
+%    distribution of the data set on the map.
275
+
276
+%    Here, the hit histogram for the whole data set is calculated
277
+%    and visualized on the U-matrix.
278
+
279
+h = som_hits(sMap,sDiris);
280
+som_show_add('hit',h,'MarkerColor','w','Subplot',1)
281
+
282
+pause % Strike any key to continue...
283
+
284
+%    Multiple hit histograms can be shown simultaniously. Here, three
285
+%    hit histograms corresponding to the three species of Iris
286
+%    flowers is calculated and shown. 
287
+
288
+%    First, the old hit histogram is removed.
289
+
290
+som_show_clear('hit',1)
291
+
292
+%    Then, the histograms are calculated. The first 50 samples in
293
+%    the data set are of the 'Setosa' species, the next 50 samples
294
+%    of the 'Versicolor' species and the last 50 samples of the
295
+%    'Virginica' species. 
296
+
297
+h1 = som_hits(sMap,sDiris.data(1:50,:));
298
+h2 = som_hits(sMap,sDiris.data(51:100,:));
299
+h3 = som_hits(sMap,sDiris.data(101:150,:));
300
+
301
+som_show_add('hit',[h1, h2, h3],'MarkerColor',[1 0 0; 0 1 0; 0 0 1],'Subplot',1)
302
+
303
+%    Red color is for 'Setosa', green for 'Versicolor' and blue for
304
+%    'Virginica'. One can see that the three species are pretty well
305
+%    separated, although 'Versicolor' and 'Virginica' are slightly
306
+%    mixed up.
307
+
308
+pause % Strike any key to continue...
309
+
310
+
311
+
312
+clf
313
+clc
314
+
315
+%    STEP 4: VISUALIZING THE SELF-ORGANIZING MAP: SOM_GRID
316
+%    =====================================================
317
+
318
+%    There's also another visualization function: SOM_GRID.  This
319
+%    allows visualization of the SOM in freely specified coordinates,
320
+%    for example the input space (of course, only upto 3D space). This
321
+%    function has quite a lot of options, and is pretty flexible.
322
+
323
+%    Basically, the SOM_GRID visualizes the SOM network: each unit is
324
+%    shown with a marker and connected to its neighbors with lines.
325
+%    The user has control over: 
326
+%     - the coordinate of each unit (2D or 3D)
327
+%     - the marker type, color and size of each unit
328
+%     - the linetype, color and width of the connecting lines
329
+%    There are also some other options.
330
+
331
+pause % Strike any key to see some visualizations...
332
+
333
+%    Here are four visualizations made with SOM_GRID: 
334
+%     - The map grid in the output space.
335
+
336
+subplot(2,2,1)
337
+som_grid(sMap,'Linecolor','k')
338
+view(0,-90), title('Map grid')
339
+
340
+%     - A surface plot of distance matrix: both color and 
341
+%       z-coordinate indicate average distance to neighboring 
342
+%       map units. This is closely related to the U-matrix.
343
+
344
+subplot(2,2,2)
345
+Co=som_unit_coords(sMap); U=som_umat(sMap); U=U(1:2:size(U,1),1:2:size(U,2));
346
+som_grid(sMap,'Coord',[Co, U(:)],'Surf',U(:),'Marker','none');
347
+view(-80,45), axis tight, title('Distance matrix')
348
+
349
+%     - The map grid in the output space. Three first components
350
+%       determine the 3D-coordinates of the map unit, and the size
351
+%       of the marker is determined by the fourth component.
352
+%       Note that the values have been denormalized.
353
+
354
+subplot(2,2,3)
355
+M = som_denormalize(sMap.codebook,sMap);
356
+som_grid(sMap,'Coord',M(:,1:3),'MarkerSize',M(:,4)*2)
357
+view(-80,45), axis tight, title('Prototypes')
358
+
359
+%     - Map grid as above, but the original data has been plotted
360
+%       also: coordinates show the values of three first components
361
+%       and color indicates the species of each sample.  Fourth
362
+%       component is not shown.
363
+
364
+subplot(2,2,4)
365
+som_grid(sMap,'Coord',M(:,1:3),'MarkerSize',M(:,4)*2)
366
+hold on
367
+D = som_denormalize(sDiris.data,sDiris); 
368
+plot3(D(1:50,1),D(1:50,2),D(1:50,3),'r.',...
369
+      D(51:100,1),D(51:100,2),D(51:100,3),'g.',...
370
+      D(101:150,1),D(101:150,2),D(101:150,3),'b.')
371
+view(-72,64), axis tight, title('Prototypes and data')
372
+
373
+pause % Strike any key to continue...
374
+
375
+%    STEP 5: ANALYSIS OF RESULTS
376
+%    ===========================
377
+
378
+%    The purpose of this step highly depends on the purpose of the
379
+%    whole data analysis: is it segmentation, modeling, novelty
380
+%    detection, classification, or something else? For this reason, 
381
+%    there is not a single general-purpose analysis function, but 
382
+%    a number of individual functions which may, or may not, prove 
383
+%    useful in any specific case.
384
+
385
+%    Visualization is of course part of the analysis of
386
+%    results. Examination of labels and hit histograms is another
387
+%    part. Yet another is validation of the quality of the SOM (see
388
+%    the use of SOM_QUALITY in SOM_DEMO1).
389
+
390
+[qe,te] = som_quality(sMap,sDiris)
391
+
392
+%    People have contributed a number of functions to the Toolbox
393
+%    which can be used for the analysis. These include functions for 
394
+%    vector projection, clustering, pdf-estimation, modeling,
395
+%    classification, etc. However, ultimately the use of these
396
+%    tools is up to you.
397
+
398
+%    More about visualization is presented in SOM_DEMO3.
399
+%    More about data analysis is presented in SOM_DEMO4.
400
+
401
+echo off
402
+warning on
403
+
404
+
405
+
406
+
... ...
@@ -0,0 +1,706 @@
1
+
2
+%SOM_DEMO3 Self-organizing map visualization.
3
+
4
+% Contributed to SOM Toolbox 2.0, February 11th, 2000 by Juha Vesanto
5
+% http://www.cis.hut.fi/projects/somtoolbox/
6
+
7
+% Version 1.0beta juuso 071197 
8
+% Version 2.0beta juuso 080200 070600
9
+
10
+clf reset;
11
+figure(gcf)
12
+echo on
13
+
14
+
15
+
16
+
17
+clc
18
+%    ==========================================================
19
+%    SOM_DEMO3 - VISUALIZATION
20
+%    ==========================================================
21
+
22
+%    som_show           - Visualize map.
23
+%    som_grid           - Visualization with free coordinates.
24
+%
25
+%    som_show_add       - Add markers on som_show visualization.
26
+%    som_show_clear     - Remove markers from som_show visualization.
27
+%    som_recolorbar     - Refresh and rescale colorbars in som_show 
28
+%                         visualization.
29
+%
30
+%    som_cplane         - Visualize component/color/U-matrix plane.
31
+%    som_pieplane       - Visualize prototype vectors as pie charts.
32
+%    som_barplane       - Visualize prototype vectors as bar charts.
33
+%    som_plotplane      - Visualize prototype vectors as line graphs.
34
+%
35
+%    pcaproj            - Projection to principal component space.
36
+%    cca                - Projection with Curvilinear Component Analysis.
37
+%    sammon             - Projection with Sammon's mapping.
38
+%    som_umat           - Calculate U-matrix.
39
+%    som_colorcode      - Color coding for the map.
40
+%    som_normcolor      - RGB values of indexed colors.
41
+%    som_hits           - Hit histograms for the map.
42
+
43
+%    The basic functions for SOM visualization are SOM_SHOW and
44
+%    SOM_GRID. The SOM_SHOW has three auxiliary functions:
45
+%    SOM_SHOW_ADD, SOM_SHOW_CLEAR and SOM_RECOLORBAR which are used 
46
+%    to add and remove markers and to control the colorbars.
47
+%    SOM_SHOW actually uses SOM_CPLANE to make the visualizations.
48
+%    Also SOM_{PIE,BAR,PLOT}PLANE can be used to visualize SOMs.
49
+
50
+%    The other functions listed above do not themselves visualize
51
+%    anything, but their results are used in the visualizations.
52
+    
53
+%    There's an important limitation that visualization functions have:
54
+%    while the SOM Toolbox otherwise supports N-dimensional map grids, 
55
+%    visualization only works for 1- and 2-dimensional map grids!!!
56
+
57
+pause % Strike any key to create demo data and map...
58
+
59
+
60
+
61
+
62
+
63
+clc
64
+%    DEMO DATA AND MAP
65
+%    =================
66
+
67
+%    The data set contructed for this demo consists of random vectors
68
+%    in three gaussian kernels the centers of which are at [0, 0, 0],
69
+%    [3 3 3] and [9 0 0]. The map is trained using default parameters.
70
+
71
+D1 = randn(100,3);
72
+D2 = randn(100,3) + 3;
73
+D3 = randn(100,3); D3(:,1) = D3(:,1) + 9;
74
+
75
+sD = som_data_struct([D1; D2; D3],'name','Demo3 data',...
76
+		     'comp_names',{'X-coord','Y-coord','Z-coord'});
77
+sM = som_make(sD);
78
+
79
+%    Since the data (and thus the prototypes of the map) are
80
+%    3-dimensional, they can be directly plotted using PLOT3.
81
+%    Below, the data is plotted using red 'o's and the map
82
+%    prototype vectors with black '+'s.
83
+
84
+plot3(sD.data(:,1),sD.data(:,2),sD.data(:,3),'ro',...
85
+      sM.codebook(:,1),sM.codebook(:,2),sM.codebook(:,3),'k+')
86
+rotate3d on
87
+
88
+%    From the visualization it is pretty easy to see what the data is
89
+%    like, and how the prototypes have been positioned. One can see
90
+%    that there are three clusters, and that there are some prototype
91
+%    vectors between the clusters, although there is actually no
92
+%    data there. The map units corresponding to these prototypes
93
+%    are called 'dead' or 'interpolative' map units.
94
+
95
+pause % Strike any key to continue...
96
+
97
+
98
+
99
+clc
100
+%    VISUALIZATION OF MULTIDIMENSIONAL DATA
101
+%    ======================================
102
+
103
+%    Usually visualization of data sets is not this straightforward,
104
+%    since the dimensionality is much higher than three. In principle,
105
+%    one can embed additional information to the visualization by
106
+%    using properties other than position, for example color, size or
107
+%    shape.
108
+
109
+%    Here the data set and map prototypes are plotted again, but
110
+%    information of the cluster is shown using color: red for the
111
+%    first cluster, green for the second and blue for the last.
112
+
113
+plot3(sD.data(1:100,1),sD.data(1:100,2),sD.data(1:100,3),'ro',...
114
+      sD.data(101:200,1),sD.data(101:200,2),sD.data(101:200,3),'go',...
115
+      sD.data(201:300,1),sD.data(201:300,2),sD.data(201:300,3),'bo',...
116
+      sM.codebook(:,1),sM.codebook(:,2),sM.codebook(:,3),'k+')
117
+rotate3d on
118
+
119
+%    However, this works only for relatively small dimensionality, say
120
+%    less than 10. When the information is added this way, the
121
+%    visualization becomes harder and harder to understand. Also, not
122
+%    all properties are equal: the human visual system perceives
123
+%    colors differently from position, not to mention the complex
124
+%    rules governing perception of shape. 
125
+
126
+pause % Strike any key to learn about linking...
127
+
128
+
129
+
130
+
131
+
132
+clc
133
+%    LINKING MULTIPLE VISUALIZATIONS
134
+%    ===============================
135
+
136
+%    The other option is to use *multiple visualizations*, so called
137
+%    small multiples, instead of only one. The problem is then how to
138
+%    link these visualizations together: one should be able to idetify
139
+%    the same object from the different visualizations.
140
+
141
+%    This could be done using, for example, color: each object has
142
+%    the same color in each visualization. Another option is to use 
143
+%    similar position: each object has the same position in each
144
+%    small multiple.
145
+
146
+%    For example, here are four subplots, one for each component and
147
+%    one for cluster information, where color denotes the value and
148
+%    position is used for linking. The 2D-position is derived by
149
+%    projecting the data into the space spanned by its two greatest
150
+%    eigenvectors.
151
+
152
+[Pd,V,me] = pcaproj(sD.data,2);        % project the data
153
+Pm        = pcaproj(sM.codebook,V,me); % project the prototypes
154
+colormap(hot);                         % colormap used for values
155
+
156
+echo off
157
+for c=1:3, 
158
+  subplot(2,2,c), cla, hold on
159
+  som_grid('rect',[300 1],'coord',Pd,'Line','none',...
160
+	   'MarkerColor',som_normcolor(sD.data(:,c)));
161
+  som_grid(sM,'Coord',Pm,'Line','none','marker','+');
162
+  hold off, title(sD.comp_names{c}), xlabel('PC 1'), ylabel('PC 2');
163
+end
164
+
165
+subplot(2,2,4), cla
166
+plot(Pd(1:100,1),Pd(1:100,2),'ro',...
167
+     Pd(101:200,1),Pd(101:200,2),'go',...
168
+     Pd(201:300,1),Pd(201:300,2),'bo',...
169
+     Pm(:,1),Pm(:,2),'k+')
170
+title('Cluster')
171
+echo on
172
+
173
+pause % Strike any key to use color for linking...
174
+
175
+%    Here is another example, where color is used for linking. On the
176
+%    top right triangle are the scatter plots of each variable without
177
+%    color coding, and on the bottom left triangle with the color
178
+%    coding. In the colored figures, each data sample can be
179
+%    identified by a unique color. Well, almost identified: there are
180
+%    quite a lot of samples with almost the same color. Color is not as
181
+%    precise linking method as position.
182
+
183
+echo off 
184
+Col = som_normcolor([1:300]',jet(300));
185
+k=1;
186
+for i=1:3, 
187
+  for j=1:3, 
188
+    if i<j, i1=i; i2=j; else i1=j; i2=i; end
189
+    if i<j,
190
+      subplot(3,3,k); cla
191
+      plot(sD.data(:,i1),sD.data(:,i2),'ko')
192
+      xlabel(sD.comp_names{i1}), ylabel(sD.comp_names{i2})
193
+    elseif i>j,
194
+      subplot(3,3,k); cla
195
+      som_grid('rect',[300 1],'coord',sD.data(:,[i1 i2]),...
196
+	       'Line','none','MarkerColor',Col);
197
+      xlabel(sD.comp_names{i1}), ylabel(sD.comp_names{i2})
198
+    end
199
+    k=k+1;
200
+  end
201
+end
202
+echo on
203
+
204
+pause % Strike any key to learn about data visualization using SOM...
205
+
206
+
207
+clc
208
+%    DATA VISUALIZATION USING SOM
209
+%    ============================
210
+
211
+%    The basic visualization functions and their usage have already
212
+%    been introduced in SOM_DEMO2. In this demo, a more structured
213
+%    presentation is given. 
214
+
215
+%    Data visualization techniques using the SOM can be divided to
216
+%    three categories based on their goal:
217
+
218
+%     1. visualization of clusters and shape of the data:
219
+%        projections, U-matrices and other distance matrices
220
+%
221
+%     2. visualization of components / variables: 
222
+%        component planes, scatter plots
223
+%
224
+%     3. visualization of data projections: 
225
+%        hit histograms, response surfaces
226
+
227
+pause % Strike any key to visualize clusters with distance matrices...
228
+
229
+
230
+
231
+clf
232
+clc
233
+%    1. VISUALIZATION OF CLUSTERS: DISTANCE MATRICES
234
+%    ===============================================
235
+
236
+%    Distance matrices are typically used to show the cluster
237
+%    structure of the SOM. They show distances between neighboring
238
+%    units, and are thus closely related to single linkage clustering
239
+%    techniques. The most widely used distance matrix technique is
240
+%    the U-matrix. 
241
+
242
+%    Here, the U-matrix of the map is shown (using all three
243
+%    components in the distance calculation):
244
+
245
+colormap(1-gray)
246
+som_show(sM,'umat','all');
247
+
248
+pause % Strike any key to see more examples of distance matrices...
249
+
250
+%    The function SOM_UMAT can be used to calculate U-matrix.  The
251
+%    resulting matrix holds distances between neighboring map units,
252
+%    as well as the median distance from each map unit to its
253
+%    neighbors. These median distances corresponding to each map unit
254
+%    can be easily extracted. The result is a distance matrix using
255
+%    median distance.
256
+
257
+U = som_umat(sM);
258
+Um = U(1:2:size(U,1),1:2:size(U,2));
259
+
260
+%    A related technique is to assign colors to the map units such
261
+%    that similar map units get similar colors.
262
+
263
+%    Here, four clustering figures are shown: 
264
+%     - U-matrix
265
+%     - median distance matrix (with grayscale)
266
+%     - median distance matrix (with map unit size)
267
+%     - similarity coloring, made by spreading a colormap
268
+%       on top of the principal component projection of the
269
+%       prototype vectors
270
+
271
+subplot(2,2,1)
272
+h=som_cplane([sM.topol.lattice,'U'],sM.topol.msize, U(:)); 
273
+set(h,'Edgecolor','none'); title('U-matrix')
274
+
275
+subplot(2,2,2)
276
+h=som_cplane(sM, Um(:));
277
+set(h,'Edgecolor','none'); title('D-matrix (grayscale)')
278
+
279
+subplot(2,2,3)
280
+som_cplane(sM,'none',1-Um(:)/max(Um(:)))
281
+title('D-matrix (marker size)')
282
+
283
+subplot(2,2,4)
284
+C = som_colorcode(Pm);  % Pm is the PC-projection calculated earlier
285
+som_cplane(sM,C)
286
+title('Similarity coloring')
287
+
288
+pause % Strike any key to visualize shape and clusters with projections...
289
+
290
+
291
+
292
+clf
293
+clc
294
+%    1. VISUALIZATION OF CLUSTERS AND SHAPE: PROJECTIONS
295
+%    ===================================================
296
+
297
+%    In vector projection, a set of high-dimensional data samples is
298
+%    projected to a lower dimensional such that the distances between
299
+%    data sample pairs are preserved as well as possible. Depending 
300
+%    on the technique, the projection may be either linear or
301
+%    non-linear, and it may place special emphasis on preserving
302
+%    local distances. 
303
+
304
+%    For example SOM is a projection technique, since the prototypes
305
+%    have well-defined positions on the 2-dimensional map grid. SOM as
306
+%    a projection is however a very crude one. Other projection
307
+%    techniques include the principal component projection used
308
+%    earlier, Sammon's mapping and Curvilinear Component Analysis
309
+%    (to name a few). These have been implemented in functions
310
+%    PCAPROJ, SAMMON and CCA. 
311
+
312
+%    Projecting the map prototype vectors and joining neighboring map
313
+%    units with lines gives the SOM its characteristic net-like look.
314
+%    The projection figures can be linked to the map planes using
315
+%    color coding.
316
+
317
+%    Here is the distance matrix, color coding, a projection without
318
+%    coloring and a projection with one. In the last projection,
319
+%    the size of interpolating map units has been set to zero.
320
+
321
+subplot(2,2,1)
322
+som_cplane(sM,Um(:));
323
+title('Distance matrix')
324
+
325
+subplot(2,2,2)
326
+C = som_colorcode(sM,'rgb4');
327
+som_cplane(sM,C);
328
+title('Color code')
329
+
330
+subplot(2,2,3)
331
+som_grid(sM,'Coord',Pm,'Linecolor','k');
332
+title('PC-projection')
333
+
334
+subplot(2,2,4)
335
+h = som_hits(sM,sD); s=6*(h>0);
336
+som_grid(sM,'Coord',Pm,'MarkerColor',C,'Linecolor','k','MarkerSize',s);
337
+title('Colored PC-projection')
338
+
339
+pause % Strike any key to visualize component planes...
340
+
341
+
342
+clf
343
+clc
344
+%    2. VISUALIZATION OF COMPONENTS: COMPONENT PLANES
345
+%    ================================================
346
+
347
+%    The component planes visualizations shows what kind of values the
348
+%    prototype vectors of the map units have for different vector
349
+%    components.
350
+
351
+%    Here is the U-matrix and the three component planes of the map.
352
+
353
+som_show(sM)
354
+
355
+pause % Strike any key to continue...
356
+
357
+%    Besides SOM_SHOW and SOM_CPLANE, there are three other
358
+%    functions specifically designed for showing the values of the 
359
+%    component planes: SOM_PIEPLANE, SOM_BARPLANE, SOM_PLOTPLANE. 
360
+
361
+%    SOM_PIEPLANE shows a single pie chart for each map unit.  Each
362
+%    pie shows the relative proportion of each component of the sum of
363
+%    all components in that map unit. The component values must be
364
+%    positive. 
365
+
366
+%    SOM_BARPLANE shows a barchart in each map unit. The scaling of 
367
+%    bars can be made unit-wise or variable-wise. By default it is
368
+%    determined variable-wise.
369
+
370
+%    SOM_PLOTPLANE shows a linegraph in each map unit. 
371
+
372
+M = som_normalize(sM.codebook,'range'); 
373
+
374
+subplot(1,3,1)
375
+som_pieplane(sM, M);
376
+title('som\_pieplane')
377
+
378
+subplot(1,3,2)
379
+som_barplane(sM, M, '', 'unitwise');
380
+title('som\_barplane')
381
+
382
+subplot(1,3,3)
383
+som_plotplane(sM, M, 'b');
384
+title('som\_plotplane')
385
+
386
+pause % Strike any key to visualize cluster properties...
387
+
388
+
389
+
390
+clf
391
+clc
392
+%    2. VISUALIZATION OF COMPONENTS: CLUSTERS
393
+%    ========================================
394
+
395
+%    An interesting question is of course how do the values of the
396
+%    variables relate to the clusters: what are the values of the
397
+%    components in the clusters, and which components are the ones
398
+%    which *make* the clusters.
399
+
400
+som_show(sM)
401
+
402
+%    From the U-matrix and component planes, one can easily see
403
+%    what the typical values are in each cluster. 
404
+
405
+pause % Strike any key to continue...
406
+
407
+%    The significance of the components with respect to the clustering
408
+%    is harder to visualize. One indication of importance is that on
409
+%    the borders of the clusters, values of important variables change
410
+%    very rabidly.
411
+
412
+%    Here, the distance matrix is calculated with respect to each
413
+%    variable. 
414
+
415
+u1 = som_umat(sM,'mask',[1 0 0]'); u1=u1(1:2:size(u1,1),1:2:size(u1,2));
416
+u2 = som_umat(sM,'mask',[0 1 0]'); u2=u2(1:2:size(u2,1),1:2:size(u2,2));
417
+u3 = som_umat(sM,'mask',[0 0 1]'); u3=u3(1:2:size(u3,1),1:2:size(u3,2));
418
+
419
+%    Here, the distance matrices are shown, as well as a piechart
420
+%    indicating the relative importance of each variable in each
421
+%    map unit. The size of piecharts has been scaled by the
422
+%    distance matrix calculated from all components.
423
+
424
+subplot(2,2,1)
425
+som_cplane(sM,u1(:));
426
+title(sM.comp_names{1})
427
+
428
+subplot(2,2,2)
429
+som_cplane(sM,u2(:));
430
+title(sM.comp_names{2})
431
+
432
+subplot(2,2,3)
433
+som_cplane(sM,u3(:));
434
+title(sM.comp_names{3})
435
+
436
+subplot(2,2,4)
437
+som_pieplane(sM, [u1(:), u2(:), u3(:)], hsv(3), Um(:)/max(Um(:)));
438
+title('Relative importance')
439
+
440
+%    From the last subplot, one can see that in the area where the
441
+%    bigger cluster border is, the 'X-coord' component (red color)
442
+%    has biggest effect, and thus is the main factor in separating
443
+%    that cluster from the rest.
444
+
445
+pause % Strike any key to learn about correlation hunting...
446
+
447
+
448
+clf
449
+clc
450
+%    2. VISUALIZATION OF COMPONENTS: CORRELATION HUNTING
451
+%    ===================================================
452
+
453
+%    Finally, the component planes are often used for correlation
454
+%    hunting. When the number of variables is high, the component
455
+%    plane visualization offers a convenient way to visualize all
456
+%    components at once and hunt for correlations (as opposed to
457
+%    N*(N-1)/2 scatterplots).
458
+
459
+%    Hunting correlations this way is not very accurate. However, it
460
+%    is easy to select interesting combinations for further
461
+%    investigation.
462
+
463
+%    Here, the first and third components are shown with scatter
464
+%    plot. As with projections, a color coding is used to link the
465
+%    visualization to the map plane. In the color coding, size shows
466
+%    the distance matrix information.
467
+
468
+C = som_colorcode(sM);
469
+subplot(1,2,1)
470
+som_cplane(sM,C,1-Um(:)/max(Um(:)));
471
+title('Color coding + distance matrix')
472
+
473
+subplot(1,2,2)
474
+som_grid(sM,'Coord',sM.codebook(:,[1 3]),'MarkerColor',C);
475
+title('Scatter plot'); xlabel(sM.comp_names{1}); ylabel(sM.comp_names{3})
476
+axis equal
477
+
478
+pause % Strike any key to visualize data responses...
479
+
480
+
481
+clf
482
+clc
483
+%    3. DATA ON MAP
484
+%    ==============
485
+
486
+%    The SOM is a map of the data manifold. An interesting question
487
+%    then is where on the map a specific data sample is located, and
488
+%    how accurate is that localization? One is interested in the
489
+%    response of the map to the data sample. 
490
+
491
+%    The simplest answer is to find the BMU of the data sample.
492
+%    However, this gives no indication of the accuracy of the
493
+%    match. Is the data sample close to the BMU, or is it actually
494
+%    equally close to the neighboring map units (or even approximately
495
+%    as close to all map units)? Sometimes accuracy doesn't really
496
+%    matter, but if it does, it should be visualized somehow.
497
+
498
+%    Here are different kinds of response visualizations for two
499
+%    vectors: [0 0 0] and [99 99 99]. 
500
+%     - BMUs indicated with labels       
501
+%     - BMUs indicated with markers, relative quantization errors
502
+%       (in this case, proportion between distances to BMU and 
503
+%       Worst-MU) with vertical lines
504
+%     - quantization error between the samples and all map units 
505
+%     - fuzzy response (a non-linear function of quantization
506
+%       error) of all map units
507
+
508
+echo off
509
+[bm,qe] = som_bmus(sM,[0 0 0; 99 99 99],'all'); % distance to all map units
510
+[dummy,ind] = sort(bm(1,:)); d0 = qe(1,ind)'; 
511
+[dummy,ind] = sort(bm(2,:)); d9 = qe(2,ind)'; 
512
+bmu0 = bm(1,1); bmu9 = bm(2,1); % bmus
513
+
514
+h0 = zeros(prod(sM.topol.msize),1); h0(bmu0) = 1; % crisp hits
515
+h9 = zeros(prod(sM.topol.msize),1); h9(bmu9) = 1; 
516
+
517
+lab = cell(prod(sM.topol.msize),1); 
518
+lab{bmu0} = '[0,0,0]'; lab{bmu9} = '[99,99,99]';
519
+
520
+hf0 = som_hits(sM,[0 0 0],'fuzzy'); % fuzzy response
521
+hf9 = som_hits(sM,[99 99 99],'fuzzy'); 
522
+
523
+som_show(sM,'umat',{'all','BMU'},...
524
+	 'color',{d0,'Qerror 0'},'color',{hf0,'Fuzzy response 0'},...
525
+	 'empty','BMU+qerror',...
526
+	 'color',{d9,'Qerror 99'},'color',{hf9,'Fuzzy response 99'});	 
527
+som_show_add('label',lab,'Subplot',1,'Textcolor','r');
528
+som_show_add('hit',[h0, h9],'Subplot',4,'MarkerColor','r');
529
+hold on
530
+Co = som_vis_coords(sM.topol.lattice,sM.topol.msize);
531
+plot3(Co(bmu0,[1 1]),Co(bmu0,[2 2]),[0 10*qe(1,1)/qe(1,end)],'r-')
532
+plot3(Co(bmu9,[1 1]),Co(bmu9,[2 2]),[0 10*qe(2,1)/qe(2,end)],'r-')
533
+view(3), axis equal
534
+echo on
535
+
536
+%    Here are the distances to BMU, 2-BMU and WMU:
537
+
538
+qe(1,[1,2,end]) % [0 0 0]
539
+qe(2,[1,2,end]) % [99 99 99]
540
+
541
+%    One can see that for [0 0 0] the accuracy is pretty good as the
542
+%    quantization error of the BMU is much lower than that of the
543
+%    WMU. On the other hand [99 99 99] is very far from the map:
544
+%    distance to BMU is almost equal to distance to WMU.
545
+
546
+pause % Strike any key to visualize responses of multiple samples...
547
+
548
+
549
+
550
+clc
551
+clf
552
+%    3. DATA ON MAP: HIT HISTOGRAMS
553
+%    ==============================
554
+
555
+%    One can also investigate whole data sets using the map. When the
556
+%    BMUs of multiple data samples are aggregated, a hit histogram
557
+%    results. Instead of BMUs, one can also aggregate for example
558
+%    fuzzy responses.
559
+
560
+%    The hit histograms (or aggregated responses) can then be compared
561
+%    with each other. 
562
+
563
+%    Here are hit histograms of three data sets: one with 50 first
564
+%    vectors of the data set, one with 150 samples from the data
565
+%    set, and one with 50 randomly selected samples. In the last
566
+%    subplot, the fuzzy response of the first data set.
567
+
568
+dlen = size(sD.data,1);
569
+Dsample1 = sD.data(1:50,:); h1 = som_hits(sM,Dsample1); 
570
+Dsample2 = sD.data(1:150,:); h2 = som_hits(sM,Dsample2); 
571
+Dsample3 = sD.data(ceil(rand(50,1)*dlen),:); h3 = som_hits(sM,Dsample3); 
572
+hf = som_hits(sM,Dsample1,'fuzzy');
573
+
574
+som_show(sM,'umat','all','umat','all','umat','all','color',{hf,'Fuzzy'})
575
+som_show_add('hit',h1,'Subplot',1,'Markercolor','r')
576
+som_show_add('hit',h2,'Subplot',2,'Markercolor','r')
577
+som_show_add('hit',h3,'Subplot',3,'Markercolor','r')
578
+
579
+pause % Strike any key to visualize trajectories...
580
+
581
+
582
+
583
+clc
584
+clf
585
+%    3. DATA ON MAP: TRAJECTORIES
586
+%    ============================
587
+
588
+%    A special data mapping technique is trajectory. If the samples
589
+%    are ordered, forming a time-series for example, their response on
590
+%    the map can be tracked. The function SOM_SHOW_ADD can be used to
591
+%    show the trajectories in two different modes: 'traj' and 'comet'.
592
+
593
+%    Here, a series of data points is formed which go from [8,0,0]
594
+%    to [2,2,2]. The trajectory is plotted using the two modes.
595
+
596
+Dtraj = [linspace(9,2,20); linspace(0,2,20); linspace(0,2,20)]';
597
+T = som_bmus(sM,Dtraj);
598
+
599
+som_show(sM,'comp',[1 1]);
600
+som_show_add('traj',T,'Markercolor','r','TrajColor','r','subplot',1);
601
+som_show_add('comet',T,'MarkerColor','r','subplot',2);
602
+
603
+%    There's also a function SOM_TRAJECTORY which lauches a GUI
604
+%    specifically designed for displaying trajectories (in 'comet'
605
+%    mode).
606
+
607
+pause % Strike any key to learn about color handling...
608
+
609
+
610
+
611
+
612
+clc
613
+clf
614
+%    COLOR HANDLING
615
+%    ==============
616
+
617
+%    Matlab offers flexibility in the colormaps. Using the COLORMAP
618
+%    function, the colormap may be changed. There are several useful
619
+%    colormaps readily available, for example 'hot' and 'jet'. The
620
+%    default number of colors in the colormaps is 64. However, it is
621
+%    often advantageous to use less colors in the colormap. This way
622
+%    the components planes visualization become easier to interpret.
623
+
624
+%    Here the three component planes are visualized using the 'hot'
625
+%    colormap and only three colors.
626
+
627
+som_show(sM,'comp',[1 2 3])
628
+colormap(hot(3));
629
+som_recolorbar 
630
+
631
+pause % Press any key to change the colorbar labels...
632
+
633
+%     The function SOM_RECOLORBAR can be used to reconfigure
634
+%     the labels beside the colorbar. 
635
+
636
+%     Here the colorbar of the first subplot is labeled using labels
637
+%     'small', 'medium' and 'big' at values 0, 1 and 2.  For the
638
+%     colorbar of the second subplot, values are calculated for the
639
+%     borders between colors.
640
+
641
+som_recolorbar(1,{[0 4 9]},'',{{'small','medium','big'}});
642
+som_recolorbar(2,'border','');
643
+
644
+pause % Press any key to learn about SOM_NORMCOLOR...
645
+
646
+%     Some SOM Toolbox functions do not use indexed colors if the
647
+%     underlying Matlab function (e.g. PLOT) do not use indexed
648
+%     colors. SOM_NORMCOLOR is a convenient function to simulate
649
+%     indexed colors: it calculates fixed RGB colors that
650
+%     are similar to indexed colors with the specified colormap. 
651
+
652
+%     Here, two SOM_GRID visualizations are created. One uses the
653
+%     'surf' mode to show the component colors in indexed color
654
+%     mode, and the other uses SOM_NORMALIZE to do the same. 
655
+
656
+clf
657
+colormap(jet(64))
658
+subplot(1,2,1)
659
+som_grid(sM,'Surf',sM.codebook(:,3));
660
+title('Surf mode')
661
+
662
+subplot(1,2,2)
663
+som_grid(sM,'Markercolor',som_normcolor(sM.codebook(:,3)));
664
+title('som\_normcolor')
665
+
666
+pause % Press any key to visualize different map shapes...
667
+
668
+
669
+
670
+clc
671
+clf
672
+%    DIFFERENT MAP SHAPES
673
+%    ====================
674
+
675
+%    There's no direct way to visualize cylinder or toroid maps. When
676
+%    visualized, they are treated exactly as if they were sheet
677
+%    shaped. However, if function SOM_UNIT_COORDS is used to provide
678
+%    unit coordinates, then SOM_GRID can be used to visualize these
679
+%    alternative map shapes.
680
+
681
+%    Here the grids of the three possible map shapes (sheet, cylinder
682
+%    and toroid) are visualized. The last subplot shows a component 
683
+%    plane visualization of the toroid map.
684
+
685
+Cor = som_unit_coords(sM.topol.msize,'hexa','sheet');
686
+Coc = som_unit_coords(sM.topol.msize,'hexa','cyl');
687
+Cot = som_unit_coords(sM.topol.msize,'hexa','toroid');
688
+
689
+subplot(2,2,1)
690
+som_grid(sM,'Coord',Cor,'Markersize',3,'Linecolor','k');
691
+title('sheet'), view(0,-90), axis tight, axis equal
692
+
693
+subplot(2,2,2)
694
+som_grid(sM,'Coord',Coc,'Markersize',3,'Linecolor','k');
695
+title('cylinder'), view(5,1), axis tight, axis equal
696
+
697
+subplot(2,2,3)
698
+som_grid(sM,'Coord',Cot,'Markersize',3,'Linecolor','k');
699
+title('toroid'), view(-100,0), axis tight, axis equal
700
+
701
+subplot(2,2,4)
702
+som_grid(sM,'Coord',Cot,'Surf',sM.codebook(:,3));
703
+colormap(jet), colorbar
704
+title('toroid'), view(-100,0), axis tight, axis equal
705
+
706
+echo off
... ...
@@ -0,0 +1,307 @@
1
+
2
+%SOM_DEMO4 Data analysis using the SOM.
3
+
4
+% Contributed to SOM Toolbox 2.0, February 11th, 2000 by Juha Vesanto
5
+% http://www.cis.hut.fi/projects/somtoolbox/
6
+
7
+% Version 1.0beta juuso 071197 
8
+% Version 2.0beta juuso 090200 070600
9
+
10
+clf reset;
11
+f0 = gcf;
12
+echo on
13
+
14
+
15
+
16
+
17
+clc
18
+%    ==========================================================
19
+%    SOM_DEMO4 - DATA ANALYSIS USING THE SOM
20
+%    ==========================================================
21
+
22
+%    In this demo, the IRIS data set is analysed using SOM. First, the
23
+%    data is read from ascii file (please make sure they can be found
24
+%    from the current path), normalized, and a map is
25
+%    trained. Since the data also had labels, the map is labelled.
26
+
27
+try, 
28
+  sD = som_read_data('iris.data');     
29
+catch
30
+  echo off
31
+
32
+  warning('File ''iris.data'' not found. Using simulated data instead.')
33
+  
34
+  D = randn(50,4); 
35
+  D(:,1) = D(:,1)+5;     D(:,2) = D(:,2)+3.5; 
36
+  D(:,3) = D(:,3)/2+1.5; D(:,4) = D(:,4)/2+0.3;
37
+  D2 = randn(100,4); D2(:,2) = sort(D2(:,2));
38
+  D2(:,1) = D2(:,1)+6.5; D2(:,2) = D2(:,2)+2.8; 
39
+  D2(:,3) = D2(:,3)+5;   D2(:,4) = D2(:,4)/2+1.5;  
40
+  sD = som_data_struct([D; D2],'name','iris (simulated)',...
41
+		       'comp_names',{'SepalL','SepalW','PetalL','PetalW'});
42
+  sD = som_label(sD,'add',[1:50]','Setosa');
43
+  sD = som_label(sD,'add',[51:100]','Versicolor');
44
+  sD = som_label(sD,'add',[101:150]','Virginica');
45
+  
46
+  echo on
47
+end
48
+
49
+sD = som_normalize(sD,'var');
50
+sM = som_make(sD);
51
+sM = som_autolabel(sM,sD,'vote');
52
+
53
+pause % Strike any key to visualize the map...
54
+
55
+clc 
56
+%    VISUAL INSPECTION OF THE MAP
57
+%    ============================
58
+
59
+%    The first step in the analysis of the map is visual inspection.
60
+%    Here is the U-matrix, component planes and labels (you may
61
+%    need to enlarge the figure in order to make out the labels).
62
+
63
+som_show(sM,'umat','all','comp',[1:4],'empty','Labels','norm','d');
64
+som_show_add('label',sM.labels,'textsize',8,'textcolor','r','subplot',6);
65
+
66
+%    From this first visualization, one can see that:
67
+%     - there are essentially two clusters
68
+%     - PetalL and PetalW are highly correlated
69
+%     - SepalL is somewhat correlated to PetalL and PetalW
70
+%     - one cluster corresponds to the Setosa species and exhibits
71
+%       small petals and short but wide sepals
72
+%     - the other cluster corresponds to Virginica and Versicolor
73
+%       such that Versicolor has smaller leaves (both sepal and
74
+%       petal) than Virginica
75
+%     - inside both clusters, SepalL and SepalW are highly correlated
76
+
77
+pause % Strike any key to continue...
78
+
79
+%    Next, the projection of the data set is investigated. A
80
+%    principle component projection is made for the data, and applied
81
+%    to the map. The colormap is done by spreading a colormap on the
82
+%    projection. Distance matrix information is extracted from the
83
+%    U-matrix, and it is modified by knowledge of zero-hits
84
+%    (interpolative) units. Finally, three visualizations are shown:
85
+%    the color code, with clustering information and the number of
86
+%    hits in each unit, the projection and the labels.
87
+
88
+echo off
89
+
90
+f1=figure;
91
+[Pd,V,me,l] = pcaproj(sD,2); Pm = pcaproj(sM,V,me); % PC-projection
92
+Code = som_colorcode(Pm); % color coding
93
+hits = som_hits(sM,sD);  % hits
94
+U = som_umat(sM); % U-matrix
95
+Dm = U(1:2:size(U,1),1:2:size(U,2)); % distance matrix
96
+Dm = 1-Dm(:)/max(Dm(:)); Dm(find(hits==0)) = 0; % clustering info
97
+
98
+subplot(1,3,1)
99
+som_cplane(sM,Code,Dm);
100
+hold on
101
+som_grid(sM,'Label',cellstr(int2str(hits)),...
102
+	 'Line','none','Marker','none','Labelcolor','k');
103
+hold off 
104
+title('Color code')
105
+
106
+subplot(1,3,2)
107
+som_grid(sM,'Coord',Pm,'MarkerColor',Code,'Linecolor','k');
108
+hold on, plot(Pd(:,1),Pd(:,2),'k+'), hold off, axis tight, axis equal
109
+title('PC projection')
110
+
111
+subplot(1,3,3)
112
+som_cplane(sM,'none')
113
+hold on
114
+som_grid(sM,'Label',sM.labels,'Labelsize',8,...
115
+	 'Line','none','Marker','none','Labelcolor','r');
116
+hold off
117
+title('Labels')
118
+
119
+echo on
120
+
121
+%    From these figures one can see that: 
122
+%     - the projection confirms the existence of two different clusters
123
+%     - interpolative units seem to divide the Virginica
124
+%       flowers into two classes, the difference being in the size of
125
+%       sepal leaves
126
+    
127
+pause % Strike any key to continue...
128
+
129
+%    Finally, perhaps the most informative figure of all: simple
130
+%    scatter plots and histograms of all variables. The species
131
+%    information is coded as a fifth variable: 1 for Setosa, 2 for
132
+%    Versicolor and 3 for Virginica. Original data points are in the
133
+%    upper triangle, map prototype values on the lower triangle, and
134
+%    histograms on the diagonal: black for the data set and red for
135
+%    the map prototype values. The color coding of the data samples
136
+%    has been copied from the map (from the BMU of each sample). Note
137
+%    that the variable values have been denormalized.
138
+
139
+echo off
140
+
141
+% denormalize and add species information
142
+names = sD.comp_names; names{end+1} = 'species';
143
+D = som_denormalize(sD.data,sD); dlen = size(D,1);
144
+s = zeros(dlen,1)+NaN; s(strcmp(sD.labels,'Setosa'))=1;
145
+s(strcmp(sD.labels,'Versicolor'))=2; s(strcmp(sD.labels,'Virginica'))=3;
146
+D = [D, s];
147
+M = som_denormalize(sM.codebook,sM); munits = size(M,1);
148
+s = zeros(munits,1)+NaN; s(strcmp(sM.labels,'Setosa'))=1;
149
+s(strcmp(sM.labels,'Versicolor'))=2; s(strcmp(sM.labels,'Virginica'))=3;
150
+M = [M, s];
151
+
152
+f2=figure;
153
+
154
+% color coding copied from the map
155
+bmus = som_bmus(sM,sD); Code_data = Code(bmus,:); 
156
+
157
+k=1; 
158
+for i=1:5, for j=1:5, 
159
+    if i<j, i1=i; i2=j; else i1=j; i2=i; end
160
+    subplot(5,5,k); cla
161
+    if i<j,
162
+      som_grid('rect',[dlen 1],'coord',D(:,[i1 i2]),...
163
+	       'Line','none','MarkerColor',Code_data,'Markersize',2);
164
+      title(sprintf('%s vs. %s',names{i1},names{i2}))
165
+    elseif i>j,
166
+      som_grid(sM,'coord',M(:,[i1 i2]),...
167
+	       'markersize',2,'MarkerColor',Code);
168
+      title(sprintf('%s vs. %s',names{i1},names{i2}))
169
+    else
170
+      if i1<5, b = 10; else b = 3; end
171
+      [nd,x] = hist(D(:,i1),b); nd=nd/sum(nd); 
172
+      nm = hist(M(:,i1),x); nm = nm/sum(nm);
173
+      h=bar(x,nd,0.8); set(h,'EdgeColor','none','FaceColor','k'); 
174
+      hold on 
175
+      h=bar(x,nm,0.3); set(h,'EdgeColor','none','FaceColor','r'); 
176
+      hold off
177
+      title(names{i1})
178
+    end
179
+    k=k+1;
180
+  end
181
+end
182
+
183
+echo on
184
+
185
+%    This visualization shows quite a lot of information:
186
+%    distributions of single and pairs of variables both in the data
187
+%    and in the map. If the number of variables was even slightly
188
+%    more, it would require a really big display to be convenient to
189
+%    use.
190
+
191
+%    From this visualization we can conform many of the earlier
192
+%    conclusions, for example: 
193
+%     - there are two clusters: 'Setosa' (blue, dark green) and 
194
+%       'Virginica'/'Versicolor' (light green, yellow, reds)
195
+%       (see almost any of the subplots)
196
+%     - PetalL and PetalW have a high linear correlation (see
197
+%       subplots 4,3 and 3,4)
198
+%     - SepalL is correlated (at least in the bigger cluster) with
199
+%       PetalL and PetalW (in subplots 1,3 1,4 3,1 and 4,1)
200
+%     - SepalL and SepalW have a clear linear correlation, but it
201
+%       is slightly different for the two main clusters (in
202
+%       subplots 2,1 and 1,2)       
203
+
204
+pause % Strike any key to cluster the map...
205
+
206
+close(f1), close(f2), figure(f0), clf
207
+
208
+clc 
209
+%    CLUSTERING OF THE MAP
210
+%    =====================
211
+
212
+%    Visual inspection already hinted that there are at least two
213
+%    clusters in the data, and that the properties of the clusters are
214
+%    different from each other (esp. relation of SepalL and
215
+%    SepalW). For further investigation, the map needs to be
216
+%    partitioned.
217
+
218
+%    Here, the KMEANS_CLUSTERS function is used to find an initial
219
+%    partitioning. The plot shows the Davies-Boulding clustering
220
+%    index, which is minimized with best clustering.
221
+
222
+subplot(1,3,1)
223
+[c,p,err,ind] = kmeans_clusters(sM, 7); % find at most 7 clusters
224
+plot(1:length(ind),ind,'x-')
225
+[dummy,i] = min(ind)
226
+cl = p{i};
227
+
228
+%    The Davies-Boulding index seems to indicate that there are
229
+%    two clusters on the map. Here is the clustering info
230
+%    calculated previously and the partitioning result: 
231
+
232
+subplot(1,3,2)
233
+som_cplane(sM,Code,Dm)
234
+subplot(1,3,3)
235
+som_cplane(sM,cl)
236
+
237
+%    You could use also function SOM_SELECT to manually make or modify
238
+%    the partitioning.
239
+
240
+%    After this, the analysis would proceed with summarization of the
241
+%    results, and analysis of each cluster one at a time.
242
+%    Unfortunately, you have to do that yourself. The SOM Toolbox does
243
+%    not, yet, have functions for those purposes.
244
+
245
+pause % Strike any key to continue...
246
+
247
+
248
+clf
249
+clc 
250
+%    MODELING
251
+%    ========
252
+
253
+%    One can also build models on top of the SOM. Typically, these
254
+%    models are simple local or nearest-neighbor models. 
255
+
256
+%    Here, SOM is used for probability density estimation. Each map 
257
+%    prototype is the center of a gaussian kernel, the parameters
258
+%    of which are estimated from the data. The gaussian mixture
259
+%    model is estimated with function SOM_ESTIMATE_GMM and the
260
+%    probabilities can be calculated with SOM_PROBABILITY_GMM.
261
+
262
+[K,P] = som_estimate_gmm(sM,sD);
263
+[pd,Pdm,pmd] = som_probability_gmm(sD,sM,K,P);
264
+
265
+%    Here is the probability density function value for the first data
266
+%    sample (x=sD.data(:,1)) in terms of each map unit (m):
267
+
268
+som_cplane(sM,Pdm(:,1))
269
+colorbar
270
+title('p(x|m)')
271
+
272
+pause % Strike any key to continue...
273
+
274
+%    Here, SOM is used for classification. Although the SOM can be
275
+%    used for classification as such, one has to remember that it does
276
+%    not utilize class information at all, and thus its results are
277
+%    inherently suboptimal. However, with small modifications, the
278
+%    network can take the class into account. The function
279
+%    SOM_SUPERVISED does this.
280
+
281
+%    Learning vector quantization (LVQ) is an algorithm that is very
282
+%    similar to the SOM in many aspects. However, it is specifically
283
+%    designed for classification. In the SOM Toolbox, there are
284
+%    functions LVQ1 and LVQ3 that implement two versions of this
285
+%    algorithm.
286
+
287
+%    Here, the function SOM_SUPERVISED is used to create a classifier
288
+%    for IRIS data set:
289
+
290
+sM = som_supervised(sD,'small');
291
+
292
+som_show(sM,'umat','all');
293
+som_show_add('label',sM.labels,'TextSize',8,'TextColor','r')
294
+
295
+sD2 = som_label(sD,'clear','all'); 
296
+sD2 = som_autolabel(sD2,sM);       % classification
297
+ok = strcmp(sD2.labels,sD.labels); % errors
298
+100*(1-sum(ok)/length(ok))         % error percentage (%)
299
+
300
+echo off
301
+
302
+
303
+
304
+
305
+
306
+
307
+
... ...
@@ -0,0 +1,292 @@
1
+function [h,Coord,Color,height] = som_dendrogram(Z,varargin)
2
+
3
+%SOM_DENDROGRAM Visualize a dendrogram.
4
+%
5
+% [h,Coord,Color,height] = som_dendrogram(Z, [[argID,] value, ...])
6
+%
7
+%  Z = som_linkage(sM); 
8
+%  som_dendrogram(Z); 
9
+%  som_dendrogram(Z,sM); 
10
+%  som_dendrogram(Z,'coord',co); 
11
+%
12
+%  Input and output arguments ([]'s are optional):
13
+%   h        (vector) handle to the arc lines
14
+%   Z        (matrix) size n-1 x 1, the hierarchical cluster matrix
15
+%                     returned by functions like LINKAGE and SOM_LINKAGE
16
+%                     n is the number of original data samples.
17
+%   [argID,  (string) See below. The values which are unambiguous can 
18
+%    value]  (varies) be given without the preceeding argID.
19
+%   Coord    (matrix) size 2*n-1 x {1,2}, the coordinates of the
20
+%                     original data samples and cluster nodes used 
21
+%                     in the visualization
22
+%   Color    (matrix) size 2*n-1 x 3, the colors of ...
23
+%   height   (vector) size 2*n-1 x 1, the heights of ...
24
+%   
25
+% Here are the valid argument IDs and corresponding values. The values 
26
+% which are unambiguous (marked with '*') can be given without the
27
+% preceeding argID.
28
+%   'data'  *(struct) map or data struct: many other optional 
29
+%                     arguments require this 
30
+%            (matrix) data matrix
31
+%   'coord'  (matrix) size n x 1 or n x 2, the coordinates of 
32
+%                     the original data samples either in 1D or 2D
33
+%            (matrix) size 2*n-1 x {1,2}, the coordinates of both
34
+%                     original data samples and each cluster
35
+%           *(string) 'SOM', 'pca#', 'sammon#', or 'cca#': the coordinates
36
+%                     are calculated using the given data and the 
37
+%                     required projection algorithm. The '#' at the
38
+%                     end of projection algorithms refers to the 
39
+%                     desired output dimension and can be either 1 or 2
40
+%                     (2 by default). In case of 'SOM', the unit
41
+%                     coordinates (given by SOM_VIS_COORDS) are used.
42
+%   'color'  (matrix) size n x 3, the color of the original data samples
43
+%            (matrix) size 2*n-1 x 3, the colors of both original 
44
+%                     data samples and each cluster
45
+%            (string) color specification, e.g. 'r.', used for each node
46
+%   'height' (vector) size n-1 x 1, the heights used for each cluster
47
+%            (vector) size 2*n-1 x 1, the heights used for both original
48
+%                     data samples and each cluster
49
+%           *(string) 'order', the order of combination determines height
50
+%                     'depth', the depth at which the combination
51
+%                     happens determines height
52
+%   'linecolor' (string) color specification for the arc color, 'k' by default
53
+%               (vector) size 1 x 3
54
+%
55
+% See also SOM_LINKAGE, DENDROGRAM.
56
+
57
+% Copyright (c) 2000 by Juha Vesanto
58
+% Contributed to SOM Toolbox on June 16th, 2000 by Juha Vesanto
59
+% http://www.cis.hut.fi/projects/somtoolbox/
60
+ 
61
+% Version 2.0beta juuso 160600
62
+
63
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
64
+%% read the arguments
65
+
66
+% Z 
67
+nd = size(Z,1)+1; 
68
+nc = size(Z,1); 
69
+
70
+% varargin
71
+Coordtype = 'natural'; Coord = []; codim = 1; 
72
+Colortype = 'none'; Color = [];
73
+height = [zeros(nd,1); Z(:,3)]; 
74
+M = []; 
75
+linecol = 'k'; 
76
+
77
+i=1; 
78
+while i<=length(varargin), 
79
+  argok = 1; 
80
+  if ischar(varargin{i}), 
81
+    switch varargin{i}, 
82
+     case 'data', i = i + 1; M = varargin{i}; 
83
+     case 'coord', 
84
+      i=i+1; 
85
+      if isnumeric(varargin{i}), Coord = varargin{i}; Coordtype = 'given'; 
86
+      else 
87
+	if strcmp(varargin{i},'SOM'), Coordtype = 'SOM'; 
88
+	else Coordtype = 'projection'; Coord = varargin{i}; 
89
+	end
90
+      end
91
+     case 'color', 
92
+      i=i+1; 
93
+      if isempty(varargin{i}), Colortype = 'none'; 
94
+      elseif ischar(varargin{i}), Colortype = 'colorspec'; Color = varargin{i};
95
+      else Colortype = 'given'; Color = varargin{i}; 
96
+      end
97
+     case 'height', i=i+1; height = varargin{i}; 
98
+     case 'linecolor', i=i+1; linecol = varargin{i}; 
99
+     case 'SOM', 
100
+      Coordtype = 'SOM'; 
101
+     case {'pca','pca1','pca2','sammon','sammon1','sammon2','cca','cca1','cca2'}, 
102
+      Coordtype = 'projection'; Coord = varargin{i}; 
103
+     case {'order','depth'}, height = varargin{i};  
104
+    end
105
+  elseif isstruct(varargin{i}), M = varargin{i}; 
106
+  else
107
+    argok = 0; 
108
+  end
109
+  if ~argok, 
110
+    disp(['(som_dendrogram) Ignoring invalid argument #' num2str(i+1)]); 
111
+  end
112
+  i = i+1; 
113
+end
114
+
115
+switch Coordtype, 
116
+ case 'SOM', 
117
+  if isempty(M) | ~any(strcmp(M.type,{'som_map','som_topol'})) , 
118
+    error('Cannot determine SOM coordinates without a SOM.'); 
119
+  end
120
+  if strcmp(M.type,'som_map'), M = M.topol; end
121
+ case 'projection', 
122
+  if isempty(M), error('Cannot do projection without the data.'); end
123
+  if isstruct(M), 
124
+    if strcmp(M.type,'som_data'), M = M.data; 
125
+    elseif strcmp(M.type,'som_map'), M = M.codebook; 
126
+    end
127
+  end  
128
+  if size(M,1) ~= nd, 
129
+    error('Given data must be equal in length to the number of original data samples.')
130
+  end    
131
+ case 'given', 
132
+  if size(Coord,1) ~= nd & size(Coord,1) ~= nd+nc, 
133
+    error('Size of given coordinate matrix does not match the cluster hierarchy.');
134
+  end  
135
+end
136
+
137
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
138
+%% initialization
139
+
140
+% Coordinates
141
+switch Coordtype, 
142
+ case 'natural', o = leavesorder(Z)'; [dummy,Coord] = sort(o); codim = 1; 
143
+ case 'SOM', Coord = som_vis_coords(M.lattice,M.msize); codim = 2;   
144
+ case 'projection', 
145
+  switch Coord, 
146
+   case {'pca','pca2'},       Coord = pcaproj(M,2);   codim = 2; 
147
+   case 'pca1',               Coord = pcaproj(M,1);   codim = 1; 
148
+   case {'cca','cca2'},       Coord = cca(M,2,20);    codim = 2; 
149
+   case 'cca1',               Coord = cca(M,1,20);    codim = 1; 
150
+   case {'sammon','sammon2'}, Coord = sammon(M,2,50); codim = 2; 
151
+   case 'sammon1',            Coord = sammon(M,1,50); codim = 1; 
152
+  end
153
+ case 'given', codim = min(size(Coord,2),2); % nill
154
+end
155
+
156
+if size(Coord,1) == nd, 
157
+  Coord = [Coord; zeros(nc,size(Coord,2))]; 
158
+  for i=(nd+1):(nd+nc), 
159
+    leaves = leafnodes(Z,i,nd);
160
+    if any(leaves), Coord(i,:) = mean(Coord(leaves,:),1); else Coord(i,:) = Inf; end
161
+  end
162
+end
163
+
164
+% Colors
165
+switch Colortype, 
166
+ case 'colorspec', % nill
167
+ case 'none', Color = ''; 
168
+ case 'given',
169
+  if size(Color,1) == nd, 
170
+    Color = [Color; zeros(nc,3)]; 
171
+    for i=(nd+1):(nd+nc), 
172
+      leaves = leafnodes(Z,i,nd);
173
+      if any(leaves), Color(i,:) = mean(Color(leaves,:),1); 
174
+      else Color(i,:) = 0.8; 
175
+      end
176
+    end
177
+  end
178
+end
179
+
180
+% height
181
+if ischar(height), 
182
+  switch height, 
183
+   case 'order', height = [zeros(nd,1); [1:nc]']; 
184
+   case 'depth', height = nodedepth(Z); height = max(height) - height; 
185
+  end
186
+else
187
+  if length(height)==nc, height = [zeros(nd,1); height]; end
188
+end
189
+
190
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
191
+%% draw
192
+
193
+% the arcs
194
+lfrom = []; lto = []; 
195
+for i=1:nd+nc, 
196
+  if i<=nd, ch = [];  
197
+  elseif ~isfinite(Z(i-nd,3)), ch = []; 
198
+  else ch = Z(i-nd,1:2)'; 
199
+  end
200
+  if any(ch), 
201
+    lfrom = [lfrom; i*ones(length(ch),1)]; 
202
+    lto = [lto; ch]; 
203
+  end
204
+end
205
+
206
+% the coordinates of the arcs
207
+if codim == 1, 
208
+  Lx = [Coord(lfrom), Coord(lto), Coord(lto)];
209
+  Ly = [height(lfrom), height(lfrom), height(lto)];
210
+  Lz = []; 
211
+else
212
+  Lx = [Coord(lfrom,1), Coord(lto,1), Coord(lto,1)];
213
+  Ly = [Coord(lfrom,2), Coord(lto,2), Coord(lto,2)];
214
+  Lz = [height(lfrom), height(lfrom), height(lto)];
215
+end
216
+
217
+washold = ishold; 
218
+if ~washold, cla; end
219
+
220
+% plot the lines
221
+if isempty(Lz), 
222
+  h = line(Lx',Ly','color',linecol); 
223
+else 
224
+  h = line(Lx',Ly',Lz','color',linecol); 
225
+  if ~washold, view(3); end
226
+  rotate3d on
227
+end
228
+
229
+% plot the nodes
230
+hold on
231
+switch Colortype, 
232
+ case 'none', % nill
233
+ case 'colorspec', 
234
+  if codim == 1, plot(Coord,height,Color); 
235
+  else plot3(Coord(:,1), Coord(:,2), height, Color); 
236
+  end
237
+ case 'given', 
238
+  som_grid('rect',[nd+nc 1],'line','none','Coord',[Coord, height],...
239
+	   'Markersize',10,'Markercolor',Color);
240
+end
241
+if ~washold, hold off, end
242
+
243
+return;
244
+
245
+
246
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
247
+%% subfunctions
248
+
249
+function depth = nodedepth(Z)
250
+
251
+  nd = size(Z,1)+1; 
252
+  nc = size(Z,1);  
253
+  depth = zeros(nd+nc,1); 
254
+  ch = nc+nd-1; 
255
+  while any(ch), 
256
+    c  = ch(1); ch = ch(2:end);
257
+    if c>nd & isfinite(Z(c-nd,3)), 
258
+      chc = Z(c-nd,1:2); 
259
+      depth(chc) = depth(c) + 1; 
260
+      ch = [ch, chc]; 
261
+    end
262
+  end
263
+  return;
264
+
265
+function inds = leafnodes(Z,i,nd)
266
+
267
+  inds = []; 
268
+  ch = i; 
269
+  while any(ch), 
270
+    c  = ch(1); ch = ch(2:end);
271
+    if c>nd & isfinite(Z(c-nd,3)), ch = [ch, Z(c-nd,1:2)]; end
272
+    if c<=nd, inds(end+1) = c; end 
273
+  end
274
+  return;
275
+
276
+function order = leavesorder(Z)
277
+
278
+  nd = size(Z,1)+1;
279
+  order = 2*nd-1; 
280
+  nonleaves = 1; 
281
+  while any(nonleaves), 
282
+    j = nonleaves(1); 
283
+    ch = Z(order(j)-nd,1:2);
284
+    if j==1, oleft = []; else oleft = order(1:(j-1)); end
285
+    if j==length(order), oright = []; else oright = order((j+1):length(order)); end
286
+    order = [oleft, ch, oright];
287
+    nonleaves = find(order>nd); 
288
+  end
289
+  return; 
290
+
291
+
292
+  
0 293
\ No newline at end of file
... ...
@@ -0,0 +1,293 @@
1
+function sD = som_denormalize(sD,varargin)
2
+
3
+%SOM_DENORMALIZE Denormalize data.
4
+%   
5
+% sS = som_denormalize(sS, [argID, value, ...])               
6
+%
7
+%   sS = som_denormalize(sS) 
8
+%   sS = som_denormalize(sS,[1:3 10],'remove') 
9
+%    D = som_denormalize(D,sM.comp_norm)
10
+%    D = som_denormalize(D,sM,[1:3 10])
11
+%
12
+%  Input and output arguments ([]'s are optional): 
13
+%   sS                The data to which the denormalization is applied.
14
+%                     The modified and updated data is returned.
15
+%            (struct) data or map struct
16
+%            (matrix) data matrix (a matrix is also returned)
17
+%   [argID, (string) See below. The values which are unambiguous can 
18
+%    value] (varies) be given without the preceeding argID.
19
+%
20
+% Here are the valid argument IDs and corresponding values. The values which
21
+% are unambiguous (marked with '*') can be given without the preceeding argID.
22
+%   'norm'   *(struct) Normalization struct, or an array of such. 
23
+%                      Alternatively, a map/data struct can be given 
24
+%                      in which case its '.comp_norm' field is used 
25
+%                      (see below).
26
+%            *(cell array) Of normalization structs. Typically, the
27
+%                      '.comp_norm' field of a map/data struct. The 
28
+%                      length of the array must be equal to data dimension.
29
+%   'remove' *(string) If 'remove' tag is specified, the
30
+%                      normalization operations are not only undone, 
31
+%                      they are also removed from the struct.
32
+%   'comps'  *(vector) the components to which the denormalization is
33
+%                      applied, default is [1:dim] ie. all components
34
+%
35
+% For more help, try 'type som_denormalize' or check out online documentation.
36
+% See also SOM_NORMALIZE, SOM_NORM_VARIABLE, SOM_INFO.
37
+
38
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
39
+%
40
+% som_denormalize
41
+%
42
+% PURPOSE
43
+%
44
+% Undo normalizations of data structs/sets.
45
+%
46
+% SYNTAX
47
+%
48
+%  sS = som_denormalize(sS)
49
+%  sS = som_denormalize(...,'argID',value,...);
50
+%  sS = som_denormalize(...,value,...);
51
+%   D = som_denormalize(D,sNorm)
52
+%
53
+% DESCRIPTION
54
+%
55
+% This function is used to undo normalizations of data structs/sets. If a
56
+% data/map struct is given, all normalizations in the '.comp_norm' field are
57
+% undone and, thus, the values in the original data context are returned. If
58
+% a matrix is given, the normalizations to undo must be given as the second
59
+% argument. SOM_DENORMALIZE actually uses function SOM_NORM_VARIABLE to
60
+% handle the normalization operations, and only handles the data struct/set
61
+% specific stuff itself.
62
+%
63
+% Normalizations are always one-variable operations. In the data and map
64
+% structs the normalization information for each component is saved in the
65
+% '.comp_norm' field, which is a cell array of length dim. Each cell
66
+% contains normalizations for one vector component in a
67
+% struct array of normalization structs. Each component may have different
68
+% amounts of different kinds of normalizations. Typically, all
69
+% normalizations are either 'undone' or 'done', but in special situations
70
+% this may not be the case. The easiest way to check out the status of the
71
+% normalizations is to use function SOM_INFO, e.g. som_info(sS,3)
72
+% 
73
+% REQUIRED INPUT ARGUMENTS
74
+%
75
+%   sS                The data to which the denormalization is applied.
76
+%            (struct) Data or map struct. The normalizations in the 
77
+%                     '.comp_norm' field are undone for the specified 
78
+%                     components.
79
+%            (matrix) Data matrix. The normalization to undo must be
80
+%                     given in the second argument.
81
+%
82
+% OPTIONAL INPUT ARGUMENTS
83
+%
84
+%  argID (string) Argument identifier string (see below).
85
+%  value (varies) Value for the argument (see below).
86
+%
87
+%  The optional arguments can be given as 'argID',value -pairs. If an
88
+%  argument is given value multiple times, the last one is used. The
89
+%  valid IDs and corresponding values are listed below. The values
90
+%  which are unambiguous (marked with '*') can be given without the
91
+%  preceeding argID.
92
+%
93
+%   sNorm    *(struct) Normalization struct, or an array of structs, which
94
+%                      is undone for all specified components. If the 
95
+%                      '.status' field of the struct(s) is 'uninit', 
96
+%                      the undoing operation is interrupted - it cannot be 
97
+%                      done. Alternatively, the struct may be map or 
98
+%                      data struct in which case its '.comp_norm' field 
99
+%                      is used (see the cell array option below).
100
+%            *(cell array) In practice, the '.comp_norm' field of 
101
+%                      a data/map struct. The length of the array 
102
+%                      must be equal to the dimension of the given 
103
+%                      data set (sS). Each cell contains the
104
+%                      normalization(s) for one component. Only the
105
+%                       normalizations listed in comps argument are
106
+%                      undone though.
107
+%
108
+%   'remove' *(string) If 'remove' tag is specified, the
109
+%                      normalization operations are not only undone, 
110
+%                      they are also removed from the struct.
111
+%
112
+%   'comps'  *(vector) The components which are denormalized.
113
+%                      Default is to undo all components.
114
+%            *(string) 'all'
115
+%
116
+% OUTPUT ARGUMENTS
117
+% 
118
+%   sS                Modified and/or updated data.
119
+%            (struct) If a struct was given as input argument, the
120
+%                     same struct is returned with denormalized data and
121
+%                     updated '.comp_norm' fields. 
122
+%            (matrix) If a matrix was given as input argument, the 
123
+%                     denormalized data matrix is returned.
124
+% 
125
+% EXAMPLES
126
+%
127
+%  To undo normalization of a data/map struct: 
128
+%
129
+%    sD = som_denormalize(sD); 
130
+%    sM = som_denormalize(sM); 
131
+%
132
+%  To completely remove the normalizations, use the 'remove' tag: 
133
+%
134
+%    sD = som_denormalize(sD,'remove');
135
+%
136
+%  To undo only a few selected components, use the comps argument: 
137
+% 
138
+%    sD = som_denormalize(sD,[1 3:5]); 
139
+% 
140
+%  To denormalize a set of values from a data set D (which must be 
141
+%  of equal dimension as the data in sD): 
142
+%
143
+%    D = som_denormalize(D,sD); 
144
+%  or 
145
+%    D = som_denormalize(D,sD.comp_norm); 
146
+%  only denormalize a few components
147
+%    D = som_denormalize(D,sD,[1 3:5]); 
148
+% 
149
+%  Assuming you have a few values of a certain vector component (i)
150
+%  in a vector (x) which you want to denormalize: 
151
+%
152
+%    xorig = som_denormalize(x,sD.comp_norm{i}); 
153
+%  or using SOM_NORM_VARIABLE
154
+%    xorig = som_norm_variable(x,sD.comp_norm{i},'undo');
155
+%
156
+%  To check out the status of normalization in a struct use SOM_INFO: 
157
+% 
158
+%    som_info(sM,3)
159
+%    som_info(sD,3)
160
+%
161
+% SEE ALSO
162
+%  
163
+%  som_normalize      Add/apply/redo normalizations of a data struct/set.
164
+%  som_norm_variable  Normalization operations for a set of scalar values.
165
+%  som_info           User-friendly information of SOM Toolbox structs.
166
+
167
+% Copyright (c) 1998-2000 by the SOM toolbox programming team.
168
+% http://www.cis.hut.fi/projects/somtoolbox/
169
+
170
+% Version 2.0beta juuso 151199 150300
171
+
172
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
173
+%% check arguments
174
+
175
+error(nargchk(1, 3, nargin));  % check no. of input arguments is correct
176
+
177
+% sD
178
+struct_mode = isstruct(sD);
179
+if struct_mode, 
180
+  switch sD.type
181
+   case 'som_map', D = sD.codebook; 
182
+   case 'som_data', D = sD.data; 
183
+   otherwise, error('Illegal struct.')
184
+  end
185
+else 
186
+  D = sD;
187
+end
188
+[dlen dim] = size(D);
189
+
190
+% varargin
191
+comps = [1:dim];
192
+remove_tag = 0;
193
+if struct_mode, sNorm = sD.comp_norm; else sNorm = []; end
194
+i=1; 
195
+while i<=length(varargin), 
196
+  argok = 1; 
197
+  if ischar(varargin{i}), 
198
+    switch varargin{i}, 
199
+     % argument IDs
200
+     case 'comps', i=i+1; comps = varargin{i}; 
201
+     case {'norm','sNorm','som_norm'}, i=i+1; sNorm = varargin{i};
202
+     % unambiguous values
203
+     case 'remove', remove_tag = 1;
204
+     otherwise argok=0; 
205
+    end    
206
+  elseif isnumeric(varargin{i}), 
207
+    comps = varargin{i};
208
+  elseif isstruct(varargin{i}), 
209
+    sNorm = varargin{i};
210
+  elseif iscell(varargin{i}), 
211
+    sNorm = varargin{i};
212
+  else
213
+    argok = 0; 
214
+  end
215
+  if ~argok, 
216
+    disp(['(som_denormalize) Ignoring invalid argument #' num2str(i+1)]); 
217
+  end
218
+  i = i+1; 
219
+end
220
+
221
+% check comps
222
+if ischar(comps), comps = [1:dim]; end
223
+if isempty(comps), return; end
224
+if size(comps,1)>1, comps = comps'; end  % make it a row vector
225
+
226
+% sNorm
227
+% check out the given normalization
228
+% (and if necessary, copy it for each specified component)
229
+if isstruct(sNorm),
230
+  switch sNorm(1).type, 
231
+   case {'som_map','som_data'}, csNorm = sNorm(1).comp_norm; 
232
+   case {'som_norm'}, for i=comps, csNorm{i} = sNorm; end
233
+   otherwise, 
234
+    error('Invalid struct for sNorm.')
235
+  end
236
+elseif iscell(sNorm), 
237
+  csNorm = sNorm; 
238
+else
239
+  error('Illegal value for sNorm.')
240
+end
241
+
242
+% check that csNorm and comps possibly agree
243
+if max(comps) > length(csNorm), 
244
+  error('Given normalizations does not match the components.')
245
+end  
246
+if length(csNorm) ~= dim, 
247
+  error('Given normalizations does not match data dimension.')
248
+end  
249
+
250
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
251
+%% action
252
+
253
+% undo the normalizations 
254
+for i = comps, 
255
+  len = length(csNorm{i});
256
+  for j=len:-1:1, 
257
+    sN = csNorm{i}(j); 
258
+    if struct_mode, 
259
+      if strcmp(sN.status,'done'), 
260
+	[x,sN] = som_norm_variable(D(:,i), sN, 'undo'); 
261
+	D(:,i) = x; 
262
+	csNorm{i}(j) = sN; 
263
+      end      
264
+    else
265
+      D(:,i) = som_norm_variable(D(:,i), sN, 'undo'); 
266
+    end
267
+  end
268
+end
269
+
270
+% remove normalizations
271
+if struct_mode & remove_tag, 
272
+  for i = comps, csNorm{i} = []; end
273
+end
274
+
275
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
276
+%% output 
277
+
278
+
279
+if struct_mode, 
280
+  switch sD.type
281
+   case 'som_map', sD.codebook = D; 
282
+   case 'som_data', sD.data = D; 
283
+   otherwise, error('Illegal struct.')
284
+  end
285
+  sD.comp_norm = csNorm; 
286
+else
287
+  sD = D;
288
+end
289
+
290
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
291
+
292
+
293
+
... ...
@@ -0,0 +1,138 @@
1
+function [adm,admu,tdmu] = som_distortion(sM, D, arg1, arg2)
2
+
3
+%SOM_DISTORTION Calculate distortion measure for the map.
4
+%
5
+% [adm,admu,tdmu] = som_distortion(sMap, D, [radius], ['prob'])
6
+%
7
+%  adm = som_distortion(sMap,D);
8
+%  [adm,admu] = som_distortion(sMap,D);
9
+%  som_show(sMap,'color',admu);
10
+%
11
+%  Input and output arguments: 
12
+%   sMap     (struct) a map struct
13
+%   D        (struct) a data struct
14
+%            (matrix) size dlen x dim, a data matrix
15
+%   [radius] (scalar) neighborhood function radius to be used.
16
+%                     Defaults to the last radius_fin in the 
17
+%                     trainhist field of the map struct, or 1 if
18
+%                     that is missing.
19
+%   ['prob'] (string) If given, this argument forces the 
20
+%                     neigborhood function values for each map
21
+%                     unit to be normalized so that they sum to 1.
22
+%
23
+%   adm      (scalar) average distortion measure (sum(dm)/dlen)
24
+%   admu     (vector) size munits x 1, average distortion in each unit 
25
+%   tdmu     (vector) size munits x 1, total distortion for each unit
26
+%
27
+% The distortion measure is defined as: 
28
+%                                           2
29
+%    E = sum sum h(bmu(i),j) ||m(j) - x(i)|| 
30
+%         i   j    
31
+% 
32
+% where m(i) is the ith prototype vector of SOM, x(j) is the jth data
33
+% vector, and h(.,.) is the neighborhood function. In case of fixed
34
+% neighborhood and discreet data, the distortion measure can be
35
+% interpreted as the energy function of the SOM. Note, though, that
36
+% the learning rule that follows from the distortion measure is
37
+% different from the SOM training rule, so SOM only minimizes the
38
+% distortion measure approximately.
39
+% 
40
+% If the 'prob' argument is given, the distortion measure can be 
41
+% interpreted as an expected quantization error when the neighborhood 
42
+% function values give the likelyhoods of accidentally assigning 
43
+% vector j to unit i. The normal quantization error is a special case 
44
+% of this with zero incorrect assignement likelihood. 
45
+% 
46
+% NOTE: when calculating BMUs and distances, the mask of the given 
47
+%       map is used.
48
+%
49
+% See also SOM_QUALITY, SOM_BMUS, SOM_HITS.
50
+
51
+% Reference: Kohonen, T., "Self-Organizing Map", 2nd ed., 
52
+%    Springer-Verlag, Berlin, 1995, pp. 120-121.
53
+%
54
+%    Graepel, T., Burger, M. and Obermayer, K., 
55
+%    "Phase Transitions in Stochastic Self-Organizing Maps",
56
+%    Physical Review E, Vol 56, No 4, pp. 3876-3890 (1997).
57
+
58
+% Contributed to SOM Toolbox vs2, Feb 3rd, 2000 by Juha Vesanto
59
+% Copyright (c) by Juha Vesanto
60
+% http://www.cis.hut.fi/projects/somtoolbox/
61
+
62
+% Version 2.0beta juuso 030200
63
+
64
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
65
+%% check arguments
66
+
67
+% input arguments
68
+if nargin < 2, error('Not enough input arguments.'); end
69
+
70
+% map
71
+M = sM.codebook;
72
+munits = prod(sM.topol.msize);
73
+
74
+% data
75
+if isstruct(D), D = D.data; end
76
+[dlen dim] = size(D);
77
+
78
+% arg1, arg2
79
+rad = NaN;
80
+normalize = 0;
81
+if nargin>2, 
82
+  if isnumeric(arg1), rad = arg1;
83
+  elseif ischar(arg1) & strcmp(arg1,'prob'), normalize = 0;
84
+  end
85
+end
86
+if nargin>3, 
87
+  if isnumeric(arg2), rad = arg2;
88
+  elseif ischar(arg2) & strcmp(arg2,'prob'), normalize = 0;
89
+  end
90
+end
91
+
92
+% neighborhood radius
93
+if isempty(rad) | isnan(rad), 
94
+  if ~isempty(sM.trainhist), rad = sM.trainhist(end).radius_fin;
95
+  else rad = 1; 
96
+  end
97
+end
98
+if rad<eps, rad = eps; end
99
+
100
+% neighborhood  
101
+Ud = som_unit_dists(sM.topol); 
102
+switch sM.neigh, 
103
+ case 'bubble',   H = (Ud <= rad);
104
+ case 'gaussian', H = exp(-(Ud.^2)/(2*rad*rad)); 
105
+ case 'cutgauss', H = exp(-(Ud.^2)/(2*rad*rad)) .* (Ud <= rad);
106
+ case 'ep',       H = (1 - (Ud.^2)/rad) .* (Ud <= rad);
107
+end  
108
+if normalize, 
109
+  for i=1:munits, H(:,i) = H(:,i)/sum(H(:,i)); end
110
+end
111
+
112
+% total distortion measure
113
+mu_x_1 = ones(munits,1);
114
+tdmu = zeros(munits,1);
115
+hits = zeros(munits,1);
116
+for i=1:dlen,
117
+  x = D(i,:);                        % data sample
118
+  known = ~isnan(x);                 % its known components
119
+  Dx = M(:,known) - x(mu_x_1,known); % each map unit minus the vector
120
+  dist2 = (Dx.^2)*sM.mask(known);    % squared distances  
121
+  [qerr bmu] = min(dist2);           % find BMU
122
+  tdmu = tdmu + dist2.*H(:,bmu);     % add to distortion measure
123
+  hits(bmu) = hits(bmu)+1;           % add to hits
124
+end 
125
+
126
+% average distortion per unit
127
+admu = tdmu; 
128
+ind = find(hits>0);
129
+admu(ind) = admu(ind) ./ hits(ind);
130
+  
131
+% average distortion measure
132
+adm = sum(tdmu)/dlen;
133
+
134
+return;
135
+
136
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
137
+
138
+
... ...
@@ -0,0 +1,207 @@
1
+function [Err,sPropTotal,sPropMunits,sPropComps] = som_distortion3(sM,D,rad)
2
+
3
+%SOM_DISTORTION3 Map distortion measures.
4
+%  
5
+% [sE,Err] = som_distortion3(sM,[D],[rad]);
6
+% 
7
+%  sE = som_distortion3(sM); 
8
+%
9
+%  Input and output arguments ([]'s are optional): 
10
+%   sM          (struct) map struct
11
+%   [D]         (matrix) a matrix, size dlen x dim
12
+%               (struct) data or map struct
13
+%                        by default the map struct is used
14
+%   [rad]       (scalar) neighborhood radius, looked from sM.trainhist
15
+%                        by default, or = 1 if that has no valid values
16
+%                           
17
+%   Err         (matrix) size munits x dim x 3
18
+%                        distortion error elements (quantization error, 
19
+%                        neighborhood bias, and neighborhood variance)
20
+%                        for each map unit and component
21
+%   sPropTotal  (struct) .n   = length of data
22
+%                        .h   = mean neighborhood function value
23
+%                        .err = errors
24
+%   sPropMunits (struct) .Ni  = hits per map unit
25
+%                        .Hi  = sum of neighborhood values for each map unit
26
+%                        .Err = errors per map unit
27
+%   sPropComps  (struct) .e1  = total squared distance to centroid
28
+%                        .eq  = total squared distance to BMU
29
+%                        .Err = errors per component
30
+%
31
+% See also  SOM_QUALITY.
32
+
33
+% Contributed to SOM Toolbox 2.0, January 3rd, 2002 by Juha Vesanto
34
+% Copyright (c) by Juha Vesanto
35
+% http://www.cis.hut.fi/projects/somtoolbox/
36
+
37
+% Version 2.0beta juuso 030102
38
+
39
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
40
+%% arguments
41
+
42
+% map
43
+[munits dim] = size(sM.codebook);
44
+
45
+% neighborhood radius
46
+if nargin<3, 
47
+  if ~isempty(sM.trainhist), 
48
+    rad = sM.trainhist(end).radius_fin; 
49
+  else 
50
+    rad = 1; 
51
+  end
52
+end
53
+if rad<eps, rad = eps; end
54
+if isempty(rad) | isnan(rad), rad = 1; end
55
+
56
+% neighborhood function
57
+Ud = som_unit_dists(sM.topol); 
58
+switch sM.neigh, 
59
+ case 'bubble',   H = (Ud <= rad);
60
+ case 'gaussian', H = exp(-(Ud.^2)/(2*rad*rad)); 
61
+ case 'cutgauss', H = exp(-(Ud.^2)/(2*rad*rad)) .* (Ud <= rad);
62
+ case 'ep',       H = (1 - (Ud.^2)/rad) .* (Ud <= rad);
63
+end  
64
+Hi = sum(H,2); 
65
+
66
+% data
67
+if nargin<2, D = sM.codebook; end
68
+if isstruct(D), D = D.data; end
69
+[dlen dim] = size(D);
70
+
71
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
72
+%% quality measures
73
+
74
+% find Voronoi sets, and calculate their properties
75
+
76
+[bmus,qerr] = som_bmus(sM,D); 
77
+M  = sM.codebook; 
78
+Vn = M; 
79
+Vm = M; 
80
+Ni = zeros(munits,dim);
81
+for i=1:munits, 
82
+  inds    = find(bmus==i);   
83
+  Ni(i,:) = sum(isfinite(D(inds,:)),1);                      % size of Voronoi set
84
+  if any(Ni(i,:)), Vn(i,:) = centroid(D(inds,:),M(i,:)); end % centroid of Voronoi set  
85
+  Vm(i,:) = centroid(M,M(i,:),H(i,:)');                      % centroid of neighborhood
86
+end
87
+
88
+HN = repmat(Hi,1,dim).*Ni; 
89
+
90
+%% distortion
91
+
92
+% quantization error (in each Voronoi set and for each component)
93
+
94
+Eqx           = zeros(munits,dim); 
95
+Dx            = (Vn(bmus,:) - D).^2; 
96
+Dx(isnan(Dx)) = 0; 
97
+for i = 1:dim, 
98
+  Eqx(:,i)    = full(sum(sparse(bmus,1:dlen,Dx(:,i),munits,dlen),2)); 
99
+end
100
+Eqx           = repmat(Hi,1,dim).*Eqx; 
101
+  
102
+% bias in neighborhood (in each Voronoi set / component)
103
+
104
+Enb = (Vn-Vm).^2;
105
+Enb = HN.*Enb; 
106
+
107
+% variance in neighborhood (in each Voronoi set / component)
108
+
109
+Env = zeros(munits,dim);
110
+for i=1:munits, Env(i,:) = H(i,:)*(M-Vm(i*ones(munits,1),:)).^2; end
111
+Env = Ni.*Env; 
112
+
113
+% total distortion (in each Voronoi set / component)
114
+
115
+Ed = Eqx + Enb + Env;
116
+
117
+%% other error measures
118
+
119
+% squared quantization error (to data centroid)
120
+
121
+me            = centroid(D,mean(M));
122
+Dx            = D - me(ones(dlen,1),:); 
123
+Dx(isnan(Dx)) = 0; 
124
+e1            = sum(Dx.^2,1); 
125
+
126
+% squared quantization error (to map units)
127
+
128
+Dx            = D - M(bmus,:);
129
+Dx(isnan(Dx)) = 0; 
130
+eq            = sum(Dx.^2,1);
131
+
132
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
133
+%% output
134
+
135
+% distortion error matrix
136
+
137
+Err  = zeros(munits,dim,5); 
138
+Err(:,:,1) = Eqx; 
139
+Err(:,:,2) = Enb; 
140
+Err(:,:,3) = Env; 
141
+
142
+% total errors
143
+
144
+sPropTotal = struct('n',sum(Ni),'h',mean(Hi),'e1',sum(e1),'err',sum(sum(Err,2),1));
145
+
146
+% properties of map units
147
+
148
+sPropMunits = struct('Ni',[],'Hi',[],'Err',[]); 
149
+sPropMunits.Ni  = Ni; 
150
+sPropMunits.Hi  = Hi; 
151
+sPropMunits.Err = squeeze(sum(Err,2));
152
+
153
+% properties of components
154
+
155
+sPropComps = struct('Err',[],'e1',[],'eq',[]);
156
+sPropComps.Err = squeeze(sum(Err,1));
157
+sPropComps.e1  = e1; 
158
+sPropComps.eq  = eq;
159
+
160
+
161
+return; 
162
+
163
+
164
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55
165
+%% subfunctions
166
+
167
+function v = centroid(D,default,weights)
168
+  
169
+  [n dim] = size(D);
170
+  I       = sparse(isnan(D));
171
+  D(I)    = 0;
172
+  
173
+  if nargin==3, 
174
+    W    = weights(:,ones(1,dim)); 
175
+    W(I) = 0; 
176
+    D    = D.*W;
177
+    nn   = sum(W,1);
178
+  else
179
+    nn   = n-sum(I,1);
180
+  end 
181
+
182
+  c    = sum(D,1);
183
+  v    = default; 
184
+  i    = find(nn>0); 
185
+  v(i) = c(i)./nn(i);
186
+      
187
+  return; 
188
+
189
+
190
+function vis
191
+
192
+  figure
193
+  som_show(sM,'color',{Hi,'Hi'},'color',{Ni,'hits'},...
194
+           'color',{Ed,'distortion'},'color',{Eqx,'qxerror'},...
195
+           'color',{Enb,'N-bias'},'color',{Env,'N-Var'});
196
+
197
+  ed = Eqx + Enb + Env;
198
+  i = find(ed>0); 
199
+  eqx = 0*ed; eqx(i) = Eqx(i)./ed(i);
200
+  enb = 0*ed; enb(i) = Enb(i)./ed(i);
201
+  env = 0*ed; env(i) = Env(i)./ed(i);
202
+
203
+  figure
204
+  som_show(sM,'color',Hi,'color',Ni,'color',Ed,...
205
+           'color',eqx,'color',enb,'color',env); 
206
+
207
+
... ...
@@ -0,0 +1,96 @@
1
+function [V,I]=som_divide(sMap, D, inds, mode)
2
+
3
+%SOM_DIVIDE Divides a dataset according to a given map.
4
+%
5
+% [V,I]=som_divide(sMap, sData, [inds], [mode])
6
+%
7
+% ARGUMENTS ([]'s are optional) 
8
+%
9
+%  sMap     (struct or matrix) map struct or codebook (size munits x dim)
10
+%  sData    (struct or matrix) data struct or matrix (size N x dim )
11
+%  [inds]            From which map units should the local data sets
12
+%                    be constructed. Interpretation depends on mode
13
+%                    argument. By default [1:munits].
14
+%           'class': (vector) munits x 1 matrix of class numbers
15
+%           'index': (vector) K x 1 vector of map node indexes 
16
+%           'index': (matrix) K x k matrix of map node subscripts
17
+%  [mode]   (string) 'index' or 'class', if inds is a vector of length 
18
+%                    munits, default is 'class', otherwise 'index'.
19
+% RETURNS
20
+%  
21
+% If mode == 'index' 
22
+%  V        (matrix) data vectors hitting the specified nodes (size K x dim)                   
23
+%  I        (vector) corresponding data row indexes (size K x 1)
24
+%   
25
+% If mode == 'class' (this can be used after using som_select)
26
+%  V        (cell array) V{K} includes vectors whose BMU has class number 
27
+%                        K in the input matrix 'coord'. Note that 
28
+%                        values of K below 1 are ignored. 
29
+%  I        (cell array) corresponding data indexes in the cell array                        
30
+%
31
+% NOTE: if the same node is specified multiple times, only one
32
+%       set of hits is returned.
33
+%
34
+% See also SOM_BMU, SOM_HITS, SOM_SELECT.
35
+
36
+% Version 1.0beta 260997 Johan 
37
+% Version 2.0beta 230300 juuso
38
+
39
+% Contributed to SOM Toolbox vs2, Mar 23rd, 2000 by Juha Vesanto
40
+% http://www.cis.hut.fi/projects/somtoolbox/
41
+
42
+%%%% Init & Check %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
43
+
44
+error(nargchk(0, 4, nargin)) % check if no. of input args is correct
45
+
46
+% map
47
+if isstruct(sMap), 
48
+  msize = sMap.topol.msize;     
49
+  dim = size(sMap.codebook,2); 
50
+else
51
+  msize = [size(sMap,1) 1];
52
+  dim = size(sMap,2); 
53
+end
54
+munits = prod(msize);
55
+
56
+% data
57
+if isstruct(D), D=D.data; end
58
+
59
+% inds
60
+if nargin<3, inds = 1:munits; end
61
+isvec = prod(size(inds))==length(inds);
62
+
63
+% mode
64
+if nargin<4, 
65
+  if isvec & length(inds)==munits, 
66
+    mode = 'class'; 
67
+  else
68
+    mode = 'index'; 
69
+  end
70
+end
71
+
72
+%%% Action & Build output according to the mode string output
73
+
74
+if ~isvec, inds = som_sub2ind(msize,inds); end
75
+
76
+bmus=som_bmus(sMap,D); 
77
+
78
+switch mode
79
+ case 'index'
80
+  I=find(ismember(bmus,inds));         
81
+  V=D(I,:);
82
+ case 'class'   
83
+  K=max(inds); % classes  
84
+  V = cell(K,1); 
85
+  I = cell(K,1);
86
+  for i=1:K,
87
+    N_ind=find(inds == i);           % indexes of the units of class i
88
+    I{i}=find(ismember(bmus,N_ind)); % data indexes       
89
+    V{i}=D(I{i},:);
90
+  end
91
+end
92
+
93
+
94
+
95
+
96
+
... ...
@@ -0,0 +1,68 @@
1
+function dmat = som_dmat(sM,Ne,mode)
2
+
3
+%SOM_DMAT Find distance to neighbors for each map unit.
4
+%
5
+% dmat = som_dmat(sM,[Ne],[mode])
6
+%
7
+%  Input and output arguments ([]'s are optional):
8
+%   sM         (struct) map or data struct 
9
+%              (matrix) data matrix, size n x dim
10
+%   [Ne]       (matrix) neighborhood connections matrix 
11
+%              (string) 'Nk' (on map) or 'kNN' (any vector set)
12
+%                       where k = some number, e.g. 'N1' or '10NN'
13
+%              (empty)  use default 
14
+%   [mode]     (string) 'min', 'median', 'mean', 'max', or 
15
+%                       some arbitrary scalar function of 
16
+%                       a set of vectors
17
+%
18
+%   dmat       (vector) size n x 1, distance associated with each vector
19
+%   
20
+% See also KMEANS_CLUSTERS, SOM_CLLINKAGE, SOM_CLSTRUCT.
21
+
22
+% Copyright (c) 2000 by Juha Vesanto
23
+% Contributed to SOM Toolbox on June 16th, 2000 by Juha Vesanto
24
+% http://www.cis.hut.fi/projects/somtoolbox/
25
+ 
26
+% Version 2.0beta juuso 220800
27
+
28
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
29
+
30
+% map 
31
+if isstruct(sM), 
32
+  switch sM.type, 
33
+   case 'som_map',  M = sM.codebook; mask = sM.mask; 
34
+   case 'som_data', M = sM.data; mask = ones(size(M,2),1);
35
+  end
36
+else
37
+  M = sM; mask = ones(size(M,2),1);
38
+end
39
+[n dim] = size(M);
40
+
41
+% neighborhoods 
42
+if nargin<2 | isempty(Ne), Ne = som_neighbors(sM); 
43
+elseif ischar(Ne), Ne = som_neighbors(sM,Ne); 
44
+end
45
+l = size(Ne,1); Ne([0:l-1]*l+[1:l]) = 0; % set diagonal elements = 0
46
+
47
+% mode
48
+if nargin<3 | isempty(mode), mode = 'median'; end
49
+calc = sprintf('%s(x)',mode); 
50
+
51
+% distances
52
+dmat = zeros(n,1); 
53
+for i=1:n, 
54
+  ne = find(Ne(i,:));
55
+  if any(ne), 
56
+    [dummy,x] = som_bmus(M(ne,:),M(i,:),[1:length(ne)],mask); 
57
+    dmat(i) = eval(calc); 
58
+  else 
59
+    dmat(i) = NaN; 
60
+  end
61
+end
62
+
63
+return; 
64
+
65
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
66
+
67
+  
68
+
... ...
@@ -0,0 +1,61 @@
1
+function [base,seed] = som_dmatclusters(sM,linkage,neigh,ignore)
2
+
3
+% SOM_DMATCLUSTERS Cluster map based on neighbor distance matrix.
4
+%
5
+% base = som_dmatclusters(sM,linkage,neigh,ignore)
6
+%
7
+% sM        (struct) map or data struct
8
+%           (matrix) data matrix, size n x dim
9
+% [linkage] (string) 'closest', 'single', 'average', 'complete', 
10
+%                    'centroid', 'ward', and 'neighf' (last for SOM only)
11
+%                    default is 'centroid'
12
+% [neigh]   (string) 'kNN' or 'Nk' (which is valid for a SOM only)
13
+%                    for example '6NN' or 'N1'
14
+%                    default is '10NN' for a data set and 'N1' for SOM
15
+%           (matrix) 0/1 matrix of size size n x n, 1=connection exists
16
+% [ignore]  (vector) indeces of vectors to be ignored in the spreading
17
+%                    phase, empty vector by default
18
+%
19
+% base      (vector) size n x 1, cluster indeces (1...c)
20
+% seed      (vector) size c x 1, indeces of seed units for the clusters
21
+%
22
+% See also  SOM_NEIGHBORS, KMEANS_CLUSTERS, SOM_DMATMINIMA.
23
+
24
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
25
+%% input arguments
26
+
27
+if nargin<2 | isempty(linkage), linkage = 'centroid'; end
28
+
29
+if nargin<3 | isempty(neigh),
30
+  if isstruct(sM) & strcmp(sM.type,'som_map'),
31
+    neigh = 'N1';
32
+  else
33
+    neigh = '10NN';
34
+  end
35
+end
36
+
37
+if nargin<4, ignore = []; end
38
+n = size(sM.codebook,1);
39
+
40
+% neighborhoods
41
+if ischar(neigh),
42
+  Ne = som_neighbors(sM,neigh);
43
+else
44
+  Ne = neigh;
45
+end
46
+
47
+% find seed points
48
+seed = som_dmatminima(sM,[],Ne);
49
+
50
+% make partition
51
+base = zeros(n,1);
52
+base(seed) = 1:length(seed);
53
+if any(ignore), base(ignore) = NaN; end
54
+base = som_clspread(sM,base,linkage,Ne,0);
55
+
56
+% assign the ignored units, too
57
+base(isnan(base)) = 0;
58
+if any(base==0), base = som_clspread(sM,base,linkage,Ne,0); end
59
+
60
+return;
61
+
... ...
@@ -0,0 +1,70 @@
1
+function minima = som_dmatminima(sM,U,Ne)
2
+
3
+%SOM_DMATMINIMA Find clusters based on local minima of U-matrix.
4
+%
5
+% minima = som_dmatminima(sM,[U],[Ne])
6
+%
7
+%  Input and output arguments ([]'s are optional):
8
+%   sM         (struct) map struct
9
+%   U          (matrix) the distance matrix from which minima is
10
+%                       searched from 
11
+%                       size msize(1) x ... x msize(end) or 
12
+%                            2*msize(1)-1 x 2*msize(2)-1 or 
13
+%                            munits x 1
14
+%   Ne         (matrix) neighborhood connections matrix
15
+%
16
+%   minima     (vector) indeces of the map units where locla minima of
17
+%                       of U-matrix (or other distance matrix occured)
18
+%   
19
+% See also KMEANS_CLUSTERS, SOM_CLLINKAGE, SOM_CLSTRUCT.
20
+
21
+% Copyright (c) 2000 by Juha Vesanto
22
+% Contributed to SOM Toolbox on June 16th, 2000 by Juha Vesanto
23
+% http://www.cis.hut.fi/projects/somtoolbox/
24
+ 
25
+% Version 2.0beta juuso 220800
26
+
27
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
28
+
29
+% map 
30
+if isstruct(sM), 
31
+  switch sM.type, 
32
+   case 'som_map',  M = sM.codebook; mask = sM.mask; 
33
+   case 'som_data', M = sM.data; mask = ones(size(M,2),1);
34
+  end
35
+else
36
+  M = sM; mask = ones(size(M,2),1);
37
+end
38
+[munits dim] = size(M);
39
+
40
+% distances between map units
41
+if nargin<2, U = []; end
42
+
43
+% neighborhoods 
44
+if nargin<3, Ne = som_neighbors(sM); end
45
+
46
+% distance matrix
47
+if nargin<2 | isempty(U), U = som_dmat(sM,Ne,'median'); end
48
+if prod(size(U))>munits, U = U(1:2:size(U,1),1:2:size(U,2)); end
49
+U = U(:); 
50
+if length(U) ~= munits, error('Distance matrix has incorrect size.'); end
51
+
52
+% find local minima
53
+minima = []; 
54
+for i=1:munits, 
55
+  ne = find(Ne(i,:));
56
+  if all(U(i)<=U(ne)) & ~anycommon(ne,minima), minima(end+1)=i; end
57
+end
58
+
59
+return; 
60
+
61
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
62
+
63
+function t = anycommon(i1,i2)
64
+  if isempty(i1) | isempty(i2), t = 0; 
65
+  else 
66
+    m = max(max(i1),max(i2));
67
+    t = any(sparse(i1,1,1,m,1) & sparse(i2,1,1,m,1)); 
68
+  end
69
+  return;   
70
+
... ...
@@ -0,0 +1,88 @@
1
+function [sig,cm,truex,truey] = som_dreval(sR,D,sigmea,inds1,inds2,andor)
2
+
3
+% SOM_DREVAL Evaluate the significance of the given descriptive rule.
4
+%
5
+% [sig,Cm,truex,truey] = som_dreval(cR,D,sigmea,[inds1],[inds2],[andor]) 
6
+% 
7
+%  sR      (struct) a rule struct, or an array of rule structs
8
+%  D       (matrix) the data, of size [dlen x nr]
9
+%  sigmea  (string) significance measure ('accuracy','accuracyI','mutuconf'), 
10
+%                   see definitions below
11
+%  [inds1] (vector) indeces belonging to the group
12
+%                   (by default: the whole data set) 
13
+%  [inds2] (vector) indeces belonging to the contrast group
14
+%                   (by default: the rest of the data set)
15
+%  [andor] (string) 'and' or 'or': which conjunction operator to use
16
+%                   to join the rules for each variable
17
+%
18
+%  sig     (scalar) significance of the rule
19
+%  cm      (vector) length 4, vectorized confusion matrix ([a,c,b,d]: see below)
20
+%  truex   (vector) binary vector indicating for each item in the 
21
+%                   group whether it was true or not
22
+%  truey   (vector) binary vector indicating for each item in the 
23
+%                   contrast group whether it was true or not
24
+%
25
+% Descriptive rule significance is measured as the match between the 
26
+% given groups (inds1 = G1, inds2 = G2) and the rule being true or false.
27
+% 
28
+%          G1    G2   
29
+%       ---------------    accuracy  = (a+d) / (a+b+c+d)
30
+% true  |  a  |   b   |    
31
+%       |--------------    mutuconf  =  a*a  / ((a+b)(a+c)) 
32
+% false |  c  |   d   | 
33
+%       ---------------    accuracyI =   a   / (a+b+c)
34
+%
35
+% See also  SOM_DRSIGNIF, SOM_DRMAKE.
36
+
37
+% Contributed to SOM Toolbox 2.0, March 4th, 2002 by Juha Vesanto
38
+% Copyright (c) by Juha Vesanto
39
+% http://www.cis.hut.fi/projects/somtoolbox/
40
+
41
+% Version 2.0beta juuso 040302
42
+
43
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
44
+
45
+% input arguments
46
+if isstruct(D), 
47
+  switch D.type, 
48
+   case 'som_data', D = D.data; 
49
+   case 'som_map',  D = D.codebook; 
50
+  end
51
+end
52
+[dlen,dim] = size(D);
53
+if nargin<4, inds1 = 1:dlen; end
54
+if nargin<5, i = ones(dlen,1); i(inds1) = 0; inds2 = find(i); end
55
+if nargin<6, andor = 'and'; end
56
+
57
+% initialize
58
+nr  = length(sR);
59
+X   = D(inds1,:);
60
+Y   = D(inds2,:); 
61
+nx  = size(X,1);
62
+ny  = size(Y,1);  
63
+truex = ones(nx,1);
64
+truey = ones(ny,1);
65
+
66
+% go through the individual rules
67
+for i=1:nr,  
68
+  tx = (X(:,i)>=sR(i).low & X(:,i)<sR(i).high);
69
+  tx(isnan(X(:,i))) = sR(i).nanis;     
70
+
71
+  ty = (Y(:,i)>=sR(i).low & Y(:,i)<sR(i).high);
72
+  ty(isnan(Y(:,i))) = sR(i).nanis;     
73
+
74
+  switch andor, 
75
+   case 'and', truex = (truex & tx); truey = (truey & ty);
76
+   case 'or',  truex = (truex | tx); truey = (truey | ty);
77
+  end    
78
+end  
79
+
80
+% evaluate criteria
81
+tix = sum(truex(isfinite(truex)));
82
+tiy = sum(truey(isfinite(truey))); 
83
+cm  = [tix,nx-tix,tiy,ny-tiy];
84
+sig = som_drsignif(sigmea,cm);
85
+
86
+return; 
87
+    
88
+
... ...
@@ -0,0 +1,167 @@
1
+function [sR,best,sig,Cm] = som_drmake(D,inds1,inds2,sigmea,nanis)
2
+
3
+% SOM_DRMAKE Make descriptive rules for given group within the given data. 
4
+%
5
+% sR = som_drmake(D,[inds1],[inds2],[sigmea],[nanis]) 
6
+% 
7
+%  D        (struct) map or data struct
8
+%           (matrix) the data, of size [dlen x dim]
9
+%  [inds1]  (vector) indeces belonging to the group
10
+%                    (the whole data set by default)
11
+%  [inds2]  (vector) indeces belonging to the contrast group
12
+%                    (the rest of the data set by default)
13
+%  [sigmea] (string) significance measure: 'accuracy', 
14
+%                    'mutuconf' (default), or 'accuracyI'.
15
+%                    (See definitions below).
16
+%  [nanis]  (scalar) value given for NaNs: 0 (=FALSE, default),
17
+%                    1 (=TRUE) or NaN (=ignored)
18
+%
19
+%  sR      (struct array) best rule for each component. Each 
20
+%                   struct has the following fields:
21
+%    .type     (string) 'som_rule'
22
+%    .name     (string) name of the component
23
+%    .low      (scalar) the low end of the rule range
24
+%    .high     (scalar) the high end of the rule range
25
+%    .nanis    (scalar) how NaNs are handled: NaN, 0 or 1
26
+%
27
+%  best    (vector) indeces of rules which make the best combined rule
28
+%  sig     (vector) significance measure values for each rule, and for the combined rule
29
+%  Cm      (matrix) A matrix of vectorized confusion matrices for each rule, 
30
+%                   and for the combined rule: [a, c, b, d] (see below). 
31
+% 
32
+% For each rule, such rules sR.low <= x < sR.high are found 
33
+% which optimize the given significance measure. The confusion
34
+% matrix below between the given grouping (G: group - not G: contrast group) 
35
+% and rule (R: true or false) is used to determine the significance values:
36
+%
37
+%          G    not G    
38
+%       ---------------    accuracy  = (a+d) / (a+b+c+d)
39
+% true  |  a  |   b   |    
40
+%       |--------------    mutuconf  =  a*a  / ((a+b)(a+c)) 
41
+% false |  c  |   d   | 
42
+%       ---------------    accuracyI =   a   / (a+b+c)
43
+%
44
+% See also  SOM_DREVAL, SOM_DRTABLE.
45
+
46
+% Contributed to SOM Toolbox 2.0, January 7th, 2002 by Juha Vesanto
47
+% Copyright (c) by Juha Vesanto
48
+% http://www.cis.hut.fi/projects/somtoolbox/
49
+
50
+% Version 2.0beta juuso 070102
51
+
52
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
53
+%% input arguments
54
+
55
+if isstruct(D), 
56
+  switch D.type, 
57
+   case 'som_data', cn = D.comp_names; D = D.data; 
58
+   case 'som_map',  cn = D.comp_names; D = D.codebook; 
59
+  end  
60
+else
61
+  cn = cell(size(D,2),1);
62
+  for i=1:size(D,2), cn{i} = sprintf('Variable%d',i); end
63
+end
64
+
65
+[dlen,dim] = size(D);
66
+if nargin<2 | isempty(inds1), inds1 = 1:dlen; end
67
+if nargin<3 | isempty(inds2), i = ones(dlen,1); i(inds1) = 0; inds2 = find(i); end
68
+if nargin<4, sigmea = 'mutuconf'; end
69
+if nargin<5, nanis = 0; end
70
+
71
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
72
+%% input arguments
73
+
74
+sig = zeros(dim+1,1); 
75
+Cm  = zeros(dim+1,4); 
76
+
77
+sR1tmp = struct('type','som_rule','name','','low',-Inf,'high',Inf,'nanis',nanis,'lowstr','','highstr','');
78
+sR = sR1tmp;  
79
+
80
+% single variable rules
81
+for i=1:dim,
82
+    
83
+    % bin edges
84
+    mi = min(D(:,i)); 
85
+    ma = max(D(:,i)); 
86
+    [histcount,bins] = hist([mi,ma],10); 
87
+    if size(bins,1)>1, bins = bins'; end
88
+    edges = [-Inf, (bins(1:end-1)+bins(2:end))/2, Inf];
89
+    
90
+    % find the rule for this variable
91
+    [low,high,s,cm] = onevar_descrule(D(inds1,i),D(inds2,i),sigmea,nanis,edges);
92
+    sR1 = sR1tmp;      
93
+    sR1.name = cn{i}; 
94
+    sR1.low = low; 
95
+    sR1.high = high; 
96
+    sR(i) = sR1; 
97
+    sig(i) = s; 
98
+    Cm(i,:) = cm; 
99
+    
100
+end  
101
+
102
+% find combined rule
103
+[dummy,order] = sort(-sig);
104
+maxsig = sig(order(1)); bestcm = Cm(order(1),:);
105
+best  = order(1);
106
+for i=2:dim,    
107
+    com = [best, order(i)];
108
+    [s,cm,truex,truey] = som_dreval(sR(com),D(:,com),sigmea,inds1,inds2,'and');
109
+    if s>maxsig, best = com; maxsig = s; bestcm = cm; end
110
+end   
111
+sig(end) = maxsig;
112
+Cm(end,:) = cm; 
113
+
114
+return;
115
+    
116
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55
117
+%% descriptive rules
118
+
119
+function [low,high,sig,cm] = onevar_descrule(x,y,sigmea,nanis,edges)
120
+
121
+  % Given a set of bin edges, find the range of bins with best significance.
122
+  %
123
+  %  x          data values in cluster
124
+  %  y          data values not in cluster
125
+  %  sigmea     significance measure
126
+  %  bins       bin centers
127
+  %  nanis      how to handle NaNs 
128
+
129
+  % histogram counts
130
+  if isnan(nanis), x = x(~isnan(x)); y = y(~isnan(y)); end
131
+  [xcount,xbin] = histc(x,edges); 
132
+  [ycount,ybin] = histc(y,edges); 
133
+  xcount = xcount(1:end-1);
134
+  ycount = ycount(1:end-1); 
135
+  xnan=sum(isnan(x));
136
+  ynan=sum(isnan(y));
137
+    
138
+  % find number of true items in both groups in all possible ranges
139
+  n = length(xcount);
140
+  V = zeros(n*(n+1)/2,4); 
141
+  s1 = cumsum(xcount);
142
+  s2 = cumsum(xcount(end:-1:1)); s2 = s2(end:-1:1);       
143
+  m  = s1(end);      
144
+  Tx = triu(s1(end)-m*log(exp(s1/m)*exp(s2/m)')+repmat(xcount',[n 1])+repmat(xcount,[1 n]),0); 
145
+  s1 = cumsum(ycount); 
146
+  s2 = cumsum(ycount(end:-1:1)); s2 = s2(end:-1:1);        
147
+  Ty = triu(s1(end)-m*log(exp(s1/m)*exp(s2/m)')+repmat(ycount',[n 1])+repmat(ycount,[1 n]),0); 
148
+  [i,j] = find(Tx+Ty);
149
+  k = sub2ind(size(Tx),i,j);
150
+  V = [i, j, Tx(k), Ty(k)];
151
+  tix = V(:,3) + nanis*xnan; 
152
+  tiy = V(:,4) + nanis*ynan; 
153
+  
154
+  % select the best range
155
+  nix   = length(x);
156
+  niy   = length(y);
157
+  Cm    = [tix,nix-tix,tiy,niy-tiy];
158
+  [s,k] = max(som_drsignif(sigmea,Cm));
159
+
160
+  % output
161
+  low  = edges(V(k,1));
162
+  high = edges(V(k,2)+1);
163
+  sig  = s;   
164
+  cm   = Cm(k,:);
165
+
166
+  return;
167
+ 
0 168
\ No newline at end of file
... ...
@@ -0,0 +1,63 @@
1
+function sig = som_drsignif(sigmea,Cm)
2
+
3
+% SOM_DRSIGNIF Significance measure from confusion matrix between two clusters and a rule.
4
+%
5
+% sig = som_drsignif(sigmea,Cm)
6
+% 
7
+%  sigmea   (string) significance measure: 'accuracy', 
8
+%                    'mutuconf' (default), or 'accuracyI'.
9
+%                    (See definitions below).
10
+%  Cn                Vectorized confusion matrix, or a matrix of such vectors.
11
+%           (vector) [a, c, b, d] (see below)
12
+%           (matrix) [[a1,c1,b1,d1], ..., [an,cn,bn,dn]]
13
+%
14
+%  sig      (vector) length=n, significance values 
15
+%
16
+% The confusion matrix Cm below between group (G) and contrast group (not G)
17
+% and rule (true - false) is used to determine the significance values:
18
+%
19
+%          G    not G    
20
+%       ---------------    accuracy  = (a+d) / (a+b+c+d)
21
+% true  |  a  |   b   |    
22
+%       |--------------    mutuconf  =  a*a  / ((a+b)(a+c)) 
23
+% false |  c  |   d   | 
24
+%       ---------------    accuracyI =   a   / (a+b+c)
25
+%
26
+% See also  SOM_DREVAL, SOM_DRMAKE.
27
+
28
+% Contributed to SOM Toolbox 2.0, March 4th, 2002 by Juha Vesanto
29
+% Copyright (c) by Juha Vesanto
30
+% http://www.cis.hut.fi/projects/somtoolbox/
31
+
32
+% Version 2.0beta juuso 040302
33
+
34
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35
+%% input arguments
36
+
37
+true_x     = Cm(:,1); % x     = in group
38
+false_x    = Cm(:,2); % false = rule is false
39
+true_y     = Cm(:,3); % true  = rule is true
40
+false_y    = Cm(:,4); % y     = not in group
41
+
42
+true_items = true_x + true_y; 
43
+x_items    = true_x + false_x; 
44
+all_items  = true_x + false_x + true_y + false_y; 
45
+true_or_x  = x_items + true_items - true_x; 
46
+
47
+switch sigmea, 
48
+case 'mutuconf',
49
+    % mutual confidence, or relevance (as defined in WSOM2001 paper)
50
+    sig = zeros(size(true_x)); 
51
+    i = find(true_items>0 & x_items>0); 
52
+    sig(i) = (true_x(i).^2) ./ (true_items(i).*x_items(i)); 
53
+case 'accuracy', 
54
+    % accuracy 
55
+    sig = (true_x + false_y) ./ all_items;
56
+case 'accuracyI', 
57
+    % accuracy such that false_y is left out of consideration
58
+    sig = true_x./true_or_x;
59
+otherwise, 
60
+    error(['Unrecognized significance measures: ' sigmea]);
61
+end 
62
+
63
+return;
... ...
@@ -0,0 +1,79 @@
1
+function [K,P] = som_estimate_gmm(sM, sD)
2
+
3
+%SOM_ESTIMATE_GMM Estimate a gaussian mixture model based on map.
4
+%
5
+% [K,P] = som_estimate_gmm(sM, sD)
6
+%
7
+%  Input and output arguments:
8
+%   sM    (struct) map struct
9
+%   sD    (struct) data struct
10
+%         (matrix) size dlen x dim, the data to use when estimating
11
+%                  the gaussian kernels
12
+%
13
+%   K     (matrix) size munits x dim, kernel width parametes for 
14
+%                  each map unit
15
+%   P     (vector) size 1 x munits, a priori probability of each map unit
16
+%
17
+% See also SOM_PROBABILITY_GMM.
18
+
19
+% Reference: Alhoniemi, E., Himberg, J., Vesanto, J.,
20
+%   "Probabilistic measures for responses of Self-Organizing Maps", 
21
+%   Proceedings of Computational Intelligence Methods and
22
+%   Applications (CIMA), 1999, Rochester, N.Y., USA, pp. 286-289.
23
+
24
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Esa Alhoniemi
25
+% Copyright (c) by Esa Alhoniemi
26
+% http://www.cis.hut.fi/projects/somtoolbox/
27
+
28
+% ecco 180298 juuso 050100 250400
29
+
30
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
31
+
32
+[c, dim] = size(sM.codebook);
33
+M = sM.codebook;
34
+
35
+if isstruct(sD), D = sD.data; else D = sD; end
36
+dlen = length(D(:,1));
37
+
38
+%%%%%%%%%%%%%%%%%%%%%
39
+% compute hits & bmus
40
+
41
+[bmus, qerrs] = som_bmus(sM, D);
42
+hits = zeros(1,c);
43
+for i = 1:c, hits(i) = sum(bmus == i); end
44
+
45
+%%%%%%%%%%%%%%%%%%%%
46
+% a priori  
47
+
48
+% neighborhood kernel
49
+r  = sM.trainhist(end).radius_fin; % neighborhood radius
50
+if isempty(r) | isnan(r), r=1; end
51
+Ud = som_unit_dists(sM);
52
+Ud = Ud.^2; 
53
+r = r^2; 
54
+if r==0, r=eps; end % to get rid of div-by-zero errors
55
+switch sM.neigh, 
56
+ case 'bubble',   H = (Ud<=r); 
57
+ case 'gaussian', H = exp(-Ud/(2*r)); 
58
+ case 'cutgauss', H = exp(-Ud/(2*r)) .* (Ud<=r);
59
+ case 'ep',       H = (1-Ud/r) .* (Ud<=r);
60
+end  
61
+
62
+% a priori prob. = hit histogram weighted by the neighborhood kernel
63
+P = hits*H;
64
+P = P/sum(P);              
65
+
66
+%%%%%%%%%%%%%%%%%%%%
67
+% kernel widths (& centers)
68
+
69
+K = ones(c, dim) * NaN; % kernel widths
70
+for m = 1:c,
71
+  w = H(bmus,m);
72
+  w = w/sum(w);
73
+  for i = 1:dim,
74
+    d = (D(:,i) - M(m,i)).^2;   % compute variance of ith
75
+    K(m,i) = w'*d;              % variable of centroid m
76
+  end
77
+end
78
+
79
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,94 @@
1
+function d=som_eucdist2(Data, Proto)
2
+
3
+%SOM_EUCDIST2 Calculates matrix of squared euclidean distances between set of vectors or map, data struct
4
+%
5
+% d=som_eucdist2(D, P)
6
+%
7
+%  d=som_eucdist(sMap, sData);
8
+%  d=som_eucdist(sData, sMap);
9
+%  d=som_eucdist(sMap1, sMap2);
10
+%  d=som_eucdist(datamatrix1, datamatrix2);
11
+%
12
+%  Input and output arguments ([]'s are optional): 
13
+%   D (matrix) size Nxd
14
+%     (struct) map or data struct
15
+%   P (matrix) size Pxd
16
+%     (struct) map or data struct
17
+%   d (matrix) distance matrix of size NxP 
18
+%
19
+% IMPORTANT
20
+%
21
+% * Calculates _squared_ euclidean distances
22
+% * Observe that the mask in the map struct is not taken into account while 
23
+%   calculating the euclidean distance
24
+%
25
+% See also KNN, PDIST.
26
+
27
+% Contributed to SOM Toolbox 2.0, October 29th, 2000 by Johan Himberg
28
+% Copyright (c) by Johan Himberg
29
+% http://www.cis.hut.fi/projects/somtoolbox/
30
+
31
+% Version 2.0beta Johan 291000
32
+
33
+%% Init %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
34
+
35
+if isstruct(Data);
36
+  if isfield(Data,'type') & ischar(Data.type),
37
+    ;
38
+  else
39
+    error('Invalid map/data struct?');
40
+  end
41
+  switch Data.type
42
+   case 'som_map'
43
+    data=Data.codebook;
44
+   case 'som_data'
45
+    data=Data.data;
46
+  end
47
+else
48
+  % is already a matrix
49
+  data=Data;
50
+end
51
+
52
+% Take prototype vectors from prototype struct
53
+
54
+if isstruct(Proto),
55
+  
56
+  if isfield(Proto,'type') & ischar(Proto.type),
57
+    ;
58
+  else
59
+    error('Invalid map/data struct?');
60
+  end
61
+  switch Proto.type
62
+   case 'som_map'
63
+    proto=Proto.codebook;
64
+   case 'som_data'
65
+    proto=Proto.data;
66
+  end
67
+else
68
+  % is already a matrix
69
+  proto=Proto; 
70
+end
71
+
72
+% Check that inputs are matrices
73
+if ~vis_valuetype(proto,{'nxm'}) | ~vis_valuetype(data,{'nxm'}),
74
+  error('Prototype or data input not valid.')
75
+end
76
+
77
+% Record data&proto sizes and check their dims 
78
+[N_data dim_data]=size(data); 
79
+[N_proto dim_proto]=size(proto);
80
+if dim_proto ~= dim_data,
81
+  error('Data and prototype vector dimension does not match.');
82
+end
83
+
84
+% Calculate euclidean distances between classifiees and prototypes
85
+d=distance(data,proto);
86
+
87
+%%%% Classification %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
88
+function d=distance(X,Y);
89
+
90
+% Euclidean distance matrix between row vectors in X and Y
91
+
92
+U=~isnan(Y); Y(~U)=0;
93
+V=~isnan(X); X(~V)=0;
94
+d=abs(X.^2*U'+V*Y'.^2-2*X*Y');
... ...
@@ -0,0 +1,56 @@
1
+function sD = som_fillnans(sD,sM,bmus)
2
+
3
+% SOM_FILLNANS Replaces NaNs in the data matrix with values from
4
+%              SOM prototypes. 
5
+%
6
+%   sD = som_fillnans(sD,sM, [bmus])
7
+%
8
+%      sD      (struct) data struct
9
+%              (matrix) size dlen x dim
10
+%      sM      (struct) data struct, with .data of size dlen x dim
11
+%              (matrix) size dlen x dim, a matrix from which 
12
+%                       the values are taken from directly
13
+%              (struct) map struct: replacement values are taken from 
14
+%                       sM.codebook(bmus,:)
15
+%      [bmus]  (vector) BMU for each data vector (calculated if not specified)
16
+%
17
+% See also  SOM_MAKE.
18
+
19
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
20
+
21
+if isstruct(sD), 
22
+  [dlen dim] = size(sD.data); 
23
+  nans = find(isnan(sD.data)); 
24
+else
25
+  [dlen dim] = size(sD); 
26
+  nans = find(isnan(sD)); 
27
+end
28
+
29
+if nargin<3, 
30
+  bmus = som_bmus(sM,sD);   
31
+end
32
+
33
+if isstruct(sM) & strcmp(sM.type,'som_map'),
34
+  sM = sM.codebook(bmus,:); 
35
+elseif isstruct(sM), 
36
+  sM = sM.data(bmus,:);   
37
+else
38
+  sM = sM(bmus,:);
39
+end
40
+me = mean(sM); 
41
+
42
+if any(size(sM) ~= [dlen dim]), 
43
+  error('Invalid input arguments.')
44
+end
45
+
46
+if isstruct(sD), 
47
+  sD.data(nans) = sM(nans); 
48
+else
49
+  sD(nans) = sM(nans); 
50
+end
51
+  
52
+return; 
53
+
54
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
55
+
56
+
... ...
@@ -0,0 +1,205 @@
1
+function [color,X]=som_fuzzycolor(sM,T,R,mode,initRGB,S)
2
+
3
+% SOM_FUZZYCOLOR Heuristic contraction projection/soft cluster color coding for SOM 
4
+% 
5
+% function [color,X]=som_fuzzycolor(map,[T],[R],[mode],[initRGB],[S])
6
+%
7
+%  sM        (map struct)
8
+%  [T]       (scalar) parameter that defines the speed of contraction 
9
+%              T<1: slow contraction, T>1: fast contraction. Default: 1
10
+%  [R]       (scalar) number of rounds, default: 30
11
+%  [mode]    (string) 'lin' or 'exp', default: 'lin'  
12
+%  [initRGB] (string) Strings accepted by SOM_COLORCODE,  default: 'rgb2'
13
+%  [S]       (matrix) MxM matrix a precalculated similarity matrix 
14
+%  color     (matrix) of size MxRx3 resulting color codes at each step 
15
+%  X         (matrix) of size MxRx2 coordiantes for projected unit weight vectors 
16
+%             at each step of iteration. (Color code C is calculated using this
17
+%             projection.)
18
+%
19
+% The idea of the projection is to use a naive contraction model which
20
+% pulls the units together. Units that are close to each other in the
21
+% output space (clusters) contract faster into the same point in the
22
+% projection. The original position for each unit is its location in
23
+% the topological grid.
24
+% 
25
+% This is an explorative tool to color code the map units so that
26
+% similar units (in the sense of euclidean norm) have similar coloring
27
+% (See also SOM_KMEANSCOLOR) The tool gives a series of color codings
28
+% which start from an initial color coding (see SOM_COLORCODE) and
29
+% show the how the fuzzy clustering process evolves.
30
+%
31
+% The speed of contraction is controlled by the input parameter T. If
32
+% it is high the projection contracts more slowly and reveals more
33
+% intermediate stages (hierarchy).  A good value for T must be
34
+% searched manually. It is probable that the default values do not
35
+% yield good results.
36
+%
37
+% The conatrction process may be slow. In this case the mode can be
38
+% set to 'exp' instead of 'lin', however, then the computing becomes
39
+% heavier.
40
+%
41
+% EXAMPLE
42
+%
43
+%  load iris; % or any other map struct sM 
44
+%  [color]=som_fuzzycolor(sM,'lin',10);
45
+%  som_show(sM,'color',color);
46
+%
47
+% See also SOM_KMEANSCOLOR, SOM_COLORCODE, SOM_CLUSTERCOLOR
48
+%
49
+% REFERENCES
50
+% 
51
+% Johan Himberg, "A SOM Based Cluster Visualization and Its
52
+% Application for False Coloring", in Proceedings of International
53
+% Joint Conference on Neural Networks (IJCNN2000)},
54
+% pp. 587--592,Vol. 3, 2000
55
+% 
56
+% Esa Alhoniemi, Johan Himberg, and Juha Vesanto, Probabilistic
57
+% Measures for Responses of Self-Organizing Map Units, pp. 286--290,
58
+% in Proceedings of the International ICSC Congress on Computational
59
+% Intelligence Methods and Applications (CIMA '99)}, ICSC Academic
60
+% Press}, 1999
61
+%
62
+% Outline of the heuristic
63
+%
64
+% First a matrix D of squared pairwise euclidean distances
65
+% D(i,j)=d(i,j)^2 between map weight vectors is calculated. This
66
+% matrix is transformed into a similarity matrix S,
67
+% s(i,j)=exp(-(D(i,j)/(T.^2*v)), where T is a free input parameter and
68
+% v the variance of all elements of D v=var(D(:)). The matrix is
69
+% further normalized so that all rows sum to one. The original
70
+% topological coordinates X=som_unit_coords(sM) are successively
71
+% averaged using this matrix. X(:,:,i)=S^i*X(:,:,1); As the process is
72
+% actually a series of successive weighted averagings of the initial
73
+% coordinates, all projected points eventually contract into one
74
+% point.  T is a user defined parameter that defines how fast the
75
+% projection contracts into this center point. If T is too small, the
76
+% process will end into the center point at once.
77
+% 
78
+% In practise, we don't calculate powers of S, but compute
79
+% 
80
+%  X(:,:,i)=S.*X(:,:,i-1); % mode: 'lin'
81
+%
82
+% The contraction process may be slow if T is selected to be large,
83
+% then for each step the similarity matrix is squared
84
+%
85
+%  X(:,:,i)=S*X(:,:,1); S=S*S % mode: 'exp'
86
+%
87
+% The coloring is done using the function SOM_COLORCODE according to
88
+% the projections in X, The coordinates are rescaled in order to
89
+% achieve maximum color resolution.
90
+
91
+% Contributed to SOM Toolbox vs2, 2000 by Johan Himberg
92
+% Copyright (c) by Johan Himberg
93
+% http://www.cis.hut.fi/projects/somtoolbox/
94
+
95
+% Previously rownorm function normalized the rows of S erroneously
96
+% into unit length, this major bug was corrected 14042003. Now the
97
+% rownorm normalizes the rows to have unit sum as it should johan 14042003
98
+
99
+%% Check input arguments
100
+
101
+if isstruct(sM), 
102
+   if ~isfield(sM,'topol')
103
+      error('Topology field missing.');
104
+   end
105
+   M=size(sM.codebook,1);
106
+else
107
+   error('Requires a map struct.');
108
+end
109
+
110
+if nargin<2 | isempty(T),
111
+   T=1;
112
+end
113
+if ~vis_valuetype(T,{'1x1'})
114
+   error('Input for T must be a scalar.');
115
+end
116
+
117
+if nargin<3 | isempty(R),
118
+   R=30;
119
+end
120
+if ~vis_valuetype(R,{'1x1'})
121
+   error('Input for R must be a scalar.');
122
+end
123
+
124
+if nargin < 4 | isempty(mode),
125
+   mode='lin';
126
+end
127
+if ~ischar(mode),
128
+   error('String input expected for mode.');
129
+else
130
+   mode=lower(mode);
131
+   switch mode
132
+   case {'lin','exp'}
133
+      ;   
134
+   otherwise
135
+      error('Input for mode must be ''lin'' or ''exp''.');
136
+   end
137
+end
138
+
139
+if nargin < 5 | isempty(initRGB)
140
+   initRGB='rgb2';
141
+end
142
+
143
+if ischar(initRGB),   
144
+   try
145
+      dummy=som_colorcode(sM,initRGB);
146
+   catch
147
+      error(['Color code ''' initRGB ''' not known, see SOM_COLORCODE.']);
148
+   end
149
+else
150
+   error('Invalid color code string');   
151
+end
152
+
153
+if nargin<6 | isempty(S),
154
+   S=fuzzysimilarity(sM,1./T);
155
+end
156
+
157
+if ~vis_valuetype(S,{[M M]}),
158
+   error('Similarity matrix must be a MunitsxMunits matrix.')
159
+end
160
+
161
+x = maxnorm(som_unit_coords(sM.topol.msize,sM.topol.lattice,'sheet'));
162
+
163
+x = x-repmat(mean(x),size(x,1),1);
164
+
165
+X(:,:,1)=x; 
166
+color(:,:,1)=som_colorcode(x,'rgb2',1);
167
+
168
+%%% Actions
169
+
170
+for i=1:R,
171
+   switch mode
172
+   case 'exp'
173
+      S=rownorm(S*S);
174
+      tmpX=S*X(:,:,1);
175
+   case 'lin'
176
+      tmpX=S*X(:,:,i);
177
+   end
178
+   X(:,:,i+1)=tmpX;
179
+   color(:,:,i+1)=som_colorcode(X(:,:,i+1),initRGB);
180
+end
181
+
182
+color(isnan(color))=0;
183
+
184
+function r=fuzzysimilarity(sM,p)
185
+  % Calculate a "fuzzy response" similarity matrix
186
+  % sM: map
187
+  % p: sharpness factor
188
+  d=som_eucdist2(sM,sM);
189
+  v=std(sqrt(d(:))).^2;
190
+  r=rownorm(exp(-p^2*(d./v)));
191
+  r(~isfinite(r))=0;
192
+  return;
193
+
194
+
195
+function X = rownorm(X)
196
+
197
+  r = sum(X,2);
198
+  X = X ./ r(:,ones(size(X,2),1)); 
199
+  return;
200
+
201
+
202
+function X = maxnorm(X)
203
+
204
+  for i=1:size(X,2), r = (max(X(:,i))-min(X(:,i))); if r, X(:,i) = X(:,i) / r; end, end
205
+  return; 
... ...
@@ -0,0 +1,72 @@
1
+function [t,r,Cd,S] = som_gapindex(sM, base, between)
2
+ 
3
+% SOM_GAPINDEX Gap clustering evaluation index.
4
+%
5
+% [t,r] = som_gapindex(sM, base, [between])
6
+%
7
+%  Input and output arguments ([]'s are optional):  
8
+%    sM        (struct) map struct
9
+%    base      (vector) clusters indeces for each map unit, map units
10
+%                       with index<=0 or NaN are not taken into account
11
+%    [between] (vector) indices of prototypes which are "between" clusters:
12
+%                       the associated distances are doubled
13
+% 
14
+%    t         (scalar) Gap index index for the clustering (=mean(r))
15
+%    r         (vector) maximum Gap index for each cluster (size max(base) x 1)    
16
+% 
17
+% See also  KMEANS, KMEANS_CLUSTERS, SOM_GAPINDEX.
18
+
19
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
20
+
21
+if nargin<3, between = find(isnan(base)); end
22
+
23
+nc = max(base); 
24
+cinds = cell(nc,1); 
25
+for i=1:nc, cinds{i} = find(base==i); end
26
+ 
27
+% distances between neighboring prototypes
28
+Ne = som_neighbors(sM,'N1'); 
29
+Md = som_mdist(sM.codebook,2,[],Ne);
30
+Md(Ne==0) = NaN;
31
+
32
+Md(between,:) = Md(between,:)*2;
33
+Md(:,between) = Md(:,between)*2;
34
+Md(between,between) = Md(between,between)/2;
35
+ 
36
+% dispersion in each cluster 
37
+S = zeros(nc,1);
38
+for i=1:nc, 
39
+    inds = setdiff(cinds{i},between);    
40
+    if any(inds), 
41
+        indist = Md(inds,inds); 
42
+        for j=1:size(indist,1), indist(j,j) = NaN; end
43
+        indist = indist(isfinite(indist(:))); 
44
+        if any(indist), S(i) = mean(indist); end
45
+    end
46
+end 
47
+ 
48
+% distances between clusters
49
+Cd = zeros(nc,nc) + NaN;
50
+for i=1:nc,
51
+    inds1 = cinds{i}; 
52
+    for j=1:nc, 
53
+        inds2 = cinds{j}; 
54
+	od = Md(inds1,inds2); 
55
+	od = od(isfinite(od(:)));
56
+	if any(od), Cd(i,j) = mean(od(:)); end        
57
+    end    
58
+end
59
+
60
+% Gap index
61
+R = NaN * zeros(nc);
62
+for i = 1:nc
63
+  for j = i+1:nc
64
+    R(i,j) = (S(i) + S(j))/Cd(i,j);
65
+    R(j,i) = R(i,j); 
66
+  end
67
+end
68
+r = max(R,[],2);
69
+ 
70
+t = mean(r(isfinite(r)));
71
+ 
72
+return; 
... ...
@@ -0,0 +1,771 @@
1
+function [S,m,l,t,s]=som_grid(varargin)
2
+
3
+%SOM_GRID Visualization of a SOM grid
4
+%
5
+% [sGrid,m,l,t,s]=som_grid(sGrid, ['argID', value, ...])
6
+% [sGrid,m,l,t,s]=som_grid(topol, ['argID', value, ...])
7
+% [sGrid,m,l,t,s]=som_grid(lattice, msize, ['argID', value, ...])
8
+%
9
+% Input and output arguments ([]'s are optional)
10
+%  sGrid    (struct) som_grid struct (see output arguments)
11
+%  topol    (struct) map or topol struct for giving the topology
12
+%           (cell array) of form {'lattice', msize, ['shape']}. 
13
+%                    Default value for 'shape' is 'sheet'.
14
+%  lattice  (string) 'hexa', 'rect' 
15
+%           (matrix) size M x M, defines topological connections             
16
+%  msize    (vector) 1x2 vector defines the grid size, M=msize(1)*msize(2)
17
+%  ['argID',(string) Other arguments can be given as 'argID', value   
18
+%   value]  (varies) pairs. See list below for valid values.
19
+%
20
+%  sGrid    (struct) with fields S.msize, S.shape, S.lattice, S.coord, S.marker, 
21
+%                    S.markersize, S.markercolor, S.line, S.linewidth, S.linecolor,
22
+%                    S.surf, S.label, S.labelsize, S.labelcolor
23
+%  m        (matrix) handels to LINE objects (unit markers) 
24
+%  l        (matrix) handles to LINE objects (lines connecting the units)
25
+%  t        (matrix) handles to TEXT objects (labels)
26
+%  s        (scalar) handle  to SURF object  (surface between units)
27
+%
28
+%  Here are the valid argument IDs (case insensitive) and
29
+%  associated values: 
30
+%  'Coord'       Mx2 or Mx3 matrix of coordinates 
31
+%                (default: according to lattice as in som_cplane)
32
+%  'Marker'      string 'o','+','x','*','v','^','<','>','h','s','d','p','.', 
33
+%                'none' or Mx1 cell or char array of these strings 
34
+%                Default: 'o'.  
35
+%  'MarkerSize'  scalar or Mx1 matrix of double. Default: 6.
36
+%  'MarkerColor' ColorSpec or Mx3 matrix of RGB triples. Default: 'k'.
37
+%  'Line'        string '-',':','--' or '-.' or 'none'. Default: '-'.
38
+%  'Surf'        [], Mx1 or Mx3 matrix of RGB triples 
39
+%                to define surface values. Default: [] = no surf. 
40
+%                Note: shading is turned to 'interp'.
41
+%  'LineWidth'   scalar or MxM matrix, default: 0.5
42
+%  'LineColor'   ColorSepc, MxMx3 matrix of RGB triples or a cell array 
43
+%                of form {r g b} where r,g, and b are MxM  
44
+%                (sparse) matrices of R,G, and B values
45
+%  'Label'       Mx1 char array, cell array of strings size MxL 
46
+%                or [] to indicate no labels, default: [] = no labels.
47
+%  'LabelSize'   scalar
48
+%  'LabelColor'  ColorSpec or string 'none', default: 'g'.
49
+%
50
+% For more help, try 'type som_grid' or check out online documentation.
51
+% See also SOM_CONNECTION, SOM_SHOW, SOM_CPLANE, SOM_SET, SCATTER, SCATTER3.
52
+
53
+%%%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
54
+%
55
+% som_grid
56
+%
57
+% PURPOSE 
58
+% 
59
+%  To visualize the SOM grid in various ways 
60
+% 
61
+% SYNTAX
62
+%
63
+%  [sGrid,m,l,t,s]=som_grid(sGrid)
64
+%  [sGrid,m,l,t,s]=som_grid(sTopol)
65
+%  [sGrid,m,l,t,s]=som_grid(sMap)
66
+%  [sGrid,m,l,t,s]=som_grid({lattice, msize, [shape]}) 
67
+%  [sGrid,m,l,t,s]=som_grid(lattice, msize)
68
+%  [sGrid,m,l,t,s]=som_grid(..., ['argID', value, ...])
69
+%
70
+% DESCRIPTION 
71
+%
72
+% The SOM can be defined as a set of units (neurons) and their
73
+% topological relations.  This function is used to visualize these in
74
+% various ways. The units may be drawn using different markers and
75
+% colors, in different sizes and in different locations in 2D or
76
+% 3D. However the topological neighborhood is limited to be
77
+% 2-dimensional. The connections between these units may be drawn using
78
+% lines having different thicknesses and colors. Labeling text may be
79
+% plotted on the units. It is possible also to draw a surface between
80
+% the units. The surface coloring is either indexed (one value per
81
+% unit) or fixed RGB (a 1x3 RGB triple per unit).
82
+%
83
+% REQUIRED INPUT ARGUMENTS 
84
+%
85
+% Note: M is the number of map units.
86
+% 
87
+% The first (or first two) argument may have various different types of values
88
+%
89
+%   1. sGrid   (struct) som_grid struct (the output of this function)
90
+%  
91
+%     The struct initiates the visualization. The argID-value -pairs
92
+%     are used to alter the initiation.
93
+%
94
+%   Following argument types may be used to give the topology for the grid
95
+% 
96
+%   2. sTopol  (struct) som_topol struct 
97
+%   3. sMap    (struct) som_map struct (only topology matters)
98
+%   4. {lattice, msize} or {lattice, msize, sheet} (cell array) 
99
+%       - lattice must be 'hexa' or 'rect'
100
+%       - msize must be a 1x2 vector
101
+%       - shape (if specified) must be string 'sheet', 'cyl' or 'toroid'
102
+%         If shape is not given it is 'sheet' by default.
103
+%   5. lattice (string or matrix) AND msize (1x2 vector) as two separate arguments
104
+%       - lattice may be string 'rect' or 'hexa' or a connection matrix
105
+%         (see SOM_CONNECTION) to define a free topology. This connection
106
+%         matrix is of size MxM and its element i,j (i<j) is set
107
+%         to 1 if there is a connection between units i and j, otherwise to 
108
+%         zero. Shape is set to 'sheet' by default. Shape does not have any 
109
+%         meaning if a free topology is specified, anyway.
110
+%       - msize must be a 1x2 vector
111
+%
112
+%  In cases 2...5 the sGrid structure is initiated by default values
113
+%  which are set in SOM_SET. These include black markers 'o' (6pt),
114
+%  light gray conncection lines (graph edges), unit coordinates
115
+%  according to the lattice ('hexa','rect'), no labels, and no
116
+%  surface.
117
+%
118
+%  OPTIONAL INPUT ARGUMENTS 
119
+%   
120
+%  Note: M is the number of map units.
121
+%   
122
+%  Here is a list of the valid arguments IDs and the associated
123
+%  values (identifiers are case insensitive):
124
+%
125
+%  'Coord'     Unit coordinates
126
+%              This defines the coordinates of the units. Default: the
127
+%              topological coordinates (calculated as in function
128
+%              SOM_VIS_COORDS and SOM_CPLANE). If the topology is free
129
+%              (lattice is a connection matrix) this argument is obligatory!
130
+%     (matrix) size Mx2 of 2D coordinates for each unit
131
+%     (matrix) size Mx3 of 3D coordinates for each unit
132
+% 
133
+% 'Marker'       Unit markers, default is 'o'.
134
+%     (string) 'o','+','x','*','v','^','<','>','h','s','d', 'p','.', or 'none'
135
+%              give the same marker for each unit. 
136
+%     (cell array) of size Mx1 of previous strings gives individual 
137
+%              markers for each unit.
138
+%     
139
+% 'MarkerSize'   Size (pt) of unit markers, default is 6 (pt).
140
+%     (scalar) gives the same size for every unit.  
141
+%     (matrix) Mx1 gives an individual size for each unit marker.  
142
+%
143
+%  'MarkerColor' Unit marker colors, default is 'k'
144
+%     (ColorSpec) gives the same color each unit. 
145
+%     (matrix) Mx3 of RGB triples gives individual color for each unit
146
+%              Note that indexed coloring - like in SOM_CPLANE - is
147
+%              not possible. If indexed coloring is needed, you can
148
+%              use SOM_NORMCOLOR to calculate RGB colors that
149
+%              emulate indexed coloring. However, the colors for the
150
+%              units are fixed, so changing colormap will not
151
+%              change the colors.
152
+%  
153
+%  'Line'        Line type, default is '-'.
154
+%     (string) '-',':','--' or '-.' or 'none'. Only one linetype in
155
+%              grid is allowed.  
156
+%
157
+%  'LineWidth'   Width of the topological connection lines (edges)  
158
+%     (scalar) gives the same width for each line. Default is 0.5.
159
+%     (matrix) MxM sparse (or full) matrix gives individual width for 
160
+%              each connection. The element (i,j), i<j, gives the line width for 
161
+%              connection between nodes i and j. (The sparse form is
162
+%              recommended for saving memory, a full matrix works as well,
163
+%              of course). Note that only the elements satisfying i<j
164
+%              matter - as the elememts for which j >= i are ignored in
165
+%              order to avoid ambiguous situations if the matrix would be 
166
+%              non-symmetric. The "connections to oneself" is not drawn. 
167
+%
168
+%              Line width zero is valid and causes the line to disappear.
169
+%           
170
+%  'LineColor'   Color of connection lines, default is [0.9 0.9 0.9].
171
+%     (ColorSpec) gives the same color for each line
172
+%     (matrix) MxMx3 matrix of RGB triples gives individual width for 
173
+%              each connection. The element (i,j,:), i<j, gives the RGB triple for 
174
+%              line between nodes i and j.     
175
+%     (cell array) of three sparse (or full) matrices {r,g,b} where 
176
+%              r(i,j), g(i,j) and b(i,j) gives the R,G, and B values in the RGB
177
+%              triple for the line between nodes i and j. (The motivation for this
178
+%              form is the fact that a 3D arrays can't use sparse format in 
179
+%              Matlab version 5.1.)
180
+%  
181
+%              Note that only the elements satisfying i<j matter - the elememts 
182
+%              for which j >= i are ignored in order to avoid ambiguous situations 
183
+%              if the matrix was non-symmetric. The "connections to oneself"
184
+%              is not drawn. 
185
+%    
186
+%
187
+%  'Label'       Labels for units, default is [].
188
+%     (empty)  [] means no labels.
189
+%     (char array) of size Mx1. Element (i,:) has the label for unit i.     
190
+%     (cell array) of size MxL consisting of sets of labels. Element {i,:} 
191
+%              contains the labeling for unit i. 
192
+%               In case of multiple labels, the labels for one unit are shown 
193
+%               in one column centered at that unit.
194
+%    
195
+%   'LabelSize'   Text size of labels (points), default is 10.
196
+%     (scalar) Default is 10.
197
+%
198
+%   'LabelColor'  Color of labels, default is 'c' (cyan).
199
+%     (ColorSpec) gives the same color for each label string 'xor'
200
+%                 sets the colors automatically so that they differ
201
+%                 from the background (using Matlab's built-in xor-color feature.)
202
+%    
203
+%  'Surf'         Surface between nodes, default is [].
204
+%     (empty)  [] gives no surface
205
+%     (vector) Mx1 gives an indexed interpolated color surface between 
206
+%              units using the actual colormap.
207
+%     (matrix) Mx3 matrix of RGB triples gives a interpolated color surface 
208
+%              between units using fixed RGB colors.
209
+%    
210
+%              Note that the interpolation is done using Matlab's built-in
211
+%              color interpolation for SURF objects.
212
+%
213
+% OUTPUT ARGUMENTS
214
+%
215
+%  sGrid    (struct) with fields S.msize, S.shape, S.lattice, S.coord, S.marker, 
216
+%                    S.markersize, S.markercolor, S.line, S.linewidth, S.linecolor,
217
+%                    S.surf, S.label, S.labelsize, S.labelcolor
218
+%
219
+%  m        (matrix) handels to LINE objects (unit markers) 
220
+%
221
+%  l        (matrix) handles to LINE objects (lines connecting the units)
222
+% 
223
+%  t        (matrix) handles to TEXT objects (labels)
224
+%
225
+%  s        (scalar) handle  to SURF object  (surface between units)
226
+%
227
+% EXAMPLES
228
+%
229
+% % Make map of size 15x10 on random data:
230
+% 
231
+%    map=som_make(rand(1000,4),'msize',[15 10], 'lattice', 'hexa');
232
+%
233
+% % Draw the grid using two frist varable values as coordinates
234
+% % and store the sGrid struct in varable S:
235
+%
236
+%    S=som_grid(map, 'coord', map.codebook(:,[1 2]))
237
+%
238
+% %Define some things: 
239
+% %
240
+% % Create a cell array of size 150x1 that divides map in to two label classes
241
+% % 'circles' and 'squares'
242
+%   
243
+%    L(1:75,1)='o'; L(76:150,1)='s'; L = cellstr(L);
244
+%    
245
+% % Create a coloring according to the 3rd variable according to current
246
+% % colormap: 
247
+%    
248
+%    C = som_normcolor(map.codebook(:,3));
249
+% 
250
+% % Change the visualization: use black lines, unit markers in M and unit
251
+% % color in C, and set unit size to 10:
252
+%
253
+%    S=som_grid(S, 'linecolor', 'k', 'marker', L, 'MarkerColor',C, ...
254
+%     'MarkerSize', 10);
255
+%
256
+% % Do a new visualization, use indexed color surface calcualted from the
257
+% % first variable, coordinates according to the lattice (default) but 
258
+% % no markers nor lines:
259
+% 
260
+%    S=som_grid(map,'line','none','marker','none','surf',map.codebook(:,1));
261
+%
262
+% % Set coordinates according to three last varables
263
+%
264
+%    som_grid(S,'coord',map.codebook(:,2:4));
265
+%
266
+% % Create a random connection matrix R1 and the usual hexagonal
267
+% % neighborhood connection matrix R2: 
268
+% 
269
+%    R1=sparse(rand(150,150)>0.9); 
270
+%    R2=som_connection(map);
271
+%
272
+% % Show these connections. Note that coordinates _must_ now be given
273
+% % explicitly: we form default topological coordinates using
274
+% % som_unit_coords.
275
+%
276
+%    som_grid(R1,map.topol.msize,'coord',som_unit_coords(map));
277
+%    som_grid(R2,map.topol.msize,'coord',som_unit_coords(map));
278
+%    
279
+% % Show connections (R1 AND R2)
280
+%    som_grid(R2.*R2,map.topol.msize,'coord',som_unit_coords(map));
281
+% 
282
+% OBJECT TAGS
283
+%
284
+%  No tags are set.
285
+%
286
+% SEE ALSO
287
+%
288
+%  som_show        The basic map visualization routine
289
+%  som_cplane      The basic component plane visualization
290
+%  som_connection  The basic topological connections
291
+%  scatter         Scatter plots
292
+%  scatter3        3-dimensional scatter plots 
293
+
294
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
295
+% http://www.cis.hut.fi/projects/somtoolbox/             
296
+
297
+% Version 2.0beta Johan 061099 juuso 151199 310300
298
+
299
+%% Init %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
300
+
301
+True=1; False=0;                % const.
302
+m=[]; l=[]; t=[]; s=[];         % default values for outputs
303
+Ref=som_set('som_grid');        % reference struct
304
+
305
+num_of_args=length(varargin);   % numb. of varargins
306
+
307
+if num_of_args==0,
308
+  S=som_set('som_grid');
309
+  return;
310
+end
311
+
312
+switch class(varargin{1})
313
+case 'struct'
314
+  S=varargin{1};
315
+  first_identifier=2;
316
+  if ~isfield(S,'type'),
317
+    error('Input struct is invalid: field ''type'' is missing.');
318
+  end
319
+  switch  S.type
320
+  case 'som_grid'
321
+    S=varargin{1};
322
+    first_identifier=2;
323
+  case 'som_map'
324
+    Ref.lattice=S.topol.lattice;
325
+    Ref.msize=S.topol.msize;
326
+    Ref.shape=S.topol.shape;
327
+    S=Ref;
328
+    first_identifier=2;
329
+  case 'som_topol'
330
+    Ref.lattice=S.lattice;
331
+    Ref.msize=S.msize;
332
+    Ref.shape=S.shape;
333
+    S=Ref;
334
+    first_identifier=2;
335
+  otherwise
336
+    error('Input struct has to be of type som_grid, som_map or som_topol.');
337
+  end
338
+case 'cell'
339
+  S=varargin{1};
340
+  first_identifier=2;
341
+  if vis_valuetype(S,{'topol_cell_no_shape'}),
342
+    Ref.lattice=S{1};
343
+    Ref.msize=S{2};
344
+  elseif vis_valuetype(S,{'topol_cell'}),
345
+    Ref.lattice=S{1};
346
+    Ref.msize=S{2};
347
+    Ref.shape=S{3};
348
+  else
349
+    error(['The cell value for 1st argument has to be {lattice, msize}' ...
350
+	  'or {lattice, msize, shape}.']); 
351
+  end
352
+  S=Ref; 
353
+case{'double','sparse','char'} 
354
+  % Set defaults
355
+  S=Ref;
356
+  first_identifier=3; 
357
+  if num_of_args<2,
358
+    error('Not enough input arguments.');
359
+  end
360
+  S.lattice=varargin{1};
361
+  S.msize=varargin{2};
362
+otherwise
363
+  error('Invalid input arguments!');
364
+end  
365
+
366
+%% Check input args %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
367
+
368
+for i=first_identifier:2:num_of_args,
369
+  if ischar(varargin{i}) & isfield(Ref,lower(varargin{i})),
370
+    if i+1>num_of_args,
371
+      error('Invalid identifier-value pairs or wrong argument order.');
372
+    else
373
+      S=setfield(S,lower(varargin{i}),varargin{i+1});
374
+    end
375
+  elseif ischar(varargin{i}), 
376
+    error(['Identifier ''' varargin{i} ''' is unknown.']);
377
+  else
378
+    error('Invalid identifier-value pairs or wrong argument order.');
379
+  end
380
+end 
381
+
382
+% msize
383
+
384
+if ~vis_valuetype(S.msize,{'1x2'}),
385
+  error('msize has to be a 1x2 vector.');
386
+end
387
+munits=prod(S.msize);
388
+
389
+% Default coordinates according to negihborhood
390
+
391
+if isempty(S.coord),
392
+  if ischar(S.lattice),
393
+    switch S.lattice,
394
+    case{'hexa','rect'}
395
+      S.coord=som_vis_coords(S.lattice,S.msize);
396
+    otherwise
397
+      error('String value for lattice must be ''hexa'' or ''rect''.');
398
+    end
399
+  else
400
+    error('Lattice is not ''hexa'' or ''rect'': coordinates must be given.');
401
+  end
402
+end
403
+
404
+% connections
405
+
406
+type=class(S.lattice);
407
+switch type
408
+case {'sparse','double'}   % free topology
409
+  fixedline=False;   
410
+case 'char'                % default topologies (hexa,char)
411
+  switch S.lattice
412
+  case 'hexa'
413
+    hexa=True;
414
+  case 'rect'
415
+    hexa=False;
416
+  otherwise
417
+    error('Unknown lattice or neighborhood.');
418
+  end
419
+
420
+  % If topology is hexa/rect but linetype, color etc. is 
421
+  % not constant, the topology is set to free
422
+
423
+  if size(S.linewidth,1)>1 | size(S.linecolor,1)>1 | ...
424
+    iscell(S.linecolor) % matrix or cell = not constant 
425
+    fixedline=False;
426
+    S.lattice=som_connection({S.lattice,S.msize,S.shape});
427
+  else
428
+    fixedline=True;
429
+  end
430
+end
431
+
432
+% Check coordinate matrix size and set dummy zeros to z-axis
433
+% if 2D coordinates (always 3D plots!)
434
+
435
+if ~vis_valuetype(S.coord,{[munits 2],[munits 3]}),
436
+   error('Coordinate matrix has wrong size.');
437
+elseif size(S.coord,2)==2,
438
+   S.coord(:,3)=0;
439
+end
440
+
441
+% Fixed marker size, color, type? 
442
+
443
+if size(S.markersize,1)>1 | size(S.markercolor,1)>1 | size(S.marker,1)>1
444
+   fixedmarker=False;
445
+else
446
+   fixedmarker=True;
447
+end
448
+
449
+% Check labels
450
+
451
+if ~vis_valuetype(S.label,{'chararray','2Dcellarray_of_char'}) ...
452
+      & ~isempty(S.label),
453
+  error('Labels should be in a char array or cell array of strings.');
454
+elseif ischar(S.label)
455
+  S.label=cellstr(S.label);
456
+end
457
+
458
+if size(S.label,1) ~= munits & ~isempty(S.label),
459
+  error('Number of labels and map size do not match.');
460
+end
461
+
462
+% Check line width, marker size, marker color,
463
+% label size label color and surf sizes&types:
464
+
465
+if ~vis_valuetype(S.linewidth,{[munits munits] [1 1]}),
466
+  error('LineWidth matrix value has wrong size or dimension.');
467
+elseif any(S.linewidth(:)<0),
468
+  error('All elements of LineWidth must be non-negative.');
469
+elseif ~vis_valuetype(S.markersize,{[munits 1] [1 1]}), 
470
+  error('MarkerSize matrix value has wrong size or dimension.');
471
+elseif any(S.markersize(:)<0), 
472
+  error('All elements of MarkerSize must be non-negative.');
473
+elseif ~vis_valuetype(S.markercolor,{'1x3rgb','colorstyle'}) & ...
474
+      ~vis_valuetype(S.markercolor,{[munits 3],'nx3rgb'},'all'),
475
+  error('MarkerColor should be a ColorSpec or Mx3 matrix of RGB triples.');
476
+elseif ~vis_valuetype(S.labelcolor,{'1x3rgb','colorstyle','xor'}),
477
+  error('LabelColor shoud be a ColorSpec or ''xor'' or ''none''.')
478
+elseif ~vis_valuetype(S.labelsize,{'1x1'})
479
+  error('LabelSize should be a scalar.');
480
+elseif ~isempty(S.surf) & ~vis_valuetype(S.surf,{[munits 1] [munits 3]});
481
+  error('Surf matrix value has wrong size or dimension.');
482
+end
483
+
484
+% Check marker type & size
485
+
486
+if vis_valuetype(S.marker,{'cellcolumn_of_char'}) 
487
+  % Don't bother to check the mareker strings in this case
488
+  % let the plot3 handle them; it returns quite understandable
489
+  % error messages, anyway
490
+  
491
+  if ~size(S.marker) == [munits 1],
492
+    error(['Marker should be one of Matlab''s valid marker type,' ...
493
+	   ' string ''none'' or a Mx1 cell array of these.']); 
494
+  end
495
+elseif ~vis_valuetype(S.marker,{'markerstyle','none'}),
496
+      error(['Marker should be one of Matlab''s valid marker type,' ...
497
+	   ' string ''none'' or a Mx1 cell array of these.']); 
498
+end
499
+
500
+% Check line type & size: only one line style allowed
501
+
502
+if ~vis_valuetype(S.line,{'linestyle','none'}) 
503
+  error(['Line should be a valid Matlab''s line style string or' ...
504
+	 ' string ''none''.']);
505
+end
506
+	
507
+% Check line color
508
+
509
+if iscell(S.linecolor),
510
+  if ndims(S.linecolor) ~= 2 | any(size(S.linecolor) ~= [1 3]),
511
+    error('Cell input for LineColor should be of form {r,g,b}.')
512
+  elseif ~vis_valuetype(S.linecolor{1},{[munits munits],'nxn[0,1]'},'all')| ...
513
+	~vis_valuetype(S.linecolor{2},{[munits munits],'nxn[0,1]'},'all')| ...
514
+	~vis_valuetype(S.linecolor{3},{[munits munits],'nxn[0,1]'},'all'),
515
+    error(['In cell input {r,g,b} some matrix r,g or b is invalid: ' ...
516
+	   'Size must be MxM and values in interval [0,1].']);
517
+  end 
518
+elseif ~vis_valuetype(S.linecolor,{'colorstyle','1x3rgb'}) & ...
519
+      ~vis_valuetype(S.linecolor,{'nxnx3rgb', [munits munits 3]},'all'),
520
+  error('Invalid LineColor: see help text for valid values.'),
521
+elseif vis_valuetype(S.linecolor, {'none'}),
522
+  error('LineColor ''none'' not allowed: set Line to ''none'' instead.');
523
+end
524
+
525
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
526
+%% Action
527
+
528
+memhold=ishold; % take hold state
529
+if ~memhold
530
+   cla;
531
+end
532
+hold on;
533
+
534
+% Set surf if it exist
535
+
536
+if ~isempty(S.surf),
537
+   for i=1:3,
538
+      s(:,:,i)=reshape(S.coord(:,i),S.msize);
539
+   end
540
+   s(:,:,4:3+size(S.surf,2))=reshape(S.surf,[S.msize size(S.surf,2)]);
541
+   s=surf(s(:,:,1),s(:,:,2),s(:,:,3),s(:,:,4:end));
542
+   set(s,'EdgeColor','none','Marker','none','FaceColor','interp');
543
+end
544
+
545
+
546
+if fixedline,
547
+  % Line properties are fixed: draw fast, but
548
+  % if line is set to 'none' set empty handle ans skip
549
+  if strcmp(S.line,'none')
550
+    l={};
551
+  else
552
+    p1=reshape(S.coord, [S.msize 3]);
553
+    p2=zeros(size(p1)-[0 1 0]);
554
+    p2(1:2:end,:,:)=p1(1:2:end,2:end,:);
555
+    p2(2:2:end,:,:)=p1(2:2:end,1:end-1,:);
556
+    
557
+    l{1}=plot3(p1(:,:,1), p1(:,:,2), p1(:,:,3), ...
558
+	       'Color', S.linecolor(1,:), ...
559
+	       'LineWidth', S.linewidth(1), ...
560
+	       'LineStyle', S.line);
561
+    l{2}=plot3(p1(:,:,1)', p1(:,:,2)', p1(:,:,3)', ...
562
+	       'Color', S.linecolor(1,:), ...
563
+	       'LineWidth', S.linewidth(1), ...
564
+	       'LineStyle', S.line);
565
+    if hexa,
566
+      l{3}=plot3(p2(:,:,1), p2(:,:,2), p2(:,:,3), ...
567
+		 'Color', S.linecolor(1,:), ...
568
+		 'LineWidth', S.linewidth(1), ...
569
+		 'LineStyle', S.line);
570
+    end
571
+  end
572
+  l=cat(1,l{:});
573
+else
574
+   % Variable properties: draw connection by connection
575
+   
576
+   [I,J,lw]=find(S.lattice); 
577
+   x=[S.coord(I,1)'; S.coord(J,1)']; 
578
+   y=[S.coord(I,2)'; S.coord(J,2)'];
579
+   z=[S.coord(I,3)'; S.coord(J,3)'];
580
+   if S.linewidth(1)==0,
581
+      linewidth=0.5;
582
+   else
583
+      linewidth=S.linewidth(1);
584
+   end
585
+   if ndims(S.linecolor) ~=  3
586
+     if isstr(S.linecolor)  
587
+       l=plot3(x, y, z, ...
588
+	       'Color', S.linecolor, ...
589
+	       'LineWidth', linewidth, ...
590
+	       'LineStyle',S.line);
591
+     else 
592
+       if iscell(S.linecolor)
593
+         lcolor=[S.linecolor{1}(1,1) S.linecolor{2}(1,1) S.linecolor{3}(1,1)];
594
+         l=plot3(x, y, z, ...
595
+		 'Color', lcolor, ...
596
+		 'LineWidth', linewidth, ...
597
+		 'LineStyle',S.line);
598
+       else
599
+         l=plot3(x, y, z, ...
600
+                 'Color', S.linecolor(1,:), ...
601
+                 'LineWidth', linewidth, ...
602
+                 'LineStyle',S.line);
603
+       end
604
+     end
605
+   else
606
+     l=plot3(x, y, z, ...
607
+	     'Color', S.linecolor(1,1,:), ...
608
+	     'LineWidth', linewidth, ...
609
+	     'LineStyle',S.line);
610
+   end
611
+end
612
+
613
+if fixedmarker,
614
+
615
+  % If marker is set to 'none' skip and set empty handle 
616
+  if strcmp(S.marker,'none')
617
+    m=[]; 
618
+  else
619
+    % Fixed markers: draw all in one command
620
+
621
+    m=plot3(S.coord(:,1), S.coord(:,2), S.coord(:,3), ... 
622
+	    'LineStyle', 'none', ...
623
+	    'Marker', S.marker, ...
624
+	    'MarkerSize', S.markersize(1), ...
625
+	    'MarkerFaceColor', S.markercolor(1,:), ...
626
+	    'MarkerEdgeColor', S.markercolor(1,:));
627
+  end
628
+else
629
+  % Variable marker properties: draw marker by marker
630
+
631
+  x=[S.coord(:,1)'; S.coord(:,1)']; 
632
+  y=[S.coord(:,2)'; S.coord(:,2)'];
633
+  z=[S.coord(:,3)'; S.coord(:,3)'];
634
+  if iscell(S.marker)
635
+    marker=S.marker{1};
636
+  else
637
+    marker=S.marker(1);
638
+  end
639
+  sz=max(S.markersize(1),0.1);
640
+  m=plot3(x, y, z, ... 
641
+	  'LineStyle', 'none', ...
642
+	  'Marker', marker, ...
643
+	  'MarkerSize', sz, ... 
644
+	  'MarkerFaceColor', S.markercolor(1,:), ...
645
+	  'MarkerEdgeColor', S.markercolor(1,:));
646
+end
647
+
648
+L=length(l); 
649
+n=munits;
650
+
651
+%%% Set variable properties %%%
652
+
653
+% Line width
654
+
655
+if length(S.linewidth)>1 
656
+   lwidth=diag(S.linewidth(I,J)); 
657
+
658
+   % Handle zero width
659
+   iszero=(lwidth == 0);lwidth(iszero)=0.5;
660
+   for i=1:length(l),
661
+     set(l(i),'LineWidth', lwidth(i));
662
+   end
663
+   if ~isempty(iszero), % zero width
664
+      set(l(iszero),'Visible','off');
665
+   end
666
+end
667
+
668
+% Line color
669
+
670
+if size(S.linecolor,1)>1 | iscell(S.linecolor)
671
+   if length(size(S.linecolor)) == 3 | iscell(S.linecolor) 
672
+     if ~iscell(S.linecolor)
673
+       for i=1:L
674
+         set(l(i),'Color',S.linecolor(I(i),J(i),:));
675
+       end
676
+     else
677
+       for i=1:L
678
+         lcolor=[S.linecolor{1}(I(i),J(i)),...
679
+                 S.linecolor{2}(I(i),J(i)),...
680
+                 S.linecolor{3}(I(i),J(i))];
681
+         set(l(i),'Color',lcolor);
682
+       end
683
+     end
684
+   else
685
+     for i=1:L,
686
+       set(l(i),'Color', S.linecolor(I(i),:));
687
+     end
688
+   end
689
+end
690
+
691
+% Marker size
692
+
693
+if length(S.markersize)>1
694
+   % handle zero size
695
+   iszero=find(~S.markersize);
696
+   S.markersize(iszero)=1;
697
+   for i=1:n,
698
+      set(m(i),'MarkerSize', S.markersize(i));
699
+   end
700
+   if ~isempty(iszero), % zero size
701
+      set(m(iszero),'Visible','off');
702
+   end
703
+end
704
+
705
+% Marker type
706
+
707
+if size(S.marker,1)>1
708
+   S.marker=char(S.marker);
709
+   for i=1:n,
710
+      set(m(i),'Marker', S.marker(i));
711
+   end
712
+end
713
+
714
+% Marker color
715
+
716
+if size(S.markercolor,1)>1
717
+   for i=1:n,
718
+     set(m(i),'MarkerFaceColor', S.markercolor(i,:), ...
719
+	      'MarkerEdgeColor', S.markercolor(i,:));
720
+   end
721
+end
722
+
723
+% Set labels if they exist
724
+
725
+if ~isempty(S.label)
726
+  if vis_valuetype(S.labelcolor,{'xor'}),
727
+    S.labelcolor='g';
728
+    XOR=1;
729
+  else
730
+    XOR=0;
731
+  end
732
+  if vis_valuetype(S.labelcolor,{'none'}),
733
+    S.labelcolor='g';
734
+    VIS = 1;
735
+  else
736
+    VIS = 0;
737
+  end
738
+  for i=1:size(S.label,1),
739
+    L=cat(1,S.label(i,:)); 
740
+    for j=length(L):-1:1,
741
+      if isempty(L{j}),
742
+	L=L(1:end-1); 
743
+      end
744
+    end
745
+    
746
+    if isempty(L),
747
+      L='';
748
+    end
749
+    t(i)=text(S.coord(i,1), S.coord(i,2), S.coord(i,3), L,...
750
+	'FontSize', S.labelsize, 'Color',S.labelcolor, ...
751
+	'HorizontalAlignment', 'center');
752
+  end
753
+  if XOR
754
+    set(t,'EraseMode','xor');
755
+  end
756
+  if VIS
757
+    set(t,'Visible','off');
758
+  end 
759
+else
760
+   t=[];
761
+end
762
+
763
+%% Set hold state
764
+
765
+if ~memhold,
766
+   hold off; 
767
+end
768
+
769
+if nargout==0,
770
+  clear S m l t s;
771
+end
0 772
\ No newline at end of file
... ...
@@ -0,0 +1,3130 @@
1
+function som_gui(varargin)
2
+
3
+%SOM_GUI A GUI for initialization and training of SOM.
4
+%
5
+% som_gui([sD]) 
6
+% 
7
+%   som_gui
8
+%   som_gui(sD)
9
+%
10
+%  Input and output arguments ([]'s are optional) 
11
+%   [sD]     (struct) SOM data struct
12
+%            (matrix) a data matrix, size dlen x dim
13
+%
14
+%   Actually, there are more arguments the function takes, but 
15
+%   they are for internal action of the function only. DO NOT use
16
+%   them.
17
+%
18
+% For a more throughout description, see the online documentation.
19
+% See also PREPROCESS.
20
+
21
+%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
22
+%
23
+% IN FILES: som_gui.html,browsewin.jpg,wspace.jpg,loadgui.jpg,initgui.jpg,questdlg.jpg,paragui.jpg,mwindow.jpg,visgui.gif,reload.gif,savemap.gif,browse.gif
24
+%
25
+
26
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Mika Pollari
27
+% Copyright (c) by Mika Pollari and SOM Toolbox Team
28
+% http://www.cis.hut.fi/projects/somtoolbox/
29
+
30
+% Mika Pollari 31.1.2000 vs 1.1
31
+
32
+global NEWMAP NEWST MAPSAVED MAP DATA  LOAD_NAME LOAD_DATA;
33
+global SAVEMAP ALGORITHM HANDLE2 STOPOLINIT INIT_TYPE;
34
+global STRAIN1 STRAIN2 SOTHERS;
35
+
36
+if nargin == 0
37
+  main_gui;
38
+  action = 'dummy';	
39
+elseif nargin == 1
40
+  temp = varargin{1};
41
+  if isstruct(temp),
42
+    DATA = temp;
43
+    main_gui;
44
+    action = 'input_data';
45
+  elseif isnumeric(temp), 
46
+    DATA = som_data_struct(temp);
47
+    main_gui;
48
+    action = 'input_data';
49
+  else
50
+    action = temp;			
51
+  end
52
+end 
53
+
54
+
55
+switch(action)
56
+
57
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LOAD %%%%%%%%%%%%%%%%%%%%%%%%%%
58
+  case 'load_data'
59
+     loadgui3;		%%% Activates load GUI
60
+  case 'workspace'
61
+       workspace;	%%% Workspace selected
62
+  case 'file'
63
+        file;  		%%% File Selected
64
+  case 'file_select'
65
+	file_select; 
66
+  case 'missing'	
67
+       Handle = findobj(gcf,'Tag','Checkbox1');
68
+       set(Handle,'Value',1);	
69
+  case 'load_ok'	%%% <Load OK> pushed
70
+     	load_ok;	
71
+  case 'input_data'	%%% GUI activated with data as arg1
72
+     	input_data;     %%% eg. som_gui(data)
73
+
74
+  case 'browse'		%%% Activates Browse GUI		
75
+	browse;		%%% Browse files or workspace variables
76
+
77
+  case 'works_ok'	%%% <OK> pushed in (workspace) browse GUI
78
+	works_ok;
79
+
80
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
81
+
82
+
83
+%%%%%%%%%%%%%%%%%%%%%%%% Initialization %%%%%%%%%%%%%%%%%%%%%%%%%%%%
84
+
85
+  case 'def_initialization'	%%% Finds default initialization ...
86
+	def_initialization;     %%% parameters
87
+
88
+  case 'change_initialization'	%%% Activates change (init) parameters GUI    
89
+	change_initialization;
90
+
91
+  case 'change_initialization_ok'%%% Set new init. parameters 	
92
+	change_initialization_ok;
93
+
94
+  case 'change_initialization_cancel'
95
+	close(gcf);
96
+	return;
97
+
98
+  case 'map_size' %%% Checks that 'map_size' is given in correct form
99
+	map_size;
100
+
101
+  case 'munits'   %%% Checks that 'munits' is given in correct form
102
+	munits;
103
+  
104
+  case 'init'	%%% Initialize Map
105
+	init;
106
+
107
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
108
+
109
+%%%%%%%%%%%%%%%%%%%%%%%%% Train %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
110
+
111
+
112
+  case 'def_values_others'
113
+	def_values_others;
114
+
115
+  case 'def_values_train'
116
+ 	STRAIN1 = som_train_struct('algorithm',ALGORITHM,'phase','rough','data',DATA);
117
+	STRAIN2 = som_train_struct('previous',STRAIN1);
118
+
119
+  case 'fill_fields'	%%% Fill text fields in GUI
120
+	fill_fields;
121
+
122
+  case 'def_train'	%%% Train Map
123
+     	def_train;
124
+
125
+  case 'change_def'	%%% Change default training parameters 
126
+	change_def;	%%% Activate GUI
127
+
128
+  case 'fill_new_defaults' 
129
+	fill_new_defaults;
130
+
131
+  case 'set_batch_mask'
132
+	set_batch_mask;
133
+
134
+  case 'set_new_parameters'
135
+	set_new_parameters;
136
+
137
+  case 'only_finetune' 	%%% Train only once with finetune parameters
138
+	only_finetune;
139
+
140
+%%%%%%% Next function check correctnes of new training parameters.
141
+
142
+  case 'check_rough_radini'
143
+	check_rough_radini;
144
+  case 'check_fine_radini'
145
+	check_fine_radini;
146
+  case 'check_rough_radfin'
147
+	check_rough_radfin;
148
+  case 'check_fine_radfin'
149
+	check_fine_radfin;
150
+  case 'check_rough_alphaini'
151
+	check_rough_alphaini;
152
+  case 'check_fine_alphaini'
153
+	check_fine_alphaini;
154
+  case 'check_rough_trainlen'
155
+	check_rough_trainlen;
156
+  case 'check_fine_trainlen'
157
+	check_fine_trainlen;
158
+
159
+
160
+
161
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
162
+
163
+%%%%%%%%%%%%%%%%%%%%%%%%% Save Map %%%%%%%%%%%%%%%%%%%%%%
164
+
165
+  case 'savemap'	%%% Save as <.cod> file
166
+	savemap;
167
+  case 'save_workspace'	%%% Save in workspace
168
+	save_workspace;
169
+
170
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
171
+
172
+
173
+%%%%%%%%%%%%%%%%%%%%%%% Help & Info %%%%%%%%%%%%%%%%%%%%%%%
174
+  case 'help'
175
+    web file:///share/somtoolbox/vs2/html/som_GUI.html;
176
+  case 'helpwin'
177
+    helpwin1;
178
+  case 'helpwin2'
179
+    helpwin som_gui;	
180
+  case 'data_info'
181
+	data_info;   %%% Info about data
182
+  case 'map_info'    %%% Info about map
183
+	map_info;
184
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
185
+
186
+%%%%%%%%%%%%%%%%%%% Other Functions %%%%%%%%%%%%%%%%%%%%%%%
187
+
188
+  case 'preprocess'
189
+	preprocess_gui;		%%%%% Call preprocess GUI
190
+  case 'visualize'
191
+	visualize;		%%%%% Call visualization GUI
192
+
193
+  case 'clear_all'		%%%%% Clear all filds
194
+	clear_all;		
195
+
196
+  case 'close'
197
+	close_fig;		%%%%% Close active GUI 	
198
+
199
+end 
200
+
201
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
202
+%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%%%
203
+%%%%%%%%%%%%   END OF SWITCH-STATEMENT  %%%%%%%%%%%%%%%%%%%%%
204
+%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%%%
205
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
206
+
207
+
208
+
209
+
210
+
211
+
212
+
213
+
214
+
215
+
216
+
217
+
218
+
219
+
220
+
221
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
222
+%%%%%%%%% (SUB) FUNCTIONS
223
+
224
+
225
+
226
+
227
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
228
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
229
+%%%%%%%%%%%%%%%%%     LOAD SECTION STARTS	%%%%%%%%%%%%%%%%%%%
230
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
231
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%	
232
+
233
+function [] = workspace()
234
+Handle = findobj(gcbf,'Tag','Radiobutton2');
235
+Value = get(Handle,'Value');
236
+HandleTemp = findobj(gcbf,'Tag','Radiobutton1');
237
+if Value == 1	
238
+  set(HandleTemp,'Value',0);
239
+  HandleBar = findobj(gcbf,'Tag','PopupMenu1');
240
+  set(HandleBar,'Enable','off');
241
+  set(HandleBar,'Visible','off');
242
+  Handle3 = findobj(gcbf,'Tag','StaticText3');
243
+  set(Handle3,'Visible','off');
244
+  Handle3 = findobj(gcbf,'Tag','Checkbox1');
245
+  set(Handle3,'Visible','off');
246
+  Handle3 = findobj(gcbf,'Tag','EditText3');
247
+  set(Handle3,'Visible','off');
248
+  Handle = findobj(gcbf,'Tag','EditText2');
249
+  set(Handle,'String','');
250
+end
251
+
252
+
253
+
254
+function [] = file()
255
+Handle = findobj(gcbf,'Tag','Radiobutton1');
256
+Value = get(Handle,'Value');
257
+HandleTemp = findobj(gcbf,'Tag','Radiobutton2');
258
+if Value == 1
259
+  set(HandleTemp,'Value',0);
260
+  HandleBar = findobj(gcbf,'Tag','PopupMenu1');
261
+  set(HandleBar,'Enable','on');
262
+  set(HandleBar,'Visible','on');
263
+  Handle3 = findobj(gcbf,'Tag','StaticText3');
264
+  set(Handle3,'Visible','on');
265
+  Handle3 = findobj(gcbf,'Tag','Checkbox1');
266
+  set(Handle3,'Visible','on');
267
+  Handle3 = findobj(gcbf,'Tag','EditText3');
268
+  set(Handle3,'Visible','on'); 
269
+  Handle = findobj(gcbf,'Tag','EditText1');
270
+  set(Handle,'String','');
271
+end
272
+
273
+function [] = file_select() 
274
+Handle = findobj(gcbf,'Tag','PopupMenu1');
275
+temp = get(Handle,'String');
276
+val = get(Handle,'Value');
277
+Handle1 = findobj(gcbf,'Tag','Checkbox1');
278
+Handle2 = findobj(gcbf,'Tag','EditText3');
279
+if strcmp(temp{val},'dat file')
280
+   set(Handle2,'String','x');
281
+   set(Handle1,'Enable','on');
282
+   set(Handle2,'Enable','on');
283
+   set(Handle1,'Visible','on');
284
+   set(Handle2,'Visible','on');
285
+  else 
286
+   set(Handle1,'Value',0);
287
+   set(Handle1,'Enable','off');
288
+   set(Handle2,'Enable','off');
289
+   set(Handle1,'Visible','off');
290
+   set(Handle2,'Visible','off');
291
+end
292
+
293
+function [] = load_ok()
294
+global MAP DATA LOAD_DATA LOAD_NAME;
295
+Handle1 = findobj(gcbf,'Tag','EditText1');
296
+Handle2 = findobj(gcbf,'Tag','EditText2');
297
+Name1 = get(Handle1,'String');
298
+Name2 = get(Handle2,'String');
299
+if isempty(Name1) & not(isempty(Name2))
300
+  Handle = findobj(gcbf,'Tag','PopupMenu1')
301
+  type = get(Handle,'String');
302
+  val = get(Handle,'Value');
303
+  type = type{val};
304
+  if strcmp(type,'mat file')
305
+      ltemp = 'load:::';
306
+      ltemp = strcat(ltemp,Name2);
307
+      ltemp = strrep(ltemp,':::',' ');
308
+      evalin('base',ltemp);
309
+      DATA = evalin('base','sD');
310
+      LOAD_DATA = evalin('base','sD.data');
311
+      LOAD_NAME = evalin('base','sD.name');
312
+      LOAD_NAME = strrep(LOAD_NAME,'.','_');
313
+      load_labels = evalin('base','sD.labels');
314
+      load_comp_names = evalin('base','sD.comp_names');
315
+      DATA = som_data_struct(LOAD_DATA);
316
+      DATA.name = LOAD_NAME;
317
+      DATA.comp_names = load_comp_names;
318
+      DATA.labels = load_labels;
319
+   else
320
+      Handle = findobj(gcbf,'Tag','Checkbox1');
321
+      value = get(Handle,'Value');
322
+      if value == 0	
323
+         temp = 'som_read_data(''';
324
+         temp = strcat(temp,Name2,''');');
325
+      else 
326
+          Handle = findobj(gcbf,'Tag','EditText3');
327
+          missing = get(Handle,'String');
328
+          if not(isempty(missing))
329
+              temp = 'som_read_data(''';
330
+              temp = strcat(temp,Name2,'''',',','''',missing,''');');
331
+          else
332
+	      temp = 'som_read_data(''';
333
+              temp = strcat(temp,Name2,''');');
334
+          end   
335
+      end
336
+     evalin('base',temp);
337
+     DATA = evalin('base','ans');
338
+     name = DATA.name;
339
+     temp = findstr('/',name);
340
+     if not(isempty(temp))	
341
+         name = name(temp(end)+1:end);
342
+     end
343
+     name = strrep(name,'.','_');		
344
+     LOAD_NAME = name;
345
+     DATA.name = name;	
346
+   end
347
+elseif isempty(Name2) & not(isempty(Name1))
348
+   LOAD_DATA = evalin('base',Name1);
349
+   if not(isstruct(LOAD_DATA))
350
+      DATA = som_data_struct(LOAD_DATA);
351
+      LOAD_NAME = Name1;
352
+      DATA.name = Name1;
353
+   else
354
+      DATA = LOAD_DATA;
355
+      name = DATA.name;
356
+      temp = findstr('/',name);
357
+      if not(isempty(temp))	
358
+	 name = name(temp(end)+1:end);
359
+      end
360
+      name = strrep(name,'.','_');		
361
+      LOAD_NAME = name;
362
+      DATA.name = name;
363
+   end
364
+else 
365
+   errmsg = {'Give name of data before loading'};
366
+   errordlg(errmsg,'Empty data name!');
367
+   return;
368
+end
369
+close(gcbf);			     			
370
+if not(isempty(MAP))
371
+   clear MAP;
372
+   global MAP;
373
+   str1 = 'Map:  <empty>';
374
+   str2 = 'Train';
375
+   Handle = findobj(gcf,'Tag','StaticText3');
376
+   set(Handle,'String',str1);
377
+   Handle = findobj(gcf,'Tag','StaticText8');
378
+   set(Handle,'String',str2);
379
+end	
380
+temp =  'Data:';
381
+temp = strcat(temp,' <',LOAD_NAME,'>');	
382
+Handle = findobj(gcf,'Tag','StaticText4');
383
+set(Handle,'String',temp);
384
+som_gui('def_initialization');
385
+Handle = findobj(gcf,'Tag','Pushbutton2');
386
+set(Handle,'Enable','off');
387
+Handle = findobj(gcf,'Tag','Pushbutton4');
388
+set(Handle,'Enable','on');
389
+Handle = findobj(gcf,'Tag','Pushbutton9');
390
+set(Handle,'Enable','on');
391
+Handle = findobj(gcf,'Tag','Subuimenu2');
392
+set(Handle,'Enable','on');
393
+Handle = findobj(gcf,'Tag','&Help/InfoHelp windowuimenu1');
394
+set(Handle,'Enable','on');
395
+Handle = findobj(gcf,'Tag','&Init&Trainuimenu1');
396
+set(Handle,'Enable','on');
397
+Handle = findobj(gcf,'Tag','&Init&TrainInitialize1');
398
+set(Handle,'Enable','on');
399
+Handle = findobj(gcf,'Tag','Subuimenu1');
400
+set(Handle,'Enable','off'); %%%%%%????????	
401
+Handle = findobj(gcf,'Tag','StaticText10');
402
+set(Handle,'String','Status <data loaded>');	
403
+ 
404
+
405
+
406
+function [] = input_data()
407
+global DATA; 
408
+name = DATA.name;
409
+newname = strrep(name,'.','_');
410
+DATA.name = newname;
411
+temp = strcat('Data:  <',newname,'>');	
412
+Handle = findobj(gcf,'Tag','StaticText4');
413
+set(Handle,'String',temp);
414
+som_gui('def_initialization');
415
+Handle = findobj(gcf,'Tag','Pushbutton2');
416
+set(Handle,'Enable','off');
417
+Handle = findobj(gcf,'Tag','Pushbutton4');
418
+set(Handle,'Enable','on');
419
+Handle = findobj(gcf,'Tag','Pushbutton9');
420
+set(Handle,'Enable','on');
421
+Handle = findobj(gcf,'Tag','Subuimenu2');
422
+set(Handle,'Enable','on');
423
+Handle = findobj(gcf,'Tag','&Help/InfoHelp windowuimenu1');
424
+set(Handle,'Enable','on');
425
+Handle = findobj(gcf,'Tag','&Init&Trainuimenu1');
426
+set(Handle,'Enable','on');
427
+Handle = findobj(gcf,'Tag','&Init&TrainInitialize1');
428
+set(Handle,'Enable','on');
429
+Handle = findobj(gcf,'Tag','Subuimenu1');
430
+set(Handle,'Enable','off'); %%%%%%????????	
431
+Handle = findobj(gcf,'Tag','StaticText10');
432
+set(Handle,'String','Status <data loaded>');	
433
+
434
+
435
+function [] = browse()
436
+global HANDLE2;
437
+HandleWorkspace = findobj(gcbf,'Tag','Radiobutton2');
438
+HandleFile = findobj(gcbf,'Tag','Radiobutton1');
439
+WorkspaceVal = get(HandleWorkspace,'Value');
440
+FileVal = get(HandleFile,'Value');
441
+if FileVal == 1
442
+   Handle = findobj(gcbf,'Tag','PopupMenu1');
443
+   str = get(Handle,'String');
444
+   value = get(Handle,'Value');
445
+   str = str{value};
446
+   if strcmp(str,'mat file')
447
+      filtter = '*.mat';
448
+   else
449
+      filtter = '*.dat*';
450
+   end 
451
+   [filename pathname] = uigetfile(filtter,'Load file.');
452
+   temp = strcat(pathname,filename);
453
+   Handle = findobj(gcbf,'Tag','EditText2');
454
+   set(Handle,'String',temp);
455
+elseif WorkspaceVal == 1
456
+   HANDLE2 = gcf;
457
+   works;
458
+   temp = evalin('base','who');
459
+   index2 = 1;
460
+   names = '';
461
+   for index = 1:length(temp)
462
+      if isnumeric(evalin('base',temp{index}))
463
+	test = size(evalin('base',temp{index}));
464
+	if test(1) ~= 1 & test(2) ~= 1
465
+   	   names{index2} = temp{index};	
466
+	   index2 = index2 + 1;
467
+	end
468
+      end
469
+   end
470
+   for index = 1:length(temp)
471
+	variable = evalin('base',temp{index});
472
+	if isstruct(variable)
473
+	   fnames = fieldnames(variable);
474
+	   if size(fnames,1) == 6 & strcmp(fnames(1),'type') & strcmp(variable.type,'som_data')
475
+	     names{index2} = temp{index};	
476
+	     index2 = index2 + 1;
477
+	   end
478
+	end 
479
+   end	
480
+   Handle = findobj(gcf,'Tag','Listbox1');
481
+   %%%%%% if is empty string#%%%
482
+   set(Handle,'String',names);
483
+else
484
+   errmsg = 'Select browse type: Workspace or file.';
485
+   errordlg(errmsg,'Browse error!');
486
+   return;
487
+end
488
+
489
+
490
+function [] = works_ok()
491
+global HANDLE2;
492
+Handle = findobj(gcbf,'Tag','Listbox1');
493
+temp = get(Handle,'String');
494
+val = get(Handle,'Value');
495
+data = temp{val};
496
+Handle = findobj(HANDLE2,'Tag','EditText1');
497
+set(Handle,'String',data);
498
+close;
499
+
500
+
501
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
502
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
503
+%%%%%%%%%%%%%%%%%     END OF LOAD SECTION	%%%%%%%%%%%%%%%%%%%
504
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
505
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%	
506
+
507
+
508
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
509
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
510
+%%%%%%%%%%%%%%%%%     START OF INITIALIZATION	%%%%%%%%%%%%%%%%%%%
511
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
512
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%	
513
+
514
+function [] = def_initialization()
515
+global DATA STOPOLINIT INIT_TYPE;
516
+sTopol = som_topol_struct('data',DATA);
517
+Handle = findobj(gcf,'Tag','StaticText5');
518
+temp = num2str(sTopol.msize);
519
+temp = strcat('map size:',' [',temp,']');
520
+set(Handle,'String',temp);
521
+Handle = findobj(gcf,'Tag','StaticText6');
522
+set(Handle,'String','type: linear');
523
+Handle = findobj(gcf,'Tag','StaticText20');
524
+temp = strcat('lattice:',sTopol.lattice);
525
+set(Handle,'String',temp);
526
+Handle = findobj(gcf,'Tag','StaticText21');
527
+temp = strcat('shape:',sTopol.shape);
528
+set(Handle,'String',temp);
529
+STOPOLINIT = sTopol;
530
+INIT_TYPE = 'linear';
531
+
532
+function [] = change_initialization()
533
+global INIT_TYPE STOPOLINIT; 
534
+initialization2;
535
+Handle = findobj(gcf,'Tag','PopupMenu1');
536
+temp = get(Handle,'String');
537
+val = loop(temp,INIT_TYPE);
538
+set(Handle,'Value',val);
539
+Handle = findobj(gcf,'Tag','PopupMenu2');
540
+temp = get(Handle,'String');
541
+val = loop(temp,STOPOLINIT.lattice);
542
+set(Handle,'Value',val);
543
+Handle = findobj(gcf,'Tag','PopupMenu3');
544
+temp = get(Handle,'String');
545
+val = loop(temp,STOPOLINIT.shape);
546
+set(Handle,'Value',val);
547
+Handle = findobj(gcf,'Tag','EditText1');
548
+temp = num2str(STOPOLINIT.msize);
549
+msize = strcat('[',temp,']');
550
+set(Handle,'String',msize);
551
+
552
+function [] = change_initialization_ok()
553
+Handle = findobj(gcbf,'Tag','PopupMenu1');
554
+temp = get(Handle,'String');
555
+val = get(Handle,'Value');
556
+INIT_TYPE = temp{val};
557
+Handle = findobj(gcbf,'Tag','PopupMenu2');
558
+temp = get(Handle,'String');
559
+val = get(Handle,'Value');
560
+lattice = temp{val};
561
+Handle = findobj(gcbf,'Tag','PopupMenu3');
562
+temp = get(Handle,'String');
563
+val = get(Handle,'Value');
564
+shape = temp{val};
565
+Handle = findobj(gcbf,'Tag','EditText1');
566
+temp = get(Handle,'String');
567
+msize = str2num(temp);
568
+STOPOLINIT = som_set('som_topol','msize',msize,'lattice',lattice,'shape',shape);
569
+close(gcf);
570
+Handle = findobj(gcf,'Tag','StaticText5');
571
+temp = num2str(STOPOLINIT.msize);
572
+temp = strcat('map size:',' [',temp,']');
573
+set(Handle,'String',temp);
574
+Handle = findobj(gcf,'Tag','StaticText6');
575
+temp = strcat('type:',INIT_TYPE);
576
+set(Handle,'String',temp);
577
+Handle = findobj(gcf,'Tag','StaticText20');
578
+temp = strcat('lattice:',STOPOLINIT.lattice);
579
+set(Handle,'String',temp);
580
+Handle = findobj(gcf,'Tag','StaticText21');
581
+temp = strcat('shape:',STOPOLINIT.shape);
582
+set(Handle,'String',temp);
583
+
584
+
585
+function [] = def_values_others()
586
+global SOTHERS;
587
+Handle = findobj(gcf,'Tag','StaticText19');
588
+temp = strcat('tracking:',SOTHERS.tracking);
589
+set(Handle,'String',temp);
590
+Handle = findobj(gcf,'Tag','StaticText12');
591
+temp = strcat('order:',SOTHERS.oder);
592
+set(Handle,'String',temp); 
593
+Handle = findobj(gcf,'Tag','StaticText14');
594
+temp = strcat('length_type:',SOTHERS.length_type);
595
+set(Handle,'String',temp);
596
+
597
+
598
+
599
+function [] = fill_fields()
600
+global STRAIN1 STRAIN2 ALGORITHM
601
+
602
+neigh = STRAIN1.neigh;
603
+mask = STRAIN1.mask;
604
+rad_ini1 = STRAIN1.radius_ini;
605
+rad_ini2 = STRAIN2.radius_ini;
606
+rad_fin1 = STRAIN1.radius_fin;
607
+rad_fin2 = STRAIN2.radius_fin;
608
+trainlen1 = num2str(STRAIN1.trainlen);
609
+trainlen2 = num2str(STRAIN2.trainlen);
610
+alpha_ini1 = num2str(STRAIN1.alpha_ini);
611
+alpha_ini2 = num2str(STRAIN2.alpha_ini);
612
+if strcmp(ALGORITHM,'seq')
613
+        alpha_type = STRAIN1.alpha_type; %%% only in sequential
614
+        Handle = findobj(gcf,'Tag','StaticText28');
615
+        temp = strcat('alpha type:',alpha_type);
616
+        set(Handle,'String',temp);
617
+end
618
+Handle = findobj(gcf,'Tag','StaticText11');
619
+temp = strcat('neigh: ',neigh);
620
+set(Handle,'String',temp);
621
+Handle = findobj(gcf,'Tag','StaticText22');
622
+temp = num2str(rad_fin1);
623
+temp = strcat('radius final:',temp);
624
+set(Handle,'String',temp);
625
+Handle = findobj(gcf,'Tag','StaticText25');
626
+temp = num2str(rad_fin2);
627
+temp = strcat('radius final:',temp);
628
+set(Handle,'String',temp);
629
+Handle = findobj(gcf,'Tag','StaticText11');
630
+temp = strcat('neigh: ',neigh);
631
+set(Handle,'String',temp);
632
+Handle = findobj(gcf,'Tag','StaticText17');
633
+temp = num2str(rad_ini1);
634
+temp = strcat('radius initial:',temp);
635
+set(Handle,'String',temp);
636
+Handle = findobj(gcf,'Tag','StaticText24');
637
+temp = num2str(rad_ini2);
638
+temp = strcat('radius initial:',temp);
639
+set(Handle,'String',temp);
640
+Handle = findobj(gcf,'Tag','StaticText16');
641
+temp = num2str(trainlen1);
642
+temp = strcat('training length:',temp);
643
+set(Handle,'String',temp);
644
+Handle = findobj(gcf,'Tag','StaticText23');
645
+temp = num2str(trainlen2);
646
+temp = strcat('training length:',temp);
647
+set(Handle,'String',temp);
648
+Handle = findobj(gcf,'Tag','StaticText26');
649
+temp = strcat('alpha initial:',alpha_ini1);
650
+set(Handle,'String',temp);
651
+Handle = findobj(gcf,'Tag','StaticText27');
652
+temp = strcat('alpha initial:',alpha_ini2);
653
+set(Handle,'String',temp);
654
+
655
+
656
+function [] = init();
657
+global INIT_TYPE MAP NEWMAP ALGORITHM SOTHERS DATA STOPOLINIT;
658
+if strcmp(INIT_TYPE,'random')
659
+   MAP = som_randinit(DATA,STOPOLINIT);
660
+else 
661
+   MAP = som_lininit(DATA,STOPOLINIT);
662
+end
663
+NEWMAP = MAP;	
664
+temp = 'Map:';
665
+temp = strcat(temp,' <',MAP.name,'>');
666
+Handle = findobj(gcbf,'Tag','StaticText3');
667
+set(Handle,'String',temp);
668
+Handle = findobj(gcbf,'Tag','StaticText10');
669
+set(Handle,'String','Status <map initialized>');
670
+ALGORITHM = 'batch';
671
+Handle = findobj(gcbf,'Tag','Pushbutton4');
672
+set(Handle,'Enable','off');
673
+Handle = findobj(gcbf,'Tag','Pushbutton6');
674
+set(Handle,'Enable','on');
675
+Handle = findobj(gcbf,'Tag','Pushbutton5');
676
+set(Handle,'Enable','on');		
677
+SOTHERS.tracking = '1';
678
+SOTHERS.length_type = 'epochs';
679
+SOTHERS.oder = 'random';			
680
+som_gui('def_values_topol');
681
+som_gui('def_values_train');
682
+som_gui('def_values_others');
683
+som_gui('fill_fields');
684
+Handle = findobj(gcbf,'Tag','Pushbutton4');
685
+set(Handle,'Enable','off');
686
+Handle = findobj(gcbf,'Tag','Pushbutton9');
687
+set(Handle,'Enable','off');
688
+Handle = findobj(gcbf,'Tag','Radiobutton1');
689
+set(Handle,'Enable','on');
690
+Handle = findobj(gcbf,'Tag','&Init&TrainChange initialization valuesuimenu1');
691
+set(Handle,'Enable','on');
692
+Handle = findobj(gcbf,'Tag','&Init&TrainTrain1');
693
+set(Handle,'Enable','on');
694
+Handle = findobj(gcbf,'Tag','&Help/InfoData infouimenu1');
695
+set(Handle,'Enable','on');	
696
+Handle = findobj(gcbf,'Tag','Subuimenu2');
697
+set(Handle,'Enable','off');
698
+Handle = findobj(gcbf,'Tag','&Init&Trainuimenu1');
699
+set(Handle,'Enable','off');
700
+Handle = findobj(gcbf,'Tag','&Init&TrainInitialize1');
701
+set(Handle,'Enable','off');  %%%%%%%%%%%??????????			
702
+Handle = findobj(gcbf,'Tag','StaticText9');
703
+set(Handle,'String','training type: batch');	
704
+
705
+
706
+
707
+function [] = set_batch_mask()
708
+Handle = findobj(gcbf,'Tag','Listbox2');
709
+temp = get(Handle,'String');
710
+mask = str2num(temp);
711
+Handle = findobj(gcbf,'Tag','Listbox1');
712
+replace = get(Handle,'Value');
713
+Handle = findobj(gcbf,'Tag','EditText2');
714
+temp = get(Handle,'String');
715
+value = str2num(temp);
716
+if not(isempty(value))
717
+  mask(replace) = value;
718
+  Handle = findobj(gcbf,'Tag','Listbox2');
719
+  temp = num2str(mask);
720
+  set(Handle,'String',temp);
721
+end
722
+
723
+function [] = munits()
724
+global DATA STOPOLINIT;
725
+msgs = {'Correct map units is number';'Correct map units is number'};
726
+[msgs_nro, value] = check_ok('EditText2');
727
+if msgs_nro > 0
728
+   errordlg({msgs{msgs_nro}},'Incorrect map units!')
729
+   return;
730
+end
731
+STOPOLINIT = som_topol_struct('munits',value,'data',DATA);
732
+Handle = findobj(gcbf,'Tag','EditText1');
733
+temp = num2str(STOPOLINIT.msize);
734
+msize = strcat('[',temp,']');
735
+set(Handle,'String',msize);
736
+
737
+function [] = map_size()
738
+ global STOPOLINIT;
739
+ msgs = {'Map size must be in form [x y]';...
740
+		'Map size must be in form [x y]'};
741
+ [msgs_nro, value, Handle] = msize_ok('EditText1');
742
+ if msgs_nro > 0
743
+   errordlg({msgs{msgs_nro}},'Incorrect map size!');
744
+   temp = num2str(STOPOLINIT.msize);
745
+   temp = strcat('[',temp,']');
746
+   set(Handle,'String',temp);	
747
+   return;
748
+ end
749
+ STOPOLINIT.msize = value;
750
+ Handle = findobj(gcbf,'Tag','EditText2');
751
+ set(Handle,'String','');
752
+
753
+
754
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
755
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
756
+%%%%%%%%%%%%%%%%%     END OF INITIALIZATION	%%%%%%%%%%%%%%%%%%%
757
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
758
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%	
759
+
760
+
761
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
762
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
763
+%%%%%%%%%%%%%%%%%     START OF TRAINING		%%%%%%%%%%%%%%%%%%%
764
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
765
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%	
766
+
767
+
768
+function  [] = def_train()
769
+global SOTHERS ALGORITHM MAP NEWST DATA STRAIN1 STRAIN2 MAPSAVED;
770
+tlen_type = SOTHERS.length_type;
771
+sample_order = SOTHERS.oder;	
772
+tracking = SOTHERS.tracking;
773
+test = str2num(tracking);
774
+Handle = findobj(gcbf,'Tag','Radiobutton1');
775
+tempval = get(Handle,'Value');
776
+if strcmp(ALGORITHM,'seq')
777
+    if tempval ~= 1
778
+       [MAP NEWST] = som_seqtrain(MAP,DATA,'train',STRAIN1,tlen_type,sample_order);
779
+    end
780
+    if test > 1
781
+	figure;
782
+	set(gcf,'Name',MAP.name);
783
+	 set(gcf,'NumberTitle','off');
784
+    end
785
+    [NEWMAP NEWST] = som_seqtrain(MAP,DATA,'train',STRAIN2,'tracking',test,tlen_type,sample_order); 
786
+else
787
+    if tempval ~= 1
788
+       [MAP NEWST] = som_batchtrain(MAP,DATA,'train',STRAIN1);
789
+    end
790
+    if test > 1
791
+       figure;
792
+       set(gcf,'Name',MAP.name);
793
+       set(gcf,'NumberTitle','off');
794
+    end
795
+        [NEWMAP NEWST] = som_batchtrain(MAP,DATA,'train',STRAIN2,'tracking',test);
796
+end
797
+MAP = NEWMAP;
798
+clear MAPSAVED;	
799
+Handle = findobj(gcbf,'Tag','StaticText10');
800
+set(Handle,'String','Status <map trained>');
801
+Handle = findobj(gcbf,'Tag','Load/SaveSubuimenu1');
802
+set(Handle,'Enable','on');		
803
+Handle = findobj(gcbf,'Tag','Load/SaveSave mapuimenu1');
804
+set(Handle,'Enable','on');	 
805
+Handle = findobj(gcbf,'Tag','&Load/SaveSave mapSave in workspaceuimenu1');
806
+set(Handle,'Enable','on');
807
+Handle = findobj(gcbf,'Tag','&ToolsSubuimenu1');
808
+set(Handle,'Enable','on');
809
+Handle = findobj(gcbf,'Tag','&Init&TrainChange initialization valuesuimenu1');
810
+set(Handle,'Enable','off');
811
+Handle = findobj(gcbf,'Tag','&Init&TrainTrain1');
812
+set(Handle,'Enable','off');		
813
+
814
+
815
+function [] = change_def()
816
+global ALGORITHM STRAIN1 DATA; 
817
+
818
+ButtonName = questdlg('Select training type!',...
819
+	'Change values.',...
820
+	'Batch','Sequential','Cancel',...
821
+        'Batch');	
822
+if strcmp(ButtonName,'Sequential')
823
+   Handle = findobj(gcbf,'Visible','off');
824
+   set(Handle,'Visible','on');
825
+   ALGORITHM = 'seq';
826
+   Handle = findobj(gcf,'Tag','StaticText9');
827
+   set(Handle,'String','training type: sequential');
828
+   new_para2_2;
829
+   Handle = findobj(gcf,'Tag','StaticText1');
830
+   set(Handle,'String','Change parameters for sequential training');
831
+   Handle = findobj(gcf,'Enable','off');
832
+   set(Handle,'Enable','on');
833
+   Handle = findobj(gcf,'Visible','off');
834
+   set(Handle,'Visible','on');
835
+elseif strcmp(ButtonName,'Batch')
836
+   ALGORITHM = 'batch';
837
+   Handle = findobj(gcbf,'Tag','StaticText26');
838
+   set(Handle,'Visible','off');
839
+   Handle = findobj(gcbf,'Tag','StaticText27');
840
+   set(Handle,'Visible','off');
841
+   Handle = findobj(gcf,'Tag','StaticText9');
842
+   set(Handle,'String','training type: batch');
843
+   Handle = findobj(gcf,'Tag','StaticText12');
844
+   set(Handle,'Visible','off');
845
+   Handle = findobj(gcf,'Tag','StaticText28');
846
+   set(Handle,'Visible','off');
847
+   Handle = findobj(gcf,'Tag','StaticText14');
848
+   set(Handle,'Visible','off');
849
+   new_para2_2;	
850
+   Handle = findobj(gcf,'Tag','StaticText1');
851
+   set(Handle,'String','Change parameters for batch training');
852
+   Handle = findobj(gcf,'Tag','PopupMenu3');
853
+   set(Handle,'Enable','off');
854
+   set(Handle,'Visible','off');
855
+   Handle = findobj(gcf,'Tag','PopupMenu4');
856
+   set(Handle,'Enable','off');
857
+   set(Handle,'Visible','off');
858
+   Handle = findobj(gcf,'Tag','PopupMenu5');
859
+   set(Handle,'Enable','off');
860
+   set(Handle,'Visible','off');
861
+   Handle = findobj(gcf,'Tag','StaticText17');
862
+   set(Handle,'Visible','off');
863
+   Handle = findobj(gcf,'Tag','StaticText18');
864
+   set(Handle,'Visible','off');
865
+   Handle = findobj(gcf,'Tag','StaticText19');
866
+   set(Handle,'Visible','off');
867
+   Handle = findobj(gcf,'Tag','StaticText13');
868
+   set(Handle,'Visible','off'); 
869
+   Handle = findobj(gcf,'Tag','StaticText14');
870
+   set(Handle,'Visible','off');
871
+   Handle = findobj(gcf,'Tag','EditText6');
872
+   set(Handle,'Visible','off');
873
+   set(Handle,'Enable','off');
874
+   Handle = findobj(gcf,'Tag','EditText10');
875
+   set(Handle,'Visible','off');
876
+   set(Handle,'Enable','off');    
877
+else 
878
+   return;	
879
+end
880
+som_gui('def_values_train');	
881
+mask = STRAIN1.mask;
882
+Handle = findobj(gcf,'Tag','Listbox1');
883
+set(Handle,'String',DATA.comp_names);
884
+som_gui('fill_new_defaults');
885
+
886
+
887
+function [] = fill_new_defaults()
888
+global STRAIN1 STRAIN2 SOTHERS ALGORITHM;
889
+
890
+Handle = findobj(gcf,'Tag','EditText4');
891
+temp = num2str(STRAIN1.radius_ini);
892
+set(Handle,'String',temp);
893
+Handle = findobj(gcf,'Tag','EditText8');
894
+temp = num2str(STRAIN2.radius_ini);
895
+set(Handle,'String',temp);
896
+Handle = findobj(gcf,'Tag','EditText5');
897
+temp = num2str(STRAIN1.radius_fin);
898
+set(Handle,'String',temp);
899
+Handle = findobj(gcf,'Tag','EditText9');
900
+temp = num2str(STRAIN2.radius_fin);
901
+set(Handle,'String',temp);	
902
+Handle = findobj(gcf,'Tag','EditText6');
903
+temp = num2str(STRAIN1.alpha_ini);
904
+set(Handle,'String',temp);
905
+Handle = findobj(gcf,'Tag','EditText10');
906
+temp = num2str(STRAIN2.alpha_ini);
907
+set(Handle,'String',temp);
908
+Handle = findobj(gcf,'Tag','EditText7');
909
+temp = num2str(STRAIN1.trainlen);
910
+set(Handle,'String',temp);
911
+Handle = findobj(gcf,'Tag','EditText11');
912
+temp = num2str(STRAIN2.trainlen);
913
+set(Handle,'String',temp);
914
+Handle = findobj(gcf,'Tag','Listbox2');
915
+temp = num2str(STRAIN1.mask');
916
+set(Handle,'String',temp);
917
+Handle = findobj(gcf,'Tag','PopupMenu2');
918
+string = get(Handle,'String');
919
+val = loop(string,SOTHERS.tracking);
920
+set(Handle,'Value',val);
921
+Handle = findobj(gcf,'Tag','PopupMenu1');
922
+string = get(Handle,'String');
923
+val = loop(string,STRAIN1.neigh);
924
+set(Handle,'Value',val);
925
+if strcmp(ALGORITHM,'seq')
926
+   Handle = findobj(gcf,'Tag','PopupMenu3');
927
+   string = get(Handle,'String');
928
+   val = loop(string,SOTHERS.length_type);
929
+   set(Handle,'Value',val);
930
+   Handle = findobj(gcf,'Tag','PopupMenu4');
931
+   string = get(Handle,'String');
932
+   val = loop(string,SOTHERS.oder);
933
+   set(Handle,'Value',val);
934
+   Handle = findobj(gcf,'Tag','PopupMenu5');
935
+   string = get(Handle,'String');
936
+   val = loop(string,STRAIN1.alpha_type);
937
+   set(Handle,'Value',val);
938
+end			
939
+
940
+
941
+
942
+function [] = set_new_parameters()
943
+global STRAIN1 STRAIN2 ALGORITHM SOTHERS; 
944
+
945
+Handle = findobj(gcbf,'Tag','Listbox2');
946
+temp = get(Handle,'String');
947
+mask = str2num(temp); %%%%%%%%%%%%% Do somthing
948
+mask = mask';
949
+Handle = findobj(gcbf,'Tag','PopupMenu1');
950
+temp = get(Handle,'String');
951
+val = get(Handle,'Value');
952
+neigh = temp{val};
953
+Handle = findobj(gcbf,'Tag','PopupMenu2');
954
+temp = get(Handle,'String');
955
+val = get(Handle,'Value');
956
+SOTHERS.tracking = temp{val};  %%%%% finetune phase!
957
+Handle = findobj(gcbf,'Tag','EditText4');
958
+temp = get(Handle,'String');
959
+rad_ini1 = str2num(temp);
960
+Handle = findobj(gcbf,'Tag','EditText8');
961
+temp = get(Handle,'String');
962
+rad_ini2 = str2num(temp);
963
+Handle = findobj(gcbf,'Tag','EditText5');
964
+temp = get(Handle,'String');
965
+rad_fin1 = str2num(temp);
966
+Handle = findobj(gcbf,'Tag','EditText9');
967
+temp = get(Handle,'String');
968
+rad_fin2 = str2num(temp);
969
+Handle = findobj(gcbf,'Tag','EditText6');
970
+temp = get(Handle,'String');
971
+alpha_ini1 = str2num(temp);
972
+Handle = findobj(gcbf,'Tag','EditText10');
973
+temp = get(Handle,'String');
974
+alpha_ini2 = str2num(temp);
975
+Handle = findobj(gcbf,'Tag','EditText7');
976
+temp = get(Handle,'String');
977
+train_length1 = str2num(temp);
978
+Handle = findobj(gcbf,'Tag','EditText11');
979
+temp = get(Handle,'String');
980
+train_length2 = str2num(temp);
981
+if strcmp(ALGORITHM,'seq')
982
+   Handle = findobj(gcbf,'Tag','PopupMenu3');
983
+   temp = get(Handle,'String');
984
+   val = get(Handle,'Value');
985
+   SOTHERS.length_type = temp{val};
986
+   Handle = findobj(gcbf,'Tag','PopupMenu4');
987
+   temp = get(Handle,'String');
988
+   val = get(Handle,'Value');
989
+   SOTHERS.oder= temp{val};
990
+   Handle = findobj(gcbf,'Tag','PopupMenu5');
991
+   temp = get(Handle,'String');
992
+   val = get(Handle,'Value');
993
+   alpha_type = temp{val};
994
+else 
995
+   alpha_type = 'inv';
996
+end
997
+STRAIN1.neigh = neigh;
998
+STRAIN2.neigh = neigh;
999
+STRAIN1.mask = mask;
1000
+STRAIN2.mask = mask;
1001
+STRAIN1.radius_ini = rad_ini1;
1002
+STRAIN2.radius_ini = rad_ini2;
1003
+STRAIN1.radius_fin = rad_fin1;
1004
+STRAIN2.radius_fin = rad_fin2;
1005
+STRAIN1.alpha_ini = alpha_ini1;
1006
+STRAIN2.alpha_ini = alpha_ini2;
1007
+STRAIN1.alpha_type = alpha_type;
1008
+STRAIN2.alpha_type = alpha_type;
1009
+STRAIN1.trainlen = train_length1;
1010
+STRAIN2.trainlen = train_length2;
1011
+close(gcbf);
1012
+som_gui('fill_fields');
1013
+som_gui('def_values_others');
1014
+
1015
+function [] = only_finetune()
1016
+
1017
+Handle = findobj(gcbf,'Tag','Radiobutton1');
1018
+test = get(Handle,'Value');
1019
+if test == 1
1020
+   Handle = findobj(gcbf,'Tag','StaticText16');
1021
+   set(Handle,'Enable','off');
1022
+   Handle = findobj(gcbf,'Tag','StaticText17');
1023
+   set(Handle,'Enable','off');
1024
+   Handle = findobj(gcbf,'Tag','StaticText22');
1025
+   set(Handle,'Enable','off');
1026
+   Handle = findobj(gcbf,'Tag','StaticText26');
1027
+   set(Handle,'Enable','off');
1028
+else 
1029
+   Handle = findobj(gcbf,'Tag','StaticText16');
1030
+   set(Handle,'Enable','on');
1031
+   Handle = findobj(gcbf,'Tag','StaticText17');
1032
+   set(Handle,'Enable','on');
1033
+   Handle = findobj(gcbf,'Tag','StaticText22');
1034
+   set(Handle,'Enable','on');
1035
+   Handle = findobj(gcbf,'Tag','StaticText26');
1036
+   set(Handle,'Enable','on');
1037
+end
1038
+
1039
+
1040
+function [] = check_rough_radini()
1041
+global STRAIN1;
1042
+msgs = {'Initial radius must be number!';...
1043
+        'Initial radius must be single valued number!'};
1044
+[msgs_nro, value, Handle] = check_ok('EditText4');
1045
+if msgs_nro > 0
1046
+   errordlg({msgs{msgs_nro}},'Incorrect initial radius!')
1047
+   temp = num2str(STRAIN1.radius_ini);
1048
+   set(Handle,'String',temp);
1049
+   return;
1050
+end
1051
+
1052
+
1053
+function [] = check_fine_radini()
1054
+global STRAIN2;
1055
+msgs = {'Initial radius must be number!';...
1056
+        'Initial radius must be single valued number!'};
1057
+[msgs_nro, value, Handle] = check_ok('EditText8');
1058
+if msgs_nro > 0
1059
+   errordlg({msgs{msgs_nro}},'Incorrect initial radius!')
1060
+   temp = num2str(STRAIN2.radius_ini);
1061
+   set(Handle,'String',temp);
1062
+   return;
1063
+end
1064
+
1065
+function [] = check_rough_radfin()
1066
+global STRAIN1;
1067
+msgs = {'Final radius must be number!';...
1068
+	'Final radius must be single valued number!'};
1069
+[msgs_nro, value, Handle] = check_ok('EditText5');
1070
+if msgs_nro > 0
1071
+   errordlg({msgs{msgs_nro}},'Incorrect final radius!')
1072
+   temp = num2str(STRAIN1.radius_fin);
1073
+   set(Handle,'String',temp);
1074
+   return;
1075
+end
1076
+
1077
+function [] = check_fine_radfin()
1078
+global STRAIN2;
1079
+msgs = {'Final radius must be number!';...
1080
+	'Final radius must be single valued number!'};
1081
+[msgs_nro, value, Handle] = check_ok('EditText9');
1082
+if msgs_nro > 0
1083
+   errordlg({msgs{msgs_nro}},'Incorrect final radius!')
1084
+   temp = num2str(STRAIN2.radius_fin);
1085
+   set(Handle,'String',temp);
1086
+   return;
1087
+end
1088
+
1089
+function [] = check_rough_alphaini()
1090
+global STRAIN1;	
1091
+msgs = {'Alpha initial must be number!';...
1092
+	'Alpha initial must be single valued number!'};
1093
+[msgs_nro, value, Handle] = check_ok('EditText6');
1094
+if msgs_nro > 0
1095
+   errordlg({msgs{msgs_nro}},'Incorrect initial alpha!')
1096
+   temp = num2str(STRAIN1.alpha_ini);
1097
+   set(Handle,'String',temp);
1098
+   return;
1099
+end
1100
+
1101
+function [] = check_fine_alphaini()
1102
+global STRAIN2;
1103
+msgs = {'Alpha initial must be number!';...
1104
+	'Alpha initial must be single valued number!'};
1105
+[msgs_nro, value, Handle] = check_ok('EditText10');
1106
+if msgs_nro > 0
1107
+   errordlg({msgs{msgs_nro}},'Incorrect initial alpha!')
1108
+   temp = num2str(STRAIN2.alpha_ini);
1109
+   set(Handle,'String',temp);
1110
+   return;
1111
+end
1112
+
1113
+function [] = check_rough_trainlen()
1114
+global STRAIN1;
1115
+msgs = {'Training length must be number!';...
1116
+	'Training length must be single valued number!'};
1117
+[msgs_nro, value, Handle] = check_ok('EditText7');
1118
+if msgs_nro > 0
1119
+   errordlg({msgs{msgs_nro}},'Incorrect training length!')
1120
+   temp = num2str(STRAIN1.trainlen);
1121
+   set(Handle,'String',temp);
1122
+   return;
1123
+end
1124
+
1125
+function [] = check_fine_trainlen()
1126
+global STRAIN2;
1127
+
1128
+msgs = {'Training length must be number!';...
1129
+	'Training length must be single valued number!'};
1130
+[msgs_nro, value, Handle] = check_ok('EditText11');
1131
+if msgs_nro > 0
1132
+   errordlg({msgs{msgs_nro}},'Incorrect training length!')
1133
+   temp = num2str(STRAIN2.trainlen);
1134
+   set(Handle,'String',temp);
1135
+   return;
1136
+end	
1137
+
1138
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1139
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
1140
+%%%%%%%%%%%%%%%%%     END OF TRAINING		%%%%%%%%%%%%%%%%%%%
1141
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
1142
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%	
1143
+
1144
+
1145
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1146
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
1147
+%%%%%%%%%%%%%%%%%     START OF SAVING		%%%%%%%%%%%%%%%%%%%
1148
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
1149
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%	
1150
+
1151
+
1152
+function [] = savemap()
1153
+global MAP MAPSAVED;
1154
+if isempty(MAP)
1155
+  str = {'There is no map to be saved! Train map before saving.'};
1156
+  helpdlg(str,'Empty map!');	
1157
+  return;
1158
+end
1159
+[FileName Path] = uiputfile('*.cod','Save file!');
1160
+if FileName ~= 0
1161
+   temp = strcat(Path,FileName);
1162
+   som_write_cod(MAP,temp);
1163
+   MAPSAVED = 'SAVED';
1164
+end
1165
+Handle = findobj(gcf,'Tag','StaticText10');
1166
+set(Handle,'String','Status <map saved>');	 
1167
+
1168
+function [] = save_workspace()
1169
+global MAP MAPSAVED;
1170
+if isempty(MAP)
1171
+   str = {'There is no map to be saved! Train map before saving.'};
1172
+   helpdlg(str,'Empty map!');
1173
+   return;
1174
+else
1175
+   prompt = {'Save map as?'};
1176
+   title = 'Save map!';
1177
+   lineNo = 1;
1178
+   answer = inputdlg(prompt,title,lineNo);
1179
+   if isempty(answer)
1180
+      return;
1181
+   end
1182
+   if not(isempty(answer{1}))
1183
+      ws_variable = evalin('base','who');
1184
+      max_length = 0;
1185
+      for index = 1:size(ws_variable,1)
1186
+         if max_length < size(ws_variable{index},2)
1187
+	    max_length = size(ws_variable{index},2);
1188
+         end
1189
+      end
1190
+      length = max_length + 1;
1191
+      tempfoo(1:1:length) = 'A'; 
1192
+      assignin('base',tempfoo,answer{1});
1193
+      str = ['exist(' tempfoo ')'];	
1194
+      temp = evalin('base',str); %%%%%%%%%%@@@@@@@@@
1195
+      evalin('base',['clear ' tempfoo ]) 
1196
+      if temp == 0
1197
+         assignin('base',answer{1},MAP);
1198
+         MAPSAVED = 'SAVED';
1199
+      elseif temp ~= 0
1200
+         Questmsg = strcat('Variable',' ''',answer{1},'''',...
1201
+         ' exist. Overwrite?');
1202
+         ButtonName = questdlg(Questmsg);
1203
+         switch(ButtonName)
1204
+         case 'Yes'
1205
+            assignin('base',answer{1},MAP);
1206
+            MAPSAVED = 'SAVED';
1207
+         case 'No' 
1208
+             som_gui('save_workspace');		
1209
+         end
1210
+     end	
1211
+   else
1212
+      helpmsg = {'There cannot be any empty field in ''save'''};
1213
+      helpdlg(helpmsg,'Help Save!');
1214
+      som_gui('save'); 
1215
+   end
1216
+end
1217
+Handle = findobj(gcf,'Tag','StaticText10');
1218
+set(Handle,'String','Status <map saved>');
1219
+
1220
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1221
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
1222
+%%%%%%%%%%%%%%%%%     END OF SAVING		%%%%%%%%%%%%%%%%%%%
1223
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
1224
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%	
1225
+
1226
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1227
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
1228
+%%%%%%%%%%%%%%%%%     START OF HELP & INFO	%%%%%%%%%%%%%%%%%%%
1229
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
1230
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%	
1231
+
1232
+%HEREXX
1233
+
1234
+function [] = data_info()
1235
+global DATA;
1236
+if isempty(DATA)
1237
+   helpmsg = 'Load data first!';
1238
+   helpdlg(helpmsg,'Empty data!');
1239
+   return;
1240
+end
1241
+file_name = tempname;
1242
+file_name = strcat(file_name,'.m');
1243
+fid = fopen(file_name,'w');
1244
+fprintf(fid,'%% %+35s\n','DATA INFO');
1245
+fprintf(fid,'%%\n');
1246
+print_info(DATA,2,fid);
1247
+directory = tempdir;
1248
+addpath (directory);
1249
+helpwin (file_name);
1250
+fclose(fid);
1251
+delete(file_name);
1252
+rmpath (directory);
1253
+
1254
+
1255
+function [] = map_info()
1256
+global MAP;
1257
+if isempty(MAP)
1258
+   helpmsg = 'There is no map!';
1259
+   helpdlg(helpmsg,'Empty map!');
1260
+   return;
1261
+end
1262
+file_name = tempname;
1263
+file_name = strcat(file_name,'.m');
1264
+fid = fopen(file_name,'w');
1265
+fprintf(fid,'%% %+35s\n','MAP INFO');
1266
+fprintf(fid,'%%\n');
1267
+print_info(MAP,2,fid);
1268
+directory = tempdir;
1269
+addpath (directory);
1270
+helpwin (file_name);
1271
+fclose(fid);
1272
+delete(file_name);
1273
+rmpath (directory); 
1274
+
1275
+
1276
+function [] = helpwin1()
1277
+file1 = tempname;
1278
+file1 = strcat(file1,'.m');
1279
+directory = tempdir;	
1280
+html2tex('file:///share/somtoolbox/vs2/html/som_GUI.html',file1);
1281
+addpath (directory);
1282
+helpwin (file1);
1283
+rmpath (directory);
1284
+delete (file1);		
1285
+
1286
+
1287
+
1288
+
1289
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1290
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
1291
+%%%%%%%%%%%%%%%%%     END OF HELP & INFO	%%%%%%%%%%%%%%%%%%%
1292
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
1293
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%	
1294
+
1295
+
1296
+
1297
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1298
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
1299
+%%%%%%%%%%%%%%%%%     START OF OTHER FUNC	%%%%%%%%%%%%%%%%%%%
1300
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
1301
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%	
1302
+
1303
+
1304
+
1305
+function [msgs_nro, value, Handle] = check_ok(Tag)
1306
+Handle = findobj(gcbf,'Tag',Tag);
1307
+temp = get(Handle,'String');
1308
+value = str2num(temp);
1309
+if isempty(value)
1310
+   msgs_nro = 1;
1311
+   return;
1312
+end
1313
+[test1 test2] = size(value);
1314
+if test1 ~= 1 | test2 ~= 1
1315
+   msgs_nro = 2;	  
1316
+   return; 
1317
+end
1318
+msgs_nro = 0;	
1319
+
1320
+
1321
+function [msgs_nro, value, Handle] = msize_ok(Tag)
1322
+Handle = findobj(gcbf,'Tag',Tag);
1323
+temp = get(Handle,'String');
1324
+value = str2num(temp);
1325
+if isempty(value)
1326
+   msgs_nro = 1;
1327
+   return;
1328
+end
1329
+[test1 test2] = size(value);
1330
+if test1 ~= 1 | test2 ~= 2
1331
+   msgs_nro = 2;	  
1332
+   return; 
1333
+end
1334
+msgs_nro = 0;
1335
+
1336
+
1337
+%%% Changed 1.2.2000
1338
+
1339
+function [] = visualize()
1340
+global MAP;
1341
+if isempty(MAP)
1342
+   helpmsg = {'Train map before tryinig to visualize it!'};
1343
+   helpdlg(helpmsg,'Empty Map!');
1344
+   return;
1345
+end
1346
+
1347
+dim = size(MAP.codebook,2);
1348
+odim = 2;
1349
+[P,V] = pcaproj(MAP.codebook,odim);
1350
+ccode = som_colorcode(MAP, 'rgb1');
1351
+
1352
+figure; 
1353
+som_show(MAP,'umat','all','comp',1:dim,'norm','d');  
1354
+figure;
1355
+subplot(1,2,1) 
1356
+som_grid(MAP,'Coord',P,'MarkerColor',ccode,'Markersize',5, ...
1357
+	 'Linewidth',1,'Linecolor','k');
1358
+xlabel('PC1'), ylabel('PC2')
1359
+title('PCA-projection (on the left), color coding (on the right)')
1360
+axis tight, axis equal
1361
+subplot(1,2,2) 
1362
+som_cplane(MAP.topol.lattice,MAP.topol.msize,ccode);
1363
+
1364
+%msgbox('Save map in workspace. Load it from there.');
1365
+%som_gui('save_workspace');  
1366
+%som_comp_vis;
1367
+
1368
+%%%%%%%%%%%%%%%%
1369
+
1370
+
1371
+function [] = clear_all()
1372
+
1373
+Handle = findobj(gcbf,'Enable','off');
1374
+set(Handle,'Enable','on');
1375
+Handle = findobj(gcbf,'Tag','Radiobutton1');
1376
+set(Handle,'Value',0);
1377
+Handle = findobj(gcbf,'Tag','StaticText10');
1378
+set(Handle,'String','Status <no action>');
1379
+Handle = findobj(gcbf,'Tag','StaticText3');
1380
+set(Handle,'String','Map: <empty>');
1381
+Handle = findobj(gcbf,'Tag','StaticText4');
1382
+set(Handle,'String','Data: <empty>');
1383
+Handle = findobj(gcbf,'Tag','StaticText20');
1384
+set(Handle,'String','lattice:');
1385
+Handle = findobj(gcbf,'Tag','StaticText11');
1386
+set(Handle,'String','neigh:');
1387
+Handle = findobj(gcbf,'Tag','StaticText16');
1388
+set(Handle,'String','training length:');
1389
+Handle = findobj(gcbf,'Tag','StaticText23');
1390
+set(Handle,'String','training length:');
1391
+Handle = findobj(gcbf,'Tag','StaticText17');
1392
+set(Handle,'String','radius initial:');
1393
+Handle = findobj(gcbf,'Tag','StaticText24');
1394
+set(Handle,'String','radius initial:');
1395
+Handle = findobj(gcbf,'Tag','StaticText5');
1396
+set(Handle,'String','map size:');
1397
+Handle = findobj(gcbf,'Tag','StaticText21');
1398
+set(Handle,'String','shape:');
1399
+Handle = findobj(gcbf,'Tag','StaticText12');
1400
+set(Handle,'String','order:');
1401
+set(Handle,'Visible','off');
1402
+Handle = findobj(gcbf,'Tag','StaticText14');
1403
+set(Handle,'String','length type:');
1404
+set(Handle,'Visible','off');
1405
+Handle = findobj(gcbf,'Tag','StaticText22');
1406
+set(Handle,'String','radius final:');
1407
+Handle = findobj(gcbf,'Tag','StaticText25');
1408
+set(Handle,'String','radius final:');
1409
+Handle = findobj(gcbf,'Tag','StaticText19');
1410
+set(Handle,'String','tracking:');
1411
+Handle = findobj(gcbf,'Tag','StaticText7');
1412
+set(Handle,'String','Initialization');
1413
+Handle = findobj(gcbf,'Tag','StaticText28');
1414
+set(Handle,'String','alpha type:');
1415
+set(Handle,'Visible','off');
1416
+Handle = findobj(gcbf,'Tag','StaticText26');
1417
+set(Handle,'String','alpha initial:');
1418
+Handle = findobj(gcbf,'Tag','StaticText27');
1419
+set(Handle,'String','alpha initial:');
1420
+Handle = findobj(gcbf,'Tag','StaticText6');
1421
+set(Handle,'String','type:');
1422
+Handle = findobj(gcbf,'Tag','StaticText9');
1423
+set(Handle,'String','training type:');
1424
+Handle = findobj(gcbf,'Tag','Pushbutton9');
1425
+set(Handle,'Enable','off');
1426
+Handle = findobj(gcbf,'Tag','Pushbutton6');
1427
+set(Handle,'Enable','off');
1428
+Handle = findobj(gcbf,'Tag','Pushbutton4');
1429
+set(Handle,'Enable','off');
1430
+Handle = findobj(gcbf,'Tag','Pushbutton5');
1431
+set(Handle,'Enable','off');
1432
+Handle = findobj(gcbf,'Tag','Pushbutton2');
1433
+set(Handle,'Enable','on');
1434
+Handle = findobj(gcbf,'Tag','Radiobutton1');
1435
+set(Handle,'Enable','off');
1436
+Handle = findobj(gcbf,'Tag','Load/SaveSave mapuimenu1');
1437
+set(Handle,'Enable','off');
1438
+Handle = findobj(gcbf,'Tag','&Load/SaveSave mapSave in workspaceuimenu1');
1439
+set(Handle,'Enable','off');
1440
+Handle = findobj(gcbf,'Tag','Subuimenu2');
1441
+set(Handle,'Enable','off');
1442
+Handle = findobj(gcbf,'Tag','&ToolsSubuimenu1');
1443
+set(Handle,'Enable','off');
1444
+Handle = findobj(gcbf,'Tag','&Help/InfoHelp windowuimenu1');
1445
+set(Handle,'Enable','off');
1446
+Handle = findobj(gcbf,'Tag','&Help/InfoData infouimenu1');
1447
+set(Handle,'Enable','off');
1448
+Handle = findobj(gcbf,'Tag','&Init&Trainuimenu1');
1449
+set(Handle,'Enable','off');
1450
+Handle = findobj(gcbf,'Tag','&Init&TrainInitialize1');
1451
+set(Handle,'Enable','off');
1452
+Handle = findobj(gcbf,'Tag','&Init&TrainChange initialization valuesuimenu1');
1453
+set(Handle,'Enable','off');
1454
+Handle = findobj(gcbf,'Tag','&Init&TrainTrain1');
1455
+set(Handle,'Enable','off');
1456
+Handle = findobj(gcbf,'Tag','Load/SaveSubuimenu1');
1457
+set(Handle,'Enable','off');
1458
+Handle = findobj(gcbf,'String','alpha initial:');
1459
+set(Handle,'Visible','off');
1460
+clear;
1461
+clear global;
1462
+
1463
+
1464
+function [] = close_fig()
1465
+global MAPSAVED NEWMAP;
1466
+if isempty(MAPSAVED)
1467
+  if not(isempty(NEWMAP))
1468
+     quest = 'Save map before closing?';
1469
+     ButtonName = questdlg(quest);
1470
+     switch ButtonName
1471
+        case 'Yes'
1472
+	  som_gui('savemap');		
1473
+	  som_gui('clear');
1474
+	  clear global;
1475
+	  close(gcbf);
1476
+	 case 'No'
1477
+	   som_gui('clear');	
1478
+	   clear global;
1479
+	   close(gcbf);
1480
+	 case 'Cancel'
1481
+      end
1482
+  else
1483
+     som_gui('clear');
1484
+     clear global;
1485
+     close(gcbf);	
1486
+  end	
1487
+else
1488
+  som_gui('clear');
1489
+  clear global;
1490
+  close(gcbf);
1491
+end
1492
+
1493
+
1494
+function [] = preprocess_gui()
1495
+global DATA; 
1496
+if isempty(DATA)
1497
+   helpmsg = {'Load data before tryinig to preprocess!'};
1498
+   helpdlg(helpmsg,'Empty Data!');
1499
+   return;
1500
+end
1501
+preprocess(DATA);
1502
+waitfor(gcf);
1503
+prompt = {'Name of preprocessed data in workspace?'};
1504
+tittle = 'Reload preprocessed data!';
1505
+lineNo = 1;
1506
+def = {DATA.name};
1507
+answer = inputdlg(prompt,tittle,lineNo,def);
1508
+if isempty(answer)
1509
+  return;
1510
+end
1511
+data = answer{1};
1512
+new_name = retname;
1513
+assignin('base',new_name,data);
1514
+str = ['exist(' new_name ')'];	
1515
+temp = evalin('base',str); 
1516
+if temp ~= 1
1517
+ temp = strcat('Variable ''',data,''' doesn''t exist in workspace.',...
1518
+	'Old Data which is not preprocessed will be used.');
1519
+  errordlg(temp,'Unknown variable!');
1520
+  return;
1521
+end
1522
+evalin('base',['clear ' new_name ]) 
1523
+Handle = findobj(gcf,'Tag','StaticText4');
1524
+temp = strcat('Data: <',data,'>');
1525
+set(Handle,'String',temp);
1526
+Handle = findobj(gcf,'Tag','StaticText10');
1527
+set(Handle,'String','Status <data preprocessed>');
1528
+temp = evalin('base',data);
1529
+DATA.data = temp;
1530
+som_gui('def_initialization');
1531
+
1532
+
1533
+function [val] = loop(cell_data, search_data)
1534
+for val = 1: length(cell_data) 
1535
+  if strcmp(cell_data{val},search_data)
1536
+    break;
1537
+  end
1538
+end
1539
+if not(strcmp(cell_data{val},search_data))
1540
+  val = -1;
1541
+end
1542
+
1543
+
1544
+function [] = comp_names(names,fid)
1545
+last = size(names);
1546
+for index=1:last
1547
+	fprintf(fid,'%% %s\n',names{index})
1548
+end	
1549
+
1550
+function [] = fill_field(names,mask,fid)
1551
+last = size(mask);
1552
+for index=1:last
1553
+	num = num2str(mask(index))
1554
+	fprintf(fid,'%% %-15s %-2s\n',names{index},num)
1555
+end	
1556
+
1557
+
1558
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1559
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
1560
+%%%%%%%%%%%%%%%%%     END OF OTHER FUNC		%%%%%%%%%%%%%%%%%%%
1561
+%%%%%%%%%%%%%%%%%				%%%%%%%%%%%%%%%%%%%
1562
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%	
1563
+
1564
+
1565
+      
1566
+
1567
+function fig = main_gui()
1568
+
1569
+v = version;
1570
+ver_53_or_newer = (str2num(v(1:3)) >= 5.3);
1571
+
1572
+h0 = figure('Units','normalized', ...
1573
+	'Color',[0.85 0.85 0.85], ...
1574
+	'Name','SOM Toolbox -- Initialization & Training', ...
1575
+	'NumberTitle','off', ...
1576
+	'PaperPosition',[18 180 576 432], ...
1577
+	'PaperUnits','points', ...
1578
+	'Position',[0.3296875 0.28125 0.3828125 0.576171875], ...
1579
+	'Tag','Fig1'); 
1580
+if ver_53_or_newer, set(h0,'ToolBar','none'); end
1581
+
1582
+h1 = uimenu('Parent',h0, ...
1583
+	'Label','&Load/Save', ...
1584
+	'Tag','uimenu1');
1585
+h2 = uimenu('Parent',h1, ...
1586
+	'Callback','som_gui(''load_data'');',...
1587
+	'Label','Load Data', ...
1588
+	'Tag','Subuimenu1');
1589
+h2 = uimenu('Parent',h1, ...
1590
+	'Label','Save map', ...
1591
+	'Enable','off',...
1592
+	'Tag','Load/SaveSubuimenu1');
1593
+h3 = uimenu('Parent',h2, ...
1594
+	'Callback','som_gui(''save_workspace'');', ...
1595
+	'Enable','off', ...
1596
+	'Label','Save in workspace', ...
1597
+	'Tag','Load/SaveSave mapuimenu1');
1598
+h3 = uimenu('Parent',h2, ...
1599
+	'Callback','som_gui(''savemap'');', ...
1600
+	'Enable','off', ...
1601
+	'Label','Write cod-file', ...
1602
+	'Tag','&Load/SaveSave mapSave in workspaceuimenu1');
1603
+h1 = uimenu('Parent',h0, ...
1604
+	'Label','&Utilities', ...
1605
+	'Tag','uimenu2');
1606
+h2 = uimenu('Parent',h1, ...
1607
+	'Callback','som_gui(''preprocess'');', ...
1608
+	'Enable','off', ...
1609
+	'Label','Preprocess Data', ...
1610
+	'Tag','Subuimenu2');
1611
+h2 = uimenu('Parent',h1, ...
1612
+	'Callback','som_gui(''visualize'');', ...
1613
+	'Enable','off', ...
1614
+	'Label','Visualize Map', ...
1615
+	'Tag','&ToolsSubuimenu1');
1616
+h2 = uimenu('Parent',h1, ...
1617
+	'Callback','som_gui(''clear_all'');', ...
1618
+	'Label','Clear all', ...
1619
+	'Tag','&ToolsSubuimenu2');
1620
+h2 = uimenu('Parent',h1, ...
1621
+	'Callback','som_gui(''close'');', ...
1622
+	'Label','Close Figure', ...
1623
+	'Tag','&ToolsClear alluimenu1');
1624
+h1 = uimenu('Parent',h0, ...
1625
+	'Label','&Info', ...
1626
+	'Tag','&ToolsClose Figureuimenu1');
1627
+h2 = uimenu('Parent',h1, ...
1628
+	'Callback','som_gui(''help'');', ...
1629
+	'Label','WWW Help', ...
1630
+	'Tag','Helpuimenu1');
1631
+h2 = uimenu('Parent',h1, ...
1632
+	'Callback','som_gui(''helpwin'');', ...
1633
+	'Label','Help window', ...
1634
+	'Tag','Helpuimenu2');
1635
+h2 = uimenu('Parent',h1, ...
1636
+	'Callback','som_gui(''helpwin2'');', ...
1637
+	'Label','About GUI', ...
1638
+	'Tag','&Help/InfoHelp windowuimenu2');
1639
+h2 = uimenu('Parent',h1, ...
1640
+	'Callback','som_gui(''data_info'');', ...
1641
+	'Enable','off', ...
1642
+	'Label','Data info', ...
1643
+	'Tag','&Help/InfoHelp windowuimenu1');
1644
+h2 = uimenu('Parent',h1, ...
1645
+	'Callback','som_gui(''map_info'');', ...
1646
+	'Enable','off', ...
1647
+	'Label','Map info', ...
1648
+	'Tag','&Help/InfoData infouimenu1');
1649
+h1 = uimenu('Parent',h0, ...
1650
+	'Label','&Init/Train', ...
1651
+	'Tag','&Init/Train1');
1652
+h2 = uimenu('Parent',h1, ...
1653
+	'Callback','som_gui(''change_initialization'');', ...
1654
+	'Enable','off', ...
1655
+	'Label','Change initialization values', ...
1656
+	'Tag','&Init&Trainuimenu1');
1657
+h2 = uimenu('Parent',h1, ...
1658
+	'Callback','som_gui(''init'');', ...
1659
+	'Enable','off', ...
1660
+	'Label','Initialize', ...
1661
+	'Tag','&Init&TrainInitialize1');
1662
+h2 = uimenu('Parent',h1, ...
1663
+	'Callback','som_gui(''change_def'');', ...
1664
+	'Enable','off', ...
1665
+	'Label','Change training values', ...
1666
+	'Tag','&Init&TrainChange initialization valuesuimenu1');
1667
+h2 = uimenu('Parent',h1, ...
1668
+	'Callback','som_gui(''def_train'');', ...
1669
+	'Enable','off', ...
1670
+	'Label','Train', ...
1671
+	'Tag','&Init&TrainTrain1');
1672
+h1 = uicontrol('Parent',h0, ...
1673
+	'Units','normalized', ...
1674
+	'ListboxTop',0, ...
1675
+	'Position',[0.04081632653061224 0.01129943502824859 0.7619047619047619 0.9717514124293786], ...
1676
+	'Style','frame', ...
1677
+	'Tag','Frame1');
1678
+h1 = uicontrol('Parent',h0, ...
1679
+	'Units','normalized', ...
1680
+	'ListboxTop',0, ...
1681
+	'Position',[0.06802721088435373 0.7909604519774012 0.7074829931972788 0.1807909604519774], ...
1682
+	'Style','frame', ...
1683
+	'Tag','Frame2');
1684
+h1 = uicontrol('Parent',h0, ...
1685
+	'Units','normalized', ...
1686
+	'BackgroundColor',[0.9 0.9 0.9], ...
1687
+	'HorizontalAlignment','left', ...
1688
+	'ListboxTop',0, ...
1689
+	'Position',[0.09523809523809523 0.8527570621468927 0.6530612244897959 0.03389830508474576], ...
1690
+        'FontUnits','normalized',...
1691
+	'String','Map <empty>', ...
1692
+	'Style','text', ...
1693
+	'Tag','StaticText3');
1694
+h1 = uicontrol('Parent',h0, ...
1695
+	'Units','normalized', ...
1696
+	'BackgroundColor',[0.9 0.9 0.9], ...
1697
+	'HorizontalAlignment','left', ...
1698
+	'ListboxTop',0, ...
1699
+	'Position',[0.09523809523809523 0.8075593220338984 0.6530612244897959 0.03389830508474576], ...
1700
+	'String','Data <empty>', ...
1701
+        'FontUnits','normalized',...	       
1702
+	'Style','text', ...
1703
+	'Tag','StaticText4');
1704
+h1 = uicontrol('Parent',h0, ...
1705
+	'Units','normalized', ...
1706
+	'ListboxTop',0, ...
1707
+	'Position',[0.06802721088435373 0.5988700564971752 0.7074829931972788 0.1694915254237288], ...
1708
+	'Style','frame', ...
1709
+	'Tag','Frame3');
1710
+h1 = uicontrol('Parent',h0, ...
1711
+	'Units','normalized', ...
1712
+	'ListboxTop',0, ...
1713
+	'Position',[0.1041 0.7356 0.6286 0.0271], ...
1714
+	'String','Initialization', ...
1715
+        'FontUnits','normalized',...	       
1716
+	'Style','text', ...
1717
+	'FontWeight','bold', ...
1718
+	'Tag','StaticText7');
1719
+h1 = uicontrol('Parent',h0, ...
1720
+	'Units','normalized', ...
1721
+	'BackgroundColor',[0.9 0.9 0.9], ...
1722
+	'HorizontalAlignment','left', ...
1723
+	'ListboxTop',0, ...
1724
+	'Position',[0.4489795918367346 0.7005649717514124 0.2993197278911565 0.03389830508474576], ...
1725
+	'String','map size:', ...
1726
+        'FontUnits','normalized',...	       
1727
+	'Style','text', ...
1728
+	'Tag','StaticText5');
1729
+h1 = uicontrol('Parent',h0, ...
1730
+	'Units','normalized', ...
1731
+	'BackgroundColor',[0.9 0.9 0.9], ...
1732
+	'HorizontalAlignment','left', ...
1733
+	'ListboxTop',0, ...
1734
+	'Position',[0.09523809523809523 0.6553672316384182 0.2993197278911565 0.03389830508474576], ...
1735
+	'String','lattice:', ...
1736
+        'FontUnits','normalized',...	       
1737
+	'Style','text', ...
1738
+	'Tag','StaticText20');
1739
+h1 = uicontrol('Parent',h0, ...
1740
+	'Units','normalized', ...
1741
+	'BackgroundColor',[0.9 0.9 0.9], ...
1742
+	'HorizontalAlignment','left', ...
1743
+	'ListboxTop',0, ...
1744
+	'Position',[0.09523809523809523 0.7000000000000001 0.2993197278911565 0.03389830508474576], ...
1745
+	'String','type:', ...
1746
+   'FontUnits','normalized',...	       
1747
+	'Style','text', ...
1748
+	'Tag','StaticText6');
1749
+h1 = uicontrol('Parent',h0, ...
1750
+	'Units','normalized', ...
1751
+	'BackgroundColor',[0.9 0.9 0.9], ...
1752
+	'HorizontalAlignment','left', ...
1753
+	'ListboxTop',0, ...
1754
+	'Position',[0.4489795918367346 0.6553672316384182 0.2993197278911565 0.03389830508474576], ...
1755
+	'String','shape:', ...
1756
+        'FontUnits','normalized',...	       
1757
+	'Style','text', ...
1758
+	'Tag','StaticText21');
1759
+h1 = uicontrol('Parent',h0, ...
1760
+	'Units','normalized', ...
1761
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
1762
+	'ListboxTop',0, ...
1763
+	'Position',[0.3129251700680272 0.6101694915254238 0.217687074829932 0.03389830508474576], ...
1764
+	'String','Change values', ...
1765
+        'FontUnits','normalized',...	       
1766
+	'Callback','som_gui(''change_initialization'');', ...
1767
+	'Enable','off', ...
1768
+	'Tag','Pushbutton9');
1769
+h1 = uicontrol('Parent',h0, ...
1770
+	'Units','normalized', ...
1771
+	'ListboxTop',0, ...
1772
+	'Position',[0.06802721088435373 0.02259887005649718 0.7074829931972788 0.5536723163841808], ...
1773
+	'Style','frame', ...
1774
+	'Tag','Frame4');
1775
+h1 = uicontrol('Parent',h0, ...
1776
+	'Units','normalized', ...
1777
+	'ListboxTop',0, ...
1778
+	'Position',[0.1041 0.5316 0.6429 0.0339], ...
1779
+	'String','Training', ...
1780
+   'FontUnits','normalized',...	       
1781
+	'Style','text', ...
1782
+	'FontWeight','bold', ...
1783
+	'Tag','StaticText8');
1784
+h1 = uicontrol('Parent',h0, ...
1785
+	'Units','normalized', ...
1786
+	'BackgroundColor',[0.9 0.9 0.9], ...
1787
+	'ListboxTop',0, ...
1788
+	'Position',[0.09523809523809523 0.4971751412429379 0.6530612244897959 0.03389830508474576], ...
1789
+	'String','training type', ...
1790
+        'FontUnits','normalized',...	       
1791
+	'Style','text', ...
1792
+	'Tag','StaticText9');
1793
+h1 = uicontrol('Parent',h0, ...
1794
+	'Units','normalized', ...
1795
+	'BackgroundColor',[0.9 0.9 0.9], ...
1796
+	'HorizontalAlignment','left', ...
1797
+	'ListboxTop',0, ...
1798
+	'Position',[0.4489795918367346 0.4519774011299435 0.2993197278911565 0.03389830508474576], ...
1799
+	'String','tracking:', ...
1800
+        'FontUnits','normalized',...	       
1801
+	'Style','text', ...
1802
+	'Tag','StaticText19');
1803
+h1 = uicontrol('Parent',h0, ...
1804
+	'Units','normalized', ...
1805
+	'BackgroundColor',[0.9 0.9 0.9], ...
1806
+	'HorizontalAlignment','left', ...
1807
+	'ListboxTop',0, ...
1808
+	'Position',[0.09523809523809523 0.4519774011299435 0.2993197278911565 0.03389830508474576], ...
1809
+	'String','neigh:', ...
1810
+        'FontUnits','normalized',...	       
1811
+	'Style','text', ...
1812
+	'Tag','StaticText11');
1813
+h1 = uicontrol('Parent',h0, ...
1814
+	'Units','normalized', ...
1815
+	'HorizontalAlignment','left', ...	       
1816
+	'BackgroundColor',[0.9 0.9 0.9], ...
1817
+	'ListboxTop',0, ...
1818
+	'Position',[0.09523809523809523 0.36519774011299435 0.2993197278911565 0.03389830508474576], ...	       
1819
+	'String','alpha type:', ...
1820
+        'FontUnits','normalized',...	       
1821
+	'Style','text', ...
1822
+	'Visible','off',...
1823
+	'Tag','StaticText28');
1824
+h1 = uicontrol('Parent',h0, ...
1825
+	'Units','normalized', ...
1826
+	'BackgroundColor',[0.9 0.9 0.9], ...
1827
+	'ListboxTop',0, ...
1828
+	'HorizontalAlignment','left', ...	       
1829
+	'Position',[0.09523809523809523 0.4067796610169492 0.2993197278911565 0.03389830508474576], ...	       
1830
+	'String','length type:', ...
1831
+        'FontUnits','normalized',...	       
1832
+	'Style','text', ...
1833
+	'Visible','off',...
1834
+	'Tag','StaticText14');
1835
+h1 = uicontrol('Parent',h0, ...
1836
+	'Units','normalized', ...
1837
+	'BackgroundColor',[0.9 0.9 0.9], ...
1838
+	'HorizontalAlignment','left', ...
1839
+	'ListboxTop',0, ...
1840
+	'Position',[0.4489795918367346 0.4067796610169492 0.2993197278911565 0.03389830508474576], ...
1841
+	'String','order:', ...
1842
+        'FontUnits','normalized',...	       
1843
+	'Style','text', ...
1844
+	'Visible','off',...
1845
+	'Tag','StaticText12');
1846
+h1 = uicontrol('Parent',h0, ...
1847
+	'Units','normalized', ...
1848
+	'ListboxTop',0, ...
1849
+	'Position',[0.09523809523809523 0.07909604519774012 0.2993197278911565 0.2711864406779661], ...
1850
+	'Style','frame', ...
1851
+	'Tag','Frame5');
1852
+h1 = uicontrol('Parent',h0, ...
1853
+	'Units','normalized', ...
1854
+	'ListboxTop',0, ...
1855
+	'Position',[0.4353741496598639 0.07909604519774012 0.2993197278911565 0.2711864406779661], ...
1856
+	'Style','frame', ...
1857
+	'Tag','Frame6');
1858
+h1 = uicontrol('Parent',h0, ...
1859
+	'Units','normalized', ...
1860
+	'ListboxTop',0, ...
1861
+	'Position',[0.108843537414966 0.3050847457627119 0.2721088435374149 0.03389830508474576], ...
1862
+	'String','Rough', ...
1863
+        'FontUnits','normalized',...	       
1864
+	'Style','text', ...
1865
+	'Tag','StaticText13');
1866
+h1 = uicontrol('Parent',h0, ...
1867
+	'Units','normalized', ...
1868
+	'ListboxTop',0, ...
1869
+	'Position',[0.4489795918367346 0.3050847457627119 0.2721088435374149 0.03389830508474576], ...
1870
+	'String','Finetune', ...
1871
+        'FontUnits','normalized',...	       
1872
+	'Style','text', ...
1873
+	'Tag','StaticText15');
1874
+h1 = uicontrol('Parent',h0, ...
1875
+	'Units','normalized', ...
1876
+	'BackgroundColor',[0.9 0.9 0.9], ...
1877
+	'HorizontalAlignment','left', ...
1878
+	'ListboxTop',0, ...
1879
+	'Position',[0.108843537414966 0.1807909604519774 0.2721088435374149 0.03389830508474576], ...
1880
+	'String','training length:', ...
1881
+        'FontUnits','normalized',...	       
1882
+	'Style','text', ...
1883
+	'Tag','StaticText16');
1884
+h1 = uicontrol('Parent',h0, ...
1885
+	'Units','normalized', ...
1886
+	'BackgroundColor',[0.9 0.9 0.9], ...
1887
+	'HorizontalAlignment','left', ...
1888
+	'ListboxTop',0, ...
1889
+	'Position',[0.108843537414966 0.2694915254237288 0.2714285714285714 0.03389830508474576], ...
1890
+	'String','radius initial:', ...
1891
+        'FontUnits','normalized',...	       
1892
+	'Style','text', ...
1893
+	'Tag','StaticText17');
1894
+h1 = uicontrol('Parent',h0, ...
1895
+	'Units','normalized', ...
1896
+	'BackgroundColor',[0.9 0.9 0.9], ...
1897
+	'HorizontalAlignment','left', ...
1898
+	'ListboxTop',0, ...
1899
+	'Position',[0.1088 0.2260 0.2721 0.0339], ...
1900
+	'String','radius final:', ...
1901
+        'FontUnits','normalized',...	       
1902
+	'Style','text', ...
1903
+	'Tag','StaticText22');
1904
+h1 = uicontrol('Parent',h0, ...
1905
+	'Units','normalized', ...
1906
+	'BackgroundColor',[0.9 0.9 0.9], ...
1907
+	'ListboxTop',0, ...
1908
+	'Position',[0.108843537414966 0.13694915254237288 0.2714285714285714 0.03389830508474576], ...	       
1909
+	'String','alpha initial:', ...
1910
+        'FontUnits','normalized',...	       
1911
+	'HorizontalAlignment','left', ...	       
1912
+	'Style','text', ...
1913
+	'Visible','off',...
1914
+	'Tag','StaticText26');
1915
+h1 = uicontrol('Parent',h0, ...
1916
+	'Units','normalized', ...
1917
+	'BackgroundColor',[0.9 0.9 0.9], ...
1918
+	'HorizontalAlignment','left', ...
1919
+	'ListboxTop',0, ...
1920
+	'Position',[0.4489795918367346 0.1807909604519774 0.2721088435374149 0.03389830508474576], ...
1921
+	'String','training length:', ...
1922
+        'FontUnits','normalized',...	       
1923
+	'Style','text', ...
1924
+	'Tag','StaticText23');
1925
+h1 = uicontrol('Parent',h0, ...
1926
+	'Units','normalized', ...
1927
+	'BackgroundColor',[0.9 0.9 0.9], ...
1928
+	'HorizontalAlignment','left', ...
1929
+	'ListboxTop',0, ...
1930
+	'Position',[0.4489795918367346 0.2711864406779661 0.2721088435374149 0.03389830508474576], ...
1931
+	'String','radius initial:', ...
1932
+        'FontUnits','normalized',...	       
1933
+	'Style','text', ...
1934
+	'Tag','StaticText24');
1935
+h1 = uicontrol('Parent',h0, ...
1936
+	'Units','normalized', ...
1937
+	'BackgroundColor',[0.9 0.9 0.9], ...
1938
+	'HorizontalAlignment','left', ...
1939
+	'ListboxTop',0, ...
1940
+	'Position',[0.4490 0.2260 0.2721 0.0339], ...
1941
+	'String','radius final:', ...
1942
+        'FontUnits','normalized',...	       
1943
+	'Style','text', ...
1944
+	'Tag','StaticText25');
1945
+h1 = uicontrol('Parent',h0, ...
1946
+	'Units','normalized', ...
1947
+	'BackgroundColor',[0.9 0.9 0.9], ...
1948
+	'ListboxTop',0, ...
1949
+	'Position',[0.4489795918367346  0.13694915254237288 0.2721088435374149 0.03389830508474576], ...	       
1950
+	'String','alpha initial:', ...
1951
+        'FontUnits','normalized',...	       
1952
+	'HorizontalAlignment','left', ...	       
1953
+	'Style','text', ...
1954
+	'Visible','off',...
1955
+	'Tag','StaticText27');
1956
+h1 = uicontrol('Parent',h0, ...
1957
+	'Units','normalized', ...
1958
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
1959
+	'ListboxTop',0, ...
1960
+	'Position',[0.3129251700680272 0.03389830508474576 0.217687074829932 0.03389830508474576], ...
1961
+	'String','Change values', ...
1962
+        'FontUnits','normalized',...	       
1963
+	'Callback','som_gui(''change_def'');', ...
1964
+	'Enable','off', ...
1965
+	'Tag','Pushbutton6');
1966
+if ver_53_or_newer, set(h1,'TooltipString','Change default values in training.'); end
1967
+
1968
+h1 = uicontrol('Parent',h0, ...
1969
+	'Units','normalized', ...
1970
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
1971
+	'ListboxTop',0, ...
1972
+	'Position',[0.8163265306122448 0.8152542372881356 0.163265306122449 0.05593220338983051], ...
1973
+	'String','LOAD', ...
1974
+        'FontUnits','normalized',...	       
1975
+	'Callback','som_gui(''load_data'');', ...
1976
+	'Tag','Pushbutton2');
1977
+if ver_53_or_newer, set(h1,'TooltipString','Load data file.'); end
1978
+
1979
+h1 = uicontrol('Parent',h0, ...
1980
+	'Units','normalized', ...
1981
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
1982
+	'ListboxTop',0, ...
1983
+	'Position',[0.8163265306122448 0.6457627118644068 0.163265306122449 0.05593220338983051], ...
1984
+	'String','INITIALIZE', ...
1985
+        'FontUnits','normalized',...	       
1986
+	'Callback','som_gui(''init'');', ...
1987
+	'Enable','off', ...
1988
+	'Tag','Pushbutton4');
1989
+if ver_53_or_newer, set(h1,'TooltipString','Initialize map.'); end
1990
+
1991
+h1 = uicontrol('Parent',h0, ...
1992
+	'Units','normalized', ...
1993
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
1994
+	'ListboxTop',0, ...
1995
+	'Position',[0.8163265306122448 0.384180790960452 0.163265306122449 0.05649717514124294], ...
1996
+	'String','TRAIN', ...
1997
+        'FontUnits','normalized',...	       
1998
+	'Callback','som_gui(''def_train'');', ...
1999
+	'Enable','off', ...
2000
+	'Tag','Pushbutton5');
2001
+if ver_53_or_newer, set(h1,'TooltipString','Train map whit default values.'); end
2002
+
2003
+h1 = uicontrol('Parent',h0, ...
2004
+	'Units','normalized', ...
2005
+	'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
2006
+	'ListboxTop',0, ...
2007
+	'Position',[0.8163265306122448 0.06779661016949153 0.163265306122449 0.05649717514124294], ...
2008
+	'Callback','som_gui(''close'');', ...
2009
+	'String','CLOSE', ...
2010
+        'FontUnits','normalized',...	       
2011
+	'Tag','Pushbutton8');
2012
+if ver_53_or_newer, set(h1,'TooltipString','Close figure.'); end
2013
+
2014
+h1 = uicontrol('Parent',h0, ...
2015
+	'Units','normalized', ...
2016
+	'BackgroundColor',[0.9 0.9 0.9], ...
2017
+	'HorizontalAlignment','left', ...
2018
+	'ListboxTop',0, ...
2019
+	'Position',[0.09387755102040815 0.897954802259887 0.6530612244897959 0.03389830508474576], ...
2020
+	'String','Status <no action>', ...
2021
+        'FontUnits','normalized',...	       
2022
+	'Style','text', ...
2023
+	'Tag','StaticText10');
2024
+h1 = uicontrol('Parent',h0, ...
2025
+	'Units','normalized', ...
2026
+	'ListboxTop',0, ...
2027
+	'Position',[0.108843537414966 0.0903954802259887 0.2721088435374149 0.03389830508474576], ...
2028
+	'String','Only finetune', ...
2029
+        'FontUnits','normalized',...	       
2030
+	'Callback','som_gui(''only_finetune'');', ...
2031
+	'Enable','off', ...
2032
+	'Style','radiobutton', ...
2033
+	'Tag','Radiobutton1');
2034
+h1 = uicontrol('Parent',h0, ...
2035
+	'Units','normalized', ...
2036
+	'ListboxTop',0, ...
2037
+	'Position',[0.09523809523809523 0.9418531073446328 0.6530612244897959 0.0259887005649718], ...
2038
+   'String','Information', ...
2039
+   'FontUnits','normalized',...
2040
+	'FontWeight','bold', ...
2041
+	'Style','text', ...
2042
+	'Tag','StaticText18');
2043
+if nargout > 0, fig = h0; end
2044
+
2045
+
2046
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2047
+
2048
+
2049
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2050
+
2051
+function fig = loadgui3()
2052
+
2053
+temp = {'dat file';'mat file'};
2054
+
2055
+h0 = figure('Units','normalized', ...
2056
+        'Color',[0.8 0.8 0.8], ...
2057
+	'Name','Load data!', ...
2058
+	'NumberTitle','off', ...
2059
+	'PaperType','a4letter', ...
2060
+	'Position',[0.3828125 0.5 0.3421875 0.189453125], ...
2061
+	'Tag','Fig1');
2062
+
2063
+h1 = uicontrol('Parent',h0, ...
2064
+	'Units','normalized', ...
2065
+	'ListboxTop',0, ...
2066
+	'Position',[0.02853881278538813 0.06443298969072164 0.7705479452054794 0.8698453608247422], ...
2067
+	'Style','frame', ...
2068
+	'Tag','Frame1');
2069
+h1 = uicontrol('Parent',h0, ...
2070
+	'Units','normalized', ...
2071
+	'ListboxTop',0, ...
2072
+	'Position',[0.04337899543378995 0.547680412371134 0.7420091324200913 0.354381443298969], ...
2073
+	'Style','frame', ...
2074
+	'Tag','Frame2');
2075
+h1 = uicontrol('Parent',h0, ...
2076
+	'Units','normalized', ...
2077
+	'ListboxTop',0, ...
2078
+	'Position',[0.04280821917808219 0.09664948453608246 0.7420091324200913 0.4188144329896907], ...
2079
+	'Style','frame', ...
2080
+	'Tag','Frame3');
2081
+h1 = uicontrol('Parent',h0, ...
2082
+	'Units','normalized', ...
2083
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2084
+	'FontWeight','bold', ...
2085
+	'HorizontalAlignment','left', ...
2086
+	'ListboxTop',0, ...
2087
+	'Position',[0.05717762557077625 0.7881958762886597 0.2853881278538812 0.09664948453608246], ...
2088
+	'String','From', ...
2089
+        'FontUnits','normalized',...	       
2090
+	'Style','text', ...
2091
+	'Tag','StaticText1');
2092
+h1 = uicontrol('Parent',h0, ...
2093
+	'Units','normalized', ...
2094
+	'Callback','som_gui(''workspace'');', ...
2095
+	'ListboxTop',0, ...
2096
+	'Position',[0.05107762557077625 0.7087628865979381 0.1997716894977169 0.09664948453608246], ...	       	       
2097
+	'String','Ws', ...
2098
+   'FontUnits','normalized',...	       
2099
+	'Style','radiobutton', ...
2100
+	'Tag','Radiobutton2');
2101
+h1 = uicontrol('Parent',h0, ...
2102
+	'Units','normalized', ...
2103
+	'Callback','som_gui(''file'');', ...
2104
+	'ListboxTop',0, ...
2105
+	'Position',[0.05107762557077625 0.5773195876288659 0.2009132420091324 0.09793814432989689], ...
2106
+	'String','File', ...
2107
+        'FontUnits','normalized',...	       
2108
+	'Style','radiobutton', ...
2109
+	'Tag','Radiobutton1');
2110
+h1 = uicontrol('Parent',h0, ...
2111
+	'Units','normalized', ...
2112
+	'BackgroundColor',[1 1 1], ...
2113
+	'Callback','Handle = findobj(gcbf,''Tag'',''EditText2'');set(Handle,''String'','''');',...
2114
+        'FontUnits','normalized',...
2115
+	'HorizontalAlignment','left', ...
2116
+	'ListboxTop',0, ...
2117
+	'Position',[0.2893881278538812 0.7087628865979381 0.3139269406392694 0.09664948453608246], ...	       
2118
+	'Style','edit', ...
2119
+	'Tag','EditText1');
2120
+h1 = uicontrol('Parent',h0, ...
2121
+	'Units','normalized', ...
2122
+	'BackgroundColor',[1 1 1], ...
2123
+	'Callback','Handle = findobj(gcbf,''Tag'',''EditText1'');set(Handle,''String'','''');',...
2124
+        'FontUnits','normalized',...	       
2125
+	'HorizontalAlignment','left', ...
2126
+	'ListboxTop',0, ...
2127
+	'Position',[0.2893881278538812 0.5798969072164948 0.3139269406392694 0.09664948453608246], ...	       
2128
+	'Style','edit', ...
2129
+	'Tag','EditText2');
2130
+h1 = uicontrol('Parent',h0, ...
2131
+	'Units','normalized', ...
2132
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2133
+	'Callback','som_gui(''browse'');', ...
2134
+	'ListboxTop',0, ...
2135
+	'Position',[0.6279 0.5799 0.1427 0.2255], ...
2136
+	'String','Browse', ...
2137
+        'FontUnits','normalized',...	       
2138
+	'Tag','Pushbutton1');
2139
+h1 = uicontrol('Parent',h0, ...
2140
+	'Units','normalized', ...
2141
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2142
+	'Callback','som_gui(''load_ok'');', ...
2143
+	'ListboxTop',0, ...
2144
+	'Position',[0.8276 0.5577 0.1427 0.2255], ...
2145
+	'String','Load', ...
2146
+        'FontUnits','normalized',...	       
2147
+	'Tag','Pushbutton2');
2148
+h1 = uicontrol('Parent',h0, ...
2149
+	'Units','normalized', ...
2150
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2151
+	'Callback','close;',...
2152
+	'ListboxTop',0, ...
2153
+	'Position',[0.8276 0.2577 0.1427 0.2255], ...
2154
+	'String','Cancel', ...
2155
+	'FontUnits','normalized',...       
2156
+	'Tag','Pushbutton3');
2157
+h1 = uicontrol('Parent',h0, ...
2158
+	'Units','normalized', ...
2159
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2160
+	'Callback','som_gui(''file_select'');', ...
2161
+	'ListboxTop',0, ...
2162
+	'Max',2, ...
2163
+	'Min',1, ...
2164
+	'String',temp,...
2165
+   'FontUnits','normalized',... 
2166
+	'Position',[0.3995433789954338 0.2977319587628866 0.1997716894977169 0.08664948453608246], ...	       
2167
+	'Style','popupmenu', ...
2168
+	'Tag','PopupMenu1', ...
2169
+	'Value',1);
2170
+h1 = uicontrol('Parent',h0, ...
2171
+	'Units','normalized', ...
2172
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2173
+	'FontWeight','bold', ...
2174
+	'HorizontalAlignment','left', ...
2175
+	'ListboxTop',0, ...
2176
+	'Position',[0.05707762557077625 0.3865979381443299 0.7134703196347032 0.09664948453608246], ...
2177
+	'String','Parameters for file', ...
2178
+        'FontUnits','normalized',...
2179
+	'Style','text', ...
2180
+	'Tag','StaticText2');
2181
+h1 = uicontrol('Parent',h0, ...
2182
+	'Units','normalized', ...
2183
+	'HorizontalAlignment','left', ...
2184
+	'ListboxTop',0, ...
2185
+	'Position',[0.05707762557077625 0.2777319587628866 0.2568493150684931 0.09664948453608246], ...
2186
+	'String','File type ', ...
2187
+        'FontUnits','normalized',...	       
2188
+	'Style','text', ...
2189
+	'Tag','StaticText3');
2190
+h1 = uicontrol('Parent',h0, ...
2191
+	'Units','normalized', ...
2192
+	'ListboxTop',0, ...
2193
+	'Position',[0.05707762557077625 0.1288659793814433 0.2996575342465753 0.09664948453608246], ...
2194
+	'String','Missing value', ...
2195
+	'Style','checkbox', ...
2196
+        'FontUnits','normalized',...	       
2197
+	'Tag','Checkbox1');
2198
+h1 = uicontrol('Parent',h0, ...
2199
+	'Units','normalized', ...
2200
+	'BackgroundColor',[1 1 1], ...
2201
+	'Callback','som_gui(''missing'');',...
2202
+	'ListboxTop',0, ...
2203
+	'Position',[0.5136986301369862 0.1258659793814433 0.08561643835616438 0.10664948453608246], ...	       
2204
+	'String','x', ...
2205
+        'FontUnits','normalized',...	       
2206
+	'Style','edit', ...
2207
+	'Tag','EditText3');
2208
+if nargout > 0, fig = h0; end
2209
+
2210
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2211
+
2212
+
2213
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2214
+
2215
+
2216
+
2217
+
2218
+function fig = works()
2219
+
2220
+v = version;
2221
+ver_53_or_newer = (str2num(v(1:3)) >= 5.3);
2222
+
2223
+h0 = figure('Units','normalized', ...
2224
+	'Color',[0.8 0.8 0.8], ...
2225
+	'Name','Load from workspace!', ...
2226
+	'NumberTitle','off', ...
2227
+	'PaperPosition',[18 180 576 432], ...
2228
+	'PaperType','a4letter', ...
2229
+	'PaperUnits','points', ...
2230
+	'Position',[0.5390625 0.2490234375 0.203125 0.251953125], ...
2231
+	'Tag','Fig1');
2232
+if ver_53_or_newer, set(h0,'ToolBar','none'); end
2233
+
2234
+h1 = uicontrol('Parent',h0, ...
2235
+	'Units','normalized', ...
2236
+	'ListboxTop',0, ...
2237
+	'Position',[0.05384615384615385 0.1472868217054263 0.9076923076923078 0.8255813953488372], ...
2238
+	'Style','frame', ...
2239
+	'Tag','Frame1');
2240
+h1 = uicontrol('Parent',h0, ...
2241
+	'Units','normalized', ...
2242
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2243
+	'Callback','som_gui(''works_ok'');', ...
2244
+	'ListboxTop',0, ...
2245
+	'Position',[0.1077 0.0194 0.2885 0.1202], ...
2246
+	'String','OK', ...
2247
+        'FontUnits','normalized',...	       
2248
+	'Tag','Pushbutton1');
2249
+h1 = uicontrol('Parent',h0, ...
2250
+	'Units','normalized', ...
2251
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2252
+	'Callback','close;', ...
2253
+	'ListboxTop',0, ...
2254
+	'Position',[0.6115 0.0155 0.2885 0.1202], ...
2255
+	'String','Cancel', ...
2256
+        'FontUnits','normalized',...	       
2257
+	'Tag','Pushbutton2');
2258
+h1 = uicontrol('Parent',h0, ...
2259
+	'Units','normalized', ...
2260
+	'BackgroundColor',[1 1 1], ...
2261
+	'Position',[0.1192 0.1977 0.7692 0.6395], ...
2262
+	'String',' ', ...
2263
+        'FontUnits','normalized',...	       
2264
+	'Style','listbox', ...
2265
+	'Tag','Listbox1', ...
2266
+	'Value',1);
2267
+h1 = uicontrol('Parent',h0, ...
2268
+	'Units','normalized', ...
2269
+	'FontWeight','bold', ...
2270
+	'ListboxTop',0, ...
2271
+	'Position',[0.2115384615384616 0.8720930232558139 0.576923076923077 0.06976744186046512], ...
2272
+	'String','Your options', ...
2273
+        'FontUnits','normalized',...	       
2274
+	'Style','text', ...
2275
+	'Tag','StaticText1');
2276
+if nargout > 0, fig = h0; end
2277
+
2278
+
2279
+
2280
+
2281
+
2282
+
2283
+function fig = initialization2()
2284
+
2285
+
2286
+temp1 = {'random';'linear'};
2287
+temp2 = {'hexa';'rect'};
2288
+temp3 = {'sheet';'cyl';'toroid'};
2289
+
2290
+
2291
+
2292
+% position bug in following corrected 1.12.04 KimmoR
2293
+h0 = figure('Units','normalized', ...
2294
+        'Color',[0.8 0.8 0.8], ...
2295
+	'Name','Change initialization parameters!', ...
2296
+	'NumberTitle','off', ...
2297
+	'PaperType','a4letter', ...
2298
+	'Position',[0.48828125 0.4267578125 0.3515625 0.146484375], ...
2299
+	'Tag','Fig1');
2300
+h1 = uicontrol('Parent',h0, ...
2301
+	'Units','normalized', ...
2302
+	'ListboxTop',0, ...
2303
+	'Position',[0.02777777777777778 0.08333333333333333 0.8055555555555556 0.8333333333333334], ...	       
2304
+	'Style','frame', ...
2305
+	'Tag','Frame1');
2306
+h1 = uicontrol('Parent',h0, ...
2307
+	'Units','normalized', ...
2308
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2309
+	'Callback','som_gui(''change_initialization_ok'');', ...
2310
+	'ListboxTop',0, ...
2311
+	'Position',[0.8472222222222222 0.55 0.125 0.25], ...
2312
+        'FontUnits','normalized',...	       
2313
+	'String','OK', ...
2314
+	'Tag','Pushbutton1');
2315
+h1 = uicontrol('Parent',h0, ...
2316
+	'Units','normalized', ...
2317
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2318
+	'Callback','som_gui(''change_initialization_cancel'');', ...
2319
+	'ListboxTop',0, ...
2320
+	'Position',[0.8472222222222222 0.25 0.125 0.25], ...	       
2321
+        'FontUnits','normalized',...
2322
+	'String','Cancel', ...
2323
+	'Tag','Pushbutton2');
2324
+h1 = uicontrol('Parent',h0, ...
2325
+	'Units','normalized', ...
2326
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2327
+	'FontWeight','bold', ...
2328
+	'HorizontalAlignment','left', ...
2329
+	'ListboxTop',0, ...
2330
+	'Position',[0.08333333333333334 0.6666666666666666 0.7066666666666667 0.1933333333333333], ...
2331
+	'String','Initialization parameters:', ...
2332
+        'FontUnits','normalized',...	       
2333
+	'Style','text', ...
2334
+	'Tag','StaticText1');
2335
+h1 = uicontrol('Parent',h0, ...
2336
+	'Units','normalized', ...
2337
+	'HorizontalAlignment','left', ...
2338
+	'ListboxTop',0, ...
2339
+	'Position',[0.0556 0.200 0.1667 0.1250],...       
2340
+	'String','type:', ...
2341
+        'FontUnits','normalized',...	       
2342
+	'Style','text', ...
2343
+	'Tag','StaticText2');
2344
+h1 = uicontrol('Parent',h0, ...
2345
+	'Units','normalized', ...
2346
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2347
+	'ListboxTop',0, ...
2348
+	'Max',2, ...
2349
+	'Min',1, ...
2350
+	'Position',[0.2500 0.200 0.1667 0.1250], ...
2351
+	'String',temp1, ...
2352
+        'FontUnits','normalized',...	       
2353
+	'Style','popupmenu', ...
2354
+	'Tag','PopupMenu1', ...
2355
+	'Value',1);
2356
+h1 = uicontrol('Parent',h0, ...
2357
+	'Units','normalized', ...
2358
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2359
+	'HorizontalAlignment','left', ...
2360
+	'ListboxTop',0, ...
2361
+	'Position',[0.05555555555555556 0.6 0.1666666666666667 0.125], ...
2362
+	'String','map size:', ...
2363
+        'FontUnits','normalized',...	       
2364
+	'Style','text', ...
2365
+	'Tag','StaticText2');
2366
+h1 = uicontrol('Parent',h0, ...
2367
+	'Units','normalized', ...
2368
+	'BackgroundColor',[1 1 1], ...
2369
+	'Callback','som_gui(''map_size'');', ...
2370
+	'HorizontalAlignment','left', ...
2371
+	'ListboxTop',0, ...
2372
+	'Position',[0.25 0.6 0.1666666666666667 0.125], ...
2373
+        'FontUnits','normalized',...	       
2374
+	'Style','edit', ...
2375
+	'Tag','EditText1');
2376
+h1 = uicontrol('Parent',h0, ...
2377
+	'Units','normalized', ...
2378
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2379
+	'HorizontalAlignment','left', ...
2380
+	'ListboxTop',0, ...
2381
+	'Position',[0.05555555555555556 0.4033333333333333 0.1666666666666667 0.125], ...
2382
+	'String','lattice:', ...
2383
+        'FontUnits','normalized',...	       
2384
+	'Style','text', ...
2385
+	'Tag','StaticText3');
2386
+h1 = uicontrol('Parent',h0, ...
2387
+	'Units','normalized', ...
2388
+	'ListboxTop',0, ...
2389
+	'Max',2, ...
2390
+	'Min',1, ...
2391
+	'Position',[0.25 0.4333333333333333 0.1666666666666667 0.125], ...
2392
+	'String',temp2, ...
2393
+        'FontUnits','normalized',...	       
2394
+	'Style','popupmenu', ...
2395
+	'Tag','PopupMenu2', ...
2396
+	'Value',2);
2397
+h1 = uicontrol('Parent',h0, ...
2398
+	'Units','normalized', ...
2399
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2400
+	'HorizontalAlignment','left', ...
2401
+	'ListboxTop',0, ...
2402
+	'Position',[0.4444444444444445 0.4033333333333333 0.1666666666666667 0.125], ...	       
2403
+	'String','shape:', ...
2404
+        'FontUnits','normalized',...	       
2405
+	'Style','text', ...
2406
+	'Tag','StaticText4');
2407
+h1 = uicontrol('Parent',h0, ...
2408
+	'Units','normalized', ...
2409
+	'ListboxTop',0, ...
2410
+	'Max',3, ...
2411
+	'Min',1, ...
2412
+	'Position',[0.638888888888889 0.4333333333333333 0.1666666666666667 0.125], ...	       
2413
+	'String',temp3, ...
2414
+        'FontUnits','normalized',...	       
2415
+	'Style','popupmenu', ...
2416
+	'Tag','PopupMenu3', ...
2417
+	'Value',2);
2418
+h1 = uicontrol('Parent',h0, ...
2419
+	'Units','normalized', ...
2420
+	'HorizontalAlignment','left', ...
2421
+	'ListboxTop',0, ...
2422
+	'Position',[0.4444444444444445 0.6 0.1666666666666667 0.125], ...
2423
+        'FontUnits','normalized',...
2424
+	'String','munits:', ...
2425
+	'Style','text', ...
2426
+	'Tag','StaticText5');	       
2427
+h1 = uicontrol('Parent',h0, ...
2428
+	'Units','normalized', ...
2429
+	'BackgroundColor',[1 1 1], ...
2430
+	'Callback','som_gui(''munits'');', ...
2431
+	'ListboxTop',0, ...
2432
+	'Position',[0.638888888888889 0.6 0.1666666666666667 0.125], ...
2433
+	'Style','edit', ...
2434
+        'FontUnits','normalized',...	       
2435
+	'Tag','EditText2');
2436
+if nargout > 0, fig = h0; end
2437
+
2438
+
2439
+
2440
+
2441
+
2442
+
2443
+
2444
+function fig = new_para2_2()
2445
+
2446
+temp1 = {'0';'1';'2';'3'};
2447
+temp2 = {'gaussian';'cutgauss';'ep';'bubble'};
2448
+temp3 = {'epochs';'samples'};
2449
+temp4 = {'random';'ordered'};
2450
+temp5 = {'inv';'linear';'power'};
2451
+
2452
+v = version;
2453
+ver_53_or_newer = (str2num(v(1:3)) >= 5.3);
2454
+
2455
+h0 = figure('Units','normalized', ...
2456
+	'Color',[0.8 0.8 0.8], ...
2457
+	'Name','Change training parameters!', ...
2458
+	'NumberTitle','off', ...
2459
+	'PaperPosition',[18 180 576 432], ...
2460
+	'PaperType','a4letter', ...
2461
+	'PaperUnits','points', ...
2462
+	'Position',[0.59140625 0.4560546875 0.3046875 0.4619140625], ...
2463
+	'Tag','Fig3');
2464
+if ver_53_or_newer, set(h0,'ToolBar','none'); end
2465
+h1 = uicontrol('Parent',h0, ...
2466
+	'Units','normalized', ...
2467
+	'ListboxTop',0, ...
2468
+	'Position',[0.02051282051282051 0.08456659619450317 0.9641025641025641 0.8921775898520086], ...
2469
+	'Style','frame', ...
2470
+	'Tag','Frame1');
2471
+h1 = uicontrol('Parent',h0, ...
2472
+	'Units','normalized', ...
2473
+	'ListboxTop',0, ...
2474
+	'Position',[0.5308 0.1374 0.4000 0.3742], ...
2475
+	'Style','frame', ...
2476
+	'Tag','Frame3');
2477
+h1 = uicontrol('Parent',h0, ...
2478
+	'Units','normalized', ...
2479
+	'ListboxTop',0, ...
2480
+	'Position',[0.08012820512820512 0.1416490486257928 0.4102564102564102 0.3699788583509514], ...
2481
+	'Style','frame', ...
2482
+	'Tag','Frame2');
2483
+h1 = uicontrol('Parent',h0, ...
2484
+	'Units','normalized', ...
2485
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2486
+	'Callback','close(gcbf);', ...
2487
+	'ListboxTop',0, ...
2488
+	'Position',[0.6410 0.0036 0.2897 0.0740], ...
2489
+        'FontUnits','normalized',...	       
2490
+	'String','Cancel', ...
2491
+	'Tag','Pushbutton2');
2492
+h1 = uicontrol('Parent',h0, ...
2493
+	'Units','normalized', ...
2494
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2495
+	'Callback','som_gui(''set_new_parameters'');', ...
2496
+	'ListboxTop',0, ...
2497
+	'Position',[0.1026 0.0036 0.2897 0.0740], ...
2498
+	'String','Set parameters', ...
2499
+        'FontUnits','normalized',...	       
2500
+	'Tag','Pushbutton1');
2501
+h1 = uicontrol('Parent',h0, ...
2502
+	'Units','normalized', ...
2503
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2504
+	'ListboxTop',0, ...
2505
+	'Max',4, ...
2506
+	'Min',1, ...
2507
+	'Position',[0.7051282051282051 0.6723044397463003 0.1923076923076923 0.040169133192389], ...
2508
+	'String',temp1, ...
2509
+        'FontUnits','normalized',...	       
2510
+	'Style','popupmenu', ...
2511
+	'Tag','PopupMenu2', ...
2512
+	'Value',1);
2513
+h1 = uicontrol('Parent',h0, ...
2514
+	'Units','normalized', ...
2515
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2516
+	'ListboxTop',0, ...
2517
+	'Max',4, ...
2518
+	'Min',1, ...
2519
+	'Position',[0.2948717948717949 0.6670190274841438 0.1923076923076923 0.03964059196617336], ...
2520
+	'String',temp2, ...
2521
+	'FontUnits','normalized',...       
2522
+	'Style','popupmenu', ...
2523
+	'Tag','PopupMenu1', ...
2524
+	'Value',1);
2525
+h1 = uicontrol('Parent',h0, ...
2526
+	'Units','normalized', ...
2527
+	'Callback','som_gui(''batch_cancel'');', ...
2528
+	'HorizontalAlignment','left', ...
2529
+	'ListboxTop',0, ...
2530
+	'Position',[0.5076923076923077 0.6575052854122622 0.1923076923076923 0.05285412262156448], ...
2531
+	'String','tracking', ...
2532
+        'FontUnits','normalized',...	       
2533
+	'Style','text', ...
2534
+	'Tag','StaticText6');
2535
+h1 = uicontrol('Parent',h0, ...
2536
+	'Units','normalized', ...
2537
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2538
+	'Callback','som_gui(''batch_cancel'');', ...
2539
+	'HorizontalAlignment','left', ...
2540
+	'ListboxTop',0, ...
2541
+	'Position',[0.09615384615384615 0.6553911205073996 0.1923076923076923 0.05285412262156448], ...
2542
+	'String','neigh.', ...
2543
+        'FontUnits','normalized',...	       
2544
+	'Style','text', ...
2545
+	'Tag','StaticText5');
2546
+h1 = uicontrol('Parent',h0, ...
2547
+	'Units','normalized', ...
2548
+	'HorizontalAlignment','left', ...
2549
+	'ListboxTop',0, ...
2550
+	'Position',[0.09615384615384615 0.7526427061310783 0.09487179487179487 0.04228329809725159], ...
2551
+	'String','mask:', ...
2552
+	'FontUnits','normalized',... 
2553
+	'Style','text', ...
2554
+	'Tag','StaticText2');
2555
+h1 = uicontrol('Parent',h0, ...
2556
+	'Units','normalized', ...
2557
+	'BackgroundColor',[1 1 1], ...
2558
+	'Position',[0.2948717948717949 0.7399577167019028 0.6025641025641025 0.07399577167019028], ...
2559
+	'String',' ', ...
2560
+	'FontUnits','normalized',...  
2561
+	'Style','listbox', ...
2562
+	'Tag','Listbox2', ...
2563
+	'Value',1);
2564
+h1 = uicontrol('Parent',h0, ...
2565
+	'Units','normalized', ...
2566
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2567
+	'HorizontalAlignment','left', ...
2568
+	'ListboxTop',0, ...
2569
+	'Position',[0.0962 0.8060 0.1154 0.0529], ...
2570
+        'FontUnits','normalized',...
2571
+	'String','Set', ...
2572
+	'Style','text', ...
2573
+	'Tag','StaticText3');
2574
+h1 = uicontrol('Parent',h0, ...
2575
+	'Units','normalized', ...
2576
+	'BackgroundColor',[1 1 1], ...
2577
+	'Callback','som_gui(''set_batch_mask'');', ...
2578
+	'Position',[0.2948717948717949 0.8165961945031712 0.3205128205128205 0.05285412262156448], ...
2579
+	'String',' ', ...
2580
+        'FontUnits','normalized',...	       
2581
+	'Style','listbox', ...
2582
+	'Tag','Listbox1', ...
2583
+	'Value',1);
2584
+h1 = uicontrol('Parent',h0, ...
2585
+	'Units','normalized', ...
2586
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2587
+	'HorizontalAlignment','left', ...
2588
+	'ListboxTop',0, ...
2589
+	'Position',[0.6250 0.8060 0.1603 0.0529], ...
2590
+	'String','to value', ...
2591
+        'FontUnits','normalized',...	       
2592
+	'Style','text', ...
2593
+	'Tag','StaticText4');
2594
+h1 = uicontrol('Parent',h0, ...
2595
+	'Units','normalized', ...
2596
+	'BackgroundColor',[1 1 1], ...
2597
+	'Callback','som_gui(''set_batch_mask'');', ...
2598
+	'ListboxTop',0, ...
2599
+	'Position',[0.7923076923076923 0.8181818181818182 0.09487179487179487 0.05285412262156448], ...
2600
+	'Style','edit', ...
2601
+        'FontUnits','normalized',...	       
2602
+	'Tag','EditText2');
2603
+h1 = uicontrol('Parent',h0, ...
2604
+	'Units','normalized', ...
2605
+	'BackgroundColor',[1 1 1], ...
2606
+	'Callback','som_gui(''check_fine_trainlen'');', ...
2607
+	'ListboxTop',0, ...
2608
+	'Position',[0.7923 0.2352 0.0974 0.0402], ...
2609
+        'FontUnits','normalized',...	       
2610
+	'Style','edit', ...
2611
+	'Tag','EditText11');
2612
+h1 = uicontrol('Parent',h0, ...
2613
+	'Units','normalized', ...
2614
+	'BackgroundColor',[1 1 1], ...
2615
+	'Callback','som_gui(''check_fine_alphaini'');', ...
2616
+	'Enable','off', ...
2617
+	'ListboxTop',0, ...
2618
+	'Position',[0.7923076923076923 0.1664904862579281 0.09743589743589742 0.03805496828752643], ...
2619
+	'Style','edit', ...
2620
+        'FontUnits','normalized',...	       
2621
+	'Tag','EditText10', ...
2622
+	'Visible','off');
2623
+h1 = uicontrol('Parent',h0, ...
2624
+	'Units','normalized', ...
2625
+	'BackgroundColor',[1 1 1], ...
2626
+	'Callback','som_gui(''check_fine_radfin'');', ...
2627
+	'ListboxTop',0, ...
2628
+	'Position',[0.7923076923076923 0.3002114164904862 0.09743589743589742 0.040169133192389], ...
2629
+	'Style','edit', ...
2630
+	'FontUnits','normalized',...       
2631
+	'Tag','EditText9');
2632
+h1 = uicontrol('Parent',h0, ...
2633
+	'Units','normalized', ...
2634
+	'BackgroundColor',[1 1 1], ...
2635
+	'Callback','som_gui(''check_fine_radini'');', ...
2636
+	'ListboxTop',0, ...
2637
+	'Position',[0.7923076923076923 0.3657505285412262 0.09743589743589742 0.040169133192389], ...
2638
+	'Style','edit', ...
2639
+	'FontUnits','normalized',...     
2640
+	'Tag','EditText8');
2641
+h1 = uicontrol('Parent',h0, ...
2642
+	'Units','normalized', ...
2643
+	'BackgroundColor',[0.8 0.8 0.8], ...
2644
+	'HorizontalAlignment','left', ...
2645
+	'ListboxTop',0, ...
2646
+	'Position',[0.5590 0.2326 0.2179 0.0402], ...
2647
+	'String','training length', ...
2648
+        'FontUnits','normalized',...	       
2649
+	'Style','text', ...
2650
+	'Tag','StaticText16');
2651
+h1 = uicontrol('Parent',h0, ...
2652
+	'Units','normalized', ...
2653
+	'BackgroundColor',[0.8 0.8 0.8], ...
2654
+	'HorizontalAlignment','left', ...
2655
+	'ListboxTop',0, ...
2656
+	'Position',[0.5590 0.1665 0.2179 0.0381], ...
2657
+	'String','alpha initial', ...
2658
+	'FontUnits','normalized',...     
2659
+	'Style','text', ...
2660
+	'Tag','StaticText14', ...
2661
+	'Visible','off');
2662
+h1 = uicontrol('Parent',h0, ...
2663
+	'Units','normalized', ...
2664
+	'BackgroundColor',[0.8 0.8 0.8], ...
2665
+	'HorizontalAlignment','left', ...
2666
+	'ListboxTop',0, ...
2667
+	'Position',[0.5590 0.2981 0.2179 0.0402], ...
2668
+	'String','radius final', ...
2669
+        'FontUnits','normalized',...	       
2670
+	'Style','text', ...
2671
+	'Tag','StaticText12');
2672
+h1 = uicontrol('Parent',h0, ...
2673
+	'Units','normalized', ...
2674
+	'BackgroundColor',[0.8 0.8 0.8], ...
2675
+	'HorizontalAlignment','left', ...
2676
+	'ListboxTop',0, ...
2677
+	'Position',[0.5590 0.3636 0.2179 0.0402], ...
2678
+	'String','radius initial', ...
2679
+	'FontUnits','normalized',...      
2680
+	'Style','text', ...
2681
+	'Tag','StaticText10');
2682
+h1 = uicontrol('Parent',h0, ...
2683
+	'Units','normalized', ...
2684
+	'BackgroundColor',[1 1 1], ...
2685
+	'Callback','som_gui(''check_rough_trainlen'');', ...
2686
+	'ListboxTop',0, ...
2687
+	'Position',[0.3590 0.2352 0.0949 0.0402], ...
2688
+	'Style','edit', ...
2689
+	'FontUnits','normalized',...     
2690
+	'Tag','EditText7');
2691
+h1 = uicontrol('Parent',h0, ...
2692
+	'Units','normalized', ...
2693
+	'BackgroundColor',[1 1 1], ...
2694
+	'Callback','som_gui(''check_rough_alphaini'');', ...
2695
+	'Enable','off', ...
2696
+	'ListboxTop',0, ...
2697
+	'Position',[0.3590 0.1691 0.0949 0.0381], ...
2698
+	'Style','edit', ...
2699
+        'FontUnits','normalized',...	       
2700
+	'Tag','EditText6', ...
2701
+	'Visible','off');
2702
+h1 = uicontrol('Parent',h0, ...
2703
+	'Units','normalized', ...
2704
+	'BackgroundColor',[1 1 1], ...
2705
+	'Callback','som_gui(''check_rough_radfin'');', ...
2706
+	'ListboxTop',0, ...
2707
+	'Position',[0.358974358974359 0.3044397463002114 0.09487179487179487 0.040169133192389], ...
2708
+	'Style','edit', ...
2709
+	'FontUnits','normalized',...      
2710
+	'Tag','EditText5');
2711
+h1 = uicontrol('Parent',h0, ...
2712
+	'Units','normalized', ...
2713
+	'BackgroundColor',[1 1 1], ...
2714
+	'Callback','som_gui(''check_rough_radini'');', ...
2715
+	'ListboxTop',0, ...
2716
+	'Position',[0.358974358974359 0.3699788583509514 0.09487179487179487 0.040169133192389], ...
2717
+	'Style','edit', ...
2718
+        'FontUnits','normalized',...	       
2719
+	'Tag','EditText4');
2720
+h1 = uicontrol('Parent',h0, ...
2721
+	'Units','normalized', ...
2722
+	'BackgroundColor',[0.8 0.8 0.8], ...
2723
+	'HorizontalAlignment','left', ...
2724
+	'ListboxTop',0, ...
2725
+	'Position',[0.0962 0.2326 0.2179 0.0402], ...
2726
+	'String','training length', ...
2727
+        'FontUnits','normalized',...	       
2728
+	'Style','text', ...
2729
+	'Tag','StaticText15');
2730
+h1 = uicontrol('Parent',h0, ...
2731
+	'Units','normalized', ...
2732
+	'BackgroundColor',[0.8 0.8 0.8], ...
2733
+	'HorizontalAlignment','left', ...
2734
+	'ListboxTop',0, ...
2735
+	'Position',[0.0962 0.1691 0.2179 0.0381], ...
2736
+	'String','alpha initial', ...
2737
+        'FontUnits','normalized',...	       
2738
+	'Style','text', ...
2739
+	'Tag','StaticText13', ...
2740
+	'Visible','off');
2741
+h1 = uicontrol('Parent',h0, ...
2742
+	'Units','normalized', ...
2743
+	'BackgroundColor',[0.8 0.8 0.8], ...
2744
+	'HorizontalAlignment','left', ...
2745
+	'ListboxTop',0, ...
2746
+	'Position',[0.0962 0.3023 0.2179 0.0402], ...
2747
+	'String','radius final', ...
2748
+        'FontUnits','normalized',...	       
2749
+	'Style','text', ...
2750
+	'Tag','StaticText11');
2751
+h1 = uicontrol('Parent',h0, ...
2752
+	'Units','normalized', ...
2753
+	'BackgroundColor',[0.8 0.8 0.8], ...
2754
+	'HorizontalAlignment','left', ...
2755
+	'ListboxTop',0, ...
2756
+	'Position',[0.0962 0.3679 0.2179 0.0402], ...
2757
+        'FontUnits','normalized',...
2758
+	'String','radius initial', ...
2759
+	'Style','text', ...
2760
+	'Tag','StaticText9');
2761
+h1 = uicontrol('Parent',h0, ...
2762
+	'Units','normalized', ...
2763
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2764
+	'ListboxTop',0, ...
2765
+	'Position',[0.5948717948717949 0.4291754756871036 0.2871794871794872 0.05285412262156448], ...
2766
+	'String','Finetune', ...
2767
+        'FontUnits','normalized',...	       
2768
+	'Style','text', ...
2769
+	'Tag','StaticText8');
2770
+h1 = uicontrol('Parent',h0, ...
2771
+	'Units','normalized', ...
2772
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2773
+	'ListboxTop',0, ...
2774
+	'Position',[0.1205128205128205 0.4355179704016914 0.3153846153846154 0.04862579281183932], ...
2775
+	'String','Rough', ...
2776
+        'FontUnits','normalized',...	       
2777
+	'Style','text', ...
2778
+	'Tag','StaticText7');
2779
+h1 = uicontrol('Parent',h0, ...
2780
+	'Units','normalized', ...
2781
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2782
+	'FontWeight','bold', ...
2783
+	'ListboxTop',0, ...
2784
+	'Position',[0.1641025641025641 0.8900634249471459 0.7025641025641025 0.05285412262156448], ...
2785
+	'String','Change parameters for batch training', ...
2786
+	'Style','text', ...
2787
+        'FontUnits','normalized',...	       
2788
+	'Tag','StaticText1');
2789
+h1 = uicontrol('Parent',h0, ...
2790
+	'Units','normalized', ...
2791
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2792
+	'HorizontalAlignment','left', ...
2793
+	'ListboxTop',0, ...
2794
+	'Position',[0.09615384615384615 0.6025369978858351 0.1743589743589744 0.040169133192389], ...
2795
+	'String','length type:', ...
2796
+	'Style','text', ...
2797
+        'FontUnits','normalized',...	       
2798
+	'Tag','StaticText17');
2799
+h1 = uicontrol('Parent',h0, ...
2800
+	'Units','normalized', ...
2801
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2802
+	'ListboxTop',0, ...
2803
+	'Max',2, ...
2804
+	'Min',1, ...
2805
+	'Position',[0.2948717948717949 0.6062367864693446 0.1923076923076923 0.03964059196617336], ...
2806
+	'String',temp3, ...
2807
+        'FontUnits','normalized',...	       
2808
+	'Style','popupmenu', ...
2809
+	'Tag','PopupMenu3', ...
2810
+	'Value',1);
2811
+h1 = uicontrol('Parent',h0, ...
2812
+	'Units','normalized', ...
2813
+	'HorizontalAlignment','left', ...
2814
+	'ListboxTop',0, ...
2815
+	'Position',[0.5102564102564102 0.6004228329809724 0.1641025641025641 0.040169133192389], ...
2816
+	'String','order', ...
2817
+        'FontUnits','normalized',...	       
2818
+	'Style','text', ...
2819
+	'Tag','StaticText18');
2820
+h1 = uicontrol('Parent',h0, ...
2821
+	'Units','normalized', ...
2822
+	'HorizontalAlignment','left', ...
2823
+	'ListboxTop',0, ...
2824
+	'Max',2, ...
2825
+	'Min',1, ...
2826
+	'Position',[0.7051282051282051 0.6109936575052853 0.1923076923076923 0.040169133192389], ...
2827
+	'String',temp4, ...
2828
+        'FontUnits','normalized',...	       
2829
+	'Style','popupmenu', ...
2830
+	'Tag','PopupMenu4', ...
2831
+	'Value',1);
2832
+h1 = uicontrol('Parent',h0, ...
2833
+	'Units','normalized', ...
2834
+	'HorizontalAlignment','left', ...
2835
+	'ListboxTop',0, ...
2836
+	'Position',[0.09615384615384615 0.5369978858350951 0.2051282051282051 0.040169133192389], ...
2837
+	'String','learning func', ...
2838
+        'FontUnits','normalized',...	       
2839
+	'Style','text', ...
2840
+	'Tag','StaticText19');
2841
+h1 = uicontrol('Parent',h0, ...
2842
+	'Units','normalized', ...
2843
+	'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ...
2844
+	'ListboxTop',0, ...
2845
+	'Max',3, ...
2846
+	'Min',1, ...
2847
+	'Position',[0.2948717948717949 0.5454545454545455 0.1923076923076923 0.03964059196617336], ...
2848
+	'String',temp5, ...
2849
+        'FontUnits','normalized',...	       
2850
+	'Style','popupmenu', ...
2851
+	'Tag','PopupMenu5', ...
2852
+	'Value',1);
2853
+if nargout > 0, fig = h0; end
2854
+
2855
+
2856
+function print_info(sS,level,fid)
2857
+
2858
+
2859
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2860
+%% check arguments
2861
+
2862
+
2863
+%error(nargchk(1, 2, nargin))  % check no. of input args is correct
2864
+
2865
+if ~isstruct(sS),
2866
+  if ~iscell(sS) | ~isstruct(sS{1}), 
2867
+    error('Input argument is not a struct or a cell array of structs.')
2868
+  end
2869
+  csS = sS;
2870
+else
2871
+  csS = {sS};
2872
+end
2873
+
2874
+if nargin<2 | isempty(level) | isnan(level), level = 1; end
2875
+
2876
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2877
+%% print struct information
2878
+
2879
+for c=1:length(csS), 
2880
+ sS = csS{c};
2881
+
2882
+ switch sS.type, 
2883
+ case 'som_map', 
2884
+  mdim = length(sS.topol.msize);
2885
+  [munits dim] = size(sS.codebook);
2886
+  t    = length(sS.trainhist);  
2887
+  if t==0, st='uninitialized'; 
2888
+  elseif t==1, st = 'initialized';
2889
+  else st = sprintf('initialized, trained %d times',t-1);
2890
+  end
2891
+
2892
+  % level 1
2893
+  fprintf(fid,'%% Struct type                           : %s\n', sS.type);
2894
+  fprintf(fid,'%% Map name                              : %s\n', sS.name);
2895
+  fprintf(fid,'%% Input dimension                       : %d\n', dim);
2896
+  fprintf(fid,'%% Map grid size                         : ');
2897
+  for i = 1:mdim - 1, fprintf(fid,'%d x ',sS.topol.msize(i)); end
2898
+  fprintf(fid,'%d\n', sS.topol.msize(mdim));
2899
+  fprintf(fid,'%% Lattice type (rect/hexa)              : %s\n', sS.topol.lattice);
2900
+  fprintf(fid,'%% Shape (sheet/cyl/toroid)              : %s\n', sS.topol.shape);
2901
+  fprintf(fid,'%% Neighborhood type                     : %s\n', sS.neigh);
2902
+  fprintf(fid,'%% Mask                                  : ');
2903
+  if dim,
2904
+    for i = 1:dim-1, fprintf(fid,'%d ',sS.mask(i)); end; 
2905
+    fprintf(fid,'%d\n',sS.mask(dim));
2906
+  else fprintf(fid,'%% \n');
2907
+  end
2908
+  fprintf(fid,'%% Training status                       : %s\n', st);
2909
+   
2910
+  % level 1,
2911
+  status = cell(dim,1);
2912
+  for i=1:dim, 
2913
+    n = length(sS.comp_norm{i});
2914
+    if n, 
2915
+      uninit = strcmp('uninit',{sS.comp_norm{i}.status});
2916
+      done   = strcmp('done',{sS.comp_norm{i}.status});
2917
+      undone = strcmp('undone',{sS.comp_norm{i}.status});
2918
+      if sum(uninit)==n, status{i} = 'no normalization';
2919
+      elseif sum(done)==n, status{i} = 'normalized';
2920
+      elseif sum(undone)==n, status{i} = 'denormalized';
2921
+      else status{i} = 'partial';
2922
+      end
2923
+    else status{i} = 'no normalization'; end
2924
+  end
2925
+  if level>1, 
2926
+    fprintf(fid,'%% Vector components\n');
2927
+    M = sS.codebook;
2928
+    fprintf(fid,'%%  #   name          mask     min    mean     max     std  status\n');
2929
+    fprintf(fid,'%%  --- ------------  ----  ------  ------  ------  ------  ------\n');
2930
+    for i = 1:dim,
2931
+      fprintf(fid,'%%  %-3d %-12s  %-4.2f  %6.1g  %6.1g  %6.1g  %6.1g  %s\n', ...
2932
+              i,sS.comp_names{i}, sS.mask(i), ...
2933
+              min(M(:,i)),mean(M(:,i)),max(M(:,i)),std(M(:,i)),status{i});
2934
+    end
2935
+  end
2936
+
2937
+  % level 3
2938
+  if level>2,
2939
+    fprintf(fid,'%% Vector component normalizations\n');
2940
+    fprintf(fid,'%%  #   name          method (i=uninit,u=undone,d=done)\n');
2941
+    fprintf(fid,'%%  --- ------------  ---------------------------------------\n');
2942
+    for i=1:dim,  
2943
+      fprintf(fid,'%%  %-3d %-12s  ',i,sS.comp_names{i});
2944
+      n = length(sS.comp_norm{i}); 
2945
+      for j=1:n, 
2946
+        m = sS.comp_norm{i}(j).method;
2947
+        s = sS.comp_norm{i}(j).status;
2948
+        if strcmp(s,'uninit'), c='i'; 
2949
+        elseif strcmp(s,'undone'), c='u'; 
2950
+        else c='d';
2951
+        end
2952
+        fprintf(fid,'%% %s[%s] ',m,c);
2953
+      end
2954
+      fprintf(fid,'%% \n');
2955
+    end
2956
+  end
2957
+  
2958
+  % level 4
2959
+  if level>3,
2960
+    fprintf(fid,'%% Training history\n');
2961
+    for i=1:t, 
2962
+      sT = sS.trainhist(i);
2963
+      fprintf(fid,'%% * Algorithm: %8s   Data: %13s  Trainlen:  %8d\n',...
2964
+	      sT.algorithm,sT.data_name,sT.trainlen);
2965
+      %if i>1, 
2966
+        fprintf(fid,'%%   Neighborh: %8s  Mask:  ',sT.neigh);
2967
+        for i = 1:dim-1, fprintf(fid,'%% %d ',sT.mask(i)); end; 
2968
+        fprintf(fid,'%% %d\n',sT.mask(mdim));
2969
+        fprintf(fid,'%%   Radius:  %4.2f->%4.2f  Alpha: %5.3f (%s)\n', ...
2970
+		sT.radius_ini,sT.radius_fin,sT.alpha_ini,sT.alpha_type);
2971
+      %end
2972
+      fprintf(fid,'%%   Time:  %s\n',sT.time);
2973
+    end
2974
+  end
2975
+
2976
+ case 'som_data',
2977
+
2978
+  [dlen dim] = size(sS.data);
2979
+  if dlen*dim
2980
+    ind      = find(~isnan(sum(sS.data),2));
2981
+  else ind = []; end
2982
+  complete = size(sS.data(ind,:),1);
2983
+  partial  = dlen - complete;
2984
+  values   = prod(size(sS.data));
2985
+  missing  = sum(sum(isnan(sS.data))); 
2986
+
2987
+  % level 1  
2988
+  fprintf(fid,'%% Struct type             : %s\n', sS.type);
2989
+  fprintf(fid,'%% Data name               : %s\n', sS.name);
2990
+  fprintf(fid,'%% Vector dimension        : %d\n', dim);
2991
+  fprintf(fid,'%% Number of data vectors  : %d\n', dlen);
2992
+  fprintf(fid,'%% Complete data vectors   : %d\n', complete);
2993
+  fprintf(fid,'%% Partial data vectors    : %d\n', partial);  
2994
+  if values, r = floor(100 * (values - missing) / values); else r = 0; end
2995
+  fprintf(fid,'%% Complete values         : %d of %d (%d%%)\n', ...
2996
+          values-missing, values, r); 
2997
+
2998
+  % level 2,
2999
+  status = cell(dim,1);
3000
+  for i=1:dim, 
3001
+    n = length(sS.comp_norm{i});
3002
+    if n, 
3003
+      uninit = strcmp('uninit',{sS.comp_norm{i}.status});
3004
+      done   = strcmp('done',{sS.comp_norm{i}.status});
3005
+      undone = strcmp('undone',{sS.comp_norm{i}.status});
3006
+      if sum(uninit)==n, status{i} = 'no normalization';
3007
+      elseif sum(done)==n, status{i} = 'normalized';
3008
+      elseif sum(undone)==n, status{i} = 'denormalized';
3009
+      else status{i} = 'partial';
3010
+      end
3011
+    else status{i} = 'no normalization'; end
3012
+  end
3013
+  if level>1, 
3014
+    fprintf(fid,'%% Vector components\n');
3015
+    D = sS.data;
3016
+    fprintf(fid,'%%  #   name            min     mean     max     std  missing      status\n');
3017
+    fprintf(fid,'%%  --- ------------  ------  ------  ------  ------  -----------  ------\n');
3018
+    for i = 1:dim,
3019
+      known = find(~isnan(D(:,i))); 
3020
+      miss = dlen-length(known);
3021
+      fprintf(fid,'%%  %-3d %-12s  %6.1g  %6.1g  %6.1g  %6.1g  %5d (%2d%%)  %s\n', ...
3022
+              i,sS.comp_names{i}, ...
3023
+              min(D(known,i)),mean(D(known,i)),max(D(known,i)),std(D(known,i)), ...
3024
+              miss,floor(100*miss/dlen),status{i});
3025
+    end
3026
+  end
3027
+
3028
+  % level 3
3029
+  if level>2,
3030
+    fprintf(fid,'%% Vector component normalizations\n');
3031
+    fprintf(fid,'%%  #   name          method (i=uninit,u=undone,d=done)\n');
3032
+    fprintf(fid,'%%  --- ------------  ---------------------------------------\n');
3033
+    for i=1:dim,  
3034
+      fprintf(fid,'%%  %-3d %-12s  ',i,sS.comp_names{i});
3035
+      n = length(sS.comp_norm{i});         
3036
+      for j=1:n, 
3037
+        m = sS.comp_norm{i}(j).method;
3038
+        s = sS.comp_norm{i}(j).status;
3039
+        if strcmp(s,'uninit'), c='i'; 
3040
+        elseif strcmp(s,'undone'), c='u'; 
3041
+        else c='d';
3042
+        end
3043
+        fprintf(fid,'%% %s[%s] ',m,c);
3044
+      end
3045
+      fprintf(fid,'%% \n');
3046
+    end
3047
+  end
3048
+
3049
+ case 'som_topol', 
3050
+
3051
+  mdim = length(sS.msize);
3052
+ 
3053
+  % level 1
3054
+  fprintf(fid,'%% Struct type                           : %s\n',sS.type);
3055
+  fprintf(fid,'%% Map grid size                         : ');
3056
+  for i = 1:mdim - 1, fprintf(fid,'%% %d x ',sS.msize(i)); end
3057
+  fprintf(fid,'%% %d\n', sS.msize(mdim));
3058
+  fprintf(fid,'%% Lattice type (rect/hexa)              : %s\n', sS.lattice);
3059
+  fprintf(fid,'%% Shape (sheet/cyl/toroid)              : %s\n', sS.shape);
3060
+
3061
+ case 'som_train', 
3062
+
3063
+  % level 1
3064
+  fprintf(fid,'%% Struct type                           : %s\n',sS.type);
3065
+  fprintf(fid,'%% Training algorithm                    : %s\n',sS.algorithm);
3066
+  fprintf(fid,'%% Training data                         : %s\n',sS.data_name);
3067
+  fprintf(fid,'%% Neighborhood function                 : %s\n',sS.neigh);
3068
+  fprintf(fid,'%% Mask                                  : ');
3069
+  dim = length(sS.mask);
3070
+  if dim, 
3071
+    for i = 1:dim-1, fprintf(fid,'%% %d ',sS.mask(i)); end; 
3072
+    fprintf(fid,'%% %d\n',sS.mask(end));
3073
+  else fprintf(fid,'%% \n'); end
3074
+  fprintf(fid,'%% Initial radius                        : %-6.1f\n',sS.radius_ini);
3075
+  fprintf(fid,'%% Final radius                          : %-6.1f\n',sS.radius_fin);
3076
+  fprintf(fid,'%% Initial learning rate (alpha)         : %-6.1f\n',sS.alpha_ini);
3077
+  fprintf(fid,'%% Alpha function type (linear/inv)      : %s\n',sS.alpha_type);
3078
+  fprintf(fid,'%% Training length                       : %d\n',sS.trainlen);
3079
+  fprintf(fid,'%% Average quantization error            : %-6.1f\n',sS.qerror);
3080
+  fprintf(fid,'%% When training was done                : %s\n',sS.time);
3081
+
3082
+ case 'som_norm', 
3083
+  
3084
+  % level 1
3085
+  fprintf(fid,'%% Struct type                           : %s\n',sS.type);
3086
+  fprintf(fid,'%% Normalization method                  : %s\n',sS.method);
3087
+  fprintf(fid,'%% Status                                : %s\n',sS.status);
3088
+
3089
+  % level 2
3090
+  if level>1, 
3091
+    fprintf(fid,'%% Parameters:\n');
3092
+    sS.params
3093
+  end
3094
+ end
3095
+end
3096
+
3097
+function [] = html2tex(html_addres,texfile)
3098
+
3099
+tempfile = tempname;
3100
+fid = fopen(texfile,'w');
3101
+eval(['!lynx -dump ' html_addres ' > ' tempfile]);
3102
+fid2 = fopen(tempfile,'r');
3103
+while not(feof(fid2))
3104
+	line = fgets(fid2);
3105
+	line = strcat('%',line);
3106
+	fprintf(fid,'%s',line);
3107
+end
3108
+	fclose(fid);
3109
+	fclose(fid2);
3110
+	delete (tempfile);
3111
+
3112
+
3113
+function [name] = retname
3114
+resnames = who;
3115
+if size(resnames,1) > 0
3116
+  max_length = size(resnames{1},2);
3117
+  for index = 1:size(resnames,1)
3118
+    if size(resnames{index},2) > max_length
3119
+	max_length =  size(resnames{index},2);
3120
+    end
3121
+  end
3122
+ length = max_length + 1;
3123
+ name(:,1:1:length) = 'A' 				
3124
+else
3125
+ name = 'A';
3126
+end	
3127
+%%
3128
+
3129
+
3130
+
... ...
@@ -0,0 +1,217 @@
1
+function [hits] = som_hits(sMap, sData, mode)
2
+
3
+%SOM_HITS Calculate the response of the given data on the map.
4
+%
5
+% hits = som_hits(sMap, sData, [mode])
6
+%
7
+%   h = som_hits(sMap,sData);
8
+%   h = som_hits(sMap,sData,'fuzzy');
9
+%
10
+%  Input and output arguments ([]'s are optional): 
11
+%   sMap     (struct) map struct
12
+%            (matrix) codebook matrix, size munits x dim
13
+%   sData    (struct) data struct
14
+%            (matrix) data matrix, size dlen x dim
15
+%   [mode]   (string) 'crisp' (default), 'kernel', 'fuzzy'
16
+%
17
+%   hits     (vector) the number of hits in each map unit, length = munits
18
+%
19
+% The response of the data on the map can be calculated e.g. in
20
+% three ways, selected with the mode argument: 
21
+%  'crisp'    traditional hit histogram
22
+%  'kernel'   a sum of dlen neighborhood kernels, where kernel
23
+%             is positioned on the BMU of each data sample. The 
24
+%             neighborhood function is sMap.neigh and the
25
+%             neighborhood width is sMap.trainhist(end).radius_fin
26
+%             or 1 if this is empty or NaN
27
+%  'fuzzy'    fuzzy response calculated by summing 1./(1+(q/a)^2)
28
+%             for each data sample, where q is a vector containing
29
+%             distance from the data sample to each map unit and 
30
+%             a is average quantization error
31
+% 
32
+% For more help, try 'type som_hits' or check out online documentation.
33
+% See also SOM_AUTOLABEL, SOM_BMUS.    
34
+
35
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
36
+%
37
+% som_hits
38
+%
39
+% PURPOSE
40
+%
41
+% Calculate the response of the given data on the map.
42
+%
43
+% SYNTAX
44
+%
45
+%  hits = som_hits(sMap, sData)
46
+%  hits = som_hits(M, D)
47
+%  hits = som_hits(..., mode)
48
+%
49
+% DESCRIPTION
50
+%
51
+% Returns a vector indicating the response of the map to the data.
52
+% The response of the data on the map can be calculated e.g. in
53
+% three ways, selected with the mode argument: 
54
+%  'crisp'    traditional hit histogram: how many times each map unit 
55
+%             was the BMU for the data set
56
+%  'kernel'   a sum of neighborhood kernels, where a kernel
57
+%             is positioned on the BMU of each data sample. The 
58
+%             neighborhood function is sMap.neigh and the
59
+%             neighborhood width is sMap.trainhist(end).radius_fin
60
+%             or 1 if this is not available 
61
+%  'fuzzy'    fuzzy response calculated by summing 
62
+%
63
+%                            1
64
+%                       ------------
65
+%                       1 +  (q/a)^2
66
+%
67
+%             for each data sample, where q is a vector containing
68
+%             distance from the data sample to each map unit and 
69
+%             a is average quantization error
70
+%
71
+% REQUIRED INPUT ARGUMENTS
72
+%
73
+%   sMap              The vectors from among which the BMUs are searched
74
+%                     for. These must not have any unknown components (NaNs).
75
+%            (struct) map struct
76
+%            (matrix) codebook matrix, size munits x dim
77
+%                     
78
+%   sData             The data vector(s) for which the BMUs are searched.
79
+%            (struct) data struct
80
+%            (matrix) data matrix, size dlen x dim
81
+%
82
+% OPTIONAL INPUT ARGUMENTS
83
+%
84
+%   mode     (string) The respond mode: 'crisp' (default), 'kernel'
85
+%                     or 'fuzzy'. 'kernel' can only be used if 
86
+%                     the first argument (sMap) is a map struct.                     
87
+% 
88
+% OUTPUT ARGUMENTS
89
+% 
90
+%   hits     (vector) The number of hits in each map unit.
91
+%
92
+% EXAMPLES
93
+%
94
+%  hits = som_hits(sM,D);
95
+%  hits = som_hits(sM,D,'kernel');
96
+%  hits = som_hits(sM,D,'fuzzy');
97
+%
98
+% SEE ALSO
99
+% 
100
+%  som_bmus      Find BMUs and quantization errors for a given data set.
101
+
102
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
103
+% http://www.cis.hut.fi/projects/somtoolbox/
104
+
105
+% Version 1.0beta juuso 220997
106
+% Version 2.0beta juuso 161199
107
+
108
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
109
+%% check arguments
110
+
111
+error(nargchk(2, 3, nargin));  % check no. of input args is correct
112
+
113
+if isstruct(sMap), 
114
+  switch sMap.type, 
115
+   case 'som_map', munits = prod(sMap.topol.msize);
116
+   case 'som_data', munits = size(sMap.data,1);
117
+   otherwise, 
118
+    error('Illegal struct for 1st argument.')
119
+  end
120
+else 
121
+  munits = size(sMap,1); 
122
+end
123
+hits = zeros(munits,1);
124
+
125
+if nargin<3, mode = 'crisp'; end
126
+
127
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
128
+%% action
129
+
130
+% calculate BMUs
131
+[bmus,qerrs] = som_bmus(sMap,sData,1);
132
+
133
+switch mode, 
134
+case 'crisp',    
135
+
136
+ % for each unit, check how many hits it got
137
+ for i=1:munits, hits(i) = sum(bmus == i); end
138
+   
139
+case 'kernel',
140
+
141
+ % check that sMap really is a map 
142
+ if ~isstruct(sMap) & ~strcmp(sMap.type,'som_map'), 
143
+   error('Kernel mode can only be used for maps.');
144
+ end	   
145
+
146
+ % calculate neighborhood kernel  
147
+ Ud = som_unit_dists(sMap.topol).^2;
148
+ sTrain = sMap.trainhist(end); 
149
+ if ~isempty(sTrain), 
150
+   rad = sTrain.radius_fin; 
151
+   if isempty(rad) | isnan(rad), rad = 1; end 
152
+ else 
153
+   rad = 1; 
154
+ end    
155
+ rad = rad^2;
156
+ if rad==0, rad = eps; end % to avoid divide-by-0 errors
157
+ switch sTrain.neigh, 
158
+  case 'bubble',   H = (Ud<=rad); 
159
+  case 'gaussian', H = exp(-Ud/(2*rad)); 
160
+  case 'cutgauss', H = exp(-Ud/(2*rad)) .* (Ud<=rad);
161
+  case 'ep',       H = (1-Ud/rad) .* (Ud<=rad);
162
+ end
163
+ 
164
+ % weight hits with neighborhood kernel
165
+ hits = sum(H(bmus,:),1)';
166
+   
167
+case 'fuzzy',	
168
+
169
+ % extract the two matrices (M, D) and the mask
170
+ mask = [];
171
+ if isstruct(sMap), 
172
+   if strcmp(sMap.type,'som_data'), M = sMap.data; 
173
+   else M = sMap.codebook; mask = sMap.mask;
174
+   end
175
+ else M = sMap;
176
+ end
177
+ if any(isnan(M(:))), 
178
+   error('Data in first argument must not have any NaNs.'); 
179
+ end
180
+
181
+ if isstruct(sData), 
182
+   switch sData.type, 
183
+    case 'som_map', 
184
+     D = sData.codebook; 
185
+     if isempty(mask), mask = sData.mask; end
186
+    case 'som_data', D = sData.data;
187
+    otherwise, error('Illegal 2nd argument.');
188
+   end	
189
+ else D = sData;
190
+ end
191
+ [dlen dim] = size(D);   
192
+ if isempty(mask), mask = ones(dim,1); end
193
+
194
+ % scaling factor   
195
+ a = mean(qerrs).^2;
196
+ 
197
+ % calculate distances & bmus
198
+ % (this is better explained in som_batchtrain and som_bmus)
199
+ Known = ~isnan(D); D(find(~Known)) = 0; % unknown components  
200
+ blen = min(munits,dlen); % block size 
201
+ W1 = mask*ones(1,blen); W2 = ones(munits,1)*mask'; D = D'; Known = Known';
202
+ i0 = 0; 
203
+ while i0+1<=dlen,    
204
+   inds = [(i0+1):min(dlen,i0+blen)]; i0 = i0+blen; % indeces   
205
+   Dist = (M.^2)*(W1(:,1:length(inds)).*Known(:,inds)) ...
206
+	  + W2*(D(:,inds).^2) ...
207
+	  - 2*M*diag(mask)*D(:,inds); % squared distances
208
+   hits = hits + sum(1./(1+Dist/a),2);   
209
+ end  
210
+ 
211
+ otherwise, 
212
+  error(['Unknown mode: ' mode]);
213
+  
214
+end
215
+
216
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
217
+
... ...
@@ -0,0 +1,48 @@
1
+function cind = som_ind2cod(msize,ind)
2
+
3
+%SOM_IND2COD SOM_PAK style linear indeces from Matlab linear index.
4
+%
5
+% Cind = som_ind2cod(msize,inds)
6
+%
7
+%  cind = som_ind2cod([10 15],44);
8
+%  cind = som_ind2cod(sMap,44);
9
+%  cind = som_ind2cod(sMap.msize,44);
10
+%  Cind = som_ind2cod([10 15],[44 13 91]');
11
+%
12
+%  Input and output arguments: 
13
+%   msize  (struct) map or topology struct
14
+%          (vector) size 1 x m, specifies the map grid size
15
+%   ind    (vector) size n x 1, linear indeces of n map units
16
+% 
17
+%   cind   (matrix) size n x 1, SOM_PAK style linear indeces
18
+%                   (row first, then column)
19
+%
20
+% See also SOM_COD2IND.
21
+
22
+% Contributed to SOM Toolbox vs2, January 14th, 2002 by Juha Vesanto
23
+% http://www.cis.hut.fi/projects/somtoolbox/
24
+
25
+% Version 2.0beta juuso 140102
26
+
27
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
28
+
29
+if isstruct(msize), 
30
+  if strcmp(msize.type,'som_map'), msize = msize.topol.msize; 
31
+  elseif strcmp(msize.type,'som_topol'), msize = msize.msize;
32
+  else error('Invalid first argument.'); end
33
+end
34
+
35
+if nargin<2, ind = 1:prod(msize); end
36
+
37
+Co = som_unit_coords(msize,'rect','sheet');
38
+
39
+switch size(Co,2),
40
+case 1, I2C = [1:prod(msize)]; 
41
+case 2, I2C = 1 + Co(:,1) + Co(:,2)*msize(2); 
42
+case 3, I2C = 1 + Co(:,1) + Co(:,2)*msize(2) + Co(:,3)*msize(1)*msize(2); % ?????
43
+end
44
+
45
+cind = I2C(ind); 
46
+return; 
47
+
48
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,42 @@
1
+function Subs = som_ind2sub(msize,inds)
2
+
3
+%SOM_IND2SUB Map grid subscripts from linear index.
4
+%
5
+% Subs = som_ind2sub(msize,inds)
6
+%
7
+%  sub = som_ind2sub([10 15],44);
8
+%  sub = som_ind2sub(sMap,44);
9
+%  sub = som_ind2sub(sMap.msize,44);
10
+%  Subs = som_ind2sub([10 15],[44 13 91]');
11
+%
12
+%  Input and output arguments: 
13
+%   msize  (struct) map or topology struct
14
+%          (vector) size 1 x m, specifies the map grid size
15
+%   inds   (vector) size n x 1, linear indeces of n map units
16
+% 
17
+%   Subs   (matrix) size n x m, the subscripts
18
+%
19
+% See also SOM_SUB2IND.
20
+
21
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Vesanto
22
+% http://www.cis.hut.fi/projects/somtoolbox/
23
+
24
+% Version 2.0beta juuso 300798
25
+
26
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
27
+
28
+if isstruct(msize), 
29
+  if strcmp(msize.type,'som_map'), msize = msize.topol.msize; 
30
+  elseif strcmp(msize.type,'som_topol'), msize = msize.msize;
31
+  else error('Invalid first argument.'); end
32
+end
33
+
34
+n = length(msize); 
35
+k = [1 cumprod(msize(1:end-1))]; 
36
+inds = inds - 1;
37
+for i = n:-1:1, 
38
+  Subs(:,i) = floor(inds/k(i))+1; 
39
+  inds = rem(inds,k(i)); 
40
+end
41
+
42
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,403 @@
1
+function som_info(sS,level)
2
+
3
+%SOM_INFO Displays information on the given SOM Toolbox struct.
4
+% 
5
+% som_info(sS,[level])
6
+%
7
+%  som_info(sMap);
8
+%  som_info(sData,3);
9
+%  som_info({sMap,sData});
10
+%  som_info(sMap.comp_norm{2}); 
11
+%
12
+%  Input and output arguments ([]'s are optional): 
13
+%   sS       (struct) SOM Toolbox struct 
14
+%            (cell array of structs) several structs in a cell array
15
+%   [level]  (scalar) detail level (1-4), default = 1
16
+%
17
+% For more help, try 'type som_info' or check out online documentation.
18
+% See also SOM_SET.
19
+
20
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
21
+%
22
+% som_info
23
+%
24
+% PURPOSE
25
+%
26
+% Display information of the given SOM Toolbox struct(s).
27
+%
28
+% SYNTAX
29
+%
30
+%  som_info(sM)
31
+%  som_info({sM,sD})
32
+%  som_info(...,level)
33
+%
34
+% DESCRIPTION
35
+%
36
+% Display the contents of the given SOM Toolbox struct(s). Information
37
+% of several structs can be shown if the structs are given in a cell 
38
+% array. The level of detail can be varied with the second argument.
39
+% The number of different levels varies between structs. For map and 
40
+% data structs, not only the fields, but also some statistics of the 
41
+% vectors ('.data' and '.codebook' fields) is displayed. 
42
+%
43
+%   map struct
44
+%    level 1: name, dimension, topology, dimension, neigborhood function,
45
+%             mask and training status
46
+%    level 2: ..., training history
47
+%    level 3: ..., vector component names, statistics and normalization status
48
+%    level 4: ..., vector component normalizations
49
+%
50
+%   data struct:
51
+%    level 1: name, dimension, data set completeness statistics
52
+%    level 2: ..., vector component names, statistics and normalization status
53
+%    level 3: ..., vector component normalizations
54
+%    level 4: ..., label statistics
55
+%    
56
+%   topology struct: 
57
+%    level 1: all fields
58
+%
59
+%   train struct: 
60
+%    level 1: all fields
61
+%
62
+%   normalization struct: 
63
+%    level 1: method, status
64
+%    level 2: ..., parameters
65
+%    
66
+% REQUIRED INPUT ARGUMENTS
67
+%
68
+%   sS       (struct) SOM Toolbox struct 
69
+%            (cell array of structs) several structs in a cell array
70
+%  
71
+% OPTIONAL INPUT ARGUMENTS 
72
+%
73
+%   level    (scalar) detail level (1-4), default = 1
74
+%
75
+% EXAMPLES
76
+%
77
+%  som_info(sM)
78
+%  som_info(sM,4)
79
+%  som_info(sM.trainhist)
80
+%  som_info(sM.comp_norm{3})
81
+%
82
+% SEE ALSO
83
+% 
84
+%  som_set        Set fields and create SOM Toolbox structs.
85
+
86
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
87
+% http://www.cis.hut.fi/projects/somtoolbox/
88
+
89
+% Version 1.0beta ecco 110997
90
+% Version 2.0beta juuso 101199
91
+
92
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
93
+%% check arguments
94
+
95
+error(nargchk(1, 2, nargin))  % check no. of input args is correct
96
+
97
+if ~isstruct(sS),
98
+  if ~iscell(sS) | ~isstruct(sS{1}), 
99
+    error('Invalid first input argument.')
100
+  end
101
+  csS = sS;
102
+else
103
+  l = length(sS);   
104
+  csS = cell(l,1); 
105
+  for i=1:l, csS{i} = sS(i); end
106
+end
107
+
108
+if nargin<2 | isempty(level) | isnan(level), level = 1; end
109
+
110
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
111
+%% print struct information
112
+
113
+for c=1:length(csS), 
114
+ sS = csS{c};
115
+ fprintf(1,'\n');
116
+ 
117
+ switch sS.type, 
118
+ case 'som_map', 
119
+  mdim = length(sS.topol.msize);
120
+  [munits dim] = size(sS.codebook);
121
+  t    = length(sS.trainhist);  
122
+  if t==0, st='uninitialized'; 
123
+  elseif t==1, st = 'initialized';
124
+  else st = sprintf('initialized, trained %d times',t-1);
125
+  end
126
+
127
+  % level 1
128
+  fprintf(1,'Struct type                           : %s\n', sS.type);
129
+  fprintf(1,'Map name                              : %s\n', sS.name);
130
+  fprintf(1,'Input dimension                       : %d\n', dim);
131
+  fprintf(1,'Map grid size                         : ');
132
+  for i = 1:mdim - 1, fprintf(1,'%d x ',sS.topol.msize(i)); end
133
+  fprintf(1,'%d\n', sS.topol.msize(mdim));
134
+  fprintf(1,'Lattice type (rect/hexa)              : %s\n', sS.topol.lattice);
135
+  fprintf(1,'Shape (sheet/cyl/toroid)              : %s\n', sS.topol.shape);
136
+  fprintf(1,'Neighborhood type                     : %s\n', sS.neigh);
137
+  fprintf(1,'Mask                                  : ');
138
+  if dim,
139
+    for i = 1:dim-1, fprintf(1,'%d ',sS.mask(i)); end; 
140
+    fprintf(1,'%d\n',sS.mask(dim));
141
+  else fprintf(1,'\n');
142
+  end
143
+  fprintf(1,'Training status                       : %s\n', st);
144
+   
145
+  % level 1,
146
+  status = cell(dim,1);
147
+  for i=1:dim, 
148
+    n = length(sS.comp_norm{i});
149
+    if n, 
150
+      uninit = strcmp('uninit',{sS.comp_norm{i}.status});
151
+      done   = strcmp('done',{sS.comp_norm{i}.status});
152
+      undone = strcmp('undone',{sS.comp_norm{i}.status});
153
+      if sum(uninit)==n, status{i} = 'none';
154
+      elseif sum(done)==n, status{i} = 'done';
155
+      elseif sum(undone)==n, status{i} = 'undone';
156
+      else status{i} = 'partial';
157
+      end
158
+    else status{i} = 'no normalization'; end
159
+  end
160
+  if level>1, 
161
+    fprintf(1,'\nVector components\n');
162
+    M = sS.codebook;
163
+    fprintf(1,' #   name          mask     min    mean     max     std  normalization\n');
164
+    fprintf(1,' --- ------------  ----  ------  ------  ------  ------  -------------\n');
165
+    for i = 1:dim,
166
+      fprintf(1,' %-3d %-12s  %-4.2f  %6.2g  %6.2g  %6.2g  %6.2g  %s\n', ...
167
+              i,sS.comp_names{i}, sS.mask(i), ...
168
+              min(M(:,i)),mean(M(:,i)),max(M(:,i)),std(M(:,i)),status{i});
169
+    end
170
+  end
171
+
172
+  % level 3
173
+  if level>2,
174
+    fprintf(1,'\nVector component normalizations\n');
175
+    fprintf(1,' #   name          method (i=uninit,u=undone,d=done)\n');
176
+    fprintf(1,' --- ------------  ---------------------------------------\n');
177
+    for i=1:dim,  
178
+      fprintf(1,' %-3d %-12s  ',i,sS.comp_names{i});
179
+      n = length(sS.comp_norm{i}); 
180
+      for j=1:n, 
181
+        m = sS.comp_norm{i}(j).method;
182
+        s = sS.comp_norm{i}(j).status;
183
+        if strcmp(s,'uninit'), c='i'; 
184
+        elseif strcmp(s,'undone'), c='u'; 
185
+        else c='d';
186
+        end
187
+        fprintf(1,'%s[%s] ',m,c);
188
+      end
189
+      fprintf(1,'\n');
190
+    end
191
+  end
192
+  
193
+  % level 4
194
+  if level>3,
195
+    fprintf(1,'\nTraining history\n');
196
+    fprintf(1,'Algorithm Data          Trainlen Neigh.f. Radius     Alpha (type)   Date\n');
197
+    fprintf(1,'--------- ------------- -------- -------- ---------- -------------- --------------------\n');	       
198
+    for i=1:t, 
199
+      sT = sS.trainhist(i);
200
+      fprintf(1,'%8s  %13s %8d %8s %4.2f->%4.2f %5.3f (%6s) %s\n',...
201
+	      sT.algorithm,sT.data_name,sT.trainlen,...
202
+	      sT.neigh,sT.radius_ini,sT.radius_fin,sT.alpha_ini,sT.alpha_type,sT.time);      
203
+      %for j = 1:length(sT.mask)-1, fprintf(1,'%d ',sT.mask(j)); end; 
204
+      %if ~isempty(sT.mask), fprintf(1,'%d\n',sT.mask(end)); else fprintf(1,'\n'); end
205
+    end
206
+  end
207
+
208
+ case 'som_data',
209
+
210
+  [dlen dim] = size(sS.data);
211
+  if dlen*dim
212
+    if dim>1, ind = find(~isnan(sum(sS.data,2)));
213
+    else ind = find(~isnan(sS.data));
214
+    end
215
+  else ind = []; end
216
+  complete = size(sS.data(ind,:),1);
217
+  partial  = dlen - complete;
218
+  values   = prod(size(sS.data));
219
+  missing  = sum(sum(isnan(sS.data))); 
220
+
221
+  % level 1  
222
+  fprintf(1,'Struct type             : %s\n', sS.type);
223
+  fprintf(1,'Data name               : %s\n', sS.name);
224
+  fprintf(1,'Vector dimension        : %d\n', dim);
225
+  fprintf(1,'Number of data vectors  : %d\n', dlen);
226
+  fprintf(1,'Complete data vectors   : %d\n', complete);
227
+  fprintf(1,'Partial data vectors    : %d\n', partial);  
228
+  if values, r = floor(100 * (values - missing) / values); else r = 0; end
229
+  fprintf(1,'Complete values         : %d of %d (%d%%)\n', ...
230
+          values-missing, values, r); 
231
+
232
+  % level 2,
233
+  status = cell(dim,1);
234
+  for i=1:dim, 
235
+    n = length(sS.comp_norm{i});
236
+    if n, 
237
+      uninit = strcmp('uninit',{sS.comp_norm{i}.status});
238
+      done   = strcmp('done',{sS.comp_norm{i}.status});
239
+      undone = strcmp('undone',{sS.comp_norm{i}.status});
240
+      if sum(uninit)==n, status{i} = 'none';
241
+      elseif sum(done)==n, status{i} = 'done';
242
+      elseif sum(undone)==n, status{i} = 'undone';
243
+      else status{i} = 'partial';
244
+      end
245
+    else status{i} = 'no normalization'; end
246
+  end
247
+  if level>1, 
248
+    fprintf(1,'\nVector components\n');
249
+    D = sS.data;
250
+    fprintf(1,' #   name            min     mean     max     std  missing      normalization\n');
251
+    fprintf(1,' --- ------------  ------  ------  ------  ------  -----------  -------------\n');
252
+    for i = 1:dim,
253
+      known = find(~isnan(D(:,i))); 
254
+      miss = dlen-length(known);
255
+      switch length(known), 
256
+       case 0, mi = NaN; me = NaN; ma = NaN; st = NaN; 
257
+       case 1, mi = D(known,i); me = mi; ma = mi; st = 0;
258
+       otherwise, 
259
+	mi = min(D(known,i)); ma = max(D(known,i)); 
260
+	me = mean(D(known,i)); st = std(D(known,i)); 
261
+      end
262
+      fprintf(1,' %-3d %-12s  %6.2g  %6.2g  %6.2g  %6.2g  %5d (%2d%%)  %s\n', ...
263
+              i,sS.comp_names{i},mi,me,ma,st,miss,floor(100*miss/dlen),status{i});
264
+    end
265
+  end
266
+
267
+  % level 3
268
+  if level>2,
269
+    fprintf(1,'\nVector component normalizations\n');
270
+    fprintf(1,' #   name          method (i=uninit,u=undone,d=done)\n');
271
+    fprintf(1,' --- ------------  ---------------------------------------\n');
272
+    for i=1:dim,  
273
+      fprintf(1,' %-3d %-12s  ',i,sS.comp_names{i});
274
+      n = length(sS.comp_norm{i});         
275
+      for j=1:n, 
276
+        m = sS.comp_norm{i}(j).method;
277
+        s = sS.comp_norm{i}(j).status;
278
+        if strcmp(s,'uninit'), c='i'; 
279
+        elseif strcmp(s,'undone'), c='u'; 
280
+        else c='d';
281
+        end
282
+        fprintf(1,'%s[%s] ',m,c);
283
+      end
284
+      fprintf(1,'\n');
285
+    end
286
+  end
287
+
288
+  % level 4
289
+  if level>3,
290
+    m = size(sS.labels,2);
291
+    fprintf(1,'\nLabels\n');   
292
+    if isempty(sS.label_names),       
293
+      labs = {''}; freq = 0; 
294
+      for i=1:dlen*m, 
295
+	l = sS.labels{i}; 
296
+	if isempty(l), freq(1) = freq(1)+1; 
297
+	else 
298
+	  k = find(strcmp(labs,l)); 
299
+	  if isempty(k), labs{end+1} = l; freq(end+1) = 1; 
300
+	  else freq(k)=freq(k)+1;
301
+	  end
302
+	end
303
+      end
304
+      emp = freq(1); 
305
+      uni = length(freq)-1;
306
+      if uni>0, tot = sum(freq(2:end)); else tot = 0; end
307
+      fprintf(1,' Total: %d\n Empty: %d\n Unique: %d\n',tot,emp,uni);
308
+    else
309
+      for j=1:m, 
310
+	labs = {''}; freq = 0; 
311
+	for i=1:dlen, 
312
+	  l = sS.labels{i,j}; 
313
+	  if isempty(l), freq(1) = freq(1)+1; 
314
+	  else 
315
+	    k = find(strcmp(labs,l)); 
316
+	    if isempty(k), labs{end+1} = l; freq(end+1) = 1; 
317
+	    else freq(k)=freq(k)+1;
318
+	    end
319
+	  end
320
+	end
321
+	emp = freq(1); 
322
+	uni = length(freq)-1;
323
+	if uni>0, tot = sum(freq(2:end)); else tot = 0; end
324
+	fprintf(1,' [%s] Total / empty / unique: %d / %d / %d\n', ...
325
+		sS.label_names{j},tot,emp,uni); 
326
+      end
327
+    end
328
+  end
329
+  
330
+ case 'som_topol', 
331
+
332
+  mdim = length(sS.msize);
333
+ 
334
+  % level 1
335
+  fprintf(1,'Struct type                           : %s\n',sS.type);
336
+  fprintf(1,'Map grid size                         : ');
337
+  for i = 1:mdim - 1, fprintf(1,'%d x ',sS.msize(i)); end
338
+  fprintf(1,'%d\n', sS.msize(mdim));
339
+  fprintf(1,'Lattice type (rect/hexa)              : %s\n', sS.lattice);
340
+  fprintf(1,'Shape (sheet/cyl/toroid)              : %s\n', sS.shape);
341
+
342
+ case 'som_train', 
343
+
344
+  % level 1
345
+  fprintf(1,'Struct type                           : %s\n',sS.type);
346
+  fprintf(1,'Training algorithm                    : %s\n',sS.algorithm);
347
+  fprintf(1,'Training data                         : %s\n',sS.data_name);
348
+  fprintf(1,'Neighborhood function                 : %s\n',sS.neigh);
349
+  fprintf(1,'Mask                                  : ');
350
+  dim = length(sS.mask);
351
+  if dim, 
352
+    for i = 1:dim-1, fprintf(1,'%d ',sS.mask(i)); end; 
353
+    fprintf(1,'%d\n',sS.mask(end));
354
+  else fprintf(1,'\n'); end
355
+  fprintf(1,'Initial radius                        : %-6.1f\n',sS.radius_ini);
356
+  fprintf(1,'Final radius                          : %-6.1f\n',sS.radius_fin);
357
+  fprintf(1,'Initial learning rate (alpha)         : %-6.1f\n',sS.alpha_ini);
358
+  fprintf(1,'Alpha function type (linear/inv)      : %s\n',sS.alpha_type);
359
+  fprintf(1,'Training length                       : %d\n',sS.trainlen);
360
+  fprintf(1,'When training was done                : %s\n',sS.time);
361
+
362
+  case 'som_norm', 
363
+   
364
+   % level 1
365
+   fprintf(1,'Struct type                           : %s\n',sS.type);
366
+   fprintf(1,'Normalization method                  : %s\n',sS.method);
367
+   fprintf(1,'Status                                : %s\n',sS.status);
368
+   
369
+   % level 2
370
+   if level>1, 
371
+     fprintf(1,'Parameters:\n');
372
+     sS.params
373
+   end
374
+   
375
+  case 'som_grid', 
376
+   
377
+   % level 1
378
+   fprintf(1,'Struct type                           : %s\n',sS.type);
379
+   if ischar(sS.neigh), 
380
+     fprintf(1,'Connections                           : [%d %d], %s, %s\n',...
381
+	     sS.msize(1),sS.msize(2),sS.neigh,sS.shape);
382
+   else
383
+     fprintf(1,'Connections                           : [%d %d] %d lines\n',...
384
+	     sS.msize(1),sS.msize(2),sum(sS.neigh));
385
+   end
386
+   fprintf(1,'Line                                  : %s\n',sS.line);
387
+   if length(sS.marker)==1, 
388
+     fprintf(1,'Marker                                : %s\n',sS.marker);
389
+   else
390
+     fprintf(1,'Marker                                : varies\n');
391
+   end
392
+   fprintf(1,'Surf                                  : ');
393
+   if isempty(sS.surf), fprintf(1,'off\n'); else fprintf(1,'on\n'); end
394
+   fprintf(1,'Labels                                : ');
395
+   if isempty(sS.label), fprintf(1,'off\n'); 
396
+   else fprintf(1,'on (%d)\n',sS.labelsize); end
397
+   
398
+ end
399
+
400
+ fprintf(1,'\n');
401
+end
402
+
403
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,145 @@
1
+function [codes,clusters,err] = som_kmeans(method, D, k, epochs, verbose)
2
+
3
+% SOM_KMEANS K-means algorithm.
4
+%
5
+% [codes,clusters,err] = som_kmeans(method, D, k, [epochs], [verbose])
6
+%
7
+%  Input and output arguments ([]'s are optional):  
8
+%    method     (string) k-means algorithm type: 'batch' or 'seq'
9
+%    D          (matrix) data matrix
10
+%               (struct) data or map struct
11
+%    k          (scalar) number of centroids
12
+%    [epochs]   (scalar) number of training epochs
13
+%    [verbose]  (scalar) if <> 0 display additonal information
14
+%
15
+%    codes      (matrix) codebook vectors
16
+%    clusters   (vector) cluster number for each sample
17
+%    err        (scalar) total quantization error for the data set
18
+%
19
+% See also KMEANS_CLUSTERS, SOM_MAKE, SOM_BATCHTRAIN, SOM_SEQTRAIN.
20
+
21
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
22
+% Function has been renamed by Kimmo Raivio, because matlab65 also have 
23
+% kmeans function 1.10.02
24
+%% input arguments
25
+
26
+if isstruct(D), 
27
+    switch D.type, 
28
+    case 'som_map', data = D.codebook; 
29
+    case 'som_data', data = D.data; 
30
+    end 
31
+else 
32
+    data = D; 
33
+end
34
+[l dim]   = size(data);
35
+
36
+if nargin < 4 | isempty(epochs) | isnan(epochs), epochs = 100; end
37
+if nargin < 5, verbose = 0; end
38
+
39
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
40
+%% action
41
+
42
+rand('state', sum(100*clock)); % init rand generator
43
+
44
+lr = 0.5;                      % learning rate for sequential k-means
45
+temp      = randperm(l);
46
+centroids = data(temp(1:k),:);
47
+res       = zeros(k,l);
48
+clusters  = zeros(1, l);
49
+
50
+if dim==1, 
51
+    [codes,clusters,err] = scalar_kmeans(data,k,epochs); 
52
+    return; 
53
+end
54
+
55
+switch method
56
+ case 'seq',
57
+  len = epochs * l;
58
+  l_rate = linspace(lr,0,len);
59
+  order  = randperm(l);
60
+  for iter = 1:len
61
+    x  = D(order(rem(iter,l)+1),:);                   
62
+    dx = x(ones(k,1),:) - centroids; 
63
+    [dist nearest] = min(sum(dx.^2,2)); 
64
+    centroids(nearest,:) = centroids(nearest,:) + l_rate(iter)*dx(nearest,:);
65
+  end
66
+  [dummy clusters] = min(((ones(k, 1) * sum((data.^2)', 1))' + ...
67
+			 ones(l, 1) * sum((centroids.^2)',1) - ...
68
+			 2.*(data*(centroids')))');
69
+
70
+ case 'batch',
71
+  iter      = 0;
72
+  old_clusters = zeros(k, 1);
73
+  while iter<epochs
74
+    
75
+    [dummy clusters] = min(((ones(k, 1) * sum((data.^2)', 1))' + ...
76
+			   ones(l, 1) * sum((centroids.^2)',1) - ...
77
+			   2.*(data*(centroids')))');
78
+
79
+    for i = 1:k
80
+      f = find(clusters==i);
81
+      s = length(f);
82
+      if s, centroids(i,:) = sum(data(f,:)) / s; end
83
+    end
84
+
85
+    if iter
86
+      if sum(old_clusters==clusters)==0
87
+	if verbose, fprintf(1, 'Convergence in %d iterations\n', iter); end
88
+	break; 
89
+      end
90
+    end
91
+
92
+    old_clusters = clusters;
93
+    iter = iter + 1;
94
+  end
95
+  
96
+  [dummy clusters] = min(((ones(k, 1) * sum((data.^2)', 1))' + ...
97
+			  ones(l, 1) * sum((centroids.^2)',1) - ...
98
+			  2.*(data*(centroids')))');
99
+ otherwise,
100
+  fprintf(2, 'Unknown method\n');
101
+end
102
+
103
+err = 0;
104
+for i = 1:k
105
+  f = find(clusters==i);
106
+  s = length(f);
107
+  if s, err = err + sum(sum((data(f,:)-ones(s,1)*centroids(i,:)).^2,2)); end
108
+end
109
+
110
+codes = centroids;
111
+return; 
112
+
113
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
114
+
115
+function [y,bm,qe] = scalar_kmeans(x,k,maxepochs)
116
+
117
+    nans = ~isfinite(x);
118
+    x(nans) = []; 
119
+    n = length(x); 
120
+    mi = min(x); ma = max(x)
121
+    y = linspace(mi,ma,k)'; 
122
+    bm = ones(n,1); 
123
+    bmold = zeros(n,1); 
124
+    i = 0; 
125
+    while ~all(bm==bmold) & i<maxepochs, 
126
+        bmold  = bm;  
127
+        [c bm] = histc(x,[-Inf; (y(2:end)+y(1:end-1))/2; Inf]);
128
+        y      = full(sum(sparse(bm,1:n,x,k,n),2));
129
+        zh     = (c(1:end-1)==0);
130
+        y(~zh) = y(~zh)./c(~zh);
131
+        inds   = find(zh)';
132
+        for j=inds, if j==1, y(j) = mi; else y(j) = y(j-1) + eps; end, end         
133
+        i=i+1;
134
+    end
135
+    if i==maxepochs, [c bm] = histc(x,[-Inf; (y(2:end)+y(1:end-1))/2; Inf]); end
136
+    if nargout>2, qe = sum(abs(x-y(bm)))/n; end
137
+    if any(nans),
138
+        notnan = find(~nans); n = length(nans);
139
+        y  = full(sparse(notnan,1,y ,n,1)); y(nans)  = NaN;  
140
+        bm = full(sparse(notnan,1,bm,n,1)); bm(nans) = NaN;
141
+        if nargout>2, qe = full(sparse(notnan,1,qe,n,1)); qe(nans) = NaN; end
142
+    end 
143
+       
144
+    return; 
145
+
... ...
@@ -0,0 +1,139 @@
1
+function [color,best,kmeans]=som_kmeanscolor(sM,C,initRGB,contrast)
2
+
3
+% SOM_KMEANSCOLOR Map unit color code according to K-means clustering
4
+%
5
+% [color, best, kmeans] = som_kmeanscolor(sM, C, [initRGB],[contrast])
6
+%
7
+%  color        = som_kmeanscolor(sM,15,som_colorcode(sM,'rgb1'),'enhance');
8
+%  [color,best] = som_kmeanscolor(sM,15,[],'normal');
9
+%  
10
+%  Input and output arguments ([]'s are optional):
11
+%   sM       (struct) map struct
12
+%   C        (scalar) maximum number of clusters
13
+%   initRGB  (string, matrix) color code string accepted by SOM_COLORCODE
14
+%                     or an Mx3 matrix of RGB triples, where M is the number
15
+%                     of map units. Default: SOM_COLORCODEs default
16
+%   contrast (string) 'flat', 'enhanced' color contrast mode, default:
17
+%                     'enhanced'
18
+%
19
+%   color    (matrix) MxCx3 of RGB triples
20
+%   best     (scalar) index for "best" clustering according to 
21
+%                     Davies-Boulding index; color(:,:,best) includes the 
22
+%                     corresponding color code.
23
+%   kmeans   (cell)   output of KMEANS_CLUSTERS in a cell array.
24
+% 
25
+% The function gives a set of color codings according to K-means 
26
+% clustering. For clustering, it uses function KMEANS_CLUSTERS for map units, 
27
+% and it calculates color codings for 1,2,...,C clusters. 
28
+% The idea of coloring is that the color of a cluster is the mean of the 
29
+% original colors (RGB values) of the map units belonging to that cluster, 
30
+% see SOM_CLUSTERCOLOR. The original colors are defined by  SOM_COLORCODE
31
+% by default. Input 'contrast' simply specifies whether or not 
32
+% to linearly redistribute R,G, and B values so that minimum is 0 and 
33
+% maximum 1 ('enahanced')  or to use directly the output of 
34
+% SOM_CLUSTERCOLOR ('flat'). KMEANS_CLUSTERS uses certain heuristics to 
35
+% select the best of 5 trials for each  number of clusters. Evaluating the 
36
+% clustering multiple times may take some time. 
37
+%
38
+% EXAMPLE
39
+% 
40
+%  load iris; % or any other map struct sM 
41
+%  [color,b]=som_kmeanscolor(sM,10);
42
+%  som_show(sM,'color',color,'color',{color(:,:,b),'"Best clustering"');
43
+% 
44
+% See also SOM_SHOW, SOM_COLORCODE, SOM_CLUSTERCOLOR, KMEANS_CLUSTERS
45
+
46
+% Contributed to SOM Toolbox 2.0, April 1st, 2000 by Johan Himberg
47
+% Copyright (c) by Johan Himberg
48
+% http://www.cis.hut.fi/projects/somtoolbox/
49
+
50
+% corrected help text 11032005 johan
51
+
52
+%%% Check number of inputs
53
+
54
+error(nargchk(2, 4, nargin));  % check no. of input args
55
+
56
+%%% Check input args & set defaults
57
+
58
+if isstruct(sM) & isfield(sM,'type') & strcmp(sM.type,'som_map'),
59
+   [tmp,lattice,msize]=vis_planeGetArgs(sM);
60
+   munits=prod(msize);
61
+   if length(msize)>2 
62
+      error('Does not work with 3D maps.')
63
+   end
64
+else
65
+   error('Map struct requires for first input argument!');
66
+end
67
+
68
+if ~vis_valuetype(C,{'1x1'}),
69
+   error('Scalar value expect for maximum number of clusters.');
70
+end
71
+
72
+% check initial color coding
73
+if nargin<3 | isempty(initRGB)
74
+   initRGB=som_colorcode(sM);
75
+end
76
+
77
+% check contrast checking
78
+if nargin<4 | isempty(contrast),
79
+   contrast='enhanced';
80
+end
81
+
82
+if ~ischar(contrast),
83
+   error('String input expected for input arg. ''contrast''.');
84
+else
85
+   switch lower(contrast)
86
+   case {'flat','enhanced'}
87
+      ;
88
+   otherwise 
89
+      error(['''flat'' or ''enhanced'' expected for '...
90
+            'input argument ''contrast''.']);
91
+   end
92
+end
93
+
94
+if ischar(initRGB),
95
+   try 
96
+      initRGB=som_colorcode(sM,initRGB);
97
+   catch
98
+      error(['Color code ' initRGB ...
99
+            'was not recognized by SOM_COLORCODE.']);
100
+   end
101
+elseif vis_valuetype(initRGB,{'nx3rgb',[munits 3]},'all'),
102
+   ;
103
+else
104
+   error(['The initial color code must be a string '...
105
+         'or an Mx3 matrix of RGB triples.']);
106
+end
107
+
108
+%%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
109
+
110
+disp('Wait...');
111
+[c,p,err,ind]=kmeans_clusters(sM,C,5,0); % use 5 trials, verbose off
112
+
113
+% Store outputs to kmeans
114
+kmeans{1}=c; 
115
+kmeans{2}=p; 
116
+kmeans{3}=err; 
117
+kmeans{4}=ind;
118
+
119
+%%% Build output
120
+color=som_clustercolor(sM,cat(2,p{:}),initRGB);
121
+[tmp,best]=min(ind);
122
+
123
+switch contrast
124
+case 'flat'
125
+   ;
126
+case 'enhanced'
127
+   warning off;
128
+   ncolor=maxnorm(color);
129
+   ncolor(~isfinite(ncolor))=color(~isfinite(ncolor));
130
+   color=ncolor;
131
+   warning on;
132
+end
133
+
134
+%%% Subfunctions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
135
+function X=maxnorm(x)
136
+% normalize columns of x between [0,1]
137
+
138
+x=x-repmat(min(x),[size(x,1) 1 1]);
139
+X=x./repmat(max(x),[size(x,1) 1 1]);
... ...
@@ -0,0 +1,193 @@
1
+function [color,centroids]=som_kmeanscolor2(mode,sM,C,initRGB,contrast,R)
2
+
3
+% SOM_KMEANSCOLOR2 Color codes a SOM according to averaged or best K-means clustering
4
+%
5
+% color = som_kmeanscolor2('average',sM, C, [initRGB], [contrast],[R]) 
6
+%
7
+%  color=som_kmeanscolor2('average',sM,[2 4 8 16],som_colorcode(sM,'rgb1'),'enhanced');
8
+%  [color,centroid]=som_kmeanscolor2('best',sM,15,[],'flat',R);
9
+%  
10
+%  Input and output arguments ([]'s are optional):
11
+%
12
+%   mode       (string) 'average' or 'best', defalut: 'average'
13
+%   sM         (struct) a map struct
14
+%   C          (vector) number of clusters
15
+%   [initRGB]  (string, matrix) a color code string accepted by SOM_COLORCODE
16
+%               or an Mx3 matrix of RGB triples, where M is the number
17
+%               of map units. Default: SOM_COLORCODEs default
18
+%   [contrast] (string) 'flat', 'enhanced' color contrast mode, default:
19
+%               'enhanced'.
20
+%   [R]        (scalar) number of K-means trials, default: 30.
21
+%   color      (matrix) Mx3xC of RGB triples
22
+%   centroid   (array of matrices) centroid{i} includes codebook for the best
23
+%               k-means for C(i) clusters, i.e. the cluster centroids corresponding to
24
+%               the color code color(:,:,i).
25
+% 
26
+% The function gives a set of color codes for the SOM according to K-means 
27
+% clustering. It has two operation modes: 
28
+% 
29
+% 'average': The idea of coloring is that the color of the units belonging to the same 
30
+%   cluster is the  mean of the original RGB values (see SOM_COLORCODE) of the map units 
31
+%   belonging to the cluster (see SOM_CLUSTERCOLOR). The K-means clustering is made,
32
+%   by default, 30 times and the resulting color codes are averaged for
33
+%   each specified number of clusters C(i), i=1,...,k. In a way, the resulting averaged color 
34
+%   codes reflect the stability of the K-means clustering made on the map units.
35
+%
36
+% 'best': runs the k-means R times for C(i), i=1,...,n clusters as in previous mode, 
37
+%   but instead of averaging all the R color codes, it picks the one that corresponds to the 
38
+%   best k-means clustering for each C(i). The 'best' is the one with the lowest 
39
+%   quantization error. The result may differ from run to run.
40
+%
41
+% EXAMPLE
42
+% 
43
+%  load iris; % or any other map struct sM 
44
+%  color=som_kmeanscolor2('average',sM,[2:6]);
45
+%  som_show(sM,'umat','all','color',color);
46
+% 
47
+% See also SOM_KMEANS, SOM_SHOW, SOM_COLORCODE, SOM_CLUSTERCOLOR, SOM_KMEANSCOLOR
48
+
49
+% Contributed to SOM Toolbox 2.0, 2001 February by Johan Himberg
50
+% Copyright (c) by Johan Himberg
51
+% http://www.cis.hut.fi/projects/somtoolbox/
52
+
53
+%%% Check number of inputs
54
+
55
+error(nargchk(3, 6, nargin));  % check no. of input args
56
+
57
+%%% Check input args & set defaults
58
+
59
+if ~vis_valuetype(mode,{'string'}),
60
+   error('Mode must be a string.');
61
+end
62
+switch lower(mode),
63
+case{'average','best'}
64
+   ;
65
+otherwise
66
+   error('Mode must be string ''average'' or ''best''.');
67
+end
68
+
69
+if isstruct(sM) & isfield(sM,'type') & strcmp(sM.type,'som_map'),
70
+   [tmp,lattice,msize]=vis_planeGetArgs(sM);
71
+   munits=prod(msize);
72
+   if length(msize)>2 
73
+      error('Does not work with 3D maps.')
74
+   end
75
+else
76
+   error('Map struct required for the second input argument!');
77
+end
78
+
79
+if ~vis_valuetype(C,{'1xn','nx1'}),
80
+   error('Vector value expected for cluster number.');
81
+end
82
+
83
+% Round C and check
84
+C=round(C(:)');
85
+
86
+if any(C<2),
87
+   error('Cluster number must be 2 or more.');
88
+end
89
+
90
+% check initial color coding
91
+if nargin<4 | isempty(initRGB)
92
+   initRGB=som_colorcode(sM);
93
+end
94
+
95
+% check contrast checking
96
+if nargin<5 | isempty(contrast),
97
+   contrast='enhanced';
98
+end
99
+
100
+if ~ischar(contrast),
101
+   error('String input expected for input arg. ''contrast''.');
102
+else
103
+   switch lower(contrast)
104
+   case {'flat','enhanced'}
105
+      ;
106
+   otherwise 
107
+      error(['''flat'' or ''enhanced'' expected for '...
108
+            'input argument ''contrast''.']);
109
+   end
110
+end
111
+
112
+if ischar(initRGB),
113
+   try 
114
+      initRGB=som_colorcode(sM,initRGB);
115
+   catch
116
+      error(['Color code ' initRGB ...
117
+            'was not recognized by SOM_COLORCODE.']);
118
+   end
119
+elseif vis_valuetype(initRGB,{'nx3rgb',[munits 3]},'all'),
120
+   ;
121
+else
122
+   error(['The initial color code must be a string '...
123
+         'or an Mx3 matrix of RGB triples.']);
124
+end
125
+
126
+if nargin<6|isempty(R),
127
+   R=30;
128
+end
129
+
130
+if ~vis_valuetype(R,{'1x1'}),
131
+   error('''R'' must be scalar.');
132
+end
133
+
134
+%%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
135
+
136
+disp('Wait...');
137
+index=0; hit_=zeros(munits,munits);
138
+
139
+switch mode,
140
+   %% Averaged k-means coloring
141
+case 'average'
142
+   for k=C,
143
+      disp(['Running K-means for ' num2str(k) ' clusters...']); 
144
+      color_=zeros(munits,3);
145
+      colord_=color_;
146
+      % Average R k-means colorings for C clusters
147
+      for j=1:R,
148
+         [dummy,c]=som_kmeans('batch',sM,k,100,0); % max 100 iterations, verbose off 
149
+         color_=color_+som_clustercolor(sM,c,initRGB);
150
+      end
151
+      index=index+1;
152
+      color(:,:,index)=color_./R;
153
+   end
154
+   
155
+   %% coloring for 'best' k-means coloring
156
+case 'best'
157
+   for k=C,
158
+      disp(['Running K-means for ' num2str(k) ' clusters...']);
159
+      c=[];err=Inf; div=[];
160
+      %% look for the best k-means among R trials
161
+      for i=1:R,
162
+         [c_,div_,err_(i)]=som_kmeans('batch',sM,k,100,0); % max 100 iterations, verbose off
163
+         if err_(i)<err, 
164
+            err=err_(i); c=c_; div=div_; 
165
+         end
166
+      end
167
+      % record the 'best' k-means for C clusters
168
+      index=index+1;
169
+      color(:,:,index)=som_clustercolor(sM,div,initRGB);
170
+      centroid{index}=c;   
171
+   end
172
+end
173
+
174
+%%% Build output
175
+
176
+switch contrast
177
+case 'flat'
178
+   ;
179
+case 'enhanced'
180
+   warning off;
181
+   ncolor=maxnorm(color);
182
+   ncolor(~isfinite(ncolor))=color(~isfinite(ncolor));
183
+   color=ncolor;
184
+   warning on;
185
+end
186
+
187
+
188
+%%% Subfunctions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
189
+function X=maxnorm(x)
190
+% normalize columns of x between [0,1]
191
+
192
+x=x-repmat(min(x),[size(x,1) 1 1]);
193
+X=x./repmat(max(x),[size(x,1) 1 1]);
... ...
@@ -0,0 +1,283 @@
1
+function [sTo] = som_label(sTo, mode, inds, labels)
2
+
3
+%SOM_LABEL Give/clear labels to/from map or data struct.
4
+%
5
+% sTo = som_label(sTo, mode, inds [, labels])
6
+% 
7
+%   sD = som_label(sD,'add',20,'a_label');
8
+%   sM = som_label(sM,'replace',[2 4],'a_label');
9
+%   sM = som_label(sM,'add',som_bmus(sM,x),'BMU');
10
+%   sD = som_label(sD,'prune',[1:10]');
11
+%   sM = som_label(sM,'clear','all');         
12
+%
13
+%  Input and output arguments ([]'s are optional): 
14
+%   sTo      (struct) data or map struct to which the labels are put 
15
+%   mode     (string) 'add' or 'replace' or 'prune' or 'clear'
16
+%   inds     (vector) indeces of the vectors to which the labels
17
+%                     are put. Note: this must be a column vector!
18
+%            (matrix) subscript indeces to the '.labels' field. The vector 
19
+%                     is given by the first index (e.g. inds(i,1)). 
20
+%            (string) for 'prune' and 'clear' modes, the string 'all'
21
+%                     means that all vectors should be pruned/cleared
22
+%   [labels]          The labels themselves. The number of rows much match 
23
+%                     the number of given indeces, except if there is either
24
+%                     only one index or only one label. If mode is
25
+%                     'prune' or 'clear', labels argument is ignored.
26
+%            (string) Label.
27
+%            (string array) Each row is a label.
28
+%            (cell array of strings) All labels in a cell are handled 
29
+%                     as a group and are applied to the same vector given 
30
+%                     on the corresponding row of inds.
31
+%
32
+% Note: If there is only one label/index, it is used for each specified
33
+% index/label.
34
+%
35
+% For more help, try 'type som_label' or check out online documentation.
36
+% See also  SOM_AUTOLABEL, SOM_SHOW_ADD, SOM_SHOW.
37
+
38
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
39
+%
40
+% som_label
41
+%
42
+% PURPOSE
43
+%
44
+% Add (or remove) labels to (from) map and data structs.
45
+%
46
+% SYNTAX
47
+%
48
+%  sTo = som_label(sTo, 'clear', inds)
49
+%  sTo = som_label(sTo, 'prune', inds)
50
+%  sTo = som_label(sTo, 'add', inds, labels)
51
+%  sTo = som_label(sTo, 'replace', inds, labels)
52
+%
53
+% DESCRIPTION
54
+%
55
+% This function can be used to give and remove labels in map and data
56
+% structs. Of course the same operation could be done by hand, but this
57
+% function offers an alternative and hopefully slightly user-friendlier
58
+% way to do it.
59
+%
60
+% REQUIRED INPUT ARGUMENTS
61
+%
62
+%   sTo    (struct) data or map struct to which the labels are put 
63
+%   mode   (string) The mode of operation. 
64
+%                    'add'     : adds the given labels
65
+%                    'clear'   : removes labels
66
+%                    'replace' : replaces current labels with given
67
+%                                labels; basically same as 'clear'
68
+%                                followed by 'add'
69
+%                    'prune'   : removes empty labels ('') from between
70
+%                                non-empty labels, e.g. if the labels of
71
+%                                a vector were {'A','','','B','','C'}
72
+%                                they'd become {'A','B','C'}. Some empty
73
+%                                labels may be left at the end of the list.
74
+%
75
+%   inds            Identifies the vectors to which the operation
76
+%                   (given by mode) is applied to.
77
+%          (vector) Linear indexes of the vectors, size n x 1.
78
+%                   Notice! This should be a column vector!
79
+%          (matrix) The labels are in a cell matrix. By giving matrix 
80
+%                   argument for inds, you can address this matrix
81
+%                   directly. The first index gives the vector and the
82
+%                   second index the vertical position of the label in
83
+%                   the labels array. Size n x 2, where n is the 
84
+%                   number of labels. 
85
+%          (string) for 'prune' and 'clear' modes, the string 'all'
86
+%                   means that all vectors should be pruned/cleared
87
+%
88
+% OPTIONAL INPUT ARGUMENTS 
89
+%
90
+%   [labels]        The labels themselves. The number of rows much match 
91
+%                   the number of given indeces, except if there is either
92
+%                   only one index or only one label. 
93
+%          (string) Label, e.g. 'label'
94
+%          (string array) Each row is a label, 
95
+%                   e.g. ['label1'; 'label2'; 'label3']
96
+%          (cell array of strings) All labels in a cell are handled 
97
+%                   as a group and are applied to the same vector given 
98
+%                   on the corresponding row of inds.
99
+%                   e.g. three labels: {'label1'; 'label2'; 'label3'}
100
+%                   e.g. a group of labels: {'label1', 'label2', 'label3'}
101
+%                   e.g. three groups: {{'la1'},{'la21','la22'},{'la3'}
102
+%
103
+% OUTPUT ARGUMENTS
104
+% 
105
+%   sTo    (struct) the given data/map struct with modified labels
106
+% 
107
+% EXAMPLES
108
+%
109
+%  This is the basic way to add a label to map structure:
110
+%   sMap = som_label(sMap,'add',3,'label');
111
+%
112
+%  The following examples have identical results: 
113
+%   sMap = som_label(sMap,'add',[4; 13], ['label1'; 'label2']);
114
+%   sMap = som_label(sMap,'add',[4; 13], {{'label1'};{'label2'}});
115
+%
116
+%  Labeling the BMU of a vector x (and removing any old labels)
117
+%   sMap = som_label(sMap,'replace',som_bmus(sMap,x),'BMU');
118
+%
119
+%  Pruning labels 
120
+%   sMap = som_label(sMap,'prune','all');
121
+%
122
+%  Clearing labels from a struct
123
+%   sMap = som_label(sMap,'clear','all');
124
+%   sMap = som_label(sMap,'clear',[1:4, 9:30]');
125
+%
126
+% SEE ALSO
127
+% 
128
+%  som_autolabel   Automatically label a map/data set.
129
+%  som_show        Show map planes.
130
+%  som_show_add    Add for example labels to the SOM_SHOW visualization.
131
+
132
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
133
+% http://www.cis.hut.fi/projects/somtoolbox/
134
+
135
+% Version 2.0beta juuso 101199
136
+
137
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
138
+%% check arguments
139
+
140
+error(nargchk(3, 4, nargin));  % check no. of input args is correct
141
+
142
+% sTo
143
+switch sTo.type, 
144
+case 'som_map',  [dlen dim] = size(sTo.codebook);
145
+case 'som_data', [dlen dim] = size(sTo.data);
146
+end
147
+maxl = size(sTo.labels,2); % maximum number of labels for a single vector
148
+
149
+% inds
150
+if ischar(inds) & strcmp(inds,'all'), 
151
+  inds = [1:dlen]'; 
152
+end
153
+if length(inds)>2 & size(inds,2)>2, inds = inds'; end
154
+ni = size(inds,1);
155
+n = ni; 
156
+
157
+% labels
158
+if nargin==4, 
159
+  % convert labels to a cell array of cells
160
+  if ischar(labels), labels = cellstr(labels); end
161
+  if iscellstr(labels), 
162
+    tmplab = labels; 
163
+    nl = size(labels,1);
164
+    labels = cell(nl,1);  
165
+    for i=1:nl, 
166
+      if ~iscell(tmplab{i}) 
167
+	if ~isempty(tmplab{i}), labels{i} = tmplab(i,:);
168
+	else labels{i} = {}; end
169
+      else
170
+	labels(i) = tmplab(i);
171
+      end
172
+    end
173
+    clear tmplab;
174
+  end
175
+  nl = size(labels,1);    
176
+end
177
+
178
+% the case of a single label/index
179
+if any(strcmp(mode,{'add','replace'})),
180
+  n = max(nl,ni);   
181
+  if n>1, 
182
+    if ni==1, 
183
+      inds = zeros(n,1)+inds(1); 
184
+    elseif nl==1,
185
+      label = labels{1}; 
186
+      labels = cell(n,1); 
187
+      for i=1:n, labels{i} = label; end
188
+    elseif ni ~= nl,
189
+      error('The number of labels and indexes does not match.'); 
190
+    end
191
+  end
192
+end
193
+
194
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
195
+%% action
196
+
197
+switch mode,   
198
+ case 'clear',
199
+  if size(inds,2)>2, 
200
+    inds = inds(find(inds(:,2)<=maxl),:); % ignore if subindex is out-of-range
201
+    inds = sub2ind([dlen maxl],inds(:,1),inds(:,2)); 
202
+    sTo.labels{inds} = []; 
203
+  else
204
+    sTo.labels(inds,:) = cell(n,maxl); 
205
+  end
206
+ case 'prune', 
207
+  if size(inds,2)==1, 
208
+    % subindex gives the index from which the pruning is started
209
+    inds = [inds, ones(n,1)]; % from 1 by default
210
+  end 
211
+  select = ones(1,maxl);     
212
+  for i=1:n, 
213
+    v = inds(i,1); s = inds(i,2); select(:) = 1; 
214
+    for j=s:maxl, select(j) = ~isempty(sTo.labels{v,j}); end
215
+    if ~all(select), 
216
+      labs = cell(1,maxl); 
217
+      labs(1:sum(select)) = sTo.labels(v,find(select));
218
+      sTo.labels(v,:) = labs; 
219
+    end
220
+  end
221
+ case 'add', 
222
+  if size(inds,2)==1, 
223
+    % subindex gives the index from which the adding is started
224
+    inds = [inds, ones(n,1)]; % from 1 by default
225
+  end 
226
+  for i=1:n, 
227
+    v = inds(i,1); s = inds(i,2); l = length(labels{i});
228
+    for j=1:l, 
229
+      while s<=size(sTo.labels,2) & ~isempty(sTo.labels{v,s}), s=s+1; end
230
+      sTo.labels{v,s} = labels{i}{j}; 
231
+      s=s+1; 
232
+    end
233
+  end
234
+ case 'replace', 
235
+  if size(inds,2)==1, 
236
+    % subindex gives the index from which the replacing is started
237
+    inds = [inds, ones(n,1)]; % from 1 by default
238
+  end 
239
+  for i=1:n, 
240
+    v = inds(i,1); s = inds(i,2); l = length(labels(i)); 
241
+    for j=1:l, sTo.labels{v,s-1+j} = labels{i}{j}; end 
242
+  end
243
+ otherwise
244
+  error(['Unrecognized mode: ' mode]);
245
+end
246
+
247
+sTo.labels = remove_empty_columns(sTo.labels);
248
+
249
+[dlen maxl] = size(sTo.labels);
250
+for i=1:dlen, 
251
+  for j=1:maxl, 
252
+    if isempty(sTo.labels{i,j}) & ~ischar(sTo.labels{i,j}), 
253
+      sTo.labels{i,j} = ''; 
254
+    end
255
+  end
256
+end
257
+
258
+return;
259
+
260
+
261
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
262
+%% subfunctions
263
+
264
+function labels = remove_empty_columns(labels)
265
+
266
+  [dlen maxl] = size(labels);
267
+  
268
+  % find which columns are empty
269
+  cols = zeros(1,maxl); 
270
+  for i=1:dlen, 
271
+    for j=1:maxl,
272
+      cols(j) = cols(j) + ~isempty(labels{i,j}); 
273
+    end
274
+  end
275
+  while maxl>0 & cols(maxl)==0, maxl = maxl-1; end % check starting from end
276
+
277
+  if maxl==0, labels = cell(dlen,1); 
278
+  elseif maxl<size(labels,2), labels = labels(:,1:maxl); 
279
+  else % ok
280
+  end
281
+  % end of remove_empty_columns
282
+
283
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,70 @@
1
+function [nos,names] = som_label2num(L)
2
+
3
+%SOM_LABEL2NUM Recodes textual data labels to interger class labels 
4
+%
5
+% [class,names]=class2num(L)
6
+%
7
+%  [class,names]=class2num(sData)
8
+%  [class,names]=class2num(sMap)
9
+%  [class,names]=class2num(sData.labels);
10
+%
11
+%  Input and output arguments ([]'s are optional): 
12
+%   
13
+%   L      (map struct, data struct, 
14
+%           Nx1 cell array of strings, 
15
+%           a Nxn char array)           textual labels
16
+%   class  (vector) Nx1 vector of integers where N is the number of original text labels
17
+%   names  (cell)   kx1 array of strings where names(i) correspons to integer label i
18
+%
19
+% See also KNN
20
+
21
+% Contributed to SOM Toolbox 2.0, October 29th, 2000 by Johan Himberg
22
+% Copyright (c) by Johan Himberg
23
+% http://www.cis.hut.fi/projects/somtoolbox/
24
+
25
+% Version 2.0beta Johan 291000
26
+
27
+%% Init %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
28
+
29
+if isstruct(L);
30
+   if isfield(L,'type') & ischar(L.type),
31
+      ;
32
+   else
33
+      error('Invalid map/data struct?');
34
+   end
35
+   switch L.type
36
+   case {'som_map', 'som_data'}
37
+      class=L.labels(:,1);
38
+   otherwise error('Invalid map/data struct?');
39
+   end
40
+elseif vis_valuetype(L,{'cellcolumn_of_char'}),
41
+   class=L;
42
+elseif vis_valuetype(L,{'chararray'}),
43
+   class=cellstr(L);   
44
+else
45
+   error('Input must be an Nx1 cell array of strings, a char array, a map struct or a data struct.');   
46
+end
47
+
48
+names = {};
49
+nos = zeros(length(class),1);
50
+for i=1:length(class),
51
+   if ~isempty(class{i}) & ~any(strcmp(class{i},names)),
52
+      names=cat(1,names,class(i));
53
+   end
54
+end
55
+
56
+tmp_nos = (1:length(names))';
57
+for i=1:length(class),
58
+   if ~isempty(class{i}),
59
+      nos(i,1) = find(strcmp(class{i},names));    
60
+   end
61
+end
62
+
63
+if any(nos==0),
64
+   nos=nos+1;
65
+   names(2:end+1)=names;
66
+   names{1}='';
67
+end
68
+
69
+
70
+
... ...
@@ -0,0 +1,285 @@
1
+function sMap = som_lininit(D, varargin)
2
+
3
+%SOM_LININIT Initialize a Self-Organizing Map linearly.
4
+%
5
+% sMap = som_lininit(D, [[argID,] value, ...])
6
+%
7
+%  sMap = som_lininit(D);
8
+%  sMap = som_lininit(D,sMap);
9
+%  sMap = som_lininit(D,'munits',100,'hexa');
10
+% 
11
+%  Input and output arguments ([]'s are optional): 
12
+%   D                 The training data.
13
+%            (struct) data struct
14
+%            (matrix) data matrix, size dlen x dim
15
+%   [argID,  (string) Parameters affecting the map topology are given 
16
+%    value]  (varies) as argument ID - argument value pairs, listed below.
17
+%   sMap     (struct) map struct
18
+%
19
+% Here are the valid argument IDs and corresponding values. The values 
20
+% which are unambiguous (marked with '*') can be given without the
21
+% preceeding argID.
22
+%  'munits'       (scalar) number of map units
23
+%  'msize'        (vector) map size
24
+%  'lattice'     *(string) map lattice: 'hexa' or 'rect'
25
+%  'shape'       *(string) map shape: 'sheet', 'cyl' or 'toroid'
26
+%  'topol'       *(struct) topology struct
27
+%  'som_topol','sTopol'    = 'topol'
28
+%  'map'         *(struct) map struct
29
+%  'som_map','sMap'        = 'map'
30
+%
31
+% For more help, try 'type som_lininit' or check out online documentation.
32
+% See also SOM_MAP_STRUCT, SOM_RANDINIT, SOM_MAKE.
33
+
34
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35
+%
36
+% som_lininit
37
+%
38
+% PURPOSE
39
+%
40
+% Initializes a SOM linearly along its greatest eigenvectors.
41
+%
42
+% SYNTAX
43
+%
44
+%  sMap = som_lininit(D);
45
+%  sMap = som_lininit(D,sMap);
46
+%  sMap = som_lininit(D,'munits',100,'hexa');
47
+%
48
+% DESCRIPTION
49
+%
50
+% Initializes a SOM linearly. If necessary, a map struct is created
51
+% first. The initialization is made by first calculating the eigenvalues
52
+% and eigenvectors of the training data. Then, the map is initialized
53
+% along the mdim greatest eigenvectors of the training data, where
54
+% mdim is the dimension of the map grid.
55
+%
56
+% REFERENCES
57
+%
58
+% Kohonen, T., "Self-Organizing Map", 2nd ed., Springer-Verlag, 
59
+%    Berlin, 1995, pp. 106-107.
60
+%
61
+% REQUIRED INPUT ARGUMENTS
62
+%
63
+%  D                 The training data.
64
+%           (struct) Data struct. If this is given, its '.comp_names' and 
65
+%                    '.comp_norm' fields are copied to the map struct.
66
+%           (matrix) data matrix, size dlen x dim
67
+%  
68
+% OPTIONAL INPUT ARGUMENTS 
69
+%
70
+%  argID (string) Argument identifier string (see below).
71
+%  value (varies) Value for the argument (see below).
72
+%
73
+%  The optional arguments can be given as 'argID',value -pairs. If an
74
+%  argument is given value multiple times, the last one is used. 
75
+%
76
+%  Here are the valid argument IDs and corresponding values. The values 
77
+%  which are unambiguous (marked with '*') can be given without the 
78
+%  preceeding argID.
79
+%  'dlen'         (scalar) length of the training data
80
+%  'data'         (matrix) the training data
81
+%                *(struct) the training data
82
+%  'munits'       (scalar) number of map units
83
+%  'msize'        (vector) map size
84
+%  'lattice'     *(string) map lattice: 'hexa' or 'rect'
85
+%  'shape'       *(string) map shape: 'sheet', 'cyl' or 'toroid'
86
+%  'topol'       *(struct) topology struct
87
+%  'som_topol','sTopol'    = 'topol'
88
+%  'map'         *(struct) map struct
89
+%  'som_map','sMap'        = 'map'
90
+%
91
+% OUTPUT ARGUMENTS
92
+% 
93
+%  sMap     (struct) The initialized map struct.
94
+%
95
+% EXAMPLES
96
+%
97
+%  sMap = som_lininit(D);
98
+%  sMap = som_lininit(D,sMap);
99
+%  sMap = som_lininit(D,'msize',[10 10]);
100
+%  sMap = som_lininit(D,'munits',100,'rect');
101
+%
102
+% SEE ALSO
103
+% 
104
+%  som_map_struct   Create a map struct.
105
+%  som_randinit     Initialize a map with random values.
106
+%  som_make         Initialize and train self-organizing map.
107
+
108
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
109
+% http://www.cis.hut.fi/projects/somtoolbox/
110
+
111
+% Version 1.0beta ecco 100997
112
+% Version 2.0beta 101199
113
+
114
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
115
+%% check arguments
116
+
117
+% data
118
+if isstruct(D), 
119
+  data_name = D.name; 
120
+  comp_names = D.comp_names; 
121
+  comp_norm = D.comp_norm; 
122
+  D = D.data;
123
+  struct_mode = 1; 
124
+else 
125
+  data_name = inputname(1); 
126
+  struct_mode = 0;
127
+end
128
+[dlen dim] = size(D);
129
+
130
+% varargin
131
+sMap = [];
132
+sTopol = som_topol_struct; 
133
+sTopol.msize = 0; 
134
+munits = NaN;
135
+i=1; 
136
+while i<=length(varargin), 
137
+  argok = 1; 
138
+  if ischar(varargin{i}), 
139
+    switch varargin{i}, 
140
+     case 'munits',     i=i+1; munits = varargin{i}; sTopol.msize = 0;
141
+     case 'msize',      i=i+1; sTopol.msize = varargin{i};
142
+                               munits = prod(sTopol.msize); 
143
+     case 'lattice',    i=i+1; sTopol.lattice = varargin{i}; 
144
+     case 'shape',      i=i+1; sTopol.shape = varargin{i}; 
145
+     case {'som_topol','sTopol','topol'}, i=i+1; sTopol = varargin{i}; 
146
+     case {'som_map','sMap','map'}, i=i+1; sMap = varargin{i}; sTopol = sMap.topol;
147
+     case {'hexa','rect'}, sTopol.lattice = varargin{i}; 
148
+     case {'sheet','cyl','toroid'}, sTopol.shape = varargin{i};
149
+     otherwise argok=0; 
150
+    end
151
+  elseif isstruct(varargin{i}) & isfield(varargin{i},'type'), 
152
+    switch varargin{i}.type, 
153
+     case 'som_topol',
154
+      sTopol = varargin{i}; 
155
+     case 'som_map', 
156
+      sMap = varargin{i};
157
+      sTopol = sMap.topol;
158
+     otherwise argok=0; 
159
+    end
160
+  else
161
+    argok = 0; 
162
+  end
163
+  if ~argok, 
164
+    disp(['(som_topol_struct) Ignoring invalid argument #' num2str(i)]); 
165
+  end
166
+  i = i+1; 
167
+end
168
+
169
+if length(sTopol.msize)==1, sTopol.msize = [sTopol.msize 1]; end
170
+
171
+if ~isempty(sMap), 
172
+  [munits dim2] = size(sMap.codebook);
173
+  if dim2 ~= dim, error('Map and data must have the same dimension.'); end
174
+end
175
+
176
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
177
+%% create map
178
+
179
+% map struct
180
+if ~isempty(sMap), 
181
+  sMap = som_set(sMap,'topol',sTopol);
182
+else  
183
+  if ~prod(sTopol.msize), 
184
+    if isnan(munits), 
185
+      sTopol = som_topol_struct('data',D,sTopol);
186
+    else
187
+      sTopol = som_topol_struct('data',D,'munits',munits,sTopol);
188
+    end
189
+  end  
190
+  sMap = som_map_struct(dim, sTopol); 
191
+end
192
+
193
+if struct_mode, 
194
+  sMap = som_set(sMap,'comp_names',comp_names,'comp_norm',comp_norm);
195
+end
196
+
197
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
198
+%% initialization
199
+
200
+% train struct
201
+sTrain = som_train_struct('algorithm','lininit');
202
+sTrain = som_set(sTrain,'data_name',data_name);
203
+
204
+msize = sMap.topol.msize;
205
+mdim = length(msize);
206
+munits = prod(msize);
207
+
208
+[dlen dim] = size(D);
209
+if dlen<2,  
210
+  %if dlen==1, sMap.codebook = (sMap.codebook - 0.5)*diag(D); end
211
+  error(['Linear map initialization requires at least two NaN-free' ...
212
+	 ' samples.']);
213
+  return;
214
+end
215
+
216
+% compute principle components
217
+if dim > 1 & sum(msize > 1) > 1,
218
+  % calculate mdim largest eigenvalues and their corresponding
219
+  % eigenvectors
220
+    
221
+  % autocorrelation matrix
222
+  A = zeros(dim);
223
+  me = zeros(1,dim);
224
+  for i=1:dim, 
225
+    me(i) = mean(D(isfinite(D(:,i)),i)); 
226
+    D(:,i) = D(:,i) - me(i); 
227
+  end  
228
+  for i=1:dim, 
229
+    for j=i:dim, 
230
+      c = D(:,i).*D(:,j); c = c(isfinite(c));
231
+      A(i,j) = sum(c)/length(c); A(j,i) = A(i,j); 
232
+    end
233
+  end
234
+  
235
+  % take mdim first eigenvectors with the greatest eigenvalues
236
+  [V,S]   = eig(A);
237
+  eigval  = diag(S);
238
+  [y,ind] = sort(eigval); 
239
+  eigval  = eigval(flipud(ind));
240
+  V       = V(:,flipud(ind)); 
241
+  V       = V(:,1:mdim);
242
+  eigval  = eigval(1:mdim);   
243
+
244
+  % normalize eigenvectors to unit length and multiply them by 
245
+  % corresponding (square-root-of-)eigenvalues
246
+  for i=1:mdim, V(:,i) = (V(:,i) / norm(V(:,i))) * sqrt(eigval(i)); end
247
+  
248
+else
249
+
250
+  me = zeros(1,dim);
251
+  V = zeros(1,dim);
252
+  for i=1:dim, 
253
+    inds = find(~isnan(D(:,i)));
254
+    me(i) = mean(D(inds,i),1);
255
+    V(i) = std(D(inds,i),1);
256
+  end
257
+  
258
+end
259
+
260
+% initialize codebook vectors
261
+if dim>1, 
262
+  sMap.codebook = me(ones(munits,1),:); 
263
+  Coords = som_unit_coords(msize,'rect','sheet');
264
+  cox = Coords(:,1); Coords(:,1) = Coords(:,2); Coords(:,2) = cox;
265
+  for i=1:mdim,
266
+    ma = max(Coords(:,i)); mi = min(Coords(:,i)); 
267
+    if ma>mi, Coords(:,i) = (Coords(:,i)-mi)/(ma-mi); else Coords(:,i) = 0.5; end
268
+  end
269
+  Coords = (Coords-0.5)*2;
270
+  for n = 1:munits,   
271
+    for d = 1:mdim,    
272
+      sMap.codebook(n,:) = sMap.codebook(n,:)+Coords(n,d)*V(:, d)';
273
+    end
274
+  end
275
+else  
276
+  sMap.codebook = [0:(munits-1)]'/(munits-1)*(max(D)-min(D))+min(D);
277
+end
278
+
279
+% training struct
280
+sTrain = som_set(sTrain,'time',datestr(now,0));
281
+sMap.trainhist = sTrain;
282
+
283
+return;
284
+
285
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,291 @@
1
+function [Z,order,Md] = som_linkage(sM,varargin)
2
+
3
+%SOM_LINKAGE Make a hierarchical linkage of the SOM map units.
4
+%
5
+% [Z,order,Dist] = som_linkage(sM, [[argID,] value, ...])
6
+%  
7
+%  Z = som_linkage(sM);
8
+%  Z = som_linkage(D,'complete');
9
+%  Z = som_linkage(sM,'single','ignore',find(~som_hits(sM,D)));
10
+%  Z = som_linkage(sM,pdist(sM.codebook,'mahal'));
11
+%  som_dendrogram(Z); 
12
+%
13
+%  Input and output arguments ([]'s are optional):
14
+%   sM       (struct) map or data struct to be clustered
15
+%            (matrix) size dlen x dim, a data set: the matrix must not
16
+%                     contain any NaN's!
17
+%   [argID,  (string) See below. The values which are unambiguous can 
18
+%    value]  (varies) be given without the preceeding argID.
19
+%
20
+%   Z        (matrix) size dlen-1 x 3, the linkage info
21
+%                     Z(i,1) and Z(i,2) hold the indeces of clusters 
22
+%                     combined on level i (starting from bottom). The new
23
+%                     cluster has index dlen+i. The initial cluster 
24
+%                     index of each unit is its linear index in the 
25
+%                     original data matrix. Z(i,3) is the distance
26
+%                     between the combined clusters. See LINKAGE
27
+%                     function in the Statistics Toolbox.
28
+%                     The ignored samples are listed at the 
29
+%                     end of the Z-matrix and have Z(*,3) == Inf
30
+%   Dist     (matrix) size dlen x dlen, pairwise distance matrix
31
+%
32
+% Here are the valid argument IDs and corresponding values. The values 
33
+% which are unambiguous (marked with '*') can be given without the
34
+% preceeding argID.
35
+%   'linkage' *(string) the linkage criteria to use: 'single' (the
36
+%                       default), 'average' or 'complete' 
37
+%   'topol'   *(struct) topology struct
38
+%   'connect' *(string) 'neighbors' or 'any' (default), whether the
39
+%                       connections should be allowed only between 
40
+%                       neighbors or between any vectors
41
+%              (matrix) size dlen x dlen indicating the connections
42
+%                       between vectors
43
+%              (scalar) the N-neighborhood upto which the connections
44
+%                       should be formed (implies 'neighbors')
45
+%   'ignore'   (vector) the units/vectors which should be ignored 
46
+%   'dist'     (matrix) size dlen x dlen, pairwise distance matrix to 
47
+%                       be used instead of euclidian distances
48
+%              (vector) as the output of PDIST function
49
+%              (scalar) distance norm to use (euclidian = 2)
50
+%   'mask'     (vector) size dim x 1, the search mask used to 
51
+%                       weight distance calculation. By default 
52
+%                       sM.mask or a vector of ones is used.
53
+%
54
+% Note that together 'connect'='neighbors' and 'ignore' may form
55
+% areas on the map which will never be connected: connections
56
+% across the ignored map units simply do not exist.
57
+%
58
+% See also KMEANS_CLUSTERS, LINKAGE, PDIST, DENDROGRAM. 
59
+
60
+% Copyright (c) 2000 by Juha Vesanto
61
+% Contributed to SOM Toolbox on June 16th, 2000 by Juha Vesanto
62
+% http://www.cis.hut.fi/projects/somtoolbox/
63
+ 
64
+% Version 2.0beta juuso 160600
65
+
66
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
67
+%% input arguments
68
+
69
+% the data
70
+if isstruct(sM), 
71
+  if isfield(sM,'data'), D = sM.data; sT = []; mask = []; 
72
+  else D = sM.codebook; sT = sM.topol; mask = sM.mask;
73
+  end
74
+else
75
+  D = sM; sT = []; mask = []; 
76
+end
77
+[dlen dim] = size(D);
78
+if isempty(mask), mask = ones(dim,1); end
79
+if any(isnan(D(:))), error('Data matrix must not have any NaNs.'); end
80
+
81
+% varargin
82
+Md = 2; 
83
+linkage = 'single';
84
+ignore_units = []; 
85
+constrained = 0;
86
+i=1; 
87
+while i<=length(varargin), 
88
+  argok = 1; 
89
+  if ischar(varargin{i}), 
90
+    switch varargin{i}, 
91
+      % argument IDs
92
+     case {'topol','som_topol','sTopol'}, i=i+1; sT = varargin{i};
93
+     case 'connect', i=i+1; 
94
+       if ischar(varargin{i}), constrained = ~strcmp(varargin{i},'any');
95
+       else constrained = varargin{i}; end
96
+     case 'ignore',  i=i+1; ignore_units = varargin{i}; 
97
+     case 'dist',    i=i+1; Md = varargin{i};
98
+     case 'linkage', i=i+1; linkage = varargin{i};
99
+     case 'mask',    i=i+1; mask = varargin{i};
100
+     case 'tracking',i=i+1; tracking = varargin{i}; 
101
+      % unambiguous values
102
+     case 'neighbors', constrained = 1; 
103
+     case 'any',       constrained = 0; 
104
+     case {'single','average','complete'}, linkage = varargin{i};
105
+     otherwise argok=0; 
106
+    end
107
+  elseif isstruct(varargin{i}) & isfield(varargin{i},'type'), 
108
+    switch varargin{i}(1).type, 
109
+     case 'som_topol', sTopol = varargin{i}; 
110
+     otherwise argok=0; 
111
+    end
112
+  else
113
+    argok = 0; 
114
+  end
115
+  if ~argok, 
116
+    disp(['(som_linkage) Ignoring invalid argument #' num2str(i+1)]); 
117
+  end
118
+  i = i+1; 
119
+end
120
+
121
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
122
+%% distance matrix
123
+
124
+% given distance matrix % jh corrected this place totally 27.3. 03
125
+if (prod(size(Md))==1), % no explicit distance matrix, set flag
126
+  q=2; % 17.2.03 kr added some brackets
127
+else
128
+  if (prod(size(Md))<dlen^2), % check pdist form
129
+    Md = squareform(Md);   % transform to ordinary square diastance matrix
130
+  end
131
+  % jh: 27.3. 03 "calculate pairwise dist. matrix" see approx. 20 lines below
132
+  % sets self-distance to Inf! This must be set here also,
133
+  % otherwise clustering fails for user defined dist. matrix! 
134
+  Md(eye(dlen)==1)=Inf; 
135
+end
136
+
137
+% neighborhood constraint
138
+if length(constrained)==1 & constrained>0, 
139
+  Ne1 = som_unit_neighs(sT); 
140
+  Conn = som_neighborhood(Ne1,constrained); 
141
+  Conn(~isfinite(Conn(:))) = 0; 
142
+else Conn = constrained; end
143
+if ~isempty(Conn), for i=1:dlen, C(i,i) = 1; end, end
144
+
145
+% pairwise distance matrix across connected units
146
+n = size(D,1);
147
+if prod(size(Md))>1,   
148
+  % remove distances between non-neighbors
149
+  if constrained, for i = 1:n, Md(i,find(Conn(i,:)==0)) = Inf; end, end
150
+else    
151
+  % calculate pairwise distance matrix
152
+  q = Md; 
153
+  Md = zeros(n,n)+Inf;
154
+  if ~constrained & q==2, % fast for the default case 
155
+    for i = 1:n-1,
156
+      x = D(i,:);
157
+      inds = [(i+1):n]; 
158
+      Diff = D(inds,:) - x(ones(n-i,1),:);
159
+      Md(inds,i) = sqrt((Diff.^2)*mask);
160
+      Md(i,inds) = Md(inds,i)';
161
+    end  
162
+  else
163
+    for i = 1:n-1, 
164
+      inds = find(Conn(i,:)==1); 
165
+      inds = inds(find(inds>i)); 
166
+      Diff = abs(D(inds,:) - D(i*ones(length(inds),1),:));
167
+      switch q, 
168
+       case 1,    dist = Diff*mask;
169
+       case 2,    dist = sqrt((Diff.^2)*mask);
170
+       case Inf,  dist = max(Diff,[],2);
171
+       otherwise, dist = ((Diff.^q)*mask).^(1/q);
172
+      end
173
+      Md(inds,i) = dist; 
174
+      Md(i,inds) = dist'; 
175
+    end
176
+  end
177
+end
178
+
179
+% set distances to ignored units to Inf
180
+if ~isempty(ignore_units), 
181
+  Md(ignore_units,:) = Inf;
182
+  Md(:,ignore_units) = Inf;
183
+end
184
+
185
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
186
+%% construct dendrogram
187
+
188
+Z = zeros(n-1,3)+NaN;  % merged clusters and distance for each step
189
+clusters = 1:dlen;     % each vector is at first in its own cluster
190
+Cd = Md;               % distances between clusters
191
+
192
+h = waitbar(0,'Constructing hierarchical clustering'); 
193
+  
194
+for i=1:n-1,   
195
+
196
+  % tracking
197
+  waitbar(i/(n-1),h); 
198
+
199
+  %% combine two closest clusters  
200
+  % find the clusters which are closest to each other (c1 and c2)
201
+  [d,ind] = min(min(Cd));  
202
+  if ~isfinite(d), break; end   % no more connected clusters
203
+  [d,c1] = min(Cd(:,ind));      % cluster1
204
+  c2 = clusters(ind);           % cluster2    
205
+  % combine the two clusters
206
+  c1_inds = find(clusters==c1); % vectors belonging to c1
207
+  c2_inds = find(clusters==c2); % vectors belonging to c2
208
+  c_inds = [c1_inds, c2_inds];  % members of the new cluster  
209
+  % new cluster index = bigger cluster
210
+  if length(c2_inds)>length(c1_inds), c=c2; k=c1; else c=c1; k=c2; end
211
+  clusters(c_inds) = c;         % update cluster info
212
+  Z(i,:) = [c, k, d];           % save info into Z
213
+  
214
+  %% update cluster distances  
215
+  % remove the subclusters from the Cd table  
216
+  Cd(c_inds,c_inds) = Inf;      % distance of the cluster to its members = Inf
217
+  k_inds = c_inds(c_inds ~= c); % vectors of the smaller cluster
218
+  Cd(k_inds,:) = Inf;           % distance of the subclusters to 
219
+  Cd(:,k_inds) = Inf;           % other clusters = Inf
220
+  % update the distance of this cluster to the other clusters
221
+  cl = unique(clusters(clusters ~= c)); % indeces of all other clusters
222
+  if ~isempty(cl), % added since v6.5 works differently than 6.1
223
+    for l=cl,   
224
+      o_inds = find(clusters==l); % indeces belonging to cluster k
225
+      vd = Md(c_inds,o_inds);     % distances between vectors in c and k
226
+      vd = vd(isfinite(vd(:)));   % remove infinite distances (no connection)
227
+      len = length(vd);
228
+      if ~len, % if the two clusters are not connected, their distance in Inf
229
+	sd = Inf;
230
+      else   % otherwise, calculate the distance between them
231
+	switch linkage,
232
+	 case 'single',   sd = min(vd);
233
+	 case 'average',  sd = sum(vd)/len; 
234
+	 case 'complete', sd = max(vd);
235
+	 otherwise, error(['Unknown set distance: ' linkage]);
236
+	end
237
+      end
238
+      Cd(c,l) = sd; Cd(l,c) = sd;
239
+    end  
240
+  end
241
+end
242
+close(h); 
243
+
244
+last = Z(i,1); 
245
+if isnan(last), 
246
+  last = Z(i-1,1); 
247
+  rest = setdiff(unique(clusters),last); 
248
+  Z(i:n-1,1) = rest'; 
249
+  Z(i:n-1,2) = last; 
250
+  Z(i:n-1,3) = Inf; 
251
+  i = i - 1; 
252
+else 
253
+  rest = []; 
254
+end
255
+
256
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
257
+%% return values
258
+
259
+% calculate the order of samples
260
+order = last; 
261
+% go through the combination matrix from top to down
262
+for k=i:-1:1, 
263
+  c = Z(k,1); k = Z(k,2);                     % what (k) change to what (c)
264
+  j = find(order==c);                         % the occurance of c in order    
265
+  if j == length(order), order = [order k];   % put k behind c
266
+  else order = [order(1:j) k order(j+1:end)]; 
267
+  end
268
+end  
269
+order = [rest, order]; 
270
+
271
+% to maintain compatibility with Statistics Toolbox, the values in 
272
+% Z must be yet transformed so that they are similar to the output
273
+% of LINKAGE function
274
+
275
+Zs = Z;
276
+current_cluster = 1:dlen;
277
+for i=1:size(Z,1),
278
+  Zs(i,1) = current_cluster(Z(i,1));
279
+  Zs(i,2) = current_cluster(Z(i,2));
280
+  current_cluster(Z(i,[1 2])) = dlen+i;  
281
+end
282
+
283
+Z = Zs;
284
+
285
+return;
286
+
287
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
288
+
289
+
290
+
291
+
... ...
@@ -0,0 +1,339 @@
1
+function sMap = som_make(D, varargin)
2
+
3
+%SOM_MAKE Create, initialize and train Self-Organizing Map.
4
+%
5
+% sMap = som_make(D, [[argID,] value, ...])
6
+%
7
+%  sMap = som_make(D);
8
+%  sMap = som_make(D, 'munits', 20);
9
+%  sMap = som_make(D, 'munits', 20, 'hexa', 'sheet');
10
+%  sMap = som_make(D, 'msize', [4 6 7], 'lattice', 'rect');
11
+%
12
+%  Input and output arguments ([]'s are optional): 
13
+%   D        (matrix) training data, size dlen x dim
14
+%            (struct) data struct
15
+%   [argID,  (string) See below. The values which are unambiguous can 
16
+%    value]  (varies) be given without the preceeding argID.
17
+%
18
+%   sMap     (struct) map struct
19
+%
20
+% Here are the valid argument IDs and corresponding values. The values 
21
+% which are unambiguous (marked with '*') can be given without the
22
+% preceeding argID.
23
+%   'init'       *(string) initialization: 'randinit' or 'lininit' (default)
24
+%   'algorithm'  *(string) training: 'seq' or 'batch' (default) or 'sompak'
25
+%   'munits'      (scalar) the preferred number of map units
26
+%   'msize'       (vector) map grid size
27
+%   'mapsize'    *(string) do you want a 'small', 'normal' or 'big' map
28
+%                          Any explicit settings of munits or msize override this.
29
+%   'lattice'    *(string) map lattice, 'hexa' or 'rect'
30
+%   'shape'      *(string) map shape, 'sheet', 'cyl' or 'toroid'
31
+%   'neigh'      *(string) neighborhood function, 'gaussian', 'cutgauss',
32
+%                          'ep' or 'bubble'
33
+%   'topol'      *(struct) topology struct
34
+%   'som_topol','sTopol' = 'topol'
35
+%   'mask'        (vector) BMU search mask, size dim x 1
36
+%   'name'        (string) map name
37
+%   'comp_names'  (string array / cellstr) component names, size dim x 1
38
+%   'tracking'    (scalar) how much to report, default = 1
39
+%   'training'    (string) 'short', 'default', 'long'
40
+%                 (vector) size 1 x 2, first length of rough training in epochs, 
41
+%                          and then length of finetuning in epochs
42
+%
43
+% For more help, try 'type som_make' or check out online documentation.
44
+% See also SOM_MAP_STRUCT, SOM_TOPOL_STRUCT, SOM_TRAIN_STRUCT,
45
+%          SOM_RANDINIT, SOM_LININIT, SOM_SEQTRAIN, SOM_BATCHTRAIN.          
46
+
47
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
48
+%
49
+% som_make
50
+%
51
+% PURPOSE
52
+%
53
+% Creates, initializes and trains a SOM using default parameters.
54
+%
55
+% SYNTAX
56
+%
57
+%  sMap = som_make(D);
58
+%  sMap = som_make(...,'argID',value,...);
59
+%  sMap = som_make(...,value,...);
60
+%
61
+% DESCRIPTION
62
+%
63
+% Creates, initializes and trains a SOM with default parameters. Uses functions
64
+% SOM_TOPOL_STRUCT, SOM_TRAIN_STRUCT, SOM_DATA_STRUCT and SOM_MAP_STRUCT to come
65
+% up with the default values.
66
+%
67
+% First, the number of map units is determined. Unless they are
68
+% explicitly defined, function SOM_TOPOL_STRUCT is used to determine this.
69
+% It uses a heuristic formula of 'munits = 5*dlen^0.54321'. The 'mapsize'
70
+% argument influences the final number of map units: a 'big' map has 
71
+% x4 the default number of map units and a 'small' map has x0.25 the
72
+% default number of map units. 
73
+%
74
+% After the number of map units has been determined, the map size is 
75
+% determined. Basically, the two biggest eigenvalues of the training
76
+% data are calculated and the ratio between sidelengths of the map grid
77
+% is set to this ratio. The actual sidelengths are then set so that 
78
+% their product is as close to the desired number of map units as
79
+% possible.
80
+%
81
+% Then the SOM is initialized. First, linear initialization along two
82
+% greatest eigenvectors is tried, but if this can't be done (the
83
+% eigenvectors cannot be calculated), random initialization is used
84
+% instead.  After initialization, the SOM is trained in two phases:
85
+% first rough training and then fine-tuning. If the 'tracking'
86
+% argument is greater than zero, the average quantization error and
87
+% topographic error of the final map are calculated.
88
+%
89
+% REQUIRED INPUT ARGUMENTS
90
+%
91
+%  D           The data to use in the training.
92
+%     (struct) A data struct. If a struct is given, '.comp_names' field as 
93
+%              well as '.comp_norm' field is copied to the map struct.
94
+%     (matrix) A data matrix, size dlen x dim. The data matrix may
95
+%              contain unknown values, indicated by NaNs. 
96
+%  
97
+% OPTIONAL INPUT ARGUMENTS 
98
+%
99
+%  argID (string) Argument identifier string (see below).
100
+%  value (varies) Value for the argument (see below).
101
+%
102
+% Here are the valid argument IDs and corresponding values. The values 
103
+% which are unambiguous (marked with '*') can be given without the
104
+% preceeding argID.
105
+%   'init'       *(string) initialization: 'randinit' or 'lininit' (default)
106
+%   'algorithm'  *(string) training: 'seq' or 'batch' (default) or 'sompak'
107
+%   'munits'      (scalar) the preferred number of map units
108
+%   'msize'       (vector) map grid size
109
+%   'mapsize'    *(string) do you want a 'small', 'normal' or 'big' map
110
+%                          Any explicit settings of munits or msize override this.
111
+%   'lattice'    *(string) map lattice, 'hexa' or 'rect'
112
+%   'shape'      *(string) map shape, 'sheet', 'cyl' or 'toroid'
113
+%   'neigh'      *(string) neighborhood function, 'gaussian', 'cutgauss',
114
+%                          'ep' or 'bubble'
115
+%   'topol'      *(struct) topology struct
116
+%   'som_topol','sTopol' = 'topol'
117
+%   'mask'        (vector) BMU search mask, size dim x 1
118
+%   'name'        (string) map name
119
+%   'comp_names'  (string array / cellstr) component names, size dim x 1
120
+%   'tracking'    (scalar) how much to report, default = 1
121
+%   'training'    (string) 'short', 'default' or 'long'
122
+%                 (vector) size 1 x 2, first length of rough training in epochs, 
123
+%                          and then length of finetuning in epochs
124
+%
125
+% OUTPUT ARGUMENTS
126
+% 
127
+%  sMap (struct) the trained map struct
128
+%
129
+% EXAMPLES
130
+%
131
+%  To simply train a map with default parameters: 
132
+%
133
+%   sMap = som_make(D); 
134
+%  
135
+%  With the optional arguments, the initialization and training can be
136
+%  influenced. To change map size, use 'msize', 'munits' or 'mapsize'
137
+%  arguments:  
138
+%
139
+%   sMap = som_make(D,'mapsize','big'); or sMap=som_make(D,'big');
140
+%   sMap = som_make(D,'munits', 100);
141
+%   sMap = som_make(D,'msize', [20 10]); 
142
+%
143
+%  Argument 'algorithm' can be used to switch between 'seq' and 'batch'
144
+%  algorithms. 'batch' is the default, so to use 'seq' algorithm: 
145
+%
146
+%   sMap = som_make(D,'algorithm','seq'); or sMap = som_make(D,'seq'); 
147
+%
148
+%  The 'tracking' argument can be used to control the amout of reporting
149
+%  during training. The argument is used in this function, and it is
150
+%  passed to the training functions. To make the function work silently
151
+%  set it to 0.
152
+%
153
+%   sMap = som_make(D,'tracking',0); 
154
+%
155
+% SEE ALSO
156
+% 
157
+%  som_map_struct   Create a map struct.
158
+%  som_topol_struct Default values for SOM topology.
159
+%  som_train_struct Default values for SOM training parameters.
160
+%  som_randinint    Random initialization algorithm.
161
+%  som_lininit      Linear initialization algorithm.
162
+%  som_seqtrain     Sequential training algorithm.
163
+%  som_batchtrain   Batch training algorithm.
164
+
165
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
166
+% http://www.cis.hut.fi/projects/somtoolbox/
167
+
168
+% Version 2.0beta juuso 111199
169
+
170
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
171
+%% check arguments
172
+
173
+% D
174
+if isstruct(D) 
175
+  data_name = D.name; 
176
+  comp_names = D.comp_names;
177
+  comp_norm = D.comp_norm;
178
+  D = D.data;
179
+else 
180
+  data_name = inputname(1);
181
+  sDummy = som_data_struct(D(1,:)); 
182
+  comp_names = sDummy.comp_names;
183
+  comp_norm = sDummy.comp_norm;
184
+end
185
+[dlen dim] = size(D);
186
+
187
+% defaults
188
+mapsize = '';
189
+sM = som_map_struct(dim); 
190
+sTopol = sM.topol;
191
+munits = prod(sTopol.msize); % should be zero
192
+mask = sM.mask; 
193
+name = sM.name; 
194
+neigh = sM.neigh; 
195
+tracking = 1;
196
+algorithm = 'batch'; 
197
+initalg = 'lininit';
198
+training = 'default'; 
199
+
200
+% varargin
201
+i=1; 
202
+while i<=length(varargin), 
203
+  argok = 1; 
204
+  if ischar(varargin{i}), 
205
+    switch varargin{i}, 
206
+      % argument IDs
207
+     case 'mask',       i=i+1; mask = varargin{i}; 
208
+     case 'munits',     i=i+1; munits = varargin{i}; 
209
+     case 'msize',      i=i+1; sTopol.msize = varargin{i}; 
210
+                        munits = prod(sTopol.msize); 
211
+     case 'mapsize',    i=i+1; mapsize = varargin{i}; 
212
+     case 'name',       i=i+1; name = varargin{i};
213
+     case 'comp_names', i=i+1; comp_names = varargin{i}; 
214
+     case 'lattice',    i=i+1; sTopol.lattice = varargin{i};
215
+     case 'shape',      i=i+1; sTopol.shape = varargin{i}; 
216
+     case {'topol','som_topol','sTopol'}, 
217
+                        i=i+1; sTopol = varargin{i}; munits = prod(sTopol.msize); 
218
+     case 'neigh',      i=i+1; neigh = varargin{i};
219
+     case 'tracking',   i=i+1; tracking = varargin{i};
220
+     case 'algorithm',  i=i+1; algorithm = varargin{i}; 
221
+     case 'init',       i=i+1; initalg = varargin{i};
222
+     case 'training',   i=i+1; training = varargin{i}; 
223
+      % unambiguous values
224
+     case {'hexa','rect'}, sTopol.lattice = varargin{i};
225
+     case {'sheet','cyl','toroid'}, sTopol.shape = varargin{i}; 
226
+     case {'gaussian','cutgauss','ep','bubble'}, neigh = varargin{i};
227
+     case {'seq','batch','sompak'}, algorithm = varargin{i}; 
228
+     case {'small','normal','big'}, mapsize = varargin{i}; 
229
+     case {'randinit','lininit'}, initalg = varargin{i};
230
+     case {'short','default','long'}, training = varargin{i}; 
231
+     otherwise argok=0; 
232
+    end
233
+  elseif isstruct(varargin{i}) & isfield(varargin{i},'type'), 
234
+    switch varargin{i}(1).type, 
235
+     case 'som_topol', sTopol = varargin{i}; 
236
+     otherwise argok=0; 
237
+    end
238
+  else
239
+    argok = 0; 
240
+  end
241
+  if ~argok, 
242
+    disp(['(som_make) Ignoring invalid argument #' num2str(i+1)]); 
243
+  end
244
+  i = i+1; 
245
+end
246
+
247
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
248
+%% make the map struct
249
+
250
+%% map size
251
+if isempty(sTopol.msize) | ~prod(sTopol.msize), 
252
+  if tracking>0, fprintf(1,'Determining map size...\n'); end
253
+  if ~munits,     
254
+    sTemp = som_topol_struct('dlen',dlen);
255
+    munits = prod(sTemp.msize);
256
+    switch mapsize,
257
+     case 'small', munits = max(9,ceil(munits/4));
258
+     case 'big',   munits = munits*4;
259
+     otherwise % nil
260
+    end
261
+  end
262
+  sTemp = som_topol_struct('data',D,'munits',munits);
263
+  sTopol.msize = sTemp.msize;
264
+  if tracking>0, 
265
+    fprintf(1,' map size [%d, %d]\n',sTopol.msize(1), sTopol.msize(2));   
266
+  end
267
+end
268
+
269
+% map struct
270
+sMap = som_map_struct(dim,sTopol,neigh,'mask',mask,'name',name, ...
271
+                      'comp_names', comp_names, 'comp_norm', comp_norm); 
272
+       
273
+% function
274
+if strcmp(algorithm,'sompak'), 
275
+  algorithm = 'seq';
276
+  func = 'sompak';
277
+else
278
+  func = algorithm;
279
+end
280
+
281
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
282
+%% initialization
283
+
284
+if tracking>0, fprintf(1,'Initialization...\n'); end
285
+
286
+switch initalg, 
287
+ case 'randinit', sMap = som_randinit(D, sMap);
288
+ case 'lininit', sMap = som_lininit(D, sMap); 
289
+end
290
+sMap.trainhist(1) = som_set(sMap.trainhist(1),'data_name',data_name);
291
+
292
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
293
+%% training
294
+
295
+if tracking>0, fprintf(1,'Training using %s algorithm...\n',algorithm); end
296
+
297
+% rough train
298
+if tracking>0, fprintf(1,'Rough training phase...\n'); end
299
+sTrain = som_train_struct(sMap,'dlen',dlen,'algorithm',algorithm,'phase','rough');
300
+sTrain = som_set(sTrain,'data_name',data_name);
301
+if isnumeric(training), sTrain.trainlen = training(1); 
302
+else
303
+  switch training, 
304
+   case 'short', sTrain.trainlen = max(1,sTrain.trainlen/4);
305
+   case 'long',  sTrain.trainlen = sTrain.trainlen*4;
306
+  end
307
+end
308
+switch func,
309
+ case 'seq',    sMap = som_seqtrain(sMap,D,sTrain,'tracking',tracking,'mask',mask);
310
+ case 'sompak', sMap = som_sompaktrain(sMap,D,sTrain,'tracking',tracking,'mask',mask);
311
+ case 'batch',  sMap = som_batchtrain(sMap,D,sTrain,'tracking',tracking,'mask',mask);
312
+end
313
+
314
+% finetune
315
+if tracking>0, fprintf(1,'Finetuning phase...\n'); end
316
+sTrain = som_train_struct(sMap,'dlen',dlen,'phase','finetune');
317
+sTrain = som_set(sTrain,'data_name',data_name,'algorithm',algorithm);
318
+if isnumeric(training), sTrain.trainlen = training(2); 
319
+else
320
+  switch training, 
321
+   case 'short', sTrain.trainlen = max(1,sTrain.trainlen/4);
322
+   case 'long',  sTrain.trainlen = sTrain.trainlen*4;
323
+  end
324
+end
325
+switch func,
326
+ case 'seq',    sMap = som_seqtrain(sMap,D,sTrain,'tracking',tracking,'mask',mask);
327
+ case 'sompak', sMap = som_sompaktrain(sMap,D,sTrain,'tracking',tracking,'mask',mask);
328
+ case 'batch',  sMap = som_batchtrain(sMap,D,sTrain,'tracking',tracking,'mask',mask);
329
+end
330
+
331
+% quality
332
+if tracking>0, 
333
+  [mqe,tge] = som_quality(sMap,D);
334
+  fprintf(1,'Final quantization error: %5.3f\n',mqe)
335
+  fprintf(1,'Final topographic error:  %5.3f\n',tge)
336
+end  
337
+
338
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
339
+
... ...
@@ -0,0 +1,231 @@
1
+function sMap = som_map_struct(dim, varargin)
2
+
3
+%SOM_MAP_STRUCT Create map struct. 
4
+% 
5
+% sMap = som_map_struct(dim, [[argID,] value, ...])
6
+%
7
+%  sMap = som_map_struct(4);
8
+%  sMap = som_map_struct(4,'msize',[3 4],'hexa','sheet');
9
+%  sMap = som_map_struct(4,'msize',[3 4 5],'rect','name','a 3D-SOM');
10
+%  sMap = som_map_struct(4,'msize',[3 4],'bubble','mask',[1 1 1 0]);
11
+%
12
+%  Input and output arguments ([]'s are optional): 
13
+%   dim      (scalar) input space dimension
14
+%   [argID,  (string) See below. The values which are unambiguous can 
15
+%    value]  (varies) be given without the preceeding argID.
16
+%
17
+%   sMap     (struct) self-organizing map struct
18
+%
19
+% Here are the valid argument IDs and corresponding values. The values
20
+% which are unambiguous (marked with '*') can be given without the
21
+% preceeding argID.
22
+%   'mask'       (vector) BMU search mask, size dim x 1
23
+%   'msize'      (vector) map grid size, default is [0]
24
+%   'labels'     (string array / cellstr) labels for each map unit, 
25
+%                 length=prod(msize)
26
+%   'name'       (string) map name
27
+%   'comp_names' (string array / cellstr) component names, size dim x 1
28
+%   'comp_norm'  (cell array) normalization operations for each
29
+%                 component, size dim x 1. Each cell is either empty, 
30
+%                 or a cell array of normalization structs.
31
+%   'topol'     *(struct) topology struct
32
+%   'som_topol','sTopol' = 'topol'
33
+%   'lattice'   *(string) map lattice, 'hexa' or 'rect'
34
+%   'shape'     *(string) map shape, 'sheet', 'cyl' or 'toroid'
35
+%   'neigh'     *(string) neighborhood function, 'gaussian', 'cutgauss',
36
+%                 'ep' or 'bubble'
37
+%
38
+% For more help, try 'type som_map_struct' or check out online documentation.
39
+% See also SOM_SET, SOM_INFO, SOM_DATA_STRUCT, SOM_TOPOL_STRUCT, SOM_MAKE.
40
+
41
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
42
+%
43
+% som_map_struct
44
+%
45
+% PURPOSE
46
+%
47
+% Creates a self-organizing map structure. 
48
+%
49
+% SYNTAX
50
+%
51
+%  sM = som_map_struct(dim)
52
+%  sM = som_map_struct(...,'argID',value,...);
53
+%  sM = som_map_struct(...,value,...);
54
+%
55
+% DESCRIPTION
56
+%
57
+% Creates a self-organizing map struct. The struct contains the map
58
+% codebook, labels, topology, information on normalization and training, 
59
+% as well as component names and a name for the map. The obligatory
60
+% parameter is the map dimension. Most of the other fields can be
61
+% given values using optional arguments. If they are left unspecified,
62
+% default values are used.
63
+%
64
+%  Field         Type         Size / default value (munits = prod(msize))
65
+%  ------------------------------------------------------------------------
66
+%   .type        (string)     'som_map'               
67
+%   .name        (string)     'SOM date'
68
+%   .codebook    (matrix)     rand(munits, dim)
69
+%   .topol       (struct)     topology struct, with the following fields
70
+%     .type         (string)  'som_topol'
71
+%     .msize        (vector)  size k x 1, [0] 
72
+%     .lattice      (string)  'hexa' 
73
+%     .shape        (string)  'sheet'
74
+%   .labels      (cellstr)    size munits x m, {''; ''; ... ''}
75
+%   .neigh       (string)     'gaussian'
76
+%   .mask        (vector)     size dim x 1, [1; 1; ...; 1]
77
+%   .trainhist   (cell array) size tl x 1, []
78
+%   .comp_names  (cellstr)    size dim x 1, {'Variable1', 'Variable2', ...}
79
+%   .comp_norm   (cell array) size dim x 1, {[], [], ... []}
80
+%
81
+% '.type' field is the struct identifier. Do not change it.
82
+% '.name' field is the identifier for the whole map struct
83
+% '.codebook' field is the codebook matrix, each row corresponds to one unit
84
+% '.topol' field is the topology of the map. This struct has three fields:
85
+%   '.msize' field is the dimensions of the map grid. Note that the
86
+%         matrix notation of indeces is used.
87
+%   '.lattice' field is the map grid lattice
88
+%   '.shape' field is the map grid shape
89
+% '.labels' field contains the labels for each of the vectors. The ith row
90
+%         of '.labels' contains the labels for ith map unit. Note that 
91
+%         if some vectors have more labels than others, the others are
92
+%         are given empty labels ('') to pad the '.labels' array up.
93
+% '.neigh' field is the neighborhood function. 
94
+% '.mask' field is the BMU search mask.
95
+% '.trainhist' field contains information on the training. It is a cell
96
+%         array of training structs. The first training struct contains
97
+%         information on initialization, the others on actual trainings. 
98
+%         If the map has not been initialized, '.trainhist' is empty ([]).
99
+% '.comp_names' field contains the names of the vector components
100
+% '.comp_norm' field contains normalization information for each
101
+%         component. Each cell of '.comp_norm' is itself a cell array of
102
+%         normalization structs. If no normalizations are performed for 
103
+%         the particular component, the cell is empty ([]).
104
+%
105
+% REQUIRED INPUT ARGUMENTS
106
+%
107
+%  dim    (scalar) Input space dimension. 
108
+%  
109
+% OPTIONAL INPUT ARGUMENTS 
110
+%
111
+%  argID (string) Argument identifier string (see below).
112
+%  value (varies) Value for the argument (see below).
113
+%
114
+%  The optional arguments are given as 'argID',value -pairs. If the
115
+%  value is unambiguous (marked below with '*'), it can be given
116
+%  without the preceeding argID. If an argument is given value
117
+%  multiple times, the last one is used.
118
+%
119
+%   'mask'       (vector) BMU search mask, size dim x 1
120
+%   'msize'      (vector) map grid size, default is [0]
121
+%   'labels'     (string array / cellstr) labels for each map unit, 
122
+%                 length=prod(msize)
123
+%   'name'       (string) map name
124
+%   'comp_names' (string array / cellstr) component names, size dim x 1
125
+%   'comp_norm'  (cell array) normalization operations for each
126
+%                 component, size dim x 1. Each cell is either empty, 
127
+%                 or a cell array of normalization structs.
128
+%   'lattice'   *(string) map lattice, 'hexa' or 'rect'
129
+%   'shape'     *(string) map shape, 'sheet', 'cyl' or 'toroid'
130
+%   'topol'     *(struct) topology struct, sets msize, lattice and shape
131
+%   'som_topol','sTopol' = 'topol'
132
+%   'neigh'     *(string) neighborhood function, 'gaussian', 'cutgauss',
133
+%                 'ep' or 'bubble'
134
+%
135
+% OUTPUT ARGUMENTS
136
+% 
137
+%  sMap (struct) the map struct
138
+%
139
+% EXAMPLES
140
+%
141
+% Simplest case:
142
+%  sMap = som_map_struct(3);
143
+%  
144
+% With optional arguments, the other fields can be given values:
145
+%  sTo    = som_set('som_topol','msize',[10 5]);
146
+%  labs   = cell(50, 1); labs{1, 1} = 'first_unit';
147
+%  cnames = {'first'; 'second'; 'third'};
148
+%  sN     = som_set('som_norm');
149
+%  csN    = {sN; sN; sN};
150
+%  
151
+%  sMap = som_map_struct(3,'msize',[10 5],'rect');
152
+%  sMap = som_map_struct(3,'msize',[10 5],'lattice','rect');
153
+%  sMap = som_map_struct(3,sTo,'bubble','labels',labs);
154
+%  sMap = som_map_struct(3,sTo,'comp_names',cnames);
155
+%  sMap = som_map_struct(3,sTo,'name','a data struct');
156
+%  sMap = som_map_struct(3,sTo,'comp_norm',csN,'mask',[1 0 0.5]);
157
+%
158
+% SEE ALSO
159
+% 
160
+%  som_set          Set values and create SOM Toolbox structs.
161
+%  som_data_struct  Create a data struct.
162
+%  som_make         Initialize and train self-organizing map.
163
+%  som_topol_struct Default values for map topology.
164
+
165
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
166
+% http://www.cis.hut.fi/projects/somtoolbox/
167
+
168
+% Version 1.0beta ecco 100997
169
+% Version 2.0beta juuso 101199 130300
170
+
171
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
172
+
173
+% default values
174
+sTopol     = som_set('som_topol','lattice','hexa','shape','sheet');
175
+neigh      = 'gaussian';
176
+mask       = ones(dim,1);
177
+name       = sprintf('SOM %s', datestr(now, 1));
178
+labels     = cell(prod(sTopol.msize),1);
179
+for i=1:length(labels), labels{i} = ''; end
180
+comp_names = cell(dim,1); 
181
+for i = 1:dim, comp_names{i} = sprintf('Variable%d', i); end
182
+comp_norm  = cell(dim,1); 
183
+
184
+% varargin
185
+i=1; 
186
+while i<=length(varargin), 
187
+  argok = 1; 
188
+  if ischar(varargin{i}), 
189
+    switch varargin{i}, 
190
+      % argument IDs
191
+     case 'mask',       i=i+1; mask = varargin{i}; 
192
+     case 'msize',      i=i+1; sTopol.msize = varargin{i}; 
193
+     case 'labels',     i=i+1; labels = varargin{i};
194
+     case 'name',       i=i+1; name = varargin{i};
195
+     case 'comp_names', i=i+1; comp_names = varargin{i}; 
196
+     case 'comp_norm',  i=i+1; comp_norm = varargin{i};
197
+     case 'lattice',    i=i+1; sTopol.lattice = varargin{i};
198
+     case 'shape',      i=i+1; sTopol.shape = varargin{i}; 
199
+     case {'topol','som_topol','sTopol'}, i=i+1; sTopol = varargin{i};
200
+     case 'neigh',      i=i+1; neigh = varargin{i};
201
+      % unambiguous values
202
+     case {'hexa','rect'}, sTopol.lattice = varargin{i};
203
+     case {'sheet','cyl','toroid'}, sTopol.shape = varargin{i}; 
204
+     case {'gaussian','cutgauss','ep','bubble'}, neigh = varargin{i};
205
+     otherwise argok=0; 
206
+    end
207
+  elseif isstruct(varargin{i}) & isfield(varargin{i},'type'), 
208
+    switch varargin{i}(1).type, 
209
+     case 'som_topol', sTopol = varargin{i};
210
+     otherwise argok=0; 
211
+    end
212
+  else
213
+    argok = 0; 
214
+  end
215
+  if ~argok, 
216
+    disp(['(som_map_struct) Ignoring invalid argument #' num2str(i+1)]); 
217
+  end
218
+  i = i+1; 
219
+end
220
+
221
+% create the SOM
222
+codebook = rand(prod(sTopol.msize),dim); 
223
+sTrain = som_set('som_train','time',datestr(now,0),'mask',mask);
224
+sMap = som_set('som_map','codebook',codebook,'topol',sTopol,...
225
+                         'neigh',neigh,'labels',labels,'mask',mask,...
226
+                         'comp_names',comp_names,'name',name,...
227
+                         'comp_norm',comp_norm,'trainhist',sTrain);
228
+
229
+
230
+
231
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,89 @@
1
+function Md = som_mdist(D,q,mask,Ne)
2
+
3
+% SOM_MDIST Mutual (or pairwise) distance matrix for the given data.
4
+% 
5
+%   Md = som_mdist(D,[q],[mask],[Ne])
6
+%
7
+%    Md = som_mdist(D); 
8
+%    Md = som_mdist(D,Inf); 
9
+%    Md = som_mdist(D,2,Ne); 
10
+%
11
+%  Input and output arguments ([]'s are optional):
12
+%   D        (matrix) size dlen x dim, the data set
13
+%            (struct) map or data struct
14
+%   [q]      (scalar) distance norm, default = 2
15
+%   [mask]   (vector) size dim x 1, the weighting mask
16
+%   [Ne]     (matrix) size dlen x dlen, sparse matrix 
17
+%                     indicating which distances should be 
18
+%                     calculated (ie. less than Infinite) 
19
+%
20
+% See also PDIST. 
21
+
22
+% Copyright (c) 2000 by Juha Vesanto
23
+% Contributed to SOM Toolbox on XXX by Juha Vesanto
24
+% http://www.cis.hut.fi/projects/somtoolbox/
25
+ 
26
+% Version 2.0beta juuso 220800
27
+
28
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
29
+
30
+% mask
31
+if nargin<3, mask = []; end
32
+
33
+% the data
34
+if isstruct(D), 
35
+  switch D.type, 
36
+   case 'som_map', if isempty(mask), mask = D.mask; end, D = D.codebook; 
37
+   case 'som_data', D = D.data; 
38
+   otherwise, error('Bad first argument');
39
+  end
40
+end
41
+nans = sum(isnan(D),2);
42
+if any(nans>0), 
43
+  D(find(nans>0),:) = 0; 
44
+  warning('Distances of vectors with NaNs are not calculated.'); 
45
+end
46
+[dlen dim] = size(D);
47
+
48
+% distance norm
49
+if nargin<2 | isempty(q) | isnan(q), q = 2; end
50
+
51
+% mask
52
+if isempty(mask), mask = ones(dim,1); end
53
+
54
+% connections 
55
+if nargin<4, Ne = []; end
56
+if ~isempty(Ne), 
57
+  l = size(Ne,1); Ne([0:l-1]*l+[1:l]) = 1; % set diagonal elements = 1
58
+end
59
+
60
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
61
+
62
+m = mask; 
63
+o = ones(dlen,1); 
64
+l = dlen; 
65
+Md = zeros(dlen);
66
+calculate_all = isempty(Ne); 
67
+
68
+if ~calculate_all, Md(Ne==0) = Inf; end
69
+
70
+for i=1:l-1,
71
+  j=(i+1):l; 
72
+  if ~calculate_all, j=find(Ne(i,j))+i; end
73
+  C=D(j,:)-D(i*o(1:length(j)),:);
74
+  switch q, 
75
+   case 1,    Md(j,i)=abs(C)*m;
76
+   case 2,    Md(j,i)=sqrt((C.^2)*m);  
77
+   case Inf,  Md(j,i)=max(diag(m)*abs(C),[],2);
78
+   otherwise, Md(j,i)=((abs(C).^q)*m).^(1/q);
79
+  end   
80
+  Md(i,j) = Md(j,i)';
81
+end
82
+
83
+Md(find(nans>0),:) = NaN; 
84
+Md(:,find(nans>0)) = NaN; 
85
+
86
+return;
87
+
88
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
89
+
... ...
@@ -0,0 +1,247 @@
1
+function sD = som_modify_dataset(sD,action,varargin)
2
+
3
+%SOM_MODIFY_DATASET Add or remove components or samples to/from a data struct.
4
+%
5
+% sD = som_modify_dataset(sD, 'addcomp', D, [indsto], [cnames})
6
+% sD = som_modify_dataset(sD, 'addsamp', D, [indsto], ['norm'])
7
+% sD = som_modify_dataset(sD, 'removecomp', [inds])
8
+% sD = som_modify_dataset(sD, 'removesamp', inds)
9
+% sD = som_modify_dataset(sD, 'extractcomp', [inds])
10
+% sD = som_modify_dataset(sD, 'extractsamp', inds)
11
+% sD = som_modify_dataset(sD, 'movecomp', inds, indsto)
12
+% sD = som_modify_dataset(sD, 'movesamp', inds, indsto)
13
+%
14
+%  Input and output arguments ([]'s are optional)
15
+%   sD      (struct) data struct
16
+%   action  (string) 'addcomp', 'addsamp', 'removecomp', 'removesamp', 
17
+%                    'extractcomp', 'extractsamp', 'movecomp', or 'movesamp' 
18
+%
19
+%   other input arguments depend on the action
20
+%
21
+%   'addcomp': 
22
+%   D        (matrix) data matrix, size [dlen x d]
23
+%            (struct) data struct, size of .data field [dlen x d]
24
+%   [indsto] (vector) new indeces of the components, length=d
25
+%   [cnames] (cellstr) of size d x 1, the component names
26
+%
27
+%   'addsamp': 
28
+%   D        (matrix) data matrix, size [n x dim] 
29
+%   [indsto] (vector) new indeces of the samples, length=n
30
+%   ['norm'] (string) specified if the normalization procedure
31
+%                     should be applied to the new samples
32
+%
33
+%   'removecomp', 'extractcomp': 
34
+%   [inds]   (vector) indeces of the components to be removed/extracted. 
35
+%                     If not given, a prompt will appear from which the
36
+%                     user can select the appropriate components.
37
+%
38
+%   'removesamp', 'extractsamp': 
39
+%   inds     (vector) indeces of the samples to be removed/extracted
40
+%
41
+%   'movecomp', 'movesamp': 
42
+%   inds     (vector) indeces of the components/samples to be moved
43
+%   indsto   (vector) new indeces of the components/samples 
44
+%
45
+% See also SOM_DATA_STRUCT.
46
+
47
+% Copyright (c) 2000 by Juha Vesanto
48
+% Contributed to SOM Toolbox on June 16th, 2000 by Juha Vesanto
49
+% http://www.cis.hut.fi/projects/somtoolbox/
50
+ 
51
+% Version 2.0beta juuso 200400 160600 280800
52
+
53
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
54
+%% input arguments
55
+
56
+[dlen dim] = size(sD.data);
57
+
58
+switch action, 
59
+  case 'addcomp',  
60
+    D = varargin{1};     
61
+    if isstruct(D), [n d] = size(D.data); else [n d] = size(D); end
62
+    if n ~= dlen, error('The number of samples in the data struct and new data should match.'); end
63
+    indsto = []; 
64
+    cnames = []; 
65
+    for i=2:length(varargin), 
66
+      if isnumeric(varargin{i}), 
67
+	indsto = varargin{i}; 
68
+	if length(indsto) ~= d, 
69
+	  error('The number of indeces should match the number of new components'); 
70
+	end
71
+      else
72
+	if ischar(varargin{i}), cnames = cellstr(varargin{i}); 
73
+	elseif iscellstr(varargin{i}), cnames = varargin{i}; 
74
+	else
75
+	  error(['[som_modify_dataset] Unrecognized argument #' num2str(i+1)]); 
76
+	end	
77
+	if length(cnames) ~= d, 
78
+	  error('The number of component names should match the number of new components'); 
79
+	end
80
+      end
81
+    end
82
+ case 'addsamp',
83
+  D = varargin{1};
84
+  if isstruct(D), 
85
+    lab = D.labels; 
86
+    if isfield(D,'data'), D = D.data; else D = D.codebook; end
87
+  else lab = []; 
88
+  end
89
+  [n d] = size(D); 
90
+  if d ~= dim, 
91
+    error(['The dimensions of the old and new data sets should match.']); 
92
+  end
93
+  norm = 0; 
94
+  indsto = []; 
95
+  for i=2:length(varargin),
96
+    if ischar(varargin{i}) & strcmp(varargin{i},'norm'), norm = 1; 
97
+    elseif isnumeric(varargin{i}), 
98
+      indsto = varargin{i}; 
99
+      if length(indsto) ~= n, 
100
+	error(['The number of new indeces should match the number of new' ...
101
+	       ' samples']); 
102
+      end
103
+    else
104
+      warning(['[som_modify_dataset] Ignoring unrecognized argument #', ...
105
+	       num2str(i+2)]);
106
+    end
107
+  end
108
+ case 'removecomp',
109
+  if length(varargin)>0, 
110
+    inds = varargin{1};
111
+  else
112
+    [inds, ok] = listdlg('ListString',sD.comp_names, 'PromptString', ...
113
+                         'Components', 'Name', 'Remove components', 'uh', 25);
114
+    if ~ok, return; end
115
+  end
116
+  if min(inds)<1 | max(inds)>dim, 
117
+    error('The component indeces must be within [1,dim]'); 
118
+  end
119
+ case 'removesamp',
120
+  inds = varargin{1};
121
+  if min(inds)<1 | max(inds)>dlen, 
122
+    error('The sample indeces must be within [1,dlen]'); 
123
+  end
124
+ case 'extractcomp',
125
+  if length(varargin)>0, 
126
+    inds = varargin{1};
127
+  else
128
+    [inds, ok] = listdlg('ListString',sD.comp_names, 'PromptString',... 
129
+                         'Components', 'Name', 'Extract components', 'uh', 25);
130
+    if ~ok, return; end
131
+  end
132
+  if min(inds)<1 | max(inds)>dim, 
133
+    error('The component indeces must be within [1,dim]'); 
134
+  end
135
+ case 'extractsamp',
136
+  inds = varargin{1};
137
+  if min(inds)<1 | max(inds)>dlen, 
138
+    error('The sample indeces must be within [1,dlen]'); 
139
+  end
140
+ case 'movecomp',
141
+  inds = varargin{1};
142
+  indsto = varargin{2};
143
+  if min(inds)<1 | max(inds)>dim | min(indsto)<1 | max(indsto)>dim, 
144
+    error('The component indeces must be within [1,dim]'); 
145
+  end
146
+ case 'movesamp',
147
+  inds = varargin{1};
148
+  indsto = varargin{2};
149
+  if min(inds)<1 | max(inds)>dlen | min(indsto)<1 | max(indsto)>dlen, 
150
+    error('The sample indeces must be within [1,dlen]'); 
151
+  end
152
+ otherwise, 
153
+  error('Unrecognized action mode');
154
+end   
155
+
156
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
157
+%% action
158
+
159
+switch action, 
160
+  case 'addcomp', 
161
+    if isstruct(D),       
162
+      sD.data = [sD.data, D.data]; 
163
+      sD.comp_names(dim+[1:d]) = D.comp_names; 
164
+      sD.comp_norm(dim+[1:d]) = D.comp_norm; 
165
+      sD = som_label(sD,'add',1:dlen,D.labels);
166
+    else
167
+      sD.data = [sD.data, D];
168
+      if isempty(cnames), 
169
+	for i=1:d, sD.comp_names(dim+i) = {sprintf('Variable%d',i+dim)}; end
170
+      else
171
+	sD.comp_names(dim+[1:d]) = cnames; 
172
+      end
173
+      for i=1:d, sD.comp_norm(dim+i) = {[]}; end
174
+    end
175
+    if ~isempty(indsto), 
176
+      sD = som_modify_dataset(sD,'movecomp',dim+[1:d],indsto);
177
+    end
178
+
179
+  case 'addsamp', 
180
+    if norm, D = som_normalize(D,sD); end
181
+    sD.data = [sD.data; D]; 
182
+    nl = size(sD.labels,2); 
183
+    sD.labels(dlen+[1:n],1:nl) = {''};
184
+    if ~isempty(lab), 
185
+      nl2 = size(lab,2); 
186
+      if nl2>nl, sD.labels(1:dlen,nl+[1:(nl2-nl)]) = {''}; end
187
+      sD.labels(dlen+[1:n],1:nl2) = lab; 
188
+    end
189
+    if ~isempty(indsto), 
190
+      sD = som_modify_dataset(sD,'movesamp',dlen+[1:n],indsto);
191
+    end
192
+
193
+  case 'removecomp', 
194
+    includeinds = 1:dim; 
195
+    includeinds(inds) = 0; 
196
+    sD = som_modify_dataset(sD,'extractcomp',find(includeinds));
197
+
198
+  case 'removesamp', 
199
+    includeinds = 1:dlen; 
200
+    includeinds(inds) = 0; 
201
+    sD = som_modify_dataset(sD,'extractsamp',find(includeinds));
202
+
203
+  case 'extractcomp', 
204
+    sD.data = sD.data(:,inds);
205
+    sD.comp_names = sD.comp_names(inds);
206
+    sD.comp_norm = sD.comp_norm(inds);    
207
+
208
+  case 'extractsamp', 
209
+    sD.data = sD.data(inds,:);
210
+    sD.labels = sD.labels(inds,:);
211
+
212
+  case 'movecomp', 
213
+    [indsto,order] = sort(indsto);
214
+    inds = inds(order);
215
+    oldinds = 1:dim; 
216
+    oldinds(inds) = 0; 
217
+    newinds = oldinds(oldinds>0);
218
+    for i=1:length(indsto),
219
+      ifrom = inds(i); ito = indsto(i);
220
+      if ito==1, newinds = [ifrom, newinds];
221
+      else newinds = [newinds(1:ito-1), ifrom, newinds(ito:end)];
222
+      end
223
+    end
224
+    sD.data = sD.data(:,newinds); 
225
+    sD.comp_names = sD.comp_names(:,newinds); 
226
+    sD.comp_norm = sD.comp_norm(:,newinds); 
227
+
228
+  case 'movesamp', 
229
+    [indsto,order] = sort(indsto);
230
+    inds = inds(order);
231
+    oldinds = 1:dim; 
232
+    oldinds(inds) = 0; 
233
+    newinds = oldinds(oldinds>0);
234
+    for i=1:length(indsto),
235
+      ifrom = inds(i); ito = indsto(i);
236
+      if ito==1, newinds = [ifrom, newinds];
237
+      else newinds = [newinds(1:ito-1), ifrom, newinds(ito:end)];
238
+      end
239
+    end
240
+    sD.data = sD.data(newinds,:);
241
+    sD.labels = sD.labels(newinds,:);
242
+
243
+end
244
+
245
+%som_set(sD);
246
+
247
+
... ...
@@ -0,0 +1,157 @@
1
+function Ne = som_neighborhood(Ne1,n)
2
+
3
+%SOM_NEIGHBORHOOD Calculate neighborhood matrix.
4
+%
5
+% Ne = som_neighborhood(Ne1,n)
6
+% 
7
+%  Ne = som_neighborhood(Ne1);
8
+%  Ne = som_neighborhood(som_unit_neighs(topol),2);
9
+%
10
+%  Input and output arguments ([]'s are optional): 
11
+%   Ne1       (matrix, size [munits m]) a sparse matrix indicating
12
+%                      the units in 1-neighborhood for each map unit
13
+%   [n]       (scalar) maximum neighborhood which is calculated, default=Inf
14
+% 
15
+%   Ne        (matrix, size [munits munits]) neighborhood matrix,
16
+%                      each row (and column) contains neighborhood
17
+%                      values from the specific map unit to all other
18
+%                      map units, or Inf if the value is unknown.
19
+%
20
+% For more help, try 'type som_neighborhood' or check out online documentation.
21
+% See also SOM_UNIT_NEIGHS, SOM_UNIT_DISTS, SOM_UNIT_COORDS, SOM_CONNECTION.
22
+
23
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
24
+%
25
+% som_neighborhood
26
+%
27
+% PURPOSE
28
+%
29
+% Calculate to which neighborhood each map unit belongs to relative to
30
+% each other map unit, given the units in 1-neighborhood of each unit.
31
+%
32
+% SYNTAX
33
+%
34
+%  Ne = som_neighborhood(Ne1);
35
+%  Ne = som_neighborhood(Ne1,n);
36
+%
37
+% DESCRIPTION
38
+%
39
+% For each map unit, finds the minimum neighborhood to which it belongs
40
+% to relative to each other map unit. Or, equivalently, for each map 
41
+% unit, finds which units form its k-neighborhood, where k goes from 
42
+% 0 to n. 
43
+%
44
+% The neighborhood is calculated iteratively using the reflexivity of
45
+% neighborhood.
46
+%     let  N1i  be the 1-neighborhood set a unit i
47
+% and let  N11i be the set of units in the 1-neighborhood of any unit j in N1i
48
+%     then N2i  (the 2-neighborhood set of unit i) is N11i \ N1i
49
+%
50
+% Consider, for example, the case of a 5x5 map. The neighborhood in case of
51
+% 'rect' and 'hexa' lattices (and 'sheet' shape) for the unit at the
52
+% center of the map are depicted below: 
53
+% 
54
+%   'rect' lattice           'hexa' lattice
55
+%   --------------           --------------
56
+%   4  3  2  3  4            3  2  2  2  3
57
+%   3  2  1  2  3             2  1  1  2  3
58
+%   2  1  0  1  2            2  1  0  1  2
59
+%   3  2  1  2  3             2  1  1  2  3
60
+%   4  3  2  3  4            3  2  2  2  3
61
+% 
62
+% Because the iterative procedure is rather slow, the neighborhoods 
63
+% are calculated upto given maximal value. The uncalculated values
64
+% in the returned matrix are Inf:s.
65
+% 
66
+% REQUIRED INPUT ARGUMENTS
67
+% 
68
+%  Ne1   (matrix) Each row contains 1, if the corresponding unit is adjacent 
69
+%                 for that map unit, 0 otherwise. This can be calculated 
70
+%                 using SOM_UNIT_NEIGHS. The matrix can be sparse.
71
+%                 Size munits x munits.
72
+%
73
+% OPTIONAL INPUT ARGUMENTS
74
+%
75
+%  n     (scalar) Maximal neighborhood value which is calculated, 
76
+%                 Inf by default (all neighborhoods).
77
+%
78
+% OUTPUT ARGUMENTS
79
+%
80
+%  Ne    (matrix) neighborhood values for each map unit, size is
81
+%                 [munits, munits]. The matrix contains the minimum
82
+%                 neighborhood of unit i, to which unit j belongs, 
83
+%                 or Inf, if the neighborhood was bigger than n.
84
+%
85
+% EXAMPLES
86
+%
87
+%  Ne = som_neighborhood(Ne1,1);    % upto 1-neighborhood
88
+%  Ne = som_neighborhood(Ne1,Inf);  % all neighborhoods
89
+%  Ne = som_neighborhood(som_unit_neighs(topol),4);
90
+%
91
+% SEE ALSO
92
+% 
93
+%  som_unit_neighs   Calculate units in 1-neighborhood for each map unit.
94
+%  som_unit_coords   Calculate grid coordinates.
95
+%  som_unit_dists    Calculate interunit distances.
96
+%  som_connection    Connection matrix.
97
+
98
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
99
+% http://www.cis.hut.fi/projects/somtoolbox/
100
+
101
+% Version 1.0beta juuso 141097
102
+% Version 2.0beta juuso 101199
103
+
104
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
105
+%% Check arguments 
106
+
107
+error(nargchk(1, 2, nargin));
108
+
109
+if nargin<2, n=Inf; end
110
+
111
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
112
+%% Action
113
+
114
+% initialize
115
+if issparse(Ne1), Ne = full(Ne1); else Ne = Ne1; end
116
+clear Ne1
117
+[munits dummy] = size(Ne);
118
+Ne(find(Ne==0)) = NaN;
119
+for i=1:munits, Ne(i,i)=0; end
120
+
121
+% Calculate neighborhood distance for each unit using reflexsivity
122
+% of neighborhood: 
123
+%   let  N1i be the 1-neighborhood set a unit i
124
+%   then N2i is the union of all map units, belonging to the 
125
+%        1-neighborhood of any unit j in N1i, not already in N1i
126
+k=1; 
127
+if n>1, 
128
+  fprintf(1,'Calculating neighborhood: 1 '); 
129
+  N1 = Ne; 
130
+  N1(find(N1~=1)) = 0;   
131
+end
132
+while k<n & any(isnan(Ne(:))),
133
+  k=k+1;
134
+  fprintf(1,'%d ',k);
135
+  for i=1:munits,
136
+    candidates = isnan(Ne(i,:));              % units not in any neighborhood yet
137
+    if any(candidates), 
138
+      prevneigh = find(Ne(i,:)==k-1);         % neighborhood (k-1)
139
+      N1_of_prevneigh = any(N1(prevneigh,:)); % union of their N1:s
140
+      Nn = find(N1_of_prevneigh & candidates); 
141
+      if length(Nn), Ne(i,Nn) = k; Ne(Nn,i) = k; end
142
+    end
143
+  end
144
+end
145
+if n>1, fprintf(1,'\n'); end
146
+
147
+% finally replace all uncalculated distance values with Inf
148
+Ne(find(isnan(Ne))) = Inf;
149
+
150
+return;
151
+
152
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
153
+%% faster version? 
154
+
155
+l = size(Ne1,1); Ne1([0:l-1]*(l+1)+1) = 1; Ne = full(Ne1); M0 = Ne1; k = 2; 
156
+while any(Ne(:)==0), M1=(M0*Ne1>0); Ne(find(M1-M0))=k; M0=M1; k=k+1; end
157
+Ne([0:l-1]*(l+1)+1) = 0;
... ...
@@ -0,0 +1,46 @@
1
+function Ne = som_neighbors(sM,neigh)
2
+
3
+% Ne = som_neighbors(sM,neigh)
4
+%
5
+% sM      (struct) map or data struct
6
+%         (matrix) data matrix, size n x dim
7
+% [neigh] (string) 'kNN' or 'Nk' (which is valid for a SOM only)
8
+%                  for example '6NN' or 'N1'
9
+%                  default is '10NN' for a data set and 'N1' for SOM
10
+%
11
+% Ne      (matrix) size n x n, a sparse matrix
12
+%                  indicating the neighbors of each sample by value 1 
13
+%                  (note: the unit itself also has value 0)
14
+
15
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
16
+
17
+if isstruct(sM), 
18
+  switch sM.type, 
19
+   case 'som_map',  M = sM.codebook; 
20
+   case 'som_data', M = sM.data; sM = []; 
21
+  end
22
+else
23
+  M = sM; 
24
+  sM = []; 
25
+end
26
+
27
+n = size(M,1);
28
+
29
+if nargin<2, 
30
+  if isempty(sM), neigh = '10NN'; else neigh = 'N1'; end
31
+end
32
+
33
+if strcmp(neigh(end-1:end),'NN'),
34
+  k  = str2num(neigh(1:end-2));
35
+  kmus = som_bmus(M,M,1:k+1);
36
+  Ne = sparse(n,n);
37
+  for i=1:n, Ne(i,kmus(i,:)) = 1; end
38
+else
39
+  if ~isstruct(sM), error('Prototypes must be in a map struct.'); end      
40
+  k  = str2num(neigh(2:end));
41
+  N1 = som_unit_neighs(sM);    
42
+  Ne = sparse(som_neighborhood(N1,k)<=k);
43
+end
44
+Ne([0:n-1]*n+[1:n]) = 0; % remove self from neighbors
45
+
46
+return;
0 47
\ No newline at end of file
... ...
@@ -0,0 +1,117 @@
1
+function H = som_neighf(sMap,radius,neigh,ntype)
2
+
3
+%SOM_NEIGHF Return neighborhood function values.
4
+%
5
+% H = som_neighf(sMap,[radius],[neigh],[ntype]);
6
+% 
7
+%  Input and output arguments ([]'s are optional): 
8
+%   sMap     (struct) map or topology struct
9
+%   [radius] (scalar) neighborhood radius (by default, the last used value
10
+%                     in sMap.trainhist is used, or 1 if that is unavailable)
11
+%   [neigh]  (string) neighborhood function type (by default, ..., or 
12
+%                     'gaussian' if that is unavailable)
13
+%   [ntype]  (string) 'normal' (default), 'probability' or 'mirror'
14
+%
15
+%   H        (matrix) [munits x munits] neighborhood function values from 
16
+%                     each map unit to each other map unit
17
+%
18
+% For more help, try 'type som_batchtrain' or check out online documentation.
19
+% See also  SOM_MAKE, SOM_SEQTRAIN, SOM_TRAIN_STRUCT.
20
+
21
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
22
+% http://www.cis.hut.fi/projects/somtoolbox/
23
+
24
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
25
+%% Check arguments 
26
+
27
+% defaults
28
+rdefault = 1; 
29
+ndefault = 'gaussian';
30
+tdefault = 'normal';
31
+
32
+% map 
33
+switch sMap.type, 
34
+ case 'som_map',   
35
+   sTopol = sMap.topol; 
36
+   sTrain = sMap.trainhist(end); 
37
+   if isempty(sTrain.radius_fin) | isnan(sTrain.radius_fin), 
38
+     rdefault = 1; 
39
+   else
40
+     rdefault = sTrain.radius_fin;
41
+   end
42
+   if ~isempty(sTrain.neigh) & ~isnan(sTrain.neigh), 
43
+     ndefault = sTrain.neigh;
44
+   end
45
+ case 'som_topol', sTopol = sMap; 
46
+end
47
+munits = prod(sTopol.msize); 
48
+
49
+% other parameters
50
+if nargin<2 | isempty(radius), radius = rdefault; end
51
+if nargin<3 | isempty(neigh), neigh = ndefault; end
52
+if nargin<4 | isempty(ntype), ntype = tdefault; end
53
+
54
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
55
+%% initialize
56
+                                   
57
+% basic neighborhood 
58
+Ud = som_unit_dists(sTopol);
59
+Ud = Ud.^2;
60
+radius = radius.^2;
61
+if radius==0, radius = eps; end % zero neighborhood radius may cause div-by-zero error
62
+
63
+switch ntype, 
64
+case 'normal', 
65
+    H = neighf(neigh,Ud,radius); 
66
+case 'probability', 
67
+    H = neighf(neigh,Ud,radius); 
68
+    for i=1:munits, H(i,:) = H(i,:)/sum(H(i,:)); end
69
+case 'mirror', % only works for 2-dim grid!!!
70
+    H  = zeros(munits,munits);
71
+    Co = som_unit_coords(sTopol); 
72
+    for i=-1:1,
73
+        for j=-1:1,
74
+           Ud = gridmirrordist(Co,i,j);
75
+           H  = H + neighf(neigh,Ud,radius); 
76
+        end
77
+    end    
78
+end     
79
+
80
+return;
81
+
82
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
83
+%% subfunctions
84
+
85
+function H = neighf(neigh,Ud,radius)
86
+
87
+ switch neigh, 
88
+ case 'bubble',   H = (Ud<=radius); 
89
+ case 'gaussian', H = exp(-Ud/(2*radius)); 
90
+ case 'cutgauss', H = exp(-Ud/(2*radius)) .* (Ud<=radius);
91
+ case 'ep',       H = (1-Ud/radius) .* (Ud<=radius);
92
+ end  
93
+ return; 
94
+
95
+function Ud = gridmirrordist(Co,mirrorx,mirrory)
96
+
97
+ [munits,mdim] = size(Co); 
98
+ if mdim>2, error('Mirrored neighborhood only works for 2-dim map grids.'); end
99
+   
100
+ % width and height of the grid
101
+ dx = max(Co(:,1))-min(Co(:,1));
102
+ dy = max(Co(:,2))-min(Co(:,2));
103
+
104
+ % calculate distance from each location to each other location
105
+ Ud = zeros(munits,munits);
106
+ for i=1:munits, 
107
+   inds = [i:munits]; 
108
+   coi = Co(i,:); % take hexagonal shift into account
109
+   coi(1) = coi(1)*(1-2*(mirrorx~=0)) + 2*dx*(mirrorx==1); % +mirrorx * step
110
+   coi(2) = coi(2)*(1-2*(mirrory~=0)) + 2*dy*(mirrory==1); % +mirrory * step
111
+   Dco = (Co(inds,:) - coi(ones(munits-i+1,1),:))'; 
112
+   Ud(i,inds) = sqrt(sum(Dco.^2));
113
+   Ud(inds,i) = Ud(i,inds)'; 
114
+ end
115
+ return; 
116
+
117
+
... ...
@@ -0,0 +1,533 @@
1
+function [x,sNorm] = som_norm_variable(x, method, operation)
2
+
3
+%SOM_NORM_VARIABLE Normalize or denormalize a scalar variable.
4
+%
5
+% [x,sNorm] = som_norm_variable(x, method, operation)
6
+%
7
+%   xnew = som_norm_variable(x,'var','do');
8
+%   [dummy,sN] = som_norm_variable(x,'log','init');
9
+%   [xnew,sN]  = som_norm_variable(x,sN,'do');
10
+%   xorig      = som_norm_variable(xnew,sN,'undo');
11
+%
12
+%  Input and output arguments: 
13
+%   x         (vector) a set of values of a scalar variable for
14
+%                      which the (de)normalization is performed.
15
+%                      The processed values are returned.
16
+%   method    (string) identifier for a normalization method: 'var',
17
+%                      'range', 'log', 'logistic', 'histD', or 'histC'.
18
+%                      A normalization struct with default values is created.
19
+%             (struct) normalization struct, or an array of such
20
+%             (cellstr) first string gives normalization operation, and the
21
+%                      second gives denormalization operation, with x 
22
+%                      representing the variable, for example: 
23
+%                      {'x+2','x-2}, or {'exp(-x)','-log(x)'} or {'round(x)'}.
24
+%                      Note that in the last case, no denorm operation is 
25
+%                      defined. 
26
+%   operation (string) the operation to be performed: 'init', 'do' or 'undo'
27
+%                     
28
+%   sNorm     (struct) updated normalization struct/struct array
29
+%
30
+% For more help, try 'type som_norm_variable' or check out online documentation.
31
+% See also SOM_NORMALIZE, SOM_DENORMALIZE.
32
+
33
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
34
+%
35
+% som_norm_variable
36
+%
37
+% PURPOSE
38
+%
39
+% Initialize, apply and undo normalizations on a given vector of
40
+% scalar values.
41
+%
42
+% SYNTAX
43
+%
44
+%  xnew = som_norm_variable(x,method,operation)
45
+%  xnew = som_norm_variable(x,sNorm,operation)
46
+%  [xnew,sNorm] = som_norm_variable(...)
47
+%
48
+% DESCRIPTION
49
+%
50
+% This function is used to initialize, apply and undo normalizations
51
+% on scalar variables. It is the low-level function that upper-level
52
+% functions SOM_NORMALIZE and SOM_DENORMALIZE utilize to actually (un)do
53
+% the normalizations.
54
+%
55
+% Normalizations are typically performed to control the variance of 
56
+% vector components. If some vector components have variance which is
57
+% significantly higher than the variance of other components, those
58
+% components will dominate the map organization. Normalization of 
59
+% the variance of vector components (method 'var') is used to prevent 
60
+% that. In addition to variance normalization, other methods have
61
+% been implemented as well (see list below). 
62
+%
63
+% Usually normalizations convert the variable values so that they no 
64
+% longer make any sense: the values are still ordered, but their range 
65
+% may have changed so radically that interpreting the numbers in the 
66
+% original context is very hard. For this reason all implemented methods
67
+% are (more or less) revertible. The normalizations are monotonic
68
+% and information is saved so that they can be undone. Also, the saved
69
+% information makes it possible to apply the EXACTLY SAME normalization
70
+% to another set of values. The normalization information is determined
71
+% with 'init' operation, while 'do' and 'undo' operations are used to
72
+% apply or revert the normalization. 
73
+%
74
+% The normalization information is saved in a normalization struct, 
75
+% which is returned as the second argument of this function. Note that 
76
+% normalization operations may be stacked. In this case, normalization 
77
+% structs are positioned in a struct array. When applied, the array is 
78
+% gone through from start to end, and when undone, in reverse order.
79
+%
80
+%    method  description
81
+%
82
+%    'var'   Variance normalization. A linear transformation which 
83
+%            scales the values such that their variance=1. This is
84
+%            convenient way to use Mahalanobis distance measure without
85
+%            actually changing the distance calculation procedure.
86
+%
87
+%    'range' Normalization of range of values. A linear transformation
88
+%            which scales the values between [0,1]. 
89
+%
90
+%    'log'   Logarithmic normalization. In many cases the values of
91
+%            a vector component are exponentially distributed. This 
92
+%            normalization is a good way to get more resolution to
93
+%            (the low end of) that vector component. What this 
94
+%            actually does is a non-linear transformation: 
95
+%               x_new = log(x_old - m + 1) 
96
+%            where m=min(x_old) and log is the natural logarithm. 
97
+%            Applying the transformation to a value which is lower 
98
+%            than m-1 will give problems, as the result is then complex.
99
+%            If the minimum for values is known a priori, 
100
+%            it might be a good idea to initialize the normalization with
101
+%              [dummy,sN] = som_norm_variable(minimum,'log','init');
102
+%            and normalize only after this: 
103
+%              x_new = som_norm_variable(x,sN,'do');
104
+%
105
+%    'logistic' or softmax normalization. This normalization ensures
106
+%            that all values in the future, too, are within the range
107
+%            [0,1]. The transformation is more-or-less linear in the 
108
+%            middle range (around mean value), and has a smooth 
109
+%            nonlinearity at both ends which ensures that all values
110
+%            are within the range. The data is first scaled as in 
111
+%            variance normalization: 
112
+%               x_scaled = (x_old - mean(x_old))/std(x_old)
113
+%            and then transformed with the logistic function
114
+%               x_new = 1/(1+exp(-x_scaled))
115
+% 
116
+%    'histD' Discrete histogram equalization. Non-linear. Orders the 
117
+%            values and replaces each value by its ordinal number. 
118
+%            Finally, scales the values such that they are between [0,1].
119
+%            Useful for both discrete and continuous variables, but as 
120
+%            the saved normalization information consists of all 
121
+%            unique values of the initialization data set, it may use
122
+%            considerable amounts of memory. If the variable can get
123
+%            more than a few values (say, 20), it might be better to
124
+%            use 'histC' method below. Another important note is that
125
+%            this method is not exactly revertible if it is applied
126
+%            to values which are not part of the original value set.
127
+%            
128
+%    'histC' Continuous histogram equalization. Actually, a partially
129
+%            linear transformation which tries to do something like 
130
+%            histogram equalization. The value range is divided to 
131
+%            a number of bins such that the number of values in each
132
+%            bin is (almost) the same. The values are transformed 
133
+%            linearly in each bin. For example, values in bin number 3
134
+%            are scaled between [3,4[. Finally, all values are scaled
135
+%            between [0,1]. The number of bins is the square root
136
+%            of the number of unique values in the initialization set,
137
+%            rounded up. The resulting histogram equalization is not
138
+%            as good as the one that 'histD' makes, but the benefit
139
+%            is that it is exactly revertible - even outside the 
140
+%            original value range (although the results may be funny).
141
+%
142
+%    'eval'  With this method, freeform normalization operations can be 
143
+%            specified. The parameter field contains strings to be 
144
+%            evaluated with 'eval' function, with variable name 'x'
145
+%            representing the variable itself. The first string is 
146
+%            the normalization operation, and the second is a 
147
+%            denormalization operation. If the denormalization operation
148
+%            is empty, it is ignored.
149
+% 
150
+% INPUT ARGUMENTS
151
+%
152
+%   x          (vector) The scalar values to which the normalization      
153
+%                       operation is applied.
154
+%                     
155
+%   method              The normalization specification.
156
+%              (string) Identifier for a normalization method: 'var', 
157
+%                       'range', 'log', 'logistic', 'histD' or 'histC'. 
158
+%                       Corresponding default normalization struct is created.
159
+%              (struct) normalization struct 
160
+%              (struct array) of normalization structs, applied to 
161
+%                       x one after the other
162
+%              (cellstr) of length 
163
+%              (cellstr array) first string gives normalization operation, and 
164
+%                       the second gives denormalization operation, with x 
165
+%                       representing the variable, for example: 
166
+%                       {'x+2','x-2}, or {'exp(-x)','-log(x)'} or {'round(x)'}.
167
+%                       Note that in the last case, no denorm operation is 
168
+%                       defined. 
169
+%
170
+%               note: if the method is given as struct(s), it is
171
+%                     applied (done or undone, as specified by operation)
172
+%                     regardless of what the value of '.status' field
173
+%                     is in the struct(s). Only if the status is
174
+%                     'uninit', the undoing operation is halted.
175
+%                     Anyhow, the '.status' fields in the returned 
176
+%                     normalization struct(s) is set to approriate value.
177
+%   
178
+%   operation  (string) The operation to perform: 'init' to initialize
179
+%                       the normalization struct, 'do' to perform the 
180
+%                       normalization, 'undo' to undo the normalization, 
181
+%                       if possible. If operation 'do' is given, but the
182
+%                       normalization struct has not yet been initialized,
183
+%                       it is initialized using the given data (x).
184
+%
185
+% OUTPUT ARGUMENTS
186
+% 
187
+%   x        (vector) Appropriately processed values. 
188
+%
189
+%   sNorm    (struct) Updated normalization struct/struct array. If any,
190
+%                     the '.status' and '.params' fields are updated.
191
+% 
192
+% EXAMPLES
193
+%
194
+%  To initialize and apply a normalization on a set of scalar values: 
195
+%
196
+%    [x_new,sN] = som_norm_variable(x_old,'var','do'); 
197
+%
198
+%  To just initialize, use: 
199
+% 
200
+%    [dummy,sN] = som_norm_variable(x_old,'var','init'); 
201
+% 
202
+%  To undo the normalization(s): 
203
+%
204
+%    x_orig = som_norm_variable(x_new,sN,'undo');
205
+%
206
+%  Typically, normalizations of data structs/sets are handled using
207
+%  functions SOM_NORMALIZE and SOM_DENORMALIZE. However, when only the
208
+%  values of a single variable are of interest, SOM_NORM_VARIABLE may 
209
+%  be useful. For example, assume one wants to apply the normalization
210
+%  done on a component (i) of a data struct (sD) to a new set of values 
211
+%  (x) of that component. With SOM_NORM_VARIABLE this can be done with: 
212
+%
213
+%    x_new = som_norm_variable(x,sD.comp_norm{i},'do'); 
214
+% 
215
+%  Now, as the normalizations in sD.comp_norm{i} have already been 
216
+%  initialized with the original data set (presumably sD.data), 
217
+%  the EXACTLY SAME normalization(s) can be applied to the new values.
218
+%  The same thing can be done with SOM_NORMALIZE function, too: 
219
+%
220
+%    x_new = som_normalize(x,sD.comp_norm{i}); 
221
+%
222
+%  Or, if the new data set were in variable D - a matrix of same
223
+%  dimension as the original data set: 
224
+%
225
+%    D_new = som_normalize(D,sD,i);
226
+%
227
+% SEE ALSO
228
+%  
229
+%  som_normalize    Add/apply/redo normalizations for a data struct/set.
230
+%  som_denormalize  Undo normalizations of a data struct/set.
231
+
232
+% Copyright (c) 1998-2000 by the SOM toolbox programming team.
233
+% http://www.cis.hut.fi/projects/somtoolbox/
234
+
235
+% Version 2.0beta juuso 151199 170400 150500
236
+
237
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
238
+%% check arguments
239
+
240
+error(nargchk(3, 3, nargin));  % check no. of input arguments is correct
241
+
242
+% method
243
+sNorm = []; 
244
+if ischar(method) 
245
+  if any(strcmp(method,{'var','range','log','logistic','histD','histC'})), 
246
+    sNorm = som_set('som_norm','method',method);
247
+  else 
248
+    method = cellstr(method); 
249
+  end
250
+end
251
+if iscell(method), 
252
+  if length(method)==1 & isstruct(method{1}), sNorm = method{1}; 
253
+  else
254
+    if length(method)==1 | isempty(method{2}), method{2} = 'x'; end
255
+    sNorm = som_set('som_norm','method','eval','params',method);
256
+  end
257
+else 
258
+  sNorm = method; 
259
+end
260
+
261
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
262
+%% action
263
+
264
+order = [1:length(sNorm)]; 
265
+if length(order)>1 & strcmp(operation,'undo'), order = order(end:-1:1); end
266
+
267
+for i=order, 
268
+
269
+  % initialize
270
+  if strcmp(operation,'init') | ...
271
+     (strcmp(operation,'do') & strcmp(sNorm(i).status,'uninit')), 
272
+
273
+    % case method = 'hist'
274
+    if strcmp(sNorm(i).method,'hist'), 
275
+      inds = find(~isnan(x) & ~isinf(x));
276
+      if length(unique(x(inds)))>20, sNorm(i).method = 'histC'; 
277
+      else sNorm{i}.method = 'histD'; end
278
+    end
279
+
280
+    switch(sNorm(i).method), 
281
+    case 'var',   params = norm_variance_init(x);
282
+    case 'range', params = norm_scale01_init(x);
283
+    case 'log',   params = norm_log_init(x);
284
+    case 'logistic', params = norm_logistic_init(x);
285
+    case 'histD', params = norm_histeqD_init(x);
286
+    case 'histC', params = norm_histeqC_init(x);
287
+    case 'eval',  params = sNorm(i).params; 
288
+    otherwise, 
289
+      error(['Unrecognized method: ' sNorm(i).method]); 
290
+    end
291
+    sNorm(i).params = params;
292
+    sNorm(i).status = 'undone';
293
+  end
294
+
295
+  % do / undo
296
+  if strcmp(operation,'do'), 
297
+    switch(sNorm(i).method), 
298
+    case 'var',   x = norm_scale_do(x,sNorm(i).params);
299
+    case 'range', x = norm_scale_do(x,sNorm(i).params);
300
+    case 'log',   x = norm_log_do(x,sNorm(i).params);
301
+    case 'logistic', x = norm_logistic_do(x,sNorm(i).params);
302
+    case 'histD', x = norm_histeqD_do(x,sNorm(i).params);
303
+    case 'histC', x = norm_histeqC_do(x,sNorm(i).params);
304
+    case 'eval',  x = norm_eval_do(x,sNorm(i).params);
305
+    otherwise, 
306
+      error(['Unrecognized method: ' sNorm(i).method]);
307
+    end
308
+    sNorm(i).status = 'done';
309
+
310
+  elseif strcmp(operation,'undo'), 
311
+
312
+    if strcmp(sNorm(i).status,'uninit'), 
313
+      warning('Could not undo: uninitialized normalization struct.')
314
+      break;
315
+    end
316
+    switch(sNorm(i).method), 
317
+    case 'var',   x = norm_scale_undo(x,sNorm(i).params);
318
+    case 'range', x = norm_scale_undo(x,sNorm(i).params);
319
+    case 'log',   x = norm_log_undo(x,sNorm(i).params);    
320
+    case 'logistic', x = norm_logistic_undo(x,sNorm(i).params);
321
+    case 'histD', x = norm_histeqD_undo(x,sNorm(i).params);
322
+    case 'histC', x = norm_histeqC_undo(x,sNorm(i).params);
323
+    case 'eval',  x = norm_eval_undo(x,sNorm(i).params);
324
+    otherwise, 
325
+      error(['Unrecognized method: ' sNorm(i).method]);
326
+    end
327
+    sNorm(i).status = 'undone';
328
+
329
+  elseif ~strcmp(operation,'init'),
330
+
331
+    error(['Unrecognized operation: ' operation])
332
+
333
+  end
334
+end  
335
+
336
+return;
337
+
338
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
339
+%% subfunctions
340
+
341
+% linear scaling
342
+
343
+function p = norm_variance_init(x)
344
+  inds = find(~isnan(x) & isfinite(x));
345
+  p = [mean(x(inds)), std(x(inds))];
346
+  if p(2) == 0, p(2) = 1; end
347
+  %end of norm_variance_init
348
+
349
+function p = norm_scale01_init(x)
350
+  inds = find(~isnan(x) & isfinite(x));
351
+  mi = min(x(inds)); 
352
+  ma = max(x(inds));
353
+  if mi == ma, p = [mi, 1]; else p = [mi, ma-mi]; end
354
+  %end of norm_scale01_init  
355
+
356
+function x = norm_scale_do(x,p)
357
+  x = (x - p(1)) / p(2);
358
+  % end of norm_scale_do
359
+
360
+function x = norm_scale_undo(x,p)
361
+  x = x * p(2) + p(1);
362
+  % end of norm_scale_undo
363
+
364
+% logarithm
365
+
366
+function p = norm_log_init(x)
367
+  inds = find(~isnan(x) & isfinite(x));
368
+  p = min(x(inds));
369
+  % end of norm_log_init
370
+
371
+function x = norm_log_do(x,p)
372
+  x = log(x - p +1); 
373
+  % if any(~isreal(x)), ok = 0; end
374
+  % end of norm_log_do 
375
+
376
+function x = norm_log_undo(x,p)
377
+  x = exp(x) -1 + p; 
378
+  % end of norm_log_undo 
379
+
380
+% logistic
381
+
382
+function p = norm_logistic_init(x)
383
+  inds = find(~isnan(x) & isfinite(x));
384
+  p = [mean(x(inds)), std(x(inds))];
385
+  if p(2)==0, p(2) = 1; end
386
+  % end of norm_logistic_init
387
+
388
+function x = norm_logistic_do(x,p)
389
+  x = (x-p(1))/p(2);
390
+  x = 1./(1+exp(-x));
391
+  % end of norm_logistic_do
392
+
393
+function x = norm_logistic_undo(x,p)
394
+  x = log(x./(1-x));
395
+  x = x*p(2)+p(1);
396
+  % end of norm_logistic_undo
397
+
398
+% histogram equalization for discrete values
399
+
400
+function p = norm_histeqD_init(x)
401
+  inds = find(~isnan(x) & ~isinf(x));
402
+  p = unique(x(inds));
403
+  % end of norm_histeqD_init
404
+
405
+function x = norm_histeqD_do(x,p)
406
+  bins = length(p);
407
+  inds = find(~isnan(x) & ~isinf(x))';
408
+  for i = inds, 
409
+    [dummy ind] = min(abs(x(i) - p));
410
+    % data item closer to the left-hand bin wall is indexed after RH wall
411
+    if x(i) > p(ind) & ind < bins, 
412
+      x(i) = ind + 1;  
413
+    else 
414
+      x(i) = ind;
415
+    end
416
+  end
417
+  x = (x-1)/(bins-1); % normalization between [0,1]
418
+  % end of norm_histeqD_do 
419
+
420
+function x = norm_histeqD_undo(x,p)
421
+  bins = length(p);
422
+  x = round(x*(bins-1)+1);
423
+  inds = find(~isnan(x) & ~isinf(x));
424
+  x(inds) = p(x(inds));
425
+  % end of norm_histeqD_undo
426
+
427
+% histogram equalization with partially linear functions
428
+
429
+function p = norm_histeqC_init(x)
430
+  % investigate x
431
+  inds = find(~isnan(x) & ~isinf(x));
432
+  samples = length(inds);
433
+  xs = unique(x(inds));
434
+  mi = xs(1);
435
+  ma = xs(end);
436
+  % decide number of limits
437
+  lims = ceil(sqrt(length(xs))); % 2->2,100->10,1000->32,10000->100
438
+  % decide limits
439
+  if lims==1,     
440
+    p = [mi, mi+1];
441
+    lims = 2; 
442
+  elseif lims==2, 
443
+    p = [mi, ma];
444
+  else
445
+    p = zeros(lims,1);   
446
+    p(1) = mi; 
447
+    p(end) = ma;
448
+    binsize = zeros(lims-1,1); b = 1; avebinsize = samples/(lims-1);
449
+    for i=1:(length(xs)-1), 
450
+      binsize(b) = binsize(b) + sum(x==xs(i)); 
451
+      if binsize(b) >= avebinsize, 
452
+        b = b + 1;
453
+        p(b) = (xs(i)+xs(i+1))/2;
454
+      end
455
+      if b==(lims-1), 
456
+        binsize(b) = samples-sum(binsize); break;
457
+      else
458
+        avebinsize = (samples-sum(binsize))/(lims-1-b);
459
+      end
460
+    end
461
+  end
462
+  % end of norm_histeqC_init
463
+
464
+function x = norm_histeqC_do(x,p)
465
+  xnew = x; 
466
+  lims = length(p);
467
+  % handle values below minimum
468
+  r = p(2)-p(1); 
469
+  inds = find(x<=p(1) & isfinite(x)); 
470
+  if any(inds), xnew(inds) = 0-(p(1)-x(inds))/r; end 
471
+  % handle values above maximum
472
+  r = p(end)-p(end-1); 
473
+  inds = find(x>p(end) & isfinite(x)); 
474
+  if any(inds), xnew(inds) = lims-1+(x(inds)-p(end))/r; end
475
+  % handle all other values
476
+  for i=1:(lims-1), 
477
+    r0 = p(i); r1 = p(i+1); r = r1-r0; 
478
+    inds = find(x>r0 & x<=r1); 
479
+    if any(inds), xnew(inds) = i-1+(x(inds)-r0)/r; end
480
+  end
481
+  % scale so that minimum and maximum correspond to 0 and 1
482
+  x = xnew/(lims-1);
483
+  % end of norm_histeqC_do
484
+
485
+function x = norm_histeqC_undo(x,p)
486
+  xnew = x; 
487
+  lims = length(p); 
488
+  % scale so that 0 and 1 correspond to minimum and maximum
489
+  x = x*(lims-1);
490
+
491
+  % handle values below minimum
492
+  r = p(2)-p(1); 
493
+  inds = find(x<=0 & isfinite(x)); 
494
+  if any(inds), xnew(inds) = x(inds)*r + p(1); end 
495
+  % handle values above maximum
496
+  r = p(end)-p(end-1); 
497
+  inds = find(x>lims-1 & isfinite(x)); 
498
+  if any(inds), xnew(inds) = (x(inds)-(lims-1))*r+p(end); end
499
+  % handle all other values
500
+  for i=1:(lims-1), 
501
+    r0 = p(i); r1 = p(i+1); r = r1-r0; 
502
+    inds = find(x>i-1 & x<=i); 
503
+    if any(inds), xnew(inds) = (x(inds)-(i-1))*r + r0; end
504
+  end
505
+  x = xnew;
506
+  % end of norm_histeqC_undo
507
+
508
+% eval
509
+
510
+function p = norm_eval_init(method)
511
+  p = method;
512
+  %end of norm_eval_init
513
+
514
+function x = norm_eval_do(x,p)
515
+  x_tmp = eval(p{1});
516
+  if size(x_tmp,1)>=1 & size(x,1)>=1 & ...
517
+     size(x_tmp,2)==1 & size(x,2)==1,
518
+    x = x_tmp;
519
+  end
520
+  %end of norm_eval_do
521
+
522
+function x = norm_eval_undo(x,p)
523
+  x_tmp = eval(p{2});
524
+  if size(x_tmp,1)>=1 & size(x,1)>=1 & ...
525
+     size(x_tmp,2)==1 & size(x,2)==1,
526
+    x = x_tmp;
527
+  end
528
+  %end of norm_eval_undo
529
+
530
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
531
+
532
+
533
+
... ...
@@ -0,0 +1,319 @@
1
+function sD = som_normalize(sD,method,comps)
2
+
3
+%SOM_NORMALIZE (Re)normalize data or add new normalizations.
4
+%   
5
+% sS = som_normalize(sS,[method],[comps])               
6
+%
7
+%   sS = som_normalize(sD) 
8
+%   sS = som_normalize(sS,sNorm) 
9
+%    D = som_normalize(D,'var')
10
+%   sS = som_normalize(sS,'histC',[1:3 10])
11
+%
12
+%  Input and output arguments ([]'s are optional): 
13
+%   sS                The data to which the normalization is applied.
14
+%                     The modified and updated data is returned.
15
+%            (struct) data or map struct
16
+%            (matrix) data matrix (a matrix is also returned)
17
+%   [method]          The normalization method(s) to add/use. If missing, 
18
+%                     or an empty variable ('') is given, the 
19
+%                     normalizations in sS are used.
20
+%            (string) identifier for a normalization method to be added: 
21
+%                     'var', 'range', 'log', 'logistic', 'histD' or 'histC'. 
22
+%            (struct) Normalization struct, or an array of such. 
23
+%                     Alternatively, a map/data struct can be given 
24
+%                     in which case its '.comp_norm' field is used 
25
+%                     (see below).
26
+%            (cell array) Of normalization structs. Typically, the
27
+%                     '.comp_norm' field of a map/data struct. The 
28
+%                     length of the array must be equal to data dimension.
29
+%            (cellstr array) norm and denorm operations in a cellstr array
30
+%                     which are evaluated with EVAL command with variable
31
+%                     name 'x' reserved for the variable.
32
+%   [comps]  (vector) the components to which the normalization is
33
+%                     applied, default is [1:dim] ie. all components
34
+%
35
+% For more help, try 'type som_normalize' or check out online documentation.
36
+% See also SOM_DENORMALIZE, SOM_NORM_VARIABLE, SOM_INFO.
37
+
38
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
39
+%
40
+% som_normalize
41
+%
42
+% PURPOSE
43
+%
44
+% Add/apply/redo normalization on data structs/sets.
45
+%
46
+% SYNTAX
47
+%
48
+%  sS = som_normalize(sS)
49
+%  sS = som_normalize(sS,method)
50
+%   D = som_normalize(D,sNorm)
51
+%  sS = som_normalize(sS,csNorm)
52
+%  sS = som_normalize(...,comps)
53
+%
54
+% DESCRIPTION
55
+%
56
+% This function is used to (initialize and) add, redo and apply 
57
+% normalizations on data/map structs/sets. If a data/map struct is given, 
58
+% the specified normalizations are added to the '.comp_norm' field of the 
59
+% struct after ensuring that all normalizations specified therein have
60
+% status 'done'. SOM_NORMALIZE actually uses function SOM_NORM_VARIABLE 
61
+% to handle the normalization operations, and only handles the data 
62
+% struct/set specific stuff itself.
63
+%
64
+% The different normalization methods are listed below. For more 
65
+% detailed descriptions, see SOM_NORM_VARIABLE.
66
+%  
67
+%   method     description
68
+%   'var'      Variance is normalized to one (linear operation).
69
+%   'range'    Values are normalized between [0,1] (linear operation).
70
+%   'log'      Natural logarithm is applied to the values: 
71
+%                xnew = log(x-m+1)
72
+%              where m = min(x).
73
+%   'logistic' Logistic or softmax trasformation which scales all
74
+%              possible values between [0,1].
75
+%   'histD'    Histogram equalization, values scaled between [0,1].
76
+%   'histC'    Approximate histogram equalization with partially 
77
+%              linear operations. Values scaled between [0,1].
78
+%   'eval'     freeform operations
79
+%  
80
+% To enable undoing and applying the exactly same normalization to
81
+% other data sets, normalization information is saved into a 
82
+% normalization struct, which has the fields: 
83
+% 
84
+%   .type   ; struct type, ='som_norm'
85
+%   .method ; normalization method, a string
86
+%   .params ; normalization parameters
87
+%   .status ; string: 'uninit', 'undone' or 'done'
88
+%
89
+% Normalizations are always one-variable operations. In the data and map
90
+% structs the normalization information for each component is saved in the
91
+% '.comp_norm' field, which is a cell array of length dim. Each cell
92
+% contains normalizations for one vector component in a struct array of
93
+% normalization structs. Each component may have different amounts of
94
+% different kinds of normalizations. Typically, all normalizations are
95
+% either 'undone' or 'done', but in special situations this may not be the
96
+% case. The easiest way to check out the status of the normalizations is to
97
+% use function SOM_INFO, e.g. som_info(sS,3)
98
+%
99
+% REQUIRED INPUT ARGUMENTS
100
+%
101
+%   sS                The data to which the normalization is applied.
102
+%            (struct) Data or map struct. Before adding any new 
103
+%                     normalizations, it is ensured that the
104
+%                     normalizations for the specified components in the
105
+%                     '.comp_norm' field have status 'done'. 
106
+%            (matrix) data matrix 
107
+%
108
+% OPTIONAL INPUT ARGUMENTS
109
+%
110
+%   method            The normalization(s) to add/use. If missing, 
111
+%                     or an empty variable ('' or []) is given, the 
112
+%                     normalizations in the data struct are used.
113
+%            (string) Identifier for a normalization method to be added: 
114
+%                     'var', 'range', 'log', 'logistic', 'histD' or 'histC'. The 
115
+%                     same method is applied to all specified components
116
+%                     (given in comps). The normalizations are first 
117
+%                     initialized (for each component separately, of
118
+%                     course) and then applied.
119
+%            (struct) Normalization struct, or an array of structs, which
120
+%                     is applied to all specified components. If the 
121
+%                     '.status' field of the struct(s) is 'uninit', 
122
+%                     the normalization(s) is initialized first.
123
+%                     Alternatively, the struct may be map or data struct
124
+%                     in which case its '.comp_norm' field is used
125
+%                     (see the cell array option below).
126
+%            (cell array) In practice, the '.comp_norm' field of 
127
+%                     a data/map struct. The length of the array 
128
+%                     must be equal to the dimension of the given 
129
+%                     data set (sS). Each cell contains the
130
+%                     normalization(s) for one component. Only the
131
+%                     normalizations listed in comps argument are
132
+%                     applied though.
133
+%            (cellstr array) norm and denorm operations in a cellstr array
134
+%                     which are evaluated with EVAL command with variable
135
+%                     name 'x' reserved for the variable.
136
+%
137
+%   comps    (vector) The components to which the normalization(s) is
138
+%                     applied. Default is to apply to all components.
139
+%
140
+% OUTPUT ARGUMENTS
141
+% 
142
+%   sS                Modified and/or updated data.
143
+%            (struct) If a struct was given as input argument, the
144
+%                     same struct is returned with normalized data and
145
+%                     updated '.comp_norm' fields. 
146
+%            (matrix) If a matrix was given as input argument, the 
147
+%                     normalized data matrix is returned.
148
+% 
149
+% EXAMPLES
150
+%
151
+%  To add (initialize and apply) a normalization to a data struct: 
152
+%
153
+%    sS = som_normalize(sS,'var'); 
154
+%
155
+%  This uses 'var'-method to all components. To add a method only to
156
+%  a few selected components, use the comps argument: 
157
+% 
158
+%    sS = som_normalize(sS,'log',[1 3:5]); 
159
+% 
160
+%  To ensure that all normalization operations have indeed been done: 
161
+% 
162
+%    sS = som_normalize(sS); 
163
+%
164
+%  The same for only a few components: 
165
+%
166
+%    sS = som_normalize(sS,'',[1 3:5]); 
167
+% 
168
+%  To apply the normalizations of a data struct sS to a new data set D: 
169
+%
170
+%    D = som_normalize(D,sS); 
171
+%  or 
172
+%    D = som_normalize(D,sS.comp_norm); 
173
+% 
174
+%  To normalize a data set: 
175
+%
176
+%    D = som_normalize(D,'histD'); 
177
+%
178
+%  Note that in this case the normalization information is lost.
179
+%
180
+%  To check out the status of normalization in a struct use SOM_INFO: 
181
+% 
182
+%    som_info(sS,3)
183
+%
184
+%
185
+% SEE ALSO
186
+%  
187
+%  som_denormalize    Undo normalizations of a data struct/set.
188
+%  som_norm_variable  Normalization operations for a set of scalar values.
189
+%  som_info           User-friendly information of SOM Toolbox structs.
190
+
191
+% Copyright (c) 1998-2000 by the SOM toolbox programming team.
192
+% http://www.cis.hut.fi/projects/somtoolbox/
193
+
194
+% Version 2.0beta juuso 151199 150500
195
+
196
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
197
+%% check arguments
198
+
199
+error(nargchk(1, 3, nargin));  % check no. of input arguments is correct
200
+
201
+% sD
202
+struct_mode = isstruct(sD);
203
+if struct_mode, 
204
+  switch sD.type
205
+   case 'som_map', D = sD.codebook; 
206
+   case 'som_data', D = sD.data; 
207
+   otherwise, error('Illegal struct.')
208
+  end
209
+else 
210
+  D = sD;
211
+end
212
+[dlen dim] = size(D);
213
+
214
+% comps
215
+if nargin<3 | (ischar(comps) & strcmp(comps,'all')), 
216
+  comps = [1:dim]; 
217
+end
218
+if isempty(comps), return; end
219
+if size(comps,1)>1, comps = comps'; end  % make it a row vector
220
+
221
+% method
222
+csNorm = cell(dim,1); 
223
+if nargin<2 | isempty(method), 
224
+  if ~struct_mode, 
225
+    warning('No normalization method given. Data left unchanged.');
226
+    return; 
227
+  end
228
+  method = '';
229
+else  
230
+  % check out the given method 
231
+  % (and if necessary, copy it for each specified component)
232
+  if ischar(method),
233
+    switch method, 
234
+    case {'var','range','log','histD','histC','logistic'}, 
235
+      sN = som_set('som_norm','method',method); 
236
+    otherwise,       
237
+      error(['Unrecognized method: ' method]);
238
+    end
239
+    for i=comps, csNorm{i} = sN; end
240
+  elseif isstruct(method),
241
+    switch method(1).type, 
242
+    case {'som_map','som_data'}, csNorm = method(1).comp_norm; 
243
+    case {'som_norm'}, for i=comps, csNorm{i} = method; end
244
+    otherwise, 
245
+      error('Invalid struct given as normalization method.')
246
+    end
247
+  elseif iscellstr(method), 
248
+    [dummy,sN] = som_norm_variable(1,method,'init');      
249
+    for i=comps, csNorm{i} = sN; end
250
+  elseif iscell(method), 
251
+    csNorm = method; 
252
+  else
253
+    error('Illegal method argument.')
254
+  end
255
+  % check the size of csNorm is the same as data dimension
256
+  if length(csNorm) ~= dim, 
257
+    error('Given number of normalizations does not match data dimension.')
258
+  end
259
+end
260
+
261
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
262
+%% initialize
263
+
264
+% make sure all the current normalizations for current 
265
+% components have been done
266
+if struct_mode, 
267
+  alldone = 1; 
268
+  for i = comps, 
269
+    for j=1:length(sD.comp_norm{i}), 
270
+      sN = sD.comp_norm{i}(j); 
271
+      if ~strcmp(sN.status,'done'), 
272
+	alldone = 0; 
273
+        [x,sN] = som_norm_variable(D(:,i), sN, 'do'); 
274
+        D(:,i) = x; 
275
+        sD.comp_norm{i}(j) = sN; 
276
+      end
277
+    end
278
+  end
279
+  if isempty(method), 
280
+    if alldone,
281
+      warning('No ''undone'' normalizations found. Data left unchanged.');
282
+    else
283
+      fprintf(1,'Normalizations have been redone.\n');
284
+    end
285
+  end
286
+end
287
+
288
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
289
+%% action 
290
+
291
+% add the new normalizations to the old ones
292
+for i = comps, 
293
+  if ~isempty(csNorm{i}), 
294
+    [x,sN] = som_norm_variable(D(:,i), csNorm{i}, 'do'); 
295
+    D(:,i) = x; 
296
+    if struct_mode, 
297
+      if isempty(sD.comp_norm{i}), sD.comp_norm{i} = sN; 
298
+      else sD.comp_norm{i} = [sD.comp_norm{i}, sN]; end
299
+    end
300
+  end
301
+end
302
+
303
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
304
+%% output
305
+
306
+if struct_mode, 
307
+  switch sD.type
308
+   case 'som_map', sD.codebook = D; 
309
+   case 'som_data', sD.data = D; 
310
+   otherwise, error('Illegal struct.')
311
+  end
312
+else
313
+  sD = D;
314
+end
315
+
316
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
317
+
318
+
319
+
... ...
@@ -0,0 +1,89 @@
1
+function color = som_normcolor(data, clrmap)
2
+
3
+%SOM_NORMCOLOR RGB values of indexed colors for a given dataset and colormap 
4
+%  
5
+% color = som_normcolor(data, [clrmap])
6
+%
7
+%  color = som_normcolor(data);
8
+%  color = som_normcolor(data,jet(64));
9
+%
10
+%  Input and output arguments ([]'s are optional):
11
+%   data     (struct) map or data struct
12
+%            (matrix) size N x dim
13
+%   [clrmap] (matrix) size N x 3, a valid colormap (an RGB value matrix)
14
+%                     Default is current colormap. See COLORMAP.
15
+%
16
+%   color    (matrix) size N x 3 x dim, RGB matrix 
17
+%
18
+% Purpose of this function is to calculate fixed RGB colors that are similar
19
+% to indexed colors with the specified colormap. This is because some
20
+% SOM Toolbox visualization functions (as SOM_GRID) do not use indexed colors 
21
+% if the underlying Matlab function (e.g. PLOT) do not use indexed colors
22
+%
23
+% EXAMPLE
24
+%
25
+% %%% Visualize three variables in a map using som_grid:
26
+% %%% Give coordinates for the markers according to variables 1 and 2, and 
27
+% %%% 'indexed colors' according to variable 3. 
28
+%
29
+% som_grid(map.topol.lattice,map.topol.msize,'Coord',map.codebook(:,1:2), ...
30
+%          'markercolor', som_normcolor(map.codebook(:,3)));
31
+
32
+% Contributed to SOM Toolbox 2.0, February 11th, 2000 by Johan Himberg
33
+% Copyright (c) by Johan Himberg
34
+% http://www.cis.hut.fi/projects/somtoolbox/
35
+
36
+% juha 150799 johan 010999
37
+
38
+%%%% check possible errors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
39
+
40
+error(nargchk(1,2,nargin));
41
+
42
+if nargin < 2| isempty(clrmap),
43
+  clrmap=colormap;
44
+elseif ~vis_valuetype(clrmap,{'nx3rgb'}),
45
+  error('The specified colormap is invalid!');
46
+end
47
+
48
+d=size(clrmap,1);
49
+
50
+if isstruct(data),
51
+  m_names={'type';'codebook';'topol';'labels';'neigh';'mask';'trainhist';...
52
+           'name';'comp_names';'comp_norm'};
53
+  d_names=fieldnames(vis_struct);
54
+  if length(fieldnames(data)) ~= length(d_names)  % data is not som_data_struct
55
+    if length(fieldnames(data)) ~= length(m_names) % and not som_map_struct 
56
+      error('Input argument is not a ''som_vis'' or ''som_map'' struct.')
57
+    elseif ~all(strcmp(fieldnames(data),m_names))
58
+      error('Input argument is not a ''som_vis'' or ''som_map'' struct.')
59
+    else
60
+      data=data.codebook;
61
+    end
62
+  elseif ~all(strcmp(fieldnames(data),dnames))
63
+    error('Input argument is not a ''som_vis'' or ''som_map'' struct.')
64
+  else
65
+    data=data.data;
66
+  end
67
+end
68
+
69
+if ~isnumeric(data) | ndims(data) ~= 2
70
+  error('Data is not 2 dimensional numeric matrix.');
71
+end
72
+
73
+%%% action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
74
+
75
+data=som_normalize(data,'range');
76
+
77
+for i=1:size(data,2),
78
+  inds=~isnan(data(:,i));
79
+  color(inds,:,i)=clrmap(round(data(inds,i)*(d-1))+1,:);
80
+  color(~inds,:,i)=NaN;
81
+end
82
+
83
+  
84
+
85
+
86
+
87
+
88
+
89
+
... ...
@@ -0,0 +1,293 @@
1
+function P = som_order_cplanes(sM, varargin)
2
+
3
+%SOM_ORDER_CPLANES Orders and shows the SOM component planes.
4
+%
5
+% P = som_order_cplanes(sM, [[argID,] value, ...])
6
+%
7
+%  som_order_cplanes(sM);
8
+%  som_order_cplanes(sM,'comp',1:30,'simil',C,'pca');
9
+%  P = som_order_cplanes(sM);
10
+%
11
+%  Input and output arguments ([]'s are optional): 
12
+%   sM       (struct) map or data struct
13
+%            (matrix) a data matrix, size * x dim
14
+%   [argID,  (string) See below. The values which are unambiguous can
15
+%    value]  (varies) be given without the preceeding argID.
16
+%
17
+%   P        (matrix) size n x * (typically n x 2), the projection coordinates
18
+%   
19
+% Here are the valid argument IDs and corresponding values. The values
20
+% which are unambiguous (marked with '*') can be given without the
21
+% preceeding argID.
22
+%   'comp'    (vector) size 1 x n, which components to project, 1:dim by default
23
+%   'simil'  *(string) similarity measure to use 
24
+%                      'corr'        linear correlation between component planes
25
+%                      'abs(corr)'   absolute value of correlation (default)
26
+%                      'umat'        as 'abs(corr)' but calculated from U-matrices
27
+%                      'mutu'        mutual information (not implemented yet)
28
+%             (matrix) size n x n, a similarity matrix to be used             
29
+%   'proj'   *(string) projection method to use: 'SOM' (default), 
30
+%                      'pca', 'sammon', 'cca', 'order', 'ring'
31
+%   'msize'   (vector) size of the SOM that is used for projection
32
+%   'show'   *(string) how visualization is done: 'planes' (default), 
33
+%                      'names', or 'none'
34
+%   'mask'    (vector) dim x 1, the mask to use, ones(dim,1) by default
35
+%   'comp_names' (cell array) of strings, size dim x 1, the component names
36
+%
37
+% The visualized objects have a callback associated with them: by
38
+% clicking on the object, the index and name of the component are printed
39
+% to the standard output.
40
+% 
41
+% See also SOM_SHOW.
42
+
43
+% Copyright (c) 2000 by the SOM toolbox programming team.
44
+% Contributed to SOM Toolbox on June 16th, 2000 by Juha Vesanto
45
+% http://www.cis.hut.fi/projects/somtoolbox/
46
+
47
+% Version 2.0beta juuso 120600 070601
48
+
49
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
50
+%% check arguments
51
+
52
+% sM
53
+if isstruct(sM), 
54
+  switch sM.type
55
+  case 'som_map', 
56
+    D = sM.codebook; dim = size(D,2); cnames = sM.comp_names; mask = sM.mask; 
57
+    ismap = 1; 
58
+  case 'som_data', 
59
+    D = sM.data; dim = size(D,2); cnames = sM.comp_names; mask = ones(dim,1); 
60
+    ismap = 0; 
61
+  otherwise, error('Invalid first argument.');
62
+  end                  
63
+else
64
+  D = sM; 
65
+  dim = size(D,2); mask = ones(dim,1);
66
+  cnames = cell(dim,1); 
67
+  for i = 1:dim, cnames{i} = sprintf('Variable%d',i); end
68
+  ismap = 0; 
69
+end
70
+
71
+% defaults
72
+comps = 1:dim; 
73
+simil = 'abs(corr)';
74
+proj = 'SOM'; 
75
+show = 'planes'; 
76
+mapsize = NaN;
77
+
78
+% varargin
79
+i=1;
80
+while i<=length(varargin),
81
+  argok = 1;
82
+  if ischar(varargin{i}),
83
+    switch varargin{i},
84
+     % argument IDs
85
+     case 'mask',       i=i+1; mask = varargin{i};
86
+     case 'comp_names', i=i+1; cnames = varargin{i};
87
+     case 'comp',       i=i+1; comps = varargin{i}; 
88
+     case 'proj',       i=i+1; proj = varargin{i}; 
89
+     case 'show',       i=i+1; show = varargin{i}; 
90
+     case 'simil',      i=i+1; simil = varargin{i}; 
91
+     case 'msize',      i=i+1; mapsize = varargin{i};
92
+     % unambiguous values
93
+     case {'corr','abs(corr)','umat','mutu'}, simil = varargin{i}; 
94
+     case {'SOM','pca','sammon','cca','order','ring'}, proj = varargin{i}; 
95
+     case {'planes','names','none'}, show = varargin{i}; 
96
+     otherwise argok=0;
97
+    end
98
+  else
99
+    argok = 0;
100
+  end
101
+  if ~argok,
102
+    disp(['(som_order_cplanes) Ignoring invalid argument #' num2str(i+1)]);
103
+  end
104
+  i = i+1;
105
+end
106
+
107
+if strcmp(show,'planes') & ~ismap, 
108
+  warning('Given data is not a map: using ''names'' visualization.'); 
109
+  show = 'names'; 
110
+end
111
+
112
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
113
+%% similarity matrix
114
+
115
+fprintf(1,'Calculating similarity matrix\n');
116
+
117
+% use U-matrix
118
+if strcmp(simil,'umat'), 
119
+  if ~ismap, error('Given data is not a map: cannot use U-matrix similarity.'); end
120
+  U = som_umat(sM);
121
+  D = zeros(prod(size(U)),dim); 
122
+  m = zeros(dim,1);
123
+  for i=1:dim, m=m*0; m(i)=1; U = som_umat(sM,'mask',m); D(:,i) = U(:); end
124
+end
125
+
126
+% components
127
+D = D(:,comps); 
128
+cnames = cnames(comps);
129
+mask = mask(comps);
130
+dim = length(comps);
131
+  
132
+% similarity matrix
133
+if ischar(simil), 
134
+  switch simil, 
135
+  case {'corr','abs(corr)','umat'}, 
136
+    A = zeros(dim);
137
+    me = zeros(1,dim);
138
+    for i=1:dim, 
139
+        me(i) = mean(D(isfinite(D(:,i)),i)); D(:,i) = D(:,i) - me(i); 
140
+    end  
141
+    for i=1:dim, 
142
+      for j=i:dim, 
143
+        c = D(:,i).*D(:,j); c = c(isfinite(c));
144
+        A(i,j) = sum(c)/length(c); A(j,i) = A(i,j); 
145
+      end
146
+    end
147
+    s = diag(A); 
148
+    A = A./sqrt(s*s');
149
+    switch simil, 
150
+    case {'abs(corr)','umat'}, A = abs(A); 
151
+    case 'corr', A = A + 1; 
152
+    end
153
+  case 'mutu', 
154
+    error('Mutual information not implemented yet.');
155
+  end
156
+else
157
+  A = simil; 
158
+end
159
+
160
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
161
+%% projection
162
+
163
+fprintf(1,'Projection\n');
164
+
165
+mu = 2*dim; 
166
+
167
+switch proj, 
168
+ case 'SOM',
169
+
170
+  if isnan(mapsize), 
171
+    sMtmp = som_randinit(A,'munits',mu); 
172
+    msize = sMtmp.topol.msize; 
173
+  else 
174
+    msize = mapsize; 
175
+  end
176
+
177
+  sM2 = som_make(A,'msize',msize,'rect','tracking',0);
178
+  bm  = assign_unique_bm(sM2,A);
179
+  Co  = som_unit_coords(sM2);
180
+  P   = Co(bm,:);
181
+
182
+ case 'ring', 
183
+
184
+  if isnan(mapsize), msize = [1 mu]; else msize = mapsize; end
185
+
186
+  sM2 = som_make(A,'msize',msize,'cyl','rect','tracking',0);
187
+  bm  = assign_unique_bm(sM2,A);
188
+  Co  = som_unit_coords(sM2);
189
+  P   = Co(bm,[1 3]);   
190
+  
191
+ case 'order',
192
+
193
+  if isnan(mapsize), msize = [1 mu]; else msize = mapsize; end
194
+
195
+  sM2 = som_make(A,'msize',msize,'tracking',0);
196
+  bm  = assign_unique_bm(sM2,A);
197
+  [dummy,i] = sort(bm); 
198
+  [dummy,P] = sort(i);
199
+  if size(P,2)>1, P = P'; end
200
+  if size(P,2)==1, P(:,2) = zeros(length(P),1); end
201
+
202
+ case {'pca','sammon','cca'}, 
203
+  P = pcaproj(A,2);  
204
+  if strcmp(proj,'sammon'), P = sammon(A,P,50,'steps');
205
+  elseif strcmp(proj,'cca'), P = cca(A,P,50);
206
+  end
207
+
208
+end
209
+
210
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
211
+%% visualization
212
+
213
+if ~strcmp(show,'none'), 
214
+  fprintf(1,'Visualization\n');
215
+  cla
216
+  hold on
217
+  if strcmp(show,'planes')
218
+    s = findscaling(sM.topol.msize,P);
219
+    for i=1:dim, 
220
+      C = som_normcolor(D(:,i));
221
+      if strcmp(simil,'umat'), 
222
+	h=som_cplane([sM.topol.lattice 'U'],sM.topol.msize,C,1,s*P(i,:));
223
+      else
224
+	h=som_cplane(sM,C,1,s*P(i,:)); 
225
+      end 
226
+      set(h,'edgecolor','none','Userdata',sprintf('[%d] %s',i,cnames{i}));
227
+      set(h,'ButtonDownFcn','fprintf(1,''%s\n'',get(gco,''UserData''))');
228
+    end
229
+  else 
230
+    s=1; 
231
+    a=[min(P(:,1))-1 max(P(:,1))+1 min(P(:,2))-1-3 max(P(:,2))+1-3];
232
+    axis(s*a);
233
+  end
234
+  h=text(s*P(:,1),s*P(:,2)-3,cnames);
235
+  for i=1:length(h), set(h(i),'Userdata',sprintf('[%d] %s',i,cnames{i})); end
236
+  set(h,'ButtonDownFcn','fprintf(1,''%s\n'',get(gco,''UserData''))');
237
+  hold off
238
+
239
+  axis on; axis equal; axis tight; set(gca,'XTick',[],'YTick',[],'Box','on');
240
+end
241
+
242
+return; 
243
+
244
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
245
+%% subfunctions
246
+
247
+function bm = assign_unique_bm(sM,D)
248
+
249
+  munits = size(sM.codebook,1);
250
+  [dlen dim] = size(D);
251
+  margin = max(0,dlen-munits);
252
+
253
+  [bm,qers] = som_bmus(sM,D); 
254
+  bmi=ones(dim,1);  
255
+  hits = som_hits(sM,D); 
256
+  mult = find(hits>1); 
257
+  while any(mult) & sum(hits(mult))-length(mult)>margin, 
258
+    choices = find(bm==mult(1)); 
259
+    while length(choices)>1,
260
+      [dummy,mv] = max(qers(choices)); mv = choices(mv);
261
+      [mv_to,q] = som_bmus(sM,D(mv,:),bmi(mv)); 
262
+      bmi(mv)=bmi(mv)+1; qers(mv) = q; bm(mv) = mv_to;
263
+      choices = find(bm==mv_to);
264
+    end
265
+    for i=1:length(hits), hits(i)=sum(bm==i); end
266
+    mult = find(hits>1);
267
+  end
268
+  return;
269
+  
270
+function s = findscaling(msize,P)
271
+
272
+  d1 = median(abs(diff(unique(sort(P(:,1))))));
273
+  d2 = median(abs(diff(unique(sort(P(:,2))))));
274
+  if d1>0, s1 = 1.5*msize(2)/d1; else s1 = 0; end
275
+  if d2>0, s2 = 1.5*msize(1)/d2; else s2 = 0; end
276
+  s = max(s1,s2);
277
+  if s==0, s=1; end
278
+  return; 
279
+
280
+function alternative_SOM_plane_vis(sT,bm,simil,D,cnames)
281
+
282
+  clf
283
+  for i=1:size(D,2), 
284
+    subplot(sT.msize(2),sT.msize(1),bm(i));
285
+    if strcmp(simil,'umat'), h=som_cplane([sT.lattice 'U'],sT.msize,D(:,i));
286
+    else h=som_cplane(sT,D(:,i)); 
287
+    end
288
+    set(h,'edgecolor','none');
289
+    title(cnames{i});
290
+    axis off
291
+  end    
292
+  return;
293
+
... ...
@@ -0,0 +1,325 @@
1
+function h=som_pieplane(varargin)
2
+
3
+%SOM_PIEPLANE Visualize the map prototype vectors as pie charts
4
+%
5
+% h=som_pieplane(lattice, msize, data, [color], [s], [pos])
6
+% h=som_pieplane(topol, data, [color], [s], [pos])
7
+%
8
+%  som_pieplane('hexa',[5 5], rand(25,4), jet(4), rand(25,1)) 
9
+%  som_pieplane(sM, sM.codebook);
10
+%
11
+% Input and output arguments ([]'s are optional):
12
+%  lattice   (string) grid 'hexa' or 'rect'
13
+%  msize     (vector) size 1x2, defines the grid, M=msize(1)*msize(2)
14
+%            (matrix) size Mx2, gives explicit coordinates for each node: in 
15
+%             this case the lattice does not matter.
16
+%  topol     (struct) map or topology struct
17
+%  data      (matrix) size Mxd, Mth row is the data for Mth pie. The 
18
+%             values will be normalized to have unit sum in each row.
19
+%  [color]   (matrix) size dx3, RGB triples. The first row is the
20
+%             color of the first slice in each pie etc. Default is hsv(d).
21
+%            (string) ColorSpec or 'none' gives the same color for each slice.
22
+%  [s]       (matrix) size Mx1,  gives an individual size scaling for each node. 
23
+%            (scalar) gives the same size for each node. Default is 0.8. 
24
+%  [pos]     (vectors) a 1x2 vector that determines position for the
25
+%              origin, i.e. upper left corner. Default is no translation.
26
+%
27
+%  h         (scalar) the object handle to the PATCH object
28
+%
29
+% The data will be linearly scaled so that its sum is 1 in each unit.
30
+% Negative values are invalid. Axis are set as in som_cplane.
31
+%
32
+% For more help, try 'type som_pieplane' or check out online documentation.
33
+% See also SOM_CPLANE, SOM_PLOTPLANE, SOM_BARPLANE
34
+
35
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
36
+%
37
+% som_pieplane
38
+%
39
+% PURPOSE
40
+% 
41
+% Visualizes the map prototype vectors as pie charts.
42
+%
43
+% SYNTAX
44
+%
45
+%  h = som_pieplane(topol, data)
46
+%  h = som_pieplane(lattice, msize, data)
47
+%  h = som_pieplane(..., color)
48
+%  h = som_pieplane(..., color, s)
49
+%  h = som_pieplane(..., color, s, pos)
50
+%
51
+% DESCRIPTION
52
+%
53
+%  Visualizes the map prototype vectors as pie charts.
54
+%
55
+% KNOWN BUGS
56
+%
57
+% It is not possible to specify explicit coordinates for map
58
+% consisting of just one unit as then the msize is interpreted as
59
+% map size.
60
+%
61
+%  FEATURES
62
+% 
63
+%  - negative values in data cause an error
64
+%
65
+%  - the colors are fixed: changing colormap in the figure (see help
66
+%    colormap) will not affect the coloring of the slices.
67
+%
68
+%  - if input variable s has size Nxd it gives each slice an individual
69
+%    scaling factor. This may be used to create a glyph where
70
+%    the radius of the slice, not the angle, shows the variable
71
+%    try, e.g., som_pieplane('rect',[5 4],ones(20,4),'w',rand(20,4));
72
+%
73
+% REQUIRED INPUT ARGUMENTS
74
+% 
75
+% lattice  The basic shape of the map units 
76
+%         
77
+%    (string) 'hexa' or 'rect' positions the pies according to hexagonal or 
78
+%             rectangular map lattice.
79
+%
80
+% msize    The size of the map grid     
81
+%
82
+%    (vector) [n1 n2] vector defines the map size (height n1 units,
83
+%             width n2 units, total M=n1xn2 units). The units will 
84
+%             be placed to their topological locations to form a
85
+%             uniform hexagonal or rectangular grid.
86
+%    (matrix) Mx2 matrix defines arbitary coordinates for the M units. In 
87
+%             this case the argument 'lattice' has no effect.
88
+%
89
+% topol    Topology of the map grid
90
+%
91
+%   (struct) map or topology struct from which the topology is taken
92
+%
93
+% data     The data to be visualized
94
+%
95
+%    (matrix) Mxd matrix of data vectors. Negative values are invalid.
96
+%
97
+% OPTIONAL INPUT ARGUMENTS
98
+%
99
+% If value is unspecified or empty ([] or ''), the default values
100
+% are used for optional input arguments.
101
+%
102
+% s       The size scaling factors for the units
103
+%
104
+%    (scalar) gives each unit the same size scaling: 
105
+%             0   unit disappears (edges can be seen as a dot)
106
+%             ... default size is 0.8
107
+%             >1  unit overlaps others          
108
+%    (matrix) Mx1 double: each unit gets individual size scaling 
109
+%
110
+% color   The color of the slices in each pie
111
+%
112
+%    (string) ColorSpec or 'none' gives the same color for each slice
113
+%    (matrix) dx3 matrix assigns an RGB color determined by the dth row of
114
+%             the matrix to the dth slice (variable) in each pie plot
115
+%
116
+% pos    Position of origin       
117
+% 
118
+%    (vector) size 1x2: this is meant for drawing the plane in arbitary 
119
+%             location in a figure. Note the operation: if this argument is
120
+%             given, the axis limits setting part in the routine is skipped and 
121
+%             the limits setting will be left to be done by
122
+%             MATLAB's defaults. Default is no translation.
123
+%
124
+% OUTPUT ARGUMENTS
125
+%
126
+%  h (scalar)  Handle to the created patch object.
127
+%
128
+% OBJECT TAGS     
129
+%
130
+% One object handle is returned: field Tag is set to 'planePie'       
131
+% 
132
+% EXAMPLES
133
+%
134
+% %%% Create the data and make a map 
135
+%    
136
+% data=rand(100,5); map=som_make(data);
137
+% 
138
+% %%% Create a 'jet' colormap that has as many rows as the data has variables
139
+%    
140
+% colors=jet(5);
141
+% 
142
+% %%% Draw pies
143
+%    
144
+% som_pieplane(map, map.codebook, colors);
145
+% 
146
+% %%% Calculate the hits of data on the map and normalize them between [0,1]
147
+%  
148
+% hit=som_hits(map,data); hit=hit./max(max(hit));
149
+% 
150
+% %%% Draw the pies so that their size tells the hit count
151
+%
152
+% som_pieplane(map, map.codebook, colors, hit);
153
+% 
154
+% %%% Try this! (see section FEATURES) 
155
+%
156
+% som_pieplane('rect',[5 4],ones(20,4),'w',rand(20,4));
157
+%
158
+% SEE ALSO
159
+%
160
+% som_cplane     Visualize a 2D component plane, u-matrix or color plane
161
+% som_barplane   Visualize the map prototype vectors as bar diagrams
162
+% som_plotplane  Visualize the map prototype vectors as line graphs
163
+
164
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
165
+% http://www.cis.hut.fi/projects/somtoolbox/             
166
+
167
+% Version 2.0beta Johan 140799 juuso 310300 070600
168
+
169
+%%% Check & Init arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
170
+
171
+[nargin, lattice, msize, data, color, s, pos] = vis_planeGetArgs(varargin{:});
172
+error(nargchk(3, 6, nargin));  % check no. of input args is correct
173
+
174
+% check pos
175
+
176
+if nargin < 6 | isempty(pos)
177
+  pos=NaN;                            % default value for pos (no translation) 
178
+elseif ~vis_valuetype(pos,{'1x2'})
179
+  error('Position of origin has to be given as an 1x2 vector');
180
+end
181
+
182
+% check msize
183
+
184
+if ~vis_valuetype(msize,{'1x2','nx2'}),
185
+  error('msize has to be 1x2 grid size vector or a Nx2 coordinate matrix.');
186
+end
187
+
188
+% check data
189
+
190
+if ~isnumeric(data),
191
+  error('Data matrix must be numeric.');
192
+elseif length(size((data)))>2
193
+  error('Data matrix has too many dimensions!');
194
+else
195
+  d=size(data,2);
196
+  N=size(data,1);
197
+end
198
+
199
+if any(data(:)<0)
200
+  error('Negative data values not allowed in pie plots!');
201
+end
202
+
203
+% Check lattice
204
+if ~ischar(lattice) | ~any(strcmp(lattice,{'hexa','rect'})),
205
+  error('Invalid lattice.');
206
+end
207
+
208
+%% Calculate patch coordinates for slices
209
+
210
+for i=1:N,                            
211
+  [nx,ny]=vis_piepatch(data(i,:));    
212
+  piesx(:,(1+(i-1)*d):(i*d))=nx;
213
+  piesy(:,(1+(i-1)*d):(i*d))=ny;
214
+end
215
+l=size(piesx,1);
216
+
217
+if size(msize,1) == 1,
218
+  if prod(msize) ~= N 
219
+    error('Data matrix has wrong size.');
220
+  else
221
+    coord=som_vis_coords(lattice, msize);
222
+  end
223
+else
224
+  if N ~= size(msize,1),
225
+    error('Data matrix has wrong size.');
226
+  end
227
+  coord=msize; 
228
+  % This turns the axis tightening off,
229
+  % as now we don't now the limits (no fixed grid)
230
+  if isnan(pos); pos=[0 0]; end
231
+end
232
+x=reshape(repmat(coord(:,1),1,l*d)',l,d*N);
233
+y=reshape(repmat(coord(:,2),1,l*d)',l,d*N);
234
+
235
+% Check size
236
+
237
+if nargin < 5 | isempty(s),  
238
+  s=0.8;                              % default value for scaling
239
+elseif ~vis_valuetype(s, {'1x1', [N 1], [N d]}),
240
+  error('Size matrix does not match with the data matrix.');
241
+elseif size(s) == [N 1],
242
+  s=reshape(repmat(s,1,l*d)',l,d*N);
243
+elseif all(size(s) ~= [1 1]),
244
+  s=reshape(repmat(reshape(s',d*N,1),1,l)',l,d*N);
245
+end
246
+
247
+% Check color
248
+% C_FLAG is a flag for color 'none' 
249
+
250
+if nargin < 4 | isempty(color)
251
+  color=hsv(d); C_FLAG=0;       % default n hsv colors
252
+end
253
+
254
+if ~(vis_valuetype(color, {[d 3], 'nx3rgb'},'all')) & ...
255
+      ~vis_valuetype(color,{'colorstyle','1x3rgb'}), 
256
+  error('The color matrix has wrong size or contains invalid values.');
257
+elseif ischar(color) & strcmp(color,'none'), 
258
+  C_FLAG=1;        % check for color 'none'
259
+  color='w';    
260
+else
261
+  C_FLAG=0;        % valid color string or colormap
262
+end
263
+
264
+%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
265
+
266
+% Size zero would cause division by zero. eps is as good (node disappears)
267
+% The edge may be visible, though. (NaN causes some other problems)
268
+
269
+s(s==0)=eps;                    
270
+
271
+%% 1. Scaling
272
+x=(x./s+piesx).*s; y=(y./s+piesy).*s;      
273
+
274
+%% 2. Translation  
275
+if ~isnan(pos)
276
+  x=x+pos(1);y=y+pos(2);               
277
+end
278
+
279
+%% 3. Rearrange dx3 color matrix
280
+
281
+if ~isstr(color) & size(color,1)~=1,
282
+  color=reshape(repmat(color,N,1),[1 N*d 3]);
283
+end
284
+
285
+%% Set axes properties  
286
+ax=newplot;                            % get current axis
287
+vis_PlaneAxisProperties(ax,lattice, msize, pos);                         
288
+
289
+%% Draw the plane! 
290
+
291
+h_=patch(x,y,color);
292
+
293
+if C_FLAG
294
+  set(h_,'FaceColor','none');
295
+end
296
+
297
+set(h_,'Tag','planePie');              % tag the object 
298
+
299
+%%% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
300
+
301
+if nargout>0, h=h_; end                % Set h only if 
302
+                                       % there really is output
303
+%%% Subfunctions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
304
+
305
+function [x,y]=vis_piepatch(v)
306
+
307
+% Do a pie (see e.g. the MathWorks function PIE). 
308
+% Origin is at (0,0) and the radius is .5.
309
+
310
+N=25;
311
+
312
+if sum(v)==0, v_is_zero = 1; v(1) = 1; else v_is_zero = 0; end
313
+
314
+v(v==0) = eps; % Matlab 5.2 version of linspace doesn't work otherwise
315
+
316
+phi=[0 2*pi*cumsum(v./sum(v))];
317
+
318
+for i=2:length(phi),
319
+  [xi,yi]=pol2cart(linspace(phi(i-1),phi(i),N),0.5);
320
+  x(:,i-1)=[0 xi 0]';
321
+  y(:,i-1)=[0 yi 0]';
322
+end
323
+
324
+if v_is_zero, x = x*0; y = y*0; end
325
+
... ...
@@ -0,0 +1,122 @@
1
+function som_plotmatrix(sM,D,Col,comps)
2
+
3
+%SOM_PLOTMATRIX Visualize pairwise scatter plots and histograms.
4
+%
5
+%  som_plotmatrix(sM,[sD],[Col],[comps])
6
+% 
7
+%  Input and output arguments ([]'s are optional):
8
+%   sM       (struct) map struct
9
+%   [sD]     (struct) data struct, corresponding to the map
10
+%            (matrix) data matrix (size dlen x dim)
11
+%   [Col]    (matrix) size munits x 3, color for each map unit
12
+%   [comps]  (vector) which components to plot (1:dim by default)
13
+%
14
+% See also: SOM_SHOW, SOM_ORDER_CPLANES.
15
+
16
+% Copyright (c) 2000 by the SOM toolbox programming team.
17
+% Contributed to SOM Toolbox on June 16th, 2000 by Juha Vesanto
18
+% http://www.cis.hut.fi/projects/somtoolbox/
19
+
20
+% Version 2.0beta juuso 140600
21
+
22
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55
23
+
24
+% sM
25
+[munits dim] = size(sM.codebook); 
26
+M = sM.codebook;
27
+
28
+% sD
29
+if nargin>1 & ~isempty(D), 
30
+  if isstruct(D), D = D.data; end
31
+  bmus = som_bmus(sM,D);
32
+else D = []; bmus = []; 
33
+end
34
+
35
+% Col
36
+if nargin<3 | isempty(Col), Col = som_colorcode(sM); end
37
+if ischar(Col), Col = som_colorcode(sM,Col); end
38
+
39
+% comps
40
+if nargin<4 | isempty(comps), comps = 1:dim; end
41
+n = length(comps)+1;
42
+
43
+% histogram bins
44
+if ~isempty(D), C=D; else C=M; end
45
+cHbins = cell(dim,1);
46
+cAxis = cell(dim,1);
47
+for i=1:dim, 
48
+  if ~isempty(D), mima = [min(D(:,i)),max(D(:,i))];
49
+  else mima = [min(M(:,i)),max(M(:,i))];
50
+  end
51
+  cAxis{i} = mima; 
52
+  [dummy,cHbins{i}] = hist(mima,20);   
53
+end
54
+
55
+nt = 4; % number of ticks in scatter plots
56
+
57
+% visualization
58
+clf
59
+for i=1:n, 
60
+  for j=1:n, 
61
+    subplot(n,n,(i-1)*n+j); 
62
+    if j==1 & i==1, 
63
+      h=som_cplane(sM,Col); set(h,'edgecolor','none')
64
+    elseif i==1, 
65
+      ind = comps(j-1); 
66
+      b  = cHbins{ind};      
67
+      hs = hist(M(:,ind),b); 
68
+      h  = bar(b,hs,0.8); set(h,'EdgeColor','none','FaceColor','k'); 
69
+      axis on, axis tight
70
+      set(gca,'XTick',[],'Box','on');
71
+      title(sM.comp_names{ind});
72
+    elseif j==1, 
73
+      ind = comps(i-1); 
74
+      if ~isempty(D), 
75
+	b  = cHbins{ind}; 
76
+	hs = hist(D(:,ind),b); 
77
+	h  = bar(b,hs,0.8); set(h,'EdgeColor','none','FaceColor','k'); 
78
+	axis on, axis tight	
79
+	set(gca,'XTick',[],'Box','on');
80
+	ylabel(sM.comp_names{ind})
81
+      else
82
+	text(0.5,0.5,sM.comp_names{ind});
83
+	axis off
84
+      end
85
+    elseif i==j, 
86
+      ind = comps(i-1); 
87
+      h=som_cplane(sM,M(:,ind)); 
88
+      set(h,'edgecolor','none')
89
+      a = cAxis{ind}; 
90
+      caxis(a); v = unique([a, min(M(:,ind)), max(M(:,ind))]); 
91
+      vn=som_denormalize(v,sM.comp_norm{ind})'; 
92
+      h=colorbar('vert');
93
+      set(h,'YTick',v,'YTickLabel',cellstr(num2str(vn,2)));
94
+    elseif i<j | ~isempty(D), 
95
+      if i>j, i1 = i-1; i2 = j-1; else i1 = j-1; i2 = i-1; end
96
+      ind1 = comps(i1); ind2 = comps(i2); 
97
+      if i<j, 
98
+	som_grid(sM,'coord',M(:,[ind1 ind2]),'markersize',2,'MarkerColor',Col);
99
+      else
100
+	som_grid('rect',[size(D,1) 1],'coord',D(:,[ind1 ind2]),...
101
+		 'Line','none','MarkerColor',Col(bmus,:),'Markersize',2);	
102
+	%cla; hold on
103
+	%for k=1:max(bmus), 
104
+	%  inds = find(bmus==k); 
105
+	%  if any(inds), 
106
+	%    som_grid('rect',[length(inds) 1],'coord',D(inds,[ind1 ind2]),...
107
+	%	     'Line','none','MarkerColor',Col(k,:),'Markersize',2);	
108
+	%  end
109
+	%end
110
+      end	      
111
+      a = [cAxis{ind1} cAxis{ind2}]; axis(a); 
112
+      x = linspace(a(1),a(2),nt); xn = som_denormalize(x,sM.comp_norm{ind1})';
113
+      set(gca,'XTick',x,'XTickLabel',cellstr(num2str(xn,2)));
114
+      y = linspace(a(3),a(4),nt); yn = som_denormalize(y,sM.comp_norm{ind2})';
115
+      set(gca,'YTick',y,'YTickLabel',cellstr(num2str(yn,2)));
116
+      xlabel(sM.comp_names{ind1}), ylabel(sM.comp_names{ind2})
117
+    end    
118
+  end
119
+end
120
+
121
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55
122
+
... ...
@@ -0,0 +1,285 @@
1
+function h=som_plotplane(varargin)
2
+
3
+%SOM_PLOTPLANE  Visualize the map prototype vectors as line graphs
4
+%
5
+% h=som_plotplane(lattice, msize, data, [color], [scaling], [pos])
6
+% h=som_plotplane(topol, data, [color], [scaling], [pos])
7
+%
8
+%  som_plotplane('hexa',[5 5], rand(25,4), jet(25)) 
9
+%  som_plotplane(sM, sM.codebook)
10
+%
11
+% Input and output arguments ([]'s are optional)
12
+%  lattice   (string) grid 'hexa' or 'rect'
13
+%  msize     (vector) size 1x2, defines the grid size 
14
+%            (matrix) size Mx2, defines explicit coordinates: in 
15
+%             this case the first argument does not matter 
16
+%  topol     (struct) map or topology struct
17
+%  data      (matrix) Mxd matrix, M=prod(msize) 
18
+%  [color]   (matrix) size Mx3, gives an individual color for each graph
19
+%            (string) ColorSpec gives the same color for each
20
+%             graph, default is 'k' (black)
21
+%  [scaling] (string) 'on' or 'off', default is 'on' 
22
+%  [pos]     (vector) 1x2 vector that determines translation. 
23
+%             Default is no translation.
24
+%
25
+%  h         (vector) the object handles for the LINE objects
26
+%
27
+%  If scaling is set on, the data will be linearly scaled in each
28
+%  unit so that min and max values span from lower to upper edge
29
+%  in each unit. If scaling is 'off', the proper scaling is left to 
30
+%  the user: values in range [-.5,.5] will be plotted within the limits of the 
31
+%  unit while values exceeding this range will be out of the unit. 
32
+%  Axis are set as in SOM_CPLANE.
33
+%
34
+% For more help, try 'type som_plotplane' or check out online documentation.
35
+% See also SOM_PLANE, SOM_PIEPLANE, SOM_BARPLANE
36
+
37
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
38
+%
39
+% som_plotplane
40
+%
41
+% PURPOSE
42
+% 
43
+% Visualizes the map prototype vectors as line graph
44
+%
45
+% SYNTAX
46
+%
47
+%  h = som_plotplane(topol, data)
48
+%  h = som_plotplane(lattice, msize, data)
49
+%  h = som_plotplane(..., color)
50
+%  h = som_plotplane(..., color, scaling)
51
+%  h = som_plotplane(..., color, scaling, pos)
52
+%
53
+% DESCRIPTION
54
+%
55
+%  Visualizes the map prototype vectors as line graph
56
+%
57
+% KNOWN BUGS
58
+%
59
+%  It is not possible to specify explicit coordinates for map
60
+%  consistig of just one unit as then the msize is interpreted as
61
+%  map size.
62
+%
63
+% FEATURES
64
+%
65
+%  - the colors are fixed: changing colormap in the figure (see
66
+%    COLORMAP) will not affect the coloring of the plots
67
+%
68
+% REQUIRED INPUT ARGUMENTS
69
+% 
70
+% lattice  The basic topology
71
+%
72
+%   (string) 'hexa' or 'rect' positions the plots according to hexagonal or 
73
+%            rectangular map lattice.
74
+%
75
+% msize    The size of the map grid     
76
+%         
77
+%   (vector) [n1 n2] vector defines the map size (height n1 units, width n2 
78
+%            units, total M=n1 x n2 units). The units will be placed to their 
79
+%            topological locations in order to form a uniform hexagonal or 
80
+%            rectangular grid.   
81
+%   (matrix) Mx2 matrix defines arbitary coordinates for the M units.
82
+%            In this case the argument 'lattice' has no effect.
83
+% 
84
+% topol    Topology of the map grid
85
+%
86
+%   (struct) map or topology struct from which the topology is taken
87
+% 
88
+% data     The data to be visualized
89
+%
90
+%   (matrix) Mxd matrix of data vectors. 
91
+% 
92
+% OPTIONAL INPUT ARGUMENTS
93
+%
94
+% If unspecified or given empty values ('' or []), default values
95
+% will be used for optional input arguments.
96
+% 
97
+% color    The color of the plots
98
+%
99
+%    (string) Matlab's ColorSpec (see help plot) string gives the same color 
100
+%             for each line.
101
+%
102
+%    (matrix) Mx3 matrix assigns an RGB color determined by the Nth row of
103
+%             the matrix to the Nth plot. 
104
+%
105
+%    (vector) 1x3 RGB vector gives the same color for each line.
106
+%
107
+% scaling  The data scaling mode
108
+%
109
+%    (string) 'on or 'off': if scaling is set on, the data will be
110
+%             linearly scaled in each unit so that min and max values span from 
111
+%             lower to upper edge in each unit. If scaling is 'off', the proper 
112
+%             scaling is left to the user: values in range [-.5,.5] will be plotted 
113
+%             within the limits of the unit while values exceeding this
114
+%             range will be out of the unit.
115
+%
116
+% pos      Position of the origin          
117
+%
118
+%    (vector) This is meant for drawing the plane in arbitary location in a 
119
+%             figure. Note the operation: if this argument is given, the
120
+%             axis limits setting part in the routine is skipped and the limits
121
+%             setting will be left to be done by MATLAB's
122
+%             defaults. By default no translation is done.
123
+%
124
+% OUTPUT ARGUMENTS
125
+%
126
+%  h (scalar)  Handle to the created patch object
127
+%
128
+% OBJECT TAG     
129
+%
130
+% Object property 'Tag' is set to 'planePlot'.       
131
+%
132
+% EXAMPLES
133
+%
134
+% %%% Create the data and make a map 
135
+%    
136
+% data=rand(1000,20); map=som_make(data);
137
+% 
138
+% %%% Create a 'gray' colormap that has 64 levels
139
+%    
140
+% color_map=gray(64);
141
+% 
142
+% %%% Draw plots using red color
143
+%    
144
+% som_plotplane(map, map.codebook,'r');
145
+%
146
+% %%% Calculate hits on the map and calculate colors so that
147
+%     black = min. number of hits and white = max. number of hits
148
+%
149
+% hit=som_hits(map,data); color=som_normcolor(hit(:),color_map);
150
+%
151
+% %%% Draw plots again. Now the gray level indicates the number of hits to 
152
+%     each node
153
+%
154
+% som_plotplane(map, map.codebook, color);
155
+%
156
+% SEE ALSO  
157
+%
158
+% som_cplane     Visualize a 2D component plane, u-matrix or color plane
159
+% som_barplane   Visualize the map prototype vectors as bar diagrams.
160
+% som_pieplane   Visualize the map prototype vectors as pie charts
161
+
162
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
163
+% http://www.cis.hut.fi/projects/somtoolbox/             
164
+
165
+% Version 2.0beta Johan 160799 juuso 151199 070600
166
+
167
+%%% Init & Check arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
168
+
169
+[nargin, lattice, msize, data, color, scaling, pos] = vis_planeGetArgs(varargin{:});
170
+error(nargchk(3, 5, nargin));  % check no. of input args is correct
171
+
172
+s=0.8; % size of plot
173
+
174
+if nargin < 6 | isempty(pos)
175
+  pos=NaN; 
176
+end
177
+
178
+if nargin < 5 | isempty(scaling)
179
+  scaling='on'; 
180
+elseif ~vis_valuetype(scaling,{'string'}) | ...
181
+      ~any(strcmp(scaling,{'on','off'})),
182
+  error('Scaling should be string ''on'' or ''off''.');
183
+end
184
+
185
+l=size(data,2);
186
+
187
+if ~isnumeric(msize) | ndims(msize) ~= 2 | size(msize,2)~=2, 
188
+  error('msize has to be 1x2 grid size vector or a Nx2 coordinate matrix.');
189
+elseif size(msize,1) == 1,
190
+   xdim=msize(2);
191
+   ydim=msize(1);
192
+   N=xdim*ydim;
193
+   y=repmat(repmat([1:ydim]',xdim,1),1,l);
194
+   x=reshape(repmat([1:xdim],ydim*l,1),l,N)';
195
+else
196
+   x=repmat(msize(:,1),1,l);y=repmat(msize(:,2),1,l);
197
+   N=size(msize,1);
198
+   lattice='rect'; 
199
+   if isnan(pos),
200
+      pos=[0 0];
201
+   end
202
+end
203
+
204
+switch lattice
205
+case {'hexa', 'rect'}
206
+  ;
207
+otherwise
208
+  error(['Lattice' lattice ' not implemented!']);
209
+end  
210
+
211
+if ~isnumeric(data) | size(data,1) ~= N
212
+  error('Data matrix is invalid or has wrong size!');
213
+end
214
+
215
+if nargin < 4 | isempty(color),
216
+  color='k';
217
+elseif vis_valuetype(color, {'colorstyle',[N 3]}),
218
+  if ischar(color) & strcmp(color,'none'),
219
+    error('Colorstyle ''none'' not allowed in som_plotplane.');
220
+  end
221
+elseif vis_valuetype(color,{'1x3rgb'})
222
+  ;
223
+elseif ~vis_valuetype(color,{'nx3rgb',[N 3]},'all'), 
224
+  error('The color matrix has wrong size or contains invalid RGB values or colorstyle.');
225
+end
226
+
227
+[linesx, linesy]=vis_line(data,scaling);
228
+
229
+%%%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
230
+
231
+% Making the lattice.
232
+% Command view([0 90]) shows the map in 2D properly oriented
233
+
234
+switch lattice
235
+case 'hexa'
236
+  t=find(rem(y(:,1),2));                  % move even rows by .5
237
+  x(t,:)=x(t,:)-.5; 
238
+  x=(x./s+linesx).*s+.5; y=(y./s+linesy).*s;      % scale with s
239
+case 'rect' 
240
+  x=(x./s+linesx).*s; y=(y./s+linesy).*s;         % scale with s
241
+end
242
+
243
+%% Draw the map! ...
244
+
245
+h_=plot(x',y');
246
+
247
+if size(color,1) == 1
248
+  set(h_,'Color',color);
249
+else
250
+  for i=1:N,
251
+    set(h_(i,:),'Color',color(i,:));
252
+  end
253
+end
254
+
255
+if ~isnan(pos)
256
+  x=x+pos(1);y=y+pos(2);                    % move upper left corner 
257
+end                                         % to pos(1),pos(2)
258
+
259
+%% Set axes properties  
260
+
261
+ax=gca;           
262
+vis_PlaneAxisProperties(ax, lattice, msize, pos);
263
+
264
+%%% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
265
+
266
+set(h_,'Tag','planePlot');                % tag the lineobject 
267
+
268
+if nargout>0, h=h_; end                   % Set h only, 
269
+                                          % if there really is output
270
+                                          
271
+%% Subfuntion %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
272
+                                          
273
+function [x,y]=vis_line(data, scaling)
274
+
275
+s=size(data);
276
+% normalization between [0,1] if scaling is on
277
+if strcmp(scaling,'on')
278
+  mn=repmat(min(data,[],2),1,s(2));  
279
+  mx=repmat(max(data,[],2),1,s(2));
280
+  y=-((data-mn)./(mx-mn))+.5;        
281
+else                       % -sign is beacuse we do axis ij
282
+  y=-data;
283
+end
284
+
285
+x=repmat(linspace(-.5, .5, size(data,2)), size(data,1),1);
... ...
@@ -0,0 +1,100 @@
1
+function [pd,Pdm,pmd] = som_probability_gmm(D, sM, K, P)
2
+
3
+%SOM_PROBABILITY_GMM Probabilities based on a gaussian mixture model.
4
+%
5
+% [pd,Pdm,pmd] = som_probability_gmm(D, sM, K, P)
6
+% 
7
+%   [K,P] = som_estimate_gmm(sM,D);
8
+%   [pd,Pdm,pmd] = som_probability_gmm(D,sM,K,P);
9
+%   som_show(sM,'color',pmd(:,1),'color',Pdm(:,1))  
10
+%
11
+%  Input and output arguments:
12
+%   D    (matrix) size dlen x dim, the data for which the 
13
+%        (struct) data struct,     probabilities are calculated
14
+%   sM   (struct) map struct
15
+%        (matrix) size munits x dim, the kernel centers
16
+%   K    (matrix) size munits x dim, kernel width parameters
17
+%                 computed by SOM_ESTIMATE_GMM
18
+%   P    (matrix) size 1 x munits, a priori probabilities for each 
19
+%                 kernel computed by SOM_ESTIMATE_GMM
20
+%
21
+%   pd   (vector) size dlen x 1, probability of each data vector in 
22
+%                 terms of the whole gaussian mixture model
23
+%   Pdm  (matrix) size munits x dlen, probability of each vector in 
24
+%                 terms of each kernel
25
+%   pmd  (matrix) size munits x dlen, probability of each vector to 
26
+%                 have been generated by each kernel
27
+%
28
+% See also SOM_ESTIMATE_GMM.
29
+
30
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Esa Alhoniemi
31
+% Copyright (c) by Esa Alhoniemi
32
+% http://www.cis.hut.fi/projects/somtoolbox/
33
+
34
+% ecco 180298 juuso 050100
35
+
36
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
37
+
38
+% input arguments
39
+if isstruct(sM), M = sM.codebook; else M = sM; end
40
+[c dim] = size(M);
41
+
42
+if isstruct(D), D = D.data; end
43
+dlen = size(D,1);
44
+
45
+% reserve space for output variables
46
+pd = zeros(dlen,1); 
47
+if nargout>=2, Pdm = zeros(c,dlen); end
48
+if nargout==3, pmd = zeros(c,dlen); end
49
+
50
+% the parameters of each kernel
51
+cCoeff = cell(c,1);
52
+cCoinv = cell(c,1);
53
+for m=1:c, 
54
+  co = diag(K(m,:));
55
+  cCoinv{m} = inv(co);
56
+  cCoeff{m} = 1 / ((2*pi)^(dim/2)*det(co)^.5);
57
+end
58
+
59
+% go through the vectors one by one
60
+for i=1:dlen, 
61
+
62
+  x = D(i,:);
63
+  
64
+  % compute p(x|m)
65
+  pxm = zeros(c,1); 
66
+  for m = 1:c,
67
+    dx     = M(m,:) - x;
68
+    pxm(m) = cCoeff{m} * exp(-.5 * dx * cCoinv{m} * dx');
69
+    %pxm(m) = normal(dx, zeros(1,dim), diag(K(m,:)));  
70
+  end
71
+  pxm(isnan(pxm(:))) = 0;
72
+  
73
+  % p(x|m)  
74
+  if nargin>=2, Pdm(:,i) = pxm; end
75
+  
76
+  % P(x) = P(x|M) = sum( P(m) * p(x|m) )
77
+  pd(i) = P*pxm; 
78
+  
79
+  % p(m|x) = p(x|m) * P(m) / P(x)
80
+  if nargout==3, pmd(:,i) = (P' .* pxm) / pd(i); end
81
+  
82
+end
83
+
84
+
85
+return; 
86
+
87
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
88
+%
89
+% subfunction normal
90
+%
91
+% computes probability of x when mean and covariance matrix
92
+% of a distribution are known
93
+
94
+function result = normal(x, mu, co)
95
+
96
+[l dim] = size(x);
97
+coinv   = inv(co);
98
+coeff   = 1 / ((2*pi)^(dim/2)*det(co)^.5);
99
+diff   = x - mu;
100
+result = coeff * exp(-.5 * diff * coinv * diff');
... ...
@@ -0,0 +1,70 @@
1
+function [cPCAarg, Pdata, Pproto] = som_projections(D,sM,bmus)
2
+
3
+% SOM_PROJECTIONS Makes different kinds of projections for the data and the prototypes.
4
+%
5
+% [cPCAarg, Pdata, Pproto] = som_projections(D,sM,[bmus])
6
+%
7
+%      sD      (struct) data struct
8
+%              (matrix) size dlen x dim
9
+%      sM      (struct) map struct
10
+%              (matrix) size munits x dim: prototype vectors
11
+%      [bmus]  (vector) BMU for each data vector (calculated if not specified)
12
+%
13
+%      cPCAarg (cell array) PCA arguments: {V, me, l} from pcaproj function
14
+%      Pdata   (matrix) size dlen x 7, consisting of 3 projection coordinates from PCA, 
15
+%                       1 residual from the rest of the PCA-projection coordinates, 
16
+%                       and 3 color components 
17
+%      Pproto  (matrix) size dlen x 7, consisting of 3 projection coordinates from PCA, 
18
+%                       1 residual from the rest of the PCA-projection coordinates, 
19
+%                       3 color components, and 3 projection coordinates from CCA
20
+%
21
+% See also  PCAPROJ, CCA, SAMMON, SOM_PROJECTIONS_PLOT, SOM_COLORING, SOM_COLORCODE, 
22
+%           SOM_CLUSTERCOLOR, SOM_KMEANCOLOR.
23
+
24
+if isstruct(D), 
25
+    cn = D.comp_names;
26
+    D = D.data; 
27
+end
28
+[dlen dim] = size(D);
29
+if nargin<3, bmus = som_bmus(sM,D); end
30
+
31
+% projection of data
32
+
33
+[P0,V,me,l] = pcaproj(D,dim);
34
+D1 = som_fillnans(D,sM); 
35
+P1 = pcaproj(D1,V,me); 
36
+Res4 = zeros(dlen,1); 
37
+if dim<=3, 
38
+    Res4 = zeros(dlen,1); 
39
+else
40
+    Res4 = sqrt(sum(P1(:,4:end).*P1(:,4:end),2));
41
+end
42
+P1 = P1(:,1:min(3,dim)); 
43
+if dim<3, P1 = [P1, zeros(dlen,3-dim)]; end
44
+
45
+% projection of codebook vectors
46
+
47
+P1_m = pcaproj(sM,V,me); 
48
+Res4_m = zeros(dlen,1); 
49
+if dim<=3, 
50
+    Res4_m = zeros(dlen,1); 
51
+else
52
+    Res4_m = sum(P1_m(:,4:end).*P1_m(:,4:end),2);
53
+end
54
+P1_m = P1_m(:,1:min(3,dim)); 
55
+if dim<3, P1_m = [P1_m, zeros(size(P1_m,1),3-dim)]; end
56
+
57
+P2_m = cca(sM,P1_m,20); 
58
+
59
+PCol_m = som_coloring(sM); 
60
+
61
+PCol = PCol_m(bmus,:); 
62
+
63
+% output
64
+
65
+cPCAarg = {V,me,l};
66
+Pdata = [P1, Res4, PCol]; 
67
+Pproto = [P1_m, Res4_m, PCol_m, P2_m]; 
68
+ 
69
+return;
70
+ 
0 71
\ No newline at end of file
... ...
@@ -0,0 +1,76 @@
1
+function som_projections_plot(pmode,varargin)
2
+
3
+% SOM_PROJECTIONS_PLOT Projection visualizations.
4
+%
5
+% som_projections_plot(pmode,varargin)
6
+%
7
+%   [cPCAarg, Pdata, Pproto] = som_projections(D,sM);
8
+%   som_projections_plot('scatter',Pdata(:,1:3))
9
+%   som_projections_plot('scatter',Pproto(:,1:3),Pproto(:,5:7),5,sM)
10
+%   som_projections_plot('residuals',Pdata(:,1:4))
11
+%   som_projections_plot('scree',cPCAarg{3})
12
+%
13
+% The other arguments depend on the pmode:
14
+%
15
+%  pmode = 'scatter'
16
+%
17
+%     arg1: Co     (matrix) coordinates
18
+%     arg2: color  (matrix) color vectors
19
+%                  (string) colorstring ('k' by default)
20
+%     arg3: psize  (scalar) point size
21
+%     arg4: sT     (struct) topology struct, if map grid is drawn
22
+%  
23
+%  pmode = 'residuals'
24
+%
25
+%     arg1: Co     (matrix) coordinates (2 first columns) + residuals (the rest)
26
+%     arg2: color  (string) colorstring ('k' by default)
27
+%
28
+%  pmode = 'scree'
29
+%
30
+%     arg1: eigval (vector) vector of eigenvalues
31
+%      
32
+% See also  SOM_PROJECTIONS.
33
+
34
+switch pmode, 
35
+case 'scatter', 
36
+    Co = varargin{1}; 
37
+    if length(varargin)>1, color = varargin{2}; else color = 'k'; end
38
+    if length(varargin)>2, psize = varargin{3}; else psize = 5; end
39
+    if length(varargin)>3, sT = varargin{4}; else sT = []; end
40
+    if isstruct(sT) & strcmp(sT.type,'som_map'), sT = sT.topol; end
41
+    
42
+    if isempty(sT),
43
+        som_grid({'rect',[size(Co,1) 1]},'Coord',Co,'Markercolor',color,'line','none','markersize',psize);
44
+    else
45
+        if ischar(color), lcolor = color; else lcolor = 'k'; end
46
+        som_grid(sT,'Coord',Co,'Markercolor',color,'markersize',psize,'linecolor',lcolor); 
47
+    end 
48
+    
49
+case 'residuals',
50
+    CoRes = varargin{1}; 
51
+    n = size(CoRes,1); 
52
+    if length(varargin)>1, color = varargin{2}; else color = 'k'; end
53
+    Co = CoRes(:,1:2); Co(end+1,:) = NaN; 
54
+    res = sqrt(sum(CoRes(:,3:end).*CoRes(:,3:end),2)); 
55
+    h=plot(Co(:,1),Co(:,2),'k.'); set(h,'color',color);
56
+    Co(end+1,:) = NaN;
57
+    res = [res; 0; NaN];  
58
+    i = [1:n; 1:n; (n+1)+zeros(1,n)]; i = i(:); 
59
+    j = [(n+1)+zeros(1,n); 1:n; (n+2)+zeros(1,n)]; j = j(:);  
60
+    h = line(Co(i,1),Co(i,2),res(j)); set(h,'color',color);
61
+    axis tight, axis equal, view(3)
62
+    
63
+case 'scree', 
64
+    eigval = varargin{1};
65
+    if size(eigval,1)>1, eigval = eigval'; end
66
+    eigval = eigval / sum(eigval); 
67
+    cumeig = cumsum(eigval);
68
+    bar(cumeig,0.1)
69
+    i = find(cumeig>=0.75); i75 = i(1); 
70
+    hold on
71
+    plot([0 2],cumeig([2 2]),'r-',[0 i75],cumeig([i75 i75]),'r-');
72
+    set(gca,'YTick',unique([0:0.1:1 cumeig(2) cumeig(i75)]));  
73
+    axis tight, grid on
74
+
75
+end 
76
+
... ...
@@ -0,0 +1,155 @@
1
+function [sM,sTrain] = som_prototrain(sM, D)
2
+
3
+%SOM_PROTOTRAIN  Use sequential algorithm to train the Self-Organizing Map.
4
+%
5
+% [sM,sT] = som_prototrain(sM, D)
6
+% 
7
+%  sM = som_prototrain(sM,D);
8
+%
9
+%  Input and output arguments: 
10
+%   sM      (struct) map struct, the trained and updated map is returned
11
+%           (matrix) codebook matrix of a self-organizing map
12
+%                    size munits x dim or  msize(1) x ... x msize(k) x dim
13
+%                    The trained map codebook is returned.
14
+%   D       (struct) training data; data struct
15
+%           (matrix) training data, size dlen x dim
16
+%
17
+% This function is otherwise just like SOM_SEQTRAIN except that
18
+% the implementation of the sequential training algorithm is very 
19
+% straightforward (and slower). This should make it easy for you 
20
+% to modify the algorithm, if you want to. 
21
+%
22
+% For help on input and output parameters, try 
23
+% 'type som_prototrain' or check out the help for SOM_SEQTRAIN.
24
+% See also SOM_SEQTRAIN, SOM_BATCHTRAIN.
25
+
26
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Vesanto
27
+% http://www.cis.hut.fi/projects/somtoolbox/
28
+
29
+% Version 2.0beta juuso 080200 130300
30
+ 
31
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
32
+%% Check input arguments
33
+
34
+% map 
35
+struct_mode = isstruct(sM);
36
+if struct_mode, 
37
+  M = sM.codebook; 
38
+  sTopol = sM.topol; 
39
+  mask = sM.mask; 
40
+  msize = sTopol.msize;
41
+  neigh = sM.neigh;
42
+else  
43
+  M = sM; orig_size = size(M);
44
+  if ndims(sM) > 2, 
45
+    si = size(sM); dim = si(end); msize = si(1:end-1);
46
+    M = reshape(sM,[prod(msize) dim]);
47
+  else
48
+    msize = [orig_size(1) 1]; dim = orig_size(2);
49
+  end
50
+  sM = som_map_struct(dim,'msize',msize); sTopol = sM.topol;
51
+  mask = ones(dim,1);
52
+  neigh = 'gaussian';
53
+end
54
+[munits dim] = size(M); 
55
+
56
+% data
57
+if isstruct(D), data_name = D.name; D = D.data; 
58
+else data_name = inputname(2); 
59
+end
60
+D = D(find(sum(isnan(D),2) < dim),:); % remove empty vectors from the data
61
+[dlen ddim] = size(D);                % check input dimension
62
+if dim ~= ddim, error('Map and data input space dimensions disagree.'); end
63
+
64
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
65
+%% initialize (these are default values, change as you will)
66
+
67
+% training length
68
+trainlen = 20*dlen; % 20 epochs by default
69
+
70
+% neighborhood radius
71
+radius_type = 'linear';
72
+rini = max(msize)/2;
73
+rfin = 1;
74
+
75
+% learning rate
76
+alpha_type = 'inv'; 
77
+alpha_ini = 0.2;
78
+
79
+% initialize random number generator
80
+rand('state',sum(100*clock));
81
+
82
+% tracking 
83
+start = clock; trackstep = 100;
84
+
85
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
86
+%% Action
87
+
88
+Ud = som_unit_dists(sTopol); % distance between map units on the grid
89
+mu_x_1 = ones(munits,1);     % this is used pretty often
90
+
91
+for t = 1:trainlen, 
92
+
93
+  %% find BMU
94
+  ind = ceil(dlen*rand(1)+eps);       % select one vector
95
+  x = D(ind,:);                       % pick it up
96
+  known = ~isnan(x);                  % its known components
97
+  Dx = M(:,known) - x(mu_x_1,known);  % each map unit minus the vector
98
+  dist2 = (Dx.^2)*mask(known);        % squared distances  
99
+  [qerr bmu] = min(dist2);            % find BMU
100
+
101
+  %% neighborhood  
102
+  switch radius_type, % radius
103
+   case 'linear', r = rini+(rfin-rini)*(t-1)/(trainlen-1);
104
+  end
105
+  if ~r, r=eps; end % zero neighborhood radius may cause div-by-zero error  
106
+  switch neigh, % neighborhood function 
107
+  case 'bubble',   h = (Ud(:,bmu) <= r);
108
+  case 'gaussian', h = exp(-(Ud(:,bmu).^2)/(2*r*r)); 
109
+  case 'cutgauss', h = exp(-(Ud(:,bmu).^2)/(2*r*r)) .* (Ud(:,bmu) <= r);
110
+  case 'ep',       h = (1 - (Ud(:,bmu).^2)/(r*r)) .* (Ud(:,bmu) <= r);
111
+  end  
112
+
113
+  %% learning rate
114
+  switch alpha_type,
115
+   case 'linear', a = (1-t/trainlen)*alpha_ini;
116
+   case 'inv',    a = alpha_ini / (1 + 99*(t-1)/(trainlen-1));
117
+   case 'power',  a = alpha_ini * (0.005/alpha_ini)^((t-1)/trainlen); 
118
+  end
119
+  
120
+  %% update
121
+  M(:,known) = M(:,known) - a*h(:,ones(sum(known),1)).*Dx;
122
+			 
123
+  %% tracking
124
+  if t==1 | ~rem(t,trackstep),
125
+    elap_t = etime(clock,start); tot_t = elap_t*trainlen/t; 
126
+    fprintf(1,'\rTraining: %3.0f/ %3.0f s',elap_t,tot_t)
127
+  end
128
+  
129
+end; % for t = 1:trainlen
130
+fprintf(1,'\n');
131
+
132
+% outputs
133
+sTrain = som_set('som_train','algorithm','proto',...
134
+		 'data_name',data_name,...
135
+		 'neigh',neigh,...
136
+		 'mask',mask,...
137
+		 'radius_ini',rini,...
138
+		 'radius_fin',rfin,...
139
+		 'alpha_ini',alpha_ini,...
140
+		 'alpha_type',alpha_type,...
141
+		 'trainlen',trainlen,...
142
+		 'time',datestr(now,0));
143
+
144
+if struct_mode, 
145
+  sM = som_set(sM,'codebook',M,'mask',mask,'neigh',neigh);
146
+  sM.trainhist(end+1) = sTrain;
147
+else
148
+  sM = reshape(M,orig_size);
149
+end
150
+
151
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
152
+
153
+
154
+
155
+
... ...
@@ -0,0 +1,156 @@
1
+function [mqe,tge] = som_quality(sMap, D)
2
+
3
+%SOM_QUALITY Calculate the mean quantization and topographic error.
4
+%
5
+% [qe,te] = som_quality(sMap, D)
6
+%
7
+%  qe = som_quality(sMap,D);
8
+%  [qe,te] = som_quality(sMap,sD);
9
+%
10
+%  Input and output arguments: 
11
+%   sMap     (struct) a map struct
12
+%   D                 the data
13
+%            (struct) a data struct
14
+%            (matrix) a data matrix, size dlen x dim
15
+%
16
+%   qe       (scalar) mean quantization error
17
+%   te       (scalar) topographic error
18
+%
19
+% The issue of SOM quality is a complicated one. Typically two
20
+% evaluation criterias are used: resolution and topology preservation.
21
+% If the dimension of the data set is higher than the dimension of the 
22
+% map grid, these usually become contradictory goals. 
23
+%
24
+% The first value returned by this function measures resolution and the
25
+% second the topology preservation.
26
+%  qe : Average distance between each data vector and its BMU.
27
+%  te : Topographic error, the proportion of all data vectors
28
+%       for which first and second BMUs are not adjacent units.
29
+%
30
+% NOTE: when calculating BMUs of data vectors, the mask of the given 
31
+%       map is used.
32
+%
33
+% For more help, try 'type som_quality' or check out the online documentation.
34
+% See also SOM_BMUS.
35
+
36
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
37
+%
38
+% som_quality
39
+%
40
+% PURPOSE
41
+%
42
+% Calculates two quality measures for the given map.
43
+%
44
+% SYNTAX
45
+%
46
+%  qe = som_quality(sM,sD);
47
+%  qe = som_quality(sM,D);
48
+%  [qe,te] = som_quality(...);
49
+%
50
+% DESCRIPTION
51
+%
52
+% This function measures the quality of the given map. The measures are
53
+% data-dependent: they measure the map in terms of the given
54
+% data. Typically, the quality of the map is measured in terms of the
55
+% training data. The returned quality measures are average quantization
56
+% error and topographic error.
57
+%
58
+% The issue of SOM quality is a complicated one. Typically two evaluation
59
+% criterias are used: resolution and topology preservation. There are
60
+% many ways to measure them. The ones implemented here were chosen for
61
+% their simplicity.
62
+%
63
+%  qe : Average distance between each data vector and its BMU.
64
+%       Measures map resolution.
65
+%  te : Topographic error, the proportion of all data vectors
66
+%       for which first and second BMUs are not adjacent units.
67
+%       Measures topology preservation.
68
+%
69
+% NOTE: when calculating BMUs of data vectors, the mask of the given 
70
+%       map is used. The mask affects the quantization errors, too.
71
+%       If you want the quantization errors without the weighting given
72
+%       by the mask, you can use the following code: 
73
+%         bmus = som_bmus(sMap,D); % this uses the mask in finding the BMUs
74
+%         for i=1:length(bmus), 
75
+%           dx = sMap.codebook(bmus(i),:)-D(i,:); % m - x
76
+%           dx(isnan(dx)) = 0;                    % remove NaNs 
77
+%           qerr(i) = sqrt(sum(dx.^2));           % euclidian distance
78
+%         end
79
+%         qe = mean(qerr); % average quantization error
80
+%
81
+% Please note that you should _not_ trust the measures blindly. Generally,
82
+% both measures give the best results when the map has overfitted the
83
+% data. This may happen when the number of map units is as large or larger
84
+% than the number of training samples. Beware when you have such a case.
85
+%
86
+% REFERENCES
87
+%
88
+% Kohonen, T., "Self-Organizing Map", 2nd ed., Springer-Verlag, 
89
+%    Berlin, 1995, pp. 113.
90
+% Kiviluoto, K., "Topology Preservation in Self-Organizing Maps", 
91
+%    in the proceeding of International Conference on Neural
92
+%    Networks (ICNN), 1996, pp. 294-299.
93
+%
94
+% INPUT ARGUMENTS
95
+%
96
+%  sMap    (struct) Map struct.
97
+%  D                The data to be used.
98
+%          (matrix) A data matrix, size dlen x dim.
99
+%          (struct) A data struct.
100
+%
101
+% OUTPUT ARGUMENTS
102
+% 
103
+%  qe      (scalar) mean quantization error
104
+%  te      (scalar) topographic error
105
+%
106
+% EXAMPLES
107
+%
108
+%  qe = som_quality(sMap,D);
109
+%  [qe,te] = som_quality(sMap,sD);
110
+%
111
+% SEE ALSO
112
+% 
113
+%  som_bmus         Find BMUs for the given set of data vectors.
114
+
115
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
116
+% http://www.cis.hut.fi/projects/somtoolbox/
117
+
118
+% Version 1.0beta juuso 220997
119
+% Version 2.0beta juuso 151199
120
+
121
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
122
+%% check arguments
123
+
124
+% input arguments
125
+if nargin < 2, error('Not enough input arguments.'); end
126
+
127
+% data
128
+if isstruct(D), D = D.data; end
129
+[dlen dim] = size(D);
130
+
131
+% calculate topographic error, too?
132
+if nargout==1, b=1; else b=[1:2]; end
133
+[bmus qerrs]= som_bmus(sMap,D,b);
134
+inds = find(~isnan(bmus(:,1)));
135
+bmus = bmus(inds,:);
136
+qerrs = qerrs(inds,:);
137
+l = length(inds);
138
+if ~l, error('Empty data set.'); end
139
+
140
+% mean quantization error
141
+mqe = mean(qerrs(:,1));
142
+
143
+if length(b)==2, % topographic error
144
+  Ne = full(som_unit_neighs(sMap.topol));
145
+  tge = 0;
146
+  for i=1:l, tge = tge+(Ne(bmus(i,1),bmus(i,2)) ~= 1); end
147
+  tge = tge / l;
148
+else
149
+  tge = NaN;
150
+end
151
+
152
+return;
153
+
154
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
155
+
156
+
... ...
@@ -0,0 +1,215 @@
1
+function sMap = som_randinit(D, varargin)
2
+
3
+%SOM_RANDINIT Initialize a Self-Organizing Map with random values.
4
+%
5
+% sMap = som_randinit(D, [[argID,] value, ...])
6
+%
7
+%  sMap = som_randinit(D);
8
+%  sMap = som_randinit(D,sMap);
9
+%  sMap = som_randinit(D,'munits',100,'hexa');
10
+% 
11
+%  Input and output arguments ([]'s are optional): 
12
+%    D                 The training data.
13
+%             (struct) data struct
14
+%             (matrix) data matrix, size dlen x dim
15
+%   [argID,   (string) Parameters affecting the map topology are given 
16
+%    value]   (varies) as argument ID - argument value pairs, listed below.
17
+%
18
+%   sMap      (struct) map struct
19
+%
20
+% Here are the valid argument IDs and corresponding values. The values 
21
+% which are unambiguous (marked with '*') can be given without the
22
+% preceeding argID.
23
+%  'munits'       (scalar) number of map units
24
+%  'msize'        (vector) map size
25
+%  'lattice'     *(string) map lattice: 'hexa' or 'rect'
26
+%  'shape'       *(string) map shape: 'sheet', 'cyl' or 'toroid'
27
+%  'topol'       *(struct) topology struct
28
+%  'som_topol','sTopol'    = 'topol'
29
+%  'map'         *(struct) map struct
30
+%  'som_map','sMap'        = 'map'
31
+%
32
+% For more help, try 'type som_randinit' or check out online documentation.
33
+% See also SOM_MAP_STRUCT, SOM_LININIT, SOM_MAKE.
34
+
35
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
36
+%
37
+% som_randinit
38
+%
39
+% PURPOSE
40
+%
41
+% Initializes a SOM with random values.
42
+%
43
+% SYNTAX
44
+%
45
+%  sMap = som_randinit(D)
46
+%  sMap = som_randinit(D,sMap);
47
+%  sMap = som_randinit(D,'munits',100,'hexa');
48
+%
49
+% DESCRIPTION
50
+%
51
+% Initializes a SOM with random values. If necessary, a map struct
52
+% is created first. For each component (xi), the values are uniformly
53
+% distributed in the range of [min(xi) max(xi)]. 
54
+%
55
+% REQUIRED INPUT ARGUMENTS
56
+%
57
+%  D                 The training data.
58
+%           (struct) Data struct. If this is given, its '.comp_names' and 
59
+%                    '.comp_norm' fields are copied to the map struct.
60
+%           (matrix) data matrix, size dlen x dim
61
+%  
62
+% OPTIONAL INPUT ARGUMENTS 
63
+%
64
+%  argID (string) Argument identifier string (see below).
65
+%  value (varies) Value for the argument (see below).
66
+%
67
+%  The optional arguments can be given as 'argID',value -pairs. If an
68
+%  argument is given value multiple times, the last one is used. 
69
+%
70
+%  Here are the valid argument IDs and corresponding values. The values 
71
+%  which are unambiguous (marked with '*') can be given without the 
72
+%  preceeding argID.
73
+%  'dlen'         (scalar) length of the training data
74
+%  'data'         (matrix) the training data
75
+%                *(struct) the training data
76
+%  'munits'       (scalar) number of map units
77
+%  'msize'        (vector) map size
78
+%  'lattice'     *(string) map lattice: 'hexa' or 'rect'
79
+%  'shape'       *(string) map shape: 'sheet', 'cyl' or 'toroid'
80
+%  'topol'       *(struct) topology struct
81
+%  'som_topol','sTopol'    = 'topol'
82
+%  'map'         *(struct) map struct
83
+%  'som_map','sMap'        = 'map'
84
+%
85
+% OUTPUT ARGUMENTS
86
+% 
87
+%  sMap     (struct) The initialized map struct.
88
+%
89
+% EXAMPLES
90
+%
91
+%  sMap = som_randinit(D);
92
+%  sMap = som_randinit(D,sMap);
93
+%  sMap = som_randinit(D,sTopol);
94
+%  sMap = som_randinit(D,'msize',[10 10]);
95
+%  sMap = som_randinit(D,'munits',100,'hexa');
96
+%
97
+% SEE ALSO
98
+% 
99
+%  som_map_struct   Create a map struct.
100
+%  som_lininit      Initialize a map using linear initialization algorithm.
101
+%  som_make         Initialize and train self-organizing map.
102
+
103
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
104
+% http://www.cis.hut.fi/projects/somtoolbox/
105
+
106
+% Version 1.0beta ecco 100997
107
+% Version 2.0beta juuso 101199
108
+
109
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
110
+%% check arguments
111
+
112
+% data
113
+if isstruct(D), 
114
+  data_name = D.name; 
115
+  comp_names = D.comp_names; 
116
+  comp_norm = D.comp_norm; 
117
+  D = D.data;
118
+  struct_mode = 1; 
119
+else 
120
+  data_name = inputname(1); 
121
+  struct_mode = 0; 
122
+end
123
+[dlen dim] = size(D);
124
+
125
+% varargin
126
+sMap = [];
127
+sTopol = som_topol_struct; 
128
+sTopol.msize = 0; 
129
+munits = NaN;
130
+i=1; 
131
+while i<=length(varargin), 
132
+  argok = 1; 
133
+  if ischar(varargin{i}), 
134
+    switch varargin{i}, 
135
+     case 'munits',     i=i+1; munits = varargin{i}; sTopol.msize = 0;
136
+     case 'msize',      i=i+1; sTopol.msize = varargin{i};
137
+                               munits = prod(sTopol.msize); 
138
+     case 'lattice',    i=i+1; sTopol.lattice = varargin{i}; 
139
+     case 'shape',      i=i+1; sTopol.shape = varargin{i}; 
140
+     case {'som_topol','sTopol','topol'}, i=i+1; sTopol = varargin{i}; 
141
+     case {'som_map','sMap','map'}, i=i+1; sMap = varargin{i}; sTopol = sMap.topol;
142
+     case {'hexa','rect'},          sTopol.lattice = varargin{i}; 
143
+     case {'sheet','cyl','toroid'}, sTopol.shape = varargin{i};
144
+     otherwise argok=0; 
145
+    end
146
+  elseif isstruct(varargin{i}) & isfield(varargin{i},'type'), 
147
+    switch varargin{i}.type, 
148
+     case 'som_topol',
149
+      sTopol = varargin{i}; 
150
+     case 'som_map', 
151
+      sMap = varargin{i};
152
+      sTopol = sMap.topol;
153
+     otherwise argok=0; 
154
+    end
155
+  else
156
+    argok = 0; 
157
+  end
158
+  if ~argok, 
159
+    disp(['(som_topol_struct) Ignoring invalid argument #' num2str(i)]); 
160
+  end
161
+  i = i+1; 
162
+end
163
+
164
+if ~isempty(sMap), 
165
+  [munits dim2] = size(sMap.codebook);
166
+  if dim2 ~= dim, error('Map and data must have the same dimension.'); end
167
+end
168
+
169
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
170
+%% create map
171
+
172
+% map struct
173
+if ~isempty(sMap), 
174
+  sMap = som_set(sMap,'topol',sTopol);
175
+else  
176
+  if ~prod(sTopol.msize), 
177
+    if isnan(munits), 
178
+      sTopol = som_topol_struct('data',D,sTopol);
179
+    else
180
+      sTopol = som_topol_struct('data',D,'munits',munits,sTopol);
181
+    end
182
+  end  
183
+  sMap = som_map_struct(dim, sTopol); 
184
+end
185
+
186
+if struct_mode, 
187
+  sMap = som_set(sMap,'comp_names',comp_names,'comp_norm',comp_norm);
188
+end
189
+
190
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
191
+%% initialization
192
+
193
+% train struct
194
+sTrain = som_train_struct('algorithm','randinit');
195
+sTrain = som_set(sTrain,'data_name',data_name);
196
+
197
+munits = prod(sMap.topol.msize);
198
+sMap.codebook = rand([munits dim]); 
199
+
200
+% set interval of each component to correct value
201
+for i = 1:dim,
202
+  inds = find(~isnan(D(:,i)) & ~isinf(D(:,i))); 
203
+  if isempty(inds), mi = 0; ma = 1; 
204
+  else ma = max(D(inds,i)); mi = min(D(inds,i));  
205
+  end
206
+  sMap.codebook(:,i) = (ma - mi) * sMap.codebook(:,i) + mi; 
207
+end
208
+
209
+% training struct
210
+sTrain = som_set(sTrain,'time',datestr(now,0));
211
+sMap.trainhist = sTrain;
212
+
213
+return;
214
+
215
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
0 216
\ No newline at end of file
... ...
@@ -0,0 +1,215 @@
1
+function sMap = som_read_cod(filename)
2
+
3
+%SOM_READ_COD Reads a SOM_PAK format codebook file.
4
+%
5
+% sMap = som_read_cod(filename);
6
+%
7
+%  sMap = som_read_cod('map1.cod');
8
+%
9
+%  Input and output arguments: 
10
+%   filename    (string) name of input file
11
+%   sMap        (struct) self-organizing map structure
12
+%
13
+% The file must be in SOM_PAK format. Empty lines and lines starting 
14
+% with a '#' are ignored, except the ones starting with '#n'. The strings 
15
+% after '#n' are read to field 'comp_names' of the map structure.
16
+%
17
+% For more help, try 'type som_read_cod' or check out online documentation.
18
+% See also SOM_WRITE_COD, SOM_READ_DATA, SOM_WRITE_DATA, SOM_MAP_STRUCT.
19
+
20
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
21
+%
22
+% som_read_cod
23
+%
24
+% PURPOSE
25
+%
26
+% Reads a Self-Organizing Map from an ascii file in SOM_PAK format.
27
+%
28
+% SYNTAX
29
+%
30
+%  sMap = som_read_cod(filename); 
31
+%
32
+% DESCRIPTION
33
+%
34
+% This function is offered for compatibility with SOM_PAK, a SOM 
35
+% software package in C. It reads map files written in SOM_PAK format.
36
+%
37
+% The SOM_PAK map file format is as follows. The first line must contain
38
+% the input space dimension, lattice type ('rect' or 'hexa'), map grid
39
+% size in x-direction, map grid size in y-direction, and neighborhood
40
+% function ('bubble' or 'gaussian'), in that order. The following lines
41
+% are comment lines, empty lines or data lines. 
42
+%
43
+% Each data line contains the weight vector of one map unit and its
44
+% labels. From the beginning of the line, first are values of the vector
45
+% components separated by whitespaces, then labels, again separated by
46
+% whitespaces. The order of map units in the file are one row at a time
47
+% from right to left, from the top to the bottom of the map (x-direction
48
+% first, then y-direction). 
49
+% 
50
+% Comment lines start with '#'. Comment lines as well as empty lines are
51
+% ignored, except if the comment line starts with '#n'. In that case the
52
+% line should contain names of the vector components separated by
53
+% whitespaces.
54
+%
55
+% In the returned map struct, several fields has to be set to default
56
+% values, since the SOM_PAK file does not contain information on
57
+% them. These include map shape ('sheet'), mask ([1 ... 1]),
58
+% normalizations (none), trainhist (two entries, first with algorithm
59
+% 'init' and the second with 'seq', both with data name 'unknown'),
60
+% possibly also component names ('Var1',...). 
61
+%
62
+% REQUIRED INPUT PARAMETERS
63
+%
64
+%  filename   (string) the name of the input file
65
+%
66
+% OUTPUT ARGUMENTS
67
+%
68
+%  sMap       (struct) the resulting SOM struct
69
+% 
70
+% EXAMPLES
71
+%
72
+%  sMap = som_read_cod('map1.cod');
73
+%
74
+% SEE ALSO
75
+% 
76
+%  som_write_cod    Writes a map struct into a file in SOM_PAK format.
77
+%  som_read_data    Reads data from an ascii file.
78
+%  som_write_data   Writes data struct into a file in SOM_PAK format.
79
+%  som_map_struct   Creates map structs.
80
+
81
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
82
+% http://www.cis.hut.fi/projects/somtoolbox/
83
+
84
+% Version 1.0beta ecco 221097
85
+% Version 2.0beta juuso 151199 250400
86
+
87
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
88
+%% check arguments
89
+
90
+error(nargchk(1, 1, nargin))  % check no. of input args is correct
91
+
92
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
93
+%% initialize variables
94
+
95
+lnum           = 0;    % codebook vector counter
96
+comment_start  = '#';  % the char a SOM_PAK command line starts with
97
+comp_name_line = '#n'; % string used to start a special command line,
98
+                       % which contains names of each component
99
+
100
+% open input file
101
+
102
+fid = fopen(filename);
103
+if fid < 0, error(['Cannot open ' filename]); end
104
+ 
105
+% read header line
106
+
107
+ok_cnt = 0;
108
+lin = fgetl(fid); li = lin;
109
+[dim c err n]  = sscanf(li, '%d%[^ \t]'); ok_cnt=ok_cnt+c; li = li(n:end);
110
+[lattice c err n] = sscanf(li,'%s%[^ \t]'); ok_cnt=ok_cnt+c; li = li(n:end);
111
+[msize(2) c err n] = sscanf(li, '%d%[^ \t]'); ok_cnt=ok_cnt+c; li = li(n:end);
112
+[msize(1) c err n] = sscanf(li, '%d%[^ \t]'); ok_cnt=ok_cnt+c; li = li(n:end);
113
+[neigh c err n] = sscanf(li, '%s%[^ \t\n]'); ok_cnt=ok_cnt+c;
114
+
115
+if ok_cnt ~= 5
116
+  error([ 'Invalid header line: ' lin ]); 
117
+end                                 
118
+
119
+% create map struct and set its fields according to header line
120
+
121
+munits = prod(msize);
122
+sMap   = som_map_struct(dim, 'msize', msize, ...
123
+			lattice, 'sheet', 'neigh', neigh);
124
+[sT0, ok] = som_set('som_train','algorithm','init','data_name','unknown');
125
+sT1       = som_set('som_train','algorithm','seq','data_name','unknown',...
126
+                    'neigh',neigh,'mask',ones(dim,1));
127
+[sMap, ok, msgs] = som_set(sMap,'name',filename,'trainhist',{sT0,sT1});
128
+
129
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
130
+%% read codebook from the file
131
+
132
+codebook   = zeros(munits,dim);
133
+labels     = cell(munits,1);
134
+comp_names = sMap.comp_names;
135
+form       = [repmat('%f',[1 dim-1]) '%f%[^ \t]'];
136
+
137
+while 1, 
138
+  li = fgetl(fid);                         % read next line
139
+  if ~isstr(li), break, end;               % is this the end of file?
140
+
141
+  [data, c, err, n] = sscanf(li, form);
142
+  if c < dim % if there were less numbers than dim on the input file line
143
+    if c == 0
144
+      if strncmp(li, comp_name_line, 2) % component name line?
145
+        li = li(3:end); i = 0; c = 1;
146
+        while c
147
+          [s, c, e, n] = sscanf(li, '%s%[^ \t]');
148
+          if ~isempty(s), i = i + 1; comp_names{i} = s; li = li(n:end); end
149
+        end
150
+
151
+        if i ~= dim
152
+          error(['Illegal number of component names: ' num2str(i) ...
153
+                 ' (dimension is ' num2str(dim) ')']);
154
+        end
155
+      elseif ~strncmp(li, comment_start, 1) % not a comment, is it error?
156
+        [s, c, e, n] = sscanf(li, '%s%[^ \t]');
157
+        if c
158
+          error(['Invalid vector on input file line ' ...
159
+                 num2str(lnum+1) ': [' deblank(li) ']']),
160
+        end
161
+      end
162
+    else
163
+      error(['Only ' num2str(c) ' vector components on input file line ' ...
164
+             num2str(lnum+1) ' (dimension is ' num2str(dim) ')']);
165
+    end
166
+
167
+  else
168
+
169
+    lnum = lnum + 1;                % this was a line containing data vector
170
+    codebook(lnum, 1:dim) = data'; % add data to struct
171
+
172
+    % read labels
173
+
174
+    if n < length(li)
175
+      li = li(n:end);
176
+      i = 0; n = 1; c = 1;
177
+      while c
178
+        [s, c, e, n_new] = sscanf(li(n:end), '%s%[^ \t]');
179
+        if c, i = i + 1; labels{lnum, i} = s; n = n + n_new - 1; end
180
+      end
181
+    end
182
+  end
183
+end
184
+
185
+% close the input file
186
+
187
+if fclose(fid) < 0
188
+  error(['Cannot close file ' filename]); 
189
+else
190
+  fprintf(2, '\rmap read ok         \n');
191
+end
192
+
193
+% check that the number of lines read was correct
194
+
195
+if lnum ~= munits
196
+  error(['Illegal number of map units: ' num2str(lnum) ' (should be ' num2str(munits) ').']);
197
+end
198
+
199
+% set values
200
+
201
+% in SOM_PAK the xy-indexing is used, while in Matlab ij-indexing
202
+% therefore, the codebook vectors have to be reorganized 
203
+
204
+order = reshape([1:munits],msize);
205
+order = reshape(order',[munits 1]);
206
+codebook(order,:) = codebook;
207
+labels(order,:) = labels; 
208
+
209
+sMap.codebook   = codebook;
210
+sMap.labels     = labels;
211
+sMap.comp_names = comp_names;
212
+
213
+return;
214
+
215
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,288 @@
1
+function sData = som_read_data(filename, varargin)
2
+
3
+%SOM_READ_DATA Read data from an ascii file in SOM_PAK format.
4
+%
5
+% sD = som_read_data(filename, dim, [missing])
6
+% sD = som_read_data(filename, [missing])
7
+%
8
+%  sD = som_read_data('system.data');
9
+%  sD = som_read_data('system.data',10);
10
+%  sD = som_read_data('system.data','*');
11
+%  sD = som_read_data('system.data',10,'*');
12
+%
13
+%  Input and output arguments ([]'s are optional): 
14
+%   filename    (string) input file name
15
+%   dim         (scalar) input space dimension
16
+%   [missing]   (string) string which indicates a missing component
17
+%                        value, 'NaN' by default
18
+%
19
+%   sD          (struct) data struct
20
+%
21
+% Reads data from an ascii file. The file must be in SOM_PAK format, 
22
+% except that it may lack the input space dimension from the first
23
+% line. 
24
+%
25
+% For more help, try 'type som_read_data' or check out online documentation.
26
+% See also  SOM_WRITE_DATA, SOM_READ_COD, SOM_WRITE_COD, SOM_DATA_STRUCT.
27
+
28
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
29
+%
30
+% som_read_data
31
+%
32
+% PURPOSE
33
+%
34
+% Reads data from an ascii file in SOM_PAK format.
35
+%
36
+% SYNTAX
37
+%
38
+%  sD = som_read_data(filename)
39
+%  sD = som_read_data(..., dim)
40
+%  sD = som_read_data(..., 'missing')
41
+%  sD = som_read_data(..., dim, 'missing')
42
+%
43
+% DESCRIPTION
44
+%
45
+% This function is offered for compatibility with SOM_PAK, a SOM software
46
+% package in C. It reads data from a file in SOM_PAK format.
47
+%
48
+% The SOM_PAK data file format is as follows. The first line must
49
+% contain the input space dimension and nothing else. The following
50
+% lines are comment lines, empty lines or data lines. Unlike programs
51
+% in SOM_PAK, this function can also determine the input dimension
52
+% from the first data lines, if the input space dimension line is
53
+% missing.  Note that the SOM_PAK format is not fully supported: data
54
+% vector 'weight' and 'fixed' properties are ignored (they are treated
55
+% as labels).
56
+%
57
+% Each data line contains one data vector and its labels. From the beginning
58
+% of the line, first are values of the vector components separated by
59
+% whitespaces, then labels also separated by whitespaces. If there are
60
+% missing values in the vector, the missing value marker needs to be
61
+% specified as the last input argument ('NaN' by default). The missing
62
+% values are stored as NaNs in the data struct. 
63
+% 
64
+% Comment lines start with '#'. Comment lines as well as empty lines are
65
+% ignored, except if the comment lines that start with '#n' or '#l'. In that
66
+% case the line should contain names of the vector components or label names
67
+% separated by whitespaces.
68
+%
69
+% NOTE: The minimum value Matlab is able to deal with (realmax)
70
+% should not appear in the input file. This is because function sscanf is
71
+% not able to read NaNs: the NaNs are in the read phase converted to value
72
+% realmax.
73
+%
74
+% REQUIRED INPUT ARGUMENTS
75
+%
76
+%  filename    (string) input filename
77
+%
78
+% OPTIONAL INPUT ARGUMENTS
79
+%
80
+%  dim         (scalar) input space dimension
81
+%  missing     (string) string used to denote missing components (NaNs); 
82
+%                       default is 'NaN'
83
+%
84
+% OUTPUT ARGUMENTS
85
+%
86
+%  sD   (struct) the resulting data struct
87
+%
88
+% EXAMPLES
89
+%
90
+% The basic usage is:
91
+%  sD = som_read_data('system.data');
92
+%
93
+% If you know the input space dimension beforehand, and the file does
94
+% not contain it on the first line, it helps if you specify it as the
95
+% second argument: 
96
+%  sD = som_read_data('system.data',9);
97
+%
98
+% If the missing components in the data are marked with some other
99
+% characters than with 'NaN', you can specify it with the last argument: 
100
+%  sD = som_read_data('system.data',9,'*')
101
+%  sD = som_read_data('system.data','NaN')
102
+%
103
+% Here's an example data file:
104
+%
105
+% 5
106
+% #n one two three four five
107
+% #l ID
108
+% 10 2 3 4 5 1stline label
109
+% 0.4 0.3 0.2 0.5 0.1 2ndline label1 label2
110
+% # comment line: missing components are indicated by 'x':s
111
+% 1 x 1 x 1 3rdline missing_components
112
+% x 1 2 2 2 
113
+% x x x x x 5thline emptyline
114
+%
115
+% SEE ALSO
116
+%
117
+%  som_write_data   Writes data structs/matrices to a file in SOM_PAK format.
118
+%  som_read_cod     Read a map from a file in SOM_PAK format.
119
+%  som_write_cod    Writes data struct into a file in SOM_PAK format.
120
+%  som_data_struct  Creates data structs.
121
+
122
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
123
+% http://www.cis.hut.fi/projects/somtoolbox/
124
+
125
+% Version 1.0beta ecco 221097
126
+% Version 2.0beta ecco 060899, juuso 151199
127
+
128
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
129
+%% check arguments
130
+
131
+error(nargchk(1, 3, nargin))  % check no. of input args is correct
132
+
133
+dont_care       = 'NaN';  % default don't care string
134
+comment_start   = '#';    % the char a SOM_PAK command line starts with
135
+comp_name_line  = '#n';   % string denoting a special command line,
136
+                          % which contains names of each component
137
+label_name_line = '#l';   % string denoting a special command line,
138
+                          % which contains names of each label
139
+block_size      = 1000;   % block size used in file read
140
+
141
+kludge          = num2str(realmax, 100); % used in sscanf                
142
+  
143
+
144
+% open input file
145
+
146
+fid = fopen(filename);
147
+if fid < 0
148
+  error(['Cannot open ' filename]); 
149
+end
150
+
151
+% process input arguments
152
+
153
+if nargin == 2 
154
+  if isstr(varargin{1})
155
+    dont_care = varargin{1};
156
+  else
157
+    dim      = varargin{1};
158
+  end
159
+elseif nargin == 3
160
+  dim       = varargin{1};
161
+  dont_care = varargin{2};
162
+end
163
+
164
+% if the data dimension is not specified, find out what it is
165
+
166
+if nargin == 1 | (nargin == 2 & isstr(varargin{1}))
167
+
168
+  fpos1 = ftell(fid); c1 = 0;      % read first non-comment line
169
+  while c1 == 0,
170
+    line1 = strrep(fgetl(fid), dont_care, kludge);
171
+    [l1, c1] = sscanf(line1, '%f ');
172
+  end
173
+
174
+  fpos2 = ftell(fid); c2 = 0;      % read second non-comment line
175
+  while c2 == 0,
176
+    line2 = strrep(fgetl(fid), dont_care, kludge);
177
+    [l2, c2] = sscanf(line2, '%f ');
178
+  end
179
+
180
+  if (c1 == 1 & c2 ~= 1) | (c1 == c2 & c1 == 1 & l1 == 1)
181
+    dim = l1;
182
+    fseek(fid, fpos2, -1);
183
+  elseif (c1 == c2)
184
+    dim = c1;
185
+    fseek(fid, fpos1, -1);
186
+    warning on
187
+    warning(['Automatically determined data dimension is ' ...
188
+	     num2str(dim) '. Is it correct?']); 
189
+  else
190
+    error(['Invalid header line: ' line1]);
191
+  end
192
+end 
193
+
194
+% check the dimension is valid
195
+
196
+if dim < 1 | dim ~= round(dim) 
197
+  error(['Illegal data dimension: ' num2str(dim)]);
198
+end
199
+
200
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
201
+%% read data
202
+
203
+sData       = som_data_struct(zeros(1, dim), 'name', filename); 
204
+lnum        = 0;                                    % data vector counter
205
+data_temp   = zeros(block_size, dim);
206
+labs_temp   = cell(block_size, 1);
207
+comp_names  = sData.comp_names;
208
+label_names = sData.label_names;
209
+form        = [repmat('%g',[1 dim-1]) '%g%[^ \t]'];
210
+
211
+limit       = block_size;
212
+while 1,
213
+  li = fgetl(fid);                         % read next line
214
+  if ~isstr(li), break, end;               % is this the end of file? 
215
+
216
+  % all missing vectors are replaced by value realmax because
217
+  % sscanf is not able to read NaNs  
218
+  li = strrep(li, dont_care, kludge);     
219
+  [data, c, err, n] = sscanf(li, form);
220
+  if c < dim % if there were less numbers than dim on the input file line
221
+    if c == 0
222
+      if strncmp(li, comp_name_line, 2) % component name line?
223
+	li = strrep(li(3:end), kludge, dont_care); i = 0; c = 1;
224
+	while c
225
+	  [s, c, e, n] = sscanf(li, '%s%[^ \t]');
226
+	  if ~isempty(s), i = i + 1; comp_names{i} = s; li = li(n:end); end
227
+	end
228
+
229
+	if i ~= dim 
230
+	  error(['Illegal number of component names: ' num2str(i) ...
231
+		 ' (dimension is ' num2str(dim) ')']); 
232
+	end
233
+      elseif strncmp(li, label_name_line, 2) % label name line?
234
+	li = strrep(li(3:end), kludge, dont_care); i = 0; c = 1;
235
+	while c
236
+	  [s, c, e, n] = sscanf(li, '%s%[^ \t]');
237
+	  if ~isempty(s), i = i + 1; label_names{i} = s; li = li(n:end); end
238
+	end
239
+      elseif ~strncmp(li, comment_start, 1) % not a comment, is it error?
240
+	[s, c, e, n] = sscanf(li, '%s%[^ \t]');
241
+	if c
242
+	  error(['Invalid vector on input file data line ' ...
243
+		 num2str(lnum+1) ': [' deblank(li) ']']),
244
+	end
245
+      end
246
+    else
247
+      error(['Only ' num2str(c) ' vector components on input file data line ' ...
248
+	     num2str(lnum+1) ' (dimension is ' num2str(dim) ')']);
249
+    end
250
+
251
+  else
252
+
253
+    lnum = lnum + 1;                % this was a line containing data vector
254
+    data_temp(lnum, 1:dim) = data'; % add data to struct
255
+
256
+    if lnum == limit       % reserve more memory if necessary
257
+      data_temp(lnum+1:lnum+block_size, 1:dim) = zeros(block_size, dim);
258
+      [dummy nl] = size(labs_temp);
259
+      labs_temp(lnum+1:lnum+block_size,1:nl) = cell(block_size, nl);
260
+      limit = limit + block_size;
261
+    end
262
+    
263
+    % read labels
264
+    
265
+    if n < length(li)
266
+      li = strrep(li(n:end), kludge, dont_care); i = 0; n = 1; c = 1;
267
+      while c
268
+	[s, c, e, n_new] = sscanf(li(n:end), '%s%[^ \t]');
269
+	if c, i = i + 1; labs_temp{lnum, i} = s; n = n + n_new - 1; end
270
+      end
271
+    end
272
+  end
273
+end
274
+
275
+% close input file
276
+if fclose(fid) < 0, error(['Cannot close file ' filename]);
277
+else fprintf(2, '\rdata read ok         \n'); end
278
+
279
+% set values
280
+data_temp(data_temp == realmax) = NaN;
281
+sData.data        = data_temp(1:lnum,:);
282
+sData.labels      = labs_temp(1:lnum,:);
283
+sData.comp_names  = comp_names;
284
+sData.label_names = label_names;
285
+
286
+return;
287
+
288
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
0 289
\ No newline at end of file
... ...
@@ -0,0 +1,351 @@
1
+function h=som_recolorbar(p, ticks, scale, labels)
2
+
3
+%SOM_RECOLORBAR Refresh and  rescale colorbars in the current SOM_SHOW fig.
4
+%
5
+% h = som_recolorbar([p], [ticks], [scaling], [labels])
6
+%
7
+%   colormap(jet); som_recolorbar   
8
+%
9
+% Input and output arguments ([]'s are optional) 
10
+%  [p]      (vector) subplot number vector 
11
+%           (string) 'all' (the default), 'comp' to process only
12
+%                    component planes        
13
+%  [ticks]  (string) 'auto' or 'border', default: 'auto'
14
+%           (cell array) p x 1 cell array of p row vectors
15
+%           (vector) the same ticks are applied to all given subplots
16
+%           (scalar) value is at least 2: the number of ticks to show, 
17
+%                    evenly spaced between and including minimum and maximum 
18
+%  [scale]  (string) 'denormalized' or 'normalized' (the default)
19
+%  [labels] (cell array) p x 1 cell array of cells containing strings
20
+%
21
+%  h        (vector) handles to the colorbar objects.
22
+%
23
+% This function refreshes the colorbars in the figure created by SOM_SHOW.
24
+% Refreshing  is necessary if you have changed the colormap.
25
+% Each colorbar has letter 'd' or 'n' and possibly 'u' as label. Letter 'd' means
26
+% that the scale is denormalized, letter 'n' that the scale is
27
+% normalized, and 'u' is for user specified labels.
28
+%
29
+% For more help, try 'type som_recolorbar' or check out online documentation.
30
+% See also SOM_SHOW
31
+ 
32
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
33
+%
34
+% som_recolorbar
35
+%
36
+% PURPOSE
37
+% 
38
+% Refreshes the the colorbars in the figure.
39
+%
40
+% SYNTAX
41
+%
42
+%  h = som_recolorbar
43
+%  h = som_recolorbar(p)
44
+%  h = som_recolorbar(p, ticks)
45
+%  h = som_recolorbar(p, ticks, scaling)
46
+%  h = som_recolorbar(p, ticks, scaling, labels)
47
+%
48
+% DESCRIPTION
49
+%
50
+% This function refreshes the colorbars in the figure created by SOM_SHOW.
51
+% Refreshing is necessary if you have changed the colormap.  Each colorbar
52
+% has letter 'd' or 'n' and possibly 'u' as label. Letter 'd' means that the
53
+% scale is denormalized, letter 'n' that the scale is normalized, and 'u' is
54
+% for user specified labels.
55
+%
56
+% Different argument combinations:
57
+%
58
+% 1. Argument 'ticks' has string values:
59
+%  - 'auto' for input argument ticks sets the automatic tick
60
+%     marking on (factory default). 
61
+%  - 'border' sets the tick marks to the color borders. This is 
62
+%     convenient if there are only few colors in use. 
63
+%
64
+%  Argument scale controls the scaling of the tick mark label values. 
65
+%  'normalized' means that the tick mark labels are directly the values 
66
+%  of the ticks, that is, they refer to the map codebook values. 
67
+%  Value 'denormalized' scales the tick mark label values back to the original
68
+%  data scaling. This is made using som_denormalize_data.
69
+%
70
+% 2. Argument 'ticks' is a cell array of vectors:
71
+%  The values are set to be the tick marks to the colorbar specified by p.
72
+%  - if arg. scale is 'normalized' the ticks are set directly to the colorbar.
73
+%  - if arg. scale is 'denormalized' the tick values are first normalized 
74
+%    in the same way as the data.
75
+%
76
+% 3. Argument 'ticks' is a vector
77
+%  As above, but the same values are used for all (given) subplots.
78
+%  
79
+% 4. Argument 'ticks' is a scalar
80
+%  The ticks are set to equally spaced values between (and including)
81
+%  minimum and maximum.
82
+%     
83
+% Argument 'labels' specify user defined labels to the tick marks
84
+%
85
+% NOTE: ticks are rounded to contain three significant digits.
86
+%
87
+% OPTIONAL INPUT ARGUMENTS
88
+% 
89
+%  p        (vector) subplot number vector 
90
+%           (string) 'all' (the default), 'comp' to effect only 
91
+%                    component planes
92
+%
93
+%  ticks    (string) 'auto' or 'border', default: 'auto'
94
+%           (cell array) p x 1 cell array of p row vectors
95
+%           (vector) as the cell array, but the same vector is 
96
+%                    applied to all given subplots
97
+%           (scalar) the number of ticks to show: these are 
98
+%                    evenly space between minimum and maximum
99
+%
100
+%  scale    (string) 'denormalized' or 'normalized' (the default)
101
+%
102
+%  labels   (cell array) p x 1 cell array of cells containing strings
103
+%
104
+% OUTPUT ARGUMENTS
105
+%
106
+%  h        (vector) handles to the colorbar objects.
107
+%
108
+% EXAMPLE
109
+%
110
+%  colormap(jet(5)); som_recolorbar('all','border','denormalized')
111
+%      % Uses five colors and sets the ticks on the color borders.
112
+%      % Tick label values are denormalized back to the original data scaling
113
+%
114
+%  colormap(copper(64));som_recolorbar
115
+%      % changes to colormap copper and resets default ticking and labeling
116
+%
117
+%  som_recolorbar('all',3)
118
+%      % To put 3 ticks to each colorbar so that minimum, mean and
119
+%      % maximum values on the colorbar are shown.
120
+% 
121
+%  som_recolorbar([1 3],{[0.1 0.2 0.3];[0.2 0.4]},'denormalized')
122
+%      % Ticks colorbar 1 by first normalizing values 0.1, 0.2, 0.3 and
123
+%      % then setting the ticks to the colorbar. Labels are of course 
124
+%      % 0.1, 0.2 and 0.3. Ticks colorbar 3 in the same way using values
125
+%      % 0.2 and 0.4.
126
+%
127
+%  som_recolorbar([2 4],{[0.1 0.2];[-1.2 3]},'normalized',{{'1' '2'};{'a' 'b'}})
128
+%      % Ticks colorbar 2 and 4 directly to the specified values. Sets labels
129
+%      % '1' '2' and 'a' 'b' to the ticks.
130
+%
131
+%  som_recolorbar([2 4],{[0.1 0.2];[-1.2 3]},'normalized',{{'1' '2'};{'a' 'b'}})
132
+%      % as previous one, but normalizes tick values first
133
+%
134
+% SEE ALSO
135
+% 
136
+%  som_show        Basic SOM visualization.
137
+%  som_normalize   Normalization operations.
138
+%  som_denormalize Denormalization operations.
139
+
140
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
141
+% http://www.cis.hut.fi/projects/somtoolbox/             
142
+
143
+% Version 1.0beta Johan 061197 
144
+% Version 2.0beta juuso 151199 130300 160600 181101
145
+
146
+%% Init & check %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
147
+
148
+error(nargchk(0, 4, nargin))    % check no. of input args
149
+
150
+% Check the subplot vector p and  get the handles, exit if error
151
+% Default subplot vector is 'all'
152
+
153
+if nargin < 1 | isempty(p)                       % default p
154
+  p= 'all';
155
+end
156
+
157
+% check SOM_SHOW and get the figure data. Exit, if error
158
+
159
+[handles, msg, lattice, msize, dim, normalization, comps]= ...
160
+    vis_som_show_data(p, gcf);
161
+error(msg);                                       
162
+
163
+if nargin < 2 | isempty(ticks)                   % default tick mode is 'auto'
164
+  ticks = 'auto';
165
+elseif isa(ticks,'cell')                         % check for cell
166
+  tickValues = ticks; 
167
+  ticks= 'explicit';
168
+elseif isa(ticks,'double') & length(ticks)>1,
169
+  tickValues = {ticks}; 
170
+  ticks = 'explicit'; 
171
+elseif isa(ticks,'double') & length(ticks)==1,
172
+  tickValues = max(2,round(ticks)); 
173
+  ticks = 'evenspace'; 
174
+end
175
+if ~ischar(ticks)                                % invalid argument
176
+  error('The second argument should be a string or a cell array of vectors.');
177
+end
178
+
179
+switch ticks                                     % check ticks
180
+ case {'auto','border'}, % nill
181
+ case 'evenspace', 
182
+  tickValues_tmp = cell(length(handles),1); 
183
+  for i=1:length(handles), tickValues_tmp{i} = tickValues; end
184
+  tickValues = tickValues_tmp; 
185
+ case 'explicit', 
186
+  if length(tickValues)==1 & length(handles)>1, 
187
+    tickValues_tmp = cell(length(handles),1); 
188
+    for i=1:length(handles), tickValues_tmp{i} = tickValues{1}; end
189
+    tickValues = tickValues_tmp; 
190
+  end
191
+  if length(tickValues) ~= length(handles), 
192
+    error('Cell containing the ticks has wrong size.')
193
+  end
194
+otherwise
195
+  error('''auto'' or ''border'' expected for the second argument.');
196
+end
197
+
198
+if nargin < 3 | isempty(scale)                   % default mode is normalized
199
+  scale= 'normalized';
200
+end
201
+if ~ischar(scale)                                % check scale type
202
+  error('The third argument should be a string.'); 
203
+end
204
+switch scale                                     % check the string
205
+ case { 'normalized', 'denormalized'} % ok
206
+ case 'n', scale = 'normalized'; 
207
+ case 'd', scale = 'denormalized'; 
208
+ otherwise   
209
+  error('''normalized'' or ''denormalized'' expected for the third argument.')
210
+end
211
+
212
+if nargin < 4 | isempty(labels)                  % default is autolabeling
213
+  labels = 'auto';
214
+elseif ~isa(labels,'cell')                       % check type
215
+  error('The fourth argument should be a cell array of cells containing strings.')
216
+else
217
+  labelValues=labels;                            % set labels
218
+  labels = 'explicit';
219
+  if length(labelValues) == length(handles)      % check size
220
+    ;
221
+  else
222
+    error('Cell containing the labels has wrong size')
223
+  end
224
+end
225
+
226
+%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
227
+
228
+n = size(colormap,1)+1;                      % number of colors+1
229
+h_ = zeros(length(handles),1);  
230
+
231
+for i=1:length(handles),                   % MAIN LOOP BEGINS
232
+  axes(handles(i));                        % set axes, refres colorbar and  
233
+  if comps(i)>=0,   
234
+    h_(i)=colorbar;                          % get colorbar handles
235
+
236
+    colorbardir=get(h_(i),'YaxisLocation');
237
+    switch colorbardir                     % get colorbar direction &
238
+     case 'left'                            % set some strings
239
+      Tick='Xtick'; Lim='Xlim'; LabelMode='XTickLabelMode'; Label='XtickLabel';
240
+     case 'right'
241
+      Tick='Ytick'; Lim='Ylim'; LabelMode='YTickLabelMode'; Label='YtickLabel';
242
+     otherwise
243
+      error('Internal error: unknown value for YaxisLocation'); % fatal
244
+    end                                                         
245
+    
246
+    switch ticks                         
247
+     case 'auto'
248
+      set(h_(i),LabelMode,'auto');        % factory default ticking
249
+      tickValues{i}=get(h_(i),Tick);       % get tick values
250
+     case 'border' 
251
+      limit=caxis;                        
252
+      t=linspace(limit(1),limit(2),n);    % set n ticks between min and max 
253
+      t([1 length(t)])=get(h_(i),Lim); % <- caxis is not necerraily the same 
254
+      tickValues{i}=t;                    % as the colorbar min & max values
255
+     case 'evenspace'
256
+      limit = caxis; 
257
+      t = linspace(limit(1),limit(2),tickValues{i}); 
258
+      t([1 length(t)])=get(h_(i),Lim);
259
+      tickValues{i}=t; 
260
+     case 'explicit'
261
+      if comps(i)>0, 
262
+	if strcmp(scale,'normalized')     % normalize tick values
263
+	  tickValues{i} = som_normalize(tickValues{i},normalization{comps(i)});
264
+	end
265
+      end
266
+      
267
+     otherwise 
268
+      error('Internal error: unknown tick type')   % this shouldn't happen
269
+    end
270
+
271
+    %tickValues{i} = epsto0(tickValues{i});
272
+
273
+    switch labels
274
+     case 'auto'
275
+      switch scale                         
276
+       case 'normalized'
277
+	labelValues{i} = round2(tickValues{i});     % use the raw ones 
278
+       case 'denormalized'                 % denormalize tick values
279
+	if comps(i)>0, 
280
+	  labelValues{i} = som_denormalize(tickValues{i},normalization{comps(i)});
281
+	  labelValues{i} = round2(labelValues{i});     % round the scale
282
+	else
283
+	  labelValues{i} = round2(tickValues{i});
284
+	end
285
+       otherwise
286
+	error('Internal error: unknown scale type'); % this shouldn't happen
287
+      end
288
+     case 'explicit'
289
+      ;                                            % they are there already
290
+     otherwise
291
+      error('Internal error: unknown label type'); % this shouldn't happen
292
+    end
293
+
294
+    set(h_(i),Tick,tickValues{i});                 % set ticks and labels
295
+    set(h_(i),Label,labelValues{i});            
296
+    
297
+    if comps(i)>0, 
298
+      % Label the colorbar with letter 'n' if normalized, with letter 'd' 
299
+      % if denormalized and 'u' if the labels are user specified  
300
+      mem_axes=gca; axes(h_(i));
301
+      ch='  ';
302
+      if strcmp(scale,'normalized'),   ch(1)='n'; end
303
+      if strcmp(scale,'denormalized'), ch(1)='d'; end
304
+      if strcmp(labels,'explicit'),    ch(2)='u'; end
305
+      xlabel(ch); 
306
+      axes(mem_axes);
307
+    end
308
+  end
309
+end                                              % MAIN LOOP ENDS 
310
+
311
+
312
+%% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
313
+
314
+if nargout>0
315
+  h=h_;
316
+end
317
+
318
+return; 
319
+
320
+%% Subfunction: ROUND2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
321
+% ROUND2 rounds the labels to tol significant digits
322
+
323
+function r=round2(d)
324
+
325
+tol=3;
326
+
327
+zero=(d==0);
328
+d(zero)=1;
329
+k=floor(log10(abs(d)))-(tol-1);
330
+r=round(d./10.^k).*10.^k;
331
+r(zero)=0;
332
+%r=epsto0(r);
333
+
334
+%% Subfunction: ISVECTOR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
335
+
336
+function t=isvector(v)
337
+% ISVECTOR checks if a matrix is a vector or not
338
+
339
+t=(ndims(v) == 2 & min(size(v)) == 1) & isnumeric(v);
340
+
341
+%% Subfunction: EPSTO0
342
+
343
+function t=epsto0(t)
344
+% EPSTO0 checks whether first tick value is *very* close to zero, 
345
+% if so sets it to zero.
346
+
347
+if (t(end)-t(1))/t(end) > 1-0.005 & abs(t(1))<1, t(1) = 0; end
348
+
349
+
350
+
351
+
... ...
@@ -0,0 +1,716 @@
1
+function varargout=som_select(c_vect,plane_h,arg)
2
+
3
+%SOM_SELECT  Manual selection of map units from a visualization.
4
+%
5
+% som_select(c_vect,[plane_h])
6
+%     
7
+%   som_select(3)
8
+%   som_select(sM.labels(:,1))
9
+%
10
+%  Input arguments ([]'s are optional):
11
+%   c_vect    (scalar) number of classes 
12
+%             (vector) initial class identifiers
13
+%             (cell array) of strings, class names
14
+%             (matrix) size * x 3, the color of each class
15
+%   [plane_h] (scalar) handle of the plane (axes) to be marked. 
16
+%                      By default, the current axes is used (GCA).
17
+%                      For the function to work, the plot in the 
18
+%                      axes must have been created with the
19
+%                      SOM_CPLANE function (or SOM_SHOW).
20
+% 
21
+% Launches a GUI which allows user to select nodes from plane by 
22
+% clicking them or by choosing a region (a polygon). 
23
+% 
24
+%   Middle mouse button: selects (or clears selection of) a single node
25
+%   Left mouse button:   lets user draw a polygon
26
+%   Right mouse button:  selects (or clears selection of) the units 
27
+%                        inside the polygon
28
+% 
29
+% From the GUI, the color (class) is selected as well as whether
30
+% but buttons select or clear the selection from the units. The
31
+% buttons on the bottom have the following actions: 
32
+% 
33
+%   'OK'    Assigns the class identifiers to the 'ans' variable in 
34
+%           workspace. The value is an array of class identifiers: 
35
+%           strings (cellstr) if the c_vect was an array of
36
+%           strings, a vector otherwise.
37
+%   'Clear' Removes marks from the plane.
38
+%   'Close' Closes the application. 
39
+%
40
+% See also SOM_SHOW, SOM_CPLANE.
41
+
42
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Parhankangas 
43
+% Copyright (c) by Juha Parhankangas
44
+% http://www.cis.hut.fi/projects/somtoolbox/
45
+
46
+% Juha Parhankangas 050100, juuso 010200
47
+
48
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
49
+%% input arguments
50
+
51
+if nargin < 2, plane_h = gca; end
52
+if(isempty(gcbo)), arg='start'; end
53
+
54
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
55
+%% action
56
+
57
+switch arg
58
+ case 'start'
59
+  patch_h=find_patch(plane_h);
60
+  lattice=getfield(size(get(patch_h,'XData')),{1});
61
+  msize(1)=floor(getfield(get(plane_h,'YLim'),{2})); 
62
+  msize(2)=floor(getfield(get(plane_h,'XLim'),{2})-0.5);   
63
+  if lattice==6
64
+    lattice='hexa';
65
+  else
66
+    lattice='rect';
67
+  end
68
+  
69
+  if any(strcmp(get(patch_h,'Tag'),{'planeBar','planePie'}))
70
+    tmp_dim=size(get(patch_h,'XData'),2)/prod(msize);
71
+    tmp_xdata=get(patch_h,'XData');
72
+    tmp_x=tmp_xdata(:,(msize(1)*(msize(2)-1)+2)*tmp_dim);
73
+    if floor(tmp_x(1)) ~= round(tmp_x(1))
74
+      lattice = 'hexa';
75
+    else
76
+      lattice = 'rect';
77
+    end
78
+  elseif strcmp(get(patch_h,'Tag'),'planePlot')
79
+    tmp_lines_h=get(gca,'Children');
80
+    test_x=mean(get(tmp_lines_h(2),'XData'));
81
+    if round(test_x) ~= floor(test_x)
82
+      lattice = 'hexa';
83
+    else
84
+      lattice = 'rect';
85
+    end
86
+    form=0.5*vis_patch('hexa');
87
+    l = size(form,1);
88
+    
89
+    nx = repmat(form(:,1),1,prod(msize));
90
+    ny = repmat(form(:,2),1,prod(msize));
91
+    
92
+    x=reshape(repmat(1:msize(2),l*msize(1),1),l,prod(msize));
93
+    y=repmat(repmat(1:msize(1),l,1),1,msize(2));
94
+    
95
+    if strcmp(lattice,'hexa')
96
+      t = find(~rem(y(1,:),2));
97
+      x(:,t)=x(:,t)+.5;
98
+    end
99
+    x=x+nx;
100
+    y=y+ny;
101
+    
102
+    colors=reshape(ones(prod(msize),1)*[NaN NaN NaN],...
103
+		   [1 prod(msize) 3]);
104
+    v=caxis;
105
+    patch_h=patch(x,y,colors,...
106
+		  'EdgeColor','none',...
107
+		  'ButtonDownFcn',...
108
+		  'som_select([],[],''click'')',...
109
+		  'Tag','planePlot');
110
+    set([gca gcf],'ButtonDownFcn','som_select([],[],''click'')');
111
+    caxis(v)
112
+  end
113
+
114
+  c_colors = []; 
115
+  if iscell(c_vect)
116
+    [c_vect,c_names,c_classes]=class2num(c_vect);
117
+    if length(c_classes)<prod(msize), 
118
+      c_classes = zeros(prod(msize),1);
119
+    end
120
+  else
121
+    if all(size(c_vect)>1), 
122
+      c_colors = c_vect; 
123
+      c_names = 1:size(c_vect,1); 
124
+      c_vect = size(c_vect,1); 
125
+      c_classes = zeros(prod(msize),1);
126
+    elseif length(c_vect)==prod(msize),
127
+      c_classes = c_vect;
128
+      u = unique(c_classes(isfinite(c_classes) & c_classes>0));
129
+      c_names = u;
130
+      c_vect = length(u);       
131
+    elseif length(c_vect)>1, 
132
+      c_names = c_vect; 
133
+      c_vect = length(c_vect);
134
+      c_classes = zeros(prod(msize),1);
135
+    elseif length(c_vect)==1,
136
+      c_names = 1:c_vect;        
137
+      c_classes = zeros(prod(msize),1);
138
+    end
139
+  end
140
+  
141
+  udata.lattice=lattice;
142
+  udata.patch_h=patch_h;
143
+  udata.plane_h=plane_h;
144
+  udata.type=get(udata.patch_h,'Tag');
145
+  udata.msize=msize;
146
+  set(patch_h,'UserData',udata);
147
+  if strcmp(udata.type,'planePlot')
148
+    set([gca gcf],'UserData',udata);
149
+  end
150
+  str=cat(2,'som_select([],[],''click'')');
151
+  set(patch_h,'ButtonDownFcn',str);
152
+
153
+  draw_colorselection(c_names,c_colors);
154
+  tmp_data=findobj(get(0,'Children'),'Tag','SELECT_GUI');
155
+  tmp_data=get(tmp_data,'UserData');
156
+  tmp_data.c_names=c_names;
157
+  tmp_data.mat=reshape(c_classes,msize);
158
+  tmp_data.patch_h=patch_h;
159
+  tmp_data.plane_h=plane_h;
160
+  tmp_data.type=get(udata.patch_h,'Tag');
161
+  tmp_data.lattice=lattice;
162
+  tmp_data.coords=[];
163
+  tmp_data.poly_h=[];
164
+  tmp_data.msize=msize;
165
+  tmp_data.mode='select';  
166
+  set(tmp_data.fig_h,'UserData',tmp_data);   
167
+  draw_classes;
168
+  
169
+ case 'click'
170
+  switch get(gcf,'SelectionType')
171
+   case 'open'
172
+    return;
173
+   case {'normal','alt'}
174
+    draw_poly;
175
+   case 'extend'
176
+    click;
177
+  end 
178
+ case 'choose'
179
+  draw_colorselection(0,0,'choose');
180
+ case 'close'
181
+  close_gui;
182
+ case 'clear'
183
+  clear_plane;
184
+ case 'rb'
185
+  rb_control;
186
+ case 'ret_mat'
187
+  gui=findobj(get(0,'Children'),'Tag','SELECT_GUI');
188
+  gui=get(gui,'UserData');
189
+  mat=reshape(gui.mat,prod(size(gui.mat)),1);
190
+  if ~isempty(gui.c_names)
191
+    if isnumeric(gui.c_names), tmp=zeros(length(mat),1);
192
+    else tmp=cell(length(mat),1);
193
+    end
194
+    for i=1:length(gui.c_names)
195
+      inds=find(mat==i);
196
+      tmp(inds)=gui.c_names(i);
197
+    end       
198
+    mat=tmp;
199
+  end  
200
+  varargout{1}=mat;
201
+  %gui.mat=zeros(size(gui.mat));
202
+  %set(gui.fig_h,'UserData',gui);
203
+  %h=findobj(get(gui.plane_h,'Children'),'Tag','SEL_PATCH');
204
+  %delete(h);
205
+end  
206
+
207
+return;
208
+
209
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
210
+%% subfunctions
211
+
212
+function rb_control;
213
+
214
+h=findobj(get(gcf,'Children'),'Style','radiobutton');
215
+set(h,'Value',0);
216
+set(gcbo,'Value',1);
217
+
218
+udata=get(gcf,'UserData');
219
+if strcmp(get(gcbo,'Tag'),'Radiobutton1')
220
+  udata.mode='select';
221
+else
222
+  udata.mode='clear';
223
+end
224
+
225
+set(gcf,'UserData',udata);
226
+
227
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
228
+
229
+function clear_plane
230
+
231
+h=findobj(get(0,'Children'),'Tag','SELECT_GUI');
232
+gui=get(h,'UserData');
233
+
234
+if strcmp(get(gui.patch_h,'Tag'),'planePlot')
235
+  colors=reshape(get(gui.patch_h,'FaceVertexCData'),[prod(gui.msize) 3]);
236
+  colors(:,:)=NaN;
237
+  set(gui.patch_h,'FaceVertexCData',colors);
238
+end
239
+
240
+h=findobj(get(gui.plane_h,'Children'),'Tag','SEL_PATCH');
241
+gui.mat=zeros(gui.msize);
242
+set(gui.fig_h,'UserData',gui);
243
+delete(h);
244
+
245
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
246
+
247
+function click
248
+
249
+udata=get(gcbo,'UserData');
250
+
251
+udata=get(udata.patch_h,'UserData');  
252
+coords=get(gca,'CurrentPoint');
253
+row=round(coords(1,2));
254
+if row > udata.msize(1), row = udata.msize(1); end
255
+if row < 1, row = 1; end
256
+if any(strcmp(udata.lattice,{'hexa','hexaU'})) & ~mod(row,2), 
257
+  col=floor(coords(1,1))+0.5;
258
+  if col > udata.msize(2)+0.5, col=udata.msize(2)+0.5; end
259
+else
260
+  col=round(coords(1,1));
261
+  if col > udata.msize(2), col=udata.msize(2); end
262
+end
263
+if col < 1, col = 1; end
264
+
265
+if strcmp(udata.type,'planePlot')
266
+
267
+  if ~mod(row,2) & strcmp(udata.lattice,'hexa'), col=round(col-0.5); end
268
+  
269
+  ind=sub2ind(udata.msize,row,col);
270
+  colors=reshape(get(udata.patch_h,'FaceVertexCData'),[prod(udata.msize) 3]);
271
+  gui=findobj(get(0,'Children'),'Tag','SELECT_GUI');
272
+  gui=get(gui,'UserData');
273
+  
274
+  if ~isempty(gui.curr_col) & all(~isnan(colors(ind,1,:))),
275
+    if ~strcmp(gui.mode,'clear') & ~all(gui.curr_col == colors(ind,:))
276
+      colors(ind,:)=gui.curr_col;
277
+      gui.mat(row,col)=gui.class;
278
+    else
279
+      colors(ind,:)=[NaN NaN NaN];
280
+      gui.mat(row,col)=0;
281
+    end
282
+  elseif strcmp(gui.mode,'clear')
283
+    colors(ind,:)=[NaN NaN NaN];
284
+    gui.mat(row,col)=0;
285
+  elseif isempty(gui.curr_col)
286
+    return;
287
+  else
288
+    gui.mat(row,col)=gui.class;
289
+    colors(ind,:)=gui.curr_col;
290
+  end
291
+  set(udata.patch_h,'FaceVertexCData',colors);
292
+  set(gui.fig_h,'UserData',gui);
293
+  return;
294
+end  
295
+
296
+if any(strcmp(udata.type,{'planePie','planeBar'}))
297
+  [x,y]=pol2cart(0:0.1:2*pi,0.5);
298
+  coords=[x';0.5]*0.7;
299
+  coords(:,2)=[y';0]*0.7;
300
+elseif strcmp(udata.lattice,'hexa');
301
+  coords=0.7*vis_patch('hexa');
302
+else
303
+  coords=0.7*vis_patch('rect');
304
+end
305
+coords(:,1)=coords(:,1)+col;
306
+coords(:,2)=coords(:,2)+row;
307
+if ~mod(row,2) & strcmp(udata.lattice,'hexa'), col=round(col-0.5); end
308
+ 
309
+hold on;
310
+if gco == udata.patch_h
311
+  gui=findobj(get(0,'Children'),'Tag','SELECT_GUI');
312
+  gui=get(gui,'UserData');
313
+  if isnan(gui.curr_col) | strcmp(gui.mode,'clear'), return; end
314
+  h=fill(coords(:,1),coords(:,2),gui.curr_col);
315
+  str=cat(2,'som_select([],[],''click'')');
316
+  set(h,'ButtonDownFcn',str,'Tag','SEL_PATCH');
317
+  tmp.patch_h=udata.patch_h;
318
+  set(h,'UserData',tmp);
319
+  gui.mat(row,col)=gui.class;
320
+  set(gui.fig_h,'UserData',gui);
321
+else
322
+  gui=findobj(get(0,'Children'),'Tag','SELECT_GUI');
323
+  gui=get(gui,'UserData');
324
+  if ~all(get(gcbo,'FaceColor') == gui.curr_col) & ~strcmp(gui.mode,'clear'),
325
+    if ~isnan(gui.curr_col), 
326
+      set(gcbo,'FaceColor',gui.curr_col);
327
+      gui.mat(row,col) = gui.class;
328
+    end
329
+  else
330
+    gui.mat(row,col)=0;
331
+    delete(gco);
332
+  end
333
+  set(gui.fig_h,'UserData',gui);
334
+end
335
+
336
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
337
+
338
+function draw_colorselection(varargin)
339
+
340
+if length(varargin)==2, 
341
+
342
+  if length(varargin{1})==1, 
343
+    n = varargin{1};
344
+    names = 1:n;
345
+  else
346
+    n = length(varargin{1}); 
347
+    names = varargin{1}; 
348
+  end
349
+  colors = varargin{2}; 
350
+  
351
+  shape=[0.5 -0.5;0.5 0.5;1.5 0.5;1.5 -0.5];
352
+  rep_x=repmat(shape(:,1),1,n);
353
+  rep_y=repmat(shape(:,2),1,n);
354
+  for i=0:getfield(size(rep_y,2))-1, rep_x(:,i+1)=rep_x(:,i+1)+i; end
355
+  if isempty(colors), colors=jet(n); end
356
+  data=som_select_gui;
357
+  data.colors=colors;
358
+  data.curr_col=NaN;
359
+  data.class=0;
360
+  set(0,'CurrentFigure',data.fig_h);
361
+  hold on;
362
+  tmp=fill(rep_x,rep_y,0.8);
363
+  for i=1:n
364
+    set(tmp(i),...
365
+        'EdgeColor',[0 0 0],...
366
+        'FaceColor',colors(i,:),...
367
+        'ButtonDownFcn','som_select([],0,''choose'');');
368
+  end
369
+  axis('equal');
370
+  axis('on');
371
+  set(gca,'XTick',1:n,'XTickLabel',names,'XAxisLocation','top');
372
+  set(data.a_h,'YLim',[-0.5,0.5],...
373
+	       'XLim',[0.5 n+0.5],...
374
+	       'YTickLabel','');
375
+  set(data.fig_h,'UserData',data);
376
+
377
+elseif strcmp(varargin{3},'choose')
378
+  
379
+  udata=get(gcf,'UserData');
380
+  if strcmp(get(gcbo,'Selected'),'off')
381
+    old=findobj(get(gca,'Children'),'Type','patch');
382
+    set(old,'Selected','off');
383
+    set(gcbo,'Selected','on');
384
+    udata.curr_col=udata.colors(round(mean(get(gcbo,'XData'))),:);
385
+    udata.class=mean(get(gcbo,'XData'));
386
+  else
387
+    set(gcbo,'Selected','off');
388
+    udata.curr_col=NaN;
389
+    udata.class=0;
390
+  end
391
+  set(gcf,'UserData',udata);
392
+
393
+end
394
+
395
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
396
+
397
+function data=som_select_gui()
398
+
399
+
400
+a = figure('Color',[0.8 0.8 0.8], ...
401
+	'PaperType','a4letter', ...
402
+	'Position',[586 584 560 210], ...
403
+	'Tag','SELECT_GUI');
404
+
405
+data.fig_h=a;
406
+
407
+b = axes('Parent',a, ...
408
+	'Box','on', ...
409
+	'CameraUpVector',[0 1 0], ...
410
+	'Color',[1 1 1], ...
411
+	'DataAspectRatioMode','manual', ...
412
+	'PlotBoxAspectRatio',[20 1 2], ...
413
+	'PlotBoxAspectRatioMode','manual', ...
414
+	'Position',[0.13 0.11 0.775 0.815], ...
415
+	'Tag','Axes1', ...
416
+	'WarpToFill','off', ...
417
+	'XColor',[0 0 0], ...
418
+	'XLimMode','manual', ...
419
+	'YColor',[0 0 0], ...
420
+	'YLimMode','manual', ...
421
+	'YTickLabelMode','manual', ...
422
+	'ZColor',[0 0 0]);
423
+
424
+data.a_h=b;
425
+
426
+b = uicontrol('Parent',a, ...
427
+	'Units','points', ...
428
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
429
+	'Callback','som_select([],[],''close'')', ...
430
+	'FontWeight','demi', ...
431
+	'Position',[150 12 50 20], ...
432
+	'String','CLOSE', ...
433
+	'Tag','Pushbutton1');
434
+
435
+b = uicontrol('Parent',a, ...
436
+	'Units','points', ...
437
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
438
+        'Callback','som_select([],0,''ret_mat'')',...
439
+	'FontWeight','demi', ...
440
+	'Position',[365 12 50 20], ...
441
+	'String','OK', ...
442
+	'Tag','Pushbutton2');
443
+
444
+b = uicontrol('Parent',a, ...
445
+	'Units','points', ...
446
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
447
+        'Callback','som_select([],0,''clear'')',...
448
+	'FontWeight','demi', ...
449
+	'Position',[257.5 12 50 20], ...
450
+	'String','CLEAR', ...
451
+	'Tag','Pushbutton3');
452
+
453
+b = uicontrol('Parent',a, ...
454
+        'Units','points', ...
455
+        'Position',[50 27 17 16], ...
456
+        'Callback','som_select([],[],''rb'')',...
457
+        'Style','radiobutton', ...
458
+        'Tag','Radiobutton1', ...
459
+        'Value',1);
460
+b = uicontrol('Parent',a, ...
461
+        'Units','points', ...
462
+        'BackgroundColor',[0.701961 0.701961 0.701961], ...
463
+        'Callback','som_select([],[],''rb'')',...
464
+        'Position',[50 7 17 16], ...
465
+        'Style','radiobutton', ...
466
+        'Tag','Radiobutton2');
467
+b = uicontrol('Parent',a, ...
468
+        'Units','points', ...
469
+        'BackgroundColor',[0.8 0.8 0.8], ...
470
+        'FontSize',9, ...
471
+        'FontWeight','demi', ...
472
+        'HorizontalAlignment','left', ...
473
+        'Position',[72 25 28 15], ...
474
+        'String','Select', ...
475
+        'Style','text', ...
476
+        'Tag','StaticText1');
477
+b = uicontrol('Parent',a, ...
478
+        'Units','points', ...
479
+        'BackgroundColor',[0.8 0.8 0.8], ...
480
+        'FontSize',9, ...
481
+        'FontWeight','demi', ...
482
+        'HorizontalAlignment','left', ...
483
+        'Position',[72 7 25 13.6], ...
484
+        'String','Clear', ...
485
+        'Style','text', ...
486
+        'Tag','StaticText2');
487
+
488
+
489
+
490
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
491
+
492
+function close_gui
493
+
494
+udata=get(get(gcbo,'Parent'),'UserData');
495
+
496
+if strcmp(udata.type,'planePlot');
497
+  set(udata.plane_h,'ButtonDownFcn','','UserData',[]);
498
+  set(get(udata.plane_h,'Parent'),'ButtonDownFcn','');
499
+  delete(udata.patch_h);
500
+  return;
501
+end  
502
+
503
+h=findobj(get(udata.plane_h,'Children'),'Tag','SEL_PATCH');
504
+set(udata.patch_h,'ButtonDownFcn','','UserData',[]);
505
+delete(h);
506
+close(udata.fig_h);
507
+
508
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
509
+
510
+function draw_poly
511
+
512
+udata=get(findobj(get(0,'Children'),'Tag','SELECT_GUI'),'UserData');
513
+
514
+if isempty(udata.coords) & strcmp(get(gcf,'SelectionType'),'alt')
515
+  return;
516
+end
517
+
518
+coords(1,1) = getfield(get(gca,'CurrentPoint'),{3});
519
+coords(1,2) = getfield(get(gca,'CurrentPoint'),{1});
520
+udata.coords = cat(1,udata.coords,coords);
521
+delete(udata.poly_h);
522
+subplot(udata.plane_h);
523
+
524
+hold on;
525
+switch get(gcf,'SelectionType');
526
+ case 'normal'
527
+  udata.poly_h=plot(udata.coords(:,2),udata.coords(:,1),'black',...
528
+		    'ButtonDownFcn','som_select([],[],''click'')',...
529
+		    'LineWidth',2);
530
+  set(udata.fig_h,'UserData',udata);
531
+ case 'alt'
532
+  udata.coords=cat(1,udata.coords,udata.coords(1,:));
533
+  udata.poly_h=plot(udata.coords(:,2),udata.coords(:,1),'black',...
534
+		    'LineWidth',2);
535
+  delete(udata.poly_h);
536
+  if ~isnan(udata.curr_col)
537
+    tmp=sort(repmat((1:udata.msize(1))',udata.msize(2),1));
538
+    tmp(:,2)=repmat((1:udata.msize(2))',udata.msize(1),1);
539
+    tmp2=tmp;
540
+    if strcmp(udata.type,'planePlot')
541
+      in=find(inpolygon(tmp(:,2),tmp(:,1),...
542
+			udata.coords(:,2),udata.coords(:,1)));
543
+      row=tmp2(in,1);
544
+      col=tmp2(in,2);
545
+      in=sub2ind(udata.msize,row,col);
546
+      colors=reshape(get(udata.patch_h,'FaceVertexCData'),...
547
+		     [prod(udata.msize) 3]);
548
+      if ~isnan(udata.curr_col) & ~strcmp(udata.mode,'clear')
549
+        colors(in,:)=ones(length(in),1)*udata.curr_col;
550
+        udata.mat(row,col)=udata.class;
551
+      elseif strcmp(udata.mode,'clear')
552
+        colors(in,:)=[NaN NaN NaN];
553
+        udata.mat(row,col)=0;
554
+      end
555
+      udata.poly_h=[];
556
+      udata.coords=[];
557
+      set(udata.patch_h,'FaceVertexCData',colors);
558
+      set(udata.fig_h,'UserData',udata);
559
+      return;
560
+    end
561
+    if strcmp(udata.lattice,'hexa');
562
+      t=find(~rem(tmp(:,1),2));
563
+      tmp(t,2)=tmp(t,2)+0.5;
564
+      if any(strcmp(get(udata.patch_h,'Tag'),{'planeC','planeU'}))
565
+        p=0.7*vis_patch('hexa');
566
+      else
567
+        [x,y]=pol2cart(0:0.1:2*pi,0.5);
568
+        p=[x';0.5]*0.7;
569
+        p(:,2)=[y';0]*0.7;
570
+      end
571
+    else
572
+      if any(strcmp(get(udata.patch_h,'Tag'),{'planeC','planeU'}))
573
+        p=0.7*vis_patch('rect');
574
+      else
575
+        [x,y]=pol2cart(0:0.1:2*pi,0.5);
576
+        p=[x';0.5]*0.7;
577
+        p(:,2)=[y';0]*0.7;
578
+      end 
579
+    end
580
+    in=find(inpolygon(tmp(:,2),tmp(:,1),udata.coords(:,2),udata.coords(:,1)));
581
+    set(udata.fig_h,'UserData',udata);
582
+    if strcmp(udata.mode,'select')
583
+      remove_selpatches;
584
+      udata=get(udata.fig_h,'UserData');
585
+      for i=1:length(in)
586
+	udat.patch_h=udata.patch_h;
587
+	h=patch(p(:,1)+tmp(in(i),2),p(:,2)+tmp(in(i),1),...
588
+		udata.curr_col,...
589
+		'EdgeColor','black',...
590
+		'ButtonDownFcn','som_select([],[],''click'')', ...
591
+		'Tag','SEL_PATCH',...
592
+		'UserData',udat);
593
+	udata.mat(tmp2(in(i),1),tmp2(in(i),2))=udata.class;
594
+      end
595
+    else
596
+      remove_selpatches;
597
+      udata=get(udata.fig_h,'UserData');
598
+      %h=findobj(get(udata.plane_h,'Children'),'Tag','SEL_PATCH');
599
+      %for i=1:length(h)
600
+      %    if all(get(h(i),'FaceColor')==udata.curr_col) & ...
601
+      %       inpolygon(mean(get(h(i),'XData')),mean(get(h(i),'YData')),...
602
+      %       udata.coords(:,2),udata.coords(:,1))
603
+      %       coords=[floor(mean(get(h(i),'YData')))...
604
+      %               floor(mean(get(h(i),'XData')))];
605
+      %       udata.mat(coords(1),coords(2))=0;
606
+      %      delete(h(i));
607
+      %    end
608
+      %end
609
+    end
610
+  end
611
+  udata.poly_h=[];
612
+  udata.coords=[];
613
+  set(udata.fig_h,'UserData',udata);
614
+end
615
+
616
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
617
+
618
+function remove_selpatches
619
+
620
+udata=get(findobj(get(0,'Children'),'Tag','SELECT_GUI'),'UserData');
621
+h=findobj(get(udata.plane_h,'Children'),'Tag','SEL_PATCH');
622
+for i=1:length(h)
623
+  if inpolygon(mean(get(h(i),'XData')),mean(get(h(i),'YData')),...
624
+               udata.coords(:,2),udata.coords(:,1));
625
+    coords=[floor(mean(get(h(i),'YData')))...           
626
+            floor(mean(get(h(i),'XData')))];
627
+    udata.mat(coords(1),coords(2))=0;
628
+    delete(h(i));
629
+  end
630
+end
631
+
632
+set(udata.fig_h,'UserData',udata);
633
+
634
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
635
+
636
+function [n,names,classes]=class2num(class)
637
+
638
+names = {};
639
+classes = zeros(length(class),1);
640
+for i=1:length(class)
641
+  if ~isempty(class{i}), 
642
+    a = find(strcmp(class{i},names));
643
+    if isempty(a), 
644
+      names=cat(1,names,class(i));
645
+      classes(i) = length(names);
646
+    else
647
+      classes(i) = a;
648
+    end
649
+  end
650
+end
651
+n=length(names);
652
+
653
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
654
+
655
+function h=find_patch(a_h)
656
+
657
+h=[];
658
+
659
+tags={'planeC','planeU','planePie','planeBar','planePlot'};
660
+
661
+for i=1:5
662
+  if ~isempty(findobj(get(a_h,'Children'),'Tag',tags{i}))
663
+    h=findobj(get(gca,'Children'),'Tag',tags{i});
664
+    if length(h) > 1
665
+      h=h(1);
666
+    end
667
+    return;
668
+  end
669
+end
670
+  
671
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
672
+
673
+function draw_classes
674
+
675
+udata=get(findobj(get(0,'Children'),'Tag','SELECT_GUI'), ...
676
+	  'UserData');
677
+figure(get(udata.plane_h,'Parent'))
678
+subplot(udata.plane_h);
679
+
680
+colors=zeros(prod(udata.msize),3)+NaN;
681
+c_map=jet(length(udata.c_names));
682
+inds = find(udata.mat);
683
+for i=1:length(inds), 
684
+  colors(inds(i),:) = c_map(udata.mat(inds(i)),:);
685
+end
686
+
687
+if strcmp(udata.type,'planePlot'),
688
+
689
+  set(udata.patch_h,'FaceVertexCData',colors);
690
+  set(udata.fig_h,'UserData',udata);
691
+
692
+else
693
+
694
+  hold on
695
+  co = som_vis_coords(udata.lattice,udata.msize);
696
+  if any(strcmp(get(udata.patch_h,'Tag'),{'planeC','planeU'}))
697
+    p=0.7*vis_patch(udata.lattice);
698
+  else
699
+    [x,y]=pol2cart(0:0.1:2*pi,0.5);
700
+    p=[x';0.5]*0.7;
701
+    p(:,2)=[y';0]*0.7;
702
+  end
703
+  for i=1:length(inds),
704
+    udat.patch_h=udata.patch_h;
705
+    h=patch(p(:,1)+co(inds(i),1),p(:,2)+co(inds(i),2),...
706
+	    colors(inds(i),:),...
707
+	    'EdgeColor','black',...
708
+	    'ButtonDownFcn','som_select([],[],''click'')', ...
709
+	    'Tag','SEL_PATCH',...
710
+	    'UserData',udat);
711
+  end 
712
+  
713
+end
714
+
715
+
716
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,557 @@
1
+function [sMap, sTrain] = som_seqtrain(sMap, D, varargin)
2
+
3
+%SOM_SEQTRAIN  Use sequential algorithm to train the Self-Organizing Map.
4
+%
5
+% [sM,sT] = som_seqtrain(sM, D, [[argID,] value, ...])
6
+% 
7
+%  sM     = som_seqtrain(sM,D);
8
+%  sM     = som_seqtrain(sM,sD,'alpha_type','power','tracking',3);
9
+%  [M,sT] = som_seqtrain(M,D,'ep','trainlen',10,'inv','hexa');
10
+%
11
+%  Input and output arguments ([]'s are optional): 
12
+%   sM      (struct) map struct, the trained and updated map is returned
13
+%           (matrix) codebook matrix of a self-organizing map
14
+%                    size munits x dim or  msize(1) x ... x msize(k) x dim
15
+%                    The trained map codebook is returned.
16
+%   D       (struct) training data; data struct
17
+%           (matrix) training data, size dlen x dim
18
+%   [argID, (string) See below. The values which are unambiguous can 
19
+%    value] (varies) be given without the preceeding argID.
20
+%
21
+%   sT      (struct) learning parameters used during the training
22
+%
23
+% Here are the valid argument IDs and corresponding values. The values which
24
+% are unambiguous (marked with '*') can be given without the preceeding argID.
25
+%   'mask'        (vector) BMU search mask, size dim x 1
26
+%   'msize'       (vector) map size
27
+%   'radius'      (vector) neighborhood radiuses, length 1, 2 or trainlen
28
+%   'radius_ini'  (scalar) initial training radius
29
+%   'radius_fin'  (scalar) final training radius
30
+%   'alpha'       (vector) learning rates, length trainlen
31
+%   'alpha_ini'   (scalar) initial learning rate
32
+%   'tracking'    (scalar) tracking level, 0-3 
33
+%   'trainlen'    (scalar) training length
34
+%   'trainlen_type' *(string) is the given trainlen 'samples' or 'epochs'
35
+%   'train'      *(struct) train struct, parameters for training
36
+%   'sTrain','som_train '  = 'train'
37
+%   'alpha_type' *(string) learning rate function, 'inv', 'linear' or 'power'
38
+%   'sample_order'*(string) order of samples: 'random' or 'ordered'
39
+%   'neigh'      *(string) neighborhood function, 'gaussian', 'cutgauss',
40
+%                          'ep' or 'bubble'
41
+%   'topol'      *(struct) topology struct
42
+%   'som_topol','sTopo l'  = 'topol'
43
+%   'lattice'    *(string) map lattice, 'hexa' or 'rect'
44
+%   'shape'      *(string) map shape, 'sheet', 'cyl' or 'toroid'
45
+%
46
+% For more help, try 'type som_seqtrain' or check out online documentation.
47
+% See also  SOM_MAKE, SOM_BATCHTRAIN, SOM_TRAIN_STRUCT.
48
+
49
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
50
+%
51
+% som_seqtrain
52
+%
53
+% PURPOSE
54
+%
55
+% Trains a Self-Organizing Map using the sequential algorithm. 
56
+%
57
+% SYNTAX
58
+%
59
+%  sM = som_seqtrain(sM,D);
60
+%  sM = som_seqtrain(sM,sD);
61
+%  sM = som_seqtrain(...,'argID',value,...);
62
+%  sM = som_seqtrain(...,value,...);
63
+%  [sM,sT] = som_seqtrain(M,D,...);
64
+%
65
+% DESCRIPTION
66
+%
67
+% Trains the given SOM (sM or M above) with the given training data
68
+% (sD or D) using sequential SOM training algorithm. If no optional
69
+% arguments (argID, value) are given, a default training is done, the
70
+% parameters are obtained from SOM_TRAIN_STRUCT function. Using
71
+% optional arguments the training parameters can be specified. Returns
72
+% the trained and updated SOM and a train struct which contains
73
+% information on the training.
74
+%
75
+% REFERENCES
76
+%
77
+% Kohonen, T., "Self-Organizing Map", 2nd ed., Springer-Verlag, 
78
+%    Berlin, 1995, pp. 78-82.
79
+% Kohonen, T., "Clustering, Taxonomy, and Topological Maps of
80
+%    Patterns", International Conference on Pattern Recognition
81
+%    (ICPR), 1982, pp. 114-128.
82
+% Kohonen, T., "Self-Organized formation of topologically correct
83
+%    feature maps", Biological Cybernetics 43, 1982, pp. 59-69.
84
+%
85
+% REQUIRED INPUT ARGUMENTS
86
+%
87
+%  sM          The map to be trained. 
88
+%     (struct) map struct
89
+%     (matrix) codebook matrix (field .data of map struct)
90
+%              Size is either [munits dim], in which case the map grid 
91
+%              dimensions (msize) should be specified with optional arguments,
92
+%              or [msize(1) ... msize(k) dim] in which case the map 
93
+%              grid dimensions are taken from the size of the matrix. 
94
+%              Lattice, by default, is 'rect' and shape 'sheet'.
95
+%  D           Training data.
96
+%     (struct) data struct
97
+%     (matrix) data matrix, size [dlen dim]
98
+%  
99
+% OPTIONAL INPUT ARGUMENTS 
100
+%
101
+%  argID (string) Argument identifier string (see below).
102
+%  value (varies) Value for the argument (see below).
103
+%
104
+%  The optional arguments can be given as 'argID',value -pairs. If an
105
+%  argument is given value multiple times, the last one is
106
+%  used. The valid IDs and corresponding values are listed below. The values 
107
+%  which are unambiguous (marked with '*') can be given without the 
108
+%  preceeding argID.
109
+%
110
+%   'mask'       (vector) BMU search mask, size dim x 1. Default is 
111
+%                         the one in sM (field '.mask') or a vector of
112
+%                         ones if only a codebook matrix was given.
113
+%   'msize'      (vector) map grid dimensions. Default is the one
114
+%                         in sM (field sM.topol.msize) or 
115
+%                         'si = size(sM); msize = si(1:end-1);' 
116
+%                         if only a codebook matrix was given. 
117
+%   'radius'     (vector) neighborhood radius 
118
+%                         length = 1: radius_ini = radius
119
+%                         length = 2: [radius_ini radius_fin] = radius
120
+%                         length > 2: the vector given neighborhood
121
+%                                     radius for each step separately
122
+%                                     trainlen = length(radius)
123
+%   'radius_ini' (scalar) initial training radius
124
+%   'radius_fin' (scalar) final training radius
125
+%   'alpha'      (vector) learning rate
126
+%                         length = 1: alpha_ini = alpha
127
+%                         length > 1: the vector gives learning rate
128
+%                                     for each step separately
129
+%                                     trainlen is set to length(alpha)
130
+%                                     alpha_type is set to 'user defined'
131
+%   'alpha_ini'  (scalar) initial learning rate
132
+%   'tracking'   (scalar) tracking level: 0, 1 (default), 2 or 3
133
+%                         0 - estimate time 
134
+%                         1 - track time and quantization error 
135
+%                         2 - plot quantization error
136
+%                         3 - plot quantization error and two first 
137
+%                             components 
138
+%   'trainlen'   (scalar) training length (see also 'tlen_type')
139
+%   'trainlen_type' *(string) is the trainlen argument given in 'epochs'
140
+%                         or in 'samples'. Default is 'epochs'.
141
+%   'sample_order'*(string) is the sample order 'random' (which is the 
142
+%                         the default) or 'ordered' in which case
143
+%                         samples are taken in the order in which they 
144
+%                         appear in the data set
145
+%   'train'     *(struct) train struct, parameters for training. 
146
+%                         Default parameters, unless specified, 
147
+%                         are acquired using SOM_TRAIN_STRUCT (this 
148
+%                         also applies for 'trainlen', 'alpha_type',
149
+%                         'alpha_ini', 'radius_ini' and 'radius_fin').
150
+%   'sTrain', 'som_train' (struct) = 'train'
151
+%   'neigh'     *(string) The used neighborhood function. Default is 
152
+%                         the one in sM (field '.neigh') or 'gaussian'
153
+%                         if only a codebook matrix was given. Other 
154
+%                         possible values is 'cutgauss', 'ep' and 'bubble'.
155
+%   'topol'     *(struct) topology of the map. Default is the one
156
+%                         in sM (field '.topol').
157
+%   'sTopol', 'som_topol' (struct) = 'topol'
158
+%   'alpha_type'*(string) learning rate function, 'inv', 'linear' or 'power'
159
+%   'lattice'   *(string) map lattice. Default is the one in sM
160
+%                         (field sM.topol.lattice) or 'rect' 
161
+%                         if only a codebook matrix was given. 
162
+%   'shape'     *(string) map shape. Default is the one in sM
163
+%                         (field sM.topol.shape) or 'sheet' 
164
+%                         if only a codebook matrix was given. 
165
+%   
166
+% OUTPUT ARGUMENTS
167
+% 
168
+%  sM          the trained map
169
+%     (struct) if a map struct was given as input argument, a 
170
+%              map struct is also returned. The current training 
171
+%              is added to the training history (sM.trainhist).
172
+%              The 'neigh' and 'mask' fields of the map struct
173
+%              are updated to match those of the training.
174
+%     (matrix) if a matrix was given as input argument, a matrix
175
+%              is also returned with the same size as the input 
176
+%              argument.
177
+%  sT (struct) train struct; information of the accomplished training
178
+%  
179
+% EXAMPLES
180
+%
181
+% Simplest case:
182
+%  sM = som_seqtrain(sM,D);  
183
+%  sM = som_seqtrain(sM,sD);  
184
+%
185
+% To change the tracking level, 'tracking' argument is specified:
186
+%  sM = som_seqtrain(sM,D,'tracking',3);
187
+%
188
+% The change training parameters, the optional arguments 'train', 
189
+% 'neigh','mask','trainlen','radius','radius_ini', 'radius_fin', 
190
+% 'alpha', 'alpha_type' and 'alpha_ini' are used. 
191
+%  sM = som_seqtrain(sM,D,'neigh','cutgauss','trainlen',10,'radius_fin',0);
192
+%
193
+% Another way to specify training parameters is to create a train struct:
194
+%  sTrain = som_train_struct(sM,'dlen',size(D,1),'algorithm','seq');
195
+%  sTrain = som_set(sTrain,'neigh','cutgauss');
196
+%  sM = som_seqtrain(sM,D,sTrain);
197
+%
198
+% By default the neighborhood radius goes linearly from radius_ini to
199
+% radius_fin. If you want to change this, you can use the 'radius' argument
200
+% to specify the neighborhood radius for each step separately:
201
+%  sM = som_seqtrain(sM,D,'radius',[5 3 1 1 1 1 0.5 0.5 0.5]);
202
+%
203
+% By default the learning rate (alpha) goes from the alpha_ini to 0
204
+% along the function defined by alpha_type. If you want to change this, 
205
+% you can use the 'alpha' argument to specify the learning rate
206
+% for each step separately: 
207
+%  alpha = 0.2*(1 - log([1:100]));
208
+%  sM = som_seqtrain(sM,D,'alpha',alpha);
209
+%
210
+% You don't necessarily have to use the map struct, but you can operate
211
+% directly with codebook matrices. However, in this case you have to
212
+% specify the topology of the map in the optional arguments. The
213
+% following commads are identical (M is originally a 200 x dim sized matrix):
214
+%  M = som_seqtrain(M,D,'msize',[20 10],'lattice','hexa','shape','cyl');
215
+%
216
+%  M = som_seqtrain(M,D,'msize',[20 10],'hexa','cyl');
217
+%
218
+%  sT= som_set('som_topol','msize',[20 10],'lattice','hexa','shape','cyl');
219
+%  M = som_seqtrain(M,D,sT);
220
+%
221
+%  M = reshape(M,[20 10 dim]);
222
+%  M = som_seqtrain(M,D,'hexa','cyl');
223
+%
224
+% The som_seqtrain also returns a train struct with information on the 
225
+% accomplished training. This is the same one as is added to the end of the 
226
+% trainhist field of map struct, in case a map struct is given.
227
+%  [M,sTrain] = som_seqtrain(M,D,'msize',[20 10]);
228
+%
229
+%  [sM,sTrain] = som_seqtrain(sM,D); % sM.trainhist{end}==sTrain
230
+%
231
+% SEE ALSO
232
+% 
233
+%  som_make         Initialize and train a SOM using default parameters.
234
+%  som_batchtrain   Train SOM with batch algorithm.
235
+%  som_train_struct Determine default training parameters.
236
+
237
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
238
+% http://www.cis.hut.fi/projects/somtoolbox/
239
+
240
+% Version 1.0beta juuso 220997
241
+% Version 2.0beta juuso 101199
242
+ 
243
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
244
+%% Check arguments
245
+
246
+error(nargchk(2, Inf, nargin));  % check the number of input arguments
247
+
248
+% map 
249
+struct_mode = isstruct(sMap);
250
+if struct_mode, 
251
+  sTopol = sMap.topol;
252
+else  
253
+  orig_size = size(sMap);
254
+  if ndims(sMap) > 2, 
255
+    si = size(sMap); dim = si(end); msize = si(1:end-1);
256
+    M = reshape(sMap,[prod(msize) dim]);
257
+  else
258
+    msize = [orig_size(1) 1]; 
259
+    dim = orig_size(2);
260
+  end
261
+  sMap   = som_map_struct(dim,'msize',msize);
262
+  sTopol = sMap.topol;
263
+end
264
+[munits dim] = size(sMap.codebook);
265
+
266
+% data
267
+if isstruct(D), 
268
+  data_name = D.name; 
269
+  D = D.data; 
270
+else 
271
+  data_name = inputname(2); 
272
+end
273
+D = D(find(sum(isnan(D),2) < dim),:); % remove empty vectors from the data
274
+[dlen ddim] = size(D);                % check input dimension
275
+if dim ~= ddim, error('Map and data input space dimensions disagree.'); end
276
+
277
+% varargin
278
+sTrain = som_set('som_train','algorithm','seq','neigh', ...
279
+		 sMap.neigh,'mask',sMap.mask,'data_name',data_name);
280
+radius     = [];
281
+alpha      = [];
282
+tracking   = 1;
283
+sample_order_type = 'random';
284
+tlen_type  = 'epochs';
285
+
286
+i=1; 
287
+while i<=length(varargin), 
288
+  argok = 1; 
289
+  if ischar(varargin{i}), 
290
+    switch varargin{i}, 
291
+     % argument IDs
292
+     case 'msize', i=i+1; sTopol.msize = varargin{i}; 
293
+     case 'lattice', i=i+1; sTopol.lattice = varargin{i};
294
+     case 'shape', i=i+1; sTopol.shape = varargin{i};
295
+     case 'mask', i=i+1; sTrain.mask = varargin{i};
296
+     case 'neigh', i=i+1; sTrain.neigh = varargin{i};
297
+     case 'trainlen', i=i+1; sTrain.trainlen = varargin{i};
298
+     case 'trainlen_type', i=i+1; tlen_type = varargin{i}; 
299
+     case 'tracking', i=i+1; tracking = varargin{i};
300
+     case 'sample_order', i=i+1; sample_order_type = varargin{i};
301
+     case 'radius_ini', i=i+1; sTrain.radius_ini = varargin{i};
302
+     case 'radius_fin', i=i+1; sTrain.radius_fin = varargin{i};
303
+     case 'radius', 
304
+      i=i+1; 
305
+      l = length(varargin{i}); 
306
+      if l==1, 
307
+        sTrain.radius_ini = varargin{i}; 
308
+      else 
309
+        sTrain.radius_ini = varargin{i}(1); 
310
+        sTrain.radius_fin = varargin{i}(end);
311
+        if l>2, radius = varargin{i}; tlen_type = 'samples'; end
312
+      end 
313
+     case 'alpha_type', i=i+1; sTrain.alpha_type = varargin{i};
314
+     case 'alpha_ini', i=i+1; sTrain.alpha_ini = varargin{i};
315
+     case 'alpha',     
316
+      i=i+1; 
317
+      sTrain.alpha_ini = varargin{i}(1);
318
+      if length(varargin{i})>1, 
319
+        alpha = varargin{i}; tlen_type = 'samples'; 
320
+        sTrain.alpha_type = 'user defined'; 
321
+      end
322
+     case {'sTrain','train','som_train'}, i=i+1; sTrain = varargin{i};
323
+     case {'topol','sTopol','som_topol'}, 
324
+      i=i+1; 
325
+      sTopol = varargin{i};
326
+      if prod(sTopol.msize) ~= munits, 
327
+        error('Given map grid size does not match the codebook size.');
328
+      end
329
+      % unambiguous values
330
+     case {'inv','linear','power'}, sTrain.alpha_type = varargin{i}; 
331
+     case {'hexa','rect'}, sTopol.lattice = varargin{i};
332
+     case {'sheet','cyl','toroid'}, sTopol.shape = varargin{i}; 
333
+     case {'gaussian','cutgauss','ep','bubble'}, sTrain.neigh = varargin{i};
334
+     case {'epochs','samples'}, tlen_type = varargin{i};
335
+     case {'random', 'ordered'}, sample_order_type = varargin{i}; 
336
+     otherwise argok=0; 
337
+    end
338
+  elseif isstruct(varargin{i}) & isfield(varargin{i},'type'), 
339
+    switch varargin{i}(1).type, 
340
+     case 'som_topol', 
341
+      sTopol = varargin{i}; 
342
+      if prod(sTopol.msize) ~= munits, 
343
+        error('Given map grid size does not match the codebook size.');
344
+      end
345
+     case 'som_train', sTrain = varargin{i};
346
+     otherwise argok=0; 
347
+    end
348
+  else
349
+    argok = 0; 
350
+  end
351
+  if ~argok, 
352
+    disp(['(som_seqtrain) Ignoring invalid argument #' num2str(i+2)]); 
353
+  end
354
+  i = i+1; 
355
+end
356
+
357
+% training length
358
+if ~isempty(radius) | ~isempty(alpha), 
359
+  lr = length(radius);
360
+  la = length(alpha);
361
+  if lr>2 | la>1,
362
+    tlen_type = 'samples';
363
+    if     lr> 2 & la<=1, sTrain.trainlen = lr;
364
+    elseif lr<=2 & la> 1, sTrain.trainlen = la;
365
+    elseif lr==la,        sTrain.trainlen = la;
366
+    else
367
+      error('Mismatch between radius and learning rate vector lengths.')
368
+    end
369
+  end
370
+end
371
+if strcmp(tlen_type,'samples'), sTrain.trainlen = sTrain.trainlen/dlen; end 
372
+
373
+% check topology
374
+if struct_mode, 
375
+  if ~strcmp(sTopol.lattice,sMap.topol.lattice) | ...
376
+	~strcmp(sTopol.shape,sMap.topol.shape) | ...
377
+	any(sTopol.msize ~= sMap.topol.msize), 
378
+    warning('Changing the original map topology.');
379
+  end
380
+end
381
+sMap.topol = sTopol; 
382
+
383
+% complement the training struct
384
+sTrain = som_train_struct(sTrain,sMap,'dlen',dlen);
385
+if isempty(sTrain.mask), sTrain.mask = ones(dim,1); end
386
+
387
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
388
+%% initialize
389
+
390
+M        = sMap.codebook;
391
+mask     = sTrain.mask;
392
+trainlen = sTrain.trainlen*dlen;
393
+
394
+% neighborhood radius
395
+if length(radius)>2,
396
+  radius_type = 'user defined';
397
+else
398
+  radius = [sTrain.radius_ini sTrain.radius_fin];    
399
+  rini = radius(1); 
400
+  rstep = (radius(end)-radius(1))/(trainlen-1);
401
+  radius_type = 'linear';
402
+end    
403
+
404
+% learning rate
405
+if length(alpha)>1, 
406
+  sTrain.alpha_type ='user defined';
407
+  if length(alpha) ~= trainlen, 
408
+    error('Trainlen and length of neighborhood radius vector do not match.')
409
+  end
410
+  if any(isnan(alpha)), 
411
+    error('NaN is an illegal learning rate.')
412
+  end
413
+else
414
+  if isempty(alpha), alpha = sTrain.alpha_ini; end
415
+  if strcmp(sTrain.alpha_type,'inv'), 
416
+    % alpha(t) = a / (t+b), where a and b are chosen suitably
417
+    % below, they are chosen so that alpha_fin = alpha_ini/100
418
+    b = (trainlen - 1) / (100 - 1);
419
+    a = b * alpha;
420
+  end
421
+end
422
+                                   
423
+% initialize random number generator
424
+rand('state',sum(100*clock));
425
+
426
+% distance between map units in the output space
427
+%  Since in the case of gaussian and ep neighborhood functions, the 
428
+%  equations utilize squares of the unit distances and in bubble case
429
+%  it doesn't matter which is used, the unitdistances and neighborhood
430
+%  radiuses are squared.
431
+Ud = som_unit_dists(sTopol).^2;
432
+
433
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
434
+%% Action
435
+
436
+update_step = 100; 
437
+mu_x_1 = ones(munits,1);
438
+samples = ones(update_step,1);
439
+r = samples; 
440
+alfa = samples;
441
+
442
+qe = 0;
443
+start = clock;
444
+if tracking >  0, % initialize tracking
445
+  track_table = zeros(update_step,1);
446
+  qe = zeros(floor(trainlen/update_step),1);  
447
+end
448
+
449
+for t = 1:trainlen, 
450
+
451
+  % Every update_step, new values for sample indeces, neighborhood
452
+  % radius and learning rate are calculated. This could be done
453
+  % every step, but this way it is more efficient. Or this could 
454
+  % be done all at once outside the loop, but it would require much
455
+  % more memory.
456
+  ind = rem(t,update_step); if ind==0, ind = update_step; end
457
+  if ind==1, 
458
+    steps = [t:min(trainlen,t+update_step-1)];
459
+    % sample order    
460
+    switch sample_order_type, 
461
+     case 'ordered', samples = rem(steps,dlen)+1;
462
+     case 'random',  samples = ceil(dlen*rand(update_step,1)+eps);
463
+    end
464
+
465
+    % neighborhood radius
466
+    switch radius_type, 
467
+     case 'linear',       r = rini+(steps-1)*rstep;
468
+     case 'user defined', r = radius(steps); 
469
+    end    
470
+    r=r.^2;        % squared radius (see notes about Ud above)
471
+    r(r==0) = eps; % zero radius might cause div-by-zero error
472
+    
473
+    % learning rate
474
+    switch sTrain.alpha_type,
475
+     case 'linear',       alfa = (1-steps/trainlen)*alpha;
476
+     case 'inv',          alfa = a ./ (b + steps-1);
477
+     case 'power',        alfa = alpha * (0.005/alpha).^((steps-1)/trainlen); 
478
+     case 'user defined', alfa = alpha(steps);
479
+    end    
480
+  end
481
+  
482
+  % find BMU
483
+  x = D(samples(ind),:);                 % pick one sample vector
484
+  known = ~isnan(x);                     % its known components
485
+  Dx = M(:,known) - x(mu_x_1,known);     % each map unit minus the vector
486
+  [qerr bmu] = min((Dx.^2)*mask(known)); % minimum distance(^2) and the BMU
487
+
488
+  % tracking
489
+  if tracking>0, 
490
+    track_table(ind) = sqrt(qerr);
491
+    if ind==update_step, 
492
+      n = ceil(t/update_step); 
493
+      qe(n) = mean(track_table);
494
+      trackplot(M,D,tracking,start,n,qe);
495
+    end
496
+  end
497
+  
498
+  % neighborhood & learning rate
499
+  % notice that the elements Ud and radius have been squared!
500
+  % (see notes about Ud above)
501
+  switch sTrain.neigh, 
502
+  case 'bubble',   h = (Ud(:,bmu)<=r(ind));
503
+  case 'gaussian', h = exp(-Ud(:,bmu)/(2*r(ind))); 
504
+  case 'cutgauss', h = exp(-Ud(:,bmu)/(2*r(ind))) .* (Ud(:,bmu)<=r(ind));
505
+  case 'ep',       h = (1-Ud(:,bmu)/r(ind)) .* (Ud(:,bmu)<=r(ind));
506
+  end  
507
+  h = h*alfa(ind);  
508
+  
509
+  % update M
510
+  M(:,known) = M(:,known) - h(:,ones(sum(known),1)).*Dx;
511
+
512
+end; % for t = 1:trainlen
513
+
514
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
515
+%% Build / clean up the return arguments
516
+
517
+if tracking, fprintf(1,'\n'); end
518
+
519
+% update structures
520
+sTrain = som_set(sTrain,'time',datestr(now,0));
521
+if struct_mode, 
522
+  sMap = som_set(sMap,'codebook',M,'mask',sTrain.mask,'neigh',sTrain.neigh);
523
+  tl = length(sMap.trainhist);
524
+  sMap.trainhist(tl+1) = sTrain;
525
+else
526
+  sMap = reshape(M,orig_size);
527
+end
528
+
529
+return;
530
+
531
+
532
+
533
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
534
+%% subfunctions
535
+
536
+%%%%%%%%
537
+function [] = trackplot(M,D,tracking,start,n,qe)
538
+
539
+  l = length(qe);
540
+  elap_t = etime(clock,start); 
541
+  tot_t = elap_t*l/n;
542
+  fprintf(1,'\rTraining: %3.0f/ %3.0f s',elap_t,tot_t)  
543
+  switch tracking
544
+   case 1, 
545
+   case 2,       
546
+    plot(1:n,qe(1:n),(n+1):l,qe((n+1):l))
547
+    title('Quantization errors for latest samples')    
548
+    drawnow
549
+   otherwise,
550
+    subplot(2,1,1), plot(1:n,qe(1:n),(n+1):l,qe((n+1):l))
551
+    title('Quantization error for latest samples');
552
+    subplot(2,1,2), plot(M(:,1),M(:,2),'ro',D(:,1),D(:,2),'b.'); 
553
+    title('First two components of map units (o) and data vectors (+)');
554
+    drawnow
555
+  end  
556
+  % end of trackplot
557
+
... ...
@@ -0,0 +1,777 @@
1
+function [sS, ok, msgs] = som_set(sS, varargin)
2
+
3
+%SOM_SET Create and check SOM Toolbox structs, give values to their fields.
4
+%
5
+% [sS, ok, msgs] = som_set(sS, [field, contents, ...])
6
+%
7
+%   sM              = som_set(sM,'name','SOM#1.1');
8
+%   [dummy,ok,msgs] = som_set(sData);   
9
+%   sT              = som_set('som_topol','msize',[10 10],'lattice','hexa');
10
+%   [sTrain,ok]     = som_set(sTrain,'algorithm','lininit');
11
+%   [sN,ok,msgs]    = som_set('som_norm');
12
+%
13
+% Input and output arguments ([]'s are optional):
14
+%  sS                   the target struct
15
+%              (struct) a SOM Toolbox structure (not visualization struct)
16
+%              (string) structure identifier (see below)
17
+%                       the updated/created structure is returned
18
+%  [field,     (string) field to be given value to (see below)
19
+%   contents]  (varies) the contents for the field
20
+%
21
+%  ok          (vector)  status for each field-contents pair (1=ok)
22
+%  msgs        (cellstr) status string for each field-contents pair (''=ok)
23
+%
24
+%  There can be arbitrarily many field-contents pairs. If there
25
+%  are _no_ field-content pairs, and the first argument is a struct,
26
+%  the fields of the struct are checked for validity.
27
+% 
28
+%  Valid struct and corresponding field identifiers: 
29
+%  'som_map'   : 'codebook', 'labels', 'mask', 'neigh', 'name', 
30
+%                'topol', 'msize, 'lattice', 'shape',
31
+%                'trainhist', 'comp_names', 'comp_norm', 
32
+%  'som_data'  : 'data', 'labels', 'name', 'comp_names', 'comp_norm', 
33
+%                'label_names'
34
+%  'som_topol' : 'msize', 'lattice', 'shape'
35
+%  'som_norm'  : 'method', 'params', 'status'
36
+%  'som_train' : 'algorithm', 'data_name', 'mask', 'neigh', 
37
+%                'radius_ini', 'radius_fin', 'alpha_ini', 'alpha_type', 
38
+%                'trainlen', 'time'
39
+%  'som_grid'  : 'lattice', 'shape', 'msize', 'coord',
40
+%                'line', 'linecolor', 'linewidth', 
41
+%                'marker', 'markersize', 'markercolor', 'surf', 
42
+%                'label', 'labelcolor', 'labelsize'
43
+%                checking given values has not been implemented yet!
44
+%                
45
+% For more help, try 'type som_set' or check out online documentation.
46
+% See also SOM_INFO, SOM_MAP_STRUCT, SOM_DATA_STRUCT, SOM_VS1TO2.
47
+
48
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
49
+%
50
+% som_set
51
+%
52
+% PURPOSE
53
+%
54
+% Create and set values for fields of SOM Toolbox structs (except
55
+% visualization struct). Can also be used to check the validity of structs.
56
+%
57
+% SYNTAX
58
+%
59
+%  sMap   = som_set('som_map');
60
+%  sData  = som_set(sData);
61
+%  sNorm  = som_set(...,'field',contents,...);
62
+%  [sTopol,ok]      = som_set(sTopol,...);
63
+%  [sTrain,ok,msgs] = som_set('som_train',...);
64
+%
65
+% DESCRIPTION
66
+%
67
+% The function is used to create and set values for fields of SOM
68
+% Toolbox structs, except visualization structs. The given values are
69
+% first checked for validity, and if they are not valid, an error
70
+% message is returned. The function can also be used to check the
71
+% validity of all the fields of the struct by supplying a struct as
72
+% the first and only argument.
73
+% 
74
+% NOTE: Using SOM_SET to create structures does _not_ guarantee that the
75
+% structs are valid (try e.g. sM = som_set('som_map'); som_set(sM)). The
76
+% initial values that the function gives to the fields of the structs are
77
+% typically invalid. It is recommended that when creating map or data 
78
+% structs, the corresponding functions SOM_MAP_STRUCT and SOM_DATA_STRUCT 
79
+% are used instead of SOM_SET. However, when giving values for the fields, 
80
+% SOM_SET tries to guarantee that the values are valid.
81
+%
82
+% If a string is given as the first argument, the corresponding 
83
+% structure is first created and the field-content pairs are then
84
+% applied to it. 
85
+%
86
+% There can be arbitrarily many field-contents pairs. The pairs
87
+% are processed sequentially one pair at a time. For each pair,
88
+% the validity of the contents is checked and the corresponding 
89
+% items in the returned 'ok'-vector and 'msgs'-cellstring are set.
90
+% - if the contents is ok, the status is set to 1 and message to ''
91
+% - if the contents is suspicious, status is set to 1, but a
92
+%   message is produced
93
+% - if the contents is invalid, status is set to 0 and an error
94
+%   message is produced. The contents are _not_ given to the field.
95
+% If there is only one output argument, the status and messages
96
+% for each pair are printed to standard output.
97
+%
98
+% The different field-contents pairs have no effect on each other.
99
+% If a field is given a value multiple times, the last valid one 
100
+% stays in effect.
101
+% 
102
+% In some cases, the order of the given fields is significant.
103
+% For example in the case of 'som_map', the validity of some fields, 
104
+% like '.comp_names', depends on the input space dimension, which is
105
+% checked from the '.data' field (dim = size(sD.data,2) to be specific).
106
+% Therefore, the '.data' field (or '.codebook' field in case of map 
107
+% struct) should always be given a value first. Below is a list of 
108
+% this kind of dependancies:
109
+% 
110
+% som_map:   'comp_names', 'comp_norm', 'msize', 'topol.msize',
111
+%            'labels' and 'mask' depend on 'codebook'
112
+%            new value for 'codebook' should have equal size to the old
113
+%            one (unless the old one was empty)
114
+% som_data:  'comp_names' and 'comp_norm' depend on 'data'
115
+%            new value for 'data' should have equal dimension (size(data,2))
116
+%            as the old one (unless the old one was empty)
117
+% 
118
+% KNOWN BUGS
119
+%
120
+% Checking the values given to som_grid struct has not been
121
+% implemented. Use SOM_GRID function to give the values.
122
+%
123
+% REQUIRED INPUT ARGUMENTS
124
+%
125
+%  sS          The struct.
126
+%     (struct) A SOM Toolbox struct.
127
+%     (string) Identifier of a SOM Toolbox struct: 'som_map', 
128
+%              'som_data', 'som_topol', 'som_norm' or 'som_train'
129
+%   
130
+% OPTIONAL INPUT ARGUMENTS 
131
+%
132
+%  field     (string) Field identifier string (see below).
133
+%  contents  (varies) Value for the field (see below).
134
+%
135
+%  Below is the list of valid field identifiers for the different 
136
+%  SOM Toolbox structs. 
137
+%
138
+%  'som_map' (map struct)
139
+%    'codebook'    : matrix, size [munits, dim] 
140
+%    'labels'      : cell array of strings, 
141
+%                    size [munits, maximum_number_of_labels]
142
+%    'topol'       : topology struct (prod(topol.msize)=munits)
143
+%    'mask'        : vector, size [dim, 1]
144
+%    'neigh'       : string ('gaussian' or 'cutgauss' or 'bubble' or 'ep')
145
+%    'trainhist'   : struct array of train structs
146
+%    'name'        : string
147
+%    'comp_names'  : cellstr, size [dim, 1], e.g. {'c1','c2','c3'}
148
+%    'comp_norm'   : cell array, size [dim, 1], of cell arrays 
149
+%                    of normalization structs
150
+%    Also the following can be used (although they are fields
151
+%    of the topology struct)
152
+%    'msize'       : vector (prod(msize)=munits)
153
+%    'lattice'     : string ('rect' or 'hexa')
154
+%    'shape'       : string ('sheet' or 'cyl' or 'toroid')
155
+%
156
+%  'som_data' (data struct)
157
+%    'data'        : matrix, size [dlen, dim]
158
+%    'name'        : string
159
+%    'labels'      : cell array of strings, 
160
+%                    size [dlen, m]
161
+%    'comp_names'  : cellstr, size [dim, 1], e.g. {'c1','c2','c3'}
162
+%    'comp_norm'   : cell array, size [dim, 1], of cell arrays 
163
+%                    of normalization structs
164
+%    'label_names' : cellstr, size [m, 1]
165
+%
166
+% 'som_topol' (topology struct)
167
+%    'msize'       : vector
168
+%    'lattice'     : string ('rect' or 'hexa')
169
+%    'shape'       : string ('sheet' or 'cyl' or 'toroid')
170
+%
171
+% 'som_norm' (normalization struct)
172
+%    'method'      : string
173
+%    'params'      : varies
174
+%    'status'      : string ('done' or 'undone' or 'uninit')
175
+%
176
+% 'som_train' (train struct)
177
+%    'algorithm'   : string ('seq' or 'batch' or 'lininit' or 'randinit')
178
+%    'data_name'   : string
179
+%    'mask'        : vector, size [dim, 1]
180
+%    'neigh'       : string ('gaussian' or 'cutgauss' or 'bubble' or 'ep')
181
+%    'radius_ini'  : scalar
182
+%    'radius_fin'  : scalar
183
+%    'alpha_ini'   : scalar
184
+%    'alpha_type'  : string ('linear' or 'inv' or 'power')
185
+%    'trainlen'    : scalar
186
+%    'time'        : string
187
+%
188
+% 'som_grid' (grid struct) : checking the values has not been implemented yet!
189
+%    'lattice'     : string ('rect' or 'hexa') or 
190
+%                    (sparce) matrix, size munits x munits
191
+%    'shape'       : string ('sheet' or 'cyl' or 'toroid')
192
+%    'msize'       : vector, size 1x2
193
+%    'coord'       : matrix, size munits x 2 or munits x 3
194
+%    'line'        : string (linespec, e.g. '-', or 'none')
195
+%    'linecolor'   : RGB triple or string (colorspec, e.g. 'k') or 
196
+%                    munits x munits x 3 (sparce) matrix or cell
197
+%                    array of RGB triples 
198
+%    'linewidth'   : scalar or munits x munits (sparce) matrix
199
+%    'marker'      : string (markerspec, e.g. 'o', or 'none') or 
200
+%                    munits x 1 cell or char array of these
201
+%    'markersize'  : scalar or munits x 1 vector
202
+%    'markercolor' : RGB triple or string (colorspec, e.g. 'k')
203
+%    'surf'        : [], munits x 1 or munits x 3 matrix of RGB triples
204
+%    'label'       : [] or munits x 1 char array or 
205
+%                    munits x l cell array of strings 
206
+%    'labelcolor'  : RGB triple or string (colorspec, e.g. 'g' or 'none')
207
+%    'labelsize'   : scalar
208
+%
209
+% OUTPUT ARGUMENTS
210
+% 
211
+%  sS    (struct)  the created / updated struct
212
+%  ok    (vector)  length = number of field-contents pairs, gives
213
+%                  validity status for each pair (0=invalid, 1 otherwise)
214
+%  msgs  (cellstr) length = number of field-contents pairs, gives
215
+%                  error/warning message for each pair ('' if ok)
216
+%
217
+% EXAMPLES
218
+%
219
+% To create a struct:
220
+%  sM  = som_set('som_map');
221
+%  sD  = som_set('som_data');
222
+%  sTo = som_set('som_topol');
223
+%  sTr = som_set('som_train');
224
+%  sN  = som_set('som_norm');
225
+%  sG  = som_set('som_grid');
226
+%
227
+% To check the the contents of a struct: 
228
+%  som_set(sS);
229
+%  [dummy,ok]      = som_set(sS);
230
+%  [dummy,ok,msgs] = som_set(sS);
231
+%
232
+% To give values to fields: 
233
+%  sTo = som_set(sTo,'msize',[10 10],'lattice','hexa','shape','toroid');
234
+%  sM  = som_set('som_map','codebook',rand(100,4),'topol',sTo);
235
+%   
236
+% SEE ALSO
237
+% 
238
+%  som_info         Prints information the given struct.
239
+%  som_map_struct   Create map struct.
240
+%  som_data_struct  Create data struct.
241
+%  som_topol_struct Create topology struct.
242
+%  som_train_struct Create training struct.
243
+%  som_grid         Create and visualize grid struct.
244
+%  som_vs1to2       Conversion from version 1.0 structs to 2.0.
245
+%  som_vs2to1       Conversion from version 2.0 structs to 1.0.
246
+
247
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
248
+% http://www.cis.hut.fi/projects/somtoolbox/
249
+
250
+% Version 2.0beta juuso 101199 130300
251
+
252
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
253
+%% create struct if necessary
254
+
255
+if ischar(sS), 
256
+  switch sS
257
+   case 'som_map',
258
+    sS=struct('type', 'som_map', ...
259
+              'codebook', [], ...
260
+              'topol', som_set('som_topol'), ...
261
+              'labels', cell(1), ...
262
+              'neigh', 'gaussian', ...
263
+              'mask', [], ...
264
+              'trainhist', cell(1), ...
265
+              'name', '',...
266
+              'comp_names', {''}, ...
267
+              'comp_norm', cell(1));
268
+   case 'som_data', 
269
+    sS=struct('type', 'som_data', ...
270
+              'data', [], ...
271
+              'labels', cell(1), ...
272
+              'name', '', ...
273
+              'comp_names', {''}, ...
274
+              'comp_norm', cell(1), ...
275
+              'label_names', []);
276
+   case 'som_topol',
277
+    sS=struct('type', 'som_topol', ...
278
+              'msize', 0, ...
279
+              'lattice', 'hexa', ...
280
+              'shape', 'sheet');
281
+   case 'som_train',
282
+    sS=struct('type', 'som_train', ...
283
+              'algorithm', '', ...
284
+              'data_name', '', ...
285
+              'neigh', 'gaussian', ...
286
+              'mask', [], ...
287
+              'radius_ini', NaN, ...
288
+              'radius_fin', NaN, ...
289
+              'alpha_ini', NaN, ...
290
+              'alpha_type', 'inv', ...
291
+              'trainlen', NaN, ...
292
+              'time', '');
293
+   case 'som_norm',
294
+    sS=struct('type', 'som_norm', ...
295
+              'method', 'var', ...
296
+              'params', [], ...
297
+              'status', 'uninit');
298
+   case 'som_grid', 
299
+    sS=struct('type','som_grid',...
300
+	      'lattice','hexa',...
301
+	      'shape','sheet',...
302
+	      'msize',[1 1],...
303
+	      'coord',[],...
304
+	      'line','-',...
305
+	      'linecolor',[.9 .9 .9],...
306
+	      'linewidth',0.5,...
307
+	      'marker','o',...
308
+	      'markersize',6,...
309
+	      'markercolor','k',...
310
+	      'surf',[],...
311
+	      'label',[],...
312
+	      'labelcolor','g',...
313
+	      'labelsize',12);    
314
+   otherwise
315
+    ok=0; msgs = {['Unrecognized struct type: ' sS]}; sS = [];
316
+    return;
317
+  end  
318
+  
319
+elseif isstruct(sS) & length(varargin)==0, 
320
+  
321
+  % check all fields
322
+  fields = fieldnames(sS);
323
+  if ~any(strcmp('type',fields)), 
324
+    error('The struct has no ''type'' field.');
325
+  end
326
+  k = 0;
327
+  for i=1:length(fields), 
328
+    contents = getfield(sS,fields{i});
329
+    if ~strcmp(fields{i},'type'), 
330
+      varargin{k+1} = fields{i};
331
+      varargin{k+2} = contents;
332
+      k = k + 2;
333
+    else 
334
+      if ~any(strcmp(contents, ...
335
+        {'som_map','som_data','som_topol','som_train','som_norm'})), 
336
+	error(['Unknown struct type: ' contents]);
337
+      end
338
+    end
339
+  end
340
+  
341
+end
342
+
343
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
344
+%% set field values
345
+
346
+p = ceil(length(varargin)/2);
347
+ok = ones(p,1);
348
+msgs = cell(p,1);
349
+
350
+for i=1:p, 
351
+  field = varargin{2*i-1}; 
352
+  content = varargin{2*i};
353
+  msg = '';
354
+  isok = 0;
355
+  
356
+  si = size(content);
357
+  isscalar = (prod(si)==1);
358
+  isvector = (sum(si>1)==1);
359
+  isrowvector = (isvector & si(1)==1);
360
+  if isnumeric(content), 
361
+    iscomplete = all(~isnan(content(:))); 
362
+    ispositive = all(content(:)>0); 
363
+    isinteger  = all(content(:)==ceil(content(:)));
364
+    isrgb = all(content(:)>=0 & content(:)<=1) & size(content,2)==3;
365
+  end
366
+  
367
+  switch sS.type, 
368
+   case 'som_map',
369
+    [munits dim] = size(sS.codebook);
370
+    switch field, 
371
+     case 'codebook', 
372
+      if ~isnumeric(content), 
373
+	msg = '''codebook'' should be a numeric matrix'; 
374
+      elseif size(content) ~= size(sS.codebook) & ~isempty(sS.codebook), 
375
+	msg = 'New ''codebook'' must be equal in size to the old one.'; 
376
+      elseif ~iscomplete, 
377
+	msg = 'Map codebook must not contain NaN''s.'; 
378
+      else
379
+	sS.codebook = content; isok=1;
380
+      end
381
+     case 'labels', 
382
+      if isempty(content), 
383
+	sS.labels = cell(munits,1); isok = 1;
384
+      elseif size(content,1) ~= munits, 
385
+	msg = 'Length of labels array must be equal to the number of map units.';
386
+      elseif ~iscell(content) & ~ischar(content), 
387
+	msg = '''labels'' must be a string array or a cell array/matrix.';
388
+      else
389
+	isok = 1;
390
+	if ischar(content), content = cellstr(content); 
391
+	elseif ~iscellstr(content), 
392
+	  l = prod(size(content));
393
+	  for j=1:l, 
394
+	    if ischar(content{j}), 
395
+	      if ~isempty(content{j}), 
396
+		msg = 'Invalid ''labels'' array.';
397
+		isok = 0; 
398
+		break;
399
+	      else
400
+		content{j} = ''; 
401
+	      end
402
+	    end
403
+	  end
404
+	end
405
+	if isok, sS.labels = content; end
406
+      end
407
+     case 'topol', 
408
+      if ~isstruct(content), 
409
+	msg = '''topol'' should be a topology struct.'; 
410
+      elseif ~isfield(content,'msize') | ...
411
+	    ~isfield(content,'lattice') | ...
412
+	    ~isfield(content,'shape'), 
413
+	msg = '''topol'' is not a valid topology struct.'; 
414
+      elseif prod(content.msize) ~= munits, 
415
+	msg = '''topol''.msize does not match the number of map units.'; 
416
+      else
417
+	sS.topol = content; isok = 1;
418
+      end
419
+     case 'msize', 
420
+      if ~isnumeric(content) | ~isvector | ~ispositive | ~isinteger, 
421
+	msg = '''msize'' should be a vector with positive integer elements.'; 
422
+      elseif prod(content) ~= munits, 
423
+	msg = '''msize'' does not match the map size.'; 
424
+      else
425
+	sS.topol.msize = content; isok = 1;
426
+      end
427
+     case 'lattice', 
428
+      if ~ischar(content),
429
+	msg = '''lattice'' should be a string'; 
430
+      elseif ~strcmp(content,'rect') & ~strcmp(content,'hexa'),
431
+	msg = ['Unknown lattice type: ' content];
432
+	sS.topol.lattice = content; isok = 1;
433
+      else
434
+	sS.topol.lattice = content; isok = 1;
435
+      end
436
+     case 'shape', 
437
+      if ~ischar(content),
438
+	msg = '''shape'' should be a string';
439
+      elseif ~strcmp(content,'sheet') & ~strcmp(content,'cyl') & ...
440
+	    ~strcmp(content,'toroid'),
441
+	msg = ['Unknown shape type:' content]; 
442
+	sS.topol.shape = content; isok = 1;
443
+      else
444
+	sS.topol.shape = content; isok = 1;
445
+      end
446
+     case 'neigh', 
447
+      if ~ischar(content),
448
+	msg = '''neigh'' should be a string'; 
449
+      elseif ~strcmp(content,'gaussian') & ~strcmp(content,'ep') & ...
450
+	    ~strcmp(content,'cutgauss') & ~strcmp(content,'bubble'),
451
+	msg = ['Unknown neighborhood function: ' content]; 
452
+	sS.neigh = content; isok = 1;
453
+      else
454
+	sS.neigh = content; isok = 1;
455
+      end
456
+     case 'mask', 
457
+      if size(content,1) == 1, content = content'; end
458
+      if ~isnumeric(content) | size(content) ~= [dim 1], 
459
+	msg = '''mask'' should be a column vector (size dim x 1).'; 
460
+      else
461
+	sS.mask = content; isok = 1;
462
+      end
463
+     case 'name', 
464
+      if ~ischar(content), 
465
+	msg = '''name'' should be a string.';
466
+      else 
467
+	sS.name = content; isok = 1;
468
+      end
469
+     case 'comp_names', 
470
+      if ~iscell(content) & ~ischar(content), 
471
+	msg = '''comp_names'' should be a cell string or a string array.'; 
472
+      elseif length(content) ~= dim, 
473
+	msg = 'Length of ''comp_names'' should be equal to dim.'; 
474
+      else
475
+	if ischar(content), content = cellstr(content); end
476
+	if size(content,1)==1, content = content'; end
477
+	sS.comp_names = content;
478
+	isok = 1;
479
+      end        
480
+     case 'comp_norm', 
481
+      if ~iscell(content) & length(content)>0, 
482
+	msg = '''comp_norm'' should be a cell array.'; 
483
+      elseif length(content) ~= dim, 
484
+	msg = 'Length of ''comp_norm'' should be equal to dim.'; 
485
+      else
486
+	isok = 1;
487
+	for j=1:length(content), 
488
+	  if ~isempty(content{j}) & (~isfield(content{j}(1),'type') | ...
489
+				     ~strcmp(content{j}(1).type,'som_norm')), 
490
+	    msg = 'Each cell in ''comp_norm'' should be either empty or type ''som_norm''.';
491
+	    isok = 0; 
492
+	    break; 
493
+	  end
494
+	end
495
+	if isok, sS.comp_norm = content; end
496
+      end        
497
+     case 'trainhist', 
498
+      if ~isstruct(content) & ~isempty(content), 
499
+	msg = '''trainhist'' should be a struct array or empty.';
500
+      else
501
+	isok = 1;
502
+	for j=1:length(content), 
503
+	  if ~isfield(content(j),'type') | ~strcmp(content(j).type,'som_train'), 
504
+	    msg = 'Each cell in ''trainhist'' should be of type ''som_train''.';
505
+	    isok = 0; 
506
+	    break; 
507
+	  end
508
+	end
509
+	if isok, sS.trainhist = content; end      
510
+      end        
511
+     otherwise, 
512
+      msg = ['Invalid field for map struct: ' field]; 
513
+    end
514
+    
515
+   case 'som_data',
516
+    [dlen dim] = size(sS.data);
517
+    switch field,      
518
+     case 'data', 
519
+      [dummy dim2] = size(content);
520
+      if prod(si)==0, 
521
+	msg = '''data'' is empty';
522
+      elseif ~isnumeric(content), 
523
+	msg = '''data'' should be numeric matrix.'; 
524
+      elseif dim ~= dim2 & ~isempty(sS.data), 
525
+	msg = 'New ''data'' must have the same dimension as old one.'; 
526
+      else
527
+	sS.data = content; isok = 1;
528
+      end
529
+     case 'labels', 
530
+      if isempty(content), 
531
+	sS.labels = cell(dlen,1); isok = 1;
532
+      elseif size(content,1) ~= dlen, 
533
+	msg = 'Length of ''labels'' must be equal to the number of data vectors.';
534
+      elseif ~iscell(content) & ~ischar(content), 
535
+	msg = '''labels'' must be a string array or a cell array/matrix.';
536
+      else
537
+	isok = 1;
538
+	if ischar(content), content = cellstr(content); 
539
+	elseif ~iscellstr(content), 
540
+	  l = prod(size(content));
541
+	  for j=1:l, 
542
+	    if ~ischar(content{j}), 
543
+	      if ~isempty(content{j}), 
544
+		msg = 'Invalid ''labels'' array.';
545
+		isok = 0; j
546
+		break;
547
+	      else
548
+		content{j} = ''; 
549
+	      end
550
+	    end
551
+	  end
552
+	end
553
+	if isok, sS.labels = content; end
554
+      end
555
+     case 'name', 
556
+      if ~ischar(content), 
557
+	msg = '''name'' should be a string.';
558
+      else 
559
+	sS.name = content; isok = 1;
560
+      end
561
+     case 'comp_names', 
562
+      if ~iscell(content) & ~ischar(content), 
563
+	msg = '''comp_names'' should be a cell string or a string array.'; 
564
+      elseif length(content) ~= dim, 
565
+	msg = 'Length of ''comp_names'' should be equal to dim.'; 
566
+      else
567
+	if ischar(content), content = cellstr(content); end
568
+	if size(content,1)==1, content = content'; end
569
+	sS.comp_names = content;
570
+	isok = 1;
571
+      end        
572
+     case 'comp_norm', 
573
+      if ~iscell(content) & length(content)>0, 
574
+	msg = '''comp_norm'' should be a cell array.'; 
575
+      elseif length(content) ~= dim, 
576
+	msg = 'Length of ''comp_norm'' should be equal to dim.'; 
577
+      else
578
+	isok = 1;
579
+	for j=1:length(content), 
580
+	  if ~isempty(content{j}) & (~isfield(content{j}(1),'type') | ...
581
+				     ~strcmp(content{j}(1).type,'som_norm')), 
582
+	    msg = 'Each cell in ''comp_norm'' should be either empty or type ''som_norm''.';
583
+	    isok = 0; 
584
+	    break; 
585
+	  end
586
+	end
587
+	if isok, sS.comp_norm = content; end
588
+      end        
589
+     case 'label_names', 
590
+      if ~iscell(content) & ~ischar(content) & ~isempty(content), 
591
+	msg = ['''label_names'' should be a cell string, a string array or' ...
592
+	       ' empty.']; 
593
+      else
594
+	if ~isempty(content), 
595
+	  if ischar(content), content = cellstr(content); end
596
+	  if size(content,1)==1, content = content'; end
597
+	end
598
+	sS.label_names = content;
599
+	isok = 1;
600
+      end        
601
+     otherwise, 
602
+      msg = ['Invalid field for data struct: ' field]; 
603
+    end
604
+    
605
+   case 'som_topol', 
606
+    switch field,      
607
+     case 'msize', 
608
+      if ~isnumeric(content) | ~isvector | ~ispositive | ~isinteger, 
609
+	msg = '''msize'' should be a vector with positive integer elements.'; 
610
+      else
611
+	sS.msize = content; isok=1;
612
+      end
613
+     case 'lattice', 
614
+      if ~ischar(content),
615
+	msg = '''lattice'' should be a string'; 
616
+      elseif ~strcmp(content,'rect') & ~strcmp(content,'hexa'),
617
+	msg = ['Unknown lattice type: ' content]; 
618
+	sS.lattice = content; isok = 1;
619
+      else
620
+	sS.lattice = content; isok = 1;
621
+      end
622
+     case 'shape', 
623
+      if ~ischar(content),
624
+	msg = '''shape'' should be a string';
625
+      elseif ~strcmp(content,'sheet') & ~strcmp(content,'cyl') & ...
626
+	    ~strcmp(content,'toroid'),
627
+	msg = ['Unknown shape type: ' content]; 
628
+	sS.shape = content; isok = 1;
629
+      else
630
+	sS.shape = content; isok = 1;
631
+      end
632
+     otherwise, 
633
+      msg = ['Invalid field for topology struct: ' field]; 
634
+    end
635
+    
636
+   case 'som_train', 
637
+    switch field,      
638
+     case 'algorithm', 
639
+      if ~ischar(content),
640
+	msg = '''algorithm'' should be a string.'; 
641
+      else
642
+	sS.algorithm = content; isok = 1;
643
+      end
644
+     case 'data_name', 
645
+      if ~ischar(content),
646
+	msg = '''data_name'' should be a string'; 
647
+      else
648
+	sS.data_name = content; isok = 1;
649
+      end
650
+     case 'neigh', 
651
+      if ~ischar(content),
652
+	msg = '''neigh'' should be a string'; 
653
+      elseif ~isempty(content) & ~strcmp(content,'gaussian') & ~strcmp(content,'ep') & ...
654
+	    ~strcmp(content,'cutgauss') & ~strcmp(content,'bubble'),
655
+	msg = ['Unknown neighborhood function: ' content]; 
656
+	sS.neigh = content; isok = 1;
657
+      else
658
+	sS.neigh = content; isok = 1;
659
+      end
660
+     case 'mask', 
661
+      if size(content,1) == 1, content = content'; end
662
+      dim = size(content,1); %[munits dim] = size(sS.data); 
663
+      if ~isnumeric(content) | size(content) ~= [dim 1], 
664
+	msg = '''mask'' should be a column vector (size dim x 1).'; 
665
+      else
666
+	sS.mask = content; isok = 1;
667
+      end
668
+     case 'radius_ini', 
669
+      if ~isnumeric(content) | ~isscalar, 
670
+	msg = '''radius_ini'' should be a scalar.'; 
671
+      else
672
+	sS.radius_ini = content; isok = 1;
673
+      end
674
+     case 'radius_fin', 
675
+      if ~isnumeric(content) | ~isscalar, 
676
+	msg = '''radius_fin'' should be a scalar.'; 
677
+      else
678
+	sS.radius_fin = content; isok = 1;
679
+      end
680
+     case 'alpha_ini', 
681
+      if ~isnumeric(content) | ~isscalar,
682
+	msg = '''alpha_ini'' should be a scalar.'; 
683
+      else
684
+	sS.alpha_ini = content; isok = 1;
685
+      end
686
+     case 'alpha_type', 
687
+      if ~ischar(content),
688
+	msg = '''alpha_type'' should be a string'; 
689
+      elseif ~strcmp(content,'linear') & ~strcmp(content,'inv') & ...
690
+	    ~strcmp(content,'power') & ~strcmp(content,'constant') & ~strcmp(content,''),
691
+	msg = ['Unknown alpha type: ' content]; 
692
+	sS.alpha_type = content; isok = 1;
693
+      else
694
+	sS.alpha_type = content; isok = 1;
695
+      end        
696
+     case 'trainlen', 
697
+      if ~isnumeric(content) | ~isscalar, 
698
+	msg = '''trainlen'' should be a scalar.'; 
699
+      else
700
+	sS.trainlen = content; isok = 1;
701
+      end
702
+     case 'time', 
703
+      if ~ischar(content),
704
+	msg = '''time'' should be a string'; 
705
+      else
706
+	sS.time = content; isok = 1;
707
+      end        
708
+     otherwise, 
709
+      msg = ['Invalid field for train struct: ' field]; 
710
+    end
711
+    
712
+   case 'som_norm', 
713
+    switch field,      
714
+     case 'method', 
715
+      if ~ischar(field), 
716
+	msg = '''method'' should be a string.';
717
+      else
718
+	sS.method = content; isok = 1;
719
+      end
720
+     case 'params', 
721
+      sS.params = content; isok = 1;
722
+     case 'status', 
723
+      if ~ischar(content),
724
+	msg = '''status'' should be a string'; 
725
+      elseif ~strcmp(content,'done') & ~strcmp(content,'undone') & ...
726
+	    ~strcmp(content,'uninit'),
727
+	msg = ['Unknown status type: ' content]; 
728
+	sS.status = content; isok = 1;
729
+      else
730
+	sS.status = content; isok = 1;
731
+      end        
732
+     otherwise, 
733
+      msg = ['Invalid field for normalization struct: ' field];
734
+    end
735
+
736
+   case 'som_grid', 
737
+    if any(strcmp(field,{'lattice', 'shape', 'msize', 'coord',...
738
+			 'line', 'linecolor', 'linewidth', ...
739
+			 'marker', 'markersize', 'markercolor', 'surf', ... 
740
+			 'label', 'labelcolor', 'labelsize'})), 
741
+      warning('No checking done on field identifier or content.');
742
+      sS = setfield(sS,field,content);       
743
+      isok = 1;
744
+    else
745
+      msg = ['Invalid field for grid struct: ' field];
746
+    end
747
+    
748
+   otherwise, 
749
+    error('Unrecognized structure.'); 
750
+    
751
+  end
752
+  
753
+  msgs{i} = msg;
754
+  ok(i) = isok;
755
+  
756
+end
757
+
758
+
759
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
760
+%% return
761
+
762
+if nargout < 2, 
763
+  for i=1:p,     
764
+    if ~isempty(msgs{i}), 
765
+      if ~ok(i), fprintf(1,'[Error! '); 
766
+      else fprintf(1,'[Notice ');
767
+      end
768
+      fprintf(1,'in setting %s] ',varargin{2*i-1});
769
+      fprintf(1,'%s\n',msgs{i});
770
+    end
771
+  end
772
+end
773
+
774
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
775
+
776
+
777
+
... ...
@@ -0,0 +1,815 @@
1
+function h=som_show(sMap, varargin)
2
+
3
+% SOM_SHOW Basic SOM visualizations: component planes, u-matrix etc.
4
+%
5
+% h = som_show(sMap, ['argID', value, ...])
6
+% 
7
+%  som_show(sMap);
8
+%  som_show(sMap,'bar','none');
9
+%  som_show(sMap,'comp',[1:3],'umat','all');
10
+%  som_show(sMap,'comp',[1 2],'umat',{[1 2],'1,2 only'},'comp',[3:6]);   
11
+%  som_show(sMap,'size',m,'bar','vert','edge','off');
12
+%
13
+% Input and output arguments ([]'s are optional):
14
+%  sMap        (struct) map struct
15
+%  [argID,     (string) Additional parameters are given as argID, value
16
+%    value]    (varies) pairs. See below for list of valid IDs and values.
17
+%
18
+%  h           (struct) struct with the following fields:
19
+%   .plane     (vector) handles to the axes objecets (subplots)
20
+%   .colorbar  (vector) handles to the colorbars. Colorbars for empty
21
+%                       grids & RGB color planes do not exist: the
22
+%                       value for them in the vector is -1.
23
+%   .label     (vector) handles to the axis labels
24
+%
25
+% Here are the valid argument IDs and corresponding values. M is
26
+% the number of map units
27
+%  'comp'               Which component planes to draw, title is
28
+%                       the name of the component (from sMap.comp_names) 
29
+%              (vector) a vector of component indices
30
+%              (string) 'all' (or '' or []) for all components
31
+%  'compi'              as 'comp' but uses interpolated shading
32
+%  'umat'               Show u-matrix calculated using specified 
33
+%                       components 
34
+%              (vector) a vector of component indeces
35
+%              (string) 'all' (or '' or []) to use all components
36
+%              (cell)   of form {v, str} uses v as the vector, and put
37
+%                       str as title instead of the default 'U-matrix'
38
+%  'umati'              as 'umat' but uses interpolated shading of colors 
39
+%  'empty'     (string) Make an empty plane using given string as title
40
+%  'color'              Set arbitrary unit colors explicitly  
41
+%              (matrix) size Mx1 or Mx3, Mx1 matrix uses indexed
42
+%                       coloring;  Mx3 matrix (RGB triples as rows)
43
+%                       defines fixed unit colors
44
+%              (cell)   of from {color, str}. 'color' is the Mx1
45
+%                       or Mx3 RGB triple matrix and 'str' is title 
46
+%                       string
47
+%  'colori'             as 'color' but uses interpolated shading of colors 
48
+%  'norm'      (string) 'n' or 'd': Whether to show normalized 'n' or 
49
+%                       denormalized 'd' data values on the
50
+%                       colorbar. By default denormalized values are used.
51
+%  'bar'       (string) Colorbar direction: 'horiz', 'vert' (default)
52
+%                       or 'none'
53
+%  'size'               size of the units
54
+%              (scalar) same size for each unit, default is 1
55
+%              (vector) size Mx1, individual size for each unit
56
+%  'edge'      (string) Unit edges on component planes 'on'
57
+%                       (default) or 'off'
58
+%  'footnote'  (string) Footnote string, sMap.name by default
59
+%  'colormap'  (matrix) user defined colormap 
60
+%  'subplots'  (vector) size 1 x 2, the number of subplots in y- and
61
+%                       and x-directions (as in SUBPLOT command)
62
+%
63
+% If identifiers 'comp', 'compi', 'umat', 'umati', 'color', 'colori'
64
+% or 'empty' are not specified at all, e.g. som_show(sMap) or
65
+% som_show(sMap,'bar','none'), the U-matrix and all component planes
66
+% are shown.
67
+%
68
+% For more help, try 'type som_show' or check out online documentation. 
69
+% See also SOM_SHOW_ADD, SOM_SHOW_CLEAR, SOM_UMAT, SOM_CPLANE, SOM_GRID.
70
+
71
+%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
72
+%
73
+% som_show
74
+%
75
+% PURPOSE 
76
+%
77
+% Shows basic visualizations of SOM: component planes, unified distance
78
+% matrices as well as empty planes and fixed color planes.
79
+%
80
+% SYNTAX
81
+%
82
+%  h = som_show(sMap)
83
+%  h = som_show(sMap, 'argID', value, ...)
84
+%
85
+% DESCRIPTION 
86
+%
87
+% This function is used for basic visualization of the SOM. Four
88
+% kinds of SOM planes can be shown: 
89
+%
90
+%  1. U-matrix (see SOM_UMAT) which shows clustering structure of
91
+%     the SOM. Either all or just part of the components can 
92
+%     be used in calculating the U-matrix.
93
+%  2. component planes: each component plane shows the values of
94
+%     one variable in each map unit
95
+%  3. an empty plane which may be used as a base for, e.g., hit 
96
+%     histogram visualization or labeling (see SOM_SHOW_ADD)
97
+%  4. a fixed or indexed color representation for showing color coding or 
98
+%     clustering
99
+%
100
+% The component planes and u-matrices may have colorbars showing the
101
+% scale for the variable. The scale shows by default the values that
102
+% variables have in the map struct. It may be changed to show the
103
+% original data values (estimated by SOM_DENORMALIZE). In this case a
104
+% small 'd' appears below the colorbar. The orientation of these
105
+% colorbars may be changed, or they can be removed.
106
+%
107
+% By default the u-matrix - calculated using all variables - and all
108
+% component planes are shown. This is achieved by giving command
109
+% som_show(sMap) without any further arguments
110
+%
111
+% REQUIRED INPUT ARGUMENTS
112
+%
113
+% sMap  (struct) Map to be shown. If only this argument is
114
+%                specified, the function draws first the u-matrix 
115
+%                calculated using all the variables followed by all
116
+%                the component planes.
117
+%
118
+% OPTIONAL INPUT ARGUMENTS
119
+% 
120
+% (M is the number of map units)
121
+%
122
+% Optional arguments must be given as 'argID',value -pairs
123
+% 
124
+% 'comp'      Defines the variabels to be shown as component planes.
125
+%    (vector) 1xN or Nx1 vector with integer positive numbers ranging 
126
+%             from 1 to the number of variables in the map codebook
127
+%             (dim). This vector determines the variables to be show
128
+%             as component planes and their order. Note that the same
129
+%             component plane (the same variable index) is allowed to
130
+%             occur several times.
131
+%    (string) 'all' or '' or []. This uses all variables, that is, it's
132
+%             the same that using value [1:dim] where dim is the
133
+%             number of variables in the codebook.
134
+%       
135
+% 'compi'     Same as 'comp' but uses a Gouraud shaded color plane 
136
+%             (made using SOM_GRID function) instead of the cell-like
137
+%             visualization of 'comp' (made using SOM_CPLANE). Note
138
+%             that the color interpolation doesn't work strictly
139
+%             correctly on 'hexa' grid, as it uses rectangular grid
140
+%             (see SURF).
141
+% 
142
+% 'umat'      Show U-matrix: value defines the variables to be used
143
+%             for calculating a u-matrix.
144
+%    (vector) as in 'comps'. However, multiple occurences of the
145
+%             same variable (same variable index) are ignored. 
146
+%    (string) 'all' or '' or []. This uses all variables, that is, 
147
+%             is the same as using value [1:dim] where dim is the
148
+%             number of variables in the codebook. 
149
+%    (cell)   of form {v, str} where v is a valid index vector for 'umat' 
150
+%             (see above) and str is a string that is used as a title 
151
+%             for the u-matrix instead of the default title
152
+%             'U-matrix'. This may be useful if several u-matrices
153
+%             are shown in the same figure. 
154
+% 
155
+% 'umati'     Same as 'umat' but uses shaded color plane (see 'compi').
156
+%
157
+% 'empty'     Show an empty plane (patch edges only)
158
+%    (string) value is used as title
159
+% 
160
+% 'color'     Define fixed RGB colors for the map units
161
+%    (matrix) a Mx3 matrix of RGB triples as rows             
162
+%    (vector) a Mx1 vector of any values: sets indexed coloring using
163
+%             the current colormap (as SURF does)  
164
+%    (matrix) a Mx3xN matrix of RGB triples as rows. This gives N
165
+%             color planes.
166
+%    (matrix) a Mx1xN matrix of any values: sets indexed coloring using
167
+%             the current colormap (as SURF does). This gives N
168
+%             color planes.
169
+%    (cell)   of form {rgb, str} where rgb is a Mx3 (xN) matrix of RGB
170
+%             triples as rows and str is a string that is used as
171
+%             title(s).  
172
+%    (cell)   of form {v, str} where v is a Mx1(xN) matrix of values
173
+%             and str is a string that is used as title(s). 
174
+%
175
+% 'colori'    Same as 'color' but uses shaded color plane (see 'compi').
176
+%
177
+% 'norm'      Defines whether to use normalized or denormalized
178
+%             values in the colorbar. If denormalized values are
179
+%             used, they are acquired from SOM_DENORMALIZE function 
180
+%             using sMap.comp_norm field.
181
+%    (string) 'd' (default) for denormalized values and 'n' for
182
+%             normalized values. The corresponding letter appears
183
+%             below the colorbar.
184
+%   
185
+% 'bar'       Define the direction of the colorbars for component planes 
186
+%             and U-matrices or turn them completely off.
187
+%    (string) 'vert' (default), 'horiz' or 'none'. 'vert' gives
188
+%             vertical and 'horiz' horizontal colorbars. 'none'
189
+%             shows no colorbars at all. 
190
+%
191
+% 'size'      Define sizes of the units. 
192
+%    (scalar) all units have the same size (1 by default)
193
+%    (vector) size Mx1, each unit gets individual size scaling 
194
+%             (as in SOM_CPLANE)
195
+%
196
+% 'edge'      Unit edges on component plane visualizations.
197
+%    (string) 'on' or 'off' determines whether the unit edges on component 
198
+%             planes ('comp') are shown or not. Default is 'off'. Note that
199
+%             U-matrix and color planes are _always_ drawn without edges.
200
+%
201
+% 'footnote'  Text on the figure
202
+%    (string) is printed as a movable text object on the figure
203
+%             where it may be moved using mouse. Default value is the
204
+%             string in the sMap.name field. Note: value [] gives the
205
+%             string, but input value '' gives no footnote a all. 
206
+%             See VIS_FOOTNOTE for more information on the text object 
207
+%             and ways to change its font size.
208
+% 
209
+% 'colormap'  som_show ghages the colormap by default to a gray-level map
210
+%    (matrix) This argument is used to set some other colormap. 
211
+%
212
+% 'subplots'  the number of subplots in y- and x-directions, as in 
213
+%    (vector) command SUBPLOT
214
+% 
215
+% OUTPUT ARGUMENTS
216
+%
217
+% h (struct)
218
+%    .plane         (vector) handles to the axes objects (subplots)
219
+%    .colorbar      (vector) handles to the colorbars. Colorbars of empty
220
+%                            & color planes do not exist: the corresponding
221
+%                            value in the vector is -1
222
+%    .label         (vector) handles to the axis labels
223
+%
224
+% OBJECT TAGS
225
+%
226
+% The property field 'Tag' of the axis objects created by this function 
227
+% are set to contain string 'Cplane' if the axis contains component plane
228
+% ('comp'), color plane ('color') or empty plane ('empty') and string
229
+% 'Uplane' if it contains a u-matrix ('umat'). The tag is set to 
230
+% 'CplaneI' for planes created using 'compi' and 'colori', and 
231
+% 'UplaneI' for 'umati'.
232
+%
233
+% FEATURES
234
+%
235
+% Note that when interpolated shading is used in coloring ('compi' and
236
+% 'colori') the standard built-in bilinear Gouraud interpolation for a 
237
+% SURF object is used. If the lattice is hexagonal - or anything else than 
238
+% rectangular in general - the result is not strictly what is looked 
239
+% for, especially if the map is small. 
240
+%
241
+% EXAMPLES
242
+%
243
+%% Make random data, normalize it, and give component names
244
+%% Make a map
245
+%
246
+%   data=som_data_struct(rand(1000,3),'comp_names',{'One','Two','Three'});
247
+%   data=som_normalize(data,'var');
248
+%   map=som_make(data);
249
+%
250
+%% Do the basic visualization with som_show: u-matrix and all
251
+%% component planes
252
+%
253
+%   som_show(map);   
254
+%
255
+%% The values shown in the colorbar are denormalized codebook values 
256
+%% (if denormalization is possible). To view the actual values, use
257
+%% the ..., 'norm', 'n' argument pair.
258
+%
259
+%   som_show(map,'norm','n')
260
+%
261
+%% Something more complex:
262
+%% Show 1-2. Component planes 1 and 2 (variables 'One' and 'Two')
263
+%%        3. U-matrix that is calculated only using variables
264
+%%           'One' and 'Two' 
265
+%%           with title '1,2 only'
266
+%%        4. U-matrix that is calculated using all variables with the 
267
+%%           deafult title 'U-matrix'
268
+%%        5. The color code (in c) with title 'Color code'
269
+%%        6. Component plane 3 (variable 'Three')
270
+%% and  use vertical colorbars and and the values      
271
+%% But first: make a continuous color code (see som_colorcode)
272
+%
273
+% c=som_colorcode(map,'rgb1');
274
+% 
275
+% som_show(map,'comp',[1 2],'umat',{1:2,'1,2 only'},'umat','all', ...
276
+%  'color',{c,'Color code'},'bar','vert','norm','n','comp',3)
277
+%
278
+%  SEE ALSO
279
+%
280
+% som_show_add   Show hits, labels and trajectories on SOM_SHOW visualization.
281
+% som_show_clear Clear hit marks, labels or trajectories from current figure. 
282
+% som_umat       Compute unified distance matrix of self-organizing map.
283
+% som_grid       Visualization of a SOM grid.
284
+% som_cplane     Visualization of component, u-matrix and color planes.
285
+
286
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
287
+% http://www.cis.hut.fi/projects/somtoolbox/             
288
+
289
+% Version 1.0beta johan 100298 
290
+% Version 2.0beta johan 201099 juuso 181199 johan 011299-100200
291
+%                 juuso 130300 190600
292
+
293
+%% Check arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
294
+
295
+error(nargchk(1,Inf,nargin))     % check no. of input args
296
+
297
+if isstruct(sMap),               % check map
298
+  [tmp,ok,tmp]=som_set(sMap);
299
+  if all(ok) & strcmp(sMap.type,'som_map') 
300
+    ;
301
+  else
302
+    error('Map struct is invalid!');
303
+  end
304
+else
305
+  error('Requires a map struct!')
306
+end
307
+
308
+munits=size(sMap.codebook,1); % numb. of map units
309
+d=size(sMap.codebook,2);      % numb. of components
310
+msize=sMap.topol.msize;       % size of the map
311
+lattice=sMap.topol.lattice;   % lattice
312
+
313
+if length(msize)>2 
314
+  error('This visualizes only 2D maps!')
315
+end
316
+
317
+if rem(length(varargin),2)
318
+  error('Mismatch in identifier-value  pairs.');
319
+end
320
+
321
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
322
+%  read in optional arguments
323
+ 
324
+if isempty(varargin),
325
+  varargin = { 'umat','all','comp','all'};
326
+end
327
+
328
+%% check the varargin and build visualization infostrcuts
329
+% Vis:       what kind of planes, in which order, what are the values in
330
+%            the units
331
+% Vis_param: general properties
332
+% see subfunction
333
+
334
+% The try-catch construction is here just for avoiding the
335
+% possible termination to happen in subfunction because an error
336
+% message containing subfunction line numbers etc. might be confusing, as
337
+% there probably is nothing wrong with the subfunction but with the 
338
+% input. Ok, this isn't proper programming sytle... 
339
+
340
+try       
341
+  [Plane, General]= check_varargin(varargin, munits, d, sMap.name);
342
+catch
343
+  error(lasterr);
344
+end
345
+
346
+% Set default values for missing ones
347
+
348
+% No planes at all (only general properties given in varargin):
349
+% set default visualization
350
+
351
+if isempty(Plane)
352
+  varargin = [varargin, { 'umat','all','comp','all'}];
353
+  % and again we go...
354
+  try
355
+    [Plane, General]= check_varargin(varargin, munits, d, sMap.name);
356
+  catch
357
+    error(lasterr);
358
+  end
359
+end
360
+
361
+% set defaults for general properties
362
+
363
+if isempty(General.colorbardir)
364
+  General.colorbardir='vert';
365
+end
366
+
367
+if isempty(General.scale)
368
+  General.scale='denormalized';
369
+end
370
+
371
+if isempty(General.size)
372
+  General.size=1;
373
+end
374
+
375
+if isempty(General.edgecolor)
376
+  General.edgecolor='none';
377
+end
378
+
379
+%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
380
+
381
+% get rid of an annoying warning: "RGB color data not yet supported in
382
+% Painter's mode."
383
+%set(gcf, 'renderer','zbuffer'); 
384
+%% -> a much more annoying thing results: the output to PostScript is 
385
+%%    as bitmap, making the files over 6MB in size... 
386
+
387
+n=length(Plane);                     % the number of subfigures
388
+
389
+% get the unique component indices
390
+c=General.comp(General.comp>0);
391
+c=setdiff(unique(c),[0 -1]); 
392
+c=c(~isnan(c));                   
393
+
394
+% estimate the suitable dimension for
395
+if isempty(General.subplots), 
396
+  y=ceil(sqrt(n));                   % subplots
397
+  x=ceil(n/y);
398
+else
399
+  y = General.subplots(2); 
400
+  x = General.subplots(1); 
401
+  if y*x<n, 
402
+    error(['Given subplots grid size is too small: should be >=' num2str(n)]); 
403
+  end    
404
+end
405
+
406
+clf;                               % clear figure
407
+
408
+for i=1:n,                         % main loop
409
+  h_axes(i,1)=subplot(x,y,i);      % open a new subplot
410
+  
411
+  % Main switch: select function according to the flags set in comps  
412
+
413
+  switch Plane{i}.mode
414
+  
415
+  case 'comp'
416
+    %%% Component plane
417
+
418
+    tmp_h=som_cplane(lattice,msize, sMap.codebook(:,General.comp(i)), ...
419
+		     General.size);
420
+    set(tmp_h,'EdgeColor', General.edgecolor);
421
+    set(h_axes(i),'Tag','Cplane');
422
+    h_label(i,1)=xlabel(sMap.comp_names{General.comp(i)});
423
+    
424
+
425
+  case 'compi'
426
+    %%% Component plane (interpolated shading)
427
+    
428
+    tmp_h=som_grid(lattice, msize, 'surf', sMap.codebook(:,Plane{i}.value), ...
429
+	'Marker', 'none', 'Line', 'none');
430
+    set(h_axes(i),'Tag','CplaneI');
431
+    h_label(i,1)=xlabel(sMap.comp_names(Plane{i}.value));
432
+    vis_PlaneAxisProperties(gca,lattice,msize,NaN);
433
+  
434
+  case 'color'
435
+    %%% Color plane
436
+
437
+    tmp_h=som_cplane(lattice,msize,Plane{i}.value,General.size);
438
+    set(tmp_h,'EdgeColor','none');
439
+    set(h_axes(i),'Tag','Cplane');
440
+    h_label(i,1)=xlabel(Plane{i}.name);
441
+    
442
+      
443
+  case 'colori'
444
+    %%% Color plane (interpolated shading)
445
+    
446
+    tmp_h=som_grid(lattice, msize, 'surf', Plane{i}.value, 'Marker', 'none', ...
447
+	'Line', 'none');
448
+    set(h_axes(i),'Tag','CplaneI');
449
+    h_label(i,1)=xlabel(Plane{i}.name);
450
+    vis_PlaneAxisProperties(gca,lattice,msize,NaN);
451
+  
452
+  case 'empty'      
453
+    %%% Empty plane
454
+    
455
+    tmp_h=som_cplane(lattice,msize,'none');
456
+    h_label(i,1)=xlabel(Plane{i}.name);
457
+    set(h_axes(i),'Tag','Cplane');
458
+    
459
+  case 'umat'
460
+    %%% Umatrix  
461
+    
462
+    u=som_umat(sMap.codebook(:,Plane{i}.value),sMap.topol,'median',...
463
+	'mask',sMap.mask(Plane{i}.value)); u=u(:);
464
+    tmp_h=som_cplane([lattice 'U'],msize,u);
465
+    set(tmp_h,'EdgeColor','none');
466
+    set(h_axes(i),'Tag','Uplane');
467
+    h_label(i,1)=xlabel(Plane{i}.name);
468
+
469
+  case 'umati'
470
+    %%% Umatrix (interpolated shading) 
471
+    
472
+    u=som_umat(sMap.codebook(:,Plane{i}.value),sMap.topol,'mean',...
473
+	'mask',sMap.mask(Plane{i}.value)); u=u(1:2:end,1:2:end);
474
+    u=u(:);
475
+    tmp_h=som_grid('rect', msize, 'surf', u, ...
476
+	'Marker', 'none', 'Line', 'none', ...
477
+	'coord', som_vis_coords(lattice,msize));
478
+    set(h_axes(i),'Tag','UplaneI');
479
+    h_label(i,1)=xlabel(Plane{i}.name);
480
+    vis_PlaneAxisProperties(gca,lattice,msize,NaN);
481
+    
482
+  otherwise
483
+    error('INTERNAL ERROR: unknown visualization mode.');
484
+  end
485
+
486
+  %%% Adjust axis ratios to optimal (only 2D!) and put the
487
+  %%% title as close to axis as possible
488
+
489
+  set(h_label,'Visible','on','verticalalignment','top');
490
+  set(gca,'plotboxaspectratio',[msize(2) msize(1) msize(1)]);
491
+  
492
+  %%% Draw colorbars if they are turned on and the plane is umat or c-plane
493
+
494
+  if General.comp(i)> -1 & ~strcmp(General.colorbardir,'none'),
495
+    h_colorbar(i,1)=colorbar(General.colorbardir);           % colorbars
496
+  else
497
+    h_colorbar(i,1)=-1;
498
+    General.comp(i)=-1;
499
+  end
500
+end         %% main loop ends
501
+  
502
+% Set window name
503
+
504
+set(gcf,'Name',[ 'Map name: ' sMap.name]);
505
+
506
+%% Set axes handles to the UserData field (for som_addxxx functions
507
+%% and som_recolorbar) 
508
+%% set component indexes and normalization struct for som_recolorbar
509
+
510
+SOM_SHOW.subplotorder=h_axes;
511
+SOM_SHOW.msize=msize;
512
+SOM_SHOW.lattice=lattice;
513
+SOM_SHOW.dim=d;
514
+SOM_SHOW.comps=General.comp;
515
+SOM_SHOW.comp_norm=sMap.comp_norm; %(General.comp(find(General.comp>0)));
516
+
517
+set(gcf,'UserData', SOM_SHOW);
518
+
519
+% Set text property 'interp' to 'none' in title texts
520
+
521
+set(h_label,'interpreter','none');
522
+
523
+h_colorbar=som_recolorbar('all', 3, General.scale);   %refresh colorbars
524
+
525
+% Set a movable text to lower corner pointsize 12.
526
+
527
+vis_footnote(General.footnote);  vis_footnote(12);  
528
+
529
+% set colormap
530
+colormap(General.colormap);
531
+
532
+%% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
533
+
534
+if nargout > 0
535
+  h.plane=h_axes; h.colorbar=h_colorbar; h.label=h_label;
536
+end
537
+
538
+
539
+%%%%%% SUBFUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
540
+
541
+function [Plane, General]=check_varargin(args, munits, dim, name)
542
+
543
+% args: varargin of the main function
544
+% munits: number of map units
545
+% dim: map codebook dimension
546
+% name: map name
547
+% Define some variables (they must exist later)
548
+
549
+Plane={};           % stores the visualization data for each subplot
550
+General.comp=[];    % information stored on SOM_SHOW figure (which component)
551
+General.size=[];            % unit size
552
+General.scale=[];           % normalization
553
+General.colorbardir=[];     % colorbar direction
554
+General.edgecolor=[];       % edge colors
555
+General.footnote=name;      % footnote text
556
+General.colormap=colormap;  % default colormap (used to be gray(64).^.5;)
557
+General.subplots=[];        % number of subplots in y- and x-directions
558
+
559
+for i=1:2:length(args),
560
+  %% Check that all argument types are strings
561
+  
562
+  if ~ischar(args{i}),
563
+    error('Invalid input identifier names or input argument order.');
564
+  end
565
+  
566
+  %% Lower/uppercase in identifier types doesn't matter: 
567
+  
568
+  identifier=lower(args{i});     % identifier (lowercase)
569
+  value=args{i+1};
570
+  
571
+  %%% Check first the identifiers that define planes and get values
572
+  %%% to the visualization data struct array Plane.
573
+  %%% (comps,compi,umat,color,empty) Note that name, value and comp_
574
+  %%% must be specified in these cases 
575
+  %%% comp_ are collected to comp in order. This is stored to the
576
+  %%% SOM_SHOW user property field to give information for SOM_RECOLROBAR
577
+  %%% how to operate, i.e., which component is in which subplot:
578
+  %%% comp(i)=0: draw colorbar, but no normalization (umat) 
579
+  %%% comp(i)=1...N: a component plane of variable comp(i)
580
+  %%% comp(i)=-1: no colorbar (color or empty plane)    
581
+  
582
+  switch identifier  
583
+   case {'comp','compi'}
584
+    %%% Component planes: check values & set defaults
585
+    
586
+    if ~vis_valuetype(value,{'nx1','1xn','string'}) & ~isempty(value),
587
+      error([ 'A vector argument or string ''all'' expected for ''' ...
588
+	      identifier '''.'])
589
+    end
590
+    if isempty(value) 
591
+      value=1:dim;
592
+    elseif ischar(value), 
593
+      if ~strcmp(value,'all')
594
+	error([ 'Only string value ''all'' is valid for ''' ...
595
+		identifier '''.']);
596
+      else
597
+	value=1:dim;
598
+      end
599
+    else
600
+      value=round(value);
601
+      if min(value)<1 | max(value)>dim,
602
+	error([ 'Component indices out of range in ''' identifier '''.']) 
603
+      end
604
+    end
605
+    if size(value,1)==1, value=value';end
606
+    comp_=value; 
607
+    name=[]; % name is taken form sMap by index in main loop 
608
+    
609
+  case {'umat','umati'}
610
+    %%% Check first the possible cell input
611
+    
612
+    if iscell(value),
613
+      if ndims(value) ~= 2 | any(size(value) ~= [1 2]) | ...
614
+	    ~vis_valuetype(value{2},{'string'}),
615
+	error('Cell input for ''umat'' has to be of form {vector, string}.');
616
+      else
617
+	name=value{2}; value=value{1};
618
+      end
619
+    else 
620
+      name='U-matrix'; % no cell: default title is set
621
+    end
622
+    if ~vis_valuetype(value,{'nx1','1xn','string'}) & ~isempty(value),
623
+      error('Vector, string ''all'', or cell {vector, string} expected for ''umat''.')
624
+    end
625
+    if isempty(value)
626
+      value=1:dim;
627
+    elseif ischar(value), 
628
+      if ~strcmp(value,'all')
629
+	error('Only string value ''all'' is valid for ''umat''.')
630
+      else
631
+	value=1:dim;
632
+      end
633
+    else
634
+      value=unique(round(value));
635
+    end
636
+    if min(value)<1 | max(value)>dim,
637
+      error('Component indices out of range in ''umat''.') 
638
+    end
639
+    
640
+    if size(value,1)==1, value=value';end
641
+    comp_=0;
642
+    
643
+  case 'empty'
644
+    %%% Empty plane: check values & set defaults
645
+    
646
+    if ~vis_valuetype(value,{'string'}), 
647
+      error('A string value for title name expected for ''empty''.');
648
+    end
649
+    name=value;
650
+    comp_=-1;
651
+    
652
+  case { 'color','colori'}
653
+    %%% Color plane: check values & set defaults
654
+    
655
+    % Check first the possible cell input
656
+    if iscell(value),
657
+      if ndims(value)~=2 | any(size(value) ~= [1 2]) | ...
658
+	    ~vis_valuetype(value{2},{'string'}),
659
+	error([ 'Cell input for ''' identifier ...
660
+	      ''' has to be of form {M, string}.']);
661
+      else
662
+	name=value{2}; value=value{1};
663
+      end
664
+    else 
665
+      name='Color code'; % no cell: default title is set
666
+    end
667
+    if size(value,1)~=munits | ...
668
+	  (~vis_valuetype(value,{'nx3rgb'}) & ... 
669
+	   ~vis_valuetype(value,{'nx1'}) & ...
670
+	   ~vis_valuetype(value,{'nx1xm'}) & ...
671
+	   ~vis_valuetype(value,{'nx3xdimrgb'})),
672
+      error(['Mx3 or Mx3xN RGBmatrix, Mx1 or Mx1xN matrix, cell '...
673
+	     '{RGBmatrix, string},' ...
674
+	     ' or {matrix, string} expected for ''' identifier '''.']);
675
+    end
676
+
677
+    % if colormap is fixed, we don't draw colorbar (comp_ flag is -1)
678
+    % if colormap is indexed, we draw colorbar as in umat (comp_=0)
679
+
680
+    if size(value,2)==3
681
+      comp_=-1;
682
+    else
683
+      comp_=0;
684
+    end
685
+    
686
+    %%%% The next things are general properties of the visualization---
687
+    %%%%
688
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
689
+    
690
+  case 'size'
691
+    %%% Unit size: check & set
692
+  
693
+    if ~vis_valuetype(value,{'1x1',[munits 1]})
694
+      error('A munits x 1 vector or a scalar expected for ''size''.')
695
+    end
696
+    if isempty(value),
697
+      General.size=1;
698
+    else
699
+      General.size=value;
700
+    end
701
+    
702
+   case 'bar'
703
+    %%% Colorbar existence & direction: check & set
704
+    
705
+    if ~vis_valuetype(value,{'string'})
706
+      error('String value expected for ''bar''.')
707
+    elseif isempty(value)
708
+      value='vert';
709
+    end
710
+    if any(strcmp(value,{'vert','horiz','none'})),
711
+      General.colorbardir=value;
712
+    else
713
+      error('String ''vert'', ''horiz'' or ''none'' expected for ''bar''.');
714
+    end
715
+    
716
+  case 'norm' 
717
+    %%% Value normalization: check & set
718
+    
719
+    if ~vis_valuetype(value,{'string'})
720
+      error('String ''n'' or ''d'' expected for ''norm''.');
721
+    elseif isempty(value)
722
+      value='n';
723
+    end
724
+    if strcmp(value(1),'n'), 
725
+      General.scale='normalized';
726
+    elseif strcmp(value(1),'d'),
727
+      General.scale='denormalized';
728
+    else
729
+      error('String ''n(ormalized)'' or ''d(enormalized)'' expected for ''norm''.');
730
+    end
731
+    
732
+  case 'edge'
733
+    %%% Edge on or off : check % set 
734
+    
735
+    if ~vis_valuetype(value,{'string'}) & ~isempty(value),
736
+      error('String value expected for ''edge''.')
737
+    elseif ~isempty(value),
738
+      switch value
739
+      case 'on'
740
+	General.edgecolor='k';
741
+      case 'off' 
742
+	General.edgecolor='none';
743
+      otherwise
744
+	error('String value ''on'' or ''off'' expected for ''edge''.')  
745
+      end
746
+    end
747
+    
748
+  case 'footnote'
749
+    %%% Set the movable footnote text  
750
+    
751
+    if ~vis_valuetype(value,{'string'}) 
752
+      if ~isempty(value),
753
+	error('String value expected for ''footnote''.');
754
+      else
755
+	General.footnote=sMap.name;
756
+      end
757
+    else
758
+      General.footnote=value;
759
+    end
760
+
761
+   case 'colormap'
762
+    %%% Set the colormap
763
+    if isempty(value)
764
+      General.colormap=gray(64).^2;
765
+    elseif ~vis_valuetype(value,{'nx3rgb'})
766
+      error('Colormap is invalid!');
767
+    else
768
+      General.colormap=value;
769
+    end
770
+    
771
+   case 'subplots'
772
+    %%% set the number of subplots
773
+    if ~vis_valuetype(value,{'1x2'}) & ~vis_valuetype(value,{'2x1'})
774
+      error('Subplots grid size is invalid!');
775
+    else
776
+      General.subplots=value; 
777
+    end
778
+    
779
+  otherwise
780
+    %%% Unknown identifier
781
+    
782
+    error(['Invalid argument identifier ''' identifier '''!']);
783
+  end
784
+  
785
+  %%% Set new entry to the Plane array if the indentifier means 
786
+  %%% making a new plane/planes
787
+  
788
+  tail=length(Plane);
789
+  switch identifier
790
+  case {'comp','compi'}
791
+    for i=1:length(value)
792
+      Plane{tail+i}.mode=identifier;
793
+      Plane{tail+i}.value=value(i);
794
+      Plane{tail+i}.name=name; % not used actually
795
+    end
796
+    General.comp = [General.comp; comp_];
797
+   case {'umat','umati','empty'}
798
+    Plane{tail+1}.mode=identifier;
799
+    Plane{tail+1}.value=value;
800
+    Plane{tail+1}.name=name;
801
+    General.comp = [General.comp; comp_];
802
+   case {'color','colori'},
803
+    for i=1:size(value,3),
804
+      Plane{tail+i}.mode=identifier;
805
+      Plane{tail+i}.name=[name '_' num2str(i)];
806
+      Plane{tail+i}.value=value(:,:,i);
807
+      General.comp = [General.comp; comp_];
808
+    end
809
+    if size(value,3)==1,
810
+      Plane{tail+1}.name=name;
811
+    end
812
+  otherwise
813
+    ; % do nothing
814
+  end
815
+end
... ...
@@ -0,0 +1,1610 @@
1
+function h=som_show_add(mode,D,varargin)
2
+
3
+%SOM_SHOW_ADD Shows hits, labels and trajectories on SOM_SHOW visualization
4
+%
5
+% h = som_show_add(mode, D, ['argID',value,...])
6
+%
7
+%  som_show_add('label',sMap)
8
+%  som_show_add('hit',som_hits(sMap,sD))
9
+%  som_show_add('traj',som_bmus(sMap,sD))
10
+%  som_show_add('comet',som_bmus(sMap,sD))
11
+%  som_show_add('comet',inds, 'markersize', [1 0.2])
12
+% 
13
+%  Input and output arguments ([]'s are optional): 
14
+%   mode    (string) operation mode 'label', 'hit', 'traj', 'comet'
15
+%   D       (varies) depending on operation mode
16
+%      In 'label' mode gives the labels  
17
+%           (struct) map struct, the .labels field of which is used
18
+%           (cell array of strings) size munits x number_of_labels
19
+%      In 'hit' mode gives the hit histogram(s)
20
+%           (matrix) size munits x k, if k>1, D gives hit histograms 
21
+%                    for k different sets of data (e.g. k classes).     
22
+%      In 'traj' and 'comet' modes gives the trace of the trajectory
23
+%           (vector) size N x 1, D(1) is the current and D(end) 
24
+%                    is oldest item of the trajectory
25
+%   [argID, (string) Additional arguments are given as argID, value
26
+%    value] (varies) pairs. Depend on the operation mode (see below).                   
27
+%
28
+%   h    (vector)    handles to the created objects
29
+%
30
+% Here are the valid argument IDs and corresponding values. Most of 
31
+% them depend on the operation mode: 
32
+%
33
+% all modes
34
+%   'SubPlot'   (vector) which subplots are affected (default: current)
35
+%               (string) 'all': all subplots are affected 
36
+% mode = 'label'
37
+%   'TextSize'  (scalar) text size in points
38
+%   'TextColor' (string) ColorSpec, 'xor' or 'none': label color 
39
+%
40
+% mode = 'hit'
41
+%   'EdgeColor'  (string) ColorSpec, 'none' 
42
+%   'MarkerSize' (scalar) maximum marker size
43
+%  if k == 1, 
44
+%   'Marker'     (string) 'lattice', Matlab's built-in markerstyles, 'none'
45
+%   'MarkerColor'(string) Colorspec, 'none': fill color for markers
46
+%   'Text'       (string) 'on', 'off':  whether to write the number of hits
47
+%   'TextColor'  (string) ColorSpec, 'xor': text color if Text is 'on'
48
+%   'TextSize'   (scalar) text font size in points if Text is 'on'
49
+%  if k > 1, 
50
+%   'SizeFactor' (string) 'common', 'separate': size scaling
51
+%   'Marker'     (string) 'lattice', Matlab's built-in markerstyles, 'pie', 'none' 
52
+%                (cell array) size k x 1, marker style for each histogram
53
+%   'MarkerColor'(string) Colorspec, 'none': fill color for markers
54
+%                (matrix) size k x 3, color for each histogram
55
+%
56
+% mode = 'traj'
57
+%   'TrajWidth'  (scalar) basic trajectory line width in points
58
+%   'WidthFactor'(string) 'hit' or 'equal': effect of hits on line width 
59
+%   'TrajColor'  (string) ColorSpec, 'xor': color for trajectory line
60
+%   'Marker'     (string) 'lattice', Matlab's built-in markerstyles, 'none'
61
+%   'MarkerSize' (scalar) basic marker size (in points)
62
+%   'SizeFactor' (string) 'equal', 'hit' (equal size/size depends on freq.) 
63
+%   'MarkerColor'(string) Colorspec, 'none': color of markers
64
+%   'EdgeColor'  (string) ColorSpec, 'none': edgecolor of markers 
65
+%
66
+% mode = 'comet'
67
+%   'Marker'     (string) 'lattice', Matlab's built-in markerstyles
68
+%   'MarkerColor'(string) ColorSpec, 'none': color for the markers
69
+%                (matrix) size N x 3, RGB color for each step 
70
+%   'EdgeColor'  (string) ColorSpec, 'none': edgecolor for markers
71
+%   'MarkerSize' (vector) size 1 x 2, size of comet core and tail
72
+% 
73
+% For more help, try 'type som_show_add' or check out online documentation.
74
+% See also SOM_SHOW.
75
+
76
+%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
77
+%
78
+% som_show_add 
79
+%
80
+% PURPOSE 
81
+%
82
+%  Shows hits, labels and trajectories on SOM_SHOW visualization
83
+%
84
+% SYNTAX
85
+%
86
+%  h = som_show_add(mode, D); 
87
+%  h = som_show_add(..., 'argID', value);
88
+%
89
+% DESCRIPTION 
90
+%
91
+% The SOM_SHOW function makes the basic visualization of the SOM.
92
+% With SOM_SHOW_ADD one can set labels, hit histogarms or different 
93
+% trajectories on this visualization.
94
+%
95
+%  labels (mode = 'label')
96
+%
97
+% Labels are strings describing the units. They may be, e.g., a result
98
+% of SOM_AUTOLABEL function. Labels are centered on the unit so that
99
+% multiple labels are in a column.
100
+%
101
+%  hit histograms (mode = 'hit')
102
+%
103
+% Hit histograms indicate how the best matching units of a data
104
+% set/some data sets are distribited on a SOM. The hit histogram can
105
+% be calculated using function SOM_HITS.
106
+%
107
+%  trajectories (mode = 'traj' or mode = 'comet')
108
+%
109
+% Trajectories show the best matching units for a data set that is
110
+% time (or any ordered) series. It may be either a line connecting the
111
+% consecutive best matching units ('traj' mode) or a "comet"
112
+% trajectory where the current (first sample in D) best matching unit
113
+% has biggest marker and the oldest (last sample) has smallest
114
+% marker ('comet' mode).
115
+%
116
+% NOTE: that the SOM_SHOW_ADD function can only be applied to
117
+% figures that have been drawn by SOM_SHOW.
118
+% 
119
+% KNOWN BUGS
120
+%
121
+% for 'hit' mode, if the given hit matrix is all zeros, a series of 
122
+% error messages is generated
123
+% 
124
+% REQUIRED INPUT ARGUMENTS
125
+%
126
+% mode     (string) Visuzalization mode 
127
+%                   'label'  map labeling
128
+%                   'hit'    hit histograms
129
+%                   'traj'   line style trajectory
130
+%                   'comet'  comet style trajectory 
131
+%
132
+% D (vector, map struct, cell array of strings) Data
133
+%
134
+% The valid value of D depends on the visualization mode:
135
+%
136
+%  Mode       Valid D
137
+%  'label'    map struct or Mxl cell array of strings, where
138
+%              M is number of map units and l maximum numer of
139
+%              labels in unit.
140
+%
141
+%  'hit'      Mx1 vector or MxK matrix, where M is number of map
142
+%             units and K is number of hit histograms (of K
143
+%             different classes of data) to be shown
144
+%
145
+%  'comet'    Lx1 vector of best matchig unit indices that have to
146
+%  'traj'     be in range of the map that is in the figure. L is 
147
+%             the length of trajectory
148
+%             
149
+% OPTIONAL INPUT ARGUMENTS
150
+%
151
+% Optional arguments must be given as 'argument identifier', value
152
+% -pairs. This section is divided in four parts because each mode
153
+% functions in a different way, though they may have same identifier
154
+% names.
155
+%
156
+% If user specifies an identifier that is not operational in the
157
+% specified mode, the functions gives a warning message. If the
158
+% identifier does not exist in any mode the execution is terminated
159
+% and an error message is returned.
160
+%
161
+% GENERAL OPTIONAL INPUT ARGUMENTS (in all modes)
162
+%
163
+% 'SubPlot'     Target subplots in the figure    
164
+%      (vector) Subplots' ordinal numbers in a vector. By default
165
+%               the target is the current subplot (see GCA).
166
+%      (string) String 'all' means all subplots. 
167
+%
168
+% 'Marker'      Data marker (not in use in 'label' mode)
169
+%      (string) 'none': sets the markers off
170
+%               'lattice': sets the marker shape according to the
171
+%                lattice of the underlying map, i.e. it gives
172
+%                rectangles if underlying map lattice is 'rect' and
173
+%                hexagons for 'hexa', respectively
174
+%               any of the Matlab's built-in marker styles: 'o', 's',
175
+%               'd', 'v', '^', '<' ,'> ', 'p', 'h', 'x', '.', '*', '+'
176
+%      
177
+%               NOTE that '.','x','+' or '*' are not recommended since
178
+%               they have only edgecolor and many visualizations are 
179
+%               based on _face_ color. 
180
+%
181
+%               NOTE there is an important difference between built-in
182
+%               markers. If figure size is changed the 'lattice'
183
+%               markers are rescaled but the built-in markers stay at
184
+%               fixed size, and consequently, the size unit for
185
+%               'lattice' markers is normalized but for built-in
186
+%               markers the size is given in points. For 'lattice'
187
+%               markers size 1 means the size of the map unit.
188
+%
189
+%               NOTE that in 'hit' mode there are some additional features.
190
+%
191
+% 'EdgeColor'   Sets edgecolor for the markers (not in use in 'label' mode)
192
+%      (string) ColorSpec, e.g. 'r',  gives each edge the specified color
193
+%               'none': sets markers edges invisible 
194
+%               Default is 'none' - except if MarkerColor is set to 'none' the
195
+%               defaults is 'black'.
196
+%
197
+% OPTIONAL INPUT ARGUMENTS mode 'label'
198
+%
199
+% Labels are centered on the unit so that multiple labels are in
200
+% a single column.
201
+%
202
+% 'SubPlot'     see General Optional Input Arguments 
203
+%
204
+% 'TextSize'    Text size for labels
205
+%      (scalar) Text size in points. Default is 10.
206
+%
207
+% 'TextColor'   Text color
208
+%      (string) ColorSpec specifies the text color for all labels 
209
+%               'xor': gives Matlab's "xor" text color mode where the 
210
+%                label color depends on background color     
211
+%               'none': sets labels invisble (but creates the objects)
212
+%
213
+% OPTIONAL INPUT ARGUMENTS mode 'hit'
214
+%
215
+% The function in mode 'hit' depends on the input argument size. If
216
+% only one hit histogram is drawn (K==1), it is possible to show the
217
+% hits using numbers. This is not possible for multiple hit
218
+% histograms (K>1).
219
+%
220
+% 'SubPlot'     see General Optional Input Arguments 
221
+%        
222
+% 'Marker'      Marker style(s)
223
+%      (string) As in General Optional Input Arguments. In addition 
224
+%               'pie': sets pie charts for markers. The size of the
225
+%                pie in each unit describes the number of total hits in the
226
+%                unit and the share of each sector is the relative amount of
227
+%                hits in each class (requires multiple histograms). Color for
228
+%                each class is set by MarkerColor. Default coloring 
229
+%                is hsv(K), where K is the number of hit histograms (classes).
230
+%      (cell array) size K x 1, of built-in marker style characters. K is
231
+%               number of histograms (classes), i.e., same as size(D,2)
232
+%               where D is the second input argument. Cell value is
233
+%               valid only if multiple histograms are specified (K>1). 
234
+% 
235
+%               NOTE if multiple histograms (classes) are specified
236
+%               and Marker is one of the built-in marker styles or
237
+%               'lattice', the markers are drawn in size order from
238
+%               largest to smallest. This insures that all markers are
239
+%               visible (or at least their edges are). But if two
240
+%               markers for different classes in the same node were of
241
+%               same size, the other would be totally hidden. In order
242
+%               to prevent this, the markers for different classes are
243
+%               shifted different amounts from the exact centre of the
244
+%               unit. (Evidently, if Marker is 'pie' this problem does
245
+%               not exist.)
246
+%
247
+%               Default marker is 'lattice' for one histogram and
248
+%               'pie' for multiple histograms.
249
+%
250
+% 'MarkerColor' Marker color(s) 
251
+%      (string) ColorSpec gives all markers the same color
252
+%               'none': leaves the markes transparent (only edges are visible)
253
+%      (matrix) size K x 3, RGB triples for each histogram class
254
+%               giving each hit histogram an own color
255
+%
256
+%               NOTE that markers '*','+','x', or '.' cannot use 
257
+%               MarkerColor since these objects have no face (fill)
258
+%               color. For them only EdgeColor matters.
259
+% 
260
+% 'MarkerSize'  Maximum size for marker
261
+%      (scalar) set the _maximum_ marker size that corresponds to
262
+%               maximum hit count. If Marker is 'pie' or 'lattice' the 
263
+%               MarkerSize is in normalized scale: 1 correspons to unit size.
264
+%               If Marker is one of the built-in styles, MarkerSize is given
265
+%               in points.  
266
+%               
267
+%               Marker        Default MarkerSize  
268
+%               'lattice'      1 (normalized units)
269
+%               'pie'          1 (normalized units) 
270
+%               'o','s', etc.  6 (points)
271
+%
272
+% 'SizeFactor'  Defines the scaling of the marker sizes in multiple
273
+%               histogram case (when Marker is one of the built-in marker 
274
+%               styles or 'lattice').
275
+%      (string) 'separate' (the default) means that marker size shows 
276
+%                the share of the data which hits the unit compared to 
277
+%                amount of data in that class. That is, the size of
278
+%                markers show the relative distribution of data on the map 
279
+%                in each class separately. The maximum size is SizeFactor.       
280
+%               'common' means that marker size shows the distribution of
281
+%                the data in the different classes compared to 
282
+%                _the total amount of data_. 
283
+%
284
+% 'EdgeColor'   Sets edgecolor for the markers, see General
285
+%               Optional Input Arguments. Default is 'none' -
286
+%               except if MarkerColor is 'none' or Marker is
287
+%               'x','*,'x', or '.'. In these cases default EdgeColor is 'black'. 
288
+%
289
+% 'Text'        Write/don't write the number of hits on the
290
+%               units. This option is not in use for multiple histograms.
291
+%      (string) 'on' or 'off' (the default)
292
+%
293
+% 'TextColor'   Text color 
294
+%      (string) ColorSpec gives each letter the same color
295
+%               'xor' gives a "xor" coloring for the text
296
+%
297
+% 'TextSize'    Text size (in points)    
298
+%      (scalar) text size in points, default is 10
299
+%
300
+% OPTIONAL INPUT ARGUMENTS mode 'traj'
301
+%
302
+% Input D is a Nx1 vector of N BMU indices that describe the trace of the 
303
+% comet. First element D(1) is "newest" and D(end) "oldest". Note
304
+% that at least two indeces are expected: size of D must be at
305
+% least 2x1.
306
+%
307
+% 'SubPlot'     see General Optional Input Arguments
308
+%
309
+% 'TrajColor'   Color for trajectory line
310
+%      (string) ColorSpec gives each marker the same color, 'w' by default
311
+%               'none' sets the marker fill invisible: only edges are shown
312
+%
313
+% 'TrajWidth'   Maximum width of trajectory line
314
+%      (scalar) width in points. Default is 3.
315
+%
316
+% 'WidthFactor' Shows how often edge between two units has been traversed.
317
+%      (string) 'hit': the size of the marker shows how frequent the
318
+%                trajectory visits the unit (TrajWidth sets the
319
+%                maximum size). This is the default.
320
+%               'equal': all lines have the same width (=TrajWidth)
321
+%
322
+% 'Marker'      Marker style, see General Optional Input
323
+%               Arguments. Default is 'o'.
324
+%    
325
+%               NOTE Marker style 'lattice' is not valid in mode 'traj'.
326
+%               NOTE Markers can be turned off by setting MarkerSize to zero.
327
+%
328
+% 'MarkerSize'  Maximum size of markers
329
+%      (scalar) Default is 12 (points).
330
+%
331
+% 'SizeFactor'  Sets the frequency based marker size or constant marker size.                  
332
+%      (string) 'hit': the size of the marker shows how frequent the
333
+%                trajectory visits the unit (MarkerSize sets the
334
+%                maximum size). This is the default.
335
+%               'equal': all markers have th esame size (=MarkerSize)
336
+%
337
+% 'MarkerColor' The fill color(s) for hit markers
338
+%      (string) ColorSpec gives each marker the same color, default is 'w'
339
+%               'none' sets the marker fill invisible: only edges are shown
340
+%
341
+%               NOTE markers '*','+','x', or '.' can't use MarkerColor since
342
+%               these objects have no face (fill) color: only EdgeColor
343
+%               matters for these markers.
344
+% 
345
+% 'EdgeColor'   see General Optional Input Arguments. Default is
346
+%               'none' - except if MarkerColor is 'none' or Marker
347
+%               is 'x','*','x', or '.'. In these cases default
348
+%               EdgeColor is 'white'. 
349
+%
350
+% OPTIONAL INPUT ARGUMENTS mode 'comet'
351
+%
352
+% Input D is a Nx1 vector of N BMU indices that describe the trace of
353
+% the comet. First element D(1) is "newest" and D(end) "oldest". Note
354
+% that at least two indeces are expected: size of D must be at least
355
+% 2x1.
356
+%
357
+% 'SubPlot'     see General Optional Input Arguments 
358
+%
359
+% 'Marker'      Marker style, see General Optional Input
360
+%               Arguments. Default is 'lattice'.
361
+%
362
+% 'MarkerColor' The fill color(s) for comet markers
363
+%      (string) ColorSpec gives each marker the same color, default is 'w'
364
+%               'none' sets the marker fill invisible: only edges are shown 
365
+%      (matrix) size N x 3, consisting of RGB triples as rows 
366
+%               sets different color for each marker. This may be
367
+%               used to code the time series using color/grayscale.
368
+%
369
+%               NOTE Markers '*','+','x', or '.' can't use MarkerColor
370
+%               since these objects have no face (fill) color: only 
371
+%               EdgeColor matters for these markers.
372
+% 
373
+% 'EdgeColor'   see General Optional Input Arguments. Default is
374
+%               'none' - except if MarkerColor is 'none' or Marker
375
+%               is 'x','*,'x', or '.'. In these cases default 
376
+%               EdgeColor is 'white'. 
377
+%
378
+% 'MarkerSize'  The size of "comet core" and tail 
379
+%      (vector) size 1 x 2: first element sets the size for the marker
380
+%               representing D(1) and the second set size for D(end)
381
+%               the size (area) of the markes between these changes linearly.
382
+%               Note that size units for 'lattice' marker style are
383
+%               normalized so that 1 means map unit size but for built-in
384
+%               marker styles the size is given points.
385
+%
386
+%               Marker          default value
387
+%               'lattice'        [0.8 0.1]
388
+%               'o','v', etc.    [20 4]
389
+%
390
+% OUTPUT ARGUMENTS
391
+%
392
+% h (vector) handles to all objects created by the function
393
+% 
394
+% OBJECT TAGS
395
+%
396
+%  Field Tag in every object is set to
397
+%
398
+%   'Lab'  for objects created in mode 'label'
399
+%   'Hit'                -"-           'hit'
400
+%   'Traj'               -"-           'traj'
401
+%   'Comet'              -"-           'comet'
402
+%
403
+% EXAMPLES
404
+%
405
+% Not yet ready
406
+%
407
+% SEE ALSO
408
+%             
409
+%  som_show       Basic map visualization
410
+%  som_show_clear Clear hit marks, labels or trajectories from current figure. 
411
+
412
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
413
+% http://www.cis.hut.fi/projects/somtoolbox/             
414
+
415
+% Version 2.0beta Johan 131199
416
+
417
+%% Check arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
418
+
419
+error(nargchk(2,Inf,nargin))     % check no. of input args
420
+
421
+% Get data from the SOM_SHOW figure, exit if error
422
+
423
+[handles,msg,lattice,msize,dim]=vis_som_show_data('all',gcf);    
424
+error(msg);                    
425
+
426
+munits=prod(msize);
427
+% Initialize some variables: these must exist later; 
428
+% the default values are set by subfunctions
429
+
430
+Property=init_properties;
431
+Property.handles=handles; 
432
+
433
+%%% Check mode and that D is of right type & size for that mode 
434
+% mode has to be string
435
+if ~vis_valuetype(mode,{'string'}),
436
+  error('String value expected for first input argument (mode).');
437
+else                
438
+  mode=lower(mode); % case insensitive
439
+  mode_=mode;       % 'mode' is internal variable; 
440
+                    % for program constructs 'mode_' is shown to
441
+                    % user in some error messags
442
+end
443
+
444
+switch mode         % check mode
445
+ case 'hit'
446
+  %%% Hit histogram visualization: vector [msize k]
447
+ 
448
+  if ~vis_valuetype(D,{'nxm'}),
449
+    error('Hit visualization: a matrix expected for data input.');
450
+  elseif size(D,1) ~= prod(msize)
451
+    error('Hit visualization: data and map size do not match.');
452
+  end
453
+  % Multiple hit histograms
454
+  if size(D,2)>1
455
+    mode='mhit';
456
+    % Hit count musn't be negative
457
+    if any(D(:)<0),
458
+      error('Hit visualization: negative hit count in data not allowed!');
459
+    end
460
+  end
461
+ 
462
+ case {'traj','comet'}
463
+  %%% Trajectory like visualizations
464
+  
465
+  if ~vis_valuetype(D,{'nx1'}),
466
+    error('Trajectory/Comet: a Nx1 vector expected for data input.');
467
+  elseif any(D>prod(msize))| any(D<1),
468
+    error('Trajectory/Comet: BMU indices out of range in data input.');
469
+  elseif any(fix(D)~=D),
470
+    warning('Trajectory/Comet: BMU indices not integer. Rounding...');
471
+  elseif size(D,1)<2
472
+    error('At least two BMU indexes expected.');
473
+  end
474
+  
475
+ case  'label' 
476
+  %%% Label visualizations
477
+  
478
+  if isstruct(D),                  % check if D is a map
479
+    [tmp,ok,tmp]=som_set(D);
480
+    if all(ok) & strcmp(D.type,'som_map') 
481
+      ;
482
+    else
483
+      error('Map struct is invalid!');
484
+    end
485
+    % Size check
486
+    if length(msize) ~= length(D.topol.msize) | ...
487
+	  munits ~= prod(D.topol.msize),
488
+      error(['The size of the input map and the map in the figure' ...
489
+	     ' do not match.']);
490
+    end
491
+    D=D.labels;
492
+    % Cell input  
493
+  elseif vis_valuetype(D,{'2Dcellarray_of_char'}) 
494
+    ;
495
+    % Char input   
496
+  elseif vis_valuetype(D,{'char_array'}),
497
+    D=cellstr(D);
498
+  else
499
+    error(['Labels has to be in a map struct or in a cell array' ...
500
+	   ' of strings']);
501
+  end
502
+  if size(D,1) ~= munits
503
+    error(['The number of labels does not match the size of the map' ...
504
+	   ' in the figure.']);
505
+  end
506
+ otherwise
507
+  error('Invalid visualization mode.');
508
+end  
509
+
510
+if rem(length(varargin),2)
511
+  error('Mismatch in identifier-value pairs or wrong input argument order.');
512
+end
513
+
514
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
515
+%  read in optional arguments
516
+
517
+for i=1:2:length(varargin),
518
+  %% Check that all argument types are strings
519
+  
520
+  if ~ischar(varargin{i})
521
+    error('Invalid identifier name or input argument order.');
522
+  end
523
+  
524
+  %% Lower/uppercase in identifier types doesn't matter: 
525
+  
526
+  identifier=lower(varargin{i});     % identifier (lowercase)
527
+  value=varargin{i+1};
528
+  
529
+  % Check property identifiers and values and store the values.
530
+  % Struct used_in is set to initiate warning messages:
531
+  % if a don't care propersty is set, the user is warned.
532
+  
533
+  switch identifier  
534
+   case 'marker'
535
+    %%% Marker for hits or trajectories
536
+    switch mode
537
+     case 'mhit'
538
+      if vis_valuetype(value,{'markerstyle'}) | ...
539
+	    (vis_valuetype(value,{'string'}) & ...
540
+	     any(strcmp(value,{'lattice','pie'}))),
541
+	; % ok
542
+      elseif vis_valuetype(value,{'cellcolumn_of_char'}),
543
+	if size(value,1) ~= size(D,2)
544
+	  error([' If a cell of Markers is specified its size must be' ...
545
+		 ' number_of_hit_histograms x 1.']);
546
+	else
547
+	  for i=1:size(D,2),
548
+	    if ~vis_valuetype(value{i},{'markerstyle'})
549
+	      error('Cell input for ''Marker'' contains invalid styles.')
550
+	    end
551
+	  end
552
+	end
553
+      else
554
+	error([' Invalid ''Marker'' in case of multiple hit histograms.' ...
555
+	       char(10) ' See detailed documentation.'])
556
+      end
557
+     case {'comet','hit'}
558
+      if vis_valuetype(value,{'markerstyle'}) | isempty(value),
559
+	% ok;
560
+      elseif ischar(value) & strcmp(value,'lattice'),
561
+	% ok;
562
+      else
563
+	error(['Marker must be Matlab''s marker style, or string' ...
564
+	       ' ''lattice''.']);
565
+      end
566
+     case 'traj'
567
+      if ~vis_valuetype(value,{'markerstyle'}) & ~isempty(value),
568
+	error('In mode ''traj'' Marker must be one of Matlab''s built-in marker styles');
569
+      end
570
+    end
571
+    used_in.comet=1;           % Set relevance flags
572
+    used_in.traj=1;
573
+    used_in.label=0;
574
+    used_in.hit=1;
575
+    used_in.mhit=1;
576
+    
577
+   case 'markersize'
578
+    %%% Marker for hits or trajectories
579
+    switch mode 
580
+     case 'comet'
581
+      if ~vis_valuetype(value,{'1x2'}) & ~isempty(value), 
582
+	error('In mode ''comet'' MarkerSize'' must be a 1x2 vector.');
583
+      end
584
+     case {'hit','traj'}
585
+      if ~vis_valuetype(value,{'1x1'}) & ~isempty(value), 
586
+	error(['In mode ''' mode_ ...
587
+	       ''' ''MarkerSize'' must be a scalar.']);
588
+      end
589
+    end
590
+    used_in.comet=1;           % Set relevance flags
591
+    used_in.traj=1;
592
+    used_in.label=0;
593
+    used_in.hit=1;
594
+    used_in.mhit=1;
595
+    
596
+   case 'sizefactor'   
597
+    %%% Hit dependent size factor
598
+    switch mode
599
+     case 'traj'
600
+      if ~vis_valuetype(value,{'string'}) | ...
601
+	    ~any(strcmp(value,{'hit', 'equal'})),
602
+	error(['In mode ''traj'' ''SizeFactor'' must be ' ...
603
+	       'string ''equal'' or ''hit''.']);
604
+      end
605
+     case 'mhit'
606
+      if ~vis_valuetype(value,{'string'}) | ...
607
+	    ~any(strcmp(value,{'common', 'separate'})),
608
+	error(['In mode ''hit'' ''SizeFactor'' must be ' ...
609
+	       'string ''common'' or ''separate''.']);
610
+      end
611
+    end
612
+    used_in.comet=0;           % Set relevance flags
613
+    used_in.traj=1;
614
+    used_in.label=0;
615
+    used_in.hit=0;
616
+    used_in.mhit=1;
617
+    
618
+   case 'markercolor'
619
+    %%% Markercolor
620
+    switch mode
621
+     case 'comet' 
622
+      if ~vis_valuetype(value,{'colorstyle','1x3rgb'}) & ...
623
+	    ~vis_valuetype(value,{'nx3rgb',[size(D,1) 3]},'all') & ...
624
+	    ~isempty(value),
625
+	error(['MarkerColor in mode ''comet'' must be a ColorSpec,' ...
626
+	       ' string ''none'' or Mx3 matrix of RGB triples.']);
627
+      end
628
+     case 'mhit'
629
+      if ~vis_valuetype(value,{[size(D,2) 3],'nx3rgb'},'all') & ...
630
+	    ~vis_valuetype(value,{'colorstyle','1x3rgb'}),
631
+	error([' If multiple hit histograms in mode ''hit'' are' ...
632
+	       char(10) ...
633
+	       ' given MarkerColor must be ColorSpec or a Kx3 matrix' ...
634
+	       char(10)...
635
+	       ' of RGB triples where K is the number of histograms.']);
636
+      end
637
+     case 'hit'
638
+      if ~vis_valuetype(value,{'colorstyle','1x3rgb'}) & ...
639
+	    ~isempty(value),
640
+	error(['MarkerColor in mode ''hit'' ' ...
641
+	       'must be a ColorSpec or string ''none''.']);
642
+      end
643
+     case 'traj'
644
+      if ~vis_valuetype(value,{'colorstyle','1x3rgb'}) & ...
645
+	    ~isempty(value),
646
+	error(['MarkerColor in mode ''traj'' ' ...
647
+	       'must be a ColorSpec or string ''none''.']);
648
+      end
649
+    end
650
+    
651
+    used_in.comet=1;           % Set relevance flags
652
+    used_in.traj=1;
653
+    used_in.label=0;
654
+    used_in.hit=1;
655
+    used_in.mhit=1;
656
+    
657
+   case 'edgecolor'
658
+    %%% Color for marker edges
659
+    if ~vis_valuetype(value,{'colorstyle','1x3rgb'}) & ~isempty(value),
660
+      error('''EdgeColor'' must be a ColorSpec or string ''none''.')
661
+    end
662
+    
663
+    used_in.comet=1;           % Set relevance flags
664
+    used_in.traj=1;
665
+    used_in.label=0;
666
+    used_in.hit=1;
667
+    used_in.mhit=1;
668
+    
669
+   case 'text'
670
+    %%% Labeling for trajectories/hits
671
+    switch mode
672
+     case 'hit'
673
+      %%% Hit count using numbers?
674
+      if isempty(value),
675
+	value='off';
676
+      elseif vis_valuetype(value,{'string'}) & ...
677
+	    ~any(strcmp(value,{'on','off'})),
678
+	error('Value for Text in mode ''hit'' should be ''on'' or ''off''.');
679
+      else
680
+	; % ok
681
+      end
682
+     %case 'traj','comet'
683
+     % if ~vis_valuetype(value,{'char_array','cellcolumn_of_char'}) & ...
684
+     %	    ~isempty(value)
685
+     %	 error('Value for Text is of wrong type or size.')
686
+     % elseif ischar(value)
687
+     %	value=strcell(value) % ok, convert to cell
688
+     % end
689
+     % if size(traj_label,1)~=size(D,1)
690
+     %	error(['The number of labels in Text and the length of the' ...
691
+     % 	       ' trajectory do not match.']);
692
+     % end
693
+     case 'label'
694
+      ; % not used
695
+    end
696
+    used_in.comet=0;            % Set relevance flags
697
+    used_in.traj=0;
698
+    used_in.label=0;
699
+    used_in.hit=1;
700
+    used_in.mhit=0;
701
+    
702
+   case 'textsize'
703
+    %%% Text size for labels
704
+    
705
+    if ~vis_valuetype(value,{'1x1'}) & ~isempty(value), 
706
+      error('TextSize must be scalar.');
707
+    end
708
+    used_in.comet=0;            % Set relevance flags
709
+    used_in.traj=0;
710
+    used_in.label=1;
711
+    used_in.hit=1;
712
+    used_in.mhit=0;
713
+    
714
+   case 'textcolor'
715
+    %%% Color for labels
716
+    
717
+    if ~vis_valuetype(value,{'colorstyle','1x3rgb','xor'}) & ~isempty(value),
718
+      error('''TextColor'' must be ColorSpec, ''xor'' or ''none''.')
719
+    end
720
+    used_in.comet=0;            % Set relevance flags
721
+    used_in.traj=0;
722
+    used_in.label=1;
723
+    used_in.hit=1;
724
+    used_in.mhit=0;
725
+    
726
+   case 'trajwidth'
727
+    %%% Basic line width for a line trajectory
728
+    if ~vis_valuetype(value,{'1x1'}) & ~isempty(value), 
729
+      error('TrajWidth must be a scalar.');
730
+    end
731
+    used_in.comet=0;            % Set relevance flags
732
+    used_in.traj=1; 
733
+    used_in.label=0;
734
+    used_in.hit=0;
735
+    used_in.mhit=0;
736
+    
737
+   case 'widthfactor'
738
+    %%% Hit factor for a line trajectory
739
+    if ~vis_valuetype(value,{'string'}) | ...
740
+	  ~any(strcmp(value,{'hit', 'equal'})),
741
+      error(['In mode ''traj'' ''WidthFactor'' must be ' ...
742
+	     'string ''equal'' or ''hit''.']);
743
+    end
744
+    used_in.comet=0;            % Set relevance flags
745
+    used_in.traj=1;
746
+    used_in.label=0;
747
+    used_in.hit=0;
748
+    used_in.mhit=0;
749
+    
750
+   case 'trajcolor'
751
+    %%% Color for trajectory line
752
+    
753
+    if ~vis_valuetype(value,{'colorstyle','1x3rgb','xor'}) & ~isempty(value),
754
+      error('''TrajColor'' must be a ColorSpec or string ''xor''.')
755
+    end
756
+    used_in.comet=0;            % Set relevance flags
757
+    used_in.traj=1;
758
+    used_in.label=0;
759
+    used_in.hit=0;
760
+    used_in.mhit=0;
761
+    
762
+   case 'uselabel' 
763
+    %%% Which labels to show
764
+    error('Not yet implemented.');
765
+   
766
+   case 'shift'
767
+    if ~vis_valuetype(value,{'1x1'}) | ((value < 0) | (value > 1)),
768
+      error('''Shift'' must be a scalar in range [0,1].')
769
+    end
770
+    used_in.comet=0;            % Set relevance flags
771
+    used_in.traj=0;
772
+    used_in.label=0;
773
+    used_in.hit=0;
774
+    used_in.mhit=1;
775
+    
776
+   case 'subplot'
777
+    %%% The subplots which are affected 
778
+    
779
+    if vis_valuetype(value,{'1xn','nx1','string'}), 
780
+      if ischar(value),
781
+	if ~strcmp(value,'all'),
782
+	  error('Only valid string value for subplot indices is ''all''.');
783
+	else
784
+	  value=1:length(handles);
785
+	end
786
+      elseif any(value<1) | any(value>length(handles)),
787
+	error('Subplot indices must be in range 1...number_of_subplots!');
788
+      end
789
+    elseif ~isempty(value)
790
+      error('Invalid subplot indices!');
791
+    end
792
+    used_in.comet=1;              % Set relevance flags
793
+    used_in.traj=1;
794
+    used_in.label=1;
795
+    used_in.hit=1;
796
+    used_in.mhit=1;
797
+    
798
+   otherwise
799
+    error([ 'Unknown identifier ''' identifier '''.']);
800
+  end
801
+  
802
+  % Warn user if the property that was set has no effect in the 
803
+  % selected visuzlization mode
804
+
805
+  if ~getfield(used_in, mode),
806
+    warning(['Property ''' identifier ''' has no effect in mode ''' ...
807
+	       mode_ '''.']);
808
+  else 
809
+    Property=setfield(Property,identifier,value);
810
+  end
811
+end
812
+
813
+% set default subplot
814
+if isempty(Property.subplot)
815
+  % search the subplot number for current axis
816
+  value=find(gca==handles);    
817
+  if isempty(value) | value>length(handles) 
818
+    error('SubPlot default value setting: current axis is not in the figure!');
819
+  else
820
+    Property.subplot=value;
821
+  end
822
+end
823
+  
824
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
825
+%%%%%%% Main switch: select the right subfunction %%%%%%%%%%%%%%%%%%%
826
+
827
+switch mode
828
+ case 'hit'
829
+  h_=hit(D, lattice, msize, Property);  
830
+ case 'mhit'
831
+  h_=mhit(D, lattice, msize, Property);  
832
+ case 'label'
833
+  h_=label(D, lattice, msize, Property);
834
+ case 'traj'
835
+  h_=traj(D, lattice, msize, Property);
836
+ case 'comet'
837
+  %error('Not yet implemented.'); 
838
+  h_=comet(D, lattice, msize, Property);
839
+ otherwise
840
+  error('Whoops! Internal error: unknown mode!');
841
+end
842
+
843
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
844
+%% Build output if necessary %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
845
+
846
+if nargout>0
847
+  h=h_;
848
+end
849
+
850
+%%%% SUBFUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
851
+
852
+function h_=hit(Hits, lattice, msize, Property);  
853
+
854
+% number of map units
855
+munits=prod(msize);
856
+
857
+% subplots
858
+p=Property.subplot;
859
+handles=Property.handles;
860
+
861
+% Set default marker
862
+if isempty(Property.marker),
863
+  if strcmp(Property.text,'on')
864
+    Property.marker='none';
865
+  else
866
+    Property.marker='lattice';
867
+  end
868
+end
869
+
870
+% Set default markersize
871
+if isempty(Property.markersize)
872
+  if strcmp(Property.marker,'none'),
873
+    warning('MarkerSize is not meaningful since Marker is set to ''none''.');
874
+  elseif strcmp(Property.marker,'lattice'),
875
+    Property.markersize=1; % normalized size
876
+  else
877
+    Property.markersize=12; % points
878
+  end
879
+end
880
+
881
+% Set default colors
882
+if ~isempty(Property.markercolor),
883
+  if strcmp(Property.marker,'none')
884
+    warning('MarkerColor is not used since Marker is set to ''none''.');
885
+    Property.markercolor=[]; % not used
886
+  else
887
+    ; % ok
888
+  end
889
+elseif any(strcmp(Property.marker,{'+','*','.','x'})),
890
+  % these don't use fill color: 'none' will cause default
891
+  % edgecolor to be 'k'.
892
+  Property.markercolor='none'; 
893
+else
894
+  Property.markercolor='k';
895
+end
896
+
897
+if ~isempty(Property.edgecolor),
898
+  if strcmp(Property.marker,'none')
899
+    warning(['EdgeColor is not used since Marker is set to' ...
900
+	     ' ''none''.']);
901
+  else
902
+    ; %ok 
903
+  end
904
+elseif ~strcmp(Property.markercolor,'none'),
905
+  Property.edgecolor='none';
906
+else
907
+  Property.edgecolor='k';
908
+end
909
+
910
+% Set default text
911
+if isempty(Property.text),
912
+  Property.text='off';
913
+end
914
+
915
+% Set default textsize
916
+if isempty(Property.textsize)
917
+  Property.textsize=10;
918
+elseif strcmp(Property.text,'off')  
919
+  warning('TextSize not used as hits are not set to be shown as numbers.');
920
+end
921
+
922
+% Set default textcolor
923
+if isempty(Property.textcolor)
924
+  Property.textcolor='w';
925
+elseif strcmp(Property.text,'off')  
926
+  warning('TextColor not used as hits are not set to be shown as numbers.');
927
+end
928
+
929
+%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
930
+
931
+h_=[];          % this variable is for collecting the object handles
932
+
933
+% Select the drawing mode 
934
+
935
+if ~strcmp(Property.marker,'none') 
936
+  
937
+  %%%%% Draw spots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
938
+  
939
+  % unit coordinates 
940
+  coord=som_vis_coords(lattice,msize);
941
+  
942
+  % Calculate the size of the spots
943
+  mx=max(Hits);
944
+  
945
+  if mx==0,
946
+    % nothing to draw!
947
+    h_=[]; 
948
+    return
949
+  else
950
+    Size=sqrt(Hits./mx);      
951
+  end
952
+  % coordinates for non-zero hits (only those are drawn)
953
+  coord=coord(Size~=0,:);
954
+  Size=Size(Size~=0);
955
+  N=size(Size,1);
956
+  
957
+  % som_cplane can't draw one unit with arbitrary
958
+  % coordinates as it its mixed with msize:
959
+  if size(coord,1)==1 & strcmp(Property.marker,'lattice'),
960
+    Size=[Size;Size];
961
+    coord=[coord;coord];
962
+  end
963
+  
964
+  for i=1:length(p),
965
+    % Set axes
966
+    axes(handles(p(i)));
967
+    % Get hold state and caxis
968
+    memhold=ishold; cax=caxis;     
969
+    hold on;
970
+    
971
+    switch Property.marker
972
+     case 'lattice'
973
+      h_(i,1)=som_cplane(lattice, coord, Property.markercolor, ...
974
+			 Property.markersize*Size);
975
+     otherwise  
976
+      [S,m]=som_grid(lattice, [N 1],...
977
+		     'Coord',coord, ...
978
+		     'Line','none',...
979
+		     'Marker',Property.marker,...
980
+		     'MarkerColor',Property.markercolor,...
981
+		     'MarkerSize', Size*Property.markersize);
982
+      h_=[h_;m(:)];
983
+    end
984
+    
985
+    % Restore hold state
986
+    if ~memhold         
987
+      hold off;
988
+    end
989
+  end
990
+  
991
+  % Set edgecolor
992
+  if strcmp(Property.marker,'lattice')
993
+    set(h_,'edgecolor',Property.edgecolor);
994
+  else
995
+    set(h_,'markeredgecolor',Property.edgecolor);
996
+  end
997
+end
998
+  
999
+if strcmp(Property.text,'on'),
1000
+  %%%%% Draw numbers %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
1001
+
1002
+  % Do numbers
1003
+  Hits=reshape(Hits,[munits 1]);
1004
+  labels=cell([munits 1]);
1005
+  for i=1:length(Hits)
1006
+    if Hits(i)              % zero hit won't be shown
1007
+      labels(i)={num2str(Hits(i))};
1008
+    end
1009
+  end
1010
+
1011
+  for i=1:length(p),
1012
+    axes(handles(p(i)));    % Set axes
1013
+    memhold=ishold;         % Get hold state
1014
+    hold on;
1015
+    [S,m,l,t]=som_grid(lattice, msize, ...
1016
+		       'Line','none',...
1017
+		       'Marker','none', ...
1018
+		       'Label',labels, ...
1019
+		       'LabelColor', Property.textcolor, ...
1020
+		       'LabelSize', Property.textsize);
1021
+    % Get handles
1022
+    h_=[h_;t(:)];
1023
+    
1024
+    % Restore hold state and caxis
1025
+    if ~memhold     
1026
+      hold off;
1027
+    end
1028
+    caxis(cax);
1029
+  end
1030
+
1031
+  % Remove zero object handles (missing objects)
1032
+  h_=setdiff(h_,0);
1033
+end
1034
+
1035
+%% Set object tags (for som_show_clear) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1036
+
1037
+set(h_,'Tag','Hit')
1038
+
1039
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1040
+
1041
+function h_=mhit(Hits, lattice, msize, Property);  
1042
+
1043
+% number of map units
1044
+munits=prod(msize);
1045
+
1046
+% subplots
1047
+p=Property.subplot;
1048
+handles=Property.handles;
1049
+
1050
+
1051
+% Set default marker
1052
+if isempty(Property.marker),
1053
+  Property.marker=lattice;
1054
+end
1055
+
1056
+% variable 'mode' indicates which kind of markers are used:
1057
+
1058
+if iscell(Property.marker),
1059
+  mode='marker';
1060
+elseif vis_valuetype(Property.marker,{'markerstyle'}),
1061
+  mode='marker';
1062
+elseif strcmp(Property.marker,'pie'),
1063
+  mode='pie';
1064
+else
1065
+  mode='lattice';
1066
+end
1067
+
1068
+% Set default size scaling
1069
+if isempty(Property.sizefactor)
1070
+  Property.sizefactor='separate';
1071
+end
1072
+
1073
+% Set default markersize 
1074
+if isempty(Property.markersize)
1075
+  if any(strcmp(mode,{'lattice','pie'})),
1076
+    Property.markersize=1; % normalized
1077
+  else
1078
+    Property.markersize=12;  % points
1079
+  end
1080
+end
1081
+
1082
+% Set default colors
1083
+
1084
+if isempty(Property.markercolor),
1085
+  Property.markercolor=hsv(size(Hits,2));
1086
+end
1087
+
1088
+if isempty(Property.edgecolor),
1089
+  if vis_valuetype(Property.markercolor,{'none'}),
1090
+    Property.edgecolor='k';
1091
+  else
1092
+    Property.edgecolor='none';
1093
+  end
1094
+end
1095
+
1096
+% Set default shift
1097
+if isempty(Property.shift)
1098
+  Property.shift=0;
1099
+end
1100
+
1101
+%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1102
+
1103
+h_=[];          % this variable is for collecting the object handles
1104
+
1105
+switch mode
1106
+  case {'marker','lattice'}
1107
+   % Number of hits histograms
1108
+   n_Hits=size(Hits,2);
1109
+   % Calculate the size of the spots
1110
+   
1111
+   if strcmp(Property.sizefactor,'common')
1112
+     mx=max(max(Hits));
1113
+     if mx==0 % nothing to draw!
1114
+       h_=[]; return
1115
+     end
1116
+     spotSize=sqrt(Hits./mx);
1117
+   else
1118
+     mx=repmat(max(Hits),munits,1);
1119
+     mx(mx==0)=1; % Prevent division by zero
1120
+     spotSize=sqrt(Hits./mx);
1121
+   end
1122
+   
1123
+   %%% Make spotSize
1124
+   
1125
+   %reshape Size to a vector [spotSizeforHist(:,1); spotSizeforHist(:,2);...]
1126
+   spotSize=spotSize(:);
1127
+   
1128
+   % indices for non-zero hits (only those are drawn)
1129
+   notZero=find(spotSize ~= 0);
1130
+   
1131
+   % Drop zeros away from spotSize
1132
+   spotSize=spotSize(notZero);
1133
+   
1134
+   % Order spots so that bigger will be drawn first, so that they 
1135
+   % won't hide smaller ones
1136
+   [dummy, sizeOrder]=sort(spotSize); sizeOrder=sizeOrder(end:-1:1);
1137
+   spotSize=spotSize(sizeOrder);
1138
+   
1139
+   %%% Make unit coordinates 
1140
+   coord=som_vis_coords(lattice,msize);
1141
+   
1142
+   move=repmat(linspace(-.1,.1,n_Hits),size(coord,1),1)*Property.shift;
1143
+   move=repmat(move(:),1,2);
1144
+   
1145
+   % do n_Hits copies of unit coordinates so that they match spotSize
1146
+   coord=repmat(coord,n_Hits,1)+move;
1147
+   
1148
+   % Drop zeros away from coords and order
1149
+   coord=coord(notZero,:);
1150
+   coord=coord(sizeOrder,:);
1151
+   
1152
+   %%% Make unit colors
1153
+   
1154
+   if vis_valuetype(Property.markercolor,{'nx3'}),
1155
+     % If multiple colors Copy unit colors so that they match spotSize
1156
+     color=Property.markercolor(reshape(repmat([1:n_Hits]',1,munits)',...
1157
+					munits*n_Hits,1),:);
1158
+     % drop zeros away & order
1159
+     color=color(notZero,:);
1160
+     color=color(sizeOrder,:);
1161
+   else
1162
+     % only on color
1163
+     color=Property.markercolor;
1164
+   end
1165
+   
1166
+   %%% Make unit markers
1167
+   
1168
+   if iscell(Property.marker),
1169
+     %marker shows class: 
1170
+     marker=char(Property.marker);
1171
+     marker=marker(reshape(repmat([1:n_Hits]',1,munits)',...
1172
+			   munits*n_Hits,1),:);
1173
+     % Drop zeros, order & make to cell array (for som_grid)
1174
+     marker=marker(notZero,:);
1175
+     marker=cellstr(marker(sizeOrder,:));
1176
+   else
1177
+     marker=Property.marker;
1178
+   end
1179
+
1180
+   % som_cplane can't draw one unit with arbitrary
1181
+   % coordinates as it its mixed with msize:
1182
+   if size(coord,1)==1 & strcmp(mode,'lattice'),
1183
+     spotSize = [spotSize; spotSize];
1184
+     coord = [coord; coord];
1185
+   end
1186
+
1187
+   N=length(notZero); % for som_grid visuzalization routine
1188
+ case 'pie'
1189
+  % marker 'pie' requires size parameter totHits
1190
+  if strcmp(mode,'pie')
1191
+    coord=som_vis_coords(lattice, msize);
1192
+    notZero=sum(Hits,2)>0;
1193
+    Hits=Hits(notZero,:);
1194
+    coord=coord(notZero,:);
1195
+    N=size(notZero,1);
1196
+    totHits=sqrt(sum(Hits,2)./max(sum(Hits,2)));
1197
+  end
1198
+  
1199
+  % som_pieplane can't draw one unit with arbitrary
1200
+  % coordinates as it its mixed with msize:
1201
+  if size(coord,1)==1,
1202
+    Hits= [Hits; Hits];
1203
+    coord = [coord; coord];
1204
+  end
1205
+ otherwise
1206
+  error('Whoops: internal error. Bad mode in subfunction mhit');
1207
+end
1208
+
1209
+for i=1:length(p),    %%% Main loop begins
1210
+  % Set axis
1211
+  axes(handles(p(i)));
1212
+  % Get hold state and caxis 
1213
+  memhold=ishold; cax=caxis;
1214
+  hold on;
1215
+  
1216
+  switch mode
1217
+   case 'lattice'
1218
+    h_(i,1)=som_cplane(lattice, coord, color, spotSize*Property.markersize);
1219
+   case 'marker'
1220
+    [S,m]=som_grid(lattice, [N 1],...
1221
+		   'Coord',coord, ...
1222
+		   'Line','none',...
1223
+		   'Marker',marker,...
1224
+		   'MarkerColor',color,...
1225
+		   'MarkerSize', spotSize*Property.markersize);
1226
+    h_=[h_;m(:)];
1227
+   case 'pie'
1228
+    h_(i)=som_pieplane(lattice, coord, ...
1229
+		       Hits, Property.markercolor, ...
1230
+		       totHits*Property.markersize);
1231
+  end
1232
+  
1233
+  % Restore hold state and caxis
1234
+  if ~memhold         
1235
+    hold off;
1236
+  end
1237
+  caxis(cax);
1238
+end
1239
+
1240
+% Set edgecolor
1241
+if any(strcmp(mode,{'lattice','pie'})),
1242
+  set(h_,'edgecolor',Property.edgecolor);
1243
+else
1244
+  set(h_,'markeredgecolor',Property.edgecolor);
1245
+end
1246
+
1247
+%% Set object tags (for som_show_clear) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1248
+
1249
+set(h_,'Tag','Hit')
1250
+
1251
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1252
+
1253
+function h_=label(Labels, lattice, msize, Property)
1254
+
1255
+% number of map units
1256
+munits=prod(msize);
1257
+
1258
+% subplots and handles
1259
+p=Property.subplot;
1260
+handles= Property.handles;
1261
+
1262
+% Set default text size
1263
+if isempty(Property.textsize)   % default point size
1264
+  Property.textsize=10;
1265
+end
1266
+
1267
+% Check color/set default
1268
+if isempty(Property.textcolor),                   
1269
+  Property.textcolor='k';
1270
+end
1271
+
1272
+% handles will be collected in h_ for output
1273
+h_=[];                            
1274
+
1275
+%%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1276
+
1277
+for i=1:length(p);
1278
+  % set axes
1279
+  axes(handles(p(i)));
1280
+  % store hold state and caxis (for some reason matlab may 
1281
+  % change caxis(!?)
1282
+  memhold=ishold;
1283
+  hold on;
1284
+  cax=caxis;
1285
+  
1286
+  % Write labels
1287
+  [S,m,l,t]=som_grid(lattice, msize, ...
1288
+		     'Line','none', ...
1289
+		     'Marker', 'none', ...
1290
+		     'Label', Labels, ...
1291
+		     'LabelColor', Property.textcolor,  ...
1292
+		     'LabelSize', Property.textsize);
1293
+  % Get handles
1294
+  h_=[h_;m(:);l(:);t(:)];
1295
+  
1296
+  % reset hold state and caxis
1297
+  if ~memhold
1298
+    hold off;
1299
+  end
1300
+  caxis(cax);
1301
+end
1302
+
1303
+%%% Set object tags %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1304
+
1305
+set(h_,'Tag','Lab');
1306
+  
1307
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1308
+
1309
+function h_=traj(bmu, lattice, msize, Property)
1310
+
1311
+% number of map units
1312
+munits=prod(msize);
1313
+
1314
+% subplots and handles
1315
+p=Property.subplot;
1316
+handles=Property.handles;
1317
+
1318
+% Set default text color
1319
+%if isempty(Property.textcolor),                   
1320
+%  Property.textcolor='k';
1321
+%end
1322
+
1323
+% Set default text size
1324
+%if isempty(Property.textsize)
1325
+%  Property.textsize=10;
1326
+%end
1327
+
1328
+% Set default marker
1329
+if isempty(Property.marker)
1330
+  Property.marker='o';
1331
+end
1332
+
1333
+% Set default markersize
1334
+if isempty(Property.markersize)
1335
+  Property.markersize=10;
1336
+end
1337
+
1338
+% Set default markercolor
1339
+if isempty(Property.markercolor)
1340
+  Property.markercolor='w';
1341
+end
1342
+
1343
+% Set default sizefactor
1344
+if isempty(Property.sizefactor)
1345
+  %Property.sizefactor=0;
1346
+  Property.sizefactor='hit';
1347
+end
1348
+
1349
+% Set default trajwidth
1350
+if isempty(Property.trajwidth)
1351
+  Property.trajwidth=3;
1352
+end
1353
+
1354
+% Set default widthfactor
1355
+if isempty(Property.widthfactor)
1356
+  Property.widthfactor='hit';
1357
+end
1358
+
1359
+% Set default trajcolor
1360
+if isempty(Property.trajcolor)
1361
+  Property.trajcolor='w';
1362
+end
1363
+
1364
+% if no labels, do a empty cell array for syntax reasons
1365
+%if isempty(Property.text),
1366
+%  Property.text=cell(munits,1);
1367
+%end
1368
+
1369
+h_=[];                    % handles will be collected in h_ for output    
1370
+l=length(bmu);            % length of trajectory
1371
+C=sparse(munits, munits); % init a connection matrix
1372
+
1373
+%%%%%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1374
+
1375
+% Calculate the connection matrix that describes the trajectory
1376
+for i=1:l-1,
1377
+  % The following if structure removes the possible redundancy due
1378
+  % to travels in both directions between two nodes of trajectory 
1379
+  % (i.e. reflexivity) 
1380
+  I=bmu(i+1);J=bmu(i);
1381
+  %if bmu(i)>bmu(i+1)
1382
+  
1383
+  %else 
1384
+  %  I=bmu(i);J=bmu(i+1);
1385
+  %end
1386
+  C(I,J)=C(I,J)+1;
1387
+end
1388
+
1389
+% transitive connections are equal
1390
+C=C+C';
1391
+% drop reflexive conncetions away
1392
+C=spdiags(zeros(munits,1),0,C);
1393
+
1394
+% Do labels of trajectory nodes
1395
+
1396
+%traj_lab=cell(munits,1);
1397
+hits=zeros(munits,1);
1398
+
1399
+for i=1:l,
1400
+%  traj_lab{bmu(i)}=strvcat(traj_lab{bmu(i)},Property.text{i});
1401
+  hits(bmu(i))=(hits(bmu(i))+1);
1402
+end
1403
+
1404
+% Calculate unit coordinates
1405
+unit_coord=som_vis_coords(lattice, msize);
1406
+
1407
+% Calculate line width
1408
+if strcmp(Property.widthfactor,'equal')
1409
+  TrajWidth=(C>0)*Property.trajwidth;
1410
+else
1411
+  TrajWidth=Property.trajwidth.*sqrt(C./max(max(C)));
1412
+end
1413
+
1414
+% Calculate marker sizes
1415
+if strcmp(Property.sizefactor,'hit')
1416
+  MarkerSize=Property.markersize*sqrt(hits/max(hits));
1417
+else
1418
+  MarkerSize=Property.markersize*(hits>0);
1419
+end
1420
+
1421
+for i=1:length(p),
1422
+  axes(handles(p(i)));
1423
+  % Get hold state and caxis
1424
+  memhold=ishold; cax=caxis;
1425
+  hold on;
1426
+
1427
+  	%'Label', traj_lab, ...
1428
+	%'LabelColor', Property.textcolor, ...
1429
+	%'LabelSize', Property.textsize, ...
1430
+
1431
+  % Draw
1432
+  [S,m,l,t,s]=som_grid(C,msize,'coord',unit_coord,...
1433
+	'Line','-', ...
1434
+	'LineColor', Property.trajcolor, ...
1435
+	'LineWidth', TrajWidth, ...
1436
+	'Marker', Property.marker, ...
1437
+	'MarkerColor', Property.markercolor, ...
1438
+	'MarkerSize', MarkerSize);
1439
+  
1440
+  % Restore hold state and caxis
1441
+  if ~memhold   
1442
+    hold off;
1443
+  end
1444
+  caxis(cax);
1445
+  % Get handles
1446
+  h_=[h_;m(:);l(:);t(:);s(:)];
1447
+end
1448
+
1449
+%% Set object tags %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
1450
+
1451
+set(h_,'Tag','Traj');
1452
+
1453
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1454
+
1455
+function h_=comet(bmu, lattice, msize, Property)
1456
+
1457
+% number of map units
1458
+munits=prod(msize);
1459
+
1460
+% subplots and handles
1461
+p=Property.subplot;
1462
+handles=Property.handles;
1463
+
1464
+% Set default text color
1465
+%if isempty(Property.textcolor),                   
1466
+%  Property.textcolor='k';
1467
+%end
1468
+
1469
+%% Set default text size
1470
+%if isempty(Property.textsize)
1471
+%  Property.textsize=10;
1472
+%end
1473
+
1474
+% Set default marker
1475
+if isempty(Property.marker)
1476
+  Property.marker='o';
1477
+end
1478
+
1479
+% Set default markersize
1480
+if isempty(Property.markersize),
1481
+  if strcmp(Property.marker,'lattice'),
1482
+    Property.markersize=linspace(0.8,0.1,length(bmu))';
1483
+  else 
1484
+    Property.markersize=sqrt(linspace(400,16,length(bmu)))';
1485
+  end
1486
+else
1487
+  if strcmp(Property.marker,'lattice'),
1488
+    Property.markersize=linspace(Property.markersize(1),...
1489
+				 Property.markersize(2), ...
1490
+				 length(bmu))';
1491
+  else
1492
+    Property.markersize=sqrt(linspace(Property.markersize(1).^2,...
1493
+				      Property.markersize(2).^2, ...
1494
+				      length(bmu)))';
1495
+
1496
+  end
1497
+end
1498
+
1499
+% Set default markercolor
1500
+if isempty(Property.markercolor)
1501
+  Property.markercolor='w';
1502
+end
1503
+
1504
+% Set default edgecolor
1505
+if isempty(Property.edgecolor),
1506
+  if vis_valuetype(Property.markercolor,{'nx3rgb'}),
1507
+    Property.edgecolor='none';
1508
+  else
1509
+    Property.edgecolor=Property.markercolor;
1510
+  end
1511
+end
1512
+
1513
+h_=[];l_=[];              % handles will be collected in h_ for output       
1514
+N_bmus=length(bmu);       % length of trajectory
1515
+
1516
+% if no labels, do a empty cell array for syntax reasons
1517
+%if isempty(Property.text),
1518
+%  Property.text=cell(N_bmus,1);
1519
+%end
1520
+
1521
+%%%%%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1522
+
1523
+% Calculate unit coordinates for trajectory points
1524
+unit_coord=som_vis_coords(lattice, msize);
1525
+coord=unit_coord(bmu,:);
1526
+
1527
+% Make labels for the _unique_ units that the comet hits
1528
+
1529
+unique_bmu=unique(bmu);               % count units
1530
+%N_labels=length(unique_bmu);    
1531
+%traj_lab=cell(N_labels,1);            % cell for labels
1532
+%label_coord=unit_coord(unique_bmu,:); % label coordinates
1533
+
1534
+% Make labels
1535
+%for i=1:N_bmus,
1536
+%  index=find(unique_bmu==bmu(i));
1537
+%  traj_lab{index}=strvcat(traj_lab{index},Property.text{i});
1538
+%end
1539
+
1540
+%Main loop for drawing comets
1541
+for i=1:length(p),
1542
+  % set axis
1543
+  axes(handles(p(i)));
1544
+
1545
+  % Get hold state and caxis
1546
+  memhold=ishold; cax=caxis;
1547
+  hold on;
1548
+  
1549
+  if strcmp(Property.marker,'lattice'),
1550
+    % Draw: marker is a patch ('hexa','rect')
1551
+     l_=som_cplane(lattice, coord, Property.markercolor, ...
1552
+		  Property.markersize);
1553
+     
1554
+     % Set edgecolor
1555
+     set(l_,'edgecolor',Property.edgecolor);
1556
+  else
1557
+    % Draw: other markers than 'hexa' or 'rect'
1558
+     [S,m,l,t,s]=som_grid(lattice, [N_bmus 1], 'coord', coord,...
1559
+			  'Line','none', ...
1560
+			  'Marker', Property.marker, ...
1561
+			  'MarkerColor', Property.markercolor, ...
1562
+			  'MarkerSize',Property.markersize);
1563
+     
1564
+     % Set edgecolor
1565
+     set(m, 'markeredgecolor', Property.edgecolor);
1566
+     
1567
+     % Get handles from markers
1568
+     h_=[h_;l_(:);m(:);l(:);t(:);s(:)];
1569
+  end
1570
+  
1571
+  % Set labels
1572
+  %[S,m,l,t,s]=som_grid(lattice, [N_labels 1], 'coord', label_coord,...
1573
+  %		       'Marker','none','Line','none',...
1574
+  %		       'Label', traj_lab, ...
1575
+  %		       'LabelColor', Property.textcolor, ...
1576
+  %		       'LabelSize', Property.textsize);
1577
+  % Get handles from labels
1578
+  %h_=[h_;m(:);l(:);t(:);s(:)];
1579
+
1580
+  % Restore hold state and caxis
1581
+  if ~memhold   
1582
+    hold off;
1583
+  end
1584
+  caxis(cax);
1585
+end
1586
+
1587
+%% Set object tags %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
1588
+
1589
+set(h_,'Tag','Comet');
1590
+
1591
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1592
+
1593
+
1594
+function P=init_properties;
1595
+
1596
+% Initialize an empty property struct
1597
+
1598
+P.marker=[];
1599
+P.markersize=[];
1600
+P.sizefactor=[];
1601
+P.markercolor=[];
1602
+P.edgecolor=[];
1603
+P.trajwidth=[];
1604
+P.widthfactor=[];
1605
+P.trajcolor=[];
1606
+P.text=[];
1607
+P.textsize=[];
1608
+P.textcolor=[];
1609
+P.subplot=[];
1610
+P.shift=[];
0 1611
\ No newline at end of file
... ...
@@ -0,0 +1,142 @@
1
+function som_show_clear(type, p)
2
+
3
+%SOM_SHOW_CLEAR Clear hit marks, labels or trajectories from current figure. 
4
+%
5
+% som_show_clear([type], [p])
6
+% 
7
+%  som_show_clear
8
+%  som_show_clear('Traj',[1 2])
9
+% 
10
+% Input arguments ([]'s are optional):        
11
+%  [type] (string) which markers to delete (case insensitive)
12
+%                  'hit'   to remove hit marks
13
+%                  'lab'   to remove labels
14
+%                  'traj'  to remove line trajectories
15
+%                  'comet' to remove comet trajectories
16
+%                  'all'   to remove all (the default)
17
+%  [p]    (vector) subplot number vector 
18
+%         (string) 'all' for all subplots (the default)
19
+%
20
+% This function removes the objects made by SOM_SHOW_ADD from a
21
+% figure.  If no value is given for p, the function operates on every
22
+% axis in the current figure. It simply searches for the objects with
23
+% certain values in the 'Tag' field. It does not matter if the figure
24
+% objects are created by SOM Toolbox -functions or not. However, if
25
+% vector p or string 'all' _is_ given, the figure has to have been
26
+% created by SOM_SHOW.
27
+%  
28
+% For more help, try 'type som_show_clear' or check out the helpdesk.
29
+% See also SOM_SHOW_ADD, SOM_SHOW.
30
+
31
+%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
32
+%
33
+% som_show_clear
34
+%
35
+% PURPOSE
36
+%
37
+% Clear hit marks, labels or trajectories created by SOM_SHOW_ADD
38
+% from the current figure. 
39
+%
40
+% SYNTAX
41
+% 
42
+%  som_show_clear
43
+%  som_show_clear([type],[p])
44
+%
45
+% DESCRIPTION
46
+%
47
+% The function SOM_SHOW_ADD creates some markers on the top of
48
+% visualizations made by SOM_SHOW. These objects may be removed using
49
+% SOM_SHOW_CLEAR even if the object handles are not known. The function
50
+% removes the objects based on certain tags written to the 'Tag' property
51
+% field of the objects.
52
+%
53
+% If the function if called without input arguments it searches for
54
+% every object in the current figure that have string
55
+% 'Hit','Lab','Traj' or 'Comet' in their Tag property field and
56
+% deletes them.
57
+%
58
+% If input argument p is not specified, the function does not check that the
59
+% figure is created by function SOM_SHOW.
60
+%
61
+% OPTIONAL INPUT ARGUMENTS
62
+%
63
+% type  (string) Which type of markers to delete
64
+%                'Hit' for removing hit marks    
65
+%                'Lab'              labels 
66
+%                'Traj'             line trajectories 
67
+%                'Comet'            comet trajectories 
68
+%                'All'              all (the default)
69
+%                Strings are case insensitive.
70
+%
71
+% p     (vector) Subplots from which the markers are removed
72
+%                Specifies the subplots from which the markers are removed. 
73
+%                The valid values are 1...N where N is the number of subplots. 
74
+%                It is required that the figure has been created by 
75
+%                the SOM_SHOW function.
76
+%
77
+% EXAMPLES 
78
+%          
79
+%   som_show_clear;
80
+%      % deletes all labels, hit marks and trajectories in the figure
81
+%   som_show_clear('hit');
82
+%      % deletes all the hit marks in the current figure
83
+%   som_show_clear('lab',[1 2]);
84
+%      % deletes labels in SOM_SHOW figure subplots 1 and 2. 
85
+%
86
+% SEE ALSO
87
+%
88
+% som_show       Basic map visualizations: component planes, u-matrix etc.
89
+% som_show_add   Show hits, labels and trajectories on SOM_SHOW visualization.
90
+
91
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
92
+% http://www.cis.hut.fi/projects/somtoolbox/             
93
+
94
+% Version 1.0beta Johan 061197 
95
+% Version 2.0beta Johan 061099 juuso 181199
96
+
97
+%%% Check number of arguments
98
+
99
+error(nargchk(0,2, nargin))     % check no. of input args is correct
100
+
101
+%%% Initialize & check & action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
102
+
103
+if nargin == 0 | isempty(type) | strcmp(type,'all') % delete everything 
104
+                                                    % in the gcf
105
+  delete(findobj(gcf,'Tag','Hit'));
106
+  delete(findobj(gcf, 'Tag','Lab'));
107
+  delete(findobj(gcf, 'Tag','Traj'));
108
+  delete(findobj(gcf, 'Tag','Comet'));
109
+  return
110
+end
111
+
112
+if nargin < 2 | isempty(p)            % check handles
113
+  handle=gcf;                       
114
+else                                  % check subplot handles if p is given
115
+  [handle,msg]=vis_som_show_data(p,gcf);
116
+  if ~isempty(msg)
117
+    error('2nd argument invalid or figure not made by SOM_SHOW: try SOM_SHOW_CLEAR without arguments.');
118
+    end
119
+end
120
+
121
+switch lower(type)                    % check type & make proper tag names
122
+case 'hit'  
123
+  tag = 'Hit'; 
124
+case 'lab'
125
+  tag = 'Lab';
126
+case 'traj'
127
+  tag = 'Traj';                     
128
+case 'comet'
129
+  tag = 'Comet';
130
+otherwise                             
131
+  error('Invalid object tag. Must be {lab | hit | traj | comet}');
132
+end
133
+
134
+%%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
135
+
136
+for i=1:length(handle),
137
+  h=findobj(handle(i),'Tag',tag);     % find object handles 
138
+  delete(h);                          % delete objects
139
+end				
140
+
141
+%%% No output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
142
+
... ...
@@ -0,0 +1,708 @@
1
+function fig = som_show_gui(input,varargin)
2
+
3
+%SOM_SHOW_GUI A GUI for using SOM_SHOW and associated functions.
4
+%
5
+%  h = som_show_gui(sM);
6
+%
7
+%  Input and output arguments:
8
+%    sM     (struct) a map struct: the SOM to visualize
9
+%    h      (scalar) a handle to the GUI figure
10
+%
11
+% This is a graphical user interface to make the usage of SOM_SHOW and
12
+% associated functions somewhat easier for beginning users of the SOM
13
+% Toolbox.
14
+%
15
+% How to use the GUI: 
16
+%  1. Start the GUI by giving command som_show_gui(sM);
17
+%  2. Build a list of visualization planes using the buttons 
18
+%     ('Add components', etc.) on the right 
19
+%     - the options associated with each of the planes can be 
20
+%       modified by selecting a plane from the list, and pressing
21
+%       the 'Plane options' button
22
+%     - the controls below the list apply to all planes
23
+%     - the subplot grid size can be controlled using the 'subplots'
24
+%       field on top right corner, e.g. '4 3' to get 4 times 3 grid
25
+%  3. To visualize the planes, press the 'Visualize' button on the bottom.
26
+%  4. To add hits, labels, trajectories (or comets) to the 
27
+%     visualization, or clear them, or reset the colorbars, 
28
+%     see the tools available from the 'Tools' menu. 
29
+%     - the arguments to those tools are either given in the tool, 
30
+%       or read from the workspace ('Select variable' buttons)
31
+%     - the tools always apply to the latest figure created
32
+%       by the GUI
33
+%  5. To quit, press the 'Close' button on the bottom.
34
+%
35
+% Known bugs:
36
+%  - Especially when using the adding tools, you can easily 
37
+%    give arguments which do not fit each other, and this 
38
+%    results in a lengthy (and often cryptic) error message.
39
+%    In such a case, check the arguments you are giving to see
40
+%    if there's something wrong with them. See function 
41
+%    SOM_SHOW_ADD for more information on how the options 
42
+%    can be set.
43
+%  - The default values in the adding tools may not be 
44
+%    very reasonable: you may have to try out different 
45
+%    values for e.g. markersize before getting the kind of
46
+%    result you want.
47
+% 
48
+% SOM_SHOW_GUI has two subfunctions: VIS_SHOW_GUI_COMP and 
49
+% VIS_SHOW_GUI_TOOL. These are for internal use of SOM_SHOW_GUI.
50
+%
51
+% See also SOM_SHOW, SOM_SHOW_ADD, SOM_SHOW_CLEAR, SOM_RECOLORBAR.
52
+
53
+% Copyright (c) 2000 by Roman Feldman and Juha Vesanto
54
+% Contributed to SOM Toolbox on August 22nd, 2000
55
+% http://www.cis.hut.fi/projects/somtoolbox/
56
+ 
57
+% Version 2.0beta roman 160800 juuso 220800
58
+
59
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
60
+%                                    MAIN                                   %
61
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
62
+
63
+warning off;
64
+if (nargin < 1)
65
+  errordlg({'Make sure you have SOM as input argument'; ''; ...
66
+            'example: som_show_gui(sMap)'},'Error in SOM_VIS: input arguments');
67
+  return
68
+end
69
+
70
+if isstruct(input)
71
+  fig_h = create_main_gui(input);
72
+  if (nargout > 0) fig = fig_h; end
73
+  return;
74
+
75
+elseif ischar(input)
76
+  action = lower(input);
77
+
78
+  % 
79
+  udata = get(varargin{1},'UserData');
80
+  plot_array = udata.plot_array;
81
+  l = length(plot_array);
82
+  list1_h = udata.h(1);
83
+
84
+  if (strcmp(action,''))
85
+    errordlg('','Error in SOM_VIS: input arguments');
86
+    return;
87
+
88
+  %%%%%%%%%%%%%%%%%%%%
89
+  % add_selected_comp
90
+  %
91
+  elseif (strcmp(action,'add_selected_comp'))
92
+    if isempty(plot_array(1).string), tmp = 1; else tmp = l+1; end 
93
+    [sel,ok] = listdlg('ListString',udata.sM.comp_names,...
94
+                       'Name','Component selection',...
95
+                       'PromptString','Select components to add');  
96
+    if ok & ~isempty(sel), 
97
+      for i=1:length(sel),
98
+        plot_array(tmp+i-1).string = udata.sM.comp_names{sel(i)}; 
99
+        plot_array(tmp+i-1).args = {'comp' sel(i)};
100
+        udata.property{tmp+i-1} = {0};
101
+      end      
102
+      set(list1_h,'Value',tmp+i-1, ...
103
+                  'String',{plot_array(:).string});
104
+    end
105
+
106
+    udata.plot_array = plot_array;
107
+    set(varargin{1},'UserData',udata);
108
+
109
+  %%%%%%%%%%%%%%%%%%%%
110
+  % add_all_comps
111
+  %
112
+  elseif (strcmp(action,'add_all_comps'))
113
+    if (strcmp(plot_array(1).string,''))
114
+      tmp = 1;
115
+    else
116
+      tmp = l+1;
117
+    end
118
+    indx = length(udata.sM.comp_names);
119
+    for (i=1:indx)
120
+      plot_array(tmp+i-1).string = udata.sM.comp_names{i};
121
+      plot_array(tmp+i-1).args = {'comp' i};
122
+      udata.property{tmp+i-1} = {0};
123
+    end	
124
+    % update list
125
+    set(list1_h,'Value',tmp+indx-1, ...
126
+                'String',{plot_array(:).string});
127
+
128
+    udata.plot_array = plot_array;
129
+    set(varargin{1},'UserData',udata);
130
+
131
+  %%%%%%%%%%%%%%%%%%%%
132
+  % add_u_matrix
133
+  %
134
+  elseif (strcmp(action,'add_u_matrix'))
135
+    if (strcmp(plot_array(1).string,''))
136
+      tmp = 1;
137
+    else
138
+      tmp = l+1;
139
+    end
140
+    plot_array(tmp).string = 'U-matrix';
141
+    plot_array(tmp).args = {'umat' 'all'};
142
+    udata.property{tmp} = {0 'U-matrix' 1:length(udata.sM.comp_names)};
143
+    % update list
144
+    set(list1_h,'Value',tmp, ...
145
+                'String',{plot_array(:).string});
146
+
147
+    udata.plot_array = plot_array;
148
+    set(varargin{1},'UserData',udata);
149
+
150
+  %%%%%%%%%%%%%%%%%%%%
151
+  % add_colorplane
152
+  %
153
+  elseif (strcmp(action,'add_colorplane'))
154
+    if (strcmp(plot_array(1).string,''))
155
+      tmp = 1;
156
+    else
157
+      tmp = l+1;
158
+    end
159
+    plot_array(tmp).string = 'color plane';
160
+    c = som_colorcode(udata.sM);
161
+    plot_array(tmp).args = {'color' c};
162
+    udata.property{tmp} = {0 'Color code' {'rgb1' 'rgb2' 'rgb3' 'rgb4' 'hsv' '-variable-'} 1};
163
+    % update list
164
+    set(list1_h,'Value',tmp, ...
165
+                'String',{plot_array(:).string});
166
+
167
+    udata.plot_array = plot_array;
168
+    set(varargin{1},'UserData',udata);
169
+
170
+  %%%%%%%%%%%%%%%%%%%%
171
+  % add_empty
172
+  %
173
+  elseif (strcmp(action,'add_empty'))
174
+    if (strcmp(plot_array(1).string,''))
175
+      tmp = 1;
176
+    else
177
+      tmp = l+1;
178
+    end
179
+    plot_array(tmp).string = 'empty plane';
180
+    plot_array(tmp).args = {'empty' ''};
181
+    udata.property{tmp} = {''};
182
+    % update list
183
+    set(list1_h,'Value',tmp, ...
184
+                'String',{plot_array(:).string});
185
+
186
+    udata.plot_array = plot_array;
187
+    set(varargin{1},'UserData',udata);
188
+
189
+  %%%%%%%%%%%%%%%%%%%%
190
+  % remove
191
+  %
192
+  elseif (strcmp(action,'remove'))
193
+    rm_indx = get(list1_h,'Value');
194
+    rm_l = length(rm_indx);
195
+    % rebuild array
196
+    incl_inds = setdiff(1:length(plot_array),rm_indx);
197
+    if isempty(incl_inds), 
198
+      clear plot_array;
199
+      plot_array(1).args = {};
200
+      plot_array(1).string = '';
201
+      udata.property = {};
202
+      udata.property{1} = {};
203
+    else
204
+      plot_array = plot_array(incl_inds);
205
+      udata.property = udata.property(incl_inds);
206
+    end
207
+    set(list1_h,'Value',length(plot_array), ...
208
+                'String',{plot_array(:).string});
209
+
210
+    udata.plot_array = plot_array;
211
+    set(varargin{1},'UserData',udata);
212
+
213
+  %%%%%%%%%%%%%%%%%%%%
214
+  % remove_all
215
+  %
216
+  elseif (strcmp(action,'remove_all'))
217
+    plot_array = [];
218
+    plot_array(1).args = {};
219
+    plot_array(1).string = '';
220
+    udata.property = {};
221
+    set(list1_h,'Value',1, ...
222
+                'String',{plot_array(:).string});
223
+
224
+    udata.plot_array = plot_array;
225
+    set(varargin{1},'UserData',udata);
226
+
227
+  %%%%%%%%%%%%%%%%%%%%
228
+  % more_options
229
+  %
230
+  elseif (strcmp(action,'more_options'))
231
+    vis_show_gui_comp(varargin{1},get(list1_h,'Value'),'init');
232
+
233
+  %%%%%%%%%%%%%%%%%%%%
234
+  % close
235
+  %
236
+  elseif (strcmp(action,'close'))
237
+    close(varargin{1});
238
+
239
+  %%%%%%%%%%%%%%%%%%%%
240
+  % visualize
241
+  %
242
+  elseif (strcmp(action,'visualize'))     %% s = {k k.^2}; plot(s{:});
243
+    current_fig = varargin{1}; 
244
+    figure;
245
+    args = [{udata.sM} plot_array(:).args];
246
+    % edge
247
+    tmp = get(udata.h(2),'UserData');
248
+    i = get(udata.h(2),'Value');
249
+    args = [args {'edge' tmp{i}}];
250
+    % bar
251
+    tmp = get(udata.h(3),'UserData');
252
+    i = get(udata.h(3),'Value');
253
+    args = [args {'bar' tmp{i}}];
254
+    % norm
255
+    tmp = get(udata.h(4),'UserData');
256
+    i = get(udata.h(4),'Value');
257
+    args = [args {'norm' tmp{i}}];
258
+    % size
259
+    tmp = get(udata.h(5),'String');
260
+    args = [args {'size' eval(tmp)}];
261
+    % colormap
262
+    tmp = get(udata.h(6),'String');
263
+    if ~isempty(tmp)
264
+      args = [args {'colormap' eval(tmp)}];
265
+    end
266
+    % footnote
267
+    tmp = get(udata.h(7),'String');
268
+    args = [args {'footnote' tmp}];
269
+    % subplots
270
+    tmp = get(udata.h(8),'String');
271
+    if ~(strcmp(tmp,'default') | isempty(tmp))
272
+      tmp2 = sscanf(tmp,'%i %i');
273
+      if length(tmp2)<2, tmp2 = sscanf(tmp,'%ix%i'); end
274
+      if length(tmp2)<2, tmp = eval(tmp);
275
+      else tmp = tmp2';
276
+      end
277
+      if length(tmp)<2, tmp(2) = 1; end
278
+      if tmp(1)*tmp(2)<length(get(udata.h(1),'string')),
279
+        close(varargin{1});
280
+        errordlg('Too small subplot size', ...
281
+                 'Error in SOM_VIS: subplot size');
282
+        return;
283
+      end
284
+      args = [args {'subplots' tmp}];
285
+    end
286
+
287
+    som_show(args{:});
288
+
289
+    % udata.vis_h = varargin{1};
290
+    %  first refresh plot info
291
+    udata.vis_h = setdiff( ...
292
+                    udata.vis_h, ...
293
+                    setdiff(udata.vis_h,get(0,'children')));
294
+    udata.vis_h = [udata.vis_h gcf];
295
+    set(current_fig,'UserData',udata);
296
+
297
+  else
298
+    ;
299
+  end
300
+
301
+else
302
+  errordlg({'Make sure you have SOM as input argument'; ''; ...
303
+            'example: som_show_gui(sMap)'},'Error in SOM_VIS: input arguments');
304
+end
305
+
306
+
307
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
308
+% ----------------------        SUBFUNCTIONS       -----------------------  %
309
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
310
+
311
+
312
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
313
+%                              CREATE_MAIN_GUI                              %
314
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
315
+
316
+function fig_h = create_main_gui(sM)
317
+
318
+oldFigNumber=watchon;
319
+
320
+% init variables
321
+FIGURENAME = 'SOM_SHOW_GUI';
322
+plot_array = [];
323
+plot_array(1).args = {};
324
+plot_array(1).string = '';
325
+
326
+% colors
327
+fig_color = [0.8 0.8 0.8];
328
+bg_color1 = [0.701960784313725 0.701960784313725 0.701960784313725];
329
+bg_color2 = [0.9 0.9 0.9];
330
+
331
+%%%%  positions  %%%%%
332
+%---------  figure
333
+fig_i =            [0.02 0.25];
334
+fig_s =            [0.24 0.55];
335
+%---------  
336
+ue = 0.02;
337
+th = 0.03;
338
+hint_text_pos =                [0.05 0.94 0.8 th];
339
+big_frame_pos =                [ue 0.38 (1-2*ue) 0.56];
340
+planes_listbox_text_pos =      [0.07 0.87 0.3 th];
341
+planes_listbox_pos =           [(ue+0.03) 0.395 0.46 0.47];
342
+subplots_text_pos =            [0.53 0.885 0.2 th];
343
+subplots_pos =                 [0.73 0.88 0.22 0.05];  ah = 0.045; d = (planes_listbox_pos(4) - 10*ah)/7;
344
+add_components_pos =           [0.53 (sum(planes_listbox_pos([2 4]))-ah) 0.42 ah]; tmp = add_components_pos(2)-(d+ah);
345
+add_all_components_pos =       [0.53 tmp 0.42 ah]; tmp = add_all_components_pos(2)-(d+ah);
346
+add_u_matrix_pos =             [0.53 tmp 0.42 ah]; tmp = add_u_matrix_pos(2)-(d+ah);
347
+add_colorplane_pos =           [0.53 tmp 0.42 ah]; tmp = add_colorplane_pos(2)-(d+ah);
348
+add_empty_pos =                [0.53 tmp 0.42 ah]; tmp = add_empty_pos(2)-2*(d+ah)+d;
349
+remove_pos =                   [0.53 tmp 0.42 ah]; tmp = remove_pos(2)-(d+ah);
350
+remove_all_pos =               [0.53 tmp 0.42 ah]; tmp = remove_all_pos(2)-2*(d+ah)+d;
351
+plane_options_pos =            [0.53 tmp 0.42 ah]; 
352
+ph = 0.041;
353
+dd = (ph-th)/2;
354
+tmp = big_frame_pos(2) - (planes_listbox_pos(2)-big_frame_pos(2)) - ph;
355
+ie1 = 0.25;
356
+tw = 0.21;
357
+iw = 0.28;
358
+unit_edges_text_pos =          [ue (tmp+dd) tw th];
359
+unit_edges_pos =               [ie1 tmp iw ph]; tmp = unit_edges_pos(2)-(d+ph) - d;
360
+unit_sizes_text_pos =          [ue (tmp+dd) tw th];
361
+unit_sizes_pos =               [ie1 tmp iw ph]; tmp = unit_sizes_pos(2)-(d+ph) - d;
362
+colorbar_dir_text_pos =        [ue (tmp+dd) tw th];
363
+colorbar_dir_pos =             [ie1 tmp iw ph]; tmp2 = sum(colorbar_dir_pos([1 3]));
364
+colorbar_norm_text_pos =       [(tmp2) (tmp+dd) 0.11 th];
365
+colorbar_norm_pos =            [(1-ue-(iw+0.06)) tmp (iw+0.06) ph]; tmp = colorbar_norm_pos(2)-(d+ph) - d;
366
+colormap_text_pos =            [ue (tmp+dd) tw th];
367
+colormap_pos =                 [ie1 tmp iw ph]; tmp = colormap_pos(2)-(d+ph) - d;
368
+footnote_text_pos =            [ue (tmp+dd) tw th]; 
369
+footnote_pos =                 [ie1 tmp (1-ue-ie1) ph];
370
+tmp = planes_listbox_pos(2)-big_frame_pos(2);
371
+tmp2 = ah+2*tmp;
372
+little_frame_pos =             [ue tmp (1-2*ue) tmp2]; tmp2 = little_frame_pos(2)+tmp;
373
+ddd = 0.1;
374
+bw = (little_frame_pos(3)-2*0.03-ddd)/2;
375
+visualize_pos =                [(ue+0.03) tmp2 bw ah];
376
+close_pos =                    [(sum(visualize_pos([1 3]))+ddd) tmp2 bw ah];
377
+
378
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
379
+%  main figure
380
+%
381
+fig_h = figure( ...
382
+  'Units','normalized', ...
383
+  'Color',fig_color, ...
384
+  'PaperPosition',[18 180 576 432], ...
385
+  'PaperType','A4', ...
386
+  'PaperUnits','normalized', ...
387
+  'Position',[fig_i fig_s], ...
388
+  'ToolBar','none', ...
389
+  'NumberTitle','off', ...
390
+  'Name',FIGURENAME, ...
391
+  'Visible','off');
392
+
393
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
394
+%  hint text
395
+%
396
+uicontrol( ...
397
+  'Units','normalized', ...
398
+  'BackgroundColor',fig_color, ...
399
+  'HorizontalAlignment','left', ...
400
+  'Position',hint_text_pos, ...
401
+  'String','Add planes and then visualize', ...
402
+  'Style','text');
403
+
404
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
405
+%  planes listbox
406
+%
407
+uicontrol( ...
408
+  'Units','normalized', ...
409
+  'Position',big_frame_pos, ...
410
+  'Style','frame');
411
+
412
+uicontrol( ...
413
+  'Units','normalized', ...
414
+  'BackgroundColor',bg_color1, ...
415
+  'HorizontalAlignment','left', ...
416
+  'Position',planes_listbox_text_pos, ...
417
+  'String','Planes', ...
418
+  'Style','text');
419
+
420
+list1_h = uicontrol( ...
421
+  'Units','normalized', ...
422
+  'BackgroundColor',bg_color2, ...
423
+  'Position',planes_listbox_pos, ...
424
+  'String',{plot_array(:).string}, ...
425
+  'Style','listbox', ...
426
+  'Max',2, ...
427
+  'Value',1);
428
+
429
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
430
+% edit subplots
431
+%
432
+uicontrol( ...
433
+  'Units','normalized', ...
434
+  'BackgroundColor',bg_color1, ...
435
+  'HorizontalAlignment','center', ...
436
+  'Position',subplots_text_pos, ...
437
+  'String','subplots', ...
438
+  'Style','text');
439
+
440
+edit4_h = uicontrol( ...
441
+  'Units','normalized', ...
442
+  'BackgroundColor',bg_color2, ...
443
+  'Position',subplots_pos, ...
444
+  'FontSize',14, ...
445
+  'String','', ...
446
+  'Style','edit');
447
+
448
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
449
+%  pushbutton 'Add components'
450
+%
451
+uicontrol( ...
452
+  'Units','normalized', ...
453
+  'BackgroundColor',bg_color1, ...
454
+  'HorizontalAlignment','left', ...
455
+  'Position',add_components_pos, ...
456
+  'String',' Add components', ...
457
+  'Callback',['som_show_gui(''add_selected_comp'',' mat2str(gcf) ')']);
458
+
459
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
460
+%  pushbutton 'Add all components'
461
+%
462
+uicontrol( ...
463
+  'Units','normalized', ...
464
+  'HorizontalAlignment','left', ...
465
+  'Position',add_all_components_pos, ...
466
+  'String',' Add all components', ...
467
+  'Callback',['som_show_gui(''add_all_comps'',' mat2str(gcf) ')']);
468
+
469
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
470
+%  pushbutton 'Add U-matrix'
471
+%
472
+uicontrol( ...
473
+  'Units','normalized', ...
474
+  'HorizontalAlignment','left', ...
475
+  'Position',add_u_matrix_pos, ...
476
+  'String',' Add U-matrix', ...
477
+  'Callback',['som_show_gui(''add_u_matrix'',' mat2str(gcf) ')']);
478
+
479
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
480
+%  pushbutton 'Add colorplane'
481
+%
482
+uicontrol( ...
483
+  'Units','normalized', ...
484
+  'HorizontalAlignment','left', ...
485
+  'Position',add_colorplane_pos, ...
486
+  'String',' Add colorplane', ...
487
+  'Callback',['som_show_gui(''add_colorplane'',' mat2str(gcf) ')']);
488
+
489
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
490
+%  pushbutton 'Add empty'
491
+%
492
+uicontrol( ...
493
+  'Units','normalized', ...
494
+  'HorizontalAlignment','left', ...
495
+  'Position',add_empty_pos, ...
496
+  'String',' Add empty', ...
497
+  'Callback',['som_show_gui(''add_empty'',' mat2str(gcf) ')']);
498
+
499
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
500
+%  pushbutton 'Remove'
501
+%
502
+uicontrol( ...
503
+  'Units','normalized', ...
504
+  'HorizontalAlignment','left', ...
505
+  'Position',remove_pos, ...
506
+  'String',' Remove', ...
507
+  'Callback',['som_show_gui(''remove'',' mat2str(gcf) ')']);
508
+
509
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
510
+% creat pushbutton 'Remove all'
511
+%
512
+uicontrol( ...
513
+  'Units','normalized', ...
514
+  'BackgroundColor',bg_color1, ...
515
+  'HorizontalAlignment','left', ...
516
+  'Position',remove_all_pos, ...
517
+  'String',' Remove all', ...
518
+  'Callback',['som_show_gui(''remove_all'',' mat2str(gcf) ')']);
519
+
520
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
521
+%  pushbutton 'Plane options'
522
+%
523
+uicontrol( ...
524
+  'Units','normalized', ...
525
+  'Position',plane_options_pos, ...
526
+  'String',' Plane options', ...
527
+  'Callback',['som_show_gui(''more_options'',' mat2str(gcf) ')']);
528
+
529
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
530
+%  popupmenu unitedges
531
+%
532
+uicontrol( ...
533
+  'Units','normalized', ...
534
+  'BackgroundColor',fig_color, ...
535
+  'HorizontalAlignment','left', ...
536
+  'Position',unit_edges_text_pos, ...
537
+  'String','unit edges are', ...
538
+  'Style','text');
539
+
540
+popup1_h = uicontrol( ...
541
+  'Units','normalized', ...
542
+  'Max',2, ...
543
+  'Min',1, ...
544
+  'Position',unit_edges_pos, ...
545
+  'UserData',{'off' 'on'}, ...
546
+  'String',{'off' 'on'}, ...
547
+  'Style','popupmenu', ...
548
+  'Value',1);
549
+
550
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
551
+%  unit sizes edit
552
+%
553
+uicontrol( ...
554
+  'Units','normalized', ...
555
+  'BackgroundColor',fig_color, ...
556
+  'HorizontalAlignment','left', ...
557
+  'Position',unit_sizes_text_pos, ...
558
+  'String','unit sizes', ...
559
+  'Style','text');
560
+
561
+edit1_h = uicontrol( ...
562
+  'Units','normalized', ...
563
+  'BackgroundColor',bg_color2, ...
564
+  'Position',unit_sizes_pos, ...
565
+  'FontSize',12, ...
566
+  'String','1', ...
567
+  'Style','edit');
568
+
569
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
570
+%  popupmenu colorbardir
571
+%
572
+uicontrol( ...
573
+  'Units','normalized', ...
574
+  'BackgroundColor',fig_color, ...
575
+  'HorizontalAlignment','left', ...
576
+  'Position',colorbar_dir_text_pos, ...
577
+  'String','colorbar is', ...
578
+  'Style','text');
579
+
580
+popup2_h = uicontrol( ...
581
+  'Units','normalized', ...
582
+  'Max',3, ...
583
+  'Min',1, ...
584
+  'Position',colorbar_dir_pos, ...
585
+  'UserData', {'vert' 'horiz' 'none'}, ...
586
+  'String','vert| horiz| none', ...
587
+  'Style','popupmenu', ...
588
+  'Value',1);
589
+
590
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
591
+%  popupmenu colorbarnorm
592
+%
593
+uicontrol( ...
594
+  'Units','normalized', ...
595
+  'BackgroundColor',fig_color, ...
596
+  'HorizontalAlignment','left', ...
597
+  'Position',colorbar_norm_text_pos, ...
598
+  'String',' and  ', ...
599
+  'Style','text');
600
+
601
+popup3_h = uicontrol( ...
602
+  'Units','normalized', ...
603
+  'Max',2, ...
604
+  'Min',1, ...
605
+  'Position',colorbar_norm_pos, ...
606
+  'UserData', {'d' 'n'}, ...
607
+  'String',{'denormalized','normalized'}, ...
608
+  'Style','popupmenu', ...
609
+  'Value',1);
610
+
611
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
612
+%  colormap edittext
613
+%
614
+uicontrol( ...
615
+  'Units','normalized', ...
616
+  'BackgroundColor',fig_color, ...
617
+  'HorizontalAlignment','left', ...
618
+  'Position',colormap_text_pos, ...
619
+  'String','colormap', ...
620
+  'Style','text');
621
+
622
+edit2_h = uicontrol( ...
623
+  'Units','normalized', ...
624
+  'BackgroundColor',bg_color2, ...
625
+  'Position',colormap_pos, ...
626
+  'FontSize',12, ...
627
+  'String','', ...
628
+  'Style','edit');
629
+
630
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
631
+%  footnote edittext
632
+%
633
+uicontrol( ...
634
+  'Units','normalized', ...
635
+  'BackgroundColor',fig_color, ...
636
+  'HorizontalAlignment','left', ...
637
+  'Position',footnote_text_pos, ...
638
+  'String','footnote', ...
639
+  'Style','text');
640
+
641
+edit3_h = uicontrol( ...
642
+  'Units','normalized', ...
643
+  'BackgroundColor',bg_color2, ...
644
+  'Position',footnote_pos, ...
645
+  'FontSize',12, ...
646
+  'String',sM.name, ...
647
+  'Style','edit');
648
+
649
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
650
+%  pushbutton 'Visualize'
651
+%
652
+uicontrol( ...
653
+  'Units','normalized', ...
654
+  'Position',little_frame_pos, ...
655
+  'Style','frame');
656
+
657
+uicontrol( ...
658
+  'Units','normalized', ...
659
+  'Position',visualize_pos, ...
660
+  'String','Visualize', ...
661
+  'Callback',['som_show_gui(''visualize'',' mat2str(gcf) ')']);
662
+
663
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
664
+%  pushbutton 'Close'
665
+%
666
+uicontrol( ...
667
+  'Units','normalized', ...
668
+  'BackgroundColor',bg_color1, ...
669
+  'Position',close_pos, ...
670
+  'String','Close', ...
671
+  'Callback',['som_show_gui(''close'',' mat2str(gcf) ')']);
672
+
673
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
674
+% menus
675
+%
676
+uimenu('Parent',fig_h','Label','    ','Enable','off');
677
+m = uimenu('Parent',fig_h,'Label','Tools');
678
+ a = uimenu('Parent',m,'Label','Add');
679
+  s = strcat('vis_show_gui_tool(',mat2str(gcf),',''add_label'')');
680
+  uimenu('Parent',a,'Label','label','Callback',s);
681
+  s = strcat('vis_show_gui_tool(',mat2str(gcf),',''add_hit'')');
682
+  uimenu('Parent',a,'Label','hit','Callback',s);
683
+  s = strcat('vis_show_gui_tool(',mat2str(gcf),',''add_traj'')');
684
+  uimenu('Parent',a,'Label','traj','Callback',s);
685
+  s = strcat('vis_show_gui_tool(',mat2str(gcf),',''add_comet'')');
686
+  uimenu('Parent',a,'Label','comet','Callback',s);
687
+ s = ['vis_show_gui_tool(',mat2str(gcf),',''clear'')'];
688
+ c = uimenu('Parent',m,'Label','Clear','Separator','on','callback',s);
689
+ s = strcat('vis_show_gui_tool(',mat2str(gcf),',''recolorbar'')');
690
+ r = uimenu('Parent',m,'Label','Recolorbar','Separator','on', ...
691
+  'Callback',s);
692
+
693
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
694
+% end
695
+%
696
+
697
+ud.sM = sM;
698
+ud.plot_array = plot_array;
699
+ud.property = {};
700
+ud.vis_h = [];
701
+ud.h = [list1_h popup1_h popup2_h popup3_h ...
702
+        edit1_h edit2_h edit3_h edit4_h];
703
+
704
+watchoff(oldFigNumber);
705
+set(fig_h,'Visible','on', ...
706
+          'UserData', ud, ...
707
+          'handlevisibility','off');
708
+
... ...
@@ -0,0 +1,443 @@
1
+function [sMap, sTrain] = som_sompaktrain(sMap, D, varargin)
2
+
3
+%SOM_SOMPAKTRAIN  Use SOM_PAK to train the Self-Organizing Map.
4
+%
5
+% [sM,sT] = som_sompaktrain(sM, D, [[argID,] value, ...])
6
+% 
7
+%  sM     = som_sompaktrain(sM,D);
8
+%  sM     = som_sompaktrain(sM,sD,'alpha_type','inv');
9
+%  [M,sT] = som_sompaktrain(M,D,'bubble','trainlen',10,'inv','hexa');
10
+%
11
+%  Input and output arguments ([]'s are optional): 
12
+%   sM      (struct) map struct, the trained and updated map is returned
13
+%           (matrix) codebook matrix of a self-organizing map
14
+%                    size munits x dim or  msize(1) x ... x msize(k) x dim
15
+%                    The trained map codebook is returned.
16
+%   D       (struct) training data; data struct
17
+%           (matrix) training data, size dlen x dim
18
+%           (string) name of data file
19
+%   [argID, (string) See below. The values which are unambiguous can 
20
+%    value] (varies) be given without the preceeding argID.
21
+%
22
+%   sT      (struct) learning parameters used during the training
23
+%
24
+% Here are the valid argument IDs and corresponding values. The values which
25
+% are unambiguous (marked with '*') can be given without the preceeding argID.
26
+%   'msize'        (vector) map size
27
+%   'radius_ini'   (scalar) neighborhood radius
28
+%   'radius' = 'radius_ini'
29
+%   'alpha_ini'    (scalar) initial learning rate
30
+%   'alpha' = 'alpha_ini'
31
+%   'trainlen'     (scalar) training length
32
+%   'seed'         (scalar) seed for random number generator
33
+%   'snapfile'     (string) base name for snapshot files
34
+%   'snapinterval' (scalar) snapshot interval
35
+%   'tlen_type'   *(string) is the given trainlen 'samples' or 'epochs'
36
+%   'train'       *(struct) train struct, parameters for training
37
+%   'sTrain','som_train' = 'train'
38
+%   'alpha_type'  *(string) learning rate function, 'inv' or 'linear'
39
+%   'neigh'       *(string) neighborhood function, 'gaussian' or 'bubble'
40
+%   'topol'       *(struct) topology struct
41
+%   'som_topol','sTopol' = 'topol'
42
+%   'lattice'     *(string) map lattice, 'hexa' or 'rect'
43
+%
44
+% For more help, try 'type som_sompaktrain' or check out online documentation.
45
+% See also  SOM_MAKE, SOM_SEQTRAIN, SOM_BATCHTRAIN, SOM_TRAIN_STRUCT.
46
+
47
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
48
+%
49
+% som_sompaktrain
50
+%
51
+% PURPOSE
52
+%
53
+% Use SOM_PAK to train the Self-Organizing Map.
54
+%
55
+% SYNTAX
56
+%
57
+%  sM = som_sompaktrain(sM,D);
58
+%  sM = som_sompaktrain(sM,sD);
59
+%  sM = som_sompaktrain(...,'argID',value,...);
60
+%  sM = som_sompaktrain(...,value,...);
61
+%  [sM,sT] = som_sompaktrain(M,D,...);
62
+%
63
+% DESCRIPTION
64
+%
65
+% Trains the given SOM (sM or M above) with the given training data (sD or
66
+% D) using SOM_PAK. If no optional arguments (argID, value) are
67
+% given, a default training is done, the parameters are obtained from
68
+% SOM_TRAIN_STRUCT function.  Using optional arguments the training
69
+% parameters can be specified. Returns the trained and updated SOM and a
70
+% train struct which contains information on the training.
71
+%
72
+% Notice that the SOM_PAK program 'vsom' must be in the search path of your
73
+% shell. Alternatively, you can set a variable 'SOM_PAKDIR' in the Matlab
74
+% workspace to tell the som_sompaktrain where to find the 'vsom' program.
75
+%
76
+% Notice also that many of the training parameters are much more limited in
77
+% values than when using SOM Toolbox function for training:
78
+%   - the map shape is always 'sheet'
79
+%   - only initial value for neighborhood radius can be given
80
+%   - neighborhood function can only be 'bubble' or 'gaussian'
81
+%   - only initial value for learning rate can be given
82
+%   - learning rate can only be 'linear' or 'inv'
83
+%   - mask cannot be used: all variables are always used in BMU search
84
+% Any parameters not confirming to these restrictions will be converted
85
+% so that they do before training. On the other hand, there are some 
86
+% additional options that are not present in the SOM Toolbox: 
87
+%   - random seed
88
+%   - snapshot file and interval
89
+%
90
+% REQUIRED INPUT ARGUMENTS
91
+%
92
+%  sM          The map to be trained. 
93
+%     (struct) map struct
94
+%     (matrix) codebook matrix (field .data of map struct)
95
+%              Size is either [munits dim], in which case the map grid 
96
+%              dimensions (msize) should be specified with optional arguments,
97
+%              or [msize(1) ... msize(k) dim] in which case the map 
98
+%              grid dimensions are taken from the size of the matrix. 
99
+%              Lattice, by default, is 'rect' and shape 'sheet'.
100
+%  D           Training data.
101
+%     (struct) data struct
102
+%     (matrix) data matrix, size [dlen dim]
103
+%     (string) name of data file
104
+%  
105
+% OPTIONAL INPUT ARGUMENTS 
106
+%
107
+%  argID (string) Argument identifier string (see below).
108
+%  value (varies) Value for the argument (see below).
109
+%
110
+%  The optional arguments can be given as 'argID',value -pairs. If an
111
+%  argument is given value multiple times, the last one is
112
+%  used. The valid IDs and corresponding values are listed below. The values 
113
+%  which are unambiguous (marked with '*') can be given without the 
114
+%  preceeding argID.
115
+%
116
+%   'msize'        (vector) map grid dimensions. Default is the one
117
+%                           in sM (field sM.topol.msize) or 
118
+%                           'si = size(sM); msize = si(1:end-1);' 
119
+%                           if only a codebook matrix was given. 
120
+%   'radius_ini'   (scalar) initial neighborhood radius 
121
+%   'radius'       (scalar) = 'radius_ini'
122
+%   'alpha_ini'    (vector) initial learning rate
123
+%   'alpha'        (scalar) = 'alpha_ini'
124
+%   'trainlen'     (scalar) training length (see also 'tlen_type')
125
+%   'seed'         (scalar) seed for random number generator
126
+%   'snapfile'     (string) base name for snapshot files
127
+%   'snapinterval' (scalar) snapshot interval
128
+%   'tlen_type'   *(string) is the trainlen argument given in 'epochs' or
129
+%                           in 'samples'. Default is 'epochs'.
130
+%   'train'       *(struct) train struct, parameters for training. 
131
+%                           Default parameters, unless specified, 
132
+%                           are acquired using SOM_TRAIN_STRUCT (this 
133
+%                           also applies for 'trainlen', 'alpha_type',
134
+%                           'alpha_ini', 'radius_ini' and 'radius_fin').
135
+%   'sTrain', 'som_topol' (struct) = 'train'
136
+%   'neigh'       *(string) The used neighborhood function. Default is 
137
+%                           the one in sM (field '.neigh') or 'gaussian'
138
+%                           if only a codebook matrix was given. The other 
139
+%                           possible value is 'bubble'.
140
+%   'topol'       *(struct) topology of the map. Default is the one
141
+%                           in sM (field '.topol').
142
+%   'sTopol', 'som_topol' (struct) = 'topol'
143
+%   'alpha_type'  *(string) learning rate function, 'inv' or 'linear'
144
+%   'lattice'     *(string) map lattice. Default is the one in sM
145
+%                           (field sM.topol.lattice) or 'rect' 
146
+%                           if only a codebook matrix was given. 
147
+%   
148
+% OUTPUT ARGUMENTS
149
+% 
150
+%  sM          the trained map
151
+%     (struct) if a map struct was given as input argument, a 
152
+%              map struct is also returned. The current training 
153
+%              is added to the training history (sM.trainhist).
154
+%              The 'neigh' and 'mask' fields of the map struct
155
+%              are updated to match those of the training.
156
+%     (matrix) if a matrix was given as input argument, a matrix
157
+%              is also returned with the same size as the input 
158
+%              argument.
159
+%  sT (struct) train struct; information of the accomplished training
160
+%  
161
+% EXAMPLES
162
+%
163
+% Simplest case:
164
+%  sM = som_sompaktrain(sM,D);  
165
+%  sM = som_sompaktrain(sM,sD);  
166
+%
167
+% The change training parameters, the optional arguments 'train', 
168
+% 'neigh','mask','trainlen','radius','radius_ini', 'alpha', 
169
+% 'alpha_type' and 'alpha_ini' are used. 
170
+%  sM = som_sompaktrain(sM,D,'bubble','trainlen',10,'radius_ini',3);
171
+%
172
+% Another way to specify training parameters is to create a train struct:
173
+%  sTrain = som_train_struct(sM,'dlen',size(D,1),'algorithm','seq');
174
+%  sTrain = som_set(sTrain,'neigh','gaussian');
175
+%  sM = som_sompaktrain(sM,D,sTrain);
176
+%
177
+% You don't necessarily have to use the map struct, but you can operate
178
+% directly with codebook matrices. However, in this case you have to
179
+% specify the topology of the map in the optional arguments. The
180
+% following commads are identical (M is originally a 200 x dim sized matrix):
181
+%  M = som_sompaktrain(M,D,'msize',[20 10],'lattice','hexa');
182
+%
183
+%  M = som_sompaktrain(M,D,'msize',[20 10],'hexa');
184
+%
185
+%  sT= som_set('som_topol','msize',[20 10],'lattice','hexa');
186
+%  M = som_sompaktrain(M,D,sT);
187
+%
188
+%  M = reshape(M,[20 10 dim]);
189
+%  M = som_sompaktrain(M,D,'hexa');
190
+%
191
+% The som_sompaktrain also returns a train struct with information on the 
192
+% accomplished training. This is the same one as is added to the end of the 
193
+% trainhist field of map struct, in case a map struct is given.
194
+%  [M,sTrain] = som_sompaktrain(M,D,'msize',[20 10]);
195
+%
196
+%  [sM,sTrain] = som_sompaktrain(sM,D); % sM.trainhist(end)==sTrain
197
+%
198
+% SEE ALSO
199
+% 
200
+%  som_make         Initialize and train a SOM using default parameters.
201
+%  som_seqtrain     Train SOM with sequential algorithm.
202
+%  som_batchtrain   Train SOM with batch algorithm.
203
+%  som_train_struct Determine default training parameters.
204
+
205
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
206
+% http://www.cis.hut.fi/projects/somtoolbox/
207
+
208
+% Version 2.0beta juuso 151199
209
+ 
210
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
211
+%% Check arguments
212
+
213
+error(nargchk(2, Inf, nargin));  % check the number of input arguments
214
+
215
+% map 
216
+struct_mode = isstruct(sMap);
217
+if struct_mode, 
218
+  sTopol = sMap.topol;
219
+else  
220
+  orig_size = size(sMap);
221
+  if ndims(sMap) > 2, 
222
+    si = size(sMap); dim = si(end); msize = si(1:end-1);
223
+    M = reshape(sMap,[prod(msize) dim]);
224
+  else
225
+    msize = [orig_size(1) 1]; 
226
+    dim = orig_size(2);
227
+  end
228
+  sMap   = som_map_struct(dim,'msize',msize);
229
+  sTopol = sMap.topol;
230
+end
231
+[munits dim] = size(sMap.codebook);
232
+
233
+% data
234
+givendatafile = '';
235
+if ischar(D), 
236
+  data_name = D; 
237
+  givendatafile = D;
238
+  D = [];
239
+  dlen = NaN;
240
+else
241
+  if isstruct(D), 
242
+    data_name = D.name; 
243
+    D = D.data;   
244
+  else
245
+    data_name = inputname(2); 
246
+  end
247
+  D = D(find(sum(isnan(D),2) < dim),:); % remove empty vectors from the data
248
+  [dlen ddim] = size(D);                % check input dimension
249
+  if ddim ~= dim, error('Map and data dimensions must agree.'); end
250
+end
251
+
252
+% varargin
253
+sTrain = som_set('som_train','algorithm','seq',...
254
+			     'neigh',sMap.neigh,...
255
+			     'mask',ones(dim,1),...
256
+			     'data_name',data_name);
257
+tlen_type  = 'epochs';
258
+random_seed = 0; 
259
+snapshotname = ''; 
260
+snapshotinterval = 0;
261
+
262
+i=1; 
263
+while i<=length(varargin), 
264
+  argok = 1; 
265
+  if ischar(varargin{i}), 
266
+    switch varargin{i}, 
267
+     % argument IDs
268
+     case 'msize',       i=i+1; sTopol.msize = varargin{i}; 
269
+     case 'lattice',     i=i+1; sTopol.lattice = varargin{i};
270
+     case 'neigh',       i=i+1; sTrain.neigh = varargin{i};
271
+     case 'trainlen',    i=i+1; sTrain.trainlen = varargin{i};
272
+     case 'tlen_type',   i=i+1; tlen_type = varargin{i}; 
273
+     case 'radius_ini',  i=i+1; sTrain.radius_ini = varargin{i};
274
+     case 'radius',      i=i+1; sTrain.radius_ini = varargin{i}(1);
275
+     case 'alpha_type',  i=i+1; sTrain.alpha_type = varargin{i};
276
+     case 'alpha_ini',   i=i+1; sTrain.alpha_ini = varargin{i};
277
+     case 'alpha',       i=i+1; sTrain.alpha_ini = varargin{i}(1);
278
+     case 'seed',        i=i+1; random_seed = varargin{i};
279
+     case 'snapshotname',i=i+1; snapshotname = varargin{i};
280
+     case 'snapshotinterval',i=i+1; snapshotinterval = varargin{i};
281
+     case {'sTrain','train','som_train'}, i=i+1; sTrain = varargin{i};
282
+     case {'topol','sTopol','som_topol'}, 
283
+      i=i+1; 
284
+      sTopol = varargin{i};
285
+      if prod(sTopol.msize) ~= munits, 
286
+        error('Given map grid size does not match the codebook size.');
287
+      end
288
+      % unambiguous values
289
+     case {'inv','linear'}, sTrain.alpha_type = varargin{i}; 
290
+     case {'hexa','rect'}, sTopol.lattice = varargin{i};
291
+     case {'gaussian','bubble'}, sTrain.neigh = varargin{i};
292
+     case {'epochs','samples'}, tlen_type = varargin{i};
293
+     otherwise argok=0; 
294
+    end
295
+  elseif isstruct(varargin{i}) & isfield(varargin{i},'type'), 
296
+    switch varargin{i}(1).type, 
297
+     case 'som_topol', 
298
+      sTopol = varargin{i}; 
299
+      if prod(sTopol.msize) ~= munits, 
300
+        error('Given map grid size does not match the codebook size.');
301
+      end
302
+     case 'som_train', sTrain = varargin{i};
303
+     otherwise argok=0; 
304
+    end
305
+  else
306
+    argok = 0; 
307
+  end
308
+  if ~argok, 
309
+    disp(['(som_sompaktrain) Ignoring invalid argument #' num2str(i+2)]); 
310
+  end
311
+  i = i+1; 
312
+end
313
+
314
+% check topology
315
+if struct_mode, 
316
+  if ~strcmp(sTopol.lattice,sMap.topol.lattice) | ...
317
+	~strcmp(sTopol.shape,sMap.topol.shape) | ...
318
+	any(sTopol.msize ~= sMap.topol.msize), 
319
+    warning('Changing the original map topology.');
320
+  end
321
+end
322
+sMap.topol = sTopol; 
323
+
324
+% complement the training struct
325
+if ~isnan(dlen), 
326
+  sTrain = som_train_struct(sTrain,sMap,'dlen',dlen);
327
+else
328
+  sTrain = som_train_struct(sTrain,sMap); 
329
+end
330
+if isempty(sTrain.mask), sTrain.mask = ones(dim,1); end
331
+
332
+% training length
333
+if strcmp(tlen_type,'epochs'), 
334
+  if isnan(dlen),   
335
+    error('Training length given as epochs, but data length is not known.\n');
336
+  else
337
+    rlen = sTrain.trainlen*dlen;
338
+  end
339
+else
340
+  rlen = sTrain.trainlen;
341
+  sTrain.trainlen = sTrain.trainlen/dlen;   
342
+end 
343
+
344
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
345
+%% check arguments
346
+
347
+% mask
348
+if any(sTrain.mask~=1), 
349
+  sTrain.mask = ones(dim,1); 
350
+  fprintf(1,'Ignoring given mask.\n');
351
+end
352
+
353
+% learning rate
354
+if strcmp(sTrain.alpha_type,'power'), 
355
+  sTrain.alpha_type = 'inv';
356
+  fprintf(1,'Using ''inv'' learning rate type instead of ''power''\n');
357
+end
358
+  
359
+% neighborhood
360
+if any(strcmp(sTrain.neigh,{'cutgauss','ep'})), 
361
+  fprintf(1,'Using ''gaussian'' neighborhood function instead of %s.\n',sTrain.neigh);
362
+  sTrain.neigh = 'gaussian'; 
363
+end
364
+
365
+% map shape
366
+if ~strcmp(sMap.topol.shape,'sheet'), 
367
+  fprintf(1,'Using ''sheet'' map shape of %s.\n',sMap.topol.shape);
368
+  sMap.topol.shape = 'sheet'; 
369
+end
370
+
371
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
372
+%% Action
373
+
374
+% write files
375
+if ~isempty(givendatafile), 
376
+  temp_din = givendatafile; 
377
+else 
378
+  temp_din = tempname; 
379
+  som_write_data(D, temp_din, 'x')
380
+end
381
+temp_cin  = tempname;
382
+som_write_cod(sMap, temp_cin)
383
+temp_cout = tempname;
384
+
385
+% check if the environment variable 'SOM_PAKDIR' has been defined
386
+if any(strcmp('SOM_PAKDIR', evalin('base', 'who')))
387
+  som_pak_dir = evalin('base', 'SOM_PAKDIR');
388
+else
389
+  som_pak_dir = '';
390
+end
391
+if ~isempty(som_pak_dir) & ~strncmp(som_pak_dir(end), '/', 1)
392
+  som_pak_dir(end + 1) = '/';
393
+end
394
+
395
+aini  = sTrain.alpha_ini; 
396
+atype = sTrain.alpha_type;
397
+if strcmp(atype,'inv'), atype = 'inverse_t'; end
398
+rad   = sTrain.radius_ini;
399
+str = [som_pak_dir 'vsom ' ...
400
+       sprintf('-cin %s -din %s -cout %s', temp_cin, temp_din, temp_cout) ...
401
+       sprintf(' -rlen %d -alpha %g -alpha_type %s', rlen, aini, atype) ...
402
+       sprintf(' -radius %g -rand %g ',rad,random_seed)];
403
+if ~isempty(snapshotname) & snapinterval>0, 
404
+  str = [str, sprintf(' -snapfile %s -snapinterval %d',snapshotname,snapshotinterval)];
405
+end
406
+
407
+fprintf(1,'Execute: %s\n',str);
408
+if isunix, 
409
+  [status,w] = unix(str); 
410
+  if status, fprintf(1,'Execution failed.\n'); end
411
+  if ~isempty(w), fprintf(1,'%s\n',w); end
412
+else 
413
+  [status,w] = dos(str); 
414
+  if status, fprintf(1,'Execution failed.\n'); end
415
+  if ~isempty(w), fprintf(1,'%s\n',w); end
416
+end
417
+
418
+sMap_temp = som_read_cod(temp_cout);
419
+M = sMap_temp.codebook;
420
+
421
+if isunix
422
+  unix(['/bin/rm -f ' temp_din ' ' temp_cin ' ' temp_cout]);
423
+else
424
+  dos(['del ' temp_din ' ' temp_cin ' ' temp_cout]);
425
+end
426
+
427
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
428
+%% Build / clean up the return arguments
429
+
430
+% update structures
431
+sTrain = som_set(sTrain,'time',datestr(now,0));
432
+if struct_mode, 
433
+  sMap = som_set(sMap,'codebook',M,'mask',sTrain.mask,'neigh',sTrain.neigh);
434
+  tl = length(sMap.trainhist);
435
+  sMap.trainhist(tl+1) = sTrain;
436
+else
437
+  sMap = reshape(M,orig_size);
438
+end
439
+
440
+return;
441
+
442
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
443
+
... ...
@@ -0,0 +1,257 @@
1
+function csS = som_stats(D,varargin)
2
+
3
+%SOM_STATS Calculate descriptive statistics for the data.
4
+%  
5
+% csS = som_stats(D,[sort]); 
6
+% 
7
+%  csS = som_stats(D); 
8
+%  csS = som_stats(D,'nosort'); 
9
+%  som_table_print(som_stats_table(csS))
10
+%
11
+%  Input and output arguments ([]'s are optional): 
12
+%   D           (matrix) a matrix, size dlen x dim
13
+%               (struct) data or map struct
14
+%   [sort]      (string) 'sort' (default) or 'nosort'
15
+%                        If 'nosort' is specified, the data is not 
16
+%                        sorted, and therefore the values of
17
+%                        nunique, uvalues, ucount, fvalues, fcount, and tiles fields 
18
+%                        are not calculated. This may be useful if
19
+%                        there is a very large amount of data, and
20
+%                        one wants to reduce calculation time.
21
+%
22
+%   csS         (cell array) size dim x 1, of statistics structs with 
23
+%                        the following fields
24
+%      .type             (string) 'som_stat'
25
+%      .name             (string) name of the variable
26
+%      .normalization    (struct array) variable normalization (see SOM_NORMALIZE)
27
+%      .ntotal           (scalar) total number of values
28
+%      .nvalid           (scalar) number of valid values (not Inf or NaN)
29
+%      .min              (scalar) minimum value 
30
+%      .max              (scalar) maximum value 
31
+%      .mean             (scalar) mean value (not Inf or NaN)
32
+%      .std              (scalar) standard deviation (not Inf or NaN)
33
+%      .nunique          (scalar) number of unique values
34
+%      .mfvalue          (vector) most frequent value
35
+%      .mfcount          (vector) number of occurances of most frequent value
36
+%      .values           (vector) at most MAXDISCRETE (see below) sample values 
37
+%      .counts           (vector) number of occurances for each sampled value
38
+%      .tiles            (vector) NT-tile values, for example
39
+%                                    NT=4   for quartiles: 25%, 50% and 75%
40
+%                                    NT=100 for percentiles: 1%, 2%, ... and 99%
41
+%      .hist             (struct) histogram struct with the following fields
42
+%           .type        (string) 'som_hist'
43
+%           .bins        (vector) histogram bin centers 
44
+%           .counts      (vector) count of values in each bin
45
+%           .binlabels   (cellstr) labels for the bins (denormalized bin
46
+%                                  center values)
47
+%           .binlabels2  (cellstr) labels for the bins (denormalized bin
48
+%                                  edge values, e.g. '[1.4,2.5['
49
+%
50
+%   Constants: 
51
+%      MAXDISCRETE = 10
52
+%      NT          = 10
53
+%
54
+% See also  SOM_STATS_PLOT, SOM_STATS_TABLE, SOM_TABLE_PRINT, SOM_STATS_REPORT.
55
+
56
+% Contributed to SOM Toolbox 2.0, December 31st, 2001 by Juha Vesanto
57
+% Copyright (c) by Juha Vesanto
58
+% http://www.cis.hut.fi/projects/somtoolbox/
59
+
60
+% Version 2.0beta juuso 311201
61
+
62
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
63
+%% arguments
64
+
65
+% default values
66
+nosort      = 0; 
67
+nbins       = 10; 
68
+maxdiscrete = 20; 
69
+ntiles      = 10; 
70
+
71
+% first argument
72
+if isstruct(D), 
73
+    switch D.type, 
74
+    case 'som_map',  cn = D.comp_names; sN = D.comp_norm; D = D.codebook; 
75
+    case 'som_data', cn = D.comp_names; sN = D.comp_norm; D = D.data; 
76
+    otherwise, error('Invalid first argument')
77
+    end    
78
+else
79
+    cn = cell(size(D,2),1); 
80
+    cn(:) = {'Variable'};
81
+    for i=1:length(cn), cn{i} = sprintf('%s%d',cn{i},i); end    
82
+    sN = cell(size(D,2),1); 
83
+end
84
+[dlen dim] = size(D);
85
+
86
+% other arguments
87
+
88
+if length(varargin)>0, 
89
+  if strcmp(varargin{1},'nosort'), nosort = 1; end
90
+end
91
+
92
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
93
+%% action
94
+
95
+sStat = struct('type','som_stat','name','','normalization',[],...
96
+               'min',NaN,'max',NaN,'mean',NaN,'std',NaN,...
97
+               'nunique',NaN,'values',[],'counts',[],'mfvalue',NaN,'mfcount',NaN,'tiles',[],...
98
+               'ntotal',dlen,'nvalid',NaN,'hist',[]);
99
+csS = cell(0);
100
+           
101
+for i=1:dim, 
102
+    sS = sStat;
103
+    sS.name = cn{i};
104
+    sS.normalization = sN{i}; 
105
+    x = D(:,i); 
106
+    x(find(~isfinite(x))) = [];
107
+    % basic descriptive statistics
108
+    sS.nvalid = length(x);
109
+    if length(x), 
110
+        sS.min  = min(x);
111
+        sS.max  = max(x);
112
+        sS.mean = mean(x);  
113
+        sS.std = std(x);
114
+        bins = [];
115
+        if ~nosort, 
116
+            xsorted    = sort(x);
117
+            % number of unique values
118
+            repeated   = (xsorted(1:end-1)==xsorted(2:end));
119
+            j          = [1; find(~repeated)+1];         
120
+            xunique    = xsorted(j); 
121
+            sS.nunique = length(xunique);           
122
+            ucount     = diff([j; length(xsorted)+1]);
123
+            % most frequent value
124
+            [fcount,j] = max(ucount);
125
+            sS.mfvalue = xunique(j);
126
+            sS.mfcount = fcount;
127
+            % -tiles (k*100/ntiles % of values, k=1..)
128
+            pickind    = round(linspace(1,sS.nvalid,ntiles+1)); 
129
+            pickind    = pickind(2:end-1);
130
+            sS.tiles   = xsorted(pickind);
131
+            if sS.nunique <= sS.nvalid/2, 
132
+                % unique values
133
+                sS.values = xunique; 
134
+	            sS.counts = ucount; 
135
+                bins = sS.values; 
136
+            else
137
+                % just maxdiscrete values, evenly  picked
138
+                pickind    = round(linspace(1,sS.nunique,maxdiscrete));
139
+                sS.values  = xunique(pickind);
140
+                sS.counts  = ucount(pickind);
141
+ 	    
142
+                %% OPTION 2: maxdiscrete most frequent values
143
+                %[v,j]     = sort(ucount); 
144
+                %pickind   = j(1:maxdiscrete);             
145
+                %sS.values = xunique(pickind);
146
+                %sS.counts = ucount(pickind);
147
+
148
+                % OPTION 3: representative values - calculated using k-means
149
+                %[y,bm,qe] = kmeans(x,maxdiscrete);
150
+               %sS.values = y; 
151
+                %sS.counts = full(sum(sparse(bm,1:length(bm),1,maxdiscrete,length(bm)),2));
152
+            end 
153
+        end 
154
+        if isempty(bins), 
155
+            bins = linspace(sS.min,sS.max,nbins+1); 
156
+            bins = (bins(1:end-1)+bins(2:end))/2; 
157
+        end
158
+        sS.hist = som_hist(x,bins,sS.normalization);    
159
+    else
160
+        sS.hist = som_hist(x,0);
161
+    end
162
+    csS{end+1} = sS; 
163
+end
164
+
165
+return;
166
+
167
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
168
+%% subfunctions
169
+
170
+function sH = som_hist(x,bins,sN)
171
+
172
+    binlabels  = []; 
173
+    binlabels2 = []; 
174
+    if nargin<2 | isempty(bins) | isnan(bins), 
175
+        bins = linspace(min(x),max(x),10);    
176
+    end
177
+    if isstruct(bins), 
178
+        bins = sH.bins; 
179
+        binlabels  = sH.binlabels;
180
+        binlabels2 = sH.binlabels2;
181
+    end 
182
+    if nargin<3, sN = []; end
183
+
184
+    sH = struct('type','som_hist','bins',bins,'counts',[],...
185
+                'binlabels',binlabels,'binlabels2',binlabels2);                         
186
+            
187
+    if length(bins)==1,
188
+        sH.counts = [length(x)];
189
+        edges = bins;
190
+    elseif length(x),
191
+        edges = (bins(1:end-1)+bins(2:end))/2;
192
+        counts = histc(x,[-Inf; edges(:); Inf]);
193
+        sH.counts = counts(1:end-1);       
194
+    end 
195
+
196
+    if isempty(sH.binlabels),
197
+        b = som_denormalize(bins(:),sN); 
198
+        sH.binlabels = numtostring(b,4);
199
+    end 
200
+
201
+    if isempty(sH.binlabels2),
202
+        if length(edges)==1, 
203
+            sH.binlabels2 = numtostring(som_denormalize(edges,sN),2);
204
+            if length(bins)>1, 
205
+              sH.binlabels2 = sH.binlabels2([1 1]);
206
+              sH.binlabels2{1} = [']' sH.binlabels2{1} '['];
207
+              sH.binlabels2{2} = ['[' sH.binlabels2{2} '['];
208
+            end 
209
+        else
210
+            if size(edges,1)==1, edges = edges'; end
211
+            bstr = numtostring(som_denormalize(edges,sN),4);
212
+            sH.binlabels2 = bstr([1:end end]);
213
+            sH.binlabels2{1} = [bstr{1} '['];
214
+            for i=2:length(sH.binlabels2)-1,
215
+                sH.binlabels2{i} = ['[' bstr{i-1} ',' bstr{i} '[']; 
216
+            end 
217
+            sH.binlabels2{end} = ['[' bstr{end}];
218
+        end         
219
+    end 
220
+    
221
+    if 0, 
222
+        if length(bins)==1, sH.binlabels2 = {'constant'}; 
223
+        else    
224
+            ntiles = 10; 
225
+            plim = [1:ntiles-1] / ntiles; 
226
+            cp = cumsum(sH.counts)/sum(sH.counts);
227
+            [dummy,i] = histc(cp,[-Inf plim Inf]);            
228
+            l2 = cell(length(bins),1);            
229
+            for j=1:length(bins), l2{j} = sprintf('Q%d',i(j)); end
230
+            if i(1) > 1, l2{1} = ['...' l2{1}]; end            
231
+            k = 0; 
232
+            for j=2:length(bins), 
233
+                if i(j)==i(j-1), 
234
+                    if k==0, l2{j-1} = [l2{j-1} '.1']; k = 1; end
235
+                    k = k + 1; 
236
+                    l2{j} = [l2{j} '.' num2str(k)]; 
237
+                else k = 0; end
238
+            end 
239
+            if i(end) < ntiles, l2{end} = [l2{end} '...']; end
240
+            sH.binlabels2 = l2; 
241
+        end 
242
+    end    
243
+
244
+    return;
245
+
246
+function vstr = numtostring(v,d)
247
+
248
+    r = max(v)-min(v); 
249
+    if r==0, r=1; end
250
+    nearzero = (abs(v)/r < 10.^-d);
251
+    i1 = find(v > 0 & nearzero); 
252
+    i2 = find(v < 0 & nearzero);     
253
+    vstr = strrep(cellstr(num2str(v,d)),' ','');
254
+    vstr(i1) = {'0.0'};
255
+    vstr(i2) = {'-0.0'};
256
+    return;
257
+
... ...
@@ -0,0 +1,144 @@
1
+function som_stats_plot(csS,plottype,varargin)
2
+
3
+%SOM_STATS_PLOT Plots of data set statistics.
4
+%  
5
+% som_stats_plot(csS, plottype, [argID, value, ...])
6
+%
7
+%  som_stats_plot(csS,'stats')
8
+%  som_stats_plot(csS,'stats','p','vert','color','r')
9
+%
10
+%  Input and output arguments ([]'s are optional): 
11
+%   csS         (cell array) of statistics structs
12
+%               (struct) a statistics struct
13
+%   plottype    (string) some of the following
14
+%                        'hist'   histogram
15
+%                        'box'    min, max, mean, and std shown as a boxplot
16
+%                        'stats'  both histogram (with black) and the boxplot
17
+%   [argID, (string) See below. The values which are unambiguous can 
18
+%    value] (varies) be given without the preceeding argID.
19
+%
20
+% Here are the valid argument IDs and corresponding values. The values which
21
+% are unambiguous (marked with '*') can be given without the preceeding argID.
22
+%   'counts'      *(string) 'c' (for counts, the default) or 'p' (for percentages)
23
+%   'color'        (vector) size 1 x 3, color to be used
24
+%                  (string) a color string
25
+%   'title'        (string) 'on' (default) or 'off'
26
+%   'orientation' *(string) 'horiz' or 'vert' (default): orientation for the 
27
+%                           bin values (horizontally or vertically)
28
+%
29
+% See also  SOM_STATS, SOM_STATS_TABLE, SOM_TABLE_PRINT, SOM_STATS_REPORT.
30
+
31
+% Contributed to SOM Toolbox 2.0, December 31st, 2001 by Juha Vesanto
32
+% Copyright (c) by Juha Vesanto
33
+% http://www.cis.hut.fi/projects/somtoolbox/
34
+
35
+% Version 2.0beta juuso 311201
36
+
37
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
38
+%% arguments
39
+
40
+% statistics
41
+if isstruct(csS), csS = {csS}; end
42
+
43
+% default values
44
+useprob   = 0; 
45
+color     = [0 0 1];
46
+showtitle = 1; 
47
+horiz     = 0; 
48
+
49
+% varargin
50
+i=1; 
51
+while i<=length(varargin), 
52
+  argok = 1; 
53
+  if ischar(varargin{i}), 
54
+    switch varargin{i}, 
55
+     % argument IDs
56
+     case 'counts',      i=i+1; useprob = strcmp(varargin{i}(1),'p'); 
57
+     case 'color',       i=i+1; color = varargin{i}; 
58
+     case 'title',       i=i+1; showtitle = strcmp(varargin{i},'on');
59
+     case 'orientation', i=i+1; horiz = strcmp(varargin{i},'horiz'); 
60
+     % unambiguous values
61
+     case {'horiz','vert'}, horiz = strcmp(varargin{i},'horiz'); 
62
+     case {'c','p'}, useprob = strcmp(varargin{i}(1),'p'); 
63
+     otherwise argok=0; 
64
+    end
65
+  elseif isstruct(varargin{i}) & isfield(varargin{i},'type'), 
66
+    argok = 0; 
67
+  else
68
+    argok = 0; 
69
+  end
70
+  if ~argok, 
71
+    disp(['(som_stats_plot) Ignoring invalid argument #' num2str(i+2)]); 
72
+  end
73
+  i = i+1; 
74
+end
75
+
76
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
77
+%% action
78
+
79
+ss = ceil(sqrt(length(csS))); ss = [ss, ceil(length(csS)/ss)];
80
+
81
+for j = 1:length(csS), 
82
+    sS = csS{j};    
83
+    subplot(ss(1),ss(2),j);
84
+    switch plottype, 
85
+    case 'stats',
86
+        cla, hold on
87
+        Counts = sS.hist.counts; 
88
+        if useprob, for i=1:size(Counts,2), Counts(:,i) = Counts(:,i)/sum(Counts(:,i)); end, end
89
+        hist_plot(sS.hist.bins,sS.hist.binlabels,Counts,color);
90
+        box_plot(sS.min,sS.max,sS.mean,sS.std,[0 0 0]);
91
+    case 'hist',
92
+        cla, hold on
93
+        Counts = sS.hist.counts; 
94
+        if useprob, for i=1:size(Counts,2), Counts(:,i) = Counts(:,i)/sum(Counts(:,i)); end, end
95
+        hist_plot(sS.hist.bins,sS.hist.binlabels,Counts,color);
96
+    case 'box', 
97
+        cla
98
+	box_plot(sS.min,sS.max,sS.mean,sS.std,color);    
99
+    end
100
+    if showtitle, title(sprintf('%s (valid: %d/%d)',sS.name,sS.nvalid,sS.ntotal)); end
101
+    if ~horiz, view(90,-90); end
102
+    a = axis; a(1) = sS.min; a(2) = sS.max; axis(a); 
103
+end
104
+
105
+return;
106
+
107
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
108
+%% subfunctions
109
+
110
+function hist_plot(bins,binlabels,Counts,color)
111
+    
112
+    if nargin<4, color = jet(size(Counts,2)); end
113
+    h = bar(bins,Counts);
114
+    for j=1:length(h), set(h(j),'facecolor',color(j,:),'edgecolor','none'); end
115
+    a = axis; a(3:4) = [0 max(Counts(:))]; axis(a);
116
+    set(gca,'XTick',bins,'XTickLabel',binlabels);
117
+    return;
118
+
119
+function vstr = numtostring(v,d)
120
+
121
+    nearzero = (abs(v)/(max(v)-min(v)) < 10.^-d);
122
+    i1 = find(v > 0 & nearzero); 
123
+    i2 = find(v < 0 & nearzero);     
124
+    vstr = strrep(cellstr(num2str(v,d)),' ','');
125
+    vstr(i1) = {'0.0'};
126
+    vstr(i2) = {'-0.0'};
127
+    return;
128
+
129
+function box_plot(mi,ma,me,st,Color)
130
+
131
+    if nargin < 5, Color = jet(length(mi)); end
132
+    a = axis;      
133
+    y = linspace(a(3),a(4),length(mi)+2); y = y(2:end);
134
+    d = (y(2)-y(1))/20;   
135
+    for i=1:length(mi),
136
+        h1 = line([mi(i) ma(i)],[y(i) y(i)]); 
137
+        h2 = line([mi(i) mi(i) NaN ma(i) ma(i)],[y(i)-d y(i)+d NaN y(i)-d y(i)+d]); 
138
+        h3 = line([me(i)-st(i) me(i)+st(i)],[y(i) y(i)]); 
139
+        h4 = line([me(i) me(i)],[y(i)-2*d y(i)+2*d]); 
140
+        set([h1 h2 h3 h4],'color',Color(i,:));
141
+        set([h1 h2],'linewidth',1);
142
+        set([h3 h4],'linewidth',3);
143
+    end 
144
+    return;
... ...
@@ -0,0 +1,113 @@
1
+function som_stats_report(csS,fname,fmt,texonly)
2
+
3
+% SOM_STATS_REPORT Make report of the statistics.
4
+%  
5
+% som_stats_report(csS, fname, fmt, [standalone])
6
+%
7
+%  som_stats_report(csS, 'data_stats', 'ps')
8
+%
9
+%  Input and output arguments ([]'s are optional): 
10
+%   csS          (cell array) of statistics structs
11
+%                (struct) a statistics struct
12
+%   fname        (string) output file name (without extension)
13
+%                (cellstr) {direc, fname}
14
+%   fmt          (string) report format: 'ps', 'pdf', 'html' or 'txt'
15
+%   [texonly]    (any)    for 'ps' and 'pdf' formats: if 4th argument 
16
+%                         is given, only the tex file is written 
17
+%                         (w/o document start/end), and it is not compiled
18
+%
19
+% See also  SOM_STATS, SOM_STATS_PLOT, SOM_STATS_TABLE, SOM_TABLE_PRINT, REP_UTILS.
20
+
21
+% Contributed to SOM Toolbox 2.0, December 31st, 2001 by Juha Vesanto
22
+% Copyright (c) by Juha Vesanto
23
+% http://www.cis.hut.fi/projects/somtoolbox/
24
+
25
+% Version 2.0beta juuso 311201
26
+
27
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
28
+%% input arguments
29
+
30
+if isstruct(csS), csS = {csS}; end
31
+dim = length(csS);
32
+if iscell(fname), direc = fname{1}; fname = fname{2}; else direc = '.'; end
33
+if nargin<4, texonly = 0; else texonly = 1; end
34
+
35
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
36
+%% action
37
+
38
+% additional analysis
39
+continuity = zeros(dim,1);
40
+for i=1:dim, continuity(i) = csS{i}.nunique / csS{i}.nvalid; end
41
+
42
+entropy_rel = zeros(dim,1);
43
+for i=1:dim, 
44
+    c = csS{i}.hist.counts; 
45
+    if length(c) < 2 | all(c==0), entropy(i) = 0; 
46
+    else
47
+        maxent = log(length(c));
48
+        c = c(c>0)/sum(c);
49
+        entropy_rel(i) = -sum(c.*log(c)) / maxent;
50
+    end 
51
+end
52
+
53
+% meta-statistics
54
+values  = {'Number of variables',dim; ...
55
+           'Number of samples',csS{1}.ntotal; ...
56
+           'Valid values',c_and_p_str(count_total(csS,'nvalid'),dim*csS{1}.ntotal); ...
57
+           'Mean(#unique / #valid)',mean(continuity); ...
58
+           'Mean relative entropy',mean(entropy_rel)};
59
+           %'Dataset name',sD.name; 'Report generated',datestr(now);          
60
+sTdset = som_table_struct(values);
61
+
62
+% statistics tables
63
+[sTstats,csThist] = som_stats_table(csS); 
64
+sTstats = som_table_modify(sTstats,'addcol',entropy_rel,{'entropy'});
65
+
66
+% write report
67
+if isempty(fname), fid = 1; 
68
+else 
69
+    switch fmt,
70
+    case {'ps','pdf'}, ending = '.tex'; 
71
+    case 'html', ending = '.html'; 
72
+    case 'txt', ending = '.txt'; 
73
+    end 
74
+    fid = fopen([direc '/' fname ending],'w'); 
75
+end
76
+if ~texonly, rep_utils('header',fmt,fid); end
77
+
78
+rep_utils({'inserttable',sTdset,1,0},fmt,fid);
79
+rep_utils({'insertbreak'},fmt,fid);
80
+rep_utils({'inserttable',sTstats,1,0},fmt,fid);
81
+rep_utils({'insertbreak'},fmt,fid);
82
+som_stats_plot(csS,'stats'); 
83
+rep_utils({'printfigure',[direc '/histograms']},fmt);
84
+rep_utils({'insertfigure','histograms'},fmt,fid);
85
+for i=1:dim, 
86
+    rep_utils({'insertbreak'},fmt,fid);
87
+    rep_utils({'inserttable',csThist{i},1,0},fmt,fid);
88
+end 
89
+
90
+if ~texonly, rep_utils('footer',fmt,fid); end
91
+if fid~=1, fclose(fid); end
92
+
93
+if ~texonly & any(strcmp(fmt,{'ps','pdf'})), rep_utils('compile',fmt); end
94
+return;
95
+
96
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
97
+%% subfunctions
98
+
99
+function a = count_total(csS,field)
100
+  % count total of the field values
101
+  a = 0; for i=1:length(csS), a = a + getfield(csS{i},field); end
102
+  return;
103
+  
104
+function str = c_and_p_str(n,m)
105
+  % return a string of form # (%), e.g. '23 (12%)'
106
+  if n==m, p = '100'; 
107
+  elseif n==0, p = '0';
108
+  else p = sprintf('%.2g',100*n/m);
109
+  end
110
+  str = sprintf('%d (%s%%)',round(n),p); 
111
+  return;
112
+
113
+  
... ...
@@ -0,0 +1,116 @@
1
+function [sTstats,csThist] = som_stats_table(csS,histlabel)
2
+
3
+%SOM_STATS_TABLE Statistics table.
4
+%  
5
+% [sTstats,csThist] = som_stats_table(csS)
6
+% 
7
+%   sTstats = som_stats_table(csS); 
8
+%   som_table_print(sTstats);
9
+%  
10
+%  Input and output arguments ([]'s are optional): 
11
+%   csS           (cell array) of statistics structs
12
+%                 (struct) a statistics struct
13
+%
14
+%   sTstats       (struct) a table struct with basic descriptive 
15
+%                          statistics for each variable
16
+%   csThist       (cell array) of table structs, with histograms for
17
+%                          each variable
18
+%
19
+% See also  SOM_STATS, SOM_STATS_PLOT, SOM_TABLE_PRINT, SOM_STATS_REPORT.
20
+
21
+% Contributed to SOM Toolbox 2.0, December 31st, 2001 by Juha Vesanto
22
+% Copyright (c) by Juha Vesanto
23
+% http://www.cis.hut.fi/projects/somtoolbox/
24
+
25
+% Version 2.0beta juuso 311201
26
+
27
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
28
+%% arguments
29
+
30
+if isstruct(csS), csS = {csS}; end
31
+dim = length(csS);
32
+
33
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
34
+%% action
35
+
36
+sTable = struct('colfmt','','headers',[],'values',[],'span',[]); 
37
+
38
+% summary table of all variables
39
+sT = sTable; 
40
+sT.headers = {'name','min','mean','max','std','missing'};
41
+if ~isnan(csS{1}.nunique), sT.headers{end+1} = 'unique'; end
42
+%if length(col_values), sT.headers = [sT.headers, col_headers]; end
43
+sT.values  = cell(dim,length(sT.headers));
44
+sT.span    = ones([size(sT.values) 2]); 
45
+
46
+%if length(col_values), sT.values(:,end-size(col_values,2)+1:end) = col_values; end 
47
+%if length(col_spans),  sT.span(:,end-size(col_spans,2)+1:end,:)  = col_spans;  end 
48
+
49
+for i=1:dim, 
50
+    sT.values{i,1} = csS{i}.name;
51
+    v = [csS{i}.min,csS{i}.mean,csS{i}.max,csS{i}.std];
52
+    v = som_denormalize(v,csS{i}.normalization); 
53
+    vstr = numtostring(v,6);
54
+    sT.values(i,2:5) = vstr'; 
55
+    sT.values{i,6} = c_and_p_str(csS{i}.ntotal-csS{i}.nvalid,csS{i}.ntotal); 
56
+    if ~isnan(csS{1}.nunique),
57
+        sT.values{i,7} = c_and_p_str(csS{i}.nunique,csS{i}.nvalid);
58
+    end
59
+end
60
+sTstats = sT; 
61
+
62
+% histograms
63
+csThist = cell(dim,1); 
64
+for i=1:dim, 
65
+    sH     = csS{i}.hist; 
66
+    nvalid = csS{i}.nvalid;
67
+    nbins  = length(sH.bins); 
68
+    sT         = sTable; 
69
+    sT.headers = {[csS{i}.name ' values'],'frequency #','frequency %'};
70
+    sT.values  = cell(nbins,length(sT.headers));  
71
+    sT.span    = ones(nbins,length(sT.headers),2);
72
+    for j=1:nbins,         
73
+        if length(sH.bins) < csS{i}.nunique, sT.values{j,1} = sH.binlabels2{j};
74
+        else sT.values{j,1} = sH.binlabels{j}; end
75
+        sT.values{j,2} = sprintf('%d',round(sH.counts(j)));
76
+        sT.values{j,3} = p_str(sH.counts(j)/nvalid);
77
+    end     
78
+    csThist{i} = sT; 
79
+end   
80
+   
81
+return; 
82
+
83
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
84
+%% subfunctions
85
+
86
+function vstr = numtostring(v,d)
87
+
88
+    tp = (size(v,2)>1);  
89
+    if tp, v = v'; end
90
+    nearzero = (abs(v)/(max(v)-min(v)) < 10.^-d);
91
+    i1 = find(v > 0 & nearzero); 
92
+    i2 = find(v < 0 & nearzero);     
93
+    vstr = strrep(cellstr(num2str(v,d)),' ','');
94
+    vstr(i1) = {'0.0'};
95
+    vstr(i2) = {'-0.0'};
96
+    if tp, vstr = vstr'; end
97
+    return;
98
+
99
+function str = c_and_p_str(n,m)
100
+  % return a string of form # (%), e.g. '23 (12%)'
101
+  if     n==m, p = '100'; 
102
+  elseif n==0, p = '0';
103
+  else         p = sprintf('%.2g',100*n/m);
104
+  end
105
+  str = sprintf('%d (%s%%)',round(n),p); 
106
+  return;
107
+
108
+function str = p_str(p)
109
+  % return a string of form %, e.g. '12%'
110
+  if round(p*100)>100,  p = sprintf('%3g',100*p); 
111
+  elseif p==1,          p = '100';
112
+  elseif abs(p)<eps,    p = '0';
113
+  else                  p = sprintf('%.2g',100*p);
114
+  end
115
+  str = sprintf('%s%%',p); 
116
+  return;
... ...
@@ -0,0 +1,43 @@
1
+function inds = som_sub2ind(msize,Subs)
2
+
3
+%SOM_SUB2IND Linear index from map grid subscripts.
4
+%
5
+% ind = som_sub2ind(msize,Subs)
6
+%
7
+%  ind = som_sub2ind([10 15],[4 5]);
8
+%  ind = som_sub2ind(sMap,[4 5]);
9
+%  ind = som_sub2ind(sMap.msize,[4 5]);
10
+%  inds = som_sub2ind([10 15],[4 5; 3 2; 1 10]);
11
+%
12
+%  Input and output arguments: 
13
+%   msize  (struct) map or topology struct
14
+%          (vector) size 1 x m, specifies the map grid size
15
+%   Subs   (matrix) size n x m, the subscripts of n vectors
16
+%
17
+%   inds   (vector) size n x 1, corresponding linear indeces
18
+%
19
+% See also SOM_IND2SUB.
20
+
21
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Vesanto
22
+% http://www.cis.hut.fi/projects/somtoolbox/
23
+
24
+% juuso 300798
25
+
26
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
27
+
28
+if isstruct(msize), 
29
+  if strcmp(msize.type,'som_map'), msize = msize.topol.msize; 
30
+  elseif strcmp(msize.type,'som_topol'), msize = msize.msize;
31
+  else error('Invalid first argument.'); end
32
+end
33
+
34
+% check off-limits
35
+[n d] = size(Subs);
36
+offl = find(Subs < 1 | Subs > msize(ones(n,1),1:d)); 
37
+Subs(offl) = NaN;
38
+
39
+% indexes
40
+k = [1 cumprod(msize(1:end-1))]';
41
+inds = 1 + (Subs-1)*k;
42
+
43
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,337 @@
1
+function sM  = som_supervised(sData,varargin)
2
+
3
+%SOM_SUPERVISED SOM training which utilizes class information.
4
+%
5
+% sM = som_supervised(sData, [ArgID, value,...]))
6
+%
7
+%  Input and output arguments ([]'s are optional)
8
+%   sData    (struct) data struct, the class information is 
9
+%                     taken from the first column of .labels field
10
+%   [argID,  (string) See below. These are given as 
11
+%    value]  (varies) 'argID', value -pairs.
12
+%
13
+%   sMap     (struct) map struct
14
+%
15
+%  Here are the argument IDs and corresponding values: 
16
+%  'munits'     (scalar) the preferred number of map units
17
+%  'msize'      (vector) map grid size
18
+%  'mask'       (vector) BMU search mask, size dim x 1
19
+%  'name'       (string) map name
20
+%  'comp_names' (string array / cellstr) component names, size dim x 1
21
+%  'tracking'   (scalar) how much to report, default = 1
22
+%  The following values are unambiguous and can therefore
23
+%  be given without the preceeding argument ID:
24
+%  'algorithm'  (string) training algorithm: 'seq' or 'batch'
25
+%  'mapsize'    (string) do you want a 'small', 'normal' or 'big' map
26
+%               Any explicit settings of munits or msize override this.
27
+%  'topol'      (struct) topology struct
28
+%  'som_topol','sTopol' = 'topol'
29
+%  'lattice'    (string) map lattice, 'hexa' or 'rect'
30
+%  'shape'      (string) map shape, 'sheet', 'cyl' or 'toroid'
31
+%  'neigh'      (string) neighborhood function, 'gaussian', 'cutgauss',
32
+%                       'ep' or 'bubble'
33
+%
34
+% For more help, try 'type som_supervised', or check out online documentation.
35
+% See also SOM_MAKE, SOM_AUTOLABEL.
36
+
37
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
38
+%
39
+% som_supervised
40
+%
41
+% PURPOSE
42
+%
43
+% Creates, initializes and trains a supervised SOM by taking the 
44
+% class-identity into account.
45
+%
46
+% SYNTAX
47
+%
48
+% sMap = som_supervised(sData);
49
+% sMap = som_supervised(...,'argID',value,...)
50
+% sMap = som_make(...,value,...);
51
+%
52
+% DESCRIPTION
53
+%
54
+% Creates, initializes and trains a supervised SOM. It constructs the
55
+% training data by adding 1-of-N -coded matrix to the original data
56
+% based on the class information in the .labels field. The dimension
57
+% of vectors after the process is (the old dimension + number of
58
+% different classes). In each vector, one of the new components has
59
+% value '1' (this depends on the class of the vector), and others '0'.
60
+% Calls SOM_MAKE to construct the map. Then the class of each map unit
61
+% is determined by taking maximum over these added components, and a
62
+% label is give accordingly. Finally, the extra components (the
63
+% 1-of-N -coded ones) are removed.
64
+%
65
+% REFERENCES
66
+%
67
+% Kohonen, T., "Self-Organizing Map", 2nd ed., Springer-Verlag, 
68
+%    Berlin, 1995, pp. 160-161.
69
+% Kohonen, T., M�kivasara, K., Saram�ki, T., "Phonetic Maps - 
70
+%    Insightful Representation of Phonological Features For 
71
+%    Speech Recognition", In proceedings of International
72
+%    Conference on Pattern Recognition (ICPR), Montreal, Canada, 
73
+%    1984, pp. 182-185.
74
+%
75
+% REQUIRED INPUT ARGUMENTS
76
+%
77
+% sData           The data to use in the training.
78
+%        (struct) A data struct. '.comp_names' as well as '.name' 
79
+%                 is copied to the map. The class information is 
80
+%                 taken from the first column of '.labels' field.
81
+%
82
+% OPTIONAL INPUT ARGUMENTS 
83
+%
84
+%  argID (string) Argument identifier string (see below).
85
+%  value (varies) Value for the argument (see below).
86
+%
87
+%  The optional arguments can be given as 'argID',value -pairs. If an
88
+%  argument is given value multiple times, the last one is used. 
89
+%  Here are the argument IDs and corresponding values: 
90
+%   'munits'     (scalar) the preferred number of map units - this may 
91
+%                 change a bit, depending on the properties of the data
92
+%   'msize'      (vector) map grid size
93
+%   'mask'       (vector) BMU search mask, size dim x 1
94
+%   'name'       (string) map name
95
+%   'comp_names' (string array / cellstr) component names, size dim x 1
96
+%   'tracking'   (scalar) how much to report, default = 1. This parameter 
97
+%                 is also passed to the training functions. 
98
+%   The following values are unambiguous and can therefore
99
+%   be given without the preceeding argument ID:
100
+%   'algorithm'  (string) training algorithm: 'seq' or 'batch' (default)
101
+%   'mapsize'    (string) do you want a 'small', 'normal' or 'big' map
102
+%                 Any explicit settings of munits or msize (or topol) 
103
+%                 override this.
104
+%   'topol'      (struct) topology struct
105
+%   'som_topol','sTopol' = 'topol'
106
+%   'lattice'    (string) map lattice, 'hexa' or 'rect'
107
+%   'shape'      (string) map shape, 'sheet', 'cyl' or 'toroid'
108
+%   'neigh'      (string) neighborhood function, 'gaussian', 'cutgauss',
109
+%                 'ep' or 'bubble'
110
+%
111
+% OUTPUT ARGUMENTS
112
+% 
113
+%  sMap (struct)  SOM -map struct
114
+%
115
+% EXAMPLES
116
+%
117
+%  To simply train a map with default parameters:
118
+%
119
+%   sMap = som_supervised(sData);
120
+%
121
+%  With the optional arguments, the initialization and training can be
122
+%  influenced. To change map size, use 'msize', 'munits' or 'mapsize'
123
+%  arguments:  
124
+%
125
+%   sMap = som_supervised(D,'mapsize','big'); or 
126
+%   sMap = som_supervised(D,'big');
127
+%   sMap = som_supervised(D,'munits', 100);
128
+%   sMap = som_supervised(D,'msize', [20 10]); 
129
+%
130
+%  Argument 'algorithm' can be used to switch between 'seq' and 'batch'
131
+%  algorithms. 'batch' is the default, so to use 'seq' algorithm: 
132
+%
133
+%   sMap = som_supervised(D,'algorithm','seq'); or 
134
+%   sMap = som_supervised(D,'seq'); 
135
+%
136
+%  The 'tracking' argument can be used to control the amout of reporting
137
+%  during training. The argument is used in this function, and it is
138
+%  passed to the training functions. To make the function work silently
139
+%  set it to 0.
140
+%
141
+%   sMap = som_supervised(D,'tracking',0); 
142
+%
143
+% SEE ALSO
144
+% 
145
+%  som_make         Create, initialize and train Self-Organizing map.
146
+%  som_autolabel    Label SOM/data set based on another SOM/data set.
147
+
148
+% Contributed to SOM Toolbox vs2, Feb 2nd, 2000 by Juha Parhankangas
149
+% Copyright (c) by Juha Parhankangas
150
+% http://www.cis.hut.fi/projects/somtoolbox/
151
+
152
+% Juha Parhankangas 050100
153
+
154
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
155
+
156
+D0 = sData.data;
157
+[c,n,classlabels] = class2num(sData.labels(:,1));
158
+
159
+%%%%%%%% Checking arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
160
+
161
+if ~isstruct(sData)
162
+  error('Argument ''sData'' must be a ''som_data'' -struct.');
163
+else
164
+  data_name = sData.name;
165
+  comp_names = sData.comp_names;
166
+  comp_norm = sData.comp_norm;
167
+end
168
+
169
+[dlen,dim] = size(sData.data);
170
+
171
+% defaults
172
+
173
+mapsize = '';
174
+sM = som_map_struct(dim+n); 
175
+sTopol = sM.topol;
176
+munits = prod(sTopol.msize); % should be zero
177
+mask = sM.mask; 
178
+name = sM.name; 
179
+neigh = sM.neigh; 
180
+tracking = 1;
181
+algorithm = 'batch'; 
182
+
183
+%%%% changes to defaults (checking varargin) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
184
+
185
+i=1; 
186
+while i <= length(varargin) 
187
+  argok = 1; 
188
+  if ischar(varargin{i}) 
189
+    switch varargin{i}, 
190
+      % argument IDs
191
+     case 'mask',       
192
+      i=i+1; 
193
+      mask = varargin{i}; 
194
+     case 'munits',     
195
+      i=i+1; 
196
+      munits = varargin{i}; 
197
+     case 'msize',      
198
+      i=i+1; 
199
+      sTopol.msize = varargin{i}; 
200
+      munits = prod(sTopol.msize); 
201
+     case 'mapsize',    
202
+      i=i+1; 
203
+      mapsize = varargin{i}; 
204
+     case 'name',       
205
+      i=i+1; 
206
+      name = varargin{i};
207
+     case 'comp_names', 
208
+      i=i+1; 
209
+      comp_names = varargin{i}; 
210
+     case 'lattice',    
211
+      i=i+1; 
212
+      sTopol.lattice = varargin{i};
213
+     case 'shape',      
214
+      i=i+1; 
215
+      sTopol.shape = varargin{i}; 
216
+     case {'topol','som_topol','sTopol'}, 
217
+      i=i+1; 
218
+      sTopol = varargin{i}; 
219
+      munits = prod(sTopol.msize); 
220
+     case 'neigh',      
221
+      i=i+1; 
222
+      neigh = varargin{i};
223
+     case 'tracking',   
224
+      i=i+1; 
225
+      tracking = varargin{i};
226
+     case 'algorithm',  
227
+      i=i+1; 
228
+      algorithm = varargin{i}; 
229
+  % unambiguous values
230
+     case {'hexa','rect'}, 
231
+      sTopol.lattice = varargin{i};
232
+     case {'sheet','cyl','toroid'}, 
233
+      sTopol.shape = varargin{i}; 
234
+     case {'gaussian','cutgauss','ep','bubble'}, 
235
+      neigh = varargin{i};
236
+     case {'seq','batch'}, 
237
+      algorithm = varargin{i}; 
238
+     case {'small','normal','big'}, 
239
+      mapsize = varargin{i}; 
240
+     otherwise argok=0; 
241
+    end
242
+  elseif isstruct(varargin{i}) & isfield(varargin{i},'type'), 
243
+    switch varargin{i}(1).type, 
244
+      case 'som_topol', 
245
+       sTopol = varargin{i}; 
246
+     otherwise argok=0; 
247
+    end
248
+  else
249
+    argok = 0; 
250
+  end
251
+  if ~argok, 
252
+    disp(['(som_supervised) Ignoring invalid argument #' num2str(i+1)]); 
253
+  end
254
+  i = i+1; 
255
+end
256
+
257
+%%%%%%%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
258
+
259
+
260
+
261
+% constructing the training data by adding 1-of-N -coded matrix to the
262
+% original data.
263
+
264
+[dlen,dim] = size(D0);
265
+
266
+Dc = zeros(dlen,n);
267
+
268
+for i=1:dlen 
269
+  if c(i)
270
+    Dc(i,c(i)) = 1;
271
+  end
272
+end
273
+
274
+D = [D0, Dc];
275
+
276
+% initialization and training 
277
+
278
+sD = som_data_struct(D,...
279
+                     'name',data_name);
280
+
281
+sM = som_make(sD,...
282
+              'mask',mask,...
283
+              'munits',munits,...
284
+              'name',data_name,...
285
+              'tracking',tracking,...
286
+              'algorithm',algorithm,...
287
+              'mapsize',mapsize,...
288
+              'topol',sTopol,...
289
+              'neigh',neigh);
290
+
291
+% add labels
292
+
293
+for i=1:prod(sM.topol.msize), 
294
+  [dummy,class] = max(sM.codebook(i,dim+[1:n]));
295
+  sM.labels{i} = classlabels{class};
296
+end
297
+
298
+%sD.labels = sData.labels;
299
+%sM = som_autolabel(sM,sD,'vote');
300
+
301
+% remove extra components and modify map -struct
302
+
303
+sM.codebook = sM.codebook(:,1:dim);
304
+sM.mask = sM.mask(1:dim);
305
+sM.comp_names = sData.comp_names;
306
+sM.comp_norm = sData.comp_norm;
307
+
308
+% remove extras from sM.trainhist
309
+
310
+for i=1:length(sM.trainhist)
311
+  if sM.trainhist(i).mask
312
+    sM.trainhist(i).mask = sM.trainhist(i).mask(1:dim);
313
+  end
314
+end
315
+
316
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
317
+
318
+function [numbers, n, names] = class2num(class)
319
+
320
+names = {};
321
+numbers = zeros(length(class),1);
322
+
323
+for i=1:length(class)
324
+  if ~isempty(class{i}) & ~any(strcmp(class{i},names))
325
+    names=cat(1,names,class(i));
326
+  end
327
+end
328
+
329
+n=length(names);
330
+
331
+tmp_numbers = (1:n)';
332
+
333
+for i=1:length(class)
334
+  if ~isempty(class{i})
335
+    numbers(i,1) = find(strcmp(class{i},names));    
336
+  end
337
+end
... ...
@@ -0,0 +1,91 @@
1
+function sT = som_table_modify(sT,action,arg1,arg2,arg3)
2
+
3
+%SOM_TABLE_MODIFY Modify table: add or remove columns or rows.
4
+%  
5
+% sTable = som_table_modify(sTable,action,arg1,[arg2],[arg3])
6
+% 
7
+%  Input and output arguments ([]'s are optional): 
8
+%   sTable      (struct) table struct
9
+%   action      (string) action id (see below).
10
+%   arg1        (varies) Depending on action, 1 to 3 arguments
11
+%   [arg2]      (varies) are needed. See below.
12
+%   [arg3]      (varies) 
13
+%
14
+%   sTable      (struct) the modified table struct
15
+%
16
+%  Actions and their arguments:
17
+%   'addcol'    Add one or several new columns.
18
+%               arg1 (cell array) new values
19
+%                    (char)       new values (a single column can be given)
20
+%                    (matrix)     new values
21
+%               arg2 (cell array) new headers
22
+%               arg3 (scalar)     at which position the new columns 
23
+%                                 should be inserted (at the end by default)
24
+%   'addrow'    Add one or several new rows.
25
+%               arg1 (cell array) new values
26
+%                    (char)       new values (a single row can be given)
27
+%                    (matrix)     new values
28
+%               arg2 (scalar)     at which position the new rows 
29
+%                                 should be inserted (at the end by default)
30
+%   'removecol' Remove one or several columns.           
31
+%               arg1 (vector)     indeces of columns to be removed
32
+%   'removerow' Remove one or several rows.           
33
+%               arg1 (vector)     indeces of rows to be removed
34
+% 
35
+% See also  SOM_TABLE_STRUCT, SOM_TABLE_PRINT.
36
+
37
+% Contributed to SOM Toolbox 2.0, January 4th, 2002 by Juha Vesanto
38
+% Copyright (c) by Juha Vesanto
39
+% http://www.cis.hut.fi/projects/somtoolbox/
40
+
41
+% Version 2.0beta juuso 040102
42
+
43
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
44
+
45
+[nrT,ncT] = size(sT.values); 
46
+
47
+switch action, 
48
+ case 'addcol', 
49
+  values = arg1; 
50
+  if ischar(values), values = cellstr(values); end
51
+  if isnumeric(values), values = num2cell(values); end
52
+  spans  = ones([size(values) 2]);
53
+  [nr,nc] = size(values); 
54
+  if nargin<4, header = cell(1,nc); header(:) = {''}; else header = arg2; end
55
+  if ischar(header), header = cellstr(header); end
56
+  if nargin<5, where = ncT+1; else  where  = arg3; end
57
+  if nrT ~= nr, 
58
+    error('Mismatch between sizes of given table and additional columns')
59
+  else
60
+    sT.headers = [sT.headers(:,1:where-1), header, sT.headers(:,where:end)]; 
61
+    sT.values  = [sT.values(:,1:where-1), values, sT.values(:,where:end)]; 
62
+    sT.span    = [sT.span(:,1:where-1,:), spans, sT.span(:,where:end,:)]; 
63
+  end
64
+ case 'addrow', 
65
+  values  = arg1; 
66
+  if ischar(values), values = cellstr(values); end
67
+  if isnumeric(values), values = num2cell(values); end
68
+  [nr,nc] = size(values); 
69
+  spans   = ones([size(values) 2]);
70
+  if nargin<4, where = nrT+1; else where  = arg2; end
71
+  if ncT ~= nc, 
72
+    error('Mismatch between sizes of given table and additional rows')
73
+  else
74
+    sT.values = [sT.values(1:where-1,:); values; sT.values(where:end,:)]; 
75
+    sT.span   = [sT.span(1:where-1,:,:); spans; sT.span(where:end,:,:)]; 
76
+  end
77
+ case 'removecol',
78
+  where      = setdiff(1:ncT,arg1);     
79
+  sT.values  = sT.values(:,where); 
80
+  sT.headers = sT.headers(:,where); 
81
+  sT.span    = sT.span(:,where,:); 
82
+ case 'removerow',
83
+  where      = setdiff(1:nrT,arg1);     
84
+  sT.values  = sT.values(where,:); 
85
+  sT.headers = sT.headers(where,:); 
86
+  sT.span    = sT.span(where,:,:); 
87
+end
88
+
89
+return;
90
+
91
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,37 @@
1
+function T = som_table_print(sTable,fid,fmt)
2
+
3
+%SOM_TABLE_PRINT Print a table to a file / standard output.
4
+%  
5
+% som_table_print(sTable,[fid],[fmt])
6
+%  
7
+%  som_table_print(sTable)
8
+%  som_table_print(sTable,fid,'html')
9
+%
10
+%  Input and output arguments ([]'s are optional): 
11
+%   sTable      (struct) a table struct (see SOM_TABLE_STRUCT)
12
+%   [fid]       (scalar) a file id (from FOPEN, for example)
13
+%               (empty)  by default standard output (fid=1) is used
14
+%   [fmt]       (string) 'txt' (default), 'ps', 'pdf' or 'html'
15
+%                        the output format type
16
+%
17
+% See also  SOM_TABLE_STRUCT, SOM_STATS_TABLE, SOM_STATS_REPORT.
18
+
19
+% Contributed to SOM Toolbox 2.0, January 2nd, 2002 by Juha Vesanto
20
+% Copyright (c) by Juha Vesanto
21
+% http://www.cis.hut.fi/projects/somtoolbox/
22
+
23
+% Version 2.0beta juuso 020102
24
+
25
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
26
+
27
+if nargin<2 | isempty(fid) | isnan(fid), fid = 1; end
28
+if nargin<3 | isempty(fmt) | isnan(fmt), fmt = 'txt'; end
29
+
30
+rowlines = 0; 
31
+longtable = 0; 
32
+
33
+T = rep_utils({'inserttable',sTable,rowlines,longtable},fmt,fid);
34
+
35
+return;
36
+
37
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,64 @@
1
+function sTable = som_table_struct(values,headers,span,colfmt)
2
+
3
+%SOM_TABLE_STRUCT Create a table struct.
4
+%  
5
+% sTable = som_table_struct(values,[headers],[span],[colfmt])
6
+% 
7
+%  Input and output arguments ([]'s are optional): 
8
+%   values      (cell array) size nrow x ncol, the contents of the table 
9
+%               (char array) size nrow x *
10
+%               (matrix)     size nrow x ncol
11
+%   [headers]   (cell array) size 1 x ncol, header row of the table 
12
+%               (empty)      by default, empty headers are used ('')
13
+%   [span]      (matrix)     size nrow x ncol x 2, span of each cell of the 
14
+%                            table: span(:,:,1) gives horizontal span and 
15
+%                            span(:,:,2) gives vertical span. If the value
16
+%                            for a cell is greater than 1, it should be 
17
+%                            followed by a corresponding number of zeros
18
+%                            for the following cells (left or down)
19
+%               (empty)      by default ones(nrow,ncol,1)
20
+%   [colfmt]    (string)     the format of each column as given in LaTeX, 
21
+%                            only used if the table is printed as 'ps' or 'pdf', 
22
+%                            by default colfmt = ''
23
+%   
24
+%   sTable      (struct)     the table struct, with the following fields:
25
+%         .headers  (cell array) header row, size 1 x ncol
26
+%         .values   (cell array) values,  size nrow x ncol
27
+%         .span     (matrix)     span of each cell, size nrow x ncol x 2
28
+%
29
+% See also  SOM_TABLE_MODIFY, SOM_TABLE_PRINT.
30
+
31
+% Contributed to SOM Toolbox 2.0, December 31st, 2001 by Juha Vesanto
32
+% Copyright (c) by Juha Vesanto
33
+% http://www.cis.hut.fi/projects/somtoolbox/
34
+
35
+% Version 2.0beta juuso 311201
36
+
37
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
38
+
39
+if ischar(values), values = cellstr(values); 
40
+elseif isnumeric(values), values = num2cell(values); 
41
+end
42
+[nrow,ncol] = size(values);
43
+
44
+if nargin<2 | isempty(headers), headers = cell(1,ncol); headers(:) = {''}; end
45
+if ischar(headers), headers = cellstr(headers); end
46
+
47
+if nargin<3 | isempty(span), span = ones(nrow,ncol,2); end
48
+if sum(span(:)) > 2*nrow*ncol, 
49
+  warning('span matrix has overlapping cells')
50
+elseif sum(span(:)) < 2*nrow*ncol,
51
+  warning('span matrix has noncontinuous cells')
52
+end
53
+
54
+if nargin<4 | isempty(colfmt), colfmt = ''; end
55
+    
56
+sTable = struct('colfmt','','headers',[],'values',[],'span',[]); 
57
+sTable.colfmt  = colfmt; 
58
+sTable.headers = headers; 
59
+sTable.span    = span;
60
+sTable.values  = values; 
61
+
62
+return;
63
+
64
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,272 @@
1
+function sTopol = som_topol_struct(varargin)
2
+
3
+%SOM_TOPOL_STRUCT Default values for SOM topology.
4
+%
5
+% sT = som_topol_struct([[argID,] value, ...])
6
+%
7
+%  sTopol = som_topol_struct('data',D); 
8
+%  sTopol = som_topol_struct('data',D,'munits',200); 
9
+%  sTopol = som_topol_struct(sTopol); 
10
+%  sTopol = som_topol_struct; 
11
+% 
12
+%  Input and output arguments ([]'s are optional): 
13
+%    [argID,  (string) Default map topology depends on a number of 
14
+%     value]  (varies) factors (see below). These are given as a 
15
+%                      argument ID - argument value pairs, listed below.
16
+%
17
+%    sT       (struct) The ready topology struct.
18
+%
19
+% Topology struct contains values for map size, lattice (default is 'hexa')
20
+% and shape (default is 'sheet'). Map size depends on training data and the
21
+% number of map units. The number of map units depends on number of training
22
+% samples.
23
+%
24
+% Here are the valid argument IDs and corresponding values. The values which
25
+% are unambiguous (marked with '*') can be given without the preceeding argID.
26
+%  'dlen'         (scalar) length of the training data
27
+%  'data'         (matrix) the training data
28
+%                *(struct) the training data
29
+%  'munits'       (scalar) number of map units
30
+%  'msize'        (vector) map size
31
+%  'lattice'     *(string) map lattice: 'hexa' or 'rect'
32
+%  'shape'       *(string) map shape: 'sheet', 'cyl' or 'toroid'
33
+%  'topol'       *(struct) incomplete topology struct: its empty fields 
34
+%                          will be given values
35
+%  'som_topol','sTopol'    = 'topol'
36
+%
37
+% For more help, try 'type som_topol_struct' or check out online documentation.
38
+% See also SOM_SET, SOM_TRAIN_STRUCT, SOM_MAKE.
39
+
40
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
41
+%
42
+% som_topol_struct
43
+%
44
+% PURPOSE
45
+%
46
+% Default values for map topology and training parameters.
47
+%
48
+% SYNTAX
49
+%
50
+%  sT = som_topol_struct('argID',value,...);
51
+%  sT = som_topol_struct(value,...);
52
+%
53
+% DESCRIPTION
54
+%
55
+% This function is used to give sensible values for map topology (ie. map
56
+% size). The topology struct is returned. 
57
+%
58
+% The topology struct has three fields: '.msize', '.lattice' and
59
+% '.shape'. Of these, default value for '.lattice' is 'hexa' and for
60
+% '.shape' 'sheet'. Only the '.msize' field depends on the optional
61
+% arguments: 'dlen', 'munits' and 'data'.  The value for '.msize' field is
62
+% determined as follows.
63
+%
64
+% First, the number of map units is determined (unless it is given). A
65
+% heuristic formula of 'munits = 5*sqrt(dlen)' is used to calculate
66
+% it. After this, the map size is determined. Basically, the two biggest
67
+% eigenvalues of the training data are calculated and the ratio between
68
+% sidelengths of the map grid is set to the square root of this ratio. The
69
+% actual sidelengths are then set so that their product is as close to the
70
+% desired number of map units as possible. If the lattice of the grid is
71
+% 'hexa', the ratio is modified a bit to take it into account. If the
72
+% lattice is 'hexa' and shape is 'toroid', the map size along the first axis
73
+% must be even.
74
+%  
75
+% OPTIONAL INPUT ARGUMENTS 
76
+%
77
+%  argID (string) Argument identifier string (see below).
78
+%  value (varies) Value for the argument (see below).
79
+%
80
+%  The optional arguments can be given as 'argID',value -pairs. If an
81
+%  argument is given value multiple times, the last one is
82
+%  used. The valid IDs and corresponding values are listed below. The values 
83
+%  which are unambiguous (marked with '*') can be given without the 
84
+%  preceeding argID.
85
+%
86
+%  'dlen'         (scalar) length of the training data
87
+%  'data'         (matrix) the training data
88
+%                *(struct) the training data
89
+%  'munits'       (scalar) number of map units
90
+%  'msize'        (vector) map size
91
+%  'lattice'     *(string) map lattice: 'hexa' or 'rect'
92
+%  'shape'       *(string) map shape: 'sheet', 'cyl' or 'toroid'
93
+%  'topol'       *(struct) incomplete topology struct: its empty fields 
94
+%                          will be given values
95
+%  'som_topol','sTopol'    = 'topol'
96
+%
97
+% OUTPUT ARGUMENTS
98
+% 
99
+%  sT     (struct) The topology struct.
100
+%
101
+% EXAMPLES
102
+%
103
+%  The most important optional argument for the default topology is 'data'.
104
+%  To get a default topology (given data) use:
105
+%
106
+%    sTopol = som_topol_struct('data',D); 
107
+%
108
+%  This sets lattice to its default value 'hexa'. If you want to have a
109
+%  'rect' lattice instead: 
110
+%
111
+%    sTopol = som_topol_struct('data',D,'lattice','rect');
112
+%     or 
113
+%    sTopol = som_topol_struct('data',D,'rect');
114
+%
115
+%  If you want to have (close to) a specific number of map units, e.g. 100: 
116
+%
117
+%    sTopol = som_topol_struct('data',D,'munits',100);
118
+%
119
+% SEE ALSO
120
+%
121
+%  som_make         Initialize and train a map using default parameters.
122
+%  som_train_struct Default training parameters.
123
+%  som_randinint    Random initialization algorithm.
124
+%  som_lininit      Linear initialization algorithm.
125
+%  som_seqtrain     Sequential training algorithm.
126
+%  som_batchtrain   Batch training algorithm.
127
+
128
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
129
+% http://www.cis.hut.fi/projects/somtoolbox/
130
+
131
+% Version 2.0alpha juuso 060898 250399 070499 050899 240801
132
+
133
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
134
+%% check arguments
135
+
136
+% initialize
137
+sTopol = som_set('som_topol','lattice','hexa','shape','sheet'); 
138
+D = [];
139
+dlen = NaN;
140
+dim = 2; 
141
+munits = NaN;
142
+
143
+% varargin
144
+i=1; 
145
+while i<=length(varargin), 
146
+  argok = 1; 
147
+  if ischar(varargin{i}), 
148
+    switch varargin{i}, 
149
+     case 'dlen',       i=i+1; dlen = varargin{i}; 
150
+     case 'munits',     i=i+1; munits = varargin{i}; sTopol.msize = 0;
151
+     case 'msize',      i=i+1; sTopol.msize = varargin{i}; 
152
+     case 'lattice',    i=i+1; sTopol.lattice = varargin{i}; 
153
+     case 'shape',      i=i+1; sTopol.shape = varargin{i}; 
154
+     case 'data',       
155
+      i=i+1; 
156
+      if isstruct(varargin{i}), D = varargin{i}.data; 
157
+      else D = varargin{i}; 
158
+      end
159
+      [dlen dim] = size(D); 
160
+     case {'hexa','rect'}, sTopol.lattice = varargin{i}; 
161
+     case {'sheet','cyl','toroid'}, sTopol.shape = varargin{i};
162
+     case {'som_topol','sTopol','topol'}, 
163
+      i=i+1;
164
+      if ~isempty(varargin{i}.msize) & prod(varargin{i}.msize), 
165
+	sTopol.msize = varargin{i}.msize; 
166
+      end
167
+      if ~isempty(varargin{i}.lattice), sTopol.lattice = varargin{i}.lattice; end   
168
+      if ~isempty(varargin{i}.shape), sTopol.shape = varargin{i}.shape; end
169
+     otherwise argok=0; 
170
+    end
171
+  elseif isstruct(varargin{i}) & isfield(varargin{i},'type'), 
172
+    switch varargin{i}.type, 
173
+     case 'som_topol',
174
+      if ~isempty(varargin{i}.msize) & prod(varargin{i}.msize), 
175
+	sTopol.msize = varargin{i}.msize; 
176
+      end
177
+      if ~isempty(varargin{i}.lattice), sTopol.lattice = varargin{i}.lattice; end   
178
+      if ~isempty(varargin{i}.shape), sTopol.shape = varargin{i}.shape; end
179
+     case 'som_data', 
180
+      D = varargin{i}.data; 
181
+      [dlen dim] = size(D);       
182
+     otherwise argok=0; 
183
+    end
184
+  else
185
+    argok = 0; 
186
+  end
187
+  if ~argok, 
188
+    disp(['(som_topol_struct) Ignoring invalid argument #' num2str(i)]); 
189
+  end
190
+  i = i+1; 
191
+end
192
+
193
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
194
+%% action - topology struct
195
+
196
+% lattice and shape set already, so if msize is also set, there's
197
+% nothing else to do
198
+if prod(sTopol.msize) & ~isempty(sTopol.msize), return; end
199
+
200
+% otherwise, decide msize 
201
+% first (if necessary) determine the number of map units (munits)
202
+if isnan(munits), 
203
+  if ~isnan(dlen), 
204
+    munits = ceil(5 * dlen^0.5); % this is just one way to make a guess...
205
+  else
206
+    munits = 100; % just a convenient value
207
+  end
208
+end
209
+
210
+% then determine the map size (msize)
211
+if dim == 1, % 1-D data
212
+
213
+  sTopol.msize = [1 ceil(munits)]; 
214
+
215
+elseif size(D,1)<2, % eigenvalues cannot be determined since there's no data
216
+
217
+  sTopol.msize = round(sqrt(munits)); 
218
+  sTopol.msize(2) = round(munits/sTopol.msize(1));
219
+
220
+else % determine map size based on eigenvalues
221
+  
222
+  % initialize xdim/ydim ratio using principal components of the input
223
+  % space; the ratio is the square root of ratio of two largest eigenvalues	
224
+  
225
+  % autocorrelation matrix
226
+  A = zeros(dim)+Inf;
227
+  for i=1:dim, D(:,i) = D(:,i) - mean(D(isfinite(D(:,i)),i)); end  
228
+  for i=1:dim, 
229
+    for j=i:dim, 
230
+      c = D(:,i).*D(:,j); c = c(isfinite(c));
231
+      A(i,j) = sum(c)/length(c); A(j,i) = A(i,j); 
232
+    end
233
+  end  
234
+  % take mdim first eigenvectors with the greatest eigenvalues
235
+  [V,S]   = eig(A);
236
+  eigval  = diag(S);
237
+  [y,ind] = sort(eigval); 
238
+  eigval  = eigval(ind);
239
+  
240
+  %me     = mean(D);
241
+  %D      = D - me(ones(length(ind),1),:); % remove mean from data
242
+  %eigval = sort(eig((D'*D)./size(D,1))); 
243
+  if eigval(end)==0 | eigval(end-1)*munits<eigval(end), 
244
+    ratio = 1; 
245
+  else
246
+    ratio  = sqrt(eigval(end)/eigval(end-1)); % ratio between map sidelengths
247
+  end
248
+  
249
+  % in hexagonal lattice, the sidelengths are not directly 
250
+  % proportional to the number of units since the units on the 
251
+  % y-axis are squeezed together by a factor of sqrt(0.75)
252
+  if strcmp(sTopol.lattice,'hexa'), 
253
+    sTopol.msize(2)  = min(munits, round(sqrt(munits / ratio * sqrt(0.75))));
254
+  else
255
+    sTopol.msize(2)  = min(munits, round(sqrt(munits / ratio)));
256
+  end
257
+  sTopol.msize(1)  = round(munits / sTopol.msize(2));
258
+  
259
+  % if actual dimension of the data is 1, make the map 1-D    
260
+  if min(sTopol.msize) == 1, sTopol.msize = [1 max(sTopol.msize)]; end;
261
+  
262
+  % a special case: if the map is toroid with hexa lattice, 
263
+  % size along first axis must be even
264
+  if strcmp(sTopol.lattice,'hexa') & strcmp(sTopol.shape,'toroid'), 
265
+    if mod(sTopol.msize(1),2), sTopol.msize(1) = sTopol.msize(1) + 1; end
266
+  end
267
+
268
+end
269
+  
270
+return;
271
+
272
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,389 @@
1
+function sTrain = som_train_struct(varargin)
2
+
3
+%SOM_TRAIN_STRUCT Default values for SOM training parameters.
4
+%
5
+% sT = som_train_struct([[argID,] value, ...])
6
+%
7
+%  sTrain = som_train_struct('train',sM,sD);
8
+%  sTrain = som_train_struct('finetune','data',D); 
9
+%  sTrain = som_train_struct('previous',sT0);
10
+% 
11
+%  Input and output arguments ([]'s are optional): 
12
+%    [argID,  (string) Several default values depend on other SOM parameters
13
+%     value]  (varies) or on the proporties of a data set. See below for a
14
+%                      a list of required and optional arguments for
15
+%                      different parameters, and well as the list of valid 
16
+%                      argIDs and associated values. The values which are 
17
+%                      unambiguous can be given without the preceeding argID.
18
+%
19
+%    sT       (struct) The training struct.
20
+%
21
+% Training struct contains values for training and initialization
22
+% parameters. These parameters depend on the number of training samples,
23
+% phase of training, the training algorithm.
24
+% 
25
+% Here are the valid argument IDs and corresponding values. The values which
26
+% are unambiguous (marked with '*') can be given without the preceeding rgID.
27
+%  'dim'          (scalar) input space dimension
28
+%  'dlen'         (scalar) length of the training data
29
+%  'data'         (matrix / struct) the training data
30
+%  'munits'       (scalar) number of map units
31
+%  'msize'        (vector) map size
32
+%  'previous'     (struct) previous training struct can be given in 
33
+%                          conjunction with 'finetune' phase (see below) 
34
+%  'phase'       *(string) training phase: 'init', 'train', 'rough' or 'finetune'
35
+%  'algorithm'   *(string) algorithm to use: 'lininit', 'randinit', 'batch' or 'seq'
36
+%  'map'         *(struct) If a map struct is given, the last training struct
37
+%                          in '.trainhist' field is used as the previous training
38
+%                          struct. The map size and input space dimension are 
39
+%                          extracted from the map struct.
40
+%  'sTrain'      *(struct) a train struct, the empty fields of which are
41
+%                          filled with sensible values
42
+%
43
+% For more help, try 'type som_train_struct' or check out online documentation.
44
+% See also SOM_SET, SOM_TOPOL_STRUCT, SOM_MAKE.
45
+
46
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
47
+%
48
+% som_train_struct
49
+%
50
+% PURPOSE
51
+%
52
+% Default values for SOM training parameters.
53
+%
54
+% SYNTAX
55
+%
56
+%  sT = som_train_struct('argID',value,...);
57
+%  sT = som_train_struct(value,...);
58
+%
59
+% DESCRIPTION
60
+%
61
+% This function is used to give sensible values for SOM training
62
+% parameters and returns a training struct. Often, the parameters
63
+% depend on the properties of the map and the training data. These are
64
+% given as optional arguments to the function. If a partially filled
65
+% train struct is given, its empty fields (field value is [] or '' or
66
+% NaN) are supplimented with default values.
67
+%
68
+% The training struct has a number of fields which depend on each other
69
+% and the optional arguments in complex ways. The most important argument 
70
+% is 'phase' which can be either 'init', 'train', 'rough' or 'finetune'.
71
+%
72
+%  'init'     Map initialization. 
73
+%  'train'    Map training in a onepass operation, as opposed to the
74
+%             rough-finetune combination.
75
+%  'rough'    Rough organization of the map: large neighborhood, big
76
+%             initial value for learning coefficient. Short training.
77
+%  'finetune' Finetuning the map after rough organization phase. Small
78
+%             neighborhood, learning coefficient is small already at 
79
+%             the beginning. Long training.
80
+%
81
+% The fields of training struct set by this function are listed below.
82
+%
83
+%  '.mask'  Basically, a column vector of ones. But if a previous
84
+%           train or map struct is given, it is copied from there.
85
+%  '.neigh' Default value is 'gaussian' but if a previous train or map 
86
+%           struct is given, it is copied from there.
87
+%  '.alpha_type' Default value is 'inv' but if a previous training struct 
88
+%           is given, it is copied from there.
89
+%  '.alpha_ini' For 'train' and 'rough' phases, this is 0.5, for
90
+%           'finetune' it is 0.05.
91
+%  '.radius_ini' Depends on the previous training operation and the 
92
+%           maximum sidelength of the map ms = max(msize).
93
+%           if there isn't one, or it is 'randinit', rad_ini = max(1,ms/2)
94
+%           if it is 'lininit', rad_ini = max(1,ms/8)
95
+%           otherwise, rad_ini = rad_fin of the previous training
96
+%  '.radius_fin' Default value is 1, but if the training phase is
97
+%           'rough', rad_fin = max(1,rad_ini/4).
98
+%  '.trainlen' For 'train' phase this is 20 x mpd epochs, for 'rough'
99
+%           phase 4 x mpd epochs and for 'finetune' 16 x mpd
100
+%           epochs, where mpd = munits/dlen. If mpd cannot be
101
+%           calculated, it is set to be = 0.5. In any case,
102
+%           trainlen is at least one epoch.
103
+%  '.algorithm' Default training algorithm is 'batch' and default
104
+%           initialization algorithm is 'lininit'.
105
+%
106
+% OPTIONAL INPUT ARGUMENTS 
107
+%
108
+%  argID (string) Argument identifier string (see below).
109
+%  value (varies) Value for the argument (see below).
110
+%
111
+%  The optional arguments can be given as 'argID',value -pairs. If an
112
+%  argument is given value multiple times, the last one is used.  The
113
+%  valid IDs and corresponding values are listed below. The values
114
+%  which are unambiguous (marked with '*') can be given without the
115
+%  preceeding argID.
116
+%
117
+%  'dim'          (scalar) input space dimension
118
+%  'dlen'         (scalar) length of the training data
119
+%  'data'         (matrix / struct) the training data
120
+%  'munits'       (scalar) number of map units
121
+%  'msize'        (vector) map size
122
+%  'previous'     (struct) previous training struct can be given in 
123
+%                  conjunction with 'finetune' phase. 
124
+%  'phase'       *(string) training phase: 'init', 'train', 'rough' or 'finetune'
125
+%  'algorithm'   *(string) algorithm to use: 'lininit', 'randinit', 
126
+%                  'batch' or 'seq'
127
+%  'map'         *(struct) If a map struc is given, the last training struct
128
+%                  in '.trainhist' field is used as the previous training
129
+%                  struct. The map size and input space dimension are 
130
+%                  extracted from the map struct.
131
+%  'sTrain'      *(struct) a train struct, the empty fields of which are
132
+%                  filled with sensible values
133
+%
134
+% OUTPUT ARGUMENTS
135
+% 
136
+%  sT     (struct) The training struct.
137
+%
138
+% EXAMPLES
139
+%
140
+%  The most important optional argument for the training parameters is
141
+%  'phase'. The second most important are 'previous' and/or 'map'. 
142
+%
143
+%  To get default initialization parameters, use: 
144
+%
145
+%    sTrain = som_train_struct('phase','init');
146
+%     or
147
+%    sTrain = som_train_struct('init');
148
+%
149
+%  To get default training parameters, use: 
150
+%
151
+%    sTrain = som_train_struct('phase','train','data',D,'map',sMap);
152
+%     or  
153
+%    sTrain = som_train_struct('train','data',D,sMap);
154
+%     or
155
+%    sTrain = som_train_struct('train','dlen',dlen, ...
156
+%                              'msize',sMap.topol.msize,'dim',dim);
157
+%  
158
+%  If you want to first rough train and then finetune, do like this: 
159
+%
160
+%   sT1 = som_train_struct('rough','dlen',length(D),sMap); % rough training
161
+%   sT2 = som_train_struct('finetune','previous',sT1);     % finetuning
162
+%
163
+% SEE ALSO
164
+%
165
+%  som_make         Initialize and train a map using default parameters.
166
+%  som_topol_struct Default map topology.
167
+%  som_randinint    Random initialization algorithm.
168
+%  som_lininit      Linear initialization algorithm.
169
+%  som_seqtrain     Sequential training algorithm.
170
+%  som_batchtrain   Batch training algorithm.
171
+
172
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
173
+% http://www.cis.hut.fi/projects/somtoolbox/
174
+
175
+% Version 2.0beta juuso 101199 090200 210301
176
+
177
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
178
+%% check arguments
179
+
180
+% initial default structs
181
+sTrain = som_set('som_train'); 
182
+
183
+% initialize optional parameters
184
+dlen = NaN;
185
+msize = 0; 
186
+munits = NaN;
187
+sTprev = [];
188
+dim = NaN; 
189
+phase = '';
190
+
191
+% varargin
192
+i=1; 
193
+while i<=length(varargin), 
194
+  argok = 1; 
195
+  if ischar(varargin{i}), 
196
+    switch varargin{i}, 
197
+     case 'dim',        i=i+1; dim = varargin{i}; 
198
+     case 'dlen',       i=i+1; dlen = varargin{i}; 
199
+     case 'msize',      i=i+1; msize = varargin{i};
200
+     case 'munits',     i=i+1; munits = varargin{i}; msize = 0; 
201
+     case 'phase',      i=i+1; phase = varargin{i}; 
202
+     case 'algorithm',  i=i+1; sTrain.algorithm = varargin{i}; 
203
+     case 'mask',       i=i+1; sTrain.mask = varargin{i}; 
204
+     case {'previous','map'},   
205
+      i=i+1; 
206
+      if strcmp(varargin{i}.type,'som_map'), 
207
+	if length(varargin{i}.trainhist), 
208
+	  sTprev = varargin{i}.trainhist(end); 
209
+	  msize = varargin{i}.topol.msize;
210
+	end
211
+      elseif strcmp(varargin{i}.type,'som_train'), 
212
+	sTprev = varargin{i}; 
213
+      end
214
+     case 'data',       
215
+      i=i+1; 
216
+      if isstruct(varargin{i}), [dlen dim] = size(varargin{i}.data); 
217
+      else [dlen dim] = size(varargin{i}); 
218
+      end
219
+     case {'init','train','rough','finetune'},  phase = varargin{i};       
220
+     case {'lininit','randinit','seq','batch'}, sTrain.algorithm = varargin{i}; 
221
+     otherwise argok=0; 
222
+    end
223
+  elseif isstruct(varargin{i}) & isfield(varargin{i},'type'), 
224
+    switch varargin{i}.type, 
225
+     case 'som_train', 
226
+      sT = varargin{i}; 
227
+      if ~isempty(sT.algorithm),  sTrain.algorithm = sT.algorithm; end
228
+      if ~isempty(sT.neigh),      sTrain.neigh = sT.neigh; end
229
+      if ~isempty(sT.mask),       sTrain.mask = sT.mask; end
230
+      if ~isnan(sT.radius_ini),   sTrain.radius_ini = sT.radius_ini; end
231
+      if ~isnan(sT.radius_fin),   sTrain.radius_fin = sT.radius_fin; end
232
+      if ~isnan(sT.alpha_ini),    sTrain.alpha_ini = sT.alpha_ini; end
233
+      if ~isempty(sT.alpha_type), sTrain.alpha_type = sT.alpha_type; end
234
+      if ~isnan(sT.trainlen),     sTrain.trainlen = sT.trainlen; end
235
+      if ~isempty(sT.data_name),  sTrain.data_name = sT.data_name; end
236
+      if ~isempty(sT.time),       sTrain.time = sT.time; end
237
+     case 'som_map', 
238
+      if strcmp(varargin{i}.type,'som_map'), 
239
+	if length(varargin{i}.trainhist), 
240
+	  sTprev = varargin{i}.trainhist(end); 
241
+	  msize = varargin{i}.topol.msize; 
242
+	end
243
+	if ~isempty(varargin{i}.neigh) & isempty(sTrain.neigh), 
244
+	  sTrain.neigh = varargin{i}.neigh; 
245
+	end
246
+	if ~isempty(varargin{i}.mask) & isempty(sTrain.mask),  
247
+	  sTrain.mask = varargin{i}.mask; 
248
+	end
249
+      elseif strcmp(varargin{i}.type,'som_train'), 
250
+	sTprev = varargin{i}; 
251
+      end
252
+     case 'som_topol', msize = varargin{i}.msize; 
253
+     case 'som_data', [dlen dim] = size(varargin{i}.data); 
254
+     otherwise argok=0; 
255
+    end
256
+  else
257
+    argok = 0; 
258
+  end
259
+  if ~argok, 
260
+    disp(['(som_train_struct) Ignoring invalid argument #' num2str(i)]); 
261
+  end
262
+  i = i+1; 
263
+end
264
+
265
+% dim
266
+if ~isempty(sTprev) & isnan(dim), dim = length(sTprev.mask); end
267
+
268
+% mask
269
+if isempty(sTrain.mask) & ~isnan(dim), sTrain.mask = ones(dim,1); end
270
+
271
+% msize, munits
272
+if ~msize | isempty(msize), 
273
+  if isnan(munits), msize = [10 10]; 
274
+  else s = round(sqrt(munits)); msize = [s round(munits/s)]; 
275
+  end
276
+end
277
+munits = prod(msize);
278
+
279
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
280
+%% action
281
+
282
+% previous training
283
+prevalg = ''; 
284
+if ~isempty(sTprev), 
285
+  if any(findstr(sTprev.algorithm,'init')), prevalg = 'init';
286
+  else prevalg = sTprev.algorithm; 
287
+  end
288
+end
289
+
290
+% first determine phase  
291
+if isempty(phase), 
292
+  switch sTrain.algorithm,
293
+   case {'lininit','randinit'},    phase = 'init'; 
294
+   case {'batch','seq',''}, 
295
+    if     isempty(sTprev),        phase = 'rough'; 
296
+    elseif strcmp(prevalg,'init'), phase = 'rough';
297
+    else                           phase = 'finetune'; 
298
+    end
299
+   otherwise,                      phase = 'train'; 
300
+  end
301
+end
302
+
303
+% then determine algorithm  
304
+if isempty(sTrain.algorithm),
305
+  if     strcmp(phase,'init'),             sTrain.algorithm = 'lininit';
306
+  elseif any(strcmp(prevalg,{'init',''})), sTrain.algorithm = 'batch';
307
+  else sTrain.algorithm = sTprev.algorithm; 
308
+  end
309
+end
310
+
311
+% mask
312
+if isempty(sTrain.mask), 
313
+  if ~isempty(sTprev), sTrain.mask = sTprev.mask; 
314
+  elseif ~isnan(dim),  sTrain.mask = ones(dim,1); 
315
+  end
316
+end
317
+
318
+% neighborhood function
319
+if isempty(sTrain.neigh), 
320
+  if ~isempty(sTprev) & ~isempty(sTprev.neigh), sTrain.neigh = sTprev.neigh; 
321
+  else sTrain.neigh = 'gaussian';
322
+  end
323
+end
324
+
325
+if strcmp(phase,'init'), 
326
+  sTrain.alpha_ini = NaN;
327
+  sTrain.alpha_type = '';
328
+  sTrain.radius_ini = NaN;
329
+  sTrain.radius_fin = NaN;
330
+  sTrain.trainlen = NaN;
331
+  sTrain.neigh = '';
332
+else
333
+  mode = [phase, '-', sTrain.algorithm];
334
+  
335
+  % learning rate
336
+  if isnan(sTrain.alpha_ini), 
337
+    if strcmp(sTrain.algorithm,'batch'), sTrain.alpha_ini = NaN; 
338
+    else
339
+      switch phase, 
340
+       case {'train','rough'}, sTrain.alpha_ini = 0.5;
341
+       case 'finetune',        sTrain.alpha_ini = 0.05;
342
+      end
343
+    end
344
+  end
345
+  if isempty(sTrain.alpha_type),     
346
+    if ~isempty(sTprev) & ~isempty(sTprev.alpha_type) ... 
347
+	  & ~strcmp(sTrain.algorithm,'batch'),
348
+      sTrain.alpha_type = sTprev.alpha_type;
349
+    elseif strcmp(sTrain.algorithm,'seq'),
350
+      sTrain.alpha_type = 'inv';
351
+    end
352
+  end
353
+  
354
+  % radius
355
+  ms = max(msize);   
356
+  if isnan(sTrain.radius_ini),     
357
+    if isempty(sTprev) | strcmp(sTprev.algorithm,'randinit'), 
358
+      sTrain.radius_ini = max(1,ceil(ms/4));
359
+    elseif strcmp(sTprev.algorithm,'lininit') | isnan(sTprev.radius_fin),
360
+      sTrain.radius_ini = max(1,ceil(ms/8));
361
+    else
362
+      sTrain.radius_ini = sTprev.radius_fin;
363
+    end
364
+  end
365
+  if isnan(sTrain.radius_fin), 
366
+    if strcmp(phase,'rough'), 
367
+      sTrain.radius_fin = max(1,sTrain.radius_ini/4);
368
+    else
369
+      sTrain.radius_fin = 1;
370
+    end
371
+  end
372
+  
373
+  % trainlen  
374
+  if isnan(sTrain.trainlen),     
375
+    mpd = munits/dlen; 
376
+    if isnan(mpd), mpd = 0.5; end
377
+    switch phase, 
378
+     case 'train',    sTrain.trainlen = ceil(50*mpd);
379
+     case 'rough',    sTrain.trainlen = ceil(10*mpd); 
380
+     case 'finetune', sTrain.trainlen = ceil(40*mpd);
381
+    end
382
+    sTrain.trainlen = max(1,sTrain.trainlen);
383
+  end
384
+
385
+end
386
+
387
+return;
388
+
389
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,285 @@
1
+function som_trajectory(bmus,varargin)
2
+
3
+%SOM_TRAJECTORY Launch a "comet" trajectory visualization GUI.
4
+%
5
+%  som_show(sM,'umat','all')
6
+%  bmus = som_bmus(sM,sD);
7
+%  som_trajectory(bmus)
8
+%  som_trajectory(bmus, 'data1', sD, 'trajsize', [12 6 3 1]')
9
+%  som_trajectory(bmus, 'data1', sD.data(:,[1 2 3]), 'name1', {'fii' 'faa' 'foo'})
10
+%
11
+% Input arguments ([]'s are optional):
12
+%   bmus      (matrix) size Nx1, vector of BMUS
13
+%   ['argID', (string) Other arguments can be given as 'argID', value   
14
+%    value]   (varies) pairs. See list below for valid values.
15
+%
16
+% NOTE: the GUI only works on a figure which has been made with SOM_SHOW.
17
+%
18
+% Here are the valid argument IDs (case insensitive) and associated values: 
19
+%  'color'      string 'xor' or ColorSpec, default: 'xor'. 
20
+%               (default: according to lattice as in som_cplane)
21
+%  'TrajSize'   vector of size Nx1 to define the length of comet
22
+%               (N) and size of the comet dots in points. 
23
+%               default: [16 12 10 8 6 4]' 
24
+%  'Data1'      SOM Toolbox data struct or matrix. The size of
25
+%               data matrix (in data struct the field .data) is
26
+%               Nxd, where N must be the same as the amount of
27
+%               BMUS given in the first input argument 'bmus'
28
+%               This data is shown in a new window in d subplots.
29
+%               Default: BMU indices (first input argument)
30
+%  'Name1'      cell array of d strings which contains names
31
+%               for the components in 'Data1'. If 'Data1' is a SOM
32
+%               Toolbox data struct, the existing component names 
33
+%               are overdone.                 
34
+%  'Figure'     scalar that must be a handle to an existing figure
35
+%               which has been made using SOM_SHOW function.
36
+%               Default: current active figure (gcf).
37
+%
38
+% The following tools can be found in the 'Tools' -menu.
39
+%
40
+%  Remove Trajectory: removes trajectory from the map.
41
+%  Dye Nodes        : opens GUI for selecting color for the nodes
42
+%                     and points selected.
43
+%  Clear Markers    : removes markers from map and data figure.
44
+%  Save             : saves the current situation as a struct.
45
+%  Load             : loads the struct from workspace and draws markers.
46
+%
47
+% Mouse operation
48
+%
49
+%  In data window: Left button is used to drag the operation point ruler  
50
+%                  if left button is on blank area, it starts 
51
+%  In map window : Left button starts a polygon; right button
52
+%                  finishes; middle button toggles a unit.
53
+%
54
+% SOM_TRAJECTORY is an application for observing trajectory behavior.
55
+%
56
+% Using mouse the line in data figure can be dragged and the
57
+% trajectory moves in the SOM SHOW figure. It is also possible to move
58
+% trajectory by pressing keys '>' and '<' when mouse pointer is above
59
+% data figure.
60
+% 
61
+% Regions can be chosen from the data and the points in that region
62
+% are mapped to the component planes. Regions can be chosen also in
63
+% the map.  In this situation data points and map nodes are also
64
+% marked (Left mouse button adds point to the polygon indicating the
65
+% region and right button finals the polygon). By clicking a node (the
66
+% middle button) that node is either added or removed from selection.
67
+% 
68
+% It should be noticed that choosing intervals from data may cause
69
+% situations that seem to be bugs. If there exisist marks of different
70
+% color, removing them by clicking the map may left some marks in the
71
+% data, because more than one point in the data is mapped to the same
72
+% node in the map and the removing operation depends on the color of
73
+% the marks. However, all the marks can be removed by using the 'Clear
74
+% Markers' -operation.
75
+%
76
+% FEATURES
77
+%
78
+% The first input argument 'bmus' may also be a munits x N matrix
79
+% In this case each column defines a "fuzzy response". That is,
80
+% each column defines a hit histogram function). The element
81
+% bmus(i,t) sets the size of marker on unit i at time t. 
82
+% NOTE: - in this case no regions can be selcted on the map!
83
+%       - only > and < keys can be used to move the operation point
84
+%         line: it can't be dragged
85
+%       - "fuzzy response is always black (hope this will be fixed) 
86
+%       
87
+% It is possible to open a second data window showing different data:
88
+% use indetifiers 'Data2' (and 'Name2'). The argument syntax is
89
+% identical to 'Data1' (and 'Name1').
90
+%
91
+% See also SOM_SHOW, SOM_SHOW_ADD, SOM_BMUS. 
92
+
93
+% Contributed to SOM Toolbox 2.0, February 11th, 2000 by Johan
94
+% Himberg and Juha Parhankangas
95
+% Copyright (c) 2000 by the Johan Himberg and Juha Parhankangas
96
+% http://www.cis.hut.fi/projects/somtoolbox/        
97
+
98
+% Check arguments
99
+
100
+error(nargchk(1,Inf,nargin)); % Check no. of input arguments
101
+
102
+%% Init input argument struct (see subfunction)
103
+Traj=iniTraj(bmus);
104
+
105
+% Check tentative BMU input validity
106
+
107
+if ~vis_valuetype(bmus,{'nxm'}),
108
+  error(['First input should be a vector of BMU indices or' ...
109
+	 ' a "response matrix"']);
110
+end
111
+
112
+%% Check optional arguments
113
+for i=1:2:length(varargin)
114
+  identifier=lower(varargin{i});
115
+  value=varargin{i+1};
116
+
117
+  % Trajectory color
118
+  switch identifier  
119
+   case 'color'
120
+    if isempty(value)
121
+      value='xor';
122
+    end
123
+    if vis_valuetype(value,{'colorstyle','xor'})
124
+      Traj.color=value;
125
+    else
126
+      error('''Color'' has to be ColorSpec or string ''xor''.');
127
+    end
128
+   
129
+   % 1st data  
130
+   case 'data1'
131
+    if isempty(value),
132
+      value=[];
133
+    elseif vis_valuetype(value,{'nxm'})
134
+      Traj.primary_data=value;
135
+    elseif isstruct(value) & isfield(value,'type') & ...
136
+	  ischar(value.type) & strcmp(value.type,'som_data'),
137
+      Traj.primary_data=value.data;
138
+      if isempty(Traj.primary_names),
139
+	Traj.primary_names=value.comp_names;
140
+      end
141
+    end
142
+   
143
+    % 2nd data
144
+   case 'data2'
145
+    if isempty(value),
146
+      value=[];
147
+    elseif vis_valuetype(value,{'nxm'})
148
+      Traj.secondary_data=value;
149
+    elseif isstruct(value) & isfield(value,'type') & ...
150
+	  ischar(value.type) & strcmp(value.type,'som_data'),
151
+      Traj.secondary_data=value.data;
152
+      if isempty(Traj.secondary_names),
153
+	Traj.secondary_names=value.comp_names;
154
+      end
155
+     end
156
+   
157
+   % Trajectory length & size
158
+   case 'trajsize'
159
+    if isempty(value),
160
+      Traj.size=[16 12 10 8 6 4]';
161
+    end
162
+    if vis_valuetype(value,{'nx1'})
163
+      Traj.size=value
164
+    else
165
+      error('''TrajSize'' has to be a nx1 vector.');
166
+    end
167
+   
168
+   % Names for first data variables
169
+   case 'name1'
170
+    if isempty(value),
171
+      Traj.primary_names=[];
172
+    elseif ~vis_valuetype(value,{'cellcolumn_of_char'}),
173
+      error('''Name1'': variable names must be in a cell column array.') 
174
+    else
175
+      Traj.primary_names = value;
176
+    end
177
+   % Names for 2nd data variables
178
+   case 'name2'
179
+    if isempty(value),
180
+      Traj.secondary_names=[];
181
+    elseif ~vis_valuetype(value,{'cellcolumn_of_char'}),
182
+      error('''Name2'': variable names must be in a cell column array.') 
183
+    else
184
+      Traj.secondary_names = value;
185
+    end
186
+   
187
+   % Figure number
188
+   case 'figure'
189
+    if isempty(value)
190
+      Traj.figure='gcf';
191
+    end
192
+    if vis_valuetype(value,{'1x1'})
193
+      Traj.figure=value;
194
+    else
195
+      error('''Figure'' should be number of an existing figure.')
196
+    end
197
+  end
198
+end
199
+
200
+%% Get SOM data from figure
201
+[h,msg,lattice,msize,dim]=vis_som_show_data('all',Traj.figure);
202
+
203
+%% Not a SOM_SHOW figure?
204
+if ~isempty(msg);
205
+  error('Figure is invalid: use SOM_SHOW to draw the figure.');
206
+end
207
+
208
+% Get map size from figure data
209
+Traj.lattice=lattice; 
210
+Traj.msize=msize;  
211
+if length(msize)>2,
212
+  error(['This function works only with 2D maps: figure contains' ...
213
+	 ' something else.']);
214
+end
215
+munits=prod(msize);
216
+
217
+% Check BMU (or response) and map match 
218
+
219
+if vis_valuetype(bmus,{'nx1'});
220
+  if max(bmus)>prod(msize) | min(bmus) <1
221
+    error('BMU indexes out of range.')
222
+  elseif any(round(bmus)~=bmus)
223
+    error('BMU indexes must be integer.');
224
+  elseif isempty(Traj.primary_data),
225
+    Traj.primary_data=bmus;
226
+  end
227
+elseif size(bmus,1) ~= munits 
228
+  error(['Response matrix column number must match with the number of' ...
229
+	 ' map units.']);
230
+else
231
+  bmus=bmus';
232
+  if isempty(Traj.primary_data),
233
+    Traj.primary_data=[1:size(bmus,1)]';
234
+    Traj.primary_names={'BMU Index'};
235
+  end
236
+end
237
+
238
+size1=size(Traj.primary_data);
239
+size2=size(Traj.secondary_data);
240
+
241
+% Data2 must not be defined alone
242
+
243
+if isempty(Traj.primary_data)&~isempty(Traj.secondary_data),
244
+  error('If ''Data2'' is specified ''Data1'' must be specified, too.');
245
+elseif ~isempty(Traj.secondary_data) ...
246
+      & size1~= size2
247
+  % If data1 and data2 exist both, check data1 and data2 match
248
+  error('''Data1'' and ''Data2'' have different amount of data vectors.')
249
+end
250
+
251
+% Check BMU and data1 match (data2 matches with 1 anyway)
252
+
253
+if ~isempty(Traj.primary_data) & size(bmus,1) ~= size1,
254
+  error(['The number of data vectors in ''data1'' must match with' ...
255
+	 ' the number of rows in the first input argument (bmus).']);
256
+end
257
+
258
+% Check that number of names and data dimension is consistent
259
+
260
+if ~isempty(Traj.primary_names) & (size1(2)~=length(Traj.primary_names)),
261
+  error('Number of component names and ''Data1'' dimension mismatch.');
262
+end
263
+if ~isempty(Traj.secondary_names) & ...
264
+      (size2(2)~=length(Traj.secondary_names)),
265
+  error('Number of component names and ''Data2'' dimension mismatch.');
266
+end
267
+
268
+%% Call the function that does the job
269
+vis_trajgui(Traj);
270
+
271
+%%% Subfunctions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
272
+
273
+function Traj=iniTraj(bmus)
274
+
275
+Traj.figure=gcf;
276
+Traj.primary_data=[];
277
+Traj.secondary_data=[];
278
+Traj.primary_names = [];  
279
+Traj.secondary_names = [];  
280
+Traj.size=[16 12 10 8 6 4]';
281
+Traj.bmus=bmus;
282
+Traj.color='xor';
283
+Traj.msize=[];
284
+Traj.lattice=[];
285
+
... ...
@@ -0,0 +1,362 @@
1
+function U = som_umat(sMap, varargin)
2
+
3
+%SOM_UMAT Compute unified distance matrix of self-organizing map.
4
+%
5
+% U = som_umat(sMap, [argID, value, ...])
6
+%
7
+%  U = som_umat(sMap);  
8
+%  U = som_umat(M,sTopol,'median','mask',[1 1 0 1]);
9
+%
10
+%  Input and output arguments ([]'s are optional): 
11
+%   sMap     (struct) map struct or
12
+%            (matrix) the codebook matrix of the map
13
+%   [argID,  (string) See below. The values which are unambiguous can 
14
+%    value]  (varies) be given without the preceeding argID.
15
+%
16
+%   U        (matrix) u-matrix of the self-organizing map 
17
+%
18
+% Here are the valid argument IDs and corresponding values. The values which
19
+% are unambiguous (marked with '*') can be given without the preceeding argID.
20
+%   'mask'       (vector) size dim x 1, weighting factors for different 
21
+%                         components (same as BMU search mask)
22
+%   'msize'      (vector) map grid size
23
+%   'topol'     *(struct) topology struct
24
+%   'som_topol','sTopol' = 'topol'
25
+%   'lattice'   *(string) map lattice, 'hexa' or 'rect'
26
+%   'mode'      *(string) 'min','mean','median','max', default is 'median'
27
+%
28
+% NOTE! the U-matrix is always calculated for 'sheet'-shaped map and
29
+% the map grid must be at most 2-dimensional.
30
+% 
31
+% For more help, try 'type som_umat' or check out online documentation.
32
+% See also SOM_SHOW, SOM_CPLANE.
33
+
34
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35
+%
36
+% som_umat
37
+%
38
+% PURPOSE
39
+%
40
+% Computes the unified distance matrix of a SOM.
41
+%
42
+% SYNTAX
43
+%
44
+%  U = som_umat(sM)  
45
+%  U = som_umat(...,'argID',value,...)
46
+%  U = som_umat(...,value,...)
47
+%
48
+% DESCRIPTION
49
+%
50
+% Compute and return the unified distance matrix of a SOM. 
51
+% For example a case of 5x1 -sized map:
52
+%            m(1) m(2) m(3) m(4) m(5)
53
+% where m(i) denotes one map unit. The u-matrix is a 9x1 vector:
54
+%    u(1) u(1,2) u(2) u(2,3) u(3) u(3,4) u(4) u(4,5) u(5) 
55
+% where u(i,j) is the distance between map units m(i) and m(j)
56
+% and u(k) is the mean (or minimum, maximum or median) of the 
57
+% surrounding values, e.g. u(3) = (u(2,3) + u(3,4))/2. 
58
+%
59
+% Note that the u-matrix is always calculated for 'sheet'-shaped map and
60
+% the map grid must be at most 2-dimensional.
61
+%
62
+% REFERENCES
63
+%
64
+% Ultsch, A., Siemon, H.P., "Kohonen's Self-Organizing Feature Maps
65
+%   for Exploratory Data Analysis", in Proc. of INNC'90,
66
+%   International Neural Network Conference, Dordrecht,
67
+%   Netherlands, 1990, pp. 305-308.
68
+% Kohonen, T., "Self-Organizing Map", 2nd ed., Springer-Verlag, 
69
+%    Berlin, 1995, pp. 117-119. 
70
+% Iivarinen, J., Kohonen, T., Kangas, J., Kaski, S., "Visualizing 
71
+%   the Clusters on the Self-Organizing Map", in proceedings of
72
+%   Conference on Artificial Intelligence Research in Finland,
73
+%   Helsinki, Finland, 1994, pp. 122-126.
74
+% Kraaijveld, M.A., Mao, J., Jain, A.K., "A Nonlinear Projection
75
+%   Method Based on Kohonen's Topology Preserving Maps", IEEE
76
+%   Transactions on Neural Networks, vol. 6, no. 3, 1995, pp. 548-559.
77
+% 
78
+% REQUIRED INPUT ARGUMENTS
79
+%
80
+%  sM (struct) SOM Toolbox struct or the codebook matrix of the map.
81
+%     (matrix) The matrix may be 3-dimensional in which case the first 
82
+%              two dimensions are taken for the map grid dimensions (msize).
83
+%
84
+% OPTIONAL INPUT ARGUMENTS
85
+%
86
+%  argID (string) Argument identifier string (see below).
87
+%  value (varies) Value for the argument (see below).
88
+%
89
+%  The optional arguments are given as 'argID',value -pairs. If the 
90
+%  value is unambiguous, it can be given without the preceeding argID.
91
+%  If an argument is given value multiple times, the last one is used. 
92
+%
93
+%  Below is the list of valid arguments: 
94
+%   'mask'      (vector) mask to be used in calculating
95
+%                        the interunit distances, size [dim  1]. Default is 
96
+%                        the one in sM (field sM.mask) or a vector of
97
+%                        ones if only a codebook matrix was given.
98
+%   'topol'     (struct) topology of the map. Default is the one
99
+%                        in sM (field sM.topol).
100
+%   'sTopol','som_topol' (struct) = 'topol'
101
+%   'msize'     (vector) map grid dimensions
102
+%   'lattice'   (string) map lattice 'rect' or 'hexa'
103
+%   'mode'      (string) 'min', 'mean', 'median' or 'max'
104
+%                        Map unit value computation method. In fact, 
105
+%                        eval-function is used to evaluate this, so 
106
+%                        you can give other computation methods as well.
107
+%                        Default is 'median'. 
108
+%
109
+% OUTPUT ARGUMENTS
110
+%
111
+%  U   (matrix) the unified distance matrix of the SOM 
112
+%               size 2*n1-1 x 2*n2-1, where n1 = msize(1) and n2 = msize(2)
113
+%
114
+% EXAMPLES
115
+%
116
+%  U = som_umat(sM);  
117
+%  U = som_umat(sM.codebook,sM.topol,'median','mask',[1 1 0 1]);
118
+%  U = som_umat(rand(10,10,4),'hexa','rect'); 
119
+% 
120
+% SEE ALSO
121
+%
122
+%  som_show    show the selected component planes and the u-matrix
123
+%  som_cplane  draw a 2D unified distance matrix
124
+
125
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
126
+% http://www.cis.hut.fi/projects/somtoolbox/
127
+
128
+% Version 1.0beta juuso 260997
129
+% Version 2.0beta juuso 151199, 151299, 200900
130
+
131
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
132
+%% check arguments
133
+
134
+error(nargchk(1, Inf, nargin));  % check no. of input arguments is correct
135
+
136
+% sMap
137
+if isstruct(sMap), 
138
+  M = sMap.codebook;
139
+  sTopol = sMap.topol; 
140
+  mask = sMap.mask;
141
+elseif isnumeric(sMap),
142
+  M = sMap; 
143
+  si = size(M);
144
+  dim = si(end);
145
+  if length(si)>2, msize = si(1:end-1);
146
+  else msize = [si(1) 1];
147
+  end
148
+  munits = prod(msize);
149
+  sTopol = som_set('som_topol','msize',msize,'lattice','rect','shape','sheet'); 
150
+  mask = ones(dim,1);
151
+  M = reshape(M,[munits,dim]);
152
+end
153
+mode = 'median';
154
+
155
+% varargin
156
+i=1; 
157
+while i<=length(varargin), 
158
+  argok = 1; 
159
+  if ischar(varargin{i}), 
160
+    switch varargin{i}, 
161
+      % argument IDs
162
+     case 'mask',       i=i+1; mask = varargin{i}; 
163
+     case 'msize',      i=i+1; sTopol.msize = varargin{i}; 
164
+     case 'lattice',    i=i+1; sTopol.lattice = varargin{i};
165
+     case {'topol','som_topol','sTopol'}, i=i+1; sTopol = varargin{i};
166
+     case 'mode',       i=i+1; mode = varargin{i};
167
+      % unambiguous values
168
+     case {'hexa','rect'}, sTopol.lattice = varargin{i};
169
+     case {'min','mean','median','max'}, mode = varargin{i};
170
+     otherwise argok=0; 
171
+    end
172
+  elseif isstruct(varargin{i}) & isfield(varargin{i},'type'), 
173
+    switch varargin{i}(1).type, 
174
+     case 'som_topol', sTopol = varargin{i};
175
+     case 'som_map',   sTopol = varargin{i}.topol;
176
+     otherwise argok=0; 
177
+    end
178
+  else
179
+    argok = 0; 
180
+  end
181
+  if ~argok, 
182
+    disp(['(som_umat) Ignoring invalid argument #' num2str(i+1)]); 
183
+  end
184
+  i = i+1; 
185
+end
186
+
187
+% check
188
+[munits dim] = size(M);
189
+if prod(sTopol.msize)~=munits, 
190
+  error('Map grid size does not match the number of map units.')
191
+end
192
+if length(sTopol.msize)>2, 
193
+  error('Can only handle 1- and 2-dimensional map grids.')
194
+end
195
+if prod(sTopol.msize)==1,
196
+  warning('Only one codebook vector.'); U = []; return;
197
+end
198
+if ~strcmp(sTopol.shape,'sheet'), 
199
+  disp(['The ' sTopol.shape ' shape of the map ignored. Using sheet instead.']);
200
+end
201
+
202
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
203
+%% initialize variables
204
+
205
+y = sTopol.msize(1);
206
+x = sTopol.msize(2);
207
+lattice = sTopol.lattice;
208
+shape = sTopol.shape;
209
+M = reshape(M,[y x dim]);
210
+
211
+ux = 2 * x - 1; 
212
+uy = 2 * y - 1;
213
+U  = zeros(uy, ux);
214
+
215
+calc = sprintf('%s(a)',mode);
216
+
217
+if size(mask,2)>1, mask = mask'; end
218
+
219
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
220
+%% u-matrix computation
221
+
222
+% distances between map units
223
+
224
+if strcmp(lattice, 'rect'), % rectangular lattice
225
+  
226
+  for j=1:y, for i=1:x,
227
+      if i<x, 
228
+	dx = (M(j,i,:) - M(j,i+1,:)).^2; % horizontal
229
+	U(2*j-1,2*i) = sqrt(mask'*dx(:));
230
+      end 
231
+      if j<y, 
232
+	dy = (M(j,i,:) - M(j+1,i,:)).^2; % vertical
233
+	U(2*j,2*i-1) = sqrt(mask'*dy(:));
234
+      end
235
+      if j<y & i<x,	
236
+	dz1 = (M(j,i,:) - M(j+1,i+1,:)).^2; % diagonals
237
+	dz2 = (M(j+1,i,:) - M(j,i+1,:)).^2;
238
+	U(2*j,2*i) = (sqrt(mask'*dz1(:))+sqrt(mask'*dz2(:)))/(2 * sqrt(2));
239
+      end
240
+    end
241
+  end
242
+
243
+elseif strcmp(lattice, 'hexa') % hexagonal lattice
244
+
245
+  for j=1:y, 
246
+    for i=1:x,
247
+      if i<x,
248
+	dx = (M(j,i,:) - M(j,i+1,:)).^2; % horizontal
249
+	U(2*j-1,2*i) = sqrt(mask'*dx(:));
250
+      end
251
+      
252
+      if j<y, % diagonals
253
+	dy = (M(j,i,:) - M(j+1,i,:)).^2;
254
+	U(2*j,2*i-1) = sqrt(mask'*dy(:));	
255
+	
256
+	if rem(j,2)==0 & i<x,
257
+	  dz= (M(j,i,:) - M(j+1,i+1,:)).^2; 
258
+	  U(2*j,2*i) = sqrt(mask'*dz(:));
259
+	elseif rem(j,2)==1 & i>1,
260
+	  dz = (M(j,i,:) - M(j+1,i-1,:)).^2; 
261
+	  U(2*j,2*i-2) = sqrt(mask'*dz(:));
262
+	end
263
+      end
264
+    end
265
+  end
266
+  
267
+end
268
+
269
+% values on the units
270
+
271
+if (uy == 1 | ux == 1),
272
+  % in 1-D case, mean is equal to median 
273
+
274
+  ma = max([ux uy]);
275
+  for i = 1:2:ma,
276
+    if i>1 & i<ma, 
277
+      a = [U(i-1) U(i+1)]; 
278
+      U(i) = eval(calc);
279
+    elseif i==1, U(i) = U(i+1); 
280
+    else U(i) = U(i-1); % i==ma
281
+    end
282
+  end    
283
+
284
+elseif strcmp(lattice, 'rect')
285
+
286
+  for j=1:2:uy, 
287
+    for i=1:2:ux,
288
+      if i>1 & j>1 & i<ux & j<uy,    % middle part of the map
289
+	a = [U(j,i-1) U(j,i+1) U(j-1,i) U(j+1,i)];        
290
+      elseif j==1 & i>1 & i<ux,        % upper edge
291
+	a = [U(j,i-1) U(j,i+1) U(j+1,i)];
292
+      elseif j==uy & i>1 & i<ux,       % lower edge
293
+	a = [U(j,i-1) U(j,i+1) U(j-1,i)];
294
+      elseif i==1 & j>1 & j<uy,        % left edge
295
+	a = [U(j,i+1) U(j-1,i) U(j+1,i)];
296
+      elseif i==ux & j>1 & j<uy,       % right edge
297
+	a = [U(j,i-1) U(j-1,i) U(j+1,i)];
298
+      elseif i==1 & j==1,              % top left corner
299
+	a = [U(j,i+1) U(j+1,i)];
300
+      elseif i==ux & j==1,             % top right corner
301
+	a = [U(j,i-1) U(j+1,i)];
302
+      elseif i==1 & j==uy,             % bottom left corner
303
+	a = [U(j,i+1) U(j-1,i)];
304
+      elseif i==ux & j==uy,            % bottom right corner
305
+	a = [U(j,i-1) U(j-1,i)];
306
+      else
307
+	a = 0;
308
+      end
309
+      U(j,i) = eval(calc);
310
+    end
311
+  end
312
+
313
+elseif strcmp(lattice, 'hexa')
314
+  
315
+  for j=1:2:uy, 
316
+    for i=1:2:ux,
317
+      if i>1 & j>1 & i<ux & j<uy,      % middle part of the map
318
+	a = [U(j,i-1) U(j,i+1)];
319
+	if rem(j-1,4)==0, a = [a, U(j-1,i-1) U(j-1,i) U(j+1,i-1) U(j+1,i)];
320
+	else a = [a, U(j-1,i) U(j-1,i+1) U(j+1,i) U(j+1,i+1)]; end       
321
+      elseif j==1 & i>1 & i<ux,        % upper edge
322
+	a = [U(j,i-1) U(j,i+1) U(j+1,i-1) U(j+1,i)];
323
+      elseif j==uy & i>1 & i<ux,       % lower edge
324
+	a = [U(j,i-1) U(j,i+1)];
325
+	if rem(j-1,4)==0, a = [a, U(j-1,i-1) U(j-1,i)];
326
+	else a = [a, U(j-1,i) U(j-1,i+1)]; end
327
+      elseif i==1 & j>1 & j<uy,        % left edge
328
+	a = U(j,i+1);
329
+	if rem(j-1,4)==0, a = [a, U(j-1,i) U(j+1,i)];
330
+	else a = [a, U(j-1,i) U(j-1,i+1) U(j+1,i) U(j+1,i+1)]; end
331
+      elseif i==ux & j>1 & j<uy,       % right edge
332
+	a = U(j,i-1);
333
+	if rem(j-1,4)==0, a=[a, U(j-1,i) U(j-1,i-1) U(j+1,i) U(j+1,i-1)];
334
+	else a = [a, U(j-1,i) U(j+1,i)]; end
335
+      elseif i==1 & j==1,              % top left corner
336
+	a = [U(j,i+1) U(j+1,i)];
337
+      elseif i==ux & j==1,             % top right corner
338
+	a = [U(j,i-1) U(j+1,i-1) U(j+1,i)];
339
+      elseif i==1 & j==uy,             % bottom left corner
340
+	if rem(j-1,4)==0, a = [U(j,i+1) U(j-1,i)];
341
+	else a = [U(j,i+1) U(j-1,i) U(j-1,i+1)]; end
342
+      elseif i==ux & j==uy,            % bottom right corner
343
+	if rem(j-1,4)==0, a = [U(j,i-1) U(j-1,i) U(j-1,i-1)];
344
+	else a = [U(j,i-1) U(j-1,i)]; end
345
+      else
346
+	a=0;
347
+      end
348
+      U(j,i) = eval(calc);
349
+    end
350
+  end
351
+end
352
+
353
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
354
+%% normalization between [0,1]
355
+
356
+% U = U - min(min(U)); 
357
+% ma = max(max(U)); if ma > 0, U = U / ma; end
358
+
359
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
360
+
361
+
362
+
... ...
@@ -0,0 +1,252 @@
1
+function Coords = som_unit_coords(topol,lattice,shape)
2
+
3
+%SOM_UNIT_COORDS Locations of units on the SOM grid. 
4
+%
5
+% Co = som_unit_coords(topol, [lattice], [shape])
6
+% 
7
+%  Co = som_unit_coords(sMap);
8
+%  Co = som_unit_coords(sMap.topol);
9
+%  Co = som_unit_coords(msize, 'hexa', 'cyl');
10
+%  Co = som_unit_coords([10 4 4], 'rect', 'toroid');
11
+%
12
+%  Input and output arguments ([]'s are optional): 
13
+%   topol              topology of the SOM grid
14
+%             (struct) topology or map struct
15
+%             (vector) the 'msize' field of topology struct
16
+%   [lattice] (string) map lattice, 'rect' by default
17
+%   [shape]   (string) map shape, 'sheet' by default
18
+%
19
+%   Co        (matrix, size [munits k]) coordinates for each map unit    
20
+%
21
+% For more help, try 'type som_unit_coords' or check out online documentation.
22
+% See also SOM_UNIT_DISTS, SOM_UNIT_NEIGHS.
23
+
24
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
25
+%
26
+% som_unit_coords
27
+%
28
+% PURPOSE
29
+%
30
+% Returns map grid coordinates for the units of a Self-Organizing Map.
31
+%
32
+% SYNTAX
33
+%
34
+%  Co = som_unit_coords(sTopol);
35
+%  Co = som_unit_coords(sM.topol);
36
+%  Co = som_unit_coords(msize);
37
+%  Co = som_unit_coords(msize,'hexa');
38
+%  Co = som_unit_coords(msize,'rect','toroid');
39
+%
40
+% DESCRIPTION
41
+%
42
+% Calculates the map grid coordinates of the units of a SOM based on 
43
+% the given topology. The coordinates are such that they can be used to
44
+% position map units in space. In case of 'sheet' shape they can be 
45
+% (and are) used to measure interunit distances. 
46
+%
47
+% NOTE: for 'hexa' lattice, the x-coordinates of every other row are shifted 
48
+% by +0.5, and the y-coordinates are multiplied by sqrt(0.75). This is done 
49
+% to make distances of a unit to all its six neighbors equal. It is not 
50
+% possible to use 'hexa' lattice with higher than 2-dimensional map grids.
51
+%
52
+% 'cyl' and 'toroid' shapes: the coordinates are initially determined as 
53
+% in case of 'sheet' shape, but are then bended around the x- or the 
54
+% x- and then y-axes to get the desired shape. 
55
+% 
56
+% POSSIBLE BUGS
57
+%
58
+% I don't know if the bending operation works ok for high-dimensional
59
+% map grids. Anyway, if anyone wants to make a 4-dimensional
60
+% toroid map, (s)he deserves it.
61
+%
62
+% REQUIRED INPUT ARGUMENTS
63
+% 
64
+%  topol          Map grid dimensions.
65
+%        (struct) topology struct or map struct, the topology 
66
+%                 (msize, lattice, shape) of the map is taken from 
67
+%                 the appropriate fields (see e.g. SOM_SET)
68
+%        (vector) the vector which gives the size of the map grid
69
+%                 (msize-field of the topology struct).
70
+%  
71
+% OPTIONAL INPUT ARGUMENTS 
72
+% 
73
+%  lattice (string) The map lattice, either 'rect' or 'hexa'. Default
74
+%                   is 'rect'. 'hexa' can only be used with 1- or 
75
+%                   2-dimensional map grids.
76
+%  shape   (string) The map shape, either 'sheet', 'cyl' or 'toroid'. 
77
+%                   Default is 'sheet'. 
78
+%
79
+% OUTPUT ARGUMENTS
80
+%
81
+%  Co   (matrix) coordinates for each map units, size is [munits k] 
82
+%                where k is 2, or more if the map grid is higher
83
+%                dimensional or the shape is 'cyl' or 'toroid'
84
+%
85
+% EXAMPLES
86
+%
87
+% Simplest case:
88
+%  Co = som_unit_coords(sTopol);
89
+%  Co = som_unit_coords(sMap.topol);
90
+%  Co = som_unit_coords(msize);
91
+%  Co = som_unit_coords([10 10]);
92
+%
93
+% If topology is given as vector, lattice is 'rect' and shape is 'sheet'
94
+% by default. To change these, you can use the optional arguments:
95
+%  Co = som_unit_coords(msize, 'hexa', 'toroid');
96
+%
97
+% The coordinates can also be calculated for high-dimensional grids:
98
+%  Co = som_unit_coords([4 4 4 4 4 4]);
99
+%
100
+% SEE ALSO
101
+% 
102
+%  som_unit_dists    Calculate interunit distance along the map grid.
103
+%  som_unit_neighs   Calculate neighborhoods of map units.
104
+
105
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
106
+% http://www.cis.hut.fi/projects/somtoolbox/
107
+
108
+% Version 1.0beta juuso 110997
109
+% Version 2.0beta juuso 101199 070600
110
+
111
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
112
+%% Check arguments 
113
+
114
+error(nargchk(1, 3, nargin));
115
+
116
+% default values
117
+sTopol = som_set('som_topol','lattice','rect');
118
+
119
+% topol
120
+if isstruct(topol), 
121
+  switch topol.type, 
122
+  case 'som_map', sTopol = topol.topol;
123
+  case 'som_topol', sTopol = topol;
124
+  end
125
+elseif iscell(topol), 
126
+  for i=1:length(topol), 
127
+    if isnumeric(topol{i}), sTopol.msize = topol{i}; 
128
+    elseif ischar(topol{i}),  
129
+      switch topol{i}, 
130
+      case {'rect','hexa'}, sTopol.lattice = topol{i}; 
131
+      case {'sheet','cyl','toroid'}, sTopol.shape = topol{i}; 
132
+      end
133
+    end
134
+  end
135
+else
136
+  sTopol.msize = topol;
137
+end
138
+if prod(sTopol.msize)==0, error('Map size is 0.'); end
139
+
140
+% lattice
141
+if nargin>1 & ~isempty(lattice) & ~isnan(lattice), sTopol.lattice = lattice; end
142
+
143
+% shape 
144
+if nargin>2 & ~isempty(shape) & ~isnan(shape), sTopol.shape = shape; end
145
+
146
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
147
+%% Action
148
+
149
+msize = sTopol.msize;
150
+lattice = sTopol.lattice;
151
+shape = sTopol.shape;
152
+
153
+% init variables
154
+
155
+if length(msize)==1, msize = [msize 1]; end
156
+munits = prod(msize);
157
+mdim = length(msize);
158
+Coords = zeros(munits,mdim);
159
+
160
+% initial coordinates for each map unit ('rect' lattice, 'sheet' shape)
161
+k = [1 cumprod(msize(1:end-1))]; 
162
+inds = [0:(munits-1)]';
163
+for i = mdim:-1:1, 
164
+  Coords(:,i) = floor(inds/k(i)); % these are subscripts in matrix-notation
165
+  inds = rem(inds,k(i)); 
166
+end
167
+% change subscripts to coordinates (move from (ij)-notation to (xy)-notation)
168
+Coords(:,[1 2]) = fliplr(Coords(:,[1 2])); 
169
+
170
+% 'hexa' lattice
171
+if strcmp(lattice,'hexa'), 
172
+  % check
173
+  if mdim > 2, 
174
+    error('You can only use hexa lattice with 1- or 2-dimensional maps.');
175
+  end
176
+  % offset x-coordinates of every other row 
177
+  inds_for_row = (cumsum(ones(msize(2),1))-1)*msize(1); 
178
+  for i=2:2:msize(1), 
179
+    Coords(i+inds_for_row,1) = Coords(i+inds_for_row,1) + 0.5; 
180
+  end
181
+end
182
+
183
+% shapes
184
+switch shape, 
185
+case 'sheet', 
186
+  if strcmp(lattice,'hexa'), 
187
+    % this correction is made to make distances to all 
188
+    % neighboring units equal
189
+    Coords(:,2) = Coords(:,2)*sqrt(0.75); 
190
+  end
191
+
192
+case 'cyl', 
193
+  % to make cylinder the coordinates must lie in 3D space, at least
194
+  if mdim<3, Coords = [Coords ones(munits,1)]; mdim = 3; end
195
+
196
+  % Bend the coordinates to a circle in the plane formed by x- and 
197
+  % and z-axis. Notice that the angle to which the last coordinates
198
+  % are bended is _not_ 360 degrees, because that would be equal to 
199
+  % the angle of the first coordinates (0 degrees).
200
+
201
+  Coords(:,1)     = Coords(:,1)/max(Coords(:,1));
202
+  Coords(:,1)     = 2*pi * Coords(:,1) * msize(2)/(msize(2)+1);
203
+  Coords(:,[1 3]) = [cos(Coords(:,1)) sin(Coords(:,1))];
204
+                    
205
+case 'toroid', 
206
+
207
+  % NOTE: if lattice is 'hexa', the msize(1) should be even, otherwise 
208
+  % the bending the upper and lower edges of the map do not match 
209
+  % to each other
210
+  if strcmp(lattice,'hexa') & rem(msize(1),2)==1, 
211
+    warning('Map size along y-coordinate is not even.');
212
+  end
213
+
214
+  % to make toroid the coordinates must lie in 3D space, at least
215
+  if mdim<3, Coords = [Coords ones(munits,1)]; mdim = 3; end
216
+
217
+  % First bend the coordinates to a circle in the plane formed
218
+  % by x- and z-axis. Then bend in the plane formed by y- and
219
+  % z-axis. (See also the notes in 'cyl').
220
+
221
+  Coords(:,1)     = Coords(:,1)/max(Coords(:,1));
222
+  Coords(:,1)     = 2*pi * Coords(:,1) * msize(2)/(msize(2)+1);
223
+  Coords(:,[1 3]) = [cos(Coords(:,1)) sin(Coords(:,1))];
224
+
225
+  Coords(:,2)     = Coords(:,2)/max(Coords(:,2));
226
+  Coords(:,2)     = 2*pi * Coords(:,2) * msize(1)/(msize(1)+1);
227
+  Coords(:,3)     = Coords(:,3) - min(Coords(:,3)) + 1;
228
+  Coords(:,[2 3]) = Coords(:,[3 3]) .* [cos(Coords(:,2)) sin(Coords(:,2))];
229
+  
230
+end
231
+
232
+return;
233
+
234
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
235
+%% subfunctions
236
+
237
+function C = bend(cx,cy,angle,xishexa)
238
+
239
+  dx = max(cx) - min(cx);
240
+  if dx ~= 0, 
241
+    % in case of hexagonal lattice it must be taken into account that
242
+    % coordinates of every second row are +0.5 off to the right
243
+    if xishexa, dx = dx-0.5; end
244
+    cx = angle*(cx - min(cx))/dx; 
245
+  end    
246
+  C(:,1) = (cy - min(cy)+1) .* cos(cx);
247
+  C(:,2) = (cy - min(cy)+1) .* sin(cx);
248
+
249
+% end of bend
250
+
251
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
252
+
... ...
@@ -0,0 +1,268 @@
1
+function Ud = som_unit_dists(topol,lattice,shape)
2
+
3
+%SOM_UNIT_DISTS Distances between unit-locations on the map grid.
4
+%
5
+% Ud = som_unit_dists(topol,[lattice],[shape])
6
+% 
7
+%  Ud = som_unit_dists(sMap);
8
+%  Ud = som_unit_dists(sMap.topol);
9
+%  Ud = som_unit_dists(msize, 'hexa', 'cyl');
10
+%  Ud = som_unit_dists([10 4 4], 'rect', 'toroid');
11
+%
12
+%  Input and output arguments ([]'s are optional): 
13
+%   topol              topology of the SOM grid
14
+%             (struct) topology or map struct
15
+%             (vector) the 'msize' field of topology struct
16
+%   [lattice] (string) map lattice, 'rect' by default
17
+%   [shape]   (string) map shape, 'sheet' by default
18
+%
19
+%   Ud        (matrix, size [munits munits]) distance from each map unit 
20
+%                      to each map unit
21
+%
22
+% For more help, try 'type som_unit_dists' or check out online documentation.
23
+% See also SOM_UNIT_COORDS, SOM_UNIT_NEIGHS.
24
+
25
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
26
+%
27
+% som_unit_dists
28
+%
29
+% PURPOSE
30
+%
31
+% Returns interunit distances between the units of a Self-Organizing Map
32
+% along the map grid.
33
+%
34
+% SYNTAX
35
+%
36
+%  Ud = som_unit_dists(sTopol);
37
+%  Ud = som_unit_dists(sM.topol);
38
+%  Ud = som_unit_dists(msize);
39
+%  Ud = som_unit_dists(msize,'hexa');
40
+%  Ud = som_unit_dists(msize,'rect','toroid');
41
+%
42
+% DESCRIPTION
43
+%
44
+% Calculates the distances between the units of a SOM based on the 
45
+% given topology. The distance are euclidian and they are measured
46
+% along the map grid (in the output space). 
47
+%
48
+% In case of 'sheet' shape, the distances can be measured directly
49
+% from the unit coordinates given by SOM_UNIT_COORDS. 
50
+%
51
+% In case of 'cyl' and 'toroid' shapes this is not so. In these cases
52
+% the coordinates are calculated as in the case of 'sheet' shape and
53
+% the shape is then taken into account by shifting the map grid into
54
+% different positions. 
55
+%
56
+% Consider, for example, a 4x3 map. The basic position of map units 
57
+% is shown on the left (with '1' - 'C' each denoting one map unit). 
58
+% In case of a 'cyl' shape, units on the left and right edges are
59
+% neighbors, so for this purpose the map is copied on the left and
60
+% right sides of the map, as on right. 
61
+%
62
+%    basic               left     basic    right
63
+%    -------             -------  -------  -------
64
+%    1  5  9             1  5  9  1  5  9  1  5  9
65
+%    2  6  a             2  6  a  2  6  a  2  6  a  
66
+%    3  7  b             3  7  b  3  7  b  3  7  b 
67
+%    4  8  c             4  8  c  4  8  c  4  8  c 
68
+% 
69
+% For the 'toroid' shape a similar trick is done, except that the 
70
+% copies are placed all around the basic position:
71
+%
72
+%             1  5  9  1  5  9  1  5  9
73
+%             2  6  a  2  6  a  2  6  a  
74
+%             3  7  b  3  7  b  3  7  b 
75
+%             4  8  c  4  8  c  4  8  c 
76
+%             1  5  9  1  5  9  1  5  9
77
+%             2  6  a  2  6  a  2  6  a  
78
+%             3  7  b  3  7  b  3  7  b 
79
+%             4  8  c  4  8  c  4  8  c 
80
+%             1  5  9  1  5  9  1  5  9
81
+%             2  6  a  2  6  a  2  6  a  
82
+%             3  7  b  3  7  b  3  7  b 
83
+%             4  8  c  4  8  c  4  8  c 
84
+%
85
+% From this we can see that the distance from unit '1' is 1 to units
86
+% '9','2','4' and '5', and sqrt(2) to units 'C','A','8' and '6'. Notice 
87
+% that in the case of a 'hexa' lattice and 'toroid' shape, the size
88
+% of the map in y-direction should be even. The reason can be clearly
89
+% seen from the two figures below. On the left the basic positions for
90
+% a 3x3 map. If the map is copied above itself, it can be seen that the
91
+% lattice is broken (on the right):
92
+%
93
+%     basic positions                 example of broken lattice
94
+%     ---------------                 -------------------------
95
+%                                     1  4  7 
96
+%                                      2  5  8
97
+%                                     3  6  9
98
+%     1  4  7                         1  4  7 
99
+%      2  5  8                         2  5  8
100
+%     3  6  9                         3  6  9
101
+%
102
+% 
103
+% REQUIRED INPUT ARGUMENTS
104
+% 
105
+%  topol          Map grid dimensions.
106
+%        (struct) topology struct or map struct, the topology 
107
+%                 (msize, lattice, shape) of the map is taken from 
108
+%                 the appropriate fields (see e.g. SOM_SET)
109
+%        (vector) the vector which gives the size of the map grid
110
+%                 (msize-field of the topology struct).
111
+%  
112
+% OPTIONAL INPUT ARGUMENTS 
113
+% 
114
+%  lattice (string) The map lattice, either 'rect' or 'hexa'. Default
115
+%                   is 'rect'. 'hexa' can only be used with 1- or 
116
+%                   2-dimensional map grids.
117
+%  shape   (string) The map shape, either 'sheet', 'cyl' or 'toroid'. 
118
+%                   Default is 'sheet'. 
119
+%
120
+% OUTPUT ARGUMENTS
121
+%
122
+%  Ud   (matrix) distances from each map unit to each other map unit,
123
+%                size is [munits munits]
124
+%
125
+% EXAMPLES
126
+%
127
+% Simplest case:
128
+%  Ud = som_unit_dists(sTopol);
129
+%  Ud = som_unit_dists(sMap.topol);
130
+%  Ud = som_unit_dists(msize);
131
+%  Ud = som_unit_dists([10 10]);
132
+%
133
+% If topology is given as vector, lattice is 'rect' and shape is 'sheet'
134
+% by default. To change these, you can use the optional arguments:
135
+%  Ud = som_unit_dists(msize, 'hexa', 'toroid');
136
+%
137
+% The distances can also be calculated for high-dimensional grids:
138
+%  Ud = som_unit_dists([4 4 4 4 4 4]);
139
+%
140
+% SEE ALSO
141
+% 
142
+%  som_unit_coords   Calculate grid coordinates.
143
+%  som_unit_neighs   Calculate neighborhoods of map units.
144
+
145
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
146
+% http://www.cis.hut.fi/projects/somtoolbox/
147
+
148
+% Version 1.0beta juuso 110997
149
+% Version 2.0beta juuso 101199 170400 070600 130600
150
+
151
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
152
+%% Check arguments 
153
+
154
+error(nargchk(1, 3, nargin));
155
+
156
+% default values
157
+sTopol = som_set('som_topol','lattice','rect');
158
+
159
+% topol
160
+if isstruct(topol), 
161
+  switch topol.type, 
162
+  case 'som_map', sTopol = topol.topol;
163
+  case 'som_topol', sTopol = topol;
164
+  end
165
+elseif iscell(topol), 
166
+  for i=1:length(topol), 
167
+    if isnumeric(topol{i}), sTopol.msize = topol{i}; 
168
+    elseif ischar(topol{i}),  
169
+      switch topol{i}, 
170
+      case {'rect','hexa'}, sTopol.lattice = topol{i}; 
171
+      case {'sheet','cyl','toroid'}, sTopol.shape = topol{i}; 
172
+      end
173
+    end
174
+  end
175
+else
176
+  sTopol.msize = topol;
177
+end
178
+if prod(sTopol.msize)==0, error('Map size is 0.'); end
179
+
180
+% lattice
181
+if nargin>1 & ~isempty(lattice) & ~isnan(lattice), sTopol.lattice = lattice; end
182
+
183
+% shape 
184
+if nargin>2 & ~isempty(shape) & ~isnan(shape), sTopol.shape = shape; end
185
+
186
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
187
+%% Action
188
+
189
+msize = sTopol.msize;
190
+lattice = sTopol.lattice;
191
+shape = sTopol.shape;
192
+
193
+munits = prod(msize);
194
+Ud = zeros(munits,munits);
195
+
196
+% free topology
197
+if strcmp(lattice,'free'),
198
+  N1 = sTopol.connection; 
199
+  Ud = som_neighborhood(N1,Inf);
200
+end
201
+
202
+% coordinates of map units when the grid is spread on a plane
203
+Coords = som_unit_coords(msize,lattice,'sheet');
204
+
205
+% width and height of the grid
206
+dx = max(Coords(:,1))-min(Coords(:,1));
207
+if msize(1)>1, dx = dx*msize(1)/(msize(1)-1); else dx = dx+1; end
208
+dy = max(Coords(:,2))-min(Coords(:,2));
209
+if msize(2)>1, dy = dy*msize(2)/(msize(2)-1); else dy = dy+1; end
210
+
211
+% calculate distance from each location to each other location
212
+switch shape, 
213
+case 'sheet',
214
+  for i=1:(munits-1), 
215
+    inds = [(i+1):munits]; 
216
+    Dco = (Coords(inds,:) - Coords(ones(munits-i,1)*i,:))'; 
217
+    Ud(i,inds) = sqrt(sum(Dco.^2));
218
+  end
219
+
220
+case 'cyl', 
221
+  for i=1:(munits-1), 
222
+    inds = [(i+1):munits]; 
223
+    Dco  = (Coords(inds,:) - Coords(ones(munits-i,1)*i,:))'; 
224
+    dist = sum(Dco.^2);
225
+    % The cylinder shape is taken into account by adding and substracting
226
+    % the width of the map (dx) from the x-coordinate (ie. shifting the
227
+    % map right and left).
228
+    DcoS = Dco; DcoS(1,:) = DcoS(1,:) + dx;  %East (x+dx)
229
+    dist = min(dist,sum(DcoS.^2));
230
+    DcoS = Dco; DcoS(1,:) = DcoS(1,:) - dx;  %West (x-dx)
231
+    dist = min(dist,sum(DcoS.^2));
232
+    Ud(i,inds) = sqrt(dist);
233
+  end
234
+
235
+case 'toroid', 
236
+  for i=1:(munits-1), 
237
+    inds = [(i+1):munits]; 
238
+    Dco  = (Coords(inds,:) - Coords(ones(munits-i,1)*i,:))'; 
239
+    dist = sum(Dco.^2); 
240
+    % The toroid shape is taken into account as the cylinder shape was 
241
+    % (see above), except that the map is shifted also vertically.
242
+    DcoS = Dco; DcoS(1,:) = DcoS(1,:) + dx;  %East (x+dx)
243
+    dist = min(dist,sum(DcoS.^2));
244
+    DcoS = Dco; DcoS(1,:) = DcoS(1,:) - dx;  %West (x+dx)
245
+    dist = min(dist,sum(DcoS.^2));
246
+    DcoS = Dco; DcoS(2,:) = DcoS(2,:) + dy;  %South (y+dy)
247
+    dist = min(dist,sum(DcoS.^2));
248
+    DcoS = Dco; DcoS(2,:) = DcoS(2,:) - dy;  %North (y-dy)
249
+    dist = min(dist,sum(DcoS.^2));
250
+    DcoS = Dco; DcoS(1,:) = DcoS(1,:) + dx; DcoS(2,:) = DcoS(2,:) - dy; %NorthEast (x+dx, y-dy)
251
+    dist = min(dist,sum(DcoS.^2));
252
+    DcoS = Dco; DcoS(1,:) = DcoS(1,:) + dx; DcoS(2,:) = DcoS(2,:) + dy; %SouthEast (x+dx, y+dy)
253
+    dist = min(dist,sum(DcoS.^2));
254
+    DcoS = Dco; DcoS(1,:) = DcoS(1,:) - dx; DcoS(2,:) = DcoS(2,:) + dy; %SouthWest (x-dx, y+dy)
255
+    dist = min(dist,sum(DcoS.^2));
256
+    DcoS = Dco; DcoS(1,:) = DcoS(1,:) - dx; DcoS(2,:) = DcoS(2,:) - dy; %NorthWest (x-dx, y-dy)
257
+    dist = min(dist,sum(DcoS.^2));
258
+    Ud(i,inds) = sqrt(dist);
259
+  end
260
+
261
+otherwise, 
262
+  error (['Unknown shape: ', shape]);
263
+
264
+end
265
+
266
+Ud = Ud + Ud';
267
+
268
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,164 @@
1
+function Ne1 = som_unit_neighs(topol,lattice,shape)
2
+
3
+%SOM_UNIT_NEIGHS Matrix indicating units in 1-neighborhood for each map unit.
4
+%
5
+% Ne1 = som_unit_neighs(topol,[lattice],[shape])
6
+% 
7
+%  Ne1 = som_unit_neighs(sTopol);
8
+%  Ne1 = som_unit_neighs(sMap.topol);
9
+%  Ne1 = som_unit_neighs([10 4], 'hexa', 'cyl');
10
+%  Ne1 = som_unit_neighs(msize, 'rect', 'toroid');
11
+%
12
+%  Input and output arguments ([]'s are optional): 
13
+%   topol              topology of the SOM grid
14
+%             (struct) topology or map struct
15
+%             (vector) the 'msize' field of topology struct
16
+%   [lattice] (string) map lattice, 'rect' by default
17
+%   [shape]   (string) map shape, 'sheet' by default
18
+%
19
+%   Ne1       (matrix, size [munits munits]) a sparse matrix
20
+%                      indicating the map units in 1-neighborhood
21
+%                      by value 1 (note: the unit itself also has value 0)
22
+%
23
+% For more help, try 'type som_unit_neighs' or check out online documentation.
24
+% See also SOM_NEIGHBORHOOD, SOM_UNIT_DISTS, SOM_UNIT_COORDS, SOM_CONNECTION.
25
+
26
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
27
+%
28
+% som_unit_neighs
29
+%
30
+% PURPOSE
31
+%
32
+% Find the adjacent (in 1-neighborhood) units for each map unit of a SOM
33
+% based on given topology.
34
+%
35
+% SYNTAX
36
+%
37
+%  Ne1 = som_unit_neighs(sMap);
38
+%  Ne1 = som_unit_neighs(sM.topol);
39
+%  Ne1 = som_unit_neighs(msize);
40
+%  Ne1 = som_unit_neighs(msize,'hexa');
41
+%  Ne1 = som_unit_neighs(msize,'rect','toroid');
42
+%
43
+% DESCRIPTION
44
+%
45
+% For each map unit, find the units the distance of which from 
46
+% the map unit is equal to 1. The distances are calculated
47
+% along the map grid. Consider, for example, the case of a 4x3 map. 
48
+% The unit ('1' to 'C') positions for 'rect' and 'hexa' lattice (and
49
+% 'sheet' shape) are depicted below: 
50
+% 
51
+%   'rect' lattice           'hexa' lattice
52
+%   --------------           --------------
53
+%      1  5  9                  1  5  9
54
+%      2  6  a                   2  6  a
55
+%      3  7  b                  3  7  b
56
+%      4  8  c                   4  8  c
57
+%
58
+% The units in 1-neighborhood (adjacent units) for unit '6' are '2','5','7'
59
+% and 'a' in the 'rect' case and '5','2','7','9','a' and 'b' in the 'hexa'
60
+% case. The function returns a sparse matrix having value 1 for these units.  
61
+% Notice that not all units have equal number of neighbors. Unit '1' has only 
62
+% units '2' and '5' in its 1-neighborhood. 
63
+% 
64
+% REQUIRED INPUT ARGUMENTS
65
+% 
66
+%  topol          Map grid dimensions.
67
+%        (struct) topology struct or map struct, the topology 
68
+%                 (msize, lattice, shape) of the map is taken from 
69
+%                 the appropriate fields (see e.g. SOM_SET)
70
+%        (vector) the vector which gives the size of the map grid
71
+%                 (msize-field of the topology struct).
72
+%  
73
+% OPTIONAL INPUT ARGUMENTS 
74
+% 
75
+%  lattice (string) The map lattice, either 'rect' or 'hexa'. Default
76
+%                   is 'rect'. 'hexa' can only be used with 1- or 
77
+%                   2-dimensional map grids.
78
+%  shape   (string) The map shape, either 'sheet', 'cyl' or 'toroid'. 
79
+%                   Default is 'sheet'. 
80
+%
81
+% OUTPUT ARGUMENTS
82
+%
83
+%  Ne1   (matrix) sparse matrix indicating units in 1-neighborhood
84
+%                 by 1, all others have value 0 (including the unit itself!),
85
+%                 size is [munits munits]
86
+%
87
+% EXAMPLES
88
+%
89
+% Simplest case:
90
+%  Ne1 = som_unit_neighs(sTopol);
91
+%  Ne1 = som_unit_neighs(sMap.topol);
92
+%  Ne1 = som_unit_neighs(msize);
93
+%  Ne1 = som_unit_neighs([10 10]);
94
+%
95
+% If topology is given as vector, lattice is 'rect' and shape is 'sheet'
96
+% by default. To change these, you can use the optional arguments:
97
+%  Ne1 = som_unit_neighs(msize, 'hexa', 'toroid');
98
+%
99
+% The neighbors can also be calculated for high-dimensional grids:
100
+%  Ne1 = som_unit_neighs([4 4 4 4 4 4]);
101
+%
102
+% SEE ALSO
103
+% 
104
+%  som_neighborhood  Calculate N-neighborhoods of map units.
105
+%  som_unit_coords   Calculate grid coordinates.
106
+%  som_unit_dists    Calculate interunit distances.
107
+%  som_connection    Connection matrix.
108
+
109
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
110
+% http://www.cis.hut.fi/projects/somtoolbox/
111
+
112
+% Version 1.0beta juuso 141097
113
+% Version 2.0beta juuso 101199
114
+
115
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
116
+%% Check arguments 
117
+
118
+error(nargchk(1, 3, nargin));
119
+
120
+% default values
121
+sTopol = som_set('som_topol','lattice','rect');
122
+
123
+% topol
124
+if isstruct(topol), 
125
+  switch topol.type, 
126
+  case 'som_map', sTopol = topol.topol;
127
+  case 'som_topol', sTopol = topol;
128
+  end
129
+elseif iscell(topol), 
130
+  for i=1:length(topol), 
131
+    if isnumeric(topol{i}), sTopol.msize = topol{i}; 
132
+    elseif ischar(topol{i}),  
133
+      switch topol{i}, 
134
+      case {'rect','hexa'}, sTopol.lattice = topol{i}; 
135
+      case {'sheet','cyl','toroid'}, sTopol.shape = topol{i}; 
136
+      end
137
+    end
138
+  end
139
+else
140
+  sTopol.msize = topol;
141
+end
142
+if prod(sTopol.msize)==0, error('Map size is 0.'); end
143
+
144
+% lattice
145
+if nargin>1 & ~isempty(lattice) & ~isnan(lattice), sTopol.lattice = lattice; end
146
+
147
+% shape 
148
+if nargin>2 & ~isempty(shape) & ~isnan(shape), sTopol.shape = shape; end
149
+
150
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
151
+%% Action
152
+
153
+% distances between each map unit
154
+Ud = som_unit_dists(sTopol);
155
+
156
+% 1-neighborhood are those units the distance of which is equal to 1
157
+munits = prod(sTopol.msize);
158
+Ne1 = sparse(zeros(munits));
159
+for i=1:munits, 
160
+  inds = find(Ud(i,:)<1.01 & Ud(i,:)>0); % allow for rounding error
161
+  Ne1(i,inds) = 1;
162
+end
163
+
164
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,20 @@
1
+function som_use_vs1()
2
+
3
+% SOM_USE_VS1  Use SOM Toolbox version 1.
4
+%
5
+% Removes SOM Toolbox version 2 from the path and adds version 1 there
6
+% instead. Before doing this, remember to convert any version 2 structs you
7
+% will need to the corresponding version 1 structs using function SOM_VS2TO1.
8
+%
9
+% See also  SOM_USE_VS2, SOM_VS1TO2, SOM_VS2TO1, PATHTOOL.
10
+
11
+rmpath /share/somtoolbox/www/package/codes2
12
+
13
+s=path; 
14
+p=findstr(s,'/share/matlab5'); p=p(1);
15
+i=p+12; while ~strcmp(s(i),'/'), i=i+1; end
16
+r=strcat(s(p:i),'toolbox/somtoolbox');
17
+addpath(r)
18
+
19
+fprintf(1,'Version 1 of SOM Toolbox now in use.\n');
20
+fprintf(1,'Use som_vs2to1 function to convert any vs2 structs to vs1.\n')
... ...
@@ -0,0 +1,29 @@
1
+function som_use_vs2()
2
+
3
+% SOM_USE_VS2  Use SOM Toolbox version 2.
4
+%
5
+% Removes SOM Toolbox version 1 from the path and adds version 2
6
+% there instead. You can use function SOM_VS1TO2 to convert 
7
+% any version 1 structs to the corresponding version 2 structs.
8
+%
9
+% See also  SOM_USE_VS1, SOM_VS1TO2, SOM_VS2TO1, PATHTOOL.
10
+
11
+s=path; p=findstr(s,'somtoolbox'); 
12
+while any(p), 
13
+  p=p(1); 
14
+  i=p; while i<length(s) & ~strcmp(s(i),':'), i=i+1; end
15
+  if strcmp(s(i),':'), i=i-1; end
16
+  j=p; while j>1         & ~strcmp(s(j),':'), j=j-1; end
17
+  if strcmp(s(j),':'), j=j+1; end
18
+  r=s(j:i);
19
+  rmpath(r);
20
+  s=path; p=findstr(s,'somtoolbox'); 
21
+end
22
+
23
+addpath /share/somtoolbox/www/package/codes2
24
+
25
+fprintf(1,'Version 2 of SOM Toolbox now in use.\n');
26
+fprintf(1,'Latest changes to SOM Toolbox: August 22nd 2000\n');
27
+fprintf(1,' see /share/somtoolbox/vs2/changelog.txt\n');
28
+fprintf(1,'Use som_vs1to2 function to convert any vs1 structs to vs2.\n')
29
+
... ...
@@ -0,0 +1,153 @@
1
+function unit_coord=som_vis_coords(lattice, msize)
2
+
3
+%SOM_VIS_COORDS Unit coordinates used in visualizations.
4
+% 
5
+% Co = som_vis_coords(lattice, msize)
6
+%
7
+%  Co = som_vis_coords('hexa',[10 7])
8
+%  Co = som_vis_coords('rectU',[10 7])
9
+%
10
+%  Input and output arguments: 
11
+%   lattice   (string) 'hexa', 'rect', 'hexaU' or 'rectU'
12
+%   msize     (vector) grid size in a 1x2 vector    
13
+%
14
+%   Co        (matrix) Mx2 matrix of unit coordinates, where 
15
+%               M=prod(msize) for 'hexa' and 'rect', and 
16
+%               M=(2*msize(1)-1)*(2*msize(2)-1) for 'hexaU' and 'rectU'
17
+%
18
+% This function calculates the coordinates of map units on a 'sheet'
19
+% shaped map with either 'hexa' or 'rect' lattice as used in the
20
+% visualizations. Note that this slightly different from the
21
+% coordinates provided by SOM_UNIT_COORDS function. 
22
+%
23
+% 'rectU' and 'hexaU' gives the coordinates of both units and the
24
+% connections for u-matrix visualizations.
25
+%
26
+% For more help, try 'type som_vis_coords' or check out online documentation.
27
+% See also SOM_UNIT_COORDS, SOM_UMAT, SOM_CPLANE, SOM_GRID.
28
+
29
+%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
30
+%
31
+% PURPOSE 
32
+% 
33
+% Returns coordinates of the map units for map visualization
34
+%
35
+% SYNTAX
36
+%
37
+%  Co = som_vis_coords(lattice, msize)
38
+%
39
+% DESCRIPTION
40
+%
41
+% This function calculates the coordinates of map units in 'hexa' and
42
+% 'rect' lattices in 'sheet' shaped map for visualization purposes. It
43
+% differs from SOM_UNIT_COORDS in the sense that hexagonal lattice is
44
+% calculated in a "wrong" way in order to get integer coordinates for
45
+% the units. Another difference is that it may be used to calculate
46
+% the coordinates of units _and_ the center points of the lines
47
+% connecting them (edges) by using 'hexaU' or 'rectU' for lattice. 
48
+% This property may be used for drawing u-matrices.
49
+%
50
+% The unit number 1 is set to (ij) coordinates (1,1)+shift
51
+%                 2                            (2,1)+shift
52
+%
53
+%  ... columnwise
54
+% 
55
+%             n-1th                        (n1-1,n2)+shift
56
+%             nth                            (n1,n2)+shift
57
+%
58
+% where grid size = [n1 n2] and shift is zero, except for 
59
+% the even lines of 'hexa' lattice, for which it is +0.5.
60
+%
61
+% For 'rectU' and 'hexaU' the unit coordinates are the same and the
62
+% coordinates for connections are set according to these. In this case
63
+% the ordering of the coordinates is the following:
64
+%   let
65
+%     U  = som_umat(sMap); U=U(:); % make U a column vector
66
+%     Uc = som_vis_coords(sMap.topol.lattice, sMap.topol.msize); 
67
+%   now the kth row of matrix Uc, i.e. Uc(k,:), contains the coordinates 
68
+%   for value U(k). 
69
+%
70
+% REQUIRED INPUT ARGUMENTS 
71
+%
72
+%  lattice  (string) The local topology of the units: 
73
+%                    'hexa', 'rect', 'hexaU' or 'rectU'
74
+%  msize    (vector) size 1x2, defining the map grid size. 
75
+%                    Notice that only 2-dimensional grids
76
+%                    are allowed.
77
+%
78
+% OUTPUT ARGUMENTS
79
+% 
80
+%  Co       (matrix) size Mx2, giving the coordinates for each unit.
81
+%                    M=prod(msize) for 'hexa' and 'rect', and 
82
+%                    M=(2*msize(1)-1)*(2*msize(2)-1) for 'hexaU' and 'rectU'
83
+%
84
+% FEATURES
85
+% 
86
+% Only 'sheet' shaped maps are considered. If coordinates for 'toroid'
87
+% or 'cyl' topologies are required, you must use SOM_UNIT_COORDS
88
+% instead.
89
+%
90
+% EXAMPLES
91
+%
92
+% Though this is mainly a subroutine for visualizations it may be
93
+% used, e.g., in the following manner:
94
+%
95
+% % This makes a hexagonal lattice, where the units are rectangular
96
+% % instead of hexagons.
97
+%    som_cplane('rect',som_vis_coords('hexa',[10 7]),'none');
98
+%
99
+% % Let's make a map and calculate a u-matrix: 
100
+%    sM=som_make(data,'msize',[10 7],'lattice','hexa');
101
+%    u=som_umat(sM); u=u(:);
102
+% % Now, these produce equivalent results:
103
+%    som_cplane('hexaU',[10 7],u);
104
+%    som_cplane(vis_patch('hexa')/2,som_vis_coords('hexaU',[10 7]),u);
105
+%
106
+% SEE ALSO
107
+%
108
+% som_grid         Visualization of a SOM grid
109
+% som_cplane       Visualize a 2D component plane, u-matrix or color plane
110
+% som_barplane     Visualize the map prototype vectors as bar diagrams
111
+% som_plotplane    Visualize the map prototype vectors as line graphs
112
+% som_pieplane     Visualize the map prototype vectors as pie charts
113
+% som_unit_coords  Locations of units on the SOM grid
114
+
115
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
116
+% http://www.cis.hut.fi/projects/somtoolbox/             
117
+
118
+% Version 2.0beta Johan 201099 juuso 261199
119
+
120
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
121
+
122
+if ~vis_valuetype(msize,{'1x2'}),
123
+  error('msize must be a 1x2 vector.')
124
+end
125
+
126
+if vis_valuetype(lattice,{'string'})
127
+  switch lattice
128
+  case {'hexa', 'rect'}
129
+    munits=prod(msize);
130
+    unit_coord(:,1)=reshape(repmat([1:msize(2)],msize(1),1),1,munits)';
131
+    unit_coord(:,2)=repmat([1:msize(1)]',msize(2),1);
132
+    if strcmp(lattice,'hexa')
133
+      % Move even rows by .5
134
+      d=rem(unit_coord(:,2),2) == 0;   
135
+      unit_coord(d,1)=unit_coord(d,1)+.5;
136
+    end
137
+  case {'hexaU','rectU'}
138
+    msize=2*msize-1; munits=prod(msize);
139
+    unit_coord(:,1)=reshape(repmat([1:msize(2)],msize(1),1),1,munits)';
140
+    unit_coord(:,2)=repmat([1:msize(1)]',msize(2),1);
141
+    if strcmp(lattice,'hexaU')
142
+      d=rem(unit_coord(:,2),2) == 0;   
143
+      unit_coord(d,1)=unit_coord(d,1)+.5;
144
+      d=rem(unit_coord(:,2)+1,4) == 0; 
145
+      unit_coord(d,1)=unit_coord(d,1)+1;
146
+    end
147
+    unit_coord=unit_coord/2+.5;
148
+  otherwise
149
+    error([ 'Unknown lattice ''' lattice '''.']);
150
+  end
151
+else
152
+  error('Lattice must be a string.');
153
+end
... ...
@@ -0,0 +1,262 @@
1
+function sS = som_vs1to2(sS)
2
+
3
+%SOM_VS1TO2 Convert version 1 structure to version 2.
4
+%
5
+% sSnew = som_vs1to2(sSold)
6
+%
7
+%  sMnew = som_vs1to2(sMold);  
8
+%  sDnew = som_vs1to2(sDold);  
9
+%
10
+%  Input and output arguments: 
11
+%   sSold   (struct) a SOM Toolbox version 1 structure
12
+%   sSnew   (struct) a SOM Toolbox version 2 structure
13
+%
14
+% For more help, try 'type som_vs1to2' or check out online documentation.
15
+% See also  SOM_SET, SOM_VS2TO1.
16
+
17
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
18
+%
19
+% som_vs1to2
20
+%
21
+% PURPOSE
22
+%
23
+% Transforms SOM Toolbox 1 version structs from to 2 version structs.
24
+%
25
+% SYNTAX
26
+%
27
+%  sS2 = som_vs1to2(sS1)
28
+%
29
+% DESCRIPTION
30
+%
31
+% This function is offered to allow the change of old map and data structs
32
+% to new ones. There are quite a lot of changes between the versions,
33
+% especially in the map struct, and this function makes it easy to update 
34
+% the structs.
35
+%
36
+% WARNING!
37
+%
38
+% 'som_unit_norm' normalization type is not supported by version 2,
39
+% so this type of normalization will be lost.
40
+%
41
+% REQUIRED INPUT ARGUMENTS
42
+%
43
+%  sS1       (struct) any SOM Toolbox version 1 struct (map, data, 
44
+%                     training or normalization struct)
45
+%
46
+% OUTPUT ARGUMENTS
47
+% 
48
+%  sS2       (struct) the corresponding SOM Toolbox 2 version struct
49
+%
50
+% EXAMPLES
51
+%
52
+%  sM = som_vs1to2(sMold);
53
+%  sD = som_vs1to2(sDold);
54
+%  sT = som_vs1to2(sMold.train_sequence{1});
55
+%  sN = som_vs1to2(sDold.normalization); 
56
+%
57
+% SEE ALSO
58
+% 
59
+%  som_set          Set values and create SOM Toolbox structs.
60
+%  som_vs2to1       Transform structs from version 2.0 to 1.0.
61
+
62
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
63
+% http://www.cis.hut.fi/projects/somtoolbox/
64
+
65
+% Version 2.0beta juuso 101199
66
+
67
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
68
+%% check arguments
69
+
70
+error(nargchk(1, 1, nargin));   % check no. of input arguments is correct
71
+
72
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
73
+%% set field values
74
+
75
+if isfield(sS,'codebook'), type='som_map'; 
76
+elseif isfield(sS,'data'), type='som_data'; 
77
+elseif isfield(sS,'algorithm'), type = 'som_train';
78
+elseif isfield(sS,'inv_params'), type = 'som_norm'; 
79
+else
80
+  error('Unrecognized input struct.'); 
81
+end
82
+
83
+switch type, 
84
+ case 'som_map',
85
+  msize = sS.msize; munits = prod(msize); dim = prod(size(sS.codebook))/munits; 
86
+  M = reshape(sS.codebook,[munits dim]);
87
+
88
+  % topology
89
+  if strcmp(sS.shape,'rect'), shape = 'sheet'; else shape = sS.shape; end
90
+  sTopol = struct('type','som_topol','msize',msize,'lattice',sS.lattice,'shape',shape);
91
+  
92
+  % labels
93
+  labels = cell(munits,1);
94
+  for i=1:munits, 
95
+    for j=1:length(sS.labels{i}), labels{i,j} = sS.labels{i}{j}; end
96
+  end
97
+  
98
+  % trainhist
99
+  tl = length(sS.train_sequence); 
100
+  if strcmp(sS.init_type,'linear'); alg = 'lininit'; else alg = 'randinit'; end
101
+  trh = struct('type','som_train');
102
+  trh.algorithm = alg;
103
+  trh.neigh = sS.neigh;
104
+  trh.mask = sS.mask;
105
+  trh.data_name = sS.data_name; 
106
+  trh.radius_ini = NaN;
107
+  trh.radius_fin = NaN;
108
+  trh.alpha_ini = NaN; 
109
+  trh.alpha_type = '';
110
+  trh.trainlen = NaN;
111
+  trh.time = '';
112
+  for i=1:tl, 
113
+    trh(i+1) = som_vs1to2(sS.train_sequence{i});     
114
+    trh(i+1).mask = sS.mask;
115
+    trh(i+1).neigh = sS.neigh;
116
+    trh(i+1).data_name = sS.data_name;
117
+  end
118
+  
119
+  % component normalizations
120
+  cnorm = som_vs1to2(sS.normalization); 
121
+  if isempty(cnorm), 
122
+    cnorm = cell(dim,1);
123
+  elseif length(cnorm) ~= dim, 
124
+    warning('Incorrect number of normalizations. Normalizations ignored.\n');	    
125
+    cnorm = cell(dim,1);
126
+  else
127
+    if strcmp(cnorm{1}.method,'histD'),
128
+      M = redo_hist_norm(M,sS.normalization.inv_params,cnorm);
129
+    end
130
+  end     
131
+  
132
+  % map
133
+  sSnew = struct('type','som_map');
134
+  sSnew.codebook = M;
135
+  sSnew.topol = sTopol;
136
+  sSnew.labels = labels;
137
+  sSnew.neigh = sS.neigh;
138
+  sSnew.mask = sS.mask;
139
+  sSnew.trainhist = trh;
140
+  sSnew.name = sS.name;
141
+  sSnew.comp_norm = cnorm;
142
+  sSnew.comp_names = sS.comp_names;
143
+  
144
+ case 'som_data',
145
+  [dlen dim] = size(sS.data);
146
+  
147
+  % component normalizations
148
+  cnorm = som_vs1to2(sS.normalization);
149
+  if isempty(cnorm), 
150
+    cnorm = cell(dim,1);
151
+  elseif length(cnorm) ~= dim, 
152
+    warning('Incorrect number of normalizations. Normalizations ignored.\n');
153
+    cnorm = cell(dim,1);
154
+  else
155
+    if strcmp(cnorm{1}.method,'histD'),
156
+      sS.data = redo_hist_norm(sS.data,sS.normalization.inv_params,cnorm);
157
+    end     
158
+  end
159
+
160
+  % data
161
+  sSnew = struct('type','som_data');
162
+  sSnew.data = sS.data;
163
+  sSnew.name = sS.name;
164
+  sSnew.labels = sS.labels;
165
+  sSnew.comp_names = sS.comp_names;
166
+  sSnew.comp_norm = cnorm;
167
+  sSnew.label_names = []; 
168
+  
169
+ case 'som_norm',       
170
+  if isempty(sS.inv_params), 
171
+    sSnew = []; 
172
+  else 
173
+    dim = size(sS.inv_params,2);      
174
+    sSnew = cell(dim,1);
175
+    switch sS.name, 
176
+     case 'som_var_norm',  method = 'var'; 
177
+     case 'som_lin_norm',  method = 'range'; 
178
+     case 'som_hist_norm', method = 'histD'; 
179
+     case 'som_unit_norm', method = '';
180
+      warning(['Normalization method ''som_unit_norm'' is not available' ...
181
+	       ' in version 2 of SOM Toolbox.\n']);
182
+    end
183
+    if ~isempty(method), 
184
+      for i=1:dim, 
185
+	sSnew{i} = struct('type','som_norm');
186
+	sSnew{i}.method = method;
187
+	sSnew{i}.params = [];
188
+	sSnew{i}.status = 'done';
189
+	switch method, 
190
+	 case 'var',   
191
+	  me = sS.inv_params(1,i); st = sS.inv_params(2,i);
192
+	  sSnew{i}.params = [me, st];
193
+	 case 'range', 
194
+	  mi = sS.inv_params(1,i); ma = sS.inv_params(2,i); 
195
+	  sSnew{i}.params = [mi, ma-mi]; 
196
+	 case 'histD',
197
+	  vals = sS.inv_params(1:(end-1),i);
198
+	  bins = sum(isfinite(vals));
199
+	  vals = vals(1:bins);
200
+	  sSnew{i}.params = vals;
201
+	end	  
202
+      end
203
+    end
204
+  end
205
+  
206
+ case 'som_train', 
207
+  sSnew = struct('type','som_train');
208
+  sSnew.algorithm = sS.algorithm;
209
+  sSnew.neigh = 'gaussian';
210
+  sSnew.mask = [];
211
+  sSnew.data_name = 'unknown'; 
212
+  sSnew.radius_ini = sS.radius_ini;
213
+  sSnew.radius_fin = sS.radius_fin;
214
+  sSnew.alpha_ini = sS.alpha_ini;
215
+  sSnew.alpha_type = sS.alpha_type;
216
+  sSnew.trainlen = sS.trainlen;
217
+  sSnew.time = sS.time;
218
+  
219
+ case 'som_topol', 
220
+  disp('Version 1.0 of SOM Toolbox did not have topology structure.\n');
221
+ 
222
+ case {'som_grid','som_vis'}
223
+  disp('Version 1.0 of SOM Toolbox did not have visualization structs.\n');
224
+  
225
+ otherwise, 
226
+  
227
+  error('Unrecognized struct.');
228
+end
229
+
230
+sS = sSnew;
231
+
232
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
233
+%% subfunctions
234
+
235
+function D = redo_hist_norm(D,inv_params,cnorm)
236
+
237
+  dim = size(D,2);
238
+
239
+  % first - undo the old way
240
+  n_bins = inv_params(end,:);
241
+  D   = round(D * sparse(diag(n_bins)));
242
+  for i = 1:dim,
243
+    if any(isnan(D(:, i))), D(isnan(D(:, i)), i) = n_bins(i); end
244
+    D(:, i) = inv_params(D(:, i), i);
245
+  end
246
+  % then - redo the new way
247
+  for i=1:dim, 
248
+    bins = length(cnorm{i}.params);
249
+    x = D(:,i);
250
+    inds = find(~isnan(x) & ~isinf(x))';
251
+    for j = inds, 
252
+      [dummy ind] = min(abs(x(j) - cnorm{i}.params));
253
+      if x(j) > cnorm{i}.params(ind) & ind < bins, x(j) = ind + 1;  
254
+      else x(j) = ind;
255
+      end
256
+    end
257
+    D(:,i) = (x-1)/(bins-1);
258
+  end
259
+
260
+
261
+
262
+
... ...
@@ -0,0 +1,298 @@
1
+function sS = som_vs2to1(sS)
2
+
3
+%SOM_VS2TO1 Convert version 2 struct to version 1.
4
+%
5
+% sSold = som_vs2to1(sSnew)
6
+%
7
+%  sMold = som_vs2to1(sMnew);  
8
+%  sDold = som_vs2to1(sDnew);  
9
+%
10
+%  Input and output arguments: 
11
+%   sSnew   (struct) a SOM Toolbox version 2 struct
12
+%   sSold   (struct) a SOM Toolbox version 1 struct
13
+%
14
+% For more help, try 'type som_vs2to1' or check out online documentation.
15
+% See also  SOM_SET, SOM_VS1TO2.
16
+
17
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
18
+%
19
+% som_vs2to1
20
+%
21
+% PURPOSE
22
+%
23
+% Converts SOM Toolbox version 2 structs to version 1 structs.
24
+%
25
+% SYNTAX
26
+%
27
+%  sS1 = som_vs2to1(sS2)
28
+%
29
+% DESCRIPTION
30
+%
31
+% This function is offered to allow the change of new map and data structs
32
+% to old ones. There are quite a lot of changes between the versions,
33
+% especially in the map struct, and this function makes it possible to 
34
+% use the old functions with new structs.
35
+%
36
+% Note that part of the information is lost in the conversion. Especially, 
37
+% training history is lost, and the normalization is, except in the simplest
38
+% cases (like all have 'range' or 'var' normalization) screwed up.
39
+%
40
+% REQUIRED INPUT ARGUMENTS
41
+%
42
+%  sS2       (struct) som SOM Toolbox version 2.0 struct (map, data, 
43
+%                     training or normalization struct)
44
+%
45
+% OUTPUT ARGUMENTS
46
+% 
47
+%  sS1       (struct) the corresponding SOM Toolbox version 2.0 struct
48
+%
49
+% EXAMPLES
50
+%
51
+%  sM = som_vs2to1(sMnew);
52
+%  sD = som_vs2to1(sDnew);
53
+%  sT = som_vs2to1(sMnew.trainhist(1));
54
+%
55
+% SEE ALSO
56
+% 
57
+%  som_set          Set values and create SOM Toolbox structs.
58
+%  som_vs1to2       Transform structs from 1.0 version to 2.0.   
59
+
60
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
61
+% http://www.cis.hut.fi/projects/somtoolbox/
62
+
63
+% Version 2.0beta juuso 101199
64
+
65
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
66
+%% check arguments
67
+
68
+error(nargchk(1, 1, nargin));   % check no. of input arguments is correct
69
+
70
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
71
+%% set field values
72
+  
73
+switch sS.type, 
74
+ case 'som_map',
75
+  msize = sS.topol.msize; 
76
+  [munits dim] = size(sS.codebook);
77
+  
78
+  % topology
79
+  if strcmp(sS.topol.shape,'sheet'), shape = 'rect'; 
80
+  else shape = sS.shape; 
81
+  end
82
+  
83
+  % labels
84
+  labels = cell(munits,1);
85
+  nl = size(sS.labels,2);
86
+  for i=1:munits, 
87
+    labels{i} = cell(nl,1);      
88
+    for j=1:nl, labels{i}{j} = sS.labels{i,j}; end
89
+  end
90
+  
91
+  % trainhist 
92
+  tl = length(sS.trainhist); 
93
+  if tl==0 | strcmp(sS.trainhist(1).algorithm,'lininit'), 
94
+    init_type = 'linear';
95
+  else
96
+    init_type = 'random';
97
+  end
98
+  if tl>1, 
99
+    for i=2:tl, 
100
+      train_seq{i-1} = som_vs2to1(sS.trainhist(i));
101
+    end
102
+    train_type = sS.trainhist(tl).algorithm; 
103
+  else
104
+    train_seq = [];
105
+    train_type = 'batch';
106
+  end 
107
+  if tl>0, data_name = sS.trainhist(tl).data_name; else data_name = ''; end
108
+  
109
+  % component normalizations 
110
+  sN = convert_normalizations(sS.comp_norm);   
111
+  if strcmp(sN.name,'som_hist_norm'), 
112
+    sS.codebook = redo_hist_norm(sS.codebook,sS.comp_norm,sN);
113
+  end
114
+  
115
+  % map 
116
+  sSnew = struct('init_type', 'linear', 'train_type', 'batch', 'lattice' ,...
117
+		 'hexa', 'shape', 'rect', 'neigh', 'gaussian', 'msize', msize, ...
118
+		 'train_sequence', [], 'codebook', [], 'labels', [], ...
119
+		 'mask', [], 'data_name', 'unnamed', 'normalization', [], ...
120
+		 'comp_names', [], 'name', 'unnamed');
121
+  sSnew.init_type = init_type;
122
+  sSnew.train_type = train_type;
123
+  sSnew.lattice = sS.topol.lattice;
124
+  sSnew.shape = shape;
125
+  sSnew.neigh = sS.neigh;
126
+  sSnew.msize = sS.topol.msize;
127
+  sSnew.train_sequence = train_seq;
128
+  sSnew.codebook = reshape(sS.codebook,[sS.topol.msize dim]);
129
+  sSnew.labels = labels;
130
+  sSnew.mask = sS.mask;
131
+  sSnew.data_name = data_name;
132
+  sSnew.normalization = sN;
133
+  sSnew.comp_names = sS.comp_names;
134
+  sSnew.name = sS.name;
135
+  
136
+ case 'som_data',
137
+  [dlen dim] = size(sS.data);
138
+  
139
+  % component normalizations
140
+  sN = convert_normalizations(sS.comp_norm); 
141
+  if strcmp(sN.name,'som_hist_norm'), 
142
+    sS.codebook = redo_hist_norm(sS.codebook,sS.comp_norm,sN);
143
+  end
144
+  
145
+  % data
146
+  sSnew = struct('data', [], 'name', '', 'labels' , [], 'comp_names', ...
147
+		 [], 'normalization', []);
148
+  sSnew.data = sS.data;
149
+  sSnew.name = sS.name;
150
+  sSnew.labels = sS.labels;
151
+  sSnew.comp_names = sS.comp_names;
152
+  sSnew.normalization = sN;
153
+  
154
+ case 'som_norm',     
155
+  sSnew = struct('name','som_var_norm','inv_params',[]);
156
+  
157
+  switch sS.method, 
158
+   case 'var',   sSnew.name = 'som_var_norm';
159
+   case 'range', sSnew.name = 'som_lin_norm';
160
+   case 'histD', sSnew.name = 'som_hist_norm';
161
+   otherwise, 
162
+    warning(['Method ' method ' does not exist in version 1.'])
163
+  end
164
+
165
+  if strcmp(sS.status,'done'),   
166
+    switch sS.method, 
167
+     case 'var', 
168
+      sSnew.inv_params = zeros(2,1);
169
+      sSnew.inv_params(1) = sS.params(1);
170
+      sSnew.inv_params(2) = sS.params(2);
171
+     case 'range', 
172
+      sSnew.inv_params = zeros(2,1);
173
+      sSnew.inv_params(1) = sS.params(1);
174
+      sSnew.inv_params(2) = sS.params(2) + sS.params(1);;
175
+     case 'histD',
176
+      bins = length(sS.params);
177
+      sSnew.inv_params = zeros(bins+1,1) + Inf;
178
+      sSnew.inv_params(1:bins,i) = sS.params;
179
+      sSnew.inv_params(end,i) = bins; 
180
+    end
181
+  end
182
+  
183
+ case 'som_train', 
184
+  sSnew = struct('algorithm', sS.algorithm, 'radius_ini', ...
185
+		 sS.radius_ini, 'radius_fin', sS.radius_fin, 'alpha_ini', ...
186
+		 sS.alpha_ini, 'alpha_type', sS.alpha_type, 'trainlen', sS.trainlen, ...
187
+		 'qerror', NaN, 'time', sS.time);
188
+  
189
+ case 'som_topol', 
190
+  disp('Version 1 of SOM Toolbox did not have topology structure.\n');
191
+  
192
+ otherwise, 
193
+  
194
+  error('Unrecognized struct.');
195
+end
196
+
197
+sS = sSnew;
198
+
199
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
200
+%% subfunctions
201
+
202
+function sN = convert_normalizations(cnorm)
203
+
204
+  dim = length(cnorm);
205
+  sN = struct('name','som_var_norm','inv_params',[]);
206
+    
207
+  % check that there is exactly one normalization per component
208
+  % and that their status and method is the same
209
+  ok = 1;
210
+  nof = zeros(dim,1);
211
+  for i=1:dim, nof(i) = length(cnorm{i}); end
212
+  if any(nof>1), ok=0; 
213
+  elseif any(nof==1) & any(nof==0), ok=0;
214
+  elseif any(nof>0), 
215
+    status = cnorm{1}.status;
216
+    method = cnorm{1}.method;
217
+    for i=2:dim, 
218
+      if ~strcmp(cnorm{i}.status,status) | ~strcmp(cnorm{i}.method,method), 
219
+	ok = 0; 
220
+      end
221
+    end    
222
+  elseif all(nof==0), 
223
+    return;
224
+  end
225
+  if ~ok, 
226
+    warning(['Normalization could not be converted. All variables can' ...
227
+	     ' only be normalized with a single, and same, method.']);
228
+    return;
229
+  end  
230
+  
231
+  % method name
232
+  switch method, 
233
+   case 'var', sN.name = 'som_var_norm';
234
+   case 'range', sN.name = 'som_lin_norm';
235
+   case 'histD', sN.name = 'som_hist_norm';
236
+   otherwise, 
237
+    warning(['Normalization could not be converted. Method ' method ...
238
+	     'does not exist in version 1.']);
239
+    return;
240
+  end
241
+
242
+  % if not done, inv_params is empty
243
+  if ~strcmp(status,'done'), return; end  
244
+   
245
+  % ok, make the conversion  
246
+  switch method, 
247
+   case 'var',   
248
+    sN.inv_params = zeros(2,dim);
249
+    for i=1:dim, 
250
+      sN.inv_params(1,i) = cnorm{i}.params(1);
251
+      sN.inv_params(2,i) = cnorm{i}.params(2);
252
+    end
253
+   case 'range',
254
+    sN.inv_params = zeros(2,dim);
255
+    for i=1:dim, 
256
+      sN.inv_params(1,i) = cnorm{i}.params(1);
257
+      sN.inv_params(2,i) = cnorm{i}.params(2) + cnorm{i}.params(1);
258
+    end
259
+   case 'histD',     
260
+    bins = zeros(dim,1); 
261
+    for i=1:dim, bins(i) = length(cnorm{i}.params); end
262
+    m = max(bins); 
263
+    sN.inv_params = zeros(m+1,dim) + Inf;
264
+    for i=1:dim, 
265
+      sN.inv_params(1:bins(i),i) = cnorm{i}.params;
266
+      if bins(i)<m, sN.inv_params(bins(i)+1,i) = NaN; end
267
+      sN.inv_params(end,i) = bins(i); 
268
+    end
269
+  end
270
+
271
+function D = redo_hist_norm(D,cnorm,sN)
272
+
273
+  dim = size(D,2);
274
+
275
+  % first - undo the new way
276
+  for i=1:dim, 
277
+    bins = length(cnorm{i}.params);
278
+    D(:,i) = round(D(:,i)*(bins-1)+1);
279
+    inds = find(~isnan(D(:,i)) & ~isinf(D(:,i)));
280
+    D(inds,i) = cnorm{i}.params(D(inds,i));
281
+  end  
282
+  % then - redo the old way
283
+  n_bins = sN.inv_params(size(sN.inv_params,1),:);
284
+  for j = 1:dim,        
285
+    for i = 1:size(D, 1)
286
+      if ~isnan(D(i, j)),
287
+	[d ind] = min(abs(D(i, j) - sN.inv_params(1:n_bins(j), j)));
288
+	if (D(i, j) - sN.inv_params(ind, j)) > 0 & ind < n_bins(j),
289
+	  D(i, j) = ind + 1;   
290
+	else                   
291
+	  D(i, j) = ind;
292
+	end
293
+      end
294
+    end
295
+  end
296
+  D = D * sparse(diag(1 ./ n_bins));
297
+
298
+
... ...
@@ -0,0 +1,187 @@
1
+function som_write_cod(sMap, filename)
2
+
3
+%SOM_WRITE_COD Writes a map struct to ascii file in SOM_PAK format.
4
+%
5
+% som_write_cod(sMap,filename)
6
+%
7
+%  som_write_cod(sMap,'map1.cod');
8
+%
9
+%  Input and output arguments: 
10
+%   sMap        (struct) self-organizing map structure
11
+%   filename    (string) name of input file
12
+%
13
+% Note that much of the information in the map struct is lost.
14
+% Typically, when saving map structs into files use the 'save' command.
15
+%
16
+% For more help, try 'type som_write_cod' or check out online documentation.
17
+% See also SOM_READ_COD, SOM_READ_DATA, SOM_WRITE_DATA.
18
+
19
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
20
+%
21
+% som_write_cod
22
+%
23
+% PURPOSE
24
+%
25
+% Writes a self-organizing map struct to a file in SOM_PAK format.
26
+%
27
+% SYNTAX
28
+%
29
+%  som_write_cod(sMap,filename); 
30
+%
31
+% DESCRIPTION
32
+%
33
+% This function is offered for compatibility with SOM_PAK, a SOM 
34
+% software package in C. It writes map struct to files in SOM_PAK format.
35
+%
36
+% See SOM_READ_COD for description of the SOM_PAK map file format.
37
+% Because the SOM_PAK package does not support many of the features and
38
+% options of the SOM Toolbox, some of the information is changed, or even
39
+% lost. 
40
+%
41
+% SOM_PAK does not support 3- or higher dimensional map grids. These cannot
42
+%         be exported using this function.  
43
+% SOM_PAK always supposes that the map has 'sheet' shape. 
44
+% SOM_PAK only supports 'bubble' and 'gaussian' neighborhood functions.
45
+%         Any other neighborhood function is changed to 'gaussian'.
46
+% SOM_PAK doesn't support component names. However, the component names are
47
+%         written on a comment line which begins with '#n '. Any spaces (' ') 
48
+%         in the component names are replaced with underscores ('_').      
49
+% Information on map name, mask, training history and normalizations is lost.
50
+%
51
+% This function is only offered for compatibility with SOM_PAK. In general,
52
+% when saving map structs in files, use 'save filename.mat sMap'. This is
53
+% faster and retains all information of the map.
54
+% 
55
+% REQUIRED INPUT ARGUMENTS
56
+%
57
+%  sMap       (struct) the SOM struct to be written
58
+%  filename   (string) the name of the input file
59
+%
60
+% EXAMPLES
61
+%
62
+%  som_write_cod(sMap,'map1.cod');
63
+%
64
+% SEE ALSO
65
+% 
66
+%  som_read_cod     Read a map from a file in SOM_PAK format.
67
+%  som_read_data    Reads data from an ascii file.
68
+%  som_write_data   Writes data struct into a file in SOM_PAK format.
69
+
70
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
71
+% http://www.cis.hut.fi/projects/somtoolbox/
72
+
73
+% Version 1.0beta ecco 221097
74
+% Version 2.0beta ecco 030899, juuso 151199
75
+
76
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
77
+%% check arguments and initialize
78
+
79
+error(nargchk(2, 2, nargin))  % check no. of input args is correct
80
+
81
+% sMap
82
+msize = sMap.topol.msize;           % map grid size
83
+mdim  = length(msize);              % map grid dimension
84
+[munits dim] = size(sMap.codebook); % input space dimension
85
+
86
+% map dimension check:
87
+% map dimensions higher than 2 are not supported by SOM_PAK
88
+if mdim > 2,      
89
+  error('Cannot write maps with higher dimension than two');
90
+end
91
+
92
+% in SOM_PAK the xy-indexing is used, while in Matlab ij-indexing
93
+% therefore, the codebook vectors have to be reorganized 
94
+order = reshape([1:munits],msize);
95
+order = reshape(order',[munits 1]);
96
+msize = fliplr(msize);
97
+
98
+% open output file
99
+fid = fopen(filename, 'w');
100
+if fid < 0,
101
+  error(['Cannot open file ' filename]);
102
+end
103
+
104
+% check version
105
+v = version;
106
+ver_53_or_newer = (str2num(v(1:3)) >= 5.3);
107
+
108
+
109
+[lines numlabs] = size(sMap.labels);
110
+has_labels = zeros(lines, 1);
111
+if ver_53_or_newer
112
+  has_labels = sum((~(cellfun('isempty', sMap.labels))), 2);
113
+else
114
+  for i = 1:lines
115
+    for j = 1:numlabs
116
+      if ~isempty(sMap.labels{i,j}) 
117
+	has_labels(i) = 1; break; 
118
+      end
119
+    end
120
+  end
121
+end
122
+
123
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
124
+%% write map into a file
125
+
126
+% write header
127
+
128
+fprintf(fid, '%d %s ', dim, sMap.topol.lattice); % dimension and lattice
129
+fprintf(fid, '%d ', msize);                      % map size
130
+% neighborhood type ('ep' and 'cutgauss' are not supported by SOM_PAK; 
131
+% they are converted to 'gaussian')
132
+if strcmp(sMap.neigh,'bubble'), fprintf(fid, 'bubble\n');
133
+else 
134
+  if ~strcmp(sMap.neigh,'gaussian'), 
135
+    warning(['Neighborhood type ''' sMap.neigh ''' converted to ''gaussian''']);
136
+  end
137
+  fprintf(fid,'gaussian\n'); 
138
+end
139
+
140
+% write the component names as a SOM_PAK comment line
141
+
142
+fprintf(fid,'#n ');
143
+for i=1:dim, fprintf(fid, '%s ', strrep(sMap.comp_names{i},' ','_')); end
144
+fprintf(fid,'\n');
145
+
146
+% write codebook
147
+
148
+form  = [repmat('%g ',[1 dim]) '\n'];
149
+if ~has_labels  % no labels; fast
150
+  fprintf(fid, form, sMap.codebook(order,:)');
151
+else            % has labels; slow
152
+  for i=1:munits, 
153
+    fprintf(fid, '%g ', sMap.codebook(order(i),:));
154
+
155
+    if has_labels(order(i))
156
+      temp = '';
157
+      if ver_53_or_newer
158
+	nonempty = ~(cellfun('isempty', sMap.labels(i,:)));
159
+      else
160
+	for j = 1:numlabs, nonempty(j) = ~isempty(sMap.labels{i, j}); end
161
+      end
162
+      labs = char(sMap.labels{order(i), nonempty});
163
+      labs(:,end + 1) = ' ';
164
+      temp = reshape(labs',[1 prod(size(labs))]);
165
+      temp(findstr('  ', temp))='';
166
+      fprintf(fid, '%s\n', temp(1:end-1));
167
+    else
168
+      fprintf(fid, '\n');
169
+    end
170
+  end
171
+end
172
+
173
+% close file
174
+
175
+if fclose(fid) 
176
+  error(['Cannot close file ' filename]);
177
+else
178
+  fprintf(2, 'map write ok\n');
179
+end
180
+
181
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
182
+
183
+
184
+
185
+
186
+
187
+
... ...
@@ -0,0 +1,210 @@
1
+function som_write_data(sData, filename, missing)
2
+
3
+%SOM_WRITE_DATA Writes data structs/matrices to a file in SOM_PAK format.
4
+%
5
+% som_write_data(data,filename,[missing])
6
+%
7
+%  som_write_data(sD,'system.data')
8
+%  som_write_data(D,'system.data','*')
9
+%
10
+%  Input and output arguments ([]'s are optional): 
11
+%   data        (struct) data struct to be written in the file
12
+%               (matrix) data matrix
13
+%   filename    (string) output filename
14
+%   [missing]   (string) string used to denote missing components (NaNs); 
15
+%                default is 'NaN'
16
+%
17
+% Note that much of the information in the data struct is lost.
18
+% Typically, when saving data structs into files use the 'save' command.
19
+%
20
+% For more help, try 'type som_write_data' or check out online documentation.
21
+% See also  SOM_READ_DATA, SOM_READ_COD, SOM_WRITE_COD.
22
+
23
+%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
24
+%
25
+% som_write_data
26
+%
27
+% PURPOSE
28
+%
29
+% Writes data structs/matrices to a file in SOM_PAK format.
30
+%
31
+% SYNTAX
32
+%
33
+%  som_write_data(sD,'filename')
34
+%  som_write_data(D,'filename')
35
+%  som_write_data(...,'missing')
36
+%
37
+% DESCRIPTION
38
+%
39
+% This function is offered for compatibility with SOM_PAK, a SOM software
40
+% package in C. It writes data structs/matrices to a file in SOM_PAK format.
41
+%
42
+% See SOM_READ_DATA for a decription of the SOM_PAK data file format. Since
43
+% the format does not support information on normalizations, that
44
+% information is lost, as well as the data name. The component names are
45
+% written on a comment line which begins with '#n' and label names on
46
+% comment line which begins with '#l', respectively. Any spaces (' ') in the
47
+% component names and in the label names are replaced with
48
+% underscores ('_').
49
+%
50
+% This function is only offered for compatibility with SOM_PAK. In
51
+% general, when saving data in files, use 'save filename.mat sData'. This is
52
+% faster and retains all information of the data struct.
53
+%
54
+% The string to use for missing values (NaNs) in the written file can
55
+% be given with the last argument. Notice that if you use SOM_PAK to
56
+% read the files, you need to set the SOM_PAK environment variable
57
+% LVQSOM_MASK_STR accordingly, e.g. to 'NaN' if you use the default
58
+% replacement. For more information, see the SOM_PAK instructions.
59
+%
60
+% REQUIRED INPUT ARGUMENTS
61
+%
62
+%  data        (struct or matrix) data to be written
63
+%  filename    (string) output filename
64
+%
65
+% OPTIONAL INPUT ARGUMENTS
66
+%
67
+%  missing     (string) string used to denote missing components (NaNs); 
68
+%               default is 'NaN'
69
+%
70
+% EXAMPLES
71
+%
72
+% The basic usage is:
73
+%  som_write_data(sData,'system.data')
74
+%
75
+% To write a data matrix to a file in plain SOM_PAK format, give a
76
+% data matrix as the first argument: 
77
+%  som_write_data(D,'system.data')
78
+%
79
+% By default, all NaNs in the data matrix are written as 'NaN':s. The
80
+% third argument can be used to change this:
81
+%  som_write_data(sData,'system.data','+')
82
+%  som_write_data(sData,'system.data','missing')
83
+%
84
+% SEE ALSO
85
+%
86
+%  som_read_data    Reads data from an ascii file.
87
+%  som_read_cod     Read a map from a file in SOM_PAK format.
88
+%  som_write_cod    Writes data struct into a file in SOM_PAK format.
89
+
90
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
91
+% http://www.cis.hut.fi/projects/somtoolbox/
92
+
93
+% Version 1.0beta ecco 131197
94
+% Version 2.0beta ecco 030899 juuso 151199
95
+
96
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
97
+%% check arguments
98
+
99
+error(nargchk(2, 3, nargin));  % check no. of input args is correct
100
+
101
+% data
102
+if isstruct(sData)
103
+  is_struct = 1;
104
+  D = sData.data;
105
+else 
106
+  is_struct = 0;
107
+  D = sData; 
108
+end
109
+[samples dim] = size(D);
110
+
111
+% missing
112
+if nargin == 2, missing = 'NaN'; end
113
+
114
+% open output file
115
+fid = fopen(filename, 'w');
116
+if fid < 0, error(['Cannot open file ' filename]); end
117
+
118
+% check version
119
+v = version;
120
+ver_53_or_newer = (str2num(v(1:3)) >= 5.3);
121
+
122
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
123
+%% write data
124
+
125
+% write dimension
126
+
127
+fprintf(fid, '%d\n', dim);
128
+
129
+% write component names as a SOM_PAK comment line
130
+if is_struct,
131
+  fprintf(fid,'#n ');                     
132
+  for i = 1:dim, fprintf(fid, '%s ', strrep(sData.comp_names{i},' ','_')); end
133
+  fprintf(fid,'\n');                      
134
+  if ~isempty(sData.label_names)
135
+    fprintf(fid,'#l ');                     
136
+    l = length(sData.label_names);
137
+    for i = 1:l,  fprintf(fid, '%s ', strrep(sData.label_names{i},' ','_')); end
138
+    fprintf(fid,'\n');                      
139
+  end
140
+end
141
+
142
+% are there NaNs and/or labels?
143
+
144
+has_nans = isnan(sum(D,2)) * (~strcmp(missing, 'NaN'));
145
+
146
+has_labels = 0;
147
+if is_struct
148
+  [lines numlabs] = size(sData.labels);
149
+  has_labels = zeros(lines, 1);
150
+  if ver_53_or_newer
151
+    has_labels = sum((~(cellfun('isempty', sData.labels))), 2);
152
+  else
153
+    for i = 1:lines
154
+      for j = 1:numlabs
155
+	if ~isempty(sData.labels{i,j}) 
156
+	  has_labels(i) = 1; break; 
157
+	end
158
+      end
159
+    end
160
+  end
161
+end
162
+
163
+% write data
164
+
165
+form = [repmat('%g ',[1 dim-1]) '%g\n'];
166
+
167
+if ~sum(has_labels) & ~sum(has_nans)    % no NaNs, no labels
168
+  fprintf(fid, form, D'); 
169
+elseif ~sum(has_labels)                 % no labels, NaNs
170
+  fprintf(fid, '%s', strrep(sprintf(form, D'), 'NaN', missing));
171
+else                                    % labels and NaNs
172
+  for i = 1:samples
173
+    if has_nans(i)
174
+      fprintf(fid, strrep(sprintf('%g ', D(i,:)), 'NaN', missing));
175
+    else
176
+      fprintf(fid, '%g ', D(i,:));
177
+    end
178
+    
179
+    if has_labels(i)
180
+      temp = '';
181
+      if ver_53_or_newer
182
+	nonempty = ~(cellfun('isempty', sData.labels(i,:)));
183
+      else
184
+	for j = 1:numlabs, nonempty(j) = ~isempty(sData.labels{i, j}); end
185
+      end
186
+      labs = char(sData.labels{i, nonempty});
187
+      labs(:,end + 1) = ' ';
188
+      temp = reshape(labs',[1 prod(size(labs))]);
189
+      temp(findstr('  ', temp))='';
190
+      fprintf(fid, '%s', temp(1:end-1));
191
+    end
192
+    fprintf(fid,'\n');
193
+  end
194
+end
195
+
196
+% close file
197
+
198
+if fclose(fid), 
199
+  error(['Cannot close file ' filename]); 
200
+else
201
+  fprintf(2, 'data write ok\n');
202
+end
203
+
204
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
205
+
206
+
207
+
208
+
209
+
210
+
... ...
@@ -0,0 +1,69 @@
1
+function sompak_gui()
2
+
3
+%SOMPAK_GUI  A GUI for using SOM_PAK functions from Matlab.
4
+%
5
+%  sompak_gui
6
+%
7
+% Launches a GUI which allows the use of SOM_PAK functions from
8
+% Matlab. Notice that to use this function, the SOM_PAK programs must
9
+% be in your search path, or the variable 'SOM_PAKDIR' which is a
10
+% string containing the program path, must be defined in the
11
+% workspace. SOM_PAK programs can be found from:
12
+% http://www.cis.hut.fi/research/som_lvq_pak.shtml
13
+%  
14
+% See also SOM_GUI, SOMPAK_INIT_GUI, SOMPAK_SAMMON_GUI, SOMPAK_TRAIN_GUI.
15
+
16
+% Contributed to SOM Toolbox 2.0, February 2nd, 2000 by Juha Parhankangas
17
+% Copyright (c) by Juha Parhankangas
18
+% http://www.cis.hut.fi/projects/somtoolbox/
19
+
20
+% Juha Parhankangas 050100
21
+
22
+h=findobj(get(0,'Children'),'Tag','sompak_gui');
23
+if ~isempty(h)
24
+  figure(h);
25
+  return;
26
+end
27
+
28
+a = figure('Color',[0.8 0.8 0.8], ...
29
+	'PaperType','a4letter', ...
30
+	'Position',[689 536 210 70], ...
31
+	'Tag','sompak_gui');
32
+b = uicontrol('Parent',a, ...
33
+	'Units','points', ...
34
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
35
+        'Callback','sompak_init_gui',...
36
+	'FontWeight','demi', ...
37
+	'Position',[8 30 50 20], ...
38
+	'String','INIT', ...
39
+	'Tag','Pushbutton1');
40
+b = uicontrol('Parent',a, ...
41
+	'Units','points', ...
42
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
43
+        'Callback','sompak_train_gui',...
44
+	'FontWeight','demi', ...
45
+	'Position',[63 30 50 20], ...
46
+	'String','TRAIN', ...
47
+	'Tag','Pushbutton2');
48
+b = uicontrol('Parent',a, ...
49
+	'Units','points', ...
50
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
51
+        'Callback','sompak_sammon_gui',...
52
+	'FontWeight','demi', ...
53
+	'Position',[118 30 50 20], ...
54
+	'String','SAMMON', ...
55
+	'Tag','Pushbutton3');
56
+b = uicontrol('Parent',a, ...
57
+	'Units','points', ...
58
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
59
+	'Callback','close gcf', ...
60
+	'FontSize',9, ...
61
+	'FontWeight','demi', ...
62
+	'Position',[128 5 40 15], ...
63
+	'String','Close', ...
64
+	'Tag','Pushbutton4');
65
+
66
+
67
+
68
+
69
+
... ...
@@ -0,0 +1,211 @@
1
+function sMap=sompak_init(sData,ft,init_type,cout,ct,xdim,ydim,topol,neigh)
2
+
3
+%SOMPAK_INIT Call SOM_PAK initialization programs from Matlab.
4
+%
5
+% sMap=sompak_init(sData,ft,init_type,cout,ct,xdim,ydim,topol,neigh)
6
+%
7
+% ARGUMENTS  ([]'s are optional and can be given as empty: [] or '')
8
+%  sData      (struct) data struct
9
+%             (matrix) data matrix
10
+%             (string) filename
11
+%  [ft]       (string) 'pak' or 'box'. Argument must be defined, if input
12
+%                      file is used.
13
+%  init_type  (string) string 'rand' or 'linear'
14
+%  [cout]     (string) filename for output SOM, if argument is not defined
15
+%                      (i.e. argument is '[]') temporary file '__abcdef' is
16
+%                      used in operations and *it_is_removed* after 
17
+%                      operations!!!
18
+%  [ct]       (string) 'pak' or 'box'. Argument must be defined, if output
19
+%                      file is used.
20
+%  xdim       (scalar) Number of units of the map in x-direction.
21
+%  ydim       (scalar) Number of units of the map in y-direction.
22
+%  topol      (string) string 'hexa' or 'rect'
23
+%  neigh      (string) string 'bubble' or 'gaussian'.
24
+%
25
+% RETURNS
26
+%  sMap       (struct) map struct
27
+%
28
+% Calls SOM_PAK initialization programs (randinit and lininit) from
29
+% Matlab. Notice that to use this function, the SOM_PAK programs must
30
+% be in your search path, or the variable 'SOM_PAKDIR' which is a
31
+% string containing the program path, must be defined in the
32
+% workspace. SOM_PAK programs can be found from:
33
+% http://www.cis.hut.fi/research/som_lvq_pak.shtml
34
+%  
35
+% See also SOMPAK_TRAIN, SOMPAK_SAMMON, SOMPAK_INIT_GUI,
36
+%          SOMPAK_GUI, SOM_LININIT, SOM_RANDINIT.
37
+
38
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Parhankangas
39
+% Copyright (c) by Juha Parhankangas
40
+% http://www.cis.hut.fi/projects/somtoolbox/
41
+
42
+% Juha Parhankangas 050100
43
+
44
+nargchk(9,9,nargin);
45
+
46
+NO_FILE = 0;
47
+if isstruct(sData);
48
+  sData=sData.data;
49
+elseif ~(isreal(sData) | isstr(sData))
50
+  error('Argument ''sData'' must be a struct or a real matrix.');
51
+else
52
+  if isempty(ft)
53
+    if isstr(sData)
54
+      error('Argument ''file_type'' must be defined when input file is used.');
55
+    end
56
+  elseif strcmp(ft,'pak');
57
+    sData=som_read_data(sData);
58
+  elseif strcmp(ft,'box')
59
+    new_var=diff_varname;
60
+    varnames=evalin('base','who');
61
+    loadname=eval(cat(2,'who(''-file'',''',sData,''')'));
62
+    if any(strcmp(loadname{1},evalin('base','who')))
63
+      assignin('base',new_var,evalin('base',loadname{1}));
64
+      evalin('base',cat(2,'load(''',sData,''');'));
65
+      new_var2=diff_varname;
66
+
67
+      assignin('base',new_var2,evalin('base',loadname{1}));
68
+      assignin('base',loadname{1},evalin('base',new_var));
69
+      evalin('base',cat(2,'clear ',new_var));
70
+      sData=evalin('base',new_var2);
71
+      evalin('base',cat(2,'clear ',new_var2));
72
+    else
73
+      evalin('base',cat(2,'load(''',sData,''');'));
74
+      sData=evalin('base',loadname{1});
75
+      evalin('base',cat(2,'clear ',loadname{1}));
76
+    end              
77
+  else
78
+    error('Argument ''ft'' must be a string ''pak'' or ''box''.');
79
+  end
80
+end
81
+if isstr(init_type)
82
+  if strcmp(init_type,'rand')
83
+    if any(strcmp('SOM_PAKDIR',evalin('base','who')))
84
+      init_command=cat(2,evalin('base','SOM_PAKDIR'),'randinit');
85
+    else
86
+      init_command='randinit';
87
+    end
88
+  elseif strcmp(init_type,'linear')
89
+    if any(strcmp('SOM_PAKDIR',evalin('base','who')))
90
+      init_command=cat(2,evalin('base','SOM_PAKDIR'),'lininit');
91
+    else
92
+      init_command='lininit';
93
+    end
94
+  else
95
+    error('Argument ''init_type'' must be string ''rand'' or ''linear''.');
96
+  end
97
+else
98
+  error('Argument ''init_type'' must be string ''rand'' or ''linear''.');
99
+end
100
+
101
+if (isstr(cout) & isempty(cout)) | (~isstr(cout) & isempty(cout))
102
+  NO_FILE = 1;
103
+  cout = '__abcdef';
104
+elseif  ~isstr(cout) & ~isempty(cout)
105
+  error('Argument ''cout'' must be a string or ''[]''.');
106
+end
107
+  
108
+if ~is_positive_integer(xdim)
109
+  error('Argument ''xdim'' must be a positive integer.');
110
+end
111
+
112
+if ~is_positive_integer(ydim)
113
+  error('Argument ''ydim'' must be a positive integer.');
114
+end
115
+
116
+if isstr(topol)
117
+  if isempty(topol) | (~strcmp(topol,'hexa') & ~strcmp(topol,'rect'))
118
+    error ('Argument ''topol'' must be either a string ''hexa'' or ''rect''.');
119
+  end
120
+else
121
+  error ('Argument ''topol'' must be either a string ''hexa'' or ''rect''.');  
122
+end
123
+
124
+if isstr(neigh)
125
+  if isempty(neigh) | (~strcmp(neigh,'bubble') & ~strcmp(neigh,'gaussian'))
126
+    error(sprintf(cat(2,'Argument ''neigh'' must be either a string ',...
127
+                        '''bubble'' or ''gaussian''.')));
128
+  end
129
+else
130
+  error(sprintf(cat(2,'Argument ''neigh'' must be either a string ',...
131
+                       '''bubble'' or ''gaussian''.')));
132
+end
133
+
134
+som_write_data(sData, cout); 
135
+str=cat(2,init_command,sprintf(' -din %s -cout %s ', cout ,cout),...
136
+           sprintf('-topol %s ',topol),...
137
+           sprintf('-neigh %s ',neigh),...
138
+           sprintf('-xdim %d -ydim %d',xdim,ydim));
139
+
140
+if isunix
141
+  unix(str);
142
+else
143
+  dos(str);
144
+end
145
+
146
+sMap=som_read_cod(cout);
147
+
148
+if ~NO_FILE
149
+    if isunix
150
+      unix(cat(2,'/bin/rm ',cout));
151
+    else
152
+      dos(cat(2,'del ',cout));
153
+    end
154
+    if strcmp(ct,'pak')
155
+      som_write_cod(sMap,cout);
156
+      disp(cat(2,'Output written to the file ',cout,'.'));
157
+    elseif strcmp(ct,'box')
158
+      eval(cat(2,'save ',cout,' sMap'));	
159
+      disp(cat(2,'Output written to the file ',sprintf('''%s.mat''.',cout)));
160
+    end
161
+else
162
+  sMap.name=cat(2,'SOM ',date);
163
+  if isunix	
164
+    unix('/bin/rm __abcdef');
165
+  else
166
+    dos('del __abcdef');
167
+  end
168
+end
169
+
170
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
171
+
172
+function bool = is_positive_integer(x)
173
+
174
+bool = ~isempty(x) & isreal(x) & all(size(x) == 1) & x > 0;
175
+if ~isempty(bool)
176
+  if bool & x~=round(x)
177
+    bool = 0;
178
+  end
179
+else
180
+  bool = 0;
181
+end
182
+
183
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
184
+
185
+function str = diff_varname();
186
+
187
+array=evalin('base','who');
188
+
189
+if isempty(array)
190
+  str='a';
191
+  return;
192
+end
193
+
194
+for i=1:length(array)
195
+  lens(i)=length(array{i});
196
+end
197
+
198
+
199
+ind=max(lens);
200
+
201
+str(1:ind+1)='a';
202
+
203
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
204
+
205
+
206
+
207
+
208
+
209
+
210
+
211
+
... ...
@@ -0,0 +1,369 @@
1
+function sompak_init_gui()
2
+
3
+%SOMPAK_INIT_GUI A GUI for using SOM_PAK initialization programs from Matlab.
4
+%
5
+%  sompak_init_gui
6
+%
7
+% Launches a GUI which allows the use of SOM_PAK initialization
8
+% programs (randinit and lininit) from Matlab. Notice that to use this
9
+% function, the SOM_PAK programs must be in your search path, or the
10
+% variable 'SOM_PAKDIR' which is a string containing the program path,
11
+% must be defined in the workspace. SOM_PAK programs can be found
12
+% from: http://www.cis.hut.fi/research/som_lvq_pak.shtml
13
+%  
14
+% See also SOMPAK_INIT, SOMPAK_GUI, SOMPAK_SAMMON_GUI,
15
+%          SOMPAK_TRAIN_GUI, SOM_GUI.
16
+
17
+% Contributed to SOM Toolbox vs2, February 2nd, 2000
18
+% Copyright (c) by Juha Parhankangas
19
+% http://www.cis.hut.fi/projects/somtoolbox/
20
+
21
+% Juha Parhankangas 050100
22
+
23
+h=findobj(get(0,'Children'),'Tag','InitGUI');
24
+
25
+if ~isempty(h)
26
+  figure(h);
27
+  return;
28
+end
29
+
30
+a = figure('Color',[0.8 0.8 0.8], ...
31
+	'PaperType','a4letter', ...
32
+	'Position',[483 407 172 440], ...
33
+	'Tag','InitGUI');
34
+b = uicontrol('Parent',a, ...
35
+	'Units','points', ...
36
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
37
+        'Callback','close gcf',...
38
+	'FontWeight','demi', ...
39
+	'Position',[8 20 50 20], ...
40
+	'String','CLOSE', ...
41
+	'Tag','Pushbutton1');
42
+b = uicontrol('Parent',a, ...
43
+	'Units','points', ...
44
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
45
+	'Callback','sompak_rb_control init_ok', ...
46
+	'FontWeight','demi', ...
47
+	'Position',[86 20 50 20], ...
48
+	'String','OK', ...
49
+	'Tag','Pushbutton2');
50
+b = uicontrol('Parent',a, ...
51
+	'Units','points', ...
52
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
53
+	'Position',[8 50 130 300], ...
54
+	'Style','frame', ...
55
+	'Tag','Frame1');
56
+b = uicontrol('Parent',a, ...
57
+	'Units','points', ...
58
+	'BackgroundColor',[0.8 0.8 0.8], ...
59
+	'Position',[12 54 122 40], ...
60
+	'Style','frame', ...
61
+	'Tag','Frame2');
62
+b = uicontrol('Parent',a, ...
63
+	'Units','points', ...
64
+	'BackgroundColor',[0.8 0.8 0.8], ...
65
+	'FontWeight','demi', ...
66
+	'Position',[45.5 78 55 12], ...
67
+	'String','INIT TYPE', ...
68
+	'Style','text', ...
69
+	'Tag','StaticText1');
70
+b = uicontrol('Parent',a, ...
71
+	'Callback','sompak_rb_control linear',...
72
+	'Units','points', ...
73
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
74
+	'Position',[14 56 17 16], ...
75
+	'Style','radiobutton', ...
76
+	'Tag','LINEAR', ...
77
+	'Value',1);
78
+
79
+udata.inittype = 'linear';
80
+
81
+b = uicontrol('Parent',a, ...
82
+	'Callback','sompak_rb_control rand',...
83
+	'Units','points', ...
84
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
85
+	'Position',[73 56 17 16], ...
86
+	'Style','radiobutton', ...
87
+	'Tag','RANDOM');
88
+b = uicontrol('Parent',a, ...
89
+	'Units','points', ...
90
+	'BackgroundColor',[0.8 0.8 0.8], ...
91
+	'FontWeight','demi', ...
92
+	'HorizontalAlignment','left', ...
93
+	'Position',[33 58 30 12], ...
94
+	'String','Linear', ...
95
+	'Style','text', ...
96
+	'Tag','StaticText2');
97
+b = uicontrol('Parent',a, ...
98
+	'Units','points', ...
99
+	'BackgroundColor',[0.8 0.8 0.8], ...
100
+	'FontWeight','demi', ...
101
+	'HorizontalAlignment','left', ...
102
+	'Position',[91 58 37 12], ...
103
+	'String','Random', ...
104
+	'Style','text', ...
105
+	'Tag','StaticText3');
106
+b = uicontrol('Parent',a, ...
107
+	'Units','points', ...
108
+	'BackgroundColor',[0.8 0.8 0.8], ...
109
+	'Position',[12 96 122 40], ...
110
+	'Style','frame', ...
111
+	'Tag','Frame3');
112
+b = uicontrol('Parent',a, ...
113
+	'Units','points', ...
114
+	'BackgroundColor',[0.8 0.8 0.8], ...
115
+	'FontWeight','demi', ...
116
+	'Position',[36.4235 118.588 74 12], ...
117
+	'String','NEIGHBORHOOD', ...
118
+	'Style','text', ...
119
+	'Tag','StaticText4');
120
+b = uicontrol('Parent',a, ...
121
+	'Callback','sompak_rb_control bubble',...
122
+	'Units','points', ...
123
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
124
+	'Position',[14 98 17 16], ...
125
+	'Style','radiobutton', ...
126
+	'Tag','BUBBLE', ...
127
+	'Value',1);
128
+
129
+udata.neigh='bubble';
130
+
131
+b = uicontrol('Parent',a, ...
132
+	'Callback','sompak_rb_control gaussian',...
133
+	'Units','points', ...
134
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
135
+	'Position',[73 98 17 16], ...
136
+	'Style','radiobutton', ...
137
+	'Tag','GAUSSIAN');
138
+b = uicontrol('Parent',a, ...
139
+	'Units','points', ...
140
+	'BackgroundColor',[0.8 0.8 0.8], ...
141
+	'FontWeight','demi', ...
142
+	'HorizontalAlignment','left', ...
143
+	'Position',[33 100 32 12], ...
144
+	'String','Bubble', ...
145
+	'Style','text', ...
146
+	'Tag','StaticText5');
147
+b = uicontrol('Parent',a, ...
148
+	'Units','points', ...
149
+	'BackgroundColor',[0.8 0.8 0.8], ...
150
+	'FontWeight','demi', ...
151
+	'HorizontalAlignment','left', ...
152
+	'Position',[89.5 100 43 12], ...
153
+	'String','Gaussian', ...
154
+	'Style','text', ...
155
+	'Tag','StaticText6');
156
+b = uicontrol('Parent',a, ...
157
+	'Units','points', ...
158
+	'BackgroundColor',[0.8 0.8 0.8], ...
159
+	'Position',[12 138 122 40], ...
160
+	'Style','frame', ...
161
+	'Tag','Frame4');
162
+b = uicontrol('Parent',a, ...
163
+	'Units','points', ...
164
+	'BackgroundColor',[0.8 0.8 0.8], ...
165
+	'FontWeight','demi', ...
166
+	'Position',[45 162 55 12], ...
167
+	'String','TOPOLOGY', ...
168
+	'Style','text', ...
169
+	'Tag','StaticText7');
170
+b = uicontrol('Parent',a, ...
171
+	'Callback','sompak_rb_control hexa',...
172
+	'Units','points', ...
173
+	'Position',[14 140 17 16], ...
174
+	'Style','radiobutton', ...
175
+	'Tag','HEXA', ...
176
+	'Value',1);
177
+
178
+udata.topol='hexa';
179
+
180
+b = uicontrol('Parent',a, ...
181
+	'Callback','sompak_rb_control rect',...
182
+	'Units','points', ...
183
+	'Position',[73 140 17 16], ...
184
+	'Style','radiobutton', ...
185
+	'Tag','RECT');
186
+b = uicontrol('Parent',a, ...
187
+	'Units','points', ...
188
+	'BackgroundColor',[0.8 0.8 0.8], ...
189
+	'FontWeight','demi', ...
190
+	'HorizontalAlignment','left', ...
191
+	'Position',[33 142 30 12], ...
192
+	'String','Hexa', ...
193
+	'Style','text', ...
194
+	'Tag','StaticText8');
195
+b = uicontrol('Parent',a, ...
196
+	'Units','points', ...
197
+	'BackgroundColor',[0.8 0.8 0.8], ...
198
+	'FontWeight','demi', ...
199
+	'HorizontalAlignment','left', ...
200
+	'Position',[90 142 30 12], ...
201
+	'String','Rect', ...
202
+	'Style','text', ...
203
+	'Tag','StaticText9');
204
+b = uicontrol('Parent',a, ...
205
+	'Units','points', ...
206
+	'BackgroundColor',[0.8 0.8 0.8], ...
207
+	'Position',[12 180 122 40], ...
208
+	'Style','frame', ...
209
+	'Tag','Frame5');
210
+b = uicontrol('Parent',a, ...
211
+	'Units','points', ...
212
+	'BackgroundColor',[0.8 0.8 0.8], ...
213
+	'FontWeight','demi', ...
214
+	'HorizontalAlignment','left', ...
215
+	'Position',[25 202 33 12], ...
216
+	'String','X-dim', ...
217
+	'Style','text', ...
218
+	'Tag','StaticText10');
219
+b = uicontrol('Parent',a, ...
220
+	'Units','points', ...
221
+	'BackgroundColor',[0.8 0.8 0.8], ...
222
+	'FontWeight','demi', ...
223
+	'HorizontalAlignment','left', ...
224
+	'Position',[89 202 33 12], ...
225
+	'String','Y-dim', ...
226
+	'Style','text', ...
227
+	'Tag','StaticText11');
228
+b = uicontrol('Parent',a, ...
229
+	'Units','points', ...
230
+	'BackgroundColor',[1 1 1], ...
231
+	'Callback','sompak_rb_control xdim',...
232
+	'Position',[20 183 40 20], ...
233
+	'Style','edit', ...
234
+	'Tag','XDIM');
235
+b = uicontrol('Parent',a, ...
236
+	'Units','points', ...
237
+	'BackgroundColor',[1 1 1], ...
238
+	'Callback','sompak_rb_control ydim',...
239
+	'Position',[85 183 40 20], ...
240
+	'Style','edit', ...
241
+	'Tag','YDIM');
242
+
243
+udata.xdim=[];
244
+udata.ydim=[];
245
+
246
+b = uicontrol('Parent',a, ...
247
+	'Units','points', ...
248
+	'BackgroundColor',[0.8 0.8 0.8], ...
249
+	'Position',[12 222 122 40], ...
250
+	'Style','frame', ...
251
+	'Tag','Frame6');
252
+b = uicontrol('Parent',a, ...
253
+	'Units','points', ...
254
+	'BackgroundColor',[0.8 0.8 0.8], ...
255
+	'FontWeight','demi', ...
256
+	'Position',[25 245 95 12], ...
257
+	'String','OUTPUT VARIABLE', ...
258
+	'Style','text', ...
259
+	'Tag','StaticText12');
260
+b = uicontrol('Parent',a, ...
261
+	'Units','points', ...
262
+	'BackgroundColor',[1 1 1], ...
263
+        'Callback','sompak_rb_control out_var',...
264
+	'Position',[22 226 102 20], ...
265
+	'String','''ans''', ...
266
+	'Style','edit', ...
267
+	'Tag','OUT_VAR');
268
+
269
+udata.out_var='ans';
270
+
271
+b = uicontrol('Parent',a, ...
272
+	'Units','points', ...
273
+	'BackgroundColor',[0.8 0.8 0.8], ...
274
+	'Position',[12 264 122 40], ...
275
+	'Style','frame', ...
276
+	'Tag','Frame7');
277
+b = uicontrol('Parent',a, ...
278
+	'Units','points', ...
279
+	'BackgroundColor',[1 1 1], ...
280
+        'Callback','sompak_rb_control out_file',...
281
+	'Position',[15 267 50 20], ...
282
+	'Style','edit', ...
283
+	'Tag','OUT_FILE');
284
+
285
+udata.out_file=[];
286
+
287
+b = uicontrol('Parent',a, ...
288
+	'Units','points', ...
289
+	'BackgroundColor',[0.8 0.8 0.8], ...
290
+	'FontWeight','demi', ...
291
+	'HorizontalAlignment','left', ...
292
+	'Position',[40 288 60 12], ...
293
+	'String','OUTPUT FILE', ...
294
+	'Style','text', ...
295
+	'Tag','StaticText13');
296
+b = uicontrol('Parent',a, ...
297
+	'Units','points', ...
298
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
299
+	'Callback','sompak_rb_control out_ft',...
300
+	'FontSize',9, ...
301
+	'FontWeight','demi', ...
302
+	'HorizontalAlignment','left', ...
303
+	'Max',3, ...
304
+	'Min',1, ...
305
+	'Position',[70 272 62 15], ...
306
+	'String',{'No File';'mat-file';'cod-file'}, ...
307
+	'Style','popupmenu', ...
308
+	'Tag','OUT_FILE_TYPE', ...
309
+	'Value',1);
310
+
311
+udata.out_file_type='';
312
+
313
+b = uicontrol('Parent',a, ...
314
+	'Units','points', ...
315
+	'BackgroundColor',[0.8 0.8 0.8], ...
316
+	'Position',[12 306 122 40], ...
317
+	'Style','frame', ...
318
+	'Tag','Frame8');
319
+b = uicontrol('Parent',a, ...
320
+	'Units','points', ...
321
+	'BackgroundColor',[0.8 0.8 0.8], ...
322
+	'FontWeight','demi', ...
323
+	'HorizontalAlignment','left', ...
324
+	'Position',[57 330 30 12], ...
325
+	'String','DATA', ...
326
+	'Style','text', ...
327
+	'Tag','StaticText14');
328
+b = uicontrol('Parent',a, ...
329
+	'Units','points', ...
330
+	'BackgroundColor',[1 1 1], ...
331
+	'Callback','sompak_rb_control data',...
332
+	'Position',[15 309 50 20], ...
333
+	'Style','edit', ...
334
+	'Tag','DATA');
335
+
336
+udata.data=[];
337
+
338
+b = uicontrol('Parent',a, ...
339
+	'Units','points', ...
340
+	'Callback','sompak_rb_control input_ft',...
341
+	'FontSize',9, ...
342
+	'FontWeight','demi', ...
343
+	'HorizontalAlignment','left', ...
344
+	'Max',3, ...
345
+	'Min',1, ...
346
+	'Position',[70 314 62 15], ...
347
+	'String',{'Variable';'mat-file';'dat-file'}, ...
348
+	'Style','popupmenu', ...
349
+	'Tag','INPUT_FILE_TYPE', ...
350
+	'Value',1);
351
+udata.input_file_type='';
352
+
353
+b = uicontrol('Parent',a, ...
354
+	'Units','points', ...
355
+	'BackgroundColor',[0.8 0.8 0.8], ...
356
+	'FontSize',12, ...
357
+	'FontWeight','bold', ...
358
+	'HorizontalAlignment','left', ...
359
+	'Position',[57 355 30 12], ...
360
+	'String','INIT', ...
361
+	'Style','text', ...
362
+	'Tag','StaticText15');
363
+
364
+set(gcf,'UserData',udata);
365
+
366
+
367
+
368
+
369
+
... ...
@@ -0,0 +1,252 @@
1
+function varargout=sompak_rb_control(str)
2
+
3
+%SOMPAK_RB_CONTROL  An auxiliary function for SOMPAK_*_GUI functions.
4
+%
5
+% This is an auxiliary function for SOMPAK_GUI, SOMPAK_INIT_GUI, 
6
+% SOMPAK_SAMMON_GUI and SOMPAK_TRAIN_GUI functions. It controls the 
7
+% radio buttons in the GUIs.
8
+%  
9
+% See also SOMPAK_GUI, SOMPAK_INIT_GUI, SOMPAK_SAMMON_GUI, SOMPAK_TRAIN_GUI.
10
+
11
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Parhankangas
12
+% Copyright (c) by Juha Parhankangas
13
+% http://www.cis.hut.fi/projects/somtoolbox/
14
+
15
+% Juha Parhankangas 050100
16
+
17
+data=get(gcf,'UserData');
18
+switch str
19
+  case {'rand','linear'}
20
+   h=cat(2,findobj(get(gcf,'Children'),'Tag','RANDOM'),...
21
+	   findobj(get(gcf,'Children'),'Tag','LINEAR'));
22
+   set(h,'Value',0);
23
+   set(gcbo,'Value',1);
24
+   data.inittype=str;
25
+  case {'bubble','gaussian'}
26
+   h=cat(2,findobj(get(gcf,'Children'),'Tag','BUBBLE'),...
27
+           findobj(get(gcf,'Children'),'Tag','GAUSSIAN'));
28
+   set(h,'Value',0);
29
+   set(gcbo,'Value',1);
30
+   data.neigh=str;
31
+  case {'hexa','rect'}
32
+   h=cat(2,findobj(get(gcf,'Children'),'Tag','HEXA'),...
33
+           findobj(get(gcf,'Children'),'Tag','RECT'));
34
+   set(h,'Value',0);
35
+   set(gcbo,'Value',1);
36
+   data.topol=str;
37
+  case {'out_ft'}
38
+   value=get(gcbo,'Value');
39
+   switch value
40
+     case 1
41
+      h=findobj(get(gcf,'Children'),'Tag','OUT_FILE');
42
+      data.out_file_type='';
43
+      set(h,'String','');
44
+     case 2
45
+      data.out_file_type='box';
46
+     case 3
47
+      data.out_file_type='pak';
48
+   end
49
+  case {'input_ft'}
50
+   value=get(gcbo,'Value');
51
+   switch value
52
+     case 1
53
+      data.input_file_type='';
54
+     case 2
55
+      data.input_file_type='box';
56
+     case 3
57
+      data.input_file_type='pak';
58
+   end
59
+  case {'map_ft'}
60
+   value=get(gcbo,'Value');
61
+   switch value
62
+     case 1
63
+      data.map_type='';
64
+     case 2
65
+      data.map_type='box';
66
+     case 3
67
+      data.map_type='pak';
68
+   end
69
+  case {'out_file'}
70
+   if isempty(data.out_file_type)
71
+     data.out_file='';
72
+     h=findobj(get(gcf,'Children'),'Tag','OUT_FILE');
73
+     set(h,'String','');
74
+   else
75
+     data.out_file=get(findobj(get(gcf,'Children'),'Tag','OUT_FILE'),'String');
76
+     if isempty(data.out_file)
77
+       h=findobj(get(gcf,'Children'),'Tag','OUT_FILE_TYPE');
78
+       set(h,'Value',1);
79
+     end
80
+   end
81
+
82
+  case {'out_var'}
83
+   h=findobj(get(gcf,'Children'),'Tag','OUT_VAR');
84
+   if ~isempty(get(h,'String'))
85
+     data.out_var=get(h,'String');
86
+   else
87
+     data.out_var=[];
88
+     set(h,'String','''ans''');
89
+   end
90
+  case {'xdim'}
91
+   h=findobj(get(gcf,'Children'),'Tag','XDIM');
92
+   data.xdim=str2num(get(h,'String'));
93
+  case {'ydim'}
94
+   h=findobj(get(gcf,'Children'),'Tag','YDIM');
95
+   data.ydim=str2num(get(h,'String'));
96
+  case {'radius'}
97
+   h=findobj(get(gcf,'Children'),'Tag','RADIUS');
98
+   data.radius=str2num(get(h,'String'));
99
+  case {'data'}
100
+   h=findobj(get(gcf,'Children'),'Tag','DATA');
101
+   data.data=get(h,'String');
102
+  case {'rlen'}
103
+   h=findobj(get(gcf,'Children'),'Tag','RLEN');
104
+   data.rlen=str2num(get(h,'String'));
105
+  case {'alpha'}
106
+   h=findobj(get(gcf,'Children'),'Tag','ALPHA');
107
+   data.alpha=str2num(get(h,'String'));
108
+  case {'map'}
109
+   h=findobj(get(gcf,'Children'),'Tag','MAP');
110
+   data.map=get(h,'String');
111
+  case 'init_ok'
112
+   if isempty(data.xdim) | ~is_positive_integer(data.xdim)
113
+     errordlg('Argument ''xdim'' must be positive integer.');
114
+     return;
115
+   end
116
+   if isempty(data.ydim) | ~is_positive_integer(data.ydim)
117
+     errordlg('Argument ''ydim'' must be positive integer.');
118
+     return;
119
+   end
120
+   if isempty(data.data)
121
+     errordlg('Argument ''Workspace data'' must be a string.');
122
+     return;
123
+   end
124
+
125
+   if isempty(data.input_file_type)
126
+     sData=evalin('base',data.data);
127
+   else 
128
+     sData=data.data;
129
+   end
130
+   if isempty(data.out_file)
131
+     if ~isempty(data.out_file_type)
132
+       errordlg('Argument ''Output file'' is not defined.');
133
+       return;
134
+     end
135
+     data.out_file=[];
136
+   end
137
+   answer=sompak_init(sData,...
138
+                      data.input_file_type,...
139
+                      data.inittype,...
140
+                      data.out_file,...
141
+                      data.out_file_type,...
142
+                      data.xdim,...
143
+                      data.ydim,...
144
+                      data.topol,...
145
+                      data.neigh);
146
+   if any(strcmp(data.out_var,{'ans','''ans'''})) | isstr(answer)
147
+     varargout{1}=answer; 
148
+   else
149
+     assignin('base',data.out_var,answer);
150
+     disp(sprintf('Map is set to workspace as ''%s''.',data.out_var));
151
+   end
152
+   close(findobj(get(0,'Children'),'Tag','InitGUI'));
153
+   return;
154
+  case 'train_ok'
155
+   if isempty(data.rlen) | ~is_positive_integer(data.rlen)
156
+     errordlg('Argument ''Running Length'' must be positive integer.');
157
+     return;
158
+   end
159
+   if isempty(data.alpha) | data.alpha <= 0
160
+     errordlg('Argument ''Initial Alpha Value'' must be a positive float.');
161
+     return;
162
+   end
163
+   if isempty(data.radius) | data.radius <= 0
164
+     errordlg('Argument ''Neighborhood Radius'' must be a positive float.');
165
+     return;
166
+   end
167
+   if isempty(data.data)
168
+     errordlg('Argument ''Teaching Data'' must be a string.');
169
+     return;
170
+   end
171
+   if isempty(data.input_file_type)
172
+     sData=evalin('base',data.data);
173
+   else 
174
+     sData=data.data;
175
+   end
176
+   if isempty(data.out_file);
177
+     data.outfile = [];
178
+   end
179
+   if isempty(data.map)
180
+     errordlg('Argument ''Workspace Map'' must be a string.');
181
+     return;
182
+   end
183
+   if isempty(data.map_type)
184
+     sMap=evalin('base',data.map);
185
+   else
186
+     sMap=data.map;
187
+   end
188
+
189
+   answer=sompak_train(sMap,...
190
+                       data.map_type,...
191
+                       data.out_file,...
192
+                       data.out_file_type,...
193
+                       data.data,...
194
+                       data.input_file_type,...
195
+                       data.rlen,...
196
+                       data.alpha,...
197
+                       data.radius);
198
+   if any(strcmp(data.out_var,{'''ans''','ans'})) | isstr(answer)
199
+     varargout{1}=answer;
200
+   else
201
+     assignin('base',data.out_var,answer);
202
+     disp(sprintf('Map is set to workspace as ''%s''.',data.out_var));
203
+   end
204
+   close(findobj(get(0,'Children'),'Tag','TrainGUI')); 
205
+   return;
206
+  case 'sammon_ok'
207
+   if isempty(data.map)
208
+    errordlg('Argument ''Workspace Map'' must be a string.');
209
+    return;
210
+   end
211
+   if isempty(data.map_type)
212
+     sMap=evalin('base',data.map);
213
+   else
214
+     sMap=data.map;
215
+   end
216
+   if isempty(data.out_file);
217
+     data.outfile = [];
218
+   end
219
+   answer=sompak_sammon(sMap,...
220
+                        data.map_type,...
221
+                        data.out_file,...
222
+                        data.out_file_type,...
223
+                        data.rlen);
224
+   if strcmp(data.out_var,'''ans''')|strcmp(data.out_var,'ans')|isstr(answer)
225
+     varargout{1}=answer;
226
+   else
227
+     assignin('base',data.out_var,answer);
228
+     disp(sprintf('Codebook is set to workspace as ''%s''.',data.out_var));
229
+   end
230
+   close(findobj(get(0,'Children'),'Tag','SammonGUI')); 
231
+   return;
232
+end
233
+
234
+set(gcf,'UserData',data);
235
+
236
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
237
+
238
+function bool = is_positive_integer(x)
239
+
240
+bool = ~isempty(x) & isreal(x) & all(size(x) == 1) & x > 0;
241
+if ~isempty(bool)
242
+  if bool & x~=round(x)
243
+    bool = 0;
244
+  end
245
+else
246
+  bool = 0;
247
+end
248
+
249
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
250
+
251
+
252
+
... ...
@@ -0,0 +1,172 @@
1
+function sMap=sompak_sammon(sMap,ft,cout,ct,rlen)
2
+
3
+%SOMPAK_SAMMON Call SOM_PAK Sammon's mapping program from Matlab.
4
+%
5
+%  P = sompak_sammon(sMap,ft,cout,ct,rlen)
6
+%
7
+% ARGUMENTS ([]'s are optional and can be given as empty: [] or '')
8
+%  sMap   (struct) map struct
9
+%         (string) filename
10
+%  [ft]   (string) 'pak' or 'box'. Argument must be defined, if
11
+%                  input file is used.
12
+%  [cout] (string) output file name. If argument is not defined 
13
+%                  (i.e argument is '[]') temporary file '__abcdef' is
14
+%                  used in operations and *it_is_removed* after 
15
+%                  operations!!!
16
+%  [ct]   (string) 'pak' or 'box'. Argument must be defined, if
17
+%                  output file is used.
18
+%  rlen   (scalar) running length
19
+%
20
+% RETURNS: 
21
+%  P      (matrix) the mapping coordinates
22
+%
23
+% Calls SOM_PAK Sammon's mapping program (sammon) from Matlab. Notice
24
+% that to use this function, the SOM_PAK programs must be in your
25
+% search path, or the variable 'SOM_PAKDIR' which is a string
26
+% containing the program path, must be defined in the workspace.
27
+% SOM_PAK programs can be found from:
28
+% http://www.cis.hut.fi/research/som_lvq_pak.shtml
29
+%
30
+% See also SOMPAK_INIT, SOMPAK_SAMMON, SOMPAK_SAMMON_GUI,
31
+%          SOMPAK_GUI, SAMMON.
32
+
33
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Parhankangas
34
+% Copyright (c) by Juha Parhankangas
35
+% http://www.cis.hut.fi/projects/somtoolbox/
36
+
37
+% Juha Parhankangas 050100
38
+
39
+NO_FILE = 0;
40
+
41
+nargchk(5,5,nargin);
42
+
43
+if ~(isstruct(sMap) | isstr(sMap))
44
+  error('Argument ''sMap'' must be a struct or filename.');
45
+end
46
+
47
+if isstr(sMap)
48
+ if isempty(ft) | ~isstr(ft) | ~(strcmp(ft,'pak') | strcmp(ft,'box'))
49
+   error('Argument ''ft'' must be string ''pak'' or ''box''.');
50
+ end
51
+ if strcmp(ft,'pak')
52
+   sMap=som_read_cod(sMap);
53
+ else
54
+   new_var=diff_varname;
55
+   varnames=evalin('base','who');
56
+   loadname=eval(cat(2,'who(''-file'',''',sMap,''')'));
57
+   if any(strcmp(loadname{1},evalin('base','who')))
58
+     assignin('base',new_var,evalin('base',loadname{1}));
59
+     evalin('base',cat(2,'load(''',sMap,''');'));
60
+     new_var2=diff_varname;
61
+
62
+     assignin('base',new_var2,evalin('base',loadname{1}));
63
+     assignin('base',loadname{1},evalin('base',new_var));
64
+     evalin('base',cat(2,'clear ',new_var));
65
+     sMap=evalin('base',new_var2);
66
+     evalin('base',cat(2,'clear ',new_var2));
67
+   else
68
+     evalin('base',cat(2,'load(''',sMap,''');'));
69
+     sMap=evalin('base',loadname{1});
70
+     evalin('base',cat(2,'clear ',loadname{1}));
71
+   end   
72
+ end
73
+end
74
+
75
+if ~isstr(cout) & isempty(cout)
76
+  NO_FILE = 1;
77
+  cout = '__abcdef';
78
+elseif ~isstr(cout) | isempty(cout)
79
+  error('Argument ''cout'' must be a string or ''[]''.');
80
+end
81
+
82
+if ~NO_FILE & (isempty(ct) | ~(strcmp(ct,'pak') | strcmp(ct,'box')))
83
+  error('Argument ''ct'' must be string ''pak'' or ''box''.');
84
+end
85
+
86
+som_write_cod(sMap,cout);
87
+
88
+if ~is_positive_integer(rlen)
89
+  error('Argument ''rlen'' must be a positive integer.');
90
+end
91
+
92
+if any(strcmp('SOM_PAKDIR',evalin('base','who')))
93
+  command=cat(2,evalin('base','SOM_PAKDIR'),'sammon ');
94
+else
95
+  command='sammon ';
96
+end
97
+
98
+str = sprintf('%s -cin %s -cout %s -rlen %d',command,cout,cout,rlen);
99
+
100
+if isunix
101
+  unix(str);
102
+else
103
+  dos(str);
104
+end
105
+
106
+sMap=som_read_cod(cout);
107
+
108
+if ~NO_FILE
109
+  if isunix
110
+    unix(cat(2,'/bin/rm ',cout));
111
+  else
112
+    dos(cat(2,'del ',cout));
113
+  end
114
+  if strcmp(ct,'box');
115
+    sMap=sMap.codebook;
116
+    eval(cat(2,'save ',cout,' sMap'));
117
+    disp(cat(2,'Output is saved to the file ',sprintf('''%s.mat''.',cout)));
118
+  else
119
+    som_write_cod(sMap,cout);
120
+    sMap=sMap.codebook;
121
+    disp(cat(2,'Output is saved to the file ',cout,'.'));
122
+  end
123
+else
124
+  if isunix
125
+    unix('/bin/rm __abcdef');
126
+  else
127
+    dos('del __abcdef');
128
+  end
129
+end
130
+
131
+
132
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
133
+
134
+function bool = is_positive_integer(x)
135
+
136
+bool = ~isempty(x) & isreal(x) & all(size(x) == 1) & x > 0;
137
+if ~isempty(bool)
138
+  if bool & x~=round(x)
139
+    bool = 0;
140
+  end
141
+else
142
+  bool = 0;
143
+end
144
+
145
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
146
+
147
+function str = diff_varname();
148
+
149
+array=evalin('base','who');
150
+
151
+if isempty(array)
152
+  str='a';
153
+  return;
154
+end
155
+
156
+for i=1:length(array)
157
+  lens(i)=length(array{i});
158
+end
159
+
160
+
161
+ind=max(lens);
162
+
163
+str(1:ind+1)='a';
164
+
165
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
166
+
167
+
168
+
169
+
170
+
171
+
172
+
... ...
@@ -0,0 +1,200 @@
1
+function sompak_sammon_gui()
2
+
3
+%SOMPAK_SAMMON_GUI A GUI for using SOM_PAK Sammon's mapping program 
4
+%                  from Matlab.
5
+%
6
+%  sompak_sammon_gui
7
+%
8
+% Launches a GUI which allows the use of SOM_PAK Sammon's mapping
9
+% program (sammon) from Matlab. Notice that to use this function, the
10
+% SOM_PAK programs must be in your search path, or the variable
11
+% 'SOM_PAKDIR' which is a string containing the program path, must be
12
+% defined in the workspace. SOM_PAK programs can be found from:
13
+% http://www.cis.hut.fi/research/som_lvq_pak.shtml
14
+%
15
+% See also SOMPAK_SAMMON, SOMPAK_GUI, SOMPAK_INIT_GUI,
16
+%          SOMPAK_TRAIN_GUI, SOM_GUI.
17
+
18
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Parhankangas
19
+% Copyright (c) by Juha Parhankangas
20
+% http://www.cis.hut.fi/projects/somtoolbox/
21
+
22
+% Juha Parhankangas 050100
23
+
24
+h=findobj(get(0,'Children'),'Tag','SammonGUI');
25
+
26
+if ~isempty(h)
27
+  figure(h);
28
+  return;
29
+end
30
+
31
+
32
+a = figure('Color',[0.8 0.8 0.8], ...
33
+	'PaperType','a4letter', ...
34
+	'Position',[665 517 175 295], ...
35
+	'Tag','SammonGUI');
36
+b = uicontrol('Parent',a, ...
37
+	'Units','points', ...
38
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
39
+	'Callback','close gcf', ...
40
+	'FontWeight','demi', ...
41
+	'Position',[8 20 50 20], ...
42
+	'String','CLOSE', ...
43
+	'Tag','Pushbutton1');
44
+b = uicontrol('Parent',a, ...
45
+	'Units','points', ...
46
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
47
+	'Callback','sompak_rb_control sammon_ok',...
48
+	'FontWeight','demi', ...
49
+	'Position',[86 20 50 20], ...
50
+	'String','OK', ...
51
+	'Tag','Pushbutton2');
52
+b = uicontrol('Parent',a, ...
53
+	'Units','points', ...
54
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
55
+	'Position',[8 50 130 175], ...
56
+	'Style','frame', ...
57
+	'Tag','Frame1');
58
+b = uicontrol('Parent',a, ...
59
+	'Units','points', ...
60
+	'BackgroundColor',[0.8 0.8 0.8], ...
61
+	'Position',[12 54 122 40], ...
62
+	'Style','frame', ...
63
+	'Tag','Frame2');
64
+b = uicontrol('Parent',a, ...
65
+	'Units','points', ...
66
+	'BackgroundColor',[0.8 0.8 0.8], ...
67
+	'FontWeight','demi', ...
68
+	'HorizontalAlignment','left', ...
69
+	'Position',[30 78 90 12], ...
70
+	'String','RUNNING LENGTH', ...
71
+	'Style','text', ...
72
+	'Tag','StaticText1');
73
+b = uicontrol('Parent',a, ...
74
+	'Units','points', ...
75
+	'BackgroundColor',[1 1 1], ...
76
+	'Callback','sompak_rb_control rlen',...
77
+	'Position',[48 57 50 20], ...
78
+	'Style','edit', ...
79
+	'Tag','RLEN');
80
+
81
+udata.rlen=[];
82
+
83
+b = uicontrol('Parent',a, ...
84
+	'Units','points', ...
85
+	'BackgroundColor',[0.8 0.8 0.8], ...
86
+	'Position',[12 96 122 40], ...
87
+	'Style','frame', ...
88
+	'Tag','Frame3');
89
+b = uicontrol('Parent',a, ...
90
+	'Units','points', ...
91
+	'BackgroundColor',[0.8 0.8 0.8], ...
92
+	'FontWeight','demi', ...
93
+	'HorizontalAlignment','left', ...
94
+	'Position',[33 119 90 12], ...
95
+	'String','OUTPUT VARIABLE', ...
96
+	'Style','text', ...
97
+	'Tag','StaticText2');
98
+b = uicontrol('Parent',a, ...
99
+	'Units','points', ...
100
+	'BackgroundColor',[1 1 1], ...	
101
+	'Callback','sompak_rb_control out_var',...
102
+	'Position',[48 99 50 20], ...
103
+	'String','''ans''', ...
104
+	'Style','edit', ...
105
+	'Tag','OUT_VAR');
106
+
107
+udata.out_var='ans';
108
+
109
+b = uicontrol('Parent',a, ...
110
+	'Units','points', ...
111
+	'BackgroundColor',[0.8 0.8 0.8], ...
112
+	'Position',[12 138 122 40], ...
113
+	'Style','frame', ...
114
+	'Tag','Frame4');
115
+b = uicontrol('Parent',a, ...
116
+	'Units','points', ...
117
+	'BackgroundColor',[0.8 0.8 0.8], ...
118
+	'FontWeight','demi', ...
119
+	'HorizontalAlignment','left', ...
120
+	'Position',[43 162 60 12], ...
121
+	'String','OUTPUT FILE', ...
122
+	'Style','text', ...
123
+	'Tag','StaticText3');
124
+b = uicontrol('Parent',a, ...
125
+	'Units','points', ...
126
+	'BackgroundColor',[1 1 1], ...
127
+	'Callback','sompak_rb_control out_file',...
128
+	'Position',[15 141 50 20], ...
129
+	'Style','edit', ...
130
+	'Tag','OUT_FILE');
131
+
132
+udata.out_file=[];
133
+
134
+b = uicontrol('Parent',a, ...
135
+	'Units','points', ...
136
+	'Callback','sompak_rb_control out_ft',...
137
+	'FontWeight','demi', ...
138
+	'HorizontalAlignment','left', ...
139
+	'Max',3, ...
140
+	'Min',1, ...
141
+	'Position',[70 146 62 15], ...
142
+	'String',{'No File';'mat-file';'cod-file'}, ...
143
+	'Style','popupmenu', ...
144
+	'Tag','OUT_FILE_TYPE', ...
145
+	'Value',1);
146
+
147
+udata.out_file_type='';
148
+
149
+b = uicontrol('Parent',a, ...
150
+	'Units','points', ...
151
+	'BackgroundColor',[0.8 0.8 0.8], ...
152
+	'Position',[12 180 122 40], ...
153
+	'Style','frame', ...
154
+	'Tag','Frame5');
155
+b = uicontrol('Parent',a, ...
156
+	'Units','points', ...
157
+	'BackgroundColor',[0.8 0.8 0.8], ...
158
+	'FontWeight','demi', ...
159
+	'HorizontalAlignment','left', ...
160
+	'Position',[60 203 25 12], ...
161
+	'String','MAP', ...
162
+	'Style','text', ...
163
+	'Tag','StaticText4');
164
+b = uicontrol('Parent',a, ...
165
+	'Units','points', ...
166
+	'BackgroundColor',[1 1 1], ...
167
+	'Callback','sompak_rb_control map',...
168
+	'Position',[15 183 50 20], ...
169
+	'Style','edit', ...
170
+	'Tag','MAP');
171
+
172
+udata.map=[];
173
+
174
+b = uicontrol('Parent',a, ...
175
+	'Units','points', ...
176
+	'Callback','sompak_rb_control map_ft',... 
177
+	'FontWeight','demi', ...
178
+	'HorizontalAlignment','left', ...
179
+	'Max',3, ...
180
+	'Min',1, ...
181
+	'Position',[70 188 62 15], ...
182
+	'String',{'Variable';'mat-file';'cod-file'}, ...
183
+	'Style','popupmenu', ...
184
+	'Tag','MAP_TYPE', ...
185
+	'Value',1);
186
+
187
+udata.map_type='';
188
+
189
+b = uicontrol('Parent',a, ...
190
+	'Units','points', ...
191
+	'BackgroundColor',[0.8 0.8 0.8], ...
192
+	'FontSize',12, ...
193
+	'FontWeight','demi', ...
194
+	'Position',[41 230 62 12], ...
195
+	'String','SAMMON', ...
196
+	'Style','text', ...
197
+	'Tag','StaticText5');
198
+
199
+
200
+set(gcf,'UserData',udata);
... ...
@@ -0,0 +1,243 @@
1
+function sMap=sompak_train(sMap,ft,cout,ct,din,dt,rlen,alpha,radius)
2
+
3
+%SOMPAK_TRAIN Call SOM_PAK training program from Matlab.
4
+%
5
+% sMap=sompak_train(sMap,ft,cout,ct,din,dt,rlen,alpha,radius)
6
+%
7
+% ARGUMENTS ([]'s are optional and can be given as empty: [] or '')
8
+%  sMap   (struct) map struct 
9
+%         (string) filename
10
+%  [ft]   (string) 'pak' or 'box'. Argument must be defined, if input file
11
+%                  is used.
12
+%  [cout] (string) filename for output SOM, if argument is not defined
13
+%                  (i.e. argument is '[]') temporary file '__abcdef' is
14
+%                  used in operations and *it_is_removed* after 
15
+%                  operations!!!
16
+%   [ct]  (string) 'pak' or 'box'. Argument must be defined, if output
17
+%                  file is used.
18
+%   din   (struct) data struct to be used in teaching
19
+%         (matrix) data matrix
20
+%         (string) filename
21
+%                  If argument is not a filename or file is .mat -file, 
22
+%                   temporary file '__din' is used in operations
23
+%                   and *it_is_removed* after operations!!!
24
+%  [dt]   (string) 'pak' or 'box'. Argument must be defined, if input file
25
+%                  is used.
26
+%  rlen   (scalar) running length of teaching
27
+%  alpha  (float)  initial alpha value
28
+%  radius (float)  initial radius of neighborhood
29
+% 
30
+% RETURNS
31
+%  sMap   (struct) map struct
32
+%
33
+% Calls SOM_PAK training program (vsom) from Matlab. Notice that to
34
+% use this function, the SOM_PAK programs must be in your search path,
35
+% or the variable 'SOM_PAKDIR' which is a string containing the
36
+% program path, must be defined in the workspace. SOM_PAK programs can
37
+% be found from: http://www.cis.hut.fi/research/som_lvq_pak.shtml
38
+%
39
+% See also SOMPAK_TRAIN, SOMPAK_SAMMON, SOMPAK_TRAIN_GUI,
40
+%          SOMPAK_GUI, SOM_SEQTRAIN.
41
+
42
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Parhankangas
43
+% Copyright (c) by Juha Parhankangas
44
+% http://www.cis.hut.fi/projects/somtoolbox/
45
+
46
+% Juha Parhankangas 050100
47
+
48
+
49
+nargchk(9,9,nargin);
50
+
51
+NO_FILE=0;
52
+DIN_FILE = 0;
53
+
54
+if ~isstruct(sMap) & ~isstr(sMap)
55
+  error('Argument ''sMap'' must be a struct or string.');
56
+end
57
+
58
+if isstr(sMap)
59
+  if isempty(ft)
60
+    error('Argument ''ft'' must be defined.');
61
+  end
62
+  if strcmp(ft,'pak')
63
+    sMap=som_read_cod(sMap);
64
+  elseif strcmp(ft,'box')
65
+    new_var=diff_varname;
66
+    varnames=evalin('base','who');
67
+    loadname=eval(cat(2,'who(''-file'',''',sMap,''')'));
68
+    if any(strcmp(loadname{1},evalin('base','who')))
69
+      assignin('base',new_var,evalin('base',loadname{1}));
70
+      evalin('base',cat(2,'load(''',sMap,''');'));
71
+      new_var2=diff_varname;
72
+
73
+      assignin('base',new_var2,evalin('base',loadname{1}));
74
+      assignin('base',loadname{1},evalin('base',new_var));
75
+      evalin('base',cat(2,'clear ',new_var));
76
+      sMap=evalin('base',new_var2);
77
+      evalin('base',cat(2,'clear ',new_var2));
78
+    else
79
+      evalin('base',cat(2,'load(''',sMap,''');'));
80
+      sMap=evalin('base',loadname{1});
81
+      evalin('base',cat(2,'clear ',loadname{1}));
82
+    end
83
+
84
+  end
85
+end
86
+if ~isstr(cout) & isempty(cout)
87
+  cout = '__abcdef';
88
+  NO_FILE = 1;
89
+elseif ~isstr(cout) | (isstr(cout) & isempty(cout))
90
+  error('Argument ''cout'' must be a string or ''[]''.');
91
+end
92
+
93
+if ~NO_FILE & (isempty(ct) | ~(~isempty(ct) & ...
94
+   (strcmp(ct,'pak') | strcmp(ct,'box'))))
95
+  error('Argument ''ct'' must be string ''pak'' or ''box''.');
96
+end
97
+
98
+map_name=sMap.name;
99
+som_write_cod(sMap,cout);
100
+
101
+if ~isempty(din)
102
+  som_write_data(din, '__din');
103
+  DIN_FILE = 1;
104
+  din = '__din';
105
+else
106
+  DIN_FILE=0;
107
+end
108
+
109
+if ~DIN_FILE
110
+  if isempty(dt) | ~isstr(dt) | ~(strcmp(dt,'box') | strcmp(dt,'pak'))
111
+    error('Argument ''dt'' must be string ''pak'' or ''box''.');
112
+  end
113
+  if strcmp(dt,'box');
114
+    DIN_FILE = 1;
115
+    din_var=diff_varname;
116
+    varnames=evalin('base','who');
117
+    loadname=eval(cat(2,'who(''-file'',''',din,''')'));
118
+    if any(strcmp(loadname{1},evalin('base','who')))
119
+      assignin('base',din_var,evalin('base',loadname{1}));
120
+      evalin('base',cat(2,'load(''',din,''');'));
121
+      din_var2=diff_varname;
122
+
123
+      assignin('base',new_var2,evalin('base',loadname{1}));
124
+      assignin('base',loadname{1},evalin('base',din_var));
125
+      evalin('base',cat(2,'clear ',din_var));
126
+      din=evalin('base',din_var2);
127
+    else
128
+      evalin('base',cat(2,'load(''',din,''')'));
129
+      din=evalin('base',loadname{1});
130
+      evalin('base',cat(2,'clear ',loadname{1}));
131
+    end
132
+    som_write_data(din,'__din');
133
+    din = '__din';
134
+  end
135
+end
136
+if ~is_positive_integer(rlen)
137
+  error('Argument ''rlen'' must be positive integer.');
138
+end
139
+
140
+if ~(isreal(alpha) & all(size(alpha)==1))
141
+  error('Argument ''alpha'' must be a floating point number.');
142
+end
143
+
144
+if ~(isreal(radius) & all(size(radius)==1) & radius > 0)
145
+  error('Argument ''radius'' must be a positive floating point number.');
146
+end
147
+
148
+if any(strcmp('SOM_PAKDIR',evalin('base','who')))
149
+  traincommand=cat(2,evalin('base','SOM_PAKDIR'),'vsom ');
150
+else
151
+  traincommand='vsom ';
152
+end
153
+
154
+str=cat(2,traincommand,sprintf('-cin %s -din %s -cout %s ',cout,din,cout),...
155
+                  sprintf(' -rlen %d -alpha %f -radius %f',rlen,alpha,radius));
156
+if isunix
157
+  unix(str);
158
+else
159
+  dos(str);
160
+end
161
+
162
+sMap=som_read_cod(cout);
163
+sMap.name=map_name;
164
+
165
+if ~NO_FILE
166
+  if isunix
167
+    unix(cat(2,'/bin/rm ',cout));
168
+  else
169
+    dos(cat(2,'del ',cout));
170
+  end
171
+  if isempty(ct) | ~isstr(ct) | ~(strcmp(ct,'pak') | strcmp(ct,'box'))
172
+    error('Argument ''ct'' must be string ''pak'' or ''box''.');
173
+  elseif strcmp(ct,'box');
174
+    eval(cat(2,'save ',cout,' sMap'));
175
+    disp(cat(2,'Output written to the file ',sprintf('''%s.mat''.',cout)));
176
+  else
177
+    som_write_cod(sMap,cout);
178
+  end
179
+else
180
+  if isunix
181
+    unix('/bin/rm __abcdef');
182
+  else
183
+    dos('del __abcdef');
184
+  end
185
+end 
186
+
187
+if DIN_FILE
188
+  if isunix
189
+    unix('/bin/rm __din');
190
+  else
191
+    dos('del __abcdef');
192
+  end
193
+end
194
+
195
+
196
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
197
+
198
+function bool = is_positive_integer(x)
199
+
200
+bool = ~isempty(x) & isreal(x) & all(size(x) == 1) & x > 0;
201
+if ~isempty(bool)
202
+  if bool & x~=round(x)
203
+    bool = 0;
204
+  end
205
+else
206
+  bool = 0;
207
+end
208
+
209
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
210
+
211
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
212
+
213
+function str = diff_varname();
214
+
215
+array=evalin('base','who');
216
+
217
+if isempty(array)
218
+  str='a';
219
+  return;
220
+end
221
+
222
+for i=1:length(array)
223
+  lens(i)=length(array{i});
224
+end
225
+
226
+
227
+ind=max(lens);
228
+
229
+str(1:ind+1)='a';
230
+
231
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
232
+
233
+
234
+
235
+
236
+
237
+
238
+
239
+
240
+
241
+
242
+
243
+
... ...
@@ -0,0 +1,290 @@
1
+function sompak_train_gui()
2
+
3
+%SOMPAK_TRAIN_GUI A GUI for using SOM_PAK training program from Matlab.
4
+%
5
+%  sompak_train_gui
6
+%
7
+% Launches a GUI which allows the use of SOM_PAK training program
8
+% (vsom) from Matlab. Notice that to use this function, the SOM_PAK
9
+% programs must be in your search path, or the variable 'SOM_PAKDIR'
10
+% which is a string containing the program path, must be defined in
11
+% the workspace. SOM_PAK programs can be found from:
12
+% http://www.cis.hut.fi/research/som_lvq_pak.shtml
13
+%
14
+% See also SOMPAK_TRAIN, SOMPAK_GUI, SOMPAK_INIT_GUI,
15
+%          SOMPAK_SAMMON_GUI, SOM_GUI.
16
+
17
+% Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Parhankangas
18
+% Copyright (c) by Juha Parhankangas
19
+% http://www.cis.hut.fi/projects/somtoolbox/
20
+
21
+% Juha Parhankangas 050100
22
+
23
+h=findobj(get(0,'Children'),'Tag','TrainGUI');
24
+
25
+if ~isempty(h)
26
+  figure(h);
27
+  return;
28
+end
29
+
30
+a = figure('Color',[0.8 0.8 0.8],... 
31
+	'PaperType','a4letter', ...
32
+	'Position',[558 207 173 445], ...
33
+	'Tag','TrainGUI');
34
+b = uicontrol('Parent',a, ...
35
+	'Units','points', ...
36
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
37
+	'Callback','close gcf', ...
38
+	'FontWeight','demi', ...
39
+	'Position',[8 20 50 20], ...
40
+	'String','CLOSE', ...
41
+	'Tag','Pushbutton1');
42
+b = uicontrol('Parent',a, ...
43
+	'Units','points', ...
44
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
45
+	'Callback','sompak_rb_control train_ok',...
46
+	'FontWeight','demi', ...
47
+	'Position',[86 20 50 20], ...
48
+	'String','OK', ...
49
+	'Tag','Pushbutton2');
50
+b = uicontrol('Parent',a, ...
51
+	'Units','points', ...
52
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
53
+	'Position',[8 50 130 300], ...
54
+	'Style','frame', ...
55
+	'Tag','Frame1');
56
+b = uicontrol('Parent',a, ...
57
+	'Units','points', ...
58
+	'BackgroundColor',[0.8 0.8 0.8], ...
59
+	'Position',[12 54 122 40], ...
60
+	'Style','frame', ...
61
+	'Tag','Frame2');
62
+b = uicontrol('Parent',a, ...
63
+	'Units','points', ...
64
+	'BackgroundColor',[0.8 0.8 0.8], ...
65
+	'FontWeight','demi', ...
66
+	'HorizontalAlignment','left', ...
67
+	'Position',[18 78 110 12], ...
68
+	'String','NEIGHBORHOOD RADIUS', ...
69
+	'Style','text', ...
70
+	'Tag','StaticText1');
71
+b = uicontrol('Parent',a, ...
72
+	'Units','points', ...
73
+	'BackgroundColor',[1 1 1], ...
74
+	'Callback','sompak_rb_control radius', ...
75
+	'Position',[48 56 50 20], ...
76
+	'Style','edit', ...
77
+	'Tag','RADIUS');
78
+
79
+udata.radius=[];	
80
+
81
+b = uicontrol('Parent',a, ...
82
+	'Units','points', ...
83
+	'BackgroundColor',[0.8 0.8 0.8], ...
84
+	'Position',[12 96 122 40], ...
85
+	'Style','frame', ...
86
+	'Tag','Frame3');
87
+b = uicontrol('Parent',a, ...
88
+	'Units','points', ...
89
+	'BackgroundColor',[0.8 0.8 0.8], ...
90
+	'FontWeight','demi', ...
91
+	'HorizontalAlignment','left', ...
92
+	'Position',[22 120 101 12], ...
93
+	'String','INITIAL ALPHA VALUE', ...
94
+	'Style','text', ...
95
+	'Tag','StaticText2');
96
+b = uicontrol('Parent',a, ...
97
+	'Units','points', ...
98
+	'BackgroundColor',[1 1 1], ...
99
+	'Callback','sompak_rb_control alpha',...
100
+	'Position',[48 99 50 20], ...
101
+	'Style','edit', ...
102
+	'Tag','ALPHA');
103
+
104
+
105
+udata.alpha=[];
106
+
107
+
108
+b = uicontrol('Parent',a, ...
109
+	'Units','points', ...
110
+	'BackgroundColor',[0.8 0.8 0.8], ...
111
+	'Position',[12 138 122 40], ...
112
+	'Style','frame', ...
113
+	'Tag','Frame4');
114
+b = uicontrol('Parent',a, ...
115
+	'Units','points', ...
116
+	'BackgroundColor',[0.8 0.8 0.8], ...
117
+	'FontWeight','demi', ...
118
+	'HorizontalAlignment','left', ...
119
+	'Position',[30 163 90 12], ...
120
+	'String','RUNNING LENGTH', ...
121
+	'Style','text', ...
122
+	'Tag','StaticText3');
123
+b = uicontrol('Parent',a, ...
124
+	'Units','points', ...
125
+	'BackgroundColor',[1 1 1], ...
126
+	'Callback','sompak_rb_control rlen',...
127
+	'Position',[48 141 50 20], ...
128
+	'Style','edit', ...
129
+	'Tag','RLEN');
130
+
131
+udata.rlen=[];
132
+
133
+b = uicontrol('Parent',a, ...
134
+	'Units','points', ...
135
+	'BackgroundColor',[0.8 0.8 0.8], ...
136
+	'Position',[12 180 122 40], ...
137
+	'Style','frame', ...
138
+	'Tag','Frame5');
139
+b = uicontrol('Parent',a, ...
140
+	'Units','points', ...
141
+	'BackgroundColor',[0.8 0.8 0.8], ...
142
+	'FontWeight','demi', ...
143
+	'HorizontalAlignment','left', ...
144
+	'Position',[30 204 90 11], ...
145
+	'String','OUTPUT VARIABLE', ...
146
+	'Style','text', ...
147
+	'Tag','StaticText4');
148
+b = uicontrol('Parent',a, ...
149
+	'Units','points', ...
150
+	'BackgroundColor',[1 1 1], ...
151
+	'Callback','sompak_rb_control out_var',...
152
+	'Position',[48 183 50 20], ...
153
+	'String','''ans''',...
154
+	'Style','edit', ...
155
+	'Tag','OUT_VAR');
156
+
157
+udata.out_var='ans';
158
+
159
+b = uicontrol('Parent',a, ...
160
+	'Units','points', ...
161
+	'BackgroundColor',[0.8 0.8 0.8], ...
162
+	'Position',[12 222 122 40], ...
163
+	'Style','frame', ...
164
+	'Tag','Frame6');
165
+b = uicontrol('Parent',a, ...
166
+	'Units','points', ...
167
+	'BackgroundColor',[0.8 0.8 0.8], ...
168
+	'FontWeight','demi', ...
169
+	'HorizontalAlignment','left', ...
170
+	'Position',[42 245 65 12], ...
171
+	'String','OUTPUT FILE', ...
172
+	'Style','text', ...
173
+	'Tag','StaticText5');
174
+b = uicontrol('Parent',a, ...
175
+	'Units','points', ...
176
+	'BackgroundColor',[1 1 1], ...
177
+	'Callback','sompak_rb_control out_file',...
178
+	'Position',[15 225 50 20], ...
179
+	'Style','edit', ...
180
+	'Tag','OUT_FILE');
181
+
182
+udata.out_file=[];
183
+
184
+b = uicontrol('Parent',a, ...
185
+	'Callback','sompak_rb_control out_ft',...
186
+	'Units','points', ...
187
+	'FontWeight','demi', ...
188
+	'HorizontalAlignment','left', ...
189
+	'Max',3, ...
190
+	'Min',1, ...
191
+	'Position',[70 230 62 15], ...
192
+	'String',{'No File';'mat-file';'cod-file'}, ...
193
+	'Style','popupmenu', ...
194
+	'Tag','OUT_FILE_TYPE', ...
195
+	'Value',1);
196
+
197
+udata.out_file_type='';
198
+
199
+b = uicontrol('Parent',a, ...
200
+	'Units','points', ...
201
+	'BackgroundColor',[0.8 0.8 0.8], ...
202
+	'Position',[12 264 122 40], ...
203
+	'Style','frame', ...
204
+	'Tag','Frame7');
205
+b = uicontrol('Parent',a, ...
206
+	'Units','points', ...
207
+	'BackgroundColor',[0.8 0.8 0.8], ...
208
+	'FontWeight','demi', ...
209
+	'HorizontalAlignment','left', ...
210
+	'Position',[34 288 85 12], ...
211
+	'String','TEACHING DATA', ...
212
+	'Style','text', ...
213
+	'Tag','StaticText6');
214
+b = uicontrol('Parent',a, ...
215
+	'Units','points', ...
216
+	'BackgroundColor',[1 1 1], ...
217
+	'Callback','sompak_rb_control data',...
218
+	'Position',[15 267 50 20], ...
219
+	'Style','edit', ...
220
+	'Tag','DATA');
221
+b = uicontrol('Parent',a, ...
222
+	'Units','points', ...
223
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
224
+	'Callback','sompak_rb_control input_ft',...
225
+	'FontWeight','demi', ...
226
+	'HorizontalAlignment','left', ...
227
+	'Max',3, ...
228
+	'Min',1, ...
229
+	'Position',[70 272 62 15], ...
230
+	'String',{'Variable';'mat-file';'dat-file'}, ...
231
+	'Style','popupmenu', ...
232
+	'Tag','INPUT_FILE_TYPE', ...
233
+	'Value',1);
234
+
235
+udata.input_file_type='';
236
+
237
+b = uicontrol('Parent',a, ...
238
+	'Units','points', ...
239
+	'BackgroundColor',[0.8 0.8 0.8], ...
240
+	'Position',[12 306 122 40], ...
241
+	'Style','frame', ...
242
+	'Tag','Frame8');
243
+b = uicontrol('Parent',a, ...
244
+	'Units','points', ...
245
+	'BackgroundColor',[0.8 0.8 0.8], ...
246
+	'FontWeight','demi', ...
247
+	'HorizontalAlignment','left', ...
248
+	'Position',[60 331 25 12], ...
249
+	'String','MAP', ...
250
+	'Style','text', ...
251
+	'Tag','StaticText7');
252
+b = uicontrol('Parent',a, ...
253
+	'Units','points', ...
254
+	'BackgroundColor',[1 1 1], ...
255
+	'Callback','sompak_rb_control map',...
256
+	'Position',[15 309 50 20], ...
257
+	'Style','edit', ...
258
+	'Tag','MAP');
259
+
260
+udata.map=[];
261
+
262
+b = uicontrol('Parent',a, ...
263
+	'Units','points', ...
264
+	'BackgroundColor',[0.701961 0.701961 0.701961], ...
265
+	'Callback','sompak_rb_control map_ft',...
266
+	'FontWeight','demi', ...
267
+	'HorizontalAlignment','left', ...
268
+	'Max',3, ...
269
+	'Min',1, ...
270
+	'Position',[70 314 62 15], ...
271
+	'String',{'Variable','mat-file','cod-file'}, ...
272
+	'Style','popupmenu', ...
273
+	'Tag','MAP_TYPE', ...
274
+	'Value',1);
275
+
276
+udata.map_type='';
277
+
278
+b = uicontrol('Parent',a, ...
279
+	'Units','points', ...
280
+	'BackgroundColor',[0.8 0.8 0.8], ...
281
+	'FontSize',12, ...
282
+	'FontWeight','demi', ...
283
+	'HorizontalAlignment','left', ...
284
+	'Position',[50 359 48 12], ...
285
+	'String','TRAIN', ...
286
+	'Style','text', ...
287
+	'Tag','StaticText8');
288
+
289
+set(gcf,'UserData',udata);
290
+
... ...
@@ -0,0 +1,196 @@
1
+% SOM Toolbox
2
+% Version 2.0beta, May 30 2002
3
+% 
4
+% Copyright 1997-2000 by
5
+% Esa Alhoniemi, Johan Himberg, Juha Parhankangas and Juha Vesanto
6
+% Contributed files may contain copyrights of their own.
7
+% 
8
+% SOM Toolbox comes with ABSOLUTELY NO WARRANTY; for details
9
+% see License.txt in the program package. This is free software,
10
+% and you are welcome to redistribute it under certain conditions;
11
+% see License.txt for details.
12
+% 
13
+% 
14
+% Demos
15
+% 
16
+%            som_demo1   SOM Toolbox demo 1: basic properties
17
+%            som_demo2   SOM Toolbox demo 2: basic usage
18
+%            som_demo3   SOM Toolbox demo 3: visualization
19
+%            som_demo4   SOM Toolbox demo 4: data analysis
20
+% 
21
+% Creation of structs
22
+% 
23
+%              som_set   create & set (& check) values to structs
24
+%             som_info   print out information on a given struct  
25
+%      som_data_struct   create & initialize a data struct 
26
+%       som_map_struct   create & initialize a map struct 
27
+%     som_topol_struct   create & initialize a topology struct 
28
+%     som_train_struct   create & initialize a train struct 
29
+%         som_clstruct   create a cluster struct
30
+%            som_clset   set properties in a cluster struct
31
+%            som_clget   get stuff from a cluster struct
32
+% 
33
+% Struct conversion and file I/O
34
+% 
35
+%           som_vs1to2   converts a version 1.0 struct to version 2.0 struct
36
+%           som_vs2to1   converts a version 2.0 struct to version 1.0 struct
37
+%        som_read_data   reads a (SOM_PAK format) ASCII data file
38
+%       som_write_data   writes a SOM_PAK format codebook file
39
+%        som_write_cod   writes a SOM_PAK format data file
40
+%         som_read_cod   reads a SOM_PAK format codebook file
41
+% 
42
+% Data preprocessing
43
+% 
44
+%        som_normalize   normalize data set
45
+%      som_denormalize   denormalize data set 
46
+%    som_norm_variable   (de)normalize one variable
47
+%           preprocess   preprocessing GUI
48
+% 
49
+% Initialization and training functions
50
+% 
51
+%             som_make   create, initialize and train a SOM
52
+%         som_randinit   random initialization algorithm
53
+%          som_lininit   linear initialization algorithm
54
+%         som_seqtrain   sequential training algorithm
55
+%       som_batchtrain   batch training algorithm
56
+%              som_gui   SOM initialization and training GUI
57
+%       som_prototrain   a simple version of sequential training: easy to modify
58
+% 
59
+% Clustering algorithms
60
+% 
61
+%           som_kmeans   k-means algorithm (was earlier kmeans)
62
+%      kmeans_clusters   try and evaluate several k-means clusterings
63
+%           neural_gas   neural gas vector quantization algorithm
64
+%          som_linkage   hierarchical clustering algorithms
65
+%        som_cllinkage   hierarchical clustering of SOM
66
+%       som_dmatminima   local minima from distance (or U-) matrix
67
+%     som_dmatclusters   distance (or U-) matrix based clustering
68
+%         som_clspread   spreads clusters to unassinged map units
69
+%           som_cldist   calculate distances between clusters
70
+%         som_gapindex   gap validity index of clustering
71
+%             db_index   Davies-Bouldin validity index of clustering  
72
+% 
73
+% Supervised/classification algorithms
74
+% 
75
+%       som_supervised   supervised SOM algorithm
76
+%                 lvq1   LVQ1 algorithm
77
+%                 lvq3   LVQ3 algorithm
78
+%                  knn   k-NN classification algorithm 
79
+%              knn_old   k-NN classification algorithm (old version)
80
+% 
81
+% SOM error measures
82
+% 
83
+%          som_quality   quantization and topographic error of SOM
84
+%       som_distortion   SOM distortion measure
85
+%      som_distortion3   elements of the SOM distortion measure
86
+% 
87
+% Auxiliary functions
88
+% 
89
+%             som_bmus   calculates BMUs for given data vectors
90
+%         som_eucdist2   pairwise squared euclidian distances between vectors
91
+%            som_mdist   calculates pairwise distances between vectors 
92
+%           som_divide   extract subsets of data based on map
93
+%            som_label   give labels to map units
94
+%        som_label2num   rcodes string data labels to interger class labels 
95
+%        som_autolabel   automatically labels the SOM based on given data
96
+%      som_unit_coords   calculates coordinates in output space for map units
97
+%       som_unit_dists   distances in output space between map units
98
+%      som_unit_neighs   units in 1-neighborhood for each map unit
99
+%     som_neighborhood   calculates neighborhood matrix for the given map
100
+%        som_neighbors   calculates different kinds of neighborhoods 
101
+%           som_neighf   calculates neighborhood function values
102
+%           som_select   GUI for manual selection of map units
103
+%     som_estimate_gmm   create Gaussian mixture model on top of SOM
104
+%  som_probability_gmm   evaluate Gaussian mixture model
105
+%          som_ind2sub   from linear index to subscript index 
106
+%          som_sub2ind   from subscript index to linear index
107
+%          som_ind2cod   from linear index to SOM_PAK linear index 
108
+%          som_cod2ind   from SOM_linear index to SOM_PAK linear index 
109
+%             nanstats   mean, std and median which ignore NaNs
110
+%   som_modify_dataset   add, remove, or extract samples and components
111
+%         som_fillnans   fill NaNs in a data set based on given SOM
112
+%            som_stats   statistics of a data set
113
+%           som_drmake   calculate descriptive rules for a cluster
114
+%           som_dreval   evaluate descriptive rules for a cluster
115
+%         som_drsignif   rule significance measures
116
+% 
117
+% Using SOM_PAK from Matlab
118
+% 
119
+%      som_sompaktrain   uses SOM_PAK to train a map
120
+%           sompak_gui   GUI for using SOM_PAK from Matlab
121
+%          sompak_init   call SOM_PAK's initialization programs from Matlab
122
+%      sompak_init_gui   GUI for using SOM_PAK's initialization from Matlab
123
+%    sompak_rb_control   an auxiliary function for sompak_*_gui functions.
124
+%        sompak_sammon   call SOM_PAK's Sammon program from Matlab
125
+%    sompak_sammon_gui   GUI for using SOM_PAK's Sammon program from Matlab
126
+%         sompak_train   call SOM_PAK's training program from Matlab
127
+%     sompak_train_gui   GUI for using SOM_PAK's training program from Matlab 
128
+% 
129
+% Visualization
130
+% 
131
+%             som_show   basic visualization
132
+%         som_show_add   add labels, hits and trajectories
133
+%       som_show_clear   remove extra markers
134
+%       som_recolorbar   refresh/reconfigure colorbars
135
+%         som_show_gui   GUI for using som_show and associated functions
136
+%             som_grid   visualization of SOM grid
137
+%           som_cplane   component planes and U-matrices
138
+%         som_barplane   bar chart visualization of map
139
+%         som_pieplane   pie chart visualization of map
140
+%        som_plotplane   plot chart visualization of map
141
+%       som_trajectory   launches a GUI for presenting comet-trajectories 
142
+%       som_dendrogram   visualization of clustering tree
143
+%       som_plotmatrix   pairwise scatter plots and histograms
144
+%    som_order_cplanes   order and visualize the component planes
145
+%           som_clplot   plots of clusters (based on cluster struct)
146
+% som_projections_plot   projections plots (see som_projections)
147
+%       som_stats_plot   plots of statistics (see som_stats)
148
+% 
149
+% Auxiliary functions for visualization
150
+% 
151
+%                 hits   calculates hits, or sum of values for each map unit
152
+%             som_hits   calculates the response of data on the map
153
+%             som_umat   calculates the U-matrix
154
+%                  cca   curvilinear component analysis projection algorithm
155
+%              pcaproj   principal component projection algorithm
156
+%               sammon   Sammon's mapping projection algorithm
157
+%       som_connection   connection matrix for map 
158
+%       som_vis_coords   map unit coordinates used in visualizations
159
+%        som_colorcode   create color coding for map/2D data
160
+%         som_bmucolor   colors of the BMUs from a given map color code
161
+%        som_normcolor   simulate indexed colormap
162
+%     som_clustercolor   color coding which depends on clustering structure
163
+%      som_kmeanscolor   color coding according to k-means clustering
164
+%     som_kmeanscolor2   a newer version of the som_kmeanscolor function
165
+%       som_fuzzycolor   a fuzzy color coding 
166
+%         som_coloring   a SOM-based color coding 
167
+%      som_projections   calculates a default set of projections
168
+% 
169
+% Report generation stuff
170
+% 
171
+%     som_table_struct   creates a table struct
172
+%     som_table_modify   modifies a table struct
173
+%      som_table_print   print a table in various formats
174
+%            rep_utils   various utilities for printing report elements
175
+%      som_stats_table   a table of data set statistics
176
+%     som_stats_report   report on data set statistics
177
+% 
178
+% Low level routines used by visualization functions
179
+% 
180
+%            vis_patch   defines hexagonal and rectangular patches
181
+%    vis_som_show_data   returns UserData and subplot handles stored by som_show.m
182
+%        vis_valuetype   used for type checks 
183
+%         vis_footnote   adds a movable text to the current figure 
184
+%          vis_trajgui   the actual GUI started by som_trajectory.m 
185
+% vis_PlaneAxisProperties   set axis properties in visualization functions
186
+% vis_footnoteButtonDownFcn   callback function for vis_footnote.m
187
+%     vis_planeGetArgs   converts topol struct to lattice, msize argument pair
188
+%    vis_show_gui_comp   internal function used by som_show_gui.m
189
+%    vis_show_gui_tool   internal function used by som_show_gui.m
190
+% 
191
+% Other
192
+% 
193
+%           somtoolbox   this file
194
+%            iris.data   IRIS data set (used in demos)
195
+%          License.txt   GNU General Public License 
196
+%        Copyright.txt   Copyright notice
... ...
@@ -0,0 +1,49 @@
1
+function vis_PlaneAxisProperties(ax,lattice,msize,pos)
2
+
3
+% VIS_PLANEAXISPROPERTIES Set axis properties for SOM_CPLANE, 
4
+%                         SOM_PIEPLANE, SOM_BARPLANE and SOM_PLOTPLANE.
5
+%
6
+% vis_PlaneAxisProperties(ax,lattice,msize,pos)
7
+%
8
+%  Input arguments: 
9
+%   ax        (scalar) axis handle     
10
+%   lattice   (string) 'hexa', 'rect', 'hexaU' or 'rectU'
11
+%             (matrix) defines the patch, see e.g. help vis_patch
12
+%   msize     (vector) a 1x2 vector defining the grid size
13
+%   pos       (vector) a 1x2 vector that determines position of
14
+%                      origin or NaN which means default operation: 
15
+%                      origin to [1 1] and tighten axis limits 
16
+%                      according to the grid size.
17
+% 
18
+% This is a subfunction for SOM_CPLANE, SOM_PIEPLANE, SOM_BARPLANE and
19
+% SOM_PLOTPLANE. This subfunction sets the proper values for axis.
20
+
21
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
22
+% http://www.cis.hut.fi/projects/somtoolbox/             
23
+
24
+% Version 2.0beta Johan 060799
25
+
26
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
27
+
28
+xdim=msize(1);ydim=msize(2);
29
+set(ax,'Visible','off');
30
+set(get(ax,'Title'),'Visible','on');
31
+set(ax,'XaxisLocation','Top');            % axis orientation
32
+set(ax,'xdir','normal');                  % = axis ij = matrix mode
33
+set(ax,'ydir','reverse'); 
34
+
35
+switch lattice
36
+case {'rect', 'rectU'}
37
+  lelim=-.51; rilim=.51; uplim=-.51; lolim=.51;  % axis limits
38
+  set(ax,'DataAspectRatio', [1 1 1]);            % =axis equal
39
+case {'hexa','hexaU'}
40
+  lelim=-.51; rilim=1.01; uplim=-.67; lolim=.67; % axis limits
41
+  set(ax,'DataAspectRatio',[0.9015 1 1]);        % this corrects hexagons
42
+end
43
+
44
+% Nan: default origin [1 1] & tighten the axis
45
+if isnan(pos)
46
+  set(ax,'XLim',[1+lelim ydim+rilim],'YLim',[1+uplim xdim+lolim], ...
47
+      'XLimMode','manual','YLimMode','manual'); % tighten the axis
48
+end
49
+
... ...
@@ -0,0 +1,101 @@
1
+function h=vis_footnote(txt)
2
+
3
+% VIS_FOOTNOTE Adds a movable text to the current figure
4
+%
5
+%  h = vis_footnote(T)
6
+%
7
+%  Input and output arguments ([]'s are optional)
8
+%   [T]  (string) text to be written
9
+%        (scalar) font size to use in all strings 
10
+%
11
+%   h    (vector) handles to axis objects created by this function 
12
+%
13
+% This function sets a text to the current figure. If T is a string,
14
+% it's written as it is to the same place. If T is a scalar, the font
15
+% size of all text objects created by this function are changed to the
16
+% pointsize T. If no input argument is given the function only returns
17
+% the handles to all objects created by this function. The texts may
18
+% be dragged to a new location at any time using mouse.  Note that the
19
+% current axis will be the parent of the text object after dragging.
20
+%
21
+% String 'Info' is set to the Tag property field of the objects. 
22
+% 
23
+% EXAMPLES
24
+%
25
+% % add movable texts to the current figure and change their
26
+% % fontsize to 20 points
27
+% vis_footnote('Faa'); vis_footnote('Foo'); vis_footnote(20);
28
+% 
29
+% % delete all objects created by this function from the current figure
30
+% delete(vis_footnote);
31
+% 
32
+% See also SOM_SHOW.
33
+
34
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
35
+% http://www.cis.hut.fi/projects/somtoolbox/             
36
+
37
+% Version 2.0beta Johan 080698
38
+
39
+%% Check arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
40
+
41
+error(nargchk(0, 1, nargin))  % check no. of input args
42
+
43
+%% Init %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
44
+
45
+% Get the handles to the existing Info-axes objects
46
+
47
+h_infotxt=findobj(gcf,'tag','Info','type','text');
48
+h_infoax=findobj(gcf,'tag','Info','type','axes');
49
+
50
+%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
51
+
52
+% If no arguments are given, return the old axes handles
53
+
54
+if nargin == 0 | isempty(txt),
55
+  ;  
56
+elseif ischar(txt)                    % text: set new text
57
+  [t,h_]=movetext(txt);
58
+  h_infoax=[h_; h_infoax];
59
+elseif vis_valuetype(txt,{'1x1'})      % scalar: change font size  
60
+  set(h_infotxt,'fontunits','points');
61
+  set(h_infotxt,'fontsize',txt);
62
+else
63
+  error('Input argument should be a string or a scalar.');
64
+end
65
+
66
+%% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
67
+
68
+if nargout>0     % output only if necessary
69
+  h=h_infoax;
70
+end
71
+
72
+%%% SUBFUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
73
+
74
+function [t,h]=movetext(txt)
75
+% Moves the text. See also VIS_FOOTNOTEBUTTONDOWNFCN
76
+%
77
+%
78
+initpos=[0.05 0.05 0.01 0.01];   
79
+
80
+memaxes = gca;                   % Memorize the gca
81
+
82
+%% Create new axis on the lower left corner.
83
+%% This will be the parent for the text object
84
+
85
+h = axes('position',initpos,'units','normalized');
86
+set(h,'visible','off');          % hide axis
87
+
88
+t = text(0,0,txt);               % write text 
89
+set(t,'tag','Info');             % set tag
90
+set(h,'tag','Info');             % set tag
91
+
92
+set(t,'verticalalignment','bottom');  % set text alignment
93
+set(t,'horizontalalignment','left');
94
+
95
+%% Set ButtonDownFcn
96
+
97
+set(t,'buttondownfcn','vis_footnoteButtonDownFcn') 
98
+
99
+axes(memaxes);                   % Reset original gca
100
+
101
+
... ...
@@ -0,0 +1,64 @@
1
+function vis_footnoteButtonDownFcn
2
+
3
+% VIS_FOOTNOTEBUTTONDOWNFCN Callback set by VIS_FOOTNOTE
4
+%
5
+%  som_showtitleButtonDownFcn
6
+%
7
+% Moves the axis of current callback object using DRAGRECT
8
+% command. This callback is set to all texts added to figures by 
9
+% VIS_FOOTNOTE function.
10
+%
11
+% See also DRAGRECT, SOM_SHOWTITLE.
12
+
13
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
14
+% http://www.cis.hut.fi/projects/somtoolbox/             
15
+
16
+% Version 2.0beta Johan 080698
17
+
18
+% Action
19
+
20
+[txt,fig]=gcbo;                     % Get text and figure handles
21
+ax=get(txt,'parent');               % Get axis handle
22
+
23
+memunits_fig=get(fig,'units');      % Get figure size in pixels
24
+set(gcf,'units','pixels'); 
25
+pos_fig=get(fig,'position');        
26
+
27
+memunits_txt=get(txt,'units');      % Get text field size in pixels
28
+set(txt,'units','pixels');            
29
+text_size=get(txt,'extent');
30
+
31
+memunits_ax=get(ax,'units');        % Get axis position in pixels
32
+set(ax,'units','pixels');          
33
+pos_ax=get(ax,'position');
34
+
35
+%%% Move text
36
+
37
+pos_final=dragrect([pos_ax(1:2) text_size(3:4)]);
38
+
39
+%%% Keep the text inside the figure!
40
+
41
+pos_final(1)=max(pos_final(1),0);
42
+pos_final(2)=max(pos_final(2),0);
43
+pos_final(1)=min(pos_final(1),pos_fig(3)-text_size(3));
44
+pos_final(2)=min(pos_final(2),pos_fig(4)-text_size(4));
45
+
46
+%%% Set new position
47
+
48
+new_pos=[pos_final(1:2) pos_ax(3:4)];
49
+set(ax,'position', new_pos);
50
+
51
+%%% Set the text on the top of the object stack 
52
+
53
+children=get(gcf,'children');
54
+i=find(ismember(children,ax));
55
+new_i=[i 1:i-1 i+1:length(children)];
56
+set(gcf,'children',children(new_i));
57
+
58
+set(txt,'position',[0 0 0]);
59
+set(fig,'units',memunits_fig);
60
+set(ax,'units',memunits_ax);
61
+set(txt,'units',memunits_txt);
62
+
63
+
64
+
... ...
@@ -0,0 +1,48 @@
1
+function S=vis_grid_struct
2
+
3
+% VIS_GRID_STRUCT Initiates and returns a default grid struct
4
+%
5
+%  S = vis_grid_struct
6
+%
7
+%  Output arguments:
8
+%   S       (struct) som_grid struct 
9
+%
10
+% Fields and their initial values: 
11
+%  S.type='som_grid';
12
+%  S.neigh=neigh;
13
+%  S.shape='sheet';
14
+%  S.msize=msize;
15
+%  S.coord=[];
16
+%  S.line='-';
17
+%  S.linecolor=[.8 .8 .8];
18
+%  S.linewidth=0.5;
19
+%  S.marker='o';
20
+%  S.markersize=6;
21
+%  S.markercolor='k';
22
+%  S.surf=[];
23
+%  S.label=[];
24
+%  S.labelcolor='g';
25
+%  S.labelsize=12;
26
+%
27
+% This is a subfunction for SOM_GRID. 
28
+
29
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
30
+% http://www.cis.hut.fi/projects/somtoolbox/             
31
+
32
+% Version 2.0beta Johan 090499
33
+
34
+S.type='som_grid';
35
+S.neigh='hexa';
36
+S.shape='sheet';
37
+S.msize=[1 1];
38
+S.coord=[];
39
+S.line='-';
40
+S.linecolor=[.8 .8 .8];
41
+S.linewidth=0.5;
42
+S.marker='o';
43
+S.markersize=6;
44
+S.markercolor='k';
45
+S.surf=[];
46
+S.label=[];
47
+S.labelcolor='g';
48
+S.labelsize=12;
... ...
@@ -0,0 +1,117 @@
1
+function p=vis_patch(lattice)
2
+
3
+% VIS_PATCH Defines the basic patches (hexa and rect) used in SOM_CPLANE
4
+%
5
+%  p = vis_patch(lattice)
6
+%
7
+%  Input and output arguments: 
8
+%   lattice   (string) 'rect', 'hexa' or 'hexagon'
9
+%
10
+%   p         (matrix) size Lx2, defines the vertices of the patch
11
+%
12
+% This function produces vertex coordinates for a patch presenting
13
+% a map unit in hexagonal or rectangular lattice with its centre in (0,0). 
14
+%
15
+% For more help, try 'type vis_patch' or check out online documentation.
16
+% See also SOM_CPLANE, PATCH.
17
+
18
+%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
19
+%
20
+% vis_patch
21
+%
22
+% SYNTAX
23
+%  
24
+%  p = vis_patch(lattice)
25
+% 
26
+% DESCRIPTION
27
+% 
28
+% Forms a map unit patch for SOM_CPLANE function. Mainly a subroutine
29
+% of SOM_CPLANE, although can be used for on its own as well.
30
+%
31
+% REQUIRED INPUT ARGUMENTS
32
+%
33
+% lattice (string)
34
+% 
35
+%    'hexa'  produces vertex coordiantes for a hexagoanl patch which 
36
+%            has its center on (0,0), unit width, and a height of
37
+%            1.3334 units. This is not a regular hexagon but such that
38
+%            the node which has topological coordinates (a,b) has its
39
+%            center in the visualization at coordinates (a,b) for odd
40
+%            a and at (a,b+.5) for even a. The non-regular look of the
41
+%            patch is taken care simply by changing the axis ratio.
42
+%
43
+%    'rect'  produces vertex coordinates for a uniform rectangular patch.
44
+%            having its center on (0,0) and unit sidelength. Used as a
45
+%            subfunction in SOM_CPLANE.
46
+%
47
+%    'hexagon' produces vertex coordinates for a regular hexagonal patch.
48
+%            It may be used in som_cplane if, for some reason, truly
49
+%            regular hexagons are needed instead of the default unit
50
+%            markers which are not uniform, but have integer
51
+%            y-coordinates in the lattice.
52
+%
53
+% OUTPUT ARGUMENTS
54
+%
55
+% p (matrix) The 2-dimensional vertex coordinates: 
56
+%
57
+%   case 'rect'        case 'hexa'                case 'hexagon'
58
+%    p=[[-.5 -.5];...     p=[[0     0.6667];...    p=[[0     0.5774];...
59
+%       [-.5  .5];...        [0.5   0.3333];...       [0.5   0.2887];...
60
+%       [ .5  .5];...        [0.5  -0.3333];...       [0.5  -0.2887];...
61
+%       [ .5 -.5]];          [0    -0.6667];...       [0    -0.5774];...
62
+%                            [-0.5 -0.3333];...       [-0.5 -0.2887];...
63
+%                            [-0.5  0.3333]];         [-0.5  0.2887]]; 
64
+%
65
+% EXAMPLES
66
+%
67
+%  som_cplane(vis_patch('rect'),[6 5],'none');
68
+%  % this produces the same result as som_cplane('rect',[6 5], 'none') 
69
+%  
70
+%  som_cplane(vis_patch('hexa'), vis_unit_coord('hexa',[6 5]), 'none');
71
+%  % produces in principle the same result as 
72
+%  % som_cplane(vis_patch('hexa'),[6 5],'none'), 
73
+%  % _but_ in this case the axis are not rescaled and the non-regular 
74
+%  % shape of hexagons can be seen.
75
+%
76
+%  som_cplane(vis_patch('hexagon'), som_unit_coords([6 5],'hexa'), 'none');
77
+%  % produces a truly regular hexa lattice 
78
+%
79
+% SEE ALSO 
80
+%
81
+%  vis_unit_coord   The default 'hexa' and 'rect' coordinates in visualizations
82
+%  som_unit_coords  Locations of units on the SOM grid.
83
+
84
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
85
+% http://www.cis.hut.fi/projects/somtoolbox/             
86
+
87
+% Version 2.0beta Johan 041099
88
+
89
+if ~ischar(lattice)
90
+  error('Input argument should be a string')
91
+else
92
+  switch lattice
93
+  case 'rect'
94
+    p=[[-.5 -.5]; ...
95
+      [-.5 .5];...
96
+      [.5 .5];...
97
+      [.5 -.5]];
98
+  case 'hexagon'
99
+    p=[[0 0.5774];...
100
+      [0.5 0.2887];...
101
+      [0.5 -0.2887];...
102
+      [0 -0.5774];...
103
+      [-0.5 -0.2887];...
104
+      [-0.5 0.2887]];
105
+  case 'hexa'
106
+    p=[[0 0.6667];...
107
+      [0.5 0.3333];...
108
+      [0.5 -0.3333];...
109
+      [0 -0.6667];...
110
+      [-0.5 -0.3333];...
111
+      [-0.5 0.3333]];
112
+  otherwise
113
+    error('Unknown lattice');
114
+  end
115
+end
116
+
117
+
... ...
@@ -0,0 +1,107 @@
1
+function [nargin_,varargout]=vis_planeGetArgs(varargin)
2
+
3
+% VIS_PLANEGETARGS Subfunction for som_*plane: extracts topolopy 
4
+%                  information from the first arguments.
5
+%
6
+% [nargin,varargout]=vis_planeGetArgs(varargin)
7
+%
8
+%  Input and output arguments: 
9
+%   varargin   (varies) arguments given to som_*plane function
10
+%   nargin_    (scalar) number of arguments that nargchk of som_*plane "should see"
11
+%                       +number_of_varargins if varargin{1} is not map/topol struct
12
+%                       +number_of_varargins+1 if varargin{2} is a map/topol struct
13
+%   varargout  (varies) the arguments that som_*plane "should see"
14
+%
15
+% Basically, this function allows topology information to be given 
16
+% in various ways: either as a map/topology struct, or as a argument pair:
17
+% lattice, msize. The topology is always converted into the (lattice, msize)
18
+% argument pair.
19
+%  - if first input argument (varargin{1}) is a map or topol struct 
20
+%    the function extracts lattice and msize fields to two first 
21
+%    output variables after 'nargin_'. 
22
+%  - otherwise it copies the input arguments to the output arguments 
23
+%    after 'nargin_'. 
24
+% If there are too many inputs (as compared to number of outputs), the 
25
+% last ones are ignored. If too few, they are replaced by empty values 
26
+% in outputs.
27
+%
28
+% Example of usage: 
29
+%   function definition: h = som_cplane(varargin)
30
+%   first code line:     [nargin,lattice,msize,color,size,pos]=vis_planeGetArgs(varargin);
31
+%
32
+% See also SOM_CPLANE, SOM_BARPLANE, SOM_PLOTPLANE, SOM_PIEPLANE.
33
+
34
+% Copyright (c) 2000 by the SOM toolbox programming team.
35
+% http://www.cis.hut.fi/projects/somtoolbox/             
36
+
37
+% Version 2.0beta Johan 240300
38
+
39
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
40
+
41
+nout=nargout-1;
42
+
43
+% Set first all varargins to contain empty (==default values in som_*plane)
44
+
45
+for i=1:nout, varargout{i}=[]; end
46
+
47
+nargin_ = nargin;
48
+% Struct: might be map or topol
49
+
50
+if isstruct(varargin{1}),
51
+
52
+  % Get topol from topol field
53
+  if isfield(varargin{1},'topol'), topol=varargin{1}.topol;
54
+  else topol=varargin{1}; % assume that this is topol struct 
55
+  end
56
+
57
+  if ~isstruct(topol),
58
+    % topol not a struct !?
59
+    warning('Field ''topol'' is not a struct.');
60
+    varargout{1}=varargin{1};
61
+    varargoutC=2;
62
+    nargin_ = nargin;
63
+  elseif ~isfield(topol,'msize') | ~isfield(topol,'lattice'),
64
+    % Field missing?!
65
+    warning('Invalid topology struct.');
66
+    varargout{1}=topol;
67
+    varargoutC=2;
68
+    nargin_ = nargin;
69
+  else
70
+    varargout{1}=topol.lattice;
71
+    varargout{2}=topol.msize;
72
+    % increment input arg. counter
73
+    varargoutC=3;
74
+    nargin_ = nargin+1;    
75
+  end
76
+
77
+elseif iscell(varargin{1}), 
78
+
79
+  c = varargin{1}; 
80
+  lattice = 'hexa'; shape = 'sheet'; msize = [1 1]; 
81
+  for i=1:length(c), 
82
+    if ischar(c{i}), 
83
+      switch c{i}, 
84
+      case {'hexa','hexaU','rect','rectU'}, lattice = c{i}; 
85
+      case {'sheet','cyl','toroid'}, shape = c{i}; 
86
+      end
87
+    else
88
+      msize = c{i}; 
89
+    end 
90
+  end
91
+  varargout{1} = lattice;
92
+  varargout{2} = msize;
93
+  varargoutC=3;
94
+  nargin_ = nargin+1;    
95
+
96
+else
97
+
98
+  % should be a lattice (string) 
99
+  varargout{1}=varargin{1};
100
+  varargoutC=2;
101
+  nargin_=nargin;
102
+
103
+end
104
+
105
+for i=2:nargin, varargout{varargoutC+i-2}=varargin{i}; end
106
+
107
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... ...
@@ -0,0 +1,702 @@
1
+function vis_show_gui_comp(h, indx, action,varargin)
2
+
3
+%VIS_SHOW_GUI_COMP is a subfunction of SOM_SHOW_GUI.
4
+%
5
+%  vis_show_gui_comp(handle, indx, action, varargin)
6
+%
7
+%  Input arguments:
8
+%     handle    (struct) 
9
+%     indx     (scalar)
10
+%     action    (string)
11
+%     varargin  (varies)
12
+% 
13
+% See also  SOM_SHOW_GUI.
14
+
15
+% Copyright (c) 2000 by Roman Feldman and Juha Vesanto
16
+% Contributed to SOM Toolbox on August 22nd, 2000
17
+% http://www.cis.hut.fi/projects/somtoolbox/
18
+ 
19
+% Version 2.0beta roman 160800 juuso 220800
20
+
21
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
22
+%                                    MAIN                                   %
23
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
24
+
25
+udata = get(h,'UserData');
26
+plot_array = udata.plot_array;
27
+l = length(plot_array);
28
+
29
+ %%%%%%
30
+% init %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
31
+ %%%%%%
32
+
33
+if (strcmp(action,'init'))
34
+
35
+  %---  color vars  ---
36
+    fig_color = [0.8 0.8 0.8];
37
+    bg_color1 = [0.701960784313725 0.701960784313725 0.701960784313725];
38
+    bg_color2 = [0.9 0.9 0.9];
39
+  %---  object position vars (in pixels) ---
40
+    % calculations based on case 'comp'
41
+    %% hint text
42
+    hint_dist1 = 98.17-(61.27+36.9);   % hint text lower edge and next lower frame upper edge
43
+    hint_dist2 = 123-(98.17+18.45);    % figure upper edge and hint text upper edge
44
+    %% general
45
+    dist1 = 67.42-61.27;               % general distance between frame edge and object in frame
46
+    %% frame + ok / cancel
47
+    frames_dist = 61.27-(8.38+36.9);
48
+    frames_dist2 = 8.38;
49
+    f_fr = [7.9 8.38 216.2 36.9];      % final frame
50
+    ok_pb = [17.1 15.76 75.9 22.14];
51
+    cancel_pb = [139 15.76 75.9 22.14];
52
+    %% objects
53
+    hint_txt = [230 18.45];           % hint text width and height
54
+    interp_cb = [98.9 24.6];
55
+    title_txt = [35 hint_txt(2)];
56
+    title_edit_h =  23.083;
57
+    var_pop = interp_cb;
58
+    list_lt = [130 130];
59
+    calc_txt = [list_lt(1) hint_txt(2)];
60
+    useall_pb = [50 interp_cb(2)];
61
+
62
+  if (length(indx) > 1)
63
+    errordlg({'Same options for multiple subplots', ...
64
+              'not yet available'},'Error in SOM_VIS: options');
65
+    return;
66
+
67
+  elseif (isempty(plot_array(1).args))
68
+    errordlg({'Try to select subplot first'}, ...
69
+              'Error in SOM_VIS: options');
70
+    return;
71
+
72
+  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
73
+  % 'comp'
74
+  %
75
+  elseif (strncmp('comp',plot_array(indx).args{1},4))
76
+    old_fig_n = watchon;
77
+    W = 230; H = 123;
78
+    units = get(h,'units');
79
+    set(h,'units','pixels');
80
+    fp = get(h,'Position');
81
+    fig_pos = [(fp(1)+fp(3)) ...
82
+               (fp(2)+fp(2)+fp(4)/2-H/2) ...
83
+               W ...
84
+               H];
85
+    o1 = sum(f_fr([2 4]))+frames_dist;
86
+    o2 = o1+dist1;
87
+    o3 = 2*dist1+interp_cb(2);
88
+    o4 = o1+o3+hint_dist1;
89
+    hint_text_pos = [1 o4 hint_txt];
90
+    frame1_pos = [f_fr(1) o1 f_fr(3) o3];
91
+    interp_pos = [ok_pb(1) o2 interp_cb];
92
+    frame2_pos = f_fr;
93
+    ok_pos = ok_pb;
94
+    cancel_pos = cancel_pb;
95
+    
96
+    fig_h = figure( ...
97
+      'Units','pixels', ...
98
+      'Position', fig_pos, ...
99
+      'Color',fig_color, ...
100
+      'NumberTitle','off', ...
101
+      'Name','component', ...
102
+      'MenuBar','none', ...
103
+      'Visible','off');
104
+
105
+    set( ...
106
+    uicontrol( ...                                                            %% hint
107
+      'Units','pixels', ...
108
+      'BackgroundColor',fig_color, ...
109
+      'HorizontalAlignment','center', ...
110
+      'Position',hint_text_pos, ...
111
+      'String','Options for component plane', ...
112
+      'Style','text'),'units','normalized');
113
+
114
+    set( ...
115
+    uicontrol( ...                                                            %% [frame]
116
+      'Units','pixels', ...
117
+      'Position',frame1_pos, ...
118
+      'Style','frame'),'units','normalized');
119
+
120
+    pr = udata.property{indx};
121
+    chkb_h =  uicontrol( ...                                                  %% interpolated
122
+      'Units','pixels', ...
123
+      'HorizontalAlignment','center', ...
124
+      'Position',interp_pos, ...
125
+      'Style','checkbox', ...
126
+      'String','interpolated', ...
127
+      'Value',pr{1});
128
+    set(chkb_h,'units','normalized');
129
+
130
+    set( ...
131
+    uicontrol( ...                                                            %% [frame]
132
+      'Units','pixels', ...
133
+      'Position',frame2_pos, ...
134
+      'Style','frame'),'units','normalized');
135
+
136
+    s = ['vis_show_gui_comp(', ...
137
+         mat2str(h), ',', mat2str(indx), ...
138
+         ',''comp'',' mat2str(fig_h) ')'];
139
+    set( ...
140
+    uicontrol( ...                                                            %% OK
141
+      'Units','pixels', ...
142
+      'Position',ok_pos, ...
143
+      'String','OK', ...
144
+      'Callback',s),'units','normalized');
145
+
146
+    set( ...
147
+    uicontrol( ...                                                            %% Cancel
148
+      'Units','pixels', ...
149
+      'Position',cancel_pos, ...
150
+      'String','Cancel', ...
151
+      'Callback',['close(' mat2str(fig_h) ')']),'units','normalized');
152
+
153
+    watchoff(old_fig_n);
154
+    tmp_udata = [chkb_h];
155
+    set(fig_h,'units','normalized', ...
156
+	      'Visible','on', ...
157
+              'UserData',tmp_udata, ...
158
+              'handlevisibility','off');
159
+
160
+  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
161
+  % 'umat'
162
+  %
163
+  elseif (strncmp('umat',plot_array(indx).args{1},4))
164
+    old_fig_n = watchon;
165
+    W = 230; H = 335.893;
166
+    units = get(h,'units');
167
+    set(h,'units','pixels');
168
+    fp = get(h,'Position');
169
+    fig_pos = [(fp(1)+fp(3)) ...
170
+               (fp(2)+fp(2)+fp(4)/2-H/2) ...
171
+               W ...
172
+               H];
173
+    o1 = sum(f_fr([2 4]))+frames_dist;
174
+    o2 = o1+dist1;
175
+    o3 = 2*dist1+list_lt(2)+calc_txt(2);
176
+    o4 = o2+list_lt(2);
177
+    o5 = sum(cancel_pb([1 3]))-useall_pb(1);
178
+    o6 = o2+o3/2-useall_pb(2)/2;
179
+    o7 = o1+o3+frames_dist2;
180
+    o8 = 2*dist1+interp_cb(2);
181
+    o9 = o7+dist1;
182
+    o10 = o7+o8+frames_dist2;;
183
+    o11 = 2*dist1+max(title_edit_h,title_txt(2));
184
+    o12 = W-(title_txt(1)+2*ok_pb(1));
185
+    o13 = o10+dist1+(title_edit_h-title_txt(2))/2;
186
+    o14 = o10+dist1;
187
+    if title_txt(2)>title_edit_h,
188
+      o13 = o10+dist1;
189
+      o14 = o13+(title_edit_h-title_txt(2))/2;
190
+    end
191
+    o15 = ok_pb(1)+title_txt(1);
192
+    o16 = o10+o11+hint_dist1;
193
+    hint_text_pos = [1 o16 hint_txt];
194
+    frame1_pos = [f_fr(1) o10 f_fr(3) o11];
195
+    title_text_pos = [ok_pb(1) o13 title_txt];
196
+    title_pos = [o15 o14 o12 title_edit_h];
197
+    frame2_pos = [f_fr(1) o7 f_fr(3) o8];
198
+    interp_pos = [ok_pb(1) o9 interp_cb];
199
+    frame3_pos = [f_fr(1) o1 f_fr(3) o3];
200
+    list_text_pos = [ok_pb(1) o4 calc_txt];
201
+    list_pos = [ok_pb(1) o2 list_lt];
202
+    use_all_pos = [o5 o6 useall_pb];
203
+    frame4_pos = f_fr;
204
+    ok_pos = ok_pb;
205
+    cancel_pos = cancel_pb;
206
+
207
+    fig_h = figure( ...
208
+      'Units','pixels', ...
209
+      'Position', fig_pos, ...
210
+      'Color',fig_color, ...
211
+      'NumberTitle','off', ...
212
+      'Name','U-matrix', ...
213
+      'MenuBar','none', ...
214
+      'Visible','off');
215
+
216
+    set( ...
217
+    uicontrol( ...                                                            %% hint
218
+      'Units','pixels', ...
219
+      'BackgroundColor',fig_color, ...
220
+      'HorizontalAlignment','center', ...
221
+      'Position',hint_text_pos, ...
222
+      'String','Options for U-matrix', ...
223
+      'Style','text'),'units','normalized');
224
+
225
+    set( ...
226
+    uicontrol( ...                                                            %% [frame]
227
+      'Units','pixels', ...
228
+      'Position',frame1_pos, ...
229
+      'Style','frame'),'units','normalized');
230
+
231
+    set( ...
232
+    uicontrol( ...                                                            %% title
233
+      'Units','pixels', ...
234
+      'Position',title_text_pos, ...
235
+      'BackgroundColor',bg_color1, ...
236
+      'HorizontalAlignment','left', ...
237
+      'Style','text', ...
238
+      'String','Title'),'units','normalized');
239
+
240
+    pr = udata.property{indx};
241
+    ed_h =  uicontrol( ...                                                    %% [edit]
242
+      'Units','pixels', ...
243
+      'Position',title_pos, ...
244
+      'FontSize',12, ...
245
+      'Style','edit', ...
246
+      'String',pr{2}, ...
247
+      'BackgroundColor',bg_color2);
248
+    set(ed_h,'units','normalized');
249
+
250
+    set( ...
251
+    uicontrol( ...                                                            %% [frame]
252
+      'Units','pixels', ...
253
+      'Position',frame2_pos, ...
254
+      'Style','frame'),'units','normalized');
255
+
256
+    chkb_h =  uicontrol( ...                                                  %% interpolated
257
+      'Units','pixels', ...
258
+      'Position',interp_pos, ...
259
+      'Style','checkbox', ...
260
+      'String','interpolated', ...
261
+      'Value',pr{1});
262
+    set(chkb_h,'units','normalized');
263
+
264
+    set( ...
265
+    uicontrol( ...                                                            %% [frame]
266
+      'Units','pixels', ...
267
+      'Position',frame3_pos, ...
268
+      'Style','frame'),'units','normalized');
269
+
270
+    set( ...
271
+    uicontrol( ...                                                            %% calculated from
272
+      'Units','pixels', ...
273
+      'BackgroundColor',bg_color1, ...
274
+      'HorizontalAlignment','left', ...
275
+      'Position',list_text_pos, ...
276
+      'String','calculated from', ...
277
+      'Style','text'),'units','normalized');
278
+
279
+    list1_h = uicontrol( ...                                                  %% [listbox]
280
+      'Units','pixels', ...
281
+      'BackgroundColor',bg_color2, ...
282
+      'Position',list_pos, ...
283
+      'String',udata.sM.comp_names, ...
284
+      'Style','listbox', ...
285
+      'Max',2, ...
286
+      'Value',pr{3});
287
+    set(list1_h,'units','normalized');
288
+
289
+    s = ['tmp=get(' mat2str(fig_h) ',''userdata'');set(tmp(3),''value'',' ...
290
+         mat2str(1:length(udata.sM.comp_names)) ');'];
291
+    set( ...
292
+    uicontrol( ...                                                            %% Use all
293
+      'Units','pixels', ...
294
+      'Position',use_all_pos, ...
295
+      'String','Use all', ...
296
+      'Callback',s),'units','normalized');
297
+
298
+    set( ...
299
+    uicontrol( ...                                                            %% [frame]
300
+      'Units','pixels', ...
301
+      'Position',frame4_pos, ...
302
+      'Style','frame'),'units','normalized');
303
+
304
+    s = ['vis_show_gui_comp(' ...
305
+         mat2str(h) ',' mat2str(indx) ...
306
+         ',''umat'',' mat2str(fig_h) ')'];
307
+    set( ...
308
+    uicontrol( ...                                                            %% OK
309
+      'Units','pixels', ...
310
+      'Position',ok_pos, ...
311
+      'String','OK', ...
312
+      'Callback',s),'units','normalized');
313
+
314
+    set( ...
315
+    uicontrol( ...                                                            %% Cancel
316
+      'Units','pixels', ...
317
+      'Position',cancel_pos, ...
318
+      'String','Cancel', ...
319
+      'Callback',['close(' mat2str(fig_h) ')']),'units','normalized');
320
+
321
+    watchoff(old_fig_n);
322
+    tmp_udata = [chkb_h ed_h list1_h];
323
+    set(fig_h,'units','normalized', ...
324
+	      'Visible','on', ...
325
+              'UserData', tmp_udata, ...
326
+              'handlevisibility','off');
327
+
328
+  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
329
+  % 'color'
330
+  %
331
+  elseif (strncmp('color',plot_array(indx).args{1},5))
332
+    old_fig_n = watchon;
333
+    W = 230; H = 212.043;
334
+    units = get(h,'units');
335
+    set(h,'units','pixels');
336
+    fp = get(h,'Position');
337
+    fig_pos = [(fp(1)+fp(3)) ...
338
+               (fp(2)+fp(2)+fp(4)/2-H/2) ...
339
+                W ...
340
+                H];
341
+    o1 = sum(f_fr([2 4]))+frames_dist;
342
+    o2 = o1+dist1;
343
+    o3 = 2*dist1+var_pop(2);
344
+    o4 = o1+o3+frames_dist2;
345
+    o5 = o4+dist1;
346
+    o6 = 2*dist1+interp_cb(2);
347
+    o7 = o4+o6+frames_dist2;
348
+    o8 = 2*dist1+max(title_edit_h,title_txt(2));
349
+    o9 = W-(title_txt(1)+2*ok_pb(1));
350
+    o10 = o7+dist1+(title_edit_h-title_txt(2))/2;
351
+    o11 = o7+dist1;
352
+    if title_txt(2)>title_edit_h,
353
+      o10 = o7+dist1;
354
+      o11 = o10+(title_edit_h-title_txt(2))/2;
355
+    end
356
+    o12 = ok_pb(1)+title_txt(1);
357
+    o13 = o7+o8+hint_dist1;
358
+    hint_text_pos = [1 o13 hint_txt];
359
+    frame1_pos = [f_fr(1) o7 f_fr(3) o8];
360
+    title_text_pos = [ok_pb(1) o10 title_txt];
361
+    title_pos = [o12 o11 o9 title_edit_h];
362
+    frame2_pos = [f_fr(1) o4 f_fr(3) o6];
363
+    interp_pos = [ok_pb(1) o5 interp_cb];
364
+    frame3_pos = [f_fr(1) o1 f_fr(3) o3];
365
+    popup_pos = [ok_pb(1) o2 var_pop];
366
+    frame4_pos = f_fr;
367
+    ok_pos = ok_pb;
368
+    cancel_pos = cancel_pb;
369
+        
370
+    fig_h = figure( ...
371
+      'Units','pixels', ...
372
+      'Position',fig_pos, ...
373
+      'Color',fig_color, ...
374
+      'NumberTitle','off', ...
375
+      'Name','color plane', ...
376
+      'MenuBar','none', ...
377
+      'Visible','off');
378
+
379
+    set( ...
380
+    uicontrol( ...                                                            %% hint
381
+      'Units','pixels', ...
382
+      'BackgroundColor',fig_color, ...
383
+      'HorizontalAlignment','center', ...
384
+      'Position',hint_text_pos, ...
385
+      'String','Options for colorplane', ...
386
+      'Style','text'),'units','normalized');
387
+
388
+    set( ...
389
+    uicontrol( ...                                                            %% [frame]
390
+      'Units','pixels', ...
391
+      'Position',frame1_pos, ...
392
+      'Style','frame'),'units','normalized');
393
+
394
+    set( ...
395
+    uicontrol( ...                                                            %% title
396
+      'Units','pixels', ...
397
+      'Position',title_text_pos, ...
398
+      'HorizontalAlignment','left', ...
399
+      'Style','text', ...
400
+      'String','Title'),'units','normalized');
401
+
402
+    pr = udata.property{indx};
403
+    ed_h =  uicontrol( ...                                                    %% [edit]
404
+      'Units','pixels', ...
405
+      'Position',title_pos, ...
406
+      'FontSize',12, ...
407
+      'Style','edit', ...
408
+      'String',pr{2}, ...
409
+      'BackgroundColor',bg_color2);
410
+    set(ed_h,'units','normalized');
411
+
412
+    set( ...
413
+    uicontrol( ...                                                            %% [frame]
414
+      'Units','pixels', ...
415
+      'Position',frame2_pos, ...
416
+      'Style','frame'),'units','normalized');
417
+
418
+    chkb_h =  uicontrol(  ...                                                 %% interpolated
419
+      'Units','pixels', ...
420
+      'Position',interp_pos, ...
421
+      'Style','checkbox', ...
422
+      'String','interpolated', ...
423
+      'Value',pr{1});
424
+    set(chkb_h,'units','normalized');
425
+
426
+    set( ...
427
+    uicontrol( ...                                                            %% [frame]
428
+      'Units','pixels', ...
429
+      'Position',frame3_pos, ...
430
+      'Style','frame'),'units','normalized');
431
+
432
+    popup1_h = uicontrol( ...                                                 %% [popup]
433
+      'Units','pixels', ...
434
+      'Max',2, ...
435
+      'Min',1, ...
436
+      'Position',popup_pos, ...
437
+      'String',pr{3}, ...
438
+      'Style','popupmenu', ...
439
+      'Value',pr{4});
440
+    s = ['tmp=get(' mat2str(fig_h) ',''userdata'');' ...
441
+         'vis_show_gui_tool([tmp(3) 6],''popup_select'');' ...
442
+         'u=get(' mat2str(h) ',''UserData'');' ...
443
+         'v=' mat2str(indx) ';' ...
444
+         'pr=u.property{v};' ...
445
+         'pr{3}=get(tmp(3),''string'');' ...
446
+         'pr{4}=get(tmp(3),''value'');' ...
447
+         'u.property{v}=pr;' ...
448
+         'set(' mat2str(h) ',''userdata'',u)'];
449
+    set(popup1_h,'units','normalized', ...
450
+                 'Callback',s);
451
+
452
+    set( ...
453
+    uicontrol( ...                                                            %% [frame]
454
+      'Units','pixels', ...
455
+      'Position',frame4_pos, ...
456
+      'Style','frame'),'units','normalized');
457
+
458
+    s = ['vis_show_gui_comp(', ...
459
+         mat2str(h), ',', mat2str(indx), ...
460
+         ',''color'',' mat2str(fig_h) ')'];
461
+    set( ...
462
+    uicontrol( ...                                                            %% OK
463
+      'Units','pixels', ...
464
+      'Position',ok_pos, ...
465
+      'String','OK', ...
466
+      'Callback',s),'units','normalized');
467
+
468
+    set( ...
469
+    uicontrol( ...                                                            %% Cancel
470
+      'Units','pixels', ...
471
+      'Position',cancel_pos, ...
472
+      'String','Cancel', ...
473
+      'Callback',['close(' mat2str(fig_h) ')']),'units','normalized');
474
+
475
+    watchoff(old_fig_n);
476
+    tmp_udata = [chkb_h ed_h popup1_h];
477
+    set(fig_h,'units','normalized', ...
478
+	      'Visible','on', ...
479
+              'UserData', tmp_udata, ...
480
+              'handlevisibility','off');
481
+
482
+  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
483
+  % 'empty'
484
+  %
485
+  elseif (strncmp('empty',plot_array(indx).args{1},5))
486
+    old_fig_n = watchon;
487
+    W = 230; H = 121.483;
488
+    units = get(h,'units');
489
+    set(h,'units','pixels');
490
+    fp = get(h,'Position');
491
+    fig_pos = [(fp(1)+fp(3)) ...
492
+               (fp(2)+fp(2)+fp(4)/2-H/2) ...
493
+               W ...
494
+               H]; 
495
+    o1 = sum(f_fr([2 4]))+frames_dist;
496
+    o2 = 2*dist1+max(title_edit_h,title_txt(2));
497
+    o3 = 2*dist1+interp_cb(2);
498
+    o4 = W-(title_txt(1)+2*ok_pb(1));
499
+    o5 = o1+dist1+(title_edit_h-title_txt(2))/2;
500
+    o6 = o1+dist1;
501
+    if title_txt(2)>title_edit_h,
502
+      o5 = o1+dist1;
503
+      o6 = o5+(title_edit_h-title_txt(2))/2;
504
+    end
505
+    o7 = ok_pb(1)+title_txt(1);
506
+    o8 = o1+o2+hint_dist1;
507
+    hint_text_pos = [1 o8 hint_txt];
508
+    frame1_pos = [f_fr(1) o1 f_fr(3) o3];
509
+    title_text_pos = [ok_pb(1) o5 title_txt];
510
+    title_pos = [o7 o6 o4 title_edit_h];
511
+    frame2_pos = f_fr;
512
+    ok_pos = ok_pb;
513
+    cancel_pos = cancel_pb;
514
+    
515
+    fig_h = figure( ...
516
+      'Units','pixels', ...
517
+      'Position', fig_pos, ...
518
+      'Color',fig_color, ...
519
+      'NumberTitle','off', ...
520
+      'Name','empty plane', ...
521
+      'MenuBar','none', ...
522
+      'Visible','off');
523
+
524
+    set( ...
525
+    uicontrol( ...                                                            %% hint
526
+      'Units','pixels', ...
527
+      'BackgroundColor',fig_color, ...
528
+      'HorizontalAlignment','center', ...
529
+      'Position',hint_text_pos, ...
530
+      'String','Options for empty plane', ...
531
+      'Style','text'),'units','normalized');
532
+
533
+    set( ...
534
+    uicontrol( ...                                                            %% [frame]
535
+      'Units','pixels', ...
536
+      'Position',frame1_pos, ...
537
+      'Style','frame'),'units','normalized');
538
+
539
+    set( ...
540
+    uicontrol( ...                                                            %% title
541
+      'Units','pixels', ...
542
+      'Position',title_text_pos, ...
543
+      'HorizontalAlignment','left', ...
544
+      'Style','text', ...
545
+      'String','Title'),'units','normalized');
546
+
547
+    pr = udata.property{indx};
548
+    ed_h =  uicontrol( ...                                                    %% [edit]
549
+      'Units','pixels', ...
550
+      'Position',title_pos, ...
551
+      'Style','edit', ...
552
+      'FontSize',12, ...
553
+      'String',pr{1}, ...
554
+      'BackgroundColor',bg_color2);
555
+    set(ed_h,'units','normalized');
556
+
557
+    set( ...
558
+    uicontrol( ...                                                            %% [frame]
559
+      'Units','pixels', ...
560
+      'Position',frame2_pos, ...
561
+      'Style','frame'),'units','normalized');
562
+
563
+    s = ['vis_show_gui_comp(', ...
564
+         mat2str(h) ',' mat2str(indx), ...
565
+         ',''empty'',' mat2str(fig_h) ')'];
566
+    set( ...
567
+    uicontrol( ...                                                            %% OK
568
+      'Units','pixels', ...
569
+      'Position',ok_pos, ...
570
+      'String','OK', ...
571
+      'Callback',s),'units','normalized');
572
+
573
+    set( ...
574
+    uicontrol( ...                                                            %% Cancel
575
+      'Units','pixels', ...
576
+      'Position',cancel_pos, ...
577
+      'String','Cancel', ...
578
+      'Callback',['close(' mat2str(fig_h) ')']),'units','normalized');
579
+
580
+    watchoff(old_fig_n);
581
+    tmp_udata = [ed_h];
582
+    set(fig_h,'units','normalized', ...
583
+	      'Visible','on', ...
584
+              'UserData', tmp_udata, ...
585
+              'handlevisibility','off');
586
+
587
+  end
588
+
589
+ %%%%%%
590
+% comp %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
591
+ %%%%%%
592
+elseif (strcmp(action,'comp'))
593
+  tmp_h = get(varargin{1},'UserData');
594
+  v = get(tmp_h,'Value');
595
+  pr = udata.property{indx};
596
+  if (v)
597
+    v = 'compi';
598
+    pr{1} = 1;
599
+  else
600
+    v = 'comp';
601
+    pr{1} = 0;
602
+  end
603
+  plot_array(indx).args{1} = v;
604
+  udata.plot_array = plot_array;
605
+  udata.property{indx} = pr;
606
+  set(h,'UserData',udata);
607
+  close(varargin{1});
608
+
609
+ %%%%%%
610
+% umat %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
611
+ %%%%%%
612
+elseif (strcmp(action,'umat'))
613
+  tmp_h = get(varargin{1},'UserData');
614
+  v = get(tmp_h(1),'Value');
615
+  pr = udata.property{indx};
616
+  if (v)
617
+    v = 'umati';
618
+    pr{1} = 1;
619
+  else
620
+    v = 'umat';
621
+    pr{1} = 0;
622
+  end
623
+  plot_array(indx).args{1} = v;
624
+
625
+  s = get(tmp_h(2),'String');
626
+  v = get(tmp_h(3),'Value');  % userdata
627
+  plot_array(indx).string = s;
628
+  if strcmp(s,'U-matrix')
629
+    plot_array(indx).args{2} = v;
630
+  else
631
+    plot_array(indx).args{2} = {v s};
632
+  end
633
+  pr{2} = s;
634
+  pr{3} = v;
635
+  udata.plot_array = plot_array;
636
+  udata.property{indx} = pr;
637
+  set(h,'UserData',udata);
638
+  set(udata.h(1),'String',{plot_array(:).string});
639
+  close(varargin{1});
640
+
641
+ %%%%%%%
642
+% color %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
643
+ %%%%%%%
644
+elseif (strcmp(action,'color'))
645
+  tmp_h = get(varargin{1},'UserData'); % tmp_h =  [chkb_h ed_h popup1_h];
646
+
647
+  v = get(tmp_h(1),'Value');
648
+  pr = udata.property{indx};
649
+  if (v)
650
+    v = 'colori';
651
+    pr{1} = 1;
652
+  else
653
+    v = 'color';
654
+    pr{1} = 0;
655
+  end
656
+  plot_array(indx).args{1} = v;
657
+
658
+  v = get(tmp_h(3),'Value');
659
+  s = get(tmp_h(3),'string');
660
+  if v>5 & ~strcmp(s{v},'-variable-'),
661
+    m = evalin('base',s{v});
662
+  elseif ~strcmp(s{v},'-variable-'),
663
+    m = som_colorcode(udata.sM,s{v});
664
+  end
665
+  plot_array(indx).args{2} = m;
666
+  pr{3} = s;
667
+  s = get(tmp_h(2),'String');
668
+  plot_array(indx).string = s;
669
+  if ~strcmp(s,'Color code')
670
+    plot_array(indx).args{2} = ...
671
+        {plot_array(indx).args{2} s};
672
+  end
673
+  pr{2} = s;
674
+  pr{4} = v;
675
+  udata.plot_array = plot_array;
676
+  udata.property{indx} = pr;
677
+  set(h,'UserData',udata);
678
+  set(udata.h(1),'String',{plot_array(:).string});
679
+  close(varargin{1});
680
+
681
+ %%%%%%%
682
+% empty %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
683
+ %%%%%%%
684
+elseif (strcmp(action,'empty'))
685
+  pr = udata.property{indx};
686
+  tmp_h = get(varargin{1},'UserData');
687
+  s = get(tmp_h,'String');
688
+  pr{1} = s;
689
+  plot_array(indx).string = s;
690
+  plot_array(indx).args{2} = s;
691
+  udata.plot_array = plot_array;
692
+  udata.property{indx} = pr;
693
+  set(h,'UserData',udata);
694
+  set(udata.h(1),'String',{plot_array(:).string});
695
+  close(varargin{1});
696
+
697
+else
698
+
699
+end
700
+
701
+
702
+
... ...
@@ -0,0 +1,2085 @@
1
+function r=vis_show_gui_tool(h,action,varargin)
2
+
3
+%VIS_SHOW_GUI_TOOL is a subfunction of SOM_SHOW_GUI.
4
+%
5
+%  r = vis_show_gui_tool(handle, action, varargin)
6
+%
7
+%  Input arguments:
8
+%     handle    (struct) 
9
+%     action    (string)
10
+%     varargin  (varies)
11
+% 
12
+% See also  SOM_SHOW_GUI.
13
+
14
+% Copyright (c) 2000 by Roman Feldman and Juha Vesanto
15
+% Contributed to SOM Toolbox on August 22nd, 2000
16
+% http://www.cis.hut.fi/projects/somtoolbox/
17
+ 
18
+% Version 2.0beta roman 160800 juuso 220800
19
+
20
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
21
+
22
+if ishandle(h(1)),
23
+  udata = get(h(1),'UserData');
24
+  if isfield(udata,'plot_array'),
25
+    plot_array = udata.plot_array;
26
+    if isfield(udata,'vis_h')
27
+      % get most recent plotted
28
+      children = get(0,'children');
29
+      %  first refresh plot info
30
+      udata.vis_h = setdiff(udata.vis_h,setdiff(udata.vis_h,children));
31
+      set(h(1),'userdata',udata);
32
+      for i=1:length(children),
33
+        if any(children(i)==udata.vis_h),
34
+          child = children(i);
35
+          [handles,msg,lattice,msize,dim]=vis_som_show_data('all',children(i));
36
+          break;
37
+        elseif i==length(children),
38
+          errordlg({'Plot not found', ...
39
+                    'Try to visualize first'},'Error in SOM_VIS: tools');
40
+          return;
41
+        end
42
+      end
43
+    else
44
+      errordlg({'Plot not found', ...
45
+                'Try to visualize first'},'Error in SOM_VIS: tools');
46
+      return;
47
+    end
48
+  end
49
+end
50
+
51
+%---  color vars  ---
52
+  fig_color = [0.8 0.8 0.8];
53
+  bg_color1 = [0.701960784313725 0.701960784313725 0.701960784313725];
54
+  bg_color2 = [0.9 0.9 0.9];
55
+%---  object position vars (in pixels) ---
56
+  % calculations based on case 'comp'
57
+  %% hint text
58
+  hint_dist1 = 98.17-(61.27+36.9);   % hint text lower edge and next lower frame upper edge
59
+  hint_dist2 = 123-(98.17+18.45);    % figure upper edge and hint text upper edge
60
+  %% general
61
+  dist1 = 67.42-61.27;               % general distance between frame edge and object in frame
62
+  %% frame + ok / cancel
63
+  frames_dist = 61.27-(8.38+36.9);
64
+  frames_dist2 = 8.38;
65
+  f_fr = [7.9 8.38 216.2 36.9];      % final frame
66
+  ok_pb = [17.1 15.76 75.9 22.14];
67
+  cancel_pb = [139 15.76 75.9 22.14];
68
+  %% objects
69
+  hint_txt = [460 18.45];           % hint text width and height
70
+  interp_cb = [98.9 24.6];
71
+  title_txt = [90 hint_txt(2)-3];
72
+  title_edit_h =  23.083;
73
+  var_pop = [interp_cb(1) ok_pb(4)];
74
+  list_lt = [130 130];
75
+  calc_txt = [list_lt(1) hint_txt(2)];
76
+  selvar_pb = [110 ok_pb(4)];
77
+  strd_ed = [var_pop(1) title_edit_h];
78
+  radio_rb = selvar_pb;
79
+  
80
+ %%%%%%%%%%%
81
+% add_label %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
82
+ %%%%%%%%%%%
83
+if strcmp(action,'add_label')
84
+  old_fig_n = watchon;
85
+  W = 345.4; H = 222.769;
86
+  o21 = zeros(1,4);
87
+  o21(1) = (W-f_fr(3))/2;
88
+  f_fr = [7.9 8.38 (W-2*7.9) 36.9];      % final frame
89
+  cancel_pb = [(W-(ok_pb(1)+75.9)) 15.76 75.9 22.14];
90
+  hint_txt = [W 18.45];           % hint text width and height
91
+  units = get(h,'units');
92
+  set(h,'units','pixels');
93
+  fp = get(h,'Position');
94
+  fig_pos = [(fp(1)+fp(3)) ...
95
+             (fp(2)+fp(2)+fp(4)/2-H/2) ...
96
+             W ...
97
+             H];
98
+  o1 = sum(f_fr([2 4]))+frames_dist;
99
+  o2 = 4*dist1+2*max([title_edit_h,title_txt(2)]) ...
100
+      +max([title_txt(2),var_pop(2)]);
101
+  o6 = max([title_txt(2),var_pop(2)]);
102
+  o7 = max([title_txt(2),title_edit_h]);
103
+  o8 = max([title_txt(2),title_edit_h,selvar_pb(2)]);
104
+  o3 = o1+0.5*o6+dist1-title_txt(2)/2;
105
+  o4 = o1+0.5*o6+dist1-var_pop(2)/2;  
106
+  o5 = ok_pb(1)+title_txt(1);
107
+  o9 = o1+o6+0.5*o7+2*dist1-title_txt(2)/2;
108
+  o10 = o1+o6+0.5*o7+2*dist1-title_edit_h/2;;
109
+  o11 = o1+o6+o7+0.5*o8+3*dist1-title_txt(2)/2;
110
+  o12 = o1+o6+o7+0.5*o8+3*dist1-title_edit_h/2;
111
+  o13 = o1+o6+o7+0.5*o8+3*dist1-selvar_pb(2)/2;
112
+  o15 = o1+o2+frames_dist2;
113
+  o16 = 2*dist1+o7;
114
+  o17 = o5+strd_ed(1)+2*dist1; % W-ok_pb(1)-selvar_pb(1);
115
+  o18 = o15+0.5*o7+dist1-title_txt(2)/2;
116
+  o19 = o15+0.5*o7+dist1-title_edit_h/2;
117
+  o20 = o15+o16+hint_dist1;
118
+  hint_text_pos = [1 o20 hint_txt];
119
+  frame1_pos = [f_fr(1) o15 f_fr(3) o16];
120
+  subplots_text_pos = [ok_pb(1) o18 title_txt];
121
+  subplots_pos = [o5 o19 strd_ed];
122
+  frame2_pos = [f_fr(1) o1 f_fr(3) o2];
123
+  labels_text_pos = [ok_pb(1) o11 title_txt];
124
+  labels_pos = [o5 o12 strd_ed];
125
+  sel_var_pos = [o17 o13 selvar_pb];
126
+  text_size_text_pos = [ok_pb(1) o9 title_txt];
127
+  text_size_pos = [o5 o10  strd_ed];
128
+  text_color_text_pos = [ok_pb(1) o3 title_txt];
129
+  text_color_pos = [o5 o4 var_pop];
130
+  f_fr = [7.9 8.38 216.2 36.9];      % final frame
131
+  cancel_pb = [139 15.76 75.9 22.14];
132
+  frame3_pos = f_fr+o21;
133
+  ok_pos = ok_pb+o21;
134
+  cancel_pos = cancel_pb+o21;
135
+
136
+  fig_h = figure( ...
137
+    'Units','pixels', ...
138
+    'Position', fig_pos, ...
139
+    'Color',fig_color, ...
140
+    'NumberTitle','off', ...
141
+    'Name','add label', ...
142
+    'MenuBar','none', ...
143
+    'Visible','off');
144
+
145
+    set( ...
146
+    uicontrol( ...                                                            %% hint
147
+      'Units','pixels', ...
148
+      'BackgroundColor',fig_color, ...
149
+      'HorizontalAlignment','center', ...
150
+      'Position',hint_text_pos, ...
151
+      'String','Options for adding labels', ...
152
+      'Style','text'),'units','normalized');
153
+
154
+  set( ...
155
+  uicontrol( ...                                                            %% [frame]
156
+    'Units','pixels', ...
157
+    'Position',frame1_pos, ...
158
+    'Style','frame'),'units','normalized');
159
+
160
+  set( ...
161
+  uicontrol( ...                                                            %% To subplot(s)
162
+    'Units','pixels', ...
163
+    'Position',subplots_text_pos, ...
164
+    'HorizontalAlignment','left', ...
165
+    'String','To subplot(s)', ...
166
+    'Style','text'),'units','normalized');
167
+
168
+  ed1_h = uicontrol( ...                                                    %% [edit]
169
+    'Units','pixels', ...
170
+    'BackgroundColor',bg_color2, ...
171
+    'Position',subplots_pos, ...
172
+    'FontSize',12, ...
173
+    'Style','edit');
174
+  set(ed1_h,'units','normalized');
175
+
176
+  set( ...
177
+  uicontrol( ...                                                            %% [frame]
178
+    'Units','pixels', ...
179
+    'Position',frame2_pos, ...
180
+    'Style','frame'),'units','normalized');
181
+
182
+  set( ...
183
+  uicontrol( ...                                                            %% Labels
184
+    'Units','pixels', ...
185
+    'Position',labels_text_pos, ...
186
+    'HorizontalAlignment','left', ...
187
+    'String','Labels', ...
188
+    'Style','text'),'units','normalized');
189
+
190
+  ed2_h = uicontrol( ...                                                    %% [edit]
191
+    'Units','pixels', ...
192
+    'BackgroundColor',bg_color2, ...
193
+    'Position',labels_pos, ...
194
+    'FontSize',12, ...
195
+    'Style','edit');
196
+  set(ed2_h,'units','normalized');
197
+
198
+  s = ['tmp=get(' mat2str(fig_h) ',''userdata'');' ...
199
+       'vis_show_gui_tool(tmp(2),''select'')'];
200
+  set( ...
201
+  uicontrol( ...                                                            %% Select variable
202
+    'Units','pixels', ...
203
+    'Position',sel_var_pos, ...
204
+    'String','Select variable', ...
205
+    'Callback',s),'units','normalized');
206
+
207
+  set( ...
208
+  uicontrol( ...                                                            %% Text size
209
+    'Units','pixels', ...
210
+    'Position',text_size_text_pos, ...
211
+    'HorizontalAlignment','left', ...
212
+    'String','Text size', ...
213
+    'Style','text'),'units','normalized');
214
+
215
+  ed3_h = uicontrol( ...                                                    %% [edit]
216
+    'Units','pixels', ...
217
+    'BackgroundColor',bg_color2, ...
218
+    'Position',text_size_pos, ...
219
+    'String','10', ...
220
+    'FontSize',12, ...
221
+    'Style','edit');
222
+  set(ed3_h,'units','normalized');
223
+
224
+  set( ...
225
+  uicontrol( ...                                                            %% Text color
226
+    'Units','pixels', ...
227
+    'Position',text_color_text_pos, ...
228
+    'HorizontalAlignment','left', ...
229
+    'String','Text color', ...
230
+    'Style','text'),'units','normalized');
231
+
232
+  ud = {'k' 'w' 'y' 'm' 'c' 'r' 'g' 'b' 'xor' 'none'};
233
+  s = {'black' 'white' 'yellow' 'magenta' 'cyan' 'red' 'green' ...
234
+       'blue' 'xor' 'none'};
235
+  p_h = uicontrol( ...                                                      %% [popupmenu]
236
+    'Units','pixels', ...
237
+    'Position',text_color_pos, ...
238
+    'UserData',ud, ...
239
+    'String',s, ...
240
+    'Style','popupmenu');
241
+  set(p_h,'units','normalized');
242
+
243
+  set( ...
244
+  uicontrol( ...                                                            %% [frame]
245
+    'Units','pixels', ...
246
+    'Position',frame3_pos, ...
247
+    'Style','frame'),'units','normalized');
248
+
249
+  s = ['vis_show_gui_tool(' mat2str(h) ',''label'',' mat2str(fig_h) ')'];
250
+  set( ...
251
+  uicontrol( ...                                                            %% OK
252
+    'Units','pixels', ...
253
+    'Position',ok_pos, ...
254
+    'String','OK', ...
255
+    'Callback',s),'units','normalized');
256
+
257
+  set( ...
258
+  uicontrol( ...                                                            %% Cancel
259
+    'Units','pixels', ...
260
+    'Position',cancel_pos, ...
261
+    'String','Cancel', ...
262
+    'Callback',['close(' mat2str(fig_h) ')']),'units','normalized');
263
+
264
+  watchoff(old_fig_n);
265
+  ud = [ed1_h ed2_h ed3_h p_h];
266
+  set(fig_h,'units','normalized', ...
267
+            'Visible','on', ...
268
+            'UserData',ud, ...
269
+            'handlevisibility','off');
270
+
271
+ %%%%%%%%%
272
+% add_hit %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
273
+ %%%%%%%%%
274
+elseif strcmp(action,'add_hit')
275
+  old_fig_n = watchon;
276
+  W = 424.3; H = 337.642;
277
+  o37 = zeros(1,4);
278
+  o37(1) = (W-f_fr(3))/2;
279
+  f_fr = [7.9 8.38 (W-2*7.9) 36.9];      % final frame
280
+  cancel_pb = [(W-(ok_pb(1)+75.9)) 15.76 75.9 22.14];
281
+  hint_txt = [W 18.45];           % hint text width and height
282
+  units = get(h,'units');
283
+  set(h,'units','pixels');
284
+  fp = get(h,'Position');
285
+  fig_pos = [(fp(1)+fp(3)) ...
286
+             (fp(2)+fp(2)+fp(4)/2-H/2) ...
287
+             W ...
288
+             H];
289
+  o1 = sum(f_fr([2 4]))+frames_dist;
290
+  o2 = o1+dist1;
291
+  o6 = max([title_txt(2),var_pop(2)]);
292
+  o7 = max([title_txt(2),title_edit_h]);
293
+  o8 = max([title_txt(2),title_edit_h,var_pop(2)]);
294
+  o38 = max([title_txt(2),title_edit_h,selvar_pb(2)]);
295
+  o3 = o8+o6+3*dist1;
296
+  o4 = o1+0.5*o8+dist1-title_txt(2)/2;
297
+  o5 = o1+0.5*o8+dist1-var_pop(2)/2;
298
+  o9 = o1+0.5*o8+dist1-title_edit_h/2;
299
+  o21 = o1+o8+0.5*o6+2*dist1-title_txt(2)/2;
300
+  o22 = o1+o8+0.5*o6+2*dist1-var_pop(2)/2;
301
+  o20 = ok_pb(1)+title_txt(1);
302
+  o10 = o20+var_pop(1)+2*dist1;
303
+  o11 = o10+title_txt(1);
304
+  o12 = o2+o8+dist1+0.5*o6-title_txt(2)/2;
305
+  o13 = o2+o8+dist1+0.5*o6-var_pop(2)/2;
306
+  o14 = o1+o3+frames_dist2;
307
+  o15 = 2*o6+o8+4*dist1;
308
+  o16 = o14+dist1+0.5*o6-title_txt(2)/2;
309
+  o17 = o14+dist1+0.5*o6-var_pop(2)/2;
310
+  o18 = o14+o6+2*dist1+0.5*o8-title_txt(2)/2;
311
+  o19 = o14+o6+2*dist1+0.5*o8-title_edit_h/2;
312
+  o23 = o14+o6+2*dist1+0.5*o8-var_pop(2)/2;
313
+  o24 = o14+o6+3*dist1+o8+0.5*o6-title_txt(2)/2;
314
+  o25 = o14+o6+3*dist1+o8+0.5*o6-var_pop(2)/2;
315
+  o26 = o14+o15+frames_dist2;
316
+  o27 = o8+2*dist1;
317
+  o28 = o26+dist1+0.5*o38-title_txt(2)/2;
318
+  o29 = o26+dist1+0.5*o38-title_edit_h/2;
319
+  o30 = o26+dist1+0.5*o38-selvar_pb(2)/2;
320
+  o31 = o10; %W-(ok_pb(1)+selvar_pb(1));
321
+  o32 = o26+o27+frames_dist2;
322
+  o33 = o7+2*dist1;
323
+  o34 = o32+dist1+0.5*o7-title_txt(2)/2;
324
+  o35 = o32+dist1+0.5*o7-title_edit_h/2;
325
+  o36 = o32+o33+hint_dist1;
326
+  hint_text_pos = [1 o36 hint_txt];
327
+  frame1_pos = [f_fr(1) o32 f_fr(3) o33];
328
+  subplots_text_pos = [ok_pb(1) o34 title_txt];
329
+  subplots_pos = [o20 o35 strd_ed];
330
+  frame2_pos = [f_fr(1) o26 f_fr(3) o27];
331
+  trace_vect_text_pos = [ok_pb(1) o28 title_txt];
332
+  trace_vect_pos = [o20 o29 strd_ed];
333
+  sel_vect_pos = [o31 o30 selvar_pb];
334
+  frame3_pos = [f_fr(1) o14 f_fr(3) o15];
335
+  marker_text_pos = [ok_pb(1) o24 title_txt];
336
+  marker_pos = [o20 o25 var_pop];
337
+  marker_size_text_pos = [ok_pb(1) o18 title_txt];
338
+  marker_size_pos = [o20 o19 strd_ed];
339
+  size_fact_text_pos = [o10 o18 title_txt];
340
+  size_fact_pos = [o11 o23 var_pop];
341
+  marker_color_text_pos = [ok_pb(1) o16 title_txt];
342
+  marker_color_pos = [o20 o17 var_pop];
343
+  edge_color_text_pos = [o10 o16 title_txt];
344
+  edge_color_pos = [o11 o17 var_pop];
345
+  frame4_pos = [f_fr(1) o1 f_fr(3) o3];
346
+  text_text_pos = [ok_pb(1) o21 title_txt];
347
+  text_pos = [o20 o22 var_pop];
348
+  text_color_text_pos = [ok_pb(1) o4 title_txt];
349
+  text_color_pos = [o20 o5 var_pop];
350
+  text_size_text_pos = [o10 o4 title_txt];
351
+  text_size_pos = [o11 o9 strd_ed];
352
+  f_fr = [7.9 8.38 216.2 36.9];      % final frame
353
+  cancel_pb = [139 15.76 75.9 22.14];
354
+  frame5_pos = f_fr+o37;
355
+  ok_pos = ok_pb+o37;
356
+  cancel_pos = cancel_pb+o37;
357
+
358
+  fig_h = figure( ...
359
+    'Units','pixels', ...
360
+    'Position', fig_pos, ...
361
+    'Color',fig_color, ...
362
+    'NumberTitle','off', ...
363
+    'Name','add hit histogram', ...
364
+    'MenuBar','none', ...
365
+    'Visible','off');
366
+
367
+    set( ...
368
+    uicontrol( ...                                                            %% hint
369
+      'Units','pixels', ...
370
+      'BackgroundColor',fig_color, ...
371
+      'HorizontalAlignment','center', ...
372
+      'Position',hint_text_pos, ...
373
+      'String','Options for adding hit histogram', ...
374
+      'Style','text'),'units','normalized');
375
+
376
+  set( ...
377
+  uicontrol( ...                                                            %% [frame]
378
+    'Units','pixels', ...
379
+    'Position',frame1_pos, ...
380
+    'Style','frame'),'units','normalized');
381
+
382
+  set( ...
383
+  uicontrol( ...                                                            %% To subplot(s)
384
+    'Units','pixels', ...
385
+    'Position',subplots_text_pos, ...
386
+    'HorizontalAlignment','left', ...
387
+    'String','To subplot(s)', ...
388
+    'Style','text'),'units','normalized');
389
+
390
+  ed1_h = uicontrol( ...                                                    %% [edit]
391
+    'Units','pixels', ...
392
+    'BackgroundColor',bg_color2, ...
393
+    'Position',subplots_pos, ...
394
+    'FontSize',12, ...
395
+    'Style','edit');
396
+  set(ed1_h,'units','normalized');
397
+
398
+  set( ...
399
+  uicontrol( ...                                                            %% [frame]
400
+    'Units','pixels', ...
401
+    'Position',frame2_pos, ...
402
+    'Style','frame'),'units','normalized');
403
+
404
+  set( ...
405
+  uicontrol( ...                                                            %% Trace vector
406
+    'Units','pixels', ...
407
+    'Position',trace_vect_text_pos, ...
408
+    'HorizontalAlignment','left', ...
409
+    'String','Hit vector', ...
410
+    'Style','text'),'units','normalized');
411
+
412
+  ed2_h = uicontrol( ...                                                    %% [edit]
413
+    'Units','pixels', ...
414
+    'BackgroundColor',bg_color2, ...
415
+    'Position',trace_vect_pos, ...
416
+    'FontSize',12, ...
417
+    'Style','edit');
418
+  set(ed2_h,'units','normalized');
419
+
420
+  s = ['tmp=get(' mat2str(fig_h) ',''userdata'');' ...
421
+       'vis_show_gui_tool(tmp(2),''select'')'];
422
+  set( ...
423
+  uicontrol( ...                                                            %% Select variable
424
+    'Units','pixels', ...
425
+    'Position',sel_vect_pos, ...
426
+    'String','Select variable', ...
427
+    'Callback',s),'units','normalized');
428
+
429
+  set( ...
430
+  uicontrol( ...                                                            %% [frame]
431
+    'Units','pixels', ...
432
+    'Position',frame3_pos, ...
433
+    'Style','frame'),'units','normalized');
434
+
435
+  set( ...
436
+  uicontrol( ...                                                            %% Marker
437
+    'Units','pixels', ...
438
+    'Position',marker_text_pos, ...
439
+    'HorizontalAlignment','left', ...
440
+    'String','Marker', ...
441
+    'Style','text'),'units','normalized');
442
+
443
+  s = {'lattice' 'o' '.' 'x' '+' '*' 's' 'd' 'v' '^' ...
444
+       '<' '>' 'p' 'h' 'none' 'cell array'};
445
+  p3_h = uicontrol( ...                                                     %% [popupmenu]
446
+    'Units','pixels', ...
447
+    'Position',marker_pos, ...
448
+    'String',s, ...
449
+    'Style','popupmenu');
450
+  s = ['tmp=get(' mat2str(fig_h) ',''userdata'');' ...
451
+       'vis_show_gui_tool([tmp(6),16],''popup_select'')'];
452
+  set(p3_h,'units','normalized','Callback',s);
453
+
454
+  set( ...
455
+  uicontrol( ...                                                            %% Marker size
456
+    'Units','pixels', ...
457
+    'HorizontalAlignment','left', ...
458
+    'Position',marker_size_text_pos, ...
459
+    'String','Marker size', ...
460
+    'Style','text'),'units','normalized');
461
+
462
+  ed4_h = uicontrol( ...                                                    %% [edit]
463
+    'Units','pixels', ...
464
+    'BackgroundColor',bg_color2, ...
465
+    'Position',marker_size_pos, ...
466
+    'String','12', ...
467
+    'FontSize',12, ...
468
+    'Style','edit');
469
+  set(ed4_h,'units','normalized','Callback',s);
470
+
471
+  set( ...
472
+  uicontrol( ...                                                            %% Size factor
473
+    'Units','pixels', ...
474
+    'HorizontalAlignment','left', ...
475
+    'Position',size_fact_text_pos, ...
476
+    'String','Size factor', ...
477
+    'Style','text'),'units','normalized');
478
+
479
+  s = {'common' 'separate'};
480
+  p4_h = uicontrol( ...                                                     %% [popupmenu]
481
+    'Units','pixels', ...
482
+    'Position',size_fact_pos, ...
483
+    'String',s, ...
484
+    'Style','popupmenu');
485
+  set(p4_h,'units','normalized');
486
+
487
+
488
+  set( ...
489
+  uicontrol( ...                                                            %% Marker color
490
+    'Units','pixels', ...
491
+    'HorizontalAlignment','left', ...
492
+    'Position',marker_color_text_pos, ...
493
+    'String','Marker color', ...
494
+    'Style','text'),'units','normalized');
495
+
496
+  ud = {'w' 'k' 'y' 'm' 'c' 'r' 'g' 'b' 'none' ''};
497
+  s = {'white' 'black' 'yellow' 'magenta' 'cyan' ...
498
+       'red' 'green' 'blue' 'none' '-matrix-'};
499
+  p5_h = uicontrol( ...                                                     %% [popupmenu]
500
+    'Units','pixels', ...
501
+    'Position',marker_color_pos, ...
502
+    'UserData',ud, ...
503
+    'String',s, ...
504
+    'Style','popupmenu');
505
+  s = ['tmp=get(' mat2str(fig_h) ',''userdata'');' ...
506
+      'vis_show_gui_tool([tmp(9) 10],''popup_select'')'];
507
+  set(p5_h,'units','normalized','Callback',s);
508
+
509
+  set( ...
510
+  uicontrol( ...                                                            %% EdgeColor
511
+    'Units','pixels', ...
512
+    'Position',edge_color_text_pos, ...
513
+    'HorizontalAlignment','left', ...
514
+    'String','Edge color', ...
515
+    'Style','text'),'units','normalized');
516
+
517
+  ud = {'none' 'w' 'k' 'y' 'm' 'c' 'r' 'g' 'b'};
518
+  s = {'none' 'white' 'black' 'yellow' 'magenta' 'cyan' ...
519
+       'red' 'green' 'blue'};
520
+  p6_h = uicontrol( ...                                                     %% [popupmenu]
521
+    'Units','pixels', ...
522
+    'Position',edge_color_pos, ...
523
+    'UserData',ud, ...
524
+    'String',s, ...
525
+    'Style','popupmenu');
526
+  set(p6_h,'units','normalized');
527
+
528
+  set( ...
529
+  uicontrol( ...                                                            %% [frame]
530
+    'Units','pixels', ...
531
+    'Position',frame4_pos, ...
532
+    'Style','frame'),'units','normalized');
533
+
534
+  set( ...
535
+  uicontrol( ...                                                            %% Text
536
+    'Units','pixels', ...
537
+    'Position',text_text_pos, ...
538
+    'HorizontalAlignment','left', ...
539
+    'String','Text', ...
540
+    'Style','text'),'units','normalized');
541
+
542
+  s = {'off' 'on'};
543
+  p2_h = uicontrol( ...                                                     %% [popupmenu]
544
+    'Units','pixels', ...
545
+    'Position',text_pos, ...
546
+    'String',s, ...
547
+    'Style','popupmenu');
548
+  set(p2_h,'units','normalized');
549
+
550
+  set( ...
551
+  uicontrol( ...                                                            %% Text
552
+    'Units','pixels', ...
553
+    'Position',text_text_pos, ...
554
+    'HorizontalAlignment','left', ...
555
+    'String','Text', ...
556
+    'Style','text'),'units','normalized');
557
+
558
+  s = {'off' 'on'};
559
+  p2_h = uicontrol( ...                                                     %% [popupmenu]
560
+    'Units','pixels', ...
561
+    'Position',text_pos, ...
562
+    'String',s, ...
563
+    'Style','popupmenu');
564
+  set(p2_h,'units','normalized');
565
+
566
+  set( ...
567
+  uicontrol( ...                                                            %% Text color
568
+    'Units','pixels', ...
569
+    'Position',text_color_text_pos, ...
570
+    'HorizontalAlignment','left', ...
571
+    'String','Text color', ...
572
+    'Style','text'),'units','normalized');
573
+
574
+  ud = {'k' 'w' 'y' 'm' 'c' 'r' 'g' 'b' 'xor'};
575
+  s = {'black' 'white' 'yellow' 'magenta' 'cyan' ...
576
+       'red' 'green' 'blue' 'xor'};
577
+  p1_h = uicontrol( ...                                                     %% [popupmenu]
578
+    'Units','pixels', ...
579
+    'Position',text_color_pos, ...
580
+    'UserData',ud, ...
581
+    'String',s, ...
582
+    'Style','popupmenu');
583
+  set(p1_h,'units','normalized');
584
+
585
+  set( ...
586
+  uicontrol( ...                                                            %% Text size
587
+    'Units','pixels', ...
588
+    'Position',text_size_text_pos, ...
589
+    'HorizontalAlignment','left', ...
590
+    'String','Text size', ...
591
+    'Style','text'),'units','normalized');
592
+
593
+  ed3_h = uicontrol( ...                                                    %% [edit]
594
+    'Units','pixels', ...
595
+    'BackgroundColor',bg_color2, ...
596
+    'Position',text_size_pos, ...
597
+    'String','3', ...
598
+    'FontSize',12, ...
599
+    'Style','edit');
600
+  set(ed3_h,'units','normalized');
601
+
602
+  set( ...
603
+  uicontrol( ...                                                            %% [frame]
604
+    'Units','pixels', ...
605
+    'Position',frame5_pos, ...
606
+    'Style','frame'),'units','normalized');
607
+
608
+  s = ['vis_show_gui_tool(' mat2str(h) ',''hit'',' mat2str(fig_h) ')'];
609
+  set( ...
610
+  uicontrol( ...                                                            %% OK
611
+    'Units','pixels', ...
612
+    'Position',ok_pos, ...
613
+    'String','OK', ...
614
+    'Callback',s),'units','normalized');
615
+
616
+  set( ...
617
+  uicontrol( ...                                                            %% Cancel
618
+    'Units','pixels', ...
619
+    'Position',cancel_pos, ...
620
+    'String','Cancel', ...
621
+    'Callback',['close(' mat2str(fig_h) ')']),'units','normalized');
622
+
623
+  watchoff(old_fig_n);
624
+  tmp_udata = [ed1_h ed2_h p1_h ed3_h p2_h p3_h ed4_h p4_h p5_h p6_h];
625
+  set(fig_h,'units','normalized', ...
626
+            'Visible','on', ...
627
+            'UserData',tmp_udata, ...
628
+            'handlevisibility','off');
629
+
630
+ %%%%%%%%%%
631
+% add_traj %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
632
+ %%%%%%%%%%
633
+elseif strcmp(action,'add_traj')
634
+  old_fig_n = watchon;
635
+  W = 424.3; H = 337.642;
636
+  o34 = zeros(1,4);
637
+  o34(1) = (W-f_fr(3))/2;
638
+  f_fr = [7.9 8.38 (W-2*7.9) 36.9];      % final frame
639
+  cancel_pb = [(W-(ok_pb(1)+75.9)) 15.76 75.9 22.14];
640
+  hint_txt = [W 18.45];           % hint text width and height
641
+  units = get(h,'units');
642
+  set(h,'units','pixels');
643
+  fp = get(h,'Position');
644
+  fig_pos = [(fp(1)+fp(3)) ...
645
+             (fp(2)+fp(2)+fp(4)/2-H/2) ...
646
+             W ...
647
+             H];
648
+  o1 = sum(f_fr([2 4]))+frames_dist;
649
+  o2 = o1+dist1;
650
+  o6 = max([title_txt(2),var_pop(2)]);
651
+  o7 = max([title_txt(2),title_edit_h]);
652
+  o8 = max([title_txt(2),title_edit_h,var_pop(2)]);
653
+  o38 = max([title_txt(2),title_edit_h,selvar_pb(2)]);
654
+  o20 = ok_pb(1)+title_txt(1);
655
+  o10 = o20+var_pop(1)+2*dist1;
656
+  o11 = o10+title_txt(1);
657
+  o3 = 2*o6+o8+4*dist1;
658
+  o4 = o1+dist1+0.5*o6-title_txt(2)/2;
659
+  o5 = o1+dist1+0.5*o6-var_pop(2)/2;
660
+  o9 = o1+2*dist1+o6+0.5*o8-title_txt(2)/2;
661
+  o12 = o1+2*dist1+o6+0.5*o8-title_edit_h/2;
662
+  o13 = o1+2*dist1+o6+0.5*o8-var_pop(2)/2;
663
+  o14 = o1+3*dist1+o6+o8+0.5*o6-title_edit_h/2;
664
+  o15 = o1+3*dist1+o6+o8+0.5*o6-var_pop(2)/2;
665
+  o16 = o1+o3+frames_dist2;
666
+  o17 = o8+o6+3*dist1;
667
+  o18 = o16+dist1+0.5*o8-title_txt(2)/2;
668
+  o19 = o16+dist1+0.5*o8-title_edit_h/2;
669
+  o21 = o16+dist1+0.5*o8-var_pop(2)/2;
670
+  o22 = o16+2*dist1+o8+0.5*o6-title_txt(2)/2;
671
+  o23 = o16+2*dist1+o8+0.5*o6-var_pop(2)/2;
672
+  o24 = o16+o17+frames_dist2;
673
+  o25 = o38+2*dist1;
674
+  o26 = o24+dist1+0.5*o38-title_txt(2)/2;
675
+  o27 = o24+dist1+0.5*o38-title_edit_h/2;
676
+  o28 = o24+dist1+0.5*o38-selvar_pb(2)/2;
677
+  o29 = o24+o25+frames_dist2;
678
+  o30 = o7+2*dist1;
679
+  o31 = o29+dist1+0.5*o7-title_txt(2)/2;
680
+  o32 = o29+dist1+0.5*o7-title_edit_h/2;
681
+  o33 = o29+o30+hint_dist1;
682
+  hint_text_pos = [1 o33 hint_txt];
683
+  frame1_pos = [f_fr(1) o29 f_fr(3) o30];
684
+  subplots_text_pos = [ok_pb(1) o31 title_txt];
685
+  subplots_pos = [o20 o32 strd_ed];
686
+  frame2_pos = [f_fr(1) o24 f_fr(3) o25];
687
+  trace_vect_text_pos = [ok_pb(1) o26 title_txt];
688
+  trace_vect_pos = [o20 o27 strd_ed];
689
+  sel_vect_pos = [o10 o28 selvar_pb];
690
+  frame3_pos = [f_fr(1) o16 f_fr(3) o17];
691
+  line_color_text_pos = [ok_pb(1) o22 title_txt];
692
+  line_color_pos = [o20 o23 var_pop];
693
+  line_width_text_pos = [ok_pb(1) o18 title_txt];
694
+  line_width_pos = [o20 o19 strd_ed];
695
+  width_factor_text_pos = [o10 o18 title_txt];
696
+  width_factor_pos = [o11 o19 var_pop];
697
+  frame4_pos = [f_fr(1) o1 f_fr(3) o3];
698
+  marker_text_pos = [ok_pb(1) o14 title_txt];
699
+  marker_pos = [o20 o15 var_pop];
700
+  marker_size_text_pos = [ok_pb(1) o9 title_txt];
701
+  marker_size_pos = [o20 o12 strd_ed];
702
+  size_factor_text_pos = [o10 o9 title_txt];
703
+  size_factor_pos = [o11 o13 var_pop];
704
+  marker_color_text_pos = [ok_pb(1) o4 title_txt];
705
+  marker_color_pos = [o20 o5 var_pop];
706
+  edge_color_text_pos = [o10 o4 title_txt];
707
+  edge_color_pos = [o11 o5 var_pop];
708
+  f_fr = [7.9 8.38 216.2 36.9];      % final frame
709
+  cancel_pb = [139 15.76 75.9 22.14];
710
+  frame5_pos = f_fr+o34;
711
+  ok_pos = ok_pb+o34;
712
+  cancel_pos = cancel_pb+o34;
713
+
714
+  fig_h = figure( ...
715
+    'Units','pixels', ...
716
+    'Position', fig_pos, ...
717
+    'Color',fig_color, ...
718
+    'NumberTitle','off', ...
719
+    'Name','add trajectory', ...
720
+    'MenuBar','none', ...
721
+    'Visible','off');
722
+
723
+    set( ...
724
+    uicontrol( ...                                                            %% hint
725
+      'Units','pixels', ...
726
+      'BackgroundColor',fig_color, ...
727
+      'HorizontalAlignment','center', ...
728
+      'Position',hint_text_pos, ...
729
+      'String','Options for adding trajectory', ...
730
+      'Style','text'),'units','normalized');
731
+
732
+  set( ...
733
+  uicontrol( ...                                                            %% [frame]
734
+    'Units','pixels', ...
735
+    'Position',frame1_pos, ...
736
+    'Style','frame'),'units','normalized');
737
+
738
+  set( ...
739
+  uicontrol( ...
740
+    'Units','pixels', ...                                                   %% To subplot(s)
741
+    'Position',subplots_text_pos, ...
742
+    'HorizontalAlignment','left', ...
743
+    'String','To subplot(s)', ...
744
+    'Style','text'),'units','normalized');
745
+
746
+  ed1_h = uicontrol( ...                                                    %% [edit]
747
+    'Units','pixels', ...
748
+    'BackgroundColor',bg_color2, ...
749
+    'Position',subplots_pos, ...
750
+    'FontSize',12, ...
751
+    'Style','edit');
752
+  set(ed1_h,'units','normalized');
753
+
754
+  set( ...
755
+  uicontrol( ...                                                            %% [frame]
756
+    'Units','pixels', ...
757
+    'Position',frame2_pos, ...
758
+    'Style','frame'),'units','normalized');
759
+
760
+  set( ...
761
+  uicontrol( ...                                                            %% Trace vector
762
+    'Units','pixels', ...
763
+    'Position',trace_vect_text_pos, ...
764
+    'HorizontalAlignment','left', ...
765
+    'String','Trajectory', ...
766
+    'Style','text'),'units','normalized');
767
+
768
+  ed2_h = uicontrol( ...                                                    %% [edit]
769
+    'Units','pixels', ...
770
+    'BackgroundColor',bg_color2, ...
771
+    'Position',trace_vect_pos, ...
772
+    'FontSize',12, ...
773
+    'Style','edit');
774
+  set(ed2_h,'units','normalized');
775
+
776
+  s = ['tmp=get(' mat2str(fig_h) ',''userdata'');' ...
777
+       'vis_show_gui_tool(tmp(2),''select'')'];
778
+  set( ...
779
+  uicontrol( ...                                                            %% Select variable
780
+    'Units','pixels', ...
781
+    'Position',sel_vect_pos, ...
782
+    'String','Select variable', ...
783
+    'Callback',s),'units','normalized');
784
+
785
+  set( ...
786
+  uicontrol( ...                                                            %% [frame]
787
+    'Units','pixels', ...
788
+    'Position',frame3_pos, ...
789
+    'Style','frame'),'units','normalized');
790
+
791
+  set( ...
792
+  uicontrol( ...                                                            %% Line color
793
+    'Units','pixels', ...
794
+    'Position',line_color_text_pos, ...
795
+    'HorizontalAlignment','left', ...
796
+    'String','Line color', ...
797
+    'Style','text'),'units','normalized');
798
+
799
+  ud = {'w' 'k' 'y' 'm' 'c' 'r' 'g' 'b' 'xor'};
800
+  s = {'white' 'black' 'yellow' 'magenta' 'cyan' ...
801
+       'red' 'green' 'blue' 'xor'};
802
+  p1_h = uicontrol( ...                                                     %% [popupmenu]
803
+    'Units','pixels', ...
804
+    'Position',line_color_pos, ...
805
+    'UserData',ud, ...
806
+    'String',s, ...
807
+    'Style','popupmenu');
808
+  set(p1_h,'units','normalized');
809
+
810
+  set( ...
811
+  uicontrol( ...                                                            %% Line width
812
+    'Units','pixels', ...
813
+    'Position',line_width_text_pos, ...
814
+    'HorizontalAlignment','left', ...
815
+    'String','Line width', ...
816
+    'Style','text'),'units','normalized');
817
+
818
+  ed3_h = uicontrol( ...                                                    %% [edit]
819
+    'Units','pixels', ...
820
+    'BackgroundColor',bg_color2, ...
821
+    'Position',line_width_pos, ...
822
+    'String','3', ...
823
+    'FontSize',12, ...
824
+    'Style','edit');
825
+  set(ed3_h,'units','normalized');
826
+
827
+  set( ...
828
+  uicontrol( ...                                                            %% Factor
829
+    'Units','pixels', ...
830
+    'Position',width_factor_text_pos, ...
831
+    'HorizontalAlignment','left', ...
832
+    'String','Factor', ...
833
+    'Style','text'),'units','normalized');
834
+
835
+  s = {'hit' 'equal'};
836
+  p2_h = uicontrol( ...                                                     %% [popupmenu]
837
+    'Units','pixels', ...
838
+    'Position',width_factor_pos, ...
839
+    'String',s, ...
840
+    'Style','popupmenu');
841
+  set(p2_h,'units','normalized');
842
+
843
+  set( ...
844
+  uicontrol( ...                                                            %% [frame]
845
+    'Units','pixels', ...
846
+    'Position',frame4_pos, ...
847
+    'Style','frame'),'units','normalized');
848
+
849
+  set( ...
850
+  uicontrol( ...                                                            %% Marker
851
+    'Units','pixels', ...
852
+    'Position',marker_text_pos, ...
853
+    'HorizontalAlignment','left', ...
854
+    'String','Marker', ...
855
+    'Style','text'),'units','normalized');
856
+
857
+  s = {'o' '.' 'x' '+' '*' 's' 'd' 'v' '^' ...
858
+       '<' '>' 'p' 'h' 'none'};
859
+  p3_h = uicontrol( ...                                                     %% [popupmenu]
860
+    'Units','pixels', ...
861
+    'Position',marker_pos, ...
862
+    'String',s, ...
863
+    'Style','popupmenu');
864
+  set(p3_h,'units','normalized');
865
+
866
+  set( ...
867
+  uicontrol( ...                                                            %% Marker size
868
+    'Units','pixels', ...
869
+    'HorizontalAlignment','left', ...
870
+    'Position',marker_size_text_pos, ...
871
+    'String','Marker size', ...
872
+    'Style','text'),'units','normalized');
873
+
874
+  ed4_h = uicontrol( ...                                                    %% [edit]
875
+    'Units','pixels', ...
876
+    'BackgroundColor',bg_color2, ...
877
+    'Position',marker_size_pos, ...
878
+    'String','10', ...
879
+    'FontSize',12, ...
880
+    'Style','edit');
881
+  set(ed4_h,'units','normalized');
882
+
883
+  set( ...
884
+  uicontrol( ...                                                            %% Factor
885
+    'Units','pixels', ...
886
+    'HorizontalAlignment','left', ...
887
+    'Position',size_factor_text_pos, ...
888
+    'HorizontalAlignment','left', ...
889
+    'String','Factor', ...
890
+    'Style','text'),'units','normalized');
891
+
892
+  s = {'hit' 'equal'};
893
+  p4_h = uicontrol( ...                                                     %% [popupmenu]
894
+    'Units','pixels', ...
895
+    'Position',size_factor_pos, ...
896
+    'String',s, ...
897
+    'Style','popupmenu');
898
+  set(p4_h,'units','normalized');
899
+
900
+  set( ...
901
+  uicontrol( ...                                                            %% Marker color
902
+    'Units','pixels', ...
903
+    'HorizontalAlignment','left', ...
904
+    'Position',marker_color_text_pos, ...
905
+    'String','Marker color', ...
906
+    'Style','text'),'units','normalized');
907
+
908
+  ud = {'w' 'k' 'y' 'm' 'c' 'r' 'g' 'b' 'none'};
909
+  s = {'white' 'black' 'yellow' 'magenta' 'cyan' ...
910
+       'red' 'green' 'blue' 'none'};
911
+  p5_h = uicontrol( ...                                                     %% [popupmenu]
912
+    'Units','pixels', ...
913
+    'Position',marker_color_pos, ...
914
+    'UserData',ud, ...
915
+    'String',s, ...
916
+    'Style','popupmenu');
917
+  set(p5_h,'units','normalized');
918
+
919
+  set( ...
920
+  uicontrol( ...                                                            %% Edge color
921
+    'Units','pixels', ...
922
+    'Position',edge_color_text_pos, ...
923
+    'HorizontalAlignment','left', ...
924
+    'String','Edge color', ...
925
+    'Style','text'),'units','normalized');
926
+
927
+  ud = {'none' 'w' 'k' 'y' 'm' 'c' 'r' 'g' 'b'};
928
+  s = {'none' 'white' 'black' 'yellow' 'magenta' 'cyan' ...
929
+       'red' 'green' 'blue'};
930
+  p6_h = uicontrol( ...                                                     %% [popupmenu]
931
+    'Units','pixels', ...
932
+    'Position',edge_color_pos, ...
933
+    'UserData',ud, ...
934
+    'String',s, ...
935
+    'Style','popupmenu');
936
+  set(p6_h,'units','normalized');
937
+
938
+  set( ...
939
+  uicontrol( ...                                                            %% [frame]
940
+    'Units','pixels', ...
941
+    'Position',frame5_pos, ...
942
+    'Style','frame'),'units','normalized');
943
+
944
+  s = ['vis_show_gui_tool(' mat2str(h) ',''traj'',' mat2str(fig_h) ')'];
945
+  set( ...
946
+  uicontrol( ...                                                            %% OK
947
+    'Units','pixels', ...
948
+    'Position',ok_pos, ...
949
+    'String','OK', ...
950
+    'Callback',s),'units','normalized');
951
+
952
+  set( ...
953
+  uicontrol( ...                                                            %% Cancel
954
+    'Units','pixels', ...
955
+    'Position',cancel_pos, ...
956
+    'String','Cancel', ...
957
+    'Callback',['close(' mat2str(fig_h) ')']),'units','normalized');
958
+
959
+  watchoff(old_fig_n);
960
+  tmp_udata = [ed1_h ed2_h p1_h ed3_h p2_h p3_h ed4_h p4_h p5_h p6_h];
961
+  set(fig_h,'units','normalized', ...
962
+            'Visible','on', ...
963
+            'UserData',tmp_udata, ...
964
+            'handlevisibility','off');
965
+
966
+ %%%%%%%%%%%
967
+% add_comet %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
968
+ %%%%%%%%%%%
969
+elseif strcmp(action,'add_comet')
970
+  old_fig_n = watchon;
971
+  W = 424.3; H = 265.589;
972
+  o26 = zeros(1,4);
973
+  o26(1) = (W-f_fr(3))/2;
974
+  f_fr = [7.9 8.38 (W-2*7.9) 36.9];      % final frame
975
+  cancel_pb = [(W-(ok_pb(1)+75.9)) 15.76 75.9 22.14];
976
+  hint_txt = [W 18.45];           % hint text width and height
977
+  units = get(h,'units');
978
+  set(h,'units','pixels');
979
+  fp = get(h,'Position');
980
+  fig_pos = [(fp(1)+fp(3)) ...
981
+             (fp(2)+fp(2)+fp(4)/2-H/2) ...
982
+             W ...
983
+             H];
984
+  o1 = sum(f_fr([2 4]))+frames_dist;
985
+  o2 = o1+dist1;
986
+  o6 = max([title_txt(2),var_pop(2)]);
987
+  o7 = max([title_txt(2),title_edit_h]);
988
+  o8 = max([title_txt(2),title_edit_h,var_pop(2)]);
989
+  o38 = max([title_txt(2),title_edit_h,selvar_pb(2)]);
990
+  o20 = ok_pb(1)+title_txt(1);
991
+  o10 = o20+var_pop(1)+2*dist1;
992
+  o11 = o10+title_txt(1);
993
+  o3 = 2*o6+o7+4*dist1;
994
+  o4 = o1+dist1+0.5*o6-title_txt(2)/2;
995
+  o5 = o1+dist1+0.5*o6-var_pop(2)/2;
996
+  o9 = o1+2*dist1+o6+0.5*o7-title_txt(2)/2;
997
+  o12 = o1+2*dist1+o6+0.5*o7-title_edit_h/2;
998
+  o13 = o1+3*dist1+o7+1.5*o6-title_txt(2)/2;
999
+  o14 = o1+3*dist1+o7+1.5*o6-var_pop(2)/2;
1000
+  o15 = o1+o3+frames_dist2;
1001
+  o16 = o38+2*dist1;
1002
+  o17 = o15+dist1+0.5*o38-title_txt(2)/2;
1003
+  o18 = o15+dist1+0.5*o38-title_edit_h/2;
1004
+  o19 = o15+dist1+0.5*o38-selvar_pb(2)/2;
1005
+  o21 = o15+o16+frames_dist2;
1006
+  o22 = o7+2*dist1;
1007
+  o23 = o21+dist1+0.5*o7-title_txt(2)/2;
1008
+  o24 = o21+dist1+0.5*o7-title_edit_h/2;
1009
+  o25 = o21+o22+hint_dist1;
1010
+  hint_text_pos = [1 o25 hint_txt];
1011
+  frame1_pos = [f_fr(1) o21 f_fr(3) o22];
1012
+  subplots_text_pos = [ok_pb(1) o23 title_txt];
1013
+  subplots_pos = [o20 o24 strd_ed];
1014
+  frame2_pos = [f_fr(1) o15 f_fr(3) o16];
1015
+  trace_vect_text_pos = [ok_pb(1) o17 title_txt];
1016
+  trace_vect_pos = [o20 o18 strd_ed];
1017
+  sel_var_pos = [o10 o19 selvar_pb];
1018
+  frame3_pos = [f_fr(1) o1 f_fr(3) o3];
1019
+  marker_text_pos = [ok_pb(1) o13 title_txt];
1020
+  marker_pos = [o20 o14 var_pop];
1021
+  marker_size_text_pos = [ok_pb(1) o9 title_txt];
1022
+  marker_size_pos = [o20 o12 var_pop];
1023
+  marker_color_text_pos = [ok_pb(1) o4 title_txt];
1024
+  marker_color_pos = [o20 o5 var_pop];
1025
+  edge_color_text_pos = [o10 o4 title_txt];
1026
+  edge_color_pos = [o11 o5 var_pop];
1027
+  f_fr = [7.9 8.38 216.2 36.9];      % final frame
1028
+  cancel_pb = [139 15.76 75.9 22.14];
1029
+  frame4_pos = f_fr+o26;
1030
+  ok_pos = ok_pb+o26;
1031
+  cancel_pos = cancel_pb+o26;
1032
+
1033
+  fig_h = figure( ...
1034
+    'Units','pixels', ...
1035
+    'Position', fig_pos, ...
1036
+    'Color',fig_color, ...
1037
+    'NumberTitle','off', ...
1038
+    'Name','add comet', ...
1039
+    'MenuBar','none', ...
1040
+    'Visible','off');
1041
+
1042
+    set( ...
1043
+    uicontrol( ...                                                            %% hint
1044
+      'Units','pixels', ...
1045
+      'BackgroundColor',fig_color, ...
1046
+      'HorizontalAlignment','center', ...
1047
+      'Position',hint_text_pos, ...
1048
+      'String','Options for adding comet', ...
1049
+      'Style','text'),'units','normalized');
1050
+
1051
+  set( ...
1052
+  uicontrol( ...                                                            %% [frame]
1053
+    'Units','pixels', ...
1054
+    'Position',frame1_pos, ...
1055
+    'Style','frame'),'units','normalized');
1056
+
1057
+  set( ...
1058
+  uicontrol( ...                                                            %% To subplot(s)
1059
+    'Units','pixels', ...
1060
+    'Position',subplots_text_pos, ...
1061
+    'HorizontalAlignment','left', ...
1062
+    'String','To subplot(s)', ...
1063
+    'Style','text'),'units','normalized');
1064
+
1065
+  ed1_h = uicontrol( ...                                                    %% [edit]
1066
+    'Units','pixels', ...
1067
+    'BackgroundColor',bg_color2, ...
1068
+    'Position',subplots_pos, ...
1069
+    'FontSize',12, ...
1070
+    'Style','edit');
1071
+  set(ed1_h,'units','normalized');
1072
+
1073
+  set( ...
1074
+  uicontrol( ...                                                            %% [frame]
1075
+    'Units','pixels', ...
1076
+    'Position',frame2_pos, ...
1077
+    'Style','frame'),'units','normalized');
1078
+
1079
+  set( ...
1080
+  uicontrol( ...                                                            %% Trace vector
1081
+    'Units','pixels', ...
1082
+    'Position',trace_vect_text_pos, ...
1083
+    'HorizontalAlignment','left', ...
1084
+    'String','Trace vector', ...
1085
+    'Style','text'),'units','normalized');
1086
+
1087
+  ed2_h = uicontrol( ...                                                    %% [edit]
1088
+    'Units','pixels', ...
1089
+    'BackgroundColor',bg_color2, ...
1090
+    'Position',trace_vect_pos, ...
1091
+    'FontSize',12, ...
1092
+    'Style','edit');
1093
+  set(ed2_h,'units','normalized');
1094
+
1095
+  s = ['tmp=get(' mat2str(fig_h) ',''userdata'');' ...
1096
+       'vis_show_gui_tool(tmp(2),''select'')'];
1097
+  set( ...
1098
+  uicontrol( ...                                                            %% Select variable
1099
+    'Units','pixels', ...
1100
+    'Position',sel_var_pos, ...
1101
+    'String','Select variable', ...
1102
+    'Callback',s),'units','normalized');
1103
+
1104
+  set( ...
1105
+  uicontrol( ...                                                            %% [frame]
1106
+    'Units','pixels', ...
1107
+    'Position',frame3_pos, ...
1108
+    'Style','frame'),'units','normalized');
1109
+
1110
+  set( ...
1111
+  uicontrol( ...                                                            %% Marker
1112
+    'Units','pixels', ...
1113
+    'Position',marker_text_pos, ...
1114
+    'HorizontalAlignment','left', ...
1115
+    'String','Marker', ...
1116
+    'Style','text'),'units','normalized');
1117
+
1118
+  s = {'o' '.' 'x' '+' '*' 's' 'd' 'v' '^' ...
1119
+       '<' '>' 'p' 'h' 'lattice' 'none'};
1120
+  p1_h = uicontrol( ...                                                     %% [popupmenu]
1121
+    'Units','pixels', ...
1122
+    'Position',marker_pos, ...
1123
+    'String',s, ...
1124
+    'Style','popupmenu');
1125
+  set(p1_h,'units','normalized');
1126
+
1127
+  set( ...
1128
+  uicontrol( ...                                                            %% Marker size
1129
+    'Units','pixels', ...
1130
+    'HorizontalAlignment','left', ...
1131
+    'Position',marker_size_text_pos, ...
1132
+    'String','Marker size', ...
1133
+    'Style','text'),'units','normalized');
1134
+
1135
+  ed3_h = uicontrol( ...                                                    %% [edit]
1136
+    'Units','pixels', ...
1137
+    'BackgroundColor',bg_color2, ...
1138
+    'Position',marker_size_pos, ...
1139
+    'String','[20 4]', ...
1140
+    'FontSize',12, ...
1141
+    'Style','edit');
1142
+  set(ed3_h,'units','normalized');
1143
+
1144
+  set( ...
1145
+  uicontrol( ...                                                            %% Marker color
1146
+    'Units','pixels', ...
1147
+    'HorizontalAlignment','left', ...
1148
+    'Position',marker_color_text_pos, ...
1149
+    'String','Marker color', ...
1150
+    'Style','text'),'units','normalized');
1151
+
1152
+  ud = {'w' 'k' 'y' 'm' 'c' 'r' 'g' 'b' 'none' ''};
1153
+  s = {'white' 'black' 'yellow' 'magenta' 'cyan' ...
1154
+       'red' 'green' 'blue' 'none' '-matrix-'};
1155
+  p2_h = uicontrol( ...                                                     %% [popupmenu]
1156
+    'Units','pixels', ...
1157
+    'Position',marker_color_pos, ...
1158
+    'UserData',ud, ...
1159
+    'String',s, ...
1160
+    'Style','popupmenu');
1161
+  s = ['tmp=get(' mat2str(fig_h) ',''userdata'');' ...
1162
+       'vis_show_gui_tool([tmp(5) 10],''popup_select'')'];
1163
+  set(p2_h,'units','normalized','Callback',s);
1164
+
1165
+  set( ...
1166
+  uicontrol( ...                                                            %% Edge color
1167
+    'Units','pixels', ...
1168
+    'Position',edge_color_text_pos, ...
1169
+    'HorizontalAlignment','left', ...
1170
+    'String','Edge color', ...
1171
+    'Style','text'),'units','normalized');
1172
+
1173
+  ud = {'none' 'w' 'k' 'y' 'm' 'c' 'r' 'g' 'b'};
1174
+  s = {'none' 'white' 'black' 'yellow' 'magenta' 'cyan' ...
1175
+       'red' 'green' 'blue'};
1176
+  p3_h = uicontrol( ...                                                     %% [popupmenu]
1177
+    'Units','pixels', ...
1178
+    'Position',edge_color_pos, ...
1179
+    'UserData',ud, ...
1180
+    'String',s, ...
1181
+    'Style','popupmenu');
1182
+  set(p3_h,'units','normalized');
1183
+
1184
+  set( ...
1185
+  uicontrol( ...                                                            %% [frame]
1186
+    'Units','pixels', ...
1187
+    'Position',frame4_pos, ...
1188
+    'Style','frame'),'units','normalized');
1189
+
1190
+  s = ['vis_show_gui_tool(' mat2str(h) ',''comet'',' mat2str(fig_h) ')'];
1191
+  set( ...
1192
+  uicontrol( ...                                                            %% OK
1193
+    'Units','pixels', ...
1194
+    'Position',ok_pos, ...
1195
+    'String','OK', ...
1196
+    'Callback',s),'units','normalized');
1197
+
1198
+  set( ...
1199
+  uicontrol( ...                                                            %% Cancel
1200
+    'Units','pixels', ...
1201
+    'Position',cancel_pos, ...
1202
+    'String','Cancel', ...
1203
+    'Callback',['close(' mat2str(fig_h) ')']),'units','normalized');
1204
+
1205
+  watchoff(old_fig_n);
1206
+  tmp_udata = [ed1_h ed2_h p1_h ed3_h p2_h p3_h];
1207
+  set(fig_h,'units','normalized', ...
1208
+            'Visible','on', ...
1209
+            'UserData',tmp_udata, ...
1210
+            'handlevisibility','off');
1211
+
1212
+ %%%%%%%%%%%%
1213
+% recolorbar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1214
+ %%%%%%%%%%%%
1215
+elseif strcmp(action,'recolorbar')
1216
+  old_fig_n = watchon;
1217
+  W = 345.4; H = 237.299;
1218
+  o25 = zeros(1,4);
1219
+  o25(1) = (W-f_fr(3))/2;
1220
+  f_fr = [7.9 8.38 (W-2*7.9) 36.9];      % final frame
1221
+  cancel_pb = [(W-(ok_pb(1)+75.9)) 15.76 75.9 22.14];
1222
+  hint_txt = [W 18.45];           % hint text width and height
1223
+  units = get(h,'units');
1224
+  set(h,'units','pixels');
1225
+  fp = get(h,'Position');
1226
+  fig_pos = [(fp(1)+fp(3)) ...
1227
+             (fp(2)+fp(2)+fp(4)/2-H/2) ...
1228
+             W ...
1229
+             H];
1230
+  o1 = sum(f_fr([2 4]))+frames_dist;
1231
+  o2 = o1+dist1;
1232
+  o6 = max([title_txt(2),var_pop(2)]);
1233
+  o7 = max([title_txt(2),title_edit_h]);
1234
+  o8 = max([title_txt(2),title_edit_h,selvar_pb(2)]);
1235
+  o20 = ok_pb(1)+title_txt(1);
1236
+  o10 = o20+var_pop(1)+2*dist1;
1237
+  o11 = o10+title_txt(1);
1238
+  o3 = o6+2*dist1;
1239
+  o4 = o1+dist1+0.5*o6-title_txt(2)/2;
1240
+  o5 = o1+dist1+0.5*o6-var_pop(2)/2;
1241
+  o9 = o1+o3+frames_dist2;
1242
+  o12 = 2*o8+3*dist1;
1243
+  o13 = o9+dist1+0.5*o8-title_txt(2)/2;
1244
+  o14 = o9+dist1+0.5*o8-title_edit_h/2;
1245
+  o15 = o9+dist1+0.5*o8-var_pop(2)/2;
1246
+  o16 = o9+2*dist1+1.5*o8-title_txt(2)/2;
1247
+  o17 = o9+2*dist1+1.5*o8-title_edit_h/2;
1248
+  o18 = o9+2*dist1+1.5*o8-var_pop(2)/2;
1249
+  o19 = o9+o12+frames_dist2;
1250
+  o21 = o7+2*dist1;
1251
+  o22 = o19+dist1+0.5*o7-title_txt(2)/2;
1252
+  o23 = o19+dist1+0.5*o7-title_edit_h/2;
1253
+  o24 = o19+o21+hint_dist1;
1254
+  hint_text_pos = [1 o24 hint_txt];
1255
+  frame1_pos = [f_fr(1) o19 f_fr(3) o21];
1256
+  subplots_text_pos = [ok_pb(1) o22 title_txt];
1257
+  subplots_pos = [o20 o23 strd_ed];
1258
+  frame2_pos = [f_fr(1) o9 f_fr(3) o12];
1259
+  tics_text_pos = [ok_pb(1) o16 title_txt];
1260
+  tics_pos = [o20 o17 strd_ed];
1261
+  sel_var2_pos = [o10 o18 var_pop];
1262
+  labels_text_pos = [ok_pb(1) o13 title_txt];
1263
+  labels_pos = [o20 o14 strd_ed];
1264
+  sel_var1_pos = [o10 o15 var_pop];
1265
+  frame3_pos = [f_fr(1) o1 f_fr(3) o3];
1266
+  scale_text_pos = [ok_pb(1) o4 title_txt];
1267
+  scale_pos = [o20 o5 1.3*var_pop(1) var_pop(2)];
1268
+  f_fr = [7.9 8.38 216.2 36.9];      % final frame
1269
+  cancel_pb = [139 15.76 75.9 22.14];
1270
+  frame4_pos = f_fr+o25;
1271
+  ok_pos = ok_pb+o25;
1272
+  cancel_pos = cancel_pb+o25;
1273
+
1274
+  fig_h = figure( ...
1275
+    'Units','pixels', ...
1276
+    'Position', fig_pos, ...
1277
+    'Color',fig_color, ...
1278
+    'NumberTitle','off', ...
1279
+    'Name','recolorbar', ...
1280
+    'MenuBar','none', ...
1281
+    'Visible','off');
1282
+
1283
+    set( ...
1284
+    uicontrol( ...                                                            %% hint
1285
+      'Units','pixels', ...
1286
+      'BackgroundColor',fig_color, ...
1287
+      'HorizontalAlignment','center', ...
1288
+      'Position',hint_text_pos, ...
1289
+      'String','Options, recolorbar', ...
1290
+      'Style','text'),'units','normalized');
1291
+
1292
+  set( ...
1293
+  uicontrol( ...                                                            %% [frame]
1294
+    'Units','pixels', ...
1295
+    'Position',frame1_pos, ...
1296
+    'Style','frame'),'units','normalized');
1297
+
1298
+  set( ...
1299
+  uicontrol( ...                                                            %% In subplot(s)
1300
+    'Units','pixels', ...
1301
+    'Position',subplots_text_pos, ...
1302
+    'HorizontalAlignment','left', ...
1303
+    'String','In subplot(s)', ...
1304
+    'Style','text'),'units','normalized');
1305
+
1306
+  ed1_h = uicontrol( ...                                                    %% [edit]
1307
+    'Units','pixels', ...
1308
+    'BackgroundColor',bg_color2, ...
1309
+    'Position',subplots_pos, ...
1310
+    'FontSize',12, ...
1311
+    'Style','edit');
1312
+  set(ed1_h,'units','normalized');
1313
+
1314
+  set( ...
1315
+  uicontrol( ...                                                            %% [frame]
1316
+    'Units','pixels', ...
1317
+    'Position',frame2_pos, ...
1318
+    'Style','frame'),'units','normalized');
1319
+
1320
+  set( ...
1321
+  uicontrol( ...                                                            %% Ticks
1322
+    'Units','pixels', ...
1323
+    'Position',tics_text_pos, ...
1324
+    'HorizontalAlignment','left', ...
1325
+    'String','Ticks', ...
1326
+    'Style','text'),'units','normalized');
1327
+
1328
+  ed3_h = uicontrol( ...                                                    %% [edit]
1329
+    'Units','pixels', ...
1330
+    'BackgroundColor',bg_color2, ...
1331
+    'Position',tics_pos, ...
1332
+    'FontSize',12, ...
1333
+    'Style','edit');
1334
+  set(ed3_h,'units','normalized');
1335
+
1336
+  s = ['tmp=get(' mat2str(fig_h) ',''userdata'');' ...
1337
+       'vis_show_gui_tool(tmp(3),''select'')'];
1338
+  set( ...
1339
+  uicontrol( ...                                                            %% Select variable
1340
+    'Units','pixels', ...
1341
+    'Position',sel_var2_pos, ...
1342
+    'String','Select variable', ...
1343
+    'Callback',s),'units','normalized');
1344
+
1345
+  set( ...
1346
+  uicontrol( ...                                                            %% Labels (cell array)
1347
+    'Units','pixels', ...
1348
+    'Position',labels_text_pos, ...
1349
+    'HorizontalAlignment','left', ...
1350
+    'String','Labels', ...
1351
+    'Style','text'),'units','normalized');
1352
+
1353
+  ed2_h = uicontrol( ...                                                    %% [edit]
1354
+    'Units','pixels', ...
1355
+    'BackgroundColor',bg_color2, ...
1356
+    'Position',labels_pos, ...
1357
+    'FontSize',12, ...
1358
+    'Style','edit');
1359
+  set(ed2_h,'units','normalized');
1360
+
1361
+  s = ['tmp=get(' mat2str(fig_h) ',''userdata'');' ...
1362
+       'vis_show_gui_tool(tmp(2),''select'')'];
1363
+  set( ...
1364
+  uicontrol( ...                                                            %% Select variable
1365
+    'Units','pixels', ...
1366
+    'Position',sel_var1_pos, ...
1367
+    'String','Select variable', ...
1368
+    'Callback',s),'units','normalized');
1369
+
1370
+  set( ...
1371
+  uicontrol( ...                                                            %% [frame]
1372
+    'Units','pixels', ...
1373
+    'Position',frame3_pos, ...
1374
+    'Style','frame'),'units','normalized');
1375
+
1376
+  set( ...
1377
+  uicontrol( ...                                                            %% Scale
1378
+    'Units','pixels', ...
1379
+    'Position',scale_text_pos, ...
1380
+    'HorizontalAlignment','left', ...
1381
+    'String','Scale', ...
1382
+    'Style','text'),'units','normalized');
1383
+
1384
+  s = {'denormalized' 'normalized'};
1385
+  p1_h = uicontrol( ...                                                     %% [popupmenu]
1386
+    'Units','pixels', ...
1387
+    'Position',scale_pos, ...
1388
+    'String',s, ...
1389
+    'Style','popupmenu');
1390
+  set(p1_h,'units','normalized');
1391
+
1392
+  set( ...
1393
+  uicontrol( ...                                                            %% [frame]
1394
+    'Units','pixels', ...
1395
+    'Position',frame4_pos, ...
1396
+    'Style','frame'),'units','normalized');
1397
+
1398
+  s = ['vis_show_gui_tool(' mat2str(h) ',''do_recolorbar'',' mat2str(fig_h) ')'];
1399
+  set( ...
1400
+  uicontrol( ...                                                            %% OK
1401
+    'Units','pixels', ...
1402
+    'Position',ok_pos, ...
1403
+    'String','OK', ...
1404
+    'Callback',s),'units','normalized');
1405
+
1406
+  set( ...
1407
+  uicontrol( ...                                                            %% Cancel
1408
+    'Units','pixels', ...
1409
+    'Position',cancel_pos, ...
1410
+    'String','Cancel', ...
1411
+    'Callback',['close(' mat2str(fig_h) ')']),'units','normalized');
1412
+
1413
+  watchoff(old_fig_n);
1414
+  tmp_udata = [ed1_h ed2_h ed3_h p1_h];
1415
+  set(fig_h,'units','normalized', ...
1416
+            'Visible','on', ...
1417
+            'UserData',tmp_udata, ...
1418
+            'handlevisibility','off');
1419
+
1420
+ %%%%%%%
1421
+% clear %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1422
+ %%%%%%%
1423
+elseif strcmp(action,'clear')
1424
+  old_fig_n = watchon;
1425
+  W = 232; H = 277.463;
1426
+  o25 = zeros(1,4);
1427
+  o25(1) = (W-f_fr(3))/2;
1428
+  f_fr = [7.9 8.38 (W-2*7.9) 36.9];      % final frame
1429
+  cancel_pb = [(W-(ok_pb(1)+75.9)) 15.76 75.9 22.14];
1430
+  hint_txt = [W 18.45];           % hint text width and height
1431
+  units = get(h,'units');
1432
+  set(h,'units','pixels');
1433
+  fp = get(h,'Position');
1434
+  fig_pos = [(fp(1)+fp(3)) ...
1435
+             (fp(2)+fp(2)+fp(4)/2-H/2) ...
1436
+             W ...
1437
+             H];
1438
+  o1 = sum(f_fr([2 4]))+frames_dist;
1439
+  o2 = o1+dist1;
1440
+  o3 = (W-radio_rb(1))/2;
1441
+  o4 = o2+radio_rb(2)+dist1;
1442
+  o5 = o4+radio_rb(2)+dist1;
1443
+  o6 = o5+radio_rb(2)+dist1;
1444
+  o7 = o6+radio_rb(2)+dist1;
1445
+  o8 = 5*radio_rb(2)+6*dist1;
1446
+  o9 = o1+o8+frames_dist2;
1447
+  o10 = max([title_txt(2),title_edit_h]);
1448
+  o11 = o9+dist1+0.5*o10-title_txt(2)/2;
1449
+  o12 = o9+dist1+0.5*o10-strd_ed(2)/2;
1450
+  o20 = W-(ok_pb(1)+strd_ed(1));
1451
+  o13 = o10+2*dist1;
1452
+  o24 = o9+o13+hint_dist1;
1453
+  hint_text_pos = [1 o24 hint_txt];
1454
+  frame1_pos = [f_fr(1) o9 f_fr(3) o13];
1455
+  subplots_text_pos = [ok_pb(1) o11 title_txt];
1456
+  subplots_pos = [o20 o12 strd_ed];
1457
+  frame2_pos = [f_fr(1) o1 f_fr(3) o8];
1458
+  radiob1_pos = [o3 o7 selvar_pb];
1459
+  radiob2_pos = [o3 o6 selvar_pb];
1460
+  radiob3_pos = [o3 o5 selvar_pb];
1461
+  radiob4_pos = [o3 o4 selvar_pb];
1462
+  radiob5_pos = [o3 o2 selvar_pb];
1463
+  f_fr = [7.9 8.38 216.2 36.9];      % final frame
1464
+  cancel_pb = [139 15.76 75.9 22.14];
1465
+  frame3_pos = f_fr;%+o25;
1466
+  ok_pos = ok_pb;%+o25;
1467
+  cancel_pos = cancel_pb;%+o25;
1468
+
1469
+  fig_h = figure( ...
1470
+    'Units','pixels', ...
1471
+    'Position', fig_pos, ...
1472
+    'Color',fig_color, ...
1473
+    'NumberTitle','off', ...
1474
+    'Name','clear label', ...
1475
+    'MenuBar','none', ...
1476
+    'Visible','off');
1477
+
1478
+    set( ...
1479
+    uicontrol( ...                                                            %% hint
1480
+      'Units','pixels', ...
1481
+      'BackgroundColor',fig_color, ...
1482
+      'HorizontalAlignment','center', ...
1483
+      'Position',hint_text_pos, ...
1484
+      'String','Options for clearing', ...
1485
+      'Style','text'),'units','normalized');
1486
+
1487
+  set( ...
1488
+  uicontrol( ...                                                            %% [frame]
1489
+    'Units','pixels', ...
1490
+    'Position',frame1_pos, ...
1491
+    'Style','frame'),'units','normalized');
1492
+
1493
+  set( ...
1494
+  uicontrol( ...                                                               %% From subplots
1495
+    'Units','pixels', ...
1496
+    'Position',subplots_text_pos, ...
1497
+    'String','From subplots', ...
1498
+    'Style','text'),'units','normalized');
1499
+
1500
+  ed1_h = uicontrol( ...                                                       %% [edit]
1501
+    'Units','pixels', ...
1502
+    'BackgroundColor',bg_color2, ...
1503
+    'Position',subplots_pos, ...
1504
+    'FontSize',12, ...
1505
+    'Style','edit');
1506
+  set(ed1_h,'units','normalized');
1507
+
1508
+  set( ...
1509
+  uicontrol( ...                                                            %% [frame]
1510
+    'Units','pixels', ...
1511
+    'Position',frame2_pos, ...
1512
+    'Style','frame'),'units','normalized');
1513
+
1514
+  rb1_h = uicontrol( ...                                                       %% 
1515
+    'Units','pixels', ...
1516
+    'Position',radiob1_pos, ...
1517
+    'style','radiobutton', ...
1518
+    'String','All', ...
1519
+    'value',1);                
1520
+
1521
+  rb2_h = uicontrol( ...                                                       %% 
1522
+    'Units','pixels', ...
1523
+    'Position',radiob2_pos, ...
1524
+    'style','radiobutton', ...
1525
+    'String','Comet');                
1526
+
1527
+  rb3_h = uicontrol( ...                                                       %% 
1528
+    'Units','pixels', ...
1529
+    'Position',radiob3_pos, ...
1530
+    'style','radiobutton', ...
1531
+    'String','Hit');                
1532
+
1533
+  rb4_h = uicontrol( ...                                                       %% 
1534
+    'Units','pixels', ...
1535
+    'Position',radiob4_pos, ...
1536
+    'style','radiobutton', ...
1537
+    'String','Label');                
1538
+
1539
+  rb5_h = uicontrol( ...                                                       %% 
1540
+    'Units','pixels', ...
1541
+    'Position',radiob5_pos, ...
1542
+    'style','radiobutton', ...
1543
+    'String','Trajectory');                
1544
+
1545
+  set( ...
1546
+  uicontrol( ...                                                            %% [frame]
1547
+    'Units','pixels', ...
1548
+    'Position',frame3_pos, ...
1549
+    'Style','frame'),'units','normalized');
1550
+
1551
+  s = ['vis_show_gui_tool(' mat2str(h) ',''c_clear'',' mat2str(fig_h) ')'];
1552
+  set( ...
1553
+  uicontrol( ...                                                               %% OK
1554
+    'Units','pixels', ...
1555
+    'Position',ok_pos, ...
1556
+    'String','OK', ...
1557
+    'Callback',s),'units','normalized');
1558
+
1559
+  set( ...
1560
+  uicontrol( ...                                                               %% Cancel
1561
+    'Units','pixels', ...
1562
+    'Position',cancel_pos, ...
1563
+    'String','Cancel', ...
1564
+    'Callback',['close(' mat2str(fig_h) ')']),'units','normalized');
1565
+
1566
+  watchoff(old_fig_n);
1567
+  tmp_udata = [ed1_h rb1_h rb2_h rb3_h rb4_h rb5_h];
1568
+  set(fig_h,'units','normalized', ...
1569
+            'Visible','on', ...
1570
+            'UserData',tmp_udata, ...
1571
+            'handlevisibility','off');
1572
+
1573
+ %%%%%%%%%
1574
+% c_clear %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1575
+ %%%%%%%%%
1576
+elseif strcmp(action,'c_clear')
1577
+  thisfig = varargin{1};
1578
+  u = get(varargin{1},'UserData');
1579
+  s = get(u(1),'String');
1580
+  if ~isempty(s)
1581
+    if s(1)=='[' | (s(1)>='1' & s(1)<='9') 
1582
+      sprintf(s,'[%s]',s);
1583
+      e = eval(s); else e = s;
1584
+    end
1585
+    if vis_valuetype(e,{'1xn','nx1','string'}), 
1586
+      if ischar(e),
1587
+        if ~strcmp(e,'all'),
1588
+          errordlg({'Only valid string value' ...
1589
+                    'for subplot indices is ''all''.'}, ...
1590
+                    'Error in SOM_VIS: tools');
1591
+          return;
1592
+        else
1593
+          e=1:length(handles);
1594
+        end
1595
+      elseif any(e<1) | any(e>length(handles)),
1596
+        errordlg({'Subplot indices must be in', ...
1597
+               'range 1...number_of_subplots!'}, ...
1598
+              'Error in SOM_VIS: tools');
1599
+        return;
1600
+      end
1601
+    elseif ~isempty(e)
1602
+      errordlg('Invalid subplot indices!','Error in SOM_VIS: tools');
1603
+      return;
1604
+    end
1605
+  else,
1606
+    e = '';
1607
+  end
1608
+  set(0,'currentfigure',child)
1609
+  v = get(u(2),'value');
1610
+  if v,
1611
+    if ~isempty(e),
1612
+      som_show_clear('lab',e);
1613
+      som_show_clear('hit',e);
1614
+      som_show_clear('traj',e);
1615
+      som_show_clear('comet',e);
1616
+    else
1617
+      som_show_clear('lab');
1618
+      som_show_clear('hit');
1619
+      som_show_clear('traj');
1620
+      som_show_clear('comet');
1621
+    end
1622
+  end
1623
+  v = get(u(3),'value');
1624
+  if v,
1625
+    if ~isempty(e)
1626
+      som_show_clear('comet',e);
1627
+    else
1628
+      som_show_clear('comet');
1629
+    end
1630
+  end
1631
+  v = get(u(4),'value');
1632
+  if v,
1633
+    if ~isempty(e),
1634
+      som_show_clear('hit',e);
1635
+    else
1636
+      som_show_clear('hit');
1637
+    end
1638
+  end
1639
+  v = get(u(5),'value');
1640
+  if v,
1641
+    if ~isempty(e),
1642
+      som_show_clear('lab',e);
1643
+    else
1644
+      som_show_clear('lab');
1645
+    end
1646
+  end
1647
+  v = get(u(6),'value');
1648
+  if v,
1649
+    if ~isempty(e),
1650
+      som_show_clear('traj',e);
1651
+    else
1652
+      som_show_clear('traj');
1653
+    end
1654
+  end
1655
+  close(thisfig);
1656
+
1657
+ %%%%%%%%%%%%%%
1658
+% do_recolorbar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1659
+ %%%%%%%%%%%%%%
1660
+elseif strcmp(action,'do_recolorbar')
1661
+  args = {};
1662
+  ud = get(varargin{1},'UserData');
1663
+  s = get(ud(1),'String');
1664
+  e = 1:length(handles);
1665
+  if ~isempty(s)
1666
+    if s(1)=='[' | (s(1)>='1' & s(1)<='9') 
1667
+      sprintf(s,'[%s]',s);
1668
+      e = eval(s); else e = s;
1669
+    end
1670
+    if vis_valuetype(e,{'1xn','nx1','string'}), 
1671
+      if ischar(e) & ~strcmp(e,'all'),
1672
+        errordlg({'Only valid string value' ...
1673
+                  'for subplot indices is ''all''.'}, ...
1674
+                  'Error in SOM_VIS: tools');
1675
+        return;
1676
+      elseif any(e<1) | any(e>length(handles)),
1677
+        errordlg({'Subplot indices must be in', ...
1678
+               'range 1...number_of_subplots.'}, ...
1679
+              'Error in SOM_VIS: tools');
1680
+        return;
1681
+      end
1682
+    elseif ~isempty(e)
1683
+      errordlg('Invalid subplot indices!','Error in SOM_VIS: tools');
1684
+      return;
1685
+    end
1686
+  end
1687
+  args = [args {e}];
1688
+  s = get(ud(3),'String');
1689
+  tmp = 'auto';
1690
+  if strcmp(s,'auto') | strcmp(s,'border'),
1691
+    tmp = s;
1692
+  elseif ~isempty(s)
1693
+    tmp = evalin('base',s);
1694
+  end
1695
+  args = [args {tmp}];
1696
+  v = get(ud(4),'Value');
1697
+  s = get(ud(4),'String');
1698
+  args = [args {s{v}}];
1699
+  s = get(ud(2),'String');
1700
+  if ~isempty(s)
1701
+    args = [args {evalin('base',s)}];
1702
+  end
1703
+  thisfig = varargin{1};
1704
+  % set(0,'CurrentFigure',udata.vis_h);
1705
+  set(0,'currentfigure',child)
1706
+  som_recolorbar(args{:});
1707
+  close(thisfig);
1708
+
1709
+ %%%%%%%
1710
+% label %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1711
+ %%%%%%%
1712
+elseif strcmp(action,'label')
1713
+  args = {'label'};
1714
+  ud = get(varargin{1},'UserData');
1715
+  s = get(ud(2),'String');
1716
+  if ~isempty(s)
1717
+    args = [args {evalin('base',s)}];
1718
+  else
1719
+    args = [args {udata.sM}];
1720
+  end
1721
+  s = get(ud(3),'String');
1722
+  if ~isempty(s)
1723
+    args = [args {'TextSize' eval(s)}];
1724
+  end
1725
+  v = get(ud(4),'Value');
1726
+  if v>1,
1727
+    s = get(ud(4),'UserData');
1728
+    args = [args {'TextColor' s{v}}];
1729
+  end
1730
+  s = get(ud(1),'String');
1731
+  if ~isempty(s)
1732
+    if s(1)=='[' | (s(1)>='1' & s(1)<='9') 
1733
+      sprintf(s,'[%s]',s);
1734
+      e = eval(s); else e = s; 
1735
+    end
1736
+    if vis_valuetype(e,{'1xn','nx1','string'}), 
1737
+      if ischar(e),
1738
+        if ~strcmp(e,'all'),
1739
+          errordlg({'Only valid string value' ...
1740
+                    'for subplot indices is ''all''.'}, ...
1741
+                   'Error in SOM_VIS: tools');
1742
+          return;
1743
+        else
1744
+          e=1:length(handles);
1745
+        end
1746
+      elseif any(e<1) | any(e>length(handles)),
1747
+        errordlg({'Subplot indices must be in', ...
1748
+               'range 1...number_of_subplots!'}, ...
1749
+              'Error in SOM_VIS: tools');
1750
+        return;
1751
+      end
1752
+    elseif ~isempty(e)
1753
+      errordlg('Invalid subplot indices!','Error in SOM_VIS: tools');
1754
+      return;
1755
+    end
1756
+    args = [args {'SubPlot' e}];
1757
+  end
1758
+  thisfig = varargin{1};
1759
+  % set(0,'CurrentFigure',udata.vis_h);
1760
+  set(0,'currentfigure',child)
1761
+  som_show_add(args{:});
1762
+  close(thisfig);
1763
+
1764
+ %%%%%
1765
+% hit %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1766
+ %%%%%
1767
+elseif strcmp(action,'hit')
1768
+  args = {'hit'};
1769
+  ud = get(varargin{1},'UserData');
1770
+  s = get(ud(2),'String');
1771
+  e = evalin('base',s);
1772
+  [dummy k] = size(e);
1773
+  args = [args {e}];
1774
+  v = get(ud(10),'Value');
1775
+  s = get(ud(10),'UserData');
1776
+  args = [args {'EdgeColor' s{v}}];
1777
+  %
1778
+  s = get(ud(7),'String');
1779
+  if ~isempty(s)
1780
+    args = [args {'MarkerSize' eval(s)}];
1781
+  end
1782
+  if k == 1,
1783
+    v = get(ud(6),'Value');
1784
+    if v<16,
1785
+      s = get(ud(6),'String');
1786
+      args = [args {'Marker' s{v}}];
1787
+    else
1788
+      % errordlg();
1789
+      return;
1790
+    end
1791
+    v = get(ud(9),'Value');
1792
+    if v<10,
1793
+      s = get(ud(9),'UserData');
1794
+      args = [args {'MarkerColor' s{v}}];
1795
+    else
1796
+      % errordlg();
1797
+      return;
1798
+    end
1799
+    %
1800
+    v = get(ud(5),'Value');
1801
+    s = get(ud(5),'String');
1802
+    args = [args {'Text' s{v}}];
1803
+    if v>1,  % 1='off'
1804
+      v = get(ud(3),'Value');
1805
+      s = get(ud(3),'UserData');
1806
+      args = [args {'TextColor' s{v}}];
1807
+      %
1808
+      s = get(ud(4),'String');
1809
+      args = [args {'TextSize' eval(s)}];
1810
+    end
1811
+  else
1812
+    v = get(ud(8),'Value');
1813
+    s = get(ud(8),'String');
1814
+    args = [args {'SizeFactor' s{v}}];
1815
+    %
1816
+    v = get(ud(6),'Value');
1817
+    s = get(ud(6),'String');
1818
+    args = [args {'Marker' s{v}}];
1819
+    %
1820
+    v = get(ud(9),'Value');
1821
+    s = get(ud(9),'UserData');
1822
+    args = [args {'MarkerColor' s{v}}];
1823
+  end
1824
+
1825
+  s = get(ud(1),'String');
1826
+  if ~isempty(s)
1827
+    if s(1)=='[' | (s(1)>='1' & s(1)<='9') 
1828
+      sprintf(s,'[%s]',s);
1829
+      e = eval(s); else e = s; 
1830
+    end
1831
+    if vis_valuetype(e,{'1xn','nx1','string'}), 
1832
+      if ischar(e),
1833
+        if ~strcmp(e,'all'),
1834
+          errordlg({'Only valid string value' ...
1835
+                    'for subplot indices is ''all''.'}, ...
1836
+                   'Error in SOM_VIS: tools');
1837
+          return;
1838
+        else
1839
+          e=1:length(handles);
1840
+        end
1841
+      elseif any(e<1) | any(e>length(handles)),
1842
+        errordlg({'Subplot indices must be in', ...
1843
+               'range 1...number_of_subplots!'}, ...
1844
+              'Error in SOM_VIS: tools');
1845
+        return;
1846
+      end
1847
+    elseif ~isempty(e)
1848
+      errordlg('Invalid subplot indices!','Error in SOM_VIS: tools');
1849
+      return;
1850
+    end
1851
+    args = [args {'SubPlot' e}];
1852
+  end
1853
+  thisfig = varargin{1};
1854
+  % set(0,'CurrentFigure',udata.vis_h);
1855
+  set(0,'currentfigure',child)
1856
+  som_show_add(args{:});
1857
+  close(thisfig);
1858
+
1859
+ %%%%%%
1860
+% traj %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1861
+ %%%%%%
1862
+elseif strcmp(action,'traj')
1863
+  args = {'traj'};
1864
+  ud = get(varargin{1},'UserData');
1865
+  s = get(ud(2),'String');
1866
+  args = [args {evalin('base',s)}];
1867
+  s = get(ud(4),'String');
1868
+  if ~isempty(s)
1869
+    args = [args {'TrajWidth' eval(s)}];
1870
+  end
1871
+  v = get(ud(5),'Value');
1872
+  if v>1,
1873
+    s = get(ud(5),'String');
1874
+    args = [args {'WidthFactor' s{v}}];
1875
+  end
1876
+  v = get(ud(3),'Value');
1877
+  if v>1,
1878
+    s = get(ud(3),'UserData');
1879
+    args = [args {'TrajColor' s{v}}];
1880
+  end
1881
+  v = get(ud(6),'Value');
1882
+  if v>1,
1883
+    s = get(ud(6),'String');
1884
+    args = [args {'Marker' s{v}}];
1885
+  end
1886
+  s = get(ud(7),'String');
1887
+  if ~isempty(s)
1888
+    args = [args {'MarkerSize' eval(s)}];
1889
+  end
1890
+  v = get(ud(8),'Value');
1891
+  if v>1,
1892
+    s = get(ud(8),'String');
1893
+    args = [args {'SizeFactor' s{v}}];
1894
+  end
1895
+  v = get(ud(9),'Value');
1896
+  if v>1,
1897
+    s = get(ud(9),'UserData');
1898
+    args = [args {'MarkerColor' s{v}}];
1899
+  end
1900
+  v = get(ud(10),'Value');
1901
+  if v>1,
1902
+    s = get(ud(10),'UserData');
1903
+    args = [args {'EdgeColor' s{v}}];
1904
+  end
1905
+  s = get(ud(1),'String');
1906
+  if ~isempty(s)
1907
+    if s(1)=='[' | (s(1)>='1' & s(1)<='9') 
1908
+      sprintf(s,'[%s]',s);
1909
+      e = eval(s); else e = s; 
1910
+    end
1911
+    if vis_valuetype(e,{'1xn','nx1','string'}), 
1912
+      if ischar(e),
1913
+        if ~strcmp(e,'all'),
1914
+          errordlg({'Only valid string value' ...
1915
+                    'for subplot indices is ''all''.'}, ...
1916
+                   'Error in SOM_VIS: tools');
1917
+          return;
1918
+        else
1919
+          e=1:length(handles);
1920
+        end
1921
+      elseif any(e<1) | any(e>length(handles)),
1922
+        errordlg({'Subplot indices must be in', ...
1923
+               'range 1...number_of_subplots!'}, ...
1924
+              'Error in SOM_VIS: tools');
1925
+        return;
1926
+      end
1927
+    elseif ~isempty(e)
1928
+      errordlg('Invalid subplot indices!','Error in SOM_VIS: tools');
1929
+      return;
1930
+    end
1931
+    args = [args {'SubPlot' e}];
1932
+  end
1933
+  thisfig = varargin{1};
1934
+  % set(0,'CurrentFigure',udata.vis_h);
1935
+  set(0,'currentfigure',child)
1936
+  som_show_add(args{:});
1937
+  close(thisfig);
1938
+
1939
+ %%%%%%%
1940
+% comet %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1941
+ %%%%%%%
1942
+elseif strcmp(action,'comet')
1943
+  args = {'comet'};
1944
+  ud = get(varargin{1},'UserData');
1945
+  s = get(ud(2),'String');
1946
+  args = [args {evalin('base',s)}];
1947
+  v = get(ud(3),'Value');
1948
+  if v>1,
1949
+    s = get(ud(3),'String');
1950
+    args = [args {'Marker' s{v}}];
1951
+  end
1952
+  s = get(ud(4),'String');
1953
+  if ~isempty(s)
1954
+    args = [args {'MarkerSize' eval(s)}];
1955
+  end
1956
+  v = get(ud(5),'Value');
1957
+  s = get(ud(5),'UserData');
1958
+  if v==10,
1959
+    args = [args {'MarkerColor' evalin('base',s{10})}];
1960
+  else
1961
+    args = [args {'MarkerColor' s{v}}];
1962
+  end
1963
+  v = get(ud(6),'Value');
1964
+  if v>1,
1965
+    s = get(ud(6),'UserData');
1966
+    args = [args {'EdgeColor' s{v}}];
1967
+  end
1968
+  s = get(ud(1),'String');
1969
+  if ~isempty(s)
1970
+    if s(1)=='[' | (s(1)>='1' & s(1)<='9') 
1971
+      sprintf(s,'[%s]',s);
1972
+      e = eval(s); else e = s; 
1973
+    end
1974
+    if vis_valuetype(e,{'1xn','nx1','string'}), 
1975
+      if ischar(e),
1976
+        if ~strcmp(e,'all'),
1977
+          errordlg({'Only valid string value' ...
1978
+                    'for subplot indices is ''all''.'}, ...
1979
+                   'Error in SOM_VIS: tools');
1980
+          return;
1981
+        else
1982
+          e=1:length(handles);
1983
+        end
1984
+      elseif any(e<1) | any(e>length(handles)),
1985
+        errordlg({'Subplot indices must be in', ...
1986
+               'range 1...number_of_subplots!'}, ...
1987
+              'Error in SOM_VIS: tools');
1988
+        return;
1989
+      end
1990
+    elseif ~isempty(e)
1991
+      errordlg('Invalid subplot indices!','Error in SOM_VIS: tools');
1992
+      return;
1993
+    end
1994
+    args = [args {'SubPlot' e}];
1995
+  end
1996
+  thisfig = varargin{1};
1997
+  % set(0,'CurrentFigure',udata.vis_h);
1998
+  set(0,'currentfigure',child)
1999
+  som_show_add(args{:});
2000
+  close(thisfig);
2001
+
2002
+ %%%%%%%%
2003
+% select %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2004
+ %%%%%%%%
2005
+elseif strcmp(action,'select')
2006
+  %% NOTE: input h is not main_gui_handle
2007
+  %%       but edit menu handle
2008
+  w = evalin('base','whos');
2009
+  for (i=1:length(w)) 
2010
+    size_frst{i} = mat2str(w(i).size(1));
2011
+    x(i,1) = 'x';
2012
+    size_scnd{i} = mat2str(w(i).size(2));
2013
+  end    
2014
+  names = strvcat(w.name);
2015
+  [dummy vert] = size(names);
2016
+  for (i=1:length(w))
2017
+    for (j=1:8)
2018
+      sp(i,j) = ' ';
2019
+    end
2020
+  end
2021
+  size_M = strjust(strvcat(size_frst{:}),'right');
2022
+  size_N = strjust(strvcat(size_scnd{:}),'left');
2023
+  classes = strvcat(w.class);
2024
+  s = [cellstr([names sp size_M x size_N sp classes])]';
2025
+
2026
+  [sel,ok] = listdlg('ListString',s,...
2027
+                     'Name','Variable selection',...
2028
+                     'PromptString','Select variable', ...
2029
+                     'SelectionMode','single');
2030
+  if ok & ~isempty(sel), 
2031
+    w = {w.name};
2032
+    if ishandle(h),
2033
+      set(h,'String',w{sel});
2034
+    elseif nargout==1,
2035
+      r = w{sel};
2036
+    end
2037
+  elseif nargout==1,
2038
+    r = '';
2039
+  end
2040
+
2041
+ %%%%%%%%%%%%%%
2042
+% popup_select %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2043
+ %%%%%%%%%%%%%%
2044
+elseif strcmp(action,'popup_select')
2045
+  %% NOTE: input h is not main_gui_handle
2046
+  %%       but h(1) is popupmenu handle and h(2:end) are indeces
2047
+  v = get(h(1),'Value');
2048
+  if any(v==h(2:end)),
2049
+    w = evalin('base','whos');
2050
+    for (i=1:length(w)) 
2051
+      size_frst{i} = mat2str(w(i).size(1));
2052
+      x(i,1) = 'x';
2053
+      size_scnd{i} = mat2str(w(i).size(2));
2054
+    end
2055
+    names = strvcat(w.name);
2056
+    [dummy vert] = size(names);
2057
+    for (i=1:length(w))
2058
+      for (j=1:8)
2059
+        sp(i,j) = ' ';
2060
+      end
2061
+    end
2062
+    size_M = strjust(strvcat(size_frst{:}),'right');
2063
+    size_N = strjust(strvcat(size_scnd{:}),'left');
2064
+    classes = strvcat(w.class);
2065
+    s = [cellstr([names sp size_M x size_N sp classes])]';
2066
+    [sel,ok] = listdlg('ListString',s,...
2067
+                       'Name','Variable selection',...
2068
+                       'PromptString','Select variable', ...
2069
+                       'SelectionMode','single');
2070
+    if ok & ~isempty(sel),
2071
+      w = {w.name};
2072
+      i = find(v==h(2:end));
2073
+      s = get(h(1),'String');
2074
+      s{h(i+1)} = w{sel};
2075
+      set(h(1),'String',s);
2076
+      if nargout==1,
2077
+        r = w{sel};
2078
+      end
2079
+    elseif nargout==1,
2080
+      r = '';
2081
+    end    
2082
+  end
2083
+
2084
+end
2085
+
... ...
@@ -0,0 +1,151 @@
1
+function [handles,msg,lattice,msize,dim,normalization,comps]=vis_som_show_data(p,f)
2
+
3
+% VIS_SOM_SHOW_DATA Checks and returns UserData and subplot handles stored by SOM_SHOW
4
+%
5
+% [handles,msg,lattice,msize,dim,normalization,comps] = vis_som_show_data(p, f)
6
+%
7
+%  Input and output arguments ([]'s are optional): 
8
+%   [p]           (vector) subplot numbers 
9
+%                 (string) 'all' to process all subplots, this is default
10
+%                          'comp' to process only subplots which have
11
+%                          component planes
12
+%   [f]           (double) figure handle, default is current figure
13
+%
14
+%   handles       (vector) handles of requested subplots
15
+%   msg           (string) error message or empty string (no error)
16
+%   lattice       (string) map lattice: 'hexa' or 'rect'
17
+%   msize         (vector) map grid size in figure
18
+%   dim           (scalar) map data dimension in figure
19
+%   normalization (struct) normalization struct used in the map in figure
20
+%   comps         (vector) the component indexes in figure
21
+%
22
+% This function gets the handles of component planes and u-matrices in
23
+% subplots p from figure f. SOM_SHOW writes the handles into the
24
+% UserData field of the figure where their order won't be mixed
25
+% up. This function reads the data according to the vector p. If the
26
+% figure has been manipulated (original planes are missing) the function
27
+% warns user or returns error string.
28
+% 
29
+% The main purpose for this is to be a subfuncion for SOM_SHOW_ADD,
30
+% SOM_SHOW_CLEAR and SOM_RECOLORBAR functions, but it may be used on
31
+% command line in the followong manner:
32
+%
33
+%  % plots text on the fifth plane
34
+%  axes(vis_som_show_data(5)); hold on; text(1,3,'I am here');
35
+%    
36
+% See also SOM_SHOW, SOM_SHOW_ADD.
37
+
38
+% Copyright (c) 1997-2000 by the SOM toolbox programming team.
39
+% http://www.cis.hut.fi/projects/somtoolbox/             
40
+
41
+% Version 2.0beta Johan 201099 juuso 160600
42
+
43
+%% Check input args %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
44
+
45
+error(nargchk(0, 2, nargin))  % check no. of input args 
46
+
47
+%% Init %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
48
+
49
+handles=[];                                     % initialize output
50
+normalize=[];
51
+comps=[];
52
+dim=[];
53
+msize=[];
54
+lattice=[];
55
+msg=[];      
56
+
57
+cr=sprintf('\n');                               % carriage return            
58
+
59
+if nargin < 2 | isempty(f)
60
+  f=gcf;                                        % default figure
61
+end
62
+
63
+if nargin < 1 | isempty(p)                      % default p 
64
+  p= 'all';
65
+end
66
+
67
+% Find component planes and u-matrices from the figure and get the 
68
+% UserData field where the handles for the components are 
69
+% in the original order. 
70
+% If the fields are corrupted, return an error message.
71
+
72
+h_real = [findobj(f, 'Tag', 'Cplane'); ...
73
+    findobj(f, 'Tag', 'Uplane'); ...
74
+    findobj(f,'Tag','CplaneI'); ...
75
+    findobj(f,'Tag','UplaneI')];
76
+eval( 'h_stored=getfield(get(f,''UserData''),''subplotorder'');' , ...
77
+    'msg=[ msg cr '' Missing SOM_SHOW.subplotorder''];');  
78
+eval( 'normalization=getfield(get(f,''UserData''),''comp_norm'');' , ...
79
+    'msg=[msg cr '' Missing SOM_SHOW.comp_norm''];');
80
+eval( 'comps=getfield(get(f,''UserData''),''comps'');' , ...
81
+    'msg=[msg cr '' Missing SOM_SHOW.comps''];');    
82
+eval( 'msize=getfield(get(f,''UserData''),''msize'');' , ...
83
+    'msg=[msg cr '' Missing SOM_SHOW.msize''];');    
84
+eval( 'dim=getfield(get(f,''UserData''),''dim'');' , ...
85
+    'msg=[msg cr '' Missing SOM_SHOW.dim''];');    
86
+eval( 'lattice=getfield(get(f,''UserData''),''lattice'');' , ...
87
+    'msg=[msg cr '' Missing SOM_SHOW.lattice''];');    
88
+if ~isempty(msg), 
89
+  msg=['The figure does not contain SOM_SHOW visualization or is corrupted.'...
90
+	cr msg cr cr ...
91
+	'This command may be applied only to a SOM_SHOW visualization.']; 
92
+  return; 
93
+end
94
+
95
+%% Check arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
96
+
97
+index=ismember(h_stored, h_real);  % the original order for plot axes 
98
+
99
+if ~prod(double(index))                    % missing planes?!
100
+                                           % double added by kr 1.10.02
101
+  l1= 'Some of the original planes seems to be missing.';
102
+  l2= 'Subplot numbers now refer to the existing ones.';
103
+  warning([l1 cr l2]);
104
+end
105
+
106
+if ~prod(double(ismember(h_real, h_stored))) % extra planes?! 
107
+                                             % double added by kr 5.9.02
108
+  warning('There seems to be new planes. Subplot numbers refer to the old ones.');
109
+end
110
+
111
+h_stored=h_stored(index);          % existing original plots in original order
112
+
113
+if ischar(p)                       % check if p is 'all'
114
+  switch(p)
115
+   case 'all'                                   
116
+    p=1:size(h_stored,1);          % all original subplots
117
+   case 'comp'
118
+    p=find(comps>0); 
119
+   otherwise
120
+    msg= 'String value for subplot number vector has to be ''all''!';
121
+    return;
122
+  end
123
+end
124
+
125
+if ~vis_valuetype(p,{ '1xn','nx1'}) % check the size
126
+  msg= 'Subplot numbers (argument p in help text) have to be in a vector!';
127
+  return
128
+end
129
+
130
+if min(p) < 1                      % check for invalid values
131
+  msg= 'Subplot numbers (argument p in help text) must be at least 1!';
132
+  return
133
+end
134
+
135
+%% p is too large
136
+
137
+if max(p) > size(h_stored,1)
138
+  l1= 'There are not so many existing subplots created by SOM_SHOW in the';
139
+  l2= 'figure as you are trying to refer with subplot numbers.';
140
+  l3= 'This is probably caused by having a too large subplot number.';
141
+  l4= 'However, the reason may be invalid manipulation of';
142
+  l5= 'this figure object or a program failure, too.';
143
+  msg=([l1 cr l2 cr l3 cr cr l4 cr l5]);
144
+  return;
145
+end
146
+
147
+%% Action and building output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
148
+
149
+handles=h_stored(p);
150
+comps=comps(p);
151
+
... ...
@@ -0,0 +1,1647 @@
1
+function vis_trajgui(trajStruct,arg)
2
+
3
+% VIS_TRAJGUI subfuntion for SOM_TRAJECTORY
4
+%
5
+% This function is the actual GUI called by SOM_TRAJECTORY
6
+% function. 
7
+%
8
+% See also SOM_TRAJECTORY.
9
+
10
+% Contributed code to SOM Toolbox 2.0, February 11th, 2000 by Juha Parhankangas
11
+% Copyright (c) by Juha Parhankangas.
12
+% http://www.cis.hut.fi/projects/somtoolbox/        
13
+
14
+% Version 2.0beta juha 180699
15
+
16
+if nargin == 1
17
+
18
+  sM_h=trajStruct.figure;
19
+
20
+  if size(trajStruct.bmus,1) ~= 1 & size(trajStruct.bmus,2) ~= 1
21
+    fuzzy_traj(trajStruct,[]);
22
+    return;
23
+  end
24
+  
25
+  
26
+  if size(trajStruct.bmus,1) == 1 | size(trajStruct.bmus,2) == 1
27
+
28
+    udata.bmus = trajStruct.bmus;
29
+    udata.a_h=[findobj(get(sM_h,'Children'),'Tag','Uplane');...
30
+	       findobj(get(sM_h,'Children'),'Tag','Cplane')];
31
+    udata.sM_h=trajStruct.figure;
32
+    udata.traj=[];
33
+    data1 = trajStruct.primary_data;
34
+    if ~isempty(trajStruct.primary_names)
35
+      names=trajStruct.primary_names;
36
+    else
37
+      for i=1:size(data1,2)
38
+	names{i,1}=sprintf('Var%d',i);
39
+      end
40
+    end
41
+
42
+    udata.lattice=trajStruct.lattice;
43
+    form = 0.7*vis_patch(udata.lattice);
44
+    udata.msize = trajStruct.msize;
45
+
46
+
47
+    %%%%%%%%%%%%%%%%%%%%%%%%
48
+    %
49
+    % forming a patch object, which is placed above every component plane
50
+    %
51
+    
52
+    
53
+    l = size(form,1);
54
+    
55
+    nx = repmat(form(:,1),1,prod(udata.msize));
56
+    ny = repmat(form(:,2),1,prod(udata.msize));
57
+    
58
+    x=reshape(repmat(1:udata.msize(2),l*udata.msize(1),1),l,prod(udata.msize));
59
+    y=repmat(repmat(1:udata.msize(1),l,1),1,udata.msize(2));
60
+    
61
+    if strcmp(udata.lattice,'hexa')
62
+      t = find(~rem(y(1,:),2));
63
+      x(:,t)=x(:,t)+.5;
64
+    end
65
+    x=x+nx;
66
+    y=y+ny;
67
+    
68
+    colors=reshape(ones(prod(udata.msize),1)*[NaN NaN NaN],...
69
+		   [1 prod(udata.msize) 3]);
70
+    
71
+    set(0,'CurrentFigure',udata.sM_h);
72
+    
73
+    %%%%%%%%%%%%%%%%%%%%%%
74
+    %
75
+    % drawing patch
76
+    %
77
+    % caxis -commands keep the colormap of the original patch unchanged.
78
+    %
79
+    
80
+    for i=1:length(udata.a_h)
81
+      udata.real_patch(i)=get(udata.a_h(i),'Children');
82
+      set(udata.real_patch(i),'ButtonDownFcn',...
83
+			'vis_trajgui([],''click'')');
84
+      subplot(udata.a_h(i));
85
+      v=caxis;
86
+      udata.tmp_patch(i)=patch(x,y,colors,'EdgeColor','none',...
87
+			       'ButtonDownFcn',...
88
+			       'vis_trajgui([],''click'')',...
89
+			       'Tag','TmpPatch');
90
+      caxis(v);
91
+    end
92
+    
93
+    %%%%%%%%%%%%%%%%%%%%
94
+    
95
+    
96
+    
97
+    udata.length_of_traj=length(trajStruct.size);
98
+    udata.size=trajStruct.size;
99
+    udata.color=trajStruct.color;
100
+    udata.poly.x=[];
101
+    udata.poly.y=[];
102
+    udata.poly.h=[];
103
+    udata.new_marks=[];
104
+    udata.all_marks=[];
105
+    udata.d_mark2=[];
106
+    udata.fig1 = figure;
107
+    set(udata.fig1,'KeyPressFcn','vis_trajgui([],''key'')',...
108
+		   'Name','Primary Data');
109
+    
110
+    
111
+    %%%%%%%%%%%%%%%%%%%%
112
+    %
113
+    % making the 'Tools' -menu
114
+    %
115
+    
116
+    udata.m_i=uimenu(udata.fig1,'Label','Trajectoy T&ools');
117
+    udata.m_i(2)=uimenu(udata.m_i,'Label','&Remove Trajectory',...
118
+			'Callback',...
119
+			'vis_trajgui([],''remove_traj'')');
120
+    udata.m_i(3)=uimenu(udata.m_i(1),'Label','&Dye Nodes',...
121
+			'Callback',...
122
+			'vis_trajgui([],''dye_gui'')');
123
+    udata.m_i(4)=uimenu(udata.m_i(1),'Label','&Clear Markers',...
124
+			'Callback',...
125
+			'vis_trajgui([],''clear'')');
126
+    udata.m_i(5)=uimenu(udata.m_i(1),'Label','&Save',...
127
+			'Callback',...
128
+			'vis_trajgui([],''save'')');
129
+    udata.m_i(6)=uimenu(udata.m_i(1),'Label','&Load',...
130
+			'Callback',...
131
+			'vis_trajgui([],''load'')');
132
+
133
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
134
+    %
135
+    % drawing data components to the figure ....
136
+    %
137
+    % 
138
+    
139
+    if nargin < 5 | isempty(comps) | (isstr(comps) & strcmp(comps,'all'))
140
+      comps = 1:size(data1,2);
141
+    end
142
+    
143
+    x=1:size(data1,1);
144
+    
145
+    for i=1:length(comps)
146
+      subplot(length(comps),1,i);
147
+      udata.h(i)=gca;
148
+      udata.d_mark(i).h=[];
149
+      
150
+      udata.d(i)=plot(x,data1(:,comps(i)),...
151
+		      'ButtonDownFcn',...
152
+		      'vis_trajgui([],''line_down'')');        
153
+      set(gca,'XLim',[1 size(data1,1)],...
154
+	      'XTick',[],...	      
155
+	      'ButtonDownFcn','vis_trajgui([],''line_down'')'); %,...
156
+	      %'YLim',[min(data1(:,comps(i))) max(data1(:,comps(i)))]);
157
+	      
158
+      ylabel(names{comps(i)});
159
+      hold on;
160
+      ymin=get(udata.h(i),'YLim');
161
+      pos=mean(get(udata.h(i),'XLim'));
162
+      udata.l(i) = line([pos pos],[ymin(1) ymin(2)],...
163
+			'Color','red',...
164
+			'ButtonDownFcn',...
165
+			'vis_trajgui([],''down'')');
166
+    end
167
+    udata.text1=[];
168
+    
169
+    udata.fig2=[];
170
+    udata.h2=[];
171
+    udata.l2=[];
172
+    udata.text2=[];
173
+    
174
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%
175
+    %
176
+    % ... and to the figure 2.
177
+    %
178
+    
179
+    
180
+    if ~isempty(trajStruct.secondary_data)
181
+      data2=trajStruct.secondary_data;
182
+      if isempty(trajStruct.secondary_names)
183
+	for i=1:size(data1,2)
184
+	  names2{i,1}=sprintf('Var%d',i);
185
+	end
186
+      else
187
+	names2=trajStruct.secondary_names;
188
+      end
189
+      
190
+      udata.fig2 = figure;
191
+      set(udata.fig2,'Name','Secondary Data');
192
+      set(udata.fig2,'KeyPressFcn',...
193
+		     'vis_trajgui([],''key'')');
194
+      for i=1:size(data2,2)
195
+	subplot(size(data2,2),1,i);
196
+	udata.h2(i) = gca;
197
+	udata.d_mark2(i).h=[];
198
+	udata.d2(i) = plot(x,data2(:,i),...
199
+			   'ButtonDownFcn',...
200
+			   'vis_trajgui([],''line_down'')');
201
+	set(gca,'XLim',[1 size(data1,1)],'XTick',[],'ButtonDownFcn',...
202
+		'vis_trajgui([],[],[],[],[],[],''line_down'')');
203
+	ylabel(names2{i});
204
+	hold on;
205
+	ymin = get(udata.h2(i),'YLim');
206
+	pos = mean(get(udata.h2(i),'XLim'));
207
+	udata.l2(i) = line([pos pos],ymin,'Color','red',...
208
+			   'ButtonDownFcn','vis_trajgui([],''down'')');
209
+      end
210
+    end  
211
+    
212
+    %%%%%%%%%%%%%%%%%%%%%%%%%%
213
+    
214
+    set(udata.fig1,'UserData',udata);
215
+    if ~isempty(udata.fig2);
216
+      tmp.fig1=udata.fig1;
217
+      set(udata.fig2,'UserData',tmp);
218
+    end
219
+    tmp=get(udata.sM_h,'UserData');
220
+    tmp.fig1=udata.fig1;
221
+    set(udata.sM_h,'UserData',tmp);  
222
+    set_numbers(round(pos)); 
223
+    return;
224
+  end
225
+  
226
+end
227
+
228
+%%%%%%%%%%%%%%%%%
229
+%
230
+% if figures have been drawn, the only function calls that may exist
231
+% are the ones that change the state of the application.
232
+%
233
+udata=get(gcf,'UserData');
234
+udata=get(udata.fig1,'UserData');
235
+
236
+switch arg
237
+ case 'fuzzy'
238
+  fuzzy_traj(tS,[]);
239
+  return;
240
+ case 'move_fuzzy'
241
+  fuzzy_traj([],'move');
242
+  return;
243
+ case 'remove_traj'
244
+  remove_traj;
245
+  return;
246
+ case 'line_down'
247
+  line_bdf('down');
248
+  return;
249
+ case 'line_drag'
250
+  line_bdf('drag');
251
+  return;
252
+ case 'line_up'
253
+  line_bdf('up');
254
+  return;
255
+ case 'dye_gui';
256
+  color_gui(udata.fig1);
257
+  return;
258
+ case {'dye','cyan','magenta','yellow','red','green','blue','white','grey'}
259
+  dye_nodes(arg);
260
+  return;
261
+ case 'clear'
262
+  clear_markers;
263
+  return;
264
+ case 'key'
265
+  key_bdf;
266
+  return;   
267
+ case 'click'
268
+  click;
269
+  return;
270
+ case 'save'
271
+  save_data;
272
+  return;
273
+ case 'load'
274
+  load_data;
275
+  return;
276
+end
277
+
278
+
279
+%%%%%%%%%%
280
+%
281
+% lines in the data figure(s) are dragged ...
282
+%
283
+
284
+udata=get(gcf,'UserData');
285
+udata=get(udata.fig1,'UserData');
286
+
287
+
288
+lims=get(gca,'XLim');
289
+x = getfield(get(gca,'CurrentPoint'),{1});  % the location of the line
290
+
291
+if x < lims(1)
292
+  x=lims(1);
293
+elseif x > lims(2)
294
+  x=lims(2);
295
+end
296
+
297
+old = gcf;
298
+
299
+switch arg
300
+ case 'down',...
301
+      
302
+  % mouse button is pressed down above the line
303
+  
304
+  set(gcf,'WindowButtonMotionFcn','vis_trajgui([],''drag'')');
305
+  set(gcf,'WindowButtonUpFcn','vis_trajgui([],''up'')');
306
+  set(udata.l,'EraseMode','xor');
307
+  delete(udata.text1);
308
+  if ~isempty(udata.l2);
309
+    set(udata.l2,'EraseMode','xor');
310
+    delete(udata.text2);
311
+  end
312
+  set(gcf,'Pointer','crosshair');
313
+  
314
+ case 'drag'
315
+  % change the location of the lines
316
+  
317
+  set(0,'CurrentFigure',udata.fig1);
318
+  set(udata.l,'XData',[x x]);
319
+  if ~isempty(udata.fig2)
320
+    set(0,'CurrentFigure',udata.fig2);
321
+    set(udata.l2,'XData',[x x]);
322
+  end
323
+  draw_traj(round(x));
324
+  set(0,'CurrentFigure',old);
325
+ case 'up'
326
+  
327
+  % draw trajectory and set figure to the normal state.
328
+  
329
+  set(udata.l,'EraseMode','normal');
330
+  set(gcf,'Pointer','arrow','WindowButtonMotionFcn','',...
331
+	  'WindowButtonUpFcn','');
332
+  draw_traj(round(x));
333
+  set_numbers(round(x));
334
+end
335
+
336
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
337
+
338
+function draw_traj(point)
339
+
340
+udata=get(gcf,'UserData');
341
+udata=get(udata.fig1,'UserData');
342
+color=udata.color;
343
+eMode='normal';
344
+if isstr(udata.color) & strcmp(udata.color,'xor')
345
+  eMode='xor';
346
+  color='black';
347
+end
348
+ind=udata.bmus(point);
349
+[i j] = ind2sub(udata.msize,ind);
350
+if ~mod(i,2)
351
+  j=j+0.5;
352
+end
353
+old = gcf;
354
+set(0,'CurrentFigure',udata.sM_h);
355
+hold on;
356
+if isempty(udata.traj) | length(udata.traj.h) ~= length(udata.a_h)
357
+  
358
+  % trajectory does not exist
359
+  
360
+  for i=1:length(udata.a_h)
361
+    subplot(udata.a_h(i));
362
+    hold on;
363
+    new.h = plot(j,i,'Color',color,'EraseMode',eMode,'LineStyle','none');
364
+    udata.traj.h(i)=new;
365
+    udata.traj.j=j;
366
+    udata.traj.i=i;
367
+  end
368
+else
369
+  if length(udata.traj.j) == udata.length_of_traj
370
+    % if the length of trajectory == ..., 
371
+    udata.traj.j(1) = [];         % the first (the oldest) coordinate pair
372
+    udata.traj.i(1) = [];         % is removed.
373
+  end
374
+  udata.traj.j=[udata.traj.j;j]; % the new point is added to the
375
+  udata.traj.i=[udata.traj.i;i]; % end of coordinate vectors (i and j)
376
+  for i=1:length(udata.a_h)
377
+    subplot(udata.a_h(i));            % remove the existing trajectory
378
+    delete(udata.traj.h(i).h);          % and plot the new one.
379
+    for j=1:length(udata.traj.j)
380
+      udata.traj.h(i).h(j)=plot(udata.traj.j(j),udata.traj.i(j),...
381
+				'Color',color,...
382
+				'EraseMode',eMode,'Marker','o','LineWidth',2,...
383
+				'MarkerSize',udata.size(udata.length_of_traj-j+1),...
384
+				'LineStyle','none');
385
+    end
386
+  end
387
+end 
388
+set(0,'CurrentFigure',udata.fig1);
389
+set(udata.fig1,'UserData',udata);
390
+
391
+
392
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
393
+
394
+function set_numbers(x);
395
+
396
+% This function writes the numbers beside of the pointer lines
397
+
398
+
399
+udata=get(gcf,'UserData');
400
+udata=get(udata.fig1,'UserData');
401
+
402
+xlim = get(gca,'XLim');
403
+ylim = get(gca,'YLim');
404
+p = ylim(1) + 0.9*(ylim(2)-ylim(1));
405
+
406
+old = gcf;
407
+set(0,'CurrentFigure',udata.fig1);
408
+
409
+
410
+for i=1:length(udata.h)
411
+  subplot(udata.h(i));
412
+  
413
+  % check if the text is placed to the left side of the line...
414
+  
415
+  if abs(x-xlim(1)) > (abs(x-xlim(2)))
416
+    udata.text1(i)=text(x-1,p,sprintf('%d ->',x),...
417
+                        'VerticalAlignment','top',...
418
+                        'HorizontalAlignment','right',...
419
+                        'FontWeight','demi');
420
+  else
421
+    
422
+    %  or to the right side.
423
+    
424
+    udata.text1(i)=text(x+1,p,sprintf('<- %d',x),...
425
+			'VerticalAlignment','top',...
426
+			'FontWeight','demi');
427
+  end
428
+end
429
+
430
+if ~isempty(udata.fig2)
431
+  set(0,'CurrentFigure',udata.fig2);
432
+  
433
+  for i=1:length(udata.h2)
434
+    subplot(udata.h2(i));
435
+    
436
+    if abs(x-xlim(1)) > (abs(x-xlim(2)))
437
+      udata.text2(i)=text(x-1,p,sprintf('%d ->',x),...
438
+			  'VerticalAlignment','top',...
439
+			  'HorizontalAlignment','right',...
440
+			  'FontWeight','demi');
441
+    else
442
+      udata.text2(i)=text(x+1,p,sprintf('<- %d',x),...
443
+			  'VerticalAlignment','top',...
444
+			  'FontWeight','demi');
445
+    end
446
+  end
447
+end
448
+
449
+set(0,'CurrentFigure',old);
450
+set(udata.fig1,'UserData',udata);
451
+
452
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
453
+
454
+function remove_traj()
455
+
456
+% delete trajectory -object from every component plane.
457
+
458
+udata=get(gcf,'UserData');
459
+udata=get(udata.fig1,'UserData');
460
+
461
+if isempty(udata.traj)
462
+  return;
463
+end
464
+
465
+
466
+for i=1:length(udata.traj.h)
467
+  delete(udata.traj.h(i).h);
468
+end
469
+
470
+udata.traj=[];
471
+set(udata.fig1,'UserData',udata);
472
+
473
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
474
+
475
+function line_bdf(arg)
476
+
477
+% this function takes care of action when region is selected in the
478
+% data figure.
479
+
480
+
481
+udata=get(gcf,'UserData');
482
+udata=get(udata.fig1,'UserData');
483
+xlim=get(gca,'XLim');
484
+
485
+if ~(any(strcmp('THIS',fieldnames(udata))))
486
+  p = getfield(get(gca,'CurrentPoint'),{1});
487
+else
488
+  p = getfield(get(udata.THIS,'CurrentPoint'),{1});
489
+end
490
+
491
+if p < xlim(1)
492
+  p = xlim(1);
493
+elseif p > xlim(2)
494
+  p = xlim(2);
495
+end
496
+
497
+
498
+
499
+switch arg
500
+ case 'down'
501
+  
502
+  % the mouse button is pressed down, the pointer lines are drawn.
503
+  % and the state of the figure is changed.
504
+  
505
+  udata.THIS=gca;
506
+  set(gcf,'WindowButtonMotionFcn',...
507
+	  'vis_trajgui([],''line_drag'')',...
508
+	  'WindowButtonUpFcn','vis_trajgui([],''line_up'')');
509
+  udata.start_p=p;
510
+  
511
+  old = gcf;
512
+  set(0,'CurrentFigure',udata.fig1);
513
+  
514
+  for i=1:length(udata.h)
515
+    subplot(udata.h(i));
516
+    udata.t_line.h(i)=line([p p],get(gca,'YLim'),'Color','red');
517
+    udata.t_line.h2(i)=line([p p],get(gca,'YLim'),'Color','red',...
518
+			    'EraseMode','xor');
519
+  end
520
+  if ~isempty(udata.h2)
521
+    set(0,'CurrentFigure',udata.fig2);
522
+    for i=1:length(udata.h2)
523
+      subplot(udata.h2(i));
524
+      udata.t_line2.h(i)=line([p p],get(gca,'YLim'),'Color','red');
525
+      udata.t_line2.h2(i)=line([p p],get(gca,'YLim'),'Color','red',...
526
+			       'EraseMode','xor');
527
+    end
528
+  end
529
+  
530
+ case 'drag'
531
+  
532
+  % change the position of the pointer lines
533
+  
534
+  old = gcf;
535
+  set(0,'CurrentFigure',udata.fig1);
536
+  set(udata.t_line.h2,'XData',[p p]);
537
+  if ~isempty(udata.fig2)
538
+    set(0,'CurrentFigure',udata.fig2);
539
+    set(udata.t_line2.h2,'XData',[p p]);
540
+  end
541
+  set(0,'CurrentFigure',old);
542
+ case 'up'
543
+  
544
+  
545
+  % sort the 'points' -vector and draw the markers to the data and nodes
546
+  
547
+  points=sort([round(udata.start_p) round(p)]);
548
+  draw_markers(points(1):points(2));
549
+  udata=get(udata.fig1,'UserData');
550
+  udata.new_marks=unique([udata.new_marks ;(points(1):points(2))']);
551
+  delete([udata.t_line.h2 udata.t_line.h]);
552
+  if ~isempty(udata.fig2)
553
+    delete([udata.t_line2.h2 udata.t_line2.h]);
554
+  end
555
+  set(get(udata.THIS,'Parent'),'WindowButtonMotionFcn','',...
556
+		    'WindowButtonUpFcn','');
557
+  udata=rmfield(udata,'THIS');
558
+end
559
+
560
+set(udata.fig1,'UserData',udata);
561
+
562
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
563
+
564
+function draw_markers(x);
565
+
566
+plot2data(x);
567
+plot2plane(x);
568
+
569
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
570
+
571
+function plot2data(x);
572
+
573
+% plot black markers to the data figure(s)
574
+
575
+udata=get(gcf,'UserData');
576
+udata=get(udata.fig1,'UserData');
577
+
578
+old = gcf;
579
+
580
+set(0,'CurrentFigure',udata.fig1);
581
+
582
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
583
+
584
+% if there already exist points in the positions that are members
585
+% of the set x, then the old points are removed from data figures...
586
+
587
+for i=1:length(udata.d_mark(1).h)
588
+  tmp1 = get(udata.d_mark(1).h(i),'XData');
589
+  tmp2 = setdiff(tmp1,x);
590
+  if length(tmp1) ~= length(tmp2)
591
+    inds=[];
592
+    for j=1:length(tmp2);
593
+      inds=[inds find(tmp2(j)==tmp1)];
594
+    end
595
+    for j=1:length(udata.d_mark)
596
+      ydata=getfield(get(udata.d_mark(j).h(i),'YData'),{inds});
597
+      set(udata.d_mark(j).h(i),'XData',tmp2,'YData',ydata);
598
+    end
599
+    if ~isempty(udata.fig2)
600
+      for j=1:length(udata.d_mark2)
601
+        ydata=getfield(get(udata.d_mark2(j).h(i),'YData'),{inds});
602
+        set(udata.d_mark2(j).h(i),'XData',tmp2,'YData',ydata);
603
+      end
604
+    end
605
+  end
606
+end
607
+
608
+
609
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
610
+
611
+% ... and the new ones are plotted.
612
+
613
+for i=1:length(udata.h)
614
+  subplot(udata.h(i));
615
+  h=plot(x,getfield(get(udata.d(i),'YData'),{x}),'oblack',...
616
+	 'ButtonDownFcn',...
617
+	 'vis_trajgui([],''line_down'')');
618
+  udata.d_mark(i).h=[udata.d_mark(i).h;h];
619
+end
620
+
621
+if ~isempty(udata.h2)
622
+  set(0,'CurrentFigure',udata.fig2);
623
+  
624
+  for i=1:length(udata.h2)
625
+    subplot(udata.h2(i));
626
+    h=plot(x,getfield(get(udata.d2(i),'YData'),{x}),'oblack',...
627
+	   'ButtonDownFcn',...
628
+	   'vis_trajgui([],''line_down'')');
629
+    udata.d_mark2(i).h=[udata.d_mark2(i).h;h];
630
+  end
631
+end
632
+
633
+set(0,'CurrentFigure',old);
634
+set(udata.fig1,'UserData',udata);
635
+
636
+
637
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
638
+
639
+function plot2plane(x);
640
+
641
+% sets markers to the component planes.
642
+
643
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
644
+%
645
+% actually new markers are never plotted, but the color of the patch
646
+% lying above the original component plane patch is changed black in
647
+% the right positions.
648
+
649
+udata=get(gcf,'UserData');
650
+udata=get(udata.fig1,'UserData');
651
+
652
+udata.new_marks=unique([udata.new_marks ;x']);
653
+
654
+for i=1:length(udata.a_h)
655
+  col=get(udata.tmp_patch(i),'FaceVertexCData');
656
+  if length(size(col)) == 3
657
+    col = reshape(col,[size(col,1) 3]);
658
+  end
659
+  for j=1:length(udata.new_marks)
660
+    col(udata.bmus(udata.new_marks(j)),:)=[0 0 0];
661
+  end
662
+  set(udata.tmp_patch(i),'FaceVertexCData',col);
663
+end
664
+
665
+set(udata.fig1,'UserData',udata);
666
+
667
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
668
+
669
+function color_gui(fig1)
670
+
671
+% construct the graphical user interface for changing the color of the
672
+% black (marked) nodes.
673
+
674
+
675
+udata=get(fig1,'UserData');
676
+
677
+a = figure('Color',[0.8 0.8 0.8], ...
678
+	   'Name','Colors', ...
679
+	   'PaperType','a4letter', ...
680
+	   'Position',[518 456 120 311], ...
681
+	   'Tag','Fig1');
682
+
683
+udata.c_struct.fig=a;
684
+
685
+b = uicontrol('Parent',a, ...
686
+	      'Units','normalized', ...
687
+	      'BackgroundColor',[0.701961 0.701961 0.701961], ...
688
+	      'Position',[0.0700415 0.28956 0.830492 0.594566], ...
689
+	      'Style','frame', ...
690
+	      'Tag','Frame1');
691
+b = uicontrol('Parent',a, ...
692
+	      'Units','normalized', ...
693
+	      'BackgroundColor',[0.8 0.8 0.8], ...
694
+	      'Position',[0.100059 0.301143 0.770456 0.571399], ...
695
+	      'Style','frame', ...
696
+	      'Tag','Frame2');
697
+
698
+b = uicontrol('Parent',a, ...
699
+	      'Units','normalized', ...
700
+	      'Callback','vis_trajgui([],''cyan'')', ...
701
+	      'Position',[0.130077 0.795326 0.170101 0.0617729], ...
702
+	      'Style','radiobutton', ...
703
+	      'Tag','cyan', ...
704
+	      'Value',1);
705
+
706
+
707
+b = uicontrol('Parent',a, ...
708
+	      'Units','normalized', ...
709
+	      'Callback','vis_trajgui([],''magenta'')', ...
710
+	      'Position',[0.130077 0.733553 0.170101 0.057912], ...
711
+	      'Style','radiobutton', ...
712
+	      'Tag','magenta');
713
+
714
+
715
+b = uicontrol('Parent',a, ...
716
+	      'Units','normalized', ...
717
+	      'Callback','vis_trajgui([],''yellow'')', ...
718
+	      'Position',[0.130077 0.664059 0.170101 0.0617729], ...
719
+	      'Style','radiobutton', ...
720
+	      'Tag','yellow');
721
+
722
+
723
+b = uicontrol('Parent',a, ...
724
+	      'Units','normalized', ...
725
+	      'Callback','vis_trajgui([],''red'')', ...
726
+	      'Position',[0.130077 0.590703 0.170101 0.0617729], ...
727
+	      'Style','radiobutton', ...
728
+	      'Tag','red');
729
+
730
+
731
+b = uicontrol('Parent',a, ...
732
+	      'Units','normalized', ...
733
+	      'Callback','vis_trajgui([],''green'')', ...
734
+	      'Position',[0.130077 0.525068 0.170101 0.057912], ...
735
+	      'Style','radiobutton', ...
736
+	      'Tag','green');
737
+
738
+
739
+b = uicontrol('Parent',a, ...
740
+	      'Units','normalized', ...
741
+	      'Callback','vis_trajgui([],''blue'')', ...
742
+	      'Position',[0.130077 0.455575 0.170101 0.0617729], ...
743
+	      'Style','radiobutton', ...
744
+	      'Tag','blue');
745
+
746
+
747
+b = uicontrol('Parent',a, ...
748
+	      'Units','normalized', ...
749
+	      'Callback','vis_trajgui([],''white'')', ...
750
+	      'Position',[0.130077 0.38608 0.170101 0.0617729], ...
751
+	      'Style','radiobutton', ...
752
+	      'Tag','white');
753
+
754
+
755
+b = uicontrol('Parent',a, ...
756
+	      'Units','normalized', ...
757
+	      'Callback','vis_trajgui([],''grey'')', ...
758
+	      'Position',[0.130077 0.320447 0.170101 0.057912], ...
759
+	      'Style','radiobutton', ...
760
+	      'Tag','grey');
761
+
762
+
763
+b = uicontrol('Parent',a, ...
764
+	      'Units','normalized', ...
765
+	      'BackgroundColor',[0.8 0.8 0.8], ...
766
+	      'FontWeight','demi', ...
767
+	      'HorizontalAlignment','left', ...
768
+	      'Position',[0.32019 0.795326 0.470278 0.0501905], ...
769
+	      'String','Cyan', ...
770
+	      'Style','text', ...
771
+	      'Tag','StaticText1');
772
+b = uicontrol('Parent',a, ...
773
+	      'Units','normalized', ...
774
+	      'BackgroundColor',[0.8 0.8 0.8], ...
775
+	      'FontWeight','demi', ...
776
+	      'HorizontalAlignment','left', ...
777
+	      'Position',[0.32019 0.733553 0.520308 0.0463296], ...
778
+	      'String','Magenta', ...
779
+	      'Style','text', ...
780
+	      'Tag','StaticText2');
781
+b = uicontrol('Parent',a, ...
782
+	      'Units','normalized', ...
783
+	      'BackgroundColor',[0.8 0.8 0.8], ...
784
+	      'FontWeight','demi', ...
785
+	      'HorizontalAlignment','left', ...
786
+	      'Position',[0.32019 0.664059 0.470278 0.0501905], ...
787
+	      'String','Yellow', ...
788
+	      'Style','text', ...
789
+	      'Tag','StaticText3');
790
+b = uicontrol('Parent',a, ...
791
+	      'Units','normalized', ...
792
+	      'BackgroundColor',[0.8 0.8 0.8], ...
793
+	      'FontWeight','demi', ...
794
+	      'HorizontalAlignment','left', ...
795
+	      'Position',[0.32019 0.590703 0.470278 0.0501905], ...
796
+	      'String','Red', ...
797
+	      'Style','text', ...
798
+	      'Tag','StaticText4');
799
+b = uicontrol('Parent',a, ...
800
+	      'Units','normalized', ...
801
+	      'BackgroundColor',[0.8 0.8 0.8], ...
802
+	      'FontWeight','demi', ...
803
+	      'HorizontalAlignment','left', ...
804
+	      'Position',[0.32019 0.525068 0.470278 0.0463296], ...
805
+	      'String','Green', ...
806
+	      'Style','text', ...
807
+	      'Tag','StaticText5');
808
+b = uicontrol('Parent',a, ...
809
+	      'Units','normalized', ...
810
+	      'BackgroundColor',[0.8 0.8 0.8], ...
811
+	      'FontWeight','demi', ...
812
+	      'HorizontalAlignment','left', ...
813
+	      'Position',[0.32019 0.455575 0.470278 0.0463296], ...
814
+	      'String','Blue', ...
815
+	      'Style','text', ...
816
+	      'Tag','StaticText6');
817
+b = uicontrol('Parent',a, ...
818
+	      'Units','normalized', ...
819
+	      'BackgroundColor',[0.8 0.8 0.8], ...
820
+	      'FontWeight','demi', ...
821
+	      'HorizontalAlignment','left', ...
822
+	      'Position',[0.32019 0.38608 0.470278 0.0501905], ...
823
+	      'String','White', ...
824
+	      'Style','text', ...
825
+	      'Tag','StaticText7');
826
+b = uicontrol('Parent',a, ...
827
+	      'Units','normalized', ...
828
+	      'BackgroundColor',[0.8 0.8 0.8], ...
829
+	      'FontWeight','demi', ...
830
+	      'HorizontalAlignment','left', ...
831
+	      'Position',[0.32019 0.320447 0.470278 0.0463296], ...
832
+	      'String','Grey', ...
833
+	      'Style','text', ...
834
+	      'Tag','StaticText8');
835
+b = uicontrol('Parent',a, ...
836
+	      'Units','normalized', ...
837
+	      'Position',[0.0700415 0.146711 0.830492 0.135128], ...
838
+	      'Style','frame', ...
839
+	      'Tag','Frame3');
840
+b = uicontrol('Parent',a, ...
841
+	      'Units','normalized', ...
842
+	      'BackgroundColor',[0.8 0.8 0.8], ...
843
+	      'Position',[0.100059 0.158293 0.770456 0.111963], ...
844
+	      'Style','frame', ...
845
+	      'Tag','Frame4');
846
+b = uicontrol('Parent',a, ...
847
+	      'Units','normalized', ...
848
+	      'BackgroundColor',[0.8 0.8 0.8], ...
849
+	      'FontWeight','demi', ...
850
+	      'HorizontalAlignment','left', ...
851
+	      'Position',[0.130077 0.177597 0.270833 0.0617729], ...
852
+	      'String','RGB', ...
853
+	      'Style','text', ...
854
+	      'Tag','StaticText9');
855
+b = uicontrol('Parent',a, ...
856
+	      'Units','normalized', ...
857
+	      'BackgroundColor',[1 1 1], ...
858
+	      'Position',[0.410243 0.173736 0.420249 0.0810768], ...
859
+	      'Style','edit', ...
860
+	      'Tag','EditText1');
861
+
862
+udata.c_struct.RGB=b;
863
+
864
+b = uicontrol('Parent',a, ...
865
+	      'Units','normalized', ...
866
+	      'Callback','vis_trajgui([],''dye'')', ...
867
+	      'FontWeight','demi', ...
868
+	      'Position',[0.0700415 0.0270256 0.360214 0.0772162], ...
869
+	      'String','OK', ...
870
+	      'Tag','Pushbutton1');
871
+b = uicontrol('Parent',a, ...
872
+	      'Units','normalized', ...
873
+	      'Callback','close gcf', ...
874
+	      'FontWeight','demi', ...
875
+	      'Position',[0.54032 0.0270256 0.360214 0.0772162], ...
876
+	      'String','Close', ...
877
+	      'Tag','Pushbutton2');
878
+
879
+udata.c_struct.color=[0 1 1];
880
+
881
+tmp.fig1=fig1;
882
+set(a,'UserData',tmp);
883
+set(udata.fig1,'UserData',udata);
884
+
885
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
886
+
887
+function dye_nodes(arg)
888
+
889
+% takes care of the action, when radiobuttons are pressed 
890
+% (or the RGB value is set) in the color_gui -figure.
891
+% It also handles the starting of dying nodes and plots.
892
+
893
+udata=get(gcf,'UserData');
894
+udata=get(udata.fig1,'UserData');
895
+
896
+
897
+switch arg
898
+ case {'cyan','magenta','yellow','red','green','blue','white','grey'}
899
+  h=findobj(get(gcf,'Children'),'Style','radiobutton');
900
+  set(h,'Value',0);
901
+  set(gcbo,'Value',1);
902
+end
903
+
904
+
905
+switch arg
906
+ case 'cyan'
907
+  RGB = [0 1 1];
908
+ case 'magenta'
909
+  RGB = [1 0 1];
910
+ case 'yellow'
911
+  RGB = [1 1 0];
912
+ case 'red'
913
+  RGB = [1 0 0];
914
+ case 'green'
915
+  RGB = [0 1 0];
916
+ case 'blue'
917
+  RGB = [0 0 1];
918
+ case 'white'
919
+  RGB = [1 1 1];
920
+ case 'grey'
921
+  RGB = [0.4 0.4 0.4];
922
+ case 'dye'
923
+  
924
+  RGB = get(udata.c_struct.RGB,'String');
925
+  if isempty(RGB)
926
+    dye;
927
+    return;
928
+  else
929
+    str1='The value of RGB must be vector containing three scalars';
930
+    str2='between 0 and 1.';
931
+    color = str2num(RGB);
932
+    set(udata.c_struct.RGB,'String','');
933
+    if isempty(color)
934
+      close gcf;
935
+      udata=rmfield(udata,'c_struct');
936
+      set(udata.fig1,'UserData',udata);
937
+      errordlg([{str1};{str2}]);
938
+      return;
939
+    end
940
+    if ~all([1 3] == size(color)) & ~all([3 1] == size(color))
941
+      close gcf;
942
+      errordlg([{str1};{str2}]);
943
+      udata=rmfield(udata,'c_struct',udata);
944
+      set(udata.fig1,'UserData',udata);
945
+      return;
946
+    end
947
+    if ~isempty(cat(2,find(color>1),find(color<0)))
948
+      close gcf
949
+      errordlg([{str1};{str2}]);
950
+      udata=rmfield(udata,'c_struct',udata);
951
+      set(udata.fig1,'UserData',udata);
952
+      return;
953
+    end
954
+    udata.c_struct.color=color;
955
+    set(udata.fig1,'UserData',udata);
956
+    dye;
957
+    return;
958
+  end
959
+end
960
+
961
+udata.c_struct.color=RGB;
962
+set(udata.fig1,'UserData',udata);
963
+
964
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
965
+
966
+function dye()
967
+
968
+% dyes black markers in the component planes and in the data figures
969
+
970
+udata=get(gcf,'UserData');
971
+udata=get(udata.fig1,'UserData');
972
+
973
+inds=unique([udata.all_marks ; udata.new_marks]);
974
+
975
+
976
+for i=1:length(udata.d_mark);
977
+  for j=1:length(udata.d_mark(i).h)
978
+    if all(get(udata.d_mark(i).h(j),'Color') == [0 0 0])
979
+      set(udata.d_mark(i).h(j),'Color',udata.c_struct.color);
980
+    end
981
+  end
982
+end
983
+
984
+if ~isempty(udata.fig2);
985
+  for i=1:length(udata.d_mark2)
986
+    for j=1:length(udata.d_mark2(i).h)
987
+      if all(get(udata.d_mark2(i).h(j),'Color') == [0 0 0])
988
+        set(udata.d_mark2(i).h(j),'Color',udata.c_struct.color);
989
+      end
990
+    end
991
+  end
992
+end
993
+
994
+
995
+for i=1:length(udata.a_h)
996
+  col=get(udata.tmp_patch(i),'FaceVertexCData');
997
+  for j=1:length(udata.new_marks)
998
+    col(udata.bmus(udata.new_marks(j)),:)=udata.c_struct.color;
999
+  end
1000
+  set(udata.tmp_patch(i),'FaceVertexCData',col);
1001
+end
1002
+
1003
+
1004
+udata.all_marks=unique([udata.all_marks;udata.new_marks]);
1005
+udata.new_marks=[];
1006
+close gcf;
1007
+udata=rmfield(udata,'c_struct');
1008
+set(udata.fig1,'UserData',udata);
1009
+
1010
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1011
+
1012
+function clear_markers()
1013
+
1014
+% removes markers from the componentplanes and the data figure(s).
1015
+
1016
+udata=get(gcf,'UserData');
1017
+udata=get(udata.fig1,'UserData');
1018
+
1019
+for i=1:length(udata.d_mark)
1020
+  delete(udata.d_mark(i).h);
1021
+  udata.d_mark(i).h=[];
1022
+end
1023
+
1024
+for i=1:length(udata.d_mark2)
1025
+  delete(udata.d_mark2(i).h);
1026
+  udata.d_mark2(i).h=[];
1027
+end
1028
+
1029
+col=NaN*get(udata.tmp_patch(1),'FaceVertexCData');
1030
+col=reshape(col,[size(col,1) 3]);
1031
+
1032
+for i=1:length(udata.tmp_patch)
1033
+  set(udata.tmp_patch(i),'FaceVertexCData',col);
1034
+end
1035
+
1036
+udata.new_marks=[];
1037
+udata.all_marks=[];
1038
+
1039
+
1040
+if any(strcmp('c_struct',fieldnames(udata)))
1041
+  udata=rmfield(udata,'c_struct');
1042
+end
1043
+
1044
+set(udata.fig1,'UserData',udata);
1045
+
1046
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1047
+
1048
+function key_bdf
1049
+
1050
+% moves trajectory and pointer lines, when either of 
1051
+% the keys '>' or '<' is pressed.
1052
+
1053
+udata=get(gcf,'UserData');
1054
+udata=get(udata.fig1,'UserData');
1055
+
1056
+key=get(gcbo,'CurrentCharacter');
1057
+
1058
+% The easiest way to get a new coordinates is to get them from the texts...
1059
+% The texts are either '<- x' or 'x ->' 
1060
+
1061
+x=get(udata.text1(1),'String');
1062
+x=str2num(x(4:length(x)));
1063
+
1064
+if isempty(x)
1065
+  x=get(udata.text1(1),'String');
1066
+  x=str2num(x(1:length(x)-3));
1067
+end
1068
+
1069
+switch(key)
1070
+ case '<'
1071
+  if x ~= 1
1072
+    x= x-1;
1073
+  end
1074
+ case '>'
1075
+  if x ~= getfield(get(get(udata.text1(1),'Parent'),'XLim'),{2}) 
1076
+    x = x+1;
1077
+  end
1078
+ otherwise
1079
+  return;
1080
+end
1081
+
1082
+set(udata.l,'XData',[x x]);
1083
+if ~isempty(udata.fig2)
1084
+  set(udata.l2,'XData',[x x]);
1085
+end
1086
+
1087
+delete(udata.text1);
1088
+delete(udata.text2);
1089
+
1090
+set_numbers(x);
1091
+draw_traj(x);
1092
+
1093
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1094
+
1095
+function click()
1096
+
1097
+
1098
+switch get(gcf,'SelectionType')
1099
+ case 'open'
1100
+  return;
1101
+ case {'normal','alt'}
1102
+  draw_poly;
1103
+ case 'extend'
1104
+  click_node;
1105
+end
1106
+
1107
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1108
+
1109
+function click_node()
1110
+
1111
+% takes care of the action, when the middle mouse button is
1112
+% pressed (mouse pointer is above some component plane).
1113
+
1114
+udata=get(gcf,'UserData');
1115
+udata=get(udata.fig1,'UserData');
1116
+new_marks=[];
1117
+
1118
+old=gcf;
1119
+
1120
+NEW=0;
1121
+AGAIN = 0;
1122
+
1123
+
1124
+coords=get(gca,'CurrentPoint');
1125
+row=round(coords(1,2));
1126
+
1127
+if strcmp(udata.lattice,'hexa') & ~mod(row,2)
1128
+  col = round(coords(1,1) - 0.5);
1129
+else
1130
+  col = round(coords(1,1));
1131
+end
1132
+
1133
+ind = sub2ind(udata.msize,row,col);
1134
+new_marks=find(udata.bmus==ind);
1135
+
1136
+if strcmp(get(gcbo,'Tag'),'TmpPatch');
1137
+  
1138
+  % if the callback is made via temporary patch object, node is marked
1139
+  % (node is black) => the mark is to be removed 
1140
+  
1141
+  node_color = getfield(get(gcbo,'FaceVertexCData'),{ind,[1:3]});
1142
+  AGAIN = 1;
1143
+end
1144
+
1145
+
1146
+
1147
+for i=1:length(udata.tmp_patch)
1148
+  color = get(udata.tmp_patch(i),'FaceVertexCData');
1149
+  if length(size(color)) ~= 2
1150
+    color = reshape(color,[size(color,1) 3]);
1151
+  end
1152
+  if all(isnan(color(ind,:)))
1153
+    NEW=1;
1154
+    color(ind,:)=[0 0 0];
1155
+  else
1156
+    color(ind,:)=[NaN NaN NaN];
1157
+  end
1158
+  set(udata.tmp_patch(i),'FaceVertexCData',color);
1159
+end
1160
+
1161
+set(0,'CurrentFigure',udata.fig1);
1162
+
1163
+for j=1:length(udata.h)
1164
+  subplot(udata.h(j));
1165
+  if NEW
1166
+    y=getfield(get(udata.d(j),'YData'),{new_marks});
1167
+    udata.d_mark(j).h=[udata.d_mark(j).h;plot(new_marks,y,'Color',[0 0 0],...
1168
+                                              'LineStyle','none',...
1169
+                                              'Marker','o')];
1170
+  end
1171
+end
1172
+
1173
+
1174
+if ~isempty(udata.fig2)
1175
+  set(0,'CurrentFigure',udata.fig2);
1176
+  for j=1:length(udata.h2);
1177
+    subplot(udata.h2(j));
1178
+    if NEW
1179
+      y=getfield(get(udata.d2(j),'YData'),{new_marks});
1180
+      udata.d_mark2(j).h=[udata.d_mark2(j).h;plot(new_marks,y,...
1181
+						  'LineStyle','none',...
1182
+						  'Color','black',...
1183
+						  'Marker','o')];
1184
+    end
1185
+  end
1186
+end
1187
+
1188
+if NEW
1189
+  udata.new_marks=[udata.new_marks; new_marks];
1190
+end
1191
+
1192
+if AGAIN
1193
+  
1194
+  % find marks from the data that map to the clicked node. if the color
1195
+  % of the mark(s) is the same as the node's color, remove mark(s), else
1196
+  % let mark be unchanged.
1197
+  
1198
+  for i=1:length(udata.d_mark(1).h)
1199
+    if all(node_color==get(udata.d_mark(1).h(i),'Color'))
1200
+      tmp1 = get(udata.d_mark(1).h(i),'XData');
1201
+      tmp2 = setdiff(tmp1,new_marks);
1202
+      if length(tmp1) ~= length(tmp2)
1203
+        inds=[];
1204
+        for j=1:length(tmp2);
1205
+          inds=[inds find(tmp2(j)==tmp1)];
1206
+        end
1207
+        for j=1:length(udata.d_mark)
1208
+          ydata=getfield(get(udata.d_mark(j).h(i),'YData'),{inds});
1209
+          set(udata.d_mark(j).h(i),'XData',tmp2,'YData',ydata);
1210
+        end
1211
+        if ~isempty(udata.fig2)
1212
+          for j=1:length(udata.d_mark2)
1213
+            ydata=getfield(get(udata.d_mark2(j).h(i),'YData'),{inds});
1214
+            set(udata.d_mark2(j).h(i),'XData',tmp2,'YData',ydata);
1215
+          end
1216
+        end
1217
+      end  
1218
+    end
1219
+  end
1220
+  udata.new_marks=setdiff(udata.new_marks, new_marks);
1221
+  udata.all_marks=setdiff(udata.all_marks,new_marks);
1222
+end
1223
+
1224
+set(udata.fig1,'UserData',udata);
1225
+set(0,'CurrentFigure',old);
1226
+
1227
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1228
+
1229
+function draw_poly()
1230
+
1231
+udata=get(gcf,'UserData');
1232
+udata=get(udata.fig1,'UserData');
1233
+
1234
+if isempty(udata.poly.x)
1235
+  if strcmp(get(gcf,'SelectionType'),'alt')
1236
+    return;
1237
+  end
1238
+  udata.poly.THIS = gca;
1239
+end
1240
+
1241
+% 'THIS' indicates what was the axes where the polygon was meant to
1242
+% drawn. It is not possible to add points, that lie in another axes, to the
1243
+% polygon.
1244
+
1245
+
1246
+if gca ~= udata.poly.THIS
1247
+  return;
1248
+end
1249
+
1250
+coords(1,1) = getfield(get(gca,'CurrentPoint'),{3});
1251
+coords(1,2) = getfield(get(gca,'CurrentPoint'),{1});
1252
+
1253
+udata.poly.x=cat(1,udata.poly.x,coords(2));
1254
+udata.poly.y=cat(1,udata.poly.y,coords(1));
1255
+
1256
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1257
+% remove old 'polygon' from axis
1258
+
1259
+delete(udata.poly.h);
1260
+
1261
+
1262
+switch get(gcf,'SelectionType')
1263
+ case 'normal'
1264
+  
1265
+  % add point to the 'polygon' and draw it
1266
+  
1267
+  for i=1:length(udata.a_h)
1268
+    subplot(udata.a_h(i));
1269
+    hold on;
1270
+    udata.poly.h(i) = plot(udata.poly.x,udata.poly.y,'black',...
1271
+			   'EraseMode','xor',...
1272
+			   'ButtonDownFcn',...
1273
+			   'vis_trajgui([],''click'')',...
1274
+			   'LineWidth',2);
1275
+  end
1276
+ case 'alt'
1277
+  
1278
+  % The polygon is ready.
1279
+  
1280
+  
1281
+  udata.poly.x=cat(1,udata.poly.x,udata.poly.x(1));
1282
+  udata.poly.y=cat(1,udata.poly.y,udata.poly.y(1));
1283
+  
1284
+  for i=1:length(udata.a_h)
1285
+    subplot(udata.a_h(i));
1286
+    udata.poly.h(i) = plot(udata.poly.x,udata.poly.y,'black',...
1287
+			   'EraseMode','xor',...
1288
+			   'ButtonDownFcn',...
1289
+			   'vis_trajgui([],''click'')',...
1290
+			   'LineWidth',2);
1291
+  end
1292
+  
1293
+  tmp=sort(repmat((1:udata.msize(1))',udata.msize(2),1));
1294
+  tmp(:,2)=repmat((1:udata.msize(2))',udata.msize(1),1);
1295
+  tmp2=tmp;
1296
+  if strcmp(udata.lattice,'hexa');
1297
+    t=find(~rem(tmp(:,1),2));
1298
+    tmp(t,2)=tmp(t,2)+0.5;
1299
+  end
1300
+  
1301
+  
1302
+  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1303
+  % find the nodes that lie inside polygon and change coordinates to
1304
+  % linear indices.
1305
+  
1306
+  in = find(inpolygon(tmp(:,2),tmp(:,1),udata.poly.x,udata.poly.y));
1307
+  in = sub2ind(udata.msize,tmp2(in,1),tmp2(in,2));
1308
+  
1309
+  colors=get(udata.tmp_patch(1),'FaceVertexCData');
1310
+  colors=reshape(colors,[size(colors,1) 3]);
1311
+  tmp=ones(length(in),1);
1312
+  
1313
+  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%   
1314
+  % set the color of the nodes just selected, black.
1315
+  
1316
+  colors(in,:)=tmp*[0 0 0];
1317
+  set(udata.tmp_patch,'FaceVertexCData',colors);
1318
+  
1319
+  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1320
+  % find the points mapping to the nodes from data 
1321
+  
1322
+  inds = [];
1323
+  for i=1:length(in)
1324
+    inds=[inds;find(in(i) == udata.bmus)];
1325
+  end
1326
+  
1327
+  %%%%%%%%%%%%%%%%%%%  
1328
+  % plot marks to data
1329
+  
1330
+  set(udata.fig1,'UserData',udata);
1331
+  plot2data(inds);
1332
+  udata=get(udata.fig1,'UserData');
1333
+  udata.new_marks=union(udata.new_marks,inds);
1334
+  delete(udata.poly.h);
1335
+  udata.poly.h=[];
1336
+  udata.poly.x=[];
1337
+  udata.poly.y=[];
1338
+  udata.poly.THIS=[];
1339
+end
1340
+
1341
+set(udata.fig1,'UserData',udata);
1342
+
1343
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1344
+
1345
+function save_data()
1346
+
1347
+udata=get(gcf,'UserData');
1348
+udata=get(udata.fig1,'UserData');
1349
+
1350
+data.points=[];
1351
+data.nodes=[];
1352
+k=1;
1353
+
1354
+for i=1:length(udata.d_mark(1).h)
1355
+  data.points(i).inds=get(udata.d_mark(1).h(i),'XData');
1356
+  data.points(i).color=get(udata.d_mark(1).h(i),'Color');
1357
+end
1358
+
1359
+color=get(udata.tmp_patch(1),'FaceVertexCData');
1360
+color=reshape(color,[size(color,1) 3]);
1361
+
1362
+for i=1:size(color,1)
1363
+  if all(~isnan(color(i,:)))
1364
+    tmp.ind=i;
1365
+    tmp.color=color(i,:);
1366
+    data.nodes(k)=tmp;
1367
+    k=k+1;
1368
+  end
1369
+end
1370
+
1371
+answer=inputdlg('Enter the name of the output variable:','',1);
1372
+
1373
+if isempty(answer) | isempty(answer{1})
1374
+  msgbox('Output is not set to workspace.');
1375
+  return;
1376
+else
1377
+  assignin('base',answer{1},data);
1378
+  disp(sprintf('Struct is set to the workspace as ''%s''.',answer{1}));
1379
+end
1380
+
1381
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1382
+
1383
+function load_data()
1384
+
1385
+answer = inputdlg('Enter the name of the struct to be loaded:','',1);
1386
+
1387
+if isempty(answer) | isempty(answer{1})
1388
+  msgbox('Data is not loaded.');
1389
+  return;
1390
+end
1391
+
1392
+data=evalin('base',answer{1});
1393
+
1394
+if ~isstruct(data)  
1395
+  errordlg('Input variable must be a struct.');
1396
+  return;
1397
+end
1398
+
1399
+tmp1 = fieldnames(data);
1400
+tmp2 = {'nodes','points'};
1401
+
1402
+for i=1:length(tmp1)
1403
+  for j=1:length(tmp2);
1404
+    if ~any(strcmp(tmp2{j},tmp1))
1405
+      errordlg('Wrong type of struct.');
1406
+      return;
1407
+    end
1408
+  end
1409
+end
1410
+
1411
+if ~isempty(data.points)
1412
+  tmp1=fieldnames(data.points(1));
1413
+end
1414
+if ~isempty(data.nodes)
1415
+  tmp2=fieldnames(data.nodes(1));
1416
+end
1417
+
1418
+for i=1:length(tmp1)
1419
+  if ~any(strcmp(tmp1{i},{'inds','color'}))
1420
+    errordlg('Wrong type of struct.');
1421
+    return;
1422
+  end
1423
+end
1424
+
1425
+for i=1:length(tmp2)
1426
+  if ~any(strcmp(tmp2{i},{'ind','color'}))
1427
+    errordlg('Wrong type of struct.');
1428
+    return;
1429
+  end
1430
+end
1431
+
1432
+udata=get(gcf,'UserData');
1433
+udata=get(udata.fig1,'UserData');
1434
+
1435
+clear_markers;
1436
+remove_traj;
1437
+
1438
+old = gcf;
1439
+
1440
+for i=1:length(data.points)
1441
+  for j=1:length(udata.h);
1442
+    set(0,'CurrentFigure',udata.fig1);
1443
+    subplot(udata.h(j));
1444
+    ydata=getfield(get(udata.d(j),'YData'),{data.points(i).inds});
1445
+    udata.d_mark(j).h=[udata.d_mark(j).h;...
1446
+                       plot(data.points(i).inds,ydata,...
1447
+			    'Color',data.points(i).color,...
1448
+			    'LineStyle','none',...
1449
+			    'Marker','o',...
1450
+			    'ButtonDownFcn',...
1451
+			    'vis_trajgui([],''line_down'')')];  
1452
+    if all(data.points(i).color == [0 0 0])
1453
+      udata.new_marks=unique([udata.new_marks; (data.points(i).inds)']);
1454
+    else
1455
+      udata.all_marks=unique([udata.all_marks; (data.points(i).inds)']);
1456
+    end
1457
+  end
1458
+  if ~isempty(udata.fig2)
1459
+    set(0,'CurrentFigure',udata.fig2);
1460
+    for j=1:length(udata.h2)
1461
+      subplot(udata.h2(j));
1462
+      ydata=getfield(get(udata.d2(j),'YData'),{data.points(i).inds});
1463
+      udata.d_mark2(j).h=[udata.d_mark2(j).h;...
1464
+                          plot(data.points(i).inds,ydata,...
1465
+			       'Color',data.points(i).color,...
1466
+			       'LineStyle','none',...
1467
+			       'Marker','o',...
1468
+			       'ButtonDownFcn',...
1469
+			       'vis_trajgui([],''line_down'')')];
1470
+    end
1471
+  end
1472
+end     
1473
+
1474
+
1475
+set(0,'CurrentFigure',udata.sM_h);
1476
+color=get(udata.tmp_patch(1),'FaceVertexCData');
1477
+color=reshape(color,[size(color,1) 3]);
1478
+for i=1:length(data.nodes)
1479
+  color(data.nodes(i).ind,:)=data.nodes(i).color;
1480
+end
1481
+for i=1:length(udata.tmp_patch);
1482
+  set(udata.tmp_patch(i),'FaceVertexCData',color);
1483
+end
1484
+
1485
+set(0,'CurrentFigure',old);
1486
+set(udata.fig1,'UserData',udata);
1487
+
1488
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1489
+
1490
+function fuzzy_traj(trajStruct,arg); 
1491
+%function fuzzy_traj(sM_h,sM,sD,interval,arg)
1492
+
1493
+
1494
+if isempty(arg)
1495
+  
1496
+  if strcmp(trajStruct.lattice,'hexa')
1497
+    udata.lattice='hexa';
1498
+    udata.form=vis_patch('hexa');
1499
+  else
1500
+    data.lattice='rect';
1501
+    udata.form=vis_patch('rect');
1502
+  end
1503
+  
1504
+  % interval=[1 size(trajStruct.primary_data,1)];
1505
+  
1506
+  l=size(udata.form,1);
1507
+  dim = size(trajStruct.primary_data,2);
1508
+  udata.a_h=[findobj(get(trajStruct.figure,'Children'),'Tag','Uplane');...
1509
+             findobj(get(trajStruct.figure,'Children'),'Tag','Cplane')];
1510
+  
1511
+  udata.sM_h=trajStruct.figure;
1512
+  udata.msize=trajStruct.msize;
1513
+  
1514
+  %%%%%%%%%%%%%%%
1515
+  %
1516
+  % constructing patch that is drawn above every plane in map
1517
+  %
1518
+  
1519
+  nx = repmat(udata.form(:,1),1,prod(udata.msize));
1520
+  ny = repmat(udata.form(:,2),1,prod(udata.msize));
1521
+  
1522
+  x_c=reshape(repmat(1:udata.msize(2),l*udata.msize(1),1),l,prod(udata.msize));
1523
+  y_c=repmat(repmat(1:udata.msize(1),l,1),1,udata.msize(2));
1524
+  
1525
+  if strcmp(udata.lattice,'hexa')
1526
+    t = find(~rem(y_c(1,:),2));
1527
+    x_c(:,t)=x_c(:,t)+.5;
1528
+  end
1529
+  
1530
+  x_c=x_c+nx;
1531
+  y_c=y_c+ny;
1532
+  
1533
+  udata.orig_c=ones(prod(udata.msize),1)*[NaN NaN NaN];
1534
+  colors=reshape(udata.orig_c,[1 size(udata.orig_c,1) 3]);
1535
+  set(0,'CurrentFigure',trajStruct.figure);
1536
+  
1537
+  %%%%%%%%%
1538
+  % drawing 
1539
+  
1540
+  for i=1:length(udata.a_h);
1541
+    subplot(udata.a_h(i));
1542
+    v=caxis;
1543
+    udata.patch_h(i) =patch(x_c,y_c,colors,'EdgeColor','none');
1544
+    caxis(v);
1545
+  end
1546
+  
1547
+  
1548
+  udata.orig_x=get(udata.patch_h(1),'XData');
1549
+  udata.orig_y=get(udata.patch_h(1),'YData');
1550
+  
1551
+  %  if interval(1) < 1 | interval(2) > size(trajStruct.primary_data,1)
1552
+  %    error('Invalid argument ''interval''.');
1553
+  %  end
1554
+  
1555
+  x=1:size(trajStruct.primary_data,1);
1556
+  udata.fig1=figure;
1557
+  set(udata.fig1,'KeyPressFcn',...
1558
+                 'vis_trajgui([],''move_fuzzy'')');
1559
+  for i=1:size(trajStruct.primary_data,2)
1560
+    subplot(size(trajStruct.primary_data,2),1,i);
1561
+    udata.h(i)=gca;
1562
+    set(udata.h(1),'XTick',[]);
1563
+    udata.d(i)=plot(x,trajStruct.primary_data(:,i));
1564
+    l_x=1;
1565
+    lims(1) = round(min(trajStruct.primary_data(:,i)));
1566
+    lims(2) = round(max(trajStruct.primary_data(:,i)));
1567
+    udata.l(i) = line([l_x l_x],lims,'Color','red','EraseMode','xor');
1568
+  end
1569
+  
1570
+  udata.l_x = l_x;  
1571
+  udata.interval=[1 size(trajStruct.bmus,2)];
1572
+  
1573
+  tmp.fig1=udata.fig1;
1574
+  %  [K,P] = estimate_kernels(sM,sD);
1575
+  %  udata.K=K;
1576
+  %  udata.P=P;
1577
+  %  udata.codebook=sM.codebook;
1578
+  %  udata.data=sD.data;
1579
+  udata.bmus=trajStruct.bmus;
1580
+  set(udata.fig1,'UserData',udata);
1581
+  set(trajStruct.figure,'UserData',tmp);  
1582
+  draw_fuzzy(l_x);
1583
+  return;
1584
+end
1585
+
1586
+move_fuzzy;
1587
+
1588
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1589
+
1590
+function draw_fuzzy(x)
1591
+
1592
+udata=get(gcf,'UserData');
1593
+udata=get(udata.fig1,'UserData');
1594
+
1595
+inds = find(udata.bmus(:,x));
1596
+[row col] = ind2sub(udata.msize,inds);
1597
+if strcmp(udata.lattice,'hexa')
1598
+  t=find(~mod(row,2));
1599
+  col(t)=col(t)+0.5;
1600
+end
1601
+
1602
+color=udata.orig_c;
1603
+color=reshape(color,[size(color,1) 3]);
1604
+xdata=udata.orig_x;
1605
+ydata=udata.orig_y;
1606
+tmp= ones(size(xdata(:,1),1),1)*udata.bmus(inds,x)';
1607
+color(inds,:) = ones(length(inds),1)*[0 0 0];
1608
+xdata(:,inds) = udata.form(:,1)*ones(1,length(inds)).*tmp+ones(6,1)*col';
1609
+ydata(:,inds) = udata.form(:,2)*ones(1,length(inds)).*tmp+ones(6,1)*row';
1610
+
1611
+set(udata.patch_h,'FaceVertexCData',color,'XData',xdata,'YData',ydata);
1612
+
1613
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1614
+
1615
+function move_fuzzy
1616
+
1617
+% moves pointer lines and draws fuzzy response.
1618
+
1619
+udata=get(gcf,'UserData');
1620
+udata=get(udata.fig1,'UserData');
1621
+
1622
+switch get(gcf,'CurrentCharacter');
1623
+ case {'<','>'}
1624
+  key = get(gcf,'CurrentCharacter');
1625
+  if key == '>'
1626
+    if udata.l_x + 1 > udata.interval(2) 
1627
+      return;
1628
+    end
1629
+    l_x = udata.l_x + 1;
1630
+  else
1631
+    if udata.l_x - 1 < udata.interval(1)
1632
+      return;
1633
+    end
1634
+    l_x = udata.l_x - 1;
1635
+  end
1636
+  draw_fuzzy(l_x);
1637
+  set(udata.l,'XData',[l_x l_x]);
1638
+  udata.l_x=l_x;
1639
+  set(udata.fig1,'UserData',udata);
1640
+ otherwise
1641
+  return;
1642
+end
1643
+
1644
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1645
+
1646
+
1647
+
... ...
@@ -0,0 +1,269 @@
1
+function flag=vis_valuetype(value, valid, str);
2
+
3
+% VIS_VALUETYPE Used for type checks in SOM Toolbox visualization routines
4
+%
5
+%  flag = vis_valuetype(value, valid, str)
6
+%
7
+%  Input and output arguments:
8
+%   value  (varies) variable to be checked
9
+%   valid  (cell array) size 1xN, cells are strings or vectors (see below)
10
+%   str    (string) 'all' or 'any' (default), determines whether
11
+%                   all or just any of the types listed in argument 'valid' 
12
+%                   should be true for 'value'
13
+%
14
+%   flag   (scalar) 1 or 0 (true or false) 
15
+%
16
+% This is an internal function of SOM Toolbox visualization.  It makes
17
+% various type checks. For example:
18
+%
19
+%  % Return 1 if X is a numeric scalar otherwise 0:
20
+%  f=vis_valuetype(X,{'1x1'});
21
+%
22
+%  % Return 1 if X is a ColorSpec, that is, a 1x3 vector presenting an RGB
23
+%  % value or any of strings 'red','blue','green','yellow','magenta','cyan',
24
+%  % 'white' or 'black' or their shortenings  'r','g','b','y','m','c','w','k': 
25
+%  f=vis_valueype(X,{'1x3rgb','colorstyle'})
26
+%
27
+%  % Return 1 if X is _both_ 10x3 size numeric matrix and has RGB values as rows
28
+%  f=vis_valuetype(X,{'nx3rgb',[10 3]},'all')
29
+%
30
+% Strings that may be used in argument valid: 
31
+%  id             is true if value is 
32
+% 
33
+%  [n1 n2 ... nn] any n1 x n2 x ... x nn sized numeric matrix
34
+%  '1x1'          scalar (numeric)
35
+%  '1x2'          1x2 vector (numeric)
36
+%  'nx1'          any nx1 numeric vector
37
+%  'nx2'              nx2
38
+%  'nx3'              nx3
39
+%  'nxn'          any numeric square matrix
40
+%  'nxn[0,1]'     numeric square matrix with values in interval [0,1]
41
+%  'nxm'          any numeric matrix
42
+%  '1xn'          any 1xn numeric vector
43
+%  '1x3rgb'       1x3 vector v for which all(v>=0 & v<=1), e.g., a RGB code
44
+%  'nx3rgb'       nx3 numeric matrix that contains n RGB values as rows
45
+%  'nx3dimrgb'    nx3xdim numeric matrix that contains RGB values
46
+%  'nxnx3rgb'     nxnx3 numeric matrix of nxn RGB triples
47
+%  'none'         string 'none'
48
+%  'xor'          string 'xor'
49
+%  'indexed'      string 'indexed'
50
+%  'colorstyle'   strings 'red','blue','green','yellow','magenta','cyan','white' 
51
+%                 or 'black', or 'r','g','b','y','m','c','w','k'                 
52
+%  'markerstyle'  any of Matlab's marker chars '.','o','x','+','*','s','d','v',
53
+%                 '^','<','>','p'or 'h'
54
+%  'linestyle'    any or Matlab's line style strings '-',':','--', or '-.'
55
+%  'cellcolumn'   a nx1 cell array
56
+%  'topol_cell'   {lattice, msize, shape} 
57
+%  'topol_cell_no_shape' {lattice, msize}
58
+%  'string'       any string (1xn array of char)  
59
+%  'chararray'    any MxN char array
60
+
61
+% Copyright (c) 1999-2000 by the SOM toolbox programming team.
62
+% http://www.cis.hut.fi/projects/somtoolbox/             
63
+
64
+% Version 2.0beta Johan 201099 juuso 280800
65
+
66
+if nargin == 2
67
+  str='any';
68
+end
69
+
70
+flag=0;  
71
+sz=size(value);
72
+dims=ndims(value);
73
+
74
+% isnumeric
75
+numeric=isnumeric(value);
76
+character=ischar(value);
77
+
78
+% main loop: go through all types in arg. 'valid'
79
+for i=1:length(valid),
80
+  if isnumeric(valid{i}), % numeric size for double matrix
81
+    if numeric & length(valid{i}) == dims,
82
+      flag(i)=all(sz == valid{i});
83
+    else
84
+      flag(i)=0; % not numeric or wrong dimension
85
+    end
86
+  else
87
+    msg=''; % for a error message inside try 
88
+    try 
89
+      switch valid{i}
90
+	
91
+	% scalar
92
+       case '1x1'
93
+	flag(i)=numeric & dims == 2 & sz(1)==1 & sz(2) ==1;
94
+	
95
+	% 1x2 numeric vector
96
+       case '1x2'
97
+	flag(i)=numeric & dims == 2 & sz(1)==1 & sz(2) == 2;
98
+	
99
+	% 1xn numeric vector
100
+       case '1xn'
101
+	flag(i)=numeric & dims == 2 & sz(1) == 1;
102
+	
103
+	% any numeric matrix
104
+       case 'nxm' 
105
+	flag(i)=numeric & dims == 2;
106
+	
107
+	% nx3 numeric matrix 
108
+       case 'nx3'
109
+	flag(i)=numeric & dims == 2 & sz(2) == 3;
110
+	
111
+	% nx2 numeric matrix 
112
+       case 'nx2'
113
+	flag(i)=numeric & dims == 2 & sz(2) == 2;
114
+	
115
+	% nx1 numeric vector
116
+       case 'nx1'
117
+	flag(i)=numeric & dims == 2 & sz(2) == 1;
118
+       
119
+	% nx1xm numric matrix
120
+       case 'nx1xm'
121
+	flag(i)=numeric & dims == 3 & sz(2) == 1;
122
+	
123
+	% nx3 matrix of RGB triples
124
+       case 'nx3rgb'  
125
+	flag(i)=numeric & dims == 2 & sz(2) == 3 & in0_1(value);
126
+	
127
+	% RGB triple (ColorSpec vector)
128
+       case '1x3rgb'
129
+	flag(i) = numeric & dims == 2 & sz(1)==1 & sz(2) == 3 & in0_1(value);
130
+	
131
+	% any square matrix
132
+       case 'nxn'
133
+	flag(i)=numeric & dims == 2 & sz(1) == sz(2);
134
+	
135
+	% nx3xdim array of nxdim RGB triples
136
+       case 'nx3xdimrgb'
137
+	flag(i)=numeric & dims == 3 & sz(2) == 3 & in0_1(value);
138
+	
139
+	% nxnx3 array of nxn RGB triples
140
+       case 'nxnx3rgb'
141
+	flag(i)= numeric & dims == 3 & sz(1) == sz(2) & sz(3) == 3 ...
142
+		 & in0_1(value);
143
+	
144
+	% nxn matrix of values between [0,1]
145
+       case 'nxn[0,1]' 
146
+	
147
+	flag(i)=numeric & dims == 2 & sz(1) == sz(2) & in0_1(value);
148
+	
149
+	% string 'indexed'
150
+       case 'indexed'
151
+	flag(i) = ischar(value) & strcmp(value,'indexed');
152
+	
153
+	% string 'none'
154
+       case 'none'
155
+	flag(i) = character & strcmp(value,'none');
156
+      
157
+	% string 'xor'
158
+       case 'xor'
159
+	flag(i) = character & strcmp(value,'xor');
160
+	
161
+	% any string (1xn char array)
162
+       case 'string'
163
+	flag(i) = character & dims == 2 & sz(1)<=1;
164
+	
165
+	% any char array
166
+       case 'chararray'
167
+	flag(i) = character & dims == 2 & sz(1)>0;
168
+	
169
+	% ColorSpec string
170
+       case 'colorstyle'
171
+	flag(i)=(character &  sz(1) == 1 & sz(2) == 1 & ...
172
+		 any(ismember('ymcrgbwk',value))) | ...
173
+	(ischar(value) & any(strcmp(value,{'none','yellow','magenta',...
174
+		    'cyan','red','green','blue','white','black'})));
175
+	
176
+	% any valid Matlab's Marker
177
+       case 'markerstyle'
178
+	flag(i)=character &  sz(1) == 1 & sz(2) == 1 & ...
179
+		any(ismember('.ox+*sdv^<>ph',value));
180
+	
181
+	% any valid Matlab's LineStyle
182
+       case 'linestyle'
183
+	str=strrep(strrep(strrep(value,'z','1'),'--','z'),'-.','z');
184
+	flag(i)=character & any(ismember(str,'z-:')) & sz(1)==1 & (sz(2)==1 | sz(2)==2);
185
+	
186
+	% any struct
187
+       case 'struct'
188
+	flag(i)=isstruct(value);
189
+	
190
+	% nx1 cell array of strings
191
+       case 'cellcolumn_of_char'
192
+	flag(i)=iscell(value) & dims == 2 & sz(2)==1;  
193
+	try, char(value); catch, flag(i)=0; end
194
+	
195
+	% mxn cell array of strings
196
+       case '2Dcellarray_of_char'  
197
+	flag(i)=iscell(value) & dims == 2; 
198
+	try, char(cat(2,value{:})); catch, flag(i)=0; end
199
+	
200
+	% valid {lattice, msize} 
201
+       case 'topol_cell_no_shape'
202
+	flag(i)=1;
203
+	if ~iscell(value) | length(size(value)) ~= 2 | size(value,2)~=2
204
+	  flag(i)=0;
205
+	else
206
+	  if vis_valuetype(value{1},{'string'}),
207
+	    switch value{1}
208
+	     case { 'hexa','rect'}
209
+	      ;
210
+	     otherwise
211
+	      flag(i)=0;
212
+	    end
213
+	  end
214
+	  if ~vis_valuetype(value{2},{'1xn'}),
215
+	    flag(i)=0;
216
+	  end
217
+	end
218
+	
219
+	% valid {lattice, msize, shape} 
220
+       case 'topol_cell'
221
+	flag(i)=1;
222
+	if ~iscell(value) | length(size(value)) ~= 2 | size(value,2) ~= 3,
223
+	  flag(i)=0;
224
+	else
225
+	  if vis_valuetype(value{1},{'string'}),
226
+	    switch value{1}
227
+	     case { 'hexa','rect'}
228
+	      ;
229
+	     otherwise
230
+	      flag(i)=0;
231
+	    end
232
+	  end
233
+	  if ~vis_valuetype(value{2},{'1xn'})
234
+	    flag(i)=0;
235
+	  end
236
+	  if ~vis_valuetype(value{3},{'string'})
237
+	    flag(i)=0;
238
+	  else
239
+	    switch value{3}
240
+	     case { 'sheet','cyl', 'toroid'}
241
+	      ;
242
+	     otherwise
243
+	      flag(i)=0;
244
+	    end
245
+	  end
246
+	end
247
+       otherwise
248
+	msg='Unknown valuetype!';
249
+      end
250
+    catch 
251
+      % error during type check is due to wrong type of value: 
252
+      % lets set flag(i) to 0
253
+      flag(i)=0; 
254
+    end
255
+    % Unknown indetifier?
256
+    error(msg);
257
+  end
258
+  % set flag according to 3rd parameter (all ~ AND, any ~ OR) 
259
+  if strcmp(str,'all');
260
+    flag=all(flag);
261
+  else
262
+    flag=any(flag);
263
+  end
264
+end
265
+
266
+
267
+function f=in0_1(value)
268
+
269
+f=all(value(:) >= 0 & value(:)<=1);
0 270
\ No newline at end of file
1 271