compute_for_clases.py 19.9 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
import pandas as pd
import time
import ast
import csv
import math
from interfazGrafica import interfaz
from descarteProteinas import ejecutar,remplazar_ID_for_sequence
from generate_tha_excel import substitute_or_remove_prot_id
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
from collections import defaultdict
from pathlib import Path



def substitute_or_remove_prot_id2(data,sub_rem):
    print("inside the problem")
    with open("nombres_sust.txt") as prottosubs:
          index=prottosubs.readline()
          acept=index.split()
          listtosubs={}
          for i in range(0,len(acept)):
            listtosubs[acept[i]]=[]
          while line := prottosubs.readline():
              newline=line.split()
              #print(len(newline))
              for i in range(0,len(newline)):
                  
                  listtosubs[list(listtosubs.keys())[i]].append(newline[i].strip())  
    resub=1
    if re.search("Primary",list(listtosubs.keys())[0]):
           resub=0
    print((resub+1)%2)
    #print(data)
    #data2=data.copy()
    if(sub_rem == "s"):
       data["Proteina"].replace(list(listtosubs.values())[(resub+1)%2], list(listtosubs.values())[resub])
    #datacp=data.copy()
    #print(pd.concat([data2,datacp]).drop_duplicates())
    else: 
        global globi
        datas= data[data["Proteina"].isin(list(listtosubs.values())[(resub+1)%2])==True]
        data = data[data["Proteina"].isin(list(listtosubs.values())[(resub+1)%2])==False]
        
        #datas.to_csv('resultados/proteinasDescartadas_'+ str(globi) +'.csv', index=False) 

        globi=globi+1 
    return data 

def readData(archivoEntrada, enfermedad, archivoTarget):
57 58 59 60 61 62 63 64 65 66 67 68 69
    """
    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.
    """
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
    data = pd.read_excel(archivoEntrada)
    dataC = pd.read_csv("resultados/proteinasDescartadas2.csv")
    #data=substitute_or_remove_prot_id(data,"r")
    #dataC=substitute_or_remove_prot_id(dataC,"r")
    #Descarte de proteinas
    data = data[~data['protein_id'].isin(dataC['ProteinasDescartadas'])]
    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):
98 99 100 101 102 103 104 105 106 107 108 109 110
    """
    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.
    """
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
    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):
147 148 149 150 151 152 153 154 155 156 157
    """
    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.
    """
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
    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])))
        dict_ordered_patterns = {k: v for k, v in dict_ordered_patterns.items() if len(k) >= 4}
        df = pd.DataFrame(dict_ordered_patterns.items(), columns=['pattern', 'proteins'])
        num_patrones = df.shape[0]
    pattern_freqMin = {k: v for k, v in pattern_freqMin.items() if len(k) >= 4}
    return pattern_freqMin, num_patrones

229 230 231 232 233 234 235 236 237 238 239 240 241
def remplazar_sequence_for_ID(pattern_freqMin,name,archivoEntrada,ocurrencia,archivoClases=None):
    """
    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.
    - name: str name of the class
    - 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)
242 243
    #df_b=pd.read_excel("proteinasClase_PC00060.xlsx")
    #df_b=substitute_or_remove_prot_id(df_b,'r')
244
    cl=pd.read_excel(archivoClase)
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
    #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
    output = []

    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]
        item.append(class_dict[item[1]] if item[1] in class_dict else "N/A")    
    df_a = pd.DataFrame(output_ordered, columns=['Patron', 'Proteina', 'Posiciones','classesProt'])

    # Guardar el DataFrame actualizado en un archivo CSV
    
278
    df_a.to_csv('clases/'+ name +'/patronesIdenticos'+str(int((ocurrencia%1)*100))+'.csv', index=False)
279
    print("Se ha generado el .csv con los patrones idénticos encontrados")
280 281 282
def compute_pattern_ocurrence(df,name):
    """
    Computes the occurrence of patterns in the data and saves the results to a CSV file.
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 399 400 401 402 403 404 405 406 407 408 409
    Parameters:
    - df: pandas DataFrame, DataFrame containing pattern information.
    - name: str name of the class
    
    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.
    """
    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 ']']
             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)      
             compl+=1
         comp+=len(res)
         
    for k,v in df2:
         dicta={'Patron':[] ,'total_Patrones_por_prot':[],'numero_prot':[]}
         dicta[k]=0
         dox=0
         dix=0
         co=0
         res=0
         Posic=set()
         for index,row in v.iterrows():
             
             Posic|=set([oo for oo in ast.literal_eval(row['Posiciones']) if oo is not '[' and oo is not ']'])
             Poss=[oo for oo in ast.literal_eval(row['Posiciones']) if oo is not '[' and oo is not ']']
             co+=1
             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)   
         dix+=len(Posic)   
         dox+=len(Posic)*len(str(k))
         dox/=seq_len
         #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)
         dicta['Patron'].append(str(k))
         #dicta['total_Patrones'].append(compl)
         dicta['total_Patrones_por_prot'].append(res)
         dicta['numero_prot'].append(co)
         do=pd.DataFrame(dicta)
         if not first:
            do.to_csv('clases/'+fil.name.split('.')[0]+'/patronesOcurrencia.csv',index=False,header=False,mode='a' )
         else:
            do.to_csv('clases/'+fil.name.split('.')[0]+'/patronesOcurrencia.csv',index=False )
            first=False
    del df2                 
    
    del do    
def compute_proteinas_ocurrencia(df,name):
    """
    Computes the occurrence of proteins in the data and saves the results to a CSV file.

    Parameters:
    - df: pandas DataFrame, DataFrame containing protein information.
    - name: str name of the class
    
    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.
    """
    df3=df.groupby('Proteina')
    first=True
    df_b = pd.read_excel(archivoEntrada)
    #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:
        di={'proteinas':[],'global_ocurrence':[],"classesProt":[]}
        seq=proteinas_dict[k]
        #di['maximum_ocurrence'].append(len(seq))
        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))
        #di['patrones'].append(pato)    
        di['global_ocurrence'].append(glob_ocurrence/len(seq))
        di['classesProt'].append(class_dict[k] if k in class_dict else "N/A")
        do=pd.DataFrame(di)
        if not first:
            do.to_csv('clases/'+fil.name.split('.')[0]+'/proteinasOcurrencia.csv',index=False,header=False,mode='a' )
         else:
            do.to_csv('clases/'+fil.name.split('.')[0]+'/proteinasOcurrencia.csv',index=False )   
           first=False 
    del do        
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
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)

425
    archivoEntrada = datosInterfaz["NombreArchivoEntrada"]
426 427 428
    enfermedad = datosInterfaz["CodigoEnfermedad"]
    archivoTarget = datosInterfaz["NombreArchivoTarget"]
    similitud = float(datosInterfaz["Similitud"])
429
    archivoClase=datosIntefaz["NombreArchivoClase"]
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
    cl=pd.read_excel("alzheimer_protein_class 2.xlsx")
    #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
         
    for fil in Path("clases").rglob("*.xlsx"):
       if not os.path.exists("clases/"+fil.name.split('.')[0]+"/"):
        # Si no existe, crearla
         os.makedirs("clases/"+fil.name.split('.')[0]+"/")
         print(f"La carpeta resultados se ha creado correctamente.")
       else:
          print(f"La carpeta resultados ya existe.")
450
       #ejecutar("clases/"+fil.name, enfermedad, similitud)
451 452 453 454 455 456 457 458 459 460 461 462 463 464
       pattern_freqMin = dict()
       sequences, num_filas = readData("clases/"+fil.name, enfermedad, archivoTarget)
       df_b = pd.read_excel("clases/"+fil.name)
       #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=0
       for i in sequences:
         seq_len+=len(i)  
       print(min_ocurrence)
       pattern_freqMin, num_patrones = buscar_patrones_identicos(sequences)
465
       remplazar_sequence_for_ID(pattern_freqMin,fil.name.split('.')[0],archivoEntrada,datosInterfaz["OcurrenciaMin"],archivoClase)
466 467 468 469 470 471
   
       df=pd.read_csv('clases/'+fil.name.split('.')[0]+'/patronesIdenticos.csv', usecols=['Patron', 'Proteina', 'Posiciones',"classesProt"],index_col=False)
       #df=substitute_or_remove_prot_id2(df,"s")
       df.to_csv('clases/'+fil.name.split('.')[0]+'/patronesIdenticos.csv', index=False)
    
       #dfx=df.copy()
472 473
       compute_pattern_ocurrence(df,name)
                         
474 475
    
       
476
       compute_proteinas_ocurrencia(df,name)
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
              
    #metricas.metrica_distanciaProteinas()
       archivo = 'resultados/Metrica_distanciaProteinasMismoPatron.csv'
       nombreOutput = 'resultados/Figura_DistanciaProteinasMismoPatron'
    #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"]))

       metricas.patronesComunClas(metrica,fil.name.split('.')[0])
    
       archivo = 'resultados/Metrica_patronesComunes.csv'
       nombreOutput = 'resultados/Figura_distanciaProteinasPatronesComunes'
    #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")
       
       fin = time.time()
    
       tiempo_total = fin - inicio
       print(tiempo_total, "segundos")