-
Notifications
You must be signed in to change notification settings - Fork 6
/
widgets_f06_01_logResultDisp.py
506 lines (415 loc) · 19.7 KB
/
widgets_f06_01_logResultDisp.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
# Copyright: (c) Oskar Petersons 2013
"""Widgets for displaying a conflict's equilibria.
Loaded by the frame_06_equilibria module.
"""
from tkinter import *
from tkinter import ttk
import numpy
import json
from data_01_conflictModel import ConflictModel
from visualizerLauncher import launchVis
from distutils.dir_util import copy_tree
import os
NSEW = (N, S, E, W)
class CoalitionSelector(ttk.Frame):
def __init__(self, master, conflict, solOwner):
ttk.Frame.__init__(self, master)
self.conflict = conflict
self.owner = solOwner
self.coalitionVar = StringVar()
self.statusVar = StringVar()
self.label = ttk.Label(self, text="Coalitions:")
self.label.grid(row=0, column=0, sticky=NSEW)
self.entry = ttk.Entry(self, textvariable=self.coalitionVar,
validate='key')
vcmd = self.entry.register(self.onChange)
self.entry.configure(validatecommand=(vcmd, '%P'))
self.entry.grid(row=0, column=1, sticky=NSEW)
self.statusLabel = ttk.Label(self, textvariable=self.statusVar)
self.statusLabel.grid(row=0, column=2, sticky=NSEW)
self.columnconfigure(1, weight=1)
self.refresh()
def refresh(self):
if self.conflict.coalitions is None:
self.coalitionVar.set(str([i + 1 for i in range(len(self.conflict.decisionMakers))])[1:-1])
else:
coalitionsRep = self.conflict.coalitions.disp_rep()
self.coalitionVar.set(str(coalitionsRep)[1:-1])
self.statusVar.set("Input OK.")
def onChange(self, newCoalitions):
try:
newCoIdxs = eval("[" + newCoalitions + "]")
except:
self.statusVar.set("Invalid Syntax.")
return True
numDMs = len(self.conflict.decisionMakers)
newCos = []
seen = []
areCoalitions = False
for itm in newCoIdxs:
if type(itm) is int:
if itm in seen:
self.statusVar.set("%s appears more than once." % itm)
return True
elif (itm > numDMs) or (itm < 1):
self.statusVar.set("%s is not a valid DM number." % itm)
return True
else:
seen.append(itm)
newCos.append(self.conflict.decisionMakers[itm - 1])
elif type(itm) is list:
newCoMembers = []
for itm2 in itm:
if type(itm2) is not int:
self.statusVar.set("%s is an invalid entry" % itm2)
return True
else:
if itm2 in seen:
self.statusVar.set("%s appears more than once." % itm2)
return True
elif (itm2 > numDMs) or (itm2 < 1):
self.statusVar.set("%s is not a valid DM number." % itm2)
return True
else:
seen.append(itm2)
newCoMembers.append(self.conflict.decisionMakers[itm2 - 1])
newCos.append(self.conflict.newCoalition(newCoMembers))
areCoalitions = True
else:
self.statusVar.set("%s is an invalid entry" % itm)
return True
if len(seen) == numDMs:
self.statusVar.set("Input OK.")
self.conflict.coalitions.itemList = []
for co in newCos:
self.conflict.coalitions.append(co)
if not self.conflict.coalitions.validate():
raise Exception("Coalitions failed to validate")
self.event_generate("<<CoalitionsChanged>>")
else:
self.statusVar.set("Missing DMs" % ([x + 1 for x in range(numDMs) if x + 1 not in seen]))
return True
class OptionFormSolutionTable(ttk.Frame):
def __init__(self, master, conflict, solOwner):
ttk.Frame.__init__(self, master)
self.conflict = conflict
self.owner = solOwner
self.sortDM = None
self.sortDirection = None
self.filterVals = []
# widgets
self.tableCanvas = Canvas(self)
self.table = ttk.Frame(self.tableCanvas)
self.scrollY = ttk.Scrollbar(self, orient=VERTICAL,
command=self.tableCanvas.yview)
self.scrollX = ttk.Scrollbar(self, orient=HORIZONTAL,
command=self.tableCanvas.xview)
# configuration
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
def resize(event):
self.tableCanvas.configure(scrollregion=self.tableCanvas.bbox("all"))
self.tableCanvas.grid(column=0, row=0, sticky=NSEW)
self.scrollY.grid(column=1, row=0, sticky=NSEW)
self.scrollX.grid(column=0, row=1, sticky=NSEW)
self.tableCanvas.configure(yscrollcommand=self.scrollY.set)
self.tableCanvas.configure(xscrollcommand=self.scrollX.set)
self.tableCanvas.create_window((0, 0), window=self.table, anchor='nw')
self.table.bind("<Configure>", resize)
self.style = ttk.Style()
self.style.configure('states.TLabel', background="grey80")
self.style.configure('yn.TLabel', background="white")
self.style.configure('payoffs.TLabel', background="green")
self.style.configure('hover.TLabel', background="lightpink")
self.refresh()
def refresh(self):
rowCount = len(self.conflict.options) + len(self.conflict.decisionMakers) + 2 + 6
columnCount = len(self.conflict.feasibles) + 2
tableData = numpy.zeros((rowCount, columnCount), dtype="<U20")
# labels
tableData[0, 1] = "Ordered"
tableData[1, 1] = "Decimal"
# #DMs and options
currRow = 2
for i, dm in enumerate(self.conflict.decisionMakers):
tableData[currRow, 0] = "%s - %s" % (i + 1, dm.name)
for opt in dm.options:
tableData[currRow, 1] = opt.name
currRow += 1
# #payoff labels
for dm in self.conflict.decisionMakers:
tableData[currRow, 0:2] = ["Payoff For:", dm.name]
currRow += 1
# #stability type labels
for st in ['Nash', 'GMR', 'SEQ', 'SIM', 'SEQ & SIM', 'SMR']:
tableData[currRow, 1] = st
currRow += 1
# fill states and stabilities
currCol = 2
feasibles = self.conflict.feasibles
for state in range(len(feasibles)):
newCol = [feasibles.ordered[state], feasibles.decimal[state]] + list(feasibles.yn[state])
for dm in self.conflict.decisionMakers:
newCol.append(dm.payoffs[state])
newCol += [("Y" if stability else "N") for stability in self.owner.sol.allEquilibria[:, state]]
tableData[:, currCol] = newCol
currCol += 1
self.owner.sol.dataTableRep = numpy.copy(tableData)
# sorting
if self.sortDM is not None:
sortIndex = numpy.array(tableData[self.sortDM, 2:], int).argsort() + 2
if self.sortDirection == "ascending":
tableData[:, 2:] = tableData[:, sortIndex]
else:
tableData[:, 2:] = tableData[:, sortIndex[::-1]]
# push to display
for child in self.table.winfo_children():
child.destroy()
rows = [[] for row in range(tableData.shape[0])]
columns = [[] for col in range(tableData.shape[1])]
for row in range(tableData.shape[0]):
if row < 2:
tag = "states"
elif row < (len(self.conflict.options) + 2):
tag = "yn"
elif row < (len(self.conflict.options) + len(self.conflict.decisionMakers) + 2):
tag = "payoffs"
else:
tag = "stabilities"
for col in range(tableData.shape[1]):
if col < 2:
newEntry = ttk.Label(self.table, text=tableData[row, col], style=tag + ".TLabel")
newEntry.grid(row=row, column=col, sticky=NSEW)
else:
if (tag == "stabilities") and (tableData[row, col] == "N"):
newEntry = ttk.Label(self.table, text="",
style=tag + ".TLabel", width=4)
else:
newEntry = ttk.Label(self.table, text=tableData[row, col], style=tag + ".TLabel", width=4)
newEntry.grid(row=row, column=col + 1, sticky=NSEW)
def enterCell(event=None, row=row, col=col):
for cell, tag in rows[row]:
cell.configure(style="hover.TLabel")
for cell, tag in columns[col]:
cell.configure(style="hover.TLabel")
def exitCell(event=None, row=row, col=col):
for cell, tag in rows[row]:
cell.configure(style=tag + ".TLabel")
for cell, tag in columns[col]:
cell.configure(style=tag + ".TLabel")
if (row < 2) and (col >= 2):
columns[col].append([newEntry, tag])
newEntry.bind("<Enter>", enterCell)
newEntry.bind("<Leave>", exitCell)
elif (row >= 2) and (col == 1):
rows[row].append([newEntry, tag])
newEntry.bind("<Enter>", enterCell)
newEntry.bind("<Leave>", exitCell)
elif (col >= 2) and (row >= 2):
rows[row].append([newEntry, tag])
columns[col].append([newEntry, tag])
newEntry.bind("<Enter>", enterCell)
newEntry.bind("<Leave>", exitCell)
valRotation = {"-": "Y", "Y": "N", "N": "-"}
if len(self.filterVals) != rowCount:
self.filterVals = numpy.zeros(rowCount, dtype="<U20")
def filterStates():
for col in range(2, tableData.shape[1]):
yMatch = numpy.greater_equal(tableData[:, col] == "Y", self.filterVals == "Y")
nMatch = numpy.greater_equal(tableData[:, col] == "N", self.filterVals == "N")
if numpy.all(numpy.logical_and(yMatch, nMatch)):
for cell, tag in columns[col]:
cell.grid()
else:
for cell, tag in columns[col]:
cell.grid_remove()
filterStates()
def filtMaker(row):
newFilterVal = StringVar()
if self.filterVals[row] == "":
self.filterVals[row] = "-"
newFilterVal.set(self.filterVals[row])
def rotateVal(e=None):
newVal = valRotation[newFilterVal.get()]
newFilterVal.set(newVal)
self.filterVals[row] = newVal
filterStates()
newFilterBtn = ttk.Button(self.table, textvariable=newFilterVal,
command=rotateVal, width=5)
return newFilterBtn
def sortMaker(row):
buttonText = '-'
if self.sortDM == row:
if self.sortDirection == "descending":
buttonText = ">"
else:
buttonText = "<"
def sortByDMPrefs(e=None):
if self.sortDM != row:
self.sortDM = row
self.sortDirection = 'descending'
elif self.sortDirection == 'descending':
self.sortDirection = 'ascending'
elif self.sortDirection == 'ascending':
self.sortDM = None
self.sortDirection = None
self.refresh()
newSortButton = ttk.Button(self.table, text=buttonText,
command=sortByDMPrefs, width=5)
return newSortButton
for row in range(2, 2 + len(self.conflict.options)):
nfb = filtMaker(row)
nfb.grid(row=row, column=2, sticky=NSEW)
for row in range(2 + len(self.conflict.options) + len(self.conflict.decisionMakers), tableData.shape[0]):
nfb = filtMaker(row)
nfb.grid(row=row, column=2, sticky=NSEW)
for row in range(2 + len(self.conflict.options), 2 + len(self.conflict.options) + len(self.conflict.decisionMakers)):
nsb = sortMaker(row)
nsb.grid(row=row, column=2, sticky=NSEW)
filterLabel = ttk.Label(self.table, text="Filter", anchor='center')
filterLabel.grid(row=1, column=2, sticky=NSEW)
class LogNarrator(ttk.Frame):
def __init__(self, master, conflict, solOwner):
ttk.Frame.__init__(self, master)
self.conflict = conflict
self.owner = solOwner
self.dmVar = StringVar()
self.stateVar = StringVar()
self.eqTypeVar = StringVar()
self.useCoalitions = False
self.dmSel = ttk.Combobox(self, textvariable=self.dmVar,
state='readonly', width=15)
self.dmSel.grid(column=0, row=0, sticky=NSEW, padx=3, pady=3)
self.stateSel = ttk.Combobox(self, textvariable=self.stateVar,
state='readonly', width=15)
self.stateSel.grid(column=1, row=0, sticky=NSEW, padx=3, pady=3)
self.eqTypeSel = ttk.Combobox(self, textvariable=self.eqTypeVar,
state='readonly', width=15)
self.eqTypeSel['values'] = ('Nash', 'GMR', 'SEQ', 'SIM', 'SMR')
self.eqTypeSel.grid(column=2, row=0, sticky=NSEW, padx=3, pady=3)
self.equilibriumNarrator = Text(self, wrap='word')
self.equilibriumNarrator.grid(column=0, row=1, columnspan=3,
sticky=NSEW)
self.eqNarrScrl = ttk.Scrollbar(self, orient=VERTICAL,
command=self.equilibriumNarrator.yview)
self.equilibriumNarrator.configure(yscrollcommand=self.eqNarrScrl.set)
self.eqNarrScrl.grid(column=3, row=1, sticky=NSEW)
self.columnconfigure(0, weight=1)
self.columnconfigure(1, weight=1)
self.columnconfigure(2, weight=1)
self.rowconfigure(1, weight=1)
self.dmSel.bind('<<ComboboxSelected>>', self.refreshNarration)
self.stateSel.bind('<<ComboboxSelected>>', self.refreshNarration)
self.eqTypeSel.bind('<<ComboboxSelected>>', self.refreshNarration)
self.refresh()
def refresh(self):
if self.conflict.coalitions is None:
self.useCoalitions = False
self.dmSel['values'] = tuple([dm.name for dm in self.conflict.decisionMakers])
else:
self.useCoalitions = True
self.dmSel['values'] = tuple([co.name for co in self.conflict.coalitions])
self.dmSel.current(0)
self.stateSel['values'] = tuple(self.conflict.feasibles.ordered)
self.stateSel.current(0)
self.eqTypeSel.current(0)
def refreshNarration(self, *args):
self.equilibriumNarrator.delete('1.0', 'end')
if self.useCoalitions:
dm = self.conflict.coalitions[self.dmSel.current()]
else:
dm = self.conflict.decisionMakers[self.dmSel.current()]
state = self.stateSel.current()
eqType = self.eqTypeVar.get()
if eqType == "Nash":
newText = self.owner.sol.nash(dm, state)[1]
elif eqType == 'GMR':
newText = self.owner.sol.gmr(dm, state)[1]
elif eqType == 'SEQ':
newText = self.owner.sol.seq(dm, state)[1]
elif eqType == 'SIM':
newText = self.owner.sol.sim(dm, state)[1]
elif eqType == 'SMR':
newText = self.owner.sol.smr(dm, state)[1]
else:
newText = "Error: bad equilibrium type selected."
self.equilibriumNarrator.insert('1.0', newText)
class Exporter(ttk.Frame):
"""Export function display frame."""
def __init__(self, master, conflict, solOwner):
"""Create widgets and initialize exporter."""
ttk.Frame.__init__(self, master)
self.conflict = conflict
self.owner = solOwner
self.RMdumpBtnJSON = ttk.Button(self, text='Save all data as JSON',
command=self.saveToJSON)
self.RMdumpBtnJSON.grid(column=0, row=0, sticky=NSEW,
padx=3, pady=3)
self.ResToCSVBtn = ttk.Button(self, text='Save Results as CSV',
command=self.saveToCSV)
self.ResToCSVBtn.grid(column=1, row=0, sticky=NSEW, padx=3, pady=3)
self.visLaunchBtn = ttk.Button(self, text='Launch Visualizer',
command=self.loadVis)
self.visLaunchBtn.grid(column=2, row=0, sticky=NSEW, padx=3, pady=3)
self.RMminJSON = ttk.Button(self,
text='Save reachbility matrix to json',
command=self.rmJSON)
self.RMminJSON.grid(column=3, row=0, sticky=NSEW, padx=3, pady=3)
def saveToJSON(self, event=None):
fileName = filedialog.asksaveasfilename(
defaultextension='.json',
filetypes=(("JSON files", "*.json"), ("All files", "*.*")),
parent=self)
if fileName:
self.owner.sol.saveJSON(fileName)
def rmJSON(self, event=None):
fileName = filedialog.asksaveasfilename(
defaultextension='.json',
filetypes=(("JSON files", "*.json"), ("All files", "*.*")),
parent=self)
if fileName:
rmJSONdata = {dm.name: dm.reachability.tolist()
for dm in self.owner.sol.effectiveDMs}
with open(fileName, 'w') as jsonfile:
json.dump(rmJSONdata, jsonfile)
def loadVis(self, event=None):
"""Launch visualization in browser."""
copy_tree('gmcr-vis', os.environ['TEMP'] + '/gmcr-vis', update=True)
self.owner.sol.saveJSON(os.environ['TEMP'] +
'/gmcr-vis/json/conflictData.json')
launchVis()
def saveToCSV(self, event=None):
"""Export the currently displayed results to a csv file."""
fileName = filedialog.asksaveasfilename(defaultextension='.csv',
filetypes=(("CSV files", "*.csv"),
("All files", "*.*")),
parent=self)
if fileName:
exptTab = numpy.copy(self.owner.sol.dataTableRep)
stabilities = [(self.owner.sol.nashStabilities, 'Nash'),
(self.owner.sol.seqStabilities, 'SEQ'),
(self.owner.sol.simStabilities, 'SIM'),
(self.owner.sol.gmrStabilities, 'GMR'),
(self.owner.sol.smrStabilities, 'SMR')]
spacer = numpy.zeros((len(self.conflict.decisionMakers),
len(self.conflict.feasibles) + 2),
dtype="<U20")
for i, dm in enumerate(self.conflict.decisionMakers):
spacer[i, 1] = dm.name
for stab, name in stabilities:
spc = spacer.copy()
spc[0, 0] = name
spc[:, 2:] = stab
exptTab = numpy.concatenate((exptTab, spc), axis=0)
numpy.savetxt(fileName, exptTab, fmt="%s", delimiter=", ")
def main():
"""Run screen in test mode."""
root = Tk()
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
g1 = ConflictModel('Prisoners.gmcr')
res = LogResultDisp(root, g1)
res.grid(column=0, row=0, sticky=(N, S, E, W))
root.mainloop()
if __name__ == '__main__':
main()