Exemple #1
0
 def __init__(self, graph_path, router, print_every_n_lines=50, calculate_details=False, smart_search=False):
     self.otp = OtpsEntryPoint.fromArgs([ "--graphs", graph_path, "--router", router])
     router = self.otp.getRouter()
     self.batch_processor = self.otp.createBatchProcessor(router)
     self.request = self.otp.createBatchRequest()
     self.request.setEvalItineraries(calculate_details)
     # smart search needs details (esp. start/arrival times),
     # even if not wanted explicitly
     if smart_search:
         calculate_details = True
     self.calculate_details = calculate_details
     self.smart_search = smart_search
     self.arrive_by = False
     self.print_every_n_lines = print_every_n_lines
Exemple #2
0
#CPAL Group 4
#Team Members - Arpit Agarwal, Arpit Chaukiyal, Devendra Sawant & Tarun Goyal
#University of Texas at Dallas

from org.opentripplanner.scripting.api import *
from org.opentripplanner.scripting.api import OtpsEntryPoint

###   router = otp.getRouter("current")

# Instantiate an OtpsEntryPoint
otp = OtpsEntryPoint.fromArgs(['--graphs', 'graphs', '--router', 'current'])
# Start timing the code
import time
start_time = time.time()

# Get the default router
router = otp.getRouter('current')

# Read Points of Destination - The file points.csv contains the columns geoid, Centx and Centy.

points = otp.loadCSVPopulation('points.csv', 'Centy', 'Centx')

dests = otp.loadCSVPopulation('points.csv', 'Centy', 'Centx')
# Create a default request for a given time
#  -- for h in range(0, 24):

for h in range(8, 9):
    for m in range(0, 60, 30):  # Loop every 30 minutes
        # Create a default request for a given time
        req = otp.createRequest()
        #req1 = otp.createRequest()
#!/usr/bin/jython
from org.opentripplanner.scripting.api import OtpsEntryPoint

# Instantiate an OtpsEntryPoint
otp = OtpsEntryPoint.fromArgs(['--graphs', '.', '--router', 'portland'])

# Start timing the code
import time
start_time = time.time()

# Get the default router
router = otp.getRouter('portland')

# Create a default request for a given departure time
req = otp.createRequest()
req.setDateTime(2015, 9, 15, 10, 00, 00)  # set departure time
req.setMaxTimeSec(7200)  # set a limit to maximum travel time (seconds)
req.setModes('WALK,BUS,RAIL')  # define transport mode
# req.maxWalkDistance = 3000                 # set the maximum distance (in meters) the user is willing to walk
# req.walkSpeed = walkSpeed                 # set average walking speed ( meters ?)
# req.bikeSpeed = bikeSpeed                 # set average cycling speed (miles per hour ?)
# ?ERROR req.setSearchRadiusM(500)                 # set max snapping distance to connect trip origin to street network

# for more routing options, check: http://dev.opentripplanner.org/javadoc/0.19.0/org/opentripplanner/scripting/api/OtpsRoutingRequest.html

# Read Points of Destination - The file points.csv contains the columns GEOID, X and Y.
points = otp.loadCSVPopulation('points.csv', 'Y', 'X')
dests = otp.loadCSVPopulation('points.csv', 'Y', 'X')

# Create a CSV output
matrixCsv = otp.createCSVOutput()
Exemple #4
0
# Importing the current county and config vars
with open("config.json") as filename:
    jsondata = json.load(filename)

maxtt = jsondata["otp_settings"]["maximum_travel_time"]
modes = ','.join(jsondata["otp_settings"]["transport_modes"])
dep_date = datetime.strptime(
    jsondata["otp_settings"]["departure_date"],
    "%Y-%m-%d")
dep_time = datetime.strptime(
    jsondata["otp_settings"]["departure_time"],
    "%H:%M:%S")
geoid = "17031"

# Instantiate an OtpsEntryPoint
otp = OtpsEntryPoint.fromArgs(['--graphs', 'otp/graphs', '--router', geoid])

# Start timing the code
start_time = time.time()

# Get the default router
router = otp.getRouter(geoid)

# Create a default request for a given departure time
req = otp.createRequest()
req.setDateTime(
    dep_date.year,
    dep_date.month,
    dep_date.day,
    dep_time.hour,
    dep_time.minute,
# SOURCE: RAFAEL PRERIA, python_script
from org.opentripplanner.scripting.api import OtpsEntryPoint

# Instantiate an OtpsEntryPoint
# NOTE WOULD NEED TO CHANGE THIS IN ORDER TO
otp = OtpsEntryPoint.fromArgs([
    '--graphs', '/Users/BrianHill/otp/graphs', '--router', 'bogota_no_gondola'
])

# Start timing the code
import time
start_time = time.time()

# Get the default router
router = otp.getRouter('bogota_no_gondola')

# Create a default request for a given departure time
req = otp.createRequest()
req.setDateTime(2019, 9, 15, 10, 00, 00)  # set departure time (April 4, 2019)

#req.setWaitReluctance(1) # Set walk reluctance to be 1 instead of the default 2, make walking time equally bad to other times
#req.setMaxTimeSec(7200)                   # set a limit to maximum travel time (seconds)
req.setModes('WALK,BUS,RAIL,TRANSIT')  # define transport mode
#req.setClampInitialWait(0)                # clamp the initial wait time to zero
# req.maxWalkDistance = 3000                 # set the maximum distance (in meters) the user is willing to walk
# req.walkSpeed = walkSpeed                 # set average walking speed ( meters ?)
# req.bikeSpeed = bikeSpeed                 # set average cycling speed (miles per hour ?)
# ?ERROR req.setSearchRadiusM(500)                 # set max snapping distance to connect trip origin to street network

# for more routing options, check: http://dev.opentripplanner.org/javadoc/0.19.0/org/opentripplanner/scripting/api/OtpsRoutingRequest.html
#!/usr/bin/jython
from org.opentripplanner.scripting.api import OtpsEntryPoint


# Instantiate an OtpsEntryPoint
otp = OtpsEntryPoint.fromArgs(['--graphs', '.',
                               '--router', 'portland'])

# Start timing the code
import time
start_time = time.time()

# Get the default router
router = otp.getRouter('portland')


# Read Points of Destination - The file points.csv contains the columns GEOID, X and Y.
points = otp.loadCSVPopulation('points.csv', 'Y', 'X')
dests = otp.loadCSVPopulation('points.csv', 'Y', 'X')


for h in range(7, 13):      # Loop every hour between 7h and 13h
  for m in range(0,60,10):  # Loop every 10 minutes
  
    # Create a default request for a given time
    req = otp.createRequest()
    req.setDateTime(2015, 9, 15, h, m, 00)  # set departure time
    req.setMaxTimeSec(7200)                 # set a limit to maximum travel time (seconds)
    req.setModes('WALK,TRANSIT')           # define transport mode : ("WALK,CAR, TRANSIT, TRAM,RAIL,SUBWAY,FUNICULAR,GONDOLA,CABLE_CAR,BUS")
    
    
def OD_matrix(day, hour, minute):

    print "start" + "_" + str(day) + "_" + str(hour) + "_" + str(minute)

    # initial load graph
    otp = OtpsEntryPoint.fromArgs(
        ["--graphs", "/path/to/dir/graphs", "--router", "ttc_realtime"])

    router = otp.getRouter()

    # basic routing stuff - can set more via json
    r = otp.createRequest()
    r.setDateTime(2016, 7, day, hour, minute, 00)
    r.setModes('WALK, TRANSIT')
    r.setMaxTimeSec(3600)
    r.setClampInitialWait(0)
    r.setMaxWalkDistance(5000)

    # out lists
    out_table = []
    origin_list = []
    destination_list = []
    # grab lists of origina and destinations
    with open('da.csv', 'rb') as csv_da:
        da_reader = csv.DictReader(csv_da)
        for da in da_reader:
            if int(da['DAuid']) not in origin_list:
                origin_list.append(int(da['DAuid']))
            with open('TAZ_centroids.csv', 'rb') as csv_TAZ:
                TAZ_reader = csv.DictReader(csv_TAZ)
                for row in TAZ_reader:
                    if int(row['GTA06']) not in destination_list:
                        destination_list.append(int(row['GTA06']))

    # loop over input da and use as origins
    with open('da.csv', 'rb') as csv_da:
        da_reader = csv.DictReader(csv_da)
        d = 0
        for da in da_reader:
            # add origin
            d_lat = float(da['DAlat'])
            d_lon = float(da['DAlong'])
            # set up router for point
            r.setOrigin(d_lat, d_lon)
            spt = router.plan(r)
            # loop over input supers and use as destinations
            with open('TAZ_centroids.csv', 'rb') as csv_super:
                super_reader = csv.DictReader(csv_super)
                s = 0
                for row in super_reader:
                    out_row = []
                    # add dest
                    lat = float(row['Y'])
                    lon = float(row['X'])
                    # solve
                    result = spt.eval(lat, lon)
                    if result is not None:
                        # get time
                        travel_time = result.getTime()
                        # output row to array
                        out_row = [
                            int(da['Geo_ID']),
                            int(da['DAuid']),
                            int(row['ID']),
                            int(row['GTA06']),
                            int(travel_time)
                        ]
                        out_table.append(out_row)
                    s += 1

            d += 1
            print '---------'
            print d
            print time.time() - start_time
            print '---------'

    # sort out_table
    out_table = sorted(out_table, key=itemgetter(0, 1))

    # grab list of all origins and destinations - can bring in externally if needed
    origin_list = sorted(origin_list)
    destination_list = sorted(destination_list)

    # set up matrix
    matrix = [[0 for x in range(len(destination_list) + 1)]
              for y in range(len(origin_list) + 1)]

    print "------------"

    # code in matrix values
    for tr in out_table:
        matrix[tr[0]][tr[2]] = tr[4]

    # add row and column names
    x = 0
    while x < len(destination_list):
        x += 1
        matrix[0][x] = destination_list[x - 1]
    x = 0
    while x < len(origin_list):
        x += 1
        matrix[x][0] = origin_list[x - 1]

    matrix[0][0] = hour * 100 + minute

    # out to csv
    file_name = "r_" + "7_" + str(day) + "_" + str(hour) + "_" + str(
        minute) + ".csv"
    with open(file_name, 'wb') as csv_walk:
        writer = csv.writer(csv_walk)
        for tt in matrix:
            writer.writerow(tt)
#!/usr/bin/jython
from org.opentripplanner.scripting.api import OtpsEntryPoint

# Instantiate an OtpsEntryPoint
otp = OtpsEntryPoint.fromArgs(["--graphs", ".", "--router", "portland"])

# Start timing the code
import time

start_time = time.time()

# Get the default router
router = otp.getRouter("portland")

# Create a default request for a given time
req = otp.createRequest()
req.setDateTime(2015, 9, 15, 10, 00, 00)  # set departure time
req.setMaxTimeSec(7200)  # set a limit to maximum travel time (seconds)
req.setModes("WALK,BUS,RAIL")  # define transport mode


# Read Points of Destination - The file points.csv contains the columns GEOID, X and Y.
points = otp.loadCSVPopulation("points.csv", "Y", "X")
dests = otp.loadCSVPopulation("points.csv", "Y", "X")


# Create a CSV output
matrixCsv = otp.createCSVOutput()
matrixCsv.setHeader(["Origin", "Destination", "Walk_distance", "Travel_time"])

# Start Loop
Exemple #9
0
import random

# Start timing the code
import time
start_time = time.time()

# THREADED VERSION OF OTP SCRIPT
import threading
from time import sleep

#!/usr/bin/jython
from org.opentripplanner.scripting.api import OtpsEntryPoint

# Instantiate an OtpsEntryPoint
otp = OtpsEntryPoint.fromArgs(['--graphs', '.', '--router', router_v])

# Get the default router
router = otp.getRouter(router_v)

# Read Points of Destination - The file points.csv contains the columns GEOID, X and Y.
# points = otp.loadCSVPopulation('harris_hex.csv', 'Y', 'X')
# dests = otp.loadCSVPopulation('harris_hex.csv', 'Y', 'X')

### make a list of jobs to do
# times should be randomly selected to avoid periodicity effects
jobs = []
random.seed(534)

for h in range(fromm, until):
    for m in range(0, 60, every):
# Setup for threading
chunks = int(os.environ.get('CHUNKS'))
max_threads = int(os.environ.get('MAX_THREADS'))

# Setting up file imports
origins_file = tmp_dir + geoid + '-origins'
destinations_file = tmp_dir + geoid + '-destinations.csv'
output_file = tmp_dir + geoid + '-output'

# Getting the datetime for the nearest Monday
today = datetime.datetime.now()
get_day = lambda date, day: date + datetime.timedelta(days=(day-date.weekday() + 7) % 7)
d = get_day(today, 0)

# Instantiate an OtpsEntryPoint
otp = OtpsEntryPoint.fromArgs(['--graphs', input_dir, '--router', geoid])

# Start timing the code
start_time = time.time()

# Get the default router
router = otp.getRouter(geoid)

# Create a list of jobs if using chunking
jobs = [str(chunk).zfill(len(str(chunks))) for chunk in range(1, chunks + 1)]
i = 0

def create_matrix(chunk):

    # Create a default request for a given departure time
    req = otp.createRequest()
Exemple #11
0
parser.add_argument('--date', nargs=3, type=int,
                    default=[2015, 9,
                             14])  # default = [now.year, now.month, now.day])
parser.add_argument(
    '--time', nargs=3, type=int,
    default=[10, 00, 00])  # default = [now.hour, now.minute, now.second])
parser.add_argument('--modes', default='WALK,BUS,RAIL')
parser.add_argument('--maxTimeSec', type=int, default=7200)
parser.add_argument('--output_file', default='tt_matrix.csv')
parser.add_argument('--output_vars',
                    nargs='+',
                    default=['walk_distance', 'travel_time', 'boardings'])
args = parser.parse_args()

# Instantiate an OtpsEntryPoint
otp = OtpsEntryPoint.fromArgs(
    ['--graphs', args.graph, '--router', args.router])

# Start timing the code
import time
start_time = time.time()

# Get the default router
router = otp.getRouter('portland')

# Create a default request for a given departure time
req = otp.createRequest()
req.setDateTime(args.date[0], args.date[1], args.date[2], args.time[0],
                args.time[1], args.time[2])  # set departure time
req.setMaxTimeSec(
    args.maxTimeSec)  # set a limit to maximum travel time (seconds)
req.setModes(args.modes)  # define transport modes
Exemple #12
0
# ask how many processes to use
max_threads = int(raw_input('how many threads? -> '))

# read in the O/D points to route between
points = []
with open(ODfile, 'rb') as point_csv:
    point_reader = csv.DictReader(point_csv)
    for record in point_reader:
        points.append({
            'id': str(record['uid']),
            'lat': float(record['lat']),
            'lon': float(record['lon'])
        })
# load the graph
otp = OtpsEntryPoint.fromArgs(
    ['--graphs', 'data/graphs', '--router', router_name])


def process_matrix(time):
    # check whether this file has actually already been written
    output_file = out_dir + str(time) + '.csv'
    # and if it has skip it. No need to do that again
    if os.path.exists(output_file):
        print output_file, 'already exists'
        return
    start = unix_time()
    # make a router
    router = otp.getRouter()
    request = otp.createRequest()
    request.setModes('WALK, TRANSIT')
    request.setMaxTimeSec(1 * 3600)  # seconds
max_threads = int(os.environ.get('MAX_THREADS'))

# Setting up file imports
origins_file = working_dir + location_dir + str(geoid) + '-origins-'
destinations_file = working_dir + location_dir + str(
    geoid) + '-destinations.csv'
output_file = working_dir + str(geoid) + '-output-'

# Getting the datetime for the nearest Monday
today = datetime.datetime.now()
get_day = lambda date, day: date + datetime.timedelta(days=(day - date.weekday(
) + 7) % 7)
d = get_day(today, 0)

# Instantiate an OtpsEntryPoint
otp = OtpsEntryPoint.fromArgs(
    ['--graphs', working_dir + 'graphs/', '--router', geoid])

# Start timing the code
start_time = time.time()

# Get the default router
router = otp.getRouter(geoid)

# Create a list of jobs if using chunking
jobs = [str(chunk).zfill(len(str(chunks))) for chunk in range(1, chunks + 1)]


def create_matrix(chunk):

    # Create a default request for a given departure time
    req = otp.createRequest()
Exemple #14
0
#!/usr/bin/jython
from org.opentripplanner.scripting.api import OtpsEntryPoint
import time

#%%

# jython -Dpython.path=otp-1.2.0-shaded.jar IHM_qy_accessibility_split_loop.py
# jython -Dpython.path=otp-x.y.z-shaded.jar myscript.py
#  java -cp otp-1.2.0-shaded.jar:jython-standalone-2.7.0.jar org.opentripplanner.standalone.OTPMain --script IHM_qy_accessibility_split_loop.py

print('Instantiate an OtpsEntryPoint')

dir_graph = 'graphs'
otp = OtpsEntryPoint.fromArgs(['--graphs', dir_graph, '--router', 'gb'])

indir = 'OD_lists'
flo = '_OA2013_origs.csv'
facility = '_dests'
#mins = ['00','10','05']
#mins = ['20','15','25']
#mins = ['30','45','35']
#mins = ['40','50','55']

mins = ['00', '30']
hours = [
    '08', '10', '12', '14', '16', '18', '20', '22', '09', '11', '13', '15',
    '17', '19', '21', '07', '23', '00', '06', '05', '04', '03', '02', '01'
]

#%%
print('Get the default router')
#!/usr/bin/jython
from org.opentripplanner.scripting.api import OtpsEntryPoint

# Instantiate an OtpsEntryPoint
otp = OtpsEntryPoint.fromArgs(['--graphs', '.', '--router', 'chicago'])

# Start timing the code
import time
start_time = time.time()

# Get the default router
router = otp.getRouter('chicago')

#set times {GTFS data from 4 October 2018 to 31 December 2018}
year = 2017
month = 10
day = 19
h = 8
m = 00
s = 00

# Create a default request for a given departure time
req = otp.createRequest()
req.setDateTime(year, month, day, h, m, s)  # set departure time
req.setMaxTimeSec(50000)  # set a limit to maximum travel time (seconds)
req.setModes(
    'WALK,BUS,RAIL,TRAM,TRANSIT,SUBWAY'
)  # define transport mode ("WALK,CAR, TRANSIT, TRAM,RAIL,SUBWAY,FUNICULAR,GONDOLA,CABLE_CAR,BUS")
req.setClampInitialWait(0)  # clamp the initial wait time to zero

# Read Points of Destination - The file points.csv contains the columns GEOID, X and Y.
from org.opentripplanner.analyst.batch import BatchProcessor
from org.opentripplanner.scripting.api import OtpsEntryPoint
import time
import csv
from operator import itemgetter

print "cow!"  # print cow!

# time for time
start_time = time.time()

csv_origins = "da_wpg_2016_2.csv"
csv_destinations = "ct_wpg_2016_2.csv"

# initial load graph
otp = OtpsEntryPoint.fromArgs(["--graphs", "graphs", "--router", "g"])

router = otp.getRouter()

# basic routing stuff - can set more via json
r = otp.createRequest()


# function for single OD matrix
def OD_matrix(month, day, hour, minute):

    print "start" + "_" + str(day) + "_" + str(hour) + "_" + str(minute)

    r.setDateTime(2016, month, day, hour, minute, 00)
    r.setModes('WALK, TRANSIT')
    r.setMaxTimeSec(5400)
Exemple #17
0
# computes travel time matrix from origins (lat long in DA.csv)
# to destinations (TAZ_centroids.csv)

# run with ...
# java -Xmx4G -cp otp.jar:jython.jar org.opentripplanner.standalone.OTPMain --graphs . --script Travel_time_matrix.py
# jython -Dpython.path=otp.jar Travel_time_matrix.py

from org.opentripplanner.scripting.api import *
from org.opentripplanner.scripting.api import OtpsEntryPoint
import time
import csv
from operator import itemgetter

# initial load graph
otp = OtpsEntryPoint.fromArgs(
    ["--graphs", "/path/to/dir/graphs", "--router", "ttc_realtime"])

router = otp.getRouter()

# basic routing stuff - can set more via json
r = otp.createRequest()
r.setDateTime(2016, 4, 20, 4, 20, 00)
r.setModes('WALK, TRANSIT')
r.setMaxTimeSec(3600)
r.setClampInitialWait(0)
r.setMaxWalkDistance(5000)

# out lists
out_table = []
origin_list = []
destination_list = []