def median_temporal_distances(self, min_n_boardings=None, max_n_boardings=None):

if min_n_boardings is None:<EOL><INDENT>min_n_boardings = <NUM_LIT:0><EOL><DEDENT>if max_n_boardings is None:<EOL><INDENT>max_n_boardings = self.max_trip_n_boardings()<EOL>if max_n_boardings is None:<EOL><INDENT>max_n_boardings = <NUM_LIT:0><EOL><DEDENT><DEDENT>median_temporal_distances = [float('<STR_LIT>') for _ in range(min_n_boardings, max_n_boardings + <NUM_LIT:1>)]<EOL>for n_boardings in range(min_n_boardings, max_n_boardings + <NUM_LIT:1>):<EOL><INDENT>simple_analyzer = self.get_time_profile_analyzer(n_boardings)<EOL>median_temporal_distances[n_boardings] = simple_analyzer.median_temporal_distance()<EOL><DEDENT>return median_temporal_distances<EOL>

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 __init__(self, labels, walk_to_target_duration, start_time_dep, end_time_dep):

self._node_profile_final_labels = labels<EOL>self.start_time_dep = start_time_dep<EOL>self.end_time_dep = end_time_dep<EOL>self.all_labels = [label for label in self._node_profile_final_labels if<EOL>(start_time_dep <= label.departure_time <= end_time_dep)]<EOL>after_label_candidates = [label for label in self._node_profile_final_labels if<EOL>(label.departure_time > self.end_time_dep)]<EOL>after_label_candidates.sort(key=lambda el: (el.arrival_time_target, el.n_boardings))<EOL>min_n_boardings_observed = float('<STR_LIT>')<EOL>after_labels = []<EOL>for candidate_after_label in after_label_candidates:<EOL><INDENT>if candidate_after_label.n_boardings < min_n_boardings_observed:<EOL><INDENT>after_labels.append(candidate_after_label)<EOL>min_n_boardings_observed = candidate_after_label.n_boardings<EOL><DEDENT><DEDENT>self.all_labels.extend(after_labels)<EOL>if len(after_labels) is <NUM_LIT:0>:<EOL><INDENT>self._labels_within_time_frame = self.all_labels<EOL><DEDENT>else:<EOL><INDENT>self._labels_within_time_frame = self.all_labels[:-len(after_labels)]<EOL><DEDENT>self._walk_to_target_duration = walk_to_target_duration<EOL>self._n_boardings_to_simple_time_analyzers = {}<EOL>self._transfers_on_fastest_paths_analyzer = self._get_transfers_on_fastest_path_analyzer()<EOL>

Initialize the data structures required by

Parameters
----------
node_profile: NodeProfileMultiObjective


return float(len(self._labels_within_time_frame))<EOL>

Get number of pareto-optimal trips

Returns
-------
n_trips: float


def _truncate_colormap(cmap, minval=<NUM_LIT:0.0>, maxval=<NUM_LIT:1.0>, n=<NUM_LIT:100>):

new_cmap = LinearSegmentedColormap.from_list(<EOL>'<STR_LIT>'.format(n=cmap.name, a=minval, b=maxval),<EOL>cmap(numpy.linspace(minval, maxval, n))<EOL>)<EOL>return new_cmap<EOL>

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


to_select = []<EOL>where_clauses = []<EOL>to_select.append("<STR_LIT>")<EOL>to_select.append("<STR_LIT>")<EOL>if from_stop_I is not None:<EOL><INDENT>where_clauses.append("<STR_LIT>" + str(int(from_stop_I)))<EOL><DEDENT>if to_stop_I is not None:<EOL><INDENT>where_clauses.append("<STR_LIT>" + str(int(to_stop_I)))<EOL><DEDENT>where_clause = "<STR_LIT>"<EOL>if len(where_clauses) > <NUM_LIT:0>:<EOL><INDENT>where_clause = "<STR_LIT>" + "<STR_LIT>".join(where_clauses)<EOL><DEDENT>if not statistic:<EOL><INDENT>to_select.extend(["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>to_select.append(statistic)<EOL><DEDENT>to_select_clause = "<STR_LIT:U+002C>".join(to_select)<EOL>if not to_select_clause:<EOL><INDENT>to_select_clause = "<STR_LIT:*>"<EOL><DEDENT>sql = "<STR_LIT>" + to_select_clause + "<STR_LIT>" + travel_impedance_measure + where_clause + "<STR_LIT:;>"<EOL>df = pd.read_sql(sql, self.conn)<EOL>return df<EOL>

Recover pre-computed travel_impedance between od-pairs from the database.

Returns
-------
values: number | Pandas DataFrame


assert self._has_run<EOL>return self.__stop_labels<EOL>

Returns
-------
arrival_times: dict[int, float]
    maps integer stop_ids to floats


return self._walk_to_target_duration<EOL>

Get walking distance to target node.

Returns
-------
walk_to_target_duration: float


if dep_times is None:<EOL><INDENT>dep_times = []<EOL><DEDENT>n_dep_times = len(dep_times)<EOL>assert n_dep_times == len(set(dep_times)), "<STR_LIT>"<EOL>self._departure_times = list(reversed(sorted(dep_times)))<EOL>self.dep_times_to_index = dict(zip(self._departure_times, range(len(self._departure_times))))<EOL>self._label_bags = [[]] * len(self._departure_times)<EOL>self._walk_to_target_duration = walk_to_target_duration<EOL>self._min_dep_time = float('<STR_LIT>')<EOL>self.label_class = label_class<EOL>self.closest_target = closest_target<EOL>if self.label_class == LabelTimeBoardingsAndRoute and self._walk_to_target_duration < float('<STR_LIT>'):<EOL><INDENT>assert (self.closest_target is not None)<EOL><DEDENT>if transit_connection_dep_times is not None:<EOL><INDENT>self._connection_dep_times = transit_connection_dep_times<EOL><DEDENT>else:<EOL><INDENT>self._connection_dep_times = dep_times<EOL><DEDENT>assert (isinstance(self._connection_dep_times, (list, numpy.ndarray)))<EOL>self._closed = False<EOL>self._finalized = False<EOL>self._final_pareto_optimal_labels = None<EOL>self._real_connection_labels = None<EOL>self.node_id = node_id<EOL>

Parameters
----------
dep_times
walk_to_target_duration
label_class: label class to be used
transit_connection_dep_times:
    if not given, all connections are assumed to be real connections
closest_target: int, optional
    stop_I of the closest target if within walking distance (and Routes are recorded)


block_start_distances = [block.distance_start for block in self._profile_blocks if<EOL>block.distance_start < float('<STR_LIT>')]<EOL>block_end_distances = [block.distance_end for block in self._profile_blocks if<EOL>block.distance_end < float('<STR_LIT>')]<EOL>distances = block_start_distances + block_end_distances<EOL>if len(distances) > <NUM_LIT:0>:<EOL><INDENT>return max(distances)<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Compute the maximum temporal distance.

Returns
-------
max_temporal_distance : float


pass<EOL>


def get_upstream_stops_ratio(self, target, trough_stops, ratio):

if isinstance(trough_stops, list):<EOL><INDENT>trough_stops = "<STR_LIT:U+002C>".join(trough_stops)<EOL><DEDENT>query = """<STR_LIT>""".format(target=target, trough_stops=trough_stops, ratio=ratio)<EOL>df = read_sql_query(query, self.conn)<EOL>return df<EOL>

Selects the stops for which the ratio or higher proportion of trips to the target passes trough a set of trough stops
:param target: target of trips
:param trough_stops: stops where the selected trips are passing trough
:param ratio: threshold for inclusion
:return:


def _insert_journeys_into_db_no_route(self, stop_profiles, target_stop=None):<EOL>

print("<STR_LIT>")<EOL>journey_id = <NUM_LIT:1><EOL>journey_list = []<EOL>tot = len(stop_profiles)<EOL>for i, (origin_stop, labels) in enumerate(stop_profiles.items(), start=<NUM_LIT:1>):<EOL><INDENT>for label in labels:<EOL><INDENT>assert (isinstance(label, LabelTimeWithBoardingsCount))<EOL>if self.multitarget_routing:<EOL><INDENT>target_stop = None<EOL><DEDENT>else:<EOL><INDENT>target_stop = int(target_stop)<EOL><DEDENT>values = [int(journey_id),<EOL>int(origin_stop),<EOL>target_stop,<EOL>int(label.departure_time),<EOL>int(label.arrival_time_target),<EOL>int(label.n_boardings)]<EOL>journey_list.append(values)<EOL>journey_id += <NUM_LIT:1><EOL><DEDENT><DEDENT>print("<STR_LIT>")<EOL>insert_journeys_stmt = '''<STR_LIT>''' % ("<STR_LIT:U+002CU+0020>".join(["<STR_LIT:?>" for x in range(<NUM_LIT:6>)]))<EOL>self._executemany_exclusive(insert_journeys_stmt, journey_list)<EOL>self.conn.commit()<EOL>

con.isolation_level = 'EXCLUSIVE'
con.execute('BEGIN EXCLUSIVE')
#exclusive access starts here. Nothing else can r/w the db, do your magic here.
con.commit()


def __init__(self, gtfs_path, journey_db_path, routing_params=None, multitarget_routing=False,<EOL>track_vehicle_legs=True, track_route=False):

self.multitarget_routing = multitarget_routing<EOL>self.track_route = track_route<EOL>self.track_vehicle_legs = track_vehicle_legs<EOL>self.gtfs_path = gtfs_path<EOL>self.gtfs = GTFS(self.gtfs_path)<EOL>self.gtfs_meta = self.gtfs.meta<EOL>self.gtfs._dont_close = True<EOL>self.od_pairs = None<EOL>self._targets = None<EOL>self._origins = None<EOL>self.diff_conn = None<EOL>if not routing_params:<EOL><INDENT>routing_params = dict()<EOL><DEDENT>self.routing_params_input = routing_params<EOL>assert os.path.exists(journey_db_path) or routing_params is not None<EOL>journey_db_pre_exists = os.path.isfile(journey_db_path)<EOL>timeout = <NUM_LIT:1000><EOL>self.conn = sqlite3.connect(journey_db_path, timeout)<EOL>if not journey_db_pre_exists:<EOL><INDENT>self.initialize_database()<EOL><DEDENT>self.routing_parameters = Parameters(self.conn)<EOL>self._assert_journey_computation_paramaters_match()<EOL>self.journey_properties = {"<STR_LIT>": (_T_WALK_STR, _T_WALK_STR)}<EOL>if routing_params.get('<STR_LIT>', False) orself.routing_parameters.get('<STR_LIT>', False):<EOL><INDENT>self.journey_properties["<STR_LIT>"] = (float("<STR_LIT>"), <NUM_LIT:0>)<EOL><DEDENT>if self.track_route:<EOL><INDENT>additional_journey_parameters = {<EOL>"<STR_LIT>": (float('<STR_LIT>'), <NUM_LIT:0>),<EOL>"<STR_LIT>": (float('<STR_LIT>'), <NUM_LIT:0>),<EOL>"<STR_LIT>": (_T_WALK_STR, _T_WALK_STR),<EOL>"<STR_LIT>": (float('<STR_LIT>'), <NUM_LIT:0>)<EOL>}<EOL>self.journey_properties.update(additional_journey_parameters)<EOL><DEDENT>self.travel_impedance_measure_names = list(self.journey_properties.keys())<EOL>self.travel_impedance_measure_names += ["<STR_LIT>"]<EOL>

:param gtfs: GTFS object
:param list_of_stop_profiles: dict of NodeProfileMultiObjective
:param multitarget_routing: bool


assert (isinstance(new_label, LabelTime))<EOL>if self._labels:<EOL><INDENT>assert (new_label.departure_time <= self._labels[-<NUM_LIT:1>].departure_time)<EOL>best_later_departing_arrival_time = self._labels[-<NUM_LIT:1>].arrival_time_target<EOL><DEDENT>else:<EOL><INDENT>best_later_departing_arrival_time = float('<STR_LIT>')<EOL><DEDENT>walk_to_target_arrival_time = new_label.departure_time + self._walk_to_target_duration<EOL>best_arrival_time = min(walk_to_target_arrival_time,<EOL>best_later_departing_arrival_time,<EOL>new_label.arrival_time_target)<EOL>if (new_label.arrival_time_target < walk_to_target_arrival_time and<EOL>new_label.arrival_time_target < best_later_departing_arrival_time):<EOL><INDENT>self._labels.append(LabelTime(new_label.departure_time, best_arrival_time))<EOL>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>

Parameters
----------
new_label: LabelTime

Returns
-------
updated: bool


def evaluate_earliest_arrival_time_at_target(self, dep_time, transfer_margin):

minimum = dep_time + self._walk_to_target_duration<EOL>for label in self._labels[::-<NUM_LIT:1>]:<EOL><INDENT>if label.departure_time >= dep_time + transfer_margin:<EOL><INDENT>minimum = min(minimum, label.arrival_time_target)<EOL>break<EOL><DEDENT><DEDENT>return float(minimum)<EOL>

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
    transfer margin in seconds

Returns
-------
arrival_time : float
    Arrival time in the given time unit (seconds after unix epoch).


self.legs = []<EOL>self.departure_time = None<EOL>self.arrival_time = None<EOL>self.trip_ids = set()<EOL>self.n_boardings = <NUM_LIT:0><EOL>if legs is not None:<EOL><INDENT>for leg in legs:<EOL><INDENT>self.add_leg(leg)<EOL><DEDENT><DEDENT>

Parameters
----------
legs: list[Connection]


transfer_stop_pairs = []<EOL>previous_arrival_stop = None<EOL>current_trip_id = None<EOL>for leg in self.legs:<EOL><INDENT>if leg.trip_id is not None and leg.trip_id != current_trip_id and previous_arrival_stop is not None:<EOL><INDENT>transfer_stop_pair = (previous_arrival_stop, leg.departure_stop)<EOL>transfer_stop_pairs.append(transfer_stop_pair)<EOL><DEDENT>previous_arrival_stop = leg.arrival_stop<EOL>current_trip_id = leg.trip_id<EOL><DEDENT>return transfer_stop_pairs<EOL>

Get stop pairs through which transfers take place

Returns
-------
transfer_stop_pairs: list


def _scan_footpaths_to_departure_stop(self, connection_dep_stop, connection_dep_time, arrival_time_target):

for _, neighbor, data in self._walk_network.edges_iter(nbunch=[connection_dep_stop],<EOL>data=True):<EOL><INDENT>d_walk = data['<STR_LIT>']<EOL>neighbor_dep_time = connection_dep_time - d_walk / self._walk_speed<EOL>pt = LabelTimeSimple(departure_time=neighbor_dep_time, arrival_time_target=arrival_time_target)<EOL>self._stop_profiles[neighbor].update_pareto_optimal_tuples(pt)<EOL><DEDENT>

A helper method for scanning the footpaths. Updates self._stop_profiles accordingly


AbstractRoutingAlgorithm.__init__(self)<EOL>self._target = target_stop<EOL>self._connections = transit_events<EOL>if start_time is None:<EOL><INDENT>start_time = transit_events[-<NUM_LIT:1>].departure_time<EOL><DEDENT>if end_time is None:<EOL><INDENT>end_time = transit_events[<NUM_LIT:0>].departure_time<EOL><DEDENT>self._start_time = start_time<EOL>self._end_time = end_time<EOL>self._transfer_margin = transfer_margin<EOL>if walk_network is None:<EOL><INDENT>walk_network = networkx.Graph()<EOL><DEDENT>self._walk_network = walk_network<EOL>self._walk_speed = float(walk_speed)<EOL>self._verbose = verbose<EOL>self.__trip_min_arrival_time = defaultdict(lambda: float("<STR_LIT>"))<EOL>self._stop_profiles = defaultdict(lambda: NodeProfileSimple())<EOL>self._stop_profiles[self._target] = NodeProfileSimple(<NUM_LIT:0>)<EOL>if target_stop in walk_network.nodes():<EOL><INDENT>for target_neighbor in walk_network.neighbors(target_stop):<EOL><INDENT>edge_data = walk_network.get_edge_data(target_neighbor, target_stop)<EOL>walk_duration = edge_data["<STR_LIT>"] / self._walk_speed<EOL>self._stop_profiles[target_neighbor] = NodeProfileSimple(walk_duration)<EOL><DEDENT><DEDENT>

Parameters
----------
transit_events: list[Connection]
    events are assumed to be ordered in DECREASING departure_time (!)
target_stop: int
    index of the target stop
start_time : int, optional
    start time in unixtime seconds
end_time: int, optional
    end time in unixtime seconds (no connections will be scanned after this time)
transfer_margin: int, optional
    required extra margin required for transfers in seconds
walk_speed: float, optional
    walking speed between stops in meters / second.
walk_network: networkx.Graph, optional
    each edge should have the walking distance as a data attribute ("distance_shape") expressed in meters
verbose: boolean, optional
    whether to print out progress


assert self._has_run<EOL>return self._stop_profiles<EOL>

Returns
-------
_stop_profiles : dict[int, NodeProfileSimple]
    The pareto tuples necessary.


return numpy.median(self.trip_durations)<EOL>

Get average travel time to destination.

Returns
-------
float: max_trip_duration
    float('inf') if no trips take place


return float(len(self.trip_durations))<EOL>

Get number of pareto-optimal trips

Returns
-------
n_trips: float


return numpy.max(self.trip_durations)<EOL>

Get minimum travel time to destination.

Returns
-------
float: max_trip_duration
    float('inf') if no trips take place


return numpy.mean(self.trip_durations)<EOL>


total_width = self.end_time_dep - self.start_time_dep<EOL>total_area = sum([block.area() for block in self._profile_blocks])<EOL>return total_area / total_width<EOL>

Get mean temporal distance (in seconds) to the target.

Returns
-------
mean_temporal_distance : float


return self.profile_block_analyzer.largest_finite_distance()<EOL>


def __init__(self, labels, walk_time_to_target, start_time_dep, end_time_dep):

self.start_time_dep = start_time_dep<EOL>self.end_time_dep = end_time_dep<EOL>all_pareto_optimal_tuples = [pt for pt in labels if<EOL>(start_time_dep < pt.departure_time < end_time_dep)]<EOL>labels_after_dep_time = [label for label in labels if label.departure_time >= self.end_time_dep]<EOL>if labels_after_dep_time:<EOL><INDENT>next_label_after_end_time = min(labels_after_dep_time, key=lambda el: el.arrival_time_target)<EOL>all_pareto_optimal_tuples.append(next_label_after_end_time)<EOL><DEDENT>all_pareto_optimal_tuples = sorted(all_pareto_optimal_tuples, key=lambda ptuple: ptuple.departure_time)<EOL>arrival_time_target_at_end_time = end_time_dep + walk_time_to_target<EOL>previous_trip = None<EOL>for trip_tuple in all_pareto_optimal_tuples:<EOL><INDENT>if previous_trip:<EOL><INDENT>assert(trip_tuple.arrival_time_target > previous_trip.arrival_time_target)<EOL><DEDENT>if trip_tuple.departure_time > self.end_time_depand trip_tuple.arrival_time_target < arrival_time_target_at_end_time:<EOL><INDENT>arrival_time_target_at_end_time = trip_tuple.arrival_time_target<EOL><DEDENT>previous_trip = trip_tuple<EOL><DEDENT>self._walk_time_to_target = walk_time_to_target<EOL>self._profile_blocks = []<EOL>previous_departure_time = start_time_dep<EOL>self.trip_durations = []<EOL>self.trip_departure_times = []<EOL>for trip_pareto_tuple in all_pareto_optimal_tuples:<EOL><INDENT>if trip_pareto_tuple.departure_time > self.end_time_dep:<EOL><INDENT>continue<EOL><DEDENT>if self._walk_time_to_target <= trip_pareto_tuple.duration():<EOL><INDENT>print(self._walk_time_to_target, trip_pareto_tuple.duration())<EOL>assert(self._walk_time_to_target > trip_pareto_tuple.duration())<EOL><DEDENT>effective_trip_previous_departure_time = max(<EOL>previous_departure_time,<EOL>trip_pareto_tuple.departure_time - (self._walk_time_to_target - trip_pareto_tuple.duration())<EOL>)<EOL>if effective_trip_previous_departure_time > previous_departure_time:<EOL><INDENT>walk_block = ProfileBlock(start_time=previous_departure_time,<EOL>end_time=effective_trip_previous_departure_time,<EOL>distance_start=self._walk_time_to_target,<EOL>distance_end=self._walk_time_to_target<EOL>)<EOL>self._profile_blocks.append(walk_block)<EOL><DEDENT>trip_waiting_time = trip_pareto_tuple.departure_time - effective_trip_previous_departure_time<EOL>trip_block = ProfileBlock(end_time=trip_pareto_tuple.departure_time,<EOL>start_time=effective_trip_previous_departure_time,<EOL>distance_start=trip_pareto_tuple.duration() + trip_waiting_time,<EOL>distance_end=trip_pareto_tuple.duration())<EOL>self.trip_durations.append(trip_pareto_tuple.duration())<EOL>self.trip_departure_times.append(trip_pareto_tuple.departure_time)<EOL>self._profile_blocks.append(trip_block)<EOL>previous_departure_time = trip_pareto_tuple.departure_time<EOL><DEDENT>if not self._profile_blocks or self._profile_blocks[-<NUM_LIT:1>].end_time < end_time_dep:<EOL><INDENT>if len(self._profile_blocks) > <NUM_LIT:0>:<EOL><INDENT>dep_previous = self._profile_blocks[-<NUM_LIT:1>].end_time<EOL><DEDENT>else:<EOL><INDENT>dep_previous = start_time_dep<EOL><DEDENT>waiting_time = end_time_dep - dep_previous<EOL>distance_end_trip = arrival_time_target_at_end_time - end_time_dep<EOL>walking_wait_time = min(end_time_dep - dep_previous,<EOL>waiting_time - (self._walk_time_to_target - distance_end_trip))<EOL>walking_wait_time = max(<NUM_LIT:0>, walking_wait_time)<EOL>if walking_wait_time > <NUM_LIT:0>:<EOL><INDENT>walk_block = ProfileBlock(start_time=dep_previous,<EOL>end_time=dep_previous + walking_wait_time,<EOL>distance_start=self._walk_time_to_target,<EOL>distance_end=self._walk_time_to_target<EOL>)<EOL>assert (walk_block.start_time <= walk_block.end_time)<EOL>assert (walk_block.distance_end <= walk_block.distance_start)<EOL>self._profile_blocks.append(walk_block)<EOL><DEDENT>trip_waiting_time = waiting_time - walking_wait_time<EOL>if trip_waiting_time > <NUM_LIT:0>:<EOL><INDENT>try:<EOL><INDENT>trip_block = ProfileBlock(start_time=dep_previous + walking_wait_time,<EOL>end_time=dep_previous + walking_wait_time + trip_waiting_time,<EOL>distance_start=distance_end_trip + trip_waiting_time,<EOL>distance_end=distance_end_trip)<EOL>assert (trip_block.start_time <= trip_block.end_time)<EOL>assert (trip_block.distance_end <= trip_block.distance_start)<EOL>self._profile_blocks.append(trip_block)<EOL><DEDENT>except AssertionError as e:<EOL><INDENT>assert(trip_waiting_time < <NUM_LIT:10>**-<NUM_LIT:5>)<EOL><DEDENT><DEDENT><DEDENT>self.profile_block_analyzer = ProfileBlockAnalyzer(profile_blocks=self._profile_blocks)<EOL>

Initialize the data structures required by

Parameters
----------
node_profile: NodeProfileSimple


from matplotlib import pyplot as plt<EOL>plt.rc('<STR_LIT:text>', usetex=True)<EOL>if ax is None:<EOL><INDENT>fig = plt.figure()<EOL>ax = fig.add_subplot(<NUM_LIT>)<EOL><DEDENT>temporal_distance_split_points_ordered, densities, delta_peaks = self._temporal_distance_pdf()<EOL>xs = []<EOL>for i, x in enumerate(temporal_distance_split_points_ordered):<EOL><INDENT>xs.append(x)<EOL>xs.append(x)<EOL><DEDENT>xs = numpy.array(xs)<EOL>ys = [<NUM_LIT:0>]<EOL>for y in densities:<EOL><INDENT>ys.append(y)<EOL>ys.append(y)<EOL><DEDENT>ys.append(<NUM_LIT:0>)<EOL>ys = numpy.array(ys)<EOL>xlabel = "<STR_LIT>"<EOL>ylabel = "<STR_LIT>"<EOL>if use_minutes:<EOL><INDENT>xs /= duration_divider<EOL>ys *= duration_divider<EOL>xlabel = "<STR_LIT>"<EOL>delta_peaks = {peak / <NUM_LIT>: mass for peak, mass in delta_peaks.items()}<EOL><DEDENT>if delta_peaks:<EOL><INDENT>peak_height = max(ys) * <NUM_LIT><EOL>max_x = max(xs)<EOL>min_x = min(xs)<EOL>now_max_x = max(xs) + <NUM_LIT> * (max_x - min_x)<EOL>now_min_x = min_x - <NUM_LIT:0.1> * (max_x - min_x)<EOL>text_x_offset = <NUM_LIT:0.1> * (now_max_x - max_x)<EOL>for loc, mass in delta_peaks.items():<EOL><INDENT>text = "<STR_LIT>" + ("<STR_LIT>" % (mass))<EOL>ax.plot([<NUM_LIT:0>, peak_height], [loc, loc], color=color, lw=<NUM_LIT:5>, label=text)<EOL><DEDENT><DEDENT>ax.plot(ys, xs, "<STR_LIT>")<EOL>if delta_peaks:<EOL><INDENT>tot_delta_peak_mass = sum(delta_peaks.values())<EOL>fill_label = "<STR_LIT>" % (<NUM_LIT:1>-tot_delta_peak_mass)<EOL><DEDENT>else:<EOL><INDENT>fill_label = None<EOL><DEDENT>ax.fill_betweenx(xs, ys, color=color, alpha=<NUM_LIT>, label=fill_label)<EOL>ax.set_ylabel(xlabel)<EOL>ax.set_xlabel(ylabel)<EOL>ax.set_xlim(left=<NUM_LIT:0>, right=max(ys) * <NUM_LIT>)<EOL>if delta_peaks:<EOL><INDENT>if legend_font_size is None:<EOL><INDENT>legend_font_size = <NUM_LIT:12><EOL><DEDENT>if legend_loc is None:<EOL><INDENT>legend_loc = "<STR_LIT>"<EOL><DEDENT>ax.legend(loc=legend_loc, prop={'<STR_LIT:size>': legend_font_size})<EOL><DEDENT>if True:<EOL><INDENT>line_tyles = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT:->"][::-<NUM_LIT:1>]<EOL>to_plot_funcs = [self.max_temporal_distance, self.mean_temporal_distance, self.min_temporal_distance]<EOL>xmin, xmax = ax.get_xlim()<EOL>for to_plot_func, ls in zip(to_plot_funcs, line_tyles):<EOL><INDENT>y = to_plot_func() / duration_divider<EOL>assert y < float('<STR_LIT>')<EOL>ax.plot([xmin, xmax*<NUM_LIT:10>], [y, y], color="<STR_LIT>", ls=ls, lw=<NUM_LIT:1>)<EOL><DEDENT><DEDENT>return ax.figure<EOL>

Plot the temporal distance probability density function.

Returns
-------
fig: matplotlib.Figure


def get_prop_analyzer_flat(self, property, value_no_next_journey, value_cutoff):

kwargs = self.kwargs<EOL>fp_blocks = self.get_fastest_path_temporal_distance_blocks()<EOL>prop_blocks = []<EOL>for b in fp_blocks:<EOL><INDENT>if b.is_flat():<EOL><INDENT>if b.distance_end == self.walk_duration and b.distance_end != float('<STR_LIT>'):<EOL><INDENT>prop_value = value_cutoff<EOL><DEDENT>else:<EOL><INDENT>prop_value = value_no_next_journey<EOL><DEDENT><DEDENT>else:<EOL><INDENT>prop_value = b[property]<EOL><DEDENT>prop_block = ProfileBlock(b.start_time, b.end_time, prop_value, prop_value)<EOL>prop_blocks.append(prop_block)<EOL><DEDENT>return ProfileBlockAnalyzer(prop_blocks, **kwargs)<EOL>

Get a journey property analyzer, where each journey is weighted by the number of.

Parameters
----------
property: string
    Name of the property, needs to be one of label_props given on initialization.
value_no_next_journey:
    Value of the profile, when there is no next journey available.
value_cutoff: number
    default value of the property when cutoff is applied

Returns
-------
ProfileBlockAnalyzer


def __init__(self, labels, start_time_dep, end_time_dep, walk_duration=float('<STR_LIT>'), label_props_to_consider=None, **kwargs):

for label in labels:<EOL><INDENT>assert (hasattr(label, "<STR_LIT>"))<EOL>assert (hasattr(label, "<STR_LIT>"))<EOL><DEDENT>self.start_time_dep = start_time_dep<EOL>self.end_time_dep = end_time_dep<EOL>self.walk_duration = walk_duration<EOL>if label_props_to_consider is None:<EOL><INDENT>self.label_props = []<EOL><DEDENT>else:<EOL><INDENT>self.label_props = label_props_to_consider<EOL><DEDENT>self._fastest_path_labels = self._compute_fastest_path_labels(labels)<EOL>for label in self._fastest_path_labels:<EOL><INDENT>for prop in self.label_props:<EOL><INDENT>assert (hasattr(label, prop))<EOL><DEDENT><DEDENT>self.kwargs = kwargs<EOL>

Parameters
----------
labels: list
    List of labels (each label should at least have attributes "departure_time" and "arrival_time")
walk_duration: float
    What is the maximum duration for a journey to be considered.
label_props_to_consider: list


network_nodes = walk_network.nodes(data="<STR_LIT:true>")<EOL>stop_Is = set(gtfs.get_straight_line_transfer_distances()['<STR_LIT>'])<EOL>stops_df = gtfs.stops()<EOL>geo_index = GeoGridIndex(precision=<NUM_LIT:6>)<EOL>for net_node, data in network_nodes:<EOL><INDENT>geo_index.add_point(GeoPoint(data['<STR_LIT>'], data['<STR_LIT>'], ref=net_node))<EOL><DEDENT>stop_I_to_node = {}<EOL>stop_I_to_dist = {}<EOL>for stop_I in stop_Is:<EOL><INDENT>stop_lat = float(stops_df[stops_df.stop_I == stop_I].lat)<EOL>stop_lon = float(stops_df[stops_df.stop_I == stop_I].lon)<EOL>geo_point = GeoPoint(stop_lat, stop_lon)<EOL>min_dist = float('<STR_LIT>')<EOL>min_dist_node = None<EOL>search_distances_m = [<NUM_LIT>, <NUM_LIT>]<EOL>for search_distance_m in search_distances_m:<EOL><INDENT>for point, distance in geo_index.get_nearest_points(geo_point, search_distance_m, "<STR_LIT>"):<EOL><INDENT>if distance < min_dist:<EOL><INDENT>min_dist = distance * <NUM_LIT:1000><EOL>min_dist_node = point.ref<EOL><DEDENT><DEDENT>if min_dist_node is not None:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if min_dist_node is None:<EOL><INDENT>warn("<STR_LIT>" + str(stops_df[stops_df.stop_I == stop_I]))<EOL><DEDENT>stop_I_to_node[stop_I] = min_dist_node<EOL>stop_I_to_dist[stop_I] = min_dist<EOL><DEDENT>return stop_I_to_node, stop_I_to_dist<EOL>

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 walk_network node


def add_walk_distances_to_db_python(gtfs, osm_path, cutoff_distance_m=<NUM_LIT:1000>):

if isinstance(gtfs, str):<EOL><INDENT>gtfs = GTFS(gtfs)<EOL><DEDENT>assert (isinstance(gtfs, GTFS))<EOL>print("<STR_LIT>")<EOL>walk_network = create_walk_network_from_osm(osm_path)<EOL>print("<STR_LIT>")<EOL>stop_I_to_nearest_osm_node, stop_I_to_nearest_osm_node_distance = match_stops_to_nodes(gtfs, walk_network)<EOL>transfers = gtfs.get_straight_line_transfer_distances()<EOL>from_I_to_to_stop_Is = {stop_I: set() for stop_I in stop_I_to_nearest_osm_node}<EOL>for transfer_tuple in transfers.itertuples():<EOL><INDENT>from_I = transfer_tuple.from_stop_I<EOL>to_I = transfer_tuple.to_stop_I<EOL>from_I_to_to_stop_Is[from_I].add(to_I)<EOL><DEDENT>print("<STR_LIT>")<EOL>for from_I, to_stop_Is in from_I_to_to_stop_Is.items():<EOL><INDENT>from_node = stop_I_to_nearest_osm_node[from_I]<EOL>from_dist = stop_I_to_nearest_osm_node_distance[from_I]<EOL>shortest_paths = networkx.single_source_dijkstra_path_length(walk_network,<EOL>from_node,<EOL>cutoff=cutoff_distance_m - from_dist,<EOL>weight="<STR_LIT>")<EOL>for to_I in to_stop_Is:<EOL><INDENT>to_distance = stop_I_to_nearest_osm_node_distance[to_I]<EOL>to_node = stop_I_to_nearest_osm_node[to_I]<EOL>osm_distance = shortest_paths.get(to_node, float('<STR_LIT>'))<EOL>total_distance = from_dist + osm_distance + to_distance<EOL>from_stop_I_transfers = transfers[transfers['<STR_LIT>'] == from_I]<EOL>straigth_distance = from_stop_I_transfers[from_stop_I_transfers["<STR_LIT>"] == to_I]["<STR_LIT:d>"].values[<NUM_LIT:0>]<EOL>assert (straigth_distance < total_distance + <NUM_LIT:2>)  <EOL>if total_distance <= cutoff_distance_m:<EOL><INDENT>gtfs.conn.execute("<STR_LIT>"<EOL>"<STR_LIT>" + str(int(total_distance)) +<EOL>"<STR_LIT>" + str(from_I) + "<STR_LIT>" + str(to_I))<EOL><DEDENT><DEDENT><DEDENT>gtfs.conn.commit()<EOL>

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 OpenStreetMap file
cutoff_distance_m: number
    maximum allowed distance in meters

Returns
-------
None

See Also
--------
gtfspy.calc_transfers
compute_walk_paths_java


self.gtfs_source_dir = self.__class__.gtfs_source_dir<EOL>self.gtfs = self.__class__.G<EOL>self.extract_output_dir = os.path.join(self.gtfs_source_dir, "<STR_LIT>", "<STR_LIT>")<EOL>if not os.path.exists(self.extract_output_dir):<EOL><INDENT>makedirs(self.extract_output_dir)<EOL><DEDENT>

This method is run once before _each_ test method is executed


cls.gtfs_source_dir = os.path.join(os.path.dirname(__file__), "<STR_LIT>")<EOL>cls.G = GTFS.from_directory_as_inmemory_db(cls.gtfs_source_dir)<EOL>

This method is run once before executing any tests


self.conn = sqlite3.connect('<STR_LIT>')<EOL>self.agencyText ='<STR_LIT>''<STR_LIT>'<EOL>self.stopsText ='<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>'<EOL>self.calendarText ='<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>'<EOL>self.calendarDatesText ='<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>'<EOL>self.tripText ="<STR_LIT>""<STR_LIT>""<STR_LIT>""<STR_LIT>""<STR_LIT>"<EOL>self.routesText ="<STR_LIT>""<STR_LIT>""<STR_LIT>""<STR_LIT>"<EOL>self.shapeText ="<STR_LIT>""<STR_LIT>""<STR_LIT>""<STR_LIT>""<STR_LIT>"<EOL>self.stopTimesText ="<STR_LIT>""<STR_LIT>""<STR_LIT>""<STR_LIT>""<STR_LIT>"<EOL>self.frequenciesText ="<STR_LIT>""<STR_LIT>"<EOL>self.transfersText ="<STR_LIT>""<STR_LIT>""<STR_LIT>""<STR_LIT>""<STR_LIT>"<EOL>self.feedInfoText ="<STR_LIT>""<STR_LIT>"<EOL>self.fdict = {<EOL>'<STR_LIT>':           self.agencyText,<EOL>'<STR_LIT>':            self.stopsText,<EOL>'<STR_LIT>':         self.calendarText,<EOL>'<STR_LIT>':   self.calendarDatesText,<EOL>'<STR_LIT>':            self.tripText,<EOL>'<STR_LIT>':           self.routesText,<EOL>'<STR_LIT>':           self.shapeText,<EOL>'<STR_LIT>':       self.stopTimesText,<EOL>'<STR_LIT>':      self.frequenciesText,<EOL>'<STR_LIT>':        self.transfersText,<EOL>'<STR_LIT>':        self.feedInfoText<EOL>}<EOL>self.orig_row_factory = self.conn.row_factory<EOL>


prev_row_factory = self.setRowConn()<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>" + table_name)<EOL>print("<STR_LIT>")<EOL>cur = self.conn.execute("<STR_LIT>" % table_name)<EOL>names = [d[<NUM_LIT:0>] for d in cur.description]<EOL>for name in names:<EOL><INDENT>print(name + '<STR_LIT:U+002CU+0020>', end="<STR_LIT>")<EOL><DEDENT>print("<STR_LIT>")<EOL>for row in cur:<EOL><INDENT>print(row)<EOL><DEDENT>self.conn.row_factory = prev_row_factory<EOL>

Pretty prints a table with name table_name.

Parameters
----------
table_name : str
    name of the table


pass<EOL>

This method is run once after _each_ test method is executed


self.gtfs_source_dir = self.__class__.gtfs_source_dir<EOL>self.gtfs = self.__class__.G<EOL>


def remove_all_trips_fully_outside_buffer(db_conn, center_lat, center_lon, buffer_km, update_secondary_data=True):

distance_function_str = add_wgs84_distance_function_to_db(db_conn)<EOL>stops_within_buffer_query_sql = "<STR_LIT>" + distance_function_str +"<STR_LIT>".format(lat=float(center_lat), lon=float(center_lon), d_m=int(<NUM_LIT:1000>*buffer_km))<EOL>select_all_trip_Is_where_stop_I_is_within_buffer_sql = "<STR_LIT>" + stops_within_buffer_query_sql + "<STR_LIT:)>"<EOL>trip_Is_to_remove_sql = "<STR_LIT>" + select_all_trip_Is_where_stop_I_is_within_buffer_sql + "<STR_LIT:)>"<EOL>trip_Is_to_remove = pandas.read_sql(trip_Is_to_remove_sql, db_conn)["<STR_LIT>"].values<EOL>trip_Is_to_remove_string = "<STR_LIT:U+002C>".join([str(trip_I) for trip_I in trip_Is_to_remove])<EOL>remove_all_trips_fully_outside_buffer_sql = "<STR_LIT>" + trip_Is_to_remove_string + "<STR_LIT:)>"<EOL>remove_all_stop_times_where_trip_I_fully_outside_buffer_sql = "<STR_LIT>" + trip_Is_to_remove_string  + "<STR_LIT:)>"<EOL>db_conn.execute(remove_all_trips_fully_outside_buffer_sql)<EOL>db_conn.execute(remove_all_stop_times_where_trip_I_fully_outside_buffer_sql)<EOL>delete_stops_not_in_stop_times_and_not_as_parent_stop(db_conn)<EOL>db_conn.execute(DELETE_ROUTES_NOT_PRESENT_IN_TRIPS_SQL)<EOL>db_conn.execute(DELETE_SHAPES_NOT_REFERENCED_IN_TRIPS_SQL)<EOL>db_conn.execute(DELETE_DAYS_ENTRIES_NOT_PRESENT_IN_TRIPS_SQL)<EOL>db_conn.execute(DELETE_DAY_TRIPS2_ENTRIES_NOT_PRESENT_IN_TRIPS_SQL)<EOL>db_conn.execute(DELETE_CALENDAR_ENTRIES_FOR_NON_REFERENCE_SERVICE_IS_SQL)<EOL>db_conn.execute(DELETE_CALENDAR_DATES_ENTRIES_FOR_NON_REFERENCE_SERVICE_IS_SQL)<EOL>db_conn.execute(DELETE_FREQUENCIES_ENTRIES_NOT_PRESENT_IN_TRIPS)<EOL>db_conn.execute(DELETE_AGENCIES_NOT_REFERENCED_IN_ROUTES_SQL)<EOL>if update_secondary_data:<EOL><INDENT>update_secondary_data_copies(db_conn)<EOL><DEDENT>

Not used in the regular filter process for the time being.

Parameters
----------
db_conn: sqlite3.Connection
    connection to the GTFS object
center_lat: float
center_lon: float
buffer_km: float


if self.agency_ids_to_preserve is not None:<EOL><INDENT>logging.info("<STR_LIT>")<EOL>agency_ids_to_preserve = list(self.agency_ids_to_preserve)<EOL>agencies = pandas.read_sql("<STR_LIT>", self.copy_db_conn)<EOL>agencies_to_remove = []<EOL>for idx, row in agencies.iterrows():<EOL><INDENT>if row['<STR_LIT>'] not in agency_ids_to_preserve:<EOL><INDENT>agencies_to_remove.append(row['<STR_LIT>'])<EOL><DEDENT><DEDENT>for agency_id in agencies_to_remove:<EOL><INDENT>self.copy_db_conn.execute('<STR_LIT>', (agency_id,))<EOL><DEDENT>self.copy_db_conn.execute('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>self.copy_db_conn.execute('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>self.copy_db_conn.execute('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>self.copy_db_conn.execute('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>self.copy_db_conn.execute('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>self.copy_db_conn.execute('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>self.copy_db_conn.execute('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>self.copy_db_conn.execute('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>self.copy_db_conn.execute('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>self.copy_db_conn.commit()<EOL>return FILTERED<EOL><DEDENT>else:<EOL><INDENT>return NOT_FILTERED<EOL><DEDENT>

filter by agency ids
:param copy_db_conn:
:param agency_ids_to_preserve:
:return:


<EOL>if (self.start_date is not None) and (self.end_date is not None):<EOL><INDENT>start_date_ut = self.gtfs.get_day_start_ut(self.start_date)<EOL>end_date_ut = self.gtfs.get_day_start_ut(self.end_date)<EOL>if self.copy_db_conn.execute("<STR_LIT>"<EOL>"<STR_LIT>").fetchone() != (<NUM_LIT:0>,):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>logging.info("<STR_LIT>")<EOL>table_to_preserve_map = {<EOL>"<STR_LIT>": "<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>"<STR_LIT>": '<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>"<STR_LIT>": "<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>}<EOL>table_to_remove_map = {key: "<STR_LIT>" + to_preserve + "<STR_LIT>"<EOL>for key, to_preserve in table_to_preserve_map.items() }<EOL>GTFS(self.copy_db_conn).set_current_process_time_zone()<EOL>for table, query_template in table_to_remove_map.items():<EOL><INDENT>param_dict = {"<STR_LIT>": str(start_date_ut),<EOL>"<STR_LIT>": str(end_date_ut)}<EOL>query = "<STR_LIT>" + table + "<STR_LIT:U+0020>" +query_template.format(**param_dict)<EOL>self.copy_db_conn.execute(query)<EOL>self.copy_db_conn.commit()<EOL><DEDENT>return FILTERED<EOL><DEDENT>else:<EOL><INDENT>return NOT_FILTERED<EOL><DEDENT>

Removes rows from the sqlite database copy that are out of the time span defined by start_date and end_date
:param gtfs: GTFS object
:param copy_db_conn: sqlite database connection
:param start_date:
:param end_date:
:return:


if start_date and end_date:<EOL><INDENT>if isinstance(start_date, (datetime.datetime, datetime.date)):<EOL><INDENT>self.start_date = start_date.strftime("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>self.start_date = start_date<EOL><DEDENT>if isinstance(end_date, (datetime.datetime, datetime.date)):<EOL><INDENT>end_date_dt = end_date<EOL>self.end_date = end_date.strftime("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>self.end_date = end_date<EOL>end_date_dt = datetime.datetime.strptime(self.end_date, "<STR_LIT>")<EOL><DEDENT>end_date_to_include = end_date_dt - datetime.timedelta(days=<NUM_LIT:1>)<EOL>self.end_date_to_include_str = end_date_to_include.strftime("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>self.start_date = None<EOL>self.end_date = None<EOL><DEDENT>self.copy_db_conn = None<EOL>self.copy_db_path = copy_db_path<EOL>self.agency_ids_to_preserve = agency_ids_to_preserve<EOL>self.gtfs = G<EOL>self.buffer_lat = buffer_lat<EOL>self.buffer_lon = buffer_lon<EOL>self.buffer_distance_km = buffer_distance_km<EOL>self.update_metadata = update_metadata<EOL>if agency_distance is not None:<EOL><INDENT>raise NotImplementedError<EOL><DEDENT>self.this_db_path = self.gtfs.get_main_database_path()<EOL>assert os.path.exists(self.this_db_path), "<STR_LIT>"<EOL>assert os.path.exists(os.path.dirname(os.path.abspath(copy_db_path))),"<STR_LIT>"<EOL>assert not os.path.exists(copy_db_path), "<STR_LIT>" % copy_db_path<EOL>

Copy a database, and then based on various filters.
Only method `create_filtered_copy` is provided as we do not want to take the risk of
losing the data stored in the original database.

G: gtfspy.gtfs.GTFS
    the original database
copy_db_path : str
    path to another database database
update_metadata : boolean, optional
    whether to update metadata of the feed, defaulting to true
    (this option is mainly available for testing purposes)
start_date : str, or datetime.datetime
    filter out all data taking place before end_date (the start_time_ut of the end date)
    Date format "YYYY-MM-DD"
    (end_date_ut is not included after filtering)
end_date : str, or datetime.datetime
    Filter out all data taking place after end_date
    The end_date is not included after filtering.
agency_ids_to_preserve : iterable
    List of agency_ids to retain (str) (e.g. 'HSL' for Helsinki)
    Only routes by the listed agencies are then considered
agency_distance : float
    Only evaluated in combination with agency filter.
    Distance (in km) to the other near-by stops that should be included in addition to
    the ones defined by the agencies.
    All vehicle trips going through at least two such stops would then be included in the
    export. Note that this should not be a recursive thing.
    Or should it be? :)
buffer_lat : float
    Latitude of the buffer zone center
buffer_lon : float
    Longitude of the buffer zone center
buffer_distance : float
    Distance from the buffer zone center (in kilometers)

Returns
-------
None


query = (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return(gtfs.execute_custom_query_pandas(query))<EOL>

Get the frequency of trip_I in a particular day


def hourly_frequencies(gtfs, st, et, route_type):

timeframe = et-st<EOL>hours = timeframe/ <NUM_LIT><EOL>day = gtfs.get_suitable_date_for_daily_extract()<EOL>stops = gtfs.get_stops_for_route_type(route_type).T.drop_duplicates().T<EOL>query = ("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(h=hours, st=st, et=et, day=day))<EOL>try:<EOL><INDENT>trips_frequency = gtfs.execute_custom_query_pandas(query).T.drop_duplicates().T<EOL>df = pd.merge(stops[['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']], trips_frequency[['<STR_LIT>', '<STR_LIT>']],<EOL>on='<STR_LIT>', how='<STR_LIT>')<EOL>return df.apply(pd.to_numeric)<EOL><DEDENT>except:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Return all the number of vehicles (i.e. busses,trams,etc) that pass hourly through a stop in a time frame.

Parameters
----------
gtfs: GTFS
st : int
    start time of the time framein unix time
et : int
    end time of the time frame in unix time
route_type: int

Returns
-------
numeric pandas.DataFrame with columns
    stop_I, lat, lon, frequency


stats = get_stats(gtfs)<EOL>gtfs.update_stats(stats)<EOL>

Computes stats AND stores them into the underlying gtfs object (i.e. database).

Parameters
----------
gtfs: GTFS


stats = get_stats(gtfs)<EOL>lon_min = stats['<STR_LIT>']<EOL>lon_max = stats['<STR_LIT>']<EOL>lat_min = stats['<STR_LIT>']<EOL>lat_max = stats['<STR_LIT>']<EOL>if as_dict:<EOL><INDENT>return {'<STR_LIT>': lon_min, '<STR_LIT>': lon_max, '<STR_LIT>': lat_min, '<STR_LIT>': lat_max}<EOL><DEDENT>else:<EOL><INDENT>return lon_min, lon_max, lat_min, lat_max<EOL><DEDENT>

Parameters
----------
gtfs

Returns
-------
min_lon: float
max_lon: float
min_lat: float
max_lat: float


conn = gtfs.conn<EOL>conn.create_function("<STR_LIT>", <NUM_LIT:4>, wgs84_distance)<EOL>cur = conn.cursor()<EOL>query = '<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>'<EOL>q_result = pd.read_sql_query(query, conn)<EOL>q_result['<STR_LIT>'] = <NUM_LIT> * q_result['<STR_LIT>'] / q_result['<STR_LIT>']<EOL>q_result['<STR_LIT>'] = q_result['<STR_LIT>'] / <NUM_LIT:1000><EOL>q_result['<STR_LIT>'] = q_result['<STR_LIT>'] / <NUM_LIT><EOL>q_result = q_result.loc[q_result['<STR_LIT>'] != float("<STR_LIT>")]<EOL>if results_by_mode:<EOL><INDENT>q_results = {}<EOL>for type in q_result['<STR_LIT:type>'].unique().tolist():<EOL><INDENT>q_results[type] = q_result.loc[q_result['<STR_LIT:type>'] == type]<EOL><DEDENT>return q_results<EOL><DEDENT>else:<EOL><INDENT>return q_result<EOL><DEDENT>

Parameters
----------
gtfs: GTFS
results_by_mode: bool

Returns
-------
if results_by_mode is False:
    q_result: pandas.DataFrame
if results_by_mode is True:
    q_results: dict
        a dict with the following keys:
            [ADD HERE]


n_feeds = _n_gtfs_sources(gtfs)[<NUM_LIT:0>]<EOL>max_start = None<EOL>min_end = None<EOL>if n_feeds > <NUM_LIT:1>:<EOL><INDENT>for i in range(n_feeds):<EOL><INDENT>feed_key = "<STR_LIT>" + str(i) + "<STR_LIT:_>"<EOL>start_key = feed_key + "<STR_LIT>"<EOL>end_key = feed_key + "<STR_LIT>"<EOL>calendar_span = gtfs.conn.cursor().execute(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>', (feed_key + '<STR_LIT:%>',)).fetchone()<EOL>stats[start_key] = calendar_span[<NUM_LIT:0>]<EOL>stats[end_key] = calendar_span[<NUM_LIT:1>]<EOL>if calendar_span[<NUM_LIT:0>] is not None and calendar_span[<NUM_LIT:1>] is not None:<EOL><INDENT>if not max_start and not min_end:<EOL><INDENT>max_start = calendar_span[<NUM_LIT:0>]<EOL>min_end = calendar_span[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>if gtfs.get_day_start_ut(calendar_span[<NUM_LIT:0>]) > gtfs.get_day_start_ut(max_start):<EOL><INDENT>max_start = calendar_span[<NUM_LIT:0>]<EOL><DEDENT>if gtfs.get_day_start_ut(calendar_span[<NUM_LIT:1>]) < gtfs.get_day_start_ut(min_end):<EOL><INDENT>min_end = calendar_span[<NUM_LIT:1>]<EOL><DEDENT><DEDENT><DEDENT><DEDENT>stats["<STR_LIT>"] = max_start<EOL>stats["<STR_LIT>"] = min_end<EOL><DEDENT>else:<EOL><INDENT>stats["<STR_LIT>"] = stats["<STR_LIT>"]<EOL>stats["<STR_LIT>"] = stats["<STR_LIT>"]<EOL><DEDENT>return stats<EOL>

Computes the temporal coverage of each source feed

Parameters
----------
gtfs: gtfspy.GTFS object
stats: dict
    where to append the stats

Returns
-------
stats: dict


if isinstance(fname_or_conn, string_types):<EOL><INDENT>if os.path.isfile(fname_or_conn):<EOL><INDENT>self.conn = sqlite3.connect(fname_or_conn)<EOL>self.fname = fname_or_conn<EOL>self.conn.execute('<STR_LIT>')<EOL>self.conn.execute('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>raise FileNotFoundError("<STR_LIT>" + fname_or_conn + "<STR_LIT>")<EOL><DEDENT><DEDENT>elif isinstance(fname_or_conn, sqlite3.Connection):<EOL><INDENT>self.conn = fname_or_conn<EOL>self._dont_close = True<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError(<EOL>"<STR_LIT>" + str(type(fname_or_conn)) + "<STR_LIT>")<EOL><DEDENT>assert self.conn.execute("<STR_LIT>").fetchone() is not None<EOL>self.meta = GTFSMetadata(self.conn)<EOL>self.conn.create_function("<STR_LIT>", <NUM_LIT:4>, wgs84_distance)<EOL>self._timezone = pytz.timezone(self.get_timezone_name())<EOL>

Open a GTFS object

        Parameters
        ----------
        fname_or_conn: str | sqlite3.Connection
            path to the preprocessed gtfs database or a connection to a gtfs database


query = "<STR_LIT>"<EOL>trip_counts_per_day = pd.read_sql_query(query, self.conn, index_col="<STR_LIT:date>")<EOL>max_day = trip_counts_per_day.index.max()<EOL>min_day = trip_counts_per_day.index.min()<EOL>min_date = datetime.datetime.strptime(min_day, '<STR_LIT>')<EOL>max_date = datetime.datetime.strptime(max_day, '<STR_LIT>')<EOL>num_days = (max_date - min_date).days<EOL>dates = [min_date + datetime.timedelta(days=x) for x in range(num_days + <NUM_LIT:1>)]<EOL>trip_counts = []<EOL>date_strings = []<EOL>for date in dates:<EOL><INDENT>date_string = date.strftime("<STR_LIT>")<EOL>date_strings.append(date_string)<EOL>try:<EOL><INDENT>value = trip_counts_per_day.loc[date_string, '<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>value = <NUM_LIT:0><EOL><DEDENT>trip_counts.append(value)<EOL><DEDENT>for date_string in trip_counts_per_day.index:<EOL><INDENT>assert date_string in date_strings<EOL><DEDENT>data = {"<STR_LIT:date>": dates, "<STR_LIT>": date_strings, "<STR_LIT>": trip_counts}<EOL>return pd.DataFrame(data)<EOL>

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)


def get_transit_events(self, start_time_ut=None, end_time_ut=None, route_type=None):

table_name = self._get_day_trips_table_name()<EOL>event_query = "<STR_LIT>""<STR_LIT>""<STR_LIT>" + table_name + "<STR_LIT:U+0020>""<STR_LIT>""<STR_LIT>""<STR_LIT>"<EOL>where_clauses = []<EOL>if end_time_ut:<EOL><INDENT>where_clauses.append(table_name + "<STR_LIT>".format(end_time_ut=end_time_ut))<EOL>where_clauses.append("<STR_LIT>".format(end_time_ut=end_time_ut))<EOL><DEDENT>if start_time_ut:<EOL><INDENT>where_clauses.append(table_name + "<STR_LIT>".format(start_time_ut=start_time_ut))<EOL>where_clauses.append("<STR_LIT>".format(start_time_ut=start_time_ut))<EOL><DEDENT>if route_type is not None:<EOL><INDENT>assert route_type in ALL_ROUTE_TYPES<EOL>where_clauses.append("<STR_LIT>".format(route_type=route_type))<EOL><DEDENT>if len(where_clauses) > <NUM_LIT:0>:<EOL><INDENT>event_query += "<STR_LIT>"<EOL>for i, where_clause in enumerate(where_clauses):<EOL><INDENT>if i is not <NUM_LIT:0>:<EOL><INDENT>event_query += "<STR_LIT>"<EOL><DEDENT>event_query += where_clause<EOL><DEDENT><DEDENT>event_query += "<STR_LIT>"<EOL>events_result = pd.read_sql_query(event_query, self.conn)<EOL>from_indices = numpy.nonzero(<EOL>(events_result['<STR_LIT>'][:-<NUM_LIT:1>].values == events_result['<STR_LIT>'][<NUM_LIT:1>:].values) *<EOL>(events_result['<STR_LIT>'][:-<NUM_LIT:1>].values < events_result['<STR_LIT>'][<NUM_LIT:1>:].values)<EOL>)[<NUM_LIT:0>]<EOL>to_indices = from_indices + <NUM_LIT:1><EOL>assert (events_result['<STR_LIT>'][from_indices].values == events_result['<STR_LIT>'][to_indices].values).all()<EOL>trip_Is = events_result['<STR_LIT>'][from_indices]<EOL>from_stops = events_result['<STR_LIT>'][from_indices]<EOL>to_stops = events_result['<STR_LIT>'][to_indices]<EOL>shape_ids = events_result['<STR_LIT>'][from_indices]<EOL>dep_times = events_result['<STR_LIT>'][from_indices]<EOL>arr_times = events_result['<STR_LIT>'][to_indices]<EOL>route_types = events_result['<STR_LIT>'][from_indices]<EOL>route_ids = events_result['<STR_LIT>'][from_indices]<EOL>route_Is = events_result['<STR_LIT>'][from_indices]<EOL>durations = arr_times.values - dep_times.values<EOL>assert (durations >= <NUM_LIT:0>).all()<EOL>from_seqs = events_result['<STR_LIT>'][from_indices]<EOL>to_seqs = events_result['<STR_LIT>'][to_indices]<EOL>data_tuples = zip(from_stops, to_stops, dep_times, arr_times,<EOL>shape_ids, route_types, route_ids, trip_Is,<EOL>durations, from_seqs, to_seqs, route_Is)<EOL>columns = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL>df = pd.DataFrame.from_records(data_tuples, columns=columns)<EOL>return df<EOL>

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
----------
start_time_ut : int
    start of the time interval in unix time (seconds)
end_time_ut: int
    end of the time interval in unix time (seconds)
route_type: int
    consider only events for this route_type

Returns
-------
events: pandas.DataFrame
    with the following columns and types
        dep_time_ut: int
        arr_time_ut: int
        from_stop_I: int
        to_stop_I: int
        trip_I : int
        shape_id : int
        route_type : int

See also
--------
get_transit_events_in_time_span : an older version of the same thing


cur = self.conn.cursor()<EOL>results = cur.execute("<STR_LIT>", (route_I,))<EOL>name, rtype = results.fetchone()<EOL>return name, int(rtype)<EOL>

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
    route_type according to the GTFS standard


def _get_possible_day_starts(self, start_ut, end_ut, max_time_overnight=None):

if max_time_overnight is None:<EOL><INDENT>max_time_overnight = <NUM_LIT:7> * <NUM_LIT> * <NUM_LIT><EOL><DEDENT>assert start_ut < end_ut<EOL>start_day_ut = self.day_start_ut(start_ut)<EOL>start_day_ds = start_ut - start_day_ut<EOL>end_day_ut = self.day_start_ut(end_ut)<EOL>if start_day_ds < max_time_overnight:<EOL><INDENT>start_day_ut = self.increment_day_start_ut(start_day_ut, n_days=-<NUM_LIT:1>)<EOL><DEDENT>day_start_times_ut = [start_day_ut]<EOL>while day_start_times_ut[-<NUM_LIT:1>] < end_day_ut:<EOL><INDENT>day_start_times_ut.append(self.increment_day_start_ut(day_start_times_ut[-<NUM_LIT:1>]))<EOL><DEDENT>start_times_ds = []<EOL>end_times_ds = []<EOL>for dsut in day_start_times_ut:<EOL><INDENT>day_start_ut = max(<NUM_LIT:0>, start_ut - dsut)<EOL>start_times_ds.append(day_start_ut)<EOL>day_end_ut = end_ut - dsut<EOL>end_times_ds.append(day_end_ut)<EOL><DEDENT>return day_start_times_ut, start_times_ds, end_times_ds<EOL>

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>
    start time in unix time
end_ut : list<int>
    end time in unix time
max_time_overnight : list<int>
    the maximum length of time that a trip can take place on
    during the next day (i.e. after midnight run times like 25:35)

Returns
-------
day_start_times_ut : list
    list of ints (unix times in seconds) for returning all possible day
    start times
start_times_ds : list
    list of ints (unix times in seconds) stating the valid start time in
    day seconds
end_times_ds : list
    list of ints (unix times in seconds) stating the valid end times in
    day_seconds


def get_stop_count_data(self, start_ut, end_ut):

<EOL>trips_df = self.get_tripIs_active_in_range(start_ut, end_ut)<EOL>stop_counts = Counter()<EOL>for row in trips_df.itertuples():<EOL><INDENT>stops_seq = self.get_trip_stop_time_data(row.trip_I, row.day_start_ut)<EOL>for stop_time_row in stops_seq.itertuples(index=False):<EOL><INDENT>if (stop_time_row.dep_time_ut >= start_ut) and (stop_time_row.dep_time_ut <= end_ut):<EOL><INDENT>stop_counts[stop_time_row.stop_I] += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>all_stop_data = self.stops()<EOL>counts = [stop_counts[stop_I] for stop_I in all_stop_data["<STR_LIT>"].values]<EOL>all_stop_data.loc[:, "<STR_LIT:count>"] = pd.Series(counts, index=all_stop_data.index)<EOL>return all_stop_data<EOL>

Get stop count data.

Parameters
----------
start_ut : int
    start time in unixtime
end_ut : int
    end time in unixtime

Returns
-------
stopData : pandas.DataFrame
    each row in the stopData dataFrame is a dictionary with the following elements
        stop_I, count, lat, lon, name
    with data types
        (int, int, float, float, str)


cur = self.conn.cursor()<EOL>results = cur.execute("<STR_LIT>"<EOL>.format(trip_I=trip_I))<EOL>name, rtype = results.fetchone()<EOL>return u"<STR_LIT:%s>" % str(name), int(rtype)<EOL>

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. 195N
type: int
    route_type according to the GTFS standard


def get_events_by_tripI_and_dsut(self, trip_I, day_start_ut,<EOL>start_ut=None, end_ut=None):

<EOL>assert day_start_ut <= start_ut<EOL>assert day_start_ut <= end_ut<EOL>assert start_ut <= end_ut<EOL>events = []<EOL>if not self.tripI_takes_place_on_dsut(trip_I, day_start_ut):<EOL><INDENT>return events<EOL><DEDENT>query = """<STR_LIT>"""<EOL>params = [day_start_ut, day_start_ut,<EOL>trip_I]<EOL>if start_ut:<EOL><INDENT>query += "<STR_LIT>"<EOL>params += [start_ut, day_start_ut]<EOL><DEDENT>if end_ut:<EOL><INDENT>query += "<STR_LIT>"<EOL>params += [end_ut, day_start_ut]<EOL><DEDENT>query += "<STR_LIT>"<EOL>cur = self.conn.cursor()<EOL>rows = cur.execute(query, params)<EOL>stop_data = list(rows)<EOL>for i in range(len(stop_data) - <NUM_LIT:1>):<EOL><INDENT>event = {<EOL>"<STR_LIT>": stop_data[i][<NUM_LIT:0>],<EOL>"<STR_LIT>": stop_data[i + <NUM_LIT:1>][<NUM_LIT:0>],<EOL>"<STR_LIT>": stop_data[i][<NUM_LIT:2>],<EOL>"<STR_LIT>": stop_data[i + <NUM_LIT:1>][<NUM_LIT:1>]<EOL>}<EOL>events.append(event)<EOL><DEDENT>return events<EOL>

Get trip data as a list of events (i.e. dicts).

Parameters
----------
trip_I : int
    shorthand index of the trip.
day_start_ut : int
    the start time of the day in unix time (seconds)
start_ut : int, optional
    consider only events that start after this time
    If not specified, this filtering is not applied.
end_ut : int, optional
    Consider only events that end before this time
    If not specified, this filtering is not applied.

Returns
-------
events: list of dicts
    each element contains the following data:
        from_stop: int (stop_I)
        to_stop: int (stop_I)
        dep_time_ut: int (in unix time)
        arr_time_ut: int (in unix time)


return self.get_table("<STR_LIT>")<EOL>

Get all stop data as a pandas DataFrame

Returns
-------
df: pandas.DataFrame


return pd.read_sql("<STR_LIT>" + table_name, self.conn)<EOL>

Return a pandas.DataFrame object corresponding to the sql table

Parameters
----------
table_name: str
    name of the table in the database

Returns
-------
df : pandas.DataFrame


def get_route_difference_with_other_db(self, other_gtfs, start_time, end_time, uniqueness_threshold=None,<EOL>uniqueness_ratio=None):

from gtfspy.stats import frequencies_by_generated_route<EOL>this_df = frequencies_by_generated_route(self, start_time, end_time)<EOL>other_df = frequencies_by_generated_route(other_gtfs, start_time, end_time)<EOL>this_routes = {x: set(x.split('<STR_LIT:U+002C>')) for x in this_df["<STR_LIT>"]}<EOL>other_routes = {x: set(x.split('<STR_LIT:U+002C>')) for x in other_df["<STR_LIT>"]}<EOL>this_uniques = list(this_routes.keys())<EOL>other_uniques = list(other_routes.keys())<EOL>print("<STR_LIT>", len(this_uniques))<EOL>print("<STR_LIT>", len(other_uniques))<EOL>for i_key, i in this_routes.items():<EOL><INDENT>for j_key, j in other_routes.items():<EOL><INDENT>union = i | j<EOL>intersection = i & j<EOL>symmetric_difference = i ^ j<EOL>if uniqueness_ratio:<EOL><INDENT>if len(intersection) / len(union) >= uniqueness_ratio:<EOL><INDENT>try:<EOL><INDENT>this_uniques.remove(i_key)<EOL>this_df = this_df[this_df["<STR_LIT>"] != i_key]<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>other_uniques.remove(j_key)<EOL>other_df = other_df[other_df["<STR_LIT>"] != j_key]<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>print("<STR_LIT>", len(this_df))<EOL>print("<STR_LIT>", len(other_df))<EOL>return this_df, other_df<EOL>

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_shape_distance_between_stops(self, trip_I, from_stop_seq, to_stop_seq):

query_template = "<STR_LIT>"<EOL>stop_seqs = [from_stop_seq, to_stop_seq]<EOL>shape_breaks = []<EOL>for seq in stop_seqs:<EOL><INDENT>q = query_template.format(seq=seq, trip_I=trip_I)<EOL>shape_breaks.append(self.conn.execute(q).fetchone())<EOL><DEDENT>query_template = "<STR_LIT>""<STR_LIT>""<STR_LIT>"<EOL>distance_query = query_template.format(trip_I=trip_I, from_stop_seq=from_stop_seq, to_stop_seq=to_stop_seq)<EOL>return self.conn.execute(distance_query).fetchone()[<NUM_LIT:0>]<EOL>

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 'origin' stop
to_stop_seq : int
    the sequence number of the 'destination' stop

Returns
-------
distance : float, None
    If the shape calculation succeeded, return a float, otherwise return None
    (i.e. in the case where the shapes table is empty)


def generate_routable_transit_events(self, start_time_ut=None, end_time_ut=None, route_type=None):

from gtfspy.networks import temporal_network<EOL>df = temporal_network(self, start_time_ut=start_time_ut, end_time_ut=end_time_ut, route_type=route_type)<EOL>df.sort_values("<STR_LIT>", ascending=False, inplace=True)<EOL>for row in df.itertuples():<EOL><INDENT>yield row<EOL><DEDENT>

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 routing algorithm

Parameters
----------
start_time_ut: int
end_time_ut: int
route_type: ?

Yields
------
event: namedtuple
    containing:
        dep_time_ut: int
        arr_time_ut: int
        from_stop_I: int
        to_stop_I: int
        trip_I : int
        route_type : int
        seq: int


return list(pd.read_sql("<STR_LIT>", self.conn)["<STR_LIT:name>"])<EOL>

Return a list of the underlying tables in the database.

Returns
-------
table_names: list[str]


<EOL>from gtfspy.import_gtfs import import_gtfs<EOL>conn = sqlite3.connect("<STR_LIT>")<EOL>import_gtfs(gtfs_directory,<EOL>conn,<EOL>preserve_connection=True,<EOL>print_progress=False)<EOL>return cls(conn)<EOL>

Instantiate a GTFS object by computing

Parameters
----------
gtfs_directory: str
    path to the directory for importing the database


cur = self.conn.cursor()<EOL>stop_values = [(values.lat, values.lon, values.stop_id) for values in stop_updates.itertuples()]<EOL>cur.executemany("""<STR_LIT>""", stop_values)<EOL>self.conn.commit()<EOL>


from .timetable_validator import TimetableValidator<EOL>validator = TimetableValidator(self)<EOL>return validator.validate_and_get_warnings()<EOL>

See Validator.validate for more information.

Returns
-------
warnings_container: validator.TimetableValidationWarningsContainer


def get_trip_stop_time_data(self, trip_I, day_start_ut):

to_select = "<STR_LIT>" + str(day_start_ut) + "<STR_LIT>"<EOL>str_to_run = "<STR_LIT>" + to_select + """<STR_LIT>"""<EOL>str_to_run = str_to_run.format(trip_I=trip_I)<EOL>return pd.read_sql_query(str_to_run, self.conn)<EOL>

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 some time interval should be considered.

Parameters
----------
trip_I : int
    integer index of the trip
day_start_ut : int
    the start time of the day in unix time (seconds)

Returns
-------
df: pandas.DataFrame
    df has the following columns
    'departure_time_ut, lat, lon, seq, shape_break'


if route_type is WALK:<EOL><INDENT>return self.stops()<EOL><DEDENT>else:<EOL><INDENT>return pd.read_sql_query("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", self.conn, params=(route_type,))<EOL><DEDENT>

Parameters
----------
route_type: int

Returns
-------
stops: pandas.DataFrame


return datetime.datetime.fromtimestamp(unixtime, self._timezone)<EOL>

Convert unixtime to localized datetime

Parameters
----------
unixtime : int

Returns
-------
gtfs_datetime: datetime.datetime
    time localized to gtfs_datetime's timezone


def get_weekly_extract_start_date(self, ut=False, weekdays_at_least_of_max=<NUM_LIT>,<EOL>verbose=False, download_date_override=None):

daily_trip_counts = self.get_trip_counts_per_day()<EOL>if isinstance(download_date_override, str):<EOL><INDENT>search_start_date = datetime.datetime.strptime(download_date_override, "<STR_LIT>")<EOL><DEDENT>elif isinstance(download_date_override, datetime.datetime):<EOL><INDENT>search_start_date = download_date_override<EOL><DEDENT>else:<EOL><INDENT>assert download_date_override is None<EOL>download_date_str = self.meta['<STR_LIT>']<EOL>if download_date_str == "<STR_LIT>":<EOL><INDENT>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>" + self.get_weekly_extract_start_date.__name__ +<EOL>"<STR_LIT>")<EOL>search_start_date = daily_trip_counts['<STR_LIT:date>'].min()<EOL><DEDENT>else:<EOL><INDENT>search_start_date = datetime.datetime.strptime(download_date_str, "<STR_LIT>")<EOL><DEDENT><DEDENT>feed_min_date = daily_trip_counts['<STR_LIT:date>'].min()<EOL>feed_max_date = daily_trip_counts['<STR_LIT:date>'].max()<EOL>assert (feed_max_date - feed_min_date >= datetime.timedelta(days=<NUM_LIT:7>)),"<STR_LIT>"<EOL>next_monday_from_search_start_date = search_start_date + timedelta(days=(<NUM_LIT:7> - search_start_date.weekday()))<EOL>if not (feed_min_date <= next_monday_from_search_start_date <= feed_max_date):<EOL><INDENT>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>next_monday_from_search_start_date = feed_min_date + timedelta(days=(<NUM_LIT:7> - feed_min_date.weekday()))<EOL><DEDENT>max_trip_count = daily_trip_counts['<STR_LIT>'].quantile(<NUM_LIT>)<EOL>threshold = weekdays_at_least_of_max * max_trip_count<EOL>threshold_fulfilling_days = daily_trip_counts['<STR_LIT>'] > threshold<EOL>search_start_monday_index = daily_trip_counts[daily_trip_counts['<STR_LIT:date>'] == next_monday_from_search_start_date].index[<NUM_LIT:0>]<EOL>while_loop_monday_index = search_start_monday_index<EOL>while len(daily_trip_counts.index) >= while_loop_monday_index + <NUM_LIT:7>:<EOL><INDENT>if all(threshold_fulfilling_days[while_loop_monday_index:while_loop_monday_index + <NUM_LIT:5>]):<EOL><INDENT>row = daily_trip_counts.iloc[while_loop_monday_index]<EOL>if ut:<EOL><INDENT>return self.get_day_start_ut(row.date_str)<EOL><DEDENT>else:<EOL><INDENT>return row['<STR_LIT:date>']<EOL><DEDENT><DEDENT>while_loop_monday_index += <NUM_LIT:7><EOL><DEDENT>while_loop_monday_index = search_start_monday_index - <NUM_LIT:7><EOL>while while_loop_monday_index >= <NUM_LIT:0>:<EOL><INDENT>if all(threshold_fulfilling_days[while_loop_monday_index:while_loop_monday_index + <NUM_LIT:5>]):<EOL><INDENT>row = daily_trip_counts.iloc[while_loop_monday_index]<EOL>if ut:<EOL><INDENT>return self.get_day_start_ut(row.date_str)<EOL><DEDENT>else:<EOL><INDENT>return row['<STR_LIT:date>']<EOL><DEDENT><DEDENT>while_loop_monday_index -= <NUM_LIT:7><EOL><DEDENT>raise RuntimeError("<STR_LIT>")<EOL>

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.

Parameters
----------
ut: return unixtime?
weekdays_at_least_of_max: float

download_date_override: str, semi-optional
    Download-date in format %Y-%m-%d, weeks close to this.
    Overrides the (possibly) recorded downloaded date in the database

Returns
-------
date: int or str

Raises
------
error: RuntimeError
    If no download date could be found.


cur = self.conn.cursor()<EOL>cur.execute("<STR_LIT>")<EOL>rows = cur.fetchall()<EOL>for row in rows:<EOL><INDENT>if row[<NUM_LIT:1>] == str("<STR_LIT>"):<EOL><INDENT>return row[<NUM_LIT:2>]<EOL><DEDENT><DEDENT>

Should return the path to the database

Returns
-------
path : unicode
    path to the database, empty string for in-memory databases


TZ = self.conn.execute('<STR_LIT>').fetchall()[<NUM_LIT:0>][<NUM_LIT:0>]<EOL>return set_process_timezone(TZ)<EOL>

This function queries a GTFS connection, finds the timezone of this
database, and sets it in the TZ environment variable.  This is a
process-global configuration, by the nature of the C library!

Returns
-------
None

Alters os.environ['TZ']


def increment_day_start_ut(self, day_start_ut, n_days=<NUM_LIT:1>):

old_tz = self.set_current_process_time_zone()<EOL>day0 = time.localtime(day_start_ut + <NUM_LIT>)  <EOL>dayN = time.mktime(day0[:<NUM_LIT:2>] +  <EOL>(day0[<NUM_LIT:2>] + n_days,) +  <EOL>(<NUM_LIT:12>, <NUM_LIT>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, -<NUM_LIT:1>)) - <NUM_LIT>  <EOL>set_process_timezone(old_tz)<EOL>return dayN<EOL>

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 this, run the
            input through day_start_ut first.
        n_days: int
            number of days to increment


first_day_start_ut, last_day_start_ut = self.get_day_start_ut_span()<EOL>return first_day_start_ut, last_day_start_ut + <NUM_LIT> * <NUM_LIT><EOL>

Return conservative estimates of start_time_ut and end_time_uts.
All trips, events etc. should start after start_time_ut_conservative and end before end_time_ut_conservative

Returns
-------
start_time_ut_conservative : int
end_time_ut_conservative : int


return pd.read_sql_query("<STR_LIT>".format(stop_I=stop_I), self.conn)<EOL>

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


loc_dt = self._timezone.localize(unlocalized_datetime)<EOL>unixtime_seconds = calendar.timegm(loc_dt.utctimetuple())<EOL>return unixtime_seconds<EOL>

Convert datetime (in GTFS timezone) to unixtime

Parameters
----------
unlocalized_datetime : datetime.datetime
    (tz coerced to GTFS timezone, should NOT be UTC.)

Returns
-------
output : int (unixtime)


def get_directly_accessible_stops_within_distance(self, stop, distance):

query = """<STR_LIT>""" % (stop, distance)<EOL>return pd.read_sql_query(query, self.conn)<EOL>

Returns stops that are accessible without transfer from the stops that are within a specific walking distance
:param stop: int
:param distance: int
:return:


route_type_to_network = dict()<EOL>for route_type in route_types.ALL_ROUTE_TYPES:<EOL><INDENT>if route_type == route_types.WALK:<EOL><INDENT>net = walk_transfer_stop_to_stop_network(gtfs)<EOL><DEDENT>else:<EOL><INDENT>net = stop_to_stop_network_for_route_type(gtfs, route_type)<EOL><DEDENT>route_type_to_network[route_type] = net<EOL><DEDENT>assert len(route_type_to_network) == len(route_types.ALL_ROUTE_TYPES)<EOL>return route_type_to_network<EOL>

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)


for stop in stops.itertuples():<EOL><INDENT>data = {<EOL>"<STR_LIT>": stop.lat,<EOL>"<STR_LIT>": stop.lon,<EOL>"<STR_LIT:name>": stop.name<EOL>}<EOL>net.add_node(stop.stop_I, data)<EOL><DEDENT>

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


return self._warnings_counter<EOL>

Returns
-------
counter: collections.Counter


def _write_stop_to_stop_network_edges(net, file_name, data=True, fmt=None):

if fmt is None:<EOL><INDENT>fmt = "<STR_LIT>"<EOL><DEDENT>if fmt == "<STR_LIT>":<EOL><INDENT>if data:<EOL><INDENT>networkx.write_edgelist(net, file_name, data=True)<EOL><DEDENT>else:<EOL><INDENT>networkx.write_edgelist(net, file_name)<EOL><DEDENT><DEDENT>elif fmt == "<STR_LIT>":<EOL><INDENT>with open(file_name, '<STR_LIT:w>') as f:<EOL><INDENT>edge_iter = net.edges_iter(data=True)<EOL>_, _, edg_data = next(edge_iter)<EOL>edg_data_keys = list(sorted(edg_data.keys()))<EOL>header = "<STR_LIT:;>".join(["<STR_LIT>", "<STR_LIT>"] + edg_data_keys)<EOL>f.write(header)<EOL>for from_node_I, to_node_I, data in net.edges_iter(data=True):<EOL><INDENT>f.write("<STR_LIT:\n>")<EOL>values = [str(from_node_I), str(to_node_I)]<EOL>data_values = []<EOL>for key in edg_data_keys:<EOL><INDENT>if key == "<STR_LIT>":<EOL><INDENT>route_I_counts_string = str(data[key]).replace("<STR_LIT:U+0020>", "<STR_LIT>")[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL>data_values.append(route_I_counts_string)<EOL><DEDENT>else:<EOL><INDENT>data_values.append(str(data[key]))<EOL><DEDENT><DEDENT>all_values = values + data_values<EOL>f.write("<STR_LIT:;>".join(all_values))<EOL><DEDENT><DEDENT><DEDENT>

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
fmt: str, optional
    If "csv" write out the network in csv format.


transfers = gtfs.get_table("<STR_LIT>")<EOL>transfers.drop([u"<STR_LIT>", u"<STR_LIT>"], <NUM_LIT:1>, inplace=True)<EOL>with util.create_file(output_file_name, tmpdir=True, keepext=True) as tmpfile:<EOL><INDENT>transfers.to_csv(tmpfile, encoding='<STR_LIT:utf-8>', index=False)<EOL><DEDENT>

Parameters
----------
gtfs: gtfspy.GTFS
output_file_name: str


def write_nodes(gtfs, output, fields=None):

nodes = gtfs.get_table("<STR_LIT>")<EOL>if fields is not None:<EOL><INDENT>nodes = nodes[fields]<EOL><DEDENT>with util.create_file(output, tmpdir=True, keepext=True) as tmpfile:<EOL><INDENT>nodes.to_csv(tmpfile, encoding='<STR_LIT:utf-8>', index=False, sep="<STR_LIT:;>")<EOL><DEDENT>

Parameters
----------
gtfs: gtfspy.GTFS
output: str
    Path to the output file
fields: list, optional
    which pieces of information to provide


def write_static_networks(gtfs, output_dir, fmt=None):

if fmt is None:<EOL><INDENT>fmt = "<STR_LIT>"<EOL><DEDENT>single_layer_networks = stop_to_stop_networks_by_type(gtfs)<EOL>util.makedirs(output_dir)<EOL>for route_type, net in single_layer_networks.items():<EOL><INDENT>tag = route_types.ROUTE_TYPE_TO_LOWERCASE_TAG[route_type]<EOL>file_name = os.path.join(output_dir, "<STR_LIT>" + tag + "<STR_LIT:.>" + fmt)<EOL>if len(net.edges()) > <NUM_LIT:0>:<EOL><INDENT>_write_stop_to_stop_network_edges(net, file_name, fmt=fmt)<EOL><DEDENT><DEDENT>

Parameters
----------
gtfs: gtfspy.GTFS
output_dir: (str, unicode)
    a path where to write
fmt: None, optional
    defaulting to "edg" and writing results as ".edg" files
     If "csv" csv files are produced instead


def write_temporal_network(gtfs, output_filename, start_time_ut=None, end_time_ut=None):

util.makedirs(os.path.dirname(os.path.abspath(output_filename)))<EOL>pandas_data_frame = temporal_network(gtfs, start_time_ut=start_time_ut, end_time_ut=end_time_ut)<EOL>pandas_data_frame.to_csv(output_filename, encoding='<STR_LIT:utf-8>', index=False)<EOL>

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)


util.makedirs(extract_output_dir)<EOL>for route_type in route_types.TRANSIT_ROUTE_TYPES:<EOL><INDENT>pandas_data_frame = temporal_network(gtfs, start_time_ut=None, end_time_ut=None, route_type=route_type)<EOL>tag = route_types.ROUTE_TYPE_TO_LOWERCASE_TAG[route_type]<EOL>out_file_name = os.path.join(extract_output_dir, tag + "<STR_LIT>")<EOL>pandas_data_frame.to_csv(out_file_name, encoding='<STR_LIT:utf-8>', index=False)<EOL><DEDENT>

Write temporal networks by route type to disk.

Parameters
----------
gtfs: gtfspy.GTFS
extract_output_dir: str


def _frequency_generated_trips_rows(self, gtfs_soure_path, return_df_freq=False):

df_freq = source_csv_to_pandas(gtfs_soure_path, '<STR_LIT>')<EOL>df_trips = source_csv_to_pandas(gtfs_soure_path, "<STR_LIT>")<EOL>df_freq['<STR_LIT>'] = df_freq.apply(lambda row: len(range(str_time_to_day_seconds(row['<STR_LIT>']),<EOL>str_time_to_day_seconds(row['<STR_LIT>']),<EOL>row['<STR_LIT>'])), axis=<NUM_LIT:1>)<EOL>df_trips_freq = pd.merge(df_freq, df_trips, how='<STR_LIT>', on='<STR_LIT>')<EOL>n_freq_generated_trips = int(df_trips_freq['<STR_LIT>'].fillna(<NUM_LIT:1>).sum(axis=<NUM_LIT:0>))<EOL>if return_df_freq:<EOL><INDENT>return df_trips_freq<EOL><DEDENT>else:<EOL><INDENT>return n_freq_generated_trips<EOL><DEDENT>

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


for query, warning in zip(DANGLER_QUERIES, DANGLER_WARNINGS):<EOL><INDENT>dangler_count = self.gtfs.execute_custom_query(query).fetchone()[<NUM_LIT:0>]<EOL>if dangler_count > <NUM_LIT:0>:<EOL><INDENT>if self.verbose:<EOL><INDENT>print(str(dangler_count) + "<STR_LIT:U+0020>" + warning)<EOL><DEDENT>self.warnings_container.add_warning(warning, self.location, count=dangler_count)<EOL><DEDENT><DEDENT>

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 db_table_name in DB_TABLE_NAME_TO_SOURCE_FILE.keys():<EOL><INDENT>table_name_source_file = DB_TABLE_NAME_TO_SOURCE_FILE[db_table_name]<EOL>row_warning_str = DB_TABLE_NAME_TO_ROWS_MISSING_WARNING[db_table_name]<EOL>database_row_count = self.gtfs.get_row_count(db_table_name)<EOL>source_row_count = <NUM_LIT:0><EOL>for gtfs_source in self.gtfs_sources:<EOL><INDENT>frequencies_in_source = source_csv_to_pandas(gtfs_source, '<STR_LIT>')<EOL>try:<EOL><INDENT>if table_name_source_file == '<STR_LIT>' and not frequencies_in_source.empty:<EOL><INDENT>source_row_count += self._frequency_generated_trips_rows(gtfs_source)<EOL><DEDENT>elif table_name_source_file == '<STR_LIT>' and not frequencies_in_source.empty:<EOL><INDENT>source_row_count += self._compute_number_of_frequency_generated_stop_times(gtfs_source)<EOL><DEDENT>else:<EOL><INDENT>df = source_csv_to_pandas(gtfs_source, table_name_source_file)<EOL>source_row_count += len(df.index)<EOL><DEDENT><DEDENT>except IOError as e:<EOL><INDENT>if hasattr(e, "<STR_LIT:filename>") and db_table_name in e.filename:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise e<EOL><DEDENT><DEDENT><DEDENT>if source_row_count == database_row_count and self.verbose:<EOL><INDENT>print("<STR_LIT>" + table_name_source_file + "<STR_LIT>"<EOL>+ str(database_row_count) + "<STR_LIT:)>")<EOL><DEDENT>else:<EOL><INDENT>difference = database_row_count - source_row_count<EOL>('<STR_LIT>' + str(table_name_source_file) + '<STR_LIT>' + str(source_row_count) +<EOL>'<STR_LIT>' + str(database_row_count) + "<STR_LIT:)>")<EOL>if table_name_source_file == "<STR_LIT>" and difference > <NUM_LIT:0>:<EOL><INDENT>query = "<STR_LIT>"+ str(int(difference)) +"<STR_LIT>"<EOL>number_of_entries_added_by_calendar_dates_loader = self.gtfs.execute_custom_query(query).fetchone()[<EOL><NUM_LIT:0>]<EOL>if number_of_entries_added_by_calendar_dates_loader == difference and self.verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>if self.verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>self.warnings_container.add_warning(row_warning_str, self.location, difference)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.warnings_container.add_warning(row_warning_str, self.location, difference)<EOL><DEDENT><DEDENT><DEDENT>

Imports source .txt files, checks row counts and then compares the rowcounts with the gtfsobject
:return:


G = GTFS(conn)<EOL>cur = conn.execute('<STR_LIT>')<EOL>for date, day_start_ut in cur:<EOL><INDENT>assert day_start_ut == G.get_day_start_ut(date)<EOL><DEDENT>

This validates the day_start_ut of the days table.


def _expand_spatial_bounds_to_fit_axes(bounds, ax_width, ax_height):

b = bounds<EOL>height_meters = util.wgs84_distance(b['<STR_LIT>'], b['<STR_LIT>'], b['<STR_LIT>'], b['<STR_LIT>'])<EOL>width_meters = util.wgs84_distance(b['<STR_LIT>'], b['<STR_LIT>'], b['<STR_LIT>'], b['<STR_LIT>'])<EOL>x_per_y_meters = width_meters / height_meters<EOL>x_per_y_axes = ax_width / ax_height<EOL>if x_per_y_axes > x_per_y_meters:  <EOL><INDENT>width_meters_new = (height_meters * x_per_y_axes)<EOL>d_lon_new = ((b['<STR_LIT>'] - b['<STR_LIT>']) / width_meters) * width_meters_new<EOL>mean_lon = (b['<STR_LIT>'] + b['<STR_LIT>'])/<NUM_LIT><EOL>lon_min = mean_lon - d_lon_new / <NUM_LIT><EOL>lon_max = mean_lon + d_lon_new / <NUM_LIT><EOL>spatial_bounds = {<EOL>"<STR_LIT>": lon_min,<EOL>"<STR_LIT>": lon_max,<EOL>"<STR_LIT>": b['<STR_LIT>'],<EOL>"<STR_LIT>": b['<STR_LIT>']<EOL>}<EOL><DEDENT>else:<EOL><INDENT>height_meters_new = (width_meters / x_per_y_axes)<EOL>d_lat_new = ((b['<STR_LIT>'] - b['<STR_LIT>']) / height_meters) * height_meters_new<EOL>mean_lat = (b['<STR_LIT>'] + b['<STR_LIT>']) / <NUM_LIT><EOL>lat_min = mean_lat - d_lat_new / <NUM_LIT><EOL>lat_max = mean_lat + d_lat_new / <NUM_LIT><EOL>spatial_bounds = {<EOL>"<STR_LIT>": b['<STR_LIT>'],<EOL>"<STR_LIT>": b['<STR_LIT>'],<EOL>"<STR_LIT>": lat_min,<EOL>"<STR_LIT>": lat_max<EOL>}<EOL><DEDENT>return spatial_bounds<EOL>

Parameters
----------
bounds: dict
ax_width: float
ax_height: float

Returns
-------
spatial_bounds


def plot_route_network_from_gtfs(g, ax=None, spatial_bounds=None, map_alpha=<NUM_LIT>, scalebar=True, legend=True,<EOL>return_smopy_map=False, map_style=None):

assert(isinstance(g, GTFS))<EOL>route_shapes = g.get_all_route_shapes()<EOL>if spatial_bounds is None:<EOL><INDENT>spatial_bounds = get_spatial_bounds(g, as_dict=True)<EOL><DEDENT>if ax is not None:<EOL><INDENT>bbox = ax.get_window_extent().transformed(ax.figure.dpi_scale_trans.inverted())<EOL>width, height = bbox.width, bbox.height<EOL>spatial_bounds = _expand_spatial_bounds_to_fit_axes(spatial_bounds, width, height)<EOL><DEDENT>return plot_as_routes(route_shapes,<EOL>ax=ax,<EOL>spatial_bounds=spatial_bounds,<EOL>map_alpha=map_alpha,<EOL>plot_scalebar=scalebar,<EOL>legend=legend,<EOL>return_smopy_map=return_smopy_map,<EOL>map_style=map_style)<EOL>

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

Returns
-------
ax: matplotlib.axes.Axes


def plot_all_stops(g, ax=None, scalebar=False):

assert(isinstance(g, GTFS))<EOL>lon_min, lon_max, lat_min, lat_max = get_spatial_bounds(g)<EOL>smopy_map = get_smopy_map(lon_min, lon_max, lat_min, lat_max)<EOL>if ax is None:<EOL><INDENT>fig = plt.figure()<EOL>ax = fig.add_subplot(<NUM_LIT>)<EOL><DEDENT>ax = smopy_map.show_mpl(figsize=None, ax=ax, alpha=<NUM_LIT>)<EOL>stops = g.stops()<EOL>lats = numpy.array(stops['<STR_LIT>'])<EOL>lons = numpy.array(stops['<STR_LIT>'])<EOL>xs, ys = smopy_map.to_pixels(lats, lons)<EOL>ax.scatter(xs, ys, color="<STR_LIT>", s=<NUM_LIT:10>)<EOL>ax.set_xlim(min(xs), max(xs))<EOL>ax.set_ylim(max(ys), min(ys))<EOL>return ax<EOL>

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.

Returns
-------
ax: matplotlib.Axes


def plot_as_routes(route_shapes, ax=None, spatial_bounds=None, map_alpha=<NUM_LIT>, plot_scalebar=True, legend=True,<EOL>return_smopy_map=False, line_width_attribute=None, line_width_scale=<NUM_LIT:1.0>, map_style=None):

lon_min = spatial_bounds['<STR_LIT>']<EOL>lon_max = spatial_bounds['<STR_LIT>']<EOL>lat_min = spatial_bounds['<STR_LIT>']<EOL>lat_max = spatial_bounds['<STR_LIT>']<EOL>if ax is None:<EOL><INDENT>fig = plt.figure()<EOL>ax = fig.add_subplot(<NUM_LIT>)<EOL><DEDENT>smopy_map = get_smopy_map(lon_min, lon_max, lat_min, lat_max, map_style=map_style)<EOL>ax = smopy_map.show_mpl(figsize=None, ax=ax, alpha=map_alpha)<EOL>bound_pixel_xs, bound_pixel_ys = smopy_map.to_pixels(numpy.array([lat_min, lat_max]),<EOL>numpy.array([lon_min, lon_max]))<EOL>route_types_to_lines = {}<EOL>for shape in route_shapes:<EOL><INDENT>route_type = ROUTE_TYPE_CONVERSION[shape['<STR_LIT:type>']]<EOL>lats = numpy.array(shape['<STR_LIT>'])<EOL>lons = numpy.array(shape['<STR_LIT>'])<EOL>if line_width_attribute:<EOL><INDENT>line_width = line_width_scale * shape[line_width_attribute]<EOL><DEDENT>else:<EOL><INDENT>line_width = <NUM_LIT:1><EOL><DEDENT>xs, ys = smopy_map.to_pixels(lats, lons)<EOL>line, = ax.plot(xs, ys, linewidth=line_width, color=ROUTE_TYPE_TO_COLOR[route_type], zorder=ROUTE_TYPE_TO_ZORDER[route_type])<EOL>route_types_to_lines[route_type] = line<EOL><DEDENT>if legend:<EOL><INDENT>lines = list(route_types_to_lines.values())<EOL>labels = [ROUTE_TYPE_TO_SHORT_DESCRIPTION[route_type] for route_type in route_types_to_lines.keys()]<EOL>ax.legend(lines, labels, loc="<STR_LIT>")<EOL><DEDENT>if plot_scalebar:<EOL><INDENT>_add_scale_bar(ax, lat_max, lon_min, lon_max, bound_pixel_xs.max() - bound_pixel_xs.min())<EOL><DEDENT>ax.set_xticks([])<EOL>ax.set_yticks([])<EOL>ax.set_xlim(bound_pixel_xs.min(), bound_pixel_xs.max())<EOL>ax.set_ylim(bound_pixel_ys.max(), bound_pixel_ys.min())<EOL>if return_smopy_map:<EOL><INDENT>return ax, smopy_map<EOL><DEDENT>else:<EOL><INDENT>return ax<EOL><DEDENT>

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:

Returns
-------
ax: matplotlib.axes object


Validates/checks a given GTFS feed with respect to a number of different issues.

The set of warnings that are checked for, can be found in the gtfs_validator.ALL_WARNINGS

Returns
-------
warnings: WarningsContainer


try:<EOL><INDENT>next_photo = Photo.objects.filter(<EOL>gallery=self.gallery,<EOL>created__gt=self.created,<EOL>)[<NUM_LIT:0>]<EOL><DEDENT>except IndexError:<EOL><INDENT>next_photo = Photo.objects.filter(gallery=self.gallery)[<NUM_LIT:0>]<EOL><DEDENT>return next_photo<EOL>

Returns next photo from the same gallery (in chronological order).

Wraps around from last photo in the gallery to the first one.


def __get_rev(self, key, version, **kwa):

if '<STR_LIT>' in kwa:<EOL><INDENT>doc = kwa['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>if type(version) is int:<EOL><INDENT>if version == <NUM_LIT:0>:<EOL><INDENT>order = pymongo.ASCENDING<EOL><DEDENT>elif version == -<NUM_LIT:1>:<EOL><INDENT>order = pymongo.DESCENDING<EOL><DEDENT>doc = self._collection.find_one({'<STR_LIT:k>': key}, sort=[['<STR_LIT:d>', order]])<EOL><DEDENT>elif type(version) is datetime:<EOL><INDENT>ver = self.__round_time(version)<EOL>doc = self._collection.find_one({'<STR_LIT:k>': key, '<STR_LIT:d>': ver})<EOL><DEDENT><DEDENT>if doc is None:<EOL><INDENT>raise KeyError('<STR_LIT>'<EOL>.format(key, str(version)))<EOL><DEDENT>coded_val = doc['<STR_LIT:v>']<EOL>return pickle.loads(coded_val)<EOL>

Obtain particular version of the doc at key.


@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def POST(self):<DEDENT>

post = FormsDict()<EOL>if not self.content_type.startswith('<STR_LIT>'):<EOL><INDENT>pairs = _parse_qsl(tonat(self._get_body_string(), '<STR_LIT>'))<EOL>for key, value in pairs:<EOL><INDENT>post[key] = value<EOL><DEDENT>return post<EOL><DEDENT>safe_env = {'<STR_LIT>': '<STR_LIT>'}  <EOL>for key in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>if key in self.environ: safe_env[key] = self.environ[key]<EOL><DEDENT>args = dict(fp=self.body, environ=safe_env, keep_blank_values=True)<EOL>if py31:<EOL><INDENT>args['<STR_LIT>'] = NCTextIOWrapper(args['<STR_LIT>'],<EOL>encoding='<STR_LIT:utf8>',<EOL>newline='<STR_LIT:\n>')<EOL><DEDENT>elif py3k:<EOL><INDENT>args['<STR_LIT>'] = '<STR_LIT:utf8>'<EOL><DEDENT>data = cgi.FieldStorage(**args)<EOL>self['<STR_LIT>'] = data  <EOL>data = data.list or []<EOL>for item in data:<EOL><INDENT>if item.filename:<EOL><INDENT>post[item.name] = FileUpload(item.file, item.name,<EOL>item.filename, item.headers)<EOL><DEDENT>else:<EOL><INDENT>post[item.name] = item.value<EOL><DEDENT><DEDENT>return post<EOL>

The values of :attr:`forms` and :attr:`files` combined into a single
            :class:`FormsDict`. Values are either strings (form values) or
            instances of :class:`cgi.FieldStorage` (file uploads).


root = os.path.abspath(root) + os.sep<EOL>filename = os.path.abspath(os.path.join(root, filename.strip('<STR_LIT>')))<EOL>headers = dict()<EOL>if not filename.startswith(root):<EOL><INDENT>return HTTPError(<NUM_LIT>, "<STR_LIT>")<EOL><DEDENT>if not os.path.exists(filename) or not os.path.isfile(filename):<EOL><INDENT>return HTTPError(<NUM_LIT>, "<STR_LIT>")<EOL><DEDENT>if not os.access(filename, os.R_OK):<EOL><INDENT>return HTTPError(<NUM_LIT>, "<STR_LIT>")<EOL><DEDENT>if mimetype == '<STR_LIT>':<EOL><INDENT>if download and download != True:<EOL><INDENT>mimetype, encoding = mimetypes.guess_type(download)<EOL><DEDENT>else:<EOL><INDENT>mimetype, encoding = mimetypes.guess_type(filename)<EOL><DEDENT>if encoding: headers['<STR_LIT>'] = encoding<EOL><DEDENT>if mimetype:<EOL><INDENT>if mimetype[:<NUM_LIT:5>] == '<STR_LIT>' and charset and '<STR_LIT>' not in mimetype:<EOL><INDENT>mimetype += '<STR_LIT>' % charset<EOL><DEDENT>headers['<STR_LIT:Content-Type>'] = mimetype<EOL><DEDENT>if download:<EOL><INDENT>download = os.path.basename(filename if download == True else download)<EOL>headers['<STR_LIT>'] = '<STR_LIT>' % download<EOL><DEDENT>stats = os.stat(filename)<EOL>headers['<STR_LIT>'] = clen = stats.st_size<EOL>lm = time.strftime("<STR_LIT>", time.gmtime(stats.st_mtime))<EOL>headers['<STR_LIT>'] = lm<EOL>ims = request.environ.get('<STR_LIT>')<EOL>if ims:<EOL><INDENT>ims = parse_date(ims.split("<STR_LIT:;>")[<NUM_LIT:0>].strip())<EOL><DEDENT>if ims is not None and ims >= int(stats.st_mtime):<EOL><INDENT>headers['<STR_LIT>'] = time.strftime("<STR_LIT>",<EOL>time.gmtime())<EOL>return HTTPResponse(status=<NUM_LIT>, **headers)<EOL><DEDENT>body = '<STR_LIT>' if request.method == '<STR_LIT>' else open(filename, '<STR_LIT:rb>')<EOL>headers["<STR_LIT>"] = "<STR_LIT>"<EOL>ranges = request.environ.get('<STR_LIT>')<EOL>if '<STR_LIT>' in request.environ:<EOL><INDENT>ranges = list(parse_range_header(request.environ['<STR_LIT>'], clen))<EOL>if not ranges:<EOL><INDENT>return HTTPError(<NUM_LIT>, "<STR_LIT>")<EOL><DEDENT>offset, end = ranges[<NUM_LIT:0>]<EOL>headers["<STR_LIT>"] = "<STR_LIT>" % (offset, end - <NUM_LIT:1>, clen)<EOL>headers["<STR_LIT>"] = str(end - offset)<EOL>if body: body = _file_iter_range(body, offset, end - offset)<EOL>return HTTPResponse(body, status=<NUM_LIT>, **headers)<EOL><DEDENT>return HTTPResponse(body, **headers)<EOL>

Open a file in a safe way and return :exc:`HTTPResponse` with status
        code 200, 305, 403 or 404. The ``Content-Type``, ``Content-Encoding``,
        ``Content-Length`` and ``Last-Modified`` headers are set if possible.
        Special support for ``If-Modified-Since``, ``Range`` and ``HEAD``
        requests.

        :param filename: Name or path of the file to send.
        :param root: Root path for file lookups. Should be an absolute directory
            path.
        :param mimetype: Defines the content-type header (default: guess from
            file extension)
        :param download: If True, ask the browser to open a `Save as...` dialog
            instead of opening the file with the associated program. You can
            specify a custom filename as a string. If not specified, the
            original filename is used (default: False).
        :param charset: The charset to use for files with a ``text/*``
            mime-type. (default: UTF-8)


fname = self.raw_filename<EOL>if not isinstance(fname, unicode):<EOL><INDENT>fname = fname.decode('<STR_LIT:utf8>', '<STR_LIT:ignore>')<EOL><DEDENT>fname = normalize('<STR_LIT>', fname)<EOL>fname = fname.encode('<STR_LIT>', '<STR_LIT:ignore>').decode('<STR_LIT>')<EOL>fname = os.path.basename(fname.replace('<STR_LIT:\\>', os.path.sep))<EOL>fname = re.sub(r'<STR_LIT>', '<STR_LIT>', fname).strip()<EOL>fname = re.sub(r'<STR_LIT>', '<STR_LIT:->', fname).strip('<STR_LIT>')<EOL>return fname[:<NUM_LIT:255>] or '<STR_LIT>'<EOL>

Name of the file on the client file system, but normalized to ensure
            file system compatibility. An empty filename is returned as 'empty'.

            Only ASCII letters, digits, dashes, underscores and dots are
            allowed in the final filename. Accents are removed, if possible.
            Whitespace is replaced by a single dash. Leading or tailing dots
            or dashes are removed. The filename is limited to 255 characters.


try:<EOL><INDENT>var = self.environ['<STR_LIT>' % name]<EOL>return var.__get__(self) if hasattr(var, '<STR_LIT>') else var<EOL><DEDENT>except KeyError:<EOL><INDENT>raise AttributeError('<STR_LIT>' % name)<EOL><DEDENT>

Search in self.environ for additional user defined attributes.


return self._status_code<EOL>

The HTTP status code as an integer (e.g. 404).


def get(self, path=None, method='<STR_LIT:GET>', **options):

return self.route(path, method, **options)<EOL>


return self._syntax<EOL>

Tokens as a space separated string (default: <% %> % {{ }})


if '<STR_LIT>' in self.content_type:<EOL><INDENT>return self.content_type.split('<STR_LIT>')[-<NUM_LIT:1>].split('<STR_LIT:;>')[<NUM_LIT:0>].strip()<EOL><DEDENT>return default<EOL>

Return the charset specified in the content-type header (default: utf8).


def get_cookie(self, key, default=None, secret=None):

value = self.cookies.get(key)<EOL>if secret and value:<EOL><INDENT>dec = cookie_decode(value, secret)  <EOL>return dec[<NUM_LIT:1>] if dec and dec[<NUM_LIT:0>] == key else default<EOL><DEDENT>return value or default<EOL>

Return the content of a cookie. To read a `Signed Cookie`, the
            `secret` must match the one used to create the cookie (see
            :meth:`BaseResponse.set_cookie`). If anything goes wrong (missing
            cookie or wrong signature), return a default value.


self.dict[key] = [value]<EOL>

Replace the list of values with a single value.


def __init__(self, fileobj, name, filename, headers=None):

<EOL>self.file = fileobj<EOL>self.name = name<EOL>self.raw_filename = filename<EOL>self.headers = HeaderDict(headers) if headers else HeaderDict()<EOL>


def add(self, rule, method, target, name=None):

anons = <NUM_LIT:0>  <EOL>keys = []  <EOL>pattern = '<STR_LIT>'  <EOL>filters = []  <EOL>builder = []  <EOL>is_static = True<EOL>for key, mode, conf in self._itertokens(rule):<EOL><INDENT>if mode:<EOL><INDENT>is_static = False<EOL>if mode == '<STR_LIT:default>': mode = self.default_filter<EOL>mask, in_filter, out_filter = self.filters[mode](conf)<EOL>if not key:<EOL><INDENT>pattern += '<STR_LIT>' % mask<EOL>key = '<STR_LIT>' % anons<EOL>anons += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>pattern += '<STR_LIT>' % (key, mask)<EOL>keys.append(key)<EOL><DEDENT>if in_filter: filters.append((key, in_filter))<EOL>builder.append((key, out_filter or str))<EOL><DEDENT>elif key:<EOL><INDENT>pattern += re.escape(key)<EOL>builder.append((None, key))<EOL><DEDENT><DEDENT>self.builder[rule] = builder<EOL>if name: self.builder[name] = builder<EOL>if is_static and not self.strict_order:<EOL><INDENT>self.static.setdefault(method, {})<EOL>self.static[method][self.build(rule)] = (target, None)<EOL>return<EOL><DEDENT>try:<EOL><INDENT>re_pattern = re.compile('<STR_LIT>' % pattern)<EOL>re_match = re_pattern.match<EOL><DEDENT>except re.error:<EOL><INDENT>raise RouteSyntaxError("<STR_LIT>" %<EOL>(rule, _e()))<EOL><DEDENT>if filters:<EOL><INDENT>def getargs(path):<EOL><INDENT>url_args = re_match(path).groupdict()<EOL>for name, wildcard_filter in filters:<EOL><INDENT>try:<EOL><INDENT>url_args[name] = wildcard_filter(url_args[name])<EOL><DEDENT>except ValueError:<EOL><INDENT>raise HTTPError(<NUM_LIT>, '<STR_LIT>')<EOL><DEDENT><DEDENT>return url_args<EOL><DEDENT><DEDENT>elif re_pattern.groupindex:<EOL><INDENT>def getargs(path):<EOL><INDENT>return re_match(path).groupdict()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>getargs = None<EOL><DEDENT>flatpat = _re_flatten(pattern)<EOL>whole_rule = (rule, flatpat, target, getargs)<EOL>if (flatpat, method) in self._groups:<EOL><INDENT>if DEBUG:<EOL><INDENT>msg = '<STR_LIT>'<EOL>warnings.warn(msg % (method, rule), RuntimeWarning)<EOL><DEDENT>self.dyna_routes[method][<EOL>self._groups[flatpat, method]] = whole_rule<EOL><DEDENT>else:<EOL><INDENT>self.dyna_routes.setdefault(method, []).append(whole_rule)<EOL>self._groups[flatpat, method] = len(self.dyna_routes[method]) - <NUM_LIT:1><EOL><DEDENT>self._compile(method)<EOL>

Add a new rule or replace the target for an existing rule.


<EOL>if not out:<EOL><INDENT>if '<STR_LIT>' not in response:<EOL><INDENT>response['<STR_LIT>'] = <NUM_LIT:0><EOL><DEDENT>return []<EOL><DEDENT>if isinstance(out, (tuple, list))and isinstance(out[<NUM_LIT:0>], (bytes, unicode)):<EOL><INDENT>out = out[<NUM_LIT:0>][<NUM_LIT:0>:<NUM_LIT:0>].join(out)  <EOL><DEDENT>if isinstance(out, unicode):<EOL><INDENT>out = out.encode(response.charset)<EOL><DEDENT>if isinstance(out, bytes):<EOL><INDENT>if '<STR_LIT>' not in response:<EOL><INDENT>response['<STR_LIT>'] = len(out)<EOL><DEDENT>return [out]<EOL><DEDENT>if isinstance(out, HTTPError):<EOL><INDENT>out.apply(response)<EOL>out = self.error_handler.get(out.status_code,<EOL>self.default_error_handler)(out)<EOL>return self._cast(out)<EOL><DEDENT>if isinstance(out, HTTPResponse):<EOL><INDENT>out.apply(response)<EOL>return self._cast(out.body)<EOL><DEDENT>if hasattr(out, '<STR_LIT>'):<EOL><INDENT>if '<STR_LIT>' in request.environ:<EOL><INDENT>return request.environ['<STR_LIT>'](out)<EOL><DEDENT>elif hasattr(out, '<STR_LIT>') or not hasattr(out, '<STR_LIT>'):<EOL><INDENT>return WSGIFileWrapper(out)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>iout = iter(out)<EOL>first = next(iout)<EOL>while not first:<EOL><INDENT>first = next(iout)<EOL><DEDENT><DEDENT>except StopIteration:<EOL><INDENT>return self._cast('<STR_LIT>')<EOL><DEDENT>except HTTPResponse:<EOL><INDENT>first = _e()<EOL><DEDENT>except (KeyboardInterrupt, SystemExit, MemoryError):<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>if not self.catchall: raise<EOL>first = HTTPError(<NUM_LIT>, '<STR_LIT>', _e(), format_exc())<EOL><DEDENT>if isinstance(first, HTTPResponse):<EOL><INDENT>return self._cast(first)<EOL><DEDENT>elif isinstance(first, bytes):<EOL><INDENT>new_iter = itertools.chain([first], iout)<EOL><DEDENT>elif isinstance(first, unicode):<EOL><INDENT>encoder = lambda x: x.encode(response.charset)<EOL>new_iter = imap(encoder, itertools.chain([first], iout))<EOL><DEDENT>else:<EOL><INDENT>msg = '<STR_LIT>' % type(first)<EOL>return self._cast(HTTPError(<NUM_LIT>, msg))<EOL><DEDENT>if hasattr(out, '<STR_LIT>'):<EOL><INDENT>new_iter = _closeiter(new_iter, out.close)<EOL><DEDENT>return new_iter<EOL>

Try to convert the parameter into something WSGI compatible and set
        correct HTTP headers when possible.
        Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like,
        iterable of strings and iterable of unicodes


if not isinstance(value, Bottle):<EOL><INDENT>value = Bottle()<EOL><DEDENT>self.append(value)<EOL>return value<EOL>

Add a new :class:`Bottle` instance to the stack


return self._make_callback()<EOL>

The route callback with all plugins applied. This property is
            created on demand and then cached to speed up subsequent requests.


def meta_set(self, key, metafield, value):

self._meta.setdefault(key, {})[metafield] = value<EOL>if key in self:<EOL><INDENT>self[key] = self[key]<EOL><DEDENT>

Set the meta field for a key to a new value. This triggers the
            on-change handler for existing keys.


return self._status_line<EOL>

The HTTP status line as a string (e.g. ``404 Not Found``).


copy = FormsDict()<EOL>enc = copy.input_encoding = encoding or self.input_encoding<EOL>copy.recode_unicode = False<EOL>for key, value in self.allitems():<EOL><INDENT>copy.append(self._fix(key, enc), self._fix(value, enc))<EOL><DEDENT>return copy<EOL>

Returns a copy with all keys and values de- or recoded to match
            :attr:`input_encoding`. Some libraries (e.g. WTForms) want a
            unicode dictionary.


def get_header(self, name, default=None):

return self._headers.get(_hkey(name), [default])[-<NUM_LIT:1>]<EOL>

Return the value of a previously defined header. If there is no
            header with that name, return a default value.


return self.environ.get(self._ekey(key), default)<EOL>

Return the header value as is (may be bytes or unicode).


@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def query(self):<DEDENT>

get = self.environ['<STR_LIT>'] = FormsDict()<EOL>pairs = _parse_qsl(self.environ.get('<STR_LIT>', '<STR_LIT>'))<EOL>for key, value in pairs:<EOL><INDENT>get[key] = value<EOL><DEDENT>return get<EOL>

The :attr:`query_string` parsed into a :class:`FormsDict`. These
            values are sometimes called "URL arguments" or "GET parameters", but
            not to be confused with "URL wildcards" as they are provided by the
            :class:`Router`.