DavidD003 commited on
Commit
af68ff8
·
1 Parent(s): 12f7e6f

Delete SchedBuilderUtyModule.py

Browse files
Files changed (1) hide show
  1. SchedBuilderUtyModule.py +0 -329
SchedBuilderUtyModule.py DELETED
@@ -1,329 +0,0 @@
1
- from SchedBuilderClasses import *
2
- import openpyxl as pyxl
3
- import pandas as pd
4
- import numpy as np
5
- import sqlite3
6
- from copy import deepcopy
7
- from functools import reduce
8
- from operator import concat
9
-
10
-
11
- def debug(func):
12
- """Print the function signature and return value"""
13
- @functools.wraps(func)
14
- def wrapper_debug(*args, **kwargs):
15
- args_repr = [repr(a) for a in args] # 1
16
- kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()] # 2
17
- signature = ", ".join(args_repr + kwargs_repr) # 3
18
- print(f"Calling {func.__name__}({signature})")
19
- value = func(*args, **kwargs)
20
- print(f"{func.__name__!r} returned {value!r}") # 4
21
- return value
22
- return wrapper_debug
23
-
24
-
25
-
26
- def addTBL(tblName,fields="",dTypes=None,data=None,addOn=False):
27
- """Create table if not already existing, optionally with data, optionally clearing out old data if present. Fields as list of strings. Datatypes as list of strings, one must be provided for each field. See sqlite3 docs for mroe info"""
28
- conn = sqlite3.connect('test12.db')
29
- c = conn.cursor()
30
- listedFields=''
31
- if fields=="": #If none given, make alphabetical
32
- fields=[chr(65+i) for i in range(len(data[0]))]
33
- if dTypes==None: #Need not specify dtypes
34
- for f in fields:
35
- listedFields=listedFields+', '+ f
36
- else: #define data types at inception of table
37
- flds=list(zip(fields,dTypes))
38
- for pair in flds:
39
- listedFields=listedFields+', '+pair[0]+' '+pair[1]
40
- listedFields='('+listedFields[2:]+''')''' #Add leading and closing bracket, remove naively added comma+space from leading field
41
- c.execute('''CREATE TABLE IF NOT EXISTS '''+tblName+listedFields) # Create table.
42
- if addOn==False: #Delete if not adding
43
- c.execute('''DELETE FROM '''+tblName)
44
- if (data is not None) and len(data)>0:
45
- stmnt='INSERT INTO '+tblName+' VALUES ('
46
- for i in range(len(fields)-1):
47
- stmnt=stmnt+'?,'#Add '?,' equal to num columns less 1
48
- stmnt=stmnt+'?)' #add closing ?), no final comma
49
- for subEntry in data:
50
- c.execute(stmnt, subEntry)
51
- conn.commit()
52
-
53
- def isNumeric(n):
54
- try:
55
- n=int(n)
56
- return True
57
- except ValueError:
58
- try:
59
- n=float(n)
60
- return True
61
- except:
62
- return False
63
-
64
-
65
- def viewTBL(tblName,fields=None,sortBy=None,filterOn=None,returnStatement=0):
66
- """return np array of table with optional select fields, filtered, sorted. Sort syntax=[(field1,asc/desc),(field2,asc/desc)...] Filter syntax=[(field1,value),(field2,value)...]"""
67
- conn = sqlite3.connect('test12.db')
68
- c = conn.cursor()
69
- stmnt='SELECT '
70
- if fields!=None:
71
- flds=''
72
- for f in fields:
73
- flds=flds+', '+f
74
- stmnt=stmnt+flds[2:]+ ' FROM ' +tblName+' '
75
- else: stmnt=stmnt+'* FROM '+tblName+' ' #unspecified, select all
76
- if filterOn!=None:
77
- filt='WHERE '
78
- for f in filterOn:
79
- if isNumeric(f[1]): filt=filt+f[0]+' = '+ str(f[1])+' AND '
80
- else: filt=filt+str(f[0])+' = "'+ str(f[1])+'" AND '
81
- filt=filt[:-4] #Remove naively added final " and "
82
- stmnt=stmnt+filt
83
- if sortBy!=None:
84
- srt='ORDER BY '
85
- for s in sortBy:
86
- srt=srt+s[0]+' '+s[1]+', '
87
- srt=srt[:-2]
88
- stmnt=stmnt+srt
89
- stmnt=stmnt+';'
90
- if returnStatement==True: # Add option to print out the sql statement for troubleshooting
91
- return stmnt
92
- else:
93
- c.execute(stmnt)
94
- return [list(x) for x in c.fetchall()] #sqlite3 returns list of tuples.. want sublists for being editable
95
-
96
- def FTbtRow(ws):
97
- """Returns the excel row number for the bottom row with data in FT employee sheet"""
98
- #1st find bottom row with data
99
- for i in range(5,400):
100
- ref="C"+str(i) #Referencing EEID column. Failure mode is EEID missing for someone. Thats a bigger problem than the code not working
101
- if ws[ref].internal_value==None:
102
- #Condition met when end of data found.
103
- btmRow=i-1 #backtrack to last data
104
- break
105
- return btmRow
106
-
107
- def getFTinfo(flNm):
108
- """Returns dataframe with FT employee info (seniority,crew,eeid,name,refusal hours to date, OT hrs worked this week given path to FT refusal sheet"""
109
- myWb=pyxl.load_workbook(flNm)
110
- ws=myWb['Hourly OT']
111
- btmRow=FTbtRow(ws)
112
- tab=[[x.internal_value for x in sublist] for sublist in ws['A5:I'+str(btmRow)]]
113
- #for rec in tab: #numeric values getting cast to string on import. cast back
114
- # for i in [0,2]:
115
- # rec[i]=int(rec[i])
116
- # for i in [5,6,7]:
117
- # rec[i]=float(rec[i])
118
- #Following to turn into dataframe
119
- #df_FTinfo=pd.DataFrame(tab)
120
- #df_FTinfo=df_FTinfo[[0,1,2,3,4,5,8]] #Pull out only required columns
121
- #df_FTinfo.set_axis(['snrty', 'crew', 'eeid','last','first','yrRef','wkOT'], axis='columns', inplace=True)
122
- return tab
123
-
124
-
125
- def FTendCol(ws):
126
- """Returns column # for last column of skills matrix in excel from FT refusal sheet"""
127
- for i in range(0,400):
128
- if ws['A1'].offset(0,i).value=='Start-up':
129
- #Condition met when end of data found.
130
- endCol=i-1
131
- break
132
- return endCol
133
-
134
- def getFTskills(flNm):
135
- """Returns a dataframe containing a table with 2 fields: eeid and job name, with one record for every job an ee is trained in"""
136
- myWb=pyxl.load_workbook(flNm)
137
- ws=myWb['Hourly OT']
138
- endCol=FTendCol(ws) #Get right limit for iteration through skills
139
- btmRow=FTbtRow(ws) #Get bottom limit for iteration through skills
140
- skills=[] #Initialize empty skills list
141
- for i in range(5,btmRow+1): #Data starts on row 5. +1 because range fn not inclusive
142
- eeid=ws['C'+str(i)].value
143
- for c in range(10,endCol+1):
144
- if ws['C'+str(i)].offset(0,c-2).value==1: #subtract 2 from c because the endCol is counted from col A, and we are offsetting from col C, whihc is 2 offset from A
145
- jobNm=ws['A2'].offset(0,c).value #if 1 indicates trained, pull job name from header row
146
- skills.append([eeid,jobNm]) #Add new record to skills table
147
- #idxs=np.array(skills)[:,0]
148
- #skills=pd.DataFrame(skills,idxs) #Convert to dataframe
149
- #skills.set_axis(['eeid','skill'], axis='columns', inplace=True)
150
- return skills
151
-
152
- def TempbtRow(ws):
153
- """Returns the excel row number for the bottom row with data in Temp employee sheet"""
154
- #1st find bottom row with data
155
- for i in range(4,400):
156
- ref="C"+str(i) #Referencing EEID column. Failure mode is EEID missing for someone. Thats a bigger problem than the code not working
157
- if ws[ref].internal_value==None:
158
- #Condition met when end of data found.
159
- btmRow=i-1 #backtrack to last data
160
- break
161
- return btmRow
162
-
163
- def getTempinfo(flNm):
164
- """Returns dataframe with FT employee info (seniority,crew,eeid,name,refusal hours to date, OT hrs worked this week given path to FT refusal sheet"""
165
- myWb=pyxl.load_workbook(flNm)
166
- ws=myWb['Temp Refusal']
167
- btmRow=TempbtRow(ws)
168
- tab=[[x.internal_value for x in sublist] for sublist in ws['A4:I'+str(btmRow)]]
169
- #df_Tempinfo=pd.DataFrame(tab)
170
- #df_Tempinfo=df_Tempinfo[[0,1,2,3,4,5,8]] #Pull out only required columns
171
- #df_Tempinfo.set_axis(['snrty', 'crew', 'eeid','last','first','yrRef','wkOT'], axis='columns', inplace=True)
172
- return tab
173
-
174
- def TempendCol(ws):
175
- """Returns column # for last column of skills matrix in excel from FT refusal sheet"""
176
- for i in range(0,400):
177
- if ws['A2'].offset(0,i).value=='Start Up':
178
- #Condition met when end of data found.
179
- endCol=i-1
180
- break
181
- return endCol
182
-
183
- def getTempskills(flNm):
184
- """Returns a dataframe containing a table with 2 fields: eeid and job name, with one record for every job an ee is trained in"""
185
- myWb=pyxl.load_workbook(flNm)
186
- ws=myWb['Temp Refusal']
187
- endCol=TempendCol(ws) #Get right limit for iteration through skills
188
- btmRow=TempbtRow(ws) #Get bottom limit for iteration through skills
189
- skills=[] #Initialize empty skills list
190
- for i in range(4,btmRow+1): #Data starts on row 5. +1 because range fn not inclusive
191
- eeid=ws['C'+str(i)].value
192
- for c in range(11,endCol+1): #First skills column is 11 offset from col A
193
- if ws['C'+str(i)].offset(0,c-2).value==1: #subtract 2 from c because the endCol is counted from col A, and we are offsetting from col C, which is 2 offset from A
194
- jobNm=ws['A3'].offset(0,c).value #if 1 indicates trained, pull job name from header row
195
- skills.append([eeid,jobNm]) #Add new record to skills table
196
- #idxs=np.array(skills)[:,0]
197
- #skills=pd.DataFrame(skills,idxs) #Convert to dataframe
198
- #skills.set_axis(['eeid','skill'], axis='columns', inplace=True)
199
- return skills
200
-
201
- def imptXlTbl(XlFl,ShtNm,TblNm):
202
- myWb=pyxl.load_workbook(XlFl)
203
- ws=myWb[ShtNm]
204
- tab=ws.tables[TblNm] #Pull out table
205
- tab=[[x.value for x in sublist] for sublist in ws[tab.ref]] #Convert to list of lists (each sublist as row of excel table)
206
- return tab[1:] #Convert nested lists to array, dropping first row which is table headings
207
-
208
- def generateMasterPollTbl(pollDict):
209
- """Given a dictionary containing the polling tables for all crews, generates a master tbl in SQLlite for being able to filter on peoples availabilities, with '1' indicating interest, '0' no interest, and slot seq 1 starting at index 4"""
210
- mPollTbl=[]
211
- #the total list of all fields the table has is programmatically generated on these 3 lines
212
- flds=["eeid",'lastNm','firstNm','ytdRefHrs']
213
- flds.extend(['slot_'+str(i) for i in range(1,25)])#Note that there is one field for each slot seqID, 1 through 24, for filtering
214
- flds.append('Comment')
215
- for crewKey in pollDict:
216
- tbl=pollDict[crewKey] #Pull the crew specific OT polling table from dictionary
217
- for rec in tbl:
218
- cmnt=rec[16]#retrieve comment to tag on later
219
- slotwise_polling=list(rec[:4])
220
- for i in range(4,16):
221
- if rec[i] not in ('n','N',None) :
222
- slotwise_polling.extend(['y','y']) #Add two entries because 1 entry in polling sheet applies to two slots
223
- else:
224
- slotwise_polling.extend(['n','n'])
225
- slotwise_polling.append(cmnt)
226
- mPollTbl.append(slotwise_polling)
227
- addTBL('allPollData',fields=flds, data=mPollTbl,addOn=False)
228
-
229
-
230
- def pullTbls(FtBook,TempBook,AssnBook,PollBook): #Need to make volunteer shift data puller
231
- """Take flNm, return ftInfoTbl, ftSkillsMtx, tempInfoTbl, tempSkillsMtx, AssignmentsTbl, slot_Legend, JobTrnCrossRef, pollDict, All_Slots, senList. Uses functions defined previously to return all required tables at once. Function of functions for final script"""
232
- a=getFTinfo(FtBook) #to sqlite
233
- b=getFTskills(FtBook) #to sqlite
234
- b=[[int(d[0]),d[1]] for d in b] #Cast EEid to numeric value
235
- c=getTempinfo(TempBook) #to sqlite
236
- d=getTempskills(TempBook) #to sqlite
237
- d=[[int(data[0]),data[1]] for data in d] #Cast EEid to numeric value
238
- e=imptXlTbl(AssnBook,'Assignment_List','Assn_List')
239
- f=imptXlTbl(AssnBook,'Slot_Legend','Slot_Legend')
240
- g=imptXlTbl(AssnBook,'Job_Training_Crossref','TrainAssnMtx') #to sqlite
241
- pollDict={} #Generate empty dictionary to store tables of people voluntary overtime
242
- for crew in ['Blue','Bud','Rock']:
243
- for eeType in ['FT','Temp']:
244
- keyNm='tbl_'+crew+eeType
245
- tbl=imptXlTbl(PollBook,'Sheet1',keyNm)
246
- pollDict[keyNm]=tbl
247
- h=imptXlTbl(AssnBook,'All_Slots','All_Slots')
248
- #Generate tables in sqlite
249
- addTBL("sklMtx",fields=["EEID","trnNm"],data=b,addOn=False) #Overwrite all training data and populate FT ops, then append temps for a master table
250
- addTBL("sklMtx",fields=["EEID","trnNm"],data=d,addOn=True)
251
- addTBL("xRef",fields=["dispNm","trnNm"],data=g,addOn=False) #Skill name cross ref table for fcn dispToTrn to work
252
- addTBL("FTinfo",fields=['sen','crew','id','last','first','ytd','totref','totchrg','wtdOT'],data=a,addOn=False)
253
- addTBL("TempInfo",fields=['sen','crew','id','last','first','ytd','totref','totchrg','wtdOT'],data=c,addOn=False)
254
- # addTBL("FTinfo",fields=['sen','crew','id','last','first','ytd','totref','totchrg','wtdOT'],dTypes=['NUM','TEXT','NUM','TEXT','TEXT','NUM','NUM','NUM'],data=a,addOn=False)
255
- # addTBL("TempInfo",fields=['sen','crew','id','last','first','ytd','totref','totchrg','wtdOT'],dTypes=['INTEGER','TEXT','INTEGER','TEXT','TEXT','INTEGER','INTEGER','INTEGER'],data=c,addOn=False)
256
- #Generate a master seniority table.. following replaces hire date with integers for temps
257
- senHiLoTemps=viewTBL('TempInfo',sortBy=[('sen','ASC')]) #First retrieve list of temps, most senior to least
258
- i=100000 #Start new seniority number at arbitrarily high value not to interfere with full timer
259
- for row in senHiLoTemps:
260
- row[0]=i
261
- i+=1
262
- #Overwrite/make new master sen ref table. Then append the Temp data with integerized values
263
- addTBL("senRef",fields=['sen','crew','id','last','first','ytd','totref','totchrg','wtdOT'],data=a,addOn=False)
264
- addTBL("senRef",fields=['sen','crew','id','last','first','ytd','totref','totchrg','wtdOT'],data=senHiLoTemps,addOn=True)
265
- senList=viewTBL('senRef',sortBy=[('sen','ASC')])
266
- return a,b,c,d,e,f,g,pollDict,h,senList
267
-
268
- def dispToTrn(dispNm):
269
- """Returns the trnNm associated with Display name for a given job. assumes popualted sqlite table 'xRef' with dispNm/trnNm pairs"""
270
- q=viewTBL('xRef',fields=['dispNm','trnNm'],filterOn=[('dispNm',dispNm)])
271
- if len(q)==0:
272
- return "Custom func error 'dispToTrn' no entry found in xRef with dispNm="+str(dispNm)
273
- return q[0][1]
274
-
275
- def trnToDisp(trnNm):
276
- """Returns the trnNm associated with Display name for a given job. assumes popualted sqlite table 'xRef' with dispNm/trnNm pairs"""
277
- q=viewTBL('xRef',fields=['dispNm','trnNm'],filterOn=[('trnNm',trnNm)])
278
- if len(q)==0:
279
- return "Custom func error 'trnToDisp' no entry found in xRef with trnNm="+str(trnNm)
280
- return [e[0] for e in q] #If multiple DispNms for one train name (e.g. L4 Packer -> Packer, Candling) or Bottle Supply -> etc.
281
- #Then return list of all dispNms
282
-
283
- def sklChk(eeid,dispNm):
284
- """Returns True/False if eeid is trained on job with display name or not. Requires skills matrix named sklMtx in sqlite"""
285
- trnNm=dispToTrn(dispNm)
286
- if len(viewTBL('sklMtx',filterOn=[('EEID',eeid),('trnNm',trnNm)]))==0:
287
- return False
288
- else:
289
- return True
290
-
291
-
292
- def makeEEdict(ftInfoTbl,tempInfoTbl,wkHrs):
293
- eeDict={}
294
- for dtaTbl in [ftInfoTbl,tempInfoTbl]:
295
- for row in dtaTbl:
296
- eeSkills=viewTBL('sklMtx',['trnNm'],filterOn=[('EEID',row[2])])
297
- eeSkills=[trnToDisp(nm[0]) for nm in eeSkills] #Gather display names for skills trained on, reducing lists within list to spread elements
298
- sk=[] #Create empty to accumulate all skills present within sublists of eeSkills
299
- for s in eeSkills:
300
- sk.extend(s)
301
- sen=viewTBL('senRef',fields=['sen'],filterOn=[('id',str(row[2]))])[0][0]
302
- anEE=ee(sen,row[1],int(row[2]),row[3],row[4],row[5],row[8]+wkHrs,skills=sk) #Pull info from Refusals sheet
303
- eeDict[anEE.eeID]=anEE
304
- return eeDict
305
-
306
- def makeSlots(eeDict,AllSlots):
307
- openSlots={} #Open here meaning unassigned.. Will be required when it comes time to force
308
- for row in AllSlots:
309
- if row[6]==1: #Check that the slot generation record is labelled as 'active'
310
- for i in range(row[0],row[1]+1): #Generate a slot for each index over the range indicated... add 1 because python Range fn not inclusive of end point
311
- sl=Slot(i, row[2],dispToTrn(row[2]))
312
- #Determine how many eligible volunteers for this slot
313
- elig=[] #To track how many people trained
314
- for rec in viewTBL('allPollData',filterOn=[('slot_'+str(sl.seqID),'y')]): # iterate through results (employee info's) of query on who said yes to working at the time of this slot
315
- if sl.dispNm in eeDict[rec[0]].skills: elig.append(rec[0]) #Append EEID to list 'elig' if the ee is trained on the job
316
- sl.eligVol=elig # True values as 1.. sum to see number of eligible volunteers for the slot.
317
- openSlots[str(sl.seqID)+'_'+str(sl.dispNm)]=sl #Enter it into the dictionary
318
- return openSlots
319
-
320
- def preProcessData(Acrew,wkHrs,FtBook,TempBook,AssnBook,PollBook,pNT=False):
321
- """A function to take input data and generate all necessary tables and objects in memory to carry out algorithm. Return Schedule object containing all workSlot objects, and dictioanry fo all employee objects"""
322
- ftInfoTbl, ftSkillsMtx, tempInfoTbl, tempSkillsMtx, AssignmentsTbl, slot_Legend, JobTrnCrossRef,pollDict,AllSlots,senList=pullTbls(FtBook,TempBook,AssnBook,PollBook)
323
- #GenerateMasterPollTbl to facilitate making the Slots... require having a table with all employee preferences.
324
- generateMasterPollTbl(pollDict)
325
- #Generate Worker Objects, and assign to dictionary keyed by eeID (numeric key, not string keys)
326
- eeDict=makeEEdict(ftInfoTbl,tempInfoTbl,wkHrs)
327
- #Generate Schedule Slot objects (all unassigned slots for weekend)
328
- allSlots=makeSlots(eeDict,AllSlots)
329
- return Schedule(Acrew,allSlots,eeDict,AssignmentsTbl,senList,pollDict,slot_Legend,pNT=pNT)