-
Notifications
You must be signed in to change notification settings - Fork 1
/
simulator.py
319 lines (245 loc) · 15.1 KB
/
simulator.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
# -*- coding: utf-8 -*-
"""Overall class for running the simulations.
Contains the Simulator class, which holds all of the matching algorithms and calculates the distortion. Also logs the outcomes of the experiments for analysis and
visualization.
"""
import networkx as nx
import numpy as np
import pandas as pd
import instance_generator
import solver
import argparse
#TODO the experiment code in here has a ton of repetition - think about how this could be better formatted?
class Simulator:
"""Object that solves instances of matching problems given to it and aggregates the results in a pretty manner.
Attributes:
instance_generator (InstanceGenerator): InstanceGenerator for creating problem instances for simulation
history (dict): history of all results, stored in a dictionary for later conversion to pd.DataFrame
"""
def __init__(self, instance_generate):
"""Initializes a new Simulator.
Args:
instance_generate (InstanceGenerator): InstanceGenerator for creating problem instances for simulation
"""
self.instance_generator = instance_generate
self.history = {'id': [], 'val_index': [], 'size': [], 'valuation':[], 'algo': [], 'distortion': []}
self.id = 1
def serial_dictatorship_experiment(self, val_index, val_type, G, size=None, agent_cap=None):
"""Finds the distortion of running serial dictatorship on the given input.
Args:
val_index (int): The id of the valuation in self.instance_generator.
val_type (string): The method by which the valuation was generated.
G (nx.Graph): The actual matching input. Must be a weighted bipartite graph with numerical node labels.
size (int): The number of agents in the input. Defaults to half the size of G.nodes if not given.
agent_cap (int): An integer value i such that for all nodes with label <= i, those nodes are agents. Defaults to len(G.nodes//2) if not given.
"""
if size is None:
size = len(G.nodes)//2
M = solver.serial_dictatorship(G,agent_cap)
self.history['id'].append(self.id)
self.id += 1
self.history['val_index'].append(val_index)
self.history['size'].append(size)
self.history['valuation'].append(val_type)
self.history['algo'].append('serial_dictatorship')
self.history['distortion'].append(solver.calculate_modified_distortion(G,M,prio='pareto'))
def partial_max_matching_experiment(self, val_index, val_type, G, m, size=None, agent_cap=None):
"""Finds the distortion of running PartialMaxMatching on the given input.
Args:
val_index (int): The id of the valuation in self.instance_generator.
val_type (string): The method by which the valuation was generated.
G (nx.Graph): The actual matching input. Must be a weighted bipartite graph with numerical node labels.
m (int): The number of buckets, used as input to PartialMaxMatching.
size (int): The number of agents in the input. Defaults to half the size of G.nodes if not given.
agent_cap (int): An integer value i such that for all nodes with label <= i, those nodes are agents. Defaults to len(G.nodes//2) if not given.
"""
if size is None:
size = len(G.nodes)//2
M = solver.partial_max_matching(G,m,agent_cap)
H = solver.reassign_labels(G, M)
M_0 = solver.top_trading_cycles(H)
self.history['id'].append(self.id)
self.id += 1
self.history['val_index'].append(val_index)
self.history['size'].append(size)
self.history['valuation'].append(val_type)
self.history['algo'].append('partial_max_matching'+ '_' + str(m))
self.history['distortion'].append(solver.calculate_distortion(G,M_0))
def modified_max_matching_experiment(self, val_index, val_type, G, prio='pareto', size=None, agent_cap=None):
"""Finds the distortion of running ModifiedMaxMatching on the given input.
Args:
val_index (int): The id of the valuation in self.instance_generator.
val_type (string): The method by which the valuation was generated.
G (nx.Graph): The actual matching input. Must be a weighted bipartite graph with numerical node labels.
size (int): The number of agents in the input. Defaults to half the size of G.nodes if not given.
agent_cap (int): An integer value i such that for all nodes with label <= i, those nodes are agents. Defaults to len(G.nodes//2) if not given.
"""
if size is None:
size = len(G.nodes)//2
M_0 = solver.modified_max_matching(G,prio=prio,agent_cap=agent_cap)
self.history['id'].append(self.id)
self.id += 1
self.history['val_index'].append(val_index)
self.history['size'].append(size)
self.history['valuation'].append(val_type)
self.history['algo'].append('modified_max_matching')
self.history['distortion'].append(solver.calculate_modified_distortion(G,M_0,prio))
def top_trading_cycles_experiment(self, val_index, val_type, G, size=None, agent_cap=None):
"""Finds the distortion of running top trading cycles on the given input.
Args:
val_index (int): The id of the valuation in self.instance_generator.
val_type (string): The method by which the valuation was generated.
G (nx.Graph): The actual matching input. Must be a weighted bipartite graph with numerical node labels.
size (int): The number of agents in the input. Defaults to half the size of G.nodes if not given.
agent_cap (int): An integer value i such that for all nodes with label <= i, those nodes are agents. Defaults to len(G.nodes//2) if not given.
"""
if size is None:
size = len(G.nodes)//2
M = solver.top_trading_cycles(G,agent_cap)
self.history['id'].append(self.id)
self.id += 1
self.history['val_index'].append(val_index)
self.history['size'].append(size)
self.history['valuation'].append(val_type)
self.history['algo'].append('ttc_matching')
self.history['distortion'].append(solver.calculate_modified_distortion(G,M,prio='pareto'))
def epsilon_max_matching_experiment(self, val_index, val_type, G, epsilon, size=None, agent_cap=None):
"""Finds the distortion of running epsilon max matching on the given input.
Args:
val_index (int): The id of the valuation in self.instance_generator.
val_type (string): The method by which the valuation was generated.
G (nx.Graph): The actual matching input. Must be a weighted bipartite graph with numerical node labels.
size (int): The number of agents in the input. Defaults to half the size of G.nodes if not given.
agent_cap (int): An integer value i such that for all nodes with label <= i, those nodes are agents. Defaults to len(G.nodes//2) if not given.
"""
if size is None:
size = len(G.nodes)//2
M = solver.epsilon_max_matching(G, epsilon, agent_cap=agent_cap)
H = solver.reassign_labels(G, M)
M_0 = solver.top_trading_cycles(H)
self.history['id'].append(self.id)
self.id += 1
self.history['val_index'].append(val_index)
self.history['size'].append(size)
self.history['valuation'].append(val_type)
self.history['algo'].append('epsilon_max_matching'+str(epsilon))
self.history['distortion'].append(solver.calculate_distortion(G,M_0))
def epsilon_max_matching_prio_experiment(self, val_index, val_type, G, epsilon, prio='pareto', size=None, agent_cap=None):
"""Finds the distortion of running epsilon max matching on the given input.
Args:
val_index (int): The id of the valuation in self.instance_generator.
val_type (string): The method by which the valuation was generated.
G (nx.Graph): The actual matching input. Must be a weighted bipartite graph with numerical node labels.
prio (String): String in ['rank_maximal', 'max_cardinality_rank_maximal', 'fair'] that represents the priority vector used for this problem. Defaults to 'rank_maximal'.
size (int): The number of agents in the input. Defaults to half the size of G.nodes if not given.
agent_cap (int): An integer value i such that for all nodes with label <= i, those nodes are agents. Defaults to len(G.nodes//2) if not given.
"""
if size is None:
size = len(G.nodes)//2
M = solver.epsilon_max_matching(G, epsilon, prio, agent_cap)
self.history['id'].append(self.id)
self.id += 1
self.history['val_index'].append(val_index)
self.history['size'].append(size)
self.history['valuation'].append(val_type)
self.history['algo'].append('epsilon_max_matching '+prio+str(epsilon))
self.history['distortion'].append(solver.calculate_modified_distortion(G,M,prio))
#TODO fix inconsistent casing
def twothirds_max_matching_experiment(self, val_index, val_type, G, prio, size=None, agent_cap=None):
"""Finds the distortion of twothirds_max_matching on the given input.
Args:
val_index (int): The id of the valuation in self.instance_generator.
val_type (string): The method by which the valuation was generated.
G (nx.Graph): The actual matching input. Must be a weighted bipartite graph with numerical node labels.
prio (String): String in ['rank_maximal', 'max_cardinality_rank_maximal', 'fair'] that represents the priority vector used for this problem. Defaults to 'rank_maximal'.
size (int): The number of agents in the input. Defaults to half the size of G.nodes if not given.
agent_cap (int): An integer value i such that for all nodes with label <= i, those nodes are agents. Defaults to len(G.nodes//2) if not given.
"""
M = solver.twothirds_max_matching(G, prio, agent_cap)
self.history['id'].append(self.id)
self.id += 1
self.history['val_index'].append(val_index)
self.history['size'].append(size)
self.history['valuation'].append(val_type)
self.history['algo'].append('twothirds_max_matching '+prio)
self.history['distortion'].append(solver.calculate_modified_distortion(G,M,prio))
def updated_hybrid_max_matching_experiment(self, val_index, val_type, G, size=None, agent_cap=None):
"""Finds the distortion of running updated HybridMaxMatching on the given input.
Args:
val_index (int): The id of the valuation in self.instance_generator.
val_type (string): The method by which the valuation was generated.
G (nx.Graph): The actual matching input. Must be a weighted bipartite graph with numerical node labels.
size (int): The number of agents in the input. Defaults to half the size of G.nodes if not given.
agent_cap (int): An integer value i such that for all nodes with label <= i, those nodes are agents. Defaults to len(G.nodes//2) if not given.
"""
if size is None:
size = len(G.nodes)//2
M = solver.updated_hybrid_max_matching(G,agent_cap=agent_cap)
H = solver.reassign_labels(G, M)
M_0 = solver.top_trading_cycles(H)
self.history['id'].append(self.id)
self.id += 1
self.history['val_index'].append(val_index)
self.history['size'].append(size)
self.history['valuation'].append(val_type)
self.history['algo'].append('updated_hybrid_max_matching')
self.history['distortion'].append(solver.calculate_modified_distortion(G,M_0,prio='pareto'))
if __name__=='__main__':
instantiator = instance_generator.InstanceGenerator(True)
sim = Simulator(instantiator)
# for n in [5,10,20,50,100]: # adjust the number of intervals here
# print('current batch is', n)
# for j in range(20): # adjust number of trials per n here
# G = instantiator.generate_unit_range_arrow(n, -1) #adjust the valuation generation method here
# val_index = instantiator.index-1
# val_type = 'unit_range_arrow_-1'
# sim.serial_dictatorship_experiment(val_index,val_type,G)
# sim.updated_hybrid_max_matching_experiment(val_index,val_type,G)
# sim.top_trading_cycles_experiment(val_index,val_type,G)
# sim.epsilon_max_matching_experiment(val_index,val_type,G,1)
# sim.epsilon_max_matching_experiment(val_index,val_type,G,0.1)
# df = pd.DataFrame(sim.history)
# df.to_csv("C:/Users/sqshy/Desktop/University/Fifth Year/research/DistortionSim/updateddata/unit_range_arrow_-1_pareto.csv") #adjust path name here
# df = pd.Series(sim.instance_generator.history)
# df.to_csv("C:/Users/sqshy/Desktop/University/Fifth Year/research/DistortionSim/updateddata/unit_range_arrow_-1_pareto.csv") #adjust instance data path name here
#still need to modify which experiments to run from below
#parameters for directly modifying arguments from file
theta=0.2
norm = "range"
crit = "" # empty string and pareto are the same
#argparse parameters
parser = argparse.ArgumentParser("DistortionSim")
parser.add_argument("--theta", type=str, default="1", choices=["0.2", "1", "5"])
parser.add_argument("--norm", type=str, default="range", choices=["range", "sum"])
parser.add_argument("--crit", type=str, default="", choices=["", "pareto", "rank_maximal", "max_cardinality_rank_maximal", "fair"])
parser.add_argument("--save_dir", type=str, default="./")
parser.add_argument("--ckpt_path", type=str, default="./")
args = parser.parse_args()
theta = args.theta
norm = args.norm
crit = args.crit
#end parameter differences
val_type = f"theta{theta}unit{norm}"
sizes = [5,10,20,50,100]
for size in [5,10,20,50,100]:
filename = f"rdata/ord_n{size}_theta{theta}.txt"
print('current n value is', size)
G_list = instantiator.generate_list_from_ordinal_preferences(filename, size, 100, "unit_"+norm) #adjust unit-range vs unit-sum here
val_index = instantiator.index - 100
for i in range(len(G_list)):
G = G_list[i]
#adjust experiments here
sim.serial_dictatorship_experiment(val_index,val_type,G)
sim.top_trading_cycles_experiment(val_index,val_type,G)
sim.epsilon_max_matching_prio_experiment(val_index,val_type,G,1,prio=crit)
sim.epsilon_max_matching_prio_experiment(val_index,val_type,G,0.1,prio=crit)
sim.modified_max_matching_experiment(val_index,val_type,G,prio=crit)
sim.updated_hybrid_max_matching_experiment(val_index,val_type,G)
val_index += 1
# adjust naming conventions here
s = "ijcaidata/"+val_type+crit+".csv"
s_instances = "ijcaidata/"+val_type+crit+"instances.csv"
df = pd.DataFrame(sim.history)
df.to_csv(s)
df = pd.Series(sim.instance_generator.history)
df.to_csv(s_instances)