예제 #1
0
def geraArquivoTesteTreino(diret, arquivo, seed):
    conteudo = []
    semConteudo = []  # arquivo de pdbs sem ki
    arquivoParaLer = leCsv(
        diret +
        arquivo)  # le arquivo com os pdbs a serem processados como proteinas
    tamLista = len(arquivoParaLer)
    tamTreino = int(tamLista * 0.7) + 1  # pega 70% para treino
    random.seed(seed)
    lista_aleatoria = random.sample(range(0, tamLista), tamTreino)
    #lista_aleatoria = numpy.random.seed()(range(0,tamLista), tamTreino,100)
    listaTreino = []
    listaTeste = []
    x = 0
    QtGui.QApplication.processEvents()  # para não travar usar antes de loops
    for prot in arquivoParaLer:
        if x in lista_aleatoria:
            listaTreino.append(prot)
        else:
            listaTeste.append(prot)
        x += 1  # acresce posição
    textoTreino = ', '.join(listaTreino)
    textoTeste = ', '.join(listaTeste)
    grava(textoTreino, diret + "pdbsProteinaTreino.txt")
    grava(textoTeste, diret + "pdbsProteinaTeste.txt")
예제 #2
0
 def outliers(self): 
      
     percent = self.horizontalSlider_percent.value()/100 # corta o que esta acima de 70% do desvio/10
     self.concatenaArquivos()
     diret = "./outputFiles/"
     arq = open(diret+"juntos.csv", 'r')
     reader = csv.reader(arq)
     allRows = [row for row in reader]
     arrEstru = []
     arrVal = []
     for x in allRows:
         if not x[0] == "PDB": # elimina linhas de cabecalho
             arrVal.append(float(x[2])) # cria lista com valores experimentais
             arrEstru.append(x[0]) # cria lista com estruturas
     elements = np.array(arrVal)
     mean = np.mean(elements, axis=0)
     listaOutliers = []
     ind = 0
     for x in arrVal:
         dif = np.abs(x-mean)
         if abs(dif/mean)>percent: # verifica se nao esta na faixa
             listaOutliers.append(arrEstru[ind].upper())
         ind = ind+1
     texto = str(listaOutliers)
     texto = texto.replace("]", '')
     texto = texto.replace("[", '')
     grava(texto.split("'"), diret+"outliers.txt")
     arq.close()
     apagaArquivo(diret+"juntos.csv")
     self.limpaArquivoProteinas()
예제 #3
0
  def limpaArquivoProteinas(self):
      diret1 = "./outputFiles/"
      diret2 = "./inputFiles/"
      proteinas = leCsv(diret2+"pdbsProteina.txt")
      outliers = leCsv(diret1+"outliers.txt")
      listProt = []
      listOutliers = []
      listNovoProt = []
      tamInicial = (len(proteinas))
      #gravaConfig("quantidadeInicialProteinas", str(tamInicial).strip())
      
      for x in proteinas:
          listProt.append(x.strip())
      for x in outliers:
          listOutliers.append(x.strip())
          
      for x in listProt:
          if not(x in listOutliers):
              listNovoProt.append(x+",".strip())
 
      tam = len(listNovoProt)
      if tamInicial-tam < 1:
          QtGui.QMessageBox.information(self, "Message", "There are no outliers"+"\n"+"\n"+"Try to reducing the percentual value in the slider.")
          pass
      elif tam <20:
          QtGui.QMessageBox.information(self, "Message", "After this operation, the number of structures will be very small (only "+str(tam)+" structures)."+"\n"+"Is not possible exclude outliers!"+"\n"+"\n"+"Try increasing the percentage on the slider,")
          pass
      else:
          listNovoProt[tam-1] = listNovoProt[tam-1].replace(",","") # retira ultima virgula
          
          distancia  = pegaConfig("distanciaAtual").strip()
          txtOut = str(outliers).replace("'", "")
          txtOut = txtOut.replace("[", "")
          txtOut = txtOut.replace("]", "")
          txtOut = txtOut.lower()
          tracos = "-"*90
          tamOut = tamInicial-tam
          texto = "This "+str(tamOut)+" structures will be excluded:"+"\n" +tracos+"\n" + txtOut
          texto = texto+"\n"+tracos
          texto = texto+"\n" +"\n"+"These outliers are considering only experiments with distances < "+distancia+u'\u212b'
          texto = texto +"\n"+"\n" + "Do you want to proceed?"
          reply = QtGui.QMessageBox.question(self, "List of Outliers",texto,QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
          if reply == QtGui.QMessageBox.Yes:
              self.toolButton_iniciar.setEnabled(False)
              self.horizontalSlider_percent.setEnabled(False)
              limpaArquivosOutlier()
              limpaPastasSaidaOutlier()
              
              grava(listNovoProt, diret2+"pdbsProteina.txt") 
              gravaConfig("outlier", "yes")
              gravaConfig ("quantidadeProteinas",str(tam) )
              self.label_inicial.setText(pegaConfig('quantidadeInicialProteinas').strip())
              self.label_final.setText(pegaConfig('quantidadeProteinas').strip())
              QtGui.QMessageBox.information(self, "Important !!!", "Operation completed"+"\n"+"\n"+'You must redo "Make File"  and "Regression" again!')
             
              
          else:
              pass
예제 #4
0
def scale_data():
    """Function to scale explanatory variable data"""

    # Import libraries
    from sklearn import preprocessing
    import numpy as np

    # Read first line
    diretorio = "./adjustmentFunctions/"
    try:
        f = open(diretorio + "prep_data.csv", "r")
        first_line = f.readline()
        #print("\nExplanatory and response variables: ",end="")
    except IOError:
        mensagem = "\nI can't find prep_data.csv file! Finishing execution!!!"
        arquivoSai = "./logs/error" + str(datetime.now())
        grava(mensagem, arquivoSai)
        sys.exit("see error in TABA/logs folder")

    f.close()

    # Read data
    fo1 = np.genfromtxt(diretorio + "prep_data.csv",
                        delimiter=",",
                        skip_header=1)
    # Get number of columns and rows
    # caso não tenha ligante ativo dara erro
    try:
        cols = len(fo1[1, :])
        rows = len(fo1[1:, 0])
    except IndexError:
        mensagem = "There is some compatibility problem in the selected structures." + "\n" + "Probably the Type of Affinity does not correspond to the others datas. Try to generate a new experiment with a correct Type of Affinity"
        arquivoSai = "./logs/error" + str(datetime.now())
        grava(mensagem, arquivoSai)
        sys.exit("see error in TABA/logs folder")

    # Explanatory variable data
    X = fo1[:, :cols - 1]
    # Response variable data
    y = fo1[:, cols - 1]

    # Scale it with unit-variance scaling and mean centering
    X_scaled = preprocessing.scale(X)
    # Open scaled_data.csv
    diretorio = "./adjustmentFunctions/"
    fo2 = open(diretorio + "scaled_data.csv", "w")
    # Write new csv file
    fo2.write(first_line)  # Write headers

    # Looping through numerical data
    for i in range(0, rows +
                   1):  # ----> soma 1 para pegar última linha (09/111/2018)
        line_aux = ""
        for j in range(cols - 1):
            line_aux += "," + str(X_scaled[i, j])
        fo2.write(line_aux[1:] + "," + str(y[i]) + "\n")
    fo2.close()
예제 #5
0
    def salvaModeloOk(self):
        diret = "./models/"
        prefix = "_model"
        nomeComplementar = ''
        self.noe = ''
        arquivo = self.arquivo.strip()
        distancia = self.dist
        base0 = self.base.strip()
        base = base0.replace("Todos", "All")
        coeficiente = self.coefStr.strip()
        equacao = self.formula.strip()
        colunas = str(int(self.col) + 1)
        valorCoeficiente = str(self.melhorCoeficiente)
        melhorArquivo = self.melhorArquivo
        nomeInterno = arquivo + "_" + coeficiente + "_col" + colunas + "_" + melhorArquivo
        mensagem = "Guive a name for this model!"
        nome, ok = QtGui.QInputDialog.getText(self, 'Additional Name to Model',
                                              mensagem)
        nomeExistente = (self.verificaRepetido(nome))
        if nomeExistente:
            QtGui.QMessageBox.warning(
                self, 'Attention !!',
                "This model has already been saved with the name: " +
                nomeExistente.replace(".txt", ""), QtGui.QMessageBox.Ok)
            self.pushButton_adiciona.setEnabled(False)
            pass
        if ok:
            if nome == "":
                nome = "Taba"
            nomeComplementar = (str(nome.strip()))
            caixaTexto = self.plainTextEdit_modelo.toPlainText().replace(
                "\n", "nn")  # para recuperar corretamente depois
            caixaTexto = caixaTexto.replace(
                ", ", "vv")  # para recuperar corretamente depois
            caixaTexto = caixaTexto.replace(chr(945),
                                            "a")  # troca alpha poar a
            caixaTexto = caixaTexto.replace(
                chr(550), "hng")  # troca hngmgstrons poar hng
            textoCoeficientesCalculados = self.pegaCoeficientesCalculados()
            texto = "<nomeInterno>," + nomeInterno + "\n" + "<melhorArquivo>," + melhorArquivo + "\n" + "<distancia>," + distancia + "\n" + "<colunas>," + colunas + "\n" + "<arquivo>," + arquivo + "\n" + "<base>," + base + "\n" + "<coeficiente>," + coeficiente + "\n" + "<valorCoeficiente>," + textoCoeficientesCalculados + "\n" + "<equacao>," + equacao + "\n" + "<tuned>," + str(
                self.tuned) + "\n" + "<modelo>,", caixaTexto

            arqs = arquivosNaPastaModels()
            numero = self.verificaUltimoModelo(arqs)
            numero = str(numero + 1)
            self.nomeModelo = nomeComplementar + prefix + numero
            arquivoSai = diret + self.nomeModelo + ".txt"
            grava(texto, arquivoSai)
            self.label_nomeModelo.setText(self.nomeModelo + " saved")
            self.carregaModelos()
            self.pushButton_deleta.setEnabled(False)
            self.pushButton_adiciona.setEnabled(False)
            self.salvaDadosModelo(self.nomeModelo)
        else:
            pass
예제 #6
0
def geraArquivoComTermoDeEnergiaExperimento(arquivosParaLerUsu, distancia,
                                            tipo, tipoMedia, ligante):
    """Funcao para calcular o termo de energia"""
    cabecalho = "liganteAtivo" + "," + "arquivo" + "," + "CC" + "," + "CN" + "," + "CO" + "," + "CS" + "," + "CP" + "," + "CF" + "," + "CBr" + "," + "CCl" + "," + "CI" + "," + "CAt" + "," + "NN" + "," + "NO" + "," + "NS" + "," + "NP" + "," + "NF" + "," + "NBr" + "," + "NCl" + "," + "NI" + "," + "NAt" + "," + "OO" + "," + "OS" + "," + "OP" + "," + "OF" + "," + "OBr" + "," + "OCl" + "," + "OI" + "," + "OAt" + "," + "SS" + "," + "SP" + "," + "SF" + "," + "SBr" + "," + "SCl" + "," + "SI" + "," + "SAt" + "," + "Log(Ki)" + "\n"

    textoKiTodos = cabecalho
    #atomos = ['CC','CN','CO','CS','CP','CF','CBr','CCl','CI','CAt','NN','NO','NS','NP','NF','NBr','NCl','NI','NAt','OO','OS','OP','OF','OBr','OCl','OI','OAt','SS','SP','SF','SBr','SCl','SI','SAt']
    conj = "TRE"
    diret = "./outputFiles/"
    fileNameTodos = diret + "medDist_" + str(distancia) + "_" + conj + ".csv"
    foTodos = leCsvPulaLinha(fileNameTodos)
    fileNamePorPDB = diret + "medDistPdb_" + str(
        distancia) + "_" + tipo.upper() + ".csv"
    try:
        foPdb = open(fileNamePorPDB, 'r')
    except IOError:
        print("\n O arquivo " + fileNamePorPDB + " nao foi encontrado")
        exit()
    linha = ''
    first_line = foPdb.readline()  # pula primeira linha
    for i in foPdb:
        listaDistMediaPdb = i.split(",")
        ind = 1
        linha = listaDistMediaPdb[0] + ","
        for x in foTodos:
            mediaPdb = float(listaDistMediaPdb[ind])
            mediaTodos = float(x)
            val = (mediaTodos - mediaPdb)**2  # conferir
            valStr = str(val)
            linha = linha + valStr + ","
            ind = ind + 1
        arquivo = listaDistMediaPdb[0]
        liganteAtivo, logKiBDB, logKiPDBbind, logKiBMOAD, logKiTodos = calculaKi(
            arquivo.lower() + ".csv")
        existeLigante = verificaLigange(arquivo.lower(), ligante)
        if (logKiTodos != 0) or (existeLigante):
            textoKiTodos = textoKiTodos + liganteAtivo + "," + linha + str(
                logKiTodos) + "\n"
    diret = "./outputFiles/"
    strDist = str(distancia)
    #    ATENCAO NAO PODE GERAR LINHA ANTES E APOS O TEXTO
    # retirei Ki do nome em 29/04/2017
    arqSaida = diret + 'saidaTodos' + strDist + '_TE_' + "Usu" + '.csv'
    grava(textoKiTodos, arqSaida)
    existeLigante = verificaLigange(arquivo.lower(), ligante)
    if not existeLigante:
        diret = "nok"  # para informar que nao existe o ligante
    return diret, arqSaida
예제 #7
0
def generate_LOO_files(csv_in, n):
    """Function to generate LOO files for cross-validated r2"""

    #csv_in = scaled_data.csv
    my_list = []
    # Try to open csv_in
    try:
        fo1 = open(csv_in, "r")
        csv1 = csv.reader(fo1)
    except IOError:
        mensagem = "\nI can't find" + csv + " file! Finishing execution!(1)"
        arquivoSai = "./logs/error" + str(datetime.now())
        grava(mensagem, arquivoSai)
        sys.exit("see error in TABA/logs folder")

    # Get first line
    for line in csv1:
        first_line = line
        break
    # Get data
    for line in csv1:
        my_list.append(line)
    fo1.close()

    for i in range(len(my_list)):
        # Write LOO files
        # Fix the number of characters
        diretorio = "./adjustmentFunctions/"
        my_str_3_char = str(i)
        if len(my_str_3_char) < 4:
            my_str_lig = str((3 - len(my_str_3_char)) * "0") + my_str_3_char
            my_str = my_str_lig  # We must have three columns
        else:
            my_str = my_str_3_char
        fo1 = open(diretorio + "loo_file_" + my_str + ".csv", "w")
        aux0 = clean_line(str(first_line))
        fo1.write(aux0 + "\n")
        for j in range(len(my_list)):
            aux1 = clean_line(str(my_list[j]))
            fo1.write(aux1 + "\n")

            if i != j:
                aux1 = clean_line(str(my_list[j]))
                fo1.write(aux1 + "\n")

        fo1.close()
예제 #8
0
 def criaAtalhoOk(self):
     if pegaConfigTaba("atalho").strip() == "yes":
         desktop = get_desktop_path()
         dirAtual = os.getcwd() + "/"
         dirBase = os.path.dirname(
             os.path.dirname(dirAtual))  # pega o diretorio acima do Taba
         programa = "./Taba"
         fonte = "python3 taba.py"
         icone = "img/beagle3.png"
         arquivoAtalho = desktop + "/Taba.desktop"
         if existeArquivo(dirAtual + "taba.py"):
             textoScript = "#! /bin/bash" + "\n" + "cd " + dirAtual + "\n" + fonte
         else:
             textoScript = "#! /bin/bash" + "\n" + "cd " + dirAtual + "\n" + programa
         if existeArquivo(arquivoAtalho) == False:
             reply = QtGui.QMessageBox.question(
                 self, "Create a desktop shortcut",
                 "Do you want to create a shortcut on the desktop?" + "\n" +
                 "If you do not want to see this message again, uncheck 'Create a shortcut on the desktop' at the bottom of this window",
                 QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
                 QtGui.QMessageBox.No)
             if reply == QtGui.QMessageBox.Yes:
                 if desktop.strip() == dirBase.strip(
                 ):  # nao e possivel criar icone quando o taba esta no desktop
                     QtGui.QMessageBox.information(self, "Attention!", "It is not possible to create a shortcut when the Taba folder is on the Desktop."+"\n"+\
                     "Move the Taba folder to another location in the user's folder and check 'Create a shortcut on the desktop' at the bottom of the screen again.")
                     gravaConfigTaba("atalho", "no")
                     pass
                 else:
                     TextoLancador = "[Desktop Entry]" + "\n" + "Name=Taba" + "\n" + "Type=Application" + "\n" + "Exec=sh " + dirAtual + "taba.sh" + "\n" + "Icon=" + dirAtual + icone
                     grava(textoScript, "./taba.sh")
                     grava(TextoLancador, arquivoAtalho)
                     os.chmod(arquivoAtalho, 0o777)  # muda permissao
                     QtGui.QMessageBox.information(
                         self, "Message",
                         "The shortcut to Taba was created on the desktop!")
             else:
                 pass
         else:
             pass
     else:
         pass
예제 #9
0
def geraArquivoProteinaFinal(diret, arquivo, tipo):
    progresso = 0
    conteudo = []
    semConteudo = []  # arquivo de pdbs sem ki
    arquivoParaLer = leCsv(
        diret +
        arquivo)  # le arquivo com os pdbs a serem processados como proteinas
    for prot in arquivoParaLer:
        arquivo = prot.strip()  # nome do arquivo pdb que esta em pdbsProteinas
        arquivo = arquivo.lower() + ".csv"
        #print (arquivo)
        if le(arquivo) == "S":
            conteudo.append(prot)
            conteudo.append(",")
        else:
            semConteudo.append(prot)
            semConteudo.append(",")
    tam = len(conteudo)
    tam2 = len(semConteudo)
    conteudo.pop(tam - 1)  # para retirar a ultima virgula
    grava(conteudo, diret + "pdbsProteinaFinal" + tipo + ".txt")
    if semConteudo:
        semConteudo.pop(tam2 - 1)  # para retirar a ultima virgula
    '''
예제 #10
0
def gravaArqProteina(listaEstruturasFicam):
    # cria novo arquivo proteinas
    textoPdb = ''
    listaEstruturasFicam = sorted(listaEstruturasFicam)
    for i in listaEstruturasFicam:
        textoPdb = textoPdb + i[0] + ","
    # retira ultima virgula
    pos = textoPdb.rfind(',')
    t1 = list(textoPdb)
    t1[pos] = ''
    textoPdb = "".join(t1)
    arqProteina = "./inputFiles/pdbsProteina.txt"
    arqTreino = "./inputFiles/pdbsProteinaTreino.txt"
    arqTeste = "./inputFiles/pdbsProteinaTeste.txt"
    grava(textoPdb, arqProteina)
    #retira estruturas no arquivo treino
    listaTreinoNova = []
    textoTreino = leCsv(arqTreino)
    if len(textoTreino
           ) > 0:  # ve se ja tem os arquivos ou se serao gerados apos preparo
        listaTreino = textoTreino
        for s in listaEstruturasFicam:
            if str(s[0]) in listaTreino:
                listaTreinoNova.append(s[0])

        # retira estrutura arquivo teste
        listaTesteNova = []
        textoTeste = leCsv(arqTeste)
        listaTeste = textoTeste
        for s in listaEstruturasFicam:
            if str(s[0]) in listaTeste:
                listaTesteNova.append(s[0])

        textoTreino = ",".join(listaTreinoNova)
        textoTeste = ",".join(listaTesteNova)
        grava(textoTreino, arqTreino)
        grava(textoTeste, arqTeste)
    """
예제 #11
0
def tuning():
    diret = "./outputFiles/"
    #print("Reading resultadoTreino.csv...")
    fo1 = open(diret + "resultadoTreino.csv", "r")
    # Get data
    primeira_linha = fo1.readline()
    listaLinha = primeira_linha.split(",")
    quantidadeColunas = len(listaLinha)
    fo1.close()

    # Reads CSV file to get predicted and experimental data
    my_csv = np.genfromtxt(diret + 'resultadoTreino.csv',
                           delimiter=",",
                           skip_header=1)

    # Gets each column from CSV file
    colExp = quantidadeColunas - 2  # posicao coluna valor experimental
    colPre = quantidadeColunas - 1  # posicao coluna valor predicted
    y = my_csv[:, colPre]
    x = my_csv[:, colExp]

    #Least-squares polynomial fitting
    z = np.polyfit(x, y, 1)
    #p = np.poly1d(z)

    # Equation y = ax + b
    # z array has the coefficients a = z[0] and b = z[1]
    '''
    print("a = ",z[0])
    print("b = ",z[1])
    print("Best fit polynomial equation: ",p)
    '''
    a = z[0]
    b = z[1]

    #################################
    # Read equation
    fo3 = open(diret + "melhorEquacao.csv", "r")
    for line0 in fo3:
        break

    # Get b
    b0 = ""
    for line0 in fo3:
        for line2 in line0[17:]:
            b0 += str(line2)
        break
    coef1 = pegaPrimeiroCoef(b0)
    b0 = b0.replace(coef1, "")  # retira coeficiente
    b0 = b0.replace("\n", "")
    b0 = "(" + b0 + ")"
    constante = "(" + str(a) + "*" + coef1 + "+" + str(b) + ")"
    melhorEquacaoAjustada = constante + "+" + str(a) + "*" + str(b0)
    melhorEquacaoAjustada = melhorEquacaoAjustada.replace("+-", "-")
    melhorEquacaoAjustada = melhorEquacaoAjustada.replace("\n", "")
    melhorEquacaoAjustada = resolveEquacaoTuning(melhorEquacaoAjustada)
    fo4 = open(diret + "melhorEquacao.csv", "r")
    texto = ""
    for line in fo4:
        line_aux = line
        if "[melhor Equacao]" in line_aux:
            line_aux = "[melhor Equacao]," + melhorEquacaoAjustada + "\n"

        texto = texto + line_aux
    texto = texto + "\n" + "[tuned],yes"
    diretorio = "./outputFiles/"
    grava(texto, diretorio + "melhorEquacao.csv")
    gravaConfig("melhorEquacao", melhorEquacaoAjustada)
    fo3.close()
    fo4.close()
    return True
예제 #12
0
def calcula(
    listaVariaveis, diretorio, arquivo, formula, tipo
):  #calcula usando os termoo de energia e gera arquivo com resultados para comparar
    '''
    utiliza o termo de energia de todos os arquivos Pdb
    '''
    arquivo = arquivo.replace(
        "Tre", tipo
    )  #o arquivo que vem eh o de treino por isto substitui pelo tipo de arquivo
    arq = diretorio + arquivo
    pos = posicaoVariaveis(
        listaVariaveis, diretorio,
        arquivo)  # pega posiccao dos valores das colunas das variaveis
    listaValores = []
    listaResultados = ''
    try:
        fo = open(arq, 'r')
    except IOError:
        sys.exit("\n O arquivo " + arq + " nao foi encontrado")
    try:
        fo.readline()  # para pular primeira linha
        for line in fo:  # percorre arquivo
            linha = line.split(",")
            for x in pos:  # percorre lista de posicao e pega valores no arquivo de teste ou treino
                listaValores.append(linha[x])
            n = 0
            equacao = formula
            for lin2 in listaVariaveis:  #substitui valores na equacao
                equacao = equacao.replace(
                    listaVariaveis[n],
                    listaValores[n])  #substitui variavel pelo valor
                n = n + 1
            #equacao = limpaEquacao(equacao)  # estava desativada pois dava erro
            #print("+++++",equacao)
            valor = resolveEquacao(equacao)
            listaValores = []
            ligante = linha[0].replace("[", "")
            ligante = ligante.replace("]", "")
            pdb = linha[1]
            distancia = retornaDigito(arquivo)
            arqMedia = "medDistPdb_" + distancia + "_" + tipo.upper() + ".csv"
            lin = ""
            for atomo in listaVariaveis:
                media = pegaMediaPdb(pdb, atomo, arqMedia)
                lin = lin + "," + media
            lin.split()
            lin = pdb + "," + ligante + lin
            listaResultados = listaResultados + lin + "," + str(
                valor) + "," + linha[36].replace("\n", "") + "\n"
            #print("====Lista resultados", listaResultados)
    except:
        pass
    fo.close()
    if tipo == "Tes":
        arquivoParaSalvar = "resultadoTeste.csv"
    elif tipo == "Tre":
        arquivoParaSalvar = "resultadoTreino.csv"

    li = 'PDB,Ligand'
    for atomo in listaVariaveis:
        li = li + ',d' + atomo
    cabecalho = li + "," + 'Predicted, Experimental' + "\n"
    texto = cabecalho + listaResultados
    grava(texto, diretorio + arquivoParaSalvar)
    #print("---->listaResultados",listaResultados)
    return listaResultados
예제 #13
0
def chama_calcula(csv_file1, metodo, num_col, cabecalho, diretorio,
                  progressBar):
    texto = ""
    csv1 = csv_file1.replace("./outputFiles/", "")
    csv = csv1.replace(".csv", "")
    # Try to open SFgeral.log
    nomeArquivoParcial = "SF" + "_" + csv + "_" + metodo + "_" + str(
        num_col) + "cols" + ".csv"
    arquivo = diretorio + nomeArquivoParcial
    existe = False
    linhas = numeroLinhas(arquivo)
    try:
        with open(arquivo):
            existe = True
    except:
        existe = False
    if (existe == True) and (
            linhas > 2
    ):  # se já foi gerado o arquivo com mais de 2 linhas não gera novamente
        return True
    else:
        try:
            folGeral = open(arquivo, "w")
        except IOError:
            mensagem = "\nI can't find" + arquivo + " file! Finishing execution!(1)"
            arquivoSai = "./logs/error" + str(datetime.now())
            grava(mensagem, arquivoSai)
            sys.exit("see error in TABA/logs folder")

            # This function will create a new csv file with data restricted to selected columns
        colIn = 2  # comeca em zero
        colFin = 37  # e a coluna do log(ki) não pode mandar arquivos com menos colunas

        # chama funcao conforme a quantidade de colunas

        if num_col == 3:
            texto = gera_equacao3(colIn, colFin, csv_file1, metodo,
                                  progressBar)
        if num_col == 4:
            texto = gera_equacao4(colIn, colFin, csv_file1, metodo,
                                  progressBar)
        if num_col == 5:
            texto = gera_equacao5(colIn, colFin, csv_file1, metodo,
                                  progressBar)
        if num_col == 6:
            texto = gera_equacao6(colIn, colFin, csv_file1, metodo,
                                  progressBar)
        if num_col == 7:
            texto = gera_equacao7(colIn, colFin, csv_file1, metodo,
                                  progressBar)
        if num_col == 8:
            texto = gera_equacao8(colIn, colFin, csv_file1, metodo,
                                  progressBar)
        if num_col == 9:
            texto = gera_equacao9(colIn, colFin, csv_file1, metodo,
                                  progressBar)
        if num_col == 10:
            texto = gera_equacao10(colIn, colFin, csv_file1, metodo,
                                   progressBar)
        if num_col == 11:
            texto = gera_equacao11(colIn, colFin, csv_file1, metodo,
                                   progressBar)

        #rodape = "\n"+"Metodo:"+metodo+" Arquivo:"+csv_file1
        #folGeral.write(cabecalho+texto+rodape)
        folGeral.write(cabecalho + texto)
        folGeral.close()

        return False
예제 #14
0
 def gravaTreinoSet(self, textoTreino, textoTeste, diret):
     grava(textoTreino, diret + "pdbsProteinaTreino.txt")
     grava(textoTeste, diret + "pdbsProteinaTeste.txt")
     gravaConfig("geraSets", "y")
예제 #15
0
    def salvaOk(self):
        diretorio = "./inputFiles/"
        arquivo = "pdbsProteina.txt"
        arquivoSai = diretorio + arquivo
        self.textoConfig = self.plainTextEdit_descricao.toPlainText()
        self.textoConfig = self.textoConfig.strip()
        textoPdbTraining = self.plainTextEdit_pdbs.toPlainText()
        textoPdbTraining = textoPdbTraining.replace(" ", "")
        textoPdbTraining = textoPdbTraining.replace(
            ",,", ",")  # caso tenha esquecido alguma virgula
        textoPdbTraining = textoPdbTraining.upper()
        textoPdbTraining = textoPdbTraining.strip()
        self.plainTextEdit_pdbs.setPlainText(textoPdbTraining)
        if textoPdbTraining.endswith(','):  # retira virgula se apos o texto
            textoPdbTraining = textoPdbTraining[:-1]
            self.plainTextEdit_pdbs.setPlainText(textoPdbTraining)

        textoPdbTest = self.plainTextEdit_pdbsTestSet.toPlainText()
        textoPdbTest = textoPdbTest.replace(" ", "")
        textoPdbTest = textoPdbTest.replace(",,", ",")
        textoPdbTest = textoPdbTest.upper()
        textoPdbTest = textoPdbTest.strip()
        self.plainTextEdit_pdbsTestSet.setPlainText(textoPdbTest)

        if textoPdbTest.endswith(','):  # retira virgula se apos o texto
            textoPdbTest = textoPdbTest[:-1]
            self.plainTextEdit_pdbsTestSet.setPlainText(textoPdbTest)
        if len(textoPdbTest) > 0:  # se conjunto teste existe coloca virgula
            vg = ","
        else:
            vg = ""
        if self.radioButton_trainingTest.isChecked():
            textoPdb = textoPdbTraining + vg + textoPdbTest  #une os dois conjunttos
        else:
            textoPdb = textoPdbTraining
        grava(textoPdb, arquivoSai)

        if self.radioButton_trainingTest.isChecked(
        ):  # o usuário separou os arquivos
            self.gravaTreinoSet(textoPdbTraining, textoPdbTest, diretorio)
        else:
            self.habilitaUmaCaixaPDB()
            self.carregaUmacaixaPDB(
            )  # carrea uma caixa pois os arquvivos teste e treino serão separados depois
        lista = leCsv(arquivoSai)
        self.quantidadeProteinas = len(lista)
        self.salvaConfig()
        self.label_quantia.setText(pegaConfig("quantidadeProteinas").strip())

        # define tipo inibidor
        if self.radioButton_Kd.isChecked():
            self.inibidor = "Kd"
        elif self.radioButton_Ki.isChecked():
            self.inibidor = "Ki"
        elif self.radioButton_IC50.isChecked():
            self.inibidor = "IC50"
        elif self.radioButton_EC50.isChecked():
            self.inibidor = "EC50"
        elif self.radioButton_deltaG.isChecked():
            self.inibidor = "deltaG"
        gravaConfig("tipoAfinidade", self.inibidor.strip())
        #define tipo media
        if self.radioButton_training.isChecked():
            self.media = "training"
        elif self.radioButton_individual.isChecked():
            self.media = "individual"
        gravaConfig("tipoMedia", self.media.strip())
        comentarios = self.plainTextEdit_Comentarios.toPlainText()
        comentarios = comentarios.replace(",", "<vg>")
        gravaConfig("comentarios", comentarios)
        completaArquivoConfig()
        self.toolButton_baixa.setEnabled(True)
        self.desabilitaCampos()
        self.toolButton_saveText.setEnabled(False)
        self.toolButton_ClearText.setEnabled(False)
        self.toolButton_baixa.setEnabled(True)
        self.toolButton_cancela.setEnabled(False)
        self.toolButton_edita.setEnabled(True)
        self.toolButton_refina.setEnabled(False)
        self.toolButton_novo.setEnabled(True)
        self.toolButton_exit.setEnabled(True)
        # para poder desfazer
        self.textoInicalPdb = self.plainTextEdit_pdbs.toPlainText()
        self.textoInicalPdbTestSet = self.plainTextEdit_pdbsTestSet.toPlainText(
        )
        self.textoInicialConfig = self.plainTextEdit_descricao.toPlainText()
        self.textoInicialComentarios = self.plainTextEdit_Comentarios.toPlainText(
        )
        self.plainTextEdit_pdbs.setEnabled(False)
예제 #16
0
 def gravaPdb(self):
     diretorio = "./inputFiles/"
     arq = "pdbsProteinaUsu.txt"
     arquivo = diretorio + arq
     self.textoEstrutura = self.lineEdit_estrutura.text().upper().strip()
     grava(self.textoEstrutura, arquivo)
예제 #17
0
    def melhorEquacao(self, listaArq):
        if self.fineTuning:  #se o fine tuning está marcado nao faz nada"
            return True
        diretorio = "./outputFiles/"
        self.escondeBotoes()
        retorno = 0
        valorPartida = 0
        peloMenor = True  # define se o melhor coeficiente é o menor valor (pvs,pvp,sd, rmse) ou o maior valor (r1,r2,sp)
        # define coeficiente para comparar a melhor equação
        if self.radioButton_r1.isChecked():
            self.coeficiente = "r1"
            peloMenor = False
        if self.radioButton_r2.isChecked():
            self.coeficiente = "r2"
            peloMenor = False
        if self.radioButton_sp.isChecked():
            self.coeficiente = "sp"
            peloMenor = False
        if self.radioButton_pvs.isChecked():
            self.coeficiente = "pvs"
            peloMenor = True
        if self.radioButton_pvp.isChecked():
            self.coeficiente = "pvp"
            peloMenor = True
        if self.radioButton_sd.isChecked():
            self.coeficiente = "sd"
            peloMenor = True
        if self.radioButton_rmse.isChecked():
            self.coeficiente = "rmse"
            peloMenor = True
        if peloMenor:  # se procura o menor valor
            retorno = 9999999
            valorPartida = 9999999  # para verificar se houve retorno de algum valor
        for arq in listaArq:
            QtGui.QApplication.processEvents()  # para não travar
            coef, pv2, melhorEq = melhor(arq, self.coeficiente, peloMenor,
                                         self.dist)
            if peloMenor:
                if coef < float(retorno):
                    retorno = coef
                    self.melhorEquacao = melhorEq
                    melhorArquivo = arq
                    pv2Melhor = pv2

            else:
                if coef > float(retorno):
                    retorno = coef
                    self.melhorEquacao = melhorEq
                    melhorArquivo = arq
                    pv2Melhor = pv2

        if retorno == valorPartida:
            mensagem1 = "There is no information for your selection."
            mensagem2 = "Some times, linear regression not generate data for the chosen experiment configuration: Experiments with a number of variables greater than 6, where the number of structures is small, may not generate linear regression results."
            mensagem3 = "Try others configurations for this experiment!"
            mensagem = mensagem1 + "\n" + "\n" + mensagem2 + "\n" + "\n" + mensagem3
            QtGui.QMessageBox.information(self, "Attention!", mensagem)
            return False
        else:
            if self.coeficiente == "sp":
                self.coefStr = "Spearman"
            elif self.coeficiente == "r1":
                self.coefStr = "R"
            elif self.coeficiente == "r2":
                self.coefStr = "R2"
            elif self.coeficiente == "pvs":
                self.coefStr = "p-value Spearman"
            elif self.coeficiente == "pvp":
                self.coefStr = "p-value Pearson"
            elif self.coeficiente == "sd":
                self.coefStr = "Standard Deviation"
            elif self.coeficiente == "rmse":
                self.coefStr = "RMSE"

            self.melhor = self.melhorEquacao
            self.melhorArquivo = (melhorArquivo.replace("./outputFiles/", ""))
            coef = ("Best " + self.coefStr)
            self.melhorCoeficiente = str(retorno)
            texto = "[melhor Coeficiente(" + self.coefStr + ")]" + "," + str(
                retorno
            ) + "\n" + "[melhor Equacao]" + "," + self.melhorEquacao + "\n" + "[melhor Arquivo]" + "," + self.melhorArquivo
            grava(texto, diretorio + "melhorEquacao.csv")
        self.mostraBotoes()
        self.salvaConfig()
        return True
def mediaDistanciaTodosPdb(arquivosParaLer,distancia,conjunto, progressBar):
    # conjunto -> qual o conjunto que e para fazer a distancia media
    """
    calcula a media da distancia entre os atomos que satisfazem uma distancia.
    o paramentro dataSet diz qual dataset sera utilizado para calcular a distancia:
    podera usar somente o arquivo treino ou podera calcular individualmente nos arquivos de treino teste e experimento do usuario
    """

    tam=int(34)
    conta = np.zeros(tam,dtype = int)
    soma = np.zeros(tam,dtype = float)
    cont = 0
    progresso = 0
    quantidadeArquivos = len(arquivosParaLer)
    var = 100/quantidadeArquivos
    QtGui.QApplication.processEvents() # para não travar
    for prot in arquivosParaLer:
        progresso = progresso+var
        progressBar.setValue(progresso) 
        cont = cont +1 #quantidade arquivos processados

        diretorio = "./pdbs/"
        arquivo = prot.strip() # nome do arquivo pdb que est'em pdbsProteinas
        arquivo = arquivo.lower()
        protArq=diretorio+arquivo+"_soAtom.pdb" # coloca a terminacao para ler o arquivo so de proteinas que foram separados
        ligArq=diretorio+arquivo+"_soHetatm.pdb" # coloca a terminacao para ler o arquivo so de ligantes que foram separados
        #parAtm = ['CC','CN','CO','CS','CP','CF','CBr','CCl','CI','CAt','NN','NO','NS','NP','NF','NBr','NCl','NI','NAt','OO','OS','OP','OF','OBr','OCl','OI','OAt','SS','SP','SF','SBr','SCl','SI','SAt'] 
        # Call read_PDB_return_coor_and_lines()
        x1,y1,z1,l1 = read_PDB_return_coord_and_lines(protArq)
        x2,y2,z2,l2 = read_PDB_return_coord_and_lines(ligArq)
   
        #print ("x1----------------------------->",x1,y1,z1,l1,x2,y2)
        # Get the length of the arrays
        n1 = len(x1)
        n2 = len(x2)
        QtGui.QApplication.processEvents() # para não travar
        for i in range(n1): # proteinas  
            QtGui.QApplication.processEvents() # para não travar          
            for j in range(n2): # ligantes
                d =  np.sqrt( ((x1[i] - x2[j] )**2) + ((y1[i] - y2[j])**2) + ((z1[i] - z2[j])**2))
                if d <= distancia:

#---------- CC CN  CO  CS  CP  CF  CBR CCL CI  CAT  

                    if (l1[i][12:14]).strip() == "C" and (l2[j][12:14]).strip()  == "C":
                        conta[0] += 1
                        soma[0] = soma[0]+d                   
                    elif (l1[i][12:14]).strip() == "C" and (l2[j][12:14]).strip() == "N":
                        conta[1] += 1
                        soma[1] = soma[1]+d                                 
                    elif (l1[i][12:14]).strip() == "C" and (l2[j][12:14]).strip() == "O":
                        conta[2] += 1
                        soma[2] = soma[2]+d                     
                    elif (l1[i][12:14]).strip() == "C" and (l2[j][12:14]).strip() == "S":
                        conta[3] += 1
                        soma[3] = soma[3]+d 
                    elif (l1[i][12:14]).strip() == "C" and (l2[j][12:14]).strip() == "P":
                        conta[4] += 1
                        soma[4] = soma[4]+d
                    elif (l1[i][12:14]).strip() == "C" and (l2[j][12:14]).strip() == "F": 
                        conta[5] += 1
                        soma[5] = soma[5]+d 
                    elif (l1[i][12:14]).strip() == "C" and (l2[j][12:14]).strip() == "Br":
                        conta[6] += 1
                        soma[6] = soma[6]+d  
                    elif (l1[i][12:14]).strip() == "C" and (l2[j][12:14]).strip() == "Cl":
                        conta[7] += 1
                        soma[7] = soma[7]+d                      
                    elif (l1[i][12:14]).strip() == "C" and (l2[j][12:14]).strip() == "I":                    
                        conta[8] += 1
                        soma[8] = soma[8]+d  
                    elif (l1[i][12:14]).strip() == "C" and (l2[j][12:14]).strip() == "At":
                        conta[9] += 1
                        soma[9] = soma[9]+d                  
                    #---------- NN  NO  NS  NP  NF  NBR NCL NI  NAT
                    elif (l1[i][12:14]).strip() == "N" and (l2[j][12:14]).strip() == "N":  
                        conta[10] += 1
                        soma[10] = soma[10]+d 
                    elif (l1[i][12:14]).strip() == "N" and (l2[j][12:14]).strip() == "O":
                        conta[11] += 1
                        soma[11] = soma[11]+d
                    elif (l1[i][12:14]).strip() == "N" and (l2[j][12:14]).strip() == "S":
                        conta[12] += 1
                        soma[12] = soma[12]+d
                    elif (l1[i][12:14]).strip() == "N" and (l2[j][12:14]).strip() == "P":
                        conta[13] += 1
                        soma[13] = soma[13]+d            
                    elif (l1[i][12:14]).strip() == "N" and (l2[j][12:14]).strip() == "F":
                        conta[14] += 1
                        soma[14] = soma[14]+d 
                    elif (l1[i][12:14]).strip() == "N" and (l2[j][12:14]).strip() == "Br":
                        conta[15] += 1
                        soma[15] = soma[15]+d 
                    elif (l1[i][12:14]).strip() == "N" and (l2[j][12:14]).strip() == "Cl":
                        conta[16] += 1
                        soma[16] = soma[16]+d
                    elif (l1[i][12:14]).strip() == "N" and (l2[j][12:14]).strip() == "I":
                        conta[17] += 1
                        soma[17] = soma[17]+d 
                    elif (l1[i][12:14]).strip() == "N" and (l2[j][12:14]).strip() == "At":
                        conta[18] += 1
                        soma[181] = soma[18]+d 
                    #-------- OO  OS  OP  OF  OBR OCL OI  OAT 
                    elif (l1[i][12:14]).strip() == "O" and (l2[j][12:14]).strip() == "O":  
                        conta[19] += 1
                        soma[19] = soma[19]+d 
                    elif (l1[i][12:14]).strip() == "O" and (l2[j][12:14]).strip() == "S":
                        conta[20] += 1
                        soma[20] = soma[20]+d 
                    elif (l1[i][12:14]).strip() == "O" and (l2[j][12:14]).strip() == "P":
                        conta[21] += 1
                        soma[21] = soma[21]+d            
                    elif (l1[i][12:14]).strip() == "O" and (l2[j][12:14]).strip() == "F":
                        conta[22] += 1
                        soma[22] = soma[22]+d        
                    elif (l1[i][12:14]).strip() == "O" and (l2[j][12:14]).strip() == "Br":
                        conta[23] += 1
                        soma[23] = soma[23]+d 
                    elif (l1[i][12:14]).strip() == "O" and (l2[j][12:14]).strip() == "Cl":
                        conta[24] += 1
                        soma[24] = soma[24]+d                                         
                    elif (l1[i][12:14]).strip() == "O" and (l2[j][12:14]).strip() == "I":
                        conta[25] += 1
                        soma[25] = soma[25]+d 
                    elif (l1[i][12:14]).strip() == "O" and (l2[j][12:14]).strip() == "At":
                        conta[26] += 1
                        soma[26] = soma[26]+d                                          
                    #-------- SS  SP  SF  SBR SCL SI  SAT
                    elif (l1[i][12:14]).strip() == "S" and (l2[j][12:14]).strip() == "S":  
                        conta[27] += 1
                        soma[27] = soma[27]+d 
                    elif (l1[i][12:14]).strip() == "S" and (l2[j][12:14]).strip() == "P" :
                        conta[28] += 1
                        soma[28] = soma[28]+d               
                    elif (l1[i][12:14]).strip() == "S" and (l2[j][12:14]).strip() == "F" :
                        conta[29] += 1
                        soma[29] = soma[29]+d 
                    elif (l1[i][12:14]).strip() == "S" and (l2[j][12:14]).strip() == "Br":
                        conta[30] += 1
                        soma[30] = soma[30]+d 
                    elif (l1[i][12:14]).strip() == "S" and (l2[j][12:14]).strip() == "Cl":
                        conta[31] += 1
                        soma[31] = soma[31]+d     
                    elif (l1[i][12:14]).strip() == "S" and (l2[j][12:14]).strip() == "I":
                        conta[32] += 1
                        soma[32] = soma[32]+d 
                    elif (l1[i][12:14]).strip() == "S" and (l2[j][12:14]).strip() == "At":
                        conta[33] += 1
                        soma[33] = soma[33]+d                                                                                                               
    #calcula media de cada interacao com os dados gerados acima
    texto = ''
    for a in range(34):  
        if conta[a]>0:    # verifica se existe media 
            med = soma[a]/conta[a] #vetor com as medias 
        else:
            med = 0
        texto =  texto+str(med)+","
    texto = texto[:-1]
    diret = "./outputFiles/"
    strDist = str(distancia)   
    conj = conjunto.upper()
    arquivoSai = diret+'medDist_'+strDist+'_'+conj+'.csv'
    atm =  "CC,CN,CO,CS,CP,CF,CBr,CCl,CI,CAt,NN,NO,NS,NP,NF,NBr,NCl,NI,NAt,OO,OS,OP,OF,OBr,OCl,OI,OAt,SS,SP,SF,SBr,SCl,SI,SAt"
    texto = atm+"\n"+texto
    grava(texto, arquivoSai)
예제 #19
0
def inter_mol_term(distancia, tipo, tipoMedia):
    """Funcao para calcular o termo de energia"""
    cabecalho = "liganteAtivo" + "," + "arquivo" + "," + "CC" + "," + "CN" + "," + "CO" + "," + "CS" + "," + "CP" + "," + "CF" + "," + "CBr" + "," + "CCl" + "," + "CI" + "," + "CAt" + "," + "NN" + "," + "NO" + "," + "NS" + "," + "NP" + "," + "NF" + "," + "NBr" + "," + "NCl" + "," + "NI" + "," + "NAt" + "," + "OO" + "," + "OS" + "," + "OP" + "," + "OF" + "," + "OBr" + "," + "OCl" + "," + "OI" + "," + "OAt" + "," + "SS" + "," + "SP" + "," + "SF" + "," + "SBr" + "," + "SCl" + "," + "SI" + "," + "SAt" + "," + "Log(Ki)" + "\n"
    textoKiBDB = cabecalho
    textoKiPDBbind = cabecalho
    textoKiBMOAD = cabecalho
    textoKiTodos = cabecalho
    #atomos = ['CC','CN','CO','CS','CP','CF','CBr','CCl','CI','CAt','NN','NO','NS','NP','NF','NBr','NCl','NI','NAt','OO','OS','OP','OF','OBr','OCl','OI','OAt','SS','SP','SF','SBr','SCl','SI','SAt']

    if tipoMedia == "TRE":  # vai considera somente o conjunto treino para calcular a media
        conj = "TRE"
    else:
        conj = tipo.upper()
    diret = "./outputFiles/"
    fileNameTodos = diret + "medDist_" + str(distancia) + "_" + conj + ".csv"
    foTodos = leCsvPulaLinha(fileNameTodos)
    fileNamePorPDB = diret + "medDistPdb_" + str(
        distancia) + "_" + tipo.upper() + ".csv"
    try:
        foPdb = open(fileNamePorPDB, 'r')
    except IOError:
        print("\n O arquivo " + fileNamePorPDB + " nao foi encontrado")
        exit()
    linha = ''
    first_line = foPdb.readline()  # pula primeira linha
    for i in foPdb:
        list = i.split(",")
        ind = 1
        linha = list[0] + ","
        for x in foTodos:
            mediaPdb = float(list[ind])
            mediaTodos = float(x)
            val = (mediaTodos - mediaPdb)**2  # conferir
            valStr = str(val)
            linha = linha + valStr + ","
            ind = ind + 1
        arquivo = list[0]
        liganteAtivo, logKiBDB, logKiPDBbind, logKiBMOAD, logKiTodos = calculaKi(
            arquivo.lower() + ".csv")
        if logKiBDB != 0:
            textoKiBDB = textoKiBDB + liganteAtivo + "," + linha + str(
                logKiBDB
            ) + "\n"  # so cria linha se logki for difeerente de zero
        if logKiPDBbind != 0:
            textoKiPDBbind = textoKiPDBbind + liganteAtivo + "," + linha + str(
                logKiPDBbind) + "\n"
        if logKiBMOAD != 0:
            textoKiBMOAD = textoKiBMOAD + liganteAtivo + "," + linha + str(
                logKiBMOAD) + "\n"
        if logKiTodos != 0:
            textoKiTodos = textoKiTodos + liganteAtivo + "," + linha + str(
                logKiTodos) + "\n"
    diret = "./outputFiles/"
    strDist = str(distancia)
    #    ATENCAO NAO PODE GERAR LINHA ANTES E APOS O TEXTO
    # retirei Ki do nome em 29/04/2017
    grava(textoKiBDB, diret + 'saidaBDB' + strDist + '_TE_' + tipo + '.csv')
    grava(textoKiPDBbind,
          diret + 'saidaPDBbind' + strDist + '_TE_' + tipo + '.csv')
    grava(textoKiBMOAD,
          diret + 'saidaBMOAD' + strDist + '_TE_' + tipo + '.csv')
    grava(textoKiTodos,
          diret + 'saidaTodos' + strDist + '_TE_' + tipo + '.csv')