-
Notifications
You must be signed in to change notification settings - Fork 1
/
kNNDataSorting.m
599 lines (556 loc) · 32.6 KB
/
kNNDataSorting.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
function sortedDates = kNNDataSorting(targetVar,climateVars,addVars,queryDates,learningDates,climateData,additionalVars,normMethods,shortWindow,longWindow,daysRange,Weights,nbImages,metricKNN,optimPrep,saveOptimPrep,parallelComputing,inputDir,saveMats)
%
%
%
% REDO DOCUMENTATION
%
%
%
%tic
% checks that at least one learning and query dates are present
if any(size(learningDates)==0)
error('At least one dimension of LearningDates is 0! Code exited...')
elseif any(size(queryDates)==0)
error('At least one dimension of QueryDates is 0! Code exited...')
end
% the learning dates are ranked based on a criterion that quantifies their distance to a given query date
% adaptation to have only one big climateDataAll file, one learningDates
% file containing date and target and same for queryDates
climateDates = table2array(climateData(:,'date'));
climateMaps = table2array(removevars(climateData,'date'));
climateVarsNames = string(removevars(climateData,'date').Properties.VariableNames);
queryDatesDate = table2array(queryDates(:,1));
queryDatesData = table2array(queryDates(:,2:end));
learningDatesDate = table2array(learningDates(:,1));
learningDatesData = table2array(learningDates(:,2:end));
if optimPrep == false
% Define learningDates as itself minus the query dates
ismem = ismember(learningDatesDate, queryDatesDate);
learningDatesDate = learningDatesDate(~ismem);
learningDatesData = learningDatesData(~ismem);
end
totQDates = size(queryDatesDate,1);
totLDates = size(learningDatesDate,1);
sortedDates = cell(totQDates, 1);
sortedData = cell(totQDates, 1);
sortedTarget = cell(totQDates, 1);
sortedAddVars = cell(totQDates, 1);
sortedDist = cell(totQDates, 1);
if ~isempty(additionalVars)
addVarsDates = table2array(additionalVars(:,'date'));
addVarsData = table2array(removevars(additionalVars,'date'));
else
addVarsDates = [];
addVarsData = [];
end
% Assign different weights
idxTarget = contains(Weights.Properties.VariableNames,targetVar);
weightsTarget = table2array(Weights(:,idxTarget));
idxShort = contains(Weights.Properties.VariableNames,'Short');
weightsShort = table2array(Weights(:,idxShort));
idxLong = contains(Weights.Properties.VariableNames,'Long');
weightsLong = table2array(Weights(:,idxLong));
if ~isempty(additionalVars)
idxAddVars = contains(Weights.Properties.VariableNames,addVars);
weightsAddVars = table2array(Weights(:,idxAddVars));
else
weightsAddVars = [];
end
disp('Starting loop to sort learning dates for each query date...')
% Display progression - for parallel computing
%progress = 0;
%fprintf(1,'Progress: %3.0f%%\n',progress);
%fprintf(['\n' repmat('.',1,totQDates) '\n\n']);
if parallelComputing == true
parfor qd = 1:totQDates % parallel computing
currentQDate = queryDatesDate(qd);
dayOfYearQ = day(datetime(currentQDate,'ConvertFrom','yyyyMMdd'),'dayofyear');
minRangeQ = dayOfYearQ - daysRange;
if minRangeQ <= 0, minRangeQ = 365 + minRangeQ; end
maxRangeQ = dayOfYearQ + daysRange;
if maxRangeQ > 365, maxRangeQ = maxRangeQ - 365; end
if minRangeQ < maxRangeQ
rangeQ = minRangeQ:1:maxRangeQ;
else
rangeQmin = minRangeQ:1:365;
rangeQmax = 1:1:maxRangeQ;
rangeQ = [rangeQmin rangeQmax];
end
disp([' Processing day ' num2str(qd) '/' num2str(totQDates) ' (' num2str(currentQDate) ')'])
% Extract the longWindow climate for the current query date
queryClimate = cell(longWindow, numel(climateVars));
idx = find(climateDates == currentQDate);
if idx > longWindow
kj = 1;
for k = (longWindow-1):-1:0
queryClimate(kj,:) = climateMaps(idx-k,:);
kj = kj+1;
end
% Extract the additional data for the current query date
if ~isempty(additionalVars)
queryAddVars = cell(1, numel(addVars));
idx = find(addVarsDates == currentQDate);
queryAddVars(1,:) = addVarsData(idx,:);
else
queryAddVars = [];
end
% Compute the distances between the query climate and the climate for each learning date
%targetDistance = cell(totLDates,1);
addVarsDistance = cell(totLDates,1);
climateDistance = cell(totLDates,2);
% Display progress - only for serial computing
%fprintf(1,' Progress for current query date: %3.0f%%\n',progress);
for ld = 1:totLDates
learningClimate = cell(longWindow, numel(climateVars));
currentLDate = learningDatesDate(ld);
dayOfYearL = day(datetime(currentLDate,'ConvertFrom','yyyyMMdd'),'dayofyear');
if dayOfYearL == 366
dayOfYearL = 1;
end
idx = find(climateDates == currentLDate);
%disp([' Computing distance to day ' num2str(l) '/' num2str(totLDates) ' (' num2str(currentLDate) ')'])
if ismember(dayOfYearL,rangeQ) % if learning date is not within 3 months of the query date, it is skipped
if idx >= longWindow % skips learning dates that are in the longWindow
% Learning dates climate
kj = 1;
for k = (longWindow-1):-1:0
learningClimate(kj,:) = climateMaps(idx-k,:);
kj = kj+1;
end
% Extract the additional data for the current query date
if ~isempty(additionalVars)
learningAddVars = cell(1, numel(addVars));
idx = find(addVarsDates == currentLDate);
learningAddVars(1,:) = addVarsData(idx,:);
else
learningAddVars = [];
end
% % Target variable comparison
% if ~(isempty(cell2mat(queryDatesData(qd,:))) || unique(isnan(cell2mat(queryDatesData(qd,:))))) %&& sum(sum(cell2mat(queryDatesData(qd,:))))~=0
% if metricKNN == 1 % RMSE
% targetDistance{ld} = cellfun(@(x, y) sqrt(mean((x - y).^2, 'all', 'omitnan')), ...
% queryDatesData(qd,:), learningDatesData(ld,:)); % RMSE
% elseif metricKNN == 2 % MAE
% targetDistance{ld} = cellfun(@(x, y) mean(abs(x - y), 'all', 'omitnan'), ...
% queryDatesData(qd,:), learningDatesData(ld,:)); % MAE
% elseif metricKNN == 3 % Manhattan
% targetDistance{ld} = cellfun(@(x, y) sum(abs(x - y), 'all', 'omitnan'), ...
% queryDatesData(qd,:), learningDatesData(ld,:)); % Manhattan
% elseif metricKNN == 4 % Euclidean
% targetDistance{ld} = cellfun(@(x, y) sqrt(sum((x - y).^2, 'all', 'omitnan')), ...
% queryDatesData(qd,:), learningDatesData(ld,:)); % Euclidean
% elseif metricKNN == 5 % SPEM
% targetDistance{ld} = cellfun(@(x, y) spem(x, y), ...
% queryDatesData(qd,:), learningDatesData(ld,:));
% else
% error('Bad metricKNN parameter')
% end
% targetDistance{ld} = sum(cell2mat(targetDistance{ld}),1,'omitnan');
% if optimPrep == false
% targetDistance{ld} = targetDistance{ld}.*weightsTarget;
% targetDistance{ld} = sum(cell2mat(targetDistance(ld)),2,'omitnan');
% end
% else
% targetDistance{ld} = 0;
% end
% Additional variable comparison
% 1 distance
if ~isempty(addVars) && ~isempty(addVarsData)
if ~isempty(addVarsData(qd,:))
if metricKNN == 1 % RMSE
addVarsDistance{ld,1} = cellfun(@(x, y) sqrt(mean((x - y).^2, 'all', 'omitnan')), ...
queryAddVars, learningAddVars); % RMSE
elseif metricKNN == 2 % MAE
addVarsDistance{ld,1} = cellfun(@(x, y) mean(abs(x - y), 'all', 'omitnan'), ...
queryAddVars, learningAddVars); % MAE
elseif metricKNN == 3 % 1-bSPEM
addVarsDistance{ld,1} = cellfun(@(x, y) (1 - spem(x, y)), ...
queryAddVars, learningAddVars);
elseif metricKNN == 4 % Hellinger
addVarsDistance{ld,1} = cellfun(@(x, y) hellingerDist(x, y), ...
queryAddVars, learningAddVars);
elseif metricKNN == 5 % 0.5*(1-bSPEM) + 0.5*Hellinger
addVarsDistance{ld,1} = cellfun(@(x, y) ...
computeHellingerSPEM(x, y, @spem, @hellingerDist), ...
queryAddVars, learningAddVars);
elseif metricKNN == 6 % SPAEF
addVarsDistance{ld,1} = cellfun(@(x, y) (1 - spaef(x, y)), ...
queryAddVars, learningAddVars);
else
error('Bad metricKNN parameter')
end
addVarsDistance{ld,1} = sum(addVarsDistance{ld,1},1,'omitnan');
if optimPrep == false
addVarsDistance{ld,1} = addVarsDistance{ld,1} .* weightsAddVars;
end
end
else
addVarsDistance{ld,1} = 0;
end
% Climate distance
% 1 date, 2 distance
climateDistAll = cell(ld,1);
hammingDist = cell(ld,1);
hellingDist = cell(ld,1);
climateDistHH = cell(ld,1);
climVarIdx = zeros(1,numel(climateVarsNames));
otherIdx = ~climVarIdx;
if sum(ismember(normMethods,4))>=1
normMeIdx = find(normMethods==4);
climVarIdx = strcmpi(climateVars(normMeIdx),climateVarsNames);
otherIdx = ~climVarIdx;
binaryLClim = cellfun(@(x) (x>0)+isnan(x).*x, learningClimate(:,climVarIdx), 'UniformOutput', false);
binaryQClim = cellfun(@(x) (x>0)+isnan(x).*x, queryClimate(:,climVarIdx), 'UniformOutput', false);
hammingDist{ld,1} = cellfun(@(x,y) single(mean(x(:) ~= y(:))),binaryLClim,binaryQClim,'UniformOutput',false); % Hamming distance
hellingDist{ld,1} = cellfun(@(x,y) single(hellingerDist(x(x>0), y(y>0))), ...
learningClimate(:,climVarIdx),queryClimate(:,climVarIdx),'UniformOutput',false); % Hellinger distance
climateDistHH{ld,1} = cellfun(@(x,y) (x/2)+(y/2),hammingDist{ld,1},hellingDist{ld,1},'UniformOutput',false); % Total Hamming + Hellinger distance
climateDistAll{ld,1}(:,climVarIdx) = climateDistHH{ld,1}(:);
end
learningSubset = learningClimate(:, otherIdx);
querySubset = queryClimate(:, otherIdx);
if metricKNN == 1 % RMSE
climateDistAll{ld,1}(:,otherIdx) = cellfun(@(x, y) sqrt(mean((x - y).^2, 'all', 'omitnan')), ...
learningSubset, querySubset); % RMSE
elseif metricKNN == 2 % MAE
climateDistAll{ld,1}(:,otherIdx) = cellfun(@(x, y) mean(abs(x - y), 'all', 'omitnan'), ...
learningSubset, querySubset); % MAE
elseif metricKNN == 3 % 1-bSPEM
climateDistAll{ld,1}(:,otherIdx) = cellfun(@(x,y) (1 - spem(x, y)), ...
learningSubset, querySubset);
elseif metricKNN == 4 % Hellinger
climateDistAll{ld,1}(:,otherIdx) = cellfun(@(x,y) hellingDist(x, y), ...
learningSubset, querySubset);
elseif metricKNN == 5 % 0.5*(1-bSPEM) + 0.5*Hellinger
climateDistAll{ld,1}(:, otherIdx) = cellfun(@(x, y) ...
computeHellingerSPEM(x, y, @spem, @hellingerDist), ...
learningSubset, querySubset);
elseif metricKNN == 6 % SPAEF
climateDistAll{ld,1}(:,otherIdx) = cellfun(@(x,y) (1 - spaef(x, y)), ...
learningSubset, querySubset);
else
error('Bad metricKNN parameter')
end
climateDistance{ld,1} = currentLDate;
if shortWindow > 0
climateDistance{ld,2}(1,:) = sum(climateDistAll{ld,1}(1:shortWindow,:),1,'omitnan');
else
climateDistance{ld,2}(1,:) = zeros(1,size(climateDistAll{ld,1},2));
end
climateDistance{ld,2}(2,:) = sum(climateDistAll{ld,1}(shortWindow+1:end,:),1,'omitnan');
% Assign weights to corresponding index
if optimPrep == false
climateDistance{ld,2}(1,:) = climateDistance{ld,2}(1,:) .* weightsShort;
climateDistance{ld,2}(2,:) = climateDistance{ld,2}(2,:) .* weightsLong;
climateDistance{ld,2} = sum(climateDistance{ld,2},1,'omitnan');
climateDistance{ld,2} = sum(climateDistance{ld,2},2,'omitnan')+addVarsDistance{ld,1}; %targetDistance{ld,1}+
end
else
% If not enough climate days available, skip until loop reaches longWindow
%warning(['Climate data available is shorter than longWindow, ' num2str(currentLDate) ' skipped.'])
continue
end
else
% If learning date not in query date range, skip it
%disp([' Learning day ',num2str(currentLDate),' not in query date range, skipped'])
continue
end
end
else
fprintf('\n')
disp(' Not enough learning dates. Query date skipped...')
fprintf('\b')
continue
end
% Learning dates distance: 1 date, 2 distance
distance = climateDistance(~cellfun('isempty',climateDistance(:,1)),:);
%targetDistance = targetDistance(~cellfun('isempty',targetDistance),:);
addVarsDistance = addVarsDistance(~cellfun('isempty',addVarsDistance),:);
if optimPrep == false
distancesSort = sortrows(distance,2); % Sort rows in ascending order according to column 2
distancesBest = distancesSort(1:nbImages,1);
distSorted = distancesSort(1:nbImages,2);
sortedDates{qd} = currentQDate;
sortedData{qd} = cell2mat(distancesBest);
sortedDist{qd} = cell2mat(distSorted);
else
distancesBest = distance(:,1);
distSorted = distance(:,2);
sortedDates{qd} = currentQDate;
sortedData{qd} = distancesBest;
%sortedTarget{qd} = targetDistance;
sortedAddVars{qd} = addVarsDistance;
sortedDist{qd} = distSorted;
end
end
if optimPrep == false
sortedDatesAll = [sortedDates sortedData sortedDist];
sortedDates = sortedDatesAll;
else
sortedDatesAll = [sortedDates sortedData sortedTarget sortedAddVars sortedDist];
sortedDates = sortedDatesAll;
end
% Shut down parallel pool
poolobj = gcp('nocreate');
delete(poolobj);
else % serial computing
for qd = 1:totQDates
currentQDate = queryDatesDate(qd);
dayOfYearQ = day(datetime(currentQDate,'ConvertFrom','yyyyMMdd'),'dayofyear');
minRangeQ = dayOfYearQ - daysRange;
if minRangeQ <= 0, minRangeQ = 365 + minRangeQ; end
maxRangeQ = dayOfYearQ + daysRange;
if maxRangeQ > 365, maxRangeQ = maxRangeQ - 365; end
if minRangeQ < maxRangeQ
rangeQ = minRangeQ:1:maxRangeQ;
else
rangeQmin = minRangeQ:1:365;
rangeQmax = 1:1:maxRangeQ;
rangeQ = [rangeQmin rangeQmax];
end
fprintf(['\n Processing day ' num2str(qd) '/' num2str(totQDates) ' (' num2str(currentQDate) ')'])
% Extract the longWindow climate for the current query date
queryClimate = cell(longWindow, numel(climateVars));
idx = find(climateDates == currentQDate);
if idx > longWindow
kj = 1;
for k = (longWindow-1):-1:0
queryClimate(kj,:) = climateMaps(idx-k,:);
%queryClimate(kj,j) = climateMaps.(varClimate)(:,:,idx-k);
kj = kj+1;
end
% Extract the additional data for the current query date
if ~isempty(additionalVars)
queryAddVars = cell(1, numel(addVars));
idx = find(addVarsDates == currentQDate);
queryAddVars(1,:) = addVarsData(idx,:);
else
queryAddVars = [];
end
% Compute the distances between the query climate and the climate for each learning date
%targetDistance = cell(totLDates,1);
addVarsDistance = cell(totLDates,1);
climateDistance = cell(totLDates,2);
climateDistAll = inf(longWindow,numel(climateVars));
% Display progress - only for serial computing
progress = 0;
fprintf(1,'\n Progress for current query date: %3.0f%%\n',progress);
for ld = 1:totLDates
learningClimate = cell(longWindow, numel(climateVars));
currentLDate = learningDatesDate(ld);
dayOfYearL = day(datetime(currentLDate,'ConvertFrom','yyyyMMdd'),'dayofyear');
if dayOfYearL == 366
dayOfYearL = 1;
end
idx = find(climateDates == currentLDate);
%disp([' Computing distance to day ' num2str(l) '/' num2str(totLDates) ' (' num2str(currentLDate) ')'])
if ismember(dayOfYearL,rangeQ) % if learning date is not within 3 months of the query date, it is skipped
%disp([' Processing learning day ', num2str(currentLDate)])
if idx >= longWindow % skips learning dates that are in the longWindow
% Learning dates climate
kj = 1;
for k = (longWindow-1):-1:0
learningClimate(kj,:) = climateMaps(idx-k,:);
kj = kj+1;
end
% Extract the additional data for the current query date
if ~isempty(additionalVars)
learningAddVars = cell(1, numel(addVars));
idx = find(addVarsDates == currentLDate);
learningAddVars(1,:) = addVarsData(idx,:);
else
learningAddVars = [];
end
% Target variable comparison
% if ~(isempty(cell2mat(queryDatesData(qd,:))) || unique(isnan(cell2mat(queryDatesData(qd,:))))) %&& sum(sum(cell2mat(queryDatesData(qd,:))))~=0
% if metricKNN == 1 % RMSE
% targetDistance{ld} = cellfun(@(x, y) sqrt(mean((x - y).^2, 'all', 'omitnan')), ...
% queryDatesData(qd,:), learningDatesData(ld,:)); % RMSE
% elseif metricKNN == 2 % MAE
% targetDistance{ld} = cellfun(@(x, y) mean(abs(x - y), 'all', 'omitnan'), ...
% queryDatesData(qd,:), learningDatesData(ld,:)); % MAE
% elseif metricKNN == 3 % Manhattan
% targetDistance{ld} = cellfun(@(x, y) sum(abs(x - y), 'all', 'omitnan'), ...
% queryDatesData(qd,:), learningDatesData(ld,:)); % Manhattan
% elseif metricKNN == 4 % Euclidean
% targetDistance{ld} = cellfun(@(x, y) sqrt(sum((x - y).^2, 'all', 'omitnan')), ...
% queryDatesData(qd,:), learningDatesData(ld,:)); % Euclidean
% elseif metricKNN == 5 % SPEM
% targetDistance{ld} = cellfun(@(x, y) spem(x, y), ...
% queryDatesData(qd,:), learningDatesData(ld,:));
% else
% error('Bad metricKNN parameter')
% end
% targetDistance{ld} = sum(cell2mat(targetDistance{ld}),1,'omitnan');
% if optimPrep == false
% targetDistance{ld} = targetDistance{ld}.*weightsTarget;
% targetDistance{ld} = sum(cell2mat(targetDistance(ld)),2,'omitnan');
% end
% else
% targetDistance{ld} = 0;
% end
% Additional variable comparison
% 1 distance
if ~isempty(additionalVars) && ~isempty(addVarsData(qd,:))
if metricKNN == 1 % RMSE
addVarsDistance{ld} = cellfun(@(x, y) sqrt(mean((x - y).^2, 'all', 'omitnan')), ...
queryAddVars, learningAddVars); % RMSE
elseif metricKNN == 2 % MAE
addVarsDistance{ld} = cellfun(@(x, y) mean(abs(x - y), 'all', 'omitnan'), ...
queryAddVars, learningAddVars); % MAE
elseif metricKNN == 3 % 1-bSPEM
addVarsDistance{ld} = cellfun(@(x, y) (1 - spem(x, y)), ...
queryAddVars, learningAddVars);
elseif metricKNN == 4 % Hellinger
addVarsDistance{ld} = cellfun(@(x, y) hellingerDist(x, y), ...
queryAddVars, learningAddVars);
elseif metricKNN == 5 % 0.5*(1-bSPEM) + 0.5*Hellinger
addVarsDistance{ld} = cellfun(@(x, y) ...
computeHellingerSPEM(x, y, @spem, @hellingerDist), ...
queryAddVars, learningAddVars);
elseif metricKNN == 6 % SPAEF
addVarsDistance{ld} = cellfun(@(x, y) (1 - spaef(x, y)), ...
queryAddVars, learningAddVars);
else
error('Bad metricKNN parameter')
end
addVarsDistance{ld} = sum(addVarsDistance{ld},1,'omitnan');
if optimPrep == false
addVarsDistance{ld} = addVarsDistance{ld} .* weightsAddVars;
end
else
addVarsDistance{ld} = 0;
end
% Climate distance
% 1 date, 2 distance
% rmse = cellfun(@(x, y) sqrt(mean((x - y).^2, 'all', 'omitnan')), ...
% learningClimate, queryClimate); % root mean square error
% mae = cellfun(@(x, y) mean(abs(x - y), 'all', 'omitnan'), ...
% learningClimate, queryClimate); % mean absolute error
% manhattan = cellfun(@(x, y) sum(abs(x - y), 'all', 'omitnan'), ...
% learningClimate, queryClimate); % Manhattan
% euclidean = cellfun(@(x, y) sqrt(sum((x - y).^2, 'all', 'omitnan')), ...
% learningClimate, queryClimate); % Euclidean
climVarIdx = zeros(1,numel(climateVarsNames));
otherIdx = ~climVarIdx;
if sum(ismember(normMethods,4))>=1
normMeIdx = find(normMethods==4);
climVarIdx = strcmpi(climateVars(normMeIdx),climateVarsNames);
otherIdx = ~climVarIdx;
binaryLClim = cellfun(@(x) (x>0)+isnan(x).*x, learningClimate(:,climVarIdx), 'UniformOutput', false);
binaryQClim = cellfun(@(x) (x>0)+isnan(x).*x, queryClimate(:,climVarIdx), 'UniformOutput', false);
hammingDist = cellfun(@(x,y) single(mean(x(:) ~= y(:))),binaryLClim,binaryQClim,'UniformOutput',false); % Hamming distance
%hellingDist = cellfun(@(x, y) 1/sqrt(2)*sqrt(sum((sqrt(x(x > 0)) - sqrt(y(y > 0))).^2)), ...
% learningClimate(:,climVarIdx),queryClimate(:,climVarIdx),'UniformOutput',false); % Hellinger distance
hellingDist = cellfun(@(x,y) single(hellingerDist(x(x>0), y(y>0))), ...
learningClimate(:,climVarIdx),queryClimate(:,climVarIdx),'UniformOutput',false); % Hellinger distance
climateDistHH = cellfun(@(x,y) (x/2)+(y/2),hammingDist,hellingDist,'UniformOutput',false); % Total Hamming + Hellinger distance
climateDistAll(:,climVarIdx) = climateDistHH(:);
end
learningSubset = learningClimate(:, otherIdx);
querySubset = queryClimate(:, otherIdx);
if metricKNN == 1 % RMSE
climateDistAll(:,otherIdx) = cellfun(@(x, y) sqrt(mean((x - y).^2, 'all', 'omitnan')), ...
learningSubset, querySubset); % RMSE
elseif metricKNN == 2 % MAE
climateDistAll(:,otherIdx) = cellfun(@(x, y) mean(abs(x - y), 'all', 'omitnan'), ...
learningSubset, querySubset); % MAE
elseif metricKNN == 3 % 1-bSPEM
climateDistAll(:,otherIdx) = cellfun(@(x, y) (1 - spem(x, y)), ...
learningSubset, querySubset);
elseif metricKNN == 4 % Hellinger
climateDistAll(:,otherIdx) = cellfun(@(x, y) hellingerDist(x, y), ...
learningSubset, querySubset);
elseif metricKNN == 5 % 0.5*(1-bSPEM) + 0.5*Hellinger
climateDistAll(:, otherIdx) = cellfun(@(x, y) ...
computeHellingerSPEM(x, y, @spem, @hellingerDist), ...
learningSubset, querySubset);
elseif metricKNN == 6 % SPAEF
climateDistAll(:,otherIdx) = cellfun(@(x, y) (1 - spaef(x, y)), ...
learningSubset, querySubset);
else
error('Bad metricKNN parameter')
end
climateDistance{ld,1} = currentLDate;
if shortWindow > 0
climateDistance{ld,2}(1,:) = sum(climateDistAll(1:shortWindow,:),1,'omitnan');
else
climateDistance{ld,2}(1,:) = zeros(1,size(climateDistAll,2));
end
climateDistance{ld,2}(2,:) = sum(climateDistAll(shortWindow+1:end,:),1,'omitnan');
% Assign weights to corresponding index
if optimPrep == false
climateDistance{ld,2}(1,:) = climateDistance{ld,2}(1,:) .* weightsShort;
climateDistance{ld,2}(2,:) = climateDistance{ld,2}(2,:) .* weightsLong;
climateDistance{ld,2} = sum(climateDistance{ld,2},1,'omitnan');
climateDistance{ld,2} = sum(climateDistance{ld,2},2,'omitnan')+addVarsDistance{ld}; %+targetDistance{ld}
end
else
% If not enough climate days available, skip until loop reaches longWindow
%warning(['Climate data available is shorter than longWindow, ' num2str(currentLDate) ' skipped.'])
continue
end
else
% If learning date not in query date range, skip it
% Display computation progress - only for serial computing
progress = (100*(ld/totLDates));
fprintf(1,'\b\b\b\b%3.0f%%',progress);
%disp([' Learning day ',num2str(currentLDate),' not in query date range, skipped'])
continue
end
% Display computation progress - only for serial computing
progress = (100*(ld/totLDates));
fprintf(1,'\b\b\b\b%3.0f%%',progress);
end
else
fprintf('\n')
disp(' Not enough learning dates. Query date skipped...')
fprintf('\b')
continue
end
% Learning dates distance: 1 date, 2 distance
distance = climateDistance(~cellfun('isempty',climateDistance(:,1)),:);
%targetDistance = targetDistance(~cellfun('isempty',targetDistance),:);
addVarsDistance = addVarsDistance(~cellfun('isempty',addVarsDistance),:);
if optimPrep == false
distancesSort = sortrows(distance,2); % Sort rows in ascending order according to column 2
distancesBest = distancesSort(1:nbImages,1);
distSorted = distancesSort(1:nbImages,2);
sortedDates{qd} = currentQDate;
sortedData{qd} = cell2mat(distancesBest);
sortedDist{qd} = cell2mat(distSorted);
else
distancesBest = distance(:,1);
distSorted = distance(:,2);
sortedDates{qd} = currentQDate;
sortedData{qd} = distancesBest;
%sortedTarget{qd} = targetDistance;
sortedAddVars{qd} = addVarsDistance;
sortedDist{qd} = distSorted;
end
% Display progression - for parallel computing
%progress = (100*(l/totLDates));
%fprintf(1,'\b\b\b\b%3.0f%%',progress);
%toc
end
if optimPrep == false
sortedDatesAll = [sortedDates sortedData sortedDist];
sortedDates = sortedDatesAll;
else
sortedDatesAll = [sortedDates sortedData sortedTarget sortedAddVars sortedDist];
sortedDates = sortedDatesAll;
end
fprintf('\n')
end
sortedDates = sortedDates(~cellfun('isempty',sortedDates(:,1)),:);
if optimPrep == false && saveMats == true
disp('Saving KNNSorting.mat file...')
save(fullfile(inputDir,'KNNSorting.mat'),'sortedDates', '-v7.3','-nocompression'); % Save Ranked Learning Dates per Query Date
else
if saveOptimPrep == true
disp('Saving KNNDistances.mat file for optimisation. May take a while...')
save(fullfile(inputDir,'KNNDistances.mat'),'sortedDates', '-v7.3','-nocompression');
end
end
%toc
end