示例#1
0
    def _get_street_network_routing_matrix(
        self, instance, origins, destinations, street_network_mode, max_duration, request, request_id, **kwargs
    ):
        if street_network_mode != "bike":
            logging.getLogger(__name__).error('Geovelo, mode {} not implemented'.format(street_network_mode))
            raise InvalidArguments('Geovelo, mode {} not implemented'.format(street_network_mode))
        if len(origins) != 1 and len(destinations) != 1:
            logging.getLogger(__name__).error(
                'Geovelo, managing only 1-n in connector, requested {}-{}'.format(
                    len(origins), len(destinations)
                )
            )
            raise InvalidArguments(
                'Geovelo, managing only 1-n in connector, requested {}-{}'.format(
                    len(origins), len(destinations)
                )
            )

        data = self._make_request_arguments_isochrone(origins, destinations, request['bike_speed'])
        r = self._call_geovelo(
            '{}/{}'.format(self.service_url, 'api/v2/routes_m2m'), requests.post, ujson.dumps(data)
        )
        self._check_response(r)
        resp_json = ujson.loads(r.text)

        if len(resp_json) - 1 != len(data.get('starts', [])) * len(data.get('ends', [])):
            logging.getLogger(__name__).error('Geovelo nb response != nb requested')
            raise UnableToParse('Geovelo nb response != nb requested')

        return self._get_matrix(resp_json)
示例#2
0
    def direct_path(self, mode, pt_object_origin, pt_object_destination,
                    fallback_extremity, request):
        if mode != "bike":
            logging.getLogger(__name__).error(
                'Geovelo, mode {} not implemented'.format(mode))
            raise InvalidArguments(
                'Geovelo, mode {} not implemented'.format(mode))

        data = self._make_request_arguments_direct_path(
            pt_object_origin, pt_object_destination)
        r = self._call_geovelo(
            '{}/{}'.format(
                self.service_url, 'api/v2/computedroutes?'
                'instructions=true&'
                'elevations=false&'
                'geometry=true&'
                'single_result=true&'
                'bike_stations=false&'
                'objects_as_ids=true&'), requests.post, json.dumps(data))
        self._check_response(r)
        resp_json = r.json()

        if len(resp_json) != 1:
            logging.getLogger(__name__).error(
                'Geovelo nb response != nb requested')
            raise UnableToParse('Geovelo nb response != nb requested')

        return self._get_response(resp_json, mode, pt_object_origin,
                                  pt_object_destination, fallback_extremity)
示例#3
0
    def convert_to_utc(self, original_datetime):
        """
        convert the original_datetime in the args to UTC

        for that we need to 'guess' the timezone wanted by the user

        For the moment We only use the default instance timezone.

        It won't obviously work for multi timezone instances, we'll have to do
        something smarter.

        We'll have to consider either the departure or the arrival of the journey
        (depending on the `clockwise` param)
        and fetch the tz of this point.
        we'll have to store the tz for stop area and the coord for admin, poi, ...
        """
        if self.tz() is None:
            return original_datetime

        if original_datetime.tzinfo is not None:
            localized_dt = original_datetime
        else:
            # if we don't have a timezone in the datetime, we consider it a local time from the coverage's tz
            localized_dt = self.tz().normalize(
                self.tz().localize(original_datetime))

        try:
            utctime = localized_dt.astimezone(pytz.utc)
        except ValueError as e:
            raise UnableToParse("Unable to parse datetime, " + e.message)

        return utctime
示例#4
0
 def _get_matrix(cls, json_response):
     '''
     build the 1-n response matrix from geovelo table
     each element is ["start", "end", duration] (first being the header)
     as it is ordered, we only consider the third
     '''
     sn_routing_matrix = response_pb2.StreetNetworkRoutingMatrix()
     row = sn_routing_matrix.rows.add()
     #checking header of geovelo's response
     if json_response[0] != [
             "start_reference", "end_reference", "duration"
     ]:
         logging.getLogger(__name__).error(
             'Geovelo parsing error. Response: {}'.format(json_response))
         raise UnableToParse(
             'Geovelo parsing error. Response: {}'.format(json_response))
     for e in json_response[1:]:
         routing = row.routing_response.add()
         if e[2]:
             routing.duration = e[2]
             routing.routing_status = response_pb2.reached
         else:
             routing.duration = -1
             routing.routing_status = response_pb2.unknown
     return sn_routing_matrix
示例#5
0
    def _get_matrix(cls, json_response):
        '''
        build the 1-n response matrix from geovelo table
        each element is ["start", "end", duration] (first being the header)
        as it is ordered, we only consider the third
        '''
        sn_routing_matrix = response_pb2.StreetNetworkRoutingMatrix()
        row = sn_routing_matrix.rows.add()
        # checking header of geovelo's response
        if json_response[0] != [
                "start_reference", "end_reference", "duration"
        ]:
            logging.getLogger(__name__).error(
                'Geovelo parsing error. Response: {}'.format(json_response))
            raise UnableToParse(
                'Geovelo parsing error. Response: {}'.format(json_response))

        add_ = row.routing_response.add
        for e in itertools.islice(json_response, 1, sys.maxint):
            duration, routing_status = (
                e[2], response_pb2.reached) if e[2] else (-1,
                                                          response_pb2.unknown)
            add_(duration=duration, routing_status=routing_status)

        return sn_routing_matrix
示例#6
0
def get_pt_object_coord(pt_object):
    """
    Given a PtObject, return the coord according to its embedded_type
    :param pt_object: type_pb2.PtObject
    :return: coord: type_pb2.GeographicalCoord

    >>> pt_object = type_pb2.PtObject()
    >>> pt_object.embedded_type = type_pb2.POI
    >>> pt_object.poi.coord.lon = 42.42
    >>> pt_object.poi.coord.lat = 41.41
    >>> coord = get_pt_object_coord(pt_object)
    >>> coord.lon
    42.42
    >>> coord.lat
    41.41
    """
    if not isinstance(pt_object, type_pb2.PtObject):
        logging.getLogger(__name__).error('Invalid pt_object')
        raise InvalidArguments('Invalid pt_object')

    map_coord = {
        type_pb2.STOP_POINT: "stop_point",
        type_pb2.STOP_AREA: "stop_area",
        type_pb2.ADDRESS: "address",
        type_pb2.ADMINISTRATIVE_REGION: "administrative_region",
        type_pb2.POI: "poi",
    }
    attr = getattr(pt_object, map_coord.get(pt_object.embedded_type, ""), None)
    coord = getattr(attr, "coord", None)

    if not coord:
        logging.getLogger(__name__).error('Invalid coord for ptobject type: {}'.format(pt_object.embedded_type))
        raise UnableToParse('Invalid coord for ptobject type: {}'.format(pt_object.embedded_type))
    return coord
示例#7
0
 def _get_coord(self, pt_object):
     if not isinstance(pt_object, type_pb2.PtObject):
         logging.getLogger(__name__).error('Invalid pt_object')
         raise InvalidArguments('Invalid pt_object')
     coord = get_pt_object_coord(pt_object)
     if not coord:
         logging.getLogger(__name__).error(
             'Invalid coord for ptobject type: {}'.format(
                 pt_object.embedded_type))
         raise UnableToParse('Invalid coord for ptobject type: {}'.format(
             pt_object.embedded_type))
     return coord
示例#8
0
    def _direct_path(
        self,
        instance,
        mode,
        pt_object_origin,
        pt_object_destination,
        fallback_extremity,
        request,
        direct_path_type,
        request_id,
    ):
        if mode != "bike":
            logging.getLogger(__name__).error('Geovelo, mode {} not implemented'.format(mode))
            raise InvalidArguments('Geovelo, mode {} not implemented'.format(mode))

        data = self._make_request_arguments_direct_path(
            pt_object_origin, pt_object_destination, request['bike_speed']
        )
        single_result = True
        if (
            direct_path_type == StreetNetworkPathType.DIRECT
            and request['direct_path'] == 'only_with_alternatives'
        ):
            single_result = False
        r = self._call_geovelo(
            '{}/{}'.format(
                self.service_url,
                'api/v2/computedroutes?'
                'instructions=true&'
                'elevations=true&'
                'geometry=true&'
                'single_result={}&'
                'bike_stations=false&'
                'objects_as_ids=true&'.format(single_result),
            ),
            requests.post,
            ujson.dumps(data),
        )
        self._check_response(r)
        resp_json = ujson.loads(r.text)

        if len(resp_json) != 1 and single_result:
            logging.getLogger(__name__).error('Geovelo nb response != nb requested')
            raise UnableToParse('Geovelo nb response != nb requested')

        return self._get_response(resp_json, pt_object_origin, pt_object_destination, fallback_extremity)
示例#9
0
 def _format_coord(self, pt_object):
     if not isinstance(pt_object, type_pb2.PtObject):
         logging.getLogger(__name__).error('Invalid pt_object')
         raise InvalidArguments('Invalid pt_object')
     map_coord = {
         type_pb2.STOP_POINT: pt_object.stop_point.coord,
         type_pb2.STOP_AREA: pt_object.stop_area.coord,
         type_pb2.ADDRESS: pt_object.address.coord,
         type_pb2.ADMINISTRATIVE_REGION:
         pt_object.administrative_region.coord
     }
     coord = map_coord.get(pt_object.embedded_type, None)
     if not coord:
         logging.getLogger(__name__).error(
             'Invalid coord for ptobject type: {}'.format(
                 pt_object.embedded_type))
         raise UnableToParse('Invalid coord for ptobject type: {}'.format(
             pt_object.embedded_type))
     return {"lat": coord.lat, "lon": coord.lon, "type": "break"}