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
 
 
 
 
 
 
 
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
"""
Data interface definitions for ODesign dataset and feature processing.

This module defines standardized data structures for features and labels:
- OFeatureData: Complete feature set for model input
- OLabelData: Ground truth labels for training

These interfaces ensure type consistency and provide convenient property
accessors for data dimensions.
"""

from ._base import *
from typing import List
from attr import define
import attr
import numpy as np
from src.utils.license_register import register_license


@define(kw_only=True)
@register_license('odesign2025')
@auto_type_convert
class OFeatureData(DictAccessMixin):
    """
    Complete feature data structure for ODesign model input.
    
    This class contains all features extracted from protein/RNA/DNA/ligand structures,
    including token-level features, atomic features, MSA features, template features,
    and various masks for training and evaluation. Features are organized by category.
    
    Attributes:
        # Token-level features
        token_index (IndexType): Token index within the full sequence.
            Shape: [N_token]
            
        residue_index (IndexType): Residue index in original sequence (1-indexed).
            Shape: [N_token]
            
        asym_id (IndexType): Asymmetric unit ID (chain identifier).
            Shape: [N_token]
            
        entity_id (IndexType): Entity ID (molecule type identifier).
            Same entity ID = same sequence.
            Shape: [N_token]
            
        sym_id (IndexType): Symmetry operation ID.
            Shape: [N_token]
            
        restype (OneHotType): One-hot encoded residue/nucleotide/ligand type.
            Shape: [N_token, n_residue_types]
            
        # Bond features
        token_bonds (FeatureType): Bond features between token pairs.
            Encodes bond types and connectivity.
            Shape: [N_token, N_token, n_bond_features]
            
        token_pair_gen_mask (MaskType): Mask for token pairs to generate/evaluate.
            Shape: [N_token, N_token]
            
        token_bond_gen_mask (MaskType): Mask for bond type generation/evaluation.
            Shape: [N_token, N_token]
            
        # Reference atomic features
        ref_pos (FeatureType): Reference atomic positions from structure.
            Shape: [N_atom, 3]
            
        ref_mask (MaskType): Mask for valid reference atoms (exists in structure).
            Shape: [N_atom]
            
        ref_element (FeatureType): Atomic element encoding.
            Shape: [N_atom, n_elements] or [N_atom]
            
        ref_charge (FeatureType): Atomic partial charge.
            Shape: [N_atom]
            
        ref_atom_name_chars (OneHotType): One-hot encoded atom name characters.
            Shape: [N_atom, 4, n_char_types]
            
        ref_space_uid (IndexType): Spatial unit ID for grouping atoms in same frame.
            Used for residue-level symmetric atom permutation.
            Shape: [N_atom]
            
        has_frame (MaskType): Mask indicating atoms with valid coordinate frames.
            Shape: [N_atom]
            
        frame_atom_index (IndexType): Indices of atoms defining coordinate frames.
            For proteins: [N, CA, C] atoms; for nucleotides: [C1', C3', C4']
            Shape: [N_frame, 3]
            
        # Identity and mapping features
        atom_to_token_idx (IndexType): Mapping from atom index to token index.
            Shape: [N_atom]
            
        atom_to_tokatom_idx (IndexType): Mapping from atom to token-atom index.
            Index within atoms of the same token.
            Shape: [N_atom]
            
        is_protein (MaskType): Binary mask indicating protein atoms.
            Shape: [N_atom]
            
        is_ligand (MaskType): Binary mask indicating ligand atoms.
            Shape: [N_atom]
            
        is_dna (MaskType): Binary mask indicating DNA atoms.
            Shape: [N_atom]
            
        is_rna (MaskType): Binary mask indicating RNA atoms.
            Shape: [N_atom]
            
        # Resolution
        resolution (FeatureType): Structure resolution in Angstroms.
            Used for filtering confidence loss. Shape: scalar or [1]
            
        # Chain permutation features
        mol_id (IndexType): Molecule ID for each atom.
            Identifies individual molecules (multiple copies of same entity).
            Shape: [N_atom]
            
        mol_atom_index (IndexType): Atom index within molecule.
            Shape: [N_atom]
            
        entity_mol_id (IndexType): Entity molecule ID for each atom.
            Shape: [N_atom]
            
        masked_asym_ids (List[int], optional): List of asymmetric unit IDs
            to consider for chain permutation. None means all chains.
            
        # Atom permutation features
        atom_perm_list (list[list[int]]): List of symmetric atom groups.
            Each group contains atom indices that can be permuted
            (e.g., symmetric atoms in aromatic rings, carboxyl groups).
            
        # Various masks for training and evaluation
        pae_rep_atom_mask (MaskType): Representative atom mask for PAE computation.
            Shape: [N_atom]
            
        modified_res_mask (MaskType): Mask for modified residues.
            Shape: [N_token]
            
        is_condition_atom (MaskType): Mask for conditioned (fixed) atoms.
            Atoms not generated by diffusion.
            Shape: [N_atom]
            
        distogram_rep_atom_mask (MaskType): Representative atom mask for distogram.
            Typically Cβ/Cα for proteins, C4'/C2' for nucleotides.
            Shape: [N_atom]
            
        plddt_m_rep_atom_mask (MaskType): Representative atom mask for pLDDT-m.
            Shape: [N_atom]
            
        bond_mask (MaskType): Mask for valid bonds.
            Shape: [N_atom, N_atom] or [N_token, N_token]
            
        # Constraint features
        constraint_feature (FeatureType, optional): Constraint features for token pairs.
            Currently supports distogram constraint, pocket constraint, etc.
            Shape: [N_token, N_token, n_constraint_features]
            
        # MSA features (optional)
        msa (IndexType, optional): Multiple sequence alignment.
            Token indices from MSA sequences.
            Shape: [N_msa, N_token]
            
        has_deletion (MaskType, optional): Mask indicating deletions in MSA.
            Shape: [N_msa, N_token]
            
        deletion_value (FeatureType, optional): Deletion values in MSA.
            Shape: [N_msa, N_token]
            
        profile (FeatureType, optional): Sequence profile from MSA.
            Position-specific scoring matrix.
            Shape: [N_token, 32]
            
        deletion_mean (FeatureType, optional): Mean deletion probability.
            Shape: [N_token]
            
        msa_token_mask (MaskType, optional): Mask for valid MSA tokens.
            Shape: [N_msa, N_token]
            
        prot_pair_num_alignments (torch.Tensor, optional): Number of paired
            protein alignments.
            
        prot_unpair_num_alignments (torch.Tensor, optional): Number of unpaired
            protein alignments.
            
        rna_pair_num_alignments (torch.Tensor, optional): Number of paired
            RNA alignments.
            
        rna_unpair_num_alignments (torch.Tensor, optional): Number of unpaired
            RNA alignments.
            
        # Template features (under development)
        template_restype (IndexType, optional): Residue types in template structures.
            Shape: [N_template, N_token]
            
        template_all_atom_mask (MaskType, optional): Atom masks in templates.
            Shape: [N_template, N_token, n_atom_per_token]
            
        template_all_atom_positions (FeatureType, optional): Atom positions in templates.
            Shape: [N_template, N_token, n_atom_per_token, 3]
            
        # Hotspot features
        is_hotspot_residue (FeatureType, optional): Binary mask for hotspot residues.
            Residues of particular interest (e.g., binding site, catalytic residues).
            Shape: [N_token]
            
        # Cyclic structure features
        is_cyclic_token (FeatureType, optional): Binary mask for cyclic peptide tokens.
            Shape: [N_token]
    
    Properties:
        num_asym: Number of asymmetric units (chains).
        num_token: Number of tokens.
        num_atom: Number of atoms.
        num_msa: Number of MSA sequences.
        default_num_msa: Default number of MSA sequences for padding (1).
        default_num_templ: Default number of templates for padding (4).
        default_num_pocket: Default number of pocket residues (30).
    """
    # Token-level features
    token_index: IndexType
    residue_index: IndexType
    asym_id: IndexType
    entity_id: IndexType
    sym_id: IndexType
    restype: OneHotType

    # Bond features
    token_bonds: FeatureType
    token_pair_gen_mask: MaskType
    token_bond_gen_mask: MaskType

    # Reference atomic features
    ref_pos: FeatureType
    ref_mask: MaskType
    ref_element: FeatureType
    ref_charge: FeatureType
    ref_atom_name_chars: OneHotType
    ref_space_uid: IndexType
    has_frame: MaskType
    frame_atom_index: IndexType

    # Identity and mapping features
    atom_to_token_idx: IndexType
    atom_to_tokatom_idx: IndexType
    is_protein: MaskType
    is_ligand: MaskType
    is_dna: MaskType
    is_rna: MaskType

    # Resolution
    resolution: FeatureType

    # Chain permutation features
    mol_id: IndexType
    mol_atom_index: IndexType
    entity_mol_id: IndexType
    masked_asym_ids: List[int] | None = None

    # Atom permutation features
    atom_perm_list: list[list[int]]

    # Mask features for training and evaluation
    pae_rep_atom_mask: MaskType
    modified_res_mask: MaskType
    is_condition_atom: MaskType
    distogram_rep_atom_mask: MaskType
    plddt_m_rep_atom_mask: MaskType
    bond_mask: MaskType

    # Constraint features
    constraint_feature: FeatureType | None = None

    # MSA features (optional)
    msa: IndexType | None = None
    has_deletion: MaskType | None = None
    deletion_value: FeatureType | None = None
    profile: FeatureType | None = None
    deletion_mean: FeatureType | None = None
    msa_token_mask: MaskType | None = None
    prot_pair_num_alignments: torch.Tensor | None = None
    prot_unpair_num_alignments: torch.Tensor | None = None
    rna_pair_num_alignments: torch.Tensor | None = None
    rna_unpair_num_alignments: torch.Tensor | None = None

    # Template features (under development)
    template_restype: IndexType | None = None
    template_all_atom_mask: MaskType | None = None
    template_all_atom_positions: FeatureType | None = None

    # Hotspot features
    is_hotspot_residue: FeatureType | None = None

    # Cyclic structure features
    is_cyclic_token: FeatureType | None = None
    
    @classmethod
    def from_feature_dict(cls, feature_dict: dict) -> "OFeatureData":
        """
        Create OFeatureData instance from a feature dictionary.
        
        This factory method filters the input dictionary to only include
        fields defined in OFeatureData and validates that all required
        fields are present.
        
        Args:
            feature_dict (dict): Dictionary containing feature data.
                Keys should match OFeatureData field names.
        
        Returns:
            OFeatureData: Validated feature data instance.
        
        Raises:
            AssertionError: If required fields are missing.
        """
        all_fields = {field.name for field in attr.fields(cls)}
        filtered_dict = {k: v for k, v in feature_dict.items() if k in all_fields}
        
        def _check_required_fields(filtered_dict):
            required_fields = {
                field.name for field in attr.fields(cls) 
                if field.default == attr.NOTHING
            }
            missing_fields = required_fields - set(filtered_dict.keys())
            assert not missing_fields, (
                f"Missing required fields in {cls.__name__}: {missing_fields}"
            )

        _check_required_fields(filtered_dict)
        return cls(**filtered_dict)
    
    @property
    def num_asym(self) -> int:
        """
        Get the number of asymmetric units (chains) in the structure.
        
        Returns:
            int: Number of unique chains.
        """
        return len(torch.unique(self.asym_id))
    
    @property
    def num_token(self) -> int:
        """
        Get the number of tokens in the sequence.
        
        Returns:
            int: Number of tokens (residues/nucleotides/ligand atoms).
        """
        return self.token_index.shape[0]
    
    @property
    def num_atom(self) -> int:
        """
        Get the number of atoms in the structure.
        
        Returns:
            int: Total number of atoms.
        """
        return self.atom_to_token_idx.shape[0]
    
    @property
    def num_msa(self) -> int:
        """
        Get the number of MSA sequences.
        
        Returns:
            int: Number of sequences in multiple sequence alignment.
        """
        return self.msa.shape[0]
    
    @property
    def default_num_msa(self) -> int:
        """
        Get the default number of MSA sequences for padding.
        
        Returns:
            int: Default value (1) for structures without MSA.
        """
        return 1

    @property
    def default_num_templ(self) -> int:
        """
        Get the default number of template structures for padding.
        
        Returns:
            int: Default value (4) for template feature dimensions.
        """
        return 4

    @property
    def default_num_pocket(self) -> int:
        """
        Get the default number of pocket residues.
        
        Returns:
            int: Default value (30) for pocket size in ligand binding.
        """
        return 30
    

@define(kw_only=True)
@register_license('odesign2025')
@auto_type_convert
class OLabelData(DictAccessMixin):
    """
    Ground truth label data structure for training and evaluation.
    
    This class contains all ground truth labels including atomic coordinates,
    bond types, and metadata needed for loss computation and evaluation metrics.
    
    Attributes:
        coordinate (FeatureType): Ground truth atomic coordinates.
            Reference positions from experimental structure.
            Shape: [N_atom, 3]
            
        coordinate_mask (MaskType): Mask indicating which atoms have valid coordinates.
            Used to filter missing or disordered atoms.
            Shape: [N_atom]
            
        token_bond_type_label (FeatureType, optional): Ground truth bond type labels.
            Encodes bond types for token pairs (no_bond, single, double, triple, aromatic).
            Shape: [N_token, N_token] or [N_token, N_token, n_bond_types]
            
        ligand_bond_mask (MaskType, optional): Mask for ligand bonds.
            Indicates which bonds should be considered for ligand bond loss.
            Shape: [N_atom, N_atom] or [N_token, N_token]
            
        entity_mol_id (IndexType, optional): Entity molecule ID for each atom.
            Used for chain permutation during training.
            Shape: [N_atom]
            
        mol_id (IndexType, optional): Molecule ID for each atom.
            Identifies individual molecule instances.
            Shape: [N_atom]
            
        mol_atom_index (IndexType, optional): Atom index within molecule.
            Maps atoms to their position within molecule for permutation.
            Shape: [N_atom]
            
        pae_rep_atom_mask (MaskType, optional): Representative atom mask for PAE.
            Identifies atoms used as representatives for predicted aligned error.
            Shape: [N_atom]
            
        eval_type (np.ndarray, optional): Evaluation type identifier.
            Specifies the type of evaluation (e.g., interface, binding, folding).
            
        cluster_id (np.ndarray, optional): Cluster ID for evaluation.
            Used to group similar structures in validation.
            
        chain_1_mask (MaskType, optional): Mask for chain 1 in interface evaluation.
            Used for protein-protein interface or ligand binding evaluation.
            Shape: [N_atom]
            
        chain_2_mask (MaskType, optional): Mask for chain 2 in interface evaluation.
            Used for protein-protein interface or ligand binding evaluation.
            Shape: [N_atom]
    """
    coordinate: FeatureType
    coordinate_mask: MaskType

    token_bond_type_label: FeatureType | None = None
    ligand_bond_mask: MaskType | None = None

    entity_mol_id: IndexType | None = None
    mol_id: IndexType | None = None
    mol_atom_index: IndexType | None = None

    pae_rep_atom_mask: MaskType | None = None

    eval_type: np.ndarray | None = None
    cluster_id: np.ndarray | None = None
    chain_1_mask: MaskType | None = None
    chain_2_mask: MaskType | None = None

    @classmethod
    def from_label_dict(cls, label_dict: dict) -> "OLabelData":
        """
        Create OLabelData instance from a label dictionary.
        
        This factory method filters the input dictionary to only include
        fields defined in OLabelData and validates that all required
        fields are present.
        
        Args:
            label_dict (dict): Dictionary containing label data.
                Keys should match OLabelData field names.
        
        Returns:
            OLabelData: Validated label data instance.
        
        Raises:
            AssertionError: If required fields are missing.
        """
        all_fields = {field.name for field in attr.fields(cls)}
        filtered_dict = {k: v for k, v in label_dict.items() if k in all_fields}
        
        def _check_required_fields(filtered_dict):
            required_fields = {
                field.name for field in attr.fields(cls) 
                if field.default == attr.NOTHING
            }
            missing_fields = required_fields - set(filtered_dict.keys())
            assert not missing_fields, (
                f"Missing required fields in {cls.__name__}: {missing_fields}"
            )

        _check_required_fields(filtered_dict)
        return cls(**filtered_dict)