def path_retro(self,
                   origin,
                   dest,
                   currtime=None,
                   time_offset=None,
                   transfer_penalty=0,
                   walking_speed=1.0):
        if currtime is None:
            currtime = int(time.time())

        if time_offset is not None:
            currtime += time_offset

        wo = WalkOptions()
        wo.transfer_penalty = transfer_penalty
        wo.walking_speed = walking_speed
        spt = self.graph.shortest_path_tree_retro(origin, dest,
                                                  State(1, currtime), wo)
        wo.destroy()

        vertices, edges = spt.path_retro(origin)

        ret = list(
            postprocess_path(vertices, edges, self.vertex_events,
                             self.edge_events))

        spt.destroy()

        return json.dumps(ret, indent=2, cls=SelfEncoderHelper)
    def path(self,
             origin,
             dest,
             currtime=None,
             time_offset=None,
             transfer_penalty=0,
             walking_speed=1.0,
             hill_reluctance=1.5,
             turn_penalty=None,
             walking_reluctance=None,
             max_walk=None,
             jsoncallback=None):

        performance = {}

        if currtime is None:
            currtime = int(time.time())

        if time_offset is not None:
            currtime += time_offset

        # time path query
        t0 = time.time()
        wo = WalkOptions()
        wo.transfer_penalty = transfer_penalty
        wo.walking_speed = walking_speed
        wo.hill_reluctance = hill_reluctance
        if turn_penalty is not None:
            wo.turn_penalty = turn_penalty
        if walking_reluctance is not None:
            wo.walking_reluctance = walking_reluctance
        if max_walk is not None:
            wo.max_walk = max_walk
        spt = self.graph.shortest_path_tree(origin, dest, State(1, currtime),
                                            wo)

        vertices, edges = spt.path(dest)
        performance['path_query_time'] = time.time() - t0

        t0 = time.time()
        narrative = list(
            postprocess_path(vertices, edges, self.vertex_events,
                             self.edge_events))
        performance['narrative_postprocess_time'] = time.time() - t0

        t0 = time.time()
        wo.destroy()
        spt.destroy()
        performance['cleanup_time'] = time.time() - t0

        ret = {'narrative': narrative, 'performance': performance}

        if jsoncallback is None:
            return json.dumps(ret, indent=2, cls=SelfEncoderHelper)
        else:
            return "%s(%s)" % (
                jsoncallback, json.dumps(ret, indent=2, cls=SelfEncoderHelper))
 def path(self, 
          origin, 
          dest,
          currtime=None, 
          time_offset=None, 
          transfer_penalty=0, 
          walking_speed=1.0,
          hill_reluctance=1.5,
          turn_penalty=None,
          walking_reluctance=None,
          max_walk=None,
          jsoncallback=None):
     
     performance = {}
     
     if currtime is None:
         currtime = int(time.time())
         
     if time_offset is not None:
         currtime += time_offset
     
     # time path query
     t0 = time.time()
     wo = WalkOptions()
     wo.transfer_penalty=transfer_penalty
     wo.walking_speed=walking_speed
     wo.hill_reluctance=hill_reluctance
     if turn_penalty is not None:
         wo.turn_penalty = turn_penalty
     if walking_reluctance is not None:
         wo.walking_reluctance = walking_reluctance
     if max_walk is not None:
         wo.max_walk = max_walk
     spt = self.graph.shortest_path_tree( origin, dest, State(1,currtime), wo )
     
     
     vertices, edges = spt.path( dest )
     performance['path_query_time'] = time.time()-t0
     
     t0 = time.time()
     narrative = list(postprocess_path(vertices, edges, self.vertex_events, self.edge_events))
     performance['narrative_postprocess_time'] = time.time()-t0
     
     t0 = time.time()
     wo.destroy()
     spt.destroy()
     performance['cleanup_time'] = time.time()-t0
     
     ret = {'narrative':narrative, 'performance':performance}
     
     if jsoncallback is None:
         return json.dumps(ret, indent=2, cls=SelfEncoderHelper)
     else:
         return "%s(%s)"%(jsoncallback,json.dumps(ret, indent=2, cls=SelfEncoderHelper))
 def get_cell_weights(self, cellIndex=0, dep_time=0):
     sys.stderr.write("get_cell_weights   cell index: " + str(cellIndex) + "\n")
     # if the departure time is not specified, set it
     if (dep_time == 0):
         dep_time = int(time.time())
     wo = WalkOptions()
     wo.transfer_penalty=60
     wo.walking_speed=1.0
     wo.walking_reluctance=1.0
     wo.max_walk=10000
     wo.walking_overage=0.1
     core.shortestPathForKDTree(self.graph, State(self.graph.num_agencies,dep_time), wo, cellIndex)
     yield "Finished!"
Exemple #5
0
 def path_retro(self, origin, dest, currtime, transfer_penalty=0, walking_speed=1.0):
     
     wo = WalkOptions()
     wo.transfer_penalty = transfer_penalty
     wo.walking_speed = walking_speed
     spt = self.graph.shortest_path_tree_retro( origin, dest, State(1,currtime), wo )
     wo.destroy()
     
     vertices, edges = spt.path_retro( origin )
     
     ret = []
     for i in range(len(edges)):
         edgetype = edges[i].payload.__class__
         if edgetype in self.event_dispatch:
             ret.append( self.event_dispatch[ edges[i].payload.__class__ ]( vertices[i], edges[i], vertices[i+1] ) )
     
     spt.destroy()
     
     return json.dumps(ret)
 def path_retro(self, origin, dest, currtime=None, time_offset=None, transfer_penalty=0, walking_speed=1.0):
     if currtime is None:
         currtime = int(time.time())
         
     if time_offset is not None:
         currtime += time_offset
     
     wo = WalkOptions()
     wo.transfer_penalty = transfer_penalty
     wo.walking_speed = walking_speed
     spt = self.graph.shortest_path_tree_retro( origin, dest, State(1,currtime), wo )
     wo.destroy()
     
     vertices, edges = spt.path_retro( origin )
     
     ret = list(postprocess_path(vertices, edges, self.vertex_events, self.edge_events))
     
     spt.destroy()
     
     return json.dumps(ret, indent=2, cls=SelfEncoderHelper)
Exemple #7
0
    def path(self, 
             origin, 
             dest,
             currtime=None, 
             time_offset=None, 
             transfer_penalty=0, 
             walking_speed=1.0,
             hill_reluctance=1.5,
             turn_penalty=None,
             walking_reluctance=None,
             max_walk=None,
             jsoncallback=None):
        
        performance = {}
        
        if currtime is None:
            currtime = int(time.time())
            
        if time_offset is not None:
            currtime += time_offset
        
        # time path query
        t0 = time.time()
        wo = WalkOptions()
        wo.transfer_penalty=transfer_penalty
        wo.walking_speed=walking_speed
        wo.hill_reluctance=hill_reluctance
        if turn_penalty is not None:
            wo.turn_penalty = turn_penalty
        if walking_reluctance is not None:
            wo.walking_reluctance = walking_reluctance
        if max_walk is not None:
            wo.max_walk = max_walk
        spt = self.graph.shortest_path_tree( origin, dest, State(1,currtime), wo )
       
        try:
          vertices, edges = spt.path( dest )
	except Exception, e:
	  return json.dumps( {'error':str(e)} )
Exemple #8
0
 def path(self, 
          origin, 
          dest,
          currtime=None, 
          time_offset=None, 
          transfer_penalty=0, 
          walking_speed=1.0,
          hill_reluctance=1.5,
          turn_penalty=None,
          walking_reluctance=None,
          max_walk=None,
          jsoncallback=None):
     
     performance = {}
     
     if currtime is None:
         currtime = int(time.time())
         
     if time_offset is not None:
         currtime += time_offset
     
     # time path query
     t0 = time.time()
     wo = WalkOptions()
     wo.transfer_penalty=transfer_penalty
     wo.walking_speed=walking_speed
     wo.hill_reluctance=hill_reluctance
     if turn_penalty is not None:
         wo.turn_penalty = turn_penalty
     if walking_reluctance is not None:
         wo.walking_reluctance = walking_reluctance
     if max_walk is not None:
         wo.max_walk = max_walk
     spt = self.graph.shortest_path_tree( origin, dest, State(1,currtime), wo, maxtime=4000000000, hoplimit=2000000, weightlimit=4000000000 )
    
     try:
         vertices, edges = spt.path( dest )
     except Exception, e:
         return json.dumps( {'error':str(e)} )
d0s = time.strftime('%a %b %d %Y', t0t)
t0  = time.mktime(t0t)
print 'search date: ', d0s
print 'search time: ', time.ctime(t0), t0

gtfsdb = GTFSDatabase  ('./trimet.gtfsdb')
gdb    = GraphDatabase ('./test.gdb'  )
osmdb  = OSMDB         ('./testgrid.osmdb'  )
g      = gdb.incarnate ()

# FOOT - would be better if i could specify 0 boardings not 0 transfers
wo = WalkOptions() 
wo.max_walk = 2000 
wo.walking_overage = 0.0
wo.walking_speed = 1.0 # trimet uses 0.03 miles / 1 minute - but it uses straight line distance as well
wo.transfer_penalty = 99999
wo.walking_reluctance = 1
wo.max_transfers = 0
# make much higher?
wo.transfer_slack = 60 * 5
wo_foot = wo

# TRANSIT
wo = WalkOptions() 
wo.max_walk = 2000 
wo.walking_overage = 0.0
wo.walking_speed = 1.0 # trimet uses 0.03 miles / 1 minute - but it uses straight line distance as well
wo.transfer_penalty = 60 * 10
wo.walking_reluctance = 1.5
wo.max_transfers = 5
wo.transfer_slack = 60 * 4
Exemple #10
0
t0s = "Tue Mar 09 08:50:00 2010"
t0t = time.strptime(t0s)
d0s = time.strftime('%a %b %d %Y', t0t)
t0  = time.mktime(t0t)
print d0s
print time.ctime(t0), t0

gtfsdb = GTFSDatabase  ('/home/andrew/data/pdx/trimet-2010-02-28.gtfsdb')
gdb    = GraphDatabase ('/home/andrew/data/pdx/trimet.gsdb'  )
g      = gdb.incarnate ()

wo = WalkOptions() 
wo.max_walk = 1600 
wo.walking_overage = 0.0
wo.walking_speed = 1.0 # trimet uses 0.03 miles / 1 minute - but it uses straight line distance as well
wo.transfer_penalty = 60 * 10
wo.walking_reluctance = 2
wo.max_transfers = 5
wo.transfer_slack = 60 * 4

while(True) :
    input = raw_input('o d t / wo > ').split(' ')
    if len(input) == 0 : sys.exit(0)
    elif input[0] == 'wo' :
        try :
            wo.max_walk = int(raw_input('wo.max_walk = '))
            wo.walking_overage = float(raw_input('wo.walking_overage = '))
            wo.walking_speed = float(raw_input('wo.walking_speed = '))
            wo.transfer_penalty = int(raw_input('wo.transfer_penalty = '))
            wo.walking_reluctance = float(raw_input('wo.walking_reluctance = '))
        except :
Exemple #11
0
        stop_time = datetime.fromtimestamp(stop)

        start_time -= origin_walk_penalty
    finally:
        if tree:
            tree.destroy()

        return (start_time, stop_time)

    #narrative = list(postprocess_path(vertices, edges))
    #return json.dumps({ 'narrative': narrative }, indent=3, cls=SelfEncoderHelper)


walk_options = WalkOptions()

walk_options.transfer_penalty = 0
walk_options.walking_speed = 1.0
walk_options.hill_reluctance = 1.5
#walk_options.turn_penalty =
#walk_options.walking_reluctance =
#walk_options.max_walk =

# The full Metro King County boundaries
#lon_start = -122.506729
#lon_stop = -121.785828
#lat_start = 47.9323654
#lat_stop = 47.1891136

# Seattle & the East side
lat_start = 47.7
lat_stop = 47.5
Exemple #12
0
gdb = GraphDatabase("../data/trimet-linked-20100117.gsdb")
g = gdb.incarnate()

station_labels = [s[0] for s in gtfsdb.stops()]

origins = station_labels[:]
destinations = station_labels[:]
random.shuffle(origins)
random.shuffle(destinations)
pairs = zip(origins, destinations)[:SAMPLE_SIZE]

wo = WalkOptions()
wo.max_walk = 1000  # about 1/2 mile
wo.walking_overage = 0.2
wo.walking_speed = 0.8  # trimet uses 0.03 miles / 1 minute
wo.transfer_penalty = 0
wo.walking_reluctance = 1

residuals = []
magnitudes = []
normalize = 0
for o, d in pairs:
    og = gtfsdb.stop(o)
    dg = gtfsdb.stop(d)
    # print 'Origin (mds, gtfs)'
    # print o, og
    # print 'Destination (mds, gtfs)'
    # print d, dg
    print "from %s to %s (%f, %f) -> (%f, %f)" % (og[0], dg[0], og[2], og[3], dg[2], dg[3])

    # replace
        nodes['sta-' + id] = (lat, lon)

    os.environ['TZ'] = 'US/Pacific'
    time.tzset()
    t0s = "Tue Nov 16 07:50:30 2010"
    t0t = time.strptime(t0s)
    d0s = time.strftime('%a %b %d %Y', t0t)
    t0  = time.mktime(t0t)
    print 'search date: ', d0s
    print 'search time: ', time.ctime(t0), t0

    wo = WalkOptions() 
    wo.max_walk = 2000 
    wo.walking_overage = 0.0
    wo.walking_speed = 1.0 
    wo.transfer_penalty = 60 * 6
    wo.walking_reluctance = 1.0
    wo.max_transfers = 4

    orig = 'osm-37476896' #wes 
    dest = 'sta-2575' #to eas
    assist_spt = ag.shortest_path_tree(dest, None, State(1, 0))
    spt_a = g.shortest_path_tree_assist(assist_spt, orig, dest, State(1, t0), wo)
    spt_b = g.shortest_path_tree(orig, dest, State(1, t0), wo)
    for spt in [spt_a, spt_b]:
        print '-----search and path-----'    
        print 'number of vertices in spt:', len(spt.vertices)
        p = spt.path(dest)
        if p == None:
            print "DESTINATION NOT REACHED."
            sys.exit(0)
def get_walk( lat1, lon1, lat2, lon2 ):
    vertex1 = get_nearest_vertex( lat1, lon1 )
    vertex2 = get_nearest_vertex( lat2, lon2 )

    wo = WalkOptions()
    wo.transfer_penalty = 0
    wo.walking_speed = 1.0
    wo.hill_reluctance = 1.5

    try:
        spt = graph.shortest_path_tree( vertex1, vertex2, State(1, starttime), wo )
        vertices, edges = spt.path( vertex2 )
    except Exception:
        print "couldn't find a path between (%.4f,%4f) and (%.4f,%.4f)" % ( lat1, lon1, lat2, lon2)
        return None

    first_walk_time = None
    last_walk_time = None
    walk_streets = []
    walk_points = []
    walk_distance = 0

    for edge1,vertex1,edge2,vertex2 in zip( [None]+edges, vertices, edges+[None], vertices[1:]+[None,None] ):

        edge1payload = edge1.payload if edge1 else None
        edge2payload = edge2.payload if edge2 else None

        if edge2 is not None and isinstance(edge2.payload, Street):

            # Add the street geometry for this edge to our walk_points
            geometry_chunk = osmdb.edge( edge2.payload.name )[5]

            if edge2.payload.reverse_of_source:
                walk_points.extend( reversed( geometry_chunk ) )
            else:
                walk_points.extend( geometry_chunk )

            # Add this edge's distance in meters to the walk_distance
            walk_distance += edge2.payload.length

        if edge1 and edge2 and isinstance(edge1.payload, Street) and edge1.payload.way != edge2.payload.way:

            # We hit a turn

            walk_streets.append(get_street_name_for_edge(edge2))

        if (edge1 is None or not isinstance(edge1.payload, Street)) and (edge2 and isinstance(edge2.payload, Street)):

            # We started walking

            walk_streets.append(get_street_name_for_edge(edge2))

            if first_walk_time is None:
                first_walk_time = vertex1.state.time

        if (edge1 and isinstance(edge1.payload, Street)) and (edge2 is None or not isinstance(edge2.payload, Street)):

            # We stopped walking

            last_walk_time = vertex1.state.time

    if first_walk_time is None or last_walk_time is None:
        walk_time = 0
    else:
        walk_time = last_walk_time - first_walk_time

    ret = Walk()
    ret.time = walk_time
    ret.streets = walk_streets
    ret.points = walk_points
    ret.distance = walk_distance / 1609.344 # convert to miles

    return ret
    def path_xml(self, origlon, origlat, destlon, destlat, dep_time=0, arr_time=0, max_results=1, timezone="", transfer_penalty=60, walking_speed=1.0, walking_reluctance=1.0, max_walk=10000, walking_overage=0.1, seqno=0, street_mode="walk", transit_mode="Both", less_walking="False", udid="", version="2.0", two_way_routing="True"):
        
        if (two_way_routing == "False"):
            self.two_way_routing = False
        
        # set hard bounds on max_results [0,25]
        if (max_results < 0):
            max_results = 0
        elif (max_results > 25):
            max_results = 25
        
        sys.stderr.write("[xml_path_entry_point," + str(time.time()) + "] \"origlon=" + str(origlon) + "&origlat=" + str(origlat) + "&destlon=" + str(destlon) + "&destlat=" + str(destlat) + "&dep_time=" + str(dep_time) + "&arr_time=" + str(arr_time) + "&timezone=" + str(timezone) + "&transfer_penalty=" + str(transfer_penalty) + "&walking_speed=" + str(walking_speed) + "&walking_reluctance=" + str(walking_reluctance) + "&max_walk=" + str(max_walk) + "&walking_overage=" + str(walking_overage) + "&seqno=" + str(seqno) + "&street_mode=\"" + str(street_mode) + "\"&less_walking=\"" + str(less_walking) + "\"&udid=\"" + str(udid) + "\"&version=" + str(version) + "\"\n")
        
        if (origlon <= ChicagoMap.bounding_lon_left or origlon >= ChicagoMap.bounding_lon_right or 
            origlat <= ChicagoMap.bounding_lat_bottom or origlat >= ChicagoMap.bounding_lat_top or 
            destlon <= ChicagoMap.bounding_lon_left or destlon >= ChicagoMap.bounding_lon_right or 
            destlat <= ChicagoMap.bounding_lat_bottom or destlat >= ChicagoMap.bounding_lat_top):
            
            sys.stderr.write("[exit_outside_bounding_box," + str(time.time()) + "]\n")
            raise RoutingException
            #return '<?xml version="1.0"?><routes></routes>'
        
        # initialize spt to 'None' object
        spt = None
        
        # initialize walk options object
        wo = WalkOptions()
        
        # create database connections
        pgosmdb_conn = self.pgosmdb.create_pgosmdb_connection()
        pggtfsdb_conn = self.pggtfsdb.create_pggtfsdb_connection()
        
        try:
            # if the departure time is not specified, set it
            if (dep_time == 0):
                dep_time = int(time.time())
            
            # if the timezone is not specified, default to "America/Chicago"
            if (timezone == ""):
                timezone = "America/Chicago"
            
            # get origin and destination nodes from osm map
            sys.stderr.write("[get_osm_vertex_from_coords," + str(time.time()) + "]\n")
            orig_osm, orig_osm_dist = self.pgosmdb.get_osm_vertex_from_coords(pgosmdb_conn, origlon, origlat)
            dest_osm, dest_osm_dist = self.pgosmdb.get_osm_vertex_from_coords(pgosmdb_conn, destlon, destlat)
            
            #print "\nOrigin OSM: " + str(orig_osm) + " (" + str(orig_osm_dist) + ")"
            #print "Destination OSM: " + str(dest_osm) + " (" + str(dest_osm_dist) + ")\n"
            
            # get origin and destination nodes from gtfs database
            sys.stderr.write("[get_station_vertex_from_coords," + str(time.time()) + "]\n")
            orig_sta, orig_sta_dist = self.pggtfsdb.get_station_vertex_from_coords(pggtfsdb_conn, origlon, origlat)
            dest_sta, dest_sta_dist = self.pggtfsdb.get_station_vertex_from_coords(pggtfsdb_conn, destlon, destlat)
            
            #print "Origin STA: " + str(orig_sta) + " (" + str(orig_sta_dist) + ")"
            #print "Destination STA: " + str(dest_sta) + " (" + str(dest_sta_dist) + ")\n"
            
            # get coordinates for origin node
            if (orig_osm_dist < orig_sta_dist):
                origin = orig_osm
                sys.stderr.write("[get_coords_for_osm_vertex," + str(time.time()) + "]\n")
                orig_node_lat, orig_node_lon = self.pgosmdb.get_coords_for_osm_vertex(pgosmdb_conn, origin)
            else:
                origin = orig_sta
                sys.stderr.write("[get_coords_for_station_vertex," + str(time.time()) + "]\n")
                orig_node_lat, orig_node_lon = self.pggtfsdb.get_coords_for_station_vertex(pggtfsdb_conn, origin)
                
            # get coordinates for destination node
            if (dest_osm_dist < dest_sta_dist):
                dest = dest_osm
                sys.stderr.write("[get_coords_for_osm_vertex," + str(time.time()) + "]\n")
                dest_node_lat, dest_node_lon = self.pgosmdb.get_coords_for_osm_vertex(pgosmdb_conn, dest)
            else:
                dest = dest_sta
                sys.stderr.write("[get_coords_for_station_vertex," + str(time.time()) + "]\n")
                dest_node_lat, dest_node_lon = self.pggtfsdb.get_coords_for_station_vertex(pggtfsdb_conn, dest)
            
            #print "Origin: " + str(origin)
            #print "Destination: " + str(dest) + "\n"
            
            #print "Origin coords: " + str(orig_node_lat) + ", " + str(orig_node_lon)
            #print "Destination coords: " + str(dest_node_lat) + ", " + str(dest_node_lon)
            
            # determine distance from actual origin/destination to osm nodes
            orig_distance = vincenty(float(origlat), float(origlon), orig_node_lat, orig_node_lon)
            dest_distance = vincenty(dest_node_lat, dest_node_lon, float(destlat), float(destlon))
            
            #print "Origin distance: " + str(orig_distance)
            #print "Destination distance: " + str(dest_distance)
            
            # calculate time to origin and destination nodes (seconds)
            time_to_orig = int(round(float( float(orig_distance) / float(walking_speed) )))
            time_to_dest = int(round(float( float(dest_distance) / float(walking_speed) )))
            
            #print "Origin time: " + str(time_to_orig)
            #print "Destination time: " + str(time_to_dest)
            
            # adjust departure time by time needed to reach origin node
            dep_time = (dep_time + time_to_orig)
            
            # adjust arrival time by time needed to reach destination node
            if (arr_time != 0):
                arr_time = (arr_time - time_to_dest)
            
            #print "Adjusted departure time: " + str(dep_time)
            
            # set walk options
            wo.transfer_penalty=transfer_penalty
            wo.walking_speed=walking_speed
            wo.walking_reluctance=walking_reluctance
            wo.max_walk=max_walk
            wo.walking_overage=walking_overage
            
            # check for wheelchair street_mode
            if (street_mode == "wheelchair"):
                wo.with_wheelchair = int(True)
                wo.transfer_penalty = 180
            else:
                wo.with_wheelchair = int(False)
            
            # check for bike street_mode
            if (street_mode == "bike"):
                wo.transfer_penalty = 120
            
            # check for transit_mode
            if (transit_mode == "Both"):
                wo.transit_types = int(14)
            elif (transit_mode == "Bus"):
                wo.transit_types = int(8)
            elif (transit_mode == "Rail"):
                wo.transit_types = int(6)
            elif (transit_mode == "None"):
                wo.transit_types = int(0)
            
            # check for less_walking flag
            if (less_walking == "True"):
                wo.walking_reluctance *= 10.0
            
            # create RouteInfo object
            route_info = RouteInfo()
            route_info.origlat = origlat
            route_info.origlon = origlon
            route_info.dep_time_diff = time_to_orig
            route_info.destlat = destlat
            route_info.destlon = destlon
            route_info.arr_time_diff = time_to_dest
            route_info.street_mode = street_mode
            
            yield "--multipart-path_xml-boundary1234\n";
            
			# loop to create multiple responses
            for q in range(max_results):
                if (spt is not None):
                    spt.destroy_no_hash()
                route_info.first_edge = True
                route_info.last_edge = False
                
                # initialize return string
                ret_string = 'Content-Type: text/xml\n\n<?xml version="1.0"?><routes>'
                
                if (arr_time == 0):
                    (spt, edges, vertices) = self.shortest_path(origin,dest,dep_time,wo)
                else:
                    (spt, edges, vertices) = self.shortest_path_retro(origin,dest,arr_time,wo)
                
                # if there are no edges or vertices (i.e., there is no path found)
                if ((edges is None) or (vertices is None)): raise RoutingException
                # create WalkPath object
                walk_path = WalkPath()
                walk_path.lastlat = origlat
                walk_path.lastlon = origlon
                walk_path.timezone = timezone
                
                # string to store returned route
                curr_route = ""
                
                route_info.actual_dep_time = vertices[0].payload.time - time_to_orig
                route_info.actual_arr_time = vertices[-1].payload.time + time_to_dest
                
                # iterate through all edges in the route
                sys.stderr.write("[edges_loop," + str(time.time()) + "]\n")
                
                # determine the number of edges
                edges_len = len(edges)            
                for i in range(edges_len):
                    
                    if (i == (edges_len-1)):
                        route_info.last_edge = True
                    elif (i == (edges_len-2) and edges[i+1].payload.__class__ == graphserver.core.Link):
                        route_info.last_edge = True
                    elif (i == (edges_len-3) and edges[i+1].payload.__class__ == graphserver.core.Link and edges[i+2].payload.__class__ == graphserver.core.Link):
                        route_info.last_edge = True
                    
                    edgetype = edges[i].payload.__class__
                    if edgetype in self.event_dispatch:
                        (new_event, walk_path, route_info) = self.event_dispatch[ edges[i].payload.__class__ ]( vertices[i], edges[i], vertices[i+1], walk_path, route_info, pgosmdb_conn, pggtfsdb_conn)
                        curr_route += new_event
                
                ret_string += '<route dep_time="' + str(route_info.actual_dep_time) + '" req_dep_time="' + str(dep_time - time_to_orig) + '" arr_time="' + str(route_info.actual_arr_time) + '" req_arr_time="' + str(arr_time) + '" origlat="' + str(origlat) + '" origlon="' + str(origlon) + '" destlat="' + str(destlat) + '" destlon="' + str(destlon) + '" timezone="' + timezone + '" total_time="' + str(route_info.actual_arr_time - route_info.actual_dep_time) + '" total_walk_distance="' + str(int(round(walk_path.total_distance)) + int(round(orig_distance)) + int(round(dest_distance))) + '" walking_speed="' + str(walking_speed) + '" seqno="' + str(seqno) + '" version="' + str(version) + '">' + curr_route + '</route>'
                
                # close return string
                if q == max_results:                    
                    ret_string += '</routes>\n\n--multipart-path_xml-boundary1234--\n\n'
                else:
                    ret_string += '</routes>\n\n--multipart-path_xml-boundary1234\n'

                sys.stderr.write("[xml_path_exit_point," + str(time.time()) + "]\n")
                
                # return routes xml
                yield xstr(str(ret_string))
                
                if arr_time == 0: 
                    dep_time = route_info.actual_dep_time + time_to_orig + 60
                else:
                    arr_time = route_info.actual_arr_time - time_to_dest - 60
                            
    
        except RoutingException:
            if (spt is not None):
                spt.destroy_no_hash()
            
            yield '\n\n--multipart-path_xml-boundary1234\nContent-Type: text/xml\n\n<?xml version="1.0"?><routes></routes>--multipart-path_xml-boundary1234--\n\n '
            
        finally:
            #yield '\n\n--multipart-path_xml-boundary1234--\n\n'
            
            # close database connections
            self.pgosmdb.close_pgosmdb_connection(pgosmdb_conn)
            self.pggtfsdb.close_pggtfsdb_connection(pggtfsdb_conn)
            
            # destroy WalkOptions object
            wo.destroy()
            
            # destroy shortest path tree
            if (spt is not None):
                spt.destroy_no_hash()
 def getUrbanExplorerBlob(self, origlon, origlat, destlon, destlat, arrive_time, street_mode="walk", transit_mode="Both", less_walking="False", transfer_penalty=60, walking_speed=1.0, walking_reluctance=1.0, max_walk=10000, walking_overage=0.1,start_time=0,switch=1):
     
     # get origin and destination nodes from osm map
     sys.stderr.write("[get_osm_vertex_from_coords," + str(time.time()) + "]\n")
     orig_osm, orig_osm_dist = self.pgosmdb.get_osm_vertex_from_coords(origlon, origlat)
     dest_osm, dest_osm_dist = self.pgosmdb.get_osm_vertex_from_coords(destlon, destlat)
         
     # get origin and destination nodes from gtfs database
     sys.stderr.write("[get_station_vertex_from_coords," + str(time.time()) + "]\n")
     orig_sta, orig_sta_dist = self.pggtfsdb.get_station_vertex_from_coords(origlon, origlat)
     dest_sta, dest_sta_dist = self.pggtfsdb.get_station_vertex_from_coords(destlon, destlat)
             
     # get coordinates for origin node
     if (orig_osm_dist < orig_sta_dist):
         origin = orig_osm
         sys.stderr.write("[get_coords_for_osm_vertex," + str(time.time()) + "]\n")
         orig_node_lat, orig_node_lon = self.pgosmdb.get_coords_for_osm_vertex(origin)
     else:
         origin = orig_sta
         sys.stderr.write("[get_coords_for_station_vertex," + str(time.time()) + "]\n")
         orig_node_lat, orig_node_lon = self.pggtfsdb.get_coords_for_station_vertex(origin)
             
     # get coordinates for destination node
     if (dest_osm_dist < dest_sta_dist):
         dest = dest_osm
         sys.stderr.write("[get_coords_for_osm_vertex," + str(time.time()) + "]\n")
         dest_node_lat, dest_node_lon = self.pgosmdb.get_coords_for_osm_vertex(dest)
     else:
         dest = dest_sta
         sys.stderr.write("[get_coords_for_station_vertex," + str(time.time()) + "]\n")
         dest_node_lat, dest_node_lon = self.pggtfsdb.get_coords_for_station_vertex(dest)
 
     wo = WalkOptions()
     wo.transfer_penalty=transfer_penalty
     wo.walking_speed=walking_speed
     wo.walking_reluctance=walking_reluctance
     wo.max_walk=max_walk
     wo.walking_overage=walking_overage
     
     # check for wheelchair street_mode
     if (street_mode == "wheelchair"):
         wo.with_wheelchair = int(True)
         wo.transfer_penalty = 180
     else:
         wo.with_wheelchair = int(False)
     
     # check for bike street_mode
     if (street_mode == "bike"):
         wo.transfer_penalty = 120
     
     # check for transit_mode
     if (transit_mode == "Both"):
         wo.transit_types = int(14)
     elif (transit_mode == "Bus"):
         wo.transit_types = int(8)
     elif (transit_mode == "Rail"):
         wo.transit_types = int(6)
     elif (transit_mode == "None"):
         wo.transit_types = int(0)
         
     # check for less_walking flag
     if (less_walking == "True"):
         wo.walking_reluctance *= 10.0
     
     if (start_time == 0):
         start_time = int(time.time())
 
     if (switch == 1):
         graphserver.core.makeImage(self.graph.soul, origin, dest, State(self.graph.num_agencies,start_time), State(self.graph.num_agencies,arrive_time), wo)
         return open("explorerimages/blah.png", "rb").read()
     else:
         graphserver.core.makeUrbanExplorerBlob(self.graph.soul, origin, dest, State(self.graph.num_agencies,start_time), State(self.graph.num_agencies,arrive_time), wo)
         return open("explorerimages/blah2.png", "rb").read()
Exemple #17
0
    def run(self):
        self.gtfsdb = GTFSDatabase(self.gtfsdb)
        self.gdb = GraphDatabase(self.gdb)
        # Calculate an origin-destination matrix for the graph's stations
        print "Loading Graphserver DB..."
        self.emit(QtCore.SIGNAL("say(QString)"), QtCore.QString("Loading SQLite Graphserver graph..."))
        g = self.gdb.incarnate()

        # Set up distance-preserving projection system
        # Make a grid over the study area and save its geographic coordinates
        MARGIN = 8000  # meters beyond all stations, diagonally
        min_lon, min_lat, max_lon, max_lat = self.gtfsdb.extent()
        geod = pyproj.Geod(ellps="WGS84")
        min_lon, min_lat, arc_dist = geod.fwd(min_lon, min_lat, 180 + 45, MARGIN)
        max_lon, max_lat, arc_dist = geod.fwd(max_lon, max_lat, 45, MARGIN)
        proj = pyproj.Proj(proj="sinu", ellps="WGS84")
        min_x, min_y = proj(min_lon, min_lat)
        proj = pyproj.Proj(
            proj="sinu", ellps="WGS84", lon_0=min_lon, y_0=-min_y
        )  # why doesn't m parameter work for scaling by 100?
        grid_dim = array(proj(max_lon, max_lat), dtype=int32) / 100
        max_x, max_y = grid_dim
        print "\nMaking grid with dimesions: ", max_x, max_y
        self.emit(QtCore.SIGNAL("say(QString)"), QtCore.QString("Making %i by %i grid..." % (max_x, max_y)))
        # later, use reshape/flat to switch between 1d and 2d array representation
        grid_latlon = empty((max_x, max_y, 2), dtype=float32)
        for y in range(0, max_y):
            self.emit(QtCore.SIGNAL("progress(int, int)"), y, max_y)
            for x in range(0, max_x):
                # inverse project meters to lat/lon
                grid_latlon[x, y] = proj(x * 100, y * 100, inverse=True)

        station_vertices = [v for v in g.vertices if v.label[0:4] == "sta-"]
        station_labels = [v.label for v in station_vertices]
        n_stations = len(station_vertices)
        print "Finding station coordinates..."
        self.emit(QtCore.SIGNAL("say(QString)"), QtCore.QString("Projecting station coordinates..."))
        station_coords = empty((n_stations, 2), dtype=float32)
        for i, label in enumerate(station_labels):
            stop_id, stop_name, lat, lon = self.gtfsdb.stop(label[4:])
            station_coords[i] = proj(lon, lat)
            if i % 20 == 0:
                self.emit(QtCore.SIGNAL("progress(int, int)"), i, n_stations)
        station_coords /= 100

        # ELIMINATE STATIONS WITH SAME INTEGRAL COORDINATES
        # self.emit( QtCore.SIGNAL( 'say(QString)' ), QtCore.QString( 'Eliminating equivalent stations...'  ) )
        # while len(station_coords) > 0 :
        #    coord =
        #    mask = station_coords != station_coords[i]
        #    station_coords = station_coords[mask]
        # newer version follows
        # self.emit( QtCore.SIGNAL( 'say(QString)' ), QtCore.QString( 'Eliminating equivalent stations...' ) )
        # station_labels = np.array(station_labels)
        # station_coords_new = []
        # station_labels_new = []
        # while len(station_coords) > 0 :
        #    coord = np.round(station_coords[0])
        #    minIdx = np.argmin(np.sum(np.abs(station_coords - coord), axis=1))
        #    station_labels_new.append(station_labels[minIdx])
        #    station_coords_new.append(station_coords[minIdx])
        #    mask = np.any(np.round(station_coords) != coord, axis=1)
        #    #print mask
        #    #print len(station_coords)
        #    #print coord
        #    #print station_coords[np.logical_not(mask)]
        #    station_coords = station_coords[mask][:]
        #    station_labels = station_labels[mask][:]
        #    self.emit( QtCore.SIGNAL( 'progress(int, int)' ), n_stations - len(station_coords_new), n_stations )
        #
        # station_labels = station_labels_new
        # station_coords = station_coords_new
        # station_vertices = [g.get_vertex(slabel) for slabel in station_labels_new]
        # n_stations = len(station_labels)
        # print len(station_labels), len(station_coords), len(station_vertices)

        print "Making OD matrix..."
        os.environ["TZ"] = "US/Pacific"
        time.tzset()
        t0s = "Tue Mar 09 08:00:00 2010"
        t0t = time.strptime(t0s)
        d0s = time.strftime("%a %b %d %Y", t0t)
        t0 = int(time.mktime(t0t))
        print "search date: ", d0s
        print "search time: ", time.ctime(t0), t0

        wo = WalkOptions()
        wo.max_walk = 20000
        wo.walking_overage = 0.1
        wo.walking_speed = 1  # trimet uses 0.03 miles / 1 minute
        wo.transfer_penalty = 60 * 10
        wo.walking_reluctance = 2
        wo.max_transfers = 40
        wo.transfer_slack = 60 * 4

        matrix = zeros(
            (n_stations, n_stations), dtype=float
        )  # dtype could be uint16 except that there are inf's ---- why?
        colortable = [QtGui.QColor(i, i, i).rgb() for i in range(256)]
        colortable[254] = QtGui.QColor(050, 128, 050).rgb()
        colortable[255] = QtGui.QColor(255, 050, 050).rgb()
        matrixImage = QtGui.QImage(max_x, max_y, QtGui.QImage.Format_Indexed8)
        matrixImage.fill(0)
        matrixImage.setColorTable(colortable)
        for origin_idx in range(n_stations):
            sys.stdout.write("\rProcessing %i / %i ..." % (origin_idx, n_stations))
            sys.stdout.flush()
            self.emit(
                QtCore.SIGNAL("say(QString)"),
                QtCore.QString("Making OD matrix (station %i/%i)..." % (origin_idx, n_stations)),
            )
            self.emit(QtCore.SIGNAL("progress(int, int)"), origin_idx, n_stations)

            origin_label = station_labels[origin_idx]
            # g.spt_in_place(origin_label, None, State(1, t0), wo)
            spt = g.shortest_path_tree(origin_label, None, State(1, t0), wo)
            for dest_idx in range(n_stations):
                dest_label = station_labels[dest_idx]
                dest_vertex = spt.get_vertex(dest_label)
                # first board time should be subtracted here
                # if dest_vertex.payload is None :
                if dest_vertex is None:
                    print "Unreachable vertex. Set to infinity.", dest_idx, dest_label
                    delta_t = inf
                else:
                    # delta_t = dest_vertex.best_state.time - t0
                    bs = dest_vertex.best_state
                    delta_t = bs.time - t0 - bs.initial_wait
                if delta_t < 0:
                    print "Negative trip time; set to 0."
                    delta_t = 0

                matrix[origin_idx, dest_idx] = delta_t

                # sys.stdout.write( '%i %i\n' % (delta_t, dest_vertex.payload.initial_wait) )
                # sys.stdout.flush()
                # time.sleep(0.5)

                if dest_idx == origin_idx - 1:
                    color = 254
                elif dest_idx == origin_idx:
                    color = 255
                else:
                    color = 253 - delta_t * 3 / 60
                    if color < 0:
                        color = 0
                coord = station_coords[dest_idx]
                x = coord[0]
                y = coord[1]
                if color >= 254:
                    for x2 in range(x - 1, x + 2):
                        for y2 in range(y - 1, y + 2):
                            matrixImage.setPixel(x2, y2, color)
                else:
                    matrixImage.setPixel(x, y, color)

            self.emit(QtCore.SIGNAL("display(QImage)"), matrixImage)
            spt.destroy()
            # time.sleep(1)

        print x * y, "points, done."

        self.emit(QtCore.SIGNAL("say(QString)"), QtCore.QString("Saving as gzipped numpy ndarrays..."))

        savez(
            "od_matrix.npz",
            station_labels=station_labels,
            station_coords=station_coords,
            grid_dim=grid_dim,
            grid_latlon=grid_latlon,
            matrix=matrix,
        )
        start_time = datetime.fromtimestamp(start)
        stop_time = datetime.fromtimestamp(stop)

        start_time -= origin_walk_penalty
    finally:
        if tree:
            tree.destroy()

        return (start_time, stop_time)

    #narrative = list(postprocess_path(vertices, edges))
    #return json.dumps({ 'narrative': narrative }, indent=3, cls=SelfEncoderHelper)

walk_options = WalkOptions()

walk_options.transfer_penalty = 0
walk_options.walking_speed = 1.0
walk_options.hill_reluctance = 1.5
#walk_options.turn_penalty = 
#walk_options.walking_reluctance = 
#walk_options.max_walk = 

# The full Metro King County boundaries
#lon_start = -122.506729
#lon_stop = -121.785828
#lat_start = 47.9323654
#lat_stop = 47.1891136

# Seattle & the East side
lat_start = 47.7
lat_stop = 47.5