示例#1
0
    def test_python_data_input_model_strict(self):
        start_model = Model()
        start_model.add_file(
            options.DIRECTORY +
            "algorithms/voting_mechanisms/pref_profile_pure_model.mzn")
        start_inst = Instance(self.gecode, start_model)
        start_inst["n_vote_templates"] = len([5, 7, 4, 3, 3, 2])
        start_inst["templateCardinalities"] = [5, 7, 4, 3, 3, 2]
        start_inst["n_options"] = 4
        start_inst["prefTemplates"] = [
            [1, 3, 4, 2],
            [2, 4, 1, 3],
            [1, 4, 3, 2],
            [3, 4, 2, 1],
            [4, 3, 1, 2],
            [4, 3, 2, 1],
        ]
        condorcet_runner = CondorcetRunner(start_model, self.gecode,
                                           self.variables_of_interest,
                                           AGENTS_KEY, AGENTS_PREFERS_KEY,
                                           False)
        condorcet_runner.inst = start_inst
        sol = condorcet_runner.run_basic()

        # We should see: A, B, C, D
        self.assertEqual(4, sol["control"], "D should be Condorcet winner")
        self.assertEqual(2, len(condorcet_runner.all_solutions),
                         "We should have seen two solutions in the process.")
        actual_control_values = [
            sol["control"] for sol in condorcet_runner.all_solutions
        ]
        expected_control_values = [1, 4]
        self.assertListEqual(actual_control_values, expected_control_values,
                             "Should be that stream of solutions")
示例#2
0
    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length).decode('utf-8')
        body = json.loads(body)
        # print(body)

        # Load n-Queens model from file
        model = Model("../../Modelo Minizinc/PlantaEnergia.mzn")

        #Create data file
        writeInstace(body)

        #add data file
        model.add_file("Datos.dzn")

        # Find the MiniZinc solver configuration for Gecode
        gecode = Solver.lookup("coin-bc")

        # Create an Instance of the n-Queens model for Gecode
        instance = Instance(gecode, model)

        #Execute minizinc
        result = instance.solve()

        # Output the array q
        if result.solution is None:
            responseData = {'satisfactible': False}
        else:
            # Respuesta
            responseData = {
                'satisfactible': True,
                "N": result["PN"],
                "H": result["PH"],
                "T": result["PT"],
                "Objective": result["objective"]
            }

        print(responseData)

        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Content-Type', 'application/json')
        self.end_headers()
        response = BytesIO()

        jsonData = json.dumps(responseData)
        binaryData = jsonData.encode()
        response.write(binaryData)
        self.wfile.write(response.getvalue())
示例#3
0
def minizincSolverNew(file, model):
    games = Model(model)
    games.add_file(file)
    gecode = Solver.lookup('gecode')
    instance = Instance(gecode, games)
    result = instance.solve()
    token = None
    play = None
    total_fun = None
    sat = result.status
    time = result.statistics['time'].total_seconds()
    if result.status.has_solution():
        token = result['token']
        play = result['play']
        total_fun = re.search(r'\d+', str(result.solution)).group()
    return [sat, token, play, total_fun, time]
示例#4
0
    def runtest(self):
        # Check solution
        solution: Dict[str, Any] = self.result["solution"]
        model = Model(self.base_dir / self.result["model"])
        model["mzn_ignore_symmetry_breaking_constraints"] = True
        model["mzn_ignore_redundant_constraints"] = True
        if "data_file" in self.result and len(self.result["data_file"]) > 0:
            model.add_file(self.base_dir / self.result["data_file"])
        status = Status[self.result["status"]]
        assert check_solution(model, solution, status,
                              self.checker), "Incorrect solution"

        # Record that the problem is satisfiable for use in check_statuses
        self.user_properties.append(("sat", (self.key, True)))

        # Record objective for use in check_statuses
        if "objective" in solution:
            self.user_properties.append(
                ("objective", (self.key, solution["objective"])))
示例#5
0
    def solve(self,
              brick_layout: BrickLayout,
              verbose=True,
              intermediate_solutions=False,
              timeout=None,
              recompute_graph=False):
        if verbose:
            print(f"start solving by {self.solver_type} ...")
        start_time = time.time()
        model = Model()
        model.add_file(self.model_file)
        instance = Instance(self.solver, model)

        # add data to the solver
        instance = self.add_data_to_model(brick_layout,
                                          instance,
                                          recompute_graph=recompute_graph)

        result = instance.solve(intermediate_solutions=intermediate_solutions,
                                timeout=timeout)

        if result.status.has_solution():
            if intermediate_solutions:
                selected_nodes = [
                    1 if selected else 0
                    for selected in result.solution[-1].node
                ]
            else:
                selected_nodes = [
                    1 if selected else 0 for selected in result['node']
                ]
        else:
            selected_nodes = np.zeros(brick_layout.node_feature.shape[0])
            print("No solutions are found")

        if verbose:
            print(f"solve finished in {time.time() - start_time}")
        brick_layout.predict = selected_nodes
        return brick_layout, time.time() - start_time
示例#6
0
def main():
    file_instances = [
        f for f in listdir(path_dzn)
        if isfile(join(path_dzn, f)) and f.endswith(".dzn")
    ]
    print(sorted(file_instances))
    instance_choose_name = str(
        input("\n\nChoose an instance: [without the extension]\n"))
    instance_choose = instance_choose_name + ".dzn"

    while instance_choose not in file_instances:
        instance_choose_name = str(
            input(
                "\nWrong choice.\nChoose an instance: [without the extension]\n"
            ))  #"08x08"
        instance_choose = instance_choose_name + ".dzn"

    user_rotation = str(
        input("\n\nDo yo want to use rotation: [Y/N]\n")).upper()
    while user_rotation not in ["Y", "N"]:
        user_rotation = str(
            input("\nWrong choice.\nDo yo want to use rotation: [Y/N]\n")
        ).upper()

    print("Building the Model...")
    gecode = Solver.lookup("gecode")

    model = Model()
    if user_rotation == "Y":
        model.add_file("CP/OptimizationProjectRotation.mzn")
        path_solution_choosen = path_solution_rot
        user_rotation = True
    else:
        model.add_file("CP/OptimizationProject.mzn")
        path_solution_choosen = path_solution
        user_rotation = False

    model.add_file(path_dzn + instance_choose)

    instance = Instance(gecode, model)

    print("Solving...")
    all_sol = False
    counter_solutions = 10
    if all_sol:
        result = instance.solve(nr_solutions=counter_solutions)
        print("Stats")
        print(result.statistics)
        print_solution(result, user_rotation=user_rotation)

    else:
        result = instance.solve(all_solutions=False)
        write_solution(path_solution_choosen, instance_choose_name,
                       str(result.solution))
        print_solution(result, 1, user_rotation=user_rotation)
        print("Stats")
        print(result.statistics)
def main():
    file_instances = sorted([
        f for f in listdir(path_dzn)
        if isfile(join(path_dzn, f)) and f.endswith(".dzn")
    ])
    user_rotation_str = str(
        input("\n\nDo yo want to use rotation: [Y/N]\n")).upper()
    while user_rotation_str not in ["Y", "N"]:
        user_rotation_str = str(
            input("\nWrong choice.\nDo yo want to use rotation: [Y/N]\n")
        ).upper()

    print("Building the Model...")
    gecode = Solver.lookup("gecode")

    count_iter = 0
    solv_times = []
    while (count_iter < len(file_instances)):
        model = Model()
        if user_rotation_str == "Y":
            model.add_file("CP/OptimizationProjectRotation.mzn")
            path_solution_choosen = path_solution_rot
            user_rotation = True
        else:
            model.add_file("CP/OptimizationProject.mzn")
            path_solution_choosen = path_solution
            user_rotation = False

        instance_choose = file_instances[count_iter]
        model.add_file(path_dzn + instance_choose)

        instance = Instance(gecode, model)

        print("Solving instance: {}".format(instance_choose))
        result = instance.solve(all_solutions=False)
        #write_solution(path_solution_choosen, instance_choose.split('.')[0], str(result.solution))
        #print_solution(result, 1, user_rotation=user_rotation)
        print("Solving Time")
        print(result.solution)
        print(result.statistics)
        print(result.statistics['solveTime'])
        solv_times.append(result.statistics['solveTime'].total_seconds())
        count_iter += 1

    fig = plt.figure()
    plt.plot(range(8, len(solv_times) + 8), solv_times, 'bo')
    plt.yscale('log')
    # beautify the x-labels
    plt.xlabel("Instances")
    plt.ylabel("Solve Time (sec)")

    plt.show()
from minizinc import Instance, Model, Result, Solver, Status
gecode = Solver.lookup("gecode")
m = Model("mwe_pydata.mzn")

m["test_param"] = 3

# this did not work
#m["test_vals"] = [1, 4, 4]
#m["test_len"] = 3;
# this did not work either
m.add_file("mwe_pydata.dzn")

inst = Instance(gecode, m)
result = inst.solve()
print(result["x"])
示例#9
0
from minizinc import Instance, Model, Solver
import numpy as np
from numpy import savetxt
import sys
import json

chuffed = Solver.lookup("chuffed")

generator = Model("./scripts/minizinc/Dominosa_final.mzn")
generator.add_file("./scripts/minizinc/Dominosa.dzn")
instance = Instance(chuffed, generator)
# Find and print all possible solutions
r = instance.solve(all_solutions=True)

#m = r['temp']
#m = np.array(m,dtype=int)
#n = m.shape[0] - 1
list_sol = []
for i in range(0, len(r)):
    list_sol.append(np.array(r[i, 'temp']).flatten())

dictionary_all_solutions = {}
for index, solution in enumerate(list_sol):
    cont = 0
    dictonary_cards = {}
    for i in range(1, int((len(solution) / 2) + 1)):
        count = 0
        first = -1
        for x in range(0, len(solution)):
            if (solution[x] == i):
                if (count == 0):
示例#10
0
    def getKillerSudoku(self, base, hints, seed):
        return KillerSudokuBoard(base, self.board,hints,seed)

if __name__ == "__main__":
    SOLVABLE = False
    outputfile = "f-output4h35"#int(sys.argv[1])
    base = 4 #int(sys.argv[2])
    assert base > 0
    hints = 35
    # TODO: Seed not producing reliable results
    seed = 54 
    print("Starting Minizinc Module")

    gecode = Solver.lookup("gecode")
    model = Model()
    model.add_file(os.path.dirname(__file__) +"\\SudokuGeneration.mzn")
    model.output_type = Board
    instance = Instance(gecode, model)

    instance["Base"] = base

    result = instance.solve(verbose=True, debug_output=Path("./debug_output.txt"))
    kill_b:KillerSudokuBoard = result.solution.getKillerSudoku(base, hints, seed)

    print("Sudoku Generation Complete")
    print("Starting Cage Generation")
    if SOLVABLE:
        print("Valid")
        kill_b.gen_cages_valid(base*base*base)
    else: #Note: Sudokus obtained by the invalid process MAY be solvable, it's just not likely.
        print("Invalid")
示例#11
0
import sys

sys.path.append("../")

from OptunaMinizinc.Tuning import Tuning
from minizinc import Model, Solver, Instance

tuning = Tuning()

cbc = Solver.lookup("osicbc")
model = Model()
model.add_file("./models/mapping.mzn")

instance = Instance(cbc, model)
instance.add_file("./models/full2x2_mp3.dzn")

tuning.load_instance(instance)
tuning.load_param_from_pcs_file("../pcsFiles/osicbc.json")

params = tuning.start(n_trials=50)
print(params)