Browse code

SVMCrossVal toolbox init

git-svn-id: https://svn.discofish.de/MATLAB/spmtoolbox/SVMCrossVal@90 83ab2cfd-5345-466c-8aeb-2b2739fb922d

Christoph Budziszewski authored on 17/12/2008 13:45:29
Showing 43 changed files
1 1
new file mode 100644
... ...
@@ -0,0 +1,26 @@
1
+function map = LabelMap(label,value)
2
+%LabelMap(labelCellList,valueCellList) maps Label to Classvalues suitable for
3
+%SVM
4
+
5
+if nargin == 2
6
+    if ~ (iscell(label) && iscell(value))
7
+        error('LabelMap:Constructor:argsNoCell','Arguments have to be CellArrays. Vectors not yet supported. sorry.');
8
+    end   
9
+    if(any(size(label) ~= size(value)))
10
+        error('LabelMap:Constructor:sizeDontMatch','Label List and Value List must be the same size!');
11
+    end
12
+    
13
+    map.labelToValue = java.util.HashMap;
14
+    map.valueToLabel = java.util.HashMap;
15
+    
16
+    for i = 1:max(size(label)) % cell array is 1:x or x:1, indexing is same
17
+       map.labelToValue.put(label{i},value{i}); 
18
+       map.valueToLabel.put(value{i},label{i});
19
+    end
20
+    
21
+    map = class(map,'LabelMap');
22
+else
23
+    error('LabelMap:Constructor:noArgs','Sorry, default constructor not supported yet!');
24
+end
25
+
26
+end
0 27
\ No newline at end of file
1 28
new file mode 100644
... ...
@@ -0,0 +1,6 @@
1
+function label = getLabel(mapping,classValue)
2
+if mapping.valueToLabel.containsKey(classValue)
3
+    label = mapping.valueToLabel.get(classValue);   
4
+else
5
+     error('LabelMap:getLabel:noSuchValue','this Mapping does not contain a Value %d',classValue);
6
+end
0 7
\ No newline at end of file
1 8
new file mode 100644
... ...
@@ -0,0 +1,6 @@
1
+function value = getValue(mapping,classLabel)
2
+if mapping.labelToValue.containsKey(classLabel)
3
+    value = mapping.labelToValue.get(classLabel);   
4
+else
5
+     error('LabelMap:getValue:noSuchLabel','this Mapping does not contain a Label ''%s''',classLabel);
6
+end
0 7
\ No newline at end of file
1 8
new file mode 100644
... ...
@@ -0,0 +1,147 @@
1
+function m = SubjectRoiMapping(argv)
2
+%SUBJECTROIMAPPING Subject to ROI to Coordinate Mapping Class Constructor
3
+%   m = SUBJECTROIMAPPING() creates a predefined ROI Coordinate Mapping.
4
+%   normally called without any arguments
5
+
6
+if nargin == 0
7
+    m.subject{1} ='AI020';
8
+    m.subject{2} ='BD001';
9
+    m.subject{3} ='HG027';
10
+    m.subject{4} ='IK011';
11
+    m.subject{5} ='JZ006'; % Guter Proband
12
+    m.subject{6} ='LB001';
13
+    m.subject{7} ='SW007';
14
+    m.subject{8} ='VW005';
15
+
16
+    m.subjectNameMap = java.util.HashMap;
17
+    for subj = 1:size(m.subject,2)
18
+        m.subjectNameMap.put(m.subject{subj},subj);
19
+    end    
20
+    
21
+    
22
+    
23
+    m.roi_name{1}  ='SPL l'; % <-Parietalkortex links 
24
+    m.roi_name{2}  ='SPL r'; % <-Parietalkortex rechts 
25
+    m.roi_name{3}  ='PMd l'; 
26
+    m.roi_name{4}  ='PMd r'; 
27
+    m.roi_name{5}  ='IPSa l'; 
28
+    m.roi_name{6}  ='IPSa r'; 
29
+    m.roi_name{7}  ='SMA'; 
30
+    m.roi_name{8}  ='DLPFC'; 
31
+    m.roi_name{9}  ='V1 l'; 
32
+    m.roi_name{10} ='V1 r'; 
33
+    m.roi_name{11} ='M1 l'; % <-Motorischer Cortex l 
34
+    m.roi_name{12} ='M1 r'; % <-Motorischer Cortex r 
35
+    
36
+    m.roiNameMap = java.util.HashMap;
37
+    for roi = 1:size(m.roi_name,2)
38
+        m.roiNameMap.put(m.roi_name{roi},roi);
39
+    end
40
+
41
+    
42
+    % Koordinaten aller Probanden A von den ROIS B: rois{A}(B,[x y z in mm]) 
43
+    m.coordinate{1}(1,:)  = [-18, -78, 53];
44
+    m.coordinate{1}(2,:)  = [12, -69, 46];
45
+    m.coordinate{1}(3,:)  = [-21, -12, 49];
46
+    m.coordinate{1}(4,:)  = [30, -12, 53];
47
+    m.coordinate{1}(5,:)  = [-30, -51, 39];
48
+    m.coordinate{1}(6,:)  = [ 33, -60, 49];
49
+    m.coordinate{1}(7,:)  = [ -9, 6, 46];
50
+    m.coordinate{1}(8,:)  = [-27 27 48];
51
+    m.coordinate{1}(9,:)  = [-6, -90, -7];
52
+    m.coordinate{1}(10,:) = [12, -90, -4];
53
+    m.coordinate{1}(11,:) = [-57, -24, 49];
54
+    m.coordinate{1}(12,:) = [42, -24, 60];
55
+    m.coordinate{2}(1,:)  = [-9, -72, 56]; 
56
+    m.coordinate{2}(2,:)  = [15, -72, 60]; 
57
+    m.coordinate{2}(3,:)  = [-30, -9, 53]; 
58
+    m.coordinate{2}(4,:)  = [ 30, -9, 49]; 
59
+    m.coordinate{2}(5,:)  = [-42 -36 39]; 
60
+    m.coordinate{2}(6,:)  = [30 -36 42]; 
61
+    m.coordinate{2}(7,:)  = [ -3, 6, 53];
62
+    m.coordinate{2}(8,:)  = [-27 30 28];
63
+    m.coordinate{2}(9,:)  = [-6, -81, -7]; 
64
+    m.coordinate{2}(10,:) = [9, -78, -7];
65
+    m.coordinate{2}(11,:) = [-51, -24, 60];
66
+    m.coordinate{2}(12,:) = [48, -21, 63]; 
67
+    m.coordinate{3}(1,:)  = [-15, -72, 60];
68
+    m.coordinate{3}(2,:)  = [15, -66, 63];
69
+    m.coordinate{3}(3,:)  = [-27, -12, 56];
70
+    m.coordinate{3}(4,:)  = [24 -15 53];
71
+    m.coordinate{3}(5,:)  = [-36 -36 42];
72
+    m.coordinate{3}(6,:)  = [30 -39 35];
73
+    m.coordinate{3}(7,:)  = [-9, 3, 53]; 
74
+    m.coordinate{3}(8,:)  = [-30 30 28];
75
+    m.coordinate{3}(9,:)  = [-3, -90, 4];
76
+    m.coordinate{3}(10,:) = [15, -99, 14];
77
+    m.coordinate{3}(11,:) = [-27, -27, 74];
78
+    m.coordinate{3}(12,:) = [36, -27, 70]; 
79
+    m.coordinate{4}(1,:)  = [-21, -69, 63]; 
80
+    m.coordinate{4}(2,:)  = [21, -69, 63];
81
+    m.coordinate{4}(3,:)  = [-33 -12 53];
82
+    m.coordinate{4}(4,:)  = [12 -9 60];
83
+    m.coordinate{4}(5,:)  = [-33 -35 46];
84
+    m.coordinate{4}(6,:)  = [42 -36 39];
85
+    m.coordinate{4}(7,:)  = [-3 0 49];
86
+    m.coordinate{4}(8,:)  = [-33 33 28];
87
+    m.coordinate{4}(9,:)  = [-3, -90, -7];
88
+    m.coordinate{4}(10,:) = [9, -81, -7];
89
+    m.coordinate{4}(11,:) = [-39, -27, 53];
90
+    m.coordinate{4}(12,:) = [51, -24, 60];
91
+    m.coordinate{5}(1,:)  = [-12 -66 63];
92
+    m.coordinate{5}(2,:)  = [12, -75, 60];
93
+    m.coordinate{5}(3,:)  = [-24, -12, 53];
94
+    m.coordinate{5}(4,:)  = [27, -9, 60]; 
95
+    m.coordinate{5}(5,:)  = [-42 -42 35]; 
96
+    m.coordinate{5}(6,:)  = [33 -48 35];
97
+    m.coordinate{5}(7,:)  = [ -3, 0, 49];
98
+    m.coordinate{5}(8,:)  = [-36 33 28];
99
+    m.coordinate{5}(9,:)  = [-15, -93, -4];
100
+    m.coordinate{5}(10,:) = [15, -90, 4]; 
101
+    m.coordinate{5}(11,:) = [-39, -33, 67];
102
+    m.coordinate{5}(12,:) = [27, -18, 74];
103
+    m.coordinate{6}(1,:)  = [-21, -69, 60];
104
+    m.coordinate{6}(2,:)  = [9, -72, 63];
105
+    m.coordinate{6}(3,:)  = [-24 -12 53];
106
+    m.coordinate{6}(4,:)  = [32 -12 56]; 
107
+    m.coordinate{6}(5,:)  = [-36 -39 35];
108
+    m.coordinate{6}(6,:)  = [42 -33 46]; 
109
+    m.coordinate{6}(7,:)  = [-6 3 49]; 
110
+    m.coordinate{6}(8,:)  = [-36 33 28];
111
+    m.coordinate{6}(9,:)  = [-12, -99, 0];
112
+    m.coordinate{6}(10,:) = [9, -96, -7];
113
+    m.coordinate{6}(11,:) = [-48, -27, 60];
114
+    m.coordinate{6}(12,:) = [33, -33, 60];
115
+    m.coordinate{7}(1,:)  = [-21, -60, 56]; 
116
+    m.coordinate{7}(2,:)  = [12, -69, 60]; 
117
+    m.coordinate{7}(3,:)  = [-24, -12, 49];
118
+    m.coordinate{7}(4,:)  = [24, -6, 49]; 
119
+    m.coordinate{7}(5,:)  = [-33 -45 46]; 
120
+    m.coordinate{7}(6,:)  = [30, -51, 49];
121
+    m.coordinate{7}(7,:)  = [0, 9, 42]; 
122
+    m.coordinate{7}(8,:)  = [-30 36 35]; 
123
+    m.coordinate{7}(9,:)  = [-3, -84, -4];
124
+    m.coordinate{7}(10,:) = [18, -87, -7];
125
+    m.coordinate{7}(11,:) = [-36, -30, 63]; 
126
+    m.coordinate{7}(12,:) = [42, -27, 60];
127
+    m.coordinate{8}(1,:)  = [-27, -63, 53];
128
+    m.coordinate{8}(2,:)  = [18, -66, 56];
129
+    m.coordinate{8}(3,:)  = [-21, -6, 56];
130
+    m.coordinate{8}(4,:)  = [27 -6 53]; 
131
+    m.coordinate{8}(5,:)  = [-36, -51, 49];
132
+    m.coordinate{8}(6,:)  = [45, -39, 53];
133
+    m.coordinate{8}(7,:)  = [-9, 9, 53];
134
+    m.coordinate{8}(8,:)  = [-36 24 25]; 
135
+    m.coordinate{8}(9,:)  = [0, -90, 4]; 
136
+    m.coordinate{8}(10,:) = [0, -90, 4];
137
+    m.coordinate{8}(11,:) = [-42, -27, 67]; 
138
+    m.coordinate{8}(12,:) = [51, -27, 63]; 
139
+
140
+    m = class(m,'SubjectRoiMapping');
141
+    
142
+elseif isa(argv,'SubjectRoiMapping') % copy
143
+   m = argv;
144
+
145
+else
146
+error('SubjectRoiMapping:Constructor:NoSuchConstructor','There is no constructor matching your argv');
147
+end
0 148
\ No newline at end of file
1 149
new file mode 100644
... ...
@@ -0,0 +1,18 @@
1
+function coord = getCoordinate(mapping,subject,roi)
2
+% getCoordinate(SubjectRoiMapping,subjectID,roiID) returns the coordinate
3
+% for the given subject and the given roi. Both subjectID and roiID can
4
+% either be a valid Name (see get[Sunject|Roi]NameCellList(mapping) ) or
5
+% the corresponding numerical ID.
6
+
7
+if ischar(subject) && ischar(roi)
8
+    coord = getCoordinate(mapping,getSubjectID(mapping,subject),getRoiID(mapping,roi));
9
+elseif isnumeric(subject) && ischar(roi)
10
+    coord = getCoordinate(mapping,subject,getRoiID(mapping,roi));
11
+elseif ischar(subject) && isnumeric(roi)
12
+    coord = getCoordinate(mapping,getSubjectID(mapping,subject),roi);
13
+elseif isnumeric(subject) && isnumeric(roi)
14
+    coord = mapping.coordinate{subject}(roi,:);
15
+else
16
+    error('SubjectRoiMapping:getCoordinate:BadArguments','Subject has to be a valid subject identifier (either char or integer)');
17
+end
18
+
0 19
new file mode 100644
... ...
@@ -0,0 +1,5 @@
1
+function roinames = getRoiNameCellList(mapping)
2
+% getRoiNameCellList(SubjectRoiMapping) returns a cell Array of ROI
3
+% identifiers
4
+    roinames = mapping.roi_name;
5
+end
0 6
new file mode 100644
... ...
@@ -0,0 +1,5 @@
1
+function namelist = getSubjectCellList(mapping)
2
+% getSubjectCellList(SubjectRoiMapping) returns a cell Array of subject
3
+% identifiers
4
+    namelist = mapping.subject;
5
+end
0 6
\ No newline at end of file
1 7
new file mode 100644
... ...
@@ -0,0 +1,7 @@
1
+function id = getRoiID(mapping,roiName)
2
+if mapping.roiNameMap.containsKey(roiName)
3
+    id = mapping.roiNameMap.get(roiName);   
4
+else
5
+     error('SubjectRoiMapping:getRoiID:noSuchName','this Mapping does not contain a ROI ''%s''',roiName);
6
+end
7
+end
0 8
\ No newline at end of file
1 9
new file mode 100644
... ...
@@ -0,0 +1,7 @@
1
+function id = getSubjectID(mapping,subjectName)
2
+if mapping.subjectNameMap.containsKey(subjectName)
3
+    id = mapping.subjectNameMap.get(subjectName);   
4
+else
5
+     error('SubjectRoiMapping:getSubjectID:noSuchName','this Mapping does not contain a Name ''%s''',subjectName);
6
+end
7
+end
0 8
\ No newline at end of file
1 9
new file mode 100644
... ...
@@ -0,0 +1,20 @@
1
+function vValue = VoxelValueAtTimepoint (coordinate, timepoint)
2
+% single Voxel for single coordinate
3
+
4
+if(size(coordinate,2)>1)
5
+    error('VoxelValueAtTimepoint:CoordinateError','only single Coordinate permitted.');
6
+end
7
+
8
+imageNumber = timePointToImageNumber(timepoint, 's');
9
+V           = evalin('base','SPM.xY.VY'); % Memory Mapped Images
10
+center      = round(inv(V(imageNumber).mat)*[coordinate; 1]);
11
+
12
+x           = center(1,1);
13
+y           = center(2,1);
14
+z           = center(3,1);
15
+
16
+vValue      = spm_sample_vol(V(imageNumber), x, y, z, 0);
17
+
18
+end
19
+
20
+
0 21
new file mode 100644
... ...
@@ -0,0 +1,278 @@
1
+% function [decodePerformance rawTimecourse ] = calculateDecodePerformance(des,timeLineStart, timeLineEnd, decodeDuration, svmargs, conditionList, sessionList, voxelList, classList, labelMap,normalize)
2
+function outputStruct = calculateDecodePerformance(inputStruct)
3
+
4
+addpath 'libsvm-mat-2.88-1';
5
+
6
+outputStruct = struct;
7
+
8
+des             = inputStruct.des;
9
+timeLineStart   = inputStruct.frameShiftStart;
10
+timeLineEnd     = inputStruct.frameShiftEnd;
11
+decodeDuration  = inputStruct.decodeDuration;
12
+svmargs         = inputStruct.svmargs;
13
+sessionList     = inputStruct.sessionList;
14
+voxelList       = inputStruct.voxelList;
15
+% classList       = inputStruct.classList;
16
+% labelMap        = inputStruct.labelMap;
17
+% normalize       = inputStruct.normalize;
18
+globalStart     = inputStruct.psthStart;
19
+globalEnd       = inputStruct.psthEnd;
20
+baselineStart   = inputStruct.baselineStart;
21
+baselineEnd     = inputStruct.baselineEnd;
22
+eventList       = inputStruct.eventList;
23
+
24
+
25
+minPerformance = inf;
26
+maxPerformance = -inf;
27
+
28
+
29
+        
30
+        %Pro Voxel PSTH TIMELINE berechnen.
31
+        %   timeshift mit pst-timeline durchf�hren.
32
+        % psth-timeline -25 bis +15 zu RES Onset.
33
+        
34
+%         eventList       = [9,11,13;10,12,14];
35
+%         globalStart     = -25;
36
+%         globalEnd       = 15;
37
+%         baselineStart   = -22;
38
+%         baselineEnd     = -20;
39
+        
40
+        
41
+        for voxel = 1:size(voxelList,1)  % [[x;x],[y;y],[z;z]]
42
+                extr  = calculateImageData(voxelList(voxel,:),des);
43
+                rawdata=cell2mat({extr.mean}); % Raw Data
44
+                pst{voxel}  = calculatePST(des,globalStart,baselineStart,baselineEnd,globalEnd,eventList,rawdata,sessionList);
45
+        end
46
+
47
+        decodePerformance = [];
48
+
49
+        for timeShift   = timeLineStart:1:timeLineEnd
50
+            frameStart  = floor(-globalStart+1+timeShift - 0.5*decodeDuration);
51
+            frameEnd    = min(ceil(frameStart+decodeDuration + 0.5*decodeDuration),-globalStart+globalEnd);
52
+            
53
+            tmp =[];
54
+            anyvoxel = 1;
55
+            for label = 1:size(pst{1,anyvoxel},2) 
56
+                for dp = 1:size(pst{1,anyvoxel}{1,label},1) % data point
57
+                row = label;
58
+                    for voxel = 1:size(pst,2)
59
+                        row = [row, pst{1,voxel}{1,label}(dp,frameStart:frameEnd)]; % label,value,value
60
+                    end
61
+                tmp  = [tmp; row];
62
+                end
63
+            end 
64
+        
65
+            svmdata      = tmp(:,2:size(tmp,2));
66
+            svmlabel     = tmp(:,1);
67
+            performance  = svmtrain(svmlabel, svmdata, svmargs);
68
+
69
+            minPerformance = min(minPerformance,performance);
70
+            maxPerformance = max(maxPerformance,performance);
71
+
72
+            decodePerformance = [decodePerformance; performance];
73
+        end
74
+        
75
+        outputStruct.decodePerformance  = decodePerformance;
76
+        outputStruct.svmdata            = svmdata;
77
+        outputStruct.svmlabel           = svmlabel;
78
+        outputStruct.rawTimeCourse      = pst;
79
+        outputStruct.minPerformance     = minPerformance;
80
+        outputStruct.maxPerformance     = maxPerformance;
81
+
82
+% display(sprintf('Min CrossVal Accuracy: %g%% \t Max CrossVal Accuracy: %g%%',minPerformance,maxPerformance));
83
+end
84
+
85
+
86
+function extr = calculateImageData(voxelList,des)
87
+
88
+dtype='PSTH';
89
+
90
+switch dtype 
91
+    case 'PSTH'
92
+        V=des.xY.VY;
93
+    case 'betas'
94
+        V=des.Vbeta;
95
+end;
96
+%   for z=1:length(V) % Change Drive Letter!
97
+%       V(z).fname(1)='E';
98
+%   end;
99
+
100
+% rad = 0; % one voxel
101
+% opt = 1; % xyz coordinates [mm]
102
+
103
+
104
+vox = voxelList;
105
+nRoi = size(vox,1);
106
+
107
+nImg = numel(V);
108
+
109
+for k=1:nImg
110
+	extr(k) = struct(...
111
+        'val',   repmat(NaN, [1 nRoi]),...
112
+		'mean',  repmat(NaN, [1 nRoi]),...
113
+		'sum',   repmat(NaN, [1 nRoi]),...
114
+		'nvx',   repmat(NaN, [1 nRoi]),...
115
+		'posmm', repmat(NaN, [3 nRoi]),...
116
+		'posvx', repmat(NaN, [3 nRoi]));
117
+
118
+    roicenter = round(inv(V(k).mat)*[vox, ones(nRoi,1)]');
119
+
120
+	for l = 1:nRoi
121
+
122
+%         if rad==0
123
+            x = roicenter(1,l);
124
+            y = roicenter(2,l);
125
+            z = roicenter(3,l);
126
+%         else
127
+%             tmp = spm_imatrix(V(k).mat);
128
+%             vdim = tmp(7:9);
129
+%             vxrad = ceil((rad*ones(1,3))./(ones(nRoi,1)*vdim))';
130
+%             [x y z] = ndgrid(-vxrad(1,l):sign(vdim(1)):vxrad(1,l), ...
131
+%                       -vxrad(2,l):sign(vdim(2)):vxrad(2,l), ...
132
+%                       -vxrad(3,l):sign(vdim(3)):vxrad(3,l));
133
+%             sel = (x./vxrad(1,l)).^2 + (y./vxrad(2,l)).^2 + ...
134
+%                   (z./vxrad(3,l)).^2 <= 1;
135
+%             x = roicenter(1,l)+x(sel(:));
136
+%             y = roicenter(2,l)+y(sel(:));
137
+%             z = roicenter(3,l)+z(sel(:));
138
+%         end;
139
+		dat                 = spm_sample_vol(V(k), x, y, z,0);
140
+		[maxv maxi]         = max(dat);
141
+		tmp                 = V(k).mat*[x(maxi); y(maxi); z(maxi);1]; % Max Pos
142
+		extr(k).val(l)      = maxv;
143
+		extr(k).sum(l)      = sum(dat);
144
+		extr(k).mean(l)     = nanmean(dat);
145
+        extr(k).nvx(l)      = numel(dat);
146
+		extr(k).posmm(:,l)  = tmp(1:3);
147
+		extr(k).posvx(:,l)  = [x(maxi); y(maxi); z(maxi)]; % Max Pos
148
+	end;
149
+
150
+end;
151
+end
152
+
153
+% disp(sprintf('Extracted at %.1f %.1f %.1f [xyz(mm)], average of %i voxel(s) [%.1fmm radius Sphere]',vox,length(x),rad));
154
+
155
+function pst = calculatePST(des,globalStart,baselineStart,baselineEnd,globalEnd,eventList,data,sessionList)
156
+    bstart          = baselineStart;
157
+    bend            = baselineEnd;
158
+    edur            = 12;
159
+    pre             =  globalStart;
160
+    post            =  globalEnd;
161
+    res             = 1;
162
+
163
+    normz           = 'file';
164
+    pm              = 0;
165
+
166
+    lsess           = getNumberOfScans(des);
167
+    nSessions       = getNumberOfSessions(des);
168
+    tr              = 2;
169
+
170
+    [evntrow evntcol]=size(eventList);
171
+    
172
+
173
+    hsec=str2num(des.xsDes.High_pass_Filter(8:end-3)); % Highpass filter [sec] from SPM.mat
174
+
175
+    if strcmp(des.xBF.UNITS,'secs')
176
+        unitsecs=1;
177
+    end;
178
+
179
+    nScansPerSession=getNumberOfScans(des);
180
+    %stime=[0:tr:max(nScansPerSession)*tr+post-tr]; % Stimulus time for raw data plot
181
+    stime=0:tr:max(nScansPerSession)*tr+round(post/tr)*tr-tr; % Stimulus time for raw data plot
182
+
183
+
184
+
185
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
186
+    % RUN
187
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
188
+
189
+
190
+    % Digital Highpass
191
+    Rp=0.5;
192
+    Rs=20;
193
+    NO=1;
194
+    Wp=1/((1/2/tr)/(1/hsec));
195
+    [B, A] = ellip(NO,Rp,Rs,Wp,'high');
196
+
197
+    sdata(1:max(nScansPerSession)+round(post/tr),1:nSessions)=nan; % Open Data Matrix
198
+    for z=1:nSessions % Fill Data Matrix sessionwise
199
+        sdata(1:nScansPerSession(z),z)=data(sum(nScansPerSession(1:z))-nScansPerSession(z)+1:sum(nScansPerSession(1:z)))';
200
+    end;
201
+%         usdata=sdata; % Keep unfiltered data
202
+
203
+    sdatamean=nanmean(nanmean(sdata(:,:)));
204
+    for z=1:nSessions
205
+%             X(:,z)=[1:1:max(nScansPerSession)]'; % #Volume
206
+        sdata(1:nScansPerSession(z),z)=filtfilt(B,A,sdata(1:nScansPerSession(z),z)); %Filter Data (Highpass)
207
+    end;
208
+    sdata=sdata+sdatamean;
209
+
210
+
211
+    %%%%Parametric Modulation Modus%%%%
212
+    if pm %Find Parameters for Event of Interest
213
+        [imods modss mods erow evntrow eventList] = getParametricMappingEvents(eventList,evntrow,des,pmf);
214
+    end;
215
+    %%%%PM%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
216
+
217
+
218
+    for zr=1:evntrow
219
+        n{zr}=0;
220
+        nn{zr}=0; 
221
+        nnn{zr}=0;
222
+        sstart{zr}=1;
223
+    end;
224
+
225
+
226
+    sesst0=0; 
227
+    for sessionID=sessionList
228
+        if sessionID>1
229
+            sesst0(sessionID)=sum(lsess(1:sessionID-1))*tr;  
230
+        end;
231
+        for zr=1:evntrow  %LABEL NUMBER, EVENT GROUP
232
+            sstart{zr}=n{zr}+1;
233
+            for ze=1:evntcol % EVENT INDEX in EventList
234
+                if ze==1 || (ze>1 && eventList(zr,ze)~=eventList(zr,ze-1))
235
+                    for zz=1:length(des.Sess(sessionID).U(eventList(zr,ze)).ons) % EVENT REPETITION NUMBER
236
+                        if ~unitsecs
237
+                            des.Sess(sessionID).U(eventList(zr,ze)).ons(zz)=(des.Sess(sessionID).U(eventList(zr,ze)).ons(zz)-1)*tr;
238
+                            des.Sess(sessionID).U(eventList(zr,ze)).dur(zz)=(des.Sess(sessionID).U(eventList(zr,ze)).dur(zz)-1)*tr;
239
+                        end;
240
+
241
+                        nnn{zr}=nnn{zr}+1; % INFO for rawdataplot start
242
+                        if des.Sess(sessionID).U(eventList(zr,ze)).dur(zz)<edur
243
+                            mev{zr}(nnn{zr},1:2)=[des.Sess(sessionID).U(eventList(zr,ze)).ons(zz)+sesst0(sessionID) edur]; % modeled event [onset length]
244
+                        else
245
+                            mev{zr}(nnn{zr},1:2)=[des.Sess(sessionID).U(eventList(zr,ze)).ons(zz)+sesst0(sessionID) des.Sess(sessionID).U(eventList(zr,ze)).dur(zz)];
246
+                        end; % INFO for rawdataplot end
247
+
248
+                        n{zr}=n{zr}+1;
249
+                        pst{zr}(n{zr},:)=interp1(stime,sdata(:,sessionID),[des.Sess(sessionID).U(eventList(zr,ze)).ons(zz)+pre:res:des.Sess(sessionID).U(eventList(zr,ze)).ons(zz)+post],'linear');
250
+                        if strcmp(normz,'epoc')
251
+                            bline=nanmean(pst{zr}(n{zr},round(-pre/res+(bstart)/res+1):round(-pre/res+(bend)/res+1)));
252
+                            if isnan(bline)
253
+                                pst{zr}(n{zr},1:-pre/res+post/res+1)=nan;
254
+                            else
255
+%                                     nn{zr}=nn{zr}+1;
256
+                                pst{zr}(n{zr},:)=(pst{zr}(n{zr},:)-bline)/bline*100; % 'epoch-based' normalization
257
+                            end;
258
+                        end;
259
+                    end;
260
+                end;
261
+            end;
262
+            if ~strcmp(normz,'epoc')
263
+                bline(zr)=nanmean(nanmean(pst{zr}(sstart{zr}:n{zr},-pre/res+(bstart)/res+1:-pre/res+(bend)/res+1)));
264
+                bstd(zr)=nanmean(nanstd(pst{zr}(sstart{zr}:n{zr},-pre/res+(bstart)/res+1:-pre/res+(bend)/res+1)));
265
+                nn{zr}=n{zr};
266
+            end;
267
+        end;
268
+        if strcmp(normz,'filz')
269
+            for zr=1:evntrow
270
+                pst{zr}(sstart{zr}:n{zr},:)=(pst{zr}(sstart{zr}:n{zr},:)-mean(bline))/mean(bstd); % session-based z-score normalization
271
+            end;
272
+        elseif strcmp(normz,'file')
273
+            for zr=1:evntrow
274
+                pst{zr}(sstart{zr}:n{zr},:)=(pst{zr}(sstart{zr}:n{zr},:)-mean(bline))/mean(bline)*100; % session-based normalization
275
+            end;
276
+        end;
277
+    end;
278
+end
0 279
new file mode 100644
... ...
@@ -0,0 +1,138 @@
1
+function classify(action)
2
+
3
+if ~exist('action','var')
4
+    action='no action';
5
+end
6
+
7
+    switch(action)
8
+    case 'clear'
9
+        evalin('base','clear map lm SPM classList dataTimeLine decodeTable labelTimeLine svmopts trialProtocol voxelList xTimeEnd xTimeStart xTimeWindow');
10
+      
11
+    case 'decode'
12
+    
13
+
14
+
15
+        display('loading SPM.mat');
16
+        SubjectID = 'JZ006';
17
+%         SubjectID = 'AI020';
18
+%         SubjectID = 'HG027';
19
+        spm = load(fullfile('D:\Analyze\Choice\24pilot',SubjectID,'results\SPM.mat'));
20
+
21
+        display('done.');
22
+
23
+
24
+
25
+
26
+        map = SubjectRoiMapping;
27
+
28
+        voxelList  = [...
29
+                      getCoordinate(map,SubjectID,'SPL l')+[0,0,0];...
30
+                          getCoordinate(map,SubjectID,'SPL l')+[1,0,0];...
31
+                          getCoordinate(map,SubjectID,'SPL l')+[-1,0,0];...
32
+                          getCoordinate(map,SubjectID,'SPL l')+[0,1,0];...
33
+                          getCoordinate(map,SubjectID,'SPL l')+[0,-1,0];...
34
+                          getCoordinate(map,SubjectID,'SPL l')+[0,0,1];...
35
+                          getCoordinate(map,SubjectID,'SPL l')+[0,0,-1];...
36
+                      getCoordinate(map,SubjectID,'SPL r')+[0,0,0];...
37
+                          getCoordinate(map,SubjectID,'SPL r')+[1,0,0];...
38
+                          getCoordinate(map,SubjectID,'SPL r')+[-1,0,0];...
39
+                          getCoordinate(map,SubjectID,'SPL r')+[0,1,0];...
40
+                          getCoordinate(map,SubjectID,'SPL r')+[0,-1,0];...
41
+                          getCoordinate(map,SubjectID,'SPL r')+[0,0,1];...
42
+                          getCoordinate(map,SubjectID,'SPL r')+[0,0,-1];...
43
+                      getCoordinate(map,SubjectID,'M1 r')+[0,0,0];...
44
+                      getCoordinate(map,SubjectID,'M1 l')+[0,0,0];...
45
+                      ];
46
+        
47
+        
48
+        params = struct;
49
+        params.nClasses = 2;
50
+
51
+        assignin('base','params',params);
52
+        %% calculate
53
+        display('calculating cross-validation performance time-shift');
54
+        calculateParams  = struct;
55
+        
56
+        calculateParams.des             = spm.SPM;
57
+        calculateParams.frameShiftStart = -20;
58
+        calculateParams.frameShiftEnd   = 15;
59
+        calculateParams.decodeDuration  = 1;
60
+        calculateParams.svmargs         = '-t 0 -s 0 -v 6';
61
+        calculateParams.sessionList     = 1:3;
62
+        calculateParams.voxelList       = voxelList;
63
+        calculateParams.classList       = {'<','>'};
64
+        calculateParams.labelMap        = LabelMap({'<','>','<+<','>+>','<+>','>+<'},{-2,-1,1,2,3,4});
65
+        calculateParams.psthStart       = -25;
66
+        calculateParams.psthEnd         = 20;
67
+        calculateParams.baselineStart   = -22;
68
+        calculateParams.baselineEnd     = -20;
69
+        calculateParams.eventList       = [9,11,13; 10,12,14];
70
+        
71
+        assignin('base','calculateParams',calculateParams);
72
+        
73
+%         [decodeTable rawTimeCourse] = calculateDecodePerformance(spm,params.frameShiftStart,params.frameShiftEnd,params.xTimeWindow,params.svmopts,1:4,params.sessionList,params.voxelList,params.classList,params.labelMap,params.normalize);
74
+        decode = calculateDecodePerformance(calculateParams);
75
+        display(sprintf('Min CrossVal Accuracy: %g%% \t Max CrossVal Accuracy: %g%%',decode.minPerformance,decode.maxPerformance));
76
+        
77
+        assignin('base','decode',decode);
78
+
79
+        display('Finished calculations.');
80
+        display('Plotting.');
81
+
82
+        plotParams = struct;
83
+        plotParams.psthStart = calculateParams.psthStart;
84
+        plotParams.psthEnd   = calculateParams.psthEnd;
85
+        plotParams.nClasses  = length(calculateParams.classList);
86
+        plotParams.frameShiftStart   = calculateParams.frameShiftStart;
87
+        plotParams.frameShiftEnd     = calculateParams.frameShiftEnd;
88
+        plotParams.decodePerformance = decode.decodePerformance;
89
+        plotParams.rawTimeCourse     = decode.rawTimeCourse;
90
+        plotParams.SubjectID         = SubjectID;
91
+        
92
+        assignin('base','plotParams',plotParams);
93
+%         plotDecodePerformance(params.psthStart,params.psthEnd,params.nClasses,decode.decodeTable,params.frameShiftStart,params.frameShiftEnd,decode.rawTimeCourse);
94
+        plotDecodePerformance(plotParams);
95
+
96
+        case 'gen'
97
+            center = '[-39 -33 67]';
98
+            sessionList = '1:3';
99
+            conditionList = '1:2';
100
+            radius = 3;
101
+            normalize = 1;
102
+
103
+            cmd=sprintf(...
104
+                '[label data] = generateDataMatrix(generateVoxelList(%s,%d), generateTrialProtocol(%s,%s),%d);',...
105
+                center,radius,sessionList,conditionList,normalize);
106
+
107
+            %     assignin('base','label',label);
108
+            %     assignin('base','data',data);
109
+
110
+    case 'norm'
111
+        cmd = ['for i=1:size(data,2)'...
112
+            'data(:,i)=data(:,i)/std(data(:,i));'...
113
+        'end;'];
114
+        
115
+    case 'xtrain'
116
+        svmargs = '-t 0'; %linear kernel
117
+        svmargs = [svmargs '-v 4'];
118
+        
119
+        cmd=sprintf('model = svmtrain(label,data,''%s'')',svmargs);
120
+        
121
+    case 'train'
122
+        svmargs = '-t 0'; %linear kernel
123
+%         svmargs = [svmargs '-v 4'];
124
+        
125
+        cmd=sprintf('model = svmtrain(label,data,%s)',svmargs);
126
+       
127
+    case 'pred'
128
+        cmd = '[predicted_label, accuracy, decision_values] = svmpredict(label, data, model);';
129
+        
130
+    otherwise
131
+        display('give action command: clear load gen (norm) xtrain train pred');
132
+    end
133
+    
134
+    if exist('cmd','var') 
135
+        evalin('base',cmd);
136
+    end
137
+
138
+end
0 139
\ No newline at end of file
1 140
new file mode 100644
... ...
@@ -0,0 +1,20 @@
1
+function voxellist = generateVoxelList(center, radius)
2
+%     cx = ROICenter(1);
3
+%     cy = ROICenter(2);
4
+%     cz = ROICenter(3);
5
+    
6
+    voxellist = [];
7
+    
8
+    cx = center(1);
9
+    cy = center(2);
10
+    cz = center(3);
11
+
12
+    for z=cz-radius+1:cz+radius-1
13
+        for y=(cy-radius+1):(cy+radius-1)
14
+            for x=(cx-radius+1):(cx+radius-1)
15
+                voxellist = [voxellist [x;y;z]];
16
+            end
17
+        end
18
+    end
19
+
20
+end
0 21
\ No newline at end of file
1 22
new file mode 100644
... ...
@@ -0,0 +1,10 @@
1
+function duration = getDuration(session, condition, repetition)
2
+%session    : the session number. 
3
+%condition  : the condition intrested in (CUE1,CUE2,...)
4
+%repetition : the repetition number; same event, different time ;)
5
+
6
+cmd = sprintf('SPM.Sess(%d,%d).U(%d,%d).dur(%d)',1,session,1,condition,repetition);
7
+
8
+duration = evalin('base',cmd);
9
+
10
+end
0 11
\ No newline at end of file
1 12
new file mode 100644
... ...
@@ -0,0 +1,4 @@
1
+function rep = getNumberOfRepetitions(session,condition)
2
+   cmd = sprintf('length(SPM.Sess(%d,%d).U(%d,%d).ons)',1,session,1,condition);
3
+   rep = evalin('base',cmd);
4
+end
0 5
\ No newline at end of file
1 6
new file mode 100644
... ...
@@ -0,0 +1,4 @@
1
+% Number of Scans per session
2
+function nScan = getNumberOfScans(des)
3
+    nScan = des.nscan;
4
+end
0 5
\ No newline at end of file
1 6
new file mode 100644
... ...
@@ -0,0 +1,4 @@
1
+function nSessions = getNumberOfSessions(des)
2
+    nSessions = length(des.Sess);
3
+%     nSessions = model.nSessions;
4
+end
0 5
\ No newline at end of file
1 6
new file mode 100644
... ...
@@ -0,0 +1,11 @@
1
+function onset = getOnset(session,condition,repetition)
2
+
3
+%session    : the session number. 
4
+%condition  : the condition intrested in (CUE1,CUE2,...)
5
+%repetition : the repetition number; same event, different time ;)
6
+
7
+cmd = sprintf('SPM.Sess(%d,%d).U(%d,%d).ons(%d)',1,session,1,condition,repetition);
8
+
9
+onset = evalin('base',cmd);
10
+
11
+end
0 12
\ No newline at end of file
1 13
new file mode 100644
2 14
Binary files /dev/null and b/javahelper/LabelMap.class differ
3 15
new file mode 100644
... ...
@@ -0,0 +1,38 @@
1
+import java.util.HashMap; 
2
+
3
+class LabelMap {
4
+
5
+private HashMap<String,Double> labelToValue;
6
+private HashMap<Double,String> valueToLabel;
7
+
8
+public LabelMap(){
9
+    this(2);
10
+}
11
+
12
+public LabelMap(int numberOfLabels){
13
+    labelToValue = new HashMap<String,Double>(numberOfLabels+1,1);
14
+    valueToLabel = new HashMap<Double,String>(numberOfLabels+1,1);
15
+}
16
+
17
+public void add(String label, double value){
18
+    labelToValue.put(label,value);
19
+    valueToLabel.put(value,label);
20
+}
21
+
22
+public String getLabel(double value){
23
+    return valueToLabel.get(value);
24
+}
25
+
26
+public Double getValue(String label){
27
+    return labelToValue.get(label);
28
+}
29
+
30
+public String toString(){
31
+    StringBuffer s = new StringBuffer("LabelMap: \n");
32
+    for( String key : labelToValue.keySet()){
33
+        s.append(key+'\t'+labelToValue.get(key)+"\n");
34
+    }
35
+    return s.toString();
36
+}
37
+    
38
+}
0 39
\ No newline at end of file
1 40
new file mode 100644
2 41
Binary files /dev/null and b/javahelper/classLabelMap.mat differ
3 42
new file mode 100644
... ...
@@ -0,0 +1,14 @@
1
+function generateClassLabelValueMaps(filename)
2
+
3
+if exist(filename,'file')
4
+    vars = load(filename);
5
+    clMap = vars.classLabelMap;
6
+    nItems = size(clMap,1);
7
+    lm = LabelMap(nItems);
8
+    for item = 1:nItems
9
+        label = clMap(item,1);
10
+        value = cell2mat(clMap(item,2));
11
+        lm.add(label,value)
12
+    end
13
+    assignin('base','lm',lm);
14
+end
0 15
\ No newline at end of file
1 16
new file mode 100644
... ...
@@ -0,0 +1,5 @@
1
+function label = getClassLabel(key)
2
+    cmd = sprintf('lm.getLabel(%d)',key);
3
+    label = evalin('base',cmd);
4
+end
5
+ 
0 6
\ No newline at end of file
1 7
new file mode 100644
... ...
@@ -0,0 +1,4 @@
1
+function clazz = getClassValue(key)
2
+    cmd = sprintf('lm.getValue(''%s'')',key);
3
+    clazz = evalin('base',cmd);
4
+end
0 5
new file mode 100644
... ...
@@ -0,0 +1,31 @@
1
+
2
+Copyright (c) 2000-2008 Chih-Chung Chang and Chih-Jen Lin
3
+All rights reserved.
4
+
5
+Redistribution and use in source and binary forms, with or without
6
+modification, are permitted provided that the following conditions
7
+are met:
8
+
9
+1. Redistributions of source code must retain the above copyright
10
+notice, this list of conditions and the following disclaimer.
11
+
12
+2. Redistributions in binary form must reproduce the above copyright
13
+notice, this list of conditions and the following disclaimer in the
14
+documentation and/or other materials provided with the distribution.
15
+
16
+3. Neither name of copyright holders nor the names of its contributors
17
+may be used to endorse or promote products derived from this software
18
+without specific prior written permission.
19
+
20
+
21
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22
+``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24
+A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR
25
+CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
0 32
new file mode 100644
... ...
@@ -0,0 +1,47 @@
1
+# This Makefile is used under Linux
2
+
3
+MATLABDIR ?= /usr/local/matlab
4
+CXX ?= g++
5
+#CXX = g++-4.1
6
+CFLAGS = -Wall -O3 -fPIC -I$(MATLABDIR)/extern/include
7
+
8
+MEX = $(MATLABDIR)/bin/mex
9
+MEX_OPTION = CC\#$(CXX) CXX\#$(CXX) CFLAGS\#"$(CFLAGS)" CXXFLAGS\#"$(CFLAGS)"
10
+# comment the following line if you use MATLAB on 32-bit computer
11
+MEX_OPTION += -largeArrayDims
12
+MEX_EXT = $(shell $(MATLABDIR)/bin/mexext)
13
+
14
+OCTAVEDIR ?= /usr/include/octave
15
+OCTAVE_MEX = env CC=$(CXX) mkoctfile
16
+OCTAVE_MEX_OPTION = --mex
17
+OCTAVE_MEX_EXT = mex
18
+OCTAVE_CFLAGS = -Wall -O3 -fPIC -I$(OCTAVEDIR)
19
+
20
+all:	matlab
21
+
22
+matlab:	binary
23
+
24
+octave:
25
+	@make MEX="$(OCTAVE_MEX)" MEX_OPTION="$(OCTAVE_MEX_OPTION)" \
26
+	MEX_EXT="$(OCTAVE_MEX_EXT)" CFLAGS="$(OCTAVE_CFLAGS)" \
27
+	binary
28
+
29
+binary: svmpredict.$(MEX_EXT) svmtrain.$(MEX_EXT) read_sparse.$(MEX_EXT)
30
+
31
+svmpredict.$(MEX_EXT):     svmpredict.c svm.h svm.o svm_model_matlab.o
32
+	$(MEX) $(MEX_OPTION) svmpredict.c svm.o svm_model_matlab.o
33
+
34
+svmtrain.$(MEX_EXT):       svmtrain.c svm.h svm.o svm_model_matlab.o
35
+	$(MEX) $(MEX_OPTION) svmtrain.c svm.o svm_model_matlab.o
36
+
37
+read_sparse.$(MEX_EXT):	read_sparse.c
38
+	$(MEX) $(MEX_OPTION) read_sparse.c
39
+
40
+svm_model_matlab.o:     svm_model_matlab.c svm.h
41
+	$(CXX) $(CFLAGS) -c svm_model_matlab.c
42
+
43
+svm.o:  svm.cpp svm.h
44
+	$(CXX) $(CFLAGS) -c svm.cpp
45
+
46
+clean:
47
+	rm -f *~ *.o *.mex* *.obj
0 48
new file mode 100644
... ...
@@ -0,0 +1,210 @@
1
+-----------------------------------------
2
+--- MATLAB/OCTAVE interface of LIBSVM ---
3
+-----------------------------------------
4
+
5
+Table of Contents
6
+=================
7
+
8
+- Introduction
9
+- Installation
10
+- Usage
11
+- Returned Model Structure
12
+- Examples
13
+- Other Utilities
14
+- Additional Information
15
+
16
+
17
+Introduction
18
+============
19
+
20
+This tool provides a simple interface to LIBSVM, a library for support vector
21
+machines (http://www.csie.ntu.edu.tw/~cjlin/libsvm). It is very easy to use as
22
+the usage and the way of specifying parameters are the same as that of LIBSVM.
23
+
24
+Installation
25
+============
26
+
27
+On Unix systems, we recommend using GNU g++ as your
28
+compiler and type 'make' to build 'svmtrain.mexglx' and 'svmpredict.mexglx'.
29
+Note that we assume your MATLAB is installed in '/usr/local/matlab',
30
+if not, please change MATLABDIR in Makefile.
31
+
32
+Example:
33
+        linux> make
34
+
35
+To use Octave, type 'make octave':
36
+
37
+Example:
38
+	linux> make octave
39
+
40
+On Windows systems, pre-built 'svmtrain.mexw32' and 'svmpredict.mexw32' are
41
+included in this package, so no need to conduct installation. If you
42
+have modified the sources and would like to re-build the package, type
43
+'mex -setup' in MATLAB to choose a compiler for mex first. Then type
44
+'make' to start the installation.
45
+
46
+Starting from MATLAB 7.1 (R14SP3), the default MEX file extension is changed
47
+from .dll to .mexw32 or .mexw64 (depends on 32-bit or 64-bit Windows). If your
48
+MATLAB is older than 7.1, you have to build these files yourself.
49
+
50
+Example:
51
+        matlab> mex -setup
52
+        (ps: MATLAB will show the following messages to setup default compiler.)
53
+        Please choose your compiler for building external interface (MEX) files: 
54
+        Would you like mex to locate installed compilers [y]/n? y
55
+        Select a compiler: 
56
+        [1] Microsoft Visual C/C++ version 7.1 in C:\Program Files\Microsoft Visual Studio 
57
+        [0] None 
58
+        Compiler: 1
59
+        Please verify your choices: 
60
+        Compiler: Microsoft Visual C/C++ 7.1 
61
+        Location: C:\Program Files\Microsoft Visual Studio 
62
+        Are these correct?([y]/n): y
63
+
64
+        matlab> make
65
+
66
+
67
+Under 64-bit Windows, Visual Studio 2005 user will need "X64 Compiler and Tools".
68
+The package won't be installed by default, but you can find it in customized
69
+installation options.
70
+
71
+For list of supported/compatible compilers for MATLAB, please check the
72
+following page:
73
+
74
+http://www.mathworks.com/support/compilers/current_release/
75
+
76
+Usage
77
+=====
78
+
79
+matlab> model = svmtrain(training_label_vector, training_instance_matrix [, 'libsvm_options']);
80
+
81
+        -training_label_vector:
82
+            An m by 1 vector of training labels (type must be double).
83
+        -training_instance_matrix:
84
+            An m by n matrix of m training instances with n features.
85
+            It can be dense or sparse (type must be double).
86
+        -libsvm_options:
87
+            A string of training options in the same format as that of LIBSVM.
88
+
89
+matlab> [predicted_label, accuracy, decision_values/prob_estimates] = svmpredict(testing_label_vector, testing_instance_matrix, model [, 'libsvm_options']);
90
+
91
+        -testing_label_vector:
92
+            An m by 1 vector of prediction labels. If labels of test
93
+            data are unknown, simply use any random values. (type must be double)
94
+        -testing_instance_matrix:
95
+            An m by n matrix of m testing instances with n features.
96
+            It can be dense or sparse. (type must be double)
97
+        -model:
98
+            The output of svmtrain.
99
+        -libsvm_options:
100
+            A string of testing options in the same format as that of LIBSVM.
101
+
102
+Returned Model Structure
103
+========================
104
+
105
+The 'svmtrain' function returns a model which can be used for future
106
+prediction.  It is a structure and is organized as [Parameters, nr_class,
107
+totalSV, rho, Label, ProbA, ProbB, nSV, sv_coef, SVs]:
108
+
109
+        -Parameters: parameters
110
+        -nr_class: number of classes; = 2 for regression/one-class svm
111
+        -totalSV: total #SV
112
+        -rho: -b of the decision function(s) wx+b
113
+        -Label: label of each class; empty for regression/one-class SVM
114
+        -ProbA: pairwise probability information; empty if -b 0 or in one-class SVM
115
+        -ProbB: pairwise probability information; empty if -b 0 or in one-class SVM
116
+        -nSV: number of SVs for each class; empty for regression/one-class SVM
117
+        -sv_coef: coefficients for SVs in decision functions
118
+        -SVs: support vectors
119
+
120
+If you do not use the option '-b 1', ProbA and ProbB are empty
121
+matrices. If the '-v' option is specified, cross validation is
122
+conducted and the returned model is just a scalar: cross-validation
123
+accuracy for classification and mean-squared error for regression.
124
+
125
+More details about this model can be found in LIBSVM FAQ
126
+(http://www.csie.ntu.edu.tw/~cjlin/libsvm/faq.html) and LIBSVM
127
+implementation document
128
+(http://www.csie.ntu.edu.tw/~cjlin/papers/libsvm.pdf).
129
+
130
+Result of Prediction
131
+====================
132
+
133
+The function 'svmpredict' has three outputs. The first one,
134
+predictd_label, is a vector of predicted labels. The second output,
135
+accuracy, is a vector including accuracy (for classification), mean
136
+squared error, and squared correlation coefficient (for regression).
137
+The third is a matrix containing decision values or probability
138
+estimates (if '-b 1' is specified). If k is the number of classes,
139
+for decision values, each row includes results of predicting
140
+k(k-1/2) binary-class SVMs. For probabilities, each row contains k values
141
+indicating the probability that the testing instance is in each class.
142
+Note that the order of classes here is the same as 'Label' field
143
+in the model structure.
144
+
145
+Examples
146
+========
147
+
148
+Train and test on the provided data heart_scale:
149
+
150
+matlab> load heart_scale.mat
151
+matlab> model = svmtrain(heart_scale_label, heart_scale_inst, '-c 1 -g 0.07');
152
+matlab> [predict_label, accuracy, dec_values] = svmpredict(heart_scale_label, heart_scale_inst, model); % test the training data
153
+
154
+For probability estimates, you need '-b 1' for training and testing:
155
+
156
+matlab> load heart_scale.mat
157
+matlab> model = svmtrain(heart_scale_label, heart_scale_inst, '-c 1 -g 0.07 -b 1');
158
+matlab> load heart_scale.mat
159
+matlab> [predict_label, accuracy, prob_estimates] = svmpredict(heart_scale_label, heart_scale_inst, model, '-b 1');
160
+
161
+To use precomputed kernel, you must include sample serial number as
162
+the first column of the training and testing data (assume your kernel
163
+matrix is K, # of instances is n):
164
+
165
+matlab> K1 = [(1:n)', K]; % include sample serial number as first column
166
+matlab> model = svmtrain(label_vector, K1, '-t 4');
167
+matlab> [predict_label, accuracy, dec_values] = svmpredict(label_vector, K1, model); % test the training data
168
+
169
+Take linear kernel for example, the following precomputed kernel example 
170
+gives exactly same training error as LIBSVM built-in linear kernel
171
+
172
+matlab> load heart_scale.mat
173
+matlab> n = size(heart_scale_inst,1);
174
+matlab> K = heart_scale_inst*heart_scale_inst';
175
+matlab> K1 = [(1:n)', K];
176
+matlab> model = svmtrain(heart_scale_label, K1, '-t 4');
177
+matlab> [predict_label, accuracy, dec_values] = svmpredict(heart_scale_label, K1, model);
178
+       
179
+Note that for testing, you can put anything in the testing_label_vector.  For
180
+details of precomputed kernels, please read the section ``Precomputed
181
+Kernels'' in the README of the LIBSVM package.
182
+
183
+Other Utilities
184
+===============
185
+
186
+A matlab function read_sparse reads files in LIBSVM format: 
187
+
188
+[label_vector, instance_matrix] = read_sparse('data.txt'); 
189
+
190
+Two outputs are labels and instances, which can then be used as inputs
191
+of svmtrain or svmpredict. This code is derived from svm-train.c in
192
+LIBSVM by Rong-En Fan from National Taiwan University.
193
+
194
+Additional Information
195
+======================
196
+
197
+This interface was initially written by Jun-Cheng Chen, Kuan-Jen Peng,
198
+Chih-Yuan Yang and Chih-Huai Cheng from Department of Computer
199
+Science, National Taiwan University. The current version was prepared
200
+by Rong-En Fan and Ting-Fan Wu. If you find this tool useful, please
201
+cite LIBSVM as follows
202
+
203
+Chih-Chung Chang and Chih-Jen Lin, LIBSVM : a library for
204
+support vector machines, 2001. Software available at
205
+http://www.csie.ntu.edu.tw/~cjlin/libsvm
206
+
207
+For any question, please contact Chih-Jen Lin <cjlin@csie.ntu.edu.tw>,
208
+or check the FAQ page:
209
+
210
+http://www.csie.ntu.edu.tw/~cjlin/libsvm/faq.html#/Q9:_MATLAB_interface
0 211
new file mode 100644
1 212
Binary files /dev/null and b/libsvm-mat-2.88-1/heart_scale.mat differ
2 213
new file mode 100644
... ...
@@ -0,0 +1,7 @@
1
+% This make.m is used under Windows
2
+
3
+mex -O -c svm.cpp
4
+mex -O -c svm_model_matlab.c
5
+mex -O svmtrain.c svm.obj svm_model_matlab.obj
6
+mex -O svmpredict.c svm.obj svm_model_matlab.obj
7
+mex -O read_sparse.c
0 8
new file mode 100644
... ...
@@ -0,0 +1,200 @@
1
+#include <stdio.h>
2
+#include <string.h>
3
+#include <stdlib.h>
4
+#include <ctype.h>
5
+#include <errno.h>
6
+
7
+#include "mex.h"
8
+
9
+#if MX_API_VER < 0x07030000
10
+typedef int mwIndex;
11
+#endif 
12
+#define max(x,y) (((x)>(y))?(x):(y))
13
+#define min(x,y) (((x)<(y))?(x):(y))
14
+
15
+void exit_with_help()
16
+{
17
+	mexPrintf(
18
+	"Usage: [label_vector, instance_matrix] = read_sparse(fname);\n"
19
+	);
20
+}
21
+
22
+static void fake_answer(mxArray *plhs[])
23
+{
24
+	plhs[0] = mxCreateDoubleMatrix(0, 0, mxREAL);
25
+	plhs[1] = mxCreateDoubleMatrix(0, 0, mxREAL);
26
+}
27
+
28
+static char *line;
29
+static int max_line_len;
30
+
31
+static char* readline(FILE *input)
32
+{
33
+	int len;
34
+	
35
+	if(fgets(line,max_line_len,input) == NULL)
36
+		return NULL;
37
+
38
+	while(strrchr(line,'\n') == NULL)
39
+	{
40
+		max_line_len *= 2;
41
+		line = (char *) realloc(line, max_line_len);
42
+		len = (int) strlen(line);
43
+		if(fgets(line+len,max_line_len-len,input) == NULL)
44
+			break;
45
+	}
46
+	return line;
47
+}
48
+
49
+// read in a problem (in svmlight format)
50
+void read_problem(const char *filename, mxArray *plhs[])
51
+{
52
+	int max_index, min_index, inst_max_index, i;
53
+	long elements, k;
54
+	FILE *fp = fopen(filename,"r");
55
+	int l = 0;
56
+	char *endptr;
57
+	mwIndex *ir, *jc;
58
+	double *labels, *samples;
59
+	
60
+	if(fp == NULL)
61
+	{
62
+		mexPrintf("can't open input file %s\n",filename);
63
+		fake_answer(plhs);
64
+		return;
65
+	}
66
+
67
+	max_line_len = 1024;
68
+	line = (char *) malloc(max_line_len*sizeof(char));
69
+
70
+	max_index = 0;
71
+	min_index = 1; // our index starts from 1
72
+	elements = 0;
73
+	while(readline(fp) != NULL)
74
+	{
75
+		char *idx, *val;
76
+		// features
77
+		int index = 0;
78
+
79
+		inst_max_index = -1; // strtol gives 0 if wrong format, and precomputed kernel has <index> start from 0
80
+		strtok(line," \t"); // label
81
+		while (1)
82
+		{
83
+			idx = strtok(NULL,":"); // index:value
84
+			val = strtok(NULL," \t");
85
+			if(val == NULL)
86
+				break;
87
+
88
+			errno = 0;
89
+			index = (int) strtol(idx,&endptr,10);
90
+			if(endptr == idx || errno != 0 || *endptr != '\0' || index <= inst_max_index)
91
+			{
92
+				mexPrintf("Wrong input format at line %d\n",l+1);
93
+				fake_answer(plhs);
94
+				return;
95
+			}
96
+			else
97
+				inst_max_index = index;
98
+
99
+			min_index = min(min_index, index);
100
+			elements++;
101
+		}
102
+		max_index = max(max_index, inst_max_index);
103
+		l++;
104
+	}
105
+	rewind(fp);
106
+
107
+	// y
108
+	plhs[0] = mxCreateDoubleMatrix(l, 1, mxREAL);
109
+	// x^T
110
+	if (min_index <= 0)
111
+		plhs[1] = mxCreateSparse(max_index-min_index+1, l, elements, mxREAL);
112
+	else
113
+		plhs[1] = mxCreateSparse(max_index, l, elements, mxREAL);
114
+
115
+	labels = mxGetPr(plhs[0]);
116
+	samples = mxGetPr(plhs[1]);
117
+	ir = mxGetIr(plhs[1]);
118
+	jc = mxGetJc(plhs[1]);
119
+
120
+	k=0;
121
+	for(i=0;i<l;i++)
122
+	{
123
+		char *idx, *val, *label;
124
+		jc[i] = k;
125
+
126
+		readline(fp);
127
+
128
+		label = strtok(line," \t");
129
+		labels[i] = (int)strtol(label,&endptr,10);
130
+		if(endptr == label)
131
+		{
132
+			mexPrintf("Wrong input format at line %d\n",i+1);
133
+			fake_answer(plhs);
134
+			return;
135
+		}
136
+
137
+		// features
138
+		while(1)
139
+		{
140
+			idx = strtok(NULL,":");
141
+			val = strtok(NULL," \t");
142
+			if(val == NULL)
143
+				break;
144
+
145
+			ir[k] = (mwIndex) (strtol(idx,&endptr,10) - min_index); // precomputed kernel has <index> start from 0
146
+
147
+			errno = 0;
148
+			samples[k] = strtod(val,&endptr);
149
+			if (endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr)))
150
+			{
151
+				mexPrintf("Wrong input format at line %d\n",i+1);
152
+				fake_answer(plhs);
153
+				return;
154
+			}
155
+			++k;
156
+		}
157
+	}
158
+	jc[l] = k;
159
+
160
+	fclose(fp);
161
+	free(line);
162
+
163
+	{
164
+		mxArray *rhs[1], *lhs[1];
165
+		rhs[0] = plhs[1];
166
+		if(mexCallMATLAB(1, lhs, 1, rhs, "transpose"))
167
+		{
168
+			mexPrintf("Error: cannot transpose problem\n");
169
+			fake_answer(plhs);
170
+			return;
171
+		}
172
+		plhs[1] = lhs[0];
173
+	}
174
+}
175
+
176
+void mexFunction( int nlhs, mxArray *plhs[],
177
+		int nrhs, const mxArray *prhs[] )
178
+{
179
+	if(nrhs == 1)
180
+	{
181
+		char filename[256];
182
+
183
+		mxGetString(prhs[0], filename, mxGetN(prhs[0]) + 1);
184
+
185
+		if(filename == NULL)
186
+		{
187
+			mexPrintf("Error: filename is NULL\n");
188
+			return;
189
+		}
190
+
191
+		read_problem(filename, plhs);
192
+	}
193
+	else
194
+	{
195
+		exit_with_help();
196
+		fake_answer(plhs);
197
+		return;
198
+	}
199
+}
200
+
0 201
new file mode 100644
1 202
Binary files /dev/null and b/libsvm-mat-2.88-1/read_sparse.mexw32 differ
2 203
new file mode 100644
... ...
@@ -0,0 +1,3030 @@
1
+#include <math.h>
2
+#include <stdio.h>
3
+#include <stdlib.h>
4
+#include <ctype.h>
5
+#include <float.h>
6
+#include <string.h>
7
+#include <stdarg.h>
8
+#include "svm.h"
9
+typedef float Qfloat;
10
+typedef signed char schar;
11
+#ifndef min
12
+template <class T> inline T min(T x,T y) { return (x<y)?x:y; }
13
+#endif
14
+#ifndef max
15
+template <class T> inline T max(T x,T y) { return (x>y)?x:y; }
16
+#endif
17
+template <class T> inline void swap(T& x, T& y) { T t=x; x=y; y=t; }
18
+template <class S, class T> inline void clone(T*& dst, S* src, int n)
19
+{
20
+	dst = new T[n];
21
+	memcpy((void *)dst,(void *)src,sizeof(T)*n);
22
+}
23
+inline double powi(double base, int times)
24
+{
25
+        double tmp = base, ret = 1.0;
26
+
27
+        for(int t=times; t>0; t/=2)
28
+	{
29
+                if(t%2==1) ret*=tmp;
30
+                tmp = tmp * tmp;
31
+        }
32
+        return ret;
33
+}