-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCacheNetwork.py
1979 lines (1655 loc) · 81.1 KB
/
CacheNetwork.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python
'''
A Cache Network
'''
import argparse
import itertools
import logging
import networkx
import numpy as np
import pandas as pd
# from statsmodels.distributions.empirical_distribution import ECDF
import pickle
import random
import time
from abc import ABCMeta, abstractmethod
from cvxopt import spmatrix, matrix
from cvxopt.solvers import lp
from networkx import Graph, DiGraph, shortest_path
from numpy.linalg import matrix_rank
from scipy.stats import rv_discrete
from simpy import *
import topologies
from Caches import PriorityCache, EWMACache, LMinimalCache, Slot
class CONFIG(object):
QUERY_MESSAGE_LENGTH = 0.0
RESPONSE_MESSAGE_LENGTH = 0.0
EXPLORE_MESSAGE_LENGTH = 0.0
EXPLORE_RESPONSE_MESSAGE_LENGTH = 0.0
WEIGHT_EXPLORE_MESSAGE_LENGTH = 0.0
WEIGHT_EXPLORE_RESPONSE_MESSAGE_LENGTH = 0.0
def pp(l):
return ' '.join(map(str, l))
class Demand:
""" A demand object. Contains the item requested, the path a request follows, as a list, and the
rate with which requests are generated. Tallies count various metrics.
Attributes:
item: the id of the item requested
path: a list of nodes to be visited
rate: the rate with which this request is generated
query_source: first node on the path
item_source: last node on the path
"""
def __init__(self, item, path, rate):
""" Initialize a new request.
"""
self.item = item
self.path = path
self.rate = rate
self.query_source = path[0]
self.item_source = path[-1]
def __str__(self):
return Demand.__repr__(self)
def __repr__(self):
return 'Demand(' + ','.join(map(str, [self.item, self.path, self.rate])) + ')'
def succ(self, node):
""" The successor of a node in the path.
"""
path = self.path
if node not in path:
return None
i = path.index(node)
if i + 1 == len(path):
return None
else:
return path[i + 1]
def pred(self, node):
"""The predecessor of a node in the path.
"""
path = self.path
if node not in path:
return None
i = path.index(node)
if i - 1 < 0:
return None
else:
return path[i - 1]
class Message(object):
"""A Message object.
Attributes:
header: the header of the message (e.g., query_message, response_message
payload: the payload, can be set by the programmer
length: length, to be used in transmission delay calculations
stats: statistics collected as the message traverses nodes
u_bit: indicates if the message is going upstream or downstream
"""
def __init__(self, header, payload, length, stats, u_bit):
self.header = header
self.payload = payload
self.length = length
self.u_bit = u_bit
if stats == None:
self.stats = {}
self.stats['delay'] = 0.0
self.stats['hops'] = 0.0
self.stats['weight'] = 0.0
self.stats['downweight'] = 0.0
else:
self.stats = stats
def __str__(self):
return Message.__repr__(self)
def __repr__(self):
return pp(['Message(', self.header, ',', self.payload, ',', self.length, ',', self.stats, ')'])
class QueryMessage(Message):
"""
A query message.
"""
def __init__(self, d, query_id, stats=None):
Message.__init__(self, header=("QUERY", d, query_id), payload=None, length=CONFIG.QUERY_MESSAGE_LENGTH,
stats=stats, u_bit=True)
class ResponseMessage(Message):
"""
A response message.
"""
def __init__(self, d, query_id, stats=None):
Message.__init__(self, header=("RESPONSE", d, query_id), payload=None, length=CONFIG.RESPONSE_MESSAGE_LENGTH,
stats=stats, u_bit=False)
class CacheNetwork(DiGraph):
"""A cache network.
A cache network comprises a weighted graph and a list of demands. Each node in the graph is associated with a cache of finite capacity.
NetworkCaches must support a message receive operation, that determines how they handle incoming messages.
The cache networks handles messaging using simpy stores and processes. In partiqular, each cache, edge and demand is associated with a
Store object, that receives, stores, and processes messages from simpy processes.
In more detail:
- Each demand is associated with two processes, one that generates new queries, and one that monitors and logs completed queries (existing only for logging purposes)
- Each cache/node is associated with a process that receives messages, and processes them, and produces new messages to be routed, e.g., towards neigboring edges
- Each edge is associated with a process that receives messages to be routed over the edge, and delivers them to the appropriate target node.
During "delivery", messages are (a) delayed, according to configuration parameters, and (b) statistics about them are logged (e.g., number of hops, etc.)
Finally, a global monitoring process computes the social welfare at poisson time intervals.
"""
def __init__(self, G, cacheGenerator, demands, item_sources, capacities, weights, delays, warmup=0,
monitoring_rate=1.0, demand_change_rate=0, demand_min=1.0, demand_max=1.0, trace_params=None):
self.env = Environment()
self.warmup = warmup
self.demandstats = {}
self.sw = {}
self.funstats = {}
self.optstats = {}
self.monitoring_rate = monitoring_rate
self.demand_change_rate = demand_change_rate
self.demand_min = demand_min
self.demand_max = demand_max
self.capacities = capacities
DiGraph.__init__(self, G)
for x in self.nodes():
self.node[x]['cache'] = cacheGenerator(capacities[x], x)
self.node[x]['pipe'] = Store(self.env)
for e in self.edges():
x = e[0]
y = e[1]
self.edge[x][y]['weight'] = weights[e]
self.edge[x][y]['delay'] = delays[e]
self.edge[x][y]['pipe'] = Store(self.env)
self.demands = {}
self.item_set = set()
for d in demands:
self.demands[d] = {}
self.demands[d]['pipe'] = Store(self.env)
self.demands[d]['queries_spawned'] = 0
self.demands[d]['queries_satisfied'] = 0
self.demands[d]['queries_logged'] = 0.0
self.demands[d]['pending'] = set([])
self.demands[d]['stats'] = {}
self.item_set.add(d.item)
for item in item_sources:
for source in item_sources[item]:
self.node[source]['cache'].makePermanent(item) ###THIS NEEDS TO BE IMPLEMENTED BY THE NETWORKED CACHE
if trace_params is not None:
trace, item_demands_dic, rate_of_requests = trace_params
self.env.process(self.spawn_trace_process(demands, trace, item_demands_dic, rate_of_requests))
for d in self.demands:
self.env.process(self.demand_monitor_process(d))
else:
for d in self.demands:
self.env.process(self.spawn_queries_process(d))
self.env.process(self.demand_monitor_process(d))
if self.demand_change_rate > 0.0:
self.env.process(self.demand_change_process(d))
if self.demand_change_rate > 0.0:
self.env.process(self.compute_opt_process())
for e in self.edges():
self.env.process(self.message_pusher_process(e))
for x in self.nodes():
self.env.process(self.cache_process(x))
self.env.process(self.monitor_process())
def run(self, finish_time):
logging.info('Simulating..')
self.env.run(until=finish_time)
logging.info('..done simulating')
def spawn_trace_process(self, demands, trace, item_demands_dic, rate_of_requests):
i = 0
while True:
# print(i / trace.size * 100)
item = trace[i]
uniform_choices = np.random.choice(item_demands_dic[item])
d = demands[uniform_choices]
i += 1
logging.debug(pp([self.env.now, ':New query for', d.item, 'to follow', d.path]))
_id = self.demands[d]['queries_spawned']
qm = QueryMessage(d, _id) # create a new query message at the query_source
self.demands[d]['pending'].add(_id)
self.demands[d]['queries_spawned'] += 1
wem = WeightExploreMessage(d, _id, d.query_source)
if _id == 0:
yield self.node[d.query_source]['pipe'].put((wem, (d, d.query_source)))
yield self.env.timeout(0.1)
yield self.node[d.query_source]['pipe'].put((qm, (d, d.query_source)))
yield self.env.timeout(rate_of_requests) # random.expovariate(d.rate))
def spawn_queries_process(self, d):
""" A process that spawns queries.
Queries are generated according to a Poisson process with the appropriate rate. Queries generated are pushed to the query source node.
"""
while True:
logging.debug(pp([self.env.now, ':New query for', d.item, 'to follow', d.path]))
_id = self.demands[d]['queries_spawned']
qm = QueryMessage(d, _id) # create a new query message at the query_source
self.demands[d]['pending'].add(_id)
self.demands[d]['queries_spawned'] += 1
wem = WeightExploreMessage(d, _id, d.query_source)
if _id == 0:
yield self.node[d.query_source]['pipe'].put((wem, (d, d.query_source)))
yield self.env.timeout(0.1)
yield self.node[d.query_source]['pipe'].put((qm, (d, d.query_source)))
yield self.env.timeout(random.expovariate(d.rate))
def demand_monitor_process(self, d):
""" A process monitoring statistics about completed requests.
"""
while True:
msg = yield self.demands[d]['pipe'].get()
lab, dem, query_id = msg.header
stats = msg.stats
now = self.env.now
if lab != "RESPONSE":
logging.warning(pp([now, ':', d, 'received a non-response message:', msg]))
continue
if dem is not d:
logging.warning(pp([now, ':', d, 'received a message', msg, 'aimed for demand', dem]))
continue
if query_id not in self.demands[d]['pending']:
logging.warning(pp(['Query', query_id, 'of', d, 'satisfied but not pending']))
continue
else:
self.demands[d]['pending'].remove(query_id)
logging.debug(pp(['Query', query_id, 'of', d, 'satisfied with stats', stats]))
self.demands[d]['queries_satisfied'] += 1
if now >= self.warmup:
self.demands[d]['queries_logged'] += 1.0
for key in stats:
if key in self.demands[d]['stats']:
self.demands[d]['stats'][key] += stats[key]
else:
self.demands[d]['stats'][key] = stats[key]
def demand_change_process(self, d):
""" A process changing the demand periodically
"""
while True:
yield self.env.timeout(1. / self.demand_change_rate)
new_rate = random.uniform(self.demand_min, self.demand_max)
logging.info(pp(
[self.env.now, ':Demand for ', d.item, 'following', d.path, 'changing rate from', d.rate, 'to',
new_rate]))
d.rate = new_rate
def compute_opt_process(self):
''' Process recomputing optimal values after demand changes. Used only if demand changes periodically
'''
yield self.env.timeout(
0.01 * 1. / self.demand_change_rate) # Tiny offset, to make sure all demands have been updated by measurement time
while True:
Y, res = self.minimizeRelaxation()
logging.info(pp([self.env.now, ': Optimal Relaxation is: ', self.relaxation(Y)]))
logging.info(
pp([self.env.now, ': Expected caching gain at relaxation point is: ', self.expected_caching_gain(Y)]))
optimal_stats = {}
optimal_stats['res'] = res
optimal_stats['Y'] = Y
optimal_stats['L'] = self.relaxation(Y)
optimal_stats['F'] = self.expected_caching_gain(Y)
self.optstats[self.env.now] = optimal_stats
yield self.env.timeout(1. / self.demand_change_rate)
def message_pusher_process(self, e):
""" A process handling message transmissions over edges.
It delays messages, accoding to delay specs, and increments stat counters in them.
"""
while True:
msg = yield self.edge[e[0]][e[1]]['pipe'].get()
logging.debug(pp([self.env.now, ':', 'Pipe at', e, 'pushing', msg]))
time_before = self.env.now
yield self.env.timeout(msg.length * random.expovariate(1 / self.edge[e[0]][e[1]]['delay']))
delay = self.env.now - time_before
msg.stats['delay'] += delay
msg.stats['hops'] += 1.0
msg.stats['weight'] += self.edge[e[0]][e[1]]['weight']
if not msg.u_bit:
# msg.stats['downweight'] += self.edge[e[0]][e[1]]['weight'] + self.edge[e[1]][e[0]]['weight']
msg.stats['downweight'] += self.edge[e[0]][e[1]]['weight']
# if msg.stats['downweight']*2 > msg.stats['weight'] and msg.header[0] == 'RESPONSE':
# print('error')
logging.debug(pp([self.env.now, ':', 'Pipe at', e, 'delivering', msg]))
self.node[e[1]]['pipe'].put((msg, e))
def cache_process(self, x):
"""A process handling messages sent to caches.
It is effectively a wrapper for a receive call, made to a NetworkedCache object.
"""
while True:
(msg, e) = yield self.node[x]['pipe'].get()
generated_messages = self.node[e[1]]['cache'].receive(msg, e,
self.env.now) # THIS NEEDS TO BE IMPLEMENTED BY THE NETWORKED CACHE!!!!
if generated_messages is not None:
for (new_msg, new_e) in generated_messages:
if new_e[1] in self.demands:
yield self.demands[new_e[1]]['pipe'].put(new_msg)
else:
if not new_e[1] is None:
yield self.edge[new_e[0]][new_e[1]]['pipe'].put(new_msg)
else:
logging.error(pp([self.env.now, ':', 'Node', x, 'sending message to nowhere!']))
def cachesToMatrix(self):
"""Constructs a matrix containing cache information.
"""
zipped = []
n = len(self.nodes())
m = max(len(self.item_set), max(self.item_set) + 1)
for x in self.nodes():
for item in self.node[x]['cache']:
zipped.append((1, x, item))
zipped = list(set(zipped))
val, I, J = list(zip(*zipped))
return spmatrix(np.array(val), np.array(I), np.array(J), size=(n, m))
def statesToMatrix(self):
"""Constructs a matrix containing marginal information. This assumes that caches contain a state() function, capturing maginals. Only LMin implements this
"""
zipped = []
n = len(self.nodes())
m = max([d.item for d in self.demands]) + 1
Y = matrix()
for x in self.nodes():
for item in self.node[x]['cache'].non_zero_state_items():
zipped.append((self.node[x]['cache'].state(item), x, item))
val, I, J = list(zip(*zipped))
return spmatrix(np.array(val), np.array(I), np.array(J), size=(n, m))
def social_welfare(self):
""" Function computing the social welfare.
"""
dsw = 0.0
hsw = 0.0
wsw = 0.0
sumrate = 0.0
for d in self.demands:
item = d.item
rate = d.rate
sumrate += rate
x = d.query_source
while not (item in self.node[x][
'cache'] or x is d.item_source): # THIS NEEDS TO BE IMPLEMENTED BY THE NETWORKED CACHE!!!
s = d.succ(x)
dsw += rate * (CONFIG.QUERY_MESSAGE_LENGTH * self.edge[x][s]['delay'] + CONFIG.RESPONSE_MESSAGE_LENGTH *
self.edge[s][x]['delay'])
wsw += rate * (self.edge[x][s]['weight'] + self.edge[s][x]['weight'])
hsw += rate * (2)
x = s
return (dsw / sumrate, hsw / sumrate, wsw / sumrate)
def caching_gain(self):
""" Function computing the caching gain under the present caching situation
"""
X = self.cachesToMatrix()
return self.expected_caching_gain(X)
def cost_without_cache(self):
cost = 0.0
sum_queries = 0.0
for d in self.demands:
item = d.item
queries_logged = self.demands[d]['queries_logged']
sum_queries += queries_logged
x = d.query_source
s = d.succ(x)
while s is not None:
cost += queries_logged * (self.edge[s][x]['weight'] + self.edge[x][s]['weight'])
x = s
s = d.succ(x)
return cost / sum_queries
def cost_without_caching(self):
""" Function computing the cost of recovering all items demanded from respective sources."""
cost = 0.0
sumrate = 0.0
for d in self.demands:
item = d.item
rate = d.rate
sumrate += rate
x = d.query_source
s = d.succ(x)
while s is not None:
cost += rate * (self.edge[s][x]['weight'] + self.edge[x][s]['weight'])
x = s
s = d.succ(x)
return cost / sumrate
def expected_caching_gain(self, Y):
""" Function computing the expected caching gain under marginals Y, presuming product form. Also computes deterministic caching gain if Y is integral.
"""
ecg = 0.0
sumrate = 0.0
for d in self.demands:
item = d.item
rate = d.rate
sumrate += rate
x = d.query_source
s = d.succ(x)
prodsofar = 1 - Y[int(x), int(item)]
while s is not None:
ecg += rate * (self.edge[s][x]['weight'] + self.edge[x][s]['weight']) * (1 - prodsofar)
x = s
s = d.succ(x)
prodsofar *= 1 - Y[int(x), int(item)]
return ecg / sumrate
def relaxation(self, Y):
""" Function computing the relaxation of caching gain under marginals Y. Relaxation equals deterministic caching gain if Y is integral.
"""
rel = 0.0
sumrate = 0.0
for d in self.demands:
item = d.item
rate = d.rate
sumrate += rate
x = d.query_source
s = d.succ(x)
sumsofar = Y[int(x), int(item)]
while s is not None:
rel += rate * (self.edge[s][x]['weight'] + self.edge[x][s]['weight']) * min(1.0, sumsofar)
x = s
s = d.succ(x)
sumsofar += Y[int(x), int(item)]
return rel / sumrate
def demand_stats(self):
""" Computed stats across demands.
"""
stats = {}
queries_logged = 0.0
rate = 0.0
for d in self.demands:
queries_logged += self.demands[d]['queries_logged']
for key in self.demands[d]['stats']:
if key in stats:
stats[key] += self.demands[d]['stats'][key]
else:
stats[key] = self.demands[d]['stats'][key]
for key in stats:
stats[key] = stats[key] / queries_logged
return stats
def monitor_process(self):
X_prev = None
uc = 0
while True:
now = self.env.now
if now >= self.warmup:
self.sw[now] = self.social_welfare()
self.demandstats[now] = self.demand_stats()
X = self.cachesToMatrix()
if X_prev is not None:
diff = np.array((X - X_prev).V).flatten()
uc += np.sum(diff[diff > 0])
X_prev = X
ecg = self.expected_caching_gain(X)
rel = self.relaxation(X)
etot = self.cost_without_caching()
esw = etot - ecg
tot = self.cost_without_cache()
self.funstats[now] = (ecg, rel, esw, etot, tot, uc)
logging.info(pp(
[now, ':', 'DSW = %f, HSW = %f, WSW = %f' % self.sw[now], ', DEMSTATS =', self.demandstats[now],
'FUNSTATS =', self.funstats[now], 'tacg=',
self.funstats[now][4] - self.demandstats[now]['weight']]))
try:
# if True:
Y = self.statesToMatrix()
secg = self.expected_caching_gain(Y)
srel = self.relaxation(Y)
self.funstats[now] += (secg, srel)
logging.info(pp([now, ': SECG=', secg, 'SREL=', srel]))
except AttributeError:
logging.debug(pp([now, ": No states in this class"]))
# M=self.cachesToMatrix()
# formatted = [ (i,j,'*') if self.node[i]['cache'].isPermanent(j) else (i,j) for i,j,v in zip(M.I,M.J,M.V) ]
# logging.info(str(sorted(formatted)))
yield self.env.timeout(random.expovariate(self.monitoring_rate))
def minimizeRelaxation(self):
n = len(self.nodes())
m = max([d.item for d in self.demands]) + 1
number_of_placement_variables = n * m
def position(node, item):
return node * m + item
A = []
b = []
row = 0
# Permanent set constraints
logging.debug('Creating permanent set constaints...')
row = 0
for x in self.nodes():
perm_set = self.node[x]['cache'].perm_set()
if len(perm_set) > 0:
for item in perm_set:
A += [(1.0, row, position(x, item))]
b += [1.0]
row += 1
logging.debug('...done. Created %d constraints' % row)
total_equality_constraints = row
G = []
h = []
# Capacity constraints
logging.debug('Creating capacity constaints...')
G += [(1.0, x, position(x, item)) for item in range(m) for x in self.nodes()]
h += [self.node[x]['cache'].capacity() + len(self.node[x]['cache'].perm_set()) for x in self.nodes()]
# h += [ self.node[x]['cache'].capacity() for x in self.nodes()]
logging.debug('...done at %d rows' % len(h))
row = n
t = number_of_placement_variables
# t's smaller than sums of y_vi's in path
logging.debug('Creating t up constraints...')
for d in self.demands:
item = d.item
path = d.path
sofar = []
for v in path:
if len(sofar) > 0:
for u in sofar:
G += [(-1.0, row, position(u, item))]
G += [(1.0, row, t)]
h += [0.0]
row += 1
t += 1
sofar += [v]
logging.debug('...done at %d rows' % row)
total_ts = t - number_of_placement_variables
# t's smaller than 1.0
logging.debug('Creating t ll one constraints...')
t = number_of_placement_variables
while t < (number_of_placement_variables + total_ts):
G += [(1.0, row, t)]
h += [1.0]
row += 1
t += 1
logging.debug('...done at %d rows' % row)
# y's less than 1
logging.debug('Creating y ll one gg 0 constraints...')
y = 0
while y < number_of_placement_variables:
G += [(1.0, row, y)]
h += [1.0]
row += 1
G += [(-1.0, row, y)]
h += [0.0]
row += 1
y += 1
logging.debug('...done at %d rows' % row)
total_inequality_constraints = row
# objective
logging.debug('Creating objective vector...')
c = number_of_placement_variables * [0]
for d in self.demands:
rate = d.rate
path = d.path
x = d.query_source
s = d.succ(x)
while s is not None:
c += [-rate * (self.edge[s][x]['weight'] + self.edge[x][s]['weight'])]
x = s
s = d.succ(x)
logging.debug('...done at %d terms' % len(c))
val, I, J = list(zip(*A))
A = spmatrix(np.array(val), np.array(I), np.array(J),
size=(total_equality_constraints, number_of_placement_variables + total_ts))
b = matrix(b)
val, I, J = list(zip(*G))
G = spmatrix(np.array(val), np.array(I), np.array(J),
size=(total_inequality_constraints, number_of_placement_variables + total_ts))
h = matrix(h)
c = matrix(c)
logging.debug('c has length %d ' % len(c))
logging.debug('G has dims %d x %d and matrix_rank ' % G.size + str(matrix_rank(G)))
logging.debug('h has length %d ' % len(h))
logging.debug('A has dims %d x %d and matrix_rank' % A.size + str(matrix_rank(A)))
logging.debug('b has length %d ' % len(b))
res = lp(c, G, h, A,
b) # , primalstart={'x':matrix(np.zeros(c.size)*1.e-99),'s':matrix( total_inequality_constraints*[1.e-20])})
opt = res['x'][:number_of_placement_variables]
return np.reshape(opt, (n, m), order='C'), res
def cache_gain(self, Y):
""" Function computing the expected caching gain under marginals Y, presuming product form. Also computes deterministic caching gain if Y is integral.
"""
ecg = 0.0
sum_queries = 0.0
for d in self.demands:
item = d.item
queries_logged = self.demands[d]['queries_logged']
sum_queries += queries_logged
x = d.query_source
s = d.succ(x)
prodsofar = 1 - Y[int(x), int(item)]
while s is not None:
ecg += queries_logged * (self.edge[s][x]['weight'] + self.edge[x][s]['weight']) * (1 - prodsofar)
x = s
s = d.succ(x)
prodsofar *= 1 - Y[int(x), int(item)]
return ecg / sum_queries
def sampleCache(self, G, colors):
S = {}
for v in G:
S[v] = {}
for j in G[v]:
if colors[v][j] in G[v][j]:
S[v][j] = G[v][j][colors[v][j]]
return S
def SlotSetToMatrix(self, S):
"""Constructs a matrix containing cache information.
"""
zipped = []
n = len(self.nodes())
m = max(len(self.item_set), max(self.item_set) + 1)
for v in S:
for j in S[v]:
zipped.append((1, v, S[v][j]))
if zipped == []:
return matrix(0, (n, m))
zipped = list(set(zipped))
val, V, I = list(zip(*zipped))
return spmatrix(np.array(val), np.array(V), np.array(I), size=(n, m))
def TBGRY(self, number_colors, samples):
def findMax(G, v, j, m, color_vector):
max_F = 0
argmax_i = 0
for i in self.item_set:
CacheGain = 0
G[v][j][m] = i
for t in color_vector:
S = self.sampleCache(G, color_vector[t])
Y = self.SlotSetToMatrix(S)
CacheGain += self.cache_gain(Y)
if CacheGain > max_F:
max_F = CacheGain
argmax_i = i
elif CacheGain == max_F:
argmax_i = random.choice([argmax_i, i])
return argmax_i
color_vector = {}
for t in range(samples):
color_vector[t] = {}
for v in self.nodes():
color_vector[t][v] = {}
for j in range(self.capacities[v]):
color_vector[t][v][j] = random.randint(0, number_colors - 1)
G = {}
for m in range(number_colors):
for v in self.nodes():
if self.node[v]['cache'].has_visited:
if v not in G:
G[v] = {}
for j in range(self.capacities[v]):
if j not in G[v]:
G[v][j] = {}
G[v][j][m] = findMax(G, v, j, m, color_vector)
# for v in self.nodes():
# if self.node[v]['cache'].has_visited:
# for j in range(self.capacities[v]):
# m = random.randint(0, number_colors - 1)
# self.node[v]['cache'].cache[j].clear()
# self.node[v]['cache'].cache[j].add(G[v][j][m])
colors = random.choice(range(samples))
S = self.sampleCache(G, color_vector[colors])
Y = self.SlotSetToMatrix(S)
CacheGain = self.cache_gain(Y)
return CacheGain
# X = self.cachesToMatrix()
# cache_gain = self.cache_gain(X)
# return cache_gain
class NetworkedCache(object, metaclass=ABCMeta):
"""An abstract networked cache.
"""
@abstractmethod
def __init__(self, capacity, _id):
pass
@abstractmethod
def capacity(self):
pass
@abstractmethod
def perm_set(self):
pass
@abstractmethod
def makePermanent(self, item):
pass
@abstractmethod
def receive(self, message, edge, time):
pass
@abstractmethod
def __contains__(self, item):
pass
@abstractmethod
def __iter__(self):
pass
@abstractmethod
def isPermanent(self, item):
pass
class PriorityNetworkCache(NetworkedCache):
""" A Priority Networked Cache. Supports LRU,LFU, and RR policies.
Note: the capacity of the cache does not include its permanent set; i.e., the capacity concerns only files handled through the LRU principle.
"""
def __init__(self, capacity, _id, principle):
self.cache = PriorityCache(capacity, _id)
self.permanent_set = set([])
self._id = _id
self._capacity = capacity
self.stats = {}
self.stats['queries'] = 0.0
self.stats['hits'] = 0.0
self.stats['responses'] = 0.0
self.principle = principle
def __str__(self):
return str(self.cache) + '+' + str(self.permanent_set)
def __contains__(self, item):
return item in self.cache or item in self.permanent_set
def __iter__(self):
return itertools.chain(self.cache, self.permanent_set)
def isPermanent(self, item):
return item in self.permanent_set
def capacity(self):
return self._capacity
def perm_set(self):
return self.permanent_set
def makePermanent(self, item):
self.permanent_set.add(item)
def receive(self, msg, e, now):
label, d, query_id = msg.header
if label == "QUERY":
item = d.item
logging.debug(pp([now, ': Query message for item', item, 'received by cache', self._id]))
self.stats['queries'] += 1.0
inside_cache = item in self.cache
inside_permanent_set = item in self.permanent_set
if inside_cache or inside_permanent_set:
logging.debug(pp(
[now, ': Item', item, 'is inside', 'permanent set' if inside_permanent_set else 'cache', 'of',
self._id]))
if inside_cache: # i.e., not in permanent set
princ_map = {'LRU': now, 'LFU': self.cache.priority(item) + 1, 'RR': random.random(),
'FIFO': self.cache.priority(item)}
logging.debug(
pp([now, ': Priority of', item, 'updated to', princ_map[self.principle], 'at cache', self._id]))
self.cache.add(item, princ_map[self.principle])
self.stats['hits'] += 1
if self._id == d.query_source:
logging.debug(pp(
[now, ': Response to query', query_id, 'of', d, 'delivered to query source by cache',
self._id]))
pred = d
else:
pred = d.pred(self._id)
logging.debug(pp([now, ': Response to query', query_id, 'of', d, ' generated by cache', self._id]))
e = (self._id, pred)
rmsg = ResponseMessage(d, query_id, stats=msg.stats)
return [(rmsg, e)]
else:
logging.debug(pp([now, ': Item', item, 'is not inside', self._id, 'continue searching']))
succ = d.succ(self._id)
if succ == None:
logging.error(pp([now, ':Query', query_id, 'of', d, 'reached', self._id,
'and has nowhere to go, will be dropped']))
return []
e = (self._id, succ)
return [(msg, e)]
if label == "RESPONSE":
logging.debug(pp([now, ': Response message for', d, 'received by cache', self._id]))
self.stats['responses'] += 1.0
item = d.item
princ_map = {'LRU': now, 'LFU': self.cache.priority(item) + 1 if item in self.cache else 1,
'RR': random.random(), 'FIFO': self.cache.priority(item) if item in self.cache else now}
logging.debug(pp([now, ': Priority of', item, 'updated to', princ_map[self.principle], 'at', self._id]))
self.cache.add(item, princ_map[self.principle]) # add the item to the cache/update priority
if d.query_source == self._id:
logging.debug(
pp([now, ': Response to query', query_id, 'of', d, ' finally delivered by cache', self._id]))
pred = d
else:
logging.debug(pp([now, ': Response to query', query_id, 'of', d, 'passes through cache', self._id,
'moving further down path']))
pred = d.pred(self._id)
e = (self._id, pred)
return [(msg, e)]
class ExploreMessage(Message):
"""
An exploration message.
"""
def __init__(self, d, query_id, initiator, stats=None):
Message.__init__(self, header=("EXPLORE", d, query_id), payload=[], length=CONFIG.EXPLORE_MESSAGE_LENGTH,
stats=stats, u_bit=True)
self.explore_source = initiator
class ExploreResponseMessage(Message):
"""
An exploration response message.
"""
def __init__(self, d, query_id, initiator, stats=None):
Message.__init__(self, header=("EXPLORE_RESPONSE", d, query_id), payload=[],
length=CONFIG.EXPLORE_RESPONSE_MESSAGE_LENGTH, stats=stats, u_bit=False)
self.explore_source = initiator
class WeightExploreMessage(Message):
"""
An exploration message.
"""
def __init__(self, d, query_id, initiator, stats=None):
Message.__init__(self, header=("WEIGHT_EXPLORE", d, query_id), payload=None,
length=CONFIG.WEIGHT_EXPLORE_MESSAGE_LENGTH,
stats=stats, u_bit=True)
self.explore_source = initiator
class WeightExploreResponseMessage(Message):
"""
An exploration response message.
"""
def __init__(self, d, query_id, initiator, stats=None):
Message.__init__(self, header=("WEIGHT_EXPLORE_RESPONSE", d, query_id), payload=None,
length=CONFIG.WEIGHT_EXPLORE_RESPONSE_MESSAGE_LENGTH, stats=stats, u_bit=False)
self.explore_source = initiator
class GreedyCache(NetworkedCache):
""" An Table Greedy Networked Cache.
Note: the capacity of the cache does not include its permanent set; i.e., the capacity concerns only files handled through the EWMA principle.
"""
def __init__(self, capacity, _id, number_colors, number_items, color_update_frequency, T, batch, eta,
correlated_action_selectors):