'''

##  Name:
        expasy.py

##  Version: [1.0]

##  Author:
        <NAME> <<EMAIL>>

##  Created: [2021-10-22]

##  Description:
        Based on GO term list and UniProt ID list, load SwissProt files for each
        ID, search for GO terms, and save information if found.

##  Usage:
        python expasy.py

##  Arguments:
        None

##  Requirements:
        Bio.Entrez, Bio.ExPASy, Bio.SwissProt, Bio.SeqIO

## Example
        prot_filter_by_GO(GO_Terms, uniprot_IDs)

        GO_Terms = ["GO:0046755", "GO:0046761",
                    "GO:0046760", "GO:0039702",
                    "GO:0046765", "GO:0046762"]
        uniprot_IDs = ["A0A0K2RVI7_9BETC", "A8R4D4_9BETC",
                        "POLG_YEFV1", "POLG_DEN1W",
                        "Q6W352_CVEN9", "D9SV67_CLOC7",
                        "A9KSF7_LACP7", "B8I7R6_RUMCH"]
'''

from Bio import Entrez, ExPASy, SwissProt, SeqIO

# Definir email
Entrez.email = "<EMAIL>"

def prot_filter_by_GO(GO_Terms, uniprot_IDs, path=None):
    """Get SwissProt files from uniprot_IDs, search for GO_terms.

    Parameters:
        - GO_Terms (list): list of GO terms to search for
        - uniprot_IDs (list): list of UniProt IDs to get files
        - path (str, optional): path for file to save information (if found),
                            if not given, prot_filter_by_GO.txt file will be created

    Returns:
        - Writes output file if information is found
    """
    # Archivo
    if not path:
        path = 'prot_filter_by_GO.txt'
    file = open(path, 'w')

    # Iteramos primero sobre los ids de UniProt
    for uniprot in uniprot_IDs:
        # Descargamos el archivo de SwissProt, y lo leemos con la libreria correspondiente
        handle = ExPASy.get_sprot_raw(uniprot)
        record = SwissProt.read(handle).__dict__

        # Para cada GO term buscado
        for search_go in GO_Terms:
            # Compararemos con los GO terms del archivo, en cross_references
            for go_term in record['cross_references']:
                if go_term[1] == search_go:
                    # Si lo encontramos, guardamos la información en el archivo
                    file.write(f'ID: {uniprot}\n\n')  # ID

                    # Nombre se obtiene de la descipción
                    nombre = record["description"].split(";")[0]

                    file.write(f'Nombre: {nombre.split("=")[1]}\n\n' # Nombre
                               f'GO: {go_term[1:3]}\n\n' # Término GO y definición
                               f'Organismo: {record["organism"]}\n\n') # Organismo

                    # Para la sublocalización, accesamos a los comentarios
                    file.write('Localización:\n')
                    for comment in record['comments']:
                        if "SUBCELLULAR LOCATION" in comment:
                            file.write(f'{comment}\n')
                    file.write('\n\n')

                    # Para el prosite id, volvemos a iterar sobre cross_reference
                    file.write('PROSITE:\n')
                    for ref in record['cross_references']:
                        if ref[0] == 'PROSITE':
                            file.write(f'{ref[0]}: {ref[1]}\n')
                    file.write('\n\n')

                    # Para el abstract, obtenemos primero las referencias del
                    # primer artículo citado
                    file.write('Abstract:\n')
                    refs = record['references'][0].references
                    # Buscamos PubMed
                    for ref in refs:
                        if ref[0] == 'PubMed':
                            # Buscamos con efetch
                            handle = Entrez.efetch(db="pubmed", id=ref[1], \
                                                   rettype="abstract", \
                                                   retmode="text")
                            abstract = handle.read()
                            handle.close()
                            file.write(abstract)

                    # Separar proteinas
                    file.write('-'*60+'\n\n')

                    break  # Salir del for interno si se encontró

    file.close()
    return


GO_Terms = ["GO:0046755", "GO:0046761",
            "GO:0046760", "GO:0039702",
            "GO:0046765", "GO:0046762"]
uniprot_IDs = ["A0A0K2RVI7_9BETC", "A8R4D4_9BETC",
                "POLG_YEFV1", "POLG_DEN1W",
                "Q6W352_CVEN9", "D9SV67_CLOC7",
                "A9KSF7_LACP7", "B8I7R6_RUMCH"]

prot_filter_by_GO(GO_Terms, uniprot_IDs)

'''

##  Name:
        expasy.py

##  Version: [1.0]

##  Author:
        <NAME> <<EMAIL>>

##  Created: [2021-10-22]

##  Description:
        Based on GO term list and UniProt ID list, load SwissProt files for each
        ID, search for GO terms, and save information if found.

##  Usage:
        python expasy.py

##  Arguments:
        None

##  Requirements:
        Bio.Entrez, Bio.ExPASy, Bio.SwissProt, Bio.SeqIO

## Example
        prot_filter_by_GO(GO_Terms, uniprot_IDs)

        GO_Terms = ["GO:0046755", "GO:0046761",
                    "GO:0046760", "GO:0039702",
                    "GO:0046765", "GO:0046762"]
        uniprot_IDs = ["A0A0K2RVI7_9BETC", "A8R4D4_9BETC",
                        "POLG_YEFV1", "POLG_DEN1W",
                        "Q6W352_CVEN9", "D9SV67_CLOC7",
                        "A9KSF7_LACP7", "B8I7R6_RUMCH"]
'''

from Bio import Entrez, ExPASy, SwissProt, SeqIO

# Definir email
Entrez.email = "<EMAIL>"

def prot_filter_by_GO(GO_Terms, uniprot_IDs, path=None):
    """Get SwissProt files from uniprot_IDs, search for GO_terms.

    Parameters:
        - GO_Terms (list): list of GO terms to search for
        - uniprot_IDs (list): list of UniProt IDs to get files
        - path (str, optional): path for file to save information (if found),
                            if not given, prot_filter_by_GO.txt file will be created

    Returns:
        - Writes output file if information is found
    """
    # Archivo
    if not path:
        path = 'prot_filter_by_GO.txt'
    file = open(path, 'w')

    # Iteramos primero sobre los ids de UniProt
    for uniprot in uniprot_IDs:
        # Descargamos el archivo de SwissProt, y lo leemos con la libreria correspondiente
        handle = ExPASy.get_sprot_raw(uniprot)
        record = SwissProt.read(handle).__dict__

        # Para cada GO term buscado
        for search_go in GO_Terms:
            # Compararemos con los GO terms del archivo, en cross_references
            for go_term in record['cross_references']:
                if go_term[1] == search_go:
                    # Si lo encontramos, guardamos la información en el archivo
                    file.write(f'ID: {uniprot}\n\n')  # ID

                    # Nombre se obtiene de la descipción
                    nombre = record["description"].split(";")[0]

                    file.write(f'Nombre: {nombre.split("=")[1]}\n\n' # Nombre
                               f'GO: {go_term[1:3]}\n\n' # Término GO y definición
                               f'Organismo: {record["organism"]}\n\n') # Organismo

                    # Para la sublocalización, accesamos a los comentarios
                    file.write('Localización:\n')
                    for comment in record['comments']:
                        if "SUBCELLULAR LOCATION" in comment:
                            file.write(f'{comment}\n')
                    file.write('\n\n')

                    # Para el prosite id, volvemos a iterar sobre cross_reference
                    file.write('PROSITE:\n')
                    for ref in record['cross_references']:
                        if ref[0] == 'PROSITE':
                            file.write(f'{ref[0]}: {ref[1]}\n')
                    file.write('\n\n')

                    # Para el abstract, obtenemos primero las referencias del
                    # primer artículo citado
                    file.write('Abstract:\n')
                    refs = record['references'][0].references
                    # Buscamos PubMed
                    for ref in refs:
                        if ref[0] == 'PubMed':
                            # Buscamos con efetch
                            handle = Entrez.efetch(db="pubmed", id=ref[1], \
                                                   rettype="abstract", \
                                                   retmode="text")
                            abstract = handle.read()
                            handle.close()
                            file.write(abstract)

                    # Separar proteinas
                    file.write('-'*60+'\n\n')

                    break  # Salir del for interno si se encontró

    file.close()
    return


GO_Terms = ["GO:0046755", "GO:0046761",
            "GO:0046760", "GO:0039702",
            "GO:0046765", "GO:0046762"]
uniprot_IDs = ["A0A0K2RVI7_9BETC", "A8R4D4_9BETC",
                "POLG_YEFV1", "POLG_DEN1W",
                "Q6W352_CVEN9", "D9SV67_CLOC7",
                "A9KSF7_LACP7", "B8I7R6_RUMCH"]

prot_filter_by_GO(GO_Terms, uniprot_IDs)

##  Name:         expasy.py  ##  Version: [1.0]  ##  Author:         <NAME> <<EMAIL>>  ##  Created: [2021-10-22]  ##  Description:         Based on GO term list and UniProt ID list, load SwissProt files for each         ID, search for GO terms, and save information if found.  ##  Usage:         python expasy.py  ##  Arguments:         None  ##  Requirements:         Bio.Entrez, Bio.ExPASy, Bio.SwissProt, Bio.SeqIO  ## Example         prot_filter_by_GO(GO_Terms, uniprot_IDs)          GO_Terms = ["GO:0046755", "GO:0046761",                     "GO:0046760", "GO:0039702",                     "GO:0046765", "GO:0046762"]         uniprot_IDs = ["A0A0K2RVI7_9BETC", "A8R4D4_9BETC",                         "POLG_YEFV1", "POLG_DEN1W",                         "Q6W352_CVEN9", "D9SV67_CLOC7",                         "A9KSF7_LACP7", "B8I7R6_RUMCH"] # Definir email Get SwissProt files from uniprot_IDs, search for GO_terms.      Parameters:         - GO_Terms (list): list of GO terms to search for         - uniprot_IDs (list): list of UniProt IDs to get files         - path (str, optional): path for file to save information (if found),                             if not given, prot_filter_by_GO.txt file will be created      Returns:         - Writes output file if information is found # Archivo # Iteramos primero sobre los ids de UniProt # Descargamos el archivo de SwissProt, y lo leemos con la libreria correspondiente # Para cada GO term buscado # Compararemos con los GO terms del archivo, en cross_references # Si lo encontramos, guardamos la información en el archivo # ID # Nombre se obtiene de la descipción # Nombre # Término GO y definición # Organismo # Para la sublocalización, accesamos a los comentarios # Para el prosite id, volvemos a iterar sobre cross_reference # Para el abstract, obtenemos primero las referencias del # primer artículo citado # Buscamos PubMed # Buscamos con efetch # Separar proteinas # Salir del for interno si se encontró