예제 #1
0
    def find_model_for(self, sentence, number_of_flips,
                       probability_of_random_walk):
        model = Model()
        cnf_sentence = CNFTransformer().transform(sentence)
        clauses = CNFClauseGatherer().collect(cnf_sentence)

        symbols = SymbolsCollector().collect_symbols(sentence)
        # model <- a random assignment of true/false to the symbols in clauses
        for symbol in symbols:
            model = model.extend(symbol, randbool())

        # for i = 1 to max_flips do
        for i in range(number_of_flips):
            # if model satisfies clauses then return model
            if self._all_clauses_satisfied(clauses, model):
                return model

            # clause <- a randomly selected clause from clauses that is false in model
            symbols_list = list(
                self._get_symbols_of_randomly_selected_false_clause(
                    clauses, model))
            # with probability p flip the value in model of a randomly selected symbol from clause
            if random.random() >= probability_of_random_walk:
                symbol = select_randomly_from_list(symbols_list)
            # else flip whichever symbol in clause maximizes the number of satisfied clauses
            else:
                symbol = self._get_symbol_whose_flip_maximises_satisfied_clauses(
                    clauses, model, symbols_list)

            model.flip(symbol)

        return None
예제 #2
0
    def find_model_for(self, sentence, number_of_flips, probability_of_random_walk):
        model = Model()
        cnf_sentence = CNFTransformer().transform(sentence)
        clauses = CNFClauseGatherer().collect(cnf_sentence)

        symbols = SymbolsCollector().collect_symbols(sentence)
        # model <- a random assignment of true/false to the symbols in clauses
        for symbol in symbols:
            model = model.extend(symbol, randbool())

        # for i = 1 to max_flips do
        for i in range(number_of_flips):
            # if model satisfies clauses then return model
            if self._all_clauses_satisfied(clauses, model):
                return model

            # clause <- a randomly selected clause from clauses that is false in model
            symbols_list = list(self._get_symbols_of_randomly_selected_false_clause(clauses, model))
            # with probability p flip the value in model of a randomly selected symbol from clause
            if random.random() >= probability_of_random_walk:
                symbol = select_randomly_from_list(symbols_list)
            # else flip whichever symbol in clause maximizes the number of satisfied clauses
            else:
                symbol = self._get_symbol_whose_flip_maximises_satisfied_clauses(clauses, model, symbols_list)

            model.flip(symbol)

        return None