Debian Codegraph @

docs/source/Manuals/Interfacing/ParallelSimPy/SimPyPP.rst

raw
1 =============================================================
2 Running SimPy on Multiple Processors with **Parallel Python**
3 =============================================================
4
5 .. contents:: Contents
6 :depth: 2
7
8 Introduction
9 =============
10
11 With SimPy 2.0, you can easily increase the performance of your simulation by
12 using `Parallel Python`_ if you have a larger number of independent processors
13 (multiple CPUs or cores). *Parallel Python* can distribute the execution of
14 your SimPy processes to all cores of your CPU and even to other computers. You
15 should read the PP documentation for further information on how this works.
16
17 .. _`Parallel Python`: http://www.parallelpython.com/
18
19 Please, note that *Parallel Python* is not included in the SimPy distribution
20 and needs to be `downloaded <http://www.parallelpython.com/>` and installed
21 separately.
22
23 Examples
24 =============
25
26 Example #1
27 -----------------
28
29 The files PPExample.txt_ and PPExampleProcess.txt_ contain a small example
30 with several car processes. It is important, that processes etc.are not
31 defined in the file that starts the PP job server and executes the jobs,
32 since ``ppserver.submit()`` only takes functions defined in the same file and
33 module names to import, but no classes.
34
35 PPExample.py::
36
37 """
38 Example for SimPy with Parallel Python.
39 """
40
41 import PPExampleProcess
42 from SimPy.Simulation import *
43 import pp
44
45
46 def runSimulation(jobNum, numCars):
47 sim = SimPy.Simulation.Simulation()
48 cars = []
49 for i in range(numCars):
50 car = PPExampleProcess.Car(sim, i * jobNum + i)
51 sim.activate(car, car.run(), at = 0)
52 cars.append(car)
53 sim.simulate(until = 30)
54
55
56 server = pp.Server(ppservers = ())
57 for i in range(4):
58 job = server.submit(
59 runSimulation,
60 (i, 2),
61 (),
62 ('SimPy.Simulation', 'PPExampleProcess'))
63 job()
64
65 PPExampleProcess.py::
66
67 from SimPy.Simulation import *
68
69 class Car(Process):
70
71 def __init__(self, sim, id):
72 Process.__init__(self, sim = sim)
73 self.id = id
74
75 def run(self):
76 while True:
77 yield hold, self, 10
78 print 'Car #%i at t = %i' % (self.id, self.sim.now())
79
80 .. _PPExample.txt: ../../../_static/PPExample.txt
81 .. _PPExampleProcess.txt: ../../../_static/PPExampleProcess.txt
82
83 The simulated process in this case is a simple car, that holds for ten steps
84 and then prints the current simulation time. Obviously, each car process is
85 independent from the other ones. Thus if we want to simulate a great number of
86 cars, we can easily distribute the processes to many CPU cores and others
87 computers in our network.
88
89 PP pickles everything it sends to other cores/computers. Since SimPy is
90 currently not pickleable, you cannot submit ``Simulation.simulate()`` to the
91 PPServer. In this example ``runSimulation`` is defined and submitted to the
92 server. The code within it will be executed on each core/computer. In the
93 example we create four simulation jobs with two cars for each job.
94
95 Run PPExample.py to execute the example.
96
97 Example #2
98 ------------
99
100 Files simulator.txt_ and processes.txt_ contain an example that
101 simulates refrigerators in single-thread and in parallel simulation mode.
102
103 Class ``Simulator`` simulates a number of fridges and gets the resulting data.
104
105 Class ``ParallelSimulator`` simulates a number of fridges and gets the resulting data.
106 A number of jobs will be created that use all available
107 CPU cores or even other computers.
108
109 To use clustering, ParallelPython needs to be installed on all computers
110 and the server demon "ppserver.py" must be started. The list of the servers'
111 IP addresses must then be passed to the constructor of this class.
112
113 Run ``simulator.py`` to execute this example.
114
115 .. _simulator.txt: ../../../_static/simulator.txt
116 .. _processes.txt: ../../../_static/processes.txt
117
118 File simulator.py::
119
120 # coding=utf8
121 """
122 The fridge simulation
123
124 @author: Stefan Scherfke
125 @contact: stefan.scherfke at uni-oldenburg.de
126 """
127
128 from time import clock
129 import logging
130
131 from SimPy.Simulation import Simulation, activate, initialize, simulate
132 import pp
133
134 from processes import Fridge, FridgeObserver
135
136 log = logging.getLogger('Simulator')
137
138 class Simulator(object):
139 """
140 This class simulates a number of fridges and gets the resulting data.
141 """
142
143 def __init__(self, numFridges, tau, aggSteps, duration):
144 """
145 Setup the simulation with the specified number of fridges.
146
147 Tau specifies the simulation step for each frige. Furthermore the
148 observer will collect data each tau. Collected data
149 will be aggregated at the end of each aggSteps simulation steps.
150
151 @param numFridges: The number of simulated fridges
152 @type numFridges: unsigned int
153 @param tau: simulation step size for collecting data and simulating
154 the fridge
155 @type tau: float
156 @param aggSteps: Collected data will be aggregated each aggSteps
157 simulation steps. Signals interval will be
158 tau * aggSteps
159 @type aggSteps: unsigned int
160 @param duration: Duration of the simulation in hours
161 @type duration: unsigned int
162 """
163 log.info('Initializing simulator ...')
164 self.simEnd = duration
165 self.sim = Simulation()
166
167 fridgeProperties = {'tau': tau}
168 self._fridges = []
169 for i in range(numFridges):
170 fridge = Fridge(self.sim, **fridgeProperties)
171 self._fridges.append(fridge)
172 self._observer = FridgeObserver(self.sim, self._fridges, tau, aggSteps)
173
174 def simulate(self):
175 """
176 Initialize the system, start the simulation and return the collected
177 data.
178
179 @return: The fridgerators consumption after each aggregation
180 """
181 log.info('Running simulation ...')
182 self.sim.initialize()
183 for fridge in self._fridges:
184 self.sim.activate(fridge, fridge.run(), at = 0)
185 self.sim.activate(self._observer, self._observer.run(), at = 0)
186 self.sim.simulate(until = self.simEnd)
187
188 log.info('Simulation run finished.')
189 return self._observer.getData()
190
191
192 class ParallelSimulator(object):
193 """
194 This class simulates a number of fridges and gets the resulting data.
195 Unlike simulator, a number of jobs will be created that use all availale
196 CPU cores or even other computers.
197
198 To use clustering, ParallelPython needs to be installed on all computers
199 and the server demon "ppserver.py" must be started. The list of the server's
200 IPs must then be passed to the constructor of this class.
201 """
202
203 def __init__(self, numFridges, tau, aggSteps, duration,
204 jobSize = 100, servers = ()):
205 """
206 Setup the simulation with the specified number of fridges. It will be
207 split up in several parallel jobs, each with the specified number of
208 jobs.
209
210 Tau specifies the simulation step for each frige. Furthermore the
211 observer will collect data each tau. Collected data
212 will be aggregated at the end of each aggSteps simulation steps.
213
214 @param numFridges: The number of simulated fridges
215 @type numFridges: unsigned int
216 @param tau: simulation step size for collecting data and simulating
217 the fridge
218 @type tau: float
219 @param aggSteps: Collected data will be aggregated each aggSteps
220 simulation steps. Signals interval will be
221 tau * aggSteps
222 @type aggSteps: unsigned int
223 @param duration: Duration of the simulation
224 @type duration: unsigned int
225 @param jobSize: The number of friges per job, defaults to 100.
226 @type jobSize: unsigned int
227 @param servers: A list of IPs from on which the simulation shall be
228 executed. Defaults to "()" (use only SMP)
229 @type servers: tuple of string
230 """
231 log.info('Initializing prallel simulation ...')
232
233 self._jobSize = jobSize
234 self._servers = servers
235 self._numFridges = numFridges
236 self._tau = tau
237 self._aggSteps = aggSteps
238 self.simEnd = duration
239
240 def simulate(self):
241 """
242 Create some simulation jobs, run them and retrieve their results.
243
244 @return: The fridgerators consumption after each aggregation
245 """
246 log.info('Running parallel simulation ...')
247 oldLevel = log.getEffectiveLevel() # pp changes the log level :(
248 jobServer = pp.Server(ppservers = self._servers)
249
250 # Start the jobs
251 remainingFridges = self._numFridges
252 jobs = []
253 while remainingFridges > 0:
254 jobs.append(jobServer.submit(self.runSimulation,
255 (min(self._jobSize, remainingFridges),),
256 (),
257 ("logging", "SimPy.Simulation", "processes")))
258 remainingFridges -= self._jobSize
259 log.info('Number of jobs for simulation: %d' % len(jobs))
260
261 # Add each job's data
262 pSum = [0] * int((60 / self._aggSteps) * self.simEnd)
263 for job in jobs:
264 data = job()
265 for i in range(len(data)):
266 pSum[i] += data[i]
267 for s in pSum:
268 s /= len(jobs)
269
270 log.setLevel(oldLevel)
271 log.info('Parallel simulation finished.')
272 return pSum
273
274 def runSimulation(self, numFridges):
275 """
276 Create a job with the specified number of fridges and controllers and
277 one observer. Simulate this and return the results.
278
279 @param numFridges: The number of fridges to use for this job
280 @type numFridges: unsigned int
281 @return: A list with the aggregated fridge consumption
282 """
283 sim = SimPy.Simulation.Simulation()
284 sim.initialize()
285
286 fridgeProperties = {'tau': self._tau}
287 fridges = []
288 for i in range(numFridges):
289 fridge = processes.Fridge(sim, **fridgeProperties)
290 fridges.append(fridge)
291 sim.activate(fridge, fridge.run(), at = 0)
292 observer = processes.FridgeObserver(sim,
293 fridges, self._tau, self._aggSteps)
294 sim.activate(observer, observer.run(), at = 0)
295
296 sim.simulate(until = self.simEnd)
297 return observer.getData()
298
299
300 if __name__ == '__main__':
301 logging.basicConfig(
302 level = logging.INFO,
303 format = '%(asctime)s %(levelname)8s: %(name)s: %(message)s')
304
305 numFridges = 5000
306 tau = 1./60
307 aggStep = 15
308 duration = 4 + tau
309
310 sim = Simulator(numFridges, tau, aggStep, duration)
311 data = sim.simulate()
312 log.info('Results: ' + str(data))
313
314 servers = ()
315 sim = ParallelSimulator(numFridges, tau, aggStep, duration, 100, servers)
316 data = sim.simulate()
317 log.info('Results: ' + str(data))
318
319 File process.py::
320
321 # coding=utf8
322 """
323 This file contains classes for simulating, controlling and observing a fridge.
324
325 @author: Stefan Scherfke
326 @contact: stefan.scherfke at uni-oldenburg.de
327 """
328
329 from math import exp
330 import logging
331 import random
332
333 from SimPy.Simulation import Process, Simulation, \
334 activate, hold, initialize, now, simulate
335
336 log = logging.getLogger('Processes')
337
338 class Fridge(Process):
339 """
340 This class represents a simulated fridge.
341
342 It's temperature T for and equidistant series of time steps is computed by
343 $T_{i+1} = \epsilon \cdot T_i + (1 - \epsilon) \cdot \left(T^O - \eta
344 \cdot \frac{q_i}{A}\right)$ with $\epsilon = e^{-\frac{\tau A}{m_c}}$.
345 """
346
347 def __init__(self, sim, T_O = 20.0, A = 3.21, m_c = 15.97, tau = 1.0/60,
348 eta = 3.0, q_i = 0.0, q_max = 70.0,
349 T_i = 5.0, T_range = [5.0, 8.0], noise = False):
350 """
351 Init all required variables.
352
353 @param sim: The SimPy simulation this process belongs to
354 @type sim: SimPy.Simulation
355 @param T_O: Outside temperature
356 @param A: Insulation
357 @param m_c: Thermal mass/thermal storage capacity
358 @param tau: Time span between t_i and t_{i+1}
359 @param eta: Efficiency of the cooling device
360 @param q_i: Initial/current electrical power
361 @param q_max: Power required during cool-down
362 @param T_i: Initial/current temperature
363 @param T_range: Allowed range for T_i
364 @param noise: Add noise to the fridge's parameters, if True
365 @type noise: bool
366 """
367 Process.__init__(self, sim = sim)
368 self.T_O = T_O
369 self.A = A
370 self.m_c = random.normalvariate(20, 4.5) if noise else m_c
371 self.tau = tau
372 self.eta = eta
373 self.q_i = q_i
374 self.q_max = q_max
375 self.T_i = random.uniform(T_range[0], T_range[1]) if noise else T_i
376 self.T_range = T_range
377
378 def run(self):
379 """
380 Calculate the fridge's temperature for the current time step.
381 """
382 while True:
383 epsilon = exp(-(self.tau * self.A) / self.m_c)
384 self.T_i = epsilon * self.T_i + (1 - epsilon) \
385 * (self.T_O - self.eta * (self.q_i / self.A))
386 if self.T_i >= self.T_range[1]:
387 self.q_i = self.q_max # Cool down
388 elif self.T_i <= self.T_range[0]:
389 self.q_i = 0.0 # Stop cooling
390 log.debug('T_i: %2.2f°C at %.2f' % (self.T_i, self.sim.now()))
391 yield hold, self, self.tau
392
393 def coolDown(self):
394 """
395 Start cooling down now!
396 """
397 self.q_i = self.q_max
398
399
400 class FridgeObserver(Process):
401 """
402 This process observes the temperature and power consumption of a set of
403 fridges.
404 """
405
406 def __init__(self, sim, fridges, tau, aggSteps):
407 """
408 Init the observer.
409
410 @param sim: The SimPy simulation this process belongs to
411 @type sim: SimPy.Simulation
412 @param fridges: A list of fridges to be observed
413 @type fridges: tuple of Fridge
414 @param tau: Time interval for observations
415 @type tau: float
416 @param aggSteps: Specifies after how many timesteps tau the collected
417 data is aggregated and stored.
418 @type aggSteps: int
419 """
420 Process.__init__(self, sim = sim)
421 self._fridges = fridges
422 self._tau = tau
423 self._aggSteps = aggSteps
424 self._data = []
425
426 def run(self):
427 """
428 Start observation
429 """
430 aggSteps = 0
431 consumption = 0
432 lastProgUpdate = 0
433 while True:
434 prog = self.sim.now() * 100 / self.sim._endtime
435 if int(prog) > lastProgUpdate:
436 log.info('Progress: %d%%' % prog)
437 lastProgUpdate = prog
438 if (aggSteps >= self._aggSteps):
439 log.debug('Aggregating at %.2f' % self.sim.now())
440 self._data.append(consumption/self._aggSteps)
441 consumption = 0
442 aggSteps = 0
443
444 for fridge in self._fridges:
445 consumption += fridge.q_i
446 aggSteps += 1
447 yield hold, self, self._tau
448
449 def getData(self):
450 """
451 Return the collected data
452
453 @return: a list with the collected data
454 """
455 return self._data
456
457
458 if __name__ == '__main__':
459 logging.basicConfig(
460 level = logging.DEBUG,
461 format = '%(levelname)-8s %(asctime)s %(name)s: %(message)s')
462
463 tau = 1./60 # Step size 1min
464 aggSteps = 15 # Aggregate consumption in 15min blocks
465 params = {'tau': tau}
466
467 sim = Simulation()
468
469 fridge = Fridge(sim, **params)
470 observer = FridgeObserver(sim, [fridge], tau, aggSteps)
471
472 sim.activate(fridge, fridge.run(), at = 0)
473 sim.activate(observer, observer.run(), at = 0)
474 sim.simulate(until = 4 + tau)
475 print observer.getData()
476
477