Esempio n. 1
0
def test_para_salvar_arquivos_em_folders_inexistentes():

    errors = []

    folder_auxiliar = 'mocks2'
    file_name = 'arquivo_teste.txt'
    path_folder_salvar = InOut().ajuste_path('\\'.join(
        [paths_files.path_mocks(), folder_auxiliar]))
    path_arquivo_salvar = InOut().ajuste_path('\\'.join(
        [paths_files.path_mocks(), folder_auxiliar, file_name]))
    conteudo = 'teste_conteudo_linha_1\nteste_conteudo_linha_2'
    if not txt.salvar(path_arquivo_salvar, conteudo):
        errors.append('erro ao salvar em caminho de pasta inexistente')
    if not txt.ler(path_arquivo_salvar) == [
            'teste_conteudo_linha_1\n', 'teste_conteudo_linha_2'
    ]:
        errors.append(
            'erro ao comparar conteudo salvo com o lido no arquivo salvo')

    try:
        shutil.rmtree(path_folder_salvar)
    except Exception as ex:
        errors.append(f'erro ao remover arquivo gerado [{ex}]')

    assert not errors, 'ocorrencia de erros:\n{}'.format('\n'.join(errors))
Esempio n. 2
0
    def _carregar_informacao(self, modules: list):
        """
        Ler o arquivo carrega toda informação e adiciona na variavel _configuracao
        """

        linha = ''
        try:
            contexto = TXT().ler(
                str(self._contexto.get_atributo(
                    EnumAtributo.PATH_CONFIGURACAO)))
            for module in modules:
                self._contexto.set_atributo('module',
                                            [InOut.ajusta_entrada(module)])

            for linha in contexto:
                linha = linha.replace("\n", "").strip()
                if (len(linha) > 0) and (not linha[0] == "*"):
                    sp = linha.split()
                    chave = sp[0].strip()
                    valor = sp[1].strip()
                    if len(sp) > 2:
                        for ii in range(2, len(sp)):
                            sp[ii] = sp[ii].strip()
                            if len(sp[ii]) > 0:
                                valor = f'{valor} {sp[ii]}'

                    self._contexto.set_atributo(chave,
                                                [InOut.ajusta_entrada(valor)])
        except Exception as ex:
            self.log(tipo=EnumLogStatus.ERRO_FATAL,
                     texto=f"Erro ao carregar arquivos. Linha [{linha}]",
                     info_ex=f'ex[{str(ex)}]')
Esempio n. 3
0
    def get_uniecos(self, uniecos):
        uniecos_executar = {}
        if type(uniecos) is list:
            for unieco in uniecos:
                uni_separado = unieco.split("#")
                unieco_path = InOut.ajuste_path(uni_separado[0])
                unieco_prob = 1 / len(uniecos)
                if len(uni_separado) > 1:
                    unieco_path = uni_separado[0]
                    unieco_prob = uni_separado[1]

                unieco_file_name = (unieco_path.split(InOut().barra())[-1]).split('.')[0]
                uniecos_executar[unieco_file_name] = {'unieco_path': unieco_path,
                                                      'unieco_file_name': unieco_file_name,
                                                      'unieco_prob': unieco_prob}
        else:
            uni_separado = uniecos.split("#")
            unieco_path = InOut.ajuste_path(uni_separado[0])
            unieco_prob = 1
            if len(uni_separado) > 1:
                unieco_path = uni_separado[0]
                unieco_prob = uni_separado[1]

            unieco_file_name = (unieco_path.split(InOut().barra())[-1]).split('.')[0]
            uniecos_executar[unieco_file_name] = {'unieco_path': unieco_path,
                                                  'unieco_file_name': unieco_file_name,
                                                  'unieco_prob': unieco_prob}

        return uniecos_executar
Esempio n. 4
0
    def _aplicando(self, variavel):
        if self._funcao.upper() == EnumValues.SIGMOIDE.name.upper():
            try:
                a = InOut.ajusta_entrada(variavel["A"])
                b = InOut.ajusta_entrada(variavel["B"])
                c = InOut.ajusta_entrada(variavel["C"])
                f_tempo = {}
                for tt in self._tempos:
                    funcao = self._BHP_Min
                    try:
                        vars = np.array([a, b, c, tt], dtype=np.float)
                        #[('divide', 'ignore'), ('invalid', 'ignore'), ('over', 'ignore'), ('under', 'ignore')]
                        with np.errstate(over='ignore',
                                         invalid='ignore',
                                         divide='ignore',
                                         under='ignore'):
                            expoente = vars[2] + vars[1] * (
                                vars[3] / 22.762) + vars[0] * (vars[3] /
                                                               22.762)**2
                            funcao = np.round(
                                self._BHP_Min +
                                (self._BHP_Max - self._BHP_Min) /
                                (1 + np.exp(expoente)), 0)
                    except Exception as ex:
                        self.log(tipo=EnumLogStatus.WARN,
                                 texto='Erro na criação da equacao',
                                 info_ex=str(ex))
                        funcao = self._BHP_Min
                    f_tempo[tt] = funcao

            except Exception as ex:
                self.log(tipo=EnumLogStatus.WARN,
                         texto='Erro no método _aplicando',
                         info_ex=str(ex))
            return f_tempo
Esempio n. 5
0
    def csv(self, contexto: Contexto, nome=None):
        """
        Método interno para salvar CSV com dados da otimização

        """

        self._contexto = contexto

        conteudo_solucao_csv = self._gerar_conteudo_solucoes_csv()

        try:

            iteracao_max = max(
                self._contexto.get_atributo(EnumAtributo.SOLUCOES).solucoes)

            path_csv = InOut().ajuste_path('/'.join([
                self._contexto.get_atributo(EnumAtributo.PATH_PROJETO),
                f'/{self._contexto.get_atributo(EnumAtributo.PATH_RESULTADO)}.csv'
            ])).format(str(iteracao_max))
            if nome is not None:
                path_csv = InOut().ajuste_path('/'.join([
                    self._contexto.get_atributo(EnumAtributo.PATH_PROJETO),
                    f'/{self._contexto.get_atributo(EnumAtributo.PATH_RESULTADO)}.csv'
                ])).format(str(nome))

            if not TXT().salvar(path_csv, conteudo_solucao_csv):
                self.log(tipo=EnumLogStatus.WARN,
                         texto=f'Erro ao salvar CSV da otimização.')

        except Exception as ex:
            self.log(tipo=EnumLogStatus.WARN,
                     texto=f'Erro ao salvar CSV da otimização.',
                     info_ex=str(ex))
Esempio n. 6
0
    def obejto(self, contexto: Contexto, nome=None):
        """
        Método interno para salvar contexto com os dados da otimização

        """

        try:
            self._contexto = contexto
            iteracao_max = max(
                self._contexto.get_atributo(EnumAtributo.SOLUCOES).solucoes)
            path_objeto = InOut().ajuste_path('/'.join([
                self._contexto.get_atributo(EnumAtributo.PATH_PROJETO),
                f'/{self._contexto.get_atributo(EnumAtributo.PATH_RESULTADO)}.rst'
            ])).format(str(iteracao_max))
            if nome is not None:
                path_objeto = InOut().ajuste_path('/'.join([
                    self._contexto.get_atributo(EnumAtributo.PATH_PROJETO),
                    f'/{self._contexto.get_atributo(EnumAtributo.PATH_RESULTADO)}.rst'
                ])).format(str(nome))
            with open(path_objeto, 'wb') as file:
                pickle.dump(self._contexto, file)
        except Exception as ex:
            self.log(tipo=EnumLogStatus.WARN,
                     texto=f'Erro ao exportar objeto.',
                     info_ex=str(ex))
Esempio n. 7
0
    def run(self, param_path: str, contexto: Contexto):

        if not contexto.tem_atributo(
                EnumAtributo.AVALIACAO_MERO_TEMPOS_G2_PATH):
            return

        self.log(texto=f'Executando o {__name__}')

        tempos_path = InOut.ajuste_path(
            contexto.get_atributo(EnumAtributo.AVALIACAO_MERO_TEMPOS_G2_PATH))
        tempos_path = InOut.ajuste_path(
            f'{contexto.get_atributo(EnumAtributo.PATH_PROJETO)}/{tempos_path}'
        )
        self._tempos = list(((CSV()).ler(tempos_path, False)).index)
        if len(self._tempos) < 1:
            return

        count = ""
        estrutura = {}
        params = TXT().ler(param_path)

        for key in params:
            try:
                chave = key.split(" ")[0]
                valor = key.split(" ")[1]
                if (chave[0] != "#") and ("@" in chave):
                    try:
                        aux = chave.split("@")
                        local = (aux[1]).upper()
                        variavel = (aux[0]).upper()
                        evento = (aux[2]).upper()

                        if self._has_evento(evento) is None:
                            continue
                        else:
                            if not local in estrutura:
                                estrutura[local] = {}
                            if not evento in estrutura[local]:
                                estrutura[local][evento] = {}
                            estrutura[local][evento][variavel] = valor
                        count += f'{key}'
                    except Exception as ex:
                        count += f'{key}'
                        print(ex)
                else:
                    count += f'{key}'
            except Exception:
                count += f'{key}'

        count += f'***Variaveis de gerenciamento segundo formula {self._funcao}\n'
        for local in estrutura:
            for evento in estrutura[local]:
                f_tempo = self._aplicando(estrutura[local][evento])
                for tempo in f_tempo:
                    count += f'{local}@{evento}@{tempo} {f_tempo[tempo]}\n'

        TXT().salvar(param_path, count)
Esempio n. 8
0
    def _str_2_niveis(self, str_niveis: str) -> tuple:
        """
        Converte as string [ | ] ou { } exemplo [1 | 3] ou {1 2 3} em list [1, 2, 3]
        :param str_niveis: string nos formatos [ | ] ou { } exemplo [1 | 3] ou {1 2 3}
        :type str_niveis: str
        :return: list do problema
        :rtype: list
        """
        niveis = []
        probabilidade = []
        discretizacao = str_niveis

        try:
            if str_niveis.find("[") >= 0:
                str_niveis = str_niveis.replace(",", "|")
            if str_niveis.find("{") >= 0:
                str_niveis = str_niveis.replace(",", " ")

            if str_niveis.find("[") >= 0 and str_niveis.find(
                    "]") > 0 and str_niveis.find("|") > 0:
                discretizacao = discretizacao.replace("[", "")
                discretizacao = discretizacao.replace("]", "")
                discretizacao = discretizacao.strip()
                limite = discretizacao.split("|")

                for rr in range(
                        int(InOut.ajusta_entrada(limite[0].strip())),
                        int(InOut.ajusta_entrada(limite[1].strip())) + 1):
                    niveis.append(InOut.ajusta_entrada(str(rr)))
                    probabilidade.append(0)

            elif str_niveis.find("{") >= 0 and str_niveis.find("}") > 0:
                discretizacao = discretizacao.replace("{", "")
                discretizacao = discretizacao.replace("}", "")
                discretizacao = discretizacao.strip()
                possiveis = discretizacao.split(" ")
                for rr in range(len(possiveis)):
                    niveis.append(
                        InOut.ajusta_entrada(possiveis[rr].strip().replace(
                            "'", "").replace('"', '')))
                    probabilidade.append(0)

            if len(niveis) > 0:
                for ii in range(len(probabilidade)):
                    probabilidade[ii] = 1 / len(probabilidade)
        except Exception as ex:
            niveis = []
            probabilidade = []
            self.log(tipo=EnumLogStatus.ERRO_FATAL,
                     texto=f"Erro para criar problema [{str_niveis}].",
                     info_ex=str(ex))

        return niveis, probabilidade
Esempio n. 9
0
    def _gera_paths_melhores_resultados(self):

        path_melhores_resultados = InOut().ajuste_path('\\'.join([
            self._contexto.get_atributo(EnumAtributo.PATH_PROJETO),
            self._contexto.get_atributo(EnumAtributo.AVALIACAO_PATH_MELHORES),
            '\\'
        ]))

        paths = glob.glob('\\'.join([path_melhores_resultados, '*']))

        paths = [InOut().ajuste_path(path) for path in paths]

        return paths
Esempio n. 10
0
    def run(self, contexto: Contexto, solucao_pdf_atualizada: Solucao,
            n_amostragem):
        """
        Executa a amostragem com o IDLHCn

        :param Contexto contexto: contexto com todas as informações necessárias
        :param Solucao solucao_pdf_atualizada: Solucao com pdf atualizada para utilizacao na amostragem
        """

        self._n_amostragem = n_amostragem

        self._contexto = contexto
        self._solucao_pdf_atualizada = solucao_pdf_atualizada

        path_projeto = self._contexto.get_atributo(EnumAtributo.PATH_PROJETO)

        self._solucoes = self._contexto.get_atributo(EnumAtributo.SOLUCOES)
        ultima_iteracao = max(map(int, self._solucoes.solucoes))
        self._ultimo_id = max(
            map(int, self._solucoes.solucoes[ultima_iteracao]))

        self._iteracao_nova_amostragem = ultima_iteracao + 1

        self._path_hldg = InOut.ajuste_path('\\'.join([
            path_projeto,
            self._contexto.get_atributo(EnumAtributo.PATH_SIMULACAO),
            f'HLDG_{self._iteracao_nova_amostragem}.mero'
        ]))
        self._gera_entrada_hldg()
        self._execucao_hldg()
        self._criar_solucoes_em_contexto()

        return self._contexto
Esempio n. 11
0
    def _criar_solucoes_em_contexto(self):
        conteudo_sorteio_txt = self._carregar_saida_HLDG()

        nomes_variaveis = conteudo_sorteio_txt[0].split('\t')[1:-1]

        lista_serializado = self._solucoes.serializacao()

        for solucao_txt in conteudo_sorteio_txt[1:]:
            nome_solucao_val_vars = solucao_txt.split('\t')
            [iteracao_solucao,
             id_solucao] = nome_solucao_val_vars[0].split('_')

            solucao = Solucao(id=int(id_solucao) + self._ultimo_id,
                              iteracao=int(iteracao_solucao),
                              solucao=self._solucao_pdf_atualizada)

            val_vars = [
                InOut().ajusta_entrada(val_var)
                for val_var in nome_solucao_val_vars[1:-1]
            ]
            for variavel, valor in zip(nomes_variaveis, val_vars):
                solucao.variaveis.get_variavel_by_nome(variavel).valor = valor

            if solucao.variaveis.serializacao() not in lista_serializado:
                self._solucoes.add_in_solucoes(solucao)

        self._contexto.set_atributo(EnumAtributo.SOLUCOES, self._solucoes,
                                    True)
        self._contexto.set_atributo(EnumAtributo.AVALIACAO_ITERACAO_AVALIAR,
                                    [int(iteracao_solucao)], True)
Esempio n. 12
0
    def _avaliacao_gevt(self):
        """

        Le gevt e seta o  self._data_inicial, self._data_final e self._dia_inicio_previsao que serao utilizados
        para calcular lista de dias e dia final de simulacao que
        """
        # disponivel ainda somente para otimização nominal
        gevts_tpls = self._contexto.get_atributo(
            EnumAtributo.AVALIACAO_MERO_GEVTS_TEMPLATES_EXECUTAR)
        for key in gevts_tpls.keys():
            path_gevt = gevts_tpls[key]['gevt_path']
        path_projeto = self._contexto.get_atributo(EnumAtributo.PATH_PROJETO)
        path_completo_gevt = InOut.ajuste_path(f'{path_projeto}/{path_gevt}')

        linhas_gevt = TXT().ler(path_completo_gevt)

        conteudo_gvt = ''

        for linha in linhas_gevt:
            conteudo_gvt += linha

        matches = re.findall(r'\n\*INITIAL_DATE\s*([^\s]+)', conteudo_gvt)
        data_inicial = matches[0]

        matches = re.findall(r'\n\*FINAL_DATE\s*([^\s]+)', conteudo_gvt)
        data_final = matches[0]

        matches = re.findall(r'\n\*TIME_LIST\s*(\w*)', conteudo_gvt)
        dia_inicio_previsao = matches[0]

        self._data_inicial = data_inicial
        self._data_final = data_final
        self._dia_inicio_previsao = int(dia_inicio_previsao)
Esempio n. 13
0
    def _carregar_contexto(self):
        try:
            path_resume = InOut().ajuste_path('\\'.join([
                self._contexto.get_atributo(EnumAtributo.PATH_PROJETO),
                self._contexto.get_atributo(
                    EnumAtributo.INICIALIZACAO_RESUME_PATH)
            ]))
            with open(path_resume, 'rb') as file:
                contexto_resume = pickle.load(file)

            Loggin.set_arquivo_log(self._contexto.arquivo_log)
            contexto_resume.set_arquivo_log(self._contexto.arquivo_log)
            contexto_resume.set_atributo(
                EnumAtributo.PATH_PROJETO,
                self._contexto.get_atributo(EnumAtributo.PATH_PROJETO), True)
            contexto_resume.set_atributo(
                EnumAtributo.PATH_CONFIGURACAO,
                self._contexto.get_atributo(EnumAtributo.PATH_CONFIGURACAO),
                True)
            contexto_resume.set_atributo(
                EnumAtributo.PATH_LOG,
                self._contexto.get_atributo(EnumAtributo.PATH_LOG), True)

            return contexto_resume
        except Exception as ex:
            self.log(tipo=EnumLogStatus.ERRO_FATAL,
                     texto='Erro ao carregar arquivo de resume',
                     info_ex=str(ex))
Esempio n. 14
0
    def run(self, contexto: Contexto):
        """
        Inicia o processo de remocao de arquivos de saida de simulaao

        :param Contexto contexto:
        """

        path_simulacao = InOut().ajuste_path('\\'.join([
            contexto.get_atributo(EnumAtributo.PATH_PROJETO),
            contexto.get_atributo(EnumAtributo.PATH_SIMULACAO), '\\'
        ]))
        try:
            import shutil
            shutil.rmtree(path_simulacao)
            self.log(texto=f'Removendo conteúdo da pasta {path_simulacao}')
        except Exception as ex:
            self.log(tipo=EnumLogStatus.WARN,
                     texto=f"Falha para remover pasta {path_simulacao}",
                     info_ex=str(ex))

        try:
            from pathlib import Path
            path_simulacao_Path = Path(path_simulacao)
            path_simulacao_Path.mkdir()
            self.log(texto=f'Pasta {path_simulacao} criada com sucesso')
        except Exception as ex:
            import time
            time.sleep(10)
            try:
                os.mkdir(path_simulacao)
                self.log(texto=f'Pasta {path_simulacao} criada com sucesso')
            except Exception as ex:
                self.log(tipo=EnumLogStatus.WARN,
                         texto=f"Falha para criar pasta {path_simulacao}",
                         info_ex=str(ex))
Esempio n. 15
0
    def _check_simulando(self):

        simular = self._buffer['simular']
        keys = deepcopy(list(simular.keys()))
        for ii in range(len(keys)):
            prefixo = keys[ii]
            iteracao = simular[prefixo]["iteracao"]
            id = simular[prefixo]["id"]
            path = simular[prefixo]["path"]
            file = InOut.ajuste_path(f'{path}.out')
            if os.path.isfile(file):
                self.log(
                    texto=
                    f'Solucao ({prefixo}) iteracao [{iteracao}] e id [{id}] simulando.'
                )
                self._buffer['simulando'][prefixo] = simular[prefixo]
                del self._buffer['simular'][prefixo]
            else:
                horas_sim_max = self._contexto.get_atributo(
                    EnumAtributo.AVALIACAO_MERO_TEMPO_MAX_SIM)
                if simular[prefixo][
                        "time"] + horas_sim_max * 60 * 60 < time.time():
                    self.log(
                        tipo=EnumLogStatus.ERRO,
                        texto=
                        f'A simulação da solucao  {prefixo}) iteracao [{iteracao}] e id [{id}] excedeu tempo de {horas_sim_max} hora.'
                    )
                    self._buffer['erro'][prefixo] = simular[prefixo]
                    self._solucoes.get_solucao_by_iteracao_id(
                        iteracao=iteracao,
                        id=id).has_erro = f"Excedeu {horas_sim_max}h"
                    del self._buffer['simular'][prefixo]
Esempio n. 16
0
def test_de_copia_de_arquivo_quando_folder_destino_eh_existente():
    path_arquivo_para_copia = paths_files.path_arquivo_exemplo()
    path_arquivo_copiado = '\\'.join([paths_files.path_mocks(), 'arquivo_copiado.txt'])

    path_arquivo_copiado = InOut().ajuste_path(path_arquivo_copiado)

    if not copy.copy_file(path_arquivo_para_copia, path_arquivo_copiado):
        pytest.fail('erro ao copiar arquivo')
    if not InOut().arquivo_existe(path_arquivo_copiado):
        pytest.fail('arquivo copiado nao foi gerado')
    if not TXT().ler(path_arquivo_copiado) == TXT().ler(path_arquivo_para_copia):
        pytest.fail('conteudo arquivo copiado nao eh igual ao original')

    try:
        os.remove(path_arquivo_copiado)
    except Exception as ex:
        pytest.fail(f'Nao foi possivel remover arquivo gerado. Erro :[{ex}]')
Esempio n. 17
0
    def _preparar_arquivos(self):
        path_projeto = self._contexto.get_atributo(EnumAtributo.PATH_PROJETO)
        path_simulacao = self._contexto.get_atributo(
            EnumAtributo.PATH_SIMULACAO)
        gevts_template_executar = self._contexto.get_atributo(
            EnumAtributo.AVALIACAO_MERO_GEVTS_TEMPLATES_EXECUTAR)

        for prefixo in gevts_template_executar.keys():
            path_completo_origem = InOut.ajuste_path(
                f'{path_projeto}/{gevts_template_executar[prefixo]["gevt_path"]}'
            )
            path_completo_destino = InOut.ajuste_path(
                f'{path_projeto}/{path_simulacao}/{gevts_template_executar[prefixo]["gevt_file_name"]}.mero'
            )

            if not Copy.copy_file(path_completo_origem, path_completo_destino):
                self.log(tipo=EnumLogStatus.ERRO_FATAL, texto=f'Erro no GEVT.')
Esempio n. 18
0
    def criar_arquivos(path_file: str) -> bool:
        """
        Criar toda estrutura de arquivo para depois fazer a copia do arquivo.
        :param str path_file: Deve ser o caminho do arquivo, com o nome do arquivo junto.
        :return: Se tudo correu ok
        :rtype: bool
        """

        test_path = ""
        try:
            barra = '/'
            inicio = '/'
            if platform.system().upper() == "WINDOWS":
                barra = '\\'
                inicio = ''

            path_aux = path_file.split(barra)

            for pp in range(len(path_aux) - 1):
                if path_aux[pp] == "":
                    continue
                if test_path == "":
                    test_path = InOut.ajuste_path(f'{inicio}{path_aux[pp]}')
                else:
                    test_path = InOut.ajuste_path(
                        f'{test_path}{barra}{path_aux[pp]}')

                if not os.path.isdir(test_path):
                    Loggin().log(arquivo=__name__,
                                 tipo=EnumLogStatus.WARN,
                                 texto=f'Caminho {test_path} não existe.')
                    os.mkdir(test_path)
                    Loggin().log(
                        arquivo=__name__,
                        tipo=EnumLogStatus.WARN,
                        texto=f'Caminho {test_path} foi criado com sucesso.')

            return True
        except Exception as ex:
            Loggin().log(arquivo=__name__,
                         tipo=EnumLogStatus.ERRO_FATAL,
                         texto=f'Não foi possível diretorios [{test_path}].',
                         info_ex=str(ex))
            return False
Esempio n. 19
0
def test_de_criação_de_folder():
    nome_diretorio_auxiliar1 = 'mocks2'
    nome_diretorio_auxiliar2 = 'mocks3\\'

    path_criacao_folder = '\\'.join([paths_files.path_mocks(), nome_diretorio_auxiliar1, nome_diretorio_auxiliar2])
    path_remocao_folder = '\\'.join([paths_files.path_mocks(), nome_diretorio_auxiliar1])

    path_criacao_folder = InOut().ajuste_path(path_criacao_folder)
    path_remocao_folder = InOut().ajuste_path(path_remocao_folder)

    if not copy.criar_arquivos(path_criacao_folder):
        pytest.fail('Criacao de folder falhou')
    if not os.path.isdir(path_criacao_folder):
        pytest.fail('Folder nao foi criado')

    try:
        shutil.rmtree(path_remocao_folder)
    except Exception as ex:
        pytest.fail(f'Nao foi possivel remover folder criado. Erro :[{ex}]')
Esempio n. 20
0
    def _execucao_hldg(self):
        executavel = InOut().ajuste_path(
            self._contexto.get_atributo(
                EnumAtributo.AVALIACAO_MERO_EXECUTAVEL))
        comando = f'{executavel} hldg -i {self._path_hldg}'

        if Terminal().run(comando):
            self.log(texto='execucao HLDG feita com sucesso')
        else:
            self.log(tipo=EnumLogStatus.ERRO_FATAL, texto='Erro execucao HLDG')
Esempio n. 21
0
    def run(self):
        """
        Metodo responsavel por utilizar avaliadores em arquivos externos python.
        O arquivo deve possuir o metodo getResult(dict_variaveis)
        """

        super(Python, self).run()

        path_python = InOut.ajuste_path('/'.join([
            self._contexto.get_atributo(EnumAtributo.PATH_PROJETO),
            self._contexto.get_atributo(EnumAtributo.AVALIACAO_PYTHON_PATH)
        ]))

        try:
            getResult = load_method(path_python)
        except Exception as ex:
            self.log(
                tipo=EnumLogStatus.ERRO,
                texto=
                f'Erro ao carregar o metodo getResult em {path_python}: [{ex}]'
            )

        iteracoes = self._contexto.get_atributo(
            EnumAtributo.AVALIACAO_ITERACAO_AVALIAR)
        self._solucoes = self._contexto.get_atributo(EnumAtributo.SOLUCOES)

        list_solucoes = self._solucoes.get_solucoes_by_iteracao_para_avaliar(
            iteracoes)

        for it in list_solucoes:
            for id in list_solucoes[it]:
                dict_variaveis = {}
                solucao = self._solucoes.get_solucao_by_iteracao_id(
                    iteracao=it, id=id)
                for nome, valor in solucao.get_variaveis_nome_valor().items():
                    valor_var = valor
                    if valor_var.__class__ is str:
                        valor_var = 0
                    dict_variaveis.update({nome: valor_var})
                try:
                    of = getResult(dict_variaveis)
                except Exception as ex:
                    self.log(
                        tipo=EnumLogStatus.ERRO,
                        texto=
                        f'Erro ao calcular of com o metodo getResult em {path_python}: [{ex}]'
                    )

                self._solucoes.get_solucao_by_iteracao_id(
                    iteracao=it, id=id).of[self._nome_of_mono].valor = of
                self._solucoes.get_solucao_by_iteracao_id(
                    iteracao=it, id=id).set_avaliada()
Esempio n. 22
0
    def _avalia_rankeamento_simulacoes_parciais(self):
        """

        Gera tabela de recall do ranqueamento em relacao ao tempo de simulacao dos n_melhores_estudos
        """
        ultima_iteracao = self._contexto.get_atributo(
            EnumAtributo.AVALIACAO_ITERACAO_AVALIAR)
        solucoes_estudo = self._contexto.get_atributo(
            EnumAtributo.SOLUCOES).solucoes[ultima_iteracao]

        dfs_dates = []

        for key, solucao in solucoes_estudo.items():
            df_economico = solucao.economico['dataframe']
            df_NPV = df_economico[df_economico['OF'] == 'NPV']
            nome_modelo = df_NPV['MODEL'].iloc[0]

            df_date = df_NPV[['DATE', 'VALUE']].T

            datas_disponiveis = df_date.iloc[0, :]
            df_date = df_date.iloc[1:, :]
            df_date.columns = datas_disponiveis
            df_date.index = [nome_modelo]
            dfs_dates.append(copy.deepcopy(df_date))

        df_date_all = pd.concat(dfs_dates, axis=0, sort=True)

        dates = list(df_date_all.columns)
        dates.sort(
            key=lambda x: (x.split('/')[2], x.split('/')[1], x.split('/')[0]))

        df_date_all = df_date_all[dates]

        df_rank = df_date_all.rank().sort_values(by=dates[-1])

        df_date_top = df_rank.iloc[0:self._contexto.get_atributo(EnumAtributo.REDUCAO_RANK_ANALISE), :] <= \
                      self._contexto.get_atributo(EnumAtributo.REDUCAO_RANK_ANALISE)

        df_precisao_por_data = df_date_top.sum(
            axis=0) / self._contexto.get_atributo(
                EnumAtributo.REDUCAO_RANK_ANALISE)

        df_precisao_por_data.index.name = 'DATA POR RECALL'

        path_csv_estudo = InOut.ajuste_path('\\'.join([
            self._contexto.get_atributo(EnumAtributo.PATH_PROJETO),
            self._contexto.get_atributo(EnumAtributo.PATH_RESULTADO)
        ])).format('estudo_recall.csv')

        CSV().salvar(path_csv_estudo, df_precisao_por_data)
Esempio n. 23
0
def test_de_copia_de_arquivo_quando_folder_destino_nao_eh_existente():
    nome_diretorio_auxiliar1 = 'mocks2'
    nome_diretorio_auxiliar2 = 'mocks3\\'

    path_arquivo_para_copia = paths_files.path_arquivo_exemplo()

    path_arquivo_copiado = '\\'.join([paths_files.path_mocks(), nome_diretorio_auxiliar1,
                                      nome_diretorio_auxiliar2, 'arquivo_copiado.txt'])
    path_arquivo_copiado = InOut().ajuste_path(path_arquivo_copiado)

    path_remocao_folder = '\\'.join([paths_files.path_mocks(), nome_diretorio_auxiliar1])
    path_remocao_folder = InOut().ajuste_path(path_remocao_folder)

    if not copy.copy_file(path_arquivo_para_copia, path_arquivo_copiado):
        pytest.fail('Criacao de arquivo copiado falhou')
    if not os.path.isfile(path_arquivo_copiado):
        pytest.fail('Arquivo nao foi copiado')
    if not TXT().ler(path_arquivo_copiado) == TXT().ler(path_arquivo_para_copia):
        pytest.fail('conteudo arquivo copiado nao eh igual ao original')

    try:
        shutil.rmtree(path_remocao_folder)
    except Exception as ex:
        pytest.fail(f'Nao foi possivel remover folder criado. Erro :[{ex}]')
Esempio n. 24
0
    def get_gevts_templates(self, gevts_templates):
        gevts_templantes_executar = {}
        if type(gevts_templates) is list:
            for gevt_template in gevts_templates:
                separacao = gevt_template.split('#')
                gevt_path = InOut.ajuste_path(separacao[0])
                gevt_file_name = (gevt_path.split(InOut.barra())[-1]).split('.')[0]
                if len(separacao) <= 1:
                    self.log(tipo=EnumLogStatus.ERRO_FATAL,
                             texto=f"Precisa ser informado o template para o GEVT [{gevt_template}]")
                template_path = InOut.ajuste_path(separacao[1])
                template_file_name = (template_path.split(InOut.barra())[-1]).split('.')[0]
                template_prob = 1 / len(gevts_templates)
                if len(separacao) > 2:
                    template_prob = separacao[2]

                    gevts_templantes_executar[f'{gevt_file_name}_{template_file_name}'] = {'gevt_path': gevt_path,
                                                                                           'gevt_file_name': gevt_file_name,
                                                                                           'template_path': template_path,
                                                                                           'template_file_name': template_file_name,
                                                                                           'template_prob': template_prob}
        else:
            separacao = gevts_templates.split('#')
            gevt_path = InOut.ajuste_path(separacao[0])
            gevt_file_name = (gevt_path.split(InOut.barra())[-1]).split('.')[0]
            if len(separacao) <= 1:
                self.log(tipo=EnumLogStatus.ERRO_FATAL,
                         texto=f"Precisa ser informado o TPL para o GEVT [{gevts_templates}]")
            template_path = InOut.ajuste_path(separacao[1])
            template_file_name = (template_path.split(InOut.barra())[-1]).split('.')[0]
            template_prob = 1
            if len(separacao) > 2 and int(InOut.ajusta_entrada(separacao[2])) != int(1):
                self.log(tipo=EnumLogStatus.ERRO, texto=f"Não faz sentido probabilidade diferente de 1 quando há somente um template.")

            gevts_templantes_executar[f'{gevt_file_name}_{template_file_name}'] = {'gevt_path': gevt_path,
                                                                                   'gevt_file_name': gevt_file_name,
                                                                                   'template_path': template_path,
                                                                                   'template_file_name': template_file_name,
                                                                                   'template_prob': template_prob}
        return gevts_templantes_executar
Esempio n. 25
0
    def salvar(self,
               path_arquivo: str,
               conteudo: str,
               metodo_gravacao: str = "w") -> bool:
        """
        Método para salvar conteudo de arquivos

        :param str path_arquivo: Caminho do arquivo
        :param str conteudo: Conteudo a ser salvo
        :param str metodo_gravacao: Método de gravação, padrão w
        :return: Se deu erro ou não
        :rtype: bool
        """
        path_arquivo = InOut.ajuste_path(path_arquivo)

        try:
            if not Copy.criar_arquivos(path_arquivo):
                return False
            arq = open(path_arquivo, metodo_gravacao)
            arq.write(conteudo)
            arq.close()
        except FileNotFoundError as ex:
            self.log(tipo=EnumLogStatus.WARN,
                     texto=f'Erro ao salvar arquivo.',
                     info_ex=str(ex))
            return False
        except PermissionError as ex:
            self.log(tipo=EnumLogStatus.WARN,
                     texto=f'Erro ao salvar arquivo.',
                     info_ex=str(ex))
            return False
        except TypeError as ex:
            self.log(tipo=EnumLogStatus.WARN,
                     texto=f'Erro ao salvar arquivo.',
                     info_ex=str(ex))
            return False
        except NameError as ex:
            self.log(tipo=EnumLogStatus.WARN,
                     texto=f'Erro ao salvar arquivo.',
                     info_ex=str(ex))
            return False
        except IOError as ex:
            self.log(tipo=EnumLogStatus.WARN,
                     texto=f'Erro ao salvar arquivo.',
                     info_ex=str(ex))
            return False
        return True
Esempio n. 26
0
    def _check_unipro(self):
        simulado = self._buffer['simulado']
        keys = deepcopy(list(simulado.keys()))
        for ii in range(len(keys)):
            prefixo = keys[ii]
            iteracao = simulado[prefixo]['iteracao']
            id = simulado[prefixo]['id']
            path = simulado[prefixo]['path']
            path_file = InOut.ajuste_path(f'{path}.unipro')

            if os.path.isfile(path_file):
                # se arquivo unipro esta escrito
                tamanho_unipro = 0
                try:
                    tamanho_unipro = os.path.getsize(path_file)
                except Exception as ex:
                    pass

                if tamanho_unipro > 300:
                    self._buffer['unipro'][prefixo] = simulado[prefixo]
                    del self._buffer['simulado'][prefixo]
                    self.log(
                        texto=
                        f'Solucao ({prefixo}) iteracao [{iteracao}] e id [{id}] foi calculado o unipro, com sucesso. '
                    )
                    continue

            horas_sim_max = self._contexto.get_atributo(
                EnumAtributo.AVALIACAO_MERO_TEMPO_MAX_SIM)
            if simulado[prefixo]["time"] + horas_sim_max * 60 * 60 < time.time(
            ):
                self.log(
                    tipo=EnumLogStatus.ERRO,
                    texto=
                    f'A simulação da solucao  {prefixo}) iteracao [{iteracao}] e id [{id}] excedeu tempo de {horas_sim_max} hora.'
                )
                self._buffer['erro'][prefixo] = simulado[prefixo]
                self._solucoes.get_solucao_by_iteracao_id(
                    iteracao=iteracao,
                    id=id).has_erro = f"Excedeu {horas_sim_max}h"
                del self._buffer['simulado'][prefixo]
Esempio n. 27
0
    def _gera_solucoes(self):
        """
        Gera as solucoes e salva na variavel de classe
        """
        self.log(texto="Gerando Soluções")
        self._solucoes = Solucoes()
        nome_variaveis = self._solucao_referencia.variaveis.get_variaveis_by_tipo(
            EnumTipoVariaveis.VARIAVEL)
        amostras = []
        for nome_variavel in nome_variaveis:
            probabilidade = self._solucao_referencia.variaveis.get_variavel_by_nome(
                nome_variavel).dominio.probabilidade
            niveis = self._solucao_referencia.variaveis.get_variavel_by_nome(
                nome_variavel).dominio.niveis

            if round(sum(probabilidade), 3) != round(1, 3):
                self.log(tipo=EnumLogStatus.ERRO_FATAL,
                         texto='Somatorio das probabilidades diferente de 1')
            amostra = self._gera_amostragem_variaveis(probabilidade, niveis,
                                                      self._tamanho_populacao)
            amostras.append(amostra)

        amostras = np.array(amostras).T
        amostras = self._checa_duplicidade(amostras)
        solucoes_df = pd.DataFrame(amostras, columns=nome_variaveis.keys())

        for i in range(solucoes_df.shape[0]):

            self._ultimo_id += 1
            solucao = Solucao(id=int(self._ultimo_id),
                              iteracao=int(self._iteracao),
                              solucao=self._solucao_referencia)

            for variavel, valor in zip(solucoes_df.columns,
                                       solucoes_df.iloc[i, :]):
                solucao.variaveis.get_variavel_by_nome(
                    variavel).valor = InOut.ajusta_entrada(str(valor))

            #Caso a simulacao ja tenha sido simulada, o avaliador sera responsavel por reutilizar o valor ja simulado
            #Caso nao queira solucoes repetidas, deve ser tratado fora da classe de sorteio
            self._solucoes.add_in_solucoes(solucao)
Esempio n. 28
0
def test_para_salvar_arquivos():

    errors = []

    file_name = 'arquivo_teste.txt'
    path_arquivo_salvar = InOut().ajuste_path('\\'.join(
        [paths_files.path_mocks(), file_name]))
    conteudo = 'teste_conteudo_linha_1\nteste_conteudo_linha_2'

    if not txt.salvar(path_arquivo_salvar, conteudo) == True:
        errors.append('erro ao salvar em caminho de pasta existente')
    if not txt.ler(path_arquivo_salvar) == [
            'teste_conteudo_linha_1\n', 'teste_conteudo_linha_2'
    ]:
        errors.append(
            'erro ao comparar conteudo salvo com o lido no arquivo salvo')

    try:
        os.remove(path_arquivo_salvar)
    except Exception as ex:
        errors.append(f'erro ao apagar arquivo gerado [{ex}]')

    assert not errors, 'ocorrencia de erros:\n{}'.format('\n'.join(errors))
Esempio n. 29
0
    def _gera_paths_origem_e_destino(self, solucoes):
        solucoes = solucoes.solucoes

        path_melhores_resultados = InOut().ajuste_path('\\'.join([
            self._contexto.get_atributo(EnumAtributo.PATH_PROJETO),
            self._contexto.get_atributo(EnumAtributo.AVALIACAO_PATH_MELHORES),
            '\\'
        ]))
        path_simulacao = InOut().ajuste_path('\\'.join([
            self._contexto.get_atributo(EnumAtributo.PATH_PROJETO),
            self._contexto.get_atributo(EnumAtributo.PATH_SIMULACAO)
        ]))

        dados_copiar_origem = list()
        dados_copiar_destino = list()
        dados_manter = list()

        paths_dados_manter = list()
        nome_melhores_solucoes = list()
        for it in list(map(int, solucoes)):
            for id in list(map(int, solucoes[it])):
                if solucoes[it][id].of_valida():
                    nome_melhores_solucoes.append(f'_{it}_{id}_')

        for nome_melhor_solucao in nome_melhores_solucoes:
            str_pesquisa_melhor_solucao = InOut.ajuste_path('\\'.join(
                [path_simulacao, '*' + nome_melhor_solucao + '*']))

            str_pesquisa_solucao_existentes = InOut.ajuste_path('\\'.join(
                [path_melhores_resultados, '*' + nome_melhor_solucao + '*']))

            dados_copiar_origem += (glob.glob(str_pesquisa_melhor_solucao))
            dados_manter += (glob.glob(str_pesquisa_solucao_existentes))

        dados_copiar_destino += \
            [InOut.ajuste_path('\\'.join([path_melhores_resultados, os.path.basename(dado_copiar_origem)])) for
             dado_copiar_origem in dados_copiar_origem]

        paths_dados_manter += \
            [InOut.ajuste_path('\\'.join([path_melhores_resultados, os.path.basename(dado_copiar_origem)])) for
             dado_copiar_origem in dados_manter]

        return dados_copiar_origem, dados_copiar_destino, paths_dados_manter
Esempio n. 30
0
    def run(self, contexto: Contexto) -> Contexto:
        """
        Executa a classe
        :param Contexto contexto: Variavel de contexto que conte todas as informações
        :return: A variavel de contexto
        :rtype: Contexto
        """

        self.log(texto=f'Executando o {self._name}')
        self._contexto = contexto
        self._gevts_templates = self._contexto.get_atributo(
            EnumAtributo.AVALIACAO_MERO_GEVTS_TEMPLATES_EXECUTAR)
        self._qualificador = self._contexto.get_atributo(
            EnumAtributo.AVALIACAO_QUALIFICADOR)
        self._solucoes: Solucoes = self._contexto.get_atributo(
            EnumAtributo.SOLUCOES)

        mero_executavel = self._contexto.get_atributo(
            EnumAtributo.AVALIACAO_MERO_EXECUTAVEL)

        iteracoes = self._contexto.get_atributo(
            EnumAtributo.AVALIACAO_ITERACAO_AVALIAR, valor_unico_list=True)
        iteracoes_str = ""
        for ss in iteracoes:
            iteracoes_str = f'{iteracoes_str}_{ss}'

        prefixo = f'{self._qualificador}{iteracoes_str}'

        path_projeto = InOut.ajuste_path(
            str(self._contexto.get_atributo(EnumAtributo.PATH_PROJETO)))
        path_simulacao = InOut.ajuste_path(
            str(self._contexto.get_atributo(EnumAtributo.PATH_SIMULACAO)))
        path_dsgu = InOut.ajuste_path(
            f'{path_projeto}/{path_simulacao}/{prefixo}_dsgu.mero')

        if not self._escrever(iteracoes, path_dsgu):
            self._contexto.set_atributo(EnumAtributo.SOLUCOES,
                                        [self._solucoes], True)
            return self._contexto

        try:
            params = self._contexto.get_atributo(
                EnumAtributo.AVALIACAO_MERO_DS_PARAMS)
            comando = f'{mero_executavel} dsgu -i {path_dsgu} {params}'
            self.log(texto=f'Executando comando {comando}.')
            self.log(texto=f'Abrindo as threads, aguarde ...')
            terminal = Terminal()
            self._thread = threading.Thread(target=terminal.run,
                                            args=(comando, ))
            self._thread.start()
        except Exception as ex:
            self.log(tipo=EnumLogStatus.ERRO,
                     texto=f'Erro executar o comando {comando}',
                     info_ex=str(ex))
            list_solucoes = self._solucoes.get_solucoes_by_iteracao_para_avaliar(
                iteracoes)
            for k_iteracao, v_est in list_solucoes.items():
                for k_id, vv_est in v_est.items():
                    vv_est.has_erro = 'DSGU'
                    self._solucoes.add_in_solucoes(vv_est, True)
            self._thread.join()
            self._thread = None

        self._contexto.set_atributo(EnumAtributo.SOLUCOES, [self._solucoes],
                                    True)
        return self._contexto