metrics.py 18.2 KB
Newer Older
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
import time
import pandas as pd
import Levenshtein
import csv
import ast
import numpy as np
from descarteProteinas import remplazar_ID_for_sequence as rp
from descarteProteinas import substitute_or_remove_prot_id
from generate_the_excel import substitute_or_remove_prot_id
    
def similitudProteinas(sequences):
    output = []

    for row1 in sequences:
        for row2 in sequences:
            if row1 != row2:
                #print(row1,row2)
                #similarity = abs(smith.SmithWaterman(row1, row2).get_score()-1) / max(len(row1), len(row2))
                similarity = abs(needle.NeedlemanWunsch(row1, row2).get_score()-1) / (2*max(len(row1), len(row2)))
                #similarity = abs(Levenshtein.distance(row1, row2)) / max(len(row1), len(row2))
                
                output.append([row1, row2, similarity*100])
    return output

def metrica_distanciaProteinas():
    # Leer los archivos CSV
    data = pd.read_csv("resultados/patronesIdenticos.csv")
    df_b = pd.read_csv("AllProteins_%Similitud.csv")

    # Crear un diccionario de similaridades
    proteinas_dict = dict(zip(zip(df_b['Proteina1'], df_b['Proteina2']), df_b['Similaridad']))

    # Agrupar por el patrón de proteína
    grupos = data.groupby('Patron')

    # Crear una lista de tuplas con los índices únicos de las filas en cada grupo
    indices = [grupo.index for patron, grupo in grupos]

    # Generar todas las combinaciones únicas de índices
    index_combinations = [(i, j) for grp in indices for i in grp for j in grp if i != j]

    # Filtrar las combinaciones que no son duplicadas y tienen diferencias en las filas correspondientes
    filtered_combinations = [comb for comb in index_combinations if not data.loc[comb[0]].equals(data.loc[comb[1]])]

    # Filtrar las combinaciones que existen en el diccionario de similaridades
    output = [[data.loc[comb[0], 'Patron'], data.loc[comb[0], 'Proteina'], data.loc[comb[1], 'Proteina'],
               proteinas_dict.get((data.loc[comb[0], 'Proteina'], data.loc[comb[1], 'Proteina']), '')] for comb in
              filtered_combinations]

    # Crear un DataFrame a partir de la lista de resultados
    df = pd.DataFrame(output, columns=['Patron', 'Proteina1', 'Proteina2', 'Similitud'])

    # Guardar el DataFrame en un archivo CSV
    df.to_csv('resultados/Metrica_distanciaProteinasMismoPatron.csv',
              index=False)

def patronesComun(patronesComun,archivoEntrada,ocurrencia,sal,archivoClases):
    
    # Leer el archivo CSV y cargar los datos en una lista de diccionarios
    registros = []
    cl=pd.read_excel(archivoClases)
    #cl=substitute_or_remove_prot_id(cl,"r")
    #data2=data.copy()
    cli=cl.groupby('protein_id')
    di=[]
    do={}
    for k,v in cli:
      for index,row in v.iterrows():
         di.append(row['class_name'])
      do[k]=di
      di=[]
    class_dict=do
    with open("resultados/patronesIdenticos"+str(int((float(ocurrencia)%1)*100))+sal+".csv", 'r') as file:
        reader = csv.DictReader(file)
        for row in reader:
            registros.append(row)
    
    # Diccionario para almacenar la cantidad de patrones únicos por proteína
    patrones_por_proteina = {}
    posiciones_patron={}
    # Iterar sobre los registros y extraer los patrones únicos de cada proteína
    for registro in registros:
        proteina = registro['Proteina']
        patron = registro['Patron']
        posicion = registro['Posiciones']
        if proteina not in patrones_por_proteina:
            patrones_por_proteina[proteina] = set()
        patrones_por_proteina[proteina].add(patron)
        pp=[oo for oo in ast.literal_eval(posicion) if oo is not '[' and oo is not ']']
        if proteina not in posiciones_patron:
            posiciones_patron[proteina]={}
        posiciones_patron[proteina][patron]=[]    
        for u in pp:
           for kaa in range(0,len(patron)):
                 posiciones_patron[proteina][patron].append(kaa+int(u))
        
    # Diccionario para almacenar las proteinas que tienen en común cada par de proteinas
    proteinas_comunes = {}
    rr=[]
    df_p = pd.read_excel(archivoEntrada)
    #df_p = pd.read_excel("proteinasClase_PC00060.xlsx")
    #df_p=substitute_or_remove_prot_id(df_p,"r")
    proteinas_dict2 = dict(df_p[['protein_id','protein_sequence']].values)
    pares_proteinas_procesados = set()
    # Filtrar las proteínas que tienen al menos 10 patrones únicos en común
        
    for proteina1, patrones1 in patrones_por_proteina.items():
        for proteina2, patrones2 in patrones_por_proteina.items():
            if proteina1 != proteina2 and (proteina2, proteina1) not in pares_proteinas_procesados:
                patrones_comunes = patrones1.intersection(patrones2)
                if len(patrones_comunes) >= patronesComun:
                    par_proteinas = (proteina1, proteina2)
                       
                       
                       
                    proteinas_comunes[par_proteinas] = patrones_comunes
                    pares_proteinas_procesados.add(par_proteinas)
            
    output = []
    df_b = pd.read_csv("AllProteins_%Similitud.csv")
    output2=[]
    proteinas_dict = df_b.set_index(['Proteina1', 'Proteina2'])['Similaridad'].to_dict()
    outbreak=[]
    first=True
    first2=True
    for par_proteinas, patrones_comunes in proteinas_comunes.items():
    
        proteina1, proteina2 = par_proteinas
        pattern_lengths = {}
        pattern_l={}
        Antecedentes={}
        
        if(proteina1 == 'Q13753' and proteina2 == 'P07550'):
            print(patrones_comunes)
        for pattern in patrones_comunes:
            length = len(pattern)
            key = f'Longitud {length}'
            if key in pattern_lengths:
                pattern_lengths[key].append([pattern])
                Add=posiciones_patron[proteina1][pattern]
                if(proteina1 == 'Q13753' and proteina2 == 'P07550'):
                    print(Add)
                if proteina1 not in Antecedentes:
                    Antecedentes[proteina1]=set()
                lex=len(Antecedentes[proteina1] & set(Add))
                Antecedentes[proteina1].update(Add)   
                pattern_l[key][0]+=len(Add)-lex
                Add=posiciones_patron[proteina2][pattern]

                if proteina2 not in Antecedentes:
                    Antecedentes[proteina2]=set()
                lex=len(Antecedentes[proteina2] & set(Add))
                Antecedentes[proteina2].update(Add)
                pattern_l[key][1]+=len(Add)-lex
                #sprint(length*len(Posic))
            else:
                pattern_lengths[key] = [[pattern]]
                Add=posiciones_patron[proteina1][pattern]
                
                if proteina1 not in Antecedentes:
                    Antecedentes[proteina1]=set()   
                lex=len(Antecedentes[proteina1] & set(Add))
                #print(lex)
                #print(Antecedentes)
                Antecedentes[proteina1].update(Add)
                Add2=posiciones_patron[proteina2][pattern]
                
                
                if proteina2 not in Antecedentes:
                    Antecedentes[proteina2]=set()
                lex2=len(Antecedentes[proteina2] & set(Add2))
                Antecedentes[proteina2].update(Add2)
                
                pattern_l[key]=[len(Add)-lex,len(Add2)-lex2]
                
        sorted_pattern_lengths = dict(sorted(pattern_lengths.items(), key=lambda x: int(x[0][9:]), reverse=True))
        
        if proteina1 != proteina2:
            prot=[proteinas_dict2[proteina1],proteinas_dict2[proteina2]]
            if Antecedentes != {} and(len(prot[0])>0 and len(prot[1])>0):
                output.append([sorted_pattern_lengths, proteina1, proteina2,class_dict[proteina1] if proteina1 in class_dict else "N/A",class_dict[proteina2] if proteina2 in class_dict else "N/A"])
                
                df = pd.DataFrame(output, columns=['Patrones', 'Proteina1', 'Proteina2',"classesProt1","classesProt2"])
                output=[]
                if(first2):
                     df.to_csv('resultados/Metrica_patronesComunes'+str(int((float(ocurrencia)%1)*100))+sal+'.csv',
              index=False)
                     first2=False
                else:
                     df.to_csv('resultados/Metrica_patronesComunes'+str(int((float(ocurrencia)%1)*100))+sal+'.csv',index=False,header=False,mode='a')
                   
            #else:
                #output.append([sorted_pattern_lengths, proteina1, proteina2,
                #               'N/A'])                               
            
                #print("prot1 : "+proteina1 + " : "+str(len(Antecedentes[proteina1])))
                #print("prot2 : "+proteina2 + " : " + str(len(Antecedentes[proteina2]) ))
            if Antecedentes != {} and(len(prot[0])>0 and len(prot[1])>0):                              
                 output2.append([proteina1,proteina2, (np.mean([len(Antecedentes[proteina1])/len(prot[0]),len(Antecedentes[proteina2])/len(prot[1])])*100),class_dict[proteina1] if proteina1 in class_dict else "N/A",class_dict[proteina2] if proteina2 in class_dict else "N/A"])
                 df2=pd.DataFrame(output2,columns=['proteina1','proteina2','%Coincidencia',"classesProt1","classesProt2"])
                 output2=[]
                 if(first):
                     df2.to_csv('resultados/Metrica_Coincidencia'+str(int((float(ocurrencia)%1)*100))+sal+'.csv',index=False)
                     first=False
                 else:
                     df2.to_csv('resultados/Metrica_Coincidencia'+str(int((float(ocurrencia)%1)*100))+sal+'.csv',index=False,header=False,mode='a')
                 
                 
                                
    #output2=sorted(output2, key = lambda x: int(x[2]))
    #df2=pd.DataFrame(output2,columns=['proteina1','proteina2','%Coincidencia'])
    #df2.to_csv('resultados/Metrica_Coincidencia.csv',
    #          index=False)
    


def patronesComunClas(patronesComun,name,archivoEntrada,ocurrencia,sal,archivoClases):
    
    # Leer el archivo CSV y cargar los datos en una lista de diccionarios
    registros = []
    cl=pd.read_excel(archivoClases)
    #cl=substitute_or_remove_prot_id(cl,"r")
    #data2=data.copy()
    cli=cl.groupby('protein_id')
    di=[]
    do={}
    for k,v in cli:
      for index,row in v.iterrows():
         di.append(row['class_name'])
      do[k]=di
      di=[]
    class_dict=do
    with open("clases/"+name+"/patronesIdenticos"+str(int((float(ocurrencia)%1)*100))+sal+".csv", 'r') as file:
        reader = csv.DictReader(file)
        for row in reader:
            registros.append(row)
    
    # Diccionario para almacenar la cantidad de patrones únicos por proteína
    patrones_por_proteina = {}
    posiciones_patron={}
    # Iterar sobre los registros y extraer los patrones únicos de cada proteína
    for registro in registros:
        proteina = registro['Proteina']
        patron = registro['Patron']
        posicion = registro['Posiciones']
        if proteina not in patrones_por_proteina:
            patrones_por_proteina[proteina] = set()
        patrones_por_proteina[proteina].add(patron)
        pp=[oo for oo in ast.literal_eval(posicion) if oo is not '[' and oo is not ']']
        if proteina not in posiciones_patron:
            posiciones_patron[proteina]={}
        posiciones_patron[proteina][patron]=[]    
        for u in pp:
           for kaa in range(0,len(patron)):
                 posiciones_patron[proteina][patron].append(kaa+int(u))
        
    # Diccionario para almacenar las proteinas que tienen en común cada par de proteinas
    proteinas_comunes = {}
    rr=[]
    df_p = pd.read_excel(archivoEntrada)
    #df_p = pd.read_excel("proteinasClase_PC00060.xlsx")
    #df_p=substitute_or_remove_prot_id(df_p,"r")
    proteinas_dict2 = dict(df_p[['protein_id','protein_sequence']].values)
    pares_proteinas_procesados = set()
    # Filtrar las proteínas que tienen al menos 10 patrones únicos en común
        
    for proteina1, patrones1 in patrones_por_proteina.items():
        for proteina2, patrones2 in patrones_por_proteina.items():
            if proteina1 != proteina2 and (proteina2, proteina1) not in pares_proteinas_procesados:
                patrones_comunes = patrones1.intersection(patrones2)
                if len(patrones_comunes) >= patronesComun:
                    par_proteinas = (proteina1, proteina2)
                       
                       
                       
                    proteinas_comunes[par_proteinas] = patrones_comunes
                    pares_proteinas_procesados.add(par_proteinas)
            
    output = []
    df_b = pd.read_csv("AllProteins_%Similitud.csv")
    output2=[]
    proteinas_dict = df_b.set_index(['Proteina1', 'Proteina2'])['Similaridad'].to_dict()
    outbreak=[]
    first=True
    first2=True
    for par_proteinas, patrones_comunes in proteinas_comunes.items():
    
        proteina1, proteina2 = par_proteinas
        pattern_lengths = {}
        pattern_l={}
        Antecedentes={}
        
        if(proteina1 == 'Q13753' and proteina2 == 'P07550'):
            print(patrones_comunes)
        for pattern in patrones_comunes:
            length = len(pattern)
            key = f'Longitud {length}'
            if key in pattern_lengths:
                pattern_lengths[key].append([pattern])
                Add=posiciones_patron[proteina1][pattern]
                if(proteina1 == 'Q13753' and proteina2 == 'P07550'):
                    print(Add)
                if proteina1 not in Antecedentes:
                    Antecedentes[proteina1]=set()
                lex=len(Antecedentes[proteina1] & set(Add))
                Antecedentes[proteina1].update(Add)   
                pattern_l[key][0]+=len(Add)-lex
                Add=posiciones_patron[proteina2][pattern]

                if proteina2 not in Antecedentes:
                    Antecedentes[proteina2]=set()
                lex=len(Antecedentes[proteina2] & set(Add))
                Antecedentes[proteina2].update(Add)
                pattern_l[key][1]+=len(Add)-lex
                #sprint(length*len(Posic))
            else:
                pattern_lengths[key] = [[pattern]]
                Add=posiciones_patron[proteina1][pattern]
                
                if proteina1 not in Antecedentes:
                    Antecedentes[proteina1]=set()   
                lex=len(Antecedentes[proteina1] & set(Add))
                #print(lex)
                #print(Antecedentes)
                Antecedentes[proteina1].update(Add)
                Add2=posiciones_patron[proteina2][pattern]
                
                
                if proteina2 not in Antecedentes:
                    Antecedentes[proteina2]=set()
                lex2=len(Antecedentes[proteina2] & set(Add2))
                Antecedentes[proteina2].update(Add2)
                
                pattern_l[key]=[len(Add)-lex,len(Add2)-lex2]
                
        sorted_pattern_lengths = dict(sorted(pattern_lengths.items(), key=lambda x: int(x[0][9:]), reverse=True))
        
        if proteina1 != proteina2:
            prot=[proteinas_dict2[proteina1],proteinas_dict2[proteina2]]
            if Antecedentes != {} and(len(prot[0])>0 and len(prot[1])>0):
                output.append([sorted_pattern_lengths, proteina1, proteina2,class_dict[proteina1] if proteina1 in class_dict else "N/A",class_dict[proteina2] if proteina2 in class_dict else "N/A"])
                
                df = pd.DataFrame(output, columns=['Patrones', 'Proteina1', 'Proteina2',"classesProt1","classesProt2"])
                output=[]
                if(first2):
                     df.to_csv('clases/'+name+'/Metrica_patronesComunes'+str(int((float(ocurrencia)%1)*100))+sal+'.csv',
              index=False)
                     first2=False
                else:
                     df.to_csv('clases/'+name+'/Metrica_patronesComunes'+str(int((float(ocurrencia)%1)*100))+sal+'.csv',index=False,header=False,mode='a')
                   
            #else:
                #output.append([sorted_pattern_lengths, proteina1, proteina2,
                #               'N/A'])                               
            
                #print("prot1 : "+proteina1 + " : "+str(len(Antecedentes[proteina1])))
                #print("prot2 : "+proteina2 + " : " + str(len(Antecedentes[proteina2]) ))
            if Antecedentes != {} and(len(prot[0])>0 and len(prot[1])>0):                              
                 output2.append([proteina1,proteina2, (np.mean([len(Antecedentes[proteina1])/len(prot[0]),len(Antecedentes[proteina2])/len(prot[1])])*100),class_dict[proteina1] if proteina1 in class_dict else "N/A",class_dict[proteina2] if proteina2 in class_dict else "N/A"])
                 df2=pd.DataFrame(output2,columns=['proteina1','proteina2','%Coincidencia',"classesProt1","classesProt2"])
                 output2=[]
                 if(first):
                     df2.to_csv('clases/'+name+'/Metrica_Coincidencia'+str(int((float(ocurrencia)%1)*100))+sal+'.csv',index=False)
                     first=False
                 else:
                     df2.to_csv('clases/'+name+'/Metrica_Coincidencia'+str(int((float(ocurrencia)%1)*100))+sal+'.csv',index=False,header=False,mode='a')
                 
                 
                                
    #output2=sorted(output2, key = lambda x: int(x[2]))
    #df2=pd.DataFrame(output2,columns=['proteina1','proteina2','%Coincidencia'])
    #df2.to_csv('resultados/Metrica_Coincidencia.csv',
    #          index=False)


def remplazar_sequence_for_ID(output,archivoEntrada):
    df_b = pd.read_excel(archivoEntrada)
    #df_b = pd.read_excel("proteinasClase_PC00060.xlsx")
    #df_b=substitute_or_remove_prot_id(df_b,"r")
    # Ordenar de mayor a menor tamaño. Las subcadenas del mismo tamaño se ordenan por orden alfabetico
    output_ordered = sorted(output, key=lambda x: (-len(x[0]), x[0]))

    proteinas_dict = dict(df_b[['protein_sequence', 'protein_id']].values)

    for item in output_ordered:
        protein_sequence1 = item[0]
        protein_sequence2 = item[1]
        if protein_sequence1 in proteinas_dict and protein_sequence2 in proteinas_dict:
            item[0] = proteinas_dict[protein_sequence1]
            item[1] = proteinas_dict[protein_sequence2]



    df_a = pd.DataFrame(output_ordered, columns=['Proteina1', 'Proteina2', 'Similaridad'])

    # Guardar el DataFrame actualizado en un archivo CSV
    df_a.to_csv('AllProteins_%Similitud.csv', index=False)