Пример #1
0
 def show(self,export=False):
    """
    Display a graph of the Markov Model.
    """
    graph = [(node,val[0]) for node in self.node_cnx for val in self.node_cnx[node]]
    edge_labels = [round(val[1],2) for node in self.node_cnx for val in self.node_cnx[node]]
    draw_graph(graph,labels=edge_labels,export=export)
Пример #2
0
 def run(self):
     s = Simulation(graph_type=self.type, graph_param=self.graph_param)
     g = s.build_graph()
     companies = s.generate_companies(g)
     graph_utils.draw_graph(g)
     s.generate_trucks(g, companies)
     cpy_companies = [(c[0], copy.deepcopy(c[1])) for c in companies]
     clients = s.generate_clients(g, cpy_companies)
     money_per_company = s.testCicle(g, s.generateMoneyPerCompany(),
                                     companies, cpy_companies, clients)
     minimum = [m[-1] for m in money_per_company]
     index_company = minimum.index(min(minimum))
     # values for index_company for different values of profit margin
     values_pm_company = []
     profitMaring_values = list(np.array(list(range(10, 50, 1))) / 10)
     for pm in profitMaring_values:
         companies[index_company][1].setProfitMargin(pm)
         money_per_company = s.testCicle(g, s.generateMoneyPerCompany(),
                                         companies, cpy_companies, clients)
         values_pm_company.append(money_per_company[index_company][-1])
         gc.collect()
     legend = [[
         "Company w/ worst profit: " + str(companies[index_company][1].pos)
     ]]
     s.drawPlot(profitMaring_values,
                values_pm_company,
                "Profit Margin",
                "Profit Margin",
                "Money",
                legend,
                per=0.05,
                color=graph_utils.colormap[companies[index_company][0]])
Пример #3
0
    def draw_graph(self, outfile="./out.png"):
        edgeslist = []
        # make a list of edges
        for u, vs in self.edges.items():
            for v in vs:
                edgeslist.append((u, v))

        draw_graph(self.nodes.values(), edgeslist)
Пример #4
0
 def run(self):
     s = Simulation(graph_type=self.type, graph_param=self.graph_param)
     g = s.build_graph()
     companies = s.generate_companies(g)
     s.generate_trucks(g, companies)
     graph_utils.draw_graph(g)
     #graph_utils.show_graphs()
     cpy_companies = [(c[0], copy.deepcopy(c[1])) for c in companies]
     clients = s.generate_clients(g, cpy_companies)
     money_per_company = s.testCicle(g, s.generateMoneyPerCompany(),
                                     companies, cpy_companies, clients)
     gc.collect()
     legend = [(graph_utils.colormap[c[0]], c[1].name, c[1].pos)
               for c in companies]
     self.drawPlot(money_per_company, "Money vs Time", "Time", "Money",
                   legend)
Пример #5
0
    def run_hospital_decide_simulation(self, heuristic, nr_tiks=200):
        nr_tiks_per_pacient = self.max_weight * 3

        self.reset_before_simulate()
        # Step 1: generate the rest of the agents and assign their postitions on the graph
        self.populate_charging_stations()
        self.generate_ambulances(hospital=self.hospital,
                                 nr_ambulances=self.nr_ambulances)
        number_of_patients = round(nr_tiks / nr_tiks_per_pacient)
        self.populate_patients(nr_tiks, number_of_patients)

        # Step 2: go through a series of iterations
        while ((self.get_tik() < nr_tiks)
               or self.patients):  # or self.patients != []):

            print("\n  TIK #" + str(self.get_tik()))

            if (self.patient_counter < number_of_patients and self.get_tik()
                    == self.patient_generation_list[self.patient_counter]):
                self.generate_patient((self.min_weight + self.max_weight) / 2)

            # 1) hospital assigns goals to each ambulance
            self.hospital.execute(self.ambulances, self.patients,
                                  self.charging_stations, self.g, heuristic)

            # 2) each ambulance executes3
            for a in self.ambulances:
                o = a.execute(self.hospital.get_hospital_pos())
                if (o == "picked_up_success"):
                    self.success += 1
                    self.patients.remove(a.get_patient())
                elif (o == "picked_up_failed"):
                    self.failed += 1
                    self.patients.remove(a.get_patient())

            self.increment_tik()
        graph_utils.draw_graph(self.g)

        print("\n\nThe simulation ended with " + str(self.success) +
              " cases of success and " + str(self.failed) +
              " cases of failure")
Пример #6
0
    def run(self):
        s = Simulation(graph_type=self.type, graph_param=self.graph_param)
        g = s.build_graph()
        while not nx.is_connected(g):
            g = s.build_graph()
        companies = s.generate_companies(g)
        s.generate_trucks(g, companies)
        graph_utils.draw_graph(g)
        cpy_companies = [(c[0], copy.deepcopy(c[1])) for c in companies]
        clients = s.generate_clients(g, cpy_companies)
        basic_preferences = [1 / s.n_companies for _ in range(s.n_companies)]
        for cli in clients:
            cli.setUtilities(basic_preferences)
            cli.risk = 1
        money_per_company = s.testCicle(g, s.generateMoneyPerCompany(),
                                        companies, cpy_companies, clients)
        if not self.last:
            maximum = [m[-1] for m in money_per_company]
            index_best_company = maximum.index(max(maximum))
            maximum[index_best_company] = 0
            index_company = maximum.index(max(maximum))
        else:
            minimum = [m[-1] for m in money_per_company]
            index_company = minimum.index(min(minimum))
        # values for index_company for different values of preferences
        values_company_preferences = []
        values_best_company = []
        preferences_values = list(np.array(list(range(20, 101, 1))) / 100)
        for pref in preferences_values:
            for cli in clients:
                cli.utilities[index_company] = pref
            money_per_company = s.testCicle(g, s.generateMoneyPerCompany(),
                                            companies, cpy_companies, clients)
            values_company_preferences.append(
                money_per_company[index_company][-1])
            if not self.last:
                values_best_company.append(
                    money_per_company[index_best_company][-1])
            gc.collect()

        if not self.last:
            self.legend[0] = self.legend[0] + str(
                companies[index_company][1].pos)
            self.legend[1] = self.legend[1] + str(
                companies[index_best_company][1].pos)
            self.drawPlot(
                preferences_values,
                values_company_preferences,
                values_best_company,
                "Preferences",
                "Preferences (%)",
                "Money",
                self.legend,
                color=[
                    graph_utils.colormap[companies[index_company][0]],
                    graph_utils.colormap[companies[index_best_company][0]]
                ])
        else:
            self.legend[0] = [
                self.legend[0][0] + str(companies[index_company][1].pos)
            ]
            s.drawPlot(preferences_values,
                       values_company_preferences,
                       "Preferences",
                       "Preferences (%)",
                       "Money",
                       self.legend,
                       per=0.05,
                       color=graph_utils.colormap[companies[index_company][0]])
Пример #7
0
                                               p=0.2,
                                               min_weight=1,
                                               max_weight=10)
# g = graph_utils.generate_weighted_barabasi_graph()

companies = generate_companies(g, n_companies=5)
generate_trucks(g, companies, n_trucks=7)
clients = [
    Client(n, [c[1] for c in companies], min_offer_val=20, max_offer_val=100)
    for n in g.nodes if "company" not in g.node[n]
]

# graph_utils.draw_graph(g)

p_remove = 0.02  # por random
graph_utils.draw_graph(g)
graph_utils.show_graphs()
for i in range(10000):
    if not len(companies):
        print("NO MORE COMPANIES")
        break

    if len(companies) == 1:
        print(
            f"WINNER: {c} -- t={i} -- offers={companies[0][1].completedOffers}"
        )

    if (randint(1, 99) / 100) < p_remove:
        do_edge_explosion(i, g)

    for cli in clients:
Пример #8
0
    def run_cooperative_ambulances_simulation(
            self,
            nr_tiks=200,
            a_s=Ambulance.ActionSelection.selective,
            l_a=Ambulance.LearningApproach.QLearning):
        self.reset_before_simulate()

        nr_tiks_per_pacient = self.max_weight * 3

        # Step 1: generate the rest of the agents and assign their postitions on the graph
        self.populate_charging_stations()
        self.generate_ambulances(hospital=self.hospital,
                                 nr_ambulances=self.nr_ambulances,
                                 g=self.g,
                                 pos_list=self.n_nodes,
                                 a_s=Ambulance.ActionSelection.selective,
                                 l_a=Ambulance.LearningApproach.QLearning)

        number_of_patients = round(nr_tiks / nr_tiks_per_pacient)
        self.populate_patients(nr_tiks, number_of_patients)
        # Step 2: let agents learn the positions where patients have more case and higher emergency
        self.populate_training_patients(self.n_training_patients)
        print("\nNumber of patients to be generated: " +
              str(self.n_training_patients))
        print("\nLearning in progress...")
        print("\nThis might take a while...")
        for i in range(self.n_training_patients * 10):
            if self.patient_counter < self.n_training_patients and i == self.training_patient_generation_list[
                    self.patient_counter]:
                self.generate_patient((self.min_weight + self.max_weight) / 2,
                                      print_info=False)

            for a in self.ambulances:
                a.getLearningMetrics(self.g, self.patients, self.hospital)
                a.executeLearning()

        self.patients.clear()
        self.patient_counter = 0
        for a in self.ambulances:
            a.set_exploitation()
        print("\nLearning completed\n\n")

        # Step 3: go through a series of iterations
        picked = 0
        while (self.get_tik() < nr_tiks) or picked <= (number_of_patients - 1):

            print("\n  TIK #" + str(self.get_tik()))

            if self.patient_counter < number_of_patients and self.get_tik(
            ) == self.patient_generation_list[self.patient_counter]:
                self.generate_patient((self.min_weight + self.max_weight) / 2)

            # 1) ambulances inform each other of their metrics
            metrics = []
            for a in self.ambulances:
                metrics.append(
                    a.send_metrics(self.g, self.patients, self.hospital))

            # 2) ambulances decide which is the one executing
            for a in self.ambulances:
                a.collect_metrics_and_decide(metrics, self.patients, self.g,
                                             self.charging_stations)

            # 3) chosen ambulances execute
            for a in self.ambulances:
                o = a.execute(self.hospital.get_hospital_pos())
                if o == "picked_up_success":
                    self.success += 1
                    self.patients.remove(a.get_patient())
                    picked += 1
                elif o == "picked_up_failed":
                    self.failed += 1
                    self.patients.remove(a.get_patient())
                    picked += 1

            self.increment_tik()

        graph_utils.draw_graph(self.g)
        print(self.patients)
        print("\n\nThe simulation ended with " + str(self.success) +
              " cases of success and " + str(self.failed) +
              " cases of failure\n")