def get_route_segment_sub_points(self, routing_table_id, reverse):
     c_list = DBControl().fetch_data("" \
             "SELECT ST_Y(geom) AS lat, ST_X(geom) AS lon " \
             "FROM (" \
                 "SELECT ST_PointN(geom_way, generate_series(1, ST_NPoints(geom_way))) AS geom " \
                 "FROM %s WHERE id = %d) AS points;" \
             % (self.temp_routing_table_name, routing_table_id))
     if reverse:
         c_list = c_list[::-1]
     point_list = []
     last_accepted_bearing = geometry.bearing_between_two_points(
                 c_list[0]['lat'], c_list[0]['lon'], c_list[1]['lat'], c_list[1]['lon'])
     for i in range(1, c_list.__len__()-1):
         new_bearing = geometry.bearing_between_two_points(
                 c_list[i]['lat'], c_list[i]['lon'], c_list[i+1]['lat'], c_list[i+1]['lon'])
         turn = geometry.turn_between_two_segments(
                 new_bearing, last_accepted_bearing)
         if turn > 22 and turn < 338:
             last_accepted_bearing = new_bearing
             point_list.append(self.poi.create_way_point(-1, c_list[i]['lat'], c_list[i]['lon'], {}))
     return point_list
Esempio n. 2
0
 def insert_into_poi_list(self, poi_list, entry, lat, lon):
     if entry == {} or entry.has_key("name") == False \
             or entry.has_key("lat") == False or entry.has_key("lon") == False:
         return poi_list
     entry['distance'] = geometry.distance_between_two_points(
         lat, lon, entry['lat'], entry['lon'])
     entry['bearing'] = geometry.bearing_between_two_points(
         lat, lon, entry['lat'], entry['lon'])
     # add in pois list sorted by distance
     if poi_list.__len__() == 0:
         poi_list.append(entry)
     else:
         inserted = False
         for index in range(0, poi_list.__len__()):
             if entry['distance'] < poi_list[index]['distance']:
                 poi_list.insert(index, entry)
                 inserted = True
                 break
         if inserted == False:
             poi_list.append(entry)
     return poi_list
Esempio n. 3
0
    def create_transport_route_object(self, start_point, legs, dest_point):
        cost = 0
        route = []
        walking_distance = 0

        # add the start point
        start_index = 0
        placeholder_segment = {
            "name": "",
            "type": "footway",
            "sub_type": "",
            "distance": 0,
            "bearing": 0
        }
        if "$Individual" in legs[0].getClass().getName():
            placeholder_segment[
                'distance'] = geometry.distance_between_two_points(
                    start_point['lat'], start_point['lon'],
                    geometry.convert_coordinate_to_float(legs[0].arrival.lat),
                    geometry.convert_coordinate_to_float(legs[0].arrival.lon))
            placeholder_segment[
                'bearing'] = geometry.bearing_between_two_points(
                    start_point['lat'], start_point['lon'],
                    geometry.convert_coordinate_to_float(legs[0].arrival.lat),
                    geometry.convert_coordinate_to_float(legs[0].arrival.lon))
            start_index += 1
        else:
            placeholder_segment[
                'distance'] = geometry.distance_between_two_points(
                    start_point['lat'], start_point['lon'],
                    geometry.convert_coordinate_to_float(
                        legs[0].departure.lat),
                    geometry.convert_coordinate_to_float(
                        legs[0].departure.lon))
            placeholder_segment[
                'bearing'] = geometry.bearing_between_two_points(
                    start_point['lat'], start_point['lon'],
                    geometry.convert_coordinate_to_float(
                        legs[0].departure.lat),
                    geometry.convert_coordinate_to_float(
                        legs[0].departure.lon))
        if placeholder_segment['distance'] > 50:
            walking_distance += placeholder_segment['distance']
            placeholder_segment['name'] = self.translator.translate(
                "transport_creator", "footway_place_holder")
            placeholder_segment['sub_type'] = "footway_place_holder"
            route.append(start_point)
            route.append(placeholder_segment)

        # check, if the last part of the trip is a walking part
        dest_index = legs.__len__()
        if "$Individual" in legs[-1].getClass().getName():
            if dest_index > 0:
                dest_index -= 1

        for index in range(start_index, dest_index):
            leg = legs[index]
            if "$Public" in leg.getClass().getName():
                # create departure and arrival objects
                line = "%s%s" % (leg.line.product.code.encode("utf-8"),
                                 leg.line.label.encode("utf-8"))
                if leg.destination != None:
                    destination_name = leg.destination.name.encode("utf-8")
                else:
                    destination_name = leg.arrival.name.encode("utf-8")
                departure = self.s_finder.get_station(leg.departure, line,
                                                      destination_name)
                if leg.departureStop.plannedDeparturePosition != None:
                    departure[
                        'platform_number'] = leg.departureStop.plannedDeparturePosition.name
                arrival = self.s_finder.get_station(leg.arrival, line,
                                                    destination_name)
                if leg.arrivalStop.plannedArrivalPosition != None:
                    arrival[
                        'platform_number'] = leg.arrivalStop.plannedArrivalPosition.name.encode(
                            "utf-8")
                self.route_logger.append_to_log(
                    "line: %s; From %s to %s" %
                    (line, departure['name'], arrival['name']))

                # create transport segment
                transport_segment = {
                    "type": "transport",
                    "line": line,
                    "direction": destination_name
                }
                # departure and arrival time
                date_format = self.gateway.jvm.java.text.SimpleDateFormat(
                    "HH:mm", self.gateway.jvm.java.util.Locale.GERMAN)
                transport_segment['departure_time'] = date_format.format(
                    leg.getDepartureTime())
                transport_segment[
                    'departure_time_millis'] = leg.getDepartureTime().getTime(
                    )
                transport_segment['arrival_time'] = date_format.format(
                    leg.getArrivalTime())
                transport_segment['arrival_time_millis'] = leg.getArrivalTime(
                ).getTime()
                duration = (leg.getArrivalTime().getTime() -
                            leg.getDepartureTime().getTime()) / 1000
                hours, remainder = divmod(duration, 3600)
                minutes, seconds = divmod(remainder, 60)
                if hours == 0:
                    transport_segment['duration'] = "%d Min" % minutes
                else:
                    transport_segment['duration'] = "%d:%d" % (hours, minutes)
                # intermediate stops
                intermediate_stop_list = leg.intermediateStops
                transport_segment['stops'] = []
                if intermediate_stop_list == None:
                    transport_segment['number_of_stops'] = 0
                else:
                    transport_segment[
                        'number_of_stops'] = intermediate_stop_list.__len__()
                    for stop in intermediate_stop_list:
                        transport_segment['stops'].append(stop.location.name)

                # first leg of trip
                is_first_leg = False
                if route.__len__() == 0:
                    is_first_leg = True
                elif route[-1]['type'] == "footway":
                    is_first_leg = True
                if is_first_leg == True:
                    # the last route segment was either a footway part or the route is still empty
                    # get cost for first departure
                    if departure['transportation_class'] == 1:
                        if departure['accuracy'] == True:
                            cost += self.costs['change_1']
                            self.route_logger.append_to_log(
                                "%s: enter tc1 +acc (+%d)" %
                                (departure['name'], self.costs['change_1']))
                        else:
                            cost += self.costs['change_2']
                            self.route_logger.append_to_log(
                                "%s: enter tc1 -acc (+%d)" %
                                (departure['name'], self.costs['change_2']))
                    else:
                        if departure['accuracy'] == True:
                            cost += self.costs['change_2']
                            self.route_logger.append_to_log(
                                "%s: enter tc2 with entrance (+%d)" %
                                (departure['name'], self.costs['change_2']))
                        else:
                            cost += self.costs['change_3']
                            self.route_logger.append_to_log(
                                "%s: enter tc2 without entrance (+%d)" %
                                (departure['name'], self.costs['change_3']))

                # change for another transportation vehicle
                else:
                    last_transport_segment = route[-2]
                    last_arrival = route[-1]
                    time_for_change = (
                        leg.getDepartureTime().getTime() -
                        last_transport_segment['arrival_time_millis']) / 60000
                    self.route_logger.append_to_log("time for change = %d" %
                                                    time_for_change)
                    placeholder_segment = {
                        "name": "",
                        "type": "footway",
                        "sub_type": "",
                        "distance": 0,
                        "bearing": 0
                    }
                    placeholder_segment[
                        'distance'] = geometry.distance_between_two_points(
                            last_arrival['lat'], last_arrival['lon'],
                            departure['lat'], departure['lon'])
                    walking_distance += placeholder_segment['distance']
                    placeholder_segment[
                        'bearing'] = geometry.bearing_between_two_points(
                            last_arrival['lat'], last_arrival['lon'],
                            departure['lat'], departure['lon'])

                    # tc1-tc1
                    if last_arrival['transportation_class'] == 1 and departure[
                            'transportation_class'] == 1:

                        # tc1-tc1: arrival and departure positions known
                        if last_arrival['accuracy'] == True and departure[
                                'accuracy'] == True:
                            # same platform, user can wait for next vehicle
                            if last_arrival['node_id'] == departure['node_id']:
                                cost += self.costs['change_1']
                                placeholder_segment[
                                    'name'] = self.translator.translate(
                                        "transport_creator", "same_station")
                                placeholder_segment[
                                    'sub_type'] = self.translator.translate(
                                        "highway", "footway")
                                self.route_logger.append_to_log(
                                    "%s - %s: same platform (+%d)" %
                                    (last_arrival['name'], departure['name'],
                                     self.costs['change_1']))
                            elif last_arrival['station_id'] == departure[
                                    'station_id']:
                                # same station but different stop position
                                last_arrival_line = last_arrival['lines'][0][
                                    'nr']
                                is_towards = False
                                for line in departure['lines']:
                                    if line['nr'] == last_arrival_line:
                                        is_towards = True
                                        break
                                if is_towards == True:
                                    placeholder_segment[
                                        'name'] = self.translator.translate(
                                            "transport_creator",
                                            "opposite_station")
                                    placeholder_segment[
                                        'sub_type'] = self.translator.translate(
                                            "highway", "footway")
                                    if time_for_change < self.short_change_interval:
                                        cost += self.costs[
                                            'change_not_enough_time']
                                        self.route_logger.append_to_log(
                                            "%s - %s: tc1_acc-tc1_acc: s_id = s_id oppposite platform (+%d)"
                                            %
                                            (last_arrival['name'],
                                             departure['name'], self.
                                             costs['change_not_enough_time']))
                                    else:
                                        cost += self.costs['change_2']
                                        self.route_logger.append_to_log(
                                            "%s - %s: tc1_acc-tc1_acc: s_id = s_id oppposite platform (+%d)"
                                            % (last_arrival['name'],
                                               departure['name'],
                                               self.costs['change_2']))
                                else:
                                    placeholder_segment[
                                        'name'] = self.translator.translate(
                                            "transport_creator",
                                            "nearby_station")
                                    placeholder_segment[
                                        'sub_type'] = self.translator.translate(
                                            "highway", "footway")
                                    if time_for_change < self.short_change_interval:
                                        cost += self.costs[
                                            'change_not_enough_time']
                                        self.route_logger.append_to_log(
                                            "%s - %s: tc1_acc-tc1_acc: s_id = s_id near by platform (+%d)"
                                            %
                                            (last_arrival['name'],
                                             departure['name'], self.
                                             costs['change_not_enough_time']))
                                    else:
                                        cost += self.costs['change_2']
                                        self.route_logger.append_to_log(
                                            "%s - %s: tc1_acc-tc1_acc: s_id = s_id near by platform (+%d)"
                                            % (last_arrival['name'],
                                               departure['name'],
                                               self.costs['change_2']))
                            else:
                                # other station
                                placeholder_segment[
                                    'name'] = self.translator.translate(
                                        "transport_creator",
                                        "footway_place_holder")
                                placeholder_segment[
                                    'sub_type'] = "footway_place_holder"
                                if time_for_change < self.long_change_interval:
                                    cost += self.costs[
                                        'change_not_enough_time']
                                    self.route_logger.append_to_log(
                                        "%s - %s: tc1_acc-tc1_acc: s_id != s_id different platform (+%d)"
                                        %
                                        (last_arrival['name'],
                                         departure['name'],
                                         self.costs['change_not_enough_time']))
                                else:
                                    cost += self.costs['change_3']
                                    self.route_logger.append_to_log(
                                        "%s - %s: tc1_acc-tc1_acc: s_id != s_id different platform (+%d)"
                                        % (last_arrival['name'],
                                           departure['name'],
                                           self.costs['change_3']))

                        # tc1-tc1: only the destination station of the change is known
                        elif departure['accuracy'] == True:
                            if last_arrival['station_id'] == departure[
                                    'station_id']:
                                placeholder_segment[
                                    'name'] = self.translator.translate(
                                        "transport_creator", "nearby_station")
                                placeholder_segment[
                                    'sub_type'] = self.translator.translate(
                                        "highway", "footway")
                                if time_for_change < self.short_change_interval:
                                    cost += self.costs[
                                        'change_not_enough_time']
                                    self.route_logger.append_to_log(
                                        "%s - %s: tc1_noacc-tc1_acc: s_id = s_id near by platform (+%d)"
                                        %
                                        (last_arrival['name'],
                                         departure['name'],
                                         self.costs['change_not_enough_time']))
                                else:
                                    cost += self.costs['change_2']
                                    self.route_logger.append_to_log(
                                        "%s - %s: tc1_noacc-tc1_acc: s_id = s_id near by platform (+%d)"
                                        % (last_arrival['name'],
                                           departure['name'],
                                           self.costs['change_2']))
                            else:
                                # other station
                                placeholder_segment[
                                    'name'] = self.translator.translate(
                                        "transport_creator",
                                        "footway_place_holder")
                                placeholder_segment[
                                    'sub_type'] = "footway_place_holder"
                                if time_for_change < self.long_change_interval:
                                    cost += self.costs[
                                        'change_not_enough_time']
                                    self.route_logger.append_to_log(
                                        "%s - %s: tc1_noacc-tc1_acc: s_id != s_id different platform (+%d)"
                                        %
                                        (last_arrival['name'],
                                         departure['name'],
                                         self.costs['change_not_enough_time']))
                                else:
                                    cost += self.costs['change_3']
                                    self.route_logger.append_to_log(
                                        "%s - %s: tc1_noacc-tc1_acc: s_id != s_id different platform (+%d)"
                                        % (last_arrival['name'],
                                           departure['name'],
                                           self.costs['change_3']))

                        # tc1-tc1: no exact station positions known
                        else:
                            if last_arrival['station_id'] == departure[
                                    'station_id']:
                                placeholder_segment[
                                    'name'] = self.translator.translate(
                                        "transport_creator",
                                        "nearby_station_no_exact_pos")
                                placeholder_segment[
                                    'sub_type'] = self.translator.translate(
                                        "highway", "footway")
                                if time_for_change < self.short_change_interval:
                                    cost += self.costs[
                                        'change_not_enough_time']
                                    self.route_logger.append_to_log(
                                        "%s - %s: tc1_noacc-tc1_noacc: s_id = s_id near by platform (+%d)"
                                        %
                                        (last_arrival['name'],
                                         departure['name'],
                                         self.costs['change_not_enough_time']))
                                else:
                                    cost += self.costs['change_3']
                                    self.route_logger.append_to_log(
                                        "%s - %s: tc1_noacc-tc1_noacc: s_id = s_id near by platform (+%d)"
                                        % (last_arrival['name'],
                                           departure['name'],
                                           self.costs['change_3']))
                            else:
                                # other station
                                placeholder_segment[
                                    'name'] = self.translator.translate(
                                        "transport_creator",
                                        "footway_place_holder")
                                placeholder_segment[
                                    'sub_type'] = "footway_place_holder"
                                if time_for_change < self.long_change_interval:
                                    cost += self.costs[
                                        'change_not_enough_time']
                                    self.route_logger.append_to_log(
                                        "%s - %s: tc1_noacc-tc1_noacc: s_id != s_id different platform (+%d)"
                                        %
                                        (last_arrival['name'],
                                         departure['name'],
                                         self.costs['change_not_enough_time']))
                                else:
                                    cost += self.costs['change_4']
                                    self.route_logger.append_to_log(
                                        "%s - %s: tc1_noacc-tc1_noacc: s_id != s_id different platform (+%d)"
                                        % (last_arrival['name'],
                                           departure['name'],
                                           self.costs['change_4']))

                    # tc1-tc2
                    elif last_arrival[
                            'transportation_class'] == 1 and departure[
                                'transportation_class'] == 2:
                        # station has entrances
                        placeholder_segment[
                            'name'] = self.translator.translate(
                                "transport_creator", "footway_place_holder")
                        placeholder_segment[
                            'sub_type'] = "footway_place_holder"
                        if departure['accuracy'] == True:
                            if time_for_change < self.short_change_interval:
                                cost += self.costs['change_not_enough_time']
                                self.route_logger.append_to_log(
                                    "%s - %s: tc1-tc2+entr (+%d)" %
                                    (last_arrival['name'], departure['name'],
                                     self.costs['change_not_enough_time']))
                            else:
                                cost += self.costs['change_3']
                                self.route_logger.append_to_log(
                                    "%s - %s: tc1-tc2+entr (+%d)" %
                                    (last_arrival['name'], departure['name'],
                                     self.costs['change_3']))
                        else:
                            if time_for_change < self.long_change_interval:
                                cost += self.costs['change_not_enough_time']
                                self.route_logger.append_to_log(
                                    "%s - %s: tc1-tc2 no_entr (+%d)" %
                                    (last_arrival['name'], departure['name'],
                                     self.costs['change_not_enough_time']))
                            else:
                                cost += self.costs['change_4']
                                self.route_logger.append_to_log(
                                    "%s - %s: tc1-tc2 no_entr (+%d)" %
                                    (last_arrival['name'], departure['name'],
                                     self.costs['change_4']))

                    # tc2-tc1
                    elif last_arrival[
                            'transportation_class'] == 2 and departure[
                                'transportation_class'] == 1:
                        # exact position of station known
                        placeholder_segment[
                            'name'] = self.translator.translate(
                                "transport_creator", "footway_place_holder")
                        placeholder_segment[
                            'sub_type'] = "footway_place_holder"
                        if departure['accuracy'] == True:
                            if time_for_change < self.short_change_interval:
                                cost += self.costs['change_not_enough_time']
                                self.route_logger.append_to_log(
                                    "%s - %s: tc2-tc1+exact (+%d)" %
                                    (last_arrival['name'], departure['name'],
                                     self.costs['change_not_enough_time']))
                            else:
                                cost += self.costs['change_2']
                                self.route_logger.append_to_log(
                                    "%s - %s: tc2-tc1+exact (+%d)" %
                                    (last_arrival['name'], departure['name'],
                                     self.costs['change_2']))
                        else:
                            if time_for_change < self.long_change_interval:
                                cost += self.costs['change_not_enough_time']
                                self.route_logger.append_to_log(
                                    "%s - %s: tc2-tc1 not_exact (+%d)" %
                                    (last_arrival['name'], departure['name'],
                                     self.costs['change_not_enough_time']))
                            else:
                                cost += self.costs['change_4']
                                self.route_logger.append_to_log(
                                    "%s - %s: tc2-tc1 not_exact (+%d)" %
                                    (last_arrival['name'], departure['name'],
                                     self.costs['change_4']))

                    # tc2-tc2
                    elif last_arrival[
                            'transportation_class'] == 2 and departure[
                                'transportation_class'] == 2:
                        if last_arrival['station_id'] == departure[
                                'station_id']:
                            placeholder_segment[
                                'name'] = self.translator.translate(
                                    "transport_creator", "within_station")
                            placeholder_segment[
                                'sub_type'] = self.translator.translate(
                                    "highway", "footway")
                            if time_for_change < self.short_change_interval:
                                cost += self.costs['change_not_enough_time']
                                self.route_logger.append_to_log(
                                    "%s - %s: tc2-tc2: same station id (+%d)" %
                                    (last_arrival['name'], departure['name'],
                                     self.costs['change_not_enough_time']))
                            else:
                                cost += self.costs['change_3']
                                self.route_logger.append_to_log(
                                    "%s - %s: tc2-tc2: same station id (+%d)" %
                                    (last_arrival['name'], departure['name'],
                                     self.costs['change_3']))
                        else:
                            placeholder_segment[
                                'name'] = self.translator.translate(
                                    "transport_creator", "different_station")
                            placeholder_segment[
                                'sub_type'] = self.translator.translate(
                                    "highway", "footway")
                            if time_for_change < self.long_change_interval:
                                cost += self.costs['change_not_enough_time']
                                self.route_logger.append_to_log(
                                    "%s - %s: tc2-tc2: diff station id (+%d)" %
                                    (last_arrival['name'], departure['name'],
                                     self.costs['change_not_enough_time']))
                            else:
                                cost += self.costs['change_4']
                                self.route_logger.append_to_log(
                                    "%s - %s: tc2-tc2: diff station id (+%d)" %
                                    (last_arrival['name'], departure['name'],
                                     self.costs['change_4']))

                    # something went wrong with the transportation class
                    else:
                        print "parsing error"
                        # raise route_parsing_exception("blub")

                    # add segment and arrival
                    route.append(placeholder_segment)

                # add departure, transport_segment and arrival
                route.append(departure)
                route.append(transport_segment)
                route.append(arrival)

        # adding the last footway segment
        placeholder_segment = {
            "name": "",
            "type": "footway",
            "sub_type": "",
            "distance": 0,
            "bearing": 0
        }
        if "$Individual" in legs[-1].getClass().getName():
            placeholder_segment[
                'distance'] = geometry.distance_between_two_points(
                    geometry.convert_coordinate_to_float(
                        legs[-1].departure.lat),
                    geometry.convert_coordinate_to_float(
                        legs[-1].departure.lon), dest_point['lat'],
                    dest_point['lon'])
            placeholder_segment[
                'bearing'] = geometry.bearing_between_two_points(
                    geometry.convert_coordinate_to_float(
                        legs[-1].departure.lat),
                    geometry.convert_coordinate_to_float(
                        legs[-1].departure.lon), dest_point['lat'],
                    dest_point['lon'])
        else:
            placeholder_segment[
                'distance'] = geometry.distance_between_two_points(
                    geometry.convert_coordinate_to_float(legs[-1].arrival.lat),
                    geometry.convert_coordinate_to_float(legs[-1].arrival.lon),
                    dest_point['lat'], dest_point['lon'])
            placeholder_segment[
                'bearing'] = geometry.bearing_between_two_points(
                    geometry.convert_coordinate_to_float(legs[-1].arrival.lat),
                    geometry.convert_coordinate_to_float(legs[-1].arrival.lon),
                    dest_point['lat'], dest_point['lon'])
        if placeholder_segment['distance'] > 50:
            walking_distance += placeholder_segment['distance']
            placeholder_segment['name'] = self.translator.translate(
                "transport_creator", "footway_place_holder")
            placeholder_segment['sub_type'] = "footway_place_holder"
            route.append(placeholder_segment)
            route.append(dest_point)

        # add walking distance to cost value
        cost += (walking_distance / self.costs['walk_dist_meters']) + 1
        self.route_logger.append_to_log(
            "Fußweg insgesamt = %d, %d Punkte" %
            (walking_distance,
             (walking_distance / self.costs['walk_dist_meters']) + 1))

        # time calculation
        departure_time = 0
        arrival_time = 0
        number_of_trips = 0
        transportation_vehicles = []
        for part in route:
            if part['type'] == "transport":
                number_of_trips += 1
                transportation_vehicles.append(part['line'])
                arrival_time = part['arrival_time_millis']
                if departure_time == 0:
                    departure_time = part['departure_time_millis']
        minutes_till_departure = (departure_time -
                                  int(time.time() * 1000)) / 60000
        trip_length = (arrival_time - departure_time) / 60000
        cost += (minutes_till_departure / self.costs['min_departure']) + 1
        cost += (trip_length / self.costs['min_trip_length']) + 1
        self.route_logger.append_to_log(
            "%d Minuten bis Abfahrt, %d Punkte" %
            (minutes_till_departure,
             (minutes_till_departure / self.costs['min_departure']) + 1))
        self.route_logger.append_to_log(
            "%d Minuten Dauer, %d Punkte" %
            (trip_length, (trip_length / self.costs['min_trip_length']) + 1))

        # create and return transport route object
        if cost < 100:
            route_description = self.translator.translate("transport_creator", "transport_route_description") \
                    % (minutes_till_departure, trip_length, (number_of_trips-1),
                    ' '.join(transportation_vehicles), walking_distance)
        else:
            route_description = self.translator.translate("transport_creator", "transport_route_description_no_time") \
                    % (minutes_till_departure, trip_length, (number_of_trips-1),
                    ' '.join(transportation_vehicles), walking_distance)
        return RouteTransportCreator.TransportRouteObject(
            route, cost, route_description, departure_time,
            ','.join(transportation_vehicles))
    def find_footway_route(self, start_point, dest_point):
        print "footway route creator"
        # a few helper variables
        t1 = time.time()
        self.route = []
        last_target_id = -1
        reverse = False
        # check for cancel command
        if Config().has_session_id_to_remove(self.session_id):
            raise RouteFootwayCreator.FootwayRouteCreationError(
                    self.translator.translate("message", "process_canceled"))

        # create temporary routing table
        distance_between_start_and_destination = geometry.distance_between_two_points(
                start_point['lat'], start_point['lon'],
                dest_point['lat'], dest_point['lon'])
        print "radius = %d" % distance_between_start_and_destination
        center_point = geometry.get_center_point(
                start_point['lat'], start_point['lon'],
                dest_point['lat'], dest_point['lon'])
        boundaries = geometry.get_boundary_box(center_point['lat'], center_point['lon'],
                self.minimum_radius + int(distance_between_start_and_destination / 2))
        # create temp table
        DBControl().send_data("" \
                "DROP TABLE IF EXISTS %s;" \
                "CREATE TABLE %s AS SELECT * FROM %s LIMIT 0;" \
                "INSERT INTO %s " \
                    "SELECT * from %s " \
                    "WHERE geom_way && ST_MakeEnvelope(%f, %f, %f, %f);"
                % (self.temp_routing_table_name, self.temp_routing_table_name,
                    self.routing_table_name, self.temp_routing_table_name,
                    self.routing_table_name, boundaries['left'], boundaries['bottom'],
                    boundaries['right'], boundaries['top']))
        # check if temp routing table is empty
        number_of_table_rows = DBControl().fetch_data("SELECT count(*) from %s" \
                % self.temp_routing_table_name)[0]['count']
        if number_of_table_rows == 0:
            DBControl().send_data("DROP TABLE %s;" % self.temp_routing_table_name)
            self.route_logger.append_to_log("Routing table too small", True)
            raise RouteFootwayCreator.FootwayRouteCreationError(
                self.translator.translate("footway_creator", "foot_route_creation_failed"))
        # adapt cost column
        t11 = time.time()
        # weight list
        for index, weight in enumerate(self.way_class_weight_list):
            DBControl().send_data("" \
                    "UPDATE %s SET cost=km*%d where kmh = %d;" \
                    % (self.temp_routing_table_name, weight, (index+1)) )
        # blocked ways
        DBControl().send_data("" \
                "UPDATE %s SET cost=km*(-1) WHERE osm_id = ANY('{%s}');" \
                % (self.temp_routing_table_name, ','.join(str(x) for x in self.blocked_ways)) )
        # add table index and recreate source and target columns
        t12 = time.time()
        DBControl().send_data("" \
                "ALTER TABLE ONLY %s ADD CONSTRAINT pkey_%s PRIMARY KEY (id);" \
                "CREATE INDEX idx_%s_source ON %s USING btree (source);" \
                "CREATE INDEX idx_%s_target ON %s USING btree (target);" \
                "CREATE INDEX idx_%s_osm_source_id ON %s USING btree (osm_source_id);" \
                "CREATE INDEX idx_%s_osm_target_id ON %s USING btree (osm_target_id);" \
                "CREATE INDEX idx_%s_geom_way ON %s USING gist (geom_way);" \
                "ALTER TABLE %s CLUSTER ON idx_%s_geom_way;" \
                "SELECT recreate_vertex_of_routing_table('%s');" \
                "ANALYZE %s;" \
                % (self.temp_routing_table_name, self.temp_routing_table_name,
                    self.temp_routing_table_name, self.temp_routing_table_name,
                    self.temp_routing_table_name, self.temp_routing_table_name,
                    self.temp_routing_table_name, self.temp_routing_table_name,
                    self.temp_routing_table_name, self.temp_routing_table_name,
                    self.temp_routing_table_name, self.temp_routing_table_name,
                    self.temp_routing_table_name, self.temp_routing_table_name,
                    self.temp_routing_table_name, self.temp_routing_table_name))
        t2 = time.time()
        self.route_logger.append_to_log("Temp table creation: %.2f (%.2f / %.2f / %.2f\nnumber of rows = %d" \
                % (t2-t1, t11-t1, t12-t11, t2-t12, number_of_table_rows), True)
        # check for cancel command
        if Config().has_session_id_to_remove(self.session_id):
            DBControl().send_data("DROP TABLE %s;" % self.temp_routing_table_name)
            raise RouteFootwayCreator.FootwayRouteCreationError(
                    self.translator.translate("message", "process_canceled"))

        # get start and destination vertex
        start_vertex_list = self.get_nearest_vertex( start_point['lat'], start_point['lon'])
        if start_vertex_list.__len__() == 0 or Config().has_session_id_to_remove(self.session_id):
            DBControl().send_data("DROP TABLE %s;" % self.temp_routing_table_name)
            if start_vertex_list.__len__() == 0:
                self.route_logger.append_to_log("Found no start vertex", True)
                raise RouteFootwayCreator.FootwayRouteCreationError(
                    self.translator.translate("footway_creator", "foot_route_creation_failed"))
            else:
                raise RouteFootwayCreator.FootwayRouteCreationError(
                        self.translator.translate("message", "process_canceled"))
        dest_vertex_list = self.get_nearest_vertex( dest_point['lat'], dest_point['lon'])
        if dest_vertex_list.__len__() == 0 or Config().has_session_id_to_remove(self.session_id):
            DBControl().send_data("DROP TABLE %s;" % self.temp_routing_table_name)
            if dest_vertex_list.__len__():
                self.route_logger.append_to_log("Found no destination vertex", True)
                raise RouteFootwayCreator.FootwayRouteCreationError(
                    self.translator.translate("footway_creator", "foot_route_creation_failed"))
            else:
                raise RouteFootwayCreator.FootwayRouteCreationError(
                        self.translator.translate("message", "process_canceled"))
        t3 = time.time()
        # check for cancel command
        if Config().has_session_id_to_remove(self.session_id):
            DBControl().send_data("DROP TABLE %s;" % self.temp_routing_table_name)
            raise RouteFootwayCreator.FootwayRouteCreationError(
                    self.translator.translate("message", "process_canceled"))

        # route calculation
        best_route = RouteFootwayCreator.RawRoute([], None, None)
        max_vertex_list_length = start_vertex_list.__len__()
        if max_vertex_list_length < dest_vertex_list.__len__():
            max_vertex_list_length = dest_vertex_list.__len__()
        print "length = %d (%d / %d)" % (max_vertex_list_length, start_vertex_list.__len__(), dest_vertex_list.__len__())
        for x in range(0, max_vertex_list_length):
            for y in range(0, x+1):
                if x < start_vertex_list.__len__() and y < dest_vertex_list.__len__() \
                        and best_route.cost == 1000000:
                    result = DBControl().fetch_data("" \
                            "SELECT seq, id1 AS node, id2 AS edge_id, cost FROM pgr_dijkstra(" \
                                "'select id, source, target, cost from %s', %d, %d, false, false)" \
                            % (self.temp_routing_table_name,
                                start_vertex_list[x].point_id, dest_vertex_list[y].point_id))
                    if any(result):
                        best_route = RouteFootwayCreator.RawRoute(result, start_vertex_list[x], dest_vertex_list[y])
                        self.route_logger.append_to_log(
                                "%d  %d    Cost: %.2f\n    start: %s\n    dest: %s" % (x, y, best_route.cost,
                                    start_vertex_list[x].__str__(), dest_vertex_list[y].__str__()), True)
                if y < start_vertex_list.__len__() and x < dest_vertex_list.__len__() \
                        and x != y and best_route.cost == 1000000:
                    result = DBControl().fetch_data("" \
                            "SELECT seq, id1 AS node, id2 AS edge_id, cost FROM pgr_dijkstra(" \
                                "'select id, source, target, cost from %s', %d, %d, false, false)" \
                            % (self.temp_routing_table_name,
                                start_vertex_list[y].point_id, dest_vertex_list[x].point_id))
                    if any(result):
                        best_route = RouteFootwayCreator.RawRoute(result, start_vertex_list[y], dest_vertex_list[x])
                        self.route_logger.append_to_log(
                                "%d  %d    Cost: %.2f\n    start: %s\n    dest: %s" % (y, x, best_route.cost,
                                    start_vertex_list[y].__str__(), dest_vertex_list[x].__str__()), True)
        if Config().has_session_id_to_remove(self.session_id):
            DBControl().send_data("DROP TABLE %s;" % self.temp_routing_table_name)
            raise RouteFootwayCreator.FootwayRouteCreationError(
                    self.translator.translate("message", "process_canceled"))
        if best_route.cost == 1000000:
            result = DBControl().fetch_data("" \
                    "SELECT seq, id1 AS node, id2 AS edge_id, cost FROM pgr_dijkstra(" \
                        "'select id, source, target, km AS cost from %s WHERE kmh != 7', %d, %d, false, false)" \
                    % (self.temp_routing_table_name,
                        start_vertex_list[0].point_id, dest_vertex_list[0].point_id))
            DBControl().send_data("DROP TABLE %s;" % self.temp_routing_table_name)
            if any(result):
                raise RouteFootwayCreator.FootwayRouteCreationError(
                        self.translator.translate("footway_creator", "foot_route_creation_failed_way_classes_missing"))
            else:
                raise RouteFootwayCreator.FootwayRouteCreationError(
                        self.translator.translate("message", "foot_route_creation_failed_no_existing_way"))
        t4 = time.time()
        self.route_logger.append_to_log("routing algorithm: %.2f" % (t4-t3), True)

        for r in best_route.route:
            if r['edge_id'] == -1:
                continue
            part = DBControl().fetch_data("SELECT * from %s where id=%d" \
                    % (self.temp_routing_table_name, r['edge_id']))[0]
    
            # exception for the first route segment
            # add start point of route first
            if part['source'] == best_route.start_vertex_tuple.point_id:
                print "start point added"
                # check if current point is an intersection
                next_point = self.poi.create_intersection_by_id(part['osm_source_id'])
                if next_point == {}:
                    next_point = self.poi.create_way_point_by_id(part['osm_source_id'])
                self.route.append(next_point)
                last_target_id = part['source']
            elif part['target'] == best_route.start_vertex_tuple.point_id:
                print "target point added"
                # check if current point is an intersection
                next_point = self.poi.create_intersection_by_id(part['osm_target_id'])
                if next_point == {}:
                    next_point = self.poi.create_way_point_by_id(part['osm_target_id'])
                self.route.append(next_point)
                last_target_id = part['target']
    
            # create next point
            if last_target_id == part['source']:
                next_point = self.poi.create_intersection_by_id(part['osm_target_id'])
                if next_point == {}:
                    next_point = self.poi.create_way_point_by_id(part['osm_target_id'])
                reverse = False
                last_target_id = part['target']
            else:
                next_point = self.poi.create_intersection_by_id(part['osm_source_id'])
                if next_point == {}:
                    next_point = self.poi.create_way_point_by_id(part['osm_source_id'])
                reverse = True
                last_target_id = part['source']
            # create next segment
            next_segment = self.poi.create_way_segment_by_id(part['osm_id'], reverse )
            next_segment['way_class'] = part['kmh']
            for point in self.get_route_segment_sub_points(part['id'], reverse) + [next_point]:
                self.add_point_to_route(point, next_segment.copy())
            # check for cancel command
            if Config().has_session_id_to_remove(self.session_id):
                raise RouteFootwayCreator.FootwayRouteCreationError(
                    self.translator.translate("message", "process_canceled"))
        t5 = time.time()
        self.route_logger.append_to_log( json.dumps( self.route, indent=4, encoding="utf-8") )
        self.route_logger.append_to_log("\n-------------\n")

        # if no route was found, just use the direct connection between start and destination
        if self.route.__len__() <= 1:
            segment = {"name":self.translator.translate("footway_creator", "direct_connection"),
                    "type":"footway", "sub_type":"", "way_id":-1}
            segment['bearing'] = geometry.bearing_between_two_points( start_point['lat'], start_point['lon'], dest_point['lat'], dest_point['lon'])
            segment['distance'] = geometry.distance_between_two_points( start_point['lat'], start_point['lon'], dest_point['lat'], dest_point['lon'])
            self.route.append(start_point)
            self.route.append(segment)
            self.route.append(dest_point)
            DBControl().send_data("DROP TABLE %s;" % self.temp_routing_table_name)
            return self.route

        # add start point
        first_segment = None
        distance_start_p0 = geometry.distance_between_two_points(
                start_point['lat'], start_point['lon'],
                self.route[0]['lat'], self.route[0]['lon'])
        bearing_start_p0 = geometry.bearing_between_two_points(
                start_point['lat'], start_point['lon'],
                self.route[0]['lat'], self.route[0]['lon'])
        bearing_p0_p1 = self.route[1]['bearing']
        turn = geometry.turn_between_two_segments(
                bearing_p0_p1, bearing_start_p0)
        print "start: turn = %d, distance = %d" % (turn, distance_start_p0)
        print "start tuple: %s" % best_route.start_vertex_tuple.__str__()
        if distance_start_p0 <= 5:
            print "small dist, replaced start point"
            self.route[0] = start_point
        elif best_route.start_vertex_tuple.way_distance <= 5 \
                or (best_route.start_vertex_tuple.way_class in [1,2] and best_route.start_vertex_tuple.way_distance <= 15):
            if turn >= 158 and turn <= 202:
                print "replaced first intersection with start point"
                self.route[1]['distance'] -= distance_start_p0
                self.route[0] = start_point
            elif self.important_intersection(self.route[0]) == False \
                    and (turn <= 22 or turn >= 338):
                print "deleted first intersection, not important + straight ahead"
                self.route[1]['distance'] += distance_start_p0
                self.route[0] = start_point
            else:
                print "added known first segment"
                first_segment = self.poi.create_way_segment_by_id(
                        best_route.start_vertex_tuple.way_id)
        else:
            print "added placeholder first segment"
            first_segment = {"name":self.translator.translate("footway_creator", "first_segment"),
                    "type":"footway", "sub_type":"", "way_id":-1, "pois":[]}
        # should we add a first segment?
        if first_segment != None:
            print "really added"
            self.route[0]['turn'] = turn
            first_segment['bearing'] = bearing_start_p0
            first_segment['distance'] = distance_start_p0
            self.route.insert(0, first_segment)
            self.route.insert(0, start_point)

        # destination point
        distance_plast_dest = geometry.distance_between_two_points(
                self.route[-1]['lat'], self.route[-1]['lon'],
                dest_point['lat'], dest_point['lon'])
        bearing_plast_dest = geometry.bearing_between_two_points(
                self.route[-1]['lat'], self.route[-1]['lon'],
                dest_point['lat'], dest_point['lon'])
        turn = geometry.turn_between_two_segments(
                bearing_plast_dest, self.route[-2]['bearing'])
        print "destination: turn = %d, distance = %d" % (turn, distance_plast_dest)
        print "dest tuple: %s" % best_route.dest_vertex_tuple.__str__()
        if distance_plast_dest <= 5:
            print "small dist, replaced dest point"
            self.route[-1] = dest_point
        elif best_route.dest_vertex_tuple.way_distance <= 5 \
                or (best_route.dest_vertex_tuple.way_class in [1,2] and best_route.dest_vertex_tuple.way_distance <= 15):
            if turn >= 158 and turn <= 202:
                # delete last route point, if you should turn around
                print "replaced last intersection with destination point, turn around"
                self.route[-2]['distance'] -= distance_plast_dest
                self.route[-1] = dest_point
            elif self.important_intersection(self.route[-1]) == False \
                    and (turn <= 22 or turn >= 338):
                print "deleted last intersection, not important + straight ahead"
                self.route[-2]['distance'] += distance_plast_dest
                self.route[-1] = dest_point
            else:
                print "added known last segment"
                dest_segment = self.poi.create_way_segment_by_id(
                        best_route.dest_vertex_tuple.way_id)
                self.add_point_to_route(dest_point, dest_segment)
        else:
            print "added placeholder last segment"
            dest_segment = {"name":self.translator.translate("footway_creator", "last_segment"),
                    "type":"footway", "sub_type":"", "way_id":-1, "pois":[]}
            self.add_point_to_route(dest_point, dest_segment)
        t6 = time.time()

        # print time overview
        DBControl().send_data("DROP TABLE %s;" % self.temp_routing_table_name)
        self.route_logger.append_to_log(
                "1. temp table: %.2f\n" \
                "2. vertex calculation: %.2f\n" \
                "3. route calculation: %.2f\n" \
                "4. add route points: %.2f\n" \
                "5. add start and destination: %.2f\n" \
                "summary: %.2f" \
                % (t2-t1, t3-t2, t4-t3, t5-t4, t6-t5, t6-t1), True)
        return self.route
 def add_point_to_route(self, next_point, next_segment, add_all_intersections=False):
     # calculate distance and bearing of new segment
     try:
         next_segment['bearing'] = geometry.bearing_between_two_points(
                 self.route[-1]['lat'], self.route[-1]['lon'],
                 next_point['lat'], next_point['lon'])
         next_segment['distance'] = geometry.distance_between_two_points(
                 self.route[-1]['lat'], self.route[-1]['lon'],
                 next_point['lat'], next_point['lon'])
         if next_segment['distance'] == 0 and next_point['type'] == "intersection":
             self.route[-1] = next_point
             return
     except IndexError as e:
         # if the route is still empty, add the next route point and exit
         self.route.append(next_point)
         return
     # try to find and delete unimportant intersections and way points
     try:
         turn = geometry.turn_between_two_segments(
                 next_segment['bearing'], self.route[-2]['bearing'])
         if (add_all_intersections == False \
                     or (add_all_intersections == True and self.route[-1]['type'] != "intersection")) \
                 and (turn <= 22 or turn >= 338) \
                 and self.route[-2]['name'] == next_segment['name'] \
                 and self.route[-2]['sub_type'] == next_segment['sub_type'] \
                 and self.important_intersection(self.route[-1], self.route[-2]) == False:
             # delete an unimportant waypoint or intersection
             del self.route[-2:]
     except IndexError as e:
         pass
     # find and delete zigzag
     try:
         turn = geometry.turn_between_two_segments(
                 next_segment['bearing'], self.route[-4]['bearing'])
         if add_all_intersections == False \
                 and (turn <= 22 or turn >= 338) \
                 and self.route[-2]['distance'] < 4 \
                 and self.important_intersection(self.route[-1], self.route[-2]) == False \
                 and self.important_intersection(self.route[-3], self.route[-4]) == False:
             del self.route[-4:]
     except IndexError as e:
         pass
     # delete double train intersection but leave first of two intersections
     try:
         turn = geometry.turn_between_two_segments(
                 next_segment['bearing'], self.route[-4]['bearing'])
         if add_all_intersections == False \
                 and (turn <= 22 or turn >= 338) \
                 and self.route[-2]['distance'] < 5 \
                 and ( \
                     self.translator.translate("railway", "tram") in self.route[-1]['name'] \
                     or self.translator.translate("railway", "rail") in self.route[-1]['name'] \
                     ) \
                 and ( \
                     self.translator.translate("railway", "tram") in self.route[-3]['name'] \
                     or self.translator.translate("railway", "rail") in self.route[-3]['name'] \
                     ):
             del self.route[-2:]
     except IndexError as e:
         pass
     # calculate the updated distance and bearing to the potentially new prev point
     next_segment['bearing'] = geometry.bearing_between_two_points(
             self.route[-1]['lat'], self.route[-1]['lon'],
             next_point['lat'], next_point['lon'])
     next_segment['distance'] = geometry.distance_between_two_points(
             self.route[-1]['lat'], self.route[-1]['lon'],
             next_point['lat'], next_point['lon'])
     # update turn value
     try:
         if "turn" not in self.route[-1]:
             self.route[-1]['turn'] = geometry.turn_between_two_segments(
                     next_segment['bearing'], self.route[-2]['bearing'])
     except IndexError as e:
         pass
     # append new segment and point
     self.route.append(next_segment)
     self.route.append(next_point)
    def follow_this_way(self, start_point, way_id, bearing, add_all_intersections):
        self.route = []
        way = DBControl().fetch_data("SELECT nodes from ways where id = %d" % way_id)[0]
        # check for cancel command
        if Config().has_session_id_to_remove(self.session_id):
            raise RouteFootwayCreator.FootwayRouteCreationError(
                    self.translator.translate("message", "process_canceled"))
        # find nearest way point
        min_dist = 1000000
        id_index = 0
        i = 0
        for id in way['nodes']:
            wp = DBControl().fetch_data("SELECT  ST_y(geom) as lat, ST_X(geom) as lon from nodes where id = %d" % id)[0]
            dist = geometry.distance_between_two_points(start_point['lat'], start_point['lon'], wp['lat'], wp['lon'])
            if dist < min_dist:
                min_dist = dist
                id_index = i
            i += 1
        if id_index == 0:
            prev = DBControl().fetch_data("SELECT  ST_y(geom) as lat, ST_X(geom) as lon from nodes where id = %d" % way['nodes'][id_index])[0]
            next = DBControl().fetch_data("SELECT  ST_y(geom) as lat, ST_X(geom) as lon from nodes where id = %d" % way['nodes'][id_index+1])[0]
        else:
            prev = DBControl().fetch_data("SELECT  ST_y(geom) as lat, ST_X(geom) as lon from nodes where id = %d" % way['nodes'][id_index-1])[0]
            next = DBControl().fetch_data("SELECT  ST_y(geom) as lat, ST_X(geom) as lon from nodes where id = %d" % way['nodes'][id_index])[0]
        bearing_difference = geometry.bearing_between_two_points(prev['lat'], prev['lon'], next['lat'], next['lon']) - bearing
        if bearing_difference < 0:
            bearing_difference += 360
        if bearing_difference < 90 or bearing_difference >= 270:
            for index in range( id_index, way['nodes'].__len__()):
                next_point = self.poi.create_intersection_by_id(way['nodes'][index])
                if next_point == {}:
                    next_point = self.poi.create_way_point_by_id(way['nodes'][index])
                next_segment = self.poi.create_way_segment_by_id(way_id)
                self.add_point_to_route(next_point, next_segment, add_all_intersections)
            last_node_id = way['nodes'][-1]
        else:
            for index in range( id_index, -1, -1):
                next_point = self.poi.create_intersection_by_id(way['nodes'][index])
                if next_point == {}:
                    next_point = self.poi.create_way_point_by_id(way['nodes'][index])
                next_segment = self.poi.create_way_segment_by_id(way_id, True)
                self.add_point_to_route(next_point, next_segment, add_all_intersections)
            last_node_id = way['nodes'][0]
        # check for cancel command
        if Config().has_session_id_to_remove(self.session_id):
            raise RouteFootwayCreator.FootwayRouteCreationError(
                    self.translator.translate("message", "process_canceled"))

        last_way_properties = self.poi.create_way_segment_by_id(way_id)
        while True:
            found_next_part = False
            result = DBControl().fetch_data("SELECT  w.id, w.nodes \
                    from ways w join way_nodes wn on w.id = wn.way_id \
                    where wn.node_id = %d and wn.way_id != %d"
                    % (last_node_id, last_way_properties['way_id']))
            if result.__len__() == 0:
                break
            for way in result:
                next_way_properties = self.poi.create_way_segment_by_id(way['id'])
                if last_way_properties['name'] != next_way_properties['name']:
                    continue
                if last_node_id == way['nodes'][0]:
                    for index in range(1, way['nodes'].__len__()):
                        next_point = self.poi.create_intersection_by_id(way['nodes'][index])
                        if next_point == {}:
                            next_point = self.poi.create_way_point_by_id(way['nodes'][index])
                        next_segment = self.poi.create_way_segment_by_id(
                                last_way_properties['way_id'])
                        self.add_point_to_route(next_point, next_segment, add_all_intersections)
                    last_node_id = way['nodes'][-1]
                    last_way_properties = next_way_properties
                    found_next_part = True
                    break
                if last_node_id == way['nodes'][-1]:
                    for index in range( way['nodes'].__len__()-2, -1, -1):
                        next_point = self.poi.create_intersection_by_id(way['nodes'][index])
                        if next_point == {}:
                            next_point = self.poi.create_way_point_by_id(way['nodes'][index])
                        next_segment = self.poi.create_way_segment_by_id(
                                last_way_properties['way_id'], True)
                        self.add_point_to_route(next_point, next_segment, add_all_intersections)
                    last_node_id = way['nodes'][0]
                    last_way_properties = next_way_properties
                    found_next_part = True
                    break
            if found_next_part == False:
                break
            # check for cancel command
            if Config().has_session_id_to_remove(self.session_id):
                raise RouteFootwayCreator.FootwayRouteCreationError(
                        self.translator.translate("message", "process_canceled"))
        return self.route
    def create_transport_route_object( self, start_point, legs, dest_point):
        cost = 0
        route = []
        walking_distance = 0

        # add the start point
        start_index = 0
        placeholder_segment = {"name":"", "type":"footway", "sub_type":"", "distance":0, "bearing":0}
        if "$Individual" in legs[0].getClass().getName():
            placeholder_segment['distance'] = geometry.distance_between_two_points( start_point['lat'], start_point['lon'],
                    geometry.convert_coordinate_to_float(legs[0].arrival.lat),
                    geometry.convert_coordinate_to_float(legs[0].arrival.lon) )
            placeholder_segment['bearing'] = geometry.bearing_between_two_points( start_point['lat'], start_point['lon'],
                    geometry.convert_coordinate_to_float(legs[0].arrival.lat),
                    geometry.convert_coordinate_to_float(legs[0].arrival.lon) )
            start_index += 1
        else:
            placeholder_segment['distance'] = geometry.distance_between_two_points( start_point['lat'], start_point['lon'],
                    geometry.convert_coordinate_to_float(legs[0].departure.lat),
                    geometry.convert_coordinate_to_float(legs[0].departure.lon) )
            placeholder_segment['bearing'] = geometry.bearing_between_two_points( start_point['lat'], start_point['lon'],
                    geometry.convert_coordinate_to_float(legs[0].departure.lat),
                    geometry.convert_coordinate_to_float(legs[0].departure.lon) )
        if placeholder_segment['distance'] > 50:
            walking_distance += placeholder_segment['distance']
            placeholder_segment['name'] = self.translator.translate("transport_creator", "footway_place_holder")
            placeholder_segment['sub_type'] = "footway_place_holder"
            route.append(start_point)
            route.append(placeholder_segment)

        # check, if the last part of the trip is a walking part
        dest_index = legs.__len__()
        if "$Individual" in legs[-1].getClass().getName():
            if dest_index > 0:
                dest_index -= 1

        for index in range(start_index, dest_index):
            leg = legs[index]
            if "$Public" in leg.getClass().getName():
                # create departure and arrival objects
                line = "%s%s" % (leg.line.product.code.encode("utf-8"), leg.line.label.encode("utf-8"))
                if leg.destination != None:
                    destination_name = leg.destination.name.encode("utf-8")
                else:
                    destination_name = leg.arrival.name.encode("utf-8")
                departure = self.s_finder.get_station( leg.departure, line, destination_name)
                if leg.departureStop.plannedDeparturePosition != None:
                    departure['platform_number'] = leg.departureStop.plannedDeparturePosition.name
                arrival = self.s_finder.get_station( leg.arrival, line, destination_name)
                if leg.arrivalStop.plannedArrivalPosition != None:
                    arrival['platform_number'] = leg.arrivalStop.plannedArrivalPosition.name.encode("utf-8")
                self.route_logger.append_to_log("line: %s; From %s to %s" % (line, departure['name'], arrival['name']))

                # create transport segment
                transport_segment = { "type":"transport", "line":line, "direction":destination_name }
                # departure and arrival time
                date_format = self.gateway.jvm.java.text.SimpleDateFormat("HH:mm", self.gateway.jvm.java.util.Locale.GERMAN)
                transport_segment['departure_time'] = date_format.format(leg.getDepartureTime())
                transport_segment['departure_time_millis'] = leg.getDepartureTime().getTime()
                transport_segment['arrival_time'] = date_format.format(leg.getArrivalTime())
                transport_segment['arrival_time_millis'] = leg.getArrivalTime().getTime()
                duration = (leg.getArrivalTime().getTime() - leg.getDepartureTime().getTime())/1000
                hours, remainder = divmod(duration, 3600)
                minutes, seconds = divmod(remainder, 60)
                if hours == 0:
                    transport_segment['duration'] = "%d Min" % minutes
                else:
                    transport_segment['duration'] = "%d:%d" % (hours, minutes)
                # intermediate stops
                intermediate_stop_list = leg.intermediateStops
                transport_segment['stops'] = []
                if intermediate_stop_list == None:
                    transport_segment['number_of_stops'] = 0
                else:
                    transport_segment['number_of_stops'] = intermediate_stop_list.__len__()
                    for stop in intermediate_stop_list:
                        transport_segment['stops'].append(stop.location.name)

                # first leg of trip
                is_first_leg = False
                if route.__len__() == 0:
                    is_first_leg = True
                elif route[-1]['type'] == "footway":
                    is_first_leg = True
                if is_first_leg == True:
                    # the last route segment was either a footway part or the route is still empty
                    # get cost for first departure
                    if departure['transportation_class'] == 1:
                        if departure['accuracy'] == True:
                            cost += self.costs['change_1']
                            self.route_logger.append_to_log("%s: enter tc1 +acc (+%d)" % 
                                    (departure['name'], self.costs['change_1']))
                        else:
                            cost += self.costs['change_2']
                            self.route_logger.append_to_log("%s: enter tc1 -acc (+%d)" % 
                                    (departure['name'], self.costs['change_2']))
                    else:
                        if departure['accuracy'] == True:
                            cost += self.costs['change_2']
                            self.route_logger.append_to_log("%s: enter tc2 with entrance (+%d)" % 
                                    (departure['name'], self.costs['change_2']))
                        else:
                            cost += self.costs['change_3']
                            self.route_logger.append_to_log("%s: enter tc2 without entrance (+%d)" % 
                                    (departure['name'], self.costs['change_3']))

                # change for another transportation vehicle
                else:
                    last_transport_segment = route[-2]
                    last_arrival = route[-1]
                    time_for_change = (leg.getDepartureTime().getTime() -
                            last_transport_segment['arrival_time_millis']) / 60000
                    self.route_logger.append_to_log("time for change = %d" % time_for_change)
                    placeholder_segment = {"name":"", "type":"footway", "sub_type":"", "distance":0, "bearing":0}
                    placeholder_segment['distance'] = geometry.distance_between_two_points(
                            last_arrival['lat'], last_arrival['lon'],
                            departure['lat'], departure['lon'])
                    walking_distance += placeholder_segment['distance']
                    placeholder_segment['bearing'] = geometry.bearing_between_two_points(
                            last_arrival['lat'], last_arrival['lon'],
                            departure['lat'], departure['lon'])

                    # tc1-tc1
                    if last_arrival['transportation_class'] == 1 and departure['transportation_class'] == 1:

                        # tc1-tc1: arrival and departure positions known
                        if last_arrival['accuracy'] == True and departure['accuracy'] == True:
                            # same platform, user can wait for next vehicle
                            if last_arrival['node_id'] == departure['node_id']:
                                cost += self.costs['change_1']
                                placeholder_segment['name'] = self.translator.translate("transport_creator", "same_station")
                                placeholder_segment['sub_type'] = self.translator.translate("highway", "footway")
                                self.route_logger.append_to_log("%s - %s: same platform (+%d)" % 
                                        (last_arrival['name'], departure['name'], self.costs['change_1']))
                            elif last_arrival['station_id'] == departure['station_id']:
                                # same station but different stop position
                                last_arrival_line = last_arrival['lines'][0]['nr']
                                is_towards = False
                                for line in departure['lines']:
                                    if line['nr'] == last_arrival_line:
                                        is_towards = True
                                        break
                                if is_towards == True:
                                    placeholder_segment['name'] = self.translator.translate("transport_creator", "opposite_station")
                                    placeholder_segment['sub_type'] = self.translator.translate("highway", "footway")
                                    if time_for_change < self.short_change_interval:
                                        cost += self.costs['change_not_enough_time']
                                        self.route_logger.append_to_log("%s - %s: tc1_acc-tc1_acc: s_id = s_id oppposite platform (+%d)" % 
                                                (last_arrival['name'], departure['name'], self.costs['change_not_enough_time']))
                                    else:
                                        cost += self.costs['change_2']
                                        self.route_logger.append_to_log("%s - %s: tc1_acc-tc1_acc: s_id = s_id oppposite platform (+%d)" % 
                                                (last_arrival['name'], departure['name'], self.costs['change_2']))
                                else:
                                    placeholder_segment['name'] = self.translator.translate("transport_creator", "nearby_station")
                                    placeholder_segment['sub_type'] = self.translator.translate("highway", "footway")
                                    if time_for_change < self.short_change_interval:
                                        cost += self.costs['change_not_enough_time']
                                        self.route_logger.append_to_log("%s - %s: tc1_acc-tc1_acc: s_id = s_id near by platform (+%d)" % 
                                                (last_arrival['name'], departure['name'], self.costs['change_not_enough_time']))
                                    else:
                                        cost += self.costs['change_2']
                                        self.route_logger.append_to_log("%s - %s: tc1_acc-tc1_acc: s_id = s_id near by platform (+%d)" % 
                                                (last_arrival['name'], departure['name'], self.costs['change_2']))
                            else:
                                # other station
                                placeholder_segment['name'] = self.translator.translate("transport_creator", "footway_place_holder")
                                placeholder_segment['sub_type'] = "footway_place_holder"
                                if time_for_change < self.long_change_interval:
                                    cost += self.costs['change_not_enough_time']
                                    self.route_logger.append_to_log("%s - %s: tc1_acc-tc1_acc: s_id != s_id different platform (+%d)" % 
                                            (last_arrival['name'], departure['name'], self.costs['change_not_enough_time']))
                                else:
                                    cost += self.costs['change_3']
                                    self.route_logger.append_to_log("%s - %s: tc1_acc-tc1_acc: s_id != s_id different platform (+%d)" % 
                                            (last_arrival['name'], departure['name'], self.costs['change_3']))

                        # tc1-tc1: only the destination station of the change is known
                        elif departure['accuracy'] == True:
                            if last_arrival['station_id'] == departure['station_id']:
                                placeholder_segment['name'] = self.translator.translate("transport_creator", "nearby_station")
                                placeholder_segment['sub_type'] = self.translator.translate("highway", "footway")
                                if time_for_change < self.short_change_interval:
                                    cost += self.costs['change_not_enough_time']
                                    self.route_logger.append_to_log("%s - %s: tc1_noacc-tc1_acc: s_id = s_id near by platform (+%d)" % 
                                            (last_arrival['name'], departure['name'], self.costs['change_not_enough_time']))
                                else:
                                    cost += self.costs['change_2']
                                    self.route_logger.append_to_log("%s - %s: tc1_noacc-tc1_acc: s_id = s_id near by platform (+%d)" % 
                                            (last_arrival['name'], departure['name'], self.costs['change_2']))
                            else:
                                # other station
                                placeholder_segment['name'] = self.translator.translate("transport_creator", "footway_place_holder")
                                placeholder_segment['sub_type'] = "footway_place_holder"
                                if time_for_change < self.long_change_interval:
                                    cost += self.costs['change_not_enough_time']
                                    self.route_logger.append_to_log("%s - %s: tc1_noacc-tc1_acc: s_id != s_id different platform (+%d)" % 
                                            (last_arrival['name'], departure['name'], self.costs['change_not_enough_time']))
                                else:
                                    cost += self.costs['change_3']
                                    self.route_logger.append_to_log("%s - %s: tc1_noacc-tc1_acc: s_id != s_id different platform (+%d)" % 
                                            (last_arrival['name'], departure['name'], self.costs['change_3']))

                        # tc1-tc1: no exact station positions known
                        else:
                            if last_arrival['station_id'] == departure['station_id']:
                                placeholder_segment['name'] = self.translator.translate("transport_creator", "nearby_station_no_exact_pos")
                                placeholder_segment['sub_type'] = self.translator.translate("highway", "footway")
                                if time_for_change < self.short_change_interval:
                                    cost += self.costs['change_not_enough_time']
                                    self.route_logger.append_to_log("%s - %s: tc1_noacc-tc1_noacc: s_id = s_id near by platform (+%d)" % 
                                            (last_arrival['name'], departure['name'], self.costs['change_not_enough_time']))
                                else:
                                    cost += self.costs['change_3']
                                    self.route_logger.append_to_log("%s - %s: tc1_noacc-tc1_noacc: s_id = s_id near by platform (+%d)" % 
                                            (last_arrival['name'], departure['name'], self.costs['change_3']))
                            else:
                                # other station
                                placeholder_segment['name'] = self.translator.translate("transport_creator", "footway_place_holder")
                                placeholder_segment['sub_type'] = "footway_place_holder"
                                if time_for_change < self.long_change_interval:
                                    cost += self.costs['change_not_enough_time']
                                    self.route_logger.append_to_log("%s - %s: tc1_noacc-tc1_noacc: s_id != s_id different platform (+%d)" % 
                                            (last_arrival['name'], departure['name'], self.costs['change_not_enough_time']))
                                else:
                                    cost += self.costs['change_4']
                                    self.route_logger.append_to_log("%s - %s: tc1_noacc-tc1_noacc: s_id != s_id different platform (+%d)" % 
                                            (last_arrival['name'], departure['name'], self.costs['change_4']))

                    # tc1-tc2
                    elif last_arrival['transportation_class'] == 1 and departure['transportation_class'] == 2:
                        # station has entrances
                        placeholder_segment['name'] = self.translator.translate("transport_creator", "footway_place_holder")
                        placeholder_segment['sub_type'] = "footway_place_holder"
                        if departure['accuracy'] == True:
                            if time_for_change < self.short_change_interval:
                                cost += self.costs['change_not_enough_time']
                                self.route_logger.append_to_log("%s - %s: tc1-tc2+entr (+%d)" % 
                                        (last_arrival['name'], departure['name'], self.costs['change_not_enough_time']))
                            else:
                                cost += self.costs['change_3']
                                self.route_logger.append_to_log("%s - %s: tc1-tc2+entr (+%d)" % 
                                        (last_arrival['name'], departure['name'], self.costs['change_3']))
                        else:
                            if time_for_change < self.long_change_interval:
                                cost += self.costs['change_not_enough_time']
                                self.route_logger.append_to_log("%s - %s: tc1-tc2 no_entr (+%d)" % 
                                        (last_arrival['name'], departure['name'], self.costs['change_not_enough_time']))
                            else:
                                cost += self.costs['change_4']
                                self.route_logger.append_to_log("%s - %s: tc1-tc2 no_entr (+%d)" % 
                                        (last_arrival['name'], departure['name'], self.costs['change_4']))

                    # tc2-tc1
                    elif last_arrival['transportation_class'] == 2 and departure['transportation_class'] == 1:
                        # exact position of station known
                        placeholder_segment['name'] = self.translator.translate("transport_creator", "footway_place_holder")
                        placeholder_segment['sub_type'] = "footway_place_holder"
                        if departure['accuracy'] == True:
                            if time_for_change < self.short_change_interval:
                                cost += self.costs['change_not_enough_time']
                                self.route_logger.append_to_log("%s - %s: tc2-tc1+exact (+%d)" % 
                                        (last_arrival['name'], departure['name'], self.costs['change_not_enough_time']))
                            else:
                                cost += self.costs['change_2']
                                self.route_logger.append_to_log("%s - %s: tc2-tc1+exact (+%d)" % 
                                        (last_arrival['name'], departure['name'], self.costs['change_2']))
                        else:
                            if time_for_change < self.long_change_interval:
                                cost += self.costs['change_not_enough_time']
                                self.route_logger.append_to_log("%s - %s: tc2-tc1 not_exact (+%d)" % 
                                        (last_arrival['name'], departure['name'], self.costs['change_not_enough_time']))
                            else:
                                cost += self.costs['change_4']
                                self.route_logger.append_to_log("%s - %s: tc2-tc1 not_exact (+%d)" % 
                                        (last_arrival['name'], departure['name'], self.costs['change_4']))

                    # tc2-tc2
                    elif last_arrival['transportation_class'] == 2 and departure['transportation_class'] == 2:
                        if last_arrival['station_id'] == departure['station_id']:
                            placeholder_segment['name'] = self.translator.translate("transport_creator", "within_station")
                            placeholder_segment['sub_type'] = self.translator.translate("highway", "footway")
                            if time_for_change < self.short_change_interval:
                                cost += self.costs['change_not_enough_time']
                                self.route_logger.append_to_log("%s - %s: tc2-tc2: same station id (+%d)" % 
                                        (last_arrival['name'], departure['name'], self.costs['change_not_enough_time']))
                            else:
                                cost += self.costs['change_3']
                                self.route_logger.append_to_log("%s - %s: tc2-tc2: same station id (+%d)" % 
                                        (last_arrival['name'], departure['name'], self.costs['change_3']))
                        else:
                            placeholder_segment['name'] = self.translator.translate("transport_creator", "different_station")
                            placeholder_segment['sub_type'] = self.translator.translate("highway", "footway")
                            if time_for_change < self.long_change_interval:
                                cost += self.costs['change_not_enough_time']
                                self.route_logger.append_to_log("%s - %s: tc2-tc2: diff station id (+%d)" % 
                                        (last_arrival['name'], departure['name'], self.costs['change_not_enough_time']))
                            else:
                                cost += self.costs['change_4']
                                self.route_logger.append_to_log("%s - %s: tc2-tc2: diff station id (+%d)" % 
                                        (last_arrival['name'], departure['name'], self.costs['change_4']))

                    # something went wrong with the transportation class
                    else:
                        print "parsing error"
                        # raise route_parsing_exception("blub")

                    # add segment and arrival
                    route.append(placeholder_segment)

                # add departure, transport_segment and arrival
                route.append(departure)
                route.append(transport_segment)
                route.append(arrival)

        # adding the last footway segment
        placeholder_segment = {"name":"", "type":"footway", "sub_type":"", "distance":0, "bearing":0}
        if "$Individual" in legs[-1].getClass().getName():
            placeholder_segment['distance'] = geometry.distance_between_two_points(
                    geometry.convert_coordinate_to_float(legs[-1].departure.lat),
                    geometry.convert_coordinate_to_float(legs[-1].departure.lon),
                    dest_point['lat'], dest_point['lon'] )
            placeholder_segment['bearing'] = geometry.bearing_between_two_points(
                    geometry.convert_coordinate_to_float(legs[-1].departure.lat),
                    geometry.convert_coordinate_to_float(legs[-1].departure.lon),
                    dest_point['lat'], dest_point['lon'] )
        else:
            placeholder_segment['distance'] = geometry.distance_between_two_points(
                    geometry.convert_coordinate_to_float(legs[-1].arrival.lat),
                    geometry.convert_coordinate_to_float(legs[-1].arrival.lon),
                    dest_point['lat'], dest_point['lon'] )
            placeholder_segment['bearing'] = geometry.bearing_between_two_points(
                    geometry.convert_coordinate_to_float(legs[-1].arrival.lat),
                    geometry.convert_coordinate_to_float(legs[-1].arrival.lon),
                    dest_point['lat'], dest_point['lon'] )
        if placeholder_segment['distance'] > 50:
            walking_distance += placeholder_segment['distance']
            placeholder_segment['name'] = self.translator.translate("transport_creator", "footway_place_holder")
            placeholder_segment['sub_type'] = "footway_place_holder"
            route.append(placeholder_segment)
            route.append(dest_point)


        # add walking distance to cost value
        cost += (walking_distance / self.costs['walk_dist_meters']) + 1
        self.route_logger.append_to_log("Fußweg insgesamt = %d, %d Punkte" % (walking_distance, (walking_distance/self.costs['walk_dist_meters'])+1))

        # time calculation
        departure_time = 0
        arrival_time = 0
        number_of_trips = 0
        transportation_vehicles = []
        for part in route:
            if part['type'] == "transport":
                number_of_trips += 1
                transportation_vehicles.append(part['line'])
                arrival_time = part['arrival_time_millis']
                if departure_time == 0:
                    departure_time = part['departure_time_millis']
        minutes_till_departure = (departure_time - int(time.time()*1000)) / 60000
        trip_length = (arrival_time - departure_time) / 60000
        cost += (minutes_till_departure / self.costs['min_departure']) + 1
        cost += (trip_length / self.costs['min_trip_length']) + 1
        self.route_logger.append_to_log("%d Minuten bis Abfahrt, %d Punkte"
                % (minutes_till_departure, (minutes_till_departure/self.costs['min_departure'])+1))
        self.route_logger.append_to_log("%d Minuten Dauer, %d Punkte"
                % (trip_length, (trip_length/self.costs['min_trip_length'])+1))

        # create and return transport route object
        if cost < 100:
            route_description = self.translator.translate("transport_creator", "transport_route_description") \
                    % (minutes_till_departure, trip_length, (number_of_trips-1),
                    ' '.join(transportation_vehicles), walking_distance)
        else:
            route_description = self.translator.translate("transport_creator", "transport_route_description_no_time") \
                    % (minutes_till_departure, trip_length, (number_of_trips-1),
                    ' '.join(transportation_vehicles), walking_distance)
        return RouteTransportCreator.TransportRouteObject(route, cost,
                route_description, departure_time, ','.join(transportation_vehicles))
Esempio n. 8
0
    def create_intersection(self, osm_id, lat, lon, name, tags,
                            number_of_streets, number_of_streets_with_name,
                            number_of_traffic_signals):
        intersection_table = Config().get_param("intersection_table")
        intersection_table_data = Config().get_param("intersection_data_table")
        intersection = {}
        if type(osm_id) is not int or type(lat) is not float or type(
                lon) is not float or type(name) is not str or type(
                    tags) is not dict or type(
                        number_of_streets) is not int or type(
                            number_of_streets_with_name) is not int or type(
                                number_of_traffic_signals) is not int:
            return intersection
        intersection = self.create_way_point(osm_id, lat, lon, tags)
        if intersection == {}:
            return intersection

        # traffic lights
        intersection['pedestrian_crossing_list'] = []
        if number_of_traffic_signals > 0:
            result = DBControl().fetch_data(
                "SELECT id, ST_X(geom) as lon, ST_Y(geom) as lat, crossing_street_name, tags \
                    from pedestrian_crossings where intersection_id = %d" %
                osm_id)
            for row in result:
                signal = self.create_poi(0, int(row['id']), row['lat'],
                                         row['lon'],
                                         self.parse_hstore_column(row['tags']),
                                         0, 0)
                if row['crossing_street_name'] != None:
                    signal['name'] += ": %s" % row['crossing_street_name']
                intersection['pedestrian_crossing_list'].append(signal)

        # intersection specific properties
        intersection['name'] = ""
        for street in name.split(","):
            translated_street = self.translator.translate(
                "highway", street.strip())
            if translated_street == street.strip():
                translated_street = self.translator.translate(
                    "railway", street.strip())
            intersection['name'] += "%s, " % translated_street
        intersection['name'] = intersection['name'].strip(",")
        intersection[
            'number_of_streets_with_name'] = number_of_streets_with_name
        intersection['type'] = "intersection"
        intersection['sub_type'] = self.translator.translate(
            "crossing", "unknown")
        if tags.has_key("crossing"):
            intersection['sub_type'] = self.translator.translate(
                "crossing", tags['crossing'])
        elif tags.has_key("highway") and tags['highway'] == "crossing" \
                and tags.has_key("crossing_ref") and tags['crossing_ref'] in ["pelican", "toucan", "zebra"]:
            intersection['sub_type'] = self.translator.translate(
                "crossing", tags['crossing_ref'])
        elif tags.has_key("highway") and tags['highway'] == "traffic_signals":
            intersection['sub_type'] = self.translator.translate(
                "highway", "traffic_signals")
        elif tags.has_key("railway") and tags['railway'] == "crossing":
            intersection['sub_type'] = self.translator.translate(
                "railway", "crossing")
        elif intersection['pedestrian_crossing_list'].__len__() > 0:
            intersection['sub_type'] = self.translator.translate(
                "crossing", "traffic_signals")

        # streets
        intersection['sub_points'] = []
        result = DBControl().fetch_data("\
                SELECT way_id, node_id, direction, way_tags, node_tags, \
                    ST_X(geom) as lon, ST_Y(geom) as lat \
                from %s where id = %d" % (intersection_table_data, osm_id))
        for street in result:
            sub_point = self.create_way_point(
                street['node_id'], street['lat'], street['lon'],
                self.parse_hstore_column(street['node_tags']))
            if street['direction'] == "B":
                way_segment = self.create_way_segment(
                    street['way_id'],
                    self.parse_hstore_column(street['way_tags']), True)
            else:
                way_segment = self.create_way_segment(
                    street['way_id'],
                    self.parse_hstore_column(street['way_tags']), False)
            for key in way_segment:
                sub_point[key] = way_segment[key]
            sub_point[
                'intersection_bearing'] = geometry.bearing_between_two_points(
                    intersection['lat'], intersection['lon'], sub_point['lat'],
                    sub_point['lon'])
            intersection['sub_points'].append(sub_point)
        return intersection