-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCloMu.py
1530 lines (998 loc) · 49.2 KB
/
CloMu.py
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 copy
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import grad
from torch.optim import Optimizer
import sys
import glob
import os
import numpy as np
def loadnpz(name, allow_pickle=False):
#This simple function more easily loads in compressed numpy files.
if allow_pickle:
data = np.load(name, allow_pickle=True)
else:
data = np.load(name)
data = data.f.arr_0
return data
def loadEither(name):
if name[-1] == 'z':
return loadnpz(name)
else:
return np.load(name)
class MutationModel(nn.Module):
def __init__(self, M):
super(MutationModel, self).__init__()
self.M = M
L = 5
#L = 10
#L2 = 2
#self.conv1 = torch.nn.Conv1d(14, mN1_1, 1)
self.nonlin = torch.tanh
#self.lin0 = torch.nn.Linear(L, L)
#print (M)
#quit()
self.lin1 = torch.nn.Linear(M+20, L)
self.lin2 = torch.nn.Linear(L, M)
#self.linI = torch.nn.Linear(1, 1)
####self.linM = torch.nn.Linear(L, L)
#self.linM1 = torch.nn.Linear(L1, L2)
#self.linM2 = torch.nn.Linear(L2, L1)
#self.linP = torch.nn.Linear(1, 20)
#self.linSum = torch.nn.Linear(2, L)
#self.linBaseline = torch.nn.Linear(L, 1)
def forward(self, x):
#print (x.shape)
#x = self.lin1(x)
#x = self.lin2(x)
xSum = torch.sum(x, dim=1)#.reshape((-1, 1))
xSum2 = torch.zeros((x.shape[0], 20))
xSum2[np.arange(x.shape[0]), xSum.long()] = 1
#x = x * 0
x = torch.cat((x, xSum2), dim=1)
x = self.lin1(x)
x1 = x[:, 0].repeat_interleave(self.M).reshape((x.shape[0], self.M) )
####x = self.linM(x)
####x = self.nonlin(x)
x = self.nonlin(x)
xNP = x.data.numpy()
#x = self.nonlin(x)
#plt.plot(xNP)
#plt.scatter(xNP[:, 2], xNP[:, 4])
#plt.show()
#quit()
#x = self.linM(x)
#x = self.nonlin(x)
#x = self.linM2(x)
#x = self.nonlin(x)
x = self.lin2(x)
#x = x * 0
x = x + x1
#shape1 = x.shape
return x, xNP
class MutationModel2(nn.Module):
def __init__(self, M):
super(MutationModel2, self).__init__()
self.M = M
L = 10
#self.lin1 = torch.nn.Linear(M+20, M)
self.lin1 = torch.nn.Linear(M, M)
def forward(self, x):
x = x.clone()
x = self.lin1(x)
xNP = x.data.numpy()
return x, xNP
def uniqueValMaker(X):
_, vals1 = np.unique(X[:, 0], return_inverse=True)
for a in range(1, X.shape[1]):
vals2 = np.copy(X[:, a])
vals2_unique, vals2 = np.unique(vals2, return_inverse=True)
vals1 = (vals1 * vals2_unique.shape[0]) + vals2
_, vals1 = np.unique(vals1, return_inverse=True)
return vals1
def addFromLog(array0):
#Just a basic function that hangles addition of logs efficiently
array = np.array(array0)
array_max = np.max(array, axis=0)
for a in range(0, array.shape[0]):
array[a] = array[a] - array_max
array = np.exp(array)
array = np.sum(array, axis=0)
array = np.log(array)
array = array + array_max
return array
def doChoice(x):
#This is a simple function that selects an option from a probability distribution given by x.
x = np.cumsum(x, axis=1) #This makes the probability cummulative
randVal = np.random.random(size=x.shape[0])
randVal = randVal.repeat(x.shape[1]).reshape(x.shape)
x = randVal - x
x2 = np.zeros(x.shape)
x2[x > 0] = 1
x2[x <= 0] = 0
x2[:, -1] = 0
x2 = np.sum(x2, axis=1)
return x2
def processTreeData(maxM, fileIn, mutationFile, infiniteSites=True, patientNames=''):
#This processes the data from a form using lists of trees to
#a form using numpy tensors.
#It also processes the mutation names into mutation numbers.
#print (fileIn)
#quit()
treeData = np.load(fileIn, allow_pickle=True)
MVal = 100
sampleInverse = np.zeros(100000)
treeLength = np.zeros(100000)
newTrees = np.zeros((100000, maxM, 2)).astype(str)
lastName = 'ZZZZZZZZZZZZZZZZ'
firstName = 'ZZZZZZZZZZ'
newTrees[:] = lastName
count1 = 0
for a in range(0, len(treeData)):
treeList = treeData[a]
treeList = np.array(list(treeList))
#print (treeList)
#quit()
if treeList.shape[1] <= maxM:
size1 = treeList.shape[0]
#print (treeList)
newTrees[count1:count1+size1, :treeList.shape[1]] = treeList
treeLength[count1:count1+size1] = treeList.shape[1]
sampleInverse[count1:count1+size1] = a
count1 += size1
newTrees = newTrees[:count1]
newTrees[newTrees == 'Root'] = 'GL'
if ('0' in newTrees) and not ('GL' in newTrees):
newTrees[newTrees == '0'] = firstName
else:
newTrees[newTrees == 'GL'] = firstName
treeLength = treeLength[:count1]
sampleInverse = sampleInverse[:count1]
shape1 = newTrees.shape
newTrees = newTrees.reshape((newTrees.size,))
uniqueMutation, newTrees = np.unique(newTrees, return_inverse=True)
#print (infiniteSites)
#quit()
uniqueMutation2 = []
for name in uniqueMutation:
if infiniteSites:
name1 = name
else:
name1 = name.split('_')[0]
uniqueMutation2.append(name1)
uniqueMutation2 = np.array(uniqueMutation2)
uniqueMutation2, mutationCategory = np.unique(uniqueMutation2, return_inverse=True)
np.save(mutationFile, uniqueMutation2[:-2])
M = uniqueMutation.shape[0] - 2
newTrees = newTrees.reshape(shape1)
if (lastName in uniqueMutation) and (lastName != uniqueMutation[-1]):
print ("Error in Mutation Name")
quit()
if patientNames != '':
np.save(patientNames, sampleInverse)
_, sampleInverse = np.unique(sampleInverse, return_inverse=True)
return newTrees, sampleInverse, mutationCategory, treeLength, uniqueMutation, M
def trainGroupModelTree(newTrees, sampleInverse, treeLength, mutationCategory, M, maxM, fileSave=False, baselineSave=False, usePurity=False, adjustProbability=True, trainSet=False, unknownRoot=False, regularizeFactor=0.02, iterations='default', verbose=False):
#This function trains a model to predict the probability of new mutations being added to clones,
#and therefore the probability of phylogeny trees generated through this process.
#This function differs from trainModelTree in that it uses groups of mutations rather than purely individual mutations.
#Because multiple mutations in the same group can be in a single tree, it must allow for a mutation group to be introduced
#multiple times in a single tree. This requires modifications of the trainModelTree code.
doTrainSet = not (type(trainSet) == type(False))
N1 = newTrees.shape[0]
N2 = int(np.max(sampleInverse) + 1)
M2 = np.unique(mutationCategory).shape[0] - 2
#This calculates the test set patients, as well as the training set trees (trainSet2)
if doTrainSet:
#trainSet = np.argwhere(np.isin(sampleInverse, trainSet))[:, 0]
testSet = np.argwhere(np.isin(np.arange(N2), trainSet) == False)[:, 0]
trainSet2 = np.argwhere(np.isin(sampleInverse, trainSet))[:, 0]
torch.autograd.set_detect_anomaly(True)
nonLin = True
#torch.autograd.set_detect_anomaly(True)
#model = MutationModel(M)
if nonLin:
model = MutationModel(M2)
else:
model = MutationModel2(M2)
#model = torch.load('./Models/savedModel.pt')
#model = torch.load('./Models/savedModel24.pt')
#N1 = 10000
nPrint = 100
#if adjustProbability:
#learningRate = 1e1
# learningRate = 1e0
#learningRate = 1e-1#-1 #1 #2
#else:
#learningRate = 1e-1#-2 #1
#learningRate = 2e0
#learningRate = 1e0
#learningRate = 2e-1
if nonLin:
learningRate = 3e-1
else:
#learningRate = 5e-1
learningRate = 1e0 #Standard version sep 22 2022
#learningRate = 2e0
optimizer = torch.optim.SGD(model.parameters(), lr = learningRate)
#learningRate = 1e-2#-1
#optimizer = torch.optim.Adam(model.parameters(), lr = learningRate)
if adjustProbability or True:
baseLine = np.ones(N1) * 0
#baseLine = np.load('./Models/baseline1.npy')
baseN = 10
accuracies = []
#iterNum = 20000
if nonLin:
#iterNum = 4000
iterNum = 10000 #Modified Oct 12 2022
else:
iterNum = 1000 #Only for TreeMHN #Standard version sep 22 2022
#iterNum = 2000
#iterNum = 4000
#iterNum = 5000
if iterations != 'default':
iterNum = iterations
for iter in range(0, iterNum):#301): #3000
doPrint = False
if iter % nPrint == 0:
doPrint = True
if doPrint:
print ('iteration ' + str(iter) + ' of ' + str(iterMax))
#This is initializing the edges of the generated trees
Edges = np.zeros((N1, maxM+1, 2))
Edges[:, 0, 1] = M
#This is initializing the clones for each possible phylogeny tree.
clones = torch.zeros((N1, maxM+1, M2))
#The edges remaining represent the edges which still need to be added
#in order to generate the correct tree. It is initialized as all
#of the edges in the tree.
edgesRemaining = np.copy(newTrees)
#edgesRemainingGroup is the remaining edges in terms of mutation groups rather than in terms
#of individual mutations.
edgesRemainingGroup = mutationCategory[edgesRemaining.astype(int)]
#This converts them to numerical incoding of edges.
edgesRemainingNum = (edgesRemaining[:, :, 0] * (M + 2)) + edgesRemainingGroup[:, :, 1]
#These are the log probability of the generation of the tree (theoretically)
#as well as the log probability of this way of generatating the tree,
#when we restrict the model to only generating this correct tree.
probLog1 = torch.zeros(N1)
probLog2 = torch.zeros(N1)
for a in range(0, maxM):
argsLength = np.argwhere(treeLength >= (a + 1))[:, 0]
M1 = a + 1
counter = np.arange(N1)
#This calculates the output of the model given the clones that exist.
clones1 = clones[:, :M1].reshape((N1 * M1, M2))
output, _ = model(clones1)
output = output.reshape((N1, M1 * M2))
output = torch.softmax(output, dim=1)
#This calculates the possible new mutations and clones for new mutations to be added to.
newStart = Edges[:, :M1, 1].repeat(M2).reshape((N1, M1 * M2))
newStartClone = np.arange(M1).repeat(N1*M2).reshape((M1, N1, M2))
newStartClone = np.swapaxes(newStartClone, 0, 1).reshape((N1, M1 * M2))
newEnd = np.arange(M2).repeat(N1*M1).reshape((M2, N1*M1)).T.reshape((N1, M1 * M2))
edgeNums = (newStart * (M + 2)) + newEnd
#This makes it so you can only add edges which are present in the correct tree.
validEndMask = np.zeros((N1, M1 * M2))
for b in range(0, N1):
validEndMask[b, np.isin(edgeNums[b], edgesRemainingNum[b])] = 1
#This removes the impossible choices, and then adjust the probability to still sum to 1.
output2 = output * torch.tensor(validEndMask).float()
output2_sum = torch.sum(output2, dim=1).repeat_interleave(M1*M2).reshape((N1, M1*M2))
output2 = output2 / output2_sum
#This makes a choice of clone to add a mutation as well as the mutation to be added based on the probabilities.
choiceNow = doChoice(output2.data.numpy()).astype(int)
printNum = 10
#This determines the probability of this specific step in the generation process, given this tree as
#the correct tree to be generated.
sampleProbability = output2[counter, choiceNow]
#This gives the probability of this tree generation process in general, not assuming
#the correct tree must be generated.
theoryProbability = output[counter, choiceNow]
#This is the numerical representation of the edge which is added to the tree.
edgeChoice = edgeNums[counter, choiceNow]
newStartClone = newStartClone[counter, choiceNow]
edgeChoice_end_individual = np.zeros(N1)
#This updates the remaining edges which need to be added based on the edges which were just added.
for b in range(0, N1):
#print (edgeChoice[b])
#print (edgesRemainingNum[b])
argIn1 = np.argwhere(edgesRemainingNum[b] == edgeChoice[b])
if argIn1.shape[0] != 0:
argIn1 = argIn1[0, 0]
edgesRemainingNum[b, argIn1] = (M + 2)**2
argIn1 = edgesRemaining[b, argIn1, 1]
edgeChoice_end_individual[b] = argIn1
#This gives the first and second node on the new edge added
edgeChoice_start = edgeChoice // (M + 2)
edgeChoice_end = edgeChoice % (M + 2)
#This adds the new clone to the clones in this phylogeny tree.
clones[counter, a+1] = clones[counter, newStartClone].clone()
clones[counter, a+1, edgeChoice_end] = clones[counter, a+1, edgeChoice_end] + 1
#This adds the new edge to the list of edges in the tree.
Edges[:, M1, 0] = edgeChoice_start
Edges[:, M1, 1] = edgeChoice_end_individual
#This adds the theoryProbability and sampleProbability (described earlier) for this edge
#to there respective sums.
probLog1[argsLength] += torch.log(theoryProbability[argsLength]+1e-12)
probLog2[argsLength] += torch.log(sampleProbability[argsLength]+1e-12)
probLog1_np = probLog1.data.numpy()
probLog2_np = probLog2.data.numpy()
#This adjusts the probabiltiy baseline for each tree.
baseLine = baseLine * ((baseN - 1) / baseN)
baseLine = baseLine + ((1 / baseN) * np.exp(probLog1_np - probLog2_np) )
#adjustProbability means that the algorithm optimizes to accuratly represent the probability
#of different trees, rather than just trying to maximize the probability of the very most
#likely trees (which is useful in some situations not discussed in the paper)
if adjustProbability:
baseLineLog = np.log(baseLine)
#This is the reinforcement learning loss function, before some adjustments for sampling frequency
loss_array = probLog1 / (torch.exp(probLog2.detach()) + 1e-10)
loss_array = loss_array / maxM
sampleUnique, sampleIndex = np.unique(sampleInverse, return_index=True)
#This will give some adjustement terms associated with sampling frequency.
#Specifically, adjustments for the fact that things are not sampled exactly proportional to
#there liklyhood according to the model. For more detailed information, read the paper.
prob_adjustment = np.zeros(sampleInverse.shape[0])
baseLineMean = np.zeros(int(np.max(sampleInverse) + 1)) + 1
for b in range(0, sampleIndex.shape[0]):
start1 = sampleIndex[b]
if b == sampleIndex.shape[0] - 1:
end1 = N1
else:
end1 = sampleIndex[b+1]
argsLocal = np.arange(end1 - start1) + start1
localProb = probLog1_np[argsLocal]
localBaseline = baseLineLog[argsLocal]
#maxLogProb = max(np.max(localBaseline), np.max(localProb))
maxLogProb = np.max(localBaseline)
localProb = localProb - maxLogProb
localBaseline = localBaseline - maxLogProb
#localProb_0 = np.copy(localProb)
localProb = np.exp(localProb) / (np.sum(np.exp(localBaseline)) + 1e-5)
#if np.max(localProb) > 1:
# print ('Hi')
# print (np.exp(localProb+maxLogProb))
# print (np.exp(localBaseline+maxLogProb))
# quit()
prob_adjustment[argsLocal] = np.copy(localProb)
#baseLineMean[b] = np.sum(baseLine[argsLocal])
baseLineMean[int(sampleUnique[b])] = np.sum(baseLine[argsLocal])
#This applies the adjustment to the loss function
loss_array = loss_array * torch.tensor(prob_adjustment)
#This takes the loss on the training set trees.
loss_array = loss_array[trainSet2]
#Thiscalculates the unsupervised learning log liklyhood loss.
# Note, this is not the same as the reinforcement learning reward function.
score_train = np.mean(np.log(baseLineMean[trainSet] + 1e-6))
score_test = np.mean(np.log(baseLineMean[testSet] + 1e-6))
else:
loss_array = torch.exp( probLog1 - probLog2.detach() )
loss_array = loss_array[trainSet2]
#This gives a minus sign, since we minimize the negative of the reward function mean.
loss = -1 * torch.mean(loss_array)
#This adds regularization.
#There are some small subset of parameters where regularization is not useful for
#preventing overfitting or increasing interpretability
regularization = 0
numHigh = 0
numAll = 0
c1 = 0
if nonLin:
for param in model.parameters():
#print (param.shape)
if c1 in [0, 2, 3]:
#regularization = regularization + torch.sum(torch.abs(param))
#regularization = regularization + torch.sum( torch.abs(param) - ( 0.9 * torch.relu( torch.abs(param) - 0.2 )) )
regularization = regularization + torch.sum( torch.abs(param) - ( 0.9 * torch.relu( torch.abs(param) - 0.1 )) ) #STANDARD!!! (before Oct 13)
#regularization = regularization + torch.sum( torch.abs(param) - ( 0.8 * torch.relu( torch.abs(param) - 0.1 )) ) #Trying Oct 13
#regularization = regularization + (torch.sum( 1 - torch.exp(-torch.abs(param) * 10) ) * 0.1)
numHigh += np.argwhere(np.abs(np.abs(param.data.numpy()) < 0.01)).shape[0]
numAll += np.argwhere(np.abs(np.abs(param.data.numpy()) > -1)).shape[0]
#numAll += param.size
c1 += 1
#quit()
else:
for param in model.parameters():
#regularization = regularization + torch.sum(torch.abs(param))
regularization = regularization + torch.sum(param**2)
c1 += 1
if regularizeFactor == 0.02:
#regularization = regularization * 0.02#0.0001#
regularization = regularization * 0.02
#regularization = regularization * 0.05
#regularization = regularization * 0.002
else:
regularization = regularization * regularizeFactor
#Adding regularization to the loss
loss = loss + regularization
if doPrint:
if verbose:
print ("")
print ('Mean Probability: ', np.mean(baseLine))
print ('Training Score: ', score_train, 'Testing Score:', score_test)
print ('Loss: ', loss.data.numpy())
#Saving the probabilities and model.
if baselineSave and fileSave:
torch.save(model, fileSave)
np.save(baselineSave, baseLine)
optimizer.zero_grad()
loss.backward()
optimizer.step()
#quit()
def trainModelTree(newTrees, sampleInverse, treeLength, mutationCategory, M, maxM, fileSave=False, baselineSave=False, usePurity=False, adjustProbability=True, trainSet=False, unknownRoot=False, regularizeFactor=0.002, iterations='default', verbose=False):
#This function trains a model to predict the probability of new mutations being added to clones,
#and therefore the probability of phylogeny trees generated through this process.
excludeSameMut = True
doTrainSet = not (type(trainSet) == type(False))
N1 = newTrees.shape[0]
N2 = int(np.max(sampleInverse) + 1)
#M2 = np.unique(mutationCategory).shape[0]
#This calculates the test set patients, as well as the training set trees (trainSet2)
if doTrainSet:
#trainSet = np.argwhere(np.isin(sampleInverse, trainSet))[:, 0]
testSet = np.argwhere(np.isin(np.arange(N2), trainSet) == False)[:, 0]
trainSet2 = np.argwhere(np.isin(sampleInverse, trainSet))[:, 0]
model = MutationModel(M)
#model = torch.load('./Models/savedModel23.pt')
#N1 = 10000
nPrint = 1#00
#learningRate = 1e0
#learningRate = 1e0 #Typically used May 22
learningRate = 1e1
#learningRate = 1e2
optimizer = torch.optim.SGD(model.parameters(), lr = learningRate)
#learningRate = 1e-1
#learningRate = 1e-2
#learningRate = 1e-3
#optimizer = torch.optim.Adam(model.parameters(), lr = learningRate)
if adjustProbability or True:
#This is the baseline probability that each tree is generated.
baseLine = np.zeros(N1) #+ 0.1
#baseLine = np.load('./Models/baseline1.npy')
#baseN = 100
baseN = 10
accuracies = []
recordBase = np.zeros((100000, N1))
recordSamp = np.zeros((100000, N1))
print ("The code runs for 1000 iterations.")
#print ("If required, the code can be stopped early.")
if verbose:
print ("The user can stop the code at any time if the testing loss has ")
print ("converged sufficiently close to the optimum for the user's applicaiton. ")
iterMax = 1000
if iterations != 'default':
iterMax = iterations
for iter in range(0, iterMax):#301): #3000
#if True:
# baseN = (min(iter, 1000) + 10)
doPrint = False
if iter % nPrint == 0:
doPrint = True
if doPrint:
print ('iteration ' + str(iter) + ' of ' + str(iterMax))
#This is initializing the edges of the generated trees
Edges = np.zeros((N1, maxM+1, 2))
Edges[:, 0, 1] = M
#This is initializing the clones for each possible phylogeny tree.
clones = torch.zeros((N1, maxM+1, M))
#The edges remaining represent the edges which still need to be added
#in order to generate the correct tree. It is initialized as all
#of the edges in the tree.
edgesRemaining = np.copy(newTrees)
#This converts them to numerical incoding of edges.
edgesRemaining = (edgesRemaining[:, :, 0] * (M + 2)) + edgesRemaining[:, :, 1]
#These are the log probability of the generation of the tree (theoretically)
#as well as the log probability of this way of generatating the tree,
#when we restrict the model to only generating this correct tree.
probLog1 = torch.zeros(N1)
probLog2 = torch.zeros(N1)
#Looping over the edges in the tree.
for a in range(0, maxM):
#These are the trees which have an "a+1"th edge, since there length
#is larger than a+1.
argsLength = np.argwhere(treeLength >= (a + 1))[:, 0]
#The "a+1"th edge should only be ran if at least some tree has an "a+1"th edge.
if argsLength.shape[0] != 0:
M1 = a + 1
counter = np.arange(N1)
#This calculates the output of the model given the clones that exist.
clones1 = clones[:, :M1].reshape((N1 * M1, M))
output, _ = model(clones1)
output = output.reshape((N1, M1 * M))
output = torch.softmax(output, dim=1)
#This calculates the possible new mutations and clones for new mutations to be added to.
newStart = Edges[:, :M1, 1].repeat(M).reshape((N1, M1 * M))
newStartClone = np.arange(M1).repeat(N1*M).reshape((M1, N1, M))
newStartClone = np.swapaxes(newStartClone, 0, 1).reshape((N1, M1 * M))
newEnd = np.arange(M).repeat(N1*M1).reshape((M, N1*M1)).T.reshape((N1, M1 * M))
edgeNums = (newStart * (M + 2)) + newEnd
#This makes it so the same mutation can not be added multiple times.
#Specifically, it assigns a probability of zero to this case.
if excludeSameMut:
notAlreadyUsedMask = np.zeros((N1, M1 * M))
for b in range(0, N1):
notAlreadyUsedMask[b, np.isin(newEnd[b], Edges[b, :M1, 1]) == False]
notAlreadyUsedMask[b, np.isin(newEnd[b], Edges[b, :M1, 1]) == False] = 1
output = output * torch.tensor(notAlreadyUsedMask).float()
output_sum = torch.sum(output, dim=1).repeat_interleave(M1*M).reshape((N1, M1*M))
output = output / output_sum
#This makes it so you can only add edges which are present in the correct tree.
validEndMask = np.zeros((N1, M1 * M))
for b in range(0, N1):
validEndMask[b, np.isin(edgeNums[b], edgesRemaining[b])] = 1
#This removes the impossible choices, and then adjust the probability to still sum to 1.
output2 = output * torch.tensor(validEndMask).float()
output2_sum = torch.sum(output2, dim=1).repeat_interleave(M1*M).reshape((N1, M1*M))
output2 = output2 / output2_sum
#This makes a choice of clone to add a mutation as well as the mutation to be added based on the probabilities.
choiceNow = doChoice(output2.data.numpy()).astype(int)
printNum = 10
#This determines the probability of this specific step in the generation process, given this tree as
#the correct tree to be generated.
sampleProbability = output2[counter, choiceNow]
#This gives the probability of this tree generation process in general, not assuming
#the correct tree must be generated.
theoryProbability = output[counter, choiceNow]
#This is the numerical representation of the edge which is added to the tree.
edgeChoice = edgeNums[counter, choiceNow]
newStartClone = newStartClone[counter, choiceNow]
#This updates the remaining edges which need to be added based on the edges which were just added.
for b in range(0, N1):
argsNotRemaining = np.argwhere(edgesRemaining[b] == edgeChoice[b])[:, 0]
edgesRemaining[b, argsNotRemaining] = (M + 2) ** 2
#This gives the first and second node on the new edge added
edgeChoice_start = edgeChoice // (M + 2)
edgeChoice_end = edgeChoice % (M + 2)
#This adds the new clone to the clones in this phylogeny tree.
clones[counter, a+1] = clones[counter, newStartClone].clone()
clones[counter, a+1, edgeChoice_end] = clones[counter, a+1, edgeChoice_end] + 1
#This adds the new edge to the list of edges in the tree.
Edges[:, M1, 0] = edgeChoice_start
Edges[:, M1, 1] = edgeChoice_end
#This adds the theoryProbability and sampleProbability (described earlier) for this edge
#to there respective sums.
probLog1[argsLength] += torch.log(theoryProbability[argsLength]+1e-12)
probLog2[argsLength] += torch.log(sampleProbability[argsLength]+1e-12)
probLog1_np = probLog1.data.numpy()
probLog2_np = probLog2.data.numpy()
#This adjusts the probabiltiy baseline for each tree.
baseLine = baseLine * ((baseN - 1) / baseN)
baseLine = baseLine + ((1 / baseN) * np.exp(probLog1_np - probLog2_np) )
#This just records data for analysis
recordBase[iter] = np.copy(probLog1_np)
recordSamp[iter] = np.copy(probLog2_np)
#adjustProbability means that the algorithm optimizes to accuratly represent the probability
#of different trees, rather than just trying to maximize the probability of the very most
#likely trees (which is useful in some situations not discussed in the paper)
if True:#adjustProbability:
baseLineLog = np.log(baseLine)
#baseLineLog = np.copy(baseLine)
#print (probLog2[:10])
#This is the reinforcement learning loss function, before some adjustments for sampling frequency
loss_array = probLog1 / (torch.exp(probLog2.detach()) + 1e-10)
loss_array = loss_array / maxM
sampleUnique, sampleIndex = np.unique(sampleInverse, return_index=True)
#This will give some adjustement terms associated with sampling frequency.
#Specifically, adjustments for the fact that things are not sampled exactly proportional to
#there liklyhood according to the model. For more detailed information, read the paper.
prob_adjustment = np.zeros(sampleInverse.shape[0])
baseLineMean = np.zeros(int(np.max(sampleInverse) + 1)) + 1
for b in range(0, sampleIndex.shape[0]):
start1 = sampleIndex[b]
if b == sampleIndex.shape[0] - 1:
end1 = N1
else:
end1 = sampleIndex[b+1]
argsLocal = np.arange(end1 - start1) + start1
localProb = probLog1_np[argsLocal]
localBaseline = baseLineLog[argsLocal]
#maxLogProb = max(np.max(localBaseline), np.max(localProb))
maxLogProb = np.max(localBaseline)
localProb = localProb - maxLogProb
localBaseline = localBaseline - maxLogProb
localProb = np.exp(localProb) / (np.sum(np.exp(localBaseline)) + 1e-5)
prob_adjustment[argsLocal] = np.copy(localProb)
baseLineMean[int(sampleUnique[b])] = np.sum(baseLine[argsLocal])
#This applies the adjustment to the loss function
loss_array = loss_array * torch.tensor(prob_adjustment)
#This takes the loss on the training set trees.
loss_array = loss_array[trainSet2]
#Thiscalculates the unsupervised learning log liklyhood loss.
# Note, this is not the same as the reinforcement learning reward function.
score_train = np.mean(np.log(baseLineMean[trainSet] + 1e-20))
score_test = np.mean(np.log(baseLineMean[testSet] + 1e-20))
#loss_array = torch.exp( probLog1 - probLog2.detach() )
#loss_array = loss_array[trainSet2]
#This gives a minus sign, since we minimize the negative of the reward function mean.
loss = -1 * torch.mean(loss_array)
#This adds regularization.
#There are some small subset of parameters where regularization is not useful for
#preventing overfitting or increasing interpretability
regularization = 0
numHigh = 0
numAll = 0
c1 = 0
for param in model.parameters():
if c1 in [0, 2, 3]:
regularization = regularization + torch.sum( torch.abs(param) ) #- ( 0.9 * torch.relu( torch.abs(param) - 0.1 )) )
numHigh += np.argwhere(np.abs(np.abs(param.data.numpy()) < 0.01)).shape[0] #Just recording information
numAll += np.argwhere(np.abs(np.abs(param.data.numpy()) > -1)).shape[0] #Just recording information
#numAll += param.size
c1 += 1
#regularization = regularization * 0.0001
#regularization = regularization * 0.0002 #Best for breast cancer
regularization = regularization * regularizeFactor
#regularization = regularization * 0.002 #Used for our occurance simulation as well
#Adding regularization to the loss
loss = loss + regularization
#Printing information about training
if doPrint:
#print (baseLine)
#quit()
if verbose:
print ("")
print ('Mean Probability: ', np.mean(baseLine))
print ('Training Score: ', score_train, 'Testing Score:', score_test)
print ('Loss: ', loss.data.numpy())
#Saving the probabilities and model.
if baselineSave and fileSave:
torch.save(model, fileSave)
np.save(baselineSave, baseLine)
if iter == 500:
#This allows for initially having a higher learning rate and then moving to a lower learning rate.
optimizer = torch.optim.SGD(model.parameters(), lr = 1e0)
optimizer.zero_grad()
loss.backward()
optimizer.step()
def trainModel(inputNameList, modelName, treeSelectionName, mutationName, patientNames='', inputFormat='simple', infiniteSites=True, trainSize='all', maxM=10, regularizeFactor='default', iterations='default', verbose=False):
if inputFormat == 'raw':
#maxM = 9
newTrees, sampleInverse, mutationCategory, treeLength, uniqueMutation, M = processTreeData(maxM, inputNameList[0], mutationName, infiniteSites=infiniteSites, patientNames=patientNames)
#newTrees, sampleInverse, mutationCategory, treeLength, uniqueMutation, M = processTreeData(maxM, './data/realData/AML.npy', './mutationName.npy')
#newTrees, sampleInverse, mutationCategory, treeLength, uniqueMutation, M = processTreeData(maxM, './data/realData/AML.npy', './mutationName.npy', infiniteSites=infiniteSites)
#print (sampleInverse.shape)
#newTrees, sampleInverse, mutationCategory, treeLength, uniqueMutation, M = processTreeData(maxM, './data/lungData/processed.npy')
elif inputFormat == 'multi':
#print ([inputNameList])
newTrees = loadnpz(inputNameList[0])
newTrees = newTrees.astype(int)
sampleInverse = loadnpz(inputNameList[1]).astype(int)