-
Notifications
You must be signed in to change notification settings - Fork 0
/
Market.py
165 lines (139 loc) · 6.13 KB
/
Market.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
"""EnergyMarket.py
A multi-independant-processes simulation about the energy market."""
from matplotlib import pyplot as plt
from matplotlib import animation
from multiprocessing import Value, Array, Process
from threading import Lock, Thread, current_thread
from signal import signal, SIGINT, SIGUSR1, SIGUSR2
from sysv_ipc import IPC_CREAT, MessageQueue, NotAttachedError, BusyError
from os import kill, getpid
from random import random
from time import sleep
from queue import Queue, Empty
marketKey = 221
period = 1
def weather(weatherAttributes, exitFlag):
print("[%d] Weather : Init" % getpid())
type(weatherAttributes)
weatherAttributes[0] = 0
weatherAttributes[1] = 0
while not exitFlag.value:
sleep(6)
weatherAttributes[0] = 20 + 5*random() # Temperature
weatherAttributes[1] = 10 + 30*random() # Rain
# print("[%d] Weather update : T = %.2f and R = %.2f" % (getpid(), weatherAttributes[0], weatherAttributes[1]))
print("[%d] Weather : Exit" % getpid())
def external(marketPID, exitFlag):
print("[%d] External : Init" % getpid())
while not exitFlag.value:
sleep(8)
if int(2*random()):
kill(marketPID, SIGUSR1)
# print("[%d] External event : SIGUSR1 sent." % getpid())
if int(2*random()):
kill(marketPID, SIGUSR2)
# print("[%d] External event : SIGUSR2 sent." % getpid())
print("[%d] External : Exit" % getpid())
def marketThread(message, array, lock):
pid, quantity = message.decode().split(':')
with lock:
array.append(int(quantity))
# print("[%d] Market_request (%s) : value added to array" % (getpid(), current_thread().name))
def market(weatherAttributes, prices, exitFlag):
print("[%d] Market (main) : Init" % getpid())
# create handler with a closure, reroute signals, and launch external process
externalEvents = [0, 0]
def market_handler(sig, frame):
if sig == SIGUSR1:
externalEvents[0] = 1
elif sig == SIGUSR2:
externalEvents[1] = 1
signal(SIGUSR1, market_handler)
signal(SIGUSR2, market_handler)
externalProcess = Process(target=external, args=(getpid(),exitFlag))
externalProcess.start()
# create lock that will be passed to many threads to treat each request
sharedLock = Lock()
# create message queues to Homes
queueToHome = MessageQueue(marketKey, IPC_CREAT)
# if queue was not properly deleted, it's still there and we have to do it ourselves
if queueToHome.current_messages > 0:
queueToHome.remove()
queueToHome = MessageQueue(marketKey, IPC_CREAT)
print("[%d] Market (main) : messageQueue created" % getpid())
buying = []
selling = []
idx = 0
price = -1
gamma = 0.90 # long-term attenuation coefficient
alpha = [ -0.052, 0.075, 0.23, -0.07] # modulating coefficient for internal factors: Temperature, Rain, bought, sold
internalEvents = [ 0, 0, 0 , 0]
beta = [ -7, 30 ] # modulating coefficient for external factors: SIGUSR1, SIGUSR2
# print("[%d] Market (main) : all external processes launched" % getpid())
while not exitFlag.value:
sleep(period)
# upon receiving a buying message, we launch a thread
try:
while queueToHome.current_messages > 0:
message, _ = queueToHome.receive(block=False, type=1)
(Thread(target=marketThread, args=(message, buying, sharedLock, ))).start()
except (NotAttachedError, BusyError):
pass
# upon receiving a selling message, we launch a thread
try:
while queueToHome.current_messages > 0:
message, _ = queueToHome.receive(block=False, type=2)
(Thread(target=marketThread, args=(message, selling, sharedLock, ))).start()
except (NotAttachedError, BusyError):
pass
print("[%d] external = %s \tweather = [ %.2f, %.2f ]\tbuying = %s\tselling = %s" % (getpid(), externalEvents, weatherAttributes[0], weatherAttributes[1], buying, selling))
internalEvents = [ weatherAttributes[0], weatherAttributes[1], sum(buying), sum(selling) ]
if price == -1:
print("[%d] Initiating energy price" % getpid())
price = sum([alpha[k]*internalEvents[k] for k in range(len(internalEvents))]) + sum([beta[k]*externalEvents[k] for k in range(len(externalEvents))])
else :
price = gamma*price + sum([alpha[k]*internalEvents[k] for k in range(len(internalEvents))]) + sum([beta[k]*externalEvents[k] for k in range(len(externalEvents))])
if price <= 0:
price = 0.05
prices[idx] = price
idx = (idx+1)%500
#print("In market : "+str(prices[0:20]))
print("[%d] Energy price = %.2f €/kWh" % (getpid(), price))
externalEvents = [0, 0]
buying = []
selling = []
queueToHome.remove()
print("[%d] Market (main) : messageQueue removed" % getpid())
print("[%d] Market (main) : Exit" % getpid())
offset = 0
def gui(prices):
global offset
plt.ion()
fig, plot = plt.subplots()
plot.set_xlabel("Time (in days)")
plot.set_ylabel("Price (in €/kWh)")
#plot.set_xlim((0,50))
while True:
#print(prices[:offset])
plot.plot(prices[:offset])
plt.pause(period)
plt.show()
offset = (offset+1)%500
if __name__ == '__main__':
print("[%d] Main process : Init" % getpid())
# creating shared memory
weatherAttributes = Array('d', range(2))
prices = Array('f', [-1 for k in range(500)])
# proper exit system : shared-variable exitFlag between processes
# and we use a closure to pass exitFlag to global_handler
exitFlag = Value('i', 0)
def global_handler(sig, frame):
if sig == SIGINT:
exitFlag.value = 1
signal(SIGINT, global_handler)
marketProcess = Process(target=market, args=(weatherAttributes, prices, exitFlag,))
weatherProcess = Process(target=weather, args=(weatherAttributes,exitFlag,))
marketProcess.start()
weatherProcess.start()
gui(prices)
print("[%d] Main process : Exit" % getpid())