loss.py 41.4 KB
Newer Older
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Copyright 2021 AlQuraishi Laboratory
# Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
16
from functools import partial
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import ml_collections
import numpy as np
import torch
import torch.nn as nn
from typing import Dict, Optional

from alphafold.np import residue_constants
from alphafold.model.primitives import Linear
from alphafold.utils.affine_utils import T
from alphafold.utils.tensor_utils import (
    tree_map, 
    tensor_tree_map, 
    masked_mean,
)


def softmax_cross_entropy(logits, labels):
    loss = -1 * torch.sum(
        labels * torch.nn.functional.log_softmax(logits),
        dim=-1,
    )
    return loss


Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
41
42
43
44
45
46
47
def sigmoid_cross_entropy(logits, labels):
    log_p = torch.nn.functional.logsigmoid(logits)
    log_not_p = torch.nn.functional.logsigmoid(-logits)
    loss = -labels * log_p - (1 - labels) * log_not_p
    return loss


Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
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
def torsion_angle_loss(
    a,           # [*, N, 7, 2]
    a_gt,        # [*, N, 7, 2]
    a_alt_gt,    # [*, N, 7, 2]
):
    # [*, N, 7]
    norm = torch.norm(a, dim=-1)

    # [*, N, 7, 2]
    a = a / norm.unsqueeze(-1)

    # [*, N, 7]
    diff_norm_gt = torch.norm(a - a_gt, dim=-1)
    diff_norm_alt_gt = torch.norm(a - a_alt_gt, dim=-1)
    min_diff = torch.minimum(diff_norm_gt ** 2, diff_norm_alt_gt ** 2)

    # [*]
    l_torsion = torch.mean(min_diff, dim=(-1, -2))
    l_angle_norm = torch.mean(torch.abs(norm - 1), dim=(-1, -2))

    an_weight = 0.02
    return l_torsion + an_weight * l_angle_norm


def compute_fape(
    pred_frames: T,
    target_frames: T,
    frames_mask: torch.Tensor,
    pred_positions: torch.Tensor,
    target_positions: torch.Tensor,
    positions_mask: torch.Tensor,
    length_scale: float,
    l1_clamp_distance: Optional[float] = None,
    eps=1e-4
) -> torch.Tensor:
    # [*, N_frames, N_pts, 3]
    local_pred_pos = pred_frames.invert()[..., None].apply(
        pred_positions[..., None, :, :],
    )
    local_target_pos = target_frames.invert()[..., None].apply(
        target_positions[..., None, :, :],
    )
    error_dist = torch.sqrt(
        (pred_positions - target_positions)**2 + eps
    )

    if(l1_clamp_distance is not None):
        error_dist = torch.clamp(error_dist, min=0, max=l1_clamp_distance)

    normed_error = error_dist / length_scale
    normed_error *= frames_mask.unsqueeze(-1)
    normed_error *= positions_mask.unsqueeze(-2)

    norm_factor = (
        torch.sum(frames_mask, dim=-1) *
        torch.sum(positions_mask, dim=-1)
    )

    normed_error = torch.sum(normed_error, dim=(-1, -2)) / (eps + norm_factor)

    return normed_error


def backbone_loss(
    batch: Dict[str, torch.Tensor],
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
113
    pred_aff_tensor: torch.Tensor,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
114
115
116
    clamp_distance: float = 10.,
    loss_unit_distance: float = 10.,
) -> torch.Tensor:
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
117
118
119
    pred_aff = T.from_tensor(pred_aff_tensor)
    gt_aff = T.from_tensor(batch["backbone_affine_tensor"])
    backbone_mask = batch["backbone_affine_mask"]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
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
    
    fape_loss = compute_fape(
        pred_aff,
        gt_aff,
        backbone_mask,
        pred_aff.get_trans(),
        gt_aff.get_trans(),
        backbone_mask,
        l1_clamp_distance=clamp_distance,
        length_scale=loss_unit_distance,
    )

    if('use_clamped_fape' in batch):
        use_clamped_fape = batch["use_clamped_fape"]
        unclamped_fape_loss = compute_fape(
            pred_aff,
            gt_aff,
            backbone_mask,
            pred_aff.get_trans(),
            gt_aff.get_trans(),
            backbone_mask,
            l1_clamp_distance=None,
            length_scale=loss_unit_distance,
        )

        fape_loss = (
            fape_loss * use_clamped_fape +
            fape_loss_unclamped * (1 - use_clamped_fape)
        )

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
150
    return torch.mean(fape_loss, dim=-1)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
151
152
153
154
155


def sidechain_loss(
    sidechain_frames,
    sidechain_atom_pos,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
156
157
158
    rigidgroups_gt_frames,
    rigidgroups_alt_gt_frames,
    rigidgroups_gt_exists,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
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
    renamed_atom14_gt_positions,
    renamed_atom14_gt_exists,
    alt_naming_is_better,
    clamp_distance=10.,
    length_scale=10.,
):
    renamed_gt_frames = (
        (1. - alt_naming_is_better[..., None, None, None, None]) *
        gt_frames +
        alt_naming_is_better[..., None, None, None, None] *
        alt_gt_frames
    )

    renamed_gt_frames = T.from_4x4(renamed_gt_frames) 

    fape = compute_fape(
        sidechain_frames,
        renamed_gt_frames,
        gt_exists,
        sidechain_atom_pos,
        renamed_atom14_gt_positions,
        renamed_atom14_gt_exists,
        l1_clamp_distance=clamp_distance,
        length_scale=length_scale,
    )

    return fape
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
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


def fape_loss(
    out: Dict[str, torch.Tensor],
    batch: Dict[str, torch.Tensor],
    config: ml_collections.ConfigDict,
) -> torch.Tensor:
    bb_loss = backbone_loss(
        batch, out["sm"]["frames"][-1], **config.backbone
    )

    sc_loss = sidechain_loss(
        out["sm"]["sidechain_frames"],
        out["sm"]["positions"],
        {
            **batch,
            **config.sidechain,
        },
    )

    return (
        config.backbone.weight * bb_loss +
        config.sidechain.weight * sc_loss
    )


def supervised_chi_loss(
    angles_sin_cos: torch.Tensor,
    unnormalized_angles_sin_cos: torch.Tensor,
    aatype: torch.Tensor,
    seq_mask: torch.Tensor,
    chi_mask: torch.Tensor,
    chi_angles: torch.Tensor,
    chi_weight: float,
    angle_norm_weight: float,
    eps=1e-6,
) -> torch.Tensor:
    pred_angles = angles_sin_cos[..., 3:, :]
    residue_type_one_hot = torch.nn.functional.one_hot(
        aatype, residue_constants.restype_num + 1,
    ).unsqueeze(-3)
    chi_pi_periodic = torch.einsum(
        "...ij,jk->ik", 
        residue_type_one_hot, 
        aatype.new_tensor(residue_constants.chi_pi_periodic)
    )

    true_chi = chi_angles.unsqueeze(-3)
    sin_true_chi = torch.sin(true_chi)
    cos_true_chi = torch.cos(true_chi)
    sin_cos_true_chi = torch.stack([sin_true_chi, cos_true_chi], dim=-1)

    shifted_mask = (1 - 2 * chi_pi_periodic).unsqueeze(-1)
    sin_cos_true_chi_shifted = shifted_mask * sin_cos_true_chi

    sq_chi_error = torch.sum(
        (sin_cos_true_chi - pred_angles)**2, dim=-1
    )
    sq_chi_error_shifted = torch.sum(
        (sin_cos_true_chi_shifted - pred_angles)**2, dim=-1
    )
    sq_chi_error = torch.minimum(sq_chi_error, sq_chi_error_shifted)

    sq_chi_loss = masked_mean(
        sq_chi_error, chi_mask.unsqueeze(-3), dim=(-1, -2, -3)
    )
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
252
    
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
    loss = 0
    loss += chi_weight * sq_chi_loss

    angle_norm = torch.sqrt(
        torch.sum(unnormalized_angles_sin_cos**2, dim=-1) + eps
    )
    norm_error = torch.abs(angle_norm - 1.)
    angle_norm_loss = masked_mean(
        norm_error, sequence_mask[..., None, :, None], dim=(-1, -2, -3)
    )

    loss += angle_norm_weight * angle_norm_loss

    return loss

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284

def compute_plddt(logits: torch.Tensor) -> torch.Tensor:
    num_bins = logits.shape[-1]
    bin_width = 1. / num_bins
    bounds = torch.arange(
        start=0.5 * bin_width, end=1.0, step=bin_width, device=logits.device
    )
    probs = torch.nn.functional.softmax(logits, dim=-1)
    pred_lddt_ca = torch.sum(
        probs * 
        bounds.view(*((1,) * len(probs.shape[:-1])), *bounds.shape),
        dim=-1,
    )
    return pred_lddt_ca * 100


def lddt_loss(
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
285
286
287
288
289
    logits: torch.Tensor,
    all_atom_pred_pos: torch.Tensor,
    all_atom_positions: torch.Tensor,
    all_atom_mask: torch.Tensor,
    resolution: torch.Tensor,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
290
291
292
293
294
    cutoff: float = 15.,
    num_bins: int = 50,
    min_resolution: float = 0.1,
    max_resolution: float = 3.0,
    eps: float = 1e-10,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
295
    **kwargs,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
296
) -> torch.Tensor:
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
297
    all_atom_positions = batch["all_atom_positions"]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
298
299
300
301
    all_atom_mask = batch["all_atom_mask"]

    n = all_atom_mask.shape[-1]
   
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
302
    ca_pos = residue_constants.atom_order["CA"]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
303
    all_atom_pred_pos = all_atom_pred_pos[..., :, ca_pos, :]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
304
    all_atom_positions = all_atom_positions[..., :, ca_pos, :]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
305
306
307
308
309
310
    all_atom_mask = all_atom_mask[..., :, ca_pos:(ca_pos + 1)] # keep dim

    dmat_true = torch.sqrt(
        eps +
        torch.sum(
            (
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
311
312
                all_atom_positions[..., None] - 
                all_atom_positions[..., None, :]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
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
            )**2,
            dim=-1,
        )
    )

    dmat_pred = torch.sqrt(
        eps +
        torch.sum(
            (
                all_atom_pred_pos[..., None] - 
                all_atom_pred_pos[..., None, :]

            )**2,
            dim=-1,
        )
    )

    dists_to_score = (
        (dmat_true < cutoff) * all_atom_mask *
        permute_final_dims(all_atom_mask, 1, 0) *
        (1. - torch.eye(n, device=all_atom_mask.device))
    )

    dist_l1 = torch.abs(dmat_true - dmat_pred)

    score = (
        (dist_l1 < 0.5) + 
        (dist_l1 < 1.0) +
        (dist_l1 < 2.0) +
        (dist_l1 < 4.0)
    )
    score *= 0.25

    norm = 1. / (eps + torch.sum(dists_to_score, dim=-1))
    score = norm * (eps + torch.sum(dists_to_score * score, dim=-1))

    # TODO: this feels a bit weird, but it's in the source
    score = score.detach() 

    bin_index = torch.floor(lddt_ca * num_bins)

    lddt_ca_one_hot = torch.nn.functional.one_hot(
        bin_index, num_classes=num_bins
    )

    errors = softmax_cross_entropy(logits, lddt_ca_one_hot)

    loss = torch.sum(errors * all_atom_mask) / (torch.sum(mask_ca) + eps)

    loss *= (
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
363
364
        (resolution >= min_resolution) &
        (resolution <= max_resolution)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
365
366
367
368
369
370
    )

    return loss


def distogram_loss(
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
371
372
373
374
375
376
377
378
    logits, 
    pseudo_beta, 
    pseudo_beta_mask, 
    min_bin=2.3125, 
    max_bin=21.6875, 
    no_bins=64, 
    eps=1e-6,
    **kwargs,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
379
380
):
    boundaries = torch.linspace(
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
381
        min_bin, max_bin, no_bins - 1, device=logits.device,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
382
383
384
385
    )
    boundaries = boundaries ** 2

    dists = torch.sum(
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
386
387
388
389
390
        (
            pseudo_beta[..., None, :] - pseudo_beta[..., None, :, :]
        ) ** 2, 
        dim=-1, 
        keepdims=True
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
391
392
393
394
395
    )

    true_bins = torch.sum(dists > sq_breaks, dim=-1)

    errors = softmax_cross_entropy(
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
396
        logits,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
397
398
399
        torch.nn.functional.one_hot(true_bins, num_bins),
    )

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
400
    square_mask = pseudo_beta_mask[..., None] * pseudo_beta_mask[..., None, :]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
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

    mean = (
        torch.sum(errors * square_mask, dim=(-1, -2)) /
        (eps + torch.sum(square_mask, dim=(-1, -2)))
    )

    return mean


def tm_score(
    logits,
    t_pred, 
    t_gt, 
    mask, 
    resolution,
    max_bin=31, 
    no_bins=64, 
    min_resolution: float = 0.1,
    max_resolution: float = 3.0,
    eps=1e-8
):
    boundaries = torch.linspace(
        min=0, 
        max=max_bin, 
        steps=(no_bins - 1), 
        device=logits.device
    )
    boundaries = boundaries ** 2

    def _points(affine):
        pts = affine.trans.unsqueeze(-3)
        return affine.invert().apply(pts, addl_dims=1)

    sq_diff = torch.sum((_points(t_pred) - _points(t_gt)) ** 2, dim=-1)
    sq_diff = sq_diff.detach()

    true_bins = torch.sum(
        sq_diff[..., None] > boundaries
    ).float()

    errors = softmax_cross_entropy(
        logits,
        torch.nn.functional.one_hot(true_bins, no_bins)
    )

    square_mask = mask[..., None] * mask[..., None, :]

    loss = (
        torch.sum(loss, dim=(-1, -2)) /
        (eps + torch.sum(square_mask, dim=(-1, -2)))
    )

    loss *= (
        (resolution >= min_resolution) &
        (resolution <= max_resolution)
    )

    return loss


def between_residue_bond_loss(
    pred_atom_positions: torch.Tensor,  # (N, 37(14), 3)
    pred_atom_mask: torch.Tensor,  # (N, 37(14))
    residue_index: torch.Tensor,  # (N)
    aatype: torch.Tensor,  # (N)
    tolerance_factor_soft=12.0,
    tolerance_factor_hard=12.0,
    eps=1e-6,
) -> Dict[str, torch.Tensor]:
    """Flat-bottom loss to penalize structural violations between residues.
  
    This is a loss penalizing any violation of the geometry around the peptide
    bond between consecutive amino acids. This loss corresponds to
    Jumper et al. (2021) Suppl. Sec. 1.9.11, eq 44, 45.
  
    Args:
      pred_atom_positions: Atom positions in atom37/14 representation
      pred_atom_mask: Atom mask in atom37/14 representation
      residue_index: Residue index for given amino acid, this is assumed to be
        monotonically increasing.
      aatype: Amino acid type of given residue
      tolerance_factor_soft: soft tolerance factor measured in standard deviations
        of pdb distributions
      tolerance_factor_hard: hard tolerance factor measured in standard deviations
        of pdb distributions
  
    Returns:
      Dict containing:
        * 'c_n_loss_mean': Loss for peptide bond length violations
        * 'ca_c_n_loss_mean': Loss for violations of bond angle around C spanned
            by CA, C, N
        * 'c_n_ca_loss_mean': Loss for violations of bond angle around N spanned
            by C, N, CA
        * 'per_residue_loss_sum': sum of all losses for each residue
        * 'per_residue_violation_mask': mask denoting all residues with violation
            present.
    """
    # Get the positions of the relevant backbone atoms.
    this_ca_pos = pred_atom_positions[..., :-1, 1, :]
    this_ca_mask = pred_atom_mask[..., :-1, 1]
    this_c_pos = pred_atom_positions[..., :-1, 2, :]
    this_c_mask = pred_atom_mask[..., :-1, 2]
    next_n_pos = pred_atom_positions[..., 1:, 0, :]
    next_n_mask = pred_atom_mask[..., 1:, 0]
    next_ca_pos = pred_atom_positions[..., 1:, 1, :]
    next_ca_mask = pred_atom_mask[..., 1:, 1]
    has_no_gap_mask = (
        (residue_index[..., 1:] - residue_index[..., :-1]) == 1.0
    )
  
    # Compute loss for the C--N bond.
    c_n_bond_length = torch.sqrt(
        eps + 
        torch.sum(
            (this_c_pos - next_n_pos)**2, dim=-1
        )
    )
  
    # The C-N bond to proline has slightly different length because of the ring.
    next_is_proline = (
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
521
        aatype[..., 1:] == residue_constants.resname_to_idx["PRO"]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
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
    )
    gt_length = (
        (~next_is_proline) * residue_constants.between_res_bond_length_c_n[0]
        + next_is_proline * residue_constants.between_res_bond_length_c_n[1]
    )
    gt_stddev = (
        (~next_is_proline) *
        residue_constants.between_res_bond_length_stddev_c_n[0] +
        next_is_proline * 
        residue_constants.between_res_bond_length_stddev_c_n[1]
    )
    c_n_bond_length_error = torch.sqrt(
        eps + (c_n_bond_length - gt_length)**2
    )
    c_n_loss_per_residue = torch.nn.functional.relu(
        c_n_bond_length_error - tolerance_factor_soft * gt_stddev
    )
    mask = this_c_mask * next_n_mask * has_no_gap_mask
    c_n_loss = torch.sum(mask * c_n_loss_per_residue) / (torch.sum(mask) + eps)
    c_n_violation_mask = mask * (
        c_n_bond_length_error > (tolerance_factor_hard * gt_stddev)
    )
  
    # Compute loss for the angles.
    ca_c_bond_length = torch.sqrt(
        eps + torch.sum((this_ca_pos - this_c_pos)**2, dim=-1)
    )
    n_ca_bond_length = torch.sqrt(
        eps + torch.sum((next_n_pos - next_ca_pos)**2, dim=-1)
    )
  
    c_ca_unit_vec = (this_ca_pos - this_c_pos) / ca_c_bond_length[..., None]
    c_n_unit_vec = (next_n_pos - this_c_pos) / c_n_bond_length[..., None]
    n_ca_unit_vec = (next_ca_pos - next_n_pos) / n_ca_bond_length[..., None]
  
    ca_c_n_cos_angle = torch.sum(c_ca_unit_vec * c_n_unit_vec, dim=-1)
    gt_angle = residue_constants.between_res_cos_angles_ca_c_n[0]
    gt_stddev = residue_constants.between_res_bond_length_stddev_c_n[0]
    ca_c_n_cos_angle_error = torch.sqrt(
        eps + (ca_c_n_cos_angle - gt_angle)**2
    )
    ca_c_n_loss_per_residue = torch.nn.functional.relu(
        ca_c_n_cos_angle_error - tolerance_factor_soft * gt_stddev
    )
    mask = this_ca_mask * this_c_mask * next_n_mask * has_no_gap_mask
    ca_c_n_loss = (
        torch.sum(mask * ca_c_n_loss_per_residue) / (torch.sum(mask) + eps)
    )
    ca_c_n_violation_mask = mask * (ca_c_n_cos_angle_error >
                                    (tolerance_factor_hard * gt_stddev))
  
    c_n_ca_cos_angle = torch.sum((-c_n_unit_vec) * n_ca_unit_vec, dim=-1)
    gt_angle = residue_constants.between_res_cos_angles_c_n_ca[0]
    gt_stddev = residue_constants.between_res_cos_angles_c_n_ca[1]
    c_n_ca_cos_angle_error = torch.sqrt(
        eps + torch.square(c_n_ca_cos_angle - gt_angle))
    c_n_ca_loss_per_residue = torch.nn.functional.relu(
        c_n_ca_cos_angle_error - tolerance_factor_soft * gt_stddev
    )
    mask = this_c_mask * next_n_mask * next_ca_mask * has_no_gap_mask
    c_n_ca_loss = (
        torch.sum(mask * c_n_ca_loss_per_residue) / (torch.sum(mask) + eps)
    )
    c_n_ca_violation_mask = mask * (
        c_n_ca_cos_angle_error > (tolerance_factor_hard * gt_stddev)
    )
  
    # Compute a per residue loss (equally distribute the loss to both
    # neighbouring residues).
    per_residue_loss_sum = (c_n_loss_per_residue +
                            ca_c_n_loss_per_residue +
                            c_n_ca_loss_per_residue)
    per_residue_loss_sum = 0.5 * (
        torch.nn.functional.pad(per_residue_loss_sum, (0, 1)) +
        torch.nn.functional.pad(per_residue_loss_sum, (1, 0))
    )
 
    # Compute hard violations.
    violation_mask = torch.max(
        torch.stack(
            [
                c_n_violation_mask,
                ca_c_n_violation_mask,
                c_n_ca_violation_mask
            ]
        ), 
        dim=-2
    )[0]
    violation_mask = torch.maximum(
        torch.nn.functional.pad(violation_mask, (0, 1)),
        torch.nn.functional.pad(violation_mask, (1, 0))
    )
  
    return {
        'c_n_loss_mean': c_n_loss,
        'ca_c_n_loss_mean': ca_c_n_loss,
        'c_n_ca_loss_mean': c_n_ca_loss,
        'per_residue_loss_sum': per_residue_loss_sum,
        'per_residue_violation_mask': violation_mask
    }


def between_residue_clash_loss(
    atom14_pred_positions: torch.Tensor,
    atom14_atom_exists: torch.Tensor,
    atom14_atom_radius: torch.Tensor,
    residue_index: torch.Tensor,
    overlap_tolerance_soft=1.5,
    overlap_tolerance_hard=1.5,
    eps=1e-10,
) -> Dict[str, torch.Tensor]:
    """Loss to penalize steric clashes between residues.
  
    This is a loss penalizing any steric clashes due to non bonded atoms in
    different peptides coming too close. This loss corresponds to the part with
    different residues of
    Jumper et al. (2021) Suppl. Sec. 1.9.11, eq 46.
  
    Args:
      atom14_pred_positions: Predicted positions of atoms in
        global prediction frame
      atom14_atom_exists: Mask denoting whether atom at positions exists for given
        amino acid type
      atom14_atom_radius: Van der Waals radius for each atom.
      residue_index: Residue index for given amino acid.
      overlap_tolerance_soft: Soft tolerance factor.
      overlap_tolerance_hard: Hard tolerance factor.
  
    Returns:
      Dict containing:
        * 'mean_loss': average clash loss
        * 'per_atom_loss_sum': sum of all clash losses per atom, shape (N, 14)
        * 'per_atom_clash_mask': mask whether atom clashes with any other atom
            shape (N, 14)
    """
    fp_type = atom14_pred_positions.dtype
    
    # Create the distance matrix.
    # (N, N, 14, 14)
    dists = torch.sqrt(
        eps + 
        torch.sum(
            (
                atom14_pred_positions[..., :, None, :, None, :] -
                atom14_pred_positions[..., None, :, None, :, :]
            )**2,
            dim=-1)
    )
  
    # Create the mask for valid distances.
    # shape (N, N, 14, 14)
    dists_mask = (
        atom14_atom_exists[..., :, None, :, None] *
        atom14_atom_exists[..., None, :, None, :]
    ).type(fp_type)
  
    # Mask out all the duplicate entries in the lower triangular matrix.
    # Also mask out the diagonal (atom-pairs from the same residue) -- these atoms
    # are handled separately.
    dists_mask *= (
        residue_index[..., :, None, None, None] < residue_index[..., None, :, None, None]
    )
  
    # Backbone C--N bond between subsequent residues is no clash.
    c_one_hot = torch.nn.functional.one_hot(
        residue_index.new_tensor(2), num_classes=14
    )
    c_one_hot = c_one_hot.reshape(
        *((1,) * len(residue_index.shape[:-1])), *c_one_hot.shape
    )
    c_one_hot = c_one_hot.type(fp_type)
    n_one_hot = torch.nn.functional.one_hot(
        residue_index.new_tensor(0), num_classes=14
    )
    n_one_hot = n_one_hot.reshape(
        *((1,) * len(residue_index.shape[:-1])), *n_one_hot.shape
    )
    n_one_hot = n_one_hot.type(fp_type)

    neighbour_mask = (
        (residue_index[..., :, None, None, None] + 1) == 
        residue_index[..., None, :, None, None]
    )
    c_n_bonds = (
        neighbour_mask * 
        c_one_hot[..., None, None, :, None] * 
        n_one_hot[..., None, None, None, :]
    )
    dists_mask *= (1. - c_n_bonds)
  
    # Disulfide bridge between two cysteines is no clash.
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
713
    cys = residue_constants.restype_name_to_atom14_names["CYS"]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
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
    cys_sg_idx = cys.index('SG')
    cys_sg_idx = residue_index.new_tensor(cys_sg_idx)
    cys_sg_idx = cys_sg_idx.reshape(
        *((1,) * len(residue_index.shape[:-1])), 1 
    ).squeeze(-1)
    cys_sg_one_hot = torch.nn.functional.one_hot(
        cys_sg_idx, num_classes=14
    )
    disulfide_bonds = (
        cys_sg_one_hot[..., None, None, :, None] *
        cys_sg_one_hot[..., None, None, None, :])
    dists_mask *= (1. - disulfide_bonds)
  
    # Compute the lower bound for the allowed distances.
    # shape (N, N, 14, 14)
    dists_lower_bound = dists_mask * (
        atom14_atom_radius[..., :, None, :, None] +
        atom14_atom_radius[..., None, :, None, :]
    )
  
    # Compute the error.
    # shape (N, N, 14, 14)
    dists_to_low_error = dists_mask * torch.nn.functional.relu(
        dists_lower_bound - overlap_tolerance_soft - dists
    )
  
    # Compute the mean loss.
    # shape ()
    mean_loss = (
        torch.sum(dists_to_low_error) / (1e-6 + torch.sum(dists_mask))
    )
  
    # Compute the per atom loss sum.
    # shape (N, 14)
    per_atom_loss_sum = (
        torch.sum(dists_to_low_error, dim=(-4, -2)) +
        torch.sum(dists_to_low_error, axis=(-3, -1))
    )
  
    # Compute the hard clash mask.
    # shape (N, N, 14, 14)
    clash_mask = dists_mask * (
        dists < (dists_lower_bound - overlap_tolerance_hard)
    )
  
    # Compute the per atom clash.
    # shape (N, 14)
    per_atom_clash_mask = torch.maximum(
        torch.amax(clash_mask, axis=(-4, -2)),
        torch.amax(clash_mask, axis=(-3, -1)),
    )
  
    return {
        'mean_loss': mean_loss,  # shape ()
        'per_atom_loss_sum': per_atom_loss_sum,  # shape (N, 14)
        'per_atom_clash_mask': per_atom_clash_mask  # shape (N, 14)
    }


def within_residue_violations(
    atom14_pred_positions: torch.Tensor,
    atom14_atom_exists: torch.Tensor,
    atom14_dists_lower_bound: torch.Tensor,
    atom14_dists_upper_bound: torch.Tensor,
    tighten_bounds_for_loss=0.0,
    eps=1e-10,
) -> Dict[str, torch.Tensor]:
    """Loss to penalize steric clashes within residues.
  
    This is a loss penalizing any steric violations or clashes of non-bonded atoms
    in a given peptide. This loss corresponds to the part with
    the same residues of
    Jumper et al. (2021) Suppl. Sec. 1.9.11, eq 46.
  
    Args:
        atom14_pred_positions ([*, N, 14, 3]): 
            Predicted positions of atoms in global prediction frame.
        atom14_atom_exists ([*, N, 14]): 
            Mask denoting whether atom at positions exists for given
            amino acid type
        atom14_dists_lower_bound ([*, N, 14]): 
            Lower bound on allowed distances.
        atom14_dists_upper_bound ([*, N, 14]): 
            Upper bound on allowed distances
        tighten_bounds_for_loss ([*, N]): 
            Extra factor to tighten loss
  
    Returns:
      Dict containing:
        * 'per_atom_loss_sum' ([*, N, 14]): 
              sum of all clash losses per atom, shape
        * 'per_atom_clash_mask' ([*, N, 14]): 
              mask whether atom clashes with any other atom shape 
    """  
    # Compute the mask for each residue.
    dists_masks = (
        1. - torch.eye(14, device=atom14_atom_exists.device)[None]
    )
    dists_masks = dists_masks.reshape(
        *((1,) * len(atom14_atom_exists.shape[:-2])), *dists_masks.shape
    )
    dists_masks = (
        atom14_atom_exists[..., :, :, None] *
        atom14_atom_exists[..., :, None, :] *
        dists_masks
    )
  
    # Distance matrix
    dists = torch.sqrt(
        eps + 
        torch.sum(
            (
                atom14_pred_positions[..., :, :, None, :] -
                atom14_pred_positions[..., :, None, :, :]
            )**2,
            dim=-1
        )
    )

    # Compute the loss.
    dists_to_low_error = torch.nn.functional.relu(
        atom14_dists_lower_bound + tighten_bounds_for_loss - dists
    )
    dists_to_high_error = torch.nn.functional.relu(
        dists - (atom14_dists_upper_bound - tighten_bounds_for_loss)
    )
    loss = dists_masks * (dists_to_low_error + dists_to_high_error)
  
    # Compute the per atom loss sum.
    per_atom_loss_sum = (
        torch.sum(loss, dim=-2) +
        torch.sum(loss, dim=-1)
    )
  
    # Compute the violations mask.
    violations = (
        dists_masks * 
        (
            (dists < atom14_dists_lower_bound) |
            (dists > atom14_dists_upper_bound)
        )
    )
  
    # Compute the per atom violations.
    per_atom_violations = torch.maximum(
        torch.max(violations, dim=-2)[0], torch.max(violations, axis=-1)[0]
    )
  
    return {
        'per_atom_loss_sum': per_atom_loss_sum,
        'per_atom_violations': per_atom_violations
    }



def find_structural_violations(
    batch: Dict[str, torch.Tensor],
    atom14_pred_positions: torch.Tensor,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
872
873
874
    violation_tolerance_factor: float,
    clash_overlap_tolerance: float,
    **kwargs,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
875
876
877
878
879
880
) -> Dict[str, torch.Tensor]:
    """Computes several checks for structural violations."""
  
    # Compute between residue backbone violations of bonds and angles.
    connection_violations = between_residue_bond_loss(
        pred_atom_positions=atom14_pred_positions,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
881
882
883
884
885
        pred_atom_mask=batch["atom14_atom_exists"],
        residue_index=batch["residue_index"],
        aatype=batch["aatype"],
        tolerance_factor_soft=violation_tolerance_factor,
        tolerance_factor_hard=violation_tolerance_factor
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
886
887
888
889
890
891
892
893
894
895
896
897
898
    )
  
    # Compute the Van der Waals radius for every atom
    # (the first letter of the atom name is the element type).
    # Shape: (N, 14).
    atomtype_radius = [
        residue_constants.van_der_waals_radius[name[0]]
        for name in residue_constants.atom_types
    ]
    atomtype_radius = atom14_pred_positions.new_tensor(
        atomtype_radius 
    )
    atom14_atom_radius = (
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
899
900
        batch["atom14_atom_exists"] *
        atomtype_radius[batch["residx_atom14_to_atom37"]]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
901
902
903
904
905
    )
  
    # Compute the between residue clash loss.
    between_residue_clashes = between_residue_clash_loss(
        atom14_pred_positions=atom14_pred_positions,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
906
        atom14_atom_exists=batch["atom14_atom_exists"],
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
907
        atom14_atom_radius=atom14_atom_radius,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
908
909
910
        residue_index=batch["residue_index"],
        overlap_tolerance_soft=clash_overlap_tolerance,
        overlap_tolerance_hard=clash_overlap_tolerance
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
911
912
913
914
915
    )
  
    # Compute all within-residue violations (clashes,
    # bond length and angle violations).
    restype_atom14_bounds = residue_constants.make_atom14_dists_bounds(
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
916
917
        overlap_tolerance=clash_overlap_tolerance,
        bond_length_tolerance_factor=violation_tolerance_factor
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
918
    )
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
919
920
    atom14_dists_lower_bound = restype_atom14_bounds["lower_bound"][
        batch["aatype"]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
921
    ]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
922
923
    atom14_dists_upper_bound = restype_atom14_bounds["upper_bound"][
        batch["aatype"]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
924
925
926
927
928
929
930
931
932
    ]
    atom14_dists_lower_bound = atom14_pred_positions.new_tensor(
        atom14_dists_lower_bound
    )
    atom14_dists_upper_bound = atom14_pred_positions.new_tensor(
        atom14_dists_upper_bound
    )
    residue_violations = within_residue_violations(
        atom14_pred_positions=atom14_pred_positions,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
933
        atom14_atom_exists=batch["atom14_atom_exists"],
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
934
935
936
937
938
939
940
941
942
        atom14_dists_lower_bound=atom14_dists_lower_bound,
        atom14_dists_upper_bound=atom14_dists_upper_bound,
        tighten_bounds_for_loss=0.0
    )
  
    # Combine them to a single per-residue violation mask (used later for LDDT).
    per_residue_violations_mask = torch.max(
        torch.stack(
            [
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
943
                connection_violations["per_residue_violation_mask"],
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
944
                torch.max(
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
945
                    between_residue_clashes["per_atom_clash_mask"], dim=-1
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
946
947
                )[0],
                torch.max(
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
948
                    residue_violations["per_atom_violations"], dim=-1
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
949
950
951
952
953
954
955
956
957
958
                )[0],
            ], 
            dim=-1,
        ), 
        dim=-1,
    )[0]

    return {
        'between_residues': {
            'bonds_c_n_loss_mean':
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
959
                connection_violations["c_n_loss_mean"],  # ()
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
960
            'angles_ca_c_n_loss_mean':
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
961
                connection_violations["ca_c_n_loss_mean"],  # ()
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
962
            'angles_c_n_ca_loss_mean':
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
963
                connection_violations["c_n_ca_loss_mean"],  # ()
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
964
            'connections_per_residue_loss_sum':
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
965
                connection_violations["per_residue_loss_sum"],  # (N)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
966
            'connections_per_residue_violation_mask':
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
967
                connection_violations["per_residue_violation_mask"],  # (N)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
968
            'clashes_mean_loss':
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
969
                between_residue_clashes["mean_loss"],  # ()
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
970
            'clashes_per_atom_loss_sum':
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
971
                between_residue_clashes["per_atom_loss_sum"],  # (N, 14)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
972
            'clashes_per_atom_clash_mask':
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
973
                between_residue_clashes["per_atom_clash_mask"],  # (N, 14)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
974
975
976
        },
        'within_residues': {
            'per_atom_loss_sum':
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
977
                residue_violations["per_atom_loss_sum"],  # (N, 14)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
978
            'per_atom_violations':
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
979
                residue_violations["per_atom_violations"],  # (N, 14),
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
        },
        'total_per_residue_violations_mask':
            per_residue_violations_mask,  # (N)
    }


def find_structural_violations_np(
    batch: Dict[str, np.ndarray],
    atom14_pred_positions: np.ndarray,
    config: ml_collections.ConfigDict
) -> Dict[str, np.ndarray]:
    to_tensor = lambda x: torch.tensor(x, requires_grad=False)
    batch = tree_map(to_tensor, batch, np.ndarray)
    atom14_pred_positions = to_tensor(atom14_pred_positions)

    out = find_structural_violations(batch, atom14_pred_positions, config)

    to_np = lambda x: np.array(x)
    np_out = tensor_tree_map(to_np, out)

    return np_out


def extreme_ca_ca_distance_violations(
      pred_atom_positions: torch.Tensor,  # (N, 37(14), 3)
      pred_atom_mask: torch.Tensor,  # (N, 37(14))
      residue_index: torch.Tensor,  # (N)
      max_angstrom_tolerance=1.5,
      eps=1e-6,
) -> torch.Tensor:
    """Counts residues whose Ca is a large distance from its neighbour.
  
    Measures the fraction of CA-CA pairs between consecutive amino acids that are
    more than 'max_angstrom_tolerance' apart.
  
    Args:
      pred_atom_positions: Atom positions in atom37/14 representation
      pred_atom_mask: Atom mask in atom37/14 representation
      residue_index: Residue index for given amino acid, this is assumed to be
        monotonically increasing.
      max_angstrom_tolerance: Maximum distance allowed to not count as violation.
    Returns:
      Fraction of consecutive CA-CA pairs with violation.
    """
    this_ca_pos = pred_atom_positions[..., :-1, 1, :]
    this_ca_mask = pred_atom_mask[..., :-1, 1]
    next_ca_pos = pred_atom_positions[..., 1:, 1, :]
    next_ca_mask = pred_atom_mask[..., 1:, 1]
    has_no_gap_mask = ((residue_index[..., 1:] - residue_index[..., :-1]) == 1.0)
    ca_ca_distance = torch.sqrt(
        eps + torch.sum((this_ca_pos - next_ca_pos)**2, dim=-1)
    )
    violations = (
        (ca_ca_distance - residue_constants.ca_ca) > max_angstrom_tolerance
    )
    mask = this_ca_mask * next_ca_mask * has_no_gap_mask
    mean = masked_mean(mask, violations, -1)
    return mean


def compute_violation_metrics(
    batch: Dict[str, torch.Tensor],
    atom14_pred_positions: torch.Tensor,  # (N, 14, 3)
    violations: Dict[str, torch.Tensor],
) -> Dict[str, torch.Tensor]:
    """Compute several metrics to assess the structural violations.""" 
    ret = {}
    extreme_ca_ca_violations = extreme_ca_ca_distance_violations(
        pred_atom_positions=atom14_pred_positions,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1049
1050
        pred_atom_mask=batch["atom14_atom_exists"],
        residue_index=batch["residue_index"]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1051
    )
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1052
1053
1054
1055
    ret["violations_extreme_ca_ca_distance"] = extreme_ca_ca_violations
    ret["violations_between_residue_bond"] = masked_mean(
        batch["seq_mask"],
        violations["between_residues"][
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1056
1057
1058
1059
            'connections_per_residue_violation_mask'
        ],
        dim=-1,
    )
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1060
1061
    ret["violations_between_residue_clash"] = masked_mean(
        mask=batch["seq_mask"],
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1062
        value=torch.max(
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1063
            violations["between_residues"]["clashes_per_atom_clash_mask"],
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1064
1065
1066
1067
            dim=-1
        )[0],
        dim=-1,
    )
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1068
1069
    ret["violations_within_residue"] = masked_mean(
        mask=batch["seq_mask"],
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1070
        value=torch.max(
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1071
            violations["within_residues"]["per_atom_violations"], dim=-1
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1072
1073
1074
        )[0],
        dim=-1,
    )
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1075
1076
1077
    ret["violations_per_residue"] = masked_mean(
        mask=batch["seq_mask"],
        value=violations["total_per_residue_violations_mask"],
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
        dim=-1,
    )
    return ret


def compute_violation_metrics_np(
    batch: Dict[str, np.ndarray],
    atom14_pred_positions: np.ndarray,
    violations: Dict[str, np.ndarray],
) -> Dict[str, np.ndarray]:
    to_tensor = lambda x: torch.tensor(x, requires_grad=False)
    batch = tree_map(to_tensor, batch, np.ndarray)
    atom14_pred_positions = to_tensor(atom14_pred_positions)
    violations = tree_map(to_tensor, violations, np.ndarray)


    out = compute_violation_metrics(batch, atom14_pred_positions, violations)

    to_np = lambda x: np.array(x)
    return tree_map(to_np, out, torch.Tensor)


Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
def violation_loss(
    violations: Dict[str, torch.Tensor],
    atom14_atom_exists: torch.Tensor,
    eps=1e-6,
) -> torch.Tensor:
    num_atoms = torch.sum(atom14_atom_exists)
    l_clash = torch.sum(
        violations["between_residues"]["clashes_per_atom_loss_sum"] +
        violations["within_residues"]["per_atom_loss_sum"]
    ) 
    l_clash = l_clash / (eps + num_atoms)
    loss = (
        violations["between_residues"]["bonds_c_n_loss_mean"] +
        violations["between_residues"]["angles_ca_c_n_loss_mean"] +
        violations["between_residues"]["angles_c_n_ca_loss_mean"] +
        l_clash
    )

    return loss


Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
def compute_renamed_ground_truth(
    batch: Dict[str, torch.Tensor],
    atom14_pred_positions: torch.Tensor,
    eps=1e-10,
) -> Dict[str, torch.Tensor]:
    """
    Find optimal renaming of ground truth based on the predicted positions.
  
    Alg. 26 "renameSymmetricGroundTruthAtoms"
  
    This renamed ground truth is then used for all losses,
    such that each loss moves the atoms in the same direction.
  
    Args:
      batch: Dictionary containing:
        * atom14_gt_positions: Ground truth positions.
        * atom14_alt_gt_positions: Ground truth positions with renaming swaps.
        * atom14_atom_is_ambiguous: 1.0 for atoms that are affected by
            renaming swaps.
        * atom14_gt_exists: Mask for which atoms exist in ground truth.
        * atom14_alt_gt_exists: Mask for which atoms exist in ground truth
            after renaming.
        * atom14_atom_exists: Mask for whether each atom is part of the given
            amino acid type.
      atom14_pred_positions: Array of atom positions in global frame with shape
    Returns:
      Dictionary containing:
        alt_naming_is_better: Array with 1.0 where alternative swap is better.
        renamed_atom14_gt_positions: Array of optimal ground truth positions
          after renaming swaps are performed.
        renamed_atom14_gt_exists: Mask after renaming swap is performed.
    """

    pred_dists = torch.sqrt(
        eps + 
        torch.sum(
            (
                atom14_pred_positions[...,    None, :, None, :] -
                atom14_pred_positions[..., None, :, None, :, :]
            )**2,
            dim=-1,
        )
    )
    
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1165
    atom14_gt_positions = batch["atom14_gt_positions"]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
    gt_dists = torch.sqrt(
        eps + 
        torch.sum(
            (
                atom14_gt_positions[...,    None, :, None, :] -
                atom14_gt_positions[..., None, :, None, :, :]
            )**2,
            dim=-1,
        )
    )

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1177
    atom14_alt_gt_positions = batch["atom14_alt_gt_positions"]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
    alt_gt_dists = torch.sqrt(
        eps + 
        torch.sum(
            (
                atom14_alt_gt_positions[...,    None, :, None, :] -
                atom14_alt_gt_positions[..., None, :, None, :, :]
            )**2,
            dim=-1,
        )
    )

    lddt = torch.sqrt(eps + (pred_dists - gt_dists)**2)
    alt_lddt = torch.sqrt(eps + (pred_dists - alt_gt_dists)**2)

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1192
1193
    atom14_gt_exists = batch["atom14_gt_exists"]
    atom14_atom_is_ambiguous = batch["atom14_atom_is_ambiguous"]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
    mask = (
        atom14_gt_exists[..., None, :, None] *
        atom14_atom_is_ambiguous[..., None, :, None] *
        atom14_gt_exists[..., None, :, None, :] *
        (1. - atom14_atom_is_ambiguous[..., None, :, None, :])
    )

    per_res_lddt = torch.sum(mask * lddt, dim=(-1, -2, -3))
    alt_per_res_lddt = torch.sum(mask * alt_lddt, dim=(-1, -2, -3))

    fp_type = atom14_pred_positions.dtype
    alt_naming_is_better = (alt_per_res_lddt < per_res_lddt).type(fp_type)

    renamed_atom14_gt_positions = (
        (1. - alt_naming_is_better[..., None, None]) *
        atom14_gt_positions +
        alt_naming_is_better[..., None, None] *
        atom14_alt_gt_positions
    )

    renamed_atom14_gt_mask = (
        (1. - alt_naming_is_better[..., None]) * atom14_gt_exists +
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1216
        alt_naming_is_better[..., None] * batch["atom14_alt_gt_exists"]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1217
1218
1219
    )

    return {
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1220
1221
1222
        "alt_naming_is_better": alt_naming_is_better,
        "renamed_atom14_gt_positions": renamed_atom14_gt_positions,
        "renamed_atom14_gt_exists": renamed_atom14_gt_mask,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1223
1224
1225
1226
1227
1228
1229
    }


def experimentally_resolved_loss(
    logits: torch.Tensor,
    atom37_atom_exists: torch.Tensor,
    all_atom_mask: torch.Tensor,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1230
1231
1232
    resolution: torch.Tensor,
    min_resolution: float,
    max_resolution: float,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1233
1234
1235
1236
1237
    eps: float = 1e-8,
) -> torch.Tensor:
    errors = sigmoid_cross_entropy(logits, all_atom_mask)
    loss_num = torch.sum(errors * atom37_atom_exists, dim=(-1, -2))
    loss = loss_num / (eps + torch.sum(atom37_atom_exists, dim=(-1, -2)))
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1238
1239
1240
1241
1242
    
    loss *= (
        (resolution >= min_resolution) &
        (resolution <= max_resolution)
    )
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1243
    return loss
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331


def masked_msa_loss(logits, true_msa, bert_mask, eps=1e-8):
    errors = softmax_cross_entropy(
        logits,
        torch.nn.functional.one_hot(true_msa, num_classes=23,
    )
    loss = (
        torch.sum(errors * bert_mask, dim=(-1, -2)) /
        (eps + torch.sum(bert_mask, dim=(-1, -2)))
    )
    return loss


class AlphaFoldLoss(nn.Module):
    """ Aggregation of the various losses described in the supplement """
    def __init__(self, config):
        super(AlphaFoldLoss, self).__init__()
        self.config = config

    def forward(self, out, batch):
        cum_loss = 0
       
        if("violation" not in out.keys() and self.config.violation.weight):
            out["violation"] = find_structural_violations(
                batch,
                out["sm"]["positions"][-1],
                **self.config.violation,
            )

        if("renamed_atom14_gt_positions" not in out.keys()):
            batch.update(compute_renamed_ground_truth(
                batch,
                out["sm"]["positions"][-1],
            ))

        loss_fns = {
            "distogram": 
                lambda: distogram_loss(
                    logits=out["distogram_logits"],
                    {**batch,
                     **self.config.distogram},
                ),
            "experimentally_resolved": 
                lambda: experimentally_resolved_loss(
                    logits=out["experimentally_resolved"],
                    {**batch,
                     **self.config.experimentally_resolved},
                ),
            "fape":
                lambda: fape_loss(
                    out,
                    batch,
                    self.config.fape,
                ),
            "lddt": 
                lambda: lddt_loss(
                    logits=out["lddt_logits"],
                    all_atom_pred_pos=out["final_atom_positions"]
                    {**batch,
                     **self.config.lddt},
                ),
            "masked_msa": 
                lambda: masked_msa_loss(
                    logits=out["masked_msa_logits"],
                    {**batch,
                     **self.config.masked_msa},
                ),
            "supervised_chi":
                lambda: supervised_chi_loss(
                    out["sm"]["angles"],
                    out["sm"]["unnormalized_angles"],
                    {**batch,
                     **self.config.supervised_chi},
                ),
            "violation":
                lambda: violation_loss(
                    out["violation"],
                    **batch,
                ),
        }
       
        for k,loss_fn in loss_fns.items():
            weight = self.config[k].weight
            if(weight):
                cum_loss += weight * loss_fn()

        return cum_loss