def getEmptySchedule(self): tmp = Schedule() # print(self) # print("Schedule size: {}, {}".format(len(self.rooms), self.NUM_TIME_SLOTS)) tmp.Schedule(len(self.rooms), self.NUM_TIME_SLOTS) # print("LEN ROOMS::") # print(len(self.rooms)) # print(len(tmp.schedule)) for i in range(len(self.rooms)): for j in range(self.NUM_TIME_SLOTS): # print("i {} j {}".format(i, j)) tmp.schedule[i][j] = -1 return tmp
def find_valid_schedules(course_list, valid_schedules): '''Finds all possible schedule combinations of the courses in course_list All courses in the list will be in each schedule Parameters: course_list (Course[]): list of the Courses to be put into the schedules valid_schedules (Sections[]): list of valid Schedules Returns: Schedule[]: list of schedules with the required courses ''' new_schedules = [] if len(course_list) == 0: return valid_schedules course = course_list.pop() if len(valid_schedules) == 0: for section in course.sections: new_schedule = Schedule() new_schedule.addSection(section) new_schedules.append(new_schedule) else: for schedule in valid_schedules: for section in course.sections: new_schedule = copy.deepcopy(schedule) try: new_schedule.addSection(section) new_schedules.append(new_schedule) except ScheduleError: pass except: print("Error in find_rc_options()") if len(new_schedules) == 0: raise NoSolutionsError return find_valid_schedules(course_list, new_schedules)
def research(self): data = self.get_input() z_arr = [] perfect_arr = [] schedule = Schedule() for data_set in data: d = data_set[1] jobs = data_set[2] num_machines = data_set[3] machines = data_set[4] z_arr.append( schedule.tardiness( d, schedule.build_schedule(self.num_d, d, jobs, num_machines, machines))) d = [sum(jobs[0]), sum(jobs[0]) + sum(jobs[1])] perfect_arr.append( schedule.tardiness( d, schedule.build_schedule(self.num_d, d, jobs, num_machines, machines))) self.compare(z_arr, perfect_arr)
def update(requests, experts, scheduleTime): """ Runs the matching function for each client request. Requires: requests (ClientsCollection), the collection of clients Requires: experts (ExpertsCollection), the collection of experts Ensures: tuple of (schedule, updatedExperts) schedule (Schedule) is the collection of matches for the schedule file. updatedExperts (ExpertsCollection) is the updated list of experts. """ newExperts = ExpertsCollection(experts.getExpertsList()) scheduleOutput = Schedule() # Running each of the clients in the requests collection parameter # through the matchClient function. Updating the Experts each time, # generating a Schedule collection and an updated Experts collection. for client in requests.items(): matchResults = matchClient(client, newExperts, scheduleTime) scheduleOutput.addToSchedule(matchResults[0]) newExperts = matchResults[1] return scheduleOutput, newExperts
def printCalendar(self, day, month, year): #months[i] = name of month i #leave empty so that months[1] = "January" months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] #days[i] = number of days in month i days = [0,31,28,31,30,31,30,31,31,30,31,30,31] #check for leap year if (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0): days[2] = 29 # calculate the number of shifts and weeks covered myDict = self.calculate(len(self.workers), month, year, day, days[month], self.dayCannotWork()) #print calendar header print " " + months[month] + " " + str(year) print " S M Tu W Th F S" # get calendar and schedule myCalendar = self.generateCalendar(month, day, year, days, myDict) myWeekList = Schedule().generateSchedule(myCalendar, self.workers, myDict, self.checkHoliday(month, day), day, self.day(month, day, year), self.dayCannotWork()) #print them out for i in range(0,len(myWeekList)): print " " + ' '.join(p for p in myCalendar[i]) print ' '.join(p for p in myWeekList[i]) return {'calendar': myCalendar, 'schedule': myWeekList}
def __init__(self, size, data): self.schedules = [] self.data = data for i in range(size): x = Schedule(data) x.generate_sample() self.schedules.append(x)
def _crossover_schedule(self, schedule1, schedule2): crossover_schedule = Schedule(self._data).initialize() for i in range(0, len(crossover_schedule.get_lectures())): if rnd.random() > 0.5: crossover_schedule.get_lectures()[i] = schedule1.get_lectures()[i] else: crossover_schedule.get_lectures()[i] = schedule2.get_lectures()[i] return crossover_schedule
def selected(): try: global Global a = Global['MyAgent'](request) return render_template('selected.html', agent=a, schedule=Schedule(a)) except: TB.print_exc() return redirect(url_for('logout'))
def draw_graph(self): schedule = self.get_schedule() tardiness = Schedule().tardiness(self.d, schedule) self.save_result(schedule, tardiness) fig, gnt = plt.subplots() gnt.set_title('Побудований розклад') gnt.set_ylim(0, (self.num_machines + 1) * 10 + 10) gnt.set_xlim( 0, max([ job[0] + job[1] for machine in schedule for due_date in machine for job in due_date ]) + 5) gnt.set_xlabel('Час') gnt.set_ylabel('Машина') gnt.grid(True) yticks = [(i + 1) * 10 + 5 for i in range(self.num_machines)] yticklabels = [str(i + 1) for i in range(self.num_machines)] gnt.set_yticks(yticks) gnt.set_yticklabels(yticklabels) # setting the schedules for i in range(self.num_machines): for j in range(2): gnt.broken_barh( schedule[i][j], ((i + 1) * 10, 9), facecolors=('orange', 'green', 'blue') * len(self.num_jobs), # mark each job with diff color edgecolors='black') # color of borders for due_date in schedule[i]: for job in due_date: gnt.text( x=job[0] + job[1] / 2, # x = gorizontal position of the label (center of the bar) y=(i + 1) * 10 + 4, # y = vertical position of the label s=job[1], # text (length of the job) ha='center', va='center', color='white', size=15) # setting the due dates for i in range(self.num_d): gnt.axvline(x=self.d[i], c='black', linewidth=5) # gnt.text(x=self.d[i] + 0.5, y=1, s=f'd = {self.d[i]}', color='black', size=10) # possible way to # set xtick for due date gnt.set_xticks(list(gnt.get_xticks()) + self.d) # set xtick for due date fig.show()
def api_schedule(): try: global Global a = Global['MyAgent'](request) s = Schedule(a) return (jsonify({'check': True, 'html': s.ToHtml()})) except: TB.print_exc() return (jsonify({'check': False}))
def make_today_schedule(self): events = [event for event in self.events if datetime.datetime.today.date() == event.start.date()] time_available = datetime.timedelta(hours=8) - sum([ev.end - ev.start for ev in events], datetime.timedelta(0)) tasks_scored = [{'task': task, 'score': self._ranking_function(task)} for task in self.tasks] return Schedule(events, self._select_tasks(tasks_scored, time_available))
def GAINIT(self, off): onlR = int(self.n * (1 - self.offP)) GAOP = GAOperator(self.DG, 0, onlR, self.gaN, off) trips = GAOP.getResult() rejs = GAOP.getRejs() shuttles = [] for trip in trips: shuttle = Shuttle(self.MG.depot, trip, [], 0) shuttles.append(shuttle) return Schedule(shuttles, rejs)
def initChromosomes(self, numberOfChromosomes): for i in range(0, numberOfChromosomes): chromosome = Schedule(self.slots, self.rooms, self.courses, self.instructors) chromosome.createSchedule() self.chromosomes.append({ "chromosome": chromosome, "fitness": chromosome.calculateFitness() })
def api_addRemoteInstallerSchedule(): response = {} payload = request.json schedule = Schedule(payload['ip']) schedule.minute = payload['minute'] schedule.hour = payload['hour'] schedule.AddCronSchedule() response['clients'] = REMOTE_CLIENTS_EVENTS response['schedules'] = Schedule.GetCronSchedules() return json.dumps(response)
def __init__(self): self.today = Schedule() # Current schedule self.schedules = { } # Dictionary of schedules like {1:Schedule(date(2015,3,27)),2:Schedule(date...} self.tads = {} # Dict w/ {user_ID: Resource(user_ID), ...} self.watches = {} self.m = Model() self.timeLimit = 360 self.verbose = True self.vars = {}
def classes(): try: global Global a = Global['MyAgent'](request) return render_template('classes.html', agent=a, schedule=Schedule(a), db=DB()) except: TB.print_exc() return redirect(url_for('logout'))
def process_data(data): """The function processes text from the file and returns a list that is used to create a spreadsheet""" # Splitting schedule into sections (0 - general info, 1-5 - days) by "----...----" pattern (2+ dashes in line) divided_schedule = re.split('-{2,}\n*', data) schedule_info = process_header(divided_schedule[0]) scd = Schedule(schedule_info) # processing info about classes and passing it to Schedule scd = process_lessons(scd, divided_schedule[1:]) return scd
def make_schedule(self) -> 'list[Schedule]': schedule = Schedule() schedule_list = [] if len(self.course_manager.courses) > 0: new_schedule_list = [] schedule_list = schedule.add_course(self.course_manager.courses[0]) for course in self.course_manager.get_courses()[1:]: for schedule in schedule_list: new_schedule_list += schedule.add_course(course) schedule_list = new_schedule_list new_schedule_list = [] return schedule_list
def localOpt(self, routes, t, rejects): routes = self.optimize(routes, t) schedule = Schedule(routes, rejects) for r in schedule.rejects: for i in range(len(schedule.shuttles)): k = self.insert(schedule.shuttles[i], r, t) if k != schedule.shuttles[i].trip: schedule.shuttles[i].trip = k[:] break schedule = Schedule(schedule.shuttles[:], schedule.rejects[:]) idx = 0 while len(schedule.shuttles) < self.shutN: if idx >= len(schedule.rejects): break r = schedule.rejects[idx] shuttle = Shuttle(self.depot, [r, -r], [], t) if self.shuttleAbleS(shuttle)[0]: schedule.shuttles.append(shuttle) idx += 1 return Schedule(schedule.shuttles[:], schedule.rejects[:])
def make_today_schedule(self): # TODO: Add logic to handle task <-> project dependence # TODO: Add logic to handle task <-> task dependence # TODO: Add logic to handle task <-> training dependence events = [event for event in self.events if datetime.datetime.today().date() == event.start.date()] time_available = datetime.timedelta(hours=8) - sum([ev.end - ev.start for ev in events], datetime.timedelta(0)) tasks_scored = [{'task' : task, 'score' : self._ranking_function(task)} for task in self.tasks] return Schedule(events, self._select_tasks(tasks_scored, time_available))
def member_schedule(MASTER, avails, name, other): m_sched = Schedule(MASTER.start, MASTER.end, name, other) # Set array/schedule size to same as MASTER for i in range(len(m_sched.array)): # Modify array with avails day_avail = avails[ i] # At this step, still strings (no dateetime conversion) dt_se = dtconvert.convert_to_datetime( day_avail, MASTER, False) # UPDATE: dt_se is the 2D list ("ranges") m_sched = modify_schedule(m_sched, dt_se, i) # new version return m_sched
def api_removeRemoteInstallerSchedule(): response = {} ip = request.args.get('ip', '') hour = request.args.get('hour', '') minute = request.args.get('minute', '') schedule = Schedule(ip) schedule.minute = minute schedule.hour = hour schedule.RemoveCronSchedule() response['clients'] = REMOTE_CLIENTS_EVENTS response['schedules'] = Schedule.GetCronSchedules() return json.dumps(response)
def schedule(): data = request.get_data().decode() data_dict = json.loads(data) year = '2020' month = data_dict['month'] for team in teams_data: if team['abbreviation'] == data_dict['team']: the_team = team break team = the_team['teamName'].lower().replace(' ', '') team_abbr = the_team['abbreviation'] with open('schedule_data.json', 'r') as f: schedule_data = json.loads(f.read()) if not schedule_data.get(team_abbr): schedule = Schedule(team, month, year) schedule_data[team_abbr] = { 'data': the_team, 'schedule': { year: { month: schedule.month_data } } } elif not schedule_data[team_abbr]['schedule'].get(year): schedule = Schedule(team, month, year) schedule_data[team_abbr]['schedule'][year] = { month: schedule.month_data } elif not schedule_data[team_abbr]['schedule'][year].get(month): schedule = Schedule(team, month, year) schedule_data[team_abbr]['schedule'][year][month] = schedule.month_data with open('schedule_data.json', 'w') as f: f.write(json.dumps(schedule_data)) return json.dumps(schedule_data[team_abbr]['schedule'][year][month])
def index(season=2015): season = int(season) champ = season - 1 # render current season if (not (champ in availableSeasons)): # render season not available print 'no data for ' + str(season) return redirect(url_for('index')) #data = season parser = HReferenceParser('app/static/data/' + str(season) + '.csv') games = parser.getGames() schedule = Schedule(games) gameLog = GameLog() stats = Stats() beltHolder = availableSeasons[champ] defendingChamp = beltHolder beltGame = None for g in schedule.games: beltGame = stats.analyzeGame(g, beltHolder) if beltGame: gameLog.addGame(beltGame) beltHolder = beltGame.getBeltHolderAfterGame() upcomingChampGame = schedule.getUpcomingChampionshipGame(beltHolder) upcomingChampGameIfHomeTeamWins = None upcomingChampGameIfAwayTeamWins = None if upcomingChampGame: upcomingChampGameIfHomeTeamWins = schedule.getUpcomingChampionshipGame( upcomingChampGame.getHomeTeam(), upcomingChampGame.getAwayTeam()) upcomingChampGameIfAwayTeamWins = schedule.getUpcomingChampionshipGame( upcomingChampGame.getAwayTeam(), upcomingChampGame.getHomeTeam()) data = {'id': beltHolder.getID(), 'name': beltHolder.getName()} return render_template( 'index.html', games=gameLog.getGames(), availableSeasons=availableSeasons, defendingChamp=defendingChamp, beltHolder=beltHolder, isOngoingSeason=season, stats=stats, gameLog=gameLog, upcomingChampGame=upcomingChampGame, upcomingChampGameIfHomeTeamWins=upcomingChampGameIfHomeTeamWins, upcomingChampGameIfAwayTeamWins=upcomingChampGameIfAwayTeamWins, sortedStats=stats.getSortedStats(), currentSeason=season, )
def generate(eventData, competitors, debug): activeSchedule = Schedule( ) # Create object for initial schedule. Probably add something to store all these objects externally later activeSchedule.events = copy.deepcopy( eventData) # Create a local instance of eventData[] seniors = [] team = [] # Assign periods randomly for self-schedule eventData for obj in activeSchedule.events: if (obj.selfSchedule == True): obj.period = random.randint(1, 6) # Loop through all the possible competitor slots in an event. for phase in range(3): # Shuffle the event lsit so that there is no bias as to when the event is random.shuffle(activeSchedule.events) # Loop through each event in the current schedule for event in activeSchedule.events: # If the event isn't filled yet if len(event.competitors) < event.size: # If we can still add people to the team, get the best competitor out of everyone if len(team) < 15: competitor = Competitor.getBestCompetitor( competitors, event.name, event.period, seniors, MAX_GRADE, MAX_QUANTITY) # If we're full, get the best competitor out of the people on the team already else: competitor = Competitor.getBestCompetitor( team, event.name, event.period, seniors, MAX_GRADE, MAX_QUANTITY) # Now that the competitor has been added to this time slot, they are occupied competitor.occupied.append(event.period) # Add the competitor to the list of poeple competing in the event event.competitors.append(competitor) # Add the competitor to the list of seniors if they are a senior and aren't already there if competitor.grade == MAX_GRADE and competitor.name not in seniors: seniors.append(competitor.name) # Add the competitor to the competing team roster if they aren't already there if competitor not in team: team.append(competitor) # Reset the occupied status of the competitors for the next schedule for c in competitors: c.occupied = [] activeSchedule.members = team return activeSchedule
def __init__(self): self.planes = {} self.instructors = {} self.students = {} self.syllabus = {} #Dictionary of syllabus events like {-3: Event(-3), -2: Event(-2), ... } self.today = Schedule(date.today()) #Current schedule self.schedules = {} #Dictionary of schedules to be written like {1:Schedule(date(2015,3,27)),2:Schedule(date...} self.sevents = {} #Dictionary containing decision variables for all possible student sorties within date range self.ievents = {} #Dictionary containing decision variables for all possible instructor sorties within date range self.m = Model() self.totalFlightDays = 1 self.timeLimit = 120 self.verbose = True self.backToBack = False
def pfm_setup(self, vt): # vt = JobShop() vt.verbose = False d = date(2016,2,13) for i in range(1, 17): vt.schedules[i] = Schedule(d + timedelta(days = i)) if not i % 7: vt.schedules[i].blank = True else: self.create_waves(vt.schedules[i]) self.event_setup(vt,4) self.student_setup(vt,2) self.instructor_setup(vt,1) self.plane_setup(vt,1) return vt
def generate_lists(self): bottom = True for i in range(0, len(self._transactions)): if self._transCounter[i] < len(self._transactions[i]): self._list.append(self._transactions[i][self._transCounter[i]]) self._transCounter[i] += 1 self.generate_lists() self._transCounter[i] -= 1 self._list.pop() bottom = False if bottom: # print(self._list) sch = Schedule(self._list) if sch.is_conflict_serializable(): self._counter += 1 print(sch.get_printable_schedule())
def addDoctors(self): d1 = Doctor('Daniel', 'Hagan', 'Opthalmologist', []) d2 = Doctor('Bravo', 'Gilbert', 'Radiologist', []) d3 = Doctor('Steven', 'Seagal', 'Cardiologist', []) d4 = Doctor('Igor', 'Dondon', 'Oncologist', []) self.doctors.append(d1) self.doctors.append(d2) self.doctors.append(d3) self.doctors.append(d4) # generating schedule for doctors for doctor in self.doctors: for day in range(1): # set number of days of program for hour in range(1, 8): # set number of hours per day today = date.today() schedule = Schedule(today, 8 + hour, 9 + hour, doctor) doctor.addSchedule(schedule)
def run_check(): """Main function""" # defines ScheduleManager Class sm = ScheduleManager('Schedules') # Grabs all files in Schedules Directory schedule_files = fm.get_files('Schedules') # Grabs all files in the Requests Directory request_file = fm.get_files('Requests') for i in range(len(schedule_files)): # assign the excel data frame to respective variable schedule = fm.read_file('Schedules', schedule_files[i]) request = fm.read_file('Requests', request_file[0]) schedule = Schedule(schedule_files[i].replace('.xlsx', ''), schedule) request = Request(request_file[0], request) # Uses constraint.py to check the schedule valid = c.run_check(schedule, request) # Is the schedule valid? if True check fitness, if false print error log if valid[1]: # Find schedule attributes schedule.set_priorities( check_priorities(schedule.experiments, request.experiments)) schedule.set_fields( check_fields(schedule.experiments, request.experiments)) schedule.set_acc( check_acc(schedule.experiments, request.experiments)) # Fitness checks output = calculate_total_fitness(request, schedule) schedule.set_fitness(output[0]) # Generates output schedule.set_output(output[1]) sm.add_schedule(schedule) else: print(schedule) print('Invalid Schedule:', valid[0]) # sorts the schedules in the schedule manager by fitness values sm.sort_by_fitness() for schedule in sm.schedules[:]: fm.write_fitness(schedule.output, schedule.file_name)