def main(): maps_file = '../input/stores.xlsx' initial_solution_file = '../results/4-simulated_annealing.xls' output_file = '../results/5-ant_coloy_opt.xls' print("[INFO] Reading store information from: {}".format(maps_file)) maps = Maps(maps_file) print("[INFO] Reading initial solution from: {}".format(initial_solution_file)) schedule = Schedule() valid_solution = schedule.read_from_xls(initial_solution_file, maps) if not valid_solution: print("[ERROR] Abort: initial solution contains invalid route(s)") return False else: print("[INFO] Start ACO to optimize each route") aco = ACO(maps) aco.optimize_all(schedule) print("[INFO] ACO best schedule score: {}".format(schedule.total_distance)) print("[INFO] Export solution to: {}".format(output_file)) ## Printing and drawing solution # for k in schedule.routes: # print(schedule.routes[k]) # schedule.draw(maps) schedule.export_to_xls(output_file, maps)
def main(): maps_file = '../input/stores.xlsx' initial_solution_file = '../results/1-nearest_neighbors.xls' output_file = '../results/2-two_edge_exchange.xls' print("[INFO] Reading store information from: {}".format(maps_file)) maps = Maps(maps_file) print("[INFO] Reading initial solution from: {}".format( initial_solution_file)) schedule = Schedule() valid_solution = schedule.read_from_xls(initial_solution_file, maps) if not valid_solution: print("[ERROR] Abort: initial solution contains invalid route(s)") return False else: print("[INFO] Initialise neighbors for 2-edge exchange") tex = TwoEdgeExchange(schedule, maps) print("[INFO] Start improving with 2-edge exchange") log = tex.solve() print("[INFO] 2-edge exchange best score: {:.2f}".format( schedule.total_distance)) print("[INFO] Export solution to: {}".format(output_file)) schedule.export_to_xls(output_file, maps)
def main(): args = get_args() output_path = Path(__file__).resolve().parent.joinpath(args.outpath) inplace = args.model in ['SRResNet'] train_generator = LR_HR_generator(args.image_dir, args.batch_size, args.image_size, args.de_num, inplace) test_generator = LR_HR_generator(args.test_dir, args.batch_size, args.image_size, args.de_num, inplace) model = get_model(args.model, args.lr) callbacks = [] callbacks.append( LearningRateScheduler(schedule=Schedule(args.epochs, args.lr))) callbacks.append( ModelCheckpoint( str(output_path) + "/weights.{epoch:03d}-{val_loss:.3f}-{val_PSNR:.5f}.hdf5", monitor="val_PSNR", verbose=1, mode="max", save_best_only=True)) hist = model.fit_generator(generator=train_generator, epochs=args.epochs, steps_per_epoch=args.steps, validation_data=test_generator, verbose=1, callbacks=callbacks) np.savez(str(output_path.joinpath("history.npz")), history=hist.history)
def callback(caller=caller): commit = False with self.smart.new_session() as session: machine = session.query(Machine) \ .join(MachineInterface) \ .options(joinedload("schedules")) \ .filter(MachineInterface.mac == schedule_data["selector"]["mac"]) \ .first() if not machine: logger.error("machine mac %s not in db", schedule_data["selector"]["mac"]) return commit else: machine_already_scheduled = [ s.role for s in machine.schedules ] for role in schedule_data["roles"]: if role in machine_already_scheduled: logger.info( "machine mac %s already scheduled with role %s", schedule_data["selector"]["mac"], role) continue session.add(Schedule(machine_id=machine.id, role=role)) logger.info("scheduling machine mac %s as role %s", schedule_data["selector"]["mac"], role) commit = True session.commit() if commit else None return commit
def test_one_machine_scheduled_cp(self): mac = "00:00:00:00:00:00" with self.smart.new_session() as session: uuid = "b7f5f93a-b029-475f-b3a4-479ba198cb8a" machine = Machine(uuid=uuid) session.add(machine) machine_id = session.query(Machine).filter( Machine.uuid == uuid).first().id session.add( MachineInterface(machine_id=machine_id, mac=mac, netmask=1, ipv4="10.10.10.10", cidrv4="127.0.0.1/8", as_boot=True, gateway="1.1.1.1", name="lol")) session.add( Schedule(machine_id=machine_id, role=ScheduleRoles.etcd_member)) session.add( Schedule(machine_id=machine_id, role=ScheduleRoles.kubernetes_control_plane)) session.commit() ms = ScheduleRepository(self.smart) ret = ms.get_available_machines() self.assertEqual(0, len(ret)) ret = ms.get_roles_by_mac_selector(mac) self.assertEqual([ ScheduleRoles.etcd_member, ScheduleRoles.kubernetes_control_plane ], ret) ret = ms.get_machines_by_roles(ScheduleRoles.etcd_member, ScheduleRoles.kubernetes_control_plane) self.assertEqual(1, len(ret)) ret = ms.get_machines_by_roles(ScheduleRoles.kubernetes_node) self.assertEqual(0, len(ret)) ret = ms.get_machines_by_roles(ScheduleRoles.etcd_member) self.assertEqual(1, len(ret)) ret = ms.get_machines_by_roles(ScheduleRoles.kubernetes_control_plane) self.assertEqual(1, len(ret))
def post(self): a, d = self.request.get('author'), self.request.get('description') # error: missing either key try: schedString = self.request.get('schedulestring') # error: missing parameter jsonSched = simplejson.loads(schedString) # error: bad json s = Schedule(auth = a, desc = d) s.put() # error: some puts succeed while others fail for pt in jsonSched["points"]: # error: not an object, or no "points" key p = Point(sched = s, location = map(int, pt), phase = ['R', 'R']) # error: setting all phases to RR p.put() # error: some puts succeed while others fail # schedule should be post-ed as json string # so parse the string into Schedule's and Point's, then save it # (check out previous versions of scheduler.py for examples of saving) self.response.out.write(simplejson.dumps({'success': 'Schedule was successfully saved!'})) # maybe add the schedule's id? except Exception, e: self.response.out.write(simplejson.dumps({'error': e.message}))
def get(self): id = int(self.request.get('id')) sched = Schedule.get_by_id(id) if sched is None: self.response.out.write(simplejson.dumps({'error': 'no schedule of id ' + str(id)})) else: s = {'author': sched.auth, 'description': sched.desc, 'points': [], 'id': sched.key().id()} for p in sched.points: s['points'].append({'location': p.location, 'phase': p.phase}) self.response.out.write(simplejson.dumps(s))
def select_category(bot, update): uid = update.message.from_user.id message = update.message.text if not user_data.get(uid): user_data[uid] = {} if message == 'Метро': user_data[uid]['category'] = 'metro' data = [ s.metro for s in Schedule.select( Schedule.metro).distinct().order_by(Schedule.metro) ] elif message == 'Возраст': user_data[uid]['category'] = 'age_from' data = [ a.age_from for a in Schedule.select( Schedule.age_from).distinct().order_by(Schedule.age_from) ] elif message == 'Курс': user_data[uid]['category'] = 'course_name' data = [ c.course_name for c in Schedule.select( Schedule.course_name).distinct().order_by(Schedule.course_name) ] elif message == 'Назад': bot.sendMessage(uid, 'Вот предыдущее меню', disable_web_page_preview=True, reply_markup=ReplyKeyboardMarkup(start_keyboard)) return ConversationHandler.END elif message == 'Полное расписание': user_data[uid]['category'] = 'all' bot.sendMessage(uid, 'Тут должно быть раписание на весь месяц', reply_markup=ReplyKeyboardMarkup(start_keyboard)) return ConversationHandler.END else: bot.sendMessage(uid, 'Выбирайте один из вариантов на клавиатуре') return keyboard = [[f'{k}+'] if isinstance(k, int) else [k] for k in data] + [['Назад']] bot.sendMessage(uid, 'Выбирай', reply_markup=ReplyKeyboardMarkup(keyboard)) return THIRD
def main(): maps_file = '../input/stores.xlsx' initial_solution_file = '../results/3-tabu_search.xls' output_file = '../results/4-simulated_annealing.xls' print("[INFO] Reading store information from: {}".format(maps_file)) maps = Maps(maps_file) print("[INFO] Reading initial solution from: {}".format(initial_solution_file)) schedule = Schedule() valid_solution = schedule.read_from_xls(initial_solution_file, maps) if not valid_solution: print("[ERROR] Abort: initial solution contains invalid route(s)") return False else: random.seed(1337) print("[INFO] Start Simulated Annealing") ## I use this configuration to get the result, ## but it will take 1 hour to run # config = { # "steps": 50000, # "Tmax": 10, # "Tmin": 1, # "updates": 100 # } # configuration used to test config = { "steps": 1000, "Tmax": 5, "Tmin": 1, "updates": 10 } sima = VRPAnnealer(schedule, maps, config) tex, e = sima.anneal() print("[INFO] Simulated Annealing best schedule score: {}".format(e)) print("[INFO] Export solution to: {}".format(output_file)) tex.schedule.export_to_xls(output_file, maps)
def req_schedule(mode: str, req_time: float) -> Optional[Schedule]: data_url = "https://splatoon2.ink/data/schedules.json" schedules = requests.get(data_url).json() for schedule in schedules.get(mode, []): start_time = schedule["start_time"] end_time = schedule["end_time"] if start_time <= req_time <= end_time: return Schedule(start_time, end_time, schedule["rule"]["name"], [ create_item(schedule["stage_a"]), create_item(schedule["stage_b"]) ]) return None
def main(): maps_file = '../input/stores.xlsx' initial_solution_file = '../results/2-two_edge_exchange.xls' output_file = '../results/3-tabu_search.xls' print("[INFO] Reading store information from: {}".format(maps_file)) maps = Maps(maps_file) print("[INFO] Reading initial solution from: {}".format( initial_solution_file)) schedule = Schedule() valid_solution = schedule.read_from_xls(initial_solution_file, maps) if not valid_solution: print("[ERROR] Abort: initial solution contains invalid route(s)") return False else: print("[INFO] Start improving schedule with Tabu Search") ts = TabuSearch(schedule, maps, tabu_period=50) ## I use this configuration to get the result, ## but it will take approx. 1 hour to run # if not ts.solve(max_iter=5000, max_no_improvement=100): # return False # configuration used for testing if not ts.solve(max_iter=100, max_no_improvement=None): return False schedule = ts.best_schedule print("[INFO] Tabu search best score: {:.2f}".format( schedule.total_distance)) ## Plotting score for each iterations # plt.plot(ts.log) # plt.show() print("[INFO] Export solution to: {}".format(output_file)) schedule.export_to_xls(output_file, maps) return True
def test_one_machine_full_scheduled_with_strategy_disable(self): mac = "00:00:00:00:00:00" with self.smart.new_session() as session: uuid = "b7f5f93a-b029-475f-b3a4-479ba198cb8a" machine = Machine(uuid=uuid) session.add(machine) machine_id = session.query(Machine).filter( Machine.uuid == uuid).first().id session.add( MachineInterface(machine_id=machine_id, mac=mac, netmask=1, ipv4="10.10.10.10", cidrv4="127.0.0.1/8", as_boot=True, gateway="1.1.1.1", name="lol")) session.add( MachineDisk(path="/dev/sda", size=1024 * 1024 * 1024, machine_id=machine_id)) session.add( MachineCurrentState(machine_id=machine_id, machine_mac=mac, state_name=MachineStates.discovery)) session.add( Schedule(machine_id=machine_id, role=ScheduleRoles.kubernetes_control_plane)) session.add( LifecycleRolling(machine_id=machine_id, strategy="kexec", enable=False)) session.commit() expect = list() expect.append({ 'CIDR': '127.0.0.1/8', 'LastReport': None, 'UpdateStrategy': 'Disable', 'LastChange': None, 'MAC': '00:00:00:00:00:00', 'UpToDate': None, 'FQDN': None, 'DiskProfile': 'S', 'LastState': MachineStates.discovery, 'Roles': ScheduleRoles.kubernetes_control_plane }) ui = user_interface_repo.UserInterfaceRepository(self.smart) data = ui.get_machines_overview() self.assertCountEqual(expect, data)
def solve(self): # get the store list, make sure all stores are visited stores_list = self.maps.get_store_list() visited_stores = [0] schedule = Schedule() # while there is still store to visit # outer loop is to iterate over the routes while (len(stores_list) > 0): route = Route() have_time = True # inner loop is to build a route while have_time and len(stores_list) > 0: curr_store_id = route.get_curr_store() next_store_id = self.maps.get_next_nearest_store( curr_store_id, visited_stores) # check if the closest store is feasible # to be visited have_time = route.add_next_store( next_store_id, self.maps ) # if it is visited if have_time: visited_stores.append(next_store_id) stores_list.remove(next_store_id) # finish route by going back to HQ dist_to_hq = self.maps.get_distance(route.get_curr_store(), 0) route.end_day(dist_to_hq) schedule.add(route) return schedule
def submittal(): """Getting variables from medication registeration form""" logged_in_user_id = session.get("user_id") print logged_in_user_id logged_in_user_email = session.get("email") print logged_in_user_email if logged_in_user_id: reason = request.form.get("reason") med_name = request.form.get("med_name") dosage_quantity = int(request.form.get("dosage_quantity")) food = bool(request.form.get("food")) water_boolean = bool(request.form.get("water")) daily_schedule = request.form.getlist("daily_schedule") new_prescription = Prescription( user_id=logged_in_user_id, reason=reason, med_name=med_name, dosage_quantity=dosage_quantity, food=food, drink=water_boolean, ) db.session.add(new_prescription) db.session.commit() this_prescription = Prescription.query.filter_by( med_name=med_name, user_id=logged_in_user_id).first() print "THIS PRESCRIPTION: ", this_prescription for time_string in daily_schedule: # 1.first convert time string into datetime object that's just the time in HOUR:MINUTE:SECONDS format timestamp = datetime.strptime(time_string, "%H:%M:%S") # 2. make dosage time object: new_dosage_time = Schedule( user_id=logged_in_user_id, timestamp=timestamp, prescription_id=this_prescription.prescription_id) # 3. do db.add db.session.add(new_dosage_time) db.session.commit() flash("Medication %s added." % med_name) return redirect("/") else: flash("User is not logged in.") return redirect("/login")
def test_schedule(): test_params = SCHEDULE_TEST_PARAMS[0] new_schedule = Schedule(test_params.values()) new_schedule.build_blocks() print(new_schedule) nbs = new_schedule.find_neighborhood() print(nbs[0].eval_consecutive_days()) print(nbs[0].eval_number_of_days()) print(nbs[0].eval_days_off()) print(nbs[0].working_days_num()) s1 = Schedule(test_params.values()) s11 = Schedule(test_params.values()) s2 = Schedule(SCHEDULE_TEST_PARAMS[1].values()) print(s1 == s11) print(s1 == s2)
def load_schedules(): """Load schedules into database.""" for i in range(10): schedule_id = db.Column(db.Integer, autoincrement=True, primary_key=True) daynight = "Day" script = "Pages 1-4" shoot_time = "10:00 AM" scene = "Bedroom Scene" shoot_description = "Bob begins to start his day, converses with mother, Lisa." talent = "Bob Eliott, Lisa Stremner" new_sched = Schedule(daynight=daynight, script=script, shoot_time=shoot_time, scene=scene, shoot_description=shoot_description, talent=talent) db.session.add(new_sched) db.session.commit()