patrones_identicos.py 19.1 KB
Newer Older
Rafael Artinano's avatar
Rafael Artinano committed
1 2 3 4 5 6 7
import pandas as pd
import time
import ast
import csv
import math
from interfazGrafica import interfaz
from descarteProteinas import ejecutar,remplazar_ID_for_sequence
8
from generate_the_excel import substitute_or_remove_prot_id
Rafael Artinano's avatar
Rafael Artinano committed
9 10 11 12 13 14 15 16
import metricas
from graficas import grafica
import os
import json
import ast
import re
from patrones_similares_aa import remplazar_sequence_for_ID as remplazar_s
from patrones_similares_aa import buscar_patrones_simAA
17
from collections import defaultdict
Rafael Artinano's avatar
Rafael Artinano committed
18 19 20 21



def readData(archivoEntrada, enfermedad, archivoTarget):
22 23 24 25 26 27 28 29 30 31 32 33 34
    """
    Reads data from an Excel file, filters it based on disease (if specified),
    and returns protein sequences along with the number of rows.

    Parameters:
    - archivoEntrada: str, path to the input Excel file.
    - enfermedad: str, disease ID for filtering (empty string for no filtering).
    - archivoTarget: str, path to the target Excel file (not currently in use).

    Returns:
    - sequences: pandas Series, protein sequences column.
    - num_filas: int, number of rows in the filtered data.
    """
Rafael Artinano's avatar
Rafael Artinano committed
35 36 37 38
    data = pd.read_excel(archivoEntrada)
    #data=substitute_or_remove_prot_id(data,"r")
    #dataC=substitute_or_remove_prot_id(dataC,"r")
    #Descarte de proteinas
39 40
    #print(data)
    #data = data[~data['protein_id'].isin(dataC['ProteinasDescartadas'])]
Rafael Artinano's avatar
Rafael Artinano committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
    print("Se ha realizado el descarte de proteínas")

    # "C0002395"
    if(enfermedad != ''):
        data = data.loc[data["disease_id"] == enfermedad]
        #dataB = pd.read_excel("proteinas_en_comun_Alzheimer.xlsx")
        #print("Se han seleccionado las proteínas de la enfermedad elegida")
        #dataB=substitute_or_remove_prot_id(dataB,"r")
    #if(archivoTarget != ''):
    #    dataB=substitute_or_remove_prot_id(dataB,"r")
        #Eliminar las proteinas target
    #    data = data[~((data["disease_id"] == enfermedad) &
    #                  (data["protein_id"].isin(dataB["protein_id"])))]
    #    print("Se han descartado las proteínas del archivo target")

    sequences = data["protein_sequence"]
    print(sequences)
    num_filas = sequences.shape[0]

    return sequences, num_filas

def guardar_patrones_len1(sequences, pattern_freqMin):
63 64 65 66 67 68 69 70 71 72 73 74 75
    """
    Processes protein sequences to find patterns of length 1 and their positions,
    filters patterns based on minimum occurrence, and saves results to a CSV file.

    Parameters:
    - sequences: pandas Series, protein sequences.
    - pattern_freqMin: dict, dictionary to store patterns and their occurrences.

    Returns:
    - pattern_freqMin: dict, updated dictionary of patterns.
    - posicionPatterns: dict, positions of each character in the sequences.
    - longitud_max: int, maximum length of protein sequences.
    """
Rafael Artinano's avatar
Rafael Artinano committed
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
    all_patterns = dict()
    longitud_max = 0
    # Each pattern associated to the proteins the pattern is in
    pattern_proteins = {}
    for protein in sequences:
        longitud = len(protein)
        if longitud > longitud_max:
            longitud_max = longitud

        all_patterns[protein] = []
        # En cada iteración guarda los patrones que aparecen en la secuencia con sus posiciones asociadas a la proteina
        posicionPatterns = dict()
        for index, letter in enumerate(protein):
            posicionPatterns[letter] = posicionPatterns.get(letter, []) + [index]

        all_patterns[protein] = posicionPatterns


    for protein, patterns in all_patterns.items():
        for pattern, positions in patterns.items():
            if pattern not in pattern_proteins:
                pattern_proteins[pattern] = {}
            if protein not in pattern_proteins[pattern]:
                pattern_proteins[pattern][protein] = []
            pattern_proteins[pattern][protein].extend(positions)


    for pattern, proteins in pattern_proteins.items():
        if len(proteins) >= min_ocurrence:
            pattern_freqMin[pattern] = proteins

    df = pd.DataFrame(pattern_freqMin.items(), columns=['pattern', 'proteins'])
    df.to_csv('prueba2.csv', index=False)
    return pattern_freqMin, posicionPatterns, longitud_max

def buscar_patrones_identicos(sequences):
112 113 114 115 116 117 118 119 120 121 122
    """
    Searches for identical patterns of different lengths in protein sequences
    and stores them along with their positions in a dictionary.

    Parameters:
    - sequences: pandas Series, protein sequences.

    Returns:
    - pattern_freqMin: dict, dictionary of patterns and their positions.
    - num_patrones: int, number of unique patterns found.
    """
Rafael Artinano's avatar
Rafael Artinano committed
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
    pattern_freqMin = {}
    pattern_freqMin, posicionPatterns, longitud_max = guardar_patrones_len1(sequences, pattern_freqMin)

    if bool(pattern_freqMin):
        for pattern_length in range(2, longitud_max + 1):
            # Si se intenta acceder a una clave que no existe se creara una lista vacia
            auxPos = {}
            sub_seqs = []
            for pattern, proteins in pattern_freqMin.items():
                if len(pattern) == pattern_length - 1:
                    for prot, positions in proteins.items():
                        protein_len = len(prot)
                        if protein_len < pattern_length - 1:
                            continue
                        for position in positions:
                            if (protein_len < position + pattern_length):
                                continue
                            sub_seq = prot[position:position + pattern_length]
                            if sub_seq in pattern_freqMin:
                                continue
                            # Si la ultima letra que es la nueva del patron ya esta min_freq, el patron es posible
                            # min freq tb
                            ultima_letra = sub_seq[-1]
                            pos_ultima_letra = position + pattern_length - 1
                            if ultima_letra in pattern_freqMin and pos_ultima_letra in pattern_freqMin[ultima_letra][prot]:
                                if sub_seq not in auxPos:
                                    auxPos[sub_seq] = {}
                                if prot not in auxPos[sub_seq]:
                                    auxPos[sub_seq][prot] = []
                                auxPos[sub_seq][prot].append(position)
                                if sub_seq not in sub_seqs:
                                    sub_seqs.append(sub_seq)
                print(pattern_length)
                sub_seqs_copy = sub_seqs.copy()
                for p in sub_seqs_copy:
                      if len(auxPos[p]) < min_ocurrence:
                          del auxPos[p]
                          sub_seqs.remove(p)

            # Si no se encuentra ningun patron de longitud pattern_length se sale del bucle. No hay mas patrones posible a encontrar
            if not bool(auxPos):
                break

            for pattern, proteins in auxPos.items():
                for prot, pos in proteins.items():
                    if pattern not in pattern_freqMin:
                        pattern_freqMin[pattern] = {}
                    if prot not in pattern_freqMin[pattern]:
                        pattern_freqMin[pattern][prot] = []
                    found=list(filter(lambda x: pos-len(pattern) <= x <= pos+len(pattern), pattern_freqMin[pattern][prot]))
                    print(found)
                    print(len(found))
                    if(len(found)<=0):        
                       pattern_freqMin[pattern][prot].extend(pos)
                       if len(pattern) > 2:
                         if pattern[:-1] in pattern_freqMin:
                            del pattern_freqMin[pattern[:-1]]
                         if pattern[1:] in pattern_freqMin:
                            del pattern_freqMin[pattern[1:]]



        # Ordenar de mayor a menor tamaño. Las subcadenas del mismo tamaño se ordenan por orden alfabetico
        
        dict_ordered_patterns = dict(sorted(pattern_freqMin.items(), key=lambda x: (-len(x[0]), x[0])))
188
        #dict_ordered_patterns = {k: v for k, v in dict_ordered_patterns.items() if len(k) >= 4}
Rafael Artinano's avatar
Rafael Artinano committed
189 190
        df = pd.DataFrame(dict_ordered_patterns.items(), columns=['pattern', 'proteins'])
        num_patrones = df.shape[0]
191
    #pattern_freqMin = {k: v for k, v in pattern_freqMin.items() if len(k) >= 4}
Rafael Artinano's avatar
Rafael Artinano committed
192 193
    return pattern_freqMin, num_patrones

194
def remplazar_sequence_for_ID(pattern_freqMin,archivoEntrada,ocurrencia,Sal,archivoClases=None):
195 196 197 198 199 200 201 202 203 204 205
    """
    Replaces identified patterns in the original data with their corresponding IDs,
    saves the results to a CSV file, and prints a success message.

    Parameters:
    - pattern_freqMin: dict, dictionary of patterns and their positions.
    - archivoEntrada: str, path to the input Excel file.
    - ocurrencia: float, occurrence parameter.
    - archivoClases (Optional): str, path to the classes Excel file.
    """
    df_b = pd.read_excel(archivoEntrada)
Rafael Artinano's avatar
Rafael Artinano committed
206 207
    #df_b=pd.read_excel("proteinasClase_PC00060.xlsx")
    #df_b=substitute_or_remove_prot_id(df_b,'r')
208 209
    if(archivoClases is not None):
      cl=pd.read_excel(archivoClases)
Rafael Artinano's avatar
Rafael Artinano committed
210 211
    #cl=substitute_or_remove_prot_id(cl,"r")
    #data2=data.copy()
212
      cli=cl.groupby('protein_id')
Rafael Artinano's avatar
Rafael Artinano committed
213
      di=[]
214 215 216 217 218 219 220 221 222
      do={}
      for k,v in cli:
        for index,row in v.iterrows():
         di.append(row['class_name'])
        do[k]=di
        di=[]
      class_dict=do
      output = []
    
Rafael Artinano's avatar
Rafael Artinano committed
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
    for key, value in pattern_freqMin.items():
        for proteina, posiciones in value.items():
            output.append([key, proteina, posiciones])

    output = [sublista for sublista in output if len(sublista[0]) != 1]

    # 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_sequence = item[1]
        if protein_sequence in proteinas_dict:
            item[1] = proteinas_dict[protein_sequence]
238 239
        item.append(class_dict[item[1]] if item[1] in class_dict else "N/A")

Rafael Artinano's avatar
Rafael Artinano committed
240 241 242
    df_a = pd.DataFrame(output_ordered, columns=['Patron', 'Proteina', 'Posiciones','classesProt'])

    # Guardar el DataFrame actualizado en un archivo CSV
243
    df_a.to_csv('resultados/patronesIdenticos'+str(int((ocurrencia%1)*100))+Sal+'.csv', index=False)
Rafael Artinano's avatar
Rafael Artinano committed
244
    print("Se ha generado el .csv con los patrones idénticos encontrados")
245 246 247
def calculate_sequence_length(sequences):
    """
    Calculates the total length of protein sequences.
Rafael Artinano's avatar
Rafael Artinano committed
248

249 250
    Parameters:
    - sequences: pandas Series, protein sequences.
Rafael Artinano's avatar
Rafael Artinano committed
251

252 253 254 255
    Returns:
    - seq_len: int, total length of protein sequences.
    """
    seq_len = 0
Rafael Artinano's avatar
Rafael Artinano committed
256
    for i in sequences:
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
        seq_len += len(i)
    return seq_len
def group_classes_by_protein(cl):
    """
    Groups classes by protein ID.

    Parameters:
    - cl: pandas DataFrame, DataFrame containing class information.

    Returns:
    - class_dict: dict, dictionary of protein IDs and associated classes.
    """
    class_dict = {}
    cli = cl.groupby('protein_id')
    for k, v in cli:
        class_names = [row['class_name'] for index, row in v.iterrows()]
        class_dict[k] = class_names
    return class_dict
275
def compute_pattern_ocurrence(df,sal):
276 277 278 279 280
    """
    Computes the occurrence of patterns in the data and saves the results to a CSV file.

    Parameters:
    - df: pandas DataFrame, DataFrame containing pattern information.
Rafael Artinano's avatar
Rafael Artinano committed
281
    
282 283
    Note: saves the patterns, the amount of times a pattern appears in proteins of the dataset and the number of proteins that have that pattern.
    """
Rafael Artinano's avatar
Rafael Artinano committed
284 285 286 287 288 289 290 291 292
    df2=df.groupby('Patron')
    compl=0
    comp=0
    first=True
    res=set()
    for k,v in df2:
         res=set()  
         for index,row in v.iterrows():
             Posic=[oo for oo in ast.literal_eval(row['Posiciones']) if oo is not '[' and oo is not ']']
293 294 295 296 297 298 299 300 301
             rem=[]
             if(len(Posic)>2):
              u=0
              while u+1<len(Posic):
                 if(Posic[u]+len(k)<=Posic[u+1]):
                    del Posic[u+1]
                 else:
                   u+=1
             res|=set(Posic)      
Rafael Artinano's avatar
Rafael Artinano committed
302 303
             compl+=1
         comp+=len(res)
304
         
Rafael Artinano's avatar
Rafael Artinano committed
305
    for k,v in df2:
306
         dicta={'Patron':[] ,'total_Patrones_por_prot':[],'numero_prot':[]}
Rafael Artinano's avatar
Rafael Artinano committed
307 308 309 310
         dicta[k]=0
         dox=0
         dix=0
         co=0
311
         res=0
Rafael Artinano's avatar
Rafael Artinano committed
312 313
         Posic=set()
         for index,row in v.iterrows():
314
             
Rafael Artinano's avatar
Rafael Artinano committed
315
             Posic|=set([oo for oo in ast.literal_eval(row['Posiciones']) if oo is not '[' and oo is not ']'])
316
             Poss=[oo for oo in ast.literal_eval(row['Posiciones']) if oo is not '[' and oo is not ']']
Rafael Artinano's avatar
Rafael Artinano committed
317
             co+=1
318 319 320 321 322 323 324 325 326
             rem=[]
             if(len(Poss)>2):
              u=0
              while u+1<len(Poss):
                 if(Poss[u]+len(k)<=Poss[u+1]):
                    del Poss[u+1]
                 else:
                   u+=1
             res+=len(Poss)   
Rafael Artinano's avatar
Rafael Artinano committed
327 328 329
         dix+=len(Posic)   
         dox+=len(Posic)*len(str(k))
         dox/=seq_len
330 331 332 333 334
         #dicta['%Ocurrencia_caracter'].append(dox*100)
         #dicta['longitud_Apariciones'].append(co)
         #dicta['longitud_Apariciones_Proteina'].append(dix)
         #dicta['%Patron'].append(co/compl*100)
         #dicta['%Patron_proteina'].append(dix/comp*100)
Rafael Artinano's avatar
Rafael Artinano committed
335
         dicta['Patron'].append(str(k))
336 337 338
         #dicta['total_Patrones'].append(compl)
         dicta['total_Patrones_por_prot'].append(res)
         dicta['numero_prot'].append(co)
Rafael Artinano's avatar
Rafael Artinano committed
339 340
         do=pd.DataFrame(dicta)
         if not first:
341
            do.to_csv('resultados/patronesOcurrencia'+str(int((float(datosInterfaz["OcurrenciaMin"])%1)*100))+sal+'.csv',index=False,header=False,mode='a' )
Rafael Artinano's avatar
Rafael Artinano committed
342
         else:
343
            do.to_csv('resultados/patronesOcurrencia'+str(int((float(datosInterfaz["OcurrenciaMin"])%1)*100))+sal+'.csv',index=False )
Rafael Artinano's avatar
Rafael Artinano committed
344 345 346 347
            first=False
    del df2                 
    
    del do
348
def compute_proteinas_ocurrencia(df,sal):
349 350 351 352 353 354 355 356
    """
    Computes the occurrence of proteins in the data and saves the results to a CSV file.

    Parameters:
    - df: pandas DataFrame, DataFrame containing protein information.
    
    Note: Saves four values the protein id, the so called global ocurrence, the classes it has each protein. Global ocurrence is the percentage of Aminoacids in the sequence that belong to a pattern vs the total of aminoacids in the sequence of a specific protein.
    """
Rafael Artinano's avatar
Rafael Artinano committed
357 358
    df3=df.groupby('Proteina')
    first=True
359
    df_b = pd.read_excel(archivoEntrada)
Rafael Artinano's avatar
Rafael Artinano committed
360 361 362 363 364
    #df_b = pd.read_excel("proteinasClase_PC00060.xlsx")
    #df_b=substitute_or_remove_prot_id(df_b,"r")
    proteinas_dict = dict(df_b[['protein_id','protein_sequence']].values)
    positions_visited=[]
    for k,v in df3:
365
        di={'proteinas':[],'global_ocurrence':[],"classesProt":[]}
Rafael Artinano's avatar
Rafael Artinano committed
366
        seq=proteinas_dict[k]
367
        #di['maximum_ocurrence'].append(len(seq))
Rafael Artinano's avatar
Rafael Artinano committed
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
        di['proteinas'].append(k)
        pato=[]
        glob_ocurrence=0
        Acum=[]
        
        
        
        for index,row in v.iterrows():
            print(row)
            pat={}
            pat['patron']=str(row['Patron'])
            Posit=[oo for oo in ast.literal_eval(row['Posiciones']) if oo is not '[' and oo is not ']']
            print(Posit)
            Add=[]
            for i in Posit:
               for kaa in range(0,len(str(row['Patron']))):
                   print(i)
                   Add.append(int(i)+kaa)
            lex=len(list(set(Acum) & set(Add)))       
                    
            Posic=Posit
            pat['loc_ocurren']=(len(Posic)*len(str(row['Patron'])))/len(seq)
            glob_ocurrence+=len(Posic)*len(str(row['Patron']))-lex
            pato.append(pat)
            Acum=list(set(Acum) | set(Add))
393 394
        #di['patrones'].append(pato)    
        di['global_ocurrence'].append(glob_ocurrence/len(seq))
Rafael Artinano's avatar
Rafael Artinano committed
395 396 397
        di['classesProt'].append(class_dict[k] if k in class_dict else "N/A")
        do=pd.DataFrame(di)
        if not first:
398
           do.to_csv('resultados/proteinasOcurrencia'+str(int((float(datosInterfaz["OcurrenciaMin"])%1)*100))+sal+'.csv',index=False,header=False,mode='a' )
Rafael Artinano's avatar
Rafael Artinano committed
399
        else: 
400
           do.to_csv('resultados/proteinasOcurrencia'+str(int((float(datosInterfaz["OcurrenciaMin"])%1)*100))+sal+'.csv',index=False)   
Rafael Artinano's avatar
Rafael Artinano committed
401 402
           first=False 
    del do        
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
if __name__ == "__main__":
    if not os.path.exists("resultados"):
        # Si no existe, crearla
        os.makedirs("resultados")
        print(f"La carpeta resultados se ha creado correctamente.")
    else:
        print(f"La carpeta resultados ya existe.")


    inicio = time.time()
    jsonfile=open("param_file.conf","r")
    datosInterfaz=json.load(jsonfile)
    #datosInterfaz = interfaz()
    print(datosInterfaz)

    archivoEntrada = datosInterfaz["NombreArchivoEntrada"]
    enfermedad = datosInterfaz["CodigoEnfermedad"]
    archivoTarget = datosInterfaz["NombreArchivoTarget"]
    similitud = float(datosInterfaz["Similitud"])
    archivoClases = datosInterfaz["NombreArchivoClases"]
    archivoAA=datosInterfaz["NombreArchivoAA"]
424
    sal=datosInterfaz["ExtensionSalida"]
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
    cl=pd.read_excel(archivoClases)
    #cl=substitute_or_remove_prot_id(cl,"r")
    #data2=data.copy()
    cli=cl.groupby('protein_id')
    class_dict=group_classes_by_protein(cl)
    #ejecutar(archivoEntrada, enfermedad, similitud)
    pattern_freqMin = dict()
    sequences, num_filas = readData(archivoEntrada, enfermedad, archivoTarget)
    df_b = pd.read_excel(archivoEntrada)
    #df_b=pd.read_excel("proteinasClase_PC00060.xlsx")
    proteinas_dict = dict(df_b[['protein_sequence', 'protein_id']].values)
    ka=""
    for item in sequences:
            ka=proteinas_dict[item]        
    min_ocurrence = math.floor(num_filas * float(datosInterfaz["OcurrenciaMin"]))
    seq_len=calculate_sequence_length(sequences)  
    print(min_ocurrence)    
    #pattern_freq, num_patrones = buscar_patrones_simAA(sequences,min_ocurrence,archivoAA)
443
    #remplazar_s(pattern_freqMin,archivoEntrada,ArchivoAA,float(datosInterfaz["OcurrenciaMin"]),sal)  
444 445 446
    print(sequences)
    #pattern_freqMin, num_patrones = buscar_patrones_identicos(sequences,archivoEntrada,archivoAA,float(datosInterfaz["OcurrenciaMin"]))
    pattern_freqMin, num_patrones = buscar_patrones_identicos(sequences)
447
    remplazar_sequence_for_ID(pattern_freqMin,archivoEntrada,float(datosInterfaz["OcurrenciaMin"]),sal,archivoClases)
448
   
449
    df=pd.read_csv('resultados/patronesIdenticos'+str(int((float(datosInterfaz["OcurrenciaMin"])%1)*100))+sal+'.csv', usecols=['Patron', 'Proteina', 'Posiciones',"classesProt"],index_col=False)
450
    
451
    df.to_csv('resultados/patronesIdenticos'+str(int((float(datosInterfaz["OcurrenciaMin"])%1)*100))+sal+'.csv', index=False)
452 453
    
    #dfx=df.copy()
454 455
    compute_pattern_ocurrence(df,sal)
    compute_proteinas_ocurrencia(df,sal)
Rafael Artinano's avatar
Rafael Artinano committed
456 457 458 459 460 461 462
    #metricas.metrica_distanciaProteinas()
    #grafica(archivo, nombreOutput)
    
    print("Se han obtenido los resultados de la métrica para la distancia entre dos proteínas que poseen el mismo patrón")

    metrica = math.floor(num_patrones * float(datosInterfaz["Metrica"]))

463
    metricas.patronesComun(metrica,archivoEntrada,float(datosInterfaz["OcurrenciaMin"]),sal,archivoClases)
464
    
Rafael Artinano's avatar
Rafael Artinano committed
465 466 467
    
    #grafica(archivo, nombreOutput)
    print("Se han obtenido los resultados de la métrica para la distancia entre dos proteínas que poseen mas de un patrón en común")
Rafael Artinano's avatar
Rafael Artinano committed
468
    
Rafael Artinano's avatar
Rafael Artinano committed
469 470 471 472
    fin = time.time()
    
    tiempo_total = fin - inicio
    print(tiempo_total, "segundos")