Пример #1
0
def gen(instance_data):
    instance = Instance(Solver.lookup('gecode'), Model('gen.mzn'))

    instance['n'] = instance_data['n']
    instance['groups'] = instance_data['groups']
    instance['rowN'] = instance_data['rowN']
    instance['colN'] = instance_data['colN']
    instance['pair'] = instance_data['pairs']

    # results = instance.solve()
    # results = instance.solve(all_solutions=True)
    results = instance.solve(nr_solutions=20)
    res_idx = random.randrange(0, len(results.solution))

    instance_data['rowSum'] = results[res_idx, 'rowSum']
    instance_data['colSum'] = results[res_idx, 'colSum']
    instance_data['results'] = results[res_idx, 'results']
    instance_data['rowSum'] = results[res_idx, 'rowSum']
    instance_data['colSum'] = results[res_idx, 'colSum']
    instance_data['results'] = [
        e.tolist()
        for e in array_split(results[res_idx, 'results'], instance_data['n'])
    ]
    instance_data['results_as_digits'] = [
        e.tolist() for e in array_split(
            [0 if e == "Empty" else 1
             for e in results[res_idx, 'results']], instance_data['n'])
    ]

    return instance_data
def run_on_all_inputs(model_path, output_dir, input_dir=INPUT_DIR):
    if not dir_exists(input_dir, label='input_dir', verbose=True):
        return

    if not output_dir[-1] == '/':
        output_dir += '/'
    os.makedirs(output_dir, exist_ok=True)

    model = Model(model_path)
    gecode = Solver.lookup("gecode")

    input_num = 0
    while not get_input(input_num) is None:
        # Se l'output e' gia' stato calcolato non ricalcolo
        if read_output(input_num, suppress_error=True) == None:
            print("Lavoro su input num %d" % (input_num))
            instance = Instance(gecode, model)
            initialize_instance(instance, input_num)
            result = instance.solve()

            output_fpath = gen_fpath(input_num, output_dir, OUTPUT_PREFIX,
                                     OUTPUT_EXT)

            write_output(result, instance, output_fpath)
        else:
            print("Trovato output per input num %d. Skip" % (input_num))

        input_num += 1
def run_on_all_inputs(model_path, model_type, output_dir):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir, exist_ok=True)
    if not output_dir[-1] == '/':
        output_dir += '/'

    fname_prefix = "output_"
    fname_suffix = ".json"

    model = Model(model_path)
    gecode = Solver.lookup("gecode")

    input_num = 0
    while not get_input(input_num) is None:
        instance = Instance(gecode, model)
        initialize(instance, input_num)
        result = instance.solve()

        output_path  = output_dir + fname_prefix
        output_path += '{:02d}'.format(input_num)
        output_path += fname_suffix

        print("Lavoro su input num %d" %(input_num))
        save_result(result, instance, model_type, output_path)

        input_num += 1
def solve_minizinc(costs_matrix, job_demands, job_durations, num_precedences,
                   predecessors, successors, prec_delays, percent):

    dur_max = max(job_durations)
    no_intervals = no_intervals_day + (dur_max - 1) * 2

    multipleDSP = Model("scripts/{}".format(minizinc_model))
    gecode = Solver.lookup("gecode")
    ins = Instance(gecode, multipleDSP)

    max_demand = int(sum(job_demands) * percent)
    ins["no_intervals"] = no_intervals
    ins["no_devices"] = len(costs_matrix)
    ins["durations"] = job_durations
    ins["demands"] = job_demands
    ins["num_precedences"] = num_precedences
    ins["predecessors"] = predecessors
    ins["successors"] = successors
    ins["prec_delays"] = prec_delays
    ins["max_demand"] = max_demand
    ins["run_costs"] = costs_matrix

    result = ins.solve()

    cp_astarts_temp = result["actual_starts"]

    cp_astarts = [(astart - dur_max + 1) % no_intervals_day
                  for astart in cp_astarts_temp]
    #
    # actual_start = (chosen_index - dur + 1) % no_intervals_day

    return cp_astarts
Пример #5
0
def main():
    f = open("bin/resources/in", "r")
    fout = open("bin/resources/out", "w")

    size = int(f.readline())

    given = []
    for _ in range(size):
        given.append(
            [int(x) if x != 'N' else None for x in f.readline().split()])

    f.close()

    model = Model("src/resources/minizinc/Binairo.mzn")
    chuffed = Solver.lookup("chuffed")
    instance = Instance(chuffed, model)
    instance['size'] = size
    instance['given'] = given

    result = instance.solve()
    if not result:
        print('NO SOLUTION!')
    else:
        solution = result['matrix']
        for line in solution:
            for x in line:
                fout.write(str(x) + " ")
            fout.write("\n")
    fout.close()
Пример #6
0
class InstanceTestCase(unittest.TestCase):
    code = ""
    instance: GenInstance
    solver: Solver

    def setUp(self):
        self.solver = Solver.lookup("gecode")
        self.instance = Instance(self.solver)
        self.instance.add_string(self.code)
Пример #7
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 minizinc(*files, solver=gecode, data={}, all_solutions=False):
    """Solve using minizinc."""
    model = Model(files)
    instance = Instance(solver, model)
    for key, value in data.items():
        if isinstance(value, str):
            instance.add_string(f'{key} = {value};\n')
        else:
            instance[key] = value
    return instance.solve(all_solutions=all_solutions)
Пример #9
0
def cp_solving(vehicle_count, vehicle_capacity, customer_count, customers, fraction=0.1):
    model_vrp = Model("./vrp.mzn")
    # Find the MiniZinc solver configuration for Gecode
    solver = Solver.lookup("chuffed")
    instance = Instance(solver, model_vrp)
    instance["nb_customers_without_depot"] = customer_count-1
    nb_customers_virtual = customer_count-1+vehicle_count+1
    range_customer_virtual = range(1, nb_customers_virtual+1)
    instance["nb_vehicle"] = vehicle_count
    closest, matrix = compute_length_matrix(customers)
    demands = [customers[i].demand for i in range(1, customer_count)]+[0]*(vehicle_count+1)
    instance["demand"] = demands
    instance["capacity_vehicle"] = vehicle_capacity
    recomputed_dist = []
    for i in range(1, customer_count):
        recomputed_dist += [[int(matrix[i, j]) for j in range(1, customer_count)]+[int(matrix[i, 0])]*(vehicle_count+1)]
    for v in range(vehicle_count+1):
        recomputed_dist += [[int(matrix[0, j]) for j in range(1, customer_count)]+[0]*(vehicle_count+1)]
    instance["distance"] = recomputed_dist
    result = instance.solve(timeout=timedelta(seconds=100))
    opt: Status = result.status
    print(result.__dict__)
    objective = result["objective"]
    print("Objective : ", objective)
    print(result["circuit_vrp"])
    iteration = 0
    dict_result = {i+1: result["circuit_vrp"][i] for i in range(nb_customers_virtual)}
    current_objective = objective
    while iteration < 1000:
        with instance.branch() as child:
            subpart_tsp = set(random.sample(range_customer_virtual, int(fraction*len(range_customer_virtual))))
            for i in range_customer_virtual:
                if i not in subpart_tsp:
                    # print("constraint color_graph["+str(i)+"] == "+ str(dict_color[i])+";\n")
                    child.add_string("constraint circuit_vrp["+str(i)+"] == "+ str(dict_result[i])+";\n")
            child.add_string(f"solve minimize(objective);\n")
            res = child.solve(timeout=timedelta(seconds=50))
            print(res.status)
            if res.solution is not None and res["objective"] <= current_objective:
                iteration += 1
                incumbent = res.solution
                current_objective = res["objective"]
                dict_result = {i+1: res["circuit_vrp"][i] for i in range(nb_customers_virtual)}
                #json.dump(dict_color, open('debug_cp.json', "w"))
                print(iteration , " : , ", res["objective"])
                print('IMPROVED : ', iteration)
                print("dict result : ", dict_result)
            else:
                try:
                    print("Not improved ")
                    print(iteration , " :  ", res["objective"])
                except:
                    print(iteration, " failed ")
                # print({i: res["color_graph"][i-1] for i in range_node})
                iteration += 1
Пример #10
0
def test_toy_minizinc():
    model = Model()
    model.add_string('''
    var -2..2: a;
    constraint a < 0;
    solve satisfy;
    ''')
    gecode = Solver.lookup("gecode")
    inst = Instance(gecode, model)
    result = inst.solve(all_solutions=True)
    print([{"a": result[i, "a"]} for i in range(len(result))])
Пример #11
0
def call_minizinc(model_file, n, l, k):
    # The supplied MIP solver doesn't support the "all_solutions"
    # flag, so we must use a CP solver. It's still about 2x faster
    # to use a MIP-style model, though.
    solver = Solver.lookup("chuffed")
    model = Model(model_file)
    instance = Instance(solver, model)
    instance["N"] = n
    instance["L"] = l
    instance["K"] = k
    return instance.solve(all_solutions=True)
Пример #12
0
    def test_assign(self):
        self.instance = Instance(self.solver)
        self.instance.add_string("""
            enum TT;
            var TT: t1;
            """)
        TT = enum.Enum("TT", ["one"])
        self.instance["TT"] = TT
        result = self.instance.solve()

        assert isinstance(result["t1"], TT)
        assert result["t1"] is TT.one
def run_on_input(model_path, input_num, input_dir=INPUT_DIR):
    if not dir_exists(input_dir, label='input_dir', verbose=True):
        return
    # TODO try catch
    model = Model(model_path)
    gecode = Solver.lookup("gecode")

    instance = Instance(gecode, model)
    initialize_instance(instance, input_num)
    result = instance.solve()

    show_result(result, instance)
Пример #14
0
class TestEnum(InstanceTestCase):
    code = """
    enum DAY = {Mo, Tu, We, Th, Fr, Sa, Su};
    var DAY: d;
    """

    def test_value(self):
        self.instance.add_string("constraint d == Mo;")
        result = self.instance.solve()
        assert isinstance(result["d"], str)
        assert result["d"] == "Mo"

    def test_cmp_in_instance(self):
        self.instance.add_string("var DAY: d2;")
        self.instance.add_string("constraint d < d2;")
        result = self.instance.solve()
        assert isinstance(result["d"], str)
        assert isinstance(result["d2"], str)
        # TODO: assert result["d"] < result["d2"]

    def test_cmp_between_instances(self):
        append = "constraint d == Mo;"
        self.instance.add_string(append)
        result = self.instance.solve()

        inst = Instance(self.solver)
        inst.add_string(self.code + append)
        result2 = inst.solve()
        assert isinstance(result["d"], str)
        assert isinstance(result2["d"], str)
        assert result["d"] == result2["d"]

        inst = Instance(self.solver)
        inst.add_string("""
            enum DAY = {Mo, Tu, We, Th, Fr};
            var DAY: d;
            """ + append)
        result2 = inst.solve()
        # TODO: assert type(result["d"]) != type(result2["d"])
        # TODO: assert result["d"] == result2["d"]

    def test_assign(self):
        self.instance = Instance(self.solver)
        self.instance.add_string("""
            enum TT;
            var TT: t1;
            """)
        TT = enum.Enum("TT", ["one"])
        self.instance["TT"] = TT
        result = self.instance.solve()

        assert isinstance(result["t1"], TT)
        assert result["t1"] is TT.one
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()
Пример #16
0
def elegantly_color(graph: AdjMatrix) -> Tuple[AdjMatrix, List[int]]:
    """Return an adjacency matrix represnting elegantly colored edges."""
    model_path = MIZNIZIC_MODELS_DIR.joinpath("elegant_labeling.mzn")
    model = Model(model_path)
    instance = Instance(Solver.lookup("gecode"), model)

    instance["graph"] = graph
    instance["total_edges"] = count_edges(graph)
    instance["total_vertices"] = len(graph)

    result = instance.solve()
    if (status := result.status) != Status.SATISFIED:
        error = f"An error occured when coloring the graph. Returned status: {status}"
        raise RuntimeError(error)
Пример #17
0
    def run_extended(self):
        inst = Instance(self.solver, self.model)

        # we'll need a solution pool of previously seen solutions
        # to rule out condorcet cycles; a solution is stored as a Python dictionary from variable to value
        solution_pool = []

        res: Result = inst.solve()
        print(res.solution)
        duels = []
        new_solution = None
        model_counter = 0

        while res.status == Status.SATISFIED:
            model_counter += 1
            old_solution = new_solution
            new_solution = {
                var: res[var]
                for var in self.variables_of_interest
            }
            solution_pool += [new_solution]

            if hasattr(res.solution, PREFERRED_BY_KEY):
                preferred_by = res[PREFERRED_BY_KEY]
                self.num_voters = res[NUM_VOTERS_KEY]
                print(preferred_by)
                duels += [(new_solution, old_solution, preferred_by)]

            with inst.branch() as child:
                child.add_string(
                    f"array[{self.agents_key}] of par int: old_score;")
                child["old_score"] = res["score"]  # copy the current ranks

                self.add_condorcet_improvement(child)
                self.add_duel_bookkeeping(child)

                # but it should be a "new" solution
                self.post_something_changes(child, solution_pool)

                # logging
                self.log_and_debug_generated_files(child, model_counter)

                res = child.solve()
                if res.solution is not None:
                    print(res.solution)

        for (winning_solution, losing_solution, preferrers) in duels:
            print(
                f"Solution {winning_solution} won against {losing_solution} with {preferrers} : {self.num_voters - preferrers}"
            )
Пример #18
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())
    def test_intenum_collections(self):
        self.instance = Instance(self.solver)
        self.instance.add_string("""
            enum TT;
            % array[int] of var TT: arr_t;
            var set of TT: set_t;
            """)
        TT = enum.IntEnum("TT", ["one", "two", "three"])
        self.instance["TT"] = TT
        # TODO:  self.instance["arr_t"] = [TT(3), TT(2), TT(1)]
        self.instance["set_t"] = {TT(2), TT(1)}
        result = self.instance.solve()

        # TODO: assert result["arr_t"] == [TT(3), TT(2), TT(1)]
        assert result["set_t"] == {TT(1), TT(2)}
Пример #20
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]
Пример #21
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")
Пример #22
0
 def to_solve(self):
     from minizinc import Instance, Model, Solver
     seaux = Model("./seaux.mzn")
     gecode = Solver.lookup("gecode")
     instance = Instance(gecode, seaux)
     instance["N"] = len(self.buckets)
     instance["init"] = [b.current for b in self.buckets]
     instance["storage"] = [b.capacity for b in self.buckets]
     instance["goal"] = [b.goal for b in self.buckets]
     result = instance.solve()
     if result is not None:
         print(result)
         #QMessageBox.information(self, "Solution", f"Le problème peut être résoulu en {result['total_steps']}")
         self.move_auto(result["transfered"], result["total_steps"] - 1)
     else:
         QMessageBox.information(self, "Solution",
                                 f"Le problème est insoluble")
Пример #23
0
 def auto(self):
     from minizinc import Instance, Model, Solver
     mouton = Model("./mouton.mzn")
     gecode = Solver.lookup("gecode")
     instance = Instance(gecode, mouton)
     instance["N"] = len(self.sheeps) // 2
     if instance["N"] == 1:
         instance["max_steps"] = 4
     elif instance["N"] == 2:
         instance["max_steps"] = 9
     else:
         instance["max_steps"] = 16
     result = instance.solve()
     if result is not None:
         self.move_auto(result["transfered"])
     else:
         QMessageBox.information(self, "Solution",
                                 f"Le problème est insoluble")
Пример #24
0
    def test_cmp_between_instances(self):
        append = "constraint d == Mo;"
        self.instance.add_string(append)
        result = self.instance.solve()

        inst = Instance(self.solver)
        inst.add_string(self.code + append)
        result2 = inst.solve()
        assert isinstance(result["d"], str)
        assert isinstance(result2["d"], str)
        assert result["d"] == result2["d"]

        inst = Instance(self.solver)
        inst.add_string("""
            enum DAY = {Mo, Tu, We, Th, Fr};
            var DAY: d;
            """ + append)
        result2 = inst.solve()
Пример #25
0
def solver(data):
    """
    Ejecucion del modelo en minizinc
    """
    # Configurar modelo y solver
    planta_energia = Model("./model/PlantaEnergia.mzn")
    coinbc = Solver.lookup("coin-bc")
    instance = Instance(coinbc, planta_energia)
    # Configurar parametros de entrada
    instance["n"] = data['n']
    instance["s"] = data['s']
    instance["CP"] = data['CP']
    instance["CC"] = data['CC']
    instance["d"] = data['d']
    # Resultado modelo
    result = instance.solve()
    print("Resultado MiniZinc:", result)
    return result
Пример #26
0
def solve():
    times, n = prep_data()
    nqueens = Model("./model.mzn")
    # Find the MiniZinc solver configuration for Gecode
    solver = Solver.lookup("chuffed")
    # Create an Instance of the n-Queens model for Gecode
    instance = Instance(solver, nqueens)
    # Assign 4 to n
    instance["N_slot"] = n
    instance["min_time"] = 0
    instance["max_time"] = 7 * 60 * 24
    instance["max_duration_meeting"] = max([s[1] - s[0] + 1 for s in times])
    instance["duration_meeting"] = 59
    instance["array_meeting"] = [s[0] for s in times]
    instance["array_duration"] = [s[1] - s[0] + 1 for s in times]
    from datetime import timedelta
    result = instance.solve(timeout=timedelta(seconds=3600))
    # Output the array q
    opt: Status = result.status
    print(result.__dict__)
    time = result["time_meeting"]

    beg = time
    end = time + 59

    day = (beg - 1) // 600

    hour = ((beg - 1 - (day * 600)) // 60)
    minute = beg - 1 - (day * 600) - (hour * 60)

    houre = ((end - 1 - (day * 600)) // 60)
    minutee = end - 1 - (day * 600) - (houre * 60)

    def countToString(hour):
        if hour < 10:
            return "0" + str(hour)
        else:
            return str(hour)

    print(
        str(day + 1) + " " + countToString(hour + 8) + ":" +
        countToString(minute) + "-" + countToString(houre + 8) + ":" +
        countToString(minutee))
    def __platform_selected(self):
        """
        The paltform selected method intialises the solver, create a instance and pass appropriate varibles values.
        Insatnce is solved and results are appended to appropriate variable.
        Returns the selected platform from minizinc that solves CSP. 

        Parameters
        ----------
        **params: 
            None

        Returns
        -------
        platform_solutions: list
            Contains all the solution obtained from the CSP solver.
        """
        # Load platfroms model from file
        minizinc_file = "./" + str(self.__minizinc_model)
        platforms = Model(minizinc_file)
        # Find the MiniZinc solver configuration for Gecode
        gecode = Solver.lookup("gecode")
        # Create an Instance of the platforms model for Gecode
        instance = Instance(gecode, platforms)
        instance["force_sensor_presence"] = self.__repo_image.force_sensor_presence
        instance["min_tactile_sensor_count"] = self.__repo_image.min_tactile_sensor_count
        instance["min_memory_fused"] = self.__repo_image.min_memory_fused
        instance["n_platforms"] = self.__repo_image.n_platforms
        instance["platforms"] = self.__repo_image.platforms
        instance["min_latency"] = self.__repo_image.fused_platform_min_latency
        instance["max_latency"] = self.__repo_image.fused_platform_max_latency
        instance["req_force_plfm_type"] = self.__repo_image.force_sensor_type
        instance["curr_memory_availability"]=  [int(x) for x in self.__repo_image.platforms_memory_availability]

        result = instance.solve(intermediate_solutions=True)
        platform_solutions = []
        if len(result) != 0:
            for i in result:
                platform_solutions.append(i.force_platform)
                platform_solutions.append(i.tactile_platform)
                platform_solutions.append(i.fused_platform)

        return platform_solutions
def present_wrapping_problem():
    model_path = "src/Project.mzn"
    pwp = Model(model_path)
    instances_directory = "src/Instances"
    gecode = Solver.lookup("gecode")
    all_files = os.listdir(instances_directory)
    os.close

    for instance_file in all_files:
        instance = Instance(gecode, pwp)
        with open(instances_directory + "/" + instance_file, "r") as file:
            solve_instance(instance, file)
Пример #29
0
 async def explore_async(self,
                         decision_model,
                         backend_solver_name='gecode'):
     mzn_model_name = decision_model.get_mzn_model_name()
     mzn_model_str = res.read_text('idesyde.minizinc', mzn_model_name)
     mzn_model = Model()
     mzn_model.add_string(mzn_model_str)
     backend_solver = Solver.lookup(backend_solver_name)
     instance = Instance(backend_solver, mzn_model)
     decision_model.populate_mzn_model(instance)
     result = await instance.solve_async()
     return decision_model.rebuild_forsyde_model(result)
Пример #30
0
def minimum_set_cover_mz(problem):
    with path('mz_python_puzzles.setcover.mz', 'setcover.mzn') as model_path:
        model = Model(model_path)
    solver = Solver.lookup('org.minizinc.mip.coin-bc')

    instance = Instance(solver, model)
    instance['N'] = len(problem.universe)
    instance['M'] = len(problem.sets)
    instance['cost'] = list(map(lambda s: s.cost, problem.sets))
    instance['items_covered'] = (
        list(map(lambda s: set(map(lambda i: i + 1, s.items)), problem.sets))
    )

    result = instance.solve(timeout=timedelta(seconds=5))

    if result.status.has_solution():
        return Cover(
            result.objective,
            [problem.sets[i] for i, s in enumerate(result.solution.chosen)
                if s == 1]
        )
    return None