Skip to content

haversine_distance

HaversineDistanceLayer ¤

HaversineDistanceLayer(
    name=None,
    input_dtype=None,
    output_dtype=None,
    lat_lon_constant=None,
    unit="km",
    **kwargs
)

Bases: BaseLayer

Computes the haversine distance operation on a given input tensor.

If lat_lon_constant is not set, inputs must be a list of 4 tensors, in the order of lat1, lon1, lat2, lon2. If lat_lon_constant is set, inputs must be a tensor of 2 tensors, in the order of lat1, lon1.

We DO NOT check if the lat/lon values are out of bounds. For lat, this is [-90, 90] and for lon, this is [-180, 180].

Initializes the HaversineDistanceLayer layer

Parameters:

Name Type Description Default
name Optional[str]

Name of the layer, defaults to None.

None
input_dtype Optional[str]

The dtype to cast the input to. Defaults to None.

None
output_dtype Optional[str]

The dtype to cast the output to. Defaults to None.

None
lat_lon_constant Optional[List[float]]

The lat/lons to use in the haversine distance.

None
unit str

The unit of the distance. Must be either 'km' or 'miles'. calculation. Defaults to None.

'km'
Source code in src/kamae/keras/core/layers/haversine_distance.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def __init__(
    self,
    name: Optional[str] = None,
    input_dtype: Optional[str] = None,
    output_dtype: Optional[str] = None,
    lat_lon_constant: Optional[List[float]] = None,
    unit: str = "km",
    **kwargs: Any,
) -> None:
    """
    Initializes the HaversineDistanceLayer layer

    :param name: Name of the layer, defaults to `None`.
    :param input_dtype: The dtype to cast the input to. Defaults to `None`.
    :param output_dtype: The dtype to cast the output to. Defaults to `None`.
    :param lat_lon_constant: The lat/lons to use in the haversine distance.
    :param unit: The unit of the distance. Must be either 'km' or 'miles'.
    calculation. Defaults to `None`.
    """
    super().__init__(
        name=name, input_dtype=input_dtype, output_dtype=output_dtype, **kwargs
    )
    if lat_lon_constant is not None and len(lat_lon_constant) != 2:
        raise ValueError("If set, lat_lon_constant must be a list of 2 floats")
    self.lat_lon_constant = lat_lon_constant
    if unit not in ["km", "miles"]:
        raise ValueError("unit must be either 'km' or 'miles'")
    self.unit = unit
    self.earth_radius = 6371.0 if unit == "km" else 3958.8

compatible_dtypes property ¤

compatible_dtypes

Returns the compatible dtypes of the layer.

Returns:

Type Description
Optional[List[str]]

The compatible dtypes of the layer.

compute_haversine_distance ¤

compute_haversine_distance(lat1, lon1, lat2, lon2)

Computes the haversine distance between two lat/lon pairs.

Parameters:

Name Type Description Default
lat1 KerasTensor

Tensor of latitudes of the first point.

required
lon1 KerasTensor

Tensor of longitudes of the first point.

required
lat2 KerasTensor

Tensor of latitudes of the second point.

required
lon2 KerasTensor

Tensor of longitudes of the second point.

required

Returns:

Type Description
KerasTensor

Tensor of haversine distances.

Source code in src/kamae/keras/core/layers/haversine_distance.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def compute_haversine_distance(
    self, lat1: KerasTensor, lon1: KerasTensor, lat2: KerasTensor, lon2: KerasTensor
) -> KerasTensor:
    """
    Computes the haversine distance between two lat/lon pairs.

    :param lat1: Tensor of latitudes of the first point.
    :param lon1: Tensor of longitudes of the first point.
    :param lat2: Tensor of latitudes of the second point.
    :param lon2: Tensor of longitudes of the second point.
    :returns: Tensor of haversine distances.
    """
    lat1_radians = get_radians(lat1)
    lon1_radians = get_radians(lon1)
    lat2_radians = get_radians(lat2)
    lon2_radians = get_radians(lon2)

    lat_diff = lat2_radians - lat1_radians
    lon_diff = lon2_radians - lon1_radians

    a = ops.power(ops.sin(lat_diff / 2.0), 2.0) + ops.cos(lat1_radians) * ops.cos(
        lat2_radians
    ) * ops.power(ops.sin(lon_diff / 2.0), 2.0)
    c = 2.0 * ops.arcsin(ops.power(a, 0.5))
    # Radius of earth in kilometers or miles
    r = ops.convert_to_tensor(self.earth_radius, dtype=c.dtype)
    return c * r

get_config ¤

get_config()

Gets the configuration of the HaversineDistance layer. Used for saving and loading from a model.

Specifically, we add the lat_lon_constant and unit to the config.

Returns:

Type Description
Dict[str, Any]

Dictionary of the configuration of the layer.

Source code in src/kamae/keras/core/layers/haversine_distance.py
150
151
152
153
154
155
156
157
158
159
160
161
def get_config(self) -> Dict[str, Any]:
    """
    Gets the configuration of the HaversineDistance layer.
    Used for saving and loading from a model.

    Specifically, we add the `lat_lon_constant` and `unit` to the config.

    :returns: Dictionary of the configuration of the layer.
    """
    config = super().get_config()
    config.update({"lat_lon_constant": self.lat_lon_constant, "unit": self.unit})
    return config