Beispiel #1
0
def initTransits(calls):
    "initialises transits which is a collection of trips"
    trips = initTrips(calls)
    transits = []
    transit = Transit.Transit()
    transits.append(transit)
    for trip in trips:
        if transit.added(trip):
            continue
        transit = Transit.Transit()
        transits.append(transit)
        transit.added(trip)
    return transits
Beispiel #2
0
def route_line_add():
    h = int(request.args.get('i'), 16)
    e = check_for_session_errors(h)
    if e:
        return e

    name = request.args.get('name')
    full_name = request.args.get('full_name')
    color_bg = request.args.get('color_bg')
    color_fg = request.args.get('color_fg')

    service_id = request.args.get('service_id')
    line_id = request.args.get('line_id')

    m = session_manager.auth_by_key(h).session.map
    line = Transit.Line(int(line_id), name)
    line.full_name = full_name
    line.color_bg = color_bg
    line.color_fg = color_fg

    for service in m.services:
        if service_id == str(service.sid):
            service.add_line(line)
            return line.to_json()

    return json.dumps({"error": "Invalid ID"})
Beispiel #3
0
def route_stop_add():
    h = int(request.args.get('i'), 16)
    e = check_for_session_errors(h)
    if e:
        return e

    service_id = request.args.get('service_id')
    line_id = request.args.get('line_id')
    station_id = request.args.get('station_id')
    stop_id = request.args.get('stop_id')

    m = session_manager.auth_by_key(h).session.map
    for service in m.services:
        if service_id == str(service.sid):
            line_exists = False
            for line in service.lines:
                if line_id == str(line.sid):
                    line_exists = True
                    line_to_use = line

            if (line_exists):
                if service.has_station(int(station_id)):
                    station = service.get_station_by_id(int(station_id))
                    stop = Transit.Stop(int(stop_id), station.sid)
                    line_to_use.add_stop(stop)
                    return stop.to_json()

    return json.dumps({"error": "Invalid ID"})
Beispiel #4
0
def station_constructor(sid, lat, lng):

    name = ""

    rgr = reverse_geocode(REVERSE_GEOCODE_PROVIDER, lat, lng)

    if (rgr.has_street):
        name = rgr.streets[0]
    elif (rgr.has_neighborhood):
        name = rgr.neighborhood
    elif (rgr.has_locality):
        name = rgr.locality
    else:
        name = "Station"
    if len(name) <= 1:
        name = "Station"

    name = re.sub(r'(\w+\s)\b(Street)\b', r'\1St', name)
    name = re.sub(r'(\w+\s)\b(Road)\b', r'\1Rd', name)
    name = re.sub(r'(\w+\s)\b(Drive)\b', r'\1Dr', name)
    name = re.sub(r'(\w+\s)\b(Avenue)\b', r'\1Av', name)
    name = re.sub(r'(\w+\s)\b(Lane)\b', r'\1Ln', name)
    name = re.sub(r'(\w+\s)\b(Boulevard)\b', r'\1Blvd', name)

    s = Transit.Station(sid, name, [lat, lng])
    s.streets = rgr.streets
    s.neighborhood = rgr.neighborhood
    s.locality = rgr.locality

    return s
Beispiel #5
0
def stop_to_station(m, stop):
    lat = float(stop['stop_lat'])
    lng = float(stop['stop_lon'])
    name = stop['stop_name']
    name = name.replace(" Underground Station", "")
    station = Transit.Station(m.create_sid(), name, [lat, lng])
    return station
Beispiel #6
0
def route_service_add():
    h = int(request.args.get('i'), 16)
    e = check_for_session_errors(h)
    if e:
        return e

    name = request.args.get('name')
    service_id = request.args.get('service_id')

    m = session_manager.auth_by_key(h).session.map
    service = Transit.Service(int(service_id), name)
    m.add_service(service)

    return service.to_json()
Beispiel #7
0
def gtfs_to_simple_map(zip_folder_location):
    m = Transit.Map(0)

    remove_bom_inplace(os.path.join(zip_folder_location, 'agency.txt'))
    agency_file = open(os.path.join(zip_folder_location, 'agency.txt'), 'rb')
    agency_reader = csv.DictReader(agency_file)
    remove_bom_inplace(os.path.join(zip_folder_location, 'routes.txt'))
    routes_file = open(os.path.join(zip_folder_location, 'routes.txt'), 'rb')
    routes_reader = csv.DictReader(routes_file)

    agencies = []
    for agency in agency_reader:
        name = "Service"
        if 'agency_name' in agency:
            name = agency['agency_name']
        s = Transit.Service(m.create_sid(), name)
        if 'agency_id' in agency:
            s.gtfs_id = agency['agency_id']
        else:
            s.gtfs_id = agency['agency_name']

        m.add_service(s)

    for route in routes_reader:
        if 'agency_id' in route:
            s = m.get_service_by_gtfs_id(route['agency_id'])
        else:
            s = m.services[0]

        l = route_to_line(m, route)
        s.add_line(l)

    agency_file.close()
    routes_file.close()

    return m
Beispiel #8
0
def route_edge_add():
    h = int(request.args.get('i'), 16)
    e = check_for_session_errors(h)
    if e:
        return e

    service_id = request.args.get('service_id')
    line_id = request.args.get('line_id')
    stop_1_id = request.args.get('stop_1_id')
    stop_2_id = request.args.get('stop_2_id')
    edge_id = request.args.get('edge_id')

    if (stop_1_id == stop_2_id):
        return json.dumps({"error": "Duplicate Stop IDs"})

    m = session_manager.auth_by_key(h).session.map
    for s in m.services:
        if service_id == str(s.sid):

            # Look for matching line.
            line_exists = False
            for line in s.lines:
                if line_id == str(line.sid):
                    line_exists = True
                    line_to_use = line

            # Look for matching stops.
            stops_found = 0
            if (line_exists):
                for stop in line_to_use.stops:
                    if stop_1_id == str(stop.sid):
                        stop_1 = stop
                        stops_found += 1
                    if stop_2_id == str(stop.sid):
                        stop_2 = stop
                        stops_found += 1
            else:
                return json.dumps({"error": "Line Not Found"})

            # Add the edge.
            if (stops_found == 2):
                edge = Transit.Edge(int(edge_id), [stop_1_id, stop_2_id])
                line_to_use.add_edge(edge)
                return edge.to_json()
            else:
                return json.dumps({"error": "Stops Not Found"})

    return json.dumps({"error": "Invalid ID"})
Beispiel #9
0
def toOrFrom(tweet):
    tweetList = tweet.split()
    transit = Transit.Transit()
    if "@buss_route" in tweetList:
        tweetList.remove("@buss_route")
    if tweetList[0][0] == "t" or tweetList[0][0] == "T":
        tweetString = "+".join(tweetList)
        tweetResponse = transit.getRouteTo(tweetString)
        return tweetResponse
    elif tweetList[0][0] == "F" or tweetList[0][0] == "f":
        tweetString = "+".join(tweetList)
        tweetResponse = transit.getRouteFrom(tweetString)
        return tweetResponse
    else:
        defaultTweet = "Please read the instructions and try again."
        return defaultTweet
Beispiel #10
0
def route_to_line(m, route):
    name = "Line"
    full_name = "Line"

    if 'route_short_name' in route:
        name = route['route_short_name']
    if 'route_long_name' in route:
        full_name = route['route_long_name']

    l = Transit.Line(m.create_sid(), name)
    l.full_name = full_name

    if len(l.name) == 0 and len(l.full_name) > 0:
        l.name = l.full_name
    if len(l.full_name) == 0 and len(l.name) > 0:
        l.full_name = l.name

    if 'route_id' in route:
        l.gtfs_id = route['route_id']

    color_bg = "808183"
    if 'route_color' in route:
        if len(route['route_color']) > 0:
            color_bg = route['route_color']
    l.color_bg = "#"+color_bg
    
    color_fg = "FFFFFF"
    if 'route_text_color' in route:
        if len(route['route_text_color']) > 0:
            color_fg = route['route_text_color']
    if 'route_text_color' not in route and 'route_color' in route:
        if len(color_bg) == 6:
            cbc = tuple(int(color_bg[i:i+2], 16) for i in (0, 2, 4))
            if ((cbc[0] + cbc[1] + cbc[2]) > (255*3/2)):
                color_fg = "000000"
        if len(color_bg) == 3:
            cbc = tuple(int(color_bg[i:i+1], 16) for i in (0, 1, 2))
            if ((cbc[0] + cbc[1] + cbc[2]) > (15*3/2)):
                color_fg = "000000"

    l.color_fg = "#"+color_fg
    return l
Beispiel #11
0
def main():
    parser = argparse.ArgumentParser(description='Load a session by ID and run interactive session')
    parser.add_argument('id', help='session id')
    args = parser.parse_args()

    config = ConfigParser.RawConfigParser()
    config.read(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'settings.cfg')))

    SESSIONS_HOST = config.get('sessions', 'host')
    SESSIONS_PORT = config.get('sessions', 'port')
    SESSIONS_DBNAME = config.get('sessions', 'dbname')
    SESSIONS_USER = config.get('sessions', 'user')
    SESSIONS_PASSWORD = config.get('sessions', 'password')
    SESSIONS_CONN_STRING = "host='"+SESSIONS_HOST+"' port='"+SESSIONS_PORT+"' dbname='"+SESSIONS_DBNAME+"' user='******' password='******'"
    SESSIONS_SECRET_KEY_PUBLIC = int(config.get('sessions', 'secret_key_public'), 16)
    SESSIONS_SECRET_KEY_PRIVATE = int(config.get('sessions', 'secret_key_private'), 16)

    # print the connection string we will use to connect
    print "Connecting to database\n	->%s" % (SESSIONS_CONN_STRING)

    conn = psycopg2.connect(SESSIONS_CONN_STRING)
    cursor = conn.cursor()

    public_id = int(args.id, 16) ^ SESSIONS_SECRET_KEY_PUBLIC
    #print public_id
    query = "SELECT updated, data from sessions WHERE id=%d;" % (public_id)
    #print query
    cursor.execute(query)

    row = cursor.fetchone()
    #print "id: %d, updated: %s, data: %s" % (public_id, row[0], row[1])

    conn.commit()

    cursor.close()
    conn.close()
    
    m = Transit.Map(0)
    m.from_json(row[1])
    return m
Beispiel #12
0
 def __init__(self):
     self.sid = uuid.uuid4().int & (1<<63)-1
     self.map = Transit.Map(0)
     self.last_edit_time = datetime.datetime.now()
Beispiel #13
0
def gtfs_to_full_map(zip_folder_location, import_filter):
    m = Transit.Map(0)

    remove_bom_inplace(os.path.join(zip_folder_location, 'agency.txt'))
    agency_file = open(os.path.join(zip_folder_location, 'agency.txt'), 'rb')
    agency_reader = csv.DictReader(agency_file)
    remove_bom_inplace(os.path.join(zip_folder_location, 'stops.txt'))
    stops_file = open(os.path.join(zip_folder_location, 'stops.txt'), 'rb')
    stops_reader = csv.DictReader(stops_file)
    remove_bom_inplace(os.path.join(zip_folder_location, 'routes.txt'))
    routes_file = open(os.path.join(zip_folder_location, 'routes.txt'), 'rb')
    routes_reader = csv.DictReader(routes_file)
    remove_bom_inplace(os.path.join(zip_folder_location, 'trips.txt'))
    trips_file = open(os.path.join(zip_folder_location, 'trips.txt'), 'rb')
    trips_reader = csv.DictReader(trips_file)
    remove_bom_inplace(os.path.join(zip_folder_location, 'stop_times.txt'))
    stop_times_file = open(os.path.join(zip_folder_location, 'stop_times.txt'), 'rb')
    stop_times_reader = csv.DictReader(stop_times_file)
    
    print("Reading agencies")
    agencies = []
    for agency in agency_reader:
        name = "Service"
        if 'agency_name' in agency:
            name = agency['agency_name']
        s = Transit.Service(m.create_sid(), name)
        if 'agency_id' in agency:
            s.gtfs_id = agency['agency_id']
        else:
            s.gtfs_id = agency['agency_name']

        if (s.gtfs_id in import_filter['services']):
            print("Adding service: "+s.gtfs_id)
            m.add_service(s)

    print("Reading stops")
    stops = {}
    for stop in stops_reader:
        stops[stop['stop_id']] = stop
    
    print("Reading trips")
    route_id_to_trip_id = {}
    trip_id_to_route_id = {}
    for trip in trips_reader:
        route_id = trip['route_id']
        if route_id in import_filter['lines']:
            if route_id in route_id_to_trip_id:
                route_id_to_trip_id[route_id].append(trip['trip_id'])
            else:
                route_id_to_trip_id[route_id] = [trip['trip_id']]
            trip_id_to_route_id[trip['trip_id']] = route_id
            
    print("Reading stop times")
    trip_id_to_stop_ids = {}
    for stop_time in stop_times_reader:
        trip_id = stop_time['trip_id']
        if trip_id in trip_id_to_route_id:
            if trip_id in trip_id_to_stop_ids:
                trip_id_to_stop_ids[trip_id].append(stop_time['stop_id'])
            else:
                trip_id_to_stop_ids[trip_id] = [stop_time['stop_id']]
    
    stops_to_station_ids = {}
    print("Reading routes")
    for route in routes_reader:
        
        # Only use routes with at least 1 trip and not filtered out
        if (route['route_id'] in route_id_to_trip_id) and (route['route_id'] in import_filter['lines']):
            #print "Adding line: "+route['route_id']
            if 'agency_id' in route:
                s = m.get_service_by_gtfs_id(route['agency_id'])
            else:
                s = m.services[0]

            l = route_to_line(m, route)
            s.add_line(l)
            
            trip_ids = route_id_to_trip_id[route['route_id']]
            num_trips_max = 99999
            trip_num = 0

            unique_stop_ids = []

            # Add all the edges.
            for trip_id in trip_ids:
                if trip_num < num_trips_max:
                    trip_stops = trip_id_to_stop_ids[trip_id]
                    #print(str(len(trip_stops))+" stops")

                    previous_stops = []
                    for stop_id in trip_stops:
                        if stop_id in stops_to_station_ids:
                            station_id = stops_to_station_ids[stop_id]
                            station = service.get_station_by_id(station_id)
                        else:
                            tstop = stops[stop_id]
                            lat = float(tstop['stop_lat'])
                            lng = float(tstop['stop_lon'])
                            station = s.get_station_by_location([lat, lng])
                            if station is None:
                                station = stop_to_station(m, tstop)
                                s.add_station(station)
                            stops_to_station_ids['stop_id'] = station.sid
                        
                        if not l.has_station(station):
                            stop = Transit.Stop(m.create_sid(), station.sid)
                            l.add_stop(stop)
                        else:
                            stop = l.get_stop_from_station(station)
                        
                        if len(previous_stops) > 0:
                            edge_exists = l.has_edge_for_stops([stop, previous_stops[-1]])
                            if not edge_exists:
                                edge = Transit.Edge(m.create_sid(), [stop.sid, previous_stops[-1].sid])
                                #print "adding edge between "+station.name+" and "+s.get_station_by_id(previous_stops[-1].station_id).name
                                l.add_edge(edge)

                        previous_stops.append(stop)

                    previous_stop_ids = []
                    for stop in previous_stops:
                        previous_stop_ids.append(stop.sid)

                    if previous_stop_ids not in unique_stop_ids:
                        unique_stop_ids.append(previous_stop_ids)

                trip_num += 1

            #print unique_stop_ids

            # Check each edge to see if it can be removed.
            edges_to_remove = []

            for edge in l.edges:
                s1 = l.get_stop_by_id(edge.stop_ids[0])
                s2 = l.get_stop_by_id(edge.stop_ids[1])

                # We want to remove this edge only if a GTFS trip defines a longer path between the two stops.
                for unique_trip in unique_stop_ids:
                    if s1.sid in unique_trip and s2.sid in unique_trip:
                        s1_index = unique_trip.index(s1.sid)
                        s2_index = unique_trip.index(s2.sid)
                        if (abs(s1_index-s2_index) > 1) and edge not in edges_to_remove:
                            edges_to_remove.append(edge)

            for edge in edges_to_remove:
                l.edges.remove(edge)

    agency_file.close()
    stops_file.close()
    routes_file.close()
    trips_file.close()
    stop_times_file.close()

    # Post-processing:
    # Remove any unused stations
    for service in m.services:
        stations_to_remove = []
        for station in service.stations:
            ec = service.station_edge_count(station)
            if ec == 0:
                if station not in stations_to_remove:
                    stations_to_remove.append(station)
        for station in stations_to_remove:
            service.remove_station(station)

    return m