-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclusterFunctions.R
More file actions
2259 lines (1917 loc) · 80.3 KB
/
clusterFunctions.R
File metadata and controls
2259 lines (1917 loc) · 80.3 KB
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Function for cleaning up raw bout data to machine-readible format for analysis
#cleanData <- function(jointFiles=jointFiles,labelDirectory=labelDirectory,dataDirectory=dataDirectory,outputLabelDir=outputLabelDir,instanceLabelDirectory=instanceLabelDirectory){
cleanData <- function(jointFiles,labelDirectory,dataDirectory,outputLabelDir,instanceLabelDirectory,outputDataDirectory,onlyLoad=FALSE,FFT=FALSE,duration=30){
participantID<-gsub(jointFiles[3],pattern = ".csv",replacement = '')
cat(paste0('starting data processing/loading for ', participantID,'\n'))
if((file.exists(file.path(instanceLabelDirectory,paste0(participantID,'Clean.csv')))==FALSE) | (onlyLoad==FALSE)){
labelData<-read.csv(file.path(labelDirectory,jointFiles[1]))
keeps <- c('participant','label','startTime','endTime')
labelData<-labelData[ , (names(labelData) %in% keeps)]
labelData$NewStart<-(as.POSIXct(labelData$startTime,'%Y-%m-%d %H:%M:%S',tz = 'GMT'))
labelData$tempEnd<-as.POSIXct(labelData$endTime,'%Y-%m-%d %H:%M:%S',tz = 'GMT')
labelData$duration<-labelData$tempEnd-labelData$NewStart
if(sum(labelData$duration==0)>0){
labelData<-labelData[-(labelData$duration==0),]
}
labelData$NewEnd<-labelData$tempEnd
checklabelData(checkData = labelData)
nrows<-nrow(labelData)
#Now relabel start and end points to lie in the midpoint of unlabelled gaps
labelData$NewEnd[1:nrows-1]<-labelData$NewEnd[1:nrows-1]+floor(labelData$NewStart[2:nrows]-labelData$NewEnd[1:nrows-1])/2
labelData$NewEnd[nrows]<-labelData$tempEnd[nrows]
labelData$NewStart[2:nrows]<-labelData$NewEnd[1:nrows-1]
labelData<-labelData[,c('participant','label','NewStart','NewEnd')]
setnames(labelData,c('identifier','behavior','StartDateTime','EndDateTime'))
labelData$identifier<-participantID
#Load up Feature Data
featureData<-read.csv(file = file.path(dataDirectory,jointFiles[2]))
featureData$identifier<-participantID
#delete first data point
featureData<-featureData[-1,]
#clean up correlation values
featureData<-cleanUpCorr(featureData=featureData)
if(FFT){
#Load up FFT Data
FFTData<-fread(file.path(dataDirectory,jointFiles[3]))
FFTData$identifier<-participantID
FFTData$Time<-substr(FFTData$Time,1,19)
}
#remove fractional seconds
featureData$timestamp<-substr(featureData$timestamp,1,19)
start_times<-labelData$StartDateTime[1]+0:(duration-1)
end_times<-labelData$EndDateTime[nrows]-0:(duration-1)
start_row<-pmatch(start_times,featureData$timestamp,duplicates.ok = TRUE)
iStart<-which(!is.na(start_row))
start_row<-start_row[iStart]
labelData$StartDateTime[1]<-start_times[iStart]
end_row<-pmatch(end_times,substr(featureData$timestamp,1,19),duplicates.ok = TRUE)
iEnd<-which(!is.na(end_row))
end_row<-end_row[iEnd]
labelData$EndDateTime[nrows]<-end_times[iEnd]
labelledData<-list()
#only store data points inside labelled epoch
if(FFT){
labelledData$labelledFFTData<-FFTData[start_row:(end_row-1),]
}
#now round labels to align with spacing of features
labelData$StartDateTime<-roundXsecs(labelData$StartDateTime,startTime = labelData$StartDateTime[1],duration = duration)
labelData$EndDateTime<-roundXsecs(labelData$EndDateTime,startTime = labelData$StartDateTime[1],duration = duration)
#now we need to turn from bout level labels to annotations. Here we use a slightly modified TLBC function, annotationsToLabels
extractLabelsSingleFile(labelData, identifier= participantID,winSize = duration,instanceLabelDirectory = instanceLabelDirectory)
labelledData$instanceLabelData<-fread(file.path(instanceLabelDirectory, paste0(participantID,'ALL.csv')))
labelledData$instanceLabelData$identifier<-participantID
#sometimes have to delete last feature data point as extractLabelsSingleFile sometimes does not output final data point for labels
if(nrow(labelledData$instanceLabelData)==(end_row-start_row)){
labelledData$labelledFeatureData<-featureData[start_row:(end_row-1),]
} else if (nrow(labelledData$instanceLabelData)==(end_row-start_row+1)){
labelledData$labelledFeatureData<-featureData[start_row:end_row,]
} else {
cat('error - off by one error between labels and features!')
}
cat(paste0('Writing ALL feature data file ', participantID,'.csv','\n'))
#write.csv(x=labelledData$labelledFeatureData,file=paste0(outputDataDirectory,'/', participantID,'ALLFeature.csv'),row.names=FALSE)
write.csv(x=labelData,file=paste0(outputDataDirectory,'/', participantID,'boutData'),row.names=FALSE)
}
return(list(cleanData=cleanData,labelledData=labelledData))
}
if(FFT){
cat(paste0('Writing ALL FFT data file ', participantID,'.csv','\n'))
write.csv(x=labelledData$labelledFFTData,file=paste0(outputDataDirectory,'/', participantID,'ALLFFT.csv'),row.names=FALSE)
}
#remove unknown labels at beginning and end of period - this is the 'clean' data
cleanData<-removeUnlabelledEnds(data=labelledData,FFT=FFT)
cat(paste0('Writing CLEAN instance data file ', participantID,'.csv','\n'))
write.csv(x=cleanData$cleanInstanceLabelData,file=paste0(instanceLabelDirectory,'/', participantID,'Clean.csv'),row.names=FALSE)
cat(paste0('Writing CLEAN feature data file ', participantID,'.csv','\n'))
write.csv(x=cleanData$cleanLabelledFeatureData,file=paste0(outputDataDirectory,'/', participantID,'CleanFeature.csv'),row.names=FALSE)
if(FFT){
cat(paste0('Writing CLEANFFT data file ', participantID,'.csv','\n'))
write.csv(x=cleanData$cleanLabelledFFTData,file=paste0(outputDataDirectory,'/', participantID,'CleanFFT.csv'),row.names=FALSE)
}
} else {
cat(paste0('processed files for ', participantID,' already exist. Loading...','\n'))
labelledData<-list()
cleanData<-list()
labelledData$instanceLabelData<-fread(file.path(instanceLabelDirectory, paste0(participantID,'ALL.csv')))
labelledData$labelledFeatureData<-fread(input =paste0(outputDataDirectory,'/', participantID,'ALLFeature.csv'))
if(FFT){
labelledData$labelledFFTData<-fread(input=paste0(outputDataDirectory,'/', participantID,'ALLFFT.csv'))
}
cleanData$cleanInstanceLabelData<-fread(input = paste0(instanceLabelDirectory,'/', participantID,'Clean.csv'))
cleanData$cleanLabelledFeatureData<-fread(input=paste0(outputDataDirectory,'/', participantID,'CleanFeature.csv'))
if(FFT){
cleanData$cleanLabelledFFTData<-fread(input=paste0(outputDataDirectory,'/', participantID,'CleanFFT.csv'))
}
}
return(list(cleanData=cleanData,labelledData=labelledData))
}
#Function for rounding to the nearest 5 seconds, based at the first time entry (ie first time is 00:00:02, all times will be rounded to end with 2 or 7 seconds)
round5secs <- function( x,startTime) {
start<-as.POSIXlt(startTime)
startSecs<-start$sec
x <- as.POSIXlt( x - startSecs+ as.difftime( 2.5, units="secs" ) )
x$sec <- 5*(x$sec %/% 5)
as.POSIXct(x+startSecs)
}
roundXsecs <- function( x,startTime,duration=30) {
start<-as.POSIXlt(startTime)
startSecs<-start$sec
x <- as.POSIXlt( x - startSecs+ as.difftime( (duration/2), units="secs" ) )
x$sec <- duration*(x$sec %/% duration)
as.POSIXct(x+startSecs)
}
checklabelData<-function(checkData, minSeparation=600){
#Check that every row of the label data has an end time after the start time
if(sum(checkData$NewEnd<checkData$NewStart)>0){stop( "some epochs end before they begin!" )}
#Check the sequence of epochs forms a sequence
nrows<-nrow(checkData)
if(sum(checkData$NewStart[2:nrows]<checkData$NewEnd[1:nrows-1])>0){stop( "epochs do not form a sequence" )}
#Check that the gaps in between epochs are not too big - default is 10 mins
if(sum(checkData$NewStart[2:nrows]-checkData$NewEnd[1:nrows-1]>minSeparation)>0){stop( "there are large gaps between epochs" )}
return(cat(paste0('completed checks for label data from ',checkData$participant[1])))
}
extractLabelsSingleFile = function(all_bouts,identifier, winSize,instanceLabelDirectory) {
dateFmt = '%Y-%m-%d %H:%M:%S'
tz = 'GMT'
annotations = unique(all_bouts$behavior)
actNames = sub(" ", "", annotations)
identifiers = identifier
for (id in 1:length(identifiers)) {
cat(identifiers[id], "\n")
bouts = all_bouts[all_bouts$identifier == identifiers[id], ]
outputFile = file.path(instanceLabelDirectory, paste0(identifiers[id],'ALL.csv'))
out<-outputFile
r = 1
l = 1
label = "NULL"
boutstart = strptime(str_trim(bouts[r, ]$StartDateTime), dateFmt,tz=tz)
boutstop = strptime(str_trim(bouts[r, ]$EndDateTime), dateFmt,tz=tz)
timestamp = boutstart
day = timestamp$mday
cat(strftime(timestamp, "%Y-%m-%d"), '\n')
if (!file.exists(instanceLabelDirectory)) {
dir.create(instanceLabelDirectory, recursive=TRUE)
}
if (file.exists(out)) {
file.remove(out)
}
cat("identifier,timestamp,behavior\n", file=out, append=TRUE)
while (TRUE) {
if ((timestamp >= boutstart) & (timestamp + winSize <= boutstop)) {
# the window is within this bout - add the label
if(class(bouts)=="data.frame"){
label = sub(" ", "", str_trim(bouts[r, c('behavior')]))
} else if (class(bouts)[1]=="data.table"){
label = sub(" ", "", str_trim(bouts[r, c('behavior'),with=FALSE]))
}
} else if (timestamp + winSize > boutstop) {
# move on to the next bout
if (r == nrow(bouts)) {
break
}
while (timestamp + winSize > boutstop) {
if (r == nrow(bouts)) {
break
}
r = r + 1
boutstart = strptime(str_trim(bouts[r, ]$StartDateTime), dateFmt,tz=tz)
boutstop = strptime(str_trim(bouts[r, ]$EndDateTime), dateFmt,tz=tz)
}
if (timestamp >= boutstart) {
# the window is within this bout - add the label
if(class(bouts)=="data.frame"){
label = sub(" ", "", str_trim(bouts[r, c('behavior')]))
} else if (class(bouts)[1]=="data.table"){
label = sub(" ", "", str_trim(bouts[r, c('behavior'),with=FALSE]))
}
}
}
cat(paste0(identifier,','), file=out, append=TRUE)
cat(strftime(timestamp, "%Y-%m-%d %H:%M:%S,"), file=out, append=TRUE)
cat(label, file=out, append=TRUE)
cat("\n", file=out, append=TRUE)
# next window
l = l + 1
label = "NULL"
timestamp = as.POSIXlt(timestamp + winSize)
}
}
return(actNames)
}
removeUnlabelledEnds<-function(data,unlabelledBehaviorName='unknown',FFT=FALSE){
kx<-which(!data$instanceLabelData$behavior==unlabelledBehaviorName)
if(length(kx)>0){
maxIndex<-min(kx[length(kx)],nrow(data$labelledFeatureData))
cleanInstanceLabelData<-data$instanceLabelData[kx[1]:maxIndex,]
cleanLabelledFeatureData<-data$labelledFeatureData[kx[1]:maxIndex,]
if(FFT){
cleanLabelledFFTData<-data$labelledFFTData[kx[1]:maxIndex,]
}
}
if(FFT){
return(list(cleanInstanceLabelData=cleanInstanceLabelData,cleanLabelledFeatureData=cleanLabelledFeatureData,cleanLabelledFFTData=cleanLabelledFFTData))
} else {
return(list(cleanInstanceLabelData=cleanInstanceLabelData,cleanLabelledFeatureData=cleanLabelledFeatureData))
}
}
#function to clean up correlation colums that contain � symbol
cleanUpCorr<-function(featureData){
ixy<-which(featureData$corrxy=='�')
ixz<-which(featureData$corrxz=='�')
iyz<-which(featureData$corryz=='�')
#replace with interpolated values
if(length(ixy>0)){
featureData$corrxy[ixy]<-as.character(0.5*(as.numeric(featureData$corrxy[ixy+1])+as.numeric(featureData$corrxy[ixy-1])))
featureData$corrxy<-as.numeric(as.character(featureData$corrxy))
}
if(length(ixz>0)){
featureData$corrxz[ixz]<-as.character(0.5*(as.numeric(featureData$corrxz[ixz+1])+as.numeric(featureData$corrxz[ixz-1])))
featureData$corrxz<-as.numeric(as.character(featureData$corrxz))
}
if(length(iyz>0)){
featureData$corryz[iyz]<-as.character(0.5*(as.numeric(featureData$corryz[iyz+1])+as.numeric(featureData$corryz[iyz-1])))
featureData$corryz<-as.numeric(as.character(featureData$corryz))
}
return(featureData)
}
FixNAs<-function(data){
NArows<-which(rowSums(is.na(data))>0)
for(i in 1:length(NArows)){
NAcols<-which(is.na(AllData[NArows[i],]))
for(j in 1:length(NAcols)){
#We will search for the nearest entry 99 places up or down that isnt NA and copy that into the value
downsequence<-(NArows[i]+1):(NArows[i]+100)
upsequence<-(NArows[i]-1):(NArows[i]-100)
rowsequence<-c(rbind(downsequence, upsequence))
potentialreplacements<-which(!is.na(data[rowsequence,NAcols[j]]))
replacement<-min(potentialreplacements)
data[NArows[i],NAcols[j]]<-data[rowsequence[potentialreplacements[replacement]],NAcols[j]]
}
}
return(data)
}
#Function to compute proximity between two node matricies -
computeProximity<-function(nodes1,nodes2,parallel=FALSE,mc.cores=1){
#Check that we have the right number of columns
if(!ncol(nodes1)==ncol(nodes2)){stop( "number of columns do not match!" )}
ntrees<-ncol(nodes1)
P<-matrix(nrow = nrow(nodes1),ncol = nrow(nodes2),dimnames = NULL)
if(parallel==FALSE){
P <- apply(
nodes1,
MARGIN = 1,
function(a){apply(
nodes2,
MARGIN = 1,
function(b){sum(a==b)})})
return(P/ntrees)
}else if (parallel==TRUE){
coresPerLevel<-floor(sqrt(mc.cores))
nrows<-nrow(nodes1)
#P=sapply(X =
P=mclapply(
X=split(nodes2,row(nodes2)),
FUN=function(a){apply(
nodes1,
MARGIN = 1,
function(b) sum(a==b))
})
#,FUN = cbind)
return(matrix(unlist(P), ncol = length(P[[1]]), byrow = TRUE,dimnames = NULL)/ntrees)
}
}
#C++ version of computeProximity - faster and better
cppFunction('NumericMatrix computeProximityC(NumericMatrix nodes1, NumericMatrix nodes2) {
int n1 = nodes1.nrow(), ntrees = nodes1.ncol(), n2= nodes2.nrow();
NumericMatrix proximity(n2,n1);
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
for (int k=0; k<ntrees; k++){
if(nodes1(i,k)==nodes2(j,k)){
proximity(j,i) += 1.0/ntrees;
}
}
}
}
return proximity;
}')
#C++ int version of computeProximity - faster and better
cppFunction(code = 'NumericMatrix computeProximityC_int(NumericMatrix nodes1, NumericMatrix nodes2) {
int n1 = nodes1.nrow(), ntrees = nodes1.ncol(), n2= nodes2.nrow();
NumericMatrix proximity(n2,n1);
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
for (int k=0; k<ntrees; k++){
if(nodes1(i,k)==nodes2(j,k)){
proximity(j,i) += 1;
}
}
}
}
return proximity;
}')
#Function to roughly split up matrix into chunks
splitMatrix<-function(data_matrix,nprocs){
#divide up matrix into nchunks=ncores chunks
chunks<-splitNumber(nrow(data_matrix),nprocs)
#attach rownames
rownames(data_matrix)<-1:nrow(data_matrix)
end_indices<-cumsum(chunks)
start_indices<-cumsum(c(1,chunks))
chunked_matrix<-lapply(X = 1:nprocs,FUN = function(x) data_matrix[start_indices[x]:end_indices[x],])
return(chunked_matrix)
}
splitMatrix_cols<-function(data_matrix,nprocs){
#divide up matrix into nchunks=ncores chunks
chunks<-splitNumber(ncol(data_matrix),nprocs)
#attach rownames
colnames(data_matrix)<-1:ncol(data_matrix)
end_indices<-cumsum(chunks)
start_indices<-cumsum(c(1,chunks))
chunked_matrix<-lapply(X = 1:nprocs,FUN = function(x) data_matrix[,start_indices[x]:end_indices[x]])
return(chunked_matrix)
}
#function to divide a number into chunks
splitNumber<-function(number,nprocs){
remainder_chunk<-number %% nprocs
chunk<-number %/% nprocs
if(!remainder_chunk==0){
large_chunk<-chunk+1
chunk_lengths<-c(rep(large_chunk,remainder_chunk),rep(chunk,nprocs-remainder_chunk))
} else{
chunk_lengths<-c(rep(chunk,nprocs))
nchunks<-nprocs
}
return(chunk_lengths)
}
#Function to roughly split up matrix into chunks
chunkOfMatrix<-function(data_matrix,nchunks,chunkID){
#divide up matrix into nchunks chunks
chunks<-splitNumber(nrow(data_matrix),nchunks)
#attach rownames
rownames(data_matrix)<-1:nrow(data_matrix)
end_indices<-cumsum(chunks)
start_indices<-cumsum(c(1,chunks))
if(chunkID<=nchunks){
chunk_of_matrix<-data_matrix[start_indices[chunkID]:end_indices[chunkID],]
return(chunk_of_matrix)
} else {
cat('chunkID must be smaller than or equal to nchunks')
}
}
#Function to roughly split up matrix into chunks
chunkOfMatrix_cols<-function(data_matrix,nchunks,chunkID){
#divide up matrix into nchunks chunks
chunks<-splitNumber(ncol(data_matrix),nchunks)
#attach rownames
colnames(data_matrix)<-1:ncol(data_matrix)
end_indices<-cumsum(chunks)
start_indices<-cumsum(c(1,chunks))
if(chunkID<=nchunks){
chunk_of_matrix<-data_matrix[,start_indices[chunkID]:end_indices[chunkID]]
return(chunk_of_matrix)
} else {
cat('chunkID must be smaller than or equal to nchunks')
}
}
calcZ<-function(ProxTrain,Kmax,CV=TRUE){
#Diag <- diag(apply(ProxTrain, 1, sum))
#U<-Diag-ProxTrain
k <- Kmax
if(CV==TRUE){
ProxTrain<-computeCVmatrix(ProxTrain)
}
evL <- eigs_sym(ProxTrain,k+1,which='LM')
Z <- evL$vectors[,1:k]
return(Z)
}
kSpaceAnalysis<-function(kval,Z,ProxTest,ProxTrain,TrainingData,testing_RF_predicitions){
#Z is our projection operator
#plot(Z, col=as.factor(AllInstanceData$behavior[ix]), pch=20)
Z_k<-Z[,1:kval]
#Now project our testing data into K space
kData<-ProxTest %*% Z_k
kTrainData<-ProxTrain %*% Z_k
#Intermediate step:
#compare the out-of-sample classification performance of LDA trained on {labels,kTrainData}
#to the original RF trained on {labels, featuredata}, and as a function of k
#using a random half of the data, 20 times
cat(paste0('doing LDA \n'))
LDA_accuracy<-c()
kMeans_accuracy<-c()
cat(paste0(ncol(kTrainData), '\n'))
lda_comparison<-lda(x=kTrainData,grouping = as.factor(TrainingData[,1]))
lda_prediction<-predict(object = lda_comparison,newdata=kData,dimen = kval)
reference<-factor(testing_RF_predicitions,levels = levels(lda_prediction$class))
LDA_confusion<-matrix(ncol=length(levels(lda_prediction$class)),nrow=length(levels(lda_prediction$class)))
for(i in 1:1){
#take a half subset of data for confusion matrix
ix<-sample(length(lda_prediction$class),replace=F,size=floor(0.5*length(lda_prediction$class)))
lda_RF_confusion_matrix<-confusionMatrix(data =lda_prediction$class[ix],reference = reference[ix])
LDA_accuracy[i]<-lda_RF_confusion_matrix$overall[1]
}
# #4.run an HMM with gaussian emission probs for the projected points in the k-space
#
# ####learn the HMM using the labelled and unlabelled data in the k-space
# cat(paste0('doing HMM for \n'))
#
#
#
# labelledInstance<-as.factor(TrainingData[,1])
#
# hmmData<-list()
# hmmData$s<-as.numeric(TrainingData[,2:17])
# hmmData$x<-t(Z)
# hmmData$N<-length(hmmData$s)
# class(hmmData)<-"hsmm.data"
#
#
#
#
#
# states<-TrainingData[,1]
# states<-states[!is.na(states)]
#
#
# #calculate empirial transition matrix
# statesLength<-length(states)
# Trans<-table(states[1:statesLength-1],states[2:statesLength])
# Trans <- Trans / rowSums(Trans)
#
# labelCode<-levels(as.factor(TrainingData[,1]))
#
# mu<-list()
# sigma<-list()
# for (j in 1:length(labelCode)){
# mu[[j]]<-colMeans(Z[which(TrainingData[,1]==labelCode[j]),])
# sigma[[j]]<-cov(Z[which(TrainingData[,1]==labelCode[j]),])
# }
#
# B <- list(mu=mu,sigma=sigma)
# model <- hmmspec(init=init, trans = Trans, parms.emis = B,dens.emis = dmvnorm.hsmm)
#
# save(model,rf, file = file.path(resultsDataDirectory,paste0(participant,'UCI_HMMandRFmodel.R')))
#
# ##Now train model
#
# #output<-hmmfit(x = hmmData,start.val = model,mstep=mstep.mvnorm,lock.transition=FALSE,tol=1e-08,maxit=1000)
#
# #train <- simulate(model, nsim=100, seed=1234, rand.emis=rmvnorm.hsmm)
# cat(paste0('predicting HMM \n'))
#
# smoothed<-predict(object = model,newdata = kData,method = 'viterbi')
#
# newLabels<-factor(smoothed$s)
#
# true_reference<-factor(TestingData[,1],levels = labelCode)
#
#
# levels(newLabels)<-labelCode
#newLabels<-as.character(newLabels)
#Calculate Confusion matrix
# HMM_confusion_matrix<-confusionMatrix(data =newLabels,reference = true_reference)
#output LDA and HMM confusion matrices
LDA_accuracy_mean<-mean(LDA_accuracy)
LDA_accuracy_std<-sd(LDA_accuracy)
LDAperformance<-list(LDA_conf=lda_RF_confusion_matrix$table)
#LDAperformance<-LDA_accuracy
# HMMperformance[[i]]<-HMM_confusion_matrix
#write predicitions
cat(paste0('saving predictions \n'))
# write.csv(x=lda_prediction,file = file.path(RFoutput,paste0(outputPrefix,kval,'UCI_LDApred.csv')))
# write.csv(x=newLabels,file = file.path(HMMoutput,'HMMpred.csv'))
# write.csv(x=LDAperformance,file = file.path(RFoutput,paste0(outputPrefix,kval,'UCI_LDAaccuracy.csv')))
#save(LDAperformance, HMMperformance, file = file.path(resultsDataDirectory,"Results.RData"))
return(LDAperformance)
}
computeCVmatrix<-function(Proximity){
rowsum<-rowSums(Proximity)
rowsum<-rowsum/ncol(Proximity)
colsum<-colSums(Proximity)
colsum<-colsum/nrow(Proximity)
cv=0.5*t(t(Proximity-rowsum+mean(Proximity))-colsum)
return(cv)
}
computeCVbigmatrix<-function(Proximity,BackingDir){
rowmean<-BigRowSums(pBigMat = Proximity@address)
matmean<-sum(rowmean)
rowmean<-rowmean/length(rowmean)
rowmean.bigmat<-big.matrix(nrow = nrow(Proximity),ncol = ncol(Proximity),type = 'double',backingfile =BackingDir)
colmean<-colsum(Proximity)
colmean<-rowmean/length(colmean)
matmean<-matmean/(length(colmean)*length(rowmean))
cv=0.5*big.t(big.t(Proximity-rowmean+matmean,dir =BackingDir)-colmean,dir = BackingDir)
return(cv)
}
RFProxLDA<-function(TrainingData,TestingData,Kmax=40,ncores,ntree){
#1.a Run RF using the labelled data points on training data
mtry = floor(sqrt(ncol(TrainingData[,2:ncol(TrainingData)])))
replace=TRUE
nodesize=1
cat(paste0('training RF\n'))
cat(paste0('nrow for training data is ',nrow(TrainingData),'\n'))
cat(paste0('size of features for training data is ',object.size(TrainingData),'\n'))
rf <- foreach(ntree=splitNumber(ntree,nprocs = ncores ), .combine=randomForest::combine, .multicombine=TRUE, .packages='randomForest') %dopar%
randomForest(x = TrainingData[,2:ncol(TrainingData)],y=as.factor(TrainingData[,1]),
ntree=ntree,
mtry=mtry,
replace=replace,
nodesize=nodesize,
importance=FALSE,
proximity = FALSE,
do.trace = 100)
#1.b we need to know which data point goes to which node of each tree in our training set!
cat(paste0('extracting training nodes \n'))
training_nodes <- foreach(features=splitMatrix(TrainingData[,2:ncol(TrainingData)],nprocs = ncores),.combine = rbind, .packages='randomForest') %dopar%
attr(predict(rf, features, type="prob",
norm.votes=TRUE, predict.all=TRUE, proximity=FALSE, nodes=TRUE,oob.prox=TRUE),which='nodes')
training_nodes<-training_nodes[order(as.numeric(rownames(training_nodes))),]
#Challenge - create proximity matrix from node locations
#training_nodes matrix has npoints rows and ntree columns
#2.Output the RF proximity matrix, for all testing data training data - ie for one participant
#Proximity matrix is npoints by npoints
cat(paste0('calculating training nodes proximity \n'))
ProxTrain <- foreach(splitTraining=splitMatrix(training_nodes,nprocs = ncores), .combine = rbind) %dopar% matrix(
computeProximityC(nodes1=training_nodes,nodes2=splitTraining),
nrow=nrow(splitTraining),dimnames=list(rownames(splitTraining)))
ProxTrain<-ProxTrain[order(as.numeric(rownames(ProxTrain))),]
#2.b we need to know which data point goes to which node of each tree in our testing set!
cat(paste0('extracting testing nodes \n'))
testing_nodes <- foreach(features=splitMatrix(TestingData,nprocs = ncores),.combine = rbind, .packages='randomForest') %dopar% attr(
predict(rf, features, type="prob",norm.votes=TRUE, predict.all=TRUE,
proximity=FALSE, nodes=TRUE),which='nodes')
reordering_indices<-order(as.numeric(row.names(testing_nodes)))
testing_nodes<-testing_nodes[reordering_indices,]
cat(paste0('extracting RF test predictions \n'))
#and also the RF predicitions
testing_RF_predicitions<-foreach(features=splitMatrix(TestingData[,2:ncol(TestingData)],nprocs = ncores),.combine = c, .packages='randomForest') %dopar%
as.character(predict(rf, features, type="response",
norm.votes=TRUE, predict.all=TRUE, proximity=FALSE, nodes=FALSE)$aggregate,names)
testing_RF_predicitions<-(testing_RF_predicitions[reordering_indices])
#Challenge - create proximity matrix from node locations of overlap between Training data and Testing Data
#testing_nodes matrix has ntraingpoints rows and ntree columns
#Proximity matrix is ntestingpoints rows by ntrainingpoints columns
cat(paste0('calculating testing nodes proximity \n'))
ProxTest <- foreach(splitTesting=splitMatrix(testing_nodes,nprocs = ncores),.combine = rbind) %dopar% matrix(
computeProximityC(nodes1=training_nodes,nodes2=splitTesting[,1:ntree]),
nrow=nrow(splitTesting),dimnames=list(rownames(splitTesting)))
ProxTest<-ProxTest[order(as.numeric(rownames(ProxTest))),]
#3.Using ideas from spectral clustering, take an eigen(like) spectral decomposition of ProxTrain and project all
# testing data points into the leading k-components of the decomposition of ProxTrain
# with k smallish (say 3 or 4 dimensions)
cat(paste0('doing kSpace transform \n'))
Z<-calcZ(ProxTrain=ProxTrain,Kmax=Kmax,CV=FALSE)
Z_cv<-calcZ(ProxTrain=ProxTrain,Kmax=Kmax,CV = TRUE)
#save(Z,file = file.path(resultsDataDirectory,paste0("UCI_Z.RData")))
#save(Z_cv,file = file.path(resultsDataDirectory,paste0("UCI_Z_cv.RData")))
#load(file='~/Documents/Oxford/Activity/UCI_Z.RData')
#load(file='~/Documents/Oxford/Activity/UCI_Z_cv.RData')
# LDAperformance_output<-foreach(k=1:Kmax,.combine = list) %dopar% kSpaceAnalysis(
# kval=k,Z=Z,ProxTest=ProxTest,ProxTrain=ProxTrain,TrainingData=TrainingData,
# testing_RF_predicitions=testing_RF_predicitions)
LDAperformance_cv_output<-foreach(k=1:Kmax,.combine = list) %dopar% kSpaceAnalysis(
kval=k,Z=Z_cv,ProxTest=ProxTest,ProxTrain=ProxTrain,TrainingData=TrainingData,
testing_RF_predicitions=testing_RF_predicitions)
return(list(LDAperformance_cv_output=LDAperformance_cv_output,Z=Z,Z_cv=Z_cv,ProxTrain=ProxTrain,ProxTest=ProxTest,testing_RF_predicitions=testing_RF_predicitions))
}
plotKData<-function(Proxdatamatrix,Zmat,k,xaxis='X1',yaxis='X2',labelData,name,outputdir){
kPlotData<-Proxdatamatrix %*% Zmat[,1:k]
kPlotData<-data.frame(kPlotData)
kPlotData$group<-factor(labelData)
kPlotDatamelt <- melt(kPlotData, id.vars = "group")
P<-ggplot(kPlotData, aes_string(x=xaxis,y=yaxis))+ geom_point(aes(colour = group), size = 1)+ggtitle(gsub(pattern = '.png',replacement = '',x = name))
ggsave(plot = P,filename =file.path(outputdir,name),device = 'png')
}
plot3DkData<-function(datalist,name,groundtruth,outputdir){
kSpaceData<-datalist$ProxTrain %*% datalist$Z_cv[,1:3]
colorVector<-rep('',times=nrow(kSpaceData))
ia<-which(factor(groundtruth)==levels(factor(groundtruth))[1])
colorVector[ia]<-'red'
colorVector[-ia]<-'blue'
png(filename =file.path(outputdir,name),width = 1000,height = 1000)
scatterplot3d(kSpaceData, main=gsub(pattern = '3D.png',replacement = '',x = name),color =colorVector, pch = 19)
dev.off()
}
RF_nodes_chunk<-function(TrainingFData,TrainingBData,TestingFData,ncores,ntree,savefileloc,chunkID,nametoken){
#1.a Run RF using the labelled data points on training data
mtry = floor(sqrt(ncol(TrainingFData)-1))
replace=TRUE
nodesize=1
cat(paste0('training RF\n'))
cat(paste0('nrow for training data is ',nrow(TrainingFData),'\n'))
cat(paste0('size of features for training data is ',object.size(TrainingFData),'\n'))
rf <- foreach(ntree=splitNumber(ntree,nprocs = ncores ), .combine=randomForest::combine, .multicombine=TRUE, .packages='randomForest') %dopar%
randomForest(x = TrainingFData,y=as.factor(TrainingBData),
ntree=ntree,
mtry=mtry,
replace=replace,
nodesize=nodesize,
importance=FALSE,
proximity = FALSE,
do.trace = 100)
cat(paste0('saving RF file \n'))
save(rf,file=file.path(savefileloc,paste0('RF_',chunkID,'_',nametoken,'.RData')))
split_Testing_features<-splitMatrix(TestingFData,nprocs = ncores)
split_Training_features<-splitMatrix(TrainingFData,nprocs = ncores)
rm(TrainingFData)
rm(TestingFData)
#2.a we need to know which data point goes to which node of each tree in our training set!
cat(paste0('extracting training nodes \n'))
training_nodes <- foreach(features=split_Training_features,.combine = rbind, .packages='randomForest') %dopar%
attr(predict(rf, features, type="prob",
norm.votes=TRUE, predict.all=TRUE, proximity=FALSE, nodes=TRUE,oob.prox=TRUE),which='nodes')
training_nodes<-training_nodes[order(as.numeric(rownames(training_nodes))),]
cat(paste0('saving training nodes \n'))
write.csv(x = training_nodes,file=file.path(savefileloc,paste0('training_nodes_',chunkID,'_',nametoken,'.csv')),row.names = FALSE)
rm(training_nodes)
cat(paste0('extracting testing nodes \n'))
#2.b we need to know which data point goes to which node of each tree in our testing set!
testing_nodes <- foreach(features=split_Testing_features,.combine = rbind, .packages='randomForest') %dopar% attr(
predict(rf, features, type="prob",norm.votes=TRUE, predict.all=TRUE,
proximity=FALSE, nodes=TRUE),which='nodes')
reordering_indices<-order(as.numeric(row.names(testing_nodes)))
testing_nodes<-testing_nodes[reordering_indices,]
cat(paste0('saving testing nodes \n'))
write.csv(x = testing_nodes,file=file.path(savefileloc,paste0('testing_nodes_',chunkID,'_',nametoken,'.csv')),row.names = FALSE)
rm(testing_nodes)
cat(paste0('extracting RF predictions \n'))
#3. and also the RF predicitions for the testing set
testing_RF_predicitions<-foreach(features=split_Testing_features,.combine = c, .packages='randomForest') %dopar%
as.character(predict(rf, features, type="response",
norm.votes=TRUE, predict.all=TRUE, proximity=FALSE, nodes=FALSE)$aggregate,names)
testing_RF_predicitions<-(testing_RF_predicitions[reordering_indices])
cat(paste0('saving RF predictions \n'))
write.csv(x = testing_RF_predicitions,file=file.path(savefileloc,paste0('testing_RF_predicitons_',chunkID,'_',nametoken,'.csv')),row.names = FALSE)
rm(testing_RF_predicitions)
return(cat(paste0('saved files for chunk ',chunkID,' with ',ntree,' trees')))
}
cbind_node_files<-function(inputDirectory,outputDirectory,startToken,leftOutParticipant=participants[leave_out],nchunks){
chunkids<-1:nchunks
listOfNodeFiles<-paste0(startToken,chunkids,'_',leftOutParticipant,'.csv')
all_nodes<-foreach(file=listOfNodeFiles,.combine = cbind,.multicombine = TRUE) %dopar% fread(input=file.path(outputDirectory,file))
}
rbind_prox_files<-function(inputDirectory,outputDirectory,startToken,leftOutParticipant=participants[leave_out],nchunks){
chunkids<-1:nchunks
listOfFiles<-paste0(startToken,chunkids,'_',leftOutParticipant,'.csv')
all_nodes<-foreach(file=listOfFiles,.combine = rbind,.multicombine = TRUE) %do% fread(input=file.path(outputDirectory,file))
}
#
# #Code to creat rowsum function for bigdata matrix
# sourceCpp(code = '// [[Rcpp::depends(BH)]]
# #include <Rcpp.h>
# using namespace Rcpp;
#
# // [[Rcpp::depends(BH, bigmemory)]]
# #include <bigmemory/MatrixAccessor.hpp>
#
# #include <numeric>
#
# // Logic for BigRowSums.
# template <typename T>
# NumericVector BigRowSums(XPtr<BigMatrix> pMat, MatrixAccessor<T> mat) {
# NumericVector rowSums(pMat->nrow(), 0.0);
# NumericVector value(1);
# for (int jj = 0; jj < pMat->ncol(); jj++) {
# for (int ii = 0; ii < pMat->nrow(); ii++) {
# value = mat[jj][ii];
# if (all(!is_na(value))) {
# rowSums[ii] += value[0];
# }
# }
# }
# return rowSums;
# }
#
# // Dispatch function for BigRowSums
# //
# // [[Rcpp::export]]
# NumericVector BigRowSums(SEXP pBigMat) {
# XPtr<BigMatrix> xpMat(pBigMat);
#
# switch(xpMat->matrix_type()) {
# case 1:
# return BigRowSums(xpMat, MatrixAccessor<char>(*xpMat));
# case 2:
# return BigRowSums(xpMat, MatrixAccessor<short>(*xpMat));
# case 4:
# return BigRowSums(xpMat, MatrixAccessor<int>(*xpMat));
# case 6:
# return BigRowSums(xpMat, MatrixAccessor<float>(*xpMat));
# case 8:
# return BigRowSums(xpMat, MatrixAccessor<double>(*xpMat));
# default:
# throw Rcpp::exception("unknown type detected for big.matrix object!");
# }
# }
# ')