Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Fix few typos and add random seed intializer
[simgrid.git] / src / mc / api / strategy / UniformStrategy.hpp
1 /* Copyright (c) 2007-2023. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #ifndef SIMGRID_MC_UNIFORMSTRATEGY_HPP
7 #define SIMGRID_MC_UNIFORMSTRATEGY_HPP
8
9 #include "src/mc/transition/Transition.hpp"
10
11 namespace simgrid::mc {
12
13 /** Guiding strategy that valuate states randomly */
14 class UniformStrategy : public Strategy {
15   std::map<aid_t, int> valuation;
16
17 public:
18   UniformStrategy()
19   {
20     for (long aid = 0; aid < 10; aid++)
21       valuation[aid] = rand() % 1000;
22   }
23   void copy_from(const Strategy* strategy) override
24   {
25     for (auto& [aid, _] : actors_to_run_)
26       valuation[aid] = rand() % 1000;
27   }
28
29   std::pair<aid_t, int> next_transition() const override
30   {
31     int possibilities = 0;
32
33     // Consider only valid actors
34     for (auto const& [aid, actor] : actors_to_run_) {
35       if (actor.is_todo() and (not actor.is_done()) and actor.is_enabled())
36         possibilities++;
37     }
38
39     int chosen;
40     if (possibilities == 0)
41       return std::make_pair(-1, 100000);
42     if (possibilities == 1)
43       chosen = 0;
44     else
45       chosen = rand() % possibilities;
46
47     for (auto const& [aid, actor] : actors_to_run_) {
48       if ((not actor.is_todo()) or actor.is_done() or (not actor.is_enabled()))
49         continue;
50       if (chosen == 0) {
51         return std::make_pair(aid, valuation.at(aid));
52       }
53       chosen--;
54     }
55
56     return std::make_pair(-1, 100000);
57   }
58
59   void execute_next(aid_t aid, RemoteApp& app) override {}
60
61   void consider_best() override
62   {
63
64     int possibilities = 0;
65     // Consider only valid actors
66     // If some actor are already considered as todo, skip
67     for (auto const& [aid, actor] : actors_to_run_) {
68       if (valuation.count(aid) == 0)
69         for (auto& [aid, _] : actors_to_run_)
70           valuation[aid] = rand() % 1000;
71       if (actor.is_todo())
72         return;
73       if (actor.is_enabled() and not actor.is_done())
74         possibilities++;
75     }
76
77     int chosen;
78     if (possibilities == 0)
79       return;
80     if (possibilities == 1)
81       chosen = 0;
82     else
83       chosen = rand() % possibilities;
84
85     for (auto& [aid, actor] : actors_to_run_) {
86       if (not actor.is_enabled() or actor.is_done())
87         continue;
88       if (chosen == 0) {
89         actor.mark_todo();
90         return;
91       }
92       chosen--;
93     }
94     THROW_IMPOSSIBLE; // One actor should be marked as todo before
95   }
96 };
97
98 } // namespace simgrid::mc
99
100 #endif