INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Parameters ---------- gtfs: gtfspy. GTFS output_filename: str path to the directory where to store the extracts start_time_ut: int | None start time of the extract in unixtime ( seconds after epoch ) end_time_ut: int | None end time of the extract in unixtime ( seconds after epoch )
def write_temporal_network(gtfs, output_filename, start_time_ut=None, end_time_ut=None): """ Parameters ---------- gtfs : gtfspy.GTFS output_filename : str path to the directory where to store the extracts start_time_ut: int | None start time of the extract in unixtime (seconds a...
Write out a network
def _write_stop_to_stop_network_edges(net, file_name, data=True, fmt=None): """ Write out a network Parameters ---------- net: networkx.DiGraph base_name: str path to the filename (without extension) data: bool, optional whether or not to write out any edge data present ...
Write out the database according to the GTFS format.
def write_gtfs(gtfs, output): """ Write out the database according to the GTFS format. Parameters ---------- gtfs: gtfspy.GTFS output: str Path where to put the GTFS files if output ends with ".zip" a ZIP-file is created instead. Returns ------- None """ out...
Remove columns ending with I from a pandas. DataFrame
def _remove_I_columns(df): """ Remove columns ending with I from a pandas.DataFrame Parameters ---------- df: dataFrame Returns ------- None """ all_columns = list(filter(lambda el: el[-2:] == "_I", df.columns)) for column in all_columns: del df[column]
A helper method for scanning the footpaths. Updates self. _stop_profiles accordingly
def _scan_footpaths_to_departure_stop(self, connection_dep_stop, connection_dep_time, arrival_time_target): """ A helper method for scanning the footpaths. Updates self._stop_profiles accordingly""" for _, neighbor, data in self._walk_network.edges_iter(nbunch=[connection_dep_stop], ...
Parameters ---------- g: A gtfspy. gtfs. GTFS object Where to get the data from? ax: matplotlib. Axes object optional If None a new figure and an axis is created spatial_bounds: dict optional with str keys: lon_min lon_max lat_min lat_max return_smopy_map: bool optional defaulting to false
def plot_route_network_from_gtfs(g, ax=None, spatial_bounds=None, map_alpha=0.8, scalebar=True, legend=True, return_smopy_map=False, map_style=None): """ Parameters ---------- g: A gtfspy.gtfs.GTFS object Where to get the data from? ax: matplotlib.Axes object...
Parameters ---------- route_shapes: list of dicts that should have the following keys name type agency lats lons with types list list str list list ax: axis object spatial_bounds: dict map_alpha: plot_scalebar: bool legend: return_smopy_map: line_width_attribute: line_width_scale:
def plot_as_routes(route_shapes, ax=None, spatial_bounds=None, map_alpha=0.8, plot_scalebar=True, legend=True, return_smopy_map=False, line_width_attribute=None, line_width_scale=1.0, map_style=None): """ Parameters ---------- route_shapes: list of dicts that should have the following...
Parameters ---------- bounds: dict ax_width: float ax_height: float
def _expand_spatial_bounds_to_fit_axes(bounds, ax_width, ax_height): """ Parameters ---------- bounds: dict ax_width: float ax_height: float Returns ------- spatial_bounds """ b = bounds height_meters = util.wgs84_distance(b['lat_min'], b['lon_min'], b['lat_max'], b['lon...
Parameters ---------- g: A gtfspy. gtfs. GTFS object ax: matplotlib. Axes object optional If None a new figure and an axis is created otherwise results are plotted on the axis. scalebar: bool optional Whether to include a scalebar to the plot.
def plot_all_stops(g, ax=None, scalebar=False): """ Parameters ---------- g: A gtfspy.gtfs.GTFS object ax: matplotlib.Axes object, optional If None, a new figure and an axis is created, otherwise results are plotted on the axis. scalebar: bool, optional Whether to include a scale...
Parameters ---------- TZ: string
def set_process_timezone(TZ): """ Parameters ---------- TZ: string """ try: prev_timezone = os.environ['TZ'] except KeyError: prev_timezone = None os.environ['TZ'] = TZ time.tzset() # Cause C-library functions to notice the update. return prev_timezone
Distance ( in meters ) between two points in WGS84 coord system.
def wgs84_distance(lat1, lon1, lat2, lon2): """Distance (in meters) between two points in WGS84 coord system.""" dLat = math.radians(lat2 - lat1) dLon = math.radians(lon2 - lon1) a = (math.sin(dLat / 2) * math.sin(dLat / 2) + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * ...
Context manager for making files with possibility of failure.
def create_file(fname=None, fname_tmp=None, tmpdir=None, save_tmpfile=False, keepext=False): """Context manager for making files with possibility of failure. If you are creating a file, it is possible that the code will fail and leave a corrupt intermediate file. This is especially damagin...
Utility function to print sqlite queries before executing.
def execute(cur, *args): """Utility function to print sqlite queries before executing. Use instead of cur.execute(). First argument is cursor. cur.execute(stmt) becomes util.execute(cur, stmt) """ stmt = args[0] if len(args) > 1: stmt = stmt.replace('%', '%%').replace('?', '%r...
Converts time strings to integer seconds: param time: %H: %M: %S string: return: integer seconds
def str_time_to_day_seconds(time): """ Converts time strings to integer seconds :param time: %H:%M:%S string :return: integer seconds """ t = str(time).split(':') seconds = int(t[0]) * 3600 + int(t[1]) * 60 + int(t[2]) return seconds
Create directories if they do not exist otherwise do nothing.
def makedirs(path): """ Create directories if they do not exist, otherwise do nothing. Return path for convenience """ if not os.path.isdir(path): os.makedirs(path) return path
Parameters ---------- path: str path to directory or zipfile table: str name of table read_csv_args: string arguments passed to the read_csv function
def source_csv_to_pandas(path, table, read_csv_args=None): """ Parameters ---------- path: str path to directory or zipfile table: str name of table read_csv_args: string arguments passed to the read_csv function Returns ------- df: pandas:DataFrame """ ...
: param data: list of dicts where dictionary contains the keys lons and lats: param shapefile_path: path where shapefile is saved: return:
def write_shapefile(data, shapefile_path): from numpy import int64 """ :param data: list of dicts where dictionary contains the keys lons and lats :param shapefile_path: path where shapefile is saved :return: """ w = shp.Writer(shp.POLYLINE) # shapeType=3) fields = [] encode_strin...
Plot a networkx. Graph by using the lat and lon attributes of nodes. Parameters ---------- net: networkx. Graph Returns ------- fig: matplotlib. figure the figure object where the network is plotted
def draw_net_using_node_coords(net): """ Plot a networkx.Graph by using the lat and lon attributes of nodes. Parameters ---------- net : networkx.Graph Returns ------- fig : matplotlib.figure the figure object where the network is plotted """ import matplotlib.pyplot as p...
Returns a dataframe with all of df_other that are not in df_self when considering the columns specified in col_names: param df_self: pandas Dataframe: param df_other: pandas Dataframe: param col_names: list of column names: return:
def difference_of_pandas_dfs(df_self, df_other, col_names=None): """ Returns a dataframe with all of df_other that are not in df_self, when considering the columns specified in col_names :param df_self: pandas Dataframe :param df_other: pandas Dataframe :param col_names: list of column names :re...
Deal with the first walks by joining profiles to other stops within walking distance.
def _finalize_profiles(self): """ Deal with the first walks by joining profiles to other stops within walking distance. """ for stop, stop_profile in self._stop_profiles.items(): assert (isinstance(stop_profile, NodeProfileMultiObjective)) neighbor_label_bags = []...
Import a GTFS database
def import_gtfs(gtfs_sources, output, preserve_connection=False, print_progress=True, location_name=None, **kwargs): """Import a GTFS database gtfs_sources: str, dict, list Paths to the gtfs zip file or to the directory containing the GTFS data. Alternatively, a dict can be prov...
This validates the day_start_ut of the days table.
def validate_day_start_ut(conn): """This validates the day_start_ut of the days table.""" G = GTFS(conn) cur = conn.execute('SELECT date, day_start_ut FROM days') for date, day_start_ut in cur: #print date, day_start_ut assert day_start_ut == G.get_day_start_ut(date)
Re - create all views.
def main_make_views(gtfs_fname): """Re-create all views. """ print("creating views") conn = GTFS(fname_or_conn=gtfs_fname).conn for L in Loaders: L(None).make_views(conn) conn.commit()
Imports source. txt files checks row counts and then compares the rowcounts with the gtfsobject: return:
def _validate_table_row_counts(self): """ Imports source .txt files, checks row counts and then compares the rowcounts with the gtfsobject :return: """ for db_table_name in DB_TABLE_NAME_TO_SOURCE_FILE.keys(): table_name_source_file = DB_TABLE_NAME_TO_SOURCE_FILE[db_t...
Loads the tables from the gtfs object and counts the number of rows that have null values in fields that should not be null. Stores the number of null rows in warnings_container
def _validate_no_null_values(self): """ Loads the tables from the gtfs object and counts the number of rows that have null values in fields that should not be null. Stores the number of null rows in warnings_container """ for table in DB_TABLE_NAMES: null_not_ok_warni...
Checks for rows that are not referenced in the the tables that should be linked
def _validate_danglers(self): """ Checks for rows that are not referenced in the the tables that should be linked stops <> stop_times using stop_I stop_times <> trips <> days, using trip_I trips <> routes, using route_I :return: """ for query, warning in ...
This function calculates the equivalent rowcounts for trips when taking into account the generated rows in the gtfs object Parameters ---------- gtfs_soure_path: path to the source file param txt: txt file in question: return: sum of all trips
def _frequency_generated_trips_rows(self, gtfs_soure_path, return_df_freq=False): """ This function calculates the equivalent rowcounts for trips when taking into account the generated rows in the gtfs object Parameters ---------- gtfs_soure_path: path to the source file ...
Parameters ---------- Same as for _frequency_generated_trips_rows but for stop times table gtfs_source_path: table_name:
def _compute_number_of_frequency_generated_stop_times(self, gtfs_source_path): """ Parameters ---------- Same as for "_frequency_generated_trips_rows" but for stop times table gtfs_source_path: table_name: Return ------ """ df_freq = self....
Parameters ---------- new_label: LabelTime
def update_pareto_optimal_tuples(self, new_label): """ Parameters ---------- new_label: LabelTime Returns ------- updated: bool """ assert (isinstance(new_label, LabelTime)) if self._labels: assert (new_label.departure_time <= ...
Print coordinates within a sequence.
def print_coords(rows, prefix=''): """Print coordinates within a sequence. This is only used for debugging. Printed in a form that can be pasted into Python for visualization.""" lat = [row['lat'] for row in rows] lon = [row['lon'] for row in rows] print('COORDS'+'-' * 5) print("%slat, %sl...
Find corresponding shape points for a list of stops and create shape break points.
def find_segments(stops, shape): """Find corresponding shape points for a list of stops and create shape break points. Parameters ---------- stops: stop-sequence (list) List of stop points shape: list of shape points shape-sequence of shape points Returns ------- break_...
Finds the best shape_id for a stop - sequence.
def find_best_segments(cur, stops, shape_ids, route_id=None, breakpoints_cache=None): """Finds the best shape_id for a stop-sequence. This is used in cases like when you have GPS data with a route name, but you don't know the route direction. It tries shapes going both direction...
Break a shape into segments between stops using break_points.
def return_segments(shape, break_points): """Break a shape into segments between stops using break_points. This function can use the `break_points` outputs from `find_segments`, and cuts the shape-sequence into pieces corresponding to each stop. """ # print 'xxx' # print stops # print s...
Add a d key for distances to a stop/ shape - sequence.
def gen_cumulative_distances(stops): """ Add a 'd' key for distances to a stop/shape-sequence. This takes a shape-sequence or stop-sequence, and adds an extra 'd' key that is cumulative, geographic distances between each point. This uses `wgs84_distance` from the util module. The distances are...
Given a shape_id return its shape - sequence.
def get_shape_points(cur, shape_id): """ Given a shape_id, return its shape-sequence. Parameters ---------- cur: sqlite3.Cursor cursor to a GTFS database shape_id: str id of the route Returns ------- shape_points: list elements are dictionaries containing th...
Given a shape_id return its shape - sequence ( as a dict of lists ). get_shape_points function returns them as a list of dicts
def get_shape_points2(cur, shape_id): """ Given a shape_id, return its shape-sequence (as a dict of lists). get_shape_points function returns them as a list of dicts Parameters ---------- cur: sqlite3.Cursor cursor to a GTFS database shape_id: str id of the route Return...
Given a route_id return its stop - sequence.
def get_route_shape_segments(cur, route_id): """ Given a route_id, return its stop-sequence. Parameters ---------- cur: sqlite3.Cursor cursor to a GTFS database route_id: str id of the route Returns ------- shape_points: list elements are dictionaries contai...
Given a trip_I ( shortened id ) return shape points between two stops ( seq_stop1 and seq_stop2 ).
def get_shape_between_stops(cur, trip_I, seq_stop1=None, seq_stop2=None, shape_breaks=None): """ Given a trip_I (shortened id), return shape points between two stops (seq_stop1 and seq_stop2). Trip_I is used for matching obtaining the full shape of one trip (route). From the resulting shape we then...
Get all scheduled stops on a particular route_id.
def get_trip_points(cur, route_id, offset=0, tripid_glob=''): """Get all scheduled stops on a particular route_id. Given a route_id, return the trip-stop-list with latitude/longitudes. This is a bit more tricky than it seems, because we have to go from table route->trips->stop_times. This functio...
Interpolate passage times for shape points.
def interpolate_shape_times(shape_distances, shape_breaks, stop_times): """ Interpolate passage times for shape points. Parameters ---------- shape_distances: list list of cumulative distances along the shape shape_breaks: list list of shape_breaks stop_times: list l...
# this function should be optimized
def update_pareto_optimal_tuples(self, new_pareto_tuple): """ # this function should be optimized Parameters ---------- new_pareto_tuple: LabelTimeSimple Returns ------- added: bool whether new_pareto_tuple was added to the set of pareto-opti...
Get the earliest arrival time at the target given a departure time.
def evaluate_earliest_arrival_time_at_target(self, dep_time, transfer_margin): """ Get the earliest arrival time at the target, given a departure time. Parameters ---------- dep_time : float, int time in unix seconds transfer_margin: float, int tr...
Run the actual simulation.
def _run(self): """ Run the actual simulation. """ if self._has_run: raise RuntimeError("This spreader instance has already been run: " "create a new Spreader object for a new run.") i = 1 while self.event_heap.size() > 0 and len...
Computes the walk paths between stops and updates these to the gtfs database.
def add_walk_distances_to_db_python(gtfs, osm_path, cutoff_distance_m=1000): """ Computes the walk paths between stops, and updates these to the gtfs database. Parameters ---------- gtfs: gtfspy.GTFS or str A GTFS object or a string representation. osm_path: str path to the Open...
Parameters ---------- gtfs: a GTFS object walk_network: networkx. Graph
def match_stops_to_nodes(gtfs, walk_network): """ Parameters ---------- gtfs : a GTFS object walk_network : networkx.Graph Returns ------- stop_I_to_node: dict maps stop_I to closest walk_network node stop_I_to_dist: dict maps stop_I to the distance to the closest wa...
Construct the walk network. If OpenStreetMap - based walking distances have been computed then those are used as the distance. Otherwise the great circle distances ( d ) is used.
def walk_transfer_stop_to_stop_network(gtfs, max_link_distance=None): """ Construct the walk network. If OpenStreetMap-based walking distances have been computed, then those are used as the distance. Otherwise, the great circle distances ("d") is used. Parameters ---------- gtfs: gtfspy.GTF...
Get a stop - to - stop network describing a single mode of travel.
def stop_to_stop_network_for_route_type(gtfs, route_type, link_attributes=None, start_time_ut=None, end_time_ut=None): """ Get a stop-to-stop network de...
Compute stop - to - stop networks for all travel modes ( route_types ).
def stop_to_stop_networks_by_type(gtfs): """ Compute stop-to-stop networks for all travel modes (route_types). Parameters ---------- gtfs: gtfspy.GTFS Returns ------- dict: dict[int, networkx.DiGraph] keys should be one of route_types.ALL_ROUTE_TYPES (i.e. GTFS route_types) ...
Compute stop - to - stop networks for all travel modes and combine them into a single network. The modes of transport are encoded to a single network. The network consists of multiple links corresponding to each travel mode. Walk mode is not included.
def combined_stop_to_stop_transit_network(gtfs, start_time_ut=None, end_time_ut=None): """ Compute stop-to-stop networks for all travel modes and combine them into a single network. The modes of transport are encoded to a single network. The network consists of multiple links corresponding to each trave...
Add nodes to the network from the pandas dataframe describing ( a part of the ) stops table in the GTFS database.
def _add_stops_to_net(net, stops): """ Add nodes to the network from the pandas dataframe describing (a part of the) stops table in the GTFS database. Parameters ---------- net: networkx.Graph stops: pandas.DataFrame """ for stop in stops.itertuples(): data = { "lat"...
Compute the temporal network of the data and return it as a pandas. DataFrame
def temporal_network(gtfs, start_time_ut=None, end_time_ut=None, route_type=None): """ Compute the temporal network of the data, and return it as a pandas.DataFrame Parameters ---------- gtfs : gtfspy.GTFS start_time_ut: int | None ...
Creates networkx graph where the nodes are bus routes and a edge indicates that there is a possibility to transfer between the routes: param gtfs:: param walking_threshold:: param start_time:: param end_time:: return:
def route_to_route_network(gtfs, walking_threshold, start_time, end_time): """ Creates networkx graph where the nodes are bus routes and a edge indicates that there is a possibility to transfer between the routes :param gtfs: :param walking_threshold: :param start_time: :param end_time: ...
Get mean temporal distance ( in seconds ) to the target.
def mean_temporal_distance(self): """ Get mean temporal distance (in seconds) to the target. Returns ------- mean_temporal_distance : float """ total_width = self.end_time_dep - self.start_time_dep total_area = sum([block.area() for block in self._profile...
Plot the temporal distance cumulative density function.
def plot_temporal_distance_cdf(self): """ Plot the temporal distance cumulative density function. Returns ------- fig: matplotlib.Figure """ xvalues, cdf = self.profile_block_analyzer._temporal_distance_cdf() fig = plt.figure() ax = fig.add_subplo...
Plot the temporal distance probability density function.
def plot_temporal_distance_pdf(self, use_minutes=True, color="green", ax=None): """ Plot the temporal distance probability density function. Returns ------- fig: matplotlib.Figure """ from matplotlib import pyplot as plt plt.rc('text', usetex=True) ...
Plot the temporal distance probability density function.
def plot_temporal_distance_pdf_horizontal(self, use_minutes=True, color="green", ax=None, duration_divider=60.0, legend_font_size=None, ...
Parameters ---------- timezone: str color: color format_string: str None if None the original values are used plot_journeys: bool optional if True small dots are plotted at the departure times
def plot_temporal_distance_profile(self, timezone=None, color="black", alpha=0.15, ax=None, lw=2, ...
Parameters ---------- leg: Connection
def add_leg(self, leg): """ Parameters ---------- leg: Connection """ assert(isinstance(leg, Connection)) if not self.legs: self.departure_time = leg.departure_time self.arrival_time = leg.arrival_time if leg.trip_id and (not self.legs ...
Get stop pairs through which transfers take place
def get_transfer_stop_pairs(self): """ Get stop pairs through which transfers take place Returns ------- transfer_stop_pairs: list """ transfer_stop_pairs = [] previous_arrival_stop = None current_trip_id = None for leg in self.legs: ...
Truncates a colormap to use. Code originall from http:// stackoverflow. com/ questions/ 18926031/ how - to - extract - a - subset - of - a - colormap - as - a - new - colormap - in - matplotlib
def _truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100): """ Truncates a colormap to use. Code originall from http://stackoverflow.com/questions/18926031/how-to-extract-a-subset-of-a-colormap-as-a-new-colormap-in-matplotlib """ new_cmap = LinearSegmentedColormap.from_list( 'trunc({n},{a:...
Parameters ---------- max_n_boardings: int The maximum number of boardings allowed for the labels used to construct the temporal distance profile
def get_time_profile_analyzer(self, max_n_boardings=None): """ Parameters ---------- max_n_boardings: int The maximum number of boardings allowed for the labels used to construct the "temporal distance profile" Returns ------- analyzer: NodeProfileAna...
Returns ------- mean_temporal_distances: list list indices encode the number of vehicle legs each element in the list tells gets the mean temporal distance
def median_temporal_distances(self, min_n_boardings=None, max_n_boardings=None): """ Returns ------- mean_temporal_distances: list list indices encode the number of vehicle legs each element in the list tells gets the mean temporal distance """ if ...
Instantiate a GTFS object by computing
def from_directory_as_inmemory_db(cls, gtfs_directory): """ Instantiate a GTFS object by computing Parameters ---------- gtfs_directory: str path to the directory for importing the database """ # this import is here to avoid circular imports (which tu...
Should return the path to the database
def get_main_database_path(self): """ Should return the path to the database Returns ------- path : unicode path to the database, empty string for in-memory databases """ cur = self.conn.cursor() cur.execute("PRAGMA database_list") row...
Get the distance along a shape between stops
def get_shape_distance_between_stops(self, trip_I, from_stop_seq, to_stop_seq): """ Get the distance along a shape between stops Parameters ---------- trip_I : int trip_ID along which we travel from_stop_seq : int the sequence number of the 'origi...
Returns stops that are accessible without transfer from the stops that are within a specific walking distance: param stop: int: param distance: int: return:
def get_directly_accessible_stops_within_distance(self, stop, distance): """ Returns stops that are accessible without transfer from the stops that are within a specific walking distance :param stop: int :param distance: int :return: """ query = """SELECT stop.* F...
Get name of the GTFS timezone
def get_timezone_name(self): """ Get name of the GTFS timezone Returns ------- timezone_name : str name of the time zone, e.g. "Europe/Helsinki" """ tz_name = self.conn.execute('SELECT timezone FROM agencies LIMIT 1').fetchone() if tz_name is ...
Return the timezone of the GTFS database object as a string. The assumed time when the timezone ( difference ) is computed is the download date of the file. This might not be optimal in all cases.
def get_timezone_string(self, dt=None): """ Return the timezone of the GTFS database object as a string. The assumed time when the timezone (difference) is computed is the download date of the file. This might not be optimal in all cases. So this function should return v...
Convert datetime ( in GTFS timezone ) to unixtime
def unlocalized_datetime_to_ut_seconds(self, unlocalized_datetime): """ Convert datetime (in GTFS timezone) to unixtime Parameters ---------- unlocalized_datetime : datetime.datetime (tz coerced to GTFS timezone, should NOT be UTC.) Returns ------- ...
Get day start time ( as specified by GTFS ) as unix time in seconds
def get_day_start_ut(self, date): """ Get day start time (as specified by GTFS) as unix time in seconds Parameters ---------- date : str | unicode | datetime.datetime something describing the date Returns ------- day_start_ut : int ...
Get complete trip data for visualizing public transport operation based on gtfs.
def get_trip_trajectories_within_timespan(self, start, end, use_shapes=True, filter_name=None): """ Get complete trip data for visualizing public transport operation based on gtfs. Parameters ---------- start: number Earliest position data to return (in unix time) ...
Get stop count data.
def get_stop_count_data(self, start_ut, end_ut): """ Get stop count data. Parameters ---------- start_ut : int start time in unixtime end_ut : int end time in unixtime Returns ------- stopData : pandas.DataFrame ...
Get segment data including PTN vehicle counts per segment that are fully _contained_ within the interval ( start end )
def get_segment_count_data(self, start, end, use_shapes=True): """ Get segment data including PTN vehicle counts per segment that are fully _contained_ within the interval (start, end) Parameters ---------- start : int start time of the simulation in unix tim...
Get the shapes of all routes.
def get_all_route_shapes(self, use_shapes=True): """ Get the shapes of all routes. Parameters ---------- use_shapes : bool, optional by default True (i.e. use shapes as the name of the function indicates) if False (fall back to lats and longitudes) ...
Obtain from the ( standard ) GTFS database list of trip_IDs ( and other trip_related info ) that are active between given start and end times.
def get_tripIs_active_in_range(self, start, end): """ Obtain from the (standard) GTFS database, list of trip_IDs (and other trip_related info) that are active between given 'start' and 'end' times. The start time of a trip is determined by the departure time at the last stop of the trip...
Get trip counts per day between the start and end day of the feed.
def get_trip_counts_per_day(self): """ Get trip counts per day between the start and end day of the feed. Returns ------- trip_counts : pandas.DataFrame Has columns "date_str" (dtype str) "trip_counts" (dtype int) """ query = "SELECT date, count(*) AS...
Parameters ---------- date: str ut: bool Whether to return the date as a string or as a an int ( seconds after epoch ).
def get_suitable_date_for_daily_extract(self, date=None, ut=False): """ Parameters ---------- date : str ut : bool Whether to return the date as a string or as a an int (seconds after epoch). Returns ------- Selects suitable date for daily ext...
Find a suitable weekly extract start date ( monday ). The goal is to obtain as usual week as possible. The weekdays of the weekly extract week should contain at least 0. 9 of the total maximum of trips.
def get_weekly_extract_start_date(self, ut=False, weekdays_at_least_of_max=0.9, verbose=False, download_date_override=None): """ Find a suitable weekly extract start date (monday). The goal is to obtain as 'usual' week as possible. The weekdays of th...
Starting from a specific point and time get complete single source shortest path spreading dynamics as trips or events.
def get_spreading_trips(self, start_time_ut, lat, lon, max_duration_ut=4 * 3600, min_transfer_time=30, use_shapes=False): """ Starting from a specific point and time, get complete single source shortest path spre...
Get closest stop to a given location.
def get_closest_stop(self, lat, lon): """ Get closest stop to a given location. Parameters ---------- lat: float latitude coordinate of the location lon: float longitude coordinate of the location Returns ------- stop_I: i...
Get route short name and type
def get_route_name_and_type_of_tripI(self, trip_I): """ Get route short name and type Parameters ---------- trip_I: int short trip index created when creating the database Returns ------- name: str short name of the route, eg. 195...
Get route short name and type
def get_route_name_and_type(self, route_I): """ Get route short name and type Parameters ---------- route_I: int route index (database specific) Returns ------- name: str short name of the route, eg. 195N type: int ...
Get coordinates for a given trip_I
def get_trip_stop_coordinates(self, trip_I): """ Get coordinates for a given trip_I Parameters ---------- trip_I : int the integer id of the trip Returns ------- stop_coords : pandas.DataFrame with columns "lats" and "lons" ...
Obtain from the ( standard ) GTFS database trip stop data ( departure time in ut lat lon seq shape_break ) as a pandas DataFrame
def get_trip_stop_time_data(self, trip_I, day_start_ut): """ Obtain from the (standard) GTFS database, trip stop data (departure time in ut, lat, lon, seq, shape_break) as a pandas DataFrame Some filtering could be applied here, if only e.g. departure times corresponding within ...
Get trip data as a list of events ( i. e. dicts ).
def get_events_by_tripI_and_dsut(self, trip_I, day_start_ut, start_ut=None, end_ut=None): """ Get trip data as a list of events (i.e. dicts). Parameters ---------- trip_I : int shorthand index of the trip. day_start_ut : i...
Check that a trip takes place during a day
def tripI_takes_place_on_dsut(self, trip_I, day_start_ut): """ Check that a trip takes place during a day Parameters ---------- trip_I : int index of the trip in the gtfs data base day_start_ut : int the starting time of the day in unix time (seco...
Convert unixtime to unixtime on GTFS start - of - day.
def day_start_ut(self, ut): """ Convert unixtime to unixtime on GTFS start-of-day. GTFS defines the start of a day as "noon minus 12 hours" to solve most DST-related problems. This means that on DST-changing days, the day start isn't midnight. This function isn't idempotent. ...
Increment the GTFS - definition of day start.
def increment_day_start_ut(self, day_start_ut, n_days=1): """Increment the GTFS-definition of "day start". Parameters ---------- day_start_ut : int unixtime of the previous start of day. If this time is between 12:00 or greater, there *will* be bugs. To solve t...
Get all possible day start times between start_ut and end_ut Currently this function is used only by get_tripIs_within_range_by_dsut
def _get_possible_day_starts(self, start_ut, end_ut, max_time_overnight=None): """ Get all possible day start times between start_ut and end_ut Currently this function is used only by get_tripIs_within_range_by_dsut Parameters ---------- start_ut : list<int> ...
Obtain a list of trip_Is that take place during a time interval. The trip needs to be only partially overlapping with the given time interval. The grouping by dsut ( day_start_ut ) is required as same trip_I could take place on multiple days.
def get_tripIs_within_range_by_dsut(self, start_time_ut, end_time_ut): """ Obtain a list of trip_Is that take place during a time interval. The trip needs to be only partially overlapping with the given time interval...
Get all stop data as a pandas DataFrame for all stops or an individual stop
def stop(self, stop_I): """ Get all stop data as a pandas DataFrame for all stops, or an individual stop' Parameters ---------- stop_I : int stop index Returns ------- stop: pandas.DataFrame """ return pd.read_sql_query("SELEC...
Parameters ---------- route_type: int
def get_stops_for_route_type(self, route_type): """ Parameters ---------- route_type: int Returns ------- stops: pandas.DataFrame """ if route_type is WALK: return self.stops() else: return pd.read_sql_query("SELEC...
Generates events that take place during a time interval [ start_time_ut end_time_ut ]. Each event needs to be only partially overlap the given time interval. Does not include walking events. This is just a quick and dirty implementation to get a way of quickly get a method for generating events compatible with the rout...
def generate_routable_transit_events(self, start_time_ut=None, end_time_ut=None, route_type=None): """ Generates events that take place during a time interval [start_time_ut, end_time_ut]. Each event needs to be only partially overlap the given time interval. Does not include walking eve...
Obtain a list of events that take place during a time interval. Each event needs to be only partially overlap the given time interval. Does not include walking events.
def get_transit_events(self, start_time_ut=None, end_time_ut=None, route_type=None): """ Obtain a list of events that take place during a time interval. Each event needs to be only partially overlap the given time interval. Does not include walking events. Parameters ---...
Compares the routes based on stops in the schedule with the routes in another db and returns the ones without match. Uniqueness thresholds or ratio can be used to allow small differences: param uniqueness_threshold:: param uniqueness_ratio:: return:
def get_route_difference_with_other_db(self, other_gtfs, start_time, end_time, uniqueness_threshold=None, uniqueness_ratio=None): """ Compares the routes based on stops in the schedule with the routes in another db and returns the ones without match. Un...
Get ( straight line ) distances to stations that can be transferred to.
def get_straight_line_transfer_distances(self, stop_I=None): """ Get (straight line) distances to stations that can be transferred to. Parameters ---------- stop_I : int, optional If not specified return all possible transfer distances Returns ------...
Return the first and last day_start_ut
def get_day_start_ut_span(self): """ Return the first and last day_start_ut Returns ------- first_day_start_ut: int last_day_start_ut: int """ cur = self.conn.cursor() first_day_start_ut, last_day_start_ut = \ cur.execute("SELECT min(d...
This function takes an external database looks of common stops and adds the missing stops to both databases. In addition the stop_pair_I column is added. This id links the stops between these two sources.: param source: directory of external database: return:
def homogenize_stops_table_with_other_db(self, source): """ This function takes an external database, looks of common stops and adds the missing stops to both databases. In addition the stop_pair_I column is added. This id links the stops between these two sources. :param source: directo...
Recover pre - computed travel_impedance between od - pairs from the database.
def read_data_as_dataframe(self, travel_impedance_measure, from_stop_I=None, to_stop_I=None, statistic=None): """ Recover pre-computed travel_impedance between od-pairs from the da...
Parameters ---------- travel_impedance_measure_name: str data: list [ dict ] Each list element must contain keys: from_stop_I to_stop_I min max median and mean
def insert_data(self, travel_impedance_measure_name, data): """ Parameters ---------- travel_impedance_measure_name: str data: list[dict] Each list element must contain keys: "from_stop_I", "to_stop_I", "min", "max", "median" and "mean" """ ...