コード例 #1
0
ファイル: shortcut_cache.py プロジェクト: fagan2888/gstrip
def reincarnate_ch(basename):
    chdowndb = GraphDatabase( basename+".down.gdb" )
    chupdb = GraphDatabase( basename+".up.gdb" )
    
    upgg = chupdb.incarnate()
    downgg = chdowndb.incarnate()
    
    return ContractionHierarchy(upgg, downgg)
コード例 #2
0
ファイル: route_all.py プロジェクト: dzwarg/hubway-challenge
    def handle(self, *args, **options):
        self.stdout.write('Loading boston.osmdb\n')
        self.nodedb = osmdb.OSMDB(settings.DATA_DIR + '/boston.osmdb')

        self.stdout.write('Importing Boston street network...\n')
        gdb = GraphDatabase(settings.DATA_DIR + '/boston.gdb')
        self.graph = gdb.incarnate()

        self.stdout.write('Importing trip network...\n')
        tripdb = osmdb.OSMDB(settings.DATA_DIR + '/trip_data.db')

        batchgeom = []
        count = 0

        # For each station
        for tnode in tripdb.nodes():
            lat1 = float(tnode[2])
            lng1 = float(tnode[3])

            # get all trips departing this station
            cursor = tripdb.get_cursor()
            tedges = cursor.execute("select * from edges where start_nd = ?",
                                    [tnode[0]])

            # For each trip
            for tedge in tedges:
                if tedge[3] == '':
                    if int(options['verbosity']) > 1:
                        self.stdout.write(
                            'Start and end nodes are the same.\n')
                    continue

                dnode = tripdb.node(tedge[3])

                lat2 = float(dnode[2])
                lng2 = float(dnode[3])

                dnode = None

                if lat2 == lat1 and lng2 == lng1:
                    continue

                geom = self._spt(lat1, lng1, lat2, lng2)
                count += 1

                batchgeom.append((
                    count,
                    geom,
                ))

                if len(batchgeom) >= options['number']:
                    self.dropfile(batchgeom, count, **options)
                    batchgeom = []

                geom = None

            # Don't keep a history of the execute tranactions
            tedges = None
            cursor = None
コード例 #3
0
 def __init__(self, graphdb_filename, pgosmdb_handle, pggtfsdb_handle, event_dispatch):
     graphdb = GraphDatabase( graphdb_filename )
     self.graph = graphdb.incarnate()
     self.graph.num_agencies = 3
     self.graph.numagencies = self.graph.num_agencies
     self.event_dispatch = event_dispatch
     self.pgosmdb = pgosmdb_handle
     self.pggtfsdb = pggtfsdb_handle
     self.two_way_routing = True
コード例 #4
0
ファイル: route_all.py プロジェクト: dzwarg/hubway-challenge
    def handle(self, *args, **options):
        self.stdout.write('Loading boston.osmdb\n')
        self.nodedb = osmdb.OSMDB(settings.DATA_DIR+'/boston.osmdb')

        self.stdout.write('Importing Boston street network...\n')
        gdb = GraphDatabase(settings.DATA_DIR+'/boston.gdb')
        self.graph = gdb.incarnate()

        self.stdout.write('Importing trip network...\n')
        tripdb = osmdb.OSMDB(settings.DATA_DIR+'/trip_data.db')
        
        
        batchgeom = []
        count = 0

        # For each station
        for tnode in tripdb.nodes():
            lat1 = float(tnode[2])
            lng1 = float(tnode[3])
            
            # get all trips departing this station
            cursor = tripdb.get_cursor()
            tedges = cursor.execute("select * from edges where start_nd = ?", [tnode[0]])
            
            # For each trip
            for tedge in tedges:
                if tedge[3] == '':
                    if int(options['verbosity']) > 1:
                        self.stdout.write('Start and end nodes are the same.\n')
                    continue

                dnode = tripdb.node(tedge[3])

                lat2 = float(dnode[2])
                lng2 = float(dnode[3])

                dnode = None

                if lat2 == lat1 and lng2 == lng1:
                    continue

                geom = self._spt(lat1, lng1, lat2, lng2)
                count += 1

                batchgeom.append((count,geom,))
                
                if len(batchgeom) >= options['number']:
                    self.dropfile(batchgeom, count, **options)
                    batchgeom = []

                geom = None


            # Don't keep a history of the execute tranactions
            tedges = None
            cursor = None
コード例 #5
0
ファイル: routeserver.py プロジェクト: dzwarg/graphserver
 def __init__(self, graphdb_filename, vertex_events, edge_events, vertex_reverse_geocoders):
     if os.path.exists("%s.gbin" % graphdb_filename):
         self.graph = Graph()
         self.graph.deserialize(graphdb_filename, os.path.exists("%s.gmm" % graphdb_filename))
     else:
         graphdb = GraphDatabase( graphdb_filename )
         self.graph = graphdb.incarnate()
     self.vertex_events = vertex_events
     self.edge_events = edge_events
     self.vertex_reverse_geocoders = vertex_reverse_geocoders
コード例 #6
0
 def __init__(self,
              graphdb_filename,
              vertex_events,
              edge_events,
              vertex_reverse_geocoders,
              config={}):
     graphdb = GraphDatabase(graphdb_filename)
     self.graph = graphdb.incarnate()
     self.vertex_events = vertex_events
     self.edge_events = edge_events
     self.vertex_reverse_geocoders = vertex_reverse_geocoders
コード例 #7
0
ファイル: main.py プロジェクト: fagan2888/gstrip
def make_native_ch(basename):
    gdb = GraphDatabase(basename + ".gdb")
    gg = gdb.incarnate()

    wo = WalkOptions()
    wo.hill_reluctance = 20
    ch = gg.get_contraction_hierarchies(wo)

    chdowndb = GraphDatabase(basename + ".down.gdb", overwrite=True)
    chdowndb.populate(ch.downgraph, reporter=sys.stdout)

    chupdb = GraphDatabase(basename + ".up.gdb", overwrite=True)
    chupdb.populate(ch.upgraph, reporter=sys.stdout)
コード例 #8
0
ファイル: main.py プロジェクト: bmander/gstrip
def make_native_ch(basename):
    gdb = GraphDatabase( basename+".gdb" )
    gg = gdb.incarnate()
    
    
    wo = WalkOptions()
    wo.hill_reluctance=20
    ch = gg.get_contraction_hierarchies( wo )
            
    chdowndb = GraphDatabase( basename+".down.gdb", overwrite=True )
    chdowndb.populate( ch.downgraph, reporter=sys.stdout )
    
    chupdb = GraphDatabase( basename+".up.gdb", overwrite=True )
    chupdb.populate( ch.upgraph, reporter=sys.stdout )
コード例 #9
0
def main(graph_db, gtfs_db):     
    graphdb = GraphDatabase( graph_db )
    gtfsdb = GTFSDatabase( gtfs_db )
    print "loading existing graph"
    full_graph = graphdb.incarnate()
    print "copying relevant vertices and edges from full graph"
    min_graph = Graph()
    copy_relevant_elements( min_graph, full_graph )    
    print "adding minimum-time transit trip edges"
    add_min_transit( min_graph, gtfsdb )
    print "writing out new graph to database"
    min_graphdb = GraphDatabase( 'min_graph.gdb', overwrite=True )
    min_graphdb.populate(min_graph)
    print "DONE."
    sys.exit(0)    
コード例 #10
0
ファイル: contourserver.py プロジェクト: dru/graphserver
 def __init__(self, settings_filename):
     settings = yaml.load( open( settings_filename ) )
     
     self.home_point = settings['center']
     
     # create cache of osm-node positions
     self.osmdb = OSMDB( settings['osmdb_filename'] )
     self.gtfsdb = GTFSDatabase( settings['gtfsdb_filename'] )
     self.port = settings['port']
     self.node_positions = {}
     self.index = Rtree()
     for node_id, tags, lat, lon in self.osmdb.nodes():
         self.node_positions[node_id] = (lon,lat)
         self.index.add( int(node_id), (lon,lat,lon,lat) )
     
     # incarnate graph from graphdb
     graphdb = GraphDatabase( settings['graphdb_filename'] )
     self.graph = graphdb.incarnate()
コード例 #11
0
ファイル: gs_serialize.py プロジェクト: dzwarg/graphserver
def main():
    usage = """usage: python gs_serialize.py [options] <basename> <graphdb_filename> """
    parser = OptionParser(usage=usage)
    parser.add_option("-m", "--memmap",
                      action="store_true", dest="memmap", default=False,
                      help="Create a memmap serialized file.")
    
    (options, args) = parser.parse_args()
    
    if len(args) != 2:
        parser.print_help()
        exit(-1)
    
    basename, graphdb_filename = args
    
    db = GraphDatabase(graphdb_filename)
    g = db.incarnate()
    g.serialize(basename, options.memmap)
    print "done"
コード例 #12
0
    def test_basic(self):
        g = Graph()
        g.add_vertex("A")
        g.add_vertex("B")
        g.add_edge("A", "B", Link())
        g.add_edge("A", "B", Street("foo", 20.0))
        gdb_file = os.path.dirname(__file__) + "unit_test.db"
        if os.path.exists(gdb_file):
            os.remove(gdb_file)
        gdb = GraphDatabase(gdb_file)
        gdb.populate(g)

        list(gdb.execute("select * from resources"))
        assert "A" in list(gdb.all_vertex_labels())
        assert "B" in list(gdb.all_vertex_labels())
        assert glen(gdb.all_edges()) == 2
        assert glen(gdb.all_outgoing("A")) == 2
        assert glen(gdb.all_outgoing("B")) == 0
        assert glen(gdb.all_incoming("A")) == 0
        assert glen(gdb.all_incoming("B")) == 2
        assert glen(gdb.resources()) == 0
        assert gdb.num_vertices() == 2
        assert gdb.num_edges() == 2

        g.destroy()
        g = gdb.incarnate()

        list(gdb.execute("select * from resources"))
        assert "A" in list(gdb.all_vertex_labels())
        assert "B" in list(gdb.all_vertex_labels())
        assert glen(gdb.all_edges()) == 2
        assert glen(gdb.all_outgoing("A")) == 2
        assert glen(gdb.all_outgoing("B")) == 0
        assert glen(gdb.all_incoming("A")) == 0
        assert glen(gdb.all_incoming("B")) == 2
        assert glen(gdb.resources()) == 0
        assert gdb.num_vertices() == 2
        assert gdb.num_edges() == 2

        os.remove(gdb_file)
コード例 #13
0
 def test_basic(self):
     g = Graph()
     g.add_vertex("A")
     g.add_vertex("B")
     g.add_edge("A", "B", Link())
     g.add_edge("A", "B", Street("foo", 20.0))
     gdb_file = os.path.dirname(__file__) + "unit_test.db"
     if os.path.exists(gdb_file):
         os.remove(gdb_file)        
     gdb = GraphDatabase(gdb_file)
     gdb.populate(g)
     
     list(gdb.execute("select * from resources"))
     assert "A" in list(gdb.all_vertex_labels())
     assert "B" in list(gdb.all_vertex_labels())
     assert glen(gdb.all_edges()) == 2
     assert glen(gdb.all_outgoing("A")) == 2
     assert glen(gdb.all_outgoing("B")) == 0
     assert glen(gdb.all_incoming("A")) == 0
     assert glen(gdb.all_incoming("B")) == 2
     assert glen(gdb.resources()) == 0
     assert gdb.num_vertices() == 2
     assert gdb.num_edges() == 2
     
     g.destroy()
     g = gdb.incarnate()
     
     list(gdb.execute("select * from resources"))
     assert "A" in list(gdb.all_vertex_labels())
     assert "B" in list(gdb.all_vertex_labels())
     assert glen(gdb.all_edges()) == 2
     assert glen(gdb.all_outgoing("A")) == 2
     assert glen(gdb.all_outgoing("B")) == 0
     assert glen(gdb.all_incoming("A")) == 0
     assert glen(gdb.all_incoming("B")) == 2
     assert glen(gdb.resources()) == 0
     assert gdb.num_vertices() == 2
     assert gdb.num_edges() == 2
     
     os.remove( gdb_file )
コード例 #14
0
    def test_ch(self):
        g = Graph()

        g.add_vertex("A")
        g.add_vertex("B")
        g.add_vertex("C")
        g.add_edge("A", "B", Street("foo", 10))
        g.add_edge("B", "C", Street("bar", 10))
        g.add_edge("C", "A", Street("baz", 10))

        wo = WalkOptions()
        ch = g.get_contraction_hierarchies(wo)

        gdb_file = os.path.dirname(__file__) + "unit_test.db"
        gdb = GraphDatabase(gdb_file)
        gdb.populate(ch.upgraph)

        laz = gdb.incarnate()

        combo = laz.edges[1]
        self.assertEqual(combo.payload.get(0).name, "baz")
        self.assertEqual(combo.payload.get(1).name, "foo")

        os.remove(gdb_file)
コード例 #15
0
    def test_ch(self):
        g = Graph()

	g.add_vertex( "A" )
	g.add_vertex( "B" )
        g.add_vertex( "C" )
	g.add_edge( "A", "B", Street( "foo", 10 ) )
	g.add_edge( "B", "C", Street( "bar", 10 ) )
	g.add_edge( "C", "A", Street( "baz", 10 ) )

        wo = WalkOptions()
	ch = g.get_contraction_hierarchies(wo)

        gdb_file = os.path.dirname(__file__) + "unit_test.db"
        gdb = GraphDatabase( gdb_file )
	gdb.populate( ch.upgraph )

	laz = gdb.incarnate()

        combo = laz.edges[1]
	self.assertEqual( combo.payload.get(0).name, "baz" )
	self.assertEqual( combo.payload.get(1).name, "foo" )

	os.remove( gdb_file )
コード例 #16
0
print "Geocoder range", geocoder_range
print "Using time", dt.ctime()
print "Bounding box tlbr: %f, %f, %f, %f" % (lat_start, lon_start, lat_stop, lon_stop)
print "Checking %d routes" % (lat_grid * lon_grid)

minimum = sys.maxint
maximum = -sys.maxint - 1

min_lon = sys.maxint
max_lon = -sys.maxint - 1

min_lat = sys.maxint
max_lat = -sys.maxint - 1

gdb = GraphDatabase('king.highway.gdb')
graph = gdb.incarnate()

rows = []

#missing_value = None
missing_value = 50000

for i in xrange(0, lat_grid):
    row = []

    print "Row %d" % i

    lat = lat_start + (i * lat_increment)

    if lat < min_lat:
        min_lat = lat
コード例 #17
0
ファイル: qt_prep.py プロジェクト: abyrd/metric-embedding
class MakeMatrixThread(QtCore.QThread):
    def __init__(self, parent=None):
        QtCore.QThread.__init__(self, parent)
        self.exiting = False

    def makeMatrix(self, gtfsdb, gdb):
        self.gtfsdb = str(gtfsdb)
        self.gdb = str(gdb)
        self.start()

    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,
        )
コード例 #18
0
ファイル: router.py プロジェクト: dzwarg/hubway-challenge
def main(count):
    print 'Loading boston.osmdb'
    nodedb = osmdb.OSMDB(DATA_DIR+'boston.osmdb')

    print 'Importing Boston street network...'
    gdb = GraphDatabase(DATA_DIR+'boston.gdb')
    graph = gdb.incarnate()

    print 'Importing trip network...'
    tripdb = osmdb.OSMDB(DATA_DIR+'trip_data.db')
    
    stime = time()
    wo = WalkOptions()
    
    cursor = tripdb.get_cursor()
    
    tripcount = 0

    # For each station
    for tnode in tripdb.nodes():
        lat1 = float(tnode[2])
        lng1 = float(tnode[3])
        
        # find origin node on the street network
        orig = nodedb.nearest_node(lat1, lng1)
        
        # get all trips departing this station
        tedges = cursor.execute("select * from edges where start_nd = ?", [tnode[0]])
        
        # For each trip
        for tedge in tedges:
            dnode = tripdb.node(tedge[3])
            
            lat2 = float(dnode[2])
            lng2 = float(dnode[3])
            
            if lat2 == lat1 and lng2 == lng1:
                # Do not route something that ends where it begins
                print 'Begin and end node are the same.'
            else:
                # find the destination node on the street network
                dest = nodedb.nearest_node(lat2, lng2)
            
                # route!
                spt = graph.shortest_path_tree('osm-'+orig[0], 'osm-'+dest[0], State(1,stime), wo)
            
                # get the path vertices and edges
                pvert, pedges = spt.path('osm-'+dest[0])
            
                # convert the results to geometries
                allgeom = []
                for e in pedges:
                    dbedge = nodedb.edge(e.payload.name)
                    if e.payload.reverse_of_source:
                        allgeom.extend( reversed( dbedge[5] ) )
                    else:
                        allgeom.extend( dbedge[5] )
            
                print allgeom
            
            tripcount += 1
            
            if tripcount >= count:
                break
        
        if tripcount >= count:
            break
コード例 #19
0
from PIL import Image
from multiprocessing import Pool

os.environ['TZ'] = 'US/Pacific'
time.tzset()
t0s = "Mon May 17 08:50:00 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

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() 
コード例 #20
0
    usage = """usage: python zzzz.py <graph_database> <assist_graph_database> <osm_database> <gtfs_database>"""
    parser = OptionParser(usage=usage)
    (options, args) = parser.parse_args()
    if len(args) != 4:
        parser.print_help()
        exit(-1)
        
    graph_db = args[0]
    assist_graph_db = args[1]
    osm_db  = args[2]    
    gtfs_db = args[3]    
    graphdb = GraphDatabase( graph_db )
    assistgraphdb = GraphDatabase( assist_graph_db )
    osmdb = OSMDB( osm_db )
    gtfsdb = GTFSDatabase( gtfs_db )
    g = graphdb.incarnate()
    ag = assistgraphdb.incarnate() 

    nodes = {}
    for id, tags, lat, lon, endnode_refs in osmdb.nodes():
        nodes['osm-' + id] = (lat, lon)
    for id, name, lat, lon in gtfsdb.stops():
        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
コード例 #21
0
ファイル: router.py プロジェクト: dzwarg/hubway-challenge
def main(count):
    print 'Loading boston.osmdb'
    nodedb = osmdb.OSMDB(DATA_DIR + 'boston.osmdb')

    print 'Importing Boston street network...'
    gdb = GraphDatabase(DATA_DIR + 'boston.gdb')
    graph = gdb.incarnate()

    print 'Importing trip network...'
    tripdb = osmdb.OSMDB(DATA_DIR + 'trip_data.db')

    stime = time()
    wo = WalkOptions()

    cursor = tripdb.get_cursor()

    tripcount = 0

    # For each station
    for tnode in tripdb.nodes():
        lat1 = float(tnode[2])
        lng1 = float(tnode[3])

        # find origin node on the street network
        orig = nodedb.nearest_node(lat1, lng1)

        # get all trips departing this station
        tedges = cursor.execute("select * from edges where start_nd = ?",
                                [tnode[0]])

        # For each trip
        for tedge in tedges:
            dnode = tripdb.node(tedge[3])

            lat2 = float(dnode[2])
            lng2 = float(dnode[3])

            if lat2 == lat1 and lng2 == lng1:
                # Do not route something that ends where it begins
                print 'Begin and end node are the same.'
            else:
                # find the destination node on the street network
                dest = nodedb.nearest_node(lat2, lng2)

                # route!
                spt = graph.shortest_path_tree('osm-' + orig[0],
                                               'osm-' + dest[0],
                                               State(1, stime), wo)

                # get the path vertices and edges
                pvert, pedges = spt.path('osm-' + dest[0])

                # convert the results to geometries
                allgeom = []
                for e in pedges:
                    dbedge = nodedb.edge(e.payload.name)
                    if e.payload.reverse_of_source:
                        allgeom.extend(reversed(dbedge[5]))
                    else:
                        allgeom.extend(dbedge[5])

                print allgeom

            tripcount += 1

            if tripcount >= count:
                break

        if tripcount >= count:
            break
コード例 #22
0
ファイル: routeserver.py プロジェクト: mtziotis/graphserver
 def __init__(self, graphdb_filename, event_dispatch):
     graphdb = GraphDatabase( graphdb_filename )
     self.graph = graphdb.incarnate()
     self.event_dispatch = event_dispatch
コード例 #23
0
except ImportError:
    import simplejson as json

graphdb_filename = "sanfrancisco.gdb"
osmdb_filename = "sanfrancisco.osmdb"
munistops_filename = "munistops.json"
munistopsdb_filename = "munistops.db"

starttime = 0
lat_adj_tolerance = 0.002
lon_adj_tolerance = 0.002
walk_adj_tolerance = 180 # 3 minutes

munistops = json.load(file(munistops_filename))
graphdb = GraphDatabase( graphdb_filename )
graph = graphdb.incarnate()
osmdb = OSMDB( osmdb_filename )
try:
    os.remove(munistopsdb_filename)
except OSError:
    pass
munistopsdb = sqlite3.connect(munistopsdb_filename)

def main():

    set_up_munistopsdb_schema()

    pairs = 0

    for start_stop_id, end_stop_id in adjacent_muni_stops_by_coords():
        start_stop = munistops[start_stop_id]
コード例 #24
0
ファイル: routeserver.py プロジェクト: ninowalker/graphserver
 def __init__(self, graphdb_filename, vertex_events, edge_events, vertex_reverse_geocoders):
     graphdb = GraphDatabase( graphdb_filename )
     self.graph = graphdb.incarnate()
     self.vertex_events = vertex_events
     self.edge_events = edge_events
     self.vertex_reverse_geocoders = vertex_reverse_geocoders
コード例 #25
0
ファイル: route.py プロジェクト: beaugunderson/routing
print "Using time", dt.ctime()
print "Bounding box tlbr: %f, %f, %f, %f" % (lat_start, lon_start, lat_stop,
                                             lon_stop)
print "Checking %d routes" % (lat_grid * lon_grid)

minimum = sys.maxint
maximum = -sys.maxint - 1

min_lon = sys.maxint
max_lon = -sys.maxint - 1

min_lat = sys.maxint
max_lat = -sys.maxint - 1

gdb = GraphDatabase('king.highway.gdb')
graph = gdb.incarnate()

rows = []

#missing_value = None
missing_value = 50000

for i in xrange(0, lat_grid):
    row = []

    print "Row %d" % i

    lat = lat_start + (i * lat_increment)

    if lat < min_lat:
        min_lat = lat