-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvoxelDPM.py
More file actions
1624 lines (1241 loc) · 71.9 KB
/
voxelDPM.py
File metadata and controls
1624 lines (1241 loc) · 71.9 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
import numpy as np
import math
from aux import *
import scipy
#import scipy.cluster.hierarchy
import scipy.spatial
import pickle
import sklearn.cluster
import scipy.stats
import pdb
from plotFunc import *
import gc
from matplotlib import pyplot as pl
import DisProgBuilder
import os
import diffEqModel
import sys
import PlotterVDPM
class VoxelDPMBuilder(DisProgBuilder.DPMBuilder):
# builds a voxel-wise disease progression model
def __init__(self, isCluster):
self.plotterObj = PlotterVDPM.PlotterVDPM()
def setPlotter(self, plotterObj):
self.plotterObj = plotterObj
def generate(self, dataIndices, expName, params):
return VoxelDPM(dataIndices, expName, params, self.plotterObj)
class VoxelDPM(DisProgBuilder.DPMInterface):
def __init__(self, dataIndices, expName, params, plotterObj):
self.thetas = np.nan
self.variances = np.nan
self.subShifts = np.nan
self.clustProb = np.nan
self.dpsLongFirstVisit = np.nan
self.params = params
self.dataIndices = dataIndices
self.expName = expName
self.outFolder = 'resfiles/%s' % expName
self.params['plotTrajParams']['outFolder'] = self.outFolder
assert(params['data'].shape[0] == params['diag'].shape[0]
== params['partCode'].shape[0] == params['ageAtScan'].shape[0]
== dataIndices.shape[0] == params['scanTimepts'].shape[0])
# can be informative or uniform(zero)
self.logPriorShiftFunc = params['logPriorShiftFunc']
self.logPriorShiftFuncDeriv = params['logPriorShiftFuncDeriv']
self.paramsPriorShift = params['paramsPriorShift']
self.logPriorThetaFunc = params['logPriorThetaFunc']
self.logPriorThetaFuncDeriv = params['logPriorThetaFuncDeriv']
self.paramsPriorTheta = None # set it later when you initialise thetas.
self.plotterObj = plotterObj
self.params['pdbPause'] = False
def runStd(self, runPart):
return self.run(runPart)
def run(self, runPart):
# filter some diagnostic groups, i.e. PCA/tAD or even for cross-validation
filtParams = diffEqModel.filterDDSPAIndices(self.params, self.dataIndices)
filtData = filtParams['data']
filtDiag = filtParams['diag']
filtScanTimepts = filtParams['scanTimepts']
filtPartCode = filtParams['partCode']
filtAgeAtScan = filtParams['ageAtScan']
# filtData = filtParams[self.dataIndices, :]
# filtDiag = self.params['diag'][self.dataIndices]
# filtScanTimepts = self.params['scanTimepts'][self.dataIndices]
# filtPartCode = self.params['partCode'][self.dataIndices]
# filtAgeAtScan = self.params['ageAtScan'][self.dataIndices]
# subjects that only contain one timepoint will be removed
(longData, longDiagAllTmpts, longDiag, longScanTimepts, longPartCode, longAgeAtScan,
uniquePartCodeInverse, crossData, crossDiag, scanTimepts, crossPartCode, crossAgeAtScan, uniquePartCode) = \
self.createLongData(filtData, filtDiag, filtScanTimepts, filtPartCode, filtAgeAtScan)
nrClust = self.params['nrClust']
plotTrajParams = self.params['plotTrajParams']
# perform some initial clustering with k-means or use a-priori defined ROIs (freesurfer)
initClust = self.runInitClust(runPart, crossData, crossDiag)
if initClust is None:
return None
(nrSubjCross, nrBiomk) = crossData.shape
nrSubjLong = len(longData)
print(len(uniquePartCodeInverse), np.max(uniquePartCodeInverse), nrSubjLong, nrSubjCross)
assert (np.max(uniquePartCodeInverse) < nrSubjLong)
nrOuterIter = self.params['nrOuterIter']
nrInnerIter = self.params['nrInnerIter']
longAge1array = [np.concatenate((x.reshape(-1, 1), np.ones(x.reshape(-1, 1).shape,
dtype=float)), axis=1) for x in longAgeAtScan]
# np array NR_SUBJ_CROSS-SECTIONALLY x 2 [ cross-sectional_age 1]
crossAge1array = np.concatenate((crossAgeAtScan.reshape(-1, 1),
np.ones(crossAgeAtScan.reshape(-1, 1).shape,dtype=float)), axis=1)
ageFirstVisitLong1array = np.array([s[0, :] for s in longAge1array])
assert (ageFirstVisitLong1array.shape[1] == 2)
# initialise cluster probabilities
prevClustProbBC = makeClustProbFromArray(initClust)
# initialise subject specific shifts and rates
subShiftsLong = np.nan * np.ones((nrOuterIter, nrInnerIter, nrSubjLong, 2), float)
subShiftsLong[0, 0, :, 0] = 1 # alpha
subShiftsLong[0, 0, :, 1] = 0 # beta
# estimate some initial thetas, which are used as starting point in the numerical optimisatrion algo
initThetas, initVariances = self.initTrajParams(crossData, crossDiag, prevClustProbBC,
crossAgeAtScan, subShiftsLong[0, 0, :, :], uniquePartCodeInverse, crossAge1array, self.params['rangeFactor'])
# infer missing values in data from initial parameters
initSubShiftsCross = subShiftsLong[0,0, uniquePartCodeInverse, :]
self.plotterObj.nanMask = np.isnan(crossData)
self.plotterObj.longDataNaNs = longData
# assert np.sum(np.isnan(self.plotterObj.longDataNaNs[0])) > 0
crossData, longData = self.inferMissingData(crossData, longData, prevClustProbBC, initThetas, initSubShiftsCross,
crossAge1array, self.trajFunc, scanTimepts, crossPartCode, uniquePartCode, self.plotterObj)
# print('longData[0]', longData[0])
# print('longPartCode', longPartCode[0])
# print('longScanTimepts', longScanTimepts[0])
# print(ads)
paramsDataFile = '%s/params_o%d.npz' % (self.outFolder, nrOuterIter)
# initThetas, initVariances, subShiftsLongInit, \
# prevClustProbBC, paramsDataFile = self.loadParamsFromFile(paramsDataFile,
# nrOuterIter, nrInnerIter)
# subShiftsLong[0, 0, :, :] = subShiftsLongInit
if runPart[1] == 'R':
clustProbOBC = np.zeros((nrOuterIter, nrBiomk, nrClust), float)
clustProbOBC[0, :, :] = prevClustProbBC
assert not np.isnan(initThetas).any()
thetas = np.nan * np.ones((nrOuterIter, nrInnerIter, nrClust, initThetas.shape[1]), float)
variances = np.nan * np.ones((nrOuterIter, nrInnerIter, nrClust), float)
thetas[0,0,:,:] = initThetas
variances[0,0,:] = initVariances
counter = 0
prevOuterIt = 0
prevInnerIt = 0
prevSubShifts = subShiftsLong[prevOuterIt, prevInnerIt, :, :]
prevThetas = thetas[prevOuterIt, prevInnerIt, :, :]
prevVariances = variances[prevOuterIt, prevInnerIt, :]
prevSubShiftsCross = prevSubShifts[uniquePartCodeInverse, :]
dpsCross = VoxelDPM.calcDps(prevSubShiftsCross, crossAge1array)
# print('crossData.shape', crossData.shape)
# print(ads)
for outerIt in range(nrOuterIter):
# fit DPM
prevClustProbBC = clustProbOBC[prevOuterIt, :,:]
prevClustProbBCColNorm = prevClustProbBC/np.sum(prevClustProbBC,0)[None, :]
self.plotterObj.plotClustProb(prevClustProbBC, prevThetas, prevVariances, prevSubShifts, plotTrajParams,
filePathNoExt='%s/clust%d_%s' % (self.outFolder, outerIt, '_'.join(self.expName.split('/'))))
print('outerIt ', outerIt)
if outerIt == 2:
self.params['pdbPause'] = True
for innerIt in range(nrInnerIter):
print('innerIt ', innerIt)
sys.stdout.flush()
prevSubShifts = subShiftsLong[prevOuterIt, prevInnerIt, :,:]
prevThetas = thetas[prevOuterIt, prevInnerIt, :, :]
prevVariances = variances[prevOuterIt, prevInnerIt, :]
prevSubShiftsCross = prevSubShifts[uniquePartCodeInverse,:]
dpsCross = VoxelDPM.calcDps(prevSubShiftsCross, crossAge1array)
dpsLong = self.makeLongArray(dpsCross, scanTimepts, crossPartCode, np.unique(crossPartCode))
# print('longAge1array', longAge1array)
fig = self.plotterObj.plotTrajWeightedDataMean(crossData, crossDiag, dpsCross, longData, longDiag, dpsLong,
prevThetas, prevVariances,
prevClustProbBCColNorm, plotTrajParams, self.trajFunc, orderClust=True)
fig.savefig('%s/loopMean%d%d1.png' % (self.outFolder, outerIt, innerIt), dpi = 100)
# fig = self.plotterObj.plotTrajWeightedDataMean(crossData, crossDiag, dpsCross, longData, longDiag, dpsLong,
# prevThetas, prevVariances,
# prevClustProbBCColNorm, plotTrajParams, self.trajFunc, orderClust=True,
# showInferredData=True)
# fig.savefig('%s/inferLoopMean%d%d1.png' % (self.outFolder, outerIt, innerIt), dpi = 100)
assert not np.isnan(crossData).any()
assert not np.isnan(crossDiag).any()
assert not np.isnan(dpsCross).any()
assert not np.isnan(prevThetas).any()
assert not np.isnan(prevVariances).any()
# print([np.isnan(a).any() for a in longAge1array])
assert not any([np.isnan(a).any() for a in longAge1array])
assert not any([np.isnan(a).any() for a in longData])
assert not np.isnan(prevClustProbBC).any()
assert not np.isnan(prevSubShifts).any()
print('Estimate subject shifts')
# estimate alphas and betas
prevSubShiftAvg = np.mean(prevSubShifts, axis=0)
for s in range(nrSubjLong):
print('Subject shift estimation %d/%d' % (s, nrSubjLong))
subShiftsLong[outerIt, innerIt, s, :] = self.estimShifts(longData[s], prevThetas,
prevVariances, longAge1array[s], prevClustProbBC, prevSubShifts[s,:], prevSubShiftAvg,
self.params['fixSpeed'])
sys.stdout.flush()
subShiftsNewCross = subShiftsLong[outerIt, innerIt, uniquePartCodeInverse, :]
dpsCrossNew = VoxelDPM.calcDps(subShiftsNewCross, crossAge1array)
dpsLongNew = self.makeLongArray(dpsCrossNew, scanTimepts, crossPartCode, np.unique(crossPartCode))
fig = self.plotterObj.plotTrajWeightedDataMean(crossData, crossDiag, dpsCrossNew, longData, longDiag,
dpsLongNew, prevThetas, prevVariances, prevClustProbBCColNorm,
plotTrajParams, self.trajFunc, orderClust=True)
fig.savefig('%s/loopMean%d%d2.png' % (self.outFolder, outerIt, innerIt), dpi = 100)
# fig = self.plotterObj.plotTrajWeightedDataMean(crossData, crossDiag, dpsCrossNew, longData, longDiag,
# dpsLongNew, prevThetas, prevVariances, prevClustProbBCColNorm,
# plotTrajParams, self.trajFunc, orderClust=True, showInferredData=True)
# fig.savefig('%s/inferLoopMean%d%d2.png' % (self.outFolder, outerIt, innerIt), dpi = 100)
print('Estimate thetas and variances')
# estimate thetas and variances
for c in range(nrClust):
print('Estimating theta %d/%d' % (c, nrClust))
(thetas[outerIt, innerIt, c, :], variances[outerIt, innerIt, c]) = self.estimThetas(crossData,
dpsCrossNew, prevClustProbBCColNorm[:,c], prevThetas[c,:], nrSubjLong)
fig = self.plotterObj.plotTrajWeightedDataMean(crossData, crossDiag, dpsCrossNew,
longData, longDiag, dpsLongNew, thetas[outerIt, innerIt, :, :],
variances[outerIt, innerIt, :], prevClustProbBCColNorm, plotTrajParams, self.trajFunc,
orderClust=True)
fig.savefig('%s/loopMean%d%d3.png' % (self.outFolder, outerIt, innerIt), dpi = 100)
# fig = self.plotterObj.plotTrajWeightedDataMean(crossData, crossDiag, dpsCrossNew,
# longData, longDiag, dpsLongNew, thetas[outerIt, innerIt, :, :],
# variances[outerIt, innerIt, :], prevClustProbBCColNorm, plotTrajParams, self.trajFunc,
# orderClust=True, showInferredData=True)
# fig.savefig('%s/inferLoopMean%d%d3.png' % (self.outFolder, outerIt, innerIt), dpi = 100)
# ensure beta is positive and make the thetas identifiable
subShiftsLong[outerIt, innerIt, :, :], shiftTransform = VoxelDPM.makeShiftsIdentif(
subShiftsLong[outerIt, innerIt,:,:], ageFirstVisitLong1array, longDiag)
# apart from making them identifiable also rescale them according to the DPS transformation
thetas[outerIt, innerIt, :, :] = self.makeThetasIdentif(thetas[outerIt, innerIt,:,:], shiftTransform)
counter += 1
prevInnerIt = innerIt
prevOuterIt = outerIt # need to also set outerIt otherwise at (2,1) it will use (1,0) instead of (2,0)
# end of inner loop
print('Recompute cluster assignments')
# recopute responsibilities p(z_t = k) that voxel t was generated by cluster k
subShiftsNewCross2 = subShiftsLong[outerIt, -1, uniquePartCodeInverse, :]
clustProbOBC[outerIt, :, :], crossData, longData = self.recompResponsib(crossData, longData, crossAge1array,
thetas[outerIt, -1, :, :], variances[outerIt, -1, :], subShiftsNewCross2, self.trajFunc,
prevClustProbBC, scanTimepts, crossPartCode, uniquePartCode)
clustProbBC = clustProbOBC[-1,:,:]
clustProbOBC = None
gc.collect()
print('freed up clustProbOBC')
sys.stdout.flush()
paramsStruct = dict(clustProbBC=clustProbBC,
thetas=thetas, variances=variances,
subShiftsLong=subShiftsLong, plotTrajParams=self.params['plotTrajParams'])
pickle.dump(paramsStruct, open(paramsDataFile, 'wb'), protocol=pickle.HIGHEST_PROTOCOL)
elif runPart[1] == 'L':
dataStruct = pickle.load(open(paramsDataFile, 'rb'))
# dataStruct['plotTrajParams'] = self.params['plotTrajParams']
# pickle.dump(dataStruct, open(paramsDataFile, 'wb'), protocol=pickle.HIGHEST_PROTOCOL)
# print(asdsa)
clustProbBC = dataStruct['clustProbBC']
thetas = dataStruct['thetas']
variances = dataStruct['variances']
subShiftsLong = dataStruct['subShiftsLong']
elif runPart[1] == 'Non-enforcing':
if os.path.isfile(paramsDataFile):
dataStruct = pickle.load(open(paramsDataFile, 'rb'))
if 'clustProbBC' in dataStruct.keys():
clustProbBC = dataStruct['clustProbBC']
else:
print('dataStruct.keys()', dataStruct.keys())
clustProbBC = dataStruct['clustProbOBC'][-1,:,:]
print('clustProbBC.shape', clustProbBC.shape)
#print('dataStruct[clustProbOBC].shape', dataStruct['clustProbOBC'].shape)
thetas = dataStruct['thetas']
variances = dataStruct['variances']
subShiftsLong = dataStruct['subShiftsLong']
else:
print('no file found at runPart[2] for %s' % self.outFolder)
return None
else:
raise ValueError('runpart needs to be either R, L or Non-enforcing')
self.thetas = thetas[nrOuterIter - 1, nrInnerIter - 1, :, :]
self.variances = variances[nrOuterIter - 1, nrInnerIter - 1, :]
self.subShifts = subShiftsLong[nrOuterIter - 1, nrInnerIter - 1, :, :]
self.clustProb = clustProbBC
assert len(self.clustProb.shape) == 2
clustProbBCColNorm = self.clustProb / np.sum(self.clustProb, 0)[None, :]
subShiftsCross = self.subShifts[uniquePartCodeInverse, :]
dpsCross = VoxelDPM.calcDps(subShiftsCross, crossAge1array)
# import pdb
# pdb.set_trace()
self.dpsLongFirstVisit = VoxelDPM.calcDps(self.subShifts, ageFirstVisitLong1array)
print('subShiftsLong.shape', subShiftsLong.shape)
aic = np.nan
bic = np.nan
lik = np.nan
bicFile = '%s/fitMetrics.npz' % self.outFolder
if runPart[2] == 'R':
lik, bic, aic = self.calcModelLogLikFromEnergy(crossData, dpsCross, self.thetas, self.variances,
self.clustProb, nrSubjLong)
dataStruct = dict(lik=lik, bic = bic, aic = aic)
pickle.dump(dataStruct, open(bicFile, 'wb'), protocol=pickle.HIGHEST_PROTOCOL)
elif runPart[2] == 'Non-enforcing':
if os.path.isfile(bicFile):
dataStruct = pickle.load(open(bicFile, 'rb'))
aic = dataStruct['aic']
bic = dataStruct['bic']
lik = dataStruct['lik']
# lik2 = self.calcModelLogLik(crossData, dpsCross, self.thetas, self.variances, self.clustProb)
# import pdb
# pdb.set_trace()
resStruct = dict(longData=longData, longDiagAllTmpts=longDiagAllTmpts, longDiag=longDiag,
longScanTimepts=longScanTimepts, longPartCode=longPartCode, longAgeAtScan=longAgeAtScan,
uniquePartCodeInverse=uniquePartCodeInverse, crossData=crossData, crossDiag=crossDiag,
scanTimepts=scanTimepts, crossPartCode=crossPartCode, crossAgeAtScan=crossAgeAtScan,
longAge1array=longAge1array, crossAge1array=crossAge1array, thetas=self.thetas,
variances=self.variances, subShifts=self.subShifts, clustProb=self.clustProb,
clustProbBCColNorm=clustProbBCColNorm, subShiftsCross=subShiftsCross,dpsCross=dpsCross,
ageFirstVisitLong1array=ageFirstVisitLong1array, lik=lik, bic=bic, aic=aic,
uniquePartCode=uniquePartCode, outFolder=self.outFolder)
# otherVariables = dict()
self.postFitAnalysis(runPart, crossData, crossDiag, dpsCross, clustProbBCColNorm, paramsDataFile, resStruct)
return resStruct
def calcPredScores(self, testInputInd, testPredInd, filteredParams):
''' Predict future biomarker values given two initial scans.
Compare accuracy with actual measured values. '''
# print('filteredParams[partCode][testInputInd]',
# filteredParams['partCode'][testInputInd])
# print('filteredParams[partCode][testPredInd]',
# filteredParams['partCode'][testPredInd])
# print('filteredParams[scanTimepts][testInputInd]',
# filteredParams['scanTimepts'][testInputInd])
# print('filteredParams[scanTimepts][testPredInd]',
# filteredParams['scanTimepts'][testPredInd])
partCodeTestInitial = filteredParams['partCode'][testInputInd]
unqPartCode = np.unique(partCodeTestInitial)
maskTwoMore = np.zeros(testInputInd.shape, bool)
for p in range(unqPartCode.shape[0]):
if np.sum(partCodeTestInitial == unqPartCode[p]) >= 2:
maskTwoMore[filteredParams['partCode'] == unqPartCode[p]] = True
print('maskTwoMore', maskTwoMore)
print('filteredParams[partCode]', filteredParams['partCode'])
print('testInputInd', np.sum(testInputInd))
testInputInd = np.logical_and(testInputInd, maskTwoMore)
print('testInputInd', np.sum(testInputInd))
print('testPredInd', np.sum(testPredInd))
# print(adsa)
# set fixed speed for predicting biomarker values, otherwise 1-2 subjects will get high, negative alphas
# due to noise in measurements
self.params['fixSpeed'] = True
maxLikStages, _, _, _, _, otherParams = self.stageSubjects(testInputInd)
# maxLikStagesFS, _, _, _, _, otherParamsFS = self.stageSubjects(testInputInd, fixSpeed=True)
subShiftsLong = otherParams['subShiftsLong']
subShiftsCross = otherParams['subShiftsCross']
testInputPartCode = otherParams['longPartCode']
testInputDPS = self.calcDpsNo1array(subShiftsCross,
filteredParams['ageAtScan'][testInputInd])
print('maxLikStages', maxLikStages)
print('subShiftsLong', subShiftsLong)
# print('maxLikStagesFS', maxLikStagesFS)
# print('subShiftsLongFS', otherParamsFS['subShiftsLong'])
# import pdb
# pdb.set_trace()
testPredCrossPartCode = filteredParams['partCode'][testPredInd]
testPredCrossAge = filteredParams['ageAtScan'][testPredInd]
testPredSubShifts = np.zeros((testPredCrossAge.shape[0], 2), float)
for p in range(testInputPartCode.shape[0]):
matchInd = np.in1d(testPredCrossPartCode, testInputPartCode[p])
print('subShiftsLong.shape', subShiftsLong.shape)
print('testPredSubShifts[matchInd,:].shape', testPredSubShifts[matchInd, :].shape)
testPredSubShifts[matchInd, :] = subShiftsLong[p, :]
print('testInputPartCode', testInputPartCode)
print('testPredCrossPartCode', testPredCrossPartCode)
print('testPredCrossAge', testPredCrossAge)
print('testPredSubShifts', testPredSubShifts)
testPredDPS = self.calcDpsNo1array(testPredSubShifts, testPredCrossAge)
testPredData = filteredParams['data'][testPredInd]
nrSubjPredCross = testPredDPS.shape[0]
nrBiomk, nrClust = self.clustProb.shape
testPredClust = np.zeros((nrSubjPredCross, nrClust), float)
for c in range(nrClust):
testPredClust[:, c] = self.trajFunc(testPredDPS, self.thetas[c, :])
assert (np.abs(np.sum(self.clustProb, axis=1) - 1) < 0.001).all()
print('testPredDPS', testPredDPS)
print('testInputDPS', testInputDPS)
# actual biomk predictions for each subject and each biomk
testPredPredPB = np.dot(testPredClust, self.clustProb.T)
dataPredDiff = (testPredPredPB - testPredData)
RMSE = np.sqrt(np.mean((dataPredDiff ** 2).astype(np.longdouble), axis=(0, 1)))
RMSEfromZero = np.sqrt(np.mean((testPredData ** 2).astype(np.longdouble), axis=(0, 1)))
print('dataPredDiff[::10000,::10000]', dataPredDiff[::10000, ::10000])
print('RMSE', RMSE)
print('RMSEfromZero', RMSEfromZero)
norm1Diff = np.sum(np.abs(dataPredDiff).astype(np.longdouble), axis=(0, 1))
norm1DiffFromZero = np.sum(np.abs(testPredData).astype(np.longdouble), axis=(0, 1))
print('norm1Diff', norm1Diff)
print('norm1DiffFromZero', norm1DiffFromZero)
testData = np.concatenate((filteredParams['data'][testInputInd],
filteredParams['data'][testPredInd]), axis=0)
testDiag = np.concatenate((filteredParams['diag'][testInputInd],
filteredParams['diag'][testPredInd]), axis=0)
testDPSCross = np.concatenate((testInputDPS, testPredDPS))
testScanTimepts = np.concatenate((filteredParams['scanTimepts'][testInputInd],
filteredParams['scanTimepts'][testPredInd]), axis=0)
testPartCode = np.concatenate((filteredParams['partCode'][testInputInd],
filteredParams['partCode'][testPredInd]), axis=0)
testAgeAtScan = np.concatenate((filteredParams['ageAtScan'][testInputInd],
filteredParams['ageAtScan'][testPredInd]), axis=0)
(longData, longDiagAllTmpts, longDiag, longScanTimepts, longPartCode, longAgeAtScan,
uniquePartCodeInverse, crossData, crossDiag, scanTimepts, crossPartCode, crossAgeAtScan, uniquePartCode) = \
self.createLongData(testData, testDiag, testScanTimepts, testPartCode, testAgeAtScan)
dpsLongNew = self.makeLongArray(testDPSCross, testScanTimepts, testPartCode,
np.unique(testPartCode))
print(testData.shape[0], testDiag.shape[0], testDPSCross.shape[0])
assert testData.shape[0] == testDiag.shape[0] == testDPSCross.shape[0]
print(len(longData), longDiag.shape[0], len(dpsLongNew))
assert len(longData) == longDiag.shape[0] == len(dpsLongNew)
for p in range(len(longData)):
print('%d' % p, 'dps', dpsLongNew[p], 'subShifts ', subShiftsLong[p, :])
# pl.figure(3)
clustProbBCColNorm = self.clustProb / np.sum(self.clustProb, 0)[None, :]
fig = self.plotterObj.plotTrajWeightedDataMean(testData, testDiag, testDPSCross,
longData, longDiag, dpsLongNew, self.thetas, self.variances,
clustProbBCColNorm, self.params['plotTrajParams'], self.trajFunc, orderClust=True,
replaceFigMode=True)
fig.savefig('%s/predScoresTestDataTraj_%s.png' %
(self.outFolder, '_'.join(self.expName.split('/'))), dpi=100)
# plot the mean difference and individual differences
# meanAbsDiffB = np.sum(np.abs(dataPredDiff), axis=0)
# self.plotterObj.plotDiffs(meanAbsDiffB, self.params['plotTrajParams'],
# filePathNoExt='%s/diffsMean_%s' % (self.outFolder, '_'.join(self.expName.split('/'))))
# nrSubjTestPred = dataPredDiff.shape[0]
# for p in range(nrSubjTestPred):
# absDiffB = np.abs(dataPredDiff[p,:])
# self.plotterObj.plotDiffs(absDiffB, self.params['plotTrajParams'],
# filePathNoExt='%s/diffs_p%d_%s' % (self.outFolder, p, '_'.join(self.expName.split('/'))))
# print(adsas)
return RMSE, testPredPredPB, testPredData
@staticmethod
def makeShiftsIdentif(subShiftsLong, ageFirstVisitLong1array, longDiag):
# make the subject shifts identifiable so that the dps_score(controls) ~ N(0,1) (as in Jedynak, 2012)
dpsLong = VoxelDPM.calcDps(subShiftsLong, ageFirstVisitLong1array)
dpsCTL = dpsLong[longDiag == CTL]
muCTL = np.mean(dpsCTL)
sigmaCTL = np.std(dpsCTL)
# need to do: alphas = alphas / std_ctl betas = (betas - mean_clt)/std_ctl
subShiftsLong[:, 1] -= muCTL # betas = (betas - mean_clt)
subShiftsLong[:, :] /= sigmaCTL # alphas = alphas / std_ctl betas = betas/std_ctl
shiftTransform = [muCTL, sigmaCTL]
return subShiftsLong, shiftTransform
@staticmethod
def makeThetasIdentif(thetas, shiftTransform):
"""
Make the parameters theta so that b > 0. Since most traj will be decreasing,
we will have that a < 0 and d > 0. The minimum will be a, and maximum will be a+d
shiftTransform = [muCTL, sigmaCTL] """
nrClust = thetas.shape[0]
for c in range(nrClust):
if thetas[c, 1] < 0:
# d_k = d_k + a_k
thetas[c, 3] = thetas[c, 3] + thetas[c, 0]
# a_k = -a_k b_k = -b_k
thetas[c, [0, 1]] = -thetas[c, [0, 1]]
#re-transform the parameters using the DPS transformation
# thetas[:,1] /= shiftTransform[1] # b = b / sigma
# thetas[:,2] = shiftTransform[0] + shiftTransform[1] * thetas[:,2] # c = mu + sigma*c
thetas[:, 1] *= shiftTransform[1] # b = b * sigma
thetas[:, 2] = (thetas[:, 2] - shiftTransform[0])/shiftTransform[1] # c = (c - mu) / sigma
return thetas
def initTrajParams(self, crossData, crossDiag, clustProbBC, crossAgeAtScan, subShiftsLong,
uniquePartCodeInverse, crossAge1array, extraRangeFactor):
assert not np.isnan(crossData).any()
assert not np.isnan(crossDiag).any()
assert not np.isnan(clustProbBC).any()
assert not np.isnan(crossAgeAtScan).any()
assert not np.isnan(subShiftsLong).any()
assert not np.isnan(uniquePartCodeInverse).any()
assert not np.isnan(crossAge1array).any()
nrClust = clustProbBC.shape[1]
initSubShiftsCross = subShiftsLong[uniquePartCodeInverse, :]
variances = np.zeros(nrClust, float)
dpsCross = VoxelDPM.calcDps(initSubShiftsCross, crossAge1array)
# calculate average voxel value for each (subject, cluster) pair, use them to initialise theta
clustProbColNorm = clustProbBC / np.sum(clustProbBC, 0)[None, :] # p(z_t = c) / (\sum_{t=1}^T) p(z_t = c)
avgVoxelSC = np.dot(crossData, clustProbColNorm) # SUBJECTS x CLUSTER array of avg voxel values
thetas = np.zeros((nrClust, 4), float)
minMaxRange = np.max(avgVoxelSC, 0) - np.min(avgVoxelSC, 0)
assert (1 <= self.params['patientID'] <= 3)
# estimate biomk direction from data, i.e. compare mean voxel value for CTL vs AD
# meanBiomkPAT = np.mean(crossData[crossDiag == self.params['patientID'],:],axis=(0,1))
# meanBiomkCTL = np.mean(crossData[crossDiag == CTL, :], axis=(0, 1))
# if meanBiomkCTL < meanBiomkPAT:
# estimSlopeSign = 1 # in case of amyloid PET
# else:
# estimSlopeSign = -1 # in case of cortical thickness
print('crossDiag', crossDiag, 'patientID', self.params['patientID'])
dpsCrossPat = np.std(dpsCross[crossDiag == self.params['patientID']])
assert (dpsCrossPat != 0 and not np.isnan(dpsCrossPat))
thetas[:, 3] = np.min(avgVoxelSC, 0) - minMaxRange * extraRangeFactor / 10 # dk
thetas[:, 0] = minMaxRange + minMaxRange * 2 * extraRangeFactor / 10 # ak = (dk + ak) - dk
thetas[:, 1] = -16 / (thetas[:, 0] * np.std(dpsCross[crossDiag == self.params['patientID']])) # bk = 4/ak so that slope = bk*ak/4 = -1
thetas[:, 2] = np.mean(crossAgeAtScan) # ck
thetas = self.makeThetasIdentif(thetas, shiftTransform=[0, 1])
print('thetas', thetas)
# print(adas)
if self.params['informPrior']:
""" WARNING. consider sigmoid with b >0, which means that minimum is a < 0, maximum is a+d.
set prior for sigmoidal params [a,b,c,d] with minimum a, maximum a+d, slope a*b/4
and slope maximum attained at center c
f(s|theta = [a,b,c,d]) = a/(1+exp(-b(s-c)))+d
These priors are very weak, but data driven. While data-driven priors can be
controversial, it is clearly better than fixing some parameters using a
data-driven estimate.
"""
avgTheta = np.mean(thetas,axis=0) # find an average sigmoid for all voxels
mu_a = avgTheta[0]
mu_b = avgTheta[1]
mu_c = avgTheta[2]
mu_d = avgTheta[3]
std_a = np.mean(minMaxRange)/2 # more informative prior
std_b = 100 # set large number to make non-informative
std_c = 100 # set large number to make non-informative
std_d = std_a # more informative prior
self.paramsPriorTheta = [mu_a, std_a, mu_b, std_b, mu_c, std_c, mu_d, std_d]
for c in range(nrClust):
# set zero subj because it's only used for DOF correction of subject shifts, and so far no shifts have been estimated.
variances[c] = 1/3*self.estimVariance(crossData, dpsCross,
clustProbColNorm[:,c], thetas[c,:], nrSubjLong=0)
# print('std dpsCrossPat', np.std(dpsCross[crossDiag == self.params['patientID']]))
# print('thetas', thetas, variances, crossData.shape, clustProbBC.shape)
#print(asdsa)
return thetas, variances
def calcModelLogLik(self, data, dpsCross, thetas, variances, _):
""" computed the full model log likelihood, used for checking if it increases during EM and for BIC"""
nrBiomk = data.shape[1]
nrClust = thetas.shape[0]
prodLikBC = np.zeros((nrBiomk, nrClust), float)
for c in range(nrClust):
sqErrorsSB = np.power((data - self.trajFunc(dpsCross, thetas[c,:])[:, None]), 2) # taken from estimTheta
pdfSB = (2*math.pi*variances[c])**(-1) * np.exp(-(2*variances[c])**(-1) * sqErrorsSB)
#np.prod(pdfSB, axis=0)
prodLikBC[:,c] = (1/nrClust) * np.prod(pdfSB, axis=0) # it is product here as the log doesn't go this far
# prodLikBC[b,c] = (1/nrClust) * np.prod(scipy.stats.norm(data[:,b], loc=self.trajFunc(dpsCross, thetas[c,:]),
# scale=variances[c]))
logLik = np.sum(np.log(np.sum(prodLikBC, axis=1)))
print('logLik', logLik)
import pdb
pdb.set_trace()
return logLik
def calcModelLogLikFromEnergy(self, data, dpsCross, thetas, variances, clustProbBC, nrSubjLong):
""" computed the full model log likelihood from the Energy (used in EM) and Entropy over Z"""
nrBiomk = data.shape[1]
nrClust = thetas.shape[0]
# first calculate the energy term used in EM
prodLogLikBC = np.zeros((nrBiomk, nrClust), float)
for c in range(nrClust):
sqErrorsSB = np.power((data - self.trajFunc(dpsCross, thetas[c,:])[:, None]), 2) # taken from estimTheta
logpdfSB = -np.log(2*math.pi*variances[c])/2 - (2*variances[c])**(-1) * sqErrorsSB
#np.prod(pdfSB, axis=0)
prodLogLikBC[:,c] = np.sum(clustProbBC[:,c][None,:] * np.sum(logpdfSB, axis=0), axis=0)
# prodLikBC[b,c] = (1/nrClust) * np.prod(scipy.stats.norm(data[:,b], loc=self.trajFunc(dpsCross, thetas[c,:]),
# scale=variances[c]))
logLikEnergy = np.sum(prodLogLikBC, axis=(0,1))
# calculate the entropy term
logClustProbBC = np.nan_to_num(np.log(clustProbBC))
# logClustProbBC[np.isnan(logClustProbBC)] = 0
logLikEntropy = -np.sum(clustProbBC * logClustProbBC, axis=(0,1))
logLik = logLikEnergy + logLikEntropy
print('logLikEnergy', logLikEnergy)
print('logLikEntropy', logLikEntropy)
print('logLik', logLik)
# import pdb
# pdb.set_trace()
# calculate BIC and AIC
nrDataPoints = data.shape[0]*data.shape[1]
# should I include the clustering prop in the nr Free params? No as they are marginalised in the model
nrFreeParams = nrClust * (thetas.shape[1]+1) + 2*nrSubjLong
# nrFreeParams = nrFreeParams + clustProbBC.shape[0] * clustProbBC.shape[1]
bic = -2*logLik + nrFreeParams * np.log(nrDataPoints)
aic = -2*logLik + nrFreeParams * 2
print('bic')
return logLik, bic, aic
def estimThetas(self, data, dpsCross, clustProbColNormB, prevTheta, nrSubjLong):
'''for sigmoidal trajectories, only fit slope and center, leave min and max fixed'''
recompThetaSig = lambda thetaFull, theta12: [thetaFull[0],theta12[0],theta12[1],thetaFull[3]]
objFunc = lambda theta12: self.objFunTheta(recompThetaSig(prevTheta, theta12),
data, dpsCross, clustProbColNormB)[0]
# objFuncDeriv = lambda theta12: self.objFunThetaDeriv(recompThetaSig(prevTheta, theta12),
# data, dpsCross, clustProbColNormB)[[1, 2]]
initTheta12 = prevTheta[[1,2]]
# res = scipy.optimize.minimize(objFunc, initTheta12, method='BFGS', jac=objFuncDeriv,
# options={'gtol': 1e-8, 'disp': True, 'maxiter':70})
res = scipy.optimize.minimize(objFunc, initTheta12, method='Nelder-Mead',
options={'xtol': 1e-8, 'disp': True, 'maxiter':70})
# print(res)
# print('-----------------------')
# print(res2)
# print(res.x, res2.x, initTheta12)
# print(objFunc(res.x),objFunc(res2.x), objFunc(initTheta12))
#
# assert(np.abs(objFunc(res.x) - objFunc(res2.x)) < 0.001)
newTheta = recompThetaSig(prevTheta, res.x)
#print(newTheta)
newVariance = self.estimVariance(data, dpsCross, clustProbColNormB, newTheta, nrSubjLong)
return newTheta, newVariance
def sampleThetas(self, data, dpsCross, clustProbB, initTheta, initVariance, nrSubjLong, nrSamples, propCovMat):
objFunc = lambda params: self.objFunThetaLogL(params[:-1], params[-1], data, dpsCross, clustProbB)
nrAccSamples = 0
currSample = np.array(list(initTheta) + [initVariance])
paramsSamples = np.zeros((nrSamples, initTheta.shape[0] + 1), float)
paramsSamples[0] = currSample
currLogL = objFunc(currSample)
logL = np.zeros((nrSamples, 1), float)
logL[0] = currLogL
stds = np.sqrt(np.diag(propCovMat))+0.000001
print('stds', stds)
import time
for s in range(1,nrSamples):
print(s)
newSample = np.random.multivariate_normal(currSample, propCovMat)
# newSample = np.array([np.random.normal(currSample[i], stds[i]) for i in range(currSample.shape[0])])
newLogL = objFunc(newSample)
# print(np.log(2))
# print(np.random.rand())
# print(np.log(np.random.rand))
if newLogL - currLogL > np.log(np.random.rand()):
# accept sample
currSample = newSample
currLogL = newLogL
nrAccSamples += 1
paramsSamples[s, :] = currSample
logL[s,:] = currLogL
print('currSample', currSample, 'logL', logL[s])
accRatio = nrAccSamples/nrSamples
print('logL ', logL, 'accRatio ', accRatio)
return paramsSamples[:,:-1], paramsSamples[:,-1]
def objFunThetaLogL(self, theta, variance, data, dpsCross, clustProbB):
# print(theta)
# print(variance)
sqErrorsSB = -np.log(2*math.pi*variance)/2 - (1/(2*variance))*np.power((data - self.trajFunc(dpsCross, theta)[:, None]),2)
meanLogL = np.sum(clustProbB[None,:] * sqErrorsSB, (0,1))
return meanLogL
def objFunTheta(self, theta, data, dpsCross, clustProbB):
#print(subShiftsCross.shape, crossAge1array.shape, dps.shape, theta.shape, self.trajFunc(dps, theta).shape, data.shape)
#print(test2)
# currTheta = prevTheta
# currTheta[1:2] = theta12
# print('theta', theta)
sqErrorsSB = np.power((data - self.trajFunc(dpsCross, theta)[:, None]),2)
meanSSD = np.sum(np.multiply(clustProbB[None,:], sqErrorsSB), (0,1))
#print("meanSSD", meanSSD, "clustProbB", clustProbB, "sqErrorsSB", sqErrorsSB)
#print("ssd/nrSubj", meanSSD/data.shape[0])
#print(asdsa)
logPriorTheta = self.logPriorThetaFunc(theta, self.paramsPriorTheta)
return meanSSD - logPriorTheta, meanSSD
def objFunThetaDeriv(self, theta, dataSB, dpsCrossS, clustProbB):
aK = theta[0]
bK = theta[1]
cK = theta[2]
errorsSB = 2*(dataSB - self.trajFunc(dpsCrossS, theta)[:, None])
# -ak (1+exp(-bk(alpha_i * t_ij + beta_i - ck)))^-2
derivTerm1S = -aK * np.power(1 + np.exp(-bK*(dpsCrossS - cK)),-2)
# *= exp(-bk(alpha_i * t_ij + beta_i - ck))
derivTerm12S = derivTerm1S * np.exp(-bK * (dpsCrossS - cK))
akDerivTermS = -np.power(1 + np.exp(-bK*(dpsCrossS - cK)),-1)
bkDerivTermS = -derivTerm12S * -(dpsCrossS - cK)
ckDerivTermS = -derivTerm12S * bK
dkDerivTermS = -np.array(1)
akSqErrorDerivSB = errorsSB * akDerivTermS[:,None]
bkSqErrorDerivSB = errorsSB * bkDerivTermS[:,None]
ckSqErrorDerivSB = errorsSB * ckDerivTermS[:,None]
dkSqErrorDerivSB = errorsSB * dkDerivTermS
akMeanSEDeriv = np.sum(clustProbB[None,:] * akSqErrorDerivSB, (0,1))
bkMeanSEDeriv = np.sum(clustProbB[None, :] * bkSqErrorDerivSB, (0, 1))
ckMeanSEDeriv = np.sum(clustProbB[None, :] * ckSqErrorDerivSB, (0, 1))
dkMeanSEDeriv = np.sum(clustProbB[None, :] * dkSqErrorDerivSB, (0, 1))
return np.array([akMeanSEDeriv, bkMeanSEDeriv, ckMeanSEDeriv, dkMeanSEDeriv])
def estimShifts(self, dataOneSubj, thetas, variances, ageOneSubj1array, clustProb, prevSubShift,
prevSubShiftAvg, fixSpeed):
if fixSpeed:
return self.estimShiftsBetaOnly(dataOneSubj, thetas, variances, ageOneSubj1array, clustProb,
prevSubShift)
objFunc = lambda shift: self.objFunShift(shift, dataOneSubj, thetas, variances, ageOneSubj1array, clustProb)
# objFuncDeriv = lambda shift: self.objFunShiftDeriv(shift, dataOneSubj, thetas, variances, ageOneSubj1array,
# clustProb)
# res = scipy.optimize.minimize(objFunc, prevSubShift, method='BFGS', jac=objFuncDeriv,
# options={'gtol': 1e-8, 'disp': True})
res = scipy.optimize.minimize(objFunc, prevSubShift, method='Nelder-Mead',
options={'xtol': 1e-8, 'disp': True, 'maxiter':70})
newShift = res.x
if newShift[0] < -400: # and -67
import pdb
pdb.set_trace()
return newShift
def estimShiftsBetaOnly(self, dataOneSubj, thetas, variances, ageOneSubj1array, clustProb, prevSubShift):
alpha = prevSubShift[0]
reconstructShifts = lambda beta: np.array([alpha, beta])
objFunc = lambda beta: self.objFunShift(reconstructShifts(beta), dataOneSubj, thetas,
variances, ageOneSubj1array, clustProb)
initBeta = prevSubShift[1]
print('ageOneSubj1array', ageOneSubj1array)
print(objFunc(initBeta))
import pdb
pdb.set_trace()
res = scipy.optimize.minimize(objFunc, initBeta, method='Nelder-Mead',
options={'xtol': 1e-8, 'disp': True, 'maxiter':70})
newShift = reconstructShifts(res.x)
return newShift
def objFunShift(self, shift, dataOneSubj, thetas, variances, ageOneSubj1array, clustProb):
dps = np.sum(np.multiply(shift, ageOneSubj1array),1)
nrClust = clustProb.shape[1]
#for tp in range(dataOneSubj.shape[0]):
sumSSD = 0
for k in range(nrClust):
sqErrorsB = np.sum(np.power((dataOneSubj - self.trajFunc(dps, thetas[k,:])[:, None]),2), axis=0)
sumSSD += np.sum(np.multiply(sqErrorsB, clustProb[:,k]))/(2*variances[k])
logPriorShift = self.logPriorShiftFunc(shift, self.paramsPriorShift)
# print('logPriorShift', logPriorShift, 'sumSSD', sumSSD)
# print(sumSSD)
# if shift[0] < -400: # and -67
# import pdb
# pdb.set_trace()
return sumSSD - logPriorShift
def objFunShiftDeriv(self, shift, dataOneSubjTB, thetas, variances, ageOneSubj1array, clustProb):
aK = thetas[:, 0]
bK = thetas[:, 1]
cK = thetas[:, 2]
dpsT = np.sum(shift * ageOneSubj1array,1)
#print(ageOneSubj1array.shape)
nrClust = clustProb.shape[1]
#for tp in range(dataOneSubj.shape[0]):
sumSqErrorDerivalpha = 0
sumSqErrorDerivbeta = 0
for k in range(nrClust):
errorsTB = dataOneSubjTB - self.trajFunc(dpsT, thetas[k, :])[:, None]
# ak*(1+exp(-bk(alpha_i * t_ij + beta_i - ck)))^-2
derivTerm1T = aK[k]*np.power((1+np.exp(-bK[k]*(dpsT-cK[k]))),-2)
# exp(-bk(alpha_i * t_ij + beta_i - ck))
derivTerm2T = derivTerm1T * np.exp(-bK[k]*(dpsT-cK[k]))
# *= -bk * t_ij
alphaDerivTermT = derivTerm2T * (-bK[k] * ageOneSubj1array[:,0])
# *= -bk
betaDerivTermT = derivTerm2T * -bK[k]
alphaSqErrorDerivTB = (2 * errorsTB * alphaDerivTermT[:,None])
betaSqErrorDerivTB = (2 * errorsTB * betaDerivTermT[:,None])
sumSqErrorDerivalpha += np.sum(np.sum(alphaSqErrorDerivTB, 0) * clustProb[:,k])/ (2*variances[k])
sumSqErrorDerivbeta += np.sum(np.sum(betaSqErrorDerivTB, 0) * clustProb[:, k]) / (2*variances[k])
logPriorShiftDeriv = self.logPriorShiftFuncDeriv(shift, self.paramsPriorShift)
if sumSqErrorDerivalpha == 0:
pdb.set_trace()
return np.array([sumSqErrorDerivalpha - logPriorShiftDeriv[0], sumSqErrorDerivbeta - logPriorShiftDeriv[1]])
def recompResponsib(self, crossData, longData, crossAge1array, thetas, variances, subShiftsCross,
trajFunc, prevClustProbBC, scanTimepts, partCode, uniquePartCode):
# I can loop over all the subjects and timepoints and add matrices log p(z_t | k) = log p(z_t | k, sub1,
# tmp1) + log p(z_t | k, sub1, tmp2) + ...
(nrSubj, nrBiomk) = crossData.shape
nrClust = thetas.shape[0]
dps = VoxelDPM.calcDps(subShiftsCross, crossAge1array)
fSK = np.zeros((nrSubj, nrClust), float)
for k in range(nrClust):
fSK[:,k] = trajFunc(dps,thetas[k,:])
logClustProb = np.zeros((nrBiomk,nrClust), float)
clustProb = np.zeros((nrBiomk, nrClust), float)
tmpSSD = np.zeros((nrBiomk, nrClust), float)
for k in range(nrClust):
tmpSSD[:,k] = np.sum(np.power(crossData - fSK[:,k][:, None], 2), 0) # sum across subjects, left with 1 x NR_BIOMK array
assert(tmpSSD[:,k].shape[0] == nrBiomk)
logClustProb[:,k] = -tmpSSD[:,k]/(2*variances[k]) - np.log(2*math.pi*variances[k])*nrSubj/2
vertexNr = 755
print('tmpSSD[vertexNr,:]', tmpSSD[vertexNr,:]) # good
print('logClustProb[vertexNr,:]', logClustProb[vertexNr,:]) # bad
for k in range(nrClust):
expDiffs = np.power(np.e,logClustProb - logClustProb[:, k][:, None])
clustProb[:,k] = np.divide(1, np.sum(expDiffs, axis=1))
for c in range(nrClust):
print('sum%d' % c, np.sum(clustProb[:,c]))
# import pdb
# pdb.set_trace()
return clustProb, crossData, longData