Exemplo n.º 1
0
def initialize():
    print("initializing")
    print(".......")
    print(".......")
    print("number of intersections:")
    n = int(input())

    data = []
    importance = []
    for i in range(n):
        global adj_list
        print(
            "input the nodes associated with current node and the congestion and importance of the road conncting them in the format \"road cogestion imortance\""
            + str(i + 1))
        inp = input()
        inp = inp.split()
        lst = [int(j) for j in inp]
        final_lst = []
        index = 0
        while index < len(lst):
            final_lst.append([lst[index], lst[index + 1], lst[index + 2]])
            index = index + 3
    # print(final_lst)
        adj_list.append(final_lst)
        lst2 = [0] * (n)
        lst_imp = [0] * (n)
        for j in final_lst:
            # print(j)
            lst2[j[0] - 1] = j[1]
            lst_imp[j[0] - 1] = j[2]
        data.append(lst2)
        importance.append(lst_imp)

    data_max = {'n': n, 'congestion_graph': data, 'importance': importance}
    dzn = pm.dict2dzn(data_max, fout='max_find.dzn')
    sol_max = pm.minizinc('maximum_calculator.mzn', 'max_find.dzn')

    max_cost = sol_max[0]['max_cost']
    max_imp = sol_max[0]['max_imp']
    print("max cost = ", max_cost)
    print("max imp = ", max_imp)
    max_turn = 25
    print("how fast do you want the system to update signals?")
    signal_period = int(input())
    prev = [[0] * (n)] * (n)
    data = {
        'n': n,
        'congestion_graph': data,
        'max_cost': max_cost,
        'max_turn': max_turn,
        'prev': prev,
        'importance': importance,
        'max_imp': max_imp
    }
    #   print(data)
    dzn = pm.dict2dzn(data, fout='datafrompython.dzn')
    dzn = pm.dict2dzn(data, fout='test_data0.dzn')
    return [dzn, signal_period]
Exemplo n.º 2
0
def update_cost(solns, dzn, period):
    data = pm.dzn2dict('datafrompython.dzn')
    decision = solns[0]['decision']
    gr = data['congestion_graph']
    rate_dec = 2
    for i in range(len(adj_list)):
        reduction = rate_dec * period
        for j in range(len(adj_list)):
            if decision[i][j] == 1:
                if reduction > gr[i][j]:
                    reduction = gr[i][j]
                gr[i][j] -= reduction

                prev_queue.append([i, j])
                if len(prev_queue) > 100:
                    prev_queue.popleft()
            elif j in adj_list[i]:
                gr[j][i] += reduction // 3
# print("congestion_graph")

#  print(gr)
    data['congestion_graph'] = gr
    n = len(gr)
    prev = [[0] * n for i in range(n)]
    for pair in prev_queue:
        prev[pair[0]][pair[1]] += 1
    data['prev'] = prev
    global iteration
    iteration += 1
    file_name = 'test_data' + str(iteration) + '.dzn'
    dzn = pm.dict2dzn(data)
    return dzn
Exemplo n.º 3
0
def main() -> int:
    '''
    Sequential operation:
        - load .dzn file
        - process it and save it in a new file
        - try to find solutions with MiniZinc and Gecode solver (optional)
        - plot in a graph all path obtained for visual feedback (optional)
    '''
    data = load_dataset(args.dzn_path)

    if not data:
        raise Exception(f"an error occurred while loading the dataset")

    data = process(data, args.dzn_path, args.order)
    # Save processed data to {args.output}.dzn file
    pymzn.dict2dzn(data, fout=args.output)

    print("Preprocessing completed.")
    if not args.solve:
        return -1

    if not file_exists(args.model, MZN_EXT):
        return -1

    print(f"Running {args.model} with {args.output}({args.dzn_path})...")
    # Default solver is Gecode (pymzn.Solver)
    sols = pymzn.minizinc(args.model,
                          args.output,
                          timeout=args.limit,
                          all_solutions=True)

    if not sols:
        print("No solutions found.")
        return -1

    path, vehicle = print_solution(sols)
    if args.plot:
        plot_path(data, path, vehicle)

    return 0
Exemplo n.º 4
0
def initialize():

    #global adj_list
    #adj_list=[]
    print("initializing")
    print(".......")
    print(".......")
    print("number of intersections:")
    n = int(input())

    data = []
    for i in range(n):
        # print("how many nodes associated with node "+str(i))
        #m=input(i)
        global adj_list
        print(
            "input the nodes associated with node and the density of the road conncting them "
            + str(i + 1))
        inp = input()
        inp = inp.split()
        lst = [int(j) for j in inp]
        final_lst = []
        index = 0
        while index < len(lst):
            final_lst.append([lst[index], lst[index + 1]])
            index = index + 2
        print(final_lst)
        adj_list.append(final_lst)
        lst2 = [0] * (n)
        for j in final_lst:
            print(j)
            lst2[j[0] - 1] = j[1]
    # for j in range len(lst):
        data.append(lst2)
    max_cost = 40
    max_turn = 25
    print("how fast do you want the system to update signals?")
    signal_period = int(input())
    prev = [[0] * (n)] * (n)
    data = {
        'n': n,
        'congestion_graph': data,
        'max_cost': max_cost,
        'max_turn': max_turn,
        'prev': prev
    }
    print(data)
    dzn = pm.dict2dzn(data, fout='datafrompython.dzn')
    #pm.dict2dzn(dzn, fout='capacity.dzn')
    return [dzn, signal_period]
Exemplo n.º 5
0
def update_cost(solns, dzn, period):
    data = pm.dzn2dict('datafrompython.dzn')
    decision = solns[0]['decision']
    gr = data['congestion_graph']

    #print("decision")
    #print(decision)

    rate_dec = 2
    for i in range(len(adj_list)):
        reduction = 3 * period
        for j in range(len(adj_list)):
            if decision[i][j] == 1:
                if reduction > gr[i][j]:
                    reduction = gr[i][j]
                gr[i][j] -= reduction

                prev_queue.append([i, j])
                if len(prev_queue) > 100:
                    prev_queue.popleft()
            elif j in adj_list[i]:
                gr[j][i] += reduction // 3
    print("congestion_graph")
    print(gr)
    data['congestion_graph'] = gr
    n = len(gr)
    prev = [[0] * n for i in range(n)]
    #print("prev queue")
    #print(prev_queue)
    #(prev[0])[1]=-2
    # print(prev)
    #exit()
    for pair in prev_queue:
        # print(pair)
        #print(pair[0])

        #print(pair[1])
        #prev[0][0]=1
        prev[pair[0]][pair[1]] += 1
    #  print(prev)
    data['prev'] = prev
    # print("prev")
    #print(prev)
    dzn = pm.dict2dzn(data)
    return dzn
Exemplo n.º 6
0
 def test_dzn(self):
     dzn = pymzn.dict2dzn({'x': 1, 'y': 2})
     self.assertIn('x = 1;', dzn)
     self.assertIn('y = 2;', dzn)
Exemplo n.º 7
0
 def test_dzn(self):
     dzn = pymzn.dict2dzn({'x': 1, 'y': 2})
     self.assertIn('x = 1;', dzn)
     self.assertIn('y = 2;', dzn)
Exemplo n.º 8
0
                # indicate non-edges for non-wrapping output images and similar
                adj_grid[d_idx, y, x] = 1 + (offset_cell[0] +
                                             (offset_cell[1] * shape[0]))
    return adj_grid


solns = pymzn.minizinc('knapsack.mzn', 'knapsack.dzn', data={'capacity': 20})
print(solns)

pymzn.dict2dzn(
    {
        'w': 8,
        'h': 8,
        'pattern_count': 95,
        'direction_count': 4,
        'adjacency_count': 992,
        'pattern_names': [],
        "relation_matrix": [],
        "adjaceny_table": [],
        "adjacency_matrix": []
    },
    fout='test.dzn')


def mz_init(prestate):
    prestate.adjacency_directions_rc = {
        i: CoordRC(a.y, a.x)
        for i, a in prestate.adjacency_directions.items()
    }
    prestate = wfc.wfc_utilities.find_pattern_center(prestate)
    wfc_state = types.SimpleNamespace(wfc_ns=prestate)
Exemplo n.º 9
0
import pymzn

pymzn.dict2dzn({
    'a': 2,
    'b': {4, 6},
    'c': {1, 2, 3},
    'd': {
        3: 4.5,
        4: 1.3
    },
    'e': [[1, 2], [3, 4], [5, 6]]
})
data = {
    'a': 2,
    'b': {4, 6},
    'c': {1, 2, 3},
    'd': {
        3: 4.5,
        4: 1.3
    },
    'e': [[1, 2], [3, 4], [5, 6]]
}

data["set_a"] = {"f1", "f2"}
pymzn.dict2dzn(data, fout='../../minizinc_labor/pymzn_test_data.dzn')

print(type(data))
Exemplo n.º 10
0
def save_as_dzn(n, matrix):
    data = {'n': n, 'matrix': matrix}
    pymzn.dict2dzn(data, fout='tsp_{}.dzn'.format(n))
Exemplo n.º 11
0
def run_experiment():
    def write_csv(data):
        with open('intermediate_results.csv', 'a') as outfile:
            writer = csv.writer(outfile)
            writer.writerow(data)

    #basic process, (10,5,5)
    #max process (10000,200,50)

    activities_set = [100, 200, 300]
    ratios = [5, 10]

    #M=45

    skills_set = [50, 100]
    M = 0.95
    utils = [0.5, 0.3, 0.1]

    #for density in densities:

    densities = range(1, 10, 4)
    densities = [d / 10 for d in densities]

    #densities = [0.5]

    scenarios = [(a, int(a / r), s, d, u) for a in activities_set
                 for r in ratios for s in skills_set for d in densities
                 for u in utils]
    string_scenarios = []
    for s in scenarios:
        string_scenarios.append(
            str(s[0]) + '_' + str(s[1]) + '_' + str(s[2]) + '_' + str(s[3]) +
            '_' + str(s[4]))
    runtimes_first = []
    runtimes_last = []
    runtimes_proof = []
    attempts = []
    #machines out of total
    objs = []
    for j, s in enumerate(scenarios):
        attempts.append(0)
        infeasible_flag = True
        while infeasible_flag == True:
            attempts[len(attempts) - 1] += 1
            print('Current scenario running: ' + string_scenarios[j])

            n_A, n_R, n_S, density, util = s

            try:
                instance_data = gen_SBPR_Completely_Random(
                    n_A, n_R, n_S, False, density, M,
                    util)  #M/n_R)#(n_R-1)/n_R) #0.5)
                #instance_data2 = gen_GAP_Completely_Random(n_A,n_R,verbose=True)
            except ValueError:
                print("Error")
                continue
            #instance_data = gen_SBPR(n_A,n_R,n_S)
            print(os.path.join("data_files", "SBPR_" + str(s) + ".dzn"))
            pymzn.dict2dzn(instance_data,
                           fout=os.path.join("data_files",
                                             "SBPR_" + str(s) + ".dzn"))
            #pymzn.dict2dzn(instance_data2, fout="arik_Gap.dzn")

            mysolver = MySolver()
            print('start solving...')
            mzn_sol = pymzn.minizinc("SBPR_problem.mzn",
                                     data=instance_data,
                                     solver=mysolver,
                                     all_solutions=True)
            #mzn_sol = pymzn.minizinc("GAP_v1.mzn", data= instance_data2, solver=mysolver, all_solutions = True)

            #mzn_sol = pymzn.minizinc("arik-problem-v2.mzn", data= instance_data,
            #solver =pymzn.Gecode(solver_id = 'gecode'))
            #         solver='chuffed')# solver = pymzn.Chuffed(solver_id='chuffed'))

            print(mzn_sol)
            if mzn_sol.status == Status.COMPLETE:
                objs.append(
                    (int(mzn_sol._solns[0]['Z']), int(mzn_sol._solns[0]['L'])))
                #objs.append(mzn_sol._solns[0]['Z'])

                split_obj = mzn_sol.log.split('objective=')[1:]
                runtimes_first.append(
                    float(
                        mzn_sol.log.split('objective=')[1:][0].split(
                            'solveTime=')[1].split('\n')[0]))
                runtimes_last.append(
                    float(
                        mzn_sol.log.split('objective=')[1:][-2].split(
                            'solveTime=')[1].split('\n')[0]))
                runtimes_proof.append(
                    float(
                        mzn_sol.log.split('objective=')[1:][-1].split(
                            'solveTime=')[1].split('\n')[0]))
                write_csv([
                    s,
                    float(
                        mzn_sol.log.split('objective=')[1:][-1].split(
                            'solveTime=')[1].split('\n')[0])
                ])
                print(runtimes_first[len(runtimes_first) - 1])
                print(runtimes_proof[len(runtimes_proof) - 1])
                #print('Time to optimal:')
                #print(tm.time() - start_time)
                #runtimes.append(tm.time() - start_time)
                infeasible_flag = False
            else:
                print('Infeasible for scenario ' + str(s))
                print('Retrying...')

    dict_ = {
        'scenarios': string_scenarios,
        'objectives': objs,
        'runtimes_first': runtimes_first,
        'runtimes_last': runtimes_last,
        'runrtimes_proof': runtimes_proof,
        'attempts': attempts
    }

    res_df = pd.DataFrame(dict_)
    print(res_df.head(10))
    res_df.to_csv(os.path.join('results', 'results.csv'))
 def export_dzn(self, file_name: str = None):
     import pymzn
     if file_name is None:
         file_name = os.path.join(path_minizinc, "coloring_example_dzn.dzn")
     pymzn.dict2dzn(self.dict_datas, fout=file_name)
     print("Successfully dumped data file ", file_name)
import numpy as np
import pymzn as mz

np.random.seed(0)

################################################################################
#       Define Sets
################################################################################

# Employee
num_employee = 80
Employee = np.char.add(np.full(num_employee, 'Employee'),
                       np.arange(num_employee).astype(str))

mz.dict2dzn({"emp": str(Employee)})

# Location
num_location = 4
Location = np.char.add(np.full(num_location, 'Location'),
                       np.arange(num_location).astype(str))
Location = Location.astype(set)
Location

# Shift
Shift = np.array(
    ['0816', '1018', '1220', '1420', '1620', '0812', '1014', '1216', '1418'])
num_shift = len(Shift)

# Skill
num_skill = 3
Exemplo n.º 14
0
                # indicate non-edges for non-wrapping output images and similar
                adj_grid[d_idx, y, x] = 1 + (offset_cell[0] +
                                             (offset_cell[1] * shape[0]))
    return adj_grid


solns = pymzn.minizinc("knapsack.mzn", "knapsack.dzn", data={"capacity": 20})
print(solns)

pymzn.dict2dzn(
    {
        "w": 8,
        "h": 8,
        "pattern_count": 95,
        "direction_count": 4,
        "adjacency_count": 992,
        "pattern_names": [],
        "relation_matrix": [],
        "adjaceny_table": [],
        "adjacency_matrix": [],
    },
    fout="test.dzn",
)


def mz_init(prestate):
    prestate.adjacency_directions_rc = {
        i: CoordRC(a.y, a.x)
        for i, a in prestate.adjacency_directions.items()
    }
    prestate = wfc.wfc_utilities.find_pattern_center(prestate)
    wfc_state = types.SimpleNamespace(wfc_ns=prestate)
    def exchange(self, agents, tasks, profits, initial_assignments, objective):
        min_objective = int(objective * self.acceptance_ratio)

        print('Objective: %d / Bound: %d' % (objective, min_objective))

        candidates = set()
        capacities = [0] + [a.capacity for a in agents]

        profit_matrix, aff_mat, weight_matrix = matrizes(agents,
                                                         tasks,
                                                         pad_dummy_agent=True)
        x = self.assignment_matrix(agents, tasks, initial_assignments)

        initial_affinities = np.sum(aff_mat * x, axis=1, keepdims=True)
        initial_profits = np.sum(profit_matrix * x, axis=1, keepdims=True)

        aff_improv = (aff_mat - initial_affinities) * (aff_mat > 0)
        aff_improv[:, [0]] -= initial_affinities
        prof_diff = (profit_matrix - initial_profits) * (profit_matrix > 0)
        prof_diff[:, [0]] -= initial_profits

        delta_welfares = []
        delta_profits = []
        delta_weights = []
        affected_agents = []
        exchanged_tasks = []

        # 1. Build a list of all potential, welfare-improving exchanges
        for source_agent, affimp in enumerate(aff_improv.T):
            # if source_agent == 0:
            #    continue  # Don't initiate from non-assigned

            pot_gains = affimp[affimp > 0]
            task_ids = np.where(affimp > 0)[0]  # row id
            sorted_order = np.argsort(affimp[affimp > 0][::-1])

            pot_gains = pot_gains[sorted_order]
            task_ids = task_ids[sorted_order]

            for dest_task, my_pot_gain in zip(task_ids, pot_gains):
                dest_agent = np.where(x[dest_task, :])[0][0]  # column id

                source_offerings = x[:, source_agent]
                dest_demand = aff_improv[:, dest_agent] > -my_pot_gain
                dest_compatible = profit_matrix[:,
                                                dest_agent] > 0  # Could also be aff_mat or weight_matrix
                potential_exchanges = np.logical_and(source_offerings,
                                                     dest_demand)
                potential_exchanges = np.logical_and(potential_exchanges,
                                                     dest_compatible)

                for source_task in np.where(potential_exchanges)[0]:
                    welfare_improv = my_pot_gain + aff_improv[source_task,
                                                              dest_agent]
                    profit_change = prof_diff[
                        dest_task, source_agent] + prof_diff[source_task,
                                                             dest_agent]

                    assert (x[source_task, source_agent])
                    assert (x[dest_task, dest_agent])
                    assert (welfare_improv >= 0)
                    assert (
                        welfare_improv == aff_improv[source_task, dest_agent] +
                        aff_improv[dest_task, source_agent])

                    ex1 = (source_agent, source_task, dest_agent,
                           aff_improv[source_task,
                                      dest_agent], prof_diff[source_task,
                                                             dest_agent],
                           (-weight_matrix[source_task, source_agent],
                            weight_matrix[source_task, dest_agent]))
                    ex2 = (dest_agent, dest_task, source_agent,
                           aff_improv[dest_task,
                                      source_agent], prof_diff[dest_task,
                                                               source_agent],
                           (-weight_matrix[dest_task, dest_agent],
                            weight_matrix[dest_task, source_agent]))
                    candidates.add(
                        ((-welfare_improv, -profit_change), ex1, ex2))

        for _, ex1, ex2 in sorted(candidates, key=lambda trans: trans[0]):
            delta_welfares.append(ex1[3])
            delta_welfares.append(ex2[3])

            delta_profits.append(ex1[4])
            delta_profits.append(ex2[4])

            delta_weights.append(list(ex1[5]))
            delta_weights.append(list(ex2[5]))

            affected_agents.append([source_agent + 1, dest_agent + 1])
            affected_agents.append([dest_agent + 1, source_agent + 1])

            exchanged_tasks.append(source_task)
            exchanged_tasks.append(dest_task)

        weight_budget = np.array(capacities) - np.sum(weight_matrix * x,
                                                      axis=0)

        assert (len(delta_welfares) == len(candidates) * 2)
        assert (len(weight_budget) == len(agents) + 1)

        data = {
            'n_agents': len(agents) + 1,
            'n_tasks': len(tasks),
            'n_exchanges': len(delta_welfares),
            'profit_budget': objective - min_objective,
            'weight_budget': weight_budget,
            'delta_welfares': delta_welfares,
            'delta_profits': delta_profits,
            'delta_weights': delta_weights,
            'agents': affected_agents,
            'task_ids': exchanged_tasks
        }

        print('Exchanges: %d' % len(delta_welfares))

        if len(delta_welfares) > 0:
            pymzn.dict2dzn(data, fout='neg1.dzn')
            start = time.time()
            output = pymzn.minizinc('negotiation.mzn',
                                    solver='gecode',
                                    data=data,
                                    timeout=30)  # Not a MIP problem
            duration = time.time() - start

            sel_exchanges = output[0]['assignment']
            affinity_improvement = output[0]['objective']
            nb_exchanges = np.count_nonzero(sel_exchanges)

            print('Applied Exchanges: %d / Improvement: %d / Time: %d' %
                  (nb_exchanges, affinity_improvement, duration))

            if nb_exchanges == 0:
                return initial_assignments, objective

            for ex_id in np.where(sel_exchanges)[0]:
                task_id = exchanged_tasks[ex_id]
                source_agent, dest_agent = affected_agents[ex_id]
                source_agent, dest_agent = source_agent - 1, dest_agent - 1

                assert (x[task_id, source_agent])
                assert (not x[task_id, dest_agent])

                x[task_id, source_agent] = 0
                x[task_id, dest_agent] = 1

            new_assignments = self.assignment_mat_to_dict(agents, tasks, x)
            new_objective = np.sum(profit_matrix * x)

            assert (np.sum(aff_mat * x) == (np.sum(initial_affinities) +
                                            affinity_improvement))
            assert (np.all(np.count_nonzero(x, axis=1) == 1))
            assert (np.all(np.sum(weight_matrix * x, axis=0) <= capacities))
            assert (new_objective >= min_objective)

            return new_assignments, new_objective
        else:
            return initial_assignments, objective