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 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 __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 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 __stops(self): if self._stops is None: data = self.__get_json_attr('stops', agencies=self.id) self._stops = { obj['id']: Stop.from_json(self, obj) for obj in data } return self._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
class Simulator(object): 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 reset(self): self.generator.reset() self.stop.reset() self._curr_time = 0 self.ln_total_bus_dict = defaultdict(dict) def move_one_step(self): dspt_buses = self.generator.dispatch(self._curr_time) for dspt_bus in dspt_buses: self.stop.enter_bus(dspt_bus) self.ln_total_bus_dict[dspt_bus.ln_id][dspt_bus.bus_id] = dspt_bus self.stop.operation(self.delta_t, self._curr_time) self._curr_time += self.delta_t
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 _process_route_response(self, result): res = {} for route_id in result: response_data = result[route_id] stops = response_data['result']['stops'] patterns = response_data['result']['lineTraces']['patternTraces'] res[route_id] = Route( route_id, [Stop.deserialize_from_json_obj(stop) for stop in stops], [ Pattern.deserialize_from_json_obj(pattern) for pattern in patterns ]) return res
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 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 from_json(cls, data): """Load Operator from GeoJSON.""" agency = cls(**data) # Add stops stops = {} for feature in data['features']: if feature['onestopId'].startswith('s'): stop = Stop.from_json(feature) stops[stop.onestop()] = stop # Add routes for feature in data['features']: if feature['onestopId'].startswith('r'): route = Route.from_json(feature) # Get stop by id, add as child. for stop in feature['serves']: route.pclink(route, stops[stop]) agency.pclink(agency, route) return agency
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
class TestStop(unittest.TestCase): @classmethod def setUp(self): print("setUp") self.stopMountJoy = Stop("MJ", "Mount Joy GO", "https://www.gotransit.com/en/stations-stops-parking/find-a-station-or-stop/results?stationCode=MJ") self.stopUnionStation = Stop("UN", "Union Station", "https://www.gotransit.com/en/stations-stops-parking/find-a-station-or-stop/results?stationCode=UN") def test_id(self): print("test_id") self.assertEqual(self.stopMountJoy.get_id(), "MJ") self.assertEqual(self.stopUnionStation.get_id(), "UN") def test_name(self): print("test_name") self.assertEqual(self.stopMountJoy.get_name(), "Mount Joy GO") self.assertEqual(self.stopUnionStation.get_name(), "Union Station") def test_url(self): print("test_url") self.assertEqual(self.stopMountJoy.get_url(), "https://www.gotransit.com/en/stations-stops-parking/find-a-station-or-stop/results?stationCode=MJ") self.assertEqual(self.stopUnionStation.get_url(), "https://www.gotransit.com/en/stations-stops-parking/find-a-station-or-stop/results?stationCode=UN")
def bootstrap_gtfs(self, gtfs_feed, feedname='unknown', populate=True): # Make sure the GTFS feed is completely loaded. gtfs_feed.preload() # Set onestopId if 'onestopId' not in self.data: self.data['onestopId'] = self.make_onestop( geohash=geom.geohash_features(gtfs_feed.stops()), name=feedname ) feedid = self.onestop() # Override operator Onestop IDs agency_onestop = {} for i in self.operatorsInFeed(): agency_onestop[i['gtfsAgencyId']] = i['onestopId'] # Check for agencies. gtfs_agencies = [] for gtfs_agency in gtfs_feed.agencies(): if populate or gtfs_agency.id() in agency_onestop: gtfs_agencies.append(gtfs_agency) else: # Unknown agency pass if not gtfs_agencies: return # Create TL Stops stops = {} # sort; process all parent stations first. order = [] order += sorted(filter(lambda x:x.location_type()==1, gtfs_feed.stops()), key=lambda x:x.id()) order += sorted(filter(lambda x:x.location_type()!=1, gtfs_feed.stops()), key=lambda x:x.id()) for gtfs_stop in order: # Create stop from GTFS stop = Stop.from_gtfs(gtfs_stop, feedid) # Merge into parent station parent = gtfs_stop.get('parent_station') if parent: stop = gtfs_feed.stop(parent)._tl_ref # Merge with existing stop key = stop.onestop() stop = stops.get(key) or stop stops[key] = stop # Add identifiers and tags gtfs_stop._tl_ref = stop stop.add_identifier(gtfs_stop.feedid(feedid)) # Create TL Routes for gtfs_route in gtfs_feed.routes(): if not gtfs_route.stops(): continue # Create route from GTFS route = Route.from_gtfs(gtfs_route, feedid) # Link to TL Stops for gtfs_stop in gtfs_route.stops(): t = getattr(gtfs_stop, '_tl_ref', None) if t: route.add_child(t) # Maintain reference to GTFS Route gtfs_route._tl_ref = route # Create TL Agencies for gtfs_agency in gtfs_agencies: operator = Operator.from_gtfs( gtfs_agency, feedid, onestop_id=agency_onestop.get(gtfs_agency.id()) ) for gtfs_route in gtfs_agency.routes(): t = getattr(gtfs_route, '_tl_ref', None) if t: operator.add_child(t) # Inelegant. operator._cache_onestop() # Add agency to feed self.add_child(operator)
def stop_7(): return Stop.from_json(json.loads( STOP_TEMPLATE.replace("STOP_ID", "stop_7").replace("STOP_NAME", "seventh stop") ))
def stop_5(): return Stop.from_json(json.loads( STOP_TEMPLATE.replace("STOP_ID", "stop_5").replace("STOP_NAME", "fifth stop") ))
def stop_3(): return Stop.from_json(json.loads( STOP_TEMPLATE.replace("STOP_ID", "stop_3").replace("STOP_NAME", "third stop") ))
def stop_2(): return Stop.from_json(json.loads( STOP_TEMPLATE.replace("STOP_ID", "stop_2").replace("STOP_NAME", "second stop") ))
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 stopentity(self, stopxml): stop = Stop(key_name=stopxml.attributes["TSN"].value) buses = self.arrivalstolist(stopxml, stopxml.getElementsByTagName('Arrival')) stop.buses = json.dumps(buses) return stop
def __stops(self): if self._stops is None: data = self.__get_json_attr('stops', agencies=self.id) self._stops = { obj['id']: Stop.from_json(self, obj) for obj in data } return self._stops