o
    ߥiL                  	   @   s.  d Z ddlZddlmZmZmZmZ ddlZddl	Z
ddlZddlmZ ddlmZ edZdZd	Zedddedddd
ZdZdZdZdZdee dee fddZdejdedejfddZdede
jfddZde
jdee e
jf fddZ!dee
j deee"  fddZ#d ee dee"ejf fd!d"Z$d#ee"ejf dejfd$d%Z%d&d'd(ejd)e&dejfd*d+Z'd,ed-ee d.e(defd/d0Z)dee d1e"dee fd2d3Z*dee d.e(defd4d5Z+dee dee fd6d7Z,d8edefd9d:Z-d-ee d.e(d1e"defd;d<Z.d=ee dee fd>d?Z/dS )@z Pairing logic for multimer data     N)DictIterableListSequence   )	NumpyDict)restypes_with_x_and_gap-g      ?g?)msa_all_seqmsa_mask_all_seqdeletion_matrix_all_seqdeletion_matrix_int_all_seqmsamsa_maskdeletion_matrixdeletion_matrix_int)r   r   r   r   )residue_indexaatypeall_atom_positionsall_atom_maskseq_maskbetween_segment_residueshas_alt_locationshas_hetatomsasym_id	entity_idsym_identity_maskdeletion_meanprediction_atom_maskliterature_positionsatom_indices_to_group_indicesrigid_group_default_framenum_sym)template_aatypetemplate_all_atom_positionstemplate_all_atom_mask)num_alignments
seq_lengthchainsreturnc           
      C   s   t | } | d  }t| dk r| S g }t| }t|}t| D ]>\}}dd | D }|D ]}|drIt|| |}	|	|dd|f  ||< q/t	
t|dd|f |d< || q |S )a  Returns the original chains with paired NUM_SEQ features.

    Args:
        chains:    A list of feature dictionaries for each chain.

    Returns:
        A list of feature dictionaries with sequence features including only
        rows to be paired.
    r      c                 S   s   i | ]\}}d |vr||qS )_all_seq ).0kvr-   r-   f/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/models/science/unifold/data/msa_pairing.py
<dictcomp>\       z*create_paired_features.<locals>.<dictcomp>r,   Nnum_alignments_all_seq)listkeyslenpair_sequencesreorder_paired_rows	enumerateitemsendswithpad_featuresnpasarrayappend)
r)   
chain_keysupdated_chains#paired_chains_to_paired_row_indicespaired_rows	chain_numchain	new_chainfeature_namefeats_paddedr-   r-   r1   create_paired_featuresG   s.   

rJ   featurerH   c                 C   sn   | j t tjksJ |dv r"| jd }t| td|g| j  }n
|dkr*dg}n| S tj| |gdd}|S )a~  Add a 'padding' row at the end of the features list.

    The padding row will be selected as a 'paired' row in the case of partial
    alignment - for the chain that doesn't have paired alignment.

    Args:
        feature: The feature to be padded.
        feature_name: The name of the feature to be padded.

    Returns:
        The feature with an additional padding row.
    )r
   r   r   r   r   msa_species_identifiers_all_seq    r   axis)dtyper>   str_shapeMSA_PAD_VALUESonesconcatenate)rK   rH   num_respaddingrI   r-   r-   r1   r=   i   s   
r=   chain_featuresc                 C   sz   | d }|d }t j|d |kddtt| }t j|dkddtt| }t| d t t| d ||d}|S )	z9Makes dataframe with msa features needed for msa pairing.r
   r   NrN      rL   )msa_species_identifiersmsa_rowmsa_similaritygap)r>   sumfloatr7   pd	DataFramearange)rX   	chain_msa	query_seqper_seq_similarityper_seq_gapmsa_dfr-   r-   r1   _make_msa_df   s   

ri   rh   c                 C   s$   i }|  dD ]\}}|||< q|S )z>Creates mapping from species to msa dataframe of that species.r[   )groupby)rh   species_lookupspecies
species_dfr-   r-   r1   _create_species_dict   s   
rn   this_species_msa_dfsc                 C   s|   g }dd | D }t |}dd }| D ]}|dur(||}|jjd| j}ndg| }|| qtt | }|S )a7  Finds MSA sequence pairings across chains based on sequence similarity.

    Each chain's MSA sequences are first sorted by their sequence similarity to
    their respective target sequence. The sequences are then paired, starting
    from the sequences most similar to their target sequence.

    Args:
        this_species_msa_dfs: a list of dataframes containing MSA features for
            sequences for a specific species.

    Returns:
     A list of lists, each containing M indices corresponding to paired MSA rows,
     where M is the number of chains.
    c                 S   s   g | ]
}|d urt |qS N)r7   r.   rm   r-   r-   r1   
<listcomp>   s
    z6_match_rows_by_sequence_similarity.<locals>.<listcomp>c                 S   s   | j ddddS )Nr]   r   F)rO   	ascending)sort_values)xr-   r-   r1   sort_by_similarity   s   z>_match_rows_by_sequence_similarity.<locals>.sort_by_similarityNrY   )	r>   minr\   ilocvaluesr@   r5   array	transpose)ro   all_paired_msa_rowsnum_seqstake_num_seqsrv   rm   species_df_sortedmsa_rowsr-   r-   r1   "_match_rows_by_sequence_similarity   s   

r   examplesc                 C   s<  t | }g }t }| D ]}t|}t|}|| |t| qt|}|d t	t | t
g}dd t|D }t	t | t
g||< |D ]H}	|	sOqJg }
d}|D ]}|	|v rg|
||	  |d7 }qU|
d qU|dkrrqJttdd |
D d	krqJt|
}|| || | qJd
d | D }|S )z7Returns indices for paired MSA sequences across chains.rM   c                 S   s   i | ]}|g qS r-   r-   )r.   r/   r-   r-   r1   r2      s    z"pair_sequences.<locals>.<dictcomp>r   r   Nc                 S   s    g | ]}t |tjrt|qS r-   )
isinstancera   rb   r7   rq   r-   r-   r1   rr      s    
z"pair_sequences.<locals>.<listcomp>iX  c                 S   s   i | ]
\}}|t |qS r-   )r>   rz   )r.   num_examplespaired_msa_rowsr-   r-   r1   r2      s    
)r7   setri   rn   r@   updatesortedremover>   zerosintrangeanyrz   r   extendr;   )r   r   all_chain_species_dictcommon_speciesrX   rh   species_dictr|   all_paired_msa_rows_dictrl   ro   species_dfs_presentr   r-   r-   r1   r8      sT   




r8   r   c                 C   sZ   g }t | ddD ]}| | }ttdd |D }t|}|||  qt|S )a  Creates a list of indices of paired MSA rows across chains.

    Args:
        all_paired_msa_rows_dict: a mapping from the number of paired chains to the
            paired indices.

    Returns:
        a list of lists, each containing indices of paired MSA rows across chains.
        The paired-index lists are ordered by:
            1) the number of chains in the paired alignment, i.e, all-chain pairings
                 will come first.
            2) e-values
    T)reversec                 S   s   g | ]}t |t jqS r-   )r>   prodastypefloat64)r.   rowsr-   r-   r1   rr     r3   z'reorder_paired_rows.<locals>.<listcomp>)r   r>   absrz   argsortr   )r   r|   num_pairingsrD   paired_rows_productpaired_rows_sort_indexr-   r-   r1   r9     s   

r9   g        )	pad_valuearrsr   c                 G   sB   dd |D }dt jj|  }t jj| }|||  |j7 }|S )z@Like scipy.linalg.block_diag but with an optional padding value.c                 S   s   g | ]}t |qS r-   )r>   	ones_liker.   ru   r-   r-   r1   rr   !  s    zblock_diag.<locals>.<listcomp>r   )scipylinalg
block_diagr   rP   )r   r   	ones_arrsoff_diag_maskdiagr-   r-   r1   r     s
   r   
np_examplenp_chains_listpair_msa_sequencesc           
      C   s  t j| d jd t jd| d< t j| d jd t jd| d< |sSg }|D ]}t |d jd }d|d< || q$t || d< d	d
 |D }t|ddi| d< | S t | d jd | d< d| d d< dd
 |D }dd
 |D }t|ddi}t j|dd}	t j|	|gdd| d< | S )z?Adds features that need to be computed/recomputed post merging.r   r   rP   r(   r   r'   r   cluster_bias_maskc                 S   "   g | ]}t j|d  jt jdqS r   r   r>   rT   rR   int8r   r-   r-   r1   rr   ?      z._correct_post_merged_feats.<locals>.<listcomp>r   	bert_maskc                 S   r   r   r   r   r-   r-   r1   rr   I  r   c                 S   r   )r
   r   r   r   r-   r-   r1   rr   L  s    rN   )r>   r?   rR   int32r   r@   rU   r   )
r   r   r   cluster_bias_masksrF   mask	msa_masksmsa_masks_all_seqmsa_mask_block_diagr   r-   r-   r1   _correct_post_merged_feats(  s@   


r   max_templatesc                 C   sh   | D ]/}|  D ](\}}|tv r0t|j}||jd  |d< dd |D }tj||dd||< qq| S )a0  For each chain pad the number of templates to a fixed size.

    Args:
        chains: A list of protein chains.
        max_templates: Each chain will be padded to have this many templates.

    Returns:
        The list of chains, updated to have template features padded to
        max_templates.
    r   c                 S   s   g | ]}d |fqS )r   r-   )r.   pr-   r-   r1   rr   i      z"_pad_templates.<locals>.<listcomp>constant)mode)r;   TEMPLATE_FEATURESr>   
zeros_likerR   pad)r)   r   rF   r/   r0   rW   r-   r-   r1   _pad_templatesX  s   r   c           
         s\  i }| d D ]  fdd| D }  dd }|tv ry|s"d v r@tj|dd| < |dkr?t|  jd dd|d	< qt|d
t  i| < |dkrxg }t	|D ]\}}|jd }t||d  }	|
|	 qUt|dd|d< q|tv rtj|dd| < q|tv rtj|dd| < q|tv rt|tj| < q|d | < q|S )aY  Merge features from multiple chains.

    Args:
        chains: A list of feature dictionaries that we want to merge.
        pair_msa_sequences: Whether to concatenate MSA features along the
            num_res dimension (if True), or to block diagonalize them (if False).

    Returns:
        A feature dictionary for the merged example.
    r   c                    s   g | ]}|  qS r-   r-   r   rH   r-   r1   rr   |  r   z8_merge_features_from_multiple_chains.<locals>.<listcomp>r,   r   rN   r   rY   msa_chains_all_seqr   r+   
msa_chains)splitMSA_FEATURESr>   rU   rT   rR   reshaper   rS   r:   r@   SEQ_FEATURESr   CHAIN_FEATURESr_   r   r   )
r)   r   merged_examplefeatsfeature_name_splitr   ifeat	cur_shapevalsr-   r   r1   $_merge_features_from_multiple_chainsn  sN   

r   c                 C   sd   t t}| D ]}|d d }|| | qg }t|D ]}|| } ||  qdd |D } | S )aU  Merge all identical chains, making the resulting MSA dense.

    Args:
        chains: An iterable of features for each chain.

    Returns:
        A list of feature dictionaries.    All features with the same entity_id
        will be merged - MSA features will be concatenated along the num_res
        dimension - making them dense.
    r   r   c                 S   s   g | ]}t |d dqS )Tr   )r   )r.   r)   r-   r-   r1   rr     s    
z-_merge_homomers_dense_msa.<locals>.<listcomp>)collectionsdefaultdictr5   r@   r   )r)   entity_chainsrF   r   grouped_chainsr-   r-   r1   _merge_homomers_dense_msa  s   
r   examplec                 C   s   t d }|D ]8}|| v r>| | }| |d  }ztj||gdd}W n ty9 } ztd||j|j|j|d}~ww || |< qtj| d jd tjd| d	< | S )
z.Merges paired and block-diagonalised features.)r   r,   r   rN   zconcat failed.Nr   r   r'   )r   r>   rU   	ExceptionrR   	__class__rz   r   )r   featuresrH   r   feat_all_seqmerged_featexr-   r-   r1   )_concatenate_paired_and_unpaired_features  s0   	
r   c                 C   s>   t | |d} t| } t| dd}|rt|}t|| |d}|S )aA  Merges features for multiple chains to single FeatureDict.

    Args:
        np_chains_list: List of FeatureDicts for each chain.
        pair_msa_sequences: Whether to merge paired MSAs.
        max_templates: The maximum number of templates to include.

    Returns:
        Single FeatureDict for entire complex.
    )r   Fr   )r   r   r   )r   r   r   r   r   )r   r   r   r   r-   r-   r1   merge_chain_features  s   r   	np_chainsc                 C   s  | d   }t}i }| D ]}t|d d }||vrntdd |d D }g }t|d D ]\}}	|	 |vr<|| q-i }
|D ](}||v ri|rR|| | |
|< qAt|| j}d|d< t	j
||| jd|
|< qA|
||< || D ]
}|| | ||< qrt	j|d jd t	jd|d< q| S )	z=Removes unpaired sequences which duplicate a paired sequence.r   r   c                 s   s    | ]}|  V  qd S rp   )tobytes)r.   sr-   r-   r1   	<genexpr>  s    z1deduplicate_unpaired_sequences.<locals>.<genexpr>r
   r   r   r'   )r6   r   r   r   r:   r   r@   r5   rR   r>   r   rP   rz   r   )r   feature_namesmsa_featurescache_msa_featuresrF   r   sequence_set	keep_rowsrow_numseqnew_msa_featuresrH   	new_shaper-   r-   r1   deduplicate_unpaired_sequences  s@   



r   )0__doc__r   typingr   r   r   r   numpyr>   pandasra   scipy.linalgr   data_opsr   residue_constantsr   indexMSA_GAP_IDXSEQUENCE_GAP_CUTOFFSEQUENCE_SIMILARITY_CUTOFFrS   r   r   r   r   rJ   ndarraystrr=   rb   ri   bytesrn   r   r   r8   r9   r`   r   boolr   r   r   r   r   r   r   r-   r-   r-   r1   <module>   s   
"

 )6
 	

0

,


