DPsim
Loading...
Searching...
No Matches
Scheduler.cpp
Go to the documentation of this file.
1/* Copyright 2017-2021 Institute for Automation of Complex Power Systems,
2 * EONERC, RWTH Aachen University
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7 *********************************************************************************/
8
9#include <dpsim/Scheduler.h>
10
11#include <algorithm>
12
13#include <filesystem>
14#include <fstream>
15#include <iostream>
16#include <unordered_map>
17#include <unordered_set>
18
19using namespace CPS;
20using namespace DPsim;
21
23
25 // Fill map here already since it's not protected by a mutex
26 for (auto task : tasks) {
27 mMeasurements[task.get()] = TaskMeasurement{};
28 }
29}
30
32 auto &measurement = mMeasurements[ptr];
33 if (measurement.count == 0) {
34 measurement.minimum = time;
35 measurement.maximum = time;
36 } else {
37 measurement.minimum = std::min(measurement.minimum, time);
38 measurement.maximum = std::max(measurement.maximum, time);
39 }
40 measurement.total += time;
41 ++measurement.count;
42}
43
45 const auto parentPath = std::filesystem::path(filename).parent_path();
46 if (!parentPath.empty())
47 std::filesystem::create_directories(parentPath);
48 std::ofstream os(filename);
49 os << "task,avg_ns,min_ns,max_ns,total_ns,calls\n";
50 for (auto &pair : mMeasurements) {
51 const auto &measurement = pair.second;
52 const TaskTime average = getAveragedMeasurement(pair.first);
53 // Keep the average in column two for readMeasurements(); also record its
54 // range and sample count without retaining every per-step sample.
55 os << pair.first->toString() << "," << average.count() << ","
56 << measurement.minimum.count() << "," << measurement.maximum.count()
57 << "," << measurement.total.count() << "," << measurement.count
58 << std::endl;
59 }
60 os.close();
61}
62
64 String filename, std::unordered_map<String, TaskTime::rep> &measurements) {
65 std::ifstream fs(filename);
66 if (!fs.good())
67 throw SchedulingException();
68
69 String name;
70 while (fs.good()) {
71 std::string line;
72 std::getline(fs, line);
73 if (line.rfind("task,", 0) == 0)
74 continue;
75 int idx = static_cast<UInt>(line.find(','));
76 if (idx == -1) {
77 if (line.empty())
78 continue;
79 throw SchedulingException();
80 }
81 measurements[line.substr(0, idx)] = std::stol(line.substr(idx + 1));
82 }
83}
84
86 const auto &measurement = mMeasurements[task];
87 if (measurement.count == 0)
88 return TaskTime::zero();
89 return measurement.total / measurement.count;
90}
91
93 Edges &outEdges) {
94 // Create graph (list of out/in edges for each node) from attribute dependencies
95 tasks.push_back(mRoot);
96 std::unordered_map<AttributeBase::Ptr, std::deque<Task::Ptr>,
97 std::hash<AttributeBase::Ptr>,
99 dependencies;
100 std::unordered_set<AttributeBase::Ptr, std::hash<AttributeBase::Ptr>,
102 prevStepDependencies;
103 for (auto task : tasks) {
104 for (AttributeBase::Ptr attr : task->getAttributeDependencies()) {
106 if (attr.getPtr() != Scheduler::external.getPtr()) {
107 AttributeBase::Set attrDependencies = attr->getDependencies();
108 for (AttributeBase::Ptr dep : attrDependencies) {
109 dependencies[dep].push_back(task);
110 }
111 } else {
112 dependencies[attr].push_back(task);
113 }
114 }
115 for (AttributeBase::Ptr attr : task->getPrevStepDependencies()) {
116 prevStepDependencies.insert(attr);
117 }
118 }
119
120 for (auto from : tasks) {
121 for (AttributeBase::Ptr attr : from->getModifiedAttributes()) {
122 for (auto to : dependencies[attr]) {
123 outEdges[from].push_back(to);
124 inEdges[to].push_back(from);
125 }
126 if (prevStepDependencies.count(attr)) {
127 outEdges[from].push_back(mRoot);
128 inEdges[mRoot].push_back(from);
129 }
130 }
131 }
132}
133
134void Scheduler::topologicalSort(const Task::List &tasks, const Edges &inEdges,
135 const Edges &outEdges,
136 Task::List &sortedTasks) {
137 sortedTasks.clear();
138
139 // make copies of the edge lists because we modify them (and it makes
140 // things easier since empty lists are automatically created)
141 Edges inEdgesCpy = inEdges, outEdgesCpy = outEdges;
142
143 // do a breadth-first search backwards from the root node first to filter
144 // out unnecessary nodes
145 std::deque<Task::Ptr> q;
146 std::unordered_set<Task::Ptr> visited;
147
148 q.push_back(mRoot);
149 while (!q.empty()) {
150 auto t = q.front();
151 q.pop_front();
152 if (visited.count(t))
153 continue;
154
155 visited.insert(t);
156 for (auto dep : inEdgesCpy[t]) {
157 if (!visited.count(dep)) {
158 q.push_back(dep);
159 }
160 }
161 }
162
163 for (auto t : tasks) {
164 if (inEdgesCpy[t].empty()) {
165 q.push_back(t);
166 }
167 }
168 // keep list of tasks without incoming edges;
169 // iteratively remove such tasks from the graph and put them into the schedule
170 while (!q.empty()) {
171 Task::Ptr t = q.front();
172 q.pop_front();
173 if (!visited.count(t)) {
174 // don't put unneeded tasks in the schedule, but process them as usual
175 // so the cycle check still works
176 SPDLOG_LOGGER_INFO(mSLog, "Dropping {:s}", t->toString());
177 } else if (t != mRoot) {
178 sortedTasks.push_back(t);
179 }
180
181 for (auto after : outEdgesCpy[t]) {
182 for (auto edgeIt = inEdgesCpy[after].begin();
183 edgeIt != inEdgesCpy[after].end(); ++edgeIt) {
184 if (*edgeIt == t) {
185 inEdgesCpy[after].erase(edgeIt);
186 break;
187 }
188 }
189 if (inEdgesCpy[after].empty()) {
190 q.push_back(after);
191 }
192 }
193 outEdgesCpy.erase(t);
194 }
195
196 // sanity check: all edges should have been removed, otherwise
197 // the graph had a cycle
198 for (auto t : tasks) {
199 if (!outEdgesCpy[t].empty() || !inEdgesCpy[t].empty())
200 throw SchedulingException();
201 }
202}
203
204void Scheduler::levelSchedule(const Task::List &tasks, const Edges &inEdges,
205 const Edges &outEdges,
206 std::vector<Task::List> &levels) {
207 std::unordered_map<Task::Ptr, int> time;
208
209 for (auto task : tasks) {
210 if (inEdges.find(task) == inEdges.end() || inEdges.at(task).empty()) {
211 time[task] = 0;
212 } else {
213 int maxdist = 0;
214 for (auto before : inEdges.at(task)) {
215 if (time[before] > maxdist)
216 maxdist = time[before];
217 }
218 time[task] = maxdist + 1;
219 }
220 }
221
222 levels.clear();
223 levels.resize(time[tasks.back()] + 1);
224 for (auto task : tasks) {
225 levels[time[task]].push_back(task);
226 }
227}
228
229void BarrierTask::addBarrier(Barrier *b) { mBarriers.push_back(b); }
230
231void BarrierTask::execute(Real time, Int timeStepCount) {
232 if (mBarriers.size() == 1) {
233 mBarriers[0]->wait();
234 } else {
235 for (size_t i = 0; i < mBarriers.size() - 1; i++) {
236 mBarriers[i]->signal();
237 }
238 mBarriers[mBarriers.size() - 1]->wait();
239 }
240}
AttributePointer< AttributeBase > Ptr
Definition Attribute.h:122
std::set< Ptr, AttributeCmp< AttributeBase > > Set
Definition Attribute.h:124
Tasks to be defined by every component.
Definition Task.h:25
std::shared_ptr< Task > Ptr
Definition Task.h:27
std::vector< Ptr > List
Definition Task.h:28
void addBarrier(Barrier *b)
void execute(Real time, Int timeStepCount)
void resolveDeps(CPS::Task::List &tasks, Edges &inEdges, Edges &outEdges)
Definition Scheduler.cpp:92
void writeMeasurements(CPS::String filename)
Write measurement data to file.
Definition Scheduler.cpp:44
void topologicalSort(const CPS::Task::List &tasks, const Edges &inEdges, const Edges &outEdges, CPS::Task::List &sortedTasks)
Simple topological sort, filtering out tasks that do not need to be executed.
static void levelSchedule(const CPS::Task::List &tasks, const Edges &inEdges, const Edges &outEdges, std::vector< CPS::Task::List > &levels)
void readMeasurements(CPS::String filename, std::unordered_map< CPS::String, TaskTime::rep > &measurements)
Read measurement data from file to use it for the scheduling.
Definition Scheduler.cpp:63
static CPS::AttributeBase::Ptr external
Definition Scheduler.h:68
CPS::Task::Ptr mRoot
Definition Scheduler.h:107
TaskTime getAveragedMeasurement(CPS::Task::Ptr task)
Definition Scheduler.h:70
void initMeasurements(const CPS::Task::List &tasks)
Definition Scheduler.cpp:24
std::unordered_map< CPS::Task::Ptr, std::deque< CPS::Task::Ptr > > Edges
Definition Scheduler.h:32
void updateMeasurement(CPS::Task *task, TaskTime time)
Definition Scheduler.cpp:31
std::chrono::steady_clock::duration TaskTime
Time measurement for the task execution.
Definition Scheduler.h:34
CPS::Logger::Log mSLog
Logger.
Definition Scheduler.h:111
CPS::Real Real
Definition Definitions.h:18
CPS::String String
Definition Definitions.h:20
CPS::Int Int
Definition Definitions.h:22
CPS::UInt UInt
Definition Definitions.h:23