Exemple #1
0
def random_place_in_paris():
    """return a random location in Paris"""
    MAX_LAT = 48.87
    MIN_LAT = 48.84
    MAX_LNG = 2.295
    MIN_LNG = 2.285

    rand_lat = uniform(MIN_LAT, MAX_LAT)
    rand_lng = uniform(MIN_LNG, MAX_LNG)
    return Place(lat=rand_lat, lng=rand_lng)
Exemple #2
0
def itinerary_search():
    try:
        TypeUser = request.args.get('TypeUser', 'Défaut')
        P_Permis = request.args.get('P_Permis', False)
        if P_Permis == "true":
            P_Permis = True
        else:
            P_Permis = False
        P_Meteo = request.args.get('P_Meteo', True)
        if P_Meteo == "true":
            P_Meteo = True
        else:
            P_Meteo = False
        P_Charge = request.args.get('P_Charge', False)
        if P_Charge == "true":
            P_Charge = True
        else:
            P_Charge = False
    except:
        abort(400)
    try:
        org = request.args.get('origine', "Champs de Mars")
        dest = request.args.get('destination', "Place de la Nation")
        print(
            "type utilisateur:{}\npermis:{}\nmeteo:{}\nchargé:{}\norigine:{}\ndestination:{}\n"
            .format(TypeUser, P_Permis, P_Meteo, P_Charge, org, dest))

        origin = Place(org)
        destination = Place(dest)
        iti = Itinerary(origin=origin, destination=destination)
        Utilisateur = User(TypeUser,
                           driving_license=P_Permis,
                           weather=P_Meteo,
                           loaded=P_Charge)
        resultat = Suggested_Itineraries(Utilisateur, iti)

        content = jsonify(resultat)

        return content

    except:
        abort(500)
    def __init__(self, origin, destination, date=None, transit_mode_type=None, itinerary_index=0):

        Itinerary.__init__(self, origin, destination, date, transit_mode_type, itinerary_index)
        self.transport_mode = "walking"

        url_request = Walking.__URL_API_DIRECTION
        url_request += "&origin=" + str(self.origin.lat) + "," + str(self.origin.lng)
        url_request += "&destination=" + str(self.destination.lat) + "," + str(self.destination.lng)
        r = requests.get(url_request)
        if r.status_code != 200:
            raise BadRequest(r.status_code)
        else:
            raw_data = r.json()
            if raw_data['status'] == "OVER_QUERY_LIMIT":
                raise QueryLimit("Can't retieve any data from API (Walking)")
            else:
                # on récupère les informations concernant les différentes étapes
                steps = raw_data['routes'][self.itinerary_index]['legs'][0]['steps']

                self.total_duration = raw_data['routes'][self.itinerary_index]['legs'][0]['duration']['value']
                self.total_polyline = [raw_data['routes'][self.itinerary_index]['overview_polyline']['points']]

                self.walking_distance = 0
                self.walking_duration = 0

                self.information_legs = []  # Notre information_legs liste stockant nos étapes de trajet

                # Parcours des étapes trouvées de notre trajet pour remplir
                # notre liste de stockage self.information_legs
                for step_number, step in enumerate(steps):
                    self.information_legs.append({})
                    self.information_legs[step_number]['transport_mode'] = step['travel_mode']
                    self.information_legs[step_number]['interim_start'] = Place(lat=step['start_location']['lat'],
                                                                                lng=step['start_location']['lng'])
                    self.information_legs[step_number]['interim_destination'] = Place(lat=step['end_location']['lat'],
                                                                                      lng=step['end_location']['lng'])
                    self.information_legs[step_number]['distance'] = step['distance']['value']
                    self.information_legs[step_number]['duration'] = step['duration']['value']
                    self.information_legs[step_number]['instructions'] = step['html_instructions']

                    self.walking_distance += step['distance']['value']
                    self.walking_duration += step['duration']['value']
    def __init__(self,
                 origin,
                 destination,
                 date=None,
                 transit_mode_type=None,
                 itinerary_index=0):

        Itinerary.__init__(self, origin, destination, date, transit_mode_type,
                           itinerary_index)
        self.transport_mode = "velib"
        #prix velib de base - beaucoup de segmentation clients pour les tarifs...
        self.price = "For 1,70€, the 1 day ticket gives you access to Velib' for 24h with the first 30min free of charge. Additional fares apply afterwards."
        # Station velib d'origine
        stop = True
        search_size = 1
        while stop:
            parameters = Velib.__PARAMETERS + "&geofilter.distance=" + "%2C".join(
                [
                    str(self.origin.lat),
                    str(self.origin.lng),
                    str(search_size * 100)
                ])
            r = requests.get(Velib.__URL_VELIB, parameters)
            if r.status_code != 200:
                raise BadRequest(r.status_code)
            else:
                raw_data = r.json()
                search_size += 1
                stations_origin = []
                possible_stations = raw_data['records']
                for possible_station in possible_stations:
                    available_bike = possible_station['fields'][
                        'available_bikes']
                    if available_bike == 0:
                        pass
                    else:
                        stop = False
                        stations_origin.append({})
                        stations_origin[-1]['station_address'] = Place(
                            address=possible_station['fields']['address'],
                            lat=possible_station['fields']['position'][0],
                            lng=possible_station['fields']['position'][1])
                        stations_origin[-1]['nb_bike'] = available_bike

        fastest_path_origin = Walking(origin,
                                      stations_origin[0]['station_address'],
                                      date=self.date)
        for station in stations_origin:
            walk = Walking(origin, station['station_address'], date=self.date)
            if walk.total_duration < fastest_path_origin.total_duration:
                fastest_path_origin = walk

        # station velib à l'arrivée
        stop = True
        search_size = 1
        while stop:
            parameters = Velib.__PARAMETERS + "&geofilter.distance=" + "%2C".join(
                [
                    str(self.destination.lat),
                    str(self.destination.lng),
                    str(search_size * 1000)
                ])
            r = requests.get(Velib.__URL_VELIB, parameters)
            if r.status_code != 200:
                raise BadRequest(r.status_code)
            else:
                raw_data = r.json()
                search_size += 1
                stations_destination = []
                possible_stations = raw_data['records']
                for possible_station in possible_stations:
                    empty_slots = possible_station['fields'][
                        'available_bike_stands']
                    if empty_slots == 0:
                        pass
                    else:
                        stop = False
                        stations_destination.append({})
                        stations_destination[-1]['station_address'] = Place(
                            address=possible_station['fields']['address'],
                            lat=possible_station['fields']['position'][0],
                            lng=possible_station['fields']['position'][1])

                        stations_destination[-1]['empty_slots'] = empty_slots

        fastest_path_destination = Walking(
            stations_destination[0]['station_address'], destination)
        for station in stations_destination:
            walk = Walking(station['station_address'], destination)
            if walk.total_duration < fastest_path_destination.total_duration:
                fastest_path_destination = walk

        # trajet en velib

        start_date_velib = self.date + timedelta(
            0, fastest_path_origin.total_duration + Velib.__COMMUTING_DURATION)
        velib = Bicycling(fastest_path_origin.destination,
                          fastest_path_destination.origin,
                          date=start_date_velib)

        # Prise en compte du temps pour la dernière étape (station d'arrivée velib à destination)
        start_date_last_leg = start_date_velib + timedelta(
            0, velib.total_duration + Velib.__COMMUTING_DURATION)
        fastest_path_destination = Walking(fastest_path_destination.origin,
                                           self.destination,
                                           date=start_date_last_leg)

        # Itineraire total = fastest_path_origin + velib + fastest_path_destination

        self.total_duration = fastest_path_origin.total_duration \
                              + velib.total_duration \
                              + fastest_path_destination.total_duration
        self.walking_duration = fastest_path_origin.walking_duration \
                                + velib.walking_duration \
                                + fastest_path_destination.walking_duration
        self.walking_distance = fastest_path_origin.walking_distance \
                                + velib.walking_distance \
                                + fastest_path_destination.walking_distance
        self.transit_duration = fastest_path_origin.transit_duration \
                                + velib.transit_duration \
                                + fastest_path_destination.transit_duration
        self.velib_duration = velib.bicycling_duration
        self.velib_distance = velib.bicycling_distance
        self.total_polyline = fastest_path_origin.total_polyline + velib.total_polyline \
                              + fastest_path_destination.total_polyline
        self.information_legs = fastest_path_origin.information_legs \
                                + velib.information_legs \
                                + fastest_path_destination.information_legs
        # Itineraire total = fastest_path_origin + velib + fastest_path_destination

        self.total_duration = fastest_path_origin.total_duration \
                              + velib.total_duration \
                              + fastest_path_destination.total_duration
        self.walking_duration = fastest_path_origin.walking_duration \
                                + velib.walking_duration \
                                + fastest_path_destination.walking_duration
        self.walking_distance = fastest_path_origin.walking_distance \
                                + velib.walking_distance \
                                + fastest_path_destination.walking_distance
        self.transit_duration = fastest_path_origin.transit_duration \
                                + velib.transit_duration \
                                + fastest_path_destination.transit_duration
        self.velib_duration = velib.bicycling_duration
        self.velib_distance = velib.bicycling_distance
        self.total_polyline = fastest_path_origin.total_polyline + velib.total_polyline \
                              + fastest_path_destination.total_polyline
        self.information_legs = fastest_path_origin.information_legs \
                                + velib.information_legs \
                                + fastest_path_destination.information_legs


if __name__ == "__main__":
    # Test des différentes portions d'une voyage en velib

    org = Place(address="Montmartre, Paris")
    des = Place(address="Cité Universitaire, Paris")
    CtoD = Velib(org, des)
    print(repr(CtoD))
                            lng=step['end_location']['lng'])
                    self.information_legs[step_number]['distance'] = step[
                        'distance']['value']
                    self.information_legs[step_number]['duration'] = step[
                        'duration']['value']
                    self.information_legs[step_number]['instructions'] = step[
                        'html_instructions']

                    if self.information_legs[step_number][
                            'transport_mode'] == "BICYCLING":
                        self.bicycling_distance += step['distance']['value']
                        self.bicycling_duration += step['duration']['value']
                    else:
                        self.walking_distance += step['distance']['value']
                        self.walking_duration += step['duration']['value']


if __name__ == "__main__":
    """Script de test de la bonne construction des classes"""

    # Test des différentes portions d'une voyage en vélo
    org = Place(address="10 rue oswaldo cruz paris 75016")
    des = Place(address="Favella Chic Paris")
    AtoB = Bicycling(org, des)
    print(repr(AtoB))

    org = Place(address="Montmartre, Paris")
    des = Place(address="Cité Universitaire, Paris")
    CtoD = Bicycling(org, des)
    print(repr(CtoD))
    def __init__(self, origin, destination, date=None, transit_mode_type=None, itinerary_index=0):
        Itinerary.__init__(self, origin, destination, date, transit_mode_type, itinerary_index)

        self.transport_mode = "autolib"

        #Prix indiqué sur le site autolib, indicatif
        self.price = "For 10€/month you have access to a car 24/7, and the rent available at the best price. +0,23€/ minute. Head to the Autolib website for more information."


        # Station autolib d'origine
        stop = True
        search_size = 1
        while stop:
            parameters = Autolib.__PARAMETERS + "&geofilter.distance=" + "%2C".join(
                [str(self.origin.lat), str(self.origin.lng), str(search_size * 100)])
            r = requests.get(Autolib.__URL_AUTOLIB, parameters)
            if r.status_code != 200:
                raise BadRequest(r.status_code)
            else:
                raw_data = r.json()
                search_size += 1
                stations_origin = []
                possible_stations = raw_data['records']
                for possible_station in possible_stations:
                    available_car = possible_station['fields']['cars']
                    if available_car == 0:
                        pass
                    else:
                        stop = False
                        stations_origin.append({})
                        stations_origin[-1]['station_address'] = Place(address=(possible_station['fields']['address']
                                                                                + " "
                                                                                + possible_station['fields'][
                                                                                    'postal_code']
                                                                                + " Paris"),
                                                                       lat=possible_station['fields']['geo_point'][0],
                                                                       lng=possible_station['fields']['geo_point'][1])
                        stations_origin[-1]['nb_auto'] = available_car

        fastest_path_origin = Walking(self.origin, stations_origin[0]['station_address'], date=self.date)
        for station in stations_origin:
            walk = Walking(self.origin, station['station_address'], date=self.date)
            if walk.total_duration < fastest_path_origin.total_duration:
                fastest_path_origin = walk

        # station autolib à l'arrivée
        stop = True
        search_size = 1
        while stop:
            parameters = Autolib.__PARAMETERS + "&geofilter.distance=" + "%2C".join(
                [str(self.destination.lat), str(self.destination.lng), str(search_size * 100)])
            r = requests.get(Autolib.__URL_AUTOLIB, parameters)
            if r.status_code != 200:
                raise BadRequest(r.status_code)
            else:
                raw_data = r.json()
                search_size += 1
                stations_destination = []
                possible_stations = raw_data['records']
                for possible_station in possible_stations:
                    empty_slots = possible_station['fields']['slots'] - possible_station['fields']['cars']
                    if empty_slots == 0:
                        pass
                    else:
                        stop = False
                        stations_destination.append({})
                        stations_destination[-1]['station_address'] = Place(
                            address=(possible_station['fields']['address']
                                     + " "
                                     + possible_station['fields'][
                                         'postal_code']
                                     + " Paris"),
                            lat=possible_station['fields']['geo_point'][0],
                            lng=possible_station['fields']['geo_point'][1])
                        stations_destination[-1]['empty_slots'] = empty_slots

        fastest_path_destination = Walking(stations_destination[0]['station_address'], self.destination)
        for station in stations_destination:
            walk = Walking(station['station_address'], self.destination)
            if walk.total_duration < fastest_path_destination.total_duration:
                fastest_path_destination = walk

        # trajet en autolib
        start_date_autolib = self.date + timedelta(0, fastest_path_origin.total_duration + Autolib.__COMMUTING_DURATION)
        autolib = Driving(fastest_path_origin.destination, fastest_path_destination.origin, date=start_date_autolib)

        # Prise en compte du temps pour la dernière étape (station d'arrivée Autolib à destination)
        start_date_last_leg = start_date_autolib + timedelta(0, autolib.total_duration + Autolib.__COMMUTING_DURATION)
        fastest_path_destination = Walking(fastest_path_destination.origin, self.destination, date=start_date_last_leg)

        # Itineraire total = fastest_path_origin + autolib + fastest_path_destination
        self.total_duration = fastest_path_origin.total_duration \
                              + autolib.total_duration \
                              + fastest_path_destination.total_duration
        self.walking_duration = fastest_path_origin.walking_duration \
                                + autolib.walking_duration \
                                + fastest_path_destination.walking_duration
        self.walking_distance = fastest_path_origin.walking_distance \
                                + autolib.walking_distance \
                                + fastest_path_destination.walking_distance
        self.transit_duration = fastest_path_origin.transit_duration \
                                + autolib.transit_duration \
                                + fastest_path_destination.transit_duration
        self.driving_duration = autolib.driving_duration
        self.driving_distance = autolib.driving_distance
        self.total_polyline = fastest_path_origin.total_polyline \
                              + autolib.total_polyline \
                              + fastest_path_destination.total_polyline
        self.information_legs = fastest_path_origin.information_legs \
                                + autolib.information_legs \
                                + fastest_path_destination.information_legs
    def __init__(self,
                 origin,
                 destination,
                 date=None,
                 transit_mode_type=None,
                 itinerary_index=0):
        Itinerary.__init__(self, origin, destination, date, transit_mode_type,
                           itinerary_index)
        self.transport_mode = "transit"
        if self.transit_mode_type is None:
            self.transit_mode_type = "bus|rail"

        url_request = Transit.__URL_API_DIRECTION_TRANSIT
        url_request += "&origin=" + str(self.origin.lat) + "," + str(
            self.origin.lng)
        url_request += "&destination=" + str(self.destination.lat) + "," + str(
            self.destination.lng)
        url_request += "&transit_mode=" + str(self.transit_mode_type)

        r = requests.get(url_request)
        if r.status_code != 200:
            raise BadRequest(r.status_code)
        else:
            raw_data = r.json()
            if raw_data['status'] == "OVER_QUERY_LIMIT":
                raise QueryLimit("Can't retieve any data from API (Transit)")
            else:
                steps = raw_data['routes'][
                    self.itinerary_index]['legs'][0]['steps']

                self.total_duration = raw_data['routes'][
                    self.itinerary_index]['legs'][0]['duration']['value']
                self.total_polyline = [
                    raw_data['routes'][self.itinerary_index]
                    ['overview_polyline']['points']
                ]

                self.walking_distance = 0
                self.walking_duration = 0
                self.transit_duration = 0

                self.information_legs = []
                # Parcours des étapes trouvées de notre trajet
                # pour remplir notre liste de stockage self.information_legs
                for step_number, step in enumerate(steps):
                    self.information_legs.append({})
                    self.information_legs[step_number][
                        'transport_mode'] = step['travel_mode']
                    self.information_legs[step_number]['distance'] = step[
                        'distance']['value']
                    self.information_legs[step_number][
                        'interim_destination'] = Place(
                            lat=step['end_location']['lat'],
                            lng=step['end_location']['lng'])
                    self.information_legs[step_number]['duration'] = step[
                        'duration']['value']
                    self.information_legs[step_number][
                        'interim_start'] = Place(
                            lat=step['start_location']['lat'],
                            lng=step['start_location']['lng'])
                    self.information_legs[step_number]['instructions'] = step[
                        'html_instructions']
                    if self.information_legs[step_number][
                            'transport_mode'] == "TRANSIT":
                        self.information_legs[step_number][
                            'arrival_stop'] = step['transit_details'][
                                'arrival_stop']['name']
                        self.information_legs[step_number]['departure_stop'] = \
                            step['transit_details']['departure_stop']['name']
                        self.information_legs[step_number][
                            'transit_mode'] = step['transit_details']['line'][
                                'vehicle']['type']
                        if 'short_name' in step['transit_details'][
                                'line'].keys():
                            self.information_legs[step_number]['line'] = step[
                                'transit_details']['line']['short_name']
                        else:
                            self.information_legs[step_number]['line'] = step[
                                'transit_details']['line']['name']
                        self.information_legs[step_number][
                            'number_stops'] = step['transit_details'][
                                'num_stops']
                        self.information_legs[step_number]['duration'] = step[
                            'duration']['value']
                        self.transit_duration += step['duration']['value']
                    if self.information_legs[step_number][
                            'transport_mode'] == "WALKING":
                        self.walking_distance += step['distance']['value']
                        self.walking_duration += step['duration']['value']
                        self.information_legs[step_number][
                            'number_stops'] = step['transit_details'][
                                'num_stops']
                        self.information_legs[step_number]['duration'] = step[
                            'duration']['value']
                        self.transit_duration += step['duration']['value']
                    if self.information_legs[step_number][
                            'transport_mode'] == "WALKING":
                        self.walking_distance += step['distance']['value']
                        self.walking_duration += step['duration']['value']


if __name__ == "__main__":
    """Script de test de la bonne construction des classes"""

    # Test des différentes portions d'une voyage en transport de commun
    org = Place(address="79 Avenue de la république 75011, Paris")
    des = Place(address="La Muette, Paris")
    AtoB = Transit(org, des, transit_mode_type="bus")
    print(repr(AtoB))

    org = Place(address="Montmartre, Paris")
    des = Place(address="Cité Universitaire, Paris")
    CtoD = Transit(org, des, transit_mode_type="bus")
    print(repr(CtoD))

    org = Place(address="10 rue oswaldo cruz paris 75016")
    des = Place(address="2 Avenue Mozart 75016 Paris")
    EtoF = Transit(org, des, transit_mode_type="bus|rail")
    print(repr(EtoF))
Exemple #10
0
 def test_place(self):
     somewhere = Place(address="3 rue Rivoli")
     self.assertEqual(somewhere.address, "3 rue Rivoli Paris")
     self.assertAlmostEqual(somewhere.lat, 48.8555654)
     self.assertAlmostEqual(somewhere.lng, 2.3589835)
        suggested_itineraries['results'][option_nb][
            'duration'] = transport_option.total_duration
        suggested_itineraries['results'][option_nb][
            'polyline_encoded'] = transport_option.total_polyline
        suggested_itineraries['results'][option_nb]['instructions'] = repr(
            transport_option).replace("\n", "<br />")

        if transport_option is 'driving':
            suggested_itineraries['results'][option][
                'distance'] = transport_option.driving_distance
        if transport_option is 'walking':
            suggested_itineraries['results'][option][
                'distance'] = transport_option.walking_distance
        if transport_option is 'bicycling':
            suggested_itineraries['results'][option][
                'distance'] = transport_option.bicycling_distance
        if transport_option is 'uber':
            suggested_itineraries['results'][option][
                'wait_time'] = transport_option.uber_wait_duration

    return suggested_itineraries


if __name__ == "__main__":
    """Script de test"""
    origin = Place("8 avenue Adrien Hebrard")
    destination = Place("nation")
    iti = Itinerary(origin=origin, destination=destination)
    pierre = User('PMR', True, False, False)
    print(Suggested_Itineraries(pierre, iti))
Exemple #12
0
            else:
                return str(h) + " h " + str(m + 1) + " min"

    @staticmethod
    def dist_formatted(nb_meter):
        """Convert a number of meters in a formatted string"""
        if nb_meter == 0:
            return "0 km"
        else:
            return str(math.floor(nb_meter / 100 + 1) / 10) + " km"


class QueryLimit(Exception):
    """Error raised when the query limit is reached"""
    pass


class BadRequest(Exception):
    """The request is not working properly."""
    pass


if __name__ == "__main__":
    """Script de test"""

    # Test des itinéraires
    org = Place(address="Opéra,Paris")
    des = Place(address="Bastille,Paris")
    AtoB = Itinerary(org, des)
    print(repr(AtoB))
Exemple #13
0
    def options_uber(self):
        return self._options_uber

    # J'ai décidé d'override celle de la classe mère, plus facile (on n'utilise pas google maps ici...)
    def __repr__(self):

        res = ""
        res += "Here is the summary of your Uber Trip:"
        res += "\n"
        res += "Your uber will be arriving in " + str(
            math.floor(self._uber_wait_duration / 60 + 1)) + " min."
        res += "\n"
        res += "Your ride will take you " + str(
            math.floor(self._uber_travel_duration / 60 + 1)
        ) + " min and " + str(self.driving_distance // 1000) + " km " + str(
            self.driving_distance % 1000) + "m to arrive at destination."
        res += "The fare estimate is " + str(self.price) + "."

        return res


if __name__ == "__main__":
    """Script de test"""

    # Test des itinéraires
    org = Place(address="Porte de Passy")
    des = Place(address="Porte de la Villette")
    AtoB = Uber(org, des, uber_type="uberberline")

    print(repr(AtoB))