<jupyter_start><jupyter_text>Probando agrupar por pares de residuos<jupyter_code>import numpy as np

amino3to1dict = {'ASH': 'A','ALA': 'A','CYX': 'C','CYS': 'C','ASP': 'D','GLU': 'E','PHE': 'F','GLY': 'G','HIS': 'H',
                 'HID': 'H','HIE': 'H','HIP': 'H','ILE': 'I','LYS': 'K','LEU': 'L','MET': 'M','MSE': 'M','ASN': 'N',
                 'PYL': 'O','HYP': 'P','PRO': 'P','GLN': 'Q','ARG': 'R','SER': 'S','THR': 'T','SEL': 'U','VAL': 'V',
                 'TRP': 'W','TYR': 'Y'}
aa_std = "ACDEFGHIKLMNPQRSTVWY"

def dfpdb_res_level(tmp_df):
    """Obtener una visualizacion de pandas dataframe a nivel de residuo.
    Modificado de pandas_pdb.py method amino3to1 para funcionar con numeracion de residuos en anticuerpos"""

    cmp = 'placeholder'
    indices = []

    for num, ind in zip(tmp_df[['residue_number', 'insertion']].iterrows(), np.arange(tmp_df.shape[0])):
        numstr = '%s%s' % (num[1][0], num[1][1])
        if numstr != cmp:
            indices.append(ind)
        cmp = numstr
    tmp_df_res_level = tmp_df.iloc[indices].copy()
    return tmp_df_res_level

def contacts_by_aa(biopdb_df, contact_dataframe, protein="p1"):

    dfpdb_res = dfpdb_res_level(biopdb_df)
    print(dfpdb_res)
    # add col chain/resi for vectorize comparizon betwen contact res id and biopandas pdb
    dfpdb_res["chain/resi"] = dfpdb_res.chain_id.astype(str) + "/" + dfpdb_res.residue_number.astype(
        str) + dfpdb_res.insertion.astype(str)
    # group contact data by chain/resnum tag , created concatenating strings of atom
    if protein == "p1":
        key = contact_dataframe.atom_bgn.str.split("/", expand=True)[0].astype(str) + "/" + \
              contact_dataframe.atom_bgn.str.split("/", expand=True)[1].astype(str)
    else:
        key = contact_dataframe.atom_end.str.split("/", expand=True)[0].astype(str) + "/" + \
              contact_dataframe.atom_end.str.split("/", expand=True)[1].astype(str)
    contact_data_grouped = contact_dataframe.groupby(by=key).sum()
    contact_data_grouped.reset_index(inplace=True)

    # compare grouped data "chain/id"(index) with dfpdb_resn ("chain/resi") and get aminoacidname,add to contac_data
    oneletter_resname = dfpdb_res["residue_name"].loc[dfpdb_res["chain/resi"].isin(contact_data_grouped["index"])].map(
        amino3to1dict)
    contact_data_grouped["aminoacid"] = oneletter_resname.values

    # group contact_data by aminoacid name
    data_by_aa = contact_data_grouped.groupby("aminoacid").sum()

    # check not present aminoacids in data, and add resdue name with 15D array of zeros, finally sort indexes
    for aa in list(aa_std):
        if aa not in data_by_aa.index:
            data_by_aa.loc[aa] = np.zeros(15, dtype=int)
    data_by_aa.sort_index(inplace=True)

    return data_by_aa.stack().values
pdbfile = str(paths).replace(".interface_contacts",".pdb")
ppdb = PandasPdb().read_pdb(pdbfile)
contact_dataframe = contact_data
dfpdb = ppdb.df["ATOM"]

dfpdb_res = dfpdb_res_level(dfpdb)
# add col chain/resi for vectorize comparizon betwen contact res id and biopandas pdb
dfpdb_res["chain/resi"] = dfpdb_res.chain_id.astype(str) + "/" + dfpdb_res.residue_number.astype(
    str) + dfpdb_res.insertion.astype(str)
a_bgn = contact_data.atom_bgn.str.rsplit("/",n=1,expand=True)[0] 
a_end = contact_data.atom_end.str.rsplit("/",n=1,expand=True)[0]
bgn_end = a_bgn+"/"+a_end
contact_data["bgn/end"] = bgn_end
contact_data_resi2resi = contact_data.groupby("bgn/end").sum()
for i in contact_data_resi2resi.index:
    bgn = i.rsplit("/",maxsplit=2)[0]
    end = i.split("/",maxsplit=2)[2]
    resname_bgn = dfpdb_res.loc[dfpdb_res["chain/resi"].isin([bgn]),"residue_name"].map(amino3to1dict).values[0]
    resname_end = dfpdb_res.loc[dfpdb_res["chain/resi"].isin([end]),"residue_name"].map(amino3to1dict).values[0]
    contact_data_resi2resi.loc[i,"res_bgn/res_end"] = resname_bgn+"_"+resname_end
    
contact_paires = contact_data_resi2resi.groupby("res_bgn/res_end").sum()
import itertools

comb = list(itertools.product(list(aa_std),repeat=2))
pairs_posibble = [t[0]+"_"+t[1] for t in comb]

contact_paires.sum?
contact_paires_sum =  contact_paires.sum(axis=1)
# check not present aminoacids pairs in data, and add pair name equal zero, finally sort indexes
for aa_pairs in pairs_posibble:
    if aa_pairs not in contact_paires_sum.index:
        contact_paires_sum.loc[aa_pairs] = 0

contact_paires_sum.sort_index(inplace=True)

contact_paires_sum.to_frame().T<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.15924276169265034, 'fraction_numerical': 0.009799554565701559, 'mean_word_length': 4.57888198757764, 'pattern_counts': {'":': 1, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '103104', 'license': 'MIT', 'n_tokens_mistral': 1791, 'n_tokens_neox': 1740, 'n_words': 300, 'path': 'notebooks/features_interface_contact.ipynb', 'repo_name': 'victorfica/Master-thesis', 'size': '4490'}