-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathmodels.py
More file actions
1489 lines (1320 loc) · 57.8 KB
/
models.py
File metadata and controls
1489 lines (1320 loc) · 57.8 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
"""CBMR Models."""
import abc
import logging
from dataclasses import dataclass
import numpy as np
import pandas as pd
try:
import torch
except ImportError as e:
raise ImportError(
"Torch is required to use `CBMR` models. Install with `pip install 'nimare[cbmr]'`."
) from e
LGR = logging.getLogger(__name__)
@dataclass(frozen=True)
class _CBMRTensorInputs:
"""Container for tensorized CBMR design and response data."""
coef_spline_bases: torch.Tensor
moderators_by_group: object
foci_per_voxel: dict
foci_per_experiment: dict
def subset(self, groups):
"""Return a group-restricted view of the tensor inputs."""
moderators_by_group = None
if self.moderators_by_group is not None:
moderators_by_group = {group: self.moderators_by_group[group] for group in groups}
return _CBMRTensorInputs(
coef_spline_bases=self.coef_spline_bases,
moderators_by_group=moderators_by_group,
foci_per_voxel={group: self.foci_per_voxel[group] for group in groups},
foci_per_experiment={group: self.foci_per_experiment[group] for group in groups},
)
class SpatialCBMRModel(torch.nn.Module):
"""Torch log-Poisson model for spatially varying CBMR.
This model is used by :class:`~nimare.meta.spatial_cbmr.SpatialCBMREstimator`.
For experiment ``m`` and voxel ``v`` in group ``g``, the linear predictor is
``B(v) @ alpha_g + Z_m @ beta_g @ B(v).T``.
Parameters
----------
groups : :obj:`list` of :obj:`str`
Ordered group names.
spatial_coef_dim : :obj:`int`
Number of spatial B-spline bases.
moderators_coef_dim : :obj:`int`, optional
Number of experiment-level moderators. Default is None.
device : :obj:`str`, optional
Device to use for computations. Default is "cpu".
"""
def __init__(self, groups, spatial_coef_dim, moderators_coef_dim=None, device="cpu"):
"""Initialize the spatially varying CBMR torch module."""
super().__init__()
self.groups = groups
self.spatial_coef_dim = spatial_coef_dim
self.moderators_coef_dim = moderators_coef_dim
self.device = device
self.spatial_coef_linears = torch.nn.ModuleDict(
{group: torch.nn.Linear(spatial_coef_dim, 1, bias=False).double() for group in groups}
)
if moderators_coef_dim:
self.moderator_coef_linears = torch.nn.ModuleDict(
{
group: torch.nn.Linear(
spatial_coef_dim,
moderators_coef_dim,
bias=False,
).double()
for group in groups
}
)
else:
self.moderator_coef_linears = None
self.to(device)
def _linear_predictor(self, coef_spline_bases, moderators, group):
"""Return experiment-by-voxel linear predictors for one group."""
group_log_intensity = self.spatial_coef_linears[group](coef_spline_bases).T
if self.moderator_coef_linears is None or moderators is None:
return group_log_intensity
moderator_coef = self.moderator_coef_linears[group](coef_spline_bases).T
return group_log_intensity + moderators @ moderator_coef
@staticmethod
def _poisson_nll(linear_predictor, foci):
"""Return the log-Poisson negative log-likelihood."""
mean = torch.exp(linear_predictor)
return -(foci * linear_predictor - mean).mean()
def forward(self, coef_spline_bases, moderators_by_group, foci_by_experiment_voxel):
"""Compute the total negative log-likelihood across groups."""
loss = torch.tensor(0.0, dtype=torch.float64, device=self.device)
for group in self.groups:
moderators = moderators_by_group[group] if moderators_by_group is not None else None
linear_predictor = self._linear_predictor(coef_spline_bases, moderators, group)
loss = loss + self._poisson_nll(linear_predictor, foci_by_experiment_voxel[group])
return loss
class GeneralLinearModelEstimator(torch.nn.Module):
"""Base class for GLM estimators.
Parameters
----------
spatial_coef_dim : :obj:`int`
Number of spatial B-spline bases. Default is None.
moderators_coef_dim : :obj:`int`, optional
Number of experiment-level moderators. Default is None.
penalty : :obj:`bool`
Whether to Firth-type regularization term. Default is False.
lr : :obj:`float`
Learning rate. Default is 0.1.
lr_decay : :obj:`float`
Learning rate decay for each iteration. Default is 0.999.
n_iter : :obj:`int`
Maximum number of iterations. Default is 1000.
tol : :obj:`float`
Tolerance for convergence. Default is 1e-2.
device : :obj:`str`
Device to use for computations. Default is "cpu".
"""
_hessian_kwargs = {
"create_graph": False,
"vectorize": True,
"outer_jacobian_strategy": "forward-mode",
}
def __init__(
self,
spatial_coef_dim=None,
moderators_coef_dim=None,
penalty=False,
lr=1,
lr_decay=0.999,
n_iter=2000,
tol=1e-9,
device="cpu",
):
super().__init__()
self.spatial_coef_dim = spatial_coef_dim
self.moderators_coef_dim = moderators_coef_dim
self.penalty = penalty
self.lr = lr
self.lr_decay = lr_decay
self.n_iter = n_iter
self.tol = tol
self.device = device
# initialization for iteration set up
self.iter = 0
# after fitting, the following attributes will be created
self.spatial_regression_coef = None
self.spatial_intensity_estimation = None
self.moderators_coef = None
self.moderators_effect = None
self.spatial_regression_coef_se = None
self.log_spatial_intensity_se = None
self.spatial_intensity_se = None
self.se_moderators = None
self._tensor_inputs_cache = None
self._tensor_inputs_cache_keys = None
def _invalidate_tensor_inputs_cache(self):
"""Drop cached tensor inputs when model state or device changes."""
self._tensor_inputs_cache = None
self._tensor_inputs_cache_keys = None
@staticmethod
def _to_numpy_array(array_like):
"""Convert tensors or array-likes to NumPy arrays on the host."""
if torch.is_tensor(array_like):
return array_like.detach().cpu().numpy()
return np.asarray(array_like)
@staticmethod
def _flatten_tensor(tensor):
"""Return a 1D view of the provided tensor."""
if tensor is None:
return None
if not torch.is_tensor(tensor):
return torch.as_tensor(tensor).reshape(-1)
return tensor.reshape(-1)
def _as_float_tensor(self, array_like):
"""Convert array-like inputs to float64 tensors on the estimator device."""
if array_like is None:
return None
return torch.as_tensor(array_like, dtype=torch.float64, device=self.device)
def _prepare_tensor_inputs(
self,
coef_spline_bases,
moderators_by_group=None,
foci_per_voxel=None,
foci_per_experiment=None,
):
"""Normalize CBMR inputs into a reusable tensor container."""
if isinstance(coef_spline_bases, _CBMRTensorInputs):
return coef_spline_bases
if foci_per_voxel is None or foci_per_experiment is None:
raise ValueError(
"foci_per_voxel and foci_per_experiment are required for CBMR fitting."
)
if moderators_by_group is not None:
moderators_by_group = {
group: self._as_float_tensor(moderators_by_group[group]) for group in self.groups
}
return _CBMRTensorInputs(
coef_spline_bases=self._as_float_tensor(coef_spline_bases),
moderators_by_group=moderators_by_group,
foci_per_voxel={
group: self._as_float_tensor(foci_per_voxel[group]) for group in self.groups
},
foci_per_experiment={
group: self._as_float_tensor(foci_per_experiment[group]) for group in self.groups
},
)
def _cache_tensor_inputs(
self,
coef_spline_bases,
moderators_by_group,
foci_per_voxel,
foci_per_experiment,
tensor_inputs,
):
"""Cache tensorized inputs so repeated inference can reuse them."""
self._tensor_inputs_cache_keys = (
id(coef_spline_bases),
id(moderators_by_group),
id(foci_per_voxel),
id(foci_per_experiment),
)
self._tensor_inputs_cache = tensor_inputs
def _resolve_tensor_inputs(
self,
coef_spline_bases,
moderators_by_group=None,
foci_per_voxel=None,
foci_per_experiment=None,
):
"""Return cached tensor inputs when the current call matches the last fit inputs."""
if isinstance(coef_spline_bases, _CBMRTensorInputs):
return coef_spline_bases
input_keys = (
id(coef_spline_bases),
id(moderators_by_group),
id(foci_per_voxel),
id(foci_per_experiment),
)
if input_keys == self._tensor_inputs_cache_keys and self._tensor_inputs_cache is not None:
return self._tensor_inputs_cache
return self._prepare_tensor_inputs(
coef_spline_bases,
moderators_by_group,
foci_per_voxel,
foci_per_experiment,
)
@staticmethod
def _frame_from_uniform_group_dict(group_values):
"""Construct a DataFrame from same-length group vectors with minimal Python overhead."""
if not group_values:
return pd.DataFrame()
group_names = list(group_values.keys())
rows = [np.ravel(np.asarray(group_values[group])) for group in group_names]
n_columns = rows[0].size
if any(row.size != n_columns for row in rows[1:]):
return pd.DataFrame.from_dict(group_values, orient="index")
return pd.DataFrame(np.vstack(rows), index=group_names)
@abc.abstractmethod
def _log_likelihood_single_group(self, **kwargs):
"""Log-likelihood of a single group.
Returns
-------
torch.Tensor
Value of the log-likelihood of a single group.
"""
pass
@abc.abstractmethod
def _log_likelihood_mult_group(self, **kwargs):
"""Total log-likelihood of all groups in the dataset.
Returns
-------
torch.Tensor
Value of total log-likelihood of all groups in the dataset.
"""
pass
@abc.abstractmethod
def forward(self, **kwargs):
"""Define the loss function (nagetive log-likelihood function) for each model.
Returns
-------
torch.Tensor
Value of the log-likelihood of a single group.
"""
pass
def init_spatial_weights(self):
"""Initialize spatial regression coefficients.
Default is uniform distribution between -0.01 and 0.01.
"""
# initialization for spatial regression coefficients
spatial_coef_linears = dict()
for group in self.groups:
spatial_coef_linear_group = torch.nn.Linear(
self.spatial_coef_dim, 1, bias=False
).double()
torch.nn.init.uniform_(spatial_coef_linear_group.weight, a=-0.01, b=0.01)
spatial_coef_linears[group] = spatial_coef_linear_group
self.spatial_coef_linears = torch.nn.ModuleDict(spatial_coef_linears)
def init_moderator_weights(self):
"""Initialize the intercept and regression coefficients for moderators.
Default is uniform distribution between -0.01 and 0.01.
"""
self.moderators_linear = torch.nn.Linear(
self.moderators_coef_dim,
1,
bias=False,
).double()
torch.nn.init.uniform_(self.moderators_linear.weight, a=-0.01, b=0.01)
return
def init_weights(self, groups, moderators, spatial_coef_dim, moderators_coef_dim):
"""Initialize spatial and experiment-level moderator coefficients."""
self.groups = groups
self.moderators = moderators
self.spatial_coef_dim = spatial_coef_dim
self.moderators_coef_dim = moderators_coef_dim
self.init_spatial_weights()
if moderators_coef_dim:
self.init_moderator_weights()
self.to(self.device)
self._invalidate_tensor_inputs_cache()
def _update(
self,
optimizer,
coef_spline_bases,
moderators,
foci_per_voxel,
foci_per_experiment,
prev_loss,
):
"""One iteration in optimization with L-BFGS.
Adjust learning rate based on the number of iteration (with learning rate decay parameter
`lr_decay`, default value is 0.999). Reset L-BFGS optimizer (as params in the previous
iteration) if NaN occurs.
Parameters
----------
optimizer : :obj:`torch.optim.lbfgs.LBFGS`
L-BFGS optimizer.
coef_spline_bases : :obj:`torch.Tensor`
Coefficient of B-spline bases evaluated at each voxel.
moderators : :obj:`dict`, optional
Dictionary of group-wise experiment-level moderators. Default is None.
foci_per_voxel : :obj:`dict`
Dictionary of group-wise number of foci per voxel.
foci_per_experiment : :obj:`dict`
Dictionary of group-wise number of foci per experiment.
prev_loss : :obj:`torch.Tensor`
Value of the loss function of the previous iteration.
Returns
-------
torch.Tensor
Updated value of the loss (negative log-likelihood) function.
"""
self.iter += 1
scheduler = torch.optim.lr_scheduler.ExponentialLR(
optimizer, gamma=self.lr_decay
) # learning rate decay
def closure():
optimizer.zero_grad()
loss = self(coef_spline_bases, moderators, foci_per_voxel, foci_per_experiment)
loss.backward()
return loss
optimizer.step(closure)
scheduler.step()
# recalculate the loss function
loss = self(coef_spline_bases, moderators, foci_per_voxel, foci_per_experiment)
if torch.isnan(loss):
raise ValueError(
f"""The current learing rate {str(self.lr)} or choice of model gives rise to
NaN log-likelihood, please try Poisson model or adjust learning rate to a smaller
value."""
)
return loss
def _optimizer(
self,
coef_spline_bases,
moderators_by_group=None,
foci_per_voxel=None,
foci_per_experiment=None,
):
"""
Optimize the loss (negative log-likelihood) function with L-BFGS.
Parameters
----------
coef_spline_bases : :obj:`numpy.ndarray`
Coefficient of B-spline bases evaluated at each voxel.
moderators_by_group : :obj:`dict`, optional
Dictionary of group-wise experiment-level moderators.
foci_per_voxel : :obj:`dict`
Dictionary of group-wise number of foci per voxel.
foci_per_experiment : :obj:`dict`
Dictionary of group-wise number of foci per experiment.
"""
tensor_inputs = self._prepare_tensor_inputs(
coef_spline_bases,
moderators_by_group,
foci_per_voxel,
foci_per_experiment,
)
optimizer = torch.optim.LBFGS(
params=self.parameters(),
lr=self.lr,
max_iter=self.n_iter,
tolerance_change=self.tol,
line_search_fn="strong_wolfe",
)
prev_loss = torch.tensor(float("inf"), dtype=torch.float64, device=self.device)
self._update(
optimizer,
tensor_inputs.coef_spline_bases,
tensor_inputs.moderators_by_group,
tensor_inputs.foci_per_voxel,
tensor_inputs.foci_per_experiment,
prev_loss,
)
return
def fit(self, coef_spline_bases, moderators_by_group, foci_per_voxel, foci_per_experiment):
"""Fit the model and estimate standard error of estimates."""
tensor_inputs = self._prepare_tensor_inputs(
coef_spline_bases,
moderators_by_group,
foci_per_voxel,
foci_per_experiment,
)
self._cache_tensor_inputs(
coef_spline_bases,
moderators_by_group,
foci_per_voxel,
foci_per_experiment,
tensor_inputs,
)
self._optimizer(tensor_inputs)
self.extract_optimized_params(coef_spline_bases, moderators_by_group)
self.standard_error_estimation(tensor_inputs)
return
def extract_optimized_params(self, coef_spline_bases, moderators_by_group):
"""Extract optimized experiment-level moderator coefficients from the model."""
coef_spline_bases = np.asarray(coef_spline_bases)
spatial_regression_coef, spatial_intensity_estimation = dict(), dict()
for group in self.groups:
# Extract optimized spatial regression coefficients from the model
group_spatial_coef_linear_weight = self.spatial_coef_linears[group].weight
group_spatial_coef_linear_weight = self._to_numpy_array(
group_spatial_coef_linear_weight
).flatten()
spatial_regression_coef[group] = group_spatial_coef_linear_weight
# Estimate group-specific spatial intensity
group_spatial_intensity_estimation = np.exp(
np.matmul(coef_spline_bases, group_spatial_coef_linear_weight)
)
spatial_intensity_estimation["spatialIntensity_group-" + group] = (
group_spatial_intensity_estimation
)
# Extract optimized regression coefficient of experiment-level moderators from the model
if self.moderators_coef_dim:
moderators_effect = dict()
moderators_coef = self.moderators_linear.weight
moderators_coef = self._to_numpy_array(moderators_coef)
for group in self.groups:
group_moderators = moderators_by_group[group]
group_moderators_effect = np.exp(np.matmul(group_moderators, moderators_coef.T))
moderators_effect[group] = group_moderators_effect.flatten()
else:
moderators_coef, moderators_effect = None, None
self.spatial_regression_coef = spatial_regression_coef
self.spatial_intensity_estimation = spatial_intensity_estimation
self.moderators_coef = moderators_coef
self.moderators_effect = moderators_effect
def standard_error_estimation(
self,
coef_spline_bases,
moderators_by_group=None,
foci_per_voxel=None,
foci_per_experiment=None,
):
"""Estimate standard error of estimates.
For spatial regression coefficients, we estimate its covariance matrix using Fisher
Information Matrix and then take the square root of the diagonal elements.
For log spatial intensity, we use the delta method to estimate its standard error.
For models with over-dispersion parameter, we also estimate its standard error.
"""
tensor_inputs = self._prepare_tensor_inputs(
coef_spline_bases,
moderators_by_group,
foci_per_voxel,
foci_per_experiment,
)
coef_spline_bases_array = self._to_numpy_array(tensor_inputs.coef_spline_bases)
spatial_regression_coef_se, log_spatial_intensity_se, spatial_intensity_se = (
dict(),
dict(),
dict(),
)
for group in self.groups:
group_foci_per_voxel = tensor_inputs.foci_per_voxel[group]
group_foci_per_experiment = tensor_inputs.foci_per_experiment[group]
group_spatial_coef = self.spatial_coef_linears[group].weight
if self.moderators_coef_dim:
group_moderators = tensor_inputs.moderators_by_group[group]
moderators_coef = self.moderators_linear.weight
else:
group_moderators, moderators_coef = None, None
ll_single_group_kwargs = {
"moderators_coef": moderators_coef if self.moderators_coef_dim else None,
"coef_spline_bases": tensor_inputs.coef_spline_bases,
"group_moderators": group_moderators if self.moderators_coef_dim else None,
"group_foci_per_voxel": group_foci_per_voxel,
"group_foci_per_experiment": group_foci_per_experiment,
"device": self.device,
}
if hasattr(self, "overdispersion"):
ll_single_group_kwargs["group_overdispersion"] = self.overdispersion[group]
# create a negative log-likelihood function
def nll_spatial_coef(group_spatial_coef):
return -self._log_likelihood_single_group(
group_spatial_coef=group_spatial_coef,
**ll_single_group_kwargs,
)
f_spatial_coef = torch.func.hessian(nll_spatial_coef)(group_spatial_coef)
f_spatial_coef = f_spatial_coef.reshape((self.spatial_coef_dim, self.spatial_coef_dim))
cov_spatial_coef = np.linalg.inv(self._to_numpy_array(f_spatial_coef))
var_spatial_coef = np.diag(cov_spatial_coef)
se_spatial_coef = np.sqrt(var_spatial_coef)
spatial_regression_coef_se[group] = se_spatial_coef
var_log_spatial_intensity = np.einsum(
"ij,ji->i",
coef_spline_bases_array,
cov_spatial_coef @ coef_spline_bases_array.T,
)
se_log_spatial_intensity = np.sqrt(var_log_spatial_intensity)
log_spatial_intensity_se[group] = se_log_spatial_intensity
group_spatial_intensity = np.exp(
np.matmul(coef_spline_bases_array, self._to_numpy_array(group_spatial_coef).T)
).flatten()
se_spatial_intensity = group_spatial_intensity * se_log_spatial_intensity
spatial_intensity_se[group] = se_spatial_intensity
# Inference on regression coefficient of moderators
if self.moderators_coef_dim:
# modify ll_single_group_kwargs so that spatial_coef is fixed
# and moderators_coef can vary
del ll_single_group_kwargs["moderators_coef"]
ll_single_group_kwargs["group_spatial_coef"] = group_spatial_coef
def nll_moderators_coef(moderators_coef):
return -self._log_likelihood_single_group(
moderators_coef=moderators_coef,
**ll_single_group_kwargs,
)
f_moderators_coef = torch.func.hessian(nll_moderators_coef)(moderators_coef)
f_moderators_coef = f_moderators_coef.reshape(
(self.moderators_coef_dim, self.moderators_coef_dim)
)
cov_moderators_coef = np.linalg.inv(self._to_numpy_array(f_moderators_coef))
var_moderators = np.diag(cov_moderators_coef).reshape((1, self.moderators_coef_dim))
se_moderators = np.sqrt(var_moderators)
else:
se_moderators = None
self.spatial_regression_coef_se = spatial_regression_coef_se
self.log_spatial_intensity_se = log_spatial_intensity_se
self.spatial_intensity_se = spatial_intensity_se
self.se_moderators = se_moderators
def summary(self):
"""Summarize the main results of the fitted model.
Summarize optimized regression coefficients from model and store in `tables`,
summarize standard error of regression coefficient and (Log-)spatial intensity
and store in `results`.
"""
params = (
self.spatial_regression_coef,
self.spatial_intensity_estimation,
self.spatial_regression_coef_se,
self.log_spatial_intensity_se,
self.spatial_intensity_se,
)
if any([param is None for param in params]):
raise ValueError("Run fit first")
tables = dict()
# Extract optimized regression coefficients from model and store them in 'tables'
tables["spatial_regression_coef"] = self._frame_from_uniform_group_dict(
self.spatial_regression_coef
)
maps = self.spatial_intensity_estimation
if self.moderators_coef_dim:
tables["moderators_regression_coef"] = pd.DataFrame(
data=self.moderators_coef, columns=self.moderators
)
tables["moderators_effect"] = self._frame_from_uniform_group_dict(
self.moderators_effect
)
# Estimate standard error of regression coefficient and (Log-)spatial intensity and store
# them in 'tables'
tables["spatial_regression_coef_se"] = self._frame_from_uniform_group_dict(
self.spatial_regression_coef_se
)
tables["log_spatial_intensity_se"] = self._frame_from_uniform_group_dict(
self.log_spatial_intensity_se
)
tables["spatial_intensity_se"] = self._frame_from_uniform_group_dict(
self.spatial_intensity_se
)
if self.moderators_coef_dim:
tables["moderators_regression_se"] = pd.DataFrame(
data=self.se_moderators, columns=self.moderators
)
return maps, tables
def fisher_info_multiple_group_spatial(
self,
involved_groups,
coef_spline_bases,
moderators_by_group,
foci_per_voxel,
foci_per_experiment,
):
"""Estimate the Fisher information matrix of spatial regression coeffcients.
Fisher information matrix is estimated by negative Hessian of the log-likelihood.
Parameters
----------
involved_groups : :obj:`list`
Group names involved in generalized linear hypothesis (GLH) testing in `CBMRInference`.
coef_spline_bases : :obj:`numpy.ndarray`
Coefficient of B-spline bases evaluated at each voxel.
moderators_by_group : :obj:`dict`, optional
Dictionary of group-wise experiment-level moderators. Default is None.
foci_per_voxel : :obj:`dict`
Dictionary of group-wise number of foci per voxel.
foci_per_experiment : :obj:`dict`
Dictionary of group-wise number of foci per experiment.
Returns
-------
numpy.ndarray
Fisher information matrix of spatial regression coefficients (for involved groups).
"""
tensor_inputs = self._resolve_tensor_inputs(
coef_spline_bases,
moderators_by_group,
foci_per_voxel,
foci_per_experiment,
).subset(involved_groups)
n_involved_groups = len(involved_groups)
involved_foci_per_voxel = [
tensor_inputs.foci_per_voxel[group] for group in involved_groups
]
involved_foci_per_experiment = [
tensor_inputs.foci_per_experiment[group] for group in involved_groups
]
spatial_coef = [self.spatial_coef_linears[group].weight.T for group in involved_groups]
spatial_coef = torch.stack(spatial_coef, dim=0)
if self.moderators_coef_dim:
involved_moderators_by_group = [
tensor_inputs.moderators_by_group[group] for group in involved_groups
]
moderators_coef = self._as_float_tensor(self.moderators_coef.T)
else:
involved_moderators_by_group, moderators_coef = None, None
ll_mult_group_kwargs = {
"moderator_coef": moderators_coef,
"coef_spline_bases": tensor_inputs.coef_spline_bases,
"foci_per_voxel": involved_foci_per_voxel,
"foci_per_experiment": involved_foci_per_experiment,
"moderators": involved_moderators_by_group,
"device": self.device,
}
if hasattr(self, "overdispersion"):
ll_mult_group_kwargs["overdispersion_coef"] = [
self.overdispersion[group] for group in involved_groups
]
# create a negative log-likelihood function
def nll_spatial_coef(spatial_coef):
return -self._log_likelihood_mult_group(
spatial_coef=spatial_coef,
**ll_mult_group_kwargs,
)
h = torch.func.hessian(nll_spatial_coef)(spatial_coef)
h = h.view(n_involved_groups * self.spatial_coef_dim, -1)
return h.detach().cpu().numpy()
def fisher_info_multiple_group_moderator(
self, coef_spline_bases, moderators_by_group, foci_per_voxel, foci_per_experiment
):
"""Estimate the Fisher information matrix of regression coefficients of moderators.
Fisher information matrix is estimated by negative Hessian of the log-likelihood.
Parameters
----------
coef_spline_bases : :obj:`numpy.ndarray`
Coefficient of B-spline bases evaluated at each voxel.
moderators_by_group : :obj:`dict`, optional
Dictionary of group-wise experiment-level moderators. Default is None.
foci_per_voxel : :obj:`dict`
Dictionary of group-wise number of foci per voxel.
foci_per_experiment : :obj:`dict`
Dictionary of group-wise number of foci per experiment.
Returns
-------
numpy.ndarray
Fisher information matrix of experiment-level moderator regressors.
"""
tensor_inputs = self._resolve_tensor_inputs(
coef_spline_bases,
moderators_by_group,
foci_per_voxel,
foci_per_experiment,
)
foci_per_voxel = [tensor_inputs.foci_per_voxel[group] for group in self.groups]
foci_per_experiment = [tensor_inputs.foci_per_experiment[group] for group in self.groups]
spatial_coef = [self.spatial_coef_linears[group].weight.T for group in self.groups]
spatial_coef = torch.stack(spatial_coef, dim=0)
if self.moderators_coef_dim:
moderators_by_group = [
tensor_inputs.moderators_by_group[group] for group in self.groups
]
moderator_coef = self._as_float_tensor(self.moderators_coef.T)
else:
moderators_by_group, moderator_coef = None, None
ll_mult_group_kwargs = {
"spatial_coef": spatial_coef,
"coef_spline_bases": tensor_inputs.coef_spline_bases,
"foci_per_voxel": foci_per_voxel,
"foci_per_experiment": foci_per_experiment,
"moderators": moderators_by_group,
"device": self.device,
}
if hasattr(self, "overdispersion"):
ll_mult_group_kwargs["overdispersion_coef"] = [
self.overdispersion[group] for group in self.groups
]
# create a negative log-likelihood function w.r.t moderator coefficients
def nll_moderator_coef(moderator_coef):
return -self._log_likelihood_mult_group(
moderator_coef=moderator_coef,
**ll_mult_group_kwargs,
)
h = torch.func.hessian(nll_moderator_coef)(moderator_coef)
h = h.view(self.moderators_coef_dim, self.moderators_coef_dim)
return h.detach().cpu().numpy()
def firth_penalty(
self,
foci_per_voxel,
foci_per_experiment,
moderators,
coef_spline_bases,
overdispersion=False,
):
"""Compute Firth's penalized log-likelihood.
Parameters
----------
foci_per_voxel : :obj:`dict`
Dictionary of group-wise number of foci per voxel.
foci_per_experiment : :obj:`dict`
Dictionary of group-wise number of foci per experiment.
moderators : :obj:`dict`, optional
Dictionary of group-wise experiment-level moderators. Default is None.
coef_spline_bases : :obj:`torch.Tensor`
Coefficient of B-spline bases evaluated at each voxel.
overdispersion : :obj:`bool`
Whether the model contains overdispersion parameter. Default is False.
Returns
-------
torch.Tensor
Firth-type regularization term.
"""
group_firth_penalty = 0
for group in self.groups:
partial_kwargs = {"coef_spline_bases": coef_spline_bases}
if overdispersion:
partial_kwargs["group_overdispersion"] = self.overdispersion[group]
if getattr(self, "square_root", False):
partial_kwargs["group_overdispersion"] = (
partial_kwargs["group_overdispersion"] ** 2
)
partial_kwargs["group_foci_per_voxel"] = foci_per_voxel[group]
partial_kwargs["group_foci_per_experiment"] = foci_per_experiment[group]
if self.moderators_coef_dim:
moderators_coef = self.moderators_linear.weight
group_moderators = moderators[group]
else:
moderators_coef, group_moderators = None, None
partial_kwargs["moderators_coef"] = moderators_coef
partial_kwargs["group_moderators"] = group_moderators
# create a negative log-likelihood function w.r.t spatial coefficients
def nll_spatial_coef(group_spatial_coef):
return -self._log_likelihood_single_group(
group_spatial_coef=group_spatial_coef,
**partial_kwargs,
)
group_spatial_coef = self.spatial_coef_linears[group].weight
group_f = torch.autograd.functional.hessian(
nll_spatial_coef,
group_spatial_coef,
**self._hessian_kwargs,
)
group_f = group_f.reshape((self.spatial_coef_dim, self.spatial_coef_dim))
group_eig_vals = torch.real(torch.linalg.eigvals(group_f))
del group_f
group_firth_penalty = 0.5 * torch.sum(torch.log(group_eig_vals))
del group_eig_vals
group_firth_penalty += group_firth_penalty
return group_firth_penalty
class OverdispersionModelEstimator(GeneralLinearModelEstimator):
"""Base class for CBMR models with over-dispersion parameter."""
def __init__(self, **kwargs):
self.square_root = kwargs.pop("square_root", False)
super().__init__(**kwargs)
def init_overdispersion_weights(self):
"""Initialize weights for overdispersion parameters.
Default is 1e-2.
"""
overdispersion = dict()
for group in self.groups:
# initialization for alpha
overdispersion_init_group = torch.tensor(1e-2, dtype=torch.float64, device=self.device)
if self.square_root:
overdispersion_init_group = torch.sqrt(overdispersion_init_group)
overdispersion[group] = torch.nn.Parameter(
overdispersion_init_group, requires_grad=True
)
self.overdispersion = torch.nn.ParameterDict(overdispersion)
def init_weights(self, groups, moderators, spatial_coef_dim, moderators_coef_dim):
"""Initialize weights for spatial and experiment-level moderator coefficients."""
super().init_weights(groups, moderators, spatial_coef_dim, moderators_coef_dim)
self.init_overdispersion_weights()
self.to(self.device)
self._invalidate_tensor_inputs_cache()
def inference_outcome(
self, coef_spline_bases, moderators_by_group, foci_per_voxel, foci_per_experiment
):
"""Summarize inference outcome into `maps` and `tables`.
Add optimized overdispersion parameter to the tables.
"""
maps, tables = super().inference_outcome(
coef_spline_bases, moderators_by_group, foci_per_voxel, foci_per_experiment
)
overdispersion_param = dict()
for group in self.groups:
group_overdispersion = self.overdispersion[group]
group_overdispersion = group_overdispersion.cpu().detach().numpy()
overdispersion_param[group] = group_overdispersion
tables["overdispersion_coef"] = self._frame_from_uniform_group_dict(overdispersion_param)
tables["overdispersion_coef"].columns = ["overdispersion"]
return maps, tables
class PoissonEstimator(GeneralLinearModelEstimator):
"""CBMR framework with Poisson model.
Poisson model is the most basic model for Coordinate-based Meta-regression (CBMR).
It's based on the assumption that foci arise from a realisation of a (continues)
inhomogeneous Poisson process, so that the (discrete) voxel-wise foci counts will
be independently distributed as Poisson random variables, with rate equal to the
integral of the (true, unobserved, continous) intensity function over each voxels.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def fisher_info_multiple_group_spatial(
self,
involved_groups,
coef_spline_bases,
moderators_by_group,
foci_per_voxel,
foci_per_experiment,
):
"""Estimate the spatial Fisher information analytically for the Poisson model."""
tensor_inputs = self._resolve_tensor_inputs(
coef_spline_bases,
moderators_by_group,
foci_per_voxel,
foci_per_experiment,
).subset(involved_groups)
coef_spline_bases = tensor_inputs.coef_spline_bases
group_fisher = []
for group in involved_groups:
group_spatial_coef = self.spatial_coef_linears[group].weight.T
log_mu_spatial = torch.matmul(coef_spline_bases, group_spatial_coef).reshape(-1)
mu_spatial = torch.exp(log_mu_spatial)
if self.moderators_coef_dim:
moderators_coef = self.moderators_linear.weight.T
group_moderators = tensor_inputs.moderators_by_group[group]
sum_moderator_effect = torch.exp(
torch.matmul(group_moderators, moderators_coef).reshape(-1)
).sum()
else:
sum_moderator_effect = torch.tensor(
float(tensor_inputs.foci_per_experiment[group].shape[0]),
dtype=torch.float64,
device=coef_spline_bases.device,
)
weighted_design = coef_spline_bases * mu_spatial[:, None]
group_fisher.append(
sum_moderator_effect * torch.matmul(coef_spline_bases.T, weighted_design)