예제 #1
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)}]')
예제 #2
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
예제 #3
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
예제 #4
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)
예제 #5
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
예제 #6
0
    def _linha_2_dominio(self, linha):
        """
        Converte a linha do arquivo de donimio.csv em um objto do tipo dominio

        :param linha: Linha do arquivo de problema nome, problema, default, probabilidade
        :type linha: str
        :return: retorna o objeto do dominio
        :rtype: Dominio
        """
        tipo = EnumTipoVariaveis.VARIAVEL
        linha = linha.strip()
        if len(linha.split(";")) < 2:
            self.log(tipo=EnumLogStatus.ERRO_FATAL,
                     texto=f"Dominio {linha} esta com erro.")

        if linha[0] == "#":
            tipo = EnumTipoVariaveis.CONSTANTE
            linha = linha.replace("#", "")

        args = linha.split(";")
        nome = args[0].strip()
        default = None
        niveis = None
        probabilidade = None
        equacao = None

        if '=' in linha:
            tipo = EnumTipoVariaveis.CONDICIONAL
            if len(args) > 2:
                self.log(
                    tipo=EnumLogStatus.WARN,
                    texto=
                    f"Para variavel tipo condicional, são usados somentes dois parametros, nome [{args[0]}] e equacao [{args[1]}]."
                )
            equacao = args[1].strip()
            equacao = equacao.replace("=", "").strip()
        else:
            niveis, probabilidade = self._str_2_niveis(args[1].strip())

            if len(args) > 2:
                default = InOut.ajusta_entrada(args[2].strip().replace(
                    "'", "").replace('"', ''))
                if default == "":
                    self.log(
                        tipo=EnumLogStatus.WARN,
                        texto=
                        f'O valor default, não existe, com isso o default será [{niveis[0]}]'
                    )
                    default = niveis[0]
                else:
                    if default in niveis:
                        pass
                    else:
                        self.log(
                            tipo=EnumLogStatus.WARN,
                            texto=
                            f'O valor default [{default}], não existe no domínio, com isso o default será [{niveis[0]}]'
                        )
                        default = niveis[0]
            if len(args) > 3:
                probabilidade = args[3].strip()
                if probabilidade == "":
                    probabilidade = None
                else:
                    probabilidade = probabilidade.replace("[", "").replace(
                        "]", "").replace(" ", "").split(",")
                    for ii in range(len(probabilidade)):
                        probabilidade[ii] = InOut.ajusta_entrada(
                            probabilidade[ii])
            if len(niveis) != len(probabilidade):
                self.log(
                    tipo=EnumLogStatus.ERRO_FATAL,
                    texto=
                    f"Quantidade de níveis [{len(niveis)}] é diferente da quantidade de probabilidades [{len(probabilidade)}]."
                )

        return Dominio(nome, niveis, probabilidade, default, equacao, tipo)