-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathaggregate.py
More file actions
332 lines (278 loc) · 11.5 KB
/
Copy pathaggregate.py
File metadata and controls
332 lines (278 loc) · 11.5 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
"""Weighted sum over an aggregate of different binding modes.
Members are explicitly re-exported in pyprobound.
"""
from __future__ import annotations
import math
from collections.abc import Iterable, Iterator
from typing import Literal, cast
import torch
from torch import Tensor
from typing_extensions import Self, override
from .base import Binding, BindingOptim, Call, Component, Spec, Transform
from .containers import TModuleList
class Contribution(Transform):
r"""Models the activity :math:`\alpha` of a Binding component.
.. math::
\alpha_a = \frac{[\text{P}_a]}{K_{\text{D}, a} (S_0)}
Attributes:
binding (Binding): The binding component whose contribution is modeled.
log_activity (Tensor): The activity :math:`\alpha` in log space.
"""
unfreezable = Literal[Transform.unfreezable, "activity"]
def __init__(
self,
binding: Binding,
train_activity: bool = True,
log_activity: float = float("-inf"),
activity_heuristic: float = 0.05,
) -> None:
r"""Initializes the contribution model.
Args:
binding: The Binding component whose contribution will be modeled.
train_activity: Whether to train the activity :math:`\alpha`.
log_activity: The initial value of `log_activity`.
activity_heuristic: The fraction of the total aggregate that the
contribution will be set to when it is first optimized.
"""
super().__init__()
if not 0 < activity_heuristic < 1:
raise ValueError(
f"activity_heuristic={activity_heuristic} is not 0 < frac < 1"
)
self.binding = binding
self.train_activity = train_activity
self.log_activity = torch.nn.Parameter(
torch.tensor(log_activity),
requires_grad=self.train_activity,
)
self.activity_heuristic = activity_heuristic
@override
def __repr__(self) -> str:
return f"{type(self).__name__}( {repr(self.binding)} )"
@override
def __str__(self) -> str:
if self.name != "":
return f"{type(self).__name__}-{self.name}"
return f"{type(self).__name__}( {str(self.binding)} )"
@override
def components(self) -> Iterator[Binding]:
yield self.binding
@override
def unfreeze(self, parameter: unfreezable = "all") -> None:
if parameter in ("activity", "all") and self.train_activity:
if torch.isneginf(self.log_activity):
raise ValueError(
"Cannot unfreeze activity without initializing it first"
)
self.log_activity.requires_grad_()
if parameter != "activity":
super().unfreeze(parameter)
def expected_log_contribution(self) -> float:
"""Calculates the expected log contribution."""
with torch.inference_mode():
training = self.training
self.eval()
out = self(self.binding.expected_sequence())
self.train(training)
return cast(float, out.item())
@override
@Transform.cache
def forward(self, seqs: Tensor) -> Tensor:
r"""Calculates the log contribution of a Binding to the Aggregate.
.. math::
\log \frac{\alpha_a}{K^{rel}_{\text{D}, a} (S_i)}
Args:
seqs: A sequence tensor of shape
:math:`(\text{minibatch},\text{length})` or
:math:`(\text{minibatch},\text{in_channels},\text{length})`.
Returns:
The log contribution tensor of shape :math:`(\text{minibatch},)`.
"""
return self.log_activity + self.binding(seqs)
def set_contribution(
self, log_contribution: float = 0, only_decrease: bool = False
) -> None:
"""Sets the activity so that E[log contribution] = `log_contribution`.
Args:
log_contribution: The new value of the expected log contribution.
only_decrease: If True, update the activity only if the
contribution would decrease
"""
log_activity = log_contribution - self.binding.expected_log_score()
if (
torch.isneginf(self.log_activity)
or not only_decrease
or log_activity < self.log_activity
):
torch.nn.init.constant_(self.log_activity, log_activity)
class Aggregate(Transform):
r"""Models the weighted sum over an aggregate of different binding modes.
.. math::
Z_{i} = \sum_a \frac{\alpha_a}{K^{rel}_{\text{D}, a} (S_i)}
Attributes:
contributions (TModuleList[Contribution]): The Contributions making up
the aggregate.
log_target_concentration (Tensor): The total protein concentration
:math:`[\text{P}]_T` in log space.
"""
unfreezable = Literal[Transform.unfreezable, "concentration"]
def __init__(
self,
contributions: Iterable[Contribution],
train_concentration: bool = False,
target_concentration: float = 1,
) -> None:
"""Initializes the aggregate.
Args:
contributions: The contributions making up the aggregate.
train_concentration: Whether to train the protein concentration.
target_concentration: Protein concentration, used for estimating
the free protein concentration.
"""
super().__init__()
self.train_concentration = train_concentration
self.log_target_concentration: Tensor = torch.nn.Parameter(
torch.tensor(math.log(target_concentration)),
requires_grad=train_concentration,
)
# Create contributions list
self.contributions: TModuleList[Contribution] = TModuleList(
contributions
)
binding = [ctrb.binding for ctrb in self.contributions]
if len(binding) != len(set(binding)):
raise ValueError(
"All Binding components in an Aggregate must be unique"
)
@classmethod
def from_binding(
cls,
binding: Iterable[Binding],
train_concentration: bool = False,
target_concentration: float = 1,
activity_heuristic: float = 0.05,
) -> Self:
r"""Creates a new instance from the binding modes.
Args:
binding: The binding modes driving enrichment.
train_concentration: Whether to train the protein concentration.
target_concentration: Protein concentration, used for estimating
the free protein concentration.
activity_heuristic: The fraction of the total aggregate that the
contribution will be set to when it is first optimized.
"""
return cls(
(
Contribution(bmd, activity_heuristic=activity_heuristic)
for bmd in binding
),
train_concentration=train_concentration,
target_concentration=target_concentration,
)
@override
def components(self) -> Iterator[Contribution]:
return iter(self.contributions)
def _contributing(self) -> Iterator[Contribution]:
"""Iterator over Contributions that contribute to the aggregate."""
for ctrb in self.contributions:
if not torch.isneginf(ctrb.log_activity):
yield ctrb
@override
def unfreeze(self, parameter: unfreezable = "all") -> None:
if parameter in ("concentration", "all"):
if self.train_concentration:
self.log_target_concentration.requires_grad_()
else:
raise ValueError(
f"{type(self).__name__} cannot unfreeze parameter {parameter}"
)
if parameter == "all":
for cmpt in self._contributing():
cmpt.unfreeze("all")
@override
def optim_procedure(
self,
ancestry: tuple[Component, ...] | None = None,
current_order: dict[tuple[Spec, ...], BindingOptim] | None = None,
) -> dict[tuple[Spec, ...], BindingOptim]:
# Call "activity_heuristic" during first step
# anywhere an aggregate is an ancestor
current_order = super().optim_procedure(ancestry, current_order)
key_to_ctrb = {ctrb.binding.key(): ctrb for ctrb in self.contributions}
for key, binding_optim in current_order.items():
ctrb = key_to_ctrb.get(key, None)
if ctrb is not None:
binding_optim.steps[0].calls.append(
Call(self, "activity_heuristic", {"contribution": ctrb})
)
binding_optim.merge_binding_optim()
return current_order
def expected_log_aggregate(self) -> float:
"""Calculates the expected log aggregate."""
with torch.inference_mode():
training = self.training
self.eval()
out = self(self.contributions[0].binding.expected_sequence())
self.train(training)
return cast(float, out.item())
@override
@Transform.cache
def forward(self, seqs: Tensor) -> Tensor:
r"""Calculates the log aggregate :math:`\log Z_i`.
.. math::
\log Z_{i} = \log\sum_a\frac{\alpha_a}{K^{rel}_{\text{D}, a} (S_i)}
Args:
seqs: A sequence tensor of shape
:math:`(\text{minibatch},\text{length})` or
:math:`(\text{minibatch},\text{in_channels},\text{length})`.
Returns:
The log aggregate tensor of shape :math:`(\text{minibatch},)`.
"""
out = torch.full(
(len(seqs),),
float("-inf"),
device=self.contributions[0].log_activity.device,
)
for ctrb in self._contributing():
out = torch.logaddexp(out, ctrb(seqs))
return self.log_target_concentration + out
def activity_heuristic(
self, contribution: Contribution, frac: float | None = None
) -> None:
"""Sets the activity so that E[contribution] = frac * E[aggregate].
Args:
contribution: The Contribution whose activity will be updated.
frac: The proportion of the aggregate the Binding contributes. If
None, uses the activity_heuristic attribute of Contribution.
"""
if frac is None:
frac = contribution.activity_heuristic
if not 0 < frac < 1:
raise ValueError(f"frac={frac} is not 0 < frac < 1")
expected_log_aggregate = (
self.expected_log_aggregate() - self.log_target_concentration
)
log_contribution = 0.0
if expected_log_aggregate != float("-inf"):
log_contribution = math.log(frac) + expected_log_aggregate
only_decrease = False
if not torch.isneginf(contribution.log_activity):
only_decrease = True
contribution.set_contribution(
log_contribution, only_decrease=only_decrease
)
if expected_log_aggregate != float("-inf"):
log_ctrb_shift = math.log(
2
- math.exp(
self.expected_log_aggregate()
- expected_log_aggregate
- self.log_target_concentration
)
)
for ctrb in self.contributions:
if ctrb is contribution:
continue
new_ctrb = log_ctrb_shift + ctrb.expected_log_contribution()
if math.isfinite(new_ctrb):
ctrb.set_contribution(new_ctrb, only_decrease=True)