-
Notifications
You must be signed in to change notification settings - Fork 15
/
mealscount-bulk-optimize.py
276 lines (241 loc) · 10.3 KB
/
mealscount-bulk-optimize.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
from tkinter import ttk,Tk,PhotoImage,filedialog,StringVar,BooleanVar,BOTH,messagebox,IntVar
import tksheet
import os,os.path,configparser
from bulktools import optimize,load_from_file,output_rows,write_to_excel
from strategies import STRATEGIES
from us.states import STATES
import threading
import multiprocessing
import sys
class MealsCountDesktop(object):
def __init__(self,app_path):
self.filename = None
self.districts = None
self.root = None
self.frame = None
self.progress = None
self.fileFrame = None
self.configFrame = None
self.runFrame = None
self.strategyVars = []
self.running = None
# Save prefs for each load
self.config = configparser.ConfigParser()
self.config['DEFAULT'] = {
'csv_file': '',
'state': 'CA',
'starts': '50',
'iterations': '1000',
'optimizeFor': 'reimbursement',
'nGroups': '10',
'debug': '5',
}
self.config['current'] = {}
self.cfg = self.config['current']
self.configLocation = os.path.join(app_path,"mealscount.cfg")
self.create_pool()
if os.path.exists(self.configLocation):
self.config.read(self.configLocation)
print(self.config.sections())
else:
self.write_cfg()
def write_cfg(self):
if not hasattr(self,"stateVar"): return
self.cfg["state"] = self.stateVar.get()
with open(self.configLocation,'w') as configFile:
self.config.write(configFile)
def initialize(self):
# root window
root = Tk()
root.title("MealsCount Bulk Optimizer SY2324")
#root.geometry("800x600")
root.grid_columnconfigure(0,weight=1)
# Create logo frame
# why did this stop working?
#logo = PhotoImage("logo",file=os.path.join("src","assets","MC_Logo@2x.png"))
#ttk.Label(root,image=logo).grid(row=0,column=0)
ttk.Label(root,text="Meals Count Bulk Optimizer").grid(row=0,column=0)
# Create frame for the rest of our components
frm = ttk.Frame(root,padding=10)
frm.grid(row=1,column=0)
self.root = root
self.frame = frm
def handle_choose_file(self):
self.filename = filedialog.askopenfilename(
title="Select file",
filetypes=(("XLSX Files","*.xlsx"),("CSV Files","*.csv"))
)
districts,schools,lastyear_groupings = load_from_file(self.filename,state=self.stateCombobox.get())
self.file_selected.config(text="Selected %s\nFound %i Districts, %i Schools" % (
os.path.basename(self.filename),
len(districts),
len(schools)
))
self.districts = districts
def handle_progress(self,n,status):
if n != None:
self.progressVar.set(round(n*100))
self.runStatusVar.set(status)
def handle_run(self):
if not self.districts:
messagebox.showerror("No Districts Loaded","Please select your CSV and make sure it shows your districts have been loaded")
return
goal = self.optimizeForVar.get()
#strategies = [v[0] for v in self.strategyVars if v[2].get()]
strategies = [s for s in STRATEGIES if "NYCMODA" not in s]
starts = int(self.startsVar.get())
iterations = int(self.iterationsVar.get())
ngroups = int(self.nGroupsVar.get())
strategies.append("NYCMODA?fresh_starts=%i&iterations=%i&ngroups=%i" % (starts,iterations,ngroups))
districts = self.districts
# Update thresholds
if self.testRunVar.get():
districts = {c:d for c,d in self.districts.items() if len(d.schools) <= 5}
if self.running:
messagebox.showerror("Please cancel current job before starting a new one")
return
self.handle_progress(0,"Starting..")
self.clear_results()
self.running = threading.Thread(target=lambda: self.run(districts,strategies,goal),daemon=True)
self.running.start()
def handle_save_as(self):
save_file = filedialog.asksaveasfile(mode="wb",defaultextension="xlsx")
if(save_file):
write_to_excel(self.resultRows,save_file)
save_file.close()
messagebox.showinfo("Saved %i district optimizations to %s" %(len(self.districts),save_file.name))
def handle_cancel(self):
if self.running:
self.pool.terminate()
self.progressVar.set(0)
# TODO nicely stop thread
self.running = None
self.create_pool()
def run(self,districts,strategies,goal):
self.write_cfg()
threshold = self.thresholdVar.get() == "40%" and 0.4 or 0.25
async_results = optimize(
districts,
strategies,
goal=goal,
isp_threshold=threshold,
pool=self.pool,
progress_callback=lambda n: self.handle_progress(n),
)
# Track progress
district_map = dict([(d.code,d) for d in districts.values()])
count = sum([len(d.schools) for d in districts.values()])
processed = 0
for r in async_results:
# TODO handle cancel as gracefully as possible
result = r.get()
_d = district_map[result["code"]]
processed += len(_d.schools)
self.handle_progress(processed/count,"Processed %s" % _d.name)
self.handle_progress(None,"Processing Complete")
# Pull results
self.results = [r.get() for r in async_results]
self.resultRows = output_rows(
self.districts,
self.results,
[], #TODO add in coverage comparison?
[], #TODO add in lastyear comparison
)
self.show_results()
total = sum([d['reimb'] for d in self.results])
self.running = None
messagebox.showinfo(
"Complete",
'''Optimization complete
%i results
Total Estimated Reimbursement: %s
''' % (len(self.results),'{:,}'.format(int(total)))
)
def clear_results(self):
self.resultSheet.set_sheet_data([])
def show_results(self):
self.resultSheet.set_sheet_data(self.resultRows)
def addFileFrame(self):
fileFrame = ttk.LabelFrame(self.frame,text="Select File",padding=10)
ttk.Button(fileFrame, text="Select File", command=self.handle_choose_file).grid(row=0,column=0,sticky="nw")
self.file_selected = ttk.Label(fileFrame,text="")
self.file_selected.grid(row=0,column=1,stick="ne")
fileFrame.grid(row=1,column=0,sticky="nsew")
def addConfigureFrame(self):
configFrame = ttk.LabelFrame(self.frame,text="Configure Run",padding=10)
stateFrame = ttk.LabelFrame(configFrame,text="State")
ttk.Label(stateFrame,text="Select State").grid(row=0,column=0,sticky="w")
self.stateVar = StringVar(value=self.cfg.get('state'))
self.stateCombobox = ttk.Combobox(stateFrame,values=[s.abbr for s in STATES],textvariable=self.stateVar)
self.stateCombobox.grid(row=1,column=0)
stateFrame.grid(row=0,column=0,stick='nsew')
optimizeForFrame = ttk.LabelFrame(configFrame,text="Optimize For",padding=5)
self.optimizeForVar = StringVar(value=self.cfg.get("optimizeFor"))
ttk.Radiobutton(optimizeForFrame,text="Max Reimbursement",value="reimbursement",var=self.optimizeForVar).grid(row=0,column=0,sticky="W")
ttk.Radiobutton(optimizeForFrame,text="Max Coverage",value="coverage",var=self.optimizeForVar).grid(row=1,column=0,sticky="W")
ttk.Label(optimizeForFrame,text="Max Number of Groups").grid(row=2,column=0,sticky="W")
self.nGroupsVar = StringVar(value=self.cfg.get("nGroups"))
ttk.Spinbox(optimizeForFrame,from_=5,to=1000,textvariable=self.nGroupsVar).grid(row=3,column=0,sticky="W")
ttk.Label(optimizeForFrame,text="ISP Threshold").grid(row=4,column=0,sticky="W")
self.thresholdVar = StringVar(value="25%")
ttk.Combobox(optimizeForFrame,values=["25%","40%"],state="25%",textvariable=self.thresholdVar).grid(row=5,column=0,sticky="W")
optimizeForFrame.grid(row=0,column=1,sticky="nsew")
iterationsFrame = ttk.LabelFrame(configFrame,text="Iterations",padding=5)
ttk.Label(iterationsFrame,text="Starts").grid(row=0,column=0)
self.startsVar = StringVar(value=self.cfg.get("starts"))
ttk.Spinbox(iterationsFrame,from_=50,to=1000,textvariable=self.startsVar).grid(row=0,column=1)
ttk.Label(iterationsFrame,text="Iterations").grid(row=1,column=0)
self.iterationsVar = StringVar(value=self.cfg.get('iterations'))
ttk.Spinbox(iterationsFrame,from_=1000,to=1000000,textvariable=self.iterationsVar).grid(row=1,column=1)
iterationsFrame.grid(row=0,column=2,sticky="nsew")
# strategyFrame = ttk.LabelFrame(configFrame,text="Strategies",padding=5)
# for i,strategy in enumerate(STRATEGIES.items()):
# sVar = BooleanVar(value=True)
# self.strategyVars.append((strategy[0],strategy[1],sVar))
# sFrame = ttk.Frame(strategyFrame)
# sFrame.pack()
# ttk.Checkbutton(sFrame,text=strategy[0],variable=sVar).pack()
# strategyFrame.pack(fill=BOTH,expand=True)
configFrame.grid(row=1,column=1,stick='nesw')
self.configFrame = configFrame
def addRunFrame(self):
runFrame = ttk.LabelFrame(self.frame,text="Run Optimization",padding=10)
ttk.Button(runFrame, text="Run",command=self.handle_run).grid(column=0, row=0)
cancel = ttk.Button(runFrame, text="Cancel", command=self.handle_cancel)
cancel.grid(column=1, row=0)
self.testRunVar = BooleanVar(value=True)
ttk.Checkbutton(runFrame,text="Test Run of 5 districts only",variable=self.testRunVar).grid(column=2,row=0)
self.runStatusVar = StringVar(value='')
ttk.Label(runFrame,textvariable=self.runStatusVar).grid(column=3,row=0)
self.progressVar = IntVar()
ttk.Progressbar(runFrame,maximum=100,variable=self.progressVar).grid(column=0,row=1,columnspan=2,sticky='nesw')
self.runFrame = runFrame
runFrame.grid(row=3,column=0,columnspan=4,sticky='nesw')
def addResultFrame(self):
resultFrame = ttk.LabelFrame(self.frame,text="Results",padding=10)
ttk.Button(resultFrame, text="Save As",command=self.handle_save_as).grid(row=0,column=0)
sheet=tksheet.Sheet(resultFrame)
#sheet.set_sheet_data([['a','b','c'],[1,2,3],[4,5,6]])
sheet.grid(row=1,column=0,columnspan=4,sticky='nesw')
self.resultSheet = sheet
resultFrame.grid(row=4,column=0,columnspan=2,sticky='nesw')
def loop(self):
self.root.mainloop()
def create_pool(self):
process_count = max(multiprocessing.cpu_count() - 1,1)
self.pool = multiprocessing.Pool(process_count)
def init(app_path):
win = MealsCountDesktop(app_path)
win.initialize()
win.addFileFrame()
win.addConfigureFrame()
win.addRunFrame()
win.addResultFrame()
win.loop()
if win.pool: win.pool.close()
if __name__=="__main__":
app_path = ""
if sys.platform.startswith('win'):
app_path = os.getenv("APPDATA")
multiprocessing.freeze_support()
init(app_path)