-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathSpectra_attn.py
More file actions
1443 lines (1231 loc) · 54.9 KB
/
Spectra_attn.py
File metadata and controls
1443 lines (1231 loc) · 54.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 torch
from collections import OrderedDict
from opt_einsum import contract
from scipy.special import logit
from tqdm import tqdm
from scipy.special import xlogy
from scipy.special import softmax
from Spectra import Spectra_util
import torch.nn as nn
import scipy
import pandas as pd
from pyvis.network import Network
import random
from torch.distributions.normal import Normal
from torch.distributions.log_normal import LogNormal
from torch.distributions.dirichlet import Dirichlet
class SPECTRA_select(nn.Module):
"""
Parameters
----------
X : np.ndarray or torch.Tensor
the ``(n, p)`` -shaped matrix containing logged expression count data. Used for initialization of self.n and self.p but not stored as an attribute
labels : np.ndarray or NoneType
the ``(n, )`` -shaped array containing cell type labels. If use_cell_types == False, then should be set to None
K : dict or OrderedDict [if use_cell_types == False then int]
``number of cell types + 1`` -shaped dictionary. Must have "global" as a key, indicating the number of global factors
{
"global": 15,
"CD8": 5,
}
> Note that K contains the number of factors that describe the expression data while L contains the number of factors that describe the graph. When K < L an additional parameter that projects the L graph factors down is initialized. When L < K the behavior is to set L to max(L,K)
L : dict or OrderedDict [if use_cell_types == False, then int]
``number of cell types + 1``-shaped dictionary. Must have "global" as a key, indicating the number of global factors
{
"global": 15,
"CD8": 5
...
}
> Format matches output of K_est.py to estimate the number of
> Must match cell type labels provided during training
> Recommended practice is to assign at minimum 2 factors per cell type
> Note that K contains the number of factors that describe the expression data while L contains the number of factors that describe the graph. When K < L an additional parameter that projects the L graph factors down is initialized. When L < K the behavior is to set L to max(L,K)
adj_matrix : dict or OrderedDict
``a dictionary of adjacency matrices, one for every cell type + a "global"
{
"global": ``(p, p)``-shaped binary np.ndarray
"CD8": ...
}
weights : dict or OrderedDict or NoneType [if use_cell_types == False, then ``(p, p)``-shaped array]
the ``(p, p)``-shaped set of edge weights per . If weight[i,j] is non-zero when adj_matrix[i,j] = 0
this weight is ignored.
if weights == None, no weights are used
lam : float
lambda parameter of the model, which controls the relative influence of the graph vs expression loss functions. This term multiplies the expression loss, so smaller values of lambda upweight the prior information
delta : float
delta parameter of the model, which controls a lower bound for gene scaling factors. If delta is small then the maximum ratio between gene scaling factors is larger and lowly expressed genes can be put on the same scale as highly expressed genes.
kappa : float or NoneType
kappa controls the background rate of edges in the graph. if kappa is a float, kappa is fixed to the given float value. If kappa == None, then kappa is a parameter that is estimated from the data.
rho : float or NoneType
rho controls the bakcground rate of non-edges in the graph. if rho is a float, rho is fixed to the given float value. If rho == None, then rho is a parameter that is estimated from the data.
use_cell_types: bool
use_cell_types is a Boolean variable that determines whether cell type labels are used to fit the model. If False, then parameters are initialized as nn.Parameter rather than as nn.ParameterDict with cell type keys that index nn.Parameter values
determinant_penalty : float
determinant penalty affects the selection parameters that are fit when L[cell_type] > K[cell_type]. A determinantally regularized selection parameter is fit with determinant penalty that encourages sparsity and diversity.
Attributes
----------
model.delta : delta parameter of the model
model.lam : lambda parameter of the model
model.determinant_penalty : determinant penalty of the model
model.K : K parameter, either int, dict, or OrderedDict()
model.L : L parameter, either int, dict or OrderedDict()
model.p : number of genes
model.n : number of cells
model.use_cell_types : if True then cell types are considered, else cell types ignored. Affects the dimensions of the initialized parameters.
model.kappa : if not kappa, nn.ParameterDict() if use_cell_types, else nn.Parameter(). If kappa is a float, it is fixed throughout training
model.rho : if not rho, nn.ParamterDict() if use_cell_types, else nn.Parameter. If rho is a float it is fixed throughout training
model.adj_matrix : adjacency matrix with diagonal removed. dict containing torch.Tensors
model.adj_matrix_1m : 1 - adjacency matrix with diagonal removed. dict containing torch.Tensors
model.weights : contains edge weights. format matches adj_matrix
model.cell_types : np.ndarray containing array of unique cell types
model.cell_type_counts : dict {key = cell type, values = number of cells}
model.theta : nn.ParameterDict() or nn.Parameter() containing the factor weights
model.alpha : nn.ParameterDict() or nn.Parameter() containing the cell loadings
model.eta : nn.ParameterDict() or nn.Parameter() containing the interaction matrix between factors
model.gene_scaling : nn.ParameterDict() or nn.Parameter() containing the gene scale factors
model.selection : nn.ParameterDict() or nn.Parameter() containing the attention weights. Only initialized when L[cell_type] > K[cell_type] for some cell type or when L > K and use_cell_types == False
model.kgeql_flag : dict or bool. dictionary of boolean values indicating whether K >= L. When use_cell_types == False, it is a boolean value
Methods
----------
model.loss(self, X, labels) : called by fit if use_cell_types = True. Evalutes the loss of the model
model.loss_no_cell_types(self,X) : called by fit if use_cell_types = False. Evalutes the loss of the model
model.initialize(self, gene_sets,val) : initialize the model based on given dictionary of gene sets. val is a float that determines the strength of the initialization.
model.initialize_no_celltypes(self, gs_list, val) : initialize the model based on given list of gene sets. val is a float that determines the strength of the initialization.
To do:
__________
> Alternative initialization functions
> comment SPECTRA-EM code
> test lower bound constraint [see pyspade_global.py implementation]
> Overlap threshold test statistic
"""
def __init__(
self,
X,
labels,
adj_matrix,
K,
L,
weights=None,
lam=10e-4,
delta=0.1,
kappa=0.00001,
rho=0.00001,
use_cell_types=True,
determinant_penalty=0.0,
):
super(SPECTRA_select, self).__init__()
# hyperparameters
self.delta = delta
self.lam = lam
self.determinant_penalty = determinant_penalty
# L and K are potentially different now - we have a projection parameter whereever L > K
self.L = L
self.K = K
# for memory efficiency we don't store X in the object attributes, but require X dimensions to be known at initialization
self.p = X.shape[1]
self.n = X.shape[0]
self.use_cell_types = use_cell_types
if not use_cell_types:
# check that L is an int
assert isinstance(self.L, int)
# trust the user to input a np.ndarray for adj_matrix
self.adj_matrix = torch.Tensor(adj_matrix) - torch.Tensor(
np.diag(np.diag(adj_matrix))
)
adj_matrix_1m = 1.0 - adj_matrix
self.adj_matrix_1m = torch.Tensor(
adj_matrix_1m - np.diag(np.diag(adj_matrix_1m))
)
if weights is not None:
self.weights = torch.Tensor(weights) - torch.Tensor(
np.diag(np.diag(adj_matrix))
)
else:
self.weights = self.adj_matrix
if self.K >= self.L:
self.theta = nn.Parameter(Normal(0.0, 1.0).sample([self.p, self.K]))
self.eta = nn.Parameter(Normal(0.0, 1.0).sample([self.K, self.K]))
self.kgeql_flag = True
else:
self.theta = nn.Parameter(Normal(0.0, 1.0).sample([self.p, self.L]))
self.selection = nn.Parameter(Normal(0.0, 1.0).sample([self.K, self.L]))
self.eta = nn.Parameter(Normal(0.0, 1.0).sample([self.L, self.L]))
self.kgeql_flag = False
self.alpha = nn.Parameter(Normal(0.0, 1.0).sample([self.n, self.K]))
self.gene_scaling = nn.Parameter(Normal(0.0, 1.0).sample([self.p]))
if kappa == None:
self.kappa = nn.Parameter(Normal(0.0, 1.0).sample())
else:
self.kappa = torch.tensor(np.log(kappa / (1 - kappa))) #
if rho == None:
self.rho = nn.Parameter(Normal(0.0, 1.0).sample())
else:
self.rho = torch.tensor(np.log(rho / (1 - rho)))
if use_cell_types:
# convert adjacency matrices to pytorch tensors to make optimization easier later
self.adj_matrix = {
cell_type: (
torch.Tensor(adj_matrix[cell_type])
- torch.Tensor(np.diag(np.diag(adj_matrix[cell_type])))
if len(adj_matrix[cell_type]) > 0
else []
)
for cell_type in adj_matrix.keys()
}
# for convenience store 1 - adjacency matrix elements [except on diagonal, where we store 0]
adj_matrix_1m = {
cell_type: (
1.0 - adj_matrix[cell_type]
if len(adj_matrix[cell_type]) > 0
else []
)
for cell_type in adj_matrix.keys()
} # one adj_matrix per cell type
self.adj_matrix_1m = {
cell_type: (
torch.Tensor(
adj_matrix_1m[cell_type]
- np.diag(np.diag(adj_matrix_1m[cell_type]))
)
if len(adj_matrix_1m[cell_type]) > 0
else []
)
for cell_type in adj_matrix_1m.keys()
} # one adj_matrix per cell type
# if weights are provided, convert these to tensors, else set weights = to adjacency matrices
if weights:
self.weights = {
cell_type: (
torch.Tensor(weights[cell_type])
- torch.Tensor(np.diag(np.diag(weights[cell_type])))
if len(weights[cell_type]) > 0
else []
)
for cell_type in weights.keys()
}
else:
self.weights = self.adj_matrix
self.cell_types = np.unique(
labels
) # cell types are the unique labels, again require knowledge of labels at initialization but do not store them
# store a dictionary containing the counts of each cell type
self.cell_type_counts = {}
for cell_type in self.cell_types:
n_c = sum(labels == cell_type)
self.cell_type_counts[cell_type] = n_c
# initialize parameters randomly, we use torch's ParameterDict() for storage for intuitive accessing cell type specific parameters
self.theta = nn.ParameterDict()
self.alpha = nn.ParameterDict()
self.eta = nn.ParameterDict()
self.gene_scaling = nn.ParameterDict()
self.selection = nn.ParameterDict()
self.kgeql_flag = {}
if kappa == None:
self.kappa = nn.ParameterDict()
if rho == None:
self.rho = nn.ParameterDict()
# initialize global params
if self.K["global"] >= self.L["global"]:
self.kgeql_flag["global"] = True
self.theta["global"] = nn.Parameter(
Normal(0.0, 1.0).sample([self.p, self.K["global"]])
)
self.eta["global"] = nn.Parameter(
Normal(0.0, 1.0).sample([self.K["global"], self.K["global"]])
)
else:
self.kgeql_flag["global"] = False
self.theta["global"] = nn.Parameter(
Normal(0.0, 1.0).sample([self.p, self.L["global"]])
)
self.selection["global"] = nn.Parameter(
Normal(0.0, 1.0).sample([self.K["global"], self.L["global"]])
)
self.eta["global"] = nn.Parameter(
Normal(0.0, 1.0).sample([self.L["global"], self.L["global"]])
)
self.gene_scaling["global"] = nn.Parameter(
Normal(0.0, 1.0).sample([self.p])
)
if kappa == None:
self.kappa["global"] = nn.Parameter(Normal(0.0, 1.0).sample())
if rho == None:
self.rho["global"] = nn.Parameter(Normal(0.0, 1.0).sample())
# initialize all cell type specific params
for cell_type in self.cell_types:
if self.K[cell_type] >= self.L[cell_type]:
self.kgeql_flag[cell_type] = True
self.theta[cell_type] = nn.Parameter(
Normal(0.0, 1.0).sample([self.p, self.K[cell_type]])
)
self.eta[cell_type] = nn.Parameter(
Normal(0.0, 1.0).sample([self.K[cell_type], self.K[cell_type]])
)
else:
self.kgeql_flag[cell_type] = False
self.theta[cell_type] = nn.Parameter(
Normal(0.0, 1.0).sample([self.p, self.L[cell_type]])
)
self.selection[cell_type] = nn.Parameter(
Normal(0.0, 1.0).sample([self.K[cell_type], self.L[cell_type]])
)
self.eta[cell_type] = nn.Parameter(
Normal(0.0, 1.0).sample([self.L[cell_type], self.L[cell_type]])
)
n_c = sum(labels == cell_type)
self.alpha[cell_type] = nn.Parameter(
Normal(0.0, 1.0).sample([n_c, self.K["global"] + self.K[cell_type]])
)
self.gene_scaling[cell_type] = nn.Parameter(
Normal(0.0, 1.0).sample([self.p])
)
if kappa == None:
self.kappa[cell_type] = nn.Parameter(Normal(0.0, 1.0).sample())
if rho == None:
self.rho[cell_type] = nn.Parameter(Normal(0.0, 1.0).sample())
# if kappa and rho are provided, hold these fixed during training, else fit as free parameters
# to unify the cases, we put this in the same format
if kappa != None:
self.kappa = {}
self.kappa["global"] = torch.tensor(np.log(kappa / (1 - kappa)))
for cell_type in self.cell_types:
self.kappa[cell_type] = torch.tensor(np.log(kappa / (1 - kappa)))
if rho != None:
self.rho = {}
self.rho["global"] = torch.tensor(np.log(rho / (1 - rho)))
for cell_type in self.cell_types:
self.rho[cell_type] = torch.tensor(np.log(rho / (1 - rho)))
def loss(self, X, labels):
assert (
self.use_cell_types
) # if this is False, fail because model has not been initialized to use cell types
# convert inputs to torch.Tensors
X = torch.Tensor(X)
# labels = torch.Tensor(labels)
# initialize loss and fetch global parameters
loss = 0.0
theta_global = torch.softmax(self.theta["global"], dim=1)
eta_global = (self.eta["global"]).exp() / (1.0 + (self.eta["global"]).exp())
eta_global = 0.5 * (eta_global + eta_global.T)
gene_scaling_global = self.gene_scaling["global"].exp() / (
1.0 + self.gene_scaling["global"].exp()
)
kappa_global = self.kappa["global"].exp() / (1 + self.kappa["global"].exp())
rho_global = self.rho["global"].exp() / (1 + self.rho["global"].exp())
if self.kgeql_flag["global"]:
theta_global_new = theta_global
else:
selection_global = self.selection["global"].softmax(dim=1)
theta_global_new = contract("ij,kj->ki", selection_global, theta_global)
loss = loss - self.determinant_penalty * torch.logdet(
contract("ij,kj->ik", selection_global, selection_global)
)
# loop through cell types and evaluate loss at every cell type
for cell_type in self.cell_types:
kappa = self.kappa[cell_type].exp() / (1 + self.kappa[cell_type].exp())
rho = self.rho[cell_type].exp() / (1 + self.rho[cell_type].exp())
gene_scaling_ct = self.gene_scaling[cell_type].exp() / (
1.0 + self.gene_scaling[cell_type].exp()
)
X_c = X[labels == cell_type]
adj_matrix = self.adj_matrix[cell_type]
weights = self.weights[cell_type]
adj_matrix_1m = self.adj_matrix_1m[cell_type]
theta_ct = torch.softmax(self.theta[cell_type], dim=1)
eta_ct = (self.eta[cell_type]).exp() / (1.0 + (self.eta[cell_type]).exp())
eta_ct = 0.5 * (eta_ct + eta_ct.T)
theta_global_ = contract(
"jk,j->jk", theta_global_new, gene_scaling_global + self.delta
)
alpha = torch.exp(self.alpha[cell_type])
# recon = contract('ik,jk->ij', alpha, theta)
# term1 = -1.0*(torch.xlogy(X_c,recon) - recon).sum()
if self.kgeql_flag[cell_type]:
theta_ct_ = contract("jk,j->jk", theta_ct, gene_scaling_ct + self.delta)
theta = torch.cat((theta_global_, theta_ct_), 1)
recon = contract("ik,jk->ij", alpha, theta)
term1 = -1.0 * (torch.xlogy(X_c, recon) - recon).sum()
else:
selection_ct = self.selection[cell_type].softmax(dim=1)
theta_ct_new = contract("ij,kj->ki", selection_ct, theta_ct)
theta_ct_ = contract(
"jk,j->jk", theta_ct_new, gene_scaling_ct + self.delta
)
theta = torch.cat((theta_global_, theta_ct_), 1)
recon = contract("ik,jk->ij", alpha, theta)
term1 = -1.0 * (
torch.xlogy(X_c, recon) - recon
).sum() - self.determinant_penalty * torch.logdet(
contract("ij,kj->ik", selection_ct, selection_ct)
)
if len(adj_matrix) > 0:
mat = contract("il,lj,kj->ik", theta_ct, eta_ct, theta_ct)
term2 = (
-1.0
* (
torch.xlogy(
adj_matrix * weights,
(1.0 - rho) * (1.0 - kappa) * mat + (1.0 - rho) * kappa,
)
).sum()
)
term3 = (
-1.0
* (
torch.xlogy(
adj_matrix_1m,
(1.0 - kappa) * (1.0 - rho) * (1.0 - mat) + rho,
)
).sum()
)
else:
term2 = 0.0
term3 = 0.0
# the magnitude of lambda is proportional to the number of cells [todo: simpler to just take the mean instead of sum in term 1]
loss = (
loss
+ self.lam * term1
+ (self.cell_type_counts[cell_type] / float(self.n)) * (term2 + term3)
)
# compute loss associated with global graph
adj_matrix = self.adj_matrix["global"]
adj_matrix_1m = self.adj_matrix_1m["global"]
weights = self.weights["global"]
if len(adj_matrix) > 0:
mat = contract("il,lj,kj->ik", theta_global, eta_global, theta_global)
term2 = (
-1.0
* (
torch.xlogy(
adj_matrix * weights,
(1.0 - rho_global) * (1.0 - kappa_global) * mat
+ (1.0 - rho_global) * kappa_global,
)
).sum()
)
term3 = (
-1.0
* (
torch.xlogy(
adj_matrix_1m,
(1.0 - kappa_global) * (1.0 - rho_global) * (1.0 - mat)
+ rho_global,
)
).sum()
)
loss = loss + term2 + term3
return loss
def loss_no_cell_types(self, X):
assert self.use_cell_types == False # if this is True, just fail
X = torch.Tensor(X)
theta = torch.softmax(self.theta, dim=1)
eta = self.eta.exp() / (1.0 + (self.eta).exp())
eta = 0.5 * (eta + eta.T)
gene_scaling = self.gene_scaling.exp() / (1.0 + self.gene_scaling.exp())
kappa = self.kappa.exp() / (1 + self.kappa.exp())
rho = self.rho.exp() / (1 + self.rho.exp())
alpha = torch.exp(self.alpha)
adj_matrix = self.adj_matrix
weights = self.weights
adj_matrix_1m = self.adj_matrix_1m
if self.kgeql_flag:
theta_ = contract("jk,j->jk", theta, gene_scaling + self.delta)
recon = contract("ik,jk->ij", alpha, theta_)
term1 = -1.0 * (torch.xlogy(X, recon) - recon).sum()
else:
selection = self.selection.softmax(dim=1)
theta_new = contract("ij,kj->ki", selection, theta)
theta_ = contract("jk,j->jk", theta_new, gene_scaling + self.delta)
recon = contract("ik,jk->ij", alpha, theta_)
term1 = -1.0 * (
torch.xlogy(X, recon) - recon
).sum() - self.determinant_penalty * torch.logdet(
contract("ij,kj->ik", selection, selection)
)
if len(adj_matrix) > 0:
mat = contract("il,lj,kj->ik", theta, eta, theta)
term2 = (
-1.0
* (
torch.xlogy(
adj_matrix * weights,
(1.0 - rho) * (1.0 - kappa) * mat + (1.0 - rho) * kappa,
)
).sum()
)
term3 = (
-1.0
* (
torch.xlogy(
adj_matrix_1m, (1.0 - kappa) * (1.0 - rho) * (1.0 - mat) + rho
)
).sum()
)
else:
term2 = 0.0
term3 = 0.0
return self.lam * term1 + term2 + term3
def initialize(self, gene_sets, val):
"""
form of gene_sets:
cell_type (inc. global) : set of sets of idxs
"""
for ct in self.cell_types:
assert self.L[ct] >= len(gene_sets[ct])
count = 0
if self.L[ct] > 0:
if len(self.adj_matrix[ct]) > 0:
for gene_set in gene_sets[ct]:
self.theta[ct].data[:, count][gene_set] = val
count = count + 1
for i in range(self.L[ct]):
self.eta[ct].data[i, -1] = -val
self.eta[ct].data[-1, i] = -val
self.theta[ct].data[:, -1][self.adj_matrix[ct].sum(axis=1) == 0] = (
val
)
self.theta[ct].data[:, -1][self.adj_matrix[ct].sum(axis=1) != 0] = (
-val
)
assert self.L["global"] >= len(gene_sets["global"])
count = 0
for gene_set in gene_sets["global"]:
self.theta["global"].data[:, count][gene_set] = val
count = count + 1
for i in range(self.L["global"]):
self.eta["global"].data[i, -1] = -val
self.eta["global"].data[-1, i] = -val
self.theta["global"].data[:, -1][self.adj_matrix["global"].sum(axis=1) == 0] = (
val
)
self.theta["global"].data[:, -1][self.adj_matrix["global"].sum(axis=1) != 0] = (
-val
)
def initialize_no_celltypes(self, gs_list, val):
assert self.L >= len(gs_list)
count = 0
for gene_set in gs_list:
self.theta.data[:, count][gene_set] = val
count = count + 1
for i in range(self.L):
self.eta.data[i, -1] = -val
self.eta.data[-1, i] = -val
self.theta.data[:, -1][self.adj_matrix.sum(axis=1) == 0] = val
self.theta.data[:, -1][self.adj_matrix.sum(axis=1) != 0] = -val
class SPECTRA_Model:
"""
Parameters
----------
X : np.ndarray or torch.Tensor
the ``(n, p)`` -shaped matrix containing logged expression count data. Used for initialization of self.n and self.p but not stored as an attribute
labels : np.ndarray or NoneType
the ``(n, )`` -shaped array containing cell type labels. If use_cell_types == False, then should be set to None
K : dict or OrderedDict [if use_cell_types == False then int]
``number of cell types + 1`` -shaped dictionary. Must have "global" as a key, indicating the number of global factors
{
"global": 15,
"CD8": 5,
}
> Note that K contains the number of factors that describe the expression data while L contains the number of factors that describe the graph. When K < L an additional parameter that projects the L graph factors down is initialized. When L < K the behavior is to set L to max(L,K)
L : dict or OrderedDict [if use_cell_types == False, then int]
``number of cell types + 1``-shaped dictionary. Must have "global" as a key, indicating the number of global factors
{
"global": 15,
"CD8": 5
...
}
> Format matches output of K_est.py to estimate the number of
> Must match cell type labels provided during training
> Recommended practice is to assign at minimum 2 factors per cell type
> Note that K contains the number of factors that describe the expression data while L contains the number of factors that describe the graph. When K < L an additional parameter that projects the L graph factors down is initialized. When L < K the behavior is to set L to max(L,K)
adj_matrix : dict or OrderedDict
``a dictionary of adjacency matrices, one for every cell type + a "global"
{
"global": ``(p, p)``-shaped binary np.ndarray
"CD8": ...
}
weights : dict or OrderedDict or NoneType [if use_cell_types == False, then ``(p, p)``-shaped array]
the ``(p, p)``-shaped set of edge weights per . If weight[i,j] is non-zero when adj_matrix[i,j] = 0
this weight is ignored.
if weights == None, no weights are used
lam : float
lambda parameter of the model, which controls the relative influence of the graph vs expression loss functions. This term multiplies the expression loss, so smaller values of lambda upweight the prior information
delta : float
delta parameter of the model, which controls a lower bound for gene scaling factors. If delta is small then the maximum ratio between gene scaling factors is larger and lowly expressed genes can be put on the same scale as highly expressed genes.
kappa : float or NoneType
kappa controls the background rate of edges in the graph. if kappa is a float, kappa is fixed to the given float value. If kappa == None, then kappa is a parameter that is estimated from the data.
rho : float or NoneType
rho controls the bakcground rate of non-edges in the graph. if rho is a float, rho is fixed to the given float value. If rho == None, then rho is a parameter that is estimated from the data.
use_cell_types: bool
use_cell_types is a Boolean variable that determines whether cell type labels are used to fit the model. If False, then parameters are initialized as nn.Parameter rather than as nn.ParameterDict with cell type keys that index nn.Parameter values
determinant_penalty : float
determinant penalty affects the selection parameters that are fit when L[cell_type] > K[cell_type]. A determinantally regularized selection parameter is fit with determinant penalty that encourages sparsity and diversity.
Attributes
----------
model.delta : delta parameter of the model
model.lam : lambda parameter of the model
model.determinant_penalty : determinant penalty of the model
model.K : K parameter, either int, dict, or OrderedDict()
model.L : L parameter, either int, dict or OrderedDict()
model.p : number of genes
model.n : number of cells
model.use_cell_types : if True then cell types are considered, else cell types ignored. Affects the dimensions of the initialized parameters.
model.kappa : if not kappa, nn.ParameterDict() if use_cell_types, else nn.Parameter(). If kappa is a float, it is fixed throughout training
model.rho : if not rho, nn.ParamterDict() if use_cell_types, else nn.Parameter. If rho is a float it is fixed throughout training
model.adj_matrix : adjacency matrix with diagonal removed. dict containing torch.Tensors
model.adj_matrix_1m : 1 - adjacency matrix with diagonal removed. dict containing torch.Tensors
model.weights : contains edge weights. format matches adj_matrix
model.cell_types : np.ndarray containing array of unique cell types
model.cell_type_counts : dict {key = cell type, values = number of cells}
model.factors : nn.ParameterDict() or nn.Parameter() containing the factor weights
model.cell_scores : nn.ParameterDict() or nn.Parameter() containing the cell loadings
model.eta : nn.ParameterDict() or nn.Parameter() containing the interaction matrix between factors
model.gene_scaling : nn.ParameterDict() or nn.Parameter() containing the gene scale factors
model.selection : nn.ParameterDict() or nn.Parameter() containing the attention weights. Only initialized when L[cell_type] > K[cell_type] for some cell type or when L > K and use_cell_types == False
Methods
----------
model.train(self, X, labels, lr_schedule,num_epochs, verbose) :
model.save()
model.load()
model.initialize
model.return_selection()
model.return_eta_diag()
model.return_cell_scores()
model.return_factors()
model.return_eta()
model.return_rho()
model.return_kappa()
model.return_gene_scalings()
model.return_graph(ct = "global") :
model.matching(markers, gene_names_dict, threshold = 0.4):
"""
def __init__(
self,
X,
labels,
K,
L=None,
vocab=None,
gs_dict=None,
use_weights=False,
adj_matrix=None,
weights=None,
lam=0.1,
delta=0.1,
kappa=None,
rho=None,
use_cell_types=True,
determinant_penalty=0.0,
):
self.K = K
self.L = L
self.lam = lam
self.delta = delta
self.kappa = kappa
self.rho = rho
self.use_cell_types = use_cell_types
self.determinant_penalty = determinant_penalty
# if gs_dict is provided instead of adj_matrix, convert to adj_matrix, overrides adj_matrix and weights
if gs_dict is not None:
gene2id = dict((v, idx) for idx, v in enumerate(vocab))
if use_cell_types:
adj_matrix, weights = Spectra_util.process_gene_sets(
gs_dict=gs_dict, gene2id=gene2id, weighted=use_weights
)
# determine L
L = OrderedDict()
for key in gs_dict.keys():
L[key] = len(gs_dict[key]) + 1
else:
adj_matrix, weights = Spectra_util.process_gene_sets_no_celltypes(
gs_dict=gs_dict, gene2id=gene2id, weighted=use_weights
)
L = len(gs_dict) + 1
self.internal_model = SPECTRA_select(
X=X,
labels=labels,
adj_matrix=adj_matrix,
L=L,
K=K,
weights=weights,
lam=lam,
delta=delta,
kappa=kappa,
rho=rho,
use_cell_types=use_cell_types,
determinant_penalty=determinant_penalty,
)
self.cell_scores = None
self.factors = None
self.B_diag = None
self.eta_matrices = None
self.gene_scalings = None
self.rho = None
self.kappa = None
def train(
self,
X,
labels=None,
lr_schedule=[1.0, 0.5, 0.1, 0.01, 0.001, 0.0001],
num_epochs=10000,
verbose=False,
):
opt = torch.optim.Adam(self.internal_model.parameters(), lr=lr_schedule[0])
counter = 0
last = np.inf
for i in tqdm(range(num_epochs)):
# print(counter)
opt.zero_grad()
if self.internal_model.use_cell_types:
assert len(labels) == X.shape[0]
loss = self.internal_model.loss(X, labels)
elif self.internal_model.use_cell_types == False:
loss = self.internal_model.loss_no_cell_types(X)
loss.backward()
opt.step()
if loss.item() >= last:
counter += 1
if int(counter / 3) >= len(lr_schedule):
break
if counter % 3 == 0:
opt = torch.optim.Adam(
self.internal_model.parameters(),
lr=lr_schedule[int(counter / 3)],
)
if verbose:
print("UPDATING LR TO " + str(lr_schedule[int(counter / 3)]))
last = loss.item()
# add all model parameters as attributes
if self.use_cell_types:
self.__store_parameters(labels)
else:
self.__store_parameters_no_celltypes()
def save(self, fp):
torch.save(self.internal_model.state_dict(), fp)
def load(self, fp, labels=None):
self.internal_model.load_state_dict(torch.load(fp))
if self.use_cell_types:
assert labels is not None
self.__store_parameters(labels)
else:
self.__store_parameters_no_celltypes()
def __store_parameters(self, labels):
"""
Replaces __cell_scores() and __compute factors() and __compute_theta()
store parameters after fitting the model:
cell scores
factors
eta
scalings
gene scalings
kappa
rho
"""
model = self.internal_model
# compute the loading matrix
k = sum(list(model.K.values()))
out = np.zeros((model.n, k))
global_idx = model.K["global"]
tot = global_idx
f = ["global"] * model.K["global"]
for cell_type in model.cell_types:
alpha = torch.exp(model.alpha[cell_type]).detach().numpy()
out[labels == cell_type, :global_idx] = alpha[:, :global_idx]
out[labels == cell_type, tot : tot + model.K[cell_type]] = alpha[
:, global_idx:
]
tot += model.K[cell_type]
f = f + [cell_type] * model.K[cell_type]
out2 = np.zeros((k, model.p))
theta_ct = torch.softmax(model.theta["global"], dim=1)
if model.kgeql_flag["global"] == False:
selection_ct = model.selection["global"].softmax(dim=1)
theta_ct = contract("ij,kj->ki", selection_ct, theta_ct)
theta = theta_ct.detach().numpy().T
tot = 0
out2[0 : theta.shape[0], :] = theta
tot += theta.shape[0]
for cell_type in model.cell_types:
theta_ct = torch.softmax(model.theta[cell_type], dim=1)
if model.kgeql_flag[cell_type] == False:
selection_ct = model.selection[cell_type].softmax(dim=1)
theta_ct = contract("ij,kj->ki", selection_ct, theta_ct)
theta = theta_ct.detach().numpy().T
out2[tot : tot + theta.shape[0], :] = theta
tot += theta.shape[0]
factors = out2
lst = []
for i in range(len(f)):
ct = f[i]
scaled = (
factors[i, :]
* (
model.gene_scaling[ct].exp().detach()
/ (1.0 + model.gene_scaling[ct].exp().detach())
+ model.delta
).numpy()
)
lst.append(scaled)
scaled = np.array(lst)
new_factors = scaled / (scaled.sum(axis=0, keepdims=True) + 1.0)
cell_scores = out * scaled.mean(axis=1).reshape(1, -1)
self.cell_scores = cell_scores
self.factors = new_factors
self.B_diag = self.__B_diag()
self.eta_matrices = self.__eta_matrices()
self.gene_scalings = {
ct: model.gene_scaling[ct].exp().detach().numpy()
/ (1.0 + model.gene_scaling[ct].exp().detach().numpy())
for ct in model.gene_scaling.keys()
}
self.rho = {
ct: model.rho[ct].exp().detach().numpy()
/ (1.0 + model.rho[ct].exp().detach().numpy())
for ct in model.rho.keys()
}
self.kappa = {
ct: model.kappa[ct].exp().detach().numpy()
/ (1.0 + model.kappa[ct].exp().detach().numpy())
for ct in model.kappa.keys()
}
self.selection = {
ct: model.selection[ct].softmax(dim=1).detach().numpy()
for ct in model.selection.keys()
}
def __B_diag(self):
model = self.internal_model
k = 0
for key in model.K.keys():
k += max(model.K[key], model.L[key])
out = np.zeros(k)
Bg = model.eta["global"].exp() / (1.0 + model.eta["global"].exp())
Bg = 0.5 * (Bg + Bg.T)
B = torch.diag(Bg).detach().numpy()
tot = 0
out[0 : B.shape[0]] = B
tot += B.shape[0]
for cell_type in model.cell_types:
Bg = model.eta[cell_type].exp() / (1.0 + model.eta[cell_type].exp())
Bg = 0.5 * (Bg + Bg.T)
B = torch.diag(Bg).detach().numpy()
out[tot : tot + B.shape[0]] = B
tot += B.shape[0]
return out
def __eta_matrices(self):
model = self.internal_model
eta = OrderedDict()
Bg = model.eta["global"].exp() / (1.0 + model.eta["global"].exp())
Bg = 0.5 * (Bg + Bg.T)
eta["global"] = Bg.detach().numpy()
for cell_type in model.cell_types:
Bg = model.eta[cell_type].exp() / (1.0 + model.eta[cell_type].exp())
Bg = 0.5 * (Bg + Bg.T)
eta[cell_type] = Bg.detach().numpy()
return eta
def __store_parameters_no_celltypes(self):
"""
store parameters after fitting the model:
cell scores
factors
eta
scalings
gene scalings
kappa
rho
"""
model = self.internal_model
alpha = torch.exp(model.alpha).detach().numpy()
out = alpha
if model.kgeql_flag:
theta_ct = torch.softmax(model.theta, dim=1)
else:
selection_ct = model.selection.softmax(dim=1)
theta_ct = torch.softmax(model.theta, dim=1)
theta_ct = contract("ij,kj->ki", selection_ct, theta_ct)
theta = theta_ct.detach().numpy().T
factors = theta
scaled = factors * (
model.gene_scaling.exp().detach()
/ (1.0 + model.gene_scaling.exp().detach())
+ model.delta
).numpy().reshape(1, -1)
new_factors = scaled / (scaled.sum(axis=0, keepdims=True) + 1.0)