Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
8 changes: 0 additions & 8 deletions .basedpyright/baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -19113,14 +19113,6 @@
"lineCount": 1
}
},
{
"code": "reportAttributeAccessIssue",
"range": {
"startColumn": 44,
"endColumn": 58,
"lineCount": 1
}
},
{
"code": "reportCallIssue",
"range": {
Expand Down
12 changes: 12 additions & 0 deletions monitoring/uss_qualifier/resources/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,15 @@ Resources for a given test configuration are all declared in a single global res
* Example: `netrid.flight_data.nominal_flights`, which would provide flight data for nominal flights which could be injected into Service Providers under test.
2. Every type of test resource must define a "resource specification", which is a serializable data type that fully defines how to create an instance of that resource type.
3. Every type of test resource must define how to create an instance of the test resource from an instance of the resource specification.


## Resource modifiers

A `ResourceModifier` is a resource that wraps another resource and produces variants of it based on an integer index. This is useful when a test scenario needs multiple unique-but-related instances of a resource (e.g., distinct flights derived from a single base flight).

To use a `ResourceModifier`:

1. Declare it like any other resource, with its `base_resource` dependency pointing to the resource to be modified.
2. When need, call `adjust(index)` to obtain a modified copy of the base resource. Different `index` values produce different (unique) variants; the same `index` produces equivalent results.

The base resource itself remains available as `base_resource` on the modifier.
4 changes: 4 additions & 0 deletions monitoring/uss_qualifier/resources/dev/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
from .noop import NoOpResource as NoOpResource
from .test_exclusions import TestExclusionsResource as TestExclusionsResource
from .test_modifier import TestModifierModifierResource as TestModifierModifierResource
from .test_modifier import TestModifierResource as TestModifierResource
from .test_modifier import TestSquareModifier as TestSquareModifier
from .test_modifier import TestSquareResource as TestSquareResource
104 changes: 104 additions & 0 deletions monitoring/uss_qualifier/resources/dev/test_modifier.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
from implicitdict import ImplicitDict

from monitoring.monitorlib.geo import LatLngBoundingBox
from monitoring.uss_qualifier.resources.modifiers import (
GeospatialModifier,
GeospatialResource,
)
from monitoring.uss_qualifier.resources.resource import Resource, ResourceModifier


class TestModifierSpecification(ImplicitDict):
base_id: int


class TestModifierResource(Resource[TestModifierSpecification]):
"""TestModifierResource is a simple resource returing 10 number, starting from base_id. Used for unit tests."""

_spec: TestModifierSpecification

def __init__(
self,
specification: TestModifierSpecification,
resource_origin: str,
):
super().__init__(specification, resource_origin)
self._spec = specification

def build_ids(self) -> list[int]:
return list(range(self._spec.base_id, self._spec.base_id + 10))


class TestModifierModifierSpecification(ImplicitDict):
shift_interval: int


class TestModifierModifierResource(
ResourceModifier[TestModifierModifierSpecification, TestModifierResource]
):
"""Modifier for a TestModifierResource. Used for unit tests."""

def adjust(self, index: int) -> TestModifierResource:

# 'Clone' the resource with new specs
return TestModifierResource(
TestModifierSpecification(
base_id=self.base_resource._spec.base_id
+ self._spec.shift_interval * index,
),
resource_origin=self.base_resource.resource_origin,
)


class TestSquareSpecification(ImplicitDict):
lat_center: float
lng_center: float


class TestSquareResource(Resource[TestSquareSpecification], GeospatialResource):
"""1km x 1km square centered at (lat_center, lng_center). Used for unit tests."""

SQUARE_SIDE_M = 1000.0

_spec: TestSquareSpecification

def __init__(
self,
specification: TestSquareSpecification,
resource_origin: str,
):
super().__init__(specification, resource_origin)
self._spec = specification

def get_extents(self) -> LatLngBoundingBox:
point = LatLngBoundingBox(
lat_min=self._spec.lat_center,
lat_max=self._spec.lat_center,
lng_min=self._spec.lng_center,
lng_max=self._spec.lng_center,
)
return point.expand(
north_meters=self.SQUARE_SIDE_M / 2,
east_meters=self.SQUARE_SIDE_M / 2,
south_meters=self.SQUARE_SIDE_M / 2,
west_meters=self.SQUARE_SIDE_M / 2,
)

def move(self, meters_east: float, meters_north: float) -> "TestSquareResource":
shifted = self.get_extents().expand(
north_meters=meters_north,
east_meters=meters_east,
south_meters=-meters_north,
west_meters=-meters_east,
)
return TestSquareResource(
TestSquareSpecification(
lat_center=(shifted.lat_min + shifted.lat_max) / 2,
lng_center=(shifted.lng_min + shifted.lng_max) / 2,
),
resource_origin=self.resource_origin,
)


class TestSquareModifier(GeospatialModifier[TestSquareResource]):
pass
45 changes: 45 additions & 0 deletions monitoring/uss_qualifier/resources/modifiers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from abc import ABC, abstractmethod
from math import isqrt
from typing import Self

from implicitdict import ImplicitDict

from monitoring.monitorlib.geo import LatLngBoundingBox, flatten
from monitoring.uss_qualifier.resources.resource import ResourceModifier


class GeospatialResource(ABC):
@abstractmethod
def get_extents(self) -> LatLngBoundingBox:
pass

@abstractmethod
def move(self, meters_east: float, meters_north: float) -> Self:
pass


class GeospatialModifierSpecification(ImplicitDict):
meters_east_margin: float = 1000
meters_north_margin: float = 1000


class GeospatialModifier[GeospatialResourceType: GeospatialResource](
ResourceModifier[GeospatialModifierSpecification, GeospatialResourceType]
):
def adjust(self, index: int) -> GeospatialResourceType:
# Make a grid based on index:
# x ->
# y 0 1 3 6
# | 2 4 7
# v 5 8
# 9
k = (isqrt(1 + 8 * index) - 1) // 2
offset = index - k * (k + 1) // 2
x = k - offset
y = offset

rect = self.base_resource.get_extents().to_latlngrect()
width_m, height_m = flatten(rect.lo(), rect.hi())
width_m += self._spec.meters_east_margin
height_m += self._spec.meters_north_margin
return self.base_resource.move(x * width_m, y * height_m)
59 changes: 59 additions & 0 deletions monitoring/uss_qualifier/resources/modifiers_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import unittest

from monitoring.monitorlib.geo import area_of_latlngrect
from monitoring.uss_qualifier.resources.definitions import (
ResourceDeclaration,
ResourceID,
)
from monitoring.uss_qualifier.resources.dev.test_modifier import (
TestSquareSpecification,
)
from monitoring.uss_qualifier.resources.modifiers import (
GeospatialModifierSpecification,
)
from monitoring.uss_qualifier.resources.resource import create_resources


class TestGeospatialModifier(unittest.TestCase):
def _build_declarations(self) -> dict[ResourceID, ResourceDeclaration]:
return {
"square": ResourceDeclaration(
resource_type="resources.dev.TestSquareResource",
specification=TestSquareSpecification(lat_center=46.5, lng_center=6.5),
),
"square_modifier": ResourceDeclaration(
resource_type="resources.dev.TestSquareModifier",
specification=GeospatialModifierSpecification(),
dependencies={
"base_resource": "square",
},
),
}

def test_overlap_only_for_same_index(self):
resources = create_resources(self._build_declarations(), "test", True)
modifier = resources["square_modifier"]

extents = [modifier.adjust(i).get_extents() for i in range(11)]
square_area = (
resources["square"].SQUARE_SIDE_M * resources["square"].SQUARE_SIDE_M
)

for i in range(11):
for j in range(11):
rect_i = extents[i].to_latlngrect()
rect_j = extents[j].to_latlngrect()
overlap = area_of_latlngrect(rect_i.intersection(rect_j))
if i == j:
assert (
overlap > 0.99 * square_area
), ( # Use 99% to compensate for errors
f"index {i}: self-overlap area {overlap:.2f}m² "
f"expected ~{square_area:.2f}m²"
)
else:
assert (
overlap < 0.01 * square_area
), ( # Use 1% to compensate for errors
f"indices {i},{j}: unexpected overlap area {overlap:.2f}m²"
)
54 changes: 52 additions & 2 deletions monitoring/uss_qualifier/resources/resource.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from abc import ABC
from typing import TypeVar, get_type_hints
from abc import ABC, abstractmethod
from typing import TypeVar, get_args, get_origin, get_type_hints

from implicitdict import ImplicitDict
from loguru import logger
Expand Down Expand Up @@ -43,6 +43,36 @@ def is_type(self, resource_type: str) -> bool:
ResourceType = TypeVar("ResourceType", bound=Resource)


class ResourceModifier[SpecificationType: ImplicitDict, ResourceType](
Resource[SpecificationType], ABC
):
"""A specifc type of resources that can return adjusted an resource that shall unique based on a specifc 'index'.
The underlying resource shall be a dependency named 'base_resource'.

Concrete subclass must implement 'adjust' as needed.
"""

_spec: SpecificationType
base_resource: ResourceType

def __init__(
self,
specification: SpecificationType,
resource_origin: str,
base_resource: ResourceType,
):
super().__init__(specification, resource_origin)
self._spec = specification
self.base_resource = base_resource

@abstractmethod
def adjust(self, index: int) -> ResourceType:
"""
Return a new instance of the base resource, modified to be unique based on 'index' value.
"""
pass


class MissingResourceError(ValueError):
missing_resource_name: str

Expand Down Expand Up @@ -156,6 +186,26 @@ def get_resource_types(
)

constructor_signature = get_type_hints(resource_type.__init__)

# Resolve generic type vars, walking up the inheritance chain
def _collect(cls: type, mapping: dict) -> None:
for base in getattr(cls, "__orig_bases__", ()):
origin = get_origin(base)
if origin is None:
continue
params = getattr(origin, "__parameters__", ())
for param, arg in zip(params, get_args(base)):
resolved = mapping.get(arg, arg)
if not isinstance(resolved, TypeVar):
mapping[param] = resolved
_collect(origin, mapping)

typevar_map: dict = {}
_collect(resource_type, typevar_map)
constructor_signature = {
name: typevar_map.get(t, t) for name, t in constructor_signature.items()
}

specification_type = None
for arg_name, arg_type in constructor_signature.items():
if arg_name == "return":
Expand Down
Loading
Loading