Skip to content
This repository has been archived by the owner on Mar 23, 2024. It is now read-only.

Sensors: Add delay model #75

Open
wants to merge 33 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
3bcfdea
Sensor: Create Sensor parent class and GPS and WindSensor child classes
chrischang5 Nov 4, 2023
6bbdb72
Sensor: Refactor code
chrischang5 Nov 4, 2023
83b105a
Sensor: Implement WindSensor and GPS classes
chrischang5 Nov 18, 2023
ed70153
Sensor: Add tests and code cleanup
chrischang5 Nov 18, 2023
9e53e3e
Bump UBCSailbot/sailbot_workspace from 1.4.2 to 1.4.7 (#55)
dependabot[bot] Nov 9, 2023
c9b9971
Make ubcsailbotsoftware a code owner (#57)
patrick-5546 Nov 11, 2023
6f65c06
Bump UBCSailbot/sailbot_workspace from 1.4.7 to 1.4.8 (#56)
dependabot[bot] Nov 11, 2023
091154a
Make ubcsailbotsoftware code owner only for test.yml (#58)
patrick-5546 Nov 12, 2023
5d999f0
Bump UBCSailbot/sailbot_workspace from 1.4.8 to 1.5.1 (#59)
dependabot[bot] Nov 13, 2023
a57a9c2
Sensor: Ignore redef mypy error
chrischang5 Nov 19, 2023
ba9cd83
Sensor: Create custom type to have cleaner type hinting
chrischang5 Nov 19, 2023
31f458c
Sensors: Complete tests and resolve typing errors
chrischang5 Nov 25, 2023
3dae5ba
Merge branch 'main' into user/chrischang5/53-implement-sensor-class
chrischang5 Nov 25, 2023
65c42e2
Try to make CI happy
chrischang5 Nov 25, 2023
96c9405
Try to make CI happy
chrischang5 Nov 25, 2023
6a63fac
Fix bugs :(
chrischang5 Nov 25, 2023
f8f6a61
Sensor: make syntax consistent
chrischang5 Nov 25, 2023
b11f176
Fix bugs
chrischang5 Nov 26, 2023
893d4b0
Sensors: add docstrings, add support to implicitly or explicitly set …
chrischang5 Dec 7, 2023
a8688fb
Sensors: finish docstrings
chrischang5 Dec 7, 2023
7c92df1
Merge branch 'main' into user/chrischang5/53-implement-sensor-class
chrischang5 Dec 7, 2023
2f6cc27
fixed an oops
chrischang5 Dec 7, 2023
2609bcc
Sensor: Add todo for dimensionality checking
chrischang5 Dec 8, 2023
770df02
Sensors: Complete delay implementation and tests
chrischang5 Feb 25, 2024
17ac1fc
Merge branch 'main' into user/chrischang5/53-implement-sensor-class
chrischang5 Feb 25, 2024
1157a0d
Fix a typo!
chrischang5 Feb 25, 2024
71b8bd5
Make linter happy
chrischang5 Feb 25, 2024
766534c
Update description
chrischang5 Mar 2, 2024
d16d573
Sensors: remove use of queue to delay values
chrischang5 Mar 3, 2024
24c36a4
Sensors: make flake8 happy
chrischang5 Mar 3, 2024
6af4756
Merge branch 'main' into user/chrischang5/53-implement-sensor-class
chrischang5 Mar 8, 2024
0ed0b95
Sensors: Support passing in noisemaker parameters
chrischang5 Mar 8, 2024
8dbe7ca
Sensors: Support passing in noisemaker parameters
chrischang5 Mar 8, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
174 changes: 138 additions & 36 deletions boat_simulator/common/sensors.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,44 @@
from dataclasses import dataclass

from typing import Optional, Any
from typing import Any
from numpy.typing import NDArray
from typing import List
import numpy as np


from boat_simulator.common.types import Scalar, ScalarOrArray

from boat_simulator.common.generators import (
ConstantGenerator,
MVGaussianGenerator,
GaussianGenerator,
)

WindSensorGenerators = Optional[MVGaussianGenerator | ConstantGenerator]
GPSGenerators = Optional[GaussianGenerator | ConstantGenerator]


@dataclass
class Sensor:
"""Interface for sensors in the Boat Simulation."""
"""

Interface for sensors in the Boat Simulation.

Data delay and noise models are supported.

Delay model will delay sensor value updates by one update cycle:
- Sensor has initial data x0 at t = 0
- Sensor provided new data x_1 at t = 1
- Sensor provided new data x_2 at t = 2. At t = 2, x1 is registered into the sensor.
- Sensor provided new data x_i at t = i. At t = i, x_{i-1} is registered into the sensor.

Noise model will add noise to sensor values drawn from a
Gaussian or Multi-variate Gaussian distribution.
"""

def __init__(self, enable_delay: bool = False, enable_noise: bool = False) -> None:
"""

Args:
enable_noise (bool): Enables noise for fields. False by default.
enable_delay (bool): Enables delay for fields. False by default.
"""

self.enable_delay = enable_delay
self.enable_noise = enable_noise

def update(self, **kwargs):
"""
Expand All @@ -29,6 +49,7 @@ def update(self, **kwargs):
Raises:
ValueError: If kwarg is not a defined attribute in Sensor
"""

for attr_name, attr_val in kwargs.items():
if attr_name in self.__annotations__:
setattr(self, attr_name, attr_val)
Expand Down Expand Up @@ -60,98 +81,179 @@ def read(self, key: str) -> Any:
)


@dataclass
class WindSensor(Sensor):
"""
Abstraction for wind sensor.

# TODO: Add delay functions.

Properties:
wind (ScalarOrArray): Wind x, y components or single value
wind_noisemaker (Optional[MVGaussianGenerator | ConstantGenerator]):
Noise function to emulate sensor noise in wind data reading
enable_noise (bool): Enables noise for fields. False by default.
enable_delay (bool): Enables delay for fields. False by default.
"""

wind: ScalarOrArray
wind_noisemaker: WindSensorGenerators = None

def __init__(
self,
wind: ScalarOrArray,
stdev: List[Scalar] = [1.0, 1.0],
enable_noise: bool = False,
enable_delay: bool = False,
) -> None:
super().__init__(enable_noise=enable_noise, enable_delay=enable_delay)
self._wind = wind

# TODO: Refactor the initialization of data fields and their respective delay controls.
# Warning: this is not easy!

self.wind_queue_next: bool = False
self.wind_next_value: ScalarOrArray = wind
self.wind_noisemaker: MVGaussianGenerator = MVGaussianGenerator(
mean=np.array([0, 0]), cov=np.diag(np.power(stdev, 2))
)

@property # type: ignore
def wind(self) -> ScalarOrArray:
# TODO: Ensure attribute value and noisemakers are using the same value shape.
# - wind scalars should add with noise scalars.
# - wind vectors should add with noise vectors.
# Could consider using a __post_init__ function for this

return (
self._wind + self.wind_noisemaker.next() # type: ignore
if self.wind_noisemaker is not None
if self.enable_noise
else self._wind
)

@wind.setter
def wind(self, wind: ScalarOrArray):
self._wind = wind

if not self.enable_delay:
self._wind = wind
return

if self.wind_queue_next:
self._wind = self.wind_next_value
else:
self.wind_queue_next = True

self.wind_next_value = wind


@dataclass
class GPS(Sensor):
"""
Abstraction for GPS.

# TODO: Add delay functions.

Properties:
lat_lon (NDArray): Boat latitude and longitude (2x1 array)
speed (Scalar): Boat speed
heading (Scalar): Boat heading
lat_lon_noisemaker (Optional[GaussianGenerator | ConstantGenerator]):
Noise function to emulate sensor noise in latitude and longitude readings
speed_noisemaker (Optional[GaussianGenerator | ConstantGenerator]):
Noise function to emulate sensor noise in speed readings
heading_noisemaker (Optional[GaussianGenerator | ConstantGenerator]):
Noise function to emulate sensor noise in heading readings
enable_noise (bool): Enables noise for fields. False by default.
enable_delay (bool): Enables delay for fields. False by default.
"""

lat_lon: NDArray
speed: Scalar
heading: Scalar

lat_lon_noisemaker: GPSGenerators = None
speed_noisemaker: GPSGenerators = None
heading_noisemaker: GPSGenerators = None
def __init__(
self,
lat_lon: NDArray,
speed: Scalar,
heading: Scalar,
stdev: Scalar = 1,
chrischang5 marked this conversation as resolved.
Show resolved Hide resolved
enable_noise: bool = False,
enable_delay: bool = False,
):
super().__init__(enable_noise=enable_noise, enable_delay=enable_delay)
self._lat_lon = lat_lon
self._speed = speed
self._heading = heading

# TODO: Refactor the initialization of data fields and their respective delay controls.
# Warning: this is not easy!

# Delay Controls
self.lat_lon_queue_next: bool = False
self.lat_lon_next_value: NDArray = lat_lon

self.speed_queue_next: bool = False
self.speed_next_value: Scalar = speed

self.heading_queue_next: bool = False
self.heading_next_value: Scalar = heading

self.lat_lon_noisemaker: GaussianGenerator = GaussianGenerator(
mean=0, stdev=stdev
)
self.speed_noisemaker: GaussianGenerator = GaussianGenerator(
mean=0, stdev=stdev
)
self.heading_noisemaker: GaussianGenerator = GaussianGenerator(
mean=0, stdev=stdev
)
chrischang5 marked this conversation as resolved.
Show resolved Hide resolved

@property # type: ignore
def lat_lon(self) -> NDArray:
return (
self._lat_lon + self.lat_lon_noisemaker.next()
if self.lat_lon_noisemaker is not None
if self.enable_noise
else self._lat_lon
)

@lat_lon.setter
def lat_lon(self, lat_lon: NDArray):
self._lat_lon = lat_lon

if not self.enable_delay:
self._lat_lon = lat_lon
return

if self.lat_lon_queue_next:
self._lat_lon = self.lat_lon_next_value
else:
self.lat_lon_queue_next = True

self.lat_lon_next_value = lat_lon

@property # type: ignore
def speed(self) -> Scalar:
return (
self._speed + self.speed_noisemaker.next() # type: ignore
if self.speed_noisemaker is not None
if self.enable_noise
else self._speed
)

@speed.setter
def speed(self, speed: Scalar):
self._speed = speed

if not self.enable_delay:
self._speed = speed
return

if self.speed_queue_next:
self._speed = self.speed_next_value
else:
self.speed_queue_next = True

self.speed_next_value = speed

@property # type: ignore
def heading(self) -> Scalar:
return (
self._heading + self.heading_noisemaker.next() # type: ignore
if self.heading_noisemaker is not None
if self.enable_noise
else self._heading
)

@heading.setter
def heading(self, heading: Scalar):
self._heading = heading

if not self.enable_delay:
self._heading = heading
return

if self.heading_queue_next:
self._heading = self.heading_next_value
else:
self.heading_queue_next = True

self.heading_next_value = heading
11 changes: 9 additions & 2 deletions boat_simulator/common/unit_conversions.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,9 @@ class ConversionFactors(Enum):
km_to_nautical_mi = nautical_mi_to_km.inverse()

# Time
sec_to_ms = ConversionFactor(factor=1000)
ms_to_sec = sec_to_ms.inverse()

min_to_sec = ConversionFactor(factor=60)
sec_to_min = min_to_sec.inverse()

Expand Down Expand Up @@ -199,7 +202,9 @@ def __init__(self, **kwargs: EnumAttr):
belonging to `ConversionFactors`.
"""
for attr_name, attr_val in kwargs.items():
assert isinstance(attr_val, Enum) and isinstance(attr_val.value, ConversionFactor)
assert isinstance(attr_val, Enum) and isinstance(
attr_val.value, ConversionFactor
)
setattr(self, attr_name, attr_val)

def convert(self, **kwargs: ScalarOrArray) -> Dict[str, ScalarOrArray]:
Expand All @@ -223,7 +228,9 @@ def convert(self, **kwargs: ScalarOrArray) -> Dict[str, ScalarOrArray]:

for attr_name, attr_val in kwargs.items():
attr = getattr(self, attr_name, None)
assert attr is not None, f"Attribute name {attr} not found in UnitConverter."
assert (
attr is not None
), f"Attribute name {attr} not found in UnitConverter."

conversion_factor = attr.value
converted_values[attr_name] = conversion_factor.forward_convert(attr_val)
Expand Down
Loading