def __init__(self, name): self.name = name self.plan = [] self.operatingState = VehicleState.vsNotStarted self.currentStatus = VehicleStatus.PARKED currentLink = str(traci.vehicle.getRoadID(self.name)) self.lastLink = currentLink currentPos = float(traci.vehicle.getLanePosition(self.name)) self.lastPos = currentPos self.visited = [] self.visited.append(Stop(-1, currentLink, currentPos, StopType.DEPOT)) self.totalPassengers = 0 self.totalDistance = 0 self.nextUpdate = None self.itineraryPenalty = 0 self.countPassengers = 0 self.capacity = 10 self.currentPassengers = [] self.end = 3660 self.parkedLink = currentLink self.parkedPos = currentPos self.occupancyTime = 0 depotStop = Stop(-1, "out", 0, StopType.DEPOT, self.end) traci.vehicle.setStop(self.name, currentLink, currentPos, 0, self.end*MILLISECONDS) self.plan.append(depotStop) self.actualEnd = self.end self.shared = 0 self.deadheading = 0 self.i = Vehicle.num Vehicle.num += 1
def test_build_mega_stops(self): stops = [Stop(1, 0, 90), Stop(2, 10, 45)] groups = {0: [0, 1]} _ = MegaStopFac(0) mega_stops = _.build_mega_stops(groups, stops) self.assertEqual(mega_stops[0].id, "M0") self.assertEqual(mega_stops[0].lat, 0) self.assertEqual(mega_stops[0].lon, 90)
def __init__(self): # dedicate to retired KCM bus No. 2333 self.number = '2333' self.id = '2333' self.line_id = '00' self.line_name = '0 - Unknown' self.position = Position() self.adjacent_stops = [Stop(), Stop()]
def addPerson(self, person, puPosition, doPosition, penalty): """ add a person to a vehicle's plan, insert stops at specified places (Person, int, int, float)""" # extract details from person personID = person.personID link1 = person.getOrigin().link pos1 = person.getOrigin().pos request = person.getOrigin().serviceTime link2 = person.getDestination().link pos2 = person.getDestination().pos # add stops to plan self.plan.insert(puPosition, Stop(personID, link1, pos1, StopType.PICKUP, request)) self.plan.insert(doPosition, Stop(personID, link2, pos2, StopType.DROPOFF)) print "Person " + str(personID) + " now waiting at " + link1 + "," + \ str(pos1) + " going to " + link2 + "," + str(pos2) + \ " waiting for " + self.name print self.name, "plan:" for i in range(0, len(self.plan)): self.plan[i].printLn() # set person to allocated person.allocated() # reroute vehicle as plan is updated self.currentLink = network.getVehicleCurrentEdge(self.name) self.currentPos = network.getVehicleCurrentPosition(self.name) if self.currentStatus == VehicleStatus.PARKED: self.currentStatus = VehicleStatus.BOOKED if self.operatingState != VehicleState.vsRunning: # raise from parking position at depot print self.parkedLink, self.parkedPos traci.vehicle.setStop(self.name, self.parkedLink, self.parkedPos, 0, 0) else: # raise from parking position traci.vehicle.setStop(self.name, self.parkedLink, self.parkedPos, 0, 0) myNextStop = self.plan[0] traci.vehicle.changeTarget(self.name, myNextStop.link) traci.vehicle.setStop(self.name, myNextStop.link, myNextStop.pos, 0, DWELLTIME) print self.name, " heading for ", myNextStop.personID, " at", \ myNextStop.link, myNextStop.pos self.operatingState = VehicleState.vsRunning
def addBookingToOptimumItinerary(self, person, step): """ determine best vehicle for person and add them to it (Person, int)""" vehicle = None penalty = 0.0 bestVehiclePenalty = 10000000 bestIncrPenalty = 100000000 puPosition = None # link duPosition = None # link bestVehicle = None bestPUPosition = None # link bestDOPosition = None # link puLink = None doLink = None # link # extract values from person personID = person.personID link1 = person.getOrigin().link pos1 = person.getOrigin().pos link2 = person.getDestination().link pos2 = person.getDestination().pos puLink = Stop(personID, link1, pos1, StopType.PICKUP) doLink = Stop(personID, link2, pos2, StopType.DROPOFF) # iterate over all vehicles for veh in self.fleet.values(): if veh.getState() <= VehicleState.vsRunning: # only if not stopped (puPosition, doPosition, penalty) = \ veh.calcTentativeItineraryPenalty(puLink, doLink, step) print veh.name, penalty, penalty - \ veh.calcCurrentItineraryPenalty(step) if penalty < 900000: incrPenalty = penalty - \ veh.calcCurrentItineraryPenalty(step) # update if best incremental penalty if incrPenalty < bestIncrPenalty: bestVehicle = veh bestIncrPenalty = incrPenalty bestVehiclePenalty = penalty bestDropoffPosition = doPosition bestPickupPosition = puPosition # add person to best vehicle if bestVehicle != None: bestVehicle.addPerson(person, bestPickupPosition, bestDropoffPosition, bestVehiclePenalty) return 0 else: return -1
def next_state(self): if self.tag_id == 0 or self.tag_id == 2 or self.tag_id == 9: return turn_tag_position.TurnTagPosition(self.next_input()) elif self.tag_id == 4 or self.tag_id == 7: return search.Search(self.next_input()) else: return Stop(self.next_input())
def test_stop_2_tup(self): tree = StopBallTree(self.stops) s = [Stop('g', 0, 0)] self.assertFalse(tree.stop_2_tup(s)[0].shape == (1, 2), msg='Stops returning not correct shape') self.assertFalse((tree.stop_2_tup(s)[0] == 0).sum() != 2, msg='Stops returning correct value')
def load_stops(self): stops_file = os.path.join(self.source_folder, 'stops.txt') self.available_files['stops.txt'] = True data = self.open(stops_file) # Iterate over all the stops and puts them in the stops dictionary for i in range(data.shape[0]): stop = Stop() # Required fields stop.id = data['stop_id'][i] stop.name = data['stop_name'][i] stop.lat = data['stop_lat'][i] stop.lon = data['stop_lon'][i] # optional fields available_fields = data.dtype.names if 'stop_code' in available_fields: stop.code = data['stop_code'][i] if 'stop_desc' in available_fields: stop.desc = data['stop_desc'][i] if 'zone_id' in available_fields: stop.zone_id = data['zone_id'][i] if 'stop_url' in available_fields: stop.url = data['stop_url'][i] if 'zone_id' in available_fields: stop.zone_id = data['zone_id'][i] if 'location_type' in available_fields: stop.location_type = data['location_type'][i] if 'parent_station' in available_fields: stop.parent_station = data['parent_station'][i] if 'timezone' in available_fields: stop.timezone = data['timezone'][i] if 'wheelchair_boarding' in available_fields: stop.wheelchair_boarding = data['wheelchair_boarding'][i] self.stops[stop.id] = stop del (data)
def setUp(self): """""" self.ids = ['a', 'b', 'c', 'd', 'e'] self.lat = [10, 20, 30, 40, 50] self.lon = [15, 30, 45, 60, 75] self.routes = [1, 1, 2, 2, 3] self.stops = [Stop(self.ids[i], self.lat[i], self.lon[i]) for i in range(len(self.ids))]
def initializeStops(self, lines): stops = [] for line in lines: if "destination" not in line: line["destination"] = "" stops.append( Stop(line["stop_id"], line["line"], line["destination"] or "")) return stops
def getStopList(self): response = requests.get("http://webservices.nextbus.com/service/publicXMLFeed?command=routeConfig&a={}&r={}".format(self.agency.tag,self.tag)) body = ElementTree.fromstring(response.content) routeTag = body.find('route') for stopTag in routeTag.findall('stop'): self.stops.append(Stop(stopTag.attrib))
def read_stops(in_file): stops = {} with open(in_file, 'r') as file: reader = csv.reader(file) for row in reader: try: tmp = Stop(int(row[0]), int(row[1]), int(row[2])) stops[tmp.id] = tmp except: pass return stops
def test_mega_stop(self): stops = [ Stop(self.ids[i], self.lat[i], self.lon[i]) for i in range(len(self.ids)) ] m1 = MegaStop(self.ids[0], [stops[0], stops[1]], True) self.assertEqual(m1.lat, 15) self.assertEqual(m1.lon, 22.5) self.assertEqual(m1.to_tuple(), ('a', 15, 22.5)) m1 = MegaStop(self.ids[0], [stops[0], stops[1]]) self.assertEqual(m1.lat, 10) self.assertEqual(m1.lon, 15)
def getCurrentPos(self): """ return current position """ if self.currentStatus != VehicleStatus.PARKED: currentLink = network.getVehicleCurrentEdge(self.name) currentPos = network.getVehicleCurrentPosition(self.name) else: currentLink = self.lastLink currentPos = self.lastPos currentStop = Stop(-1, currentLink, currentPos, StopType.CURRENT) return currentStop # Stop
def next_state(self): input_state = self.current_input[2] # this is a string if input_state == "Drive": return Drive(self.next_input()) elif input_state == "Search": return search.Search(self.next_input()) elif input_state == "PrepareToCatch": return PrepareToCatch(self.next_input()) elif input_state == "DriveUntilTagDistance": return drive_tag_distance.DriveUntilTagDistance(self.next_input()) else: print "DriveDistance --> Stop()" return Stop(self.next_input())
def test_query_radius(self): """ @todo make new test data :return: """ s = [Stop("g", 0, 0)] tree = StopBallTree(s) import math lat = 10 * math.pi / 180 lon = 15 * math.pi / 180 r = math.sqrt(lat **2 + lon ** 2) _ = tree.query_radius(s,r + 1) self.assertEqual(len(_[s[0]]),1) self.assertEqual(_[s[0]][0],s[0])
def readFile(self, fileName): """ read people from a file format: id, callTime, requestTime, originLink, originPos, destLink, destPos (string)""" with open(fileName, 'rb') as pFile: persons = csv.reader(pFile, delimiter=',') for row in persons: assert len(row) == 7 i = row[0] entry = int(row[1]) request = int(row[2]) originLink = row[3] originPos = float(row[4]) destLink = row[5] destPos = float(row[6]) p = Person(i) p.setCallTime(entry) p.setRequestTime(request) p.setOD( Stop(i, originLink, originPos, StopType.PICKUP, request), Stop(i, destLink, destPos, StopType.DROPOFF)) self.addPerson(p)
def __init__(self, sim_config): self.delta_t = sim_config.delta_t self.sim_config = sim_config # init bus generator (for scheduling arrivals) self.generator = Generator( sim_config.ln_arrival_dict, sim_config.ln_service_dict, self.sim_config.sim_duration, ) ### init the stop self.stop = Stop(sim_config.berth_num, sim_config.is_capacity_case) # running properties self._curr_time = 0 self.ln_total_bus_dict = defaultdict(dict)
def next_state(self): if self.current_input == 0: return search.Search(self.next_input()) elif self.current_input == 5: return Release(self.next_input()) elif self.current_input == 6: return PrepareToCatch(self.next_input()) elif self.current_input == 8: return PrepareToCatch(self.next_input()) elif self.current_input == 9: return PrepareToCatch(self.next_input()) return Stop(self.next_input())
def test_stop(self): stops = [ Stop(self.ids[i], self.lat[i], self.lon[i]) for i in range(len(self.ids)) ] self.assertEqual(stops[0].to_tuple(), ('a', 10, 15), msg='Stop 2 Tuple Not working') self.assertEqual(stops[0] == stops[1], False, msg='Stops equivalent not working') self.assertEqual(hash(stops[0]), hash(self.ids[0]), msg='Stops hash not working') self.assertEqual(stops[0] > stops[1], False, msg="Stops greater than not working") self.assertEqual(stops[0] < stops[1], True, msg="Stops less than not working")
def __init__(self): rospy.on_shutdown(self.shutdown_cb) self.robot_name = rospy.get_name() self.robot = Robot() self.controllers = { "rc": RCTeleop(), "gtg": GoToGoal(self.robot), "stop": Stop() } self.switch_to_state("gtg") self.dd = DifferentialDrive(self.robot.wheelbase, self.robot.wheel_radius) # Initialize TF Broadcaster self.br = tf2_ros.TransformBroadcaster() # Initialize previous wheel encoder ticks self.prev_wheel_ticks = None
def test_query(self): tree = StopBallTree(self.stops) s = [Stop("g",0,0)] dist, matches = tree.query(s) self.assertTrue(matches[0] == 0)
def chunkedStops(acs): stops = Stop(stop_filepath="data/stop_data/stops_test_no_officer_id.csv", chunk=True, acs=acs, chunksize=10) return stops.create_summary()
def acs_stops(acs): return Stop(stop_filepath='data/stop_data/stops_test.csv', acs=acs)
def stops_summary(): stops = Stop(stop_filepath='data/stop_data/stops_test.csv') stops.create_summary() return stops
def make_stop(line): stop_infos = line.split(',') return Stop(stop_infos[StopLookup["ID"]], stop_infos[StopLookup["name"]], stop_infos[StopLookup["url"]])
print("%s, bienvenido al juego!" % nombre_jugador) numero_jugador += 1 letra_a_jugar = input("Bueno %s, cual es la letra con la que jugaremos? " % jugadores[0].get_nombre()) # Para evitar que entre los jugadores se copien las respuestas, hacemos uso de getpass, que oculta lo escrito por la terminal print( "ADVERTENCIA!: debido a cuestiones de seguridad, las respuestas de cada jugador no seran visibles a medida que se escriben" ) print( "asi que no te precupes si a medida que escribes no ves nada, asegurate de escribir bien tu respuesta, cuando la tengas, solo presiona ENTER!" ) time.sleep(2) # Se inicia el juego, pasando los jugadores, la letra a jugar, y la configuracion de este juego = Stop(jugadores, configuracion, letra_a_jugar) print("Inicia el juego!") for categoria in juego.get_categorias(): categoria_actual = juego.get_categoria(categoria) # Por cada jugador, hace la pregunta de la categoria correspondiente for jugador in jugadores: respuesta = categoria_actual.realizar_pregunta(jugador.get_nombre(), letra_a_jugar) jugador.agregar_respuesta(categoria, respuesta) # revisa si la respuesta digitada por el jugador es correcta if categoria_actual.buscar_elemento(respuesta, letra_a_jugar): print( "%s, felicitaciones!, parece que tu respuesta tiene buena pinta" % jugador.get_nombre()) else:
def test_stop_2_tup(self): stops = [Stop(1, 0, 90)] _ = MegaStopFac(0) tup = _.stop_2_tup(stops)[0] self.assertAlmostEqual(tup[0], 0) self.assertAlmostEqual(tup[1], 1.5707, places=3)
from stop import Stop model_name = 'blind_with_regularization.model' COM = 'COM9' camera = 1 baudrate = 9600 width = 64 height = 64 prob = 0 label = '' print("loading model .....") model = load_model(model_name) print("model loaded") ard = Arduino(baudrate, COM) ##movleft(),movright() vce = Voice() #left(),right() st = Stop() fac = detect() current = datetime.datetime.now() flag = None cap = cv2.VideoCapture(camera) ret = True prev = None while ret: ret, frame = cap.read() frame = cv2.resize(frame, (640, 480)) faces = fac.faceDetect(frame) ##stop on left ## you have a stop on '''
def __init__(self, sim_duration, dspt_times, \ stop_locs, demand_rates, board_rates, stop_num, demand_start_times, \ link_mean_speeds, link_cv_speeds, link_lengths, link_start_locs, \ cycle_lengths, green_ratios, signal_offsets, signal_locs): self._stop_locs = stop_locs self._demand_rates = demand_rates self._board_rates = board_rates self._demand_start_times = demand_start_times self._link_mean_speeds = link_mean_speeds self._link_cv_speeds = link_cv_speeds self._link_lengths = link_lengths self._link_start_locs = link_start_locs self._cycle_lengths = cycle_lengths self._green_ratios = green_ratios self._signal_offsets = signal_offsets self._signal_locs = signal_locs self._stop_num = stop_num # current simulation time self._curr_time = 0.0 # counting the total bus for creating bus id self._total_bus = 0 # total buses for stats self._total_bus_list = [] # total simulation time self._sim_duration = sim_duration # dispatch plans self._dspt_times = deepcopy(dspt_times) # unchangable ... ### init stops self._stop_list = [] for index, (loc, demand_rate, board_rate, demand_start_time) in \ enumerate(zip(self._stop_locs, self._demand_rates, self._board_rates, self._demand_start_times)): stop = Stop(index, loc, demand_rate, board_rate, demand_start_time) self._stop_list.append(stop) ### init links self._link_list = [] for index, (mean_speed, cv_speed, length, start_loc) in \ enumerate(zip(self._link_mean_speeds, self._link_cv_speeds, self._link_lengths, self._link_start_locs)): link = Link(index, mean_speed, cv_speed, length, start_loc) self._link_list.append(link) ### init signals self._signal_list = [] for index, (cycle_length, green_ratio, offset, start_loc) in \ enumerate(zip(self._cycle_lengths, self._green_ratios, self._signal_offsets, self._signal_locs)): signal = Signal(index, cycle_length, green_ratio, offset, start_loc) self._signal_list.append(signal) ### connect links and signals for index, signal in enumerate(self._signal_list): for link_no, link in enumerate(self._link_list): if signal.start_loc > link._start_loc and signal.start_loc < link._end_loc: link.add_signal(signal) break ### connect stops and links for index, link in enumerate(self._link_list): link(self._stop_list[index]) for index, stop in enumerate(self._stop_list): if index != self._stop_num - 1: stop(self._link_list[index + 1])