def saveAndCreate(self): """Gets values from all entries in GUI and saves it into the global data lists""" global machinesList, itinerariesList flagForExit = True #create machines for m in range(len(self.timesEntries[0])): machinesList.append(Machine("M" + str(m + 1))) try: #for each itinerary create new one for r in range(len(self.timesEntries)): itin = Itinerary() itin.name = "Itinerary " + str(r + 1) #and for each machine get value after validation for corectness for c in range(len(self.timesEntries[r])): if self.timesEntries[r][c].get( ) == "" and self.machinesEntries[r][c].get() == "": pass elif (self.timesEntries[r][c].get() == "" and self.machinesEntries[r][c].get() != "") or ( self.timesEntries[r][c].get() != "" and self.machinesEntries[r][c].get() == ""): raise ValueError( "Task have no time or machine assigned", (r + 1, c + 1)) else: #create task in itinerary if machine id exist in range if int(self.machinesEntries[r][c].get()) in range( 1, len(self.timesEntries[r]) + 1): if float(self.timesEntries[r][c].get()) != 0: task = Task( "Task " + (str(c + 1)), float(self.timesEntries[r][c].get()), machinesList[ int(self.machinesEntries[r][c].get()) - 1]) itin.tasksList.append(task) else: raise ValueError( "Task duration cannot be equal zero!", (r + 1, c + 1)) else: raise ValueError("Machine ID is invalid!", (r + 1, c + 1)) #and add it to global list itinerariesList.append(itin) except ValueError as errMsg: flagForExit = False msg.showerror( STRGS['ERR'], errMsg.args[0] + STRGS['MSG_ERR_INVOLVE_TASK'] + str(errMsg.args[1])) machinesList.clear() itinerariesList.clear() if flagForExit: self.destroy()
def exportRandomDataFiles(self): machinesAmount = 0 itinerariesAmount = 0 arrAmount = [machinesAmount, itinerariesAmount] machinesRandomList =[] itinerariesRandomList = [] #python only allow pass-by-object, so this is only way to get numbers #from next gui guiMatrixParam.GuiMatrixParam(self, arrAmount).wait_window() self.focus_force() if all(x != 0 for x in arrAmount): machinesAmount, itinerariesAmount = arrAmount for mach in range(machinesAmount): machinesRandomList.append(Machine("M"+str(mach+1))) for itin in range(itinerariesAmount): itinObj = Itinerary() itinObj.name = "Itinerary "+str(itin+1) for rndTask in range(randint(1, machinesAmount)): t = Task("Task "+str(rndTask+1),randint(5, 25), machinesRandomList[randint(0, machinesAmount-1)]) itinObj.tasksList.append(t) itinerariesRandomList.append(itinObj) exItinerariesToJSON = [] #export machines in kinda serializable form for itin in itinerariesRandomList: exItinerariesToJSON.append(itin.exportToDict()) exMachinesToJSON = [] for mach in machinesRandomList: exMachinesToJSON.append(mach.exportToDict()) #to have nice structure of json file we store dictionary data in one #file exportData = {} exportData['itineraries'] = exItinerariesToJSON exportData['machines'] = exMachinesToJSON try: fileName = STRGS['TITLE_PROGRAM'] + " - randomExport "+ strftime(" %Y%m%d%H%M%S", gmtime())+".json" savePath = "TestCase M"+str(machinesAmount)+" X J"+str(itinerariesAmount)+ strftime(" %Y%m%d%H%M", gmtime()) +"/"+fileName if savePath != "": if not os.path.exists(os.path.dirname(savePath)): os.makedirs(os.path.dirname(savePath)) with open(savePath, 'w', encoding='utf-8') as outfile: json.dump(exportData, outfile, indent=4) #put serialzed json data in outfile saved in savePath directory msg.showinfo(STRGS['OK'], STRGS['MSG_OK_FILE_EXPORTED']) except Exception as err: msg.showerror(STRGS['ERR'], err) machinesRandomList.clear() itinerariesRandomList.clear() #TODO: favicon
def parseData(): """Tries to import JSON JobShop PRO file to program""" machinesList = [] itinerariesList = [] savePath = input("请输入数据保存路径:") with open(savePath, 'r', encoding="utf8") as inputfile: # read file from path importedData = json.loads(inputfile.read()) if list(importedData.keys()) == ["itineraries", "machines"]: imMachines = importedData[ 'machines'] # is first level structure is correct, then split imItineraries = importedData['itineraries'] if len(list(imMachines)) > 0 and len(list(imItineraries)) > 0: for index, dictMachine in enumerate(imMachines): machinesList.append(Machine(imMachines[index]['machineName'])) for _, dictItinerary in enumerate( imItineraries): # for each itinerary check structure tmpItinerary = Itinerary() tmpItinerary.name = dictItinerary['itineraryName'] tmpItineraryTasks = dictItinerary['tasksList'] for i, taskDict in enumerate( tmpItineraryTasks ): # check structure of each task in itinerary if list(tmpItineraryTasks[i].keys()) == [ 'taskName', 'taskMachine', 'taskDuration' ]: taskMachine = tmpItineraryTasks[i]['taskMachine'] if list(taskMachine.keys()) == [ "machineName" ]: # check corectness of elements tmpItinerary.tasksList.append( Task( tmpItineraryTasks[i]['taskName'], float( tmpItineraryTasks[i]['taskDuration']), # parse values to taskList [ mac for mac in taskMachine["machineName"] ])) # add itinerary to global list, beacuse parsing finished itinerariesList.append(tmpItinerary) return machinesList, itinerariesList
def parseNewData(savePath): itinerariesList = [] with open(savePath, 'r', encoding="utf8") as input_file: # read file from path importedData = json.loads(input_file.read()) imitineraryName = importedData['itineraryName'] imtaskList = importedData['tasksList'] insertItinerary = Itinerary() insertItinerary.name = imitineraryName for i, taskDict in enumerate(imtaskList): taskMachine = imtaskList[i]['taskMachine'] insertItinerary.tasksList.append( Task(imtaskList[i]['taskName'], float(imtaskList[i]['taskDuration']), [mac for mac in taskMachine["machineName"]])) itinerariesList.append(insertItinerary) return itinerariesList
def addNewItinerary(self): """Runs dialog to add new itinerary""" global machinesList, itinerariesList if not machinesList: messagebox.showerror(STRGS['MSG_ERR_NO_MACH_CREATE'], STRGS['MSG_ERR_NO_MACH_NO_ITINERS']) else: newItinerary = Itinerary() GuiItineraryNew(self, newItinerary, len(itinerariesList)) if newItinerary.itineraryChanged == True: itinerariesList.append(newItinerary) self.lboxItinerariesList.insert(form.END, newItinerary.name)
def dataFileImport(self): """Tries to import JSON JobShop PRO file to program""" global machinesList, itinerariesList if len(machinesList) or len(itinerariesList): answer = msg.askyesno(STRGS['WARN'],STRGS['MSG_WARN_ERASE_DATA'], icon="warning") if answer: pass else: return savePath = askopenfilename(defaultextension=".json", filetypes =(("JSON files",".json"),("All files","*.*"))) if not isStringNotBlank(savePath): return #cancelled? stop this madness now #in case of corrupted file or entering wrong file create backup of #existing data in program machinesListBackup = machinesList[:] #create backup by copying by slicing itinerariesListBackup = itinerariesList[:] importedData = None try: if savePath[-5:].upper().lower() != ".json": #insensitive extension comparision raise ValueError("This is not JSON file!") with open(savePath, 'r', encoding="utf8") as inputfile: #read file from path importedData = json.loads(inputfile.read()) if list(importedData.keys()) == ["itineraries", "machines"]: imMachines = importedData['machines'] #is firstlevel structure is correct, then split imItineraries = importedData['itineraries'] machinesList.clear() itinerariesList.clear() if len(list(imMachines)) > 0 and len(list(imItineraries)) > 0: for index, dictMachine, in enumerate(imMachines): if list(dictMachine.keys()) == ["machineName"]: #if structure of machine element is correct if isStringNotBlank(imMachines[index]['machineName']): #if not empty, parse values from dictionary machinesList.append(Machine(imMachines[index]['machineName'])) else: raise ValueError("Name of machine is empty. This is illegal!") else: raise ValueError("Machine is not correct") for _, dictItinerary in enumerate(imItineraries): #for each itinerary check structure if list(dictItinerary.keys()) == ["itineraryName", "tasksList"]: tmpItinerary = Itinerary() if isStringNotBlank(dictItinerary['itineraryName']): #and correctness tmpItinerary.name = dictItinerary['itineraryName'] if len(list(dictItinerary['tasksList'])) > 0: #if tasks not empty tmpItineraryTasks = dictItinerary['tasksList'] for i, taskDict in enumerate(tmpItineraryTasks): #check structure of each task in itinerary if list(tmpItineraryTasks[i].keys()) == ['taskName', 'taskMachine', 'taskDuration']: taskMachine = tmpItineraryTasks[i]['taskMachine'] if list(taskMachine.keys()) == ["machineName"]: #check corectness of elements if isStringNotBlank(tmpItineraryTasks[i]['taskName']) and isStringNotBlank(taskMachine["machineName"]) and tmpItineraryTasks[i]['taskDuration'] > 0: tmpItinerary.tasksList.append(Task(tmpItineraryTasks[i]['taskName'], float(tmpItineraryTasks[i]['taskDuration']), #parse values to taskList Machine(taskMachine["machineName"]))) else: raise ValueError("Task properties are incorrect.") #anything wrong? throw exception! else: raise ValueError("Machine in task is not correct") else: raise ValueError("One of tasks in itinerary is not correct") itinerariesList.append(tmpItinerary) #add itinerary to global list, beacuse parsing finished else: raise ValueError("List of task in itinerary is not correct") else: raise ValueError("Itinerary name is empty. This is illegal!") else: raise ValueError("Structure of itineraries is invalid!") else: raise ValueError("Itineraries or machines lists is empty or structure is not correct!") else: raise ValueError("Itineraries or machines structure is invalid!\nProbably not an JobShop JSON file!") #at this stage values should be OK, but check if machines are #not twisted and if that all itineraries have unique names for testItinObj in itinerariesList: for testTaskObj in testItinObj.tasksList: if not testTaskObj.machine.name in [mach.name for mach in machinesList]: raise ValueError(testTaskObj.name + " in " + testItinObj.name + " have invalid machine.\nData is incompatibile!") if len([testItinObj.name for testItinObj in itinerariesList]) != len(set([testItinObj.name for testItinObj in itinerariesList])): raise ValueError("Not all itineraries have unique names!\nData is incompatibile!") #msg.showinfo(STRGS['OK'], STRGS['MSG_OK_FILE_IMPORTED']) #notify #user that succeded #TODO: move errors string to globaldata file except ValueError as err: msg.showerror(STRGS['ERR'], err) machinesList = machinesListBackup[:] itinerariesList = itinerariesListBackup[:] except: msg.showerror("Unexpected " + STRGS['ERR'], sys.exc_info()) #in case if anything unexpected happen pop up machinesList = machinesListBackup[:] #and restore deleted data from backup itinerariesList = itinerariesListBackup[:] finally: self.updateMainLabelsConfiguration()