o
    *jL                  	   @   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   )Zresidue_indexaatypeZall_atom_positionsZall_atom_maskZseq_maskZbetween_segment_residuesZhas_alt_locationsZhas_hetatomsZasym_id	entity_idZsym_idZentity_maskZdeletion_meanZprediction_atom_maskZliterature_positionsZatom_indices_to_group_indicesZrigid_group_default_frameZnum_sym)Ztemplate_aatypeZtemplate_all_atom_positionsZ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   s/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/modelscope/models/science/unifold/data/msa_pairing.py
<dictcomp>\       z*create_paired_features.<locals>.<dictcomp>r   NZnum_alignments_all_seq)listkeyslenpair_sequencesreorder_paired_rows	enumerateitemsendswithpad_featuresnpasarrayappend)
r   Z
chain_keysZupdated_chainsZ#paired_chains_to_paired_row_indicespaired_rowsZ	chain_numchainZ	new_chainfeature_namefeats_paddedr   r   r   create_paired_featuresG   s.   

r1   featurer/   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*   Zstr_shapeMSA_PAD_VALUESonesconcatenate)r2   r/   Znum_respaddingr0   r   r   r   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   Nr5      r3   )msa_species_identifiersmsa_rowmsa_similaritygap)r*   sumfloatr#   pd	DataFrameZarange)r=   Z	chain_msaZ	query_seqZper_seq_similarityZper_seq_gapmsa_dfr   r   r   _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   Zspecies_lookupspecies
species_dfr   r   r   _create_species_dict   s   
rM   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)r#   r   rL   r   r   r   
<listcomp>   s
    z6_match_rows_by_sequence_similarity.<locals>.<listcomp>c                 S   s   | j ddddS )NrB   r   F)r6   Z	ascending)Zsort_values)xr   r   r   sort_by_similarity   s   z>_match_rows_by_sequence_similarity.<locals>.sort_by_similarityNr>   )	r*   minrA   Zilocvaluesr,   r!   arrayZ	transpose)rN   all_paired_msa_rowsZnum_seqsZtake_num_seqsrS   rL   Zspecies_df_sortedZmsa_rowsr   r   r   "_match_rows_by_sequence_similarity   s   

rX   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.r4   c                 S   s   i | ]}|g qS r   r   )r   r   r   r   r   r      s    z"pair_sequences.<locals>.<dictcomp>r   r   Nc                 S   s    g | ]}t |tjrt|qS r   )
isinstancerF   rG   r#   rP   r   r   r   rQ      s    
z"pair_sequences.<locals>.<listcomp>iX  c                 S   s   i | ]
\}}|t |qS r   )r*   rV   )r   num_examplespaired_msa_rowsr   r   r   r      s    
)r#   setrI   rM   r,   updatesortedremover*   zerosintrangeanyrV   rX   extendr'   )rY   r[   Zall_chain_species_dictZcommon_speciesr=   rH   Zspecies_dictrW   all_paired_msa_rows_dictrK   rN   Zspecies_dfs_presentr\   r   r   r   r$      sT   




r$   rf   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astypeZfloat64)r   rowsr   r   r   rQ     r    z'reorder_paired_rows.<locals>.<listcomp>)r_   r*   absrV   Zargsortre   )rf   rW   Znum_pairingsr-   Zpaired_rows_productZpaired_rows_sort_indexr   r   r   r%     s   

r%   g        )	pad_valuearrsrl   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*   Z	ones_liker   rR   r   r   r   rQ   !  s    zblock_diag.<locals>.<listcomp>r   )scipyZlinalg
block_diagri   r7   )rl   rm   Z	ones_arrsZoff_diag_maskZdiagr   r   r   rp     s
   rp   
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   r7   r   r   r   r   Zcluster_bias_maskc                 S   "   g | ]}t j|d  jt jdqS r   rt   r*   r:   r8   Zint8rn   r   r   r   rQ   ?      z._correct_post_merged_feats.<locals>.<listcomp>rl   Z	bert_maskc                 S   ru   rv   rw   rn   r   r   r   rQ   I  rx   c                 S   ru   )r
   rt   rw   rn   r   r   r   rQ   L  s    r5   )r*   r+   r8   int32ra   r,   r;   rp   )
rq   rr   rs   Zcluster_bias_masksr.   maskZ	msa_masksZmsa_masks_all_seqZmsa_mask_block_diagr   r   r   r   _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   r   rQ   i      z"_pad_templates.<locals>.<listcomp>Zconstant)mode)r'   TEMPLATE_FEATURESr*   Z
zeros_liker8   pad)r   r|   r.   r   r   r<   r   r   r   _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   rn   r/   r   r   rQ   |  r~   z8_merge_features_from_multiple_chains.<locals>.<listcomp>r   r   r5   r   r>   Zmsa_chains_all_seqrl   r   
msa_chains)splitMSA_FEATURESr*   r;   r:   r8   Zreshaperp   r9   r&   r,   SEQ_FEATURESr   CHAIN_FEATURESrD   ri   ry   )
r   rs   Zmerged_exampleZfeatsZfeature_name_splitr   ifeatZ	cur_shapevalsr   r   r   $_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rs   )r   )r   r   r   r   r   rQ     s    
z-_merge_homomers_dense_msa.<locals>.<listcomp>)collectionsdefaultdictr!   r,   r_   )r   Zentity_chainsr.   r   Zgrouped_chainsr   r   r   _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   r5   zconcat failed.Nr   rt   r   )r   r*   r;   	Exceptionr8   	__class__rV   ry   )r   featuresr/   r   Zfeat_all_seqZmerged_featexr   r   r   )_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   )rq   rr   rs   )r   r   r   r   r{   )rr   rs   r|   rq   r   r   r   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 rO   )tobytes)r   sr   r   r   	<genexpr>  s    z1deduplicate_unpaired_sequences.<locals>.<genexpr>r
   r   rt   r   )r"   r   rb   r]   r&   r   r,   r!   r8   r*   ra   r7   rV   ry   )r   Zfeature_namesZmsa_featuresZcache_msa_featuresr.   r   Zsequence_setZ	keep_rowsZrow_numseqZnew_msa_featuresr/   Z	new_shaper   r   r   deduplicate_unpaired_sequences  s@   



r   )0__doc__r   typingr   r   r   r   numpyr*   ZpandasrF   Zscipy.linalgro   Zdata_opsr   Zresidue_constantsr   indexZMSA_GAP_IDXZSEQUENCE_GAP_CUTOFFZSEQUENCE_SIMILARITY_CUTOFFr9   r   r   r   r   r1   Zndarraystrr)   rG   rI   bytesrM   rb   rX   r$   r%   rE   rp   boolr{   r   r   r   r   r   r   r   r   r   r   <module>   s   
"

 )6
 	

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