neighborhood: SearchNeighborhood
+neighborhood: SimpleSearchNeighborhood
diff --git a/mkdocs/site/packages/evo-compute/typed-objects/conditioned-simulator/ConSimParameters.html b/mkdocs/site/packages/evo-compute/typed-objects/conditioned-simulator/ConSimParameters.html
index 1f8030f45..4b7c5a384 100644
--- a/mkdocs/site/packages/evo-compute/typed-objects/conditioned-simulator/ConSimParameters.html
+++ b/mkdocs/site/packages/evo-compute/typed-objects/conditioned-simulator/ConSimParameters.html
@@ -221,7 +221,7 @@
neighborhood: SearchNeighborhood
+neighborhood: SimpleSearchNeighborhood
diff --git a/mkdocs/site/packages/evo-compute/typed-objects/search/SearchNeighborhood.html b/mkdocs/site/packages/evo-compute/typed-objects/search/SearchNeighborhood.html
index 530011b4e..c7d52c0a6 100644
--- a/mkdocs/site/packages/evo-compute/typed-objects/search/SearchNeighborhood.html
+++ b/mkdocs/site/packages/evo-compute/typed-objects/search/SearchNeighborhood.html
@@ -39,7 +39,7 @@
-
+
Next
@@ -61,7 +61,7 @@
-
GitHub source
+
GitHub source
@@ -78,8 +78,8 @@
-
- evo.compute.tasks.common.search.SearchNeighborhood
+
+ evo.compute.tasks.geostatistics.search.SearchNeighborhood
@@ -89,16 +89,10 @@
-
-
-
-
-
-
- max_samples
-
-
-
-
max_samples: int = Field(ge=1)
-
-
-
-
-
The maximum number of samples to use for each evaluation point.
-
-
-
-
-
-
-
-
-
-
- min_samples
-
-
-
-
min_samples: int | None = Field(None, ge=1)
-
-
-
-
-
The minimum number of samples required, between 1 and max_samples.
-
If fewer are found, the point may be skipped.
-
-
-
-
-
-
-
-
-
-
+
max_empty_octants
@@ -228,7 +156,7 @@
+
max_samples_per_octant
@@ -248,7 +176,7 @@
+
max_empty_quadrants
@@ -269,7 +197,7 @@
+
max_samples_per_quadrant
@@ -289,7 +217,7 @@
+
max_samples_per_drillhole
@@ -309,7 +237,7 @@
+
max_drillholes
@@ -331,7 +259,7 @@
+
min_drillholes
@@ -344,8 +272,7 @@
The minimum number of distinct drillholes required per estimate.
-
Omitted (disabled) when None or 0. Currently supported only by kriging
-and requires a downhole intervals source object.
+
Omitted (disabled) when None or 0. Requires a downhole intervals source object.
@@ -355,7 +282,7 @@
+
drillhole_limit_scope
@@ -368,8 +295,8 @@ (or None) applies max_samples_per_drillhole across the whole
neighborhood and is omitted on the wire. "quadrant" and "octant" apply
-max_samples_per_drillhole within each sector, require max_samples_per_drillhole
-to be set, and are currently supported only by kriging.
+max_samples_per_drillhole within each sector and require max_samples_per_drillhole
+to be set.
@@ -379,7 +306,7 @@
+
max_drillholes_per_estimate
diff --git a/mkdocs/site/packages/evo-compute/typed-objects/simulation-report/SimReportContext.html b/mkdocs/site/packages/evo-compute/typed-objects/simulation-report/SimReportContext.html
index 735c1d786..42edd8537 100644
--- a/mkdocs/site/packages/evo-compute/typed-objects/simulation-report/SimReportContext.html
+++ b/mkdocs/site/packages/evo-compute/typed-objects/simulation-report/SimReportContext.html
@@ -34,7 +34,7 @@
-
-
+
Previous
diff --git a/mkdocs/site/packages/evo-compute/typed-objects/simulation-report/SimulationReportParameters.html b/mkdocs/site/packages/evo-compute/typed-objects/simulation-report/SimulationReportParameters.html
index dd19a8893..88f03d85e 100644
--- a/mkdocs/site/packages/evo-compute/typed-objects/simulation-report/SimulationReportParameters.html
+++ b/mkdocs/site/packages/evo-compute/typed-objects/simulation-report/SimulationReportParameters.html
@@ -103,7 +103,7 @@ neighborhood: SearchNeighborhood
+neighborhood: SimpleSearchNeighborhood
diff --git a/mkdocs/site/packages/evo-objects/typed-objects/types/Ellipsoid.html b/mkdocs/site/packages/evo-objects/typed-objects/types/Ellipsoid.html
index 862e8aee2..da78adf8d 100644
--- a/mkdocs/site/packages/evo-objects/typed-objects/types/Ellipsoid.html
+++ b/mkdocs/site/packages/evo-objects/typed-objects/types/Ellipsoid.html
@@ -139,6 +139,28 @@
+
+
+
+
+ from_dict
+
+
+
+
from_dict(data: Mapping[str, Any]) -> Ellipsoid
+
+
+
+
+
Construct an :class:Ellipsoid from a wire-shaped mapping.
+
Accepts ellipsoid_ranges (or ranges) and an optional rotation
+mapping whose omitted angles default to 0.
+
+
+
+
+
+
diff --git a/packages/evo-compute/pyproject.toml b/packages/evo-compute/pyproject.toml
index 9a3aadf5c..55aaf12ac 100644
--- a/packages/evo-compute/pyproject.toml
+++ b/packages/evo-compute/pyproject.toml
@@ -10,7 +10,7 @@ authors = [
dependencies = [
"evo-blockmodels[utils]>=0.10.0",
- "evo-objects[utils,blockmodels]>=0.7.0",
+ "evo-objects[utils,blockmodels]>=0.7.1",
"evo-sdk-common>=0.6.0",
"pydantic>=2",
"typing_extensions>=4.0",
diff --git a/packages/evo-compute/src/evo/compute/tasks/__init__.py b/packages/evo-compute/src/evo/compute/tasks/__init__.py
index a3f860014..3bc505622 100644
--- a/packages/evo-compute/src/evo/compute/tasks/__init__.py
+++ b/packages/evo-compute/src/evo/compute/tasks/__init__.py
@@ -52,6 +52,7 @@
FilterCondition,
Rotation,
SearchNeighborhood,
+ SimpleSearchNeighborhood,
Source,
Target,
UpdateAttribute,
@@ -187,6 +188,7 @@ async def run(
"LocationWiseResult",
"Rotation",
"SearchNeighborhood",
+ "SimpleSearchNeighborhood",
"Source",
"Target",
"TaskResultList",
diff --git a/packages/evo-compute/src/evo/compute/tasks/common/__init__.py b/packages/evo-compute/src/evo/compute/tasks/common/__init__.py
index 33b8feb93..e65e7f476 100644
--- a/packages/evo-compute/src/evo/compute/tasks/common/__init__.py
+++ b/packages/evo-compute/src/evo/compute/tasks/common/__init__.py
@@ -17,7 +17,7 @@
from .filters import AllOfFilter, AnyOfFilter, Filter, FilterCondition, FilterExpression, FilterOperator
from .results import TaskAttribute, TaskResultList, TaskTarget
from .runner import TaskRegistry, TaskRunner, TParams, TResult, TResultModel, run_tasks
-from .search import SearchNeighborhood
+from .search import SearchNeighborhood, SimpleSearchNeighborhood
from .source_target import (
AnySourceAttribute,
AnyTargetAttribute,
@@ -47,6 +47,7 @@
"GeoscienceObjectReference",
"Rotation",
"SearchNeighborhood",
+ "SimpleSearchNeighborhood",
"Source",
"TParams",
"TResult",
diff --git a/packages/evo-compute/src/evo/compute/tasks/common/search.py b/packages/evo-compute/src/evo/compute/tasks/common/search.py
index 93ff79e25..87df32d75 100644
--- a/packages/evo-compute/src/evo/compute/tasks/common/search.py
+++ b/packages/evo-compute/src/evo/compute/tasks/common/search.py
@@ -9,357 +9,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-"""Search neighborhood parameters for geostatistical operations."""
+"""Backwards-compatible re-exports for geostatistics search neighborhood models."""
-from __future__ import annotations
-
-from collections.abc import Mapping
-from typing import Annotated, Any, Literal
-
-from evo.objects.typed.types import Ellipsoid, EllipsoidRanges, Rotation
-from pydantic import (
- AliasChoices,
- BaseModel,
- Field,
- PlainSerializer,
- PlainValidator,
- SerializerFunctionWrapHandler,
- WithJsonSchema,
- model_serializer,
- model_validator,
-)
-
-__all__ = [
- "SearchNeighborhood",
-]
-
-_SECTOR_AND_DRILLHOLE_LIMITS = (
- "max_empty_octants",
- "max_samples_per_octant",
- "max_empty_quadrants",
- "max_samples_per_quadrant",
- "max_samples_per_drillhole",
- "max_drillholes",
-)
-
-_ELLIPSOID_JSON_SCHEMA: dict[str, Any] = {
- "type": "object",
- "title": "Ellipsoid",
- "additionalProperties": False,
- "required": ["ellipsoid_ranges", "rotation"],
- "properties": {
- "ellipsoid_ranges": {
- "type": "object",
- "title": "Ellipsoid Ranges",
- "additionalProperties": False,
- "required": ["major", "semi_major", "minor"],
- "properties": {
- "major": {"type": "number", "exclusiveMinimum": 0, "title": "Major"},
- "semi_major": {"type": "number", "exclusiveMinimum": 0, "title": "Semi Major"},
- "minor": {"type": "number", "exclusiveMinimum": 0, "title": "Minor"},
- },
- },
- "rotation": {
- "type": "object",
- "title": "Rotation",
- "additionalProperties": False,
- "properties": {
- "dip_azimuth": {"type": "number", "minimum": 0, "maximum": 360, "default": 0, "title": "Dip Azimuth"},
- "dip": {"type": "number", "minimum": 0, "maximum": 180, "default": 0, "title": "Dip"},
- "pitch": {"type": "number", "minimum": 0, "maximum": 360, "default": 0, "title": "Pitch"},
- },
- },
- },
-}
-
-
-def _parse_ellipsoid_ranges(raw: Any) -> EllipsoidRanges:
- if isinstance(raw, EllipsoidRanges):
- return raw
- if isinstance(raw, Mapping):
- unknown = set(raw) - {"major", "semi_major", "minor"}
- if unknown:
- raise ValueError(f"Unexpected ellipsoid_ranges field(s): {', '.join(sorted(map(str, unknown)))}.")
- missing = {"major", "semi_major", "minor"} - set(raw)
- if missing:
- raise ValueError(f"Missing ellipsoid_ranges field(s): {', '.join(sorted(missing))}.")
- try:
- return EllipsoidRanges(major=raw["major"], semi_major=raw["semi_major"], minor=raw["minor"])
- except TypeError as exc:
- raise ValueError(str(exc)) from exc
- try:
- return EllipsoidRanges.from_array_like(raw)
- except TypeError as exc:
- raise ValueError(str(exc)) from exc
-
-
-def _parse_rotation(raw: Any) -> Rotation | None:
- if raw is None or isinstance(raw, Rotation):
- return raw
- if isinstance(raw, Mapping):
- unknown = set(raw) - {"dip_azimuth", "dip", "pitch"}
- if unknown:
- raise ValueError(f"Unexpected rotation field(s): {', '.join(sorted(map(str, unknown)))}.")
- try:
- return Rotation(
- dip_azimuth=raw["dip_azimuth"] if "dip_azimuth" in raw else 0.0,
- dip=raw["dip"] if "dip" in raw else 0.0,
- pitch=raw["pitch"] if "pitch" in raw else 0.0,
- )
- except TypeError as exc:
- raise ValueError(str(exc)) from exc
- try:
- return Rotation.from_array_like(raw)
- except TypeError as exc:
- raise ValueError(str(exc)) from exc
-
-
-def _validate_ellipsoid(value: Any) -> Ellipsoid:
- if isinstance(value, Ellipsoid):
- return value
- if not isinstance(value, Mapping):
- raise ValueError(f"Expected an Ellipsoid or mapping, got {type(value).__name__}.")
- unknown = set(value) - {"ellipsoid_ranges", "ranges", "rotation"}
- if unknown:
- raise ValueError(f"Unexpected ellipsoid field(s): {', '.join(sorted(map(str, unknown)))}.")
- if "ellipsoid_ranges" not in value and "ranges" not in value:
- raise ValueError("Ellipsoid mapping requires 'ellipsoid_ranges' (or 'ranges').")
- if "ellipsoid_ranges" in value and "ranges" in value:
- wire_ranges = _parse_ellipsoid_ranges(value["ellipsoid_ranges"])
- attr_ranges = _parse_ellipsoid_ranges(value["ranges"])
- if wire_ranges.to_dict() != attr_ranges.to_dict():
- raise ValueError("Conflicting 'ellipsoid_ranges' and 'ranges' values on ellipsoid.")
- ranges = wire_ranges
- elif "ellipsoid_ranges" in value:
- ranges = _parse_ellipsoid_ranges(value["ellipsoid_ranges"])
- else:
- ranges = _parse_ellipsoid_ranges(value["ranges"])
- return Ellipsoid(ranges=ranges, rotation=_parse_rotation(value.get("rotation")))
-
-
-def _serialize_ellipsoid(ellipsoid: Ellipsoid) -> dict[str, Any]:
- return ellipsoid.to_dict()
-
-
-class SearchNeighborhood(BaseModel):
- """Search neighborhood parameters for geostatistical operations.
-
- Defines how to find nearby samples when performing spatial interpolation
- or estimation. Used by kriging, simulation, and other geostatistical tasks.
-
- The search neighborhood is defined by an ellipsoid (spatial extent and
- orientation) and constraints on the number of samples to use.
-
- Kriging, IDW, KNN and declustering can further limit the samples by octant,
- quadrant and drillhole (``max_samples_per_drillhole`` and ``max_drillholes``).
- Kriging additionally supports ``min_drillholes`` and non-global
- ``drillhole_limit_scope``. The other tasks do not support these limits and
- refuse a neighborhood that sets them.
-
- Example::
-
- >>> search = SearchNeighborhood(
- ... ellipsoid=Ellipsoid(
- ... ranges=EllipsoidRanges(major=200.0, semi_major=150.0, minor=100.0),
- ... rotation=Rotation(dip_azimuth=45.0, dip=0.0, pitch=0.0),
- ... ),
- ... max_samples=20,
- ... )
- >>>
- >>> # Octant search, using at most 3 samples from each drillhole across at most 6 drillholes:
- >>> search = SearchNeighborhood(
- ... ellipsoid=Ellipsoid(ranges=EllipsoidRanges(major=200.0, semi_major=150.0, minor=100.0)),
- ... max_samples=24,
- ... max_samples_per_octant=3,
- ... max_empty_octants=4,
- ... max_samples_per_drillhole=3,
- ... max_drillholes=6,
- ... )
- """
-
- ellipsoid: Annotated[
- Ellipsoid,
- PlainValidator(_validate_ellipsoid),
- PlainSerializer(_serialize_ellipsoid),
- WithJsonSchema(_ELLIPSOID_JSON_SCHEMA),
- ]
- """The ellipsoid defining the spatial extent to search for samples."""
-
- max_samples: int = Field(ge=1)
- """The maximum number of samples to use for each evaluation point."""
-
- min_samples: int | None = Field(None, ge=1)
- """The minimum number of samples required, between 1 and ``max_samples``.
-
- If fewer are found, the point may be skipped.
- """
-
- max_empty_octants: int | None = Field(None, ge=0, le=8)
- """The maximum number of empty octants (sectors) allowed when searching for samples.
-
- Omit, or use 8, to disable the octant check.
- """
-
- max_samples_per_octant: int | None = Field(None, ge=1)
- """The maximum number of samples to use from each octant."""
-
- max_empty_quadrants: int | None = Field(None, ge=0, le=4)
- """The maximum number of empty quadrants (2D sectors, ignoring Z) allowed when searching for samples.
-
- Omit, or use 4, to disable the quadrant check.
- """
-
- max_samples_per_quadrant: int | None = Field(None, ge=1)
- """The maximum number of samples to use from each quadrant (2D sectors, ignoring Z)."""
-
- max_samples_per_drillhole: int | None = Field(None, ge=1)
- """The maximum number of samples to use from each drillhole. Requires a downhole intervals source object."""
-
- max_drillholes: int | None = Field(
- None,
- ge=1,
- validation_alias=AliasChoices("max_drillholes", "max_drillholes_per_estimate"),
- )
- """The maximum number of drillholes used in each estimate. Requires a downhole intervals source object."""
-
- min_drillholes: int | None = Field(
- None,
- ge=0,
- validation_alias=AliasChoices("min_drillholes", "min_drillholes_per_estimate"),
- )
- """The minimum number of distinct drillholes required per estimate.
-
- Omitted (disabled) when ``None`` or ``0``. Currently supported only by kriging
- and requires a downhole intervals source object.
- """
-
- drillhole_limit_scope: Literal["global", "quadrant", "octant"] | None = None
- """Scope at which ``max_samples_per_drillhole`` is applied.
-
- ``"global"`` (or ``None``) applies ``max_samples_per_drillhole`` across the whole
- neighborhood and is omitted on the wire. ``"quadrant"`` and ``"octant"`` apply
- ``max_samples_per_drillhole`` within each sector, require ``max_samples_per_drillhole``
- to be set, and are currently supported only by kriging.
- """
-
- @property
- def max_drillholes_per_estimate(self) -> int | None:
- """Backwards-compatible alias for :attr:`max_drillholes`."""
- return self.max_drillholes
-
- @model_validator(mode="before")
- @classmethod
- def _reject_conflicting_aliases(cls, data: Any) -> Any:
- if isinstance(data, Mapping):
- for canonical, legacy in (
- ("max_drillholes", "max_drillholes_per_estimate"),
- ("min_drillholes", "min_drillholes_per_estimate"),
- ):
- if canonical in data and legacy in data and data[canonical] != data[legacy]:
- raise ValueError(
- f"Conflicting values for {canonical!r} ({data[canonical]!r}) and {legacy!r} ({data[legacy]!r})."
- )
- return data
-
- @model_validator(mode="after")
- def _check_sample_limits(self) -> SearchNeighborhood:
- if self.drillhole_limit_scope in ("quadrant", "octant") and self.max_samples_per_drillhole is None:
- raise ValueError(
- f"drillhole_limit_scope={self.drillhole_limit_scope!r} requires max_samples_per_drillhole to be set."
- )
-
- if self.min_drillholes is not None and self.max_drillholes is not None:
- if self.min_drillholes > self.max_drillholes:
- raise ValueError(
- f"min_drillholes ({self.min_drillholes}) cannot exceed max_drillholes ({self.max_drillholes})."
- )
-
- scope_sectors = {"quadrant": 4, "octant": 8}.get(self.drillhole_limit_scope or "global", 1)
- sample_ceilings: list[tuple[int, str]] = [(self.max_samples, f"max_samples ({self.max_samples})")]
- if self.max_samples_per_octant is not None:
- octant_ceiling = 8 * self.max_samples_per_octant
- sample_ceilings.append((octant_ceiling, f"8 * max_samples_per_octant ({octant_ceiling})"))
- if self.max_samples_per_quadrant is not None:
- quadrant_ceiling = 4 * self.max_samples_per_quadrant
- sample_ceilings.append((quadrant_ceiling, f"4 * max_samples_per_quadrant ({quadrant_ceiling})"))
- if self.max_drillholes is not None and self.max_samples_per_drillhole is not None:
- drillhole_ceiling = self.max_drillholes * self.max_samples_per_drillhole * scope_sectors
- if scope_sectors == 1:
- label = f"max_drillholes * max_samples_per_drillhole ({drillhole_ceiling})"
- else:
- label = (
- f"max_drillholes * max_samples_per_drillhole * {scope_sectors} "
- f"({self.drillhole_limit_scope} sectors = {drillhole_ceiling})"
- )
- sample_ceilings.append((drillhole_ceiling, label))
-
- if self.min_samples is not None:
- for ceiling, label in sample_ceilings:
- if self.min_samples > ceiling:
- raise ValueError(f"min_samples ({self.min_samples}) cannot exceed {label}.")
-
- if self.min_drillholes is not None and self.min_drillholes > 0:
- for ceiling, label in sample_ceilings:
- if self.min_drillholes > ceiling:
- raise ValueError(f"min_drillholes ({self.min_drillholes}) cannot exceed {label}.")
-
- if self.max_empty_octants is not None:
- required_octants = 8 - self.max_empty_octants
- for ceiling, label in sample_ceilings:
- if required_octants > ceiling:
- raise ValueError(
- f"max_empty_octants={self.max_empty_octants} requires at least {required_octants} "
- f"occupied octants, which exceeds {label}."
- )
-
- if self.max_empty_quadrants is not None:
- required_quadrants = 4 - self.max_empty_quadrants
- for ceiling, label in sample_ceilings:
- if required_quadrants > ceiling:
- raise ValueError(
- f"max_empty_quadrants={self.max_empty_quadrants} requires at least {required_quadrants} "
- f"occupied quadrants, which exceeds {label}."
- )
-
- return self
-
- @model_serializer(mode="wrap")
- def _serialize(self, handler: SerializerFunctionWrapHandler):
- return {
- key: value
- for key, value in handler(self).items()
- if value is not None
- and not (key == "min_drillholes" and value == 0)
- and not (key == "drillhole_limit_scope" and value == "global")
- }
-
-
-def _active_kriging_only_drillhole_limits(neighborhood: SearchNeighborhood) -> list[str]:
- limits: list[str] = []
- if neighborhood.min_drillholes is not None and neighborhood.min_drillholes > 0:
- limits.append("min_drillholes")
- if neighborhood.drillhole_limit_scope not in (None, "global"):
- limits.append("drillhole_limit_scope")
- return limits
-
-
-def _reject_sector_and_drillhole_limits(neighborhood: SearchNeighborhood) -> SearchNeighborhood:
- """Refuse octant, quadrant and drillhole limits, for tasks whose service does not accept them."""
- limits = [name for name in _SECTOR_AND_DRILLHOLE_LIMITS if getattr(neighborhood, name) is not None]
- limits.extend(_active_kriging_only_drillhole_limits(neighborhood))
- if limits:
- raise ValueError(
- f"This task does not support {', '.join(limits)}. "
- "Octant, quadrant and drillhole limits are only available for kriging, IDW, KNN and declustering."
- )
- return neighborhood
-
-
-def _reject_kriging_only_drillhole_limits(neighborhood: SearchNeighborhood) -> SearchNeighborhood:
- """Refuse drillhole limits that are only supported by the kriging task."""
- if limits := _active_kriging_only_drillhole_limits(neighborhood):
- raise ValueError(
- f"This task does not support {', '.join(limits)}. "
- "min_drillholes and non-global drillhole_limit_scope are only supported by Kriging."
- )
- return neighborhood
+from ..geostatistics.search import SearchNeighborhood, SimpleSearchNeighborhood # noqa: F401
diff --git a/packages/evo-compute/src/evo/compute/tasks/geostatistics/__init__.py b/packages/evo-compute/src/evo/compute/tasks/geostatistics/__init__.py
index d8896dfd4..e372a8604 100644
--- a/packages/evo-compute/src/evo/compute/tasks/geostatistics/__init__.py
+++ b/packages/evo-compute/src/evo/compute/tasks/geostatistics/__init__.py
@@ -63,6 +63,7 @@
KrigingResult,
)
from .location_wise import LocationWiseResult
+from .search import SearchNeighborhood, SimpleSearchNeighborhood
__all__ = [
"BlockDiscretization",
@@ -75,4 +76,6 @@
"KrigingDiagnostics",
"KrigingResult",
"LocationWiseResult",
+ "SearchNeighborhood",
+ "SimpleSearchNeighborhood",
]
diff --git a/packages/evo-compute/src/evo/compute/tasks/geostatistics/break_ties.py b/packages/evo-compute/src/evo/compute/tasks/geostatistics/break_ties.py
index 7d70edfab..c0b50362c 100644
--- a/packages/evo-compute/src/evo/compute/tasks/geostatistics/break_ties.py
+++ b/packages/evo-compute/src/evo/compute/tasks/geostatistics/break_ties.py
@@ -17,13 +17,13 @@
Example::
- >>> from evo.compute.tasks import run, SearchNeighborhood, Ellipsoid, EllipsoidRanges
+ >>> from evo.compute.tasks import run, SimpleSearchNeighborhood, Ellipsoid, EllipsoidRanges
>>> from evo.compute.tasks.geostatistics.break_ties import BreakTiesParameters
>>>
>>> params = BreakTiesParameters(
... source=pointset.attributes["grade"],
... target=Target.new_attribute(pointset, "grade_tiebroken"),
- ... neighborhood=SearchNeighborhood(
+ ... neighborhood=SimpleSearchNeighborhood(
... ellipsoid=Ellipsoid(ranges=EllipsoidRanges(200, 150, 100)),
... max_samples=20,
... ),
@@ -39,16 +39,15 @@
from evo.common import IContext, IFeedback
from evo.objects import ObjectSchema
from evo.objects.typed import BaseObject, object_from_reference
-from pydantic import BaseModel, field_validator
+from pydantic import BaseModel
from ..common import (
AnySourceAttribute,
AnyTargetAttribute,
- SearchNeighborhood,
)
from ..common.results import TaskTarget
from ..common.runner import TaskRunner
-from ..common.search import _reject_sector_and_drillhole_limits
+from .search import SimpleSearchNeighborhood
__all__ = [
"BreakTiesParameters",
@@ -70,13 +69,13 @@ class BreakTiesParameters(BaseModel):
Example::
- >>> from evo.compute.tasks import run, SearchNeighborhood, Ellipsoid, EllipsoidRanges, Target
+ >>> from evo.compute.tasks import run, SimpleSearchNeighborhood, Ellipsoid, EllipsoidRanges, Target
>>> from evo.compute.tasks.geostatistics.break_ties import BreakTiesParameters
>>>
>>> params = BreakTiesParameters(
... source=pointset.attributes["grade"],
... target=Target.new_attribute(pointset, "grade_tiebroken"),
- ... neighborhood=SearchNeighborhood(
+ ... neighborhood=SimpleSearchNeighborhood(
... ellipsoid=Ellipsoid(ranges=EllipsoidRanges(200, 150, 100)),
... max_samples=20,
... ),
@@ -90,7 +89,7 @@ class BreakTiesParameters(BaseModel):
target: AnyTargetAttribute
"""The target object and attribute to create or update with tie-broken results."""
- neighborhood: SearchNeighborhood
+ neighborhood: SimpleSearchNeighborhood
"""Search neighborhood parameters.
In this break-ties algorithm, the final value of each tied point is influenced
@@ -100,11 +99,6 @@ class BreakTiesParameters(BaseModel):
seed: int = 38239342
"""Seed for the random number generator."""
- @field_validator("neighborhood")
- @classmethod
- def _check_neighborhood(cls, neighborhood: SearchNeighborhood) -> SearchNeighborhood:
- return _reject_sector_and_drillhole_limits(neighborhood)
-
# =============================================================================
# Break Ties Result Types
diff --git a/packages/evo-compute/src/evo/compute/tasks/geostatistics/conditional_turning_bands.py b/packages/evo-compute/src/evo/compute/tasks/geostatistics/conditional_turning_bands.py
index aab4196ef..71178656d 100644
--- a/packages/evo-compute/src/evo/compute/tasks/geostatistics/conditional_turning_bands.py
+++ b/packages/evo-compute/src/evo/compute/tasks/geostatistics/conditional_turning_bands.py
@@ -20,7 +20,7 @@
Example::
- >>> from evo.compute.tasks import run, SearchNeighborhood, Ellipsoid, EllipsoidRanges
+ >>> from evo.compute.tasks import run, SimpleSearchNeighborhood, Ellipsoid, EllipsoidRanges
>>> from evo.compute.tasks.geostatistics.conditioned_simulator import BlockDiscretization
>>> from evo.compute.tasks.geostatistics.conditional_turning_bands import (
... ConditionalTurningBandsParameters,
@@ -32,7 +32,7 @@
... target=grid,
... distribution=distribution_object,
... variogram_model=variogram,
- ... neighborhood=SearchNeighborhood(
+ ... neighborhood=SimpleSearchNeighborhood(
... ellipsoid=Ellipsoid(ranges=EllipsoidRanges(70, 70, 5)),
... max_samples=40,
... ),
@@ -50,18 +50,17 @@
from evo.common import IContext, IFeedback
from evo.objects import ObjectSchema
from evo.objects.typed import BaseObject, object_from_reference
-from pydantic import BaseModel, Field, field_validator
+from pydantic import BaseModel, Field
from ..common import (
AttributeExpression,
Filter,
GeoscienceObjectReference,
- SearchNeighborhood,
)
from ..common.results import TaskAttribute
from ..common.runner import TaskRunner
-from ..common.search import _reject_sector_and_drillhole_limits
from .conditioned_simulator import BlockDiscretization
+from .search import SimpleSearchNeighborhood
__all__ = [
"BlockDiscretization",
@@ -94,7 +93,7 @@ class ConditionalTurningBandsParameters(BaseModel):
... target=grid,
... distribution=distribution_object,
... variogram_model=variogram,
- ... neighborhood=SearchNeighborhood(
+ ... neighborhood=SimpleSearchNeighborhood(
... ellipsoid=Ellipsoid(ranges=EllipsoidRanges(70, 70, 5)),
... max_samples=40,
... ),
@@ -119,7 +118,7 @@ class ConditionalTurningBandsParameters(BaseModel):
source_filter: Filter | None = None
"""Optional filter restricting conditioning to a subset of the source data."""
- neighborhood: SearchNeighborhood
+ neighborhood: SimpleSearchNeighborhood
"""Search neighbourhood used both for simulation and for the conditioning kriging step."""
distribution: GeoscienceObjectReference
@@ -164,11 +163,6 @@ class ConditionalTurningBandsParameters(BaseModel):
random_seed: int = 38239342
"""Random seed for reproducible simulations."""
- @field_validator("neighborhood")
- @classmethod
- def _check_neighborhood(cls, neighborhood: SearchNeighborhood) -> SearchNeighborhood:
- return _reject_sector_and_drillhole_limits(neighborhood)
-
# =============================================================================
# Result Types
diff --git a/packages/evo-compute/src/evo/compute/tasks/geostatistics/conditioned_simulator.py b/packages/evo-compute/src/evo/compute/tasks/geostatistics/conditioned_simulator.py
index 2b66f7fe3..8803e2987 100644
--- a/packages/evo-compute/src/evo/compute/tasks/geostatistics/conditioned_simulator.py
+++ b/packages/evo-compute/src/evo/compute/tasks/geostatistics/conditioned_simulator.py
@@ -18,7 +18,7 @@
Example::
- >>> from evo.compute.tasks import run
+ >>> from evo.compute.tasks import SimpleSearchNeighborhood, run
>>> from evo.compute.tasks.geostatistics.conditioned_simulator import (
... ConSimParameters,
... BlockDiscretization,
@@ -29,7 +29,7 @@
... source_attribute=pointset.attributes["grade"],
... target_object=grid,
... variogram_model=variogram,
- ... neighborhood=SearchNeighborhood(
+ ... neighborhood=SimpleSearchNeighborhood(
... ellipsoid=Ellipsoid(ranges=EllipsoidRanges(300, 200, 100)),
... max_samples=24,
... ),
@@ -47,7 +47,7 @@
from evo.common import IContext, IFeedback
from evo.objects import ObjectSchema
from evo.objects.typed import BaseObject, object_from_reference
-from pydantic import BaseModel, Field, field_validator
+from pydantic import BaseModel, Field
from ..common import (
AttributeExpression,
@@ -55,12 +55,11 @@
CreateAttribute,
Filter,
GeoscienceObjectReference,
- SearchNeighborhood,
UpdateAttribute,
)
from ..common.results import TaskAttribute
from ..common.runner import TaskRunner
-from ..common.search import _reject_sector_and_drillhole_limits
+from .search import SimpleSearchNeighborhood
__all__ = [
"BlockDiscretization",
@@ -185,7 +184,7 @@ class ConSimParameters(BaseModel):
source_filter: Filter | None = None
"""Optional filter restricting conditioning to a subset of the source data."""
- neighborhood: SearchNeighborhood
+ neighborhood: SimpleSearchNeighborhood
"""Search neighborhood for conditioning."""
variogram_model: GeoscienceObjectReference
@@ -233,11 +232,6 @@ class ConSimParameters(BaseModel):
report_mean_thresholds: ReportMeanThresholds | None = None
"""Optional thresholds for mean comparison in the validation report."""
- @field_validator("neighborhood")
- @classmethod
- def _check_neighborhood(cls, neighborhood: SearchNeighborhood) -> SearchNeighborhood:
- return _reject_sector_and_drillhole_limits(neighborhood)
-
# =============================================================================
# Result Types
diff --git a/packages/evo-compute/src/evo/compute/tasks/geostatistics/declustering.py b/packages/evo-compute/src/evo/compute/tasks/geostatistics/declustering.py
index 5c0cc6654..a5f6154fa 100644
--- a/packages/evo-compute/src/evo/compute/tasks/geostatistics/declustering.py
+++ b/packages/evo-compute/src/evo/compute/tasks/geostatistics/declustering.py
@@ -61,17 +61,16 @@
from evo.common import IContext, IFeedback
from evo.objects import ObjectSchema
from evo.objects.typed import BaseObject, object_from_reference
-from pydantic import BaseModel, BeforeValidator, Field, SerializerFunctionWrapHandler, field_validator, model_serializer
+from pydantic import BaseModel, BeforeValidator, Field, SerializerFunctionWrapHandler, model_serializer
from ..common import (
AnyTargetAttribute,
GeoscienceObjectReference,
- SearchNeighborhood,
)
from ..common.results import TaskTarget
from ..common.runner import TaskRunner
-from ..common.search import _reject_kriging_only_drillhole_limits
from ..common.source_target import _convert_object_reference
+from .search import SearchNeighborhood
__all__ = [
"DeclusteringParameters",
@@ -172,11 +171,6 @@ class DeclusteringParameters(BaseModel):
Default is ``2.0`` (standard IDW). Must be positive when provided.
"""
- @field_validator("neighborhood")
- @classmethod
- def _check_neighborhood(cls, neighborhood: SearchNeighborhood) -> SearchNeighborhood:
- return _reject_kriging_only_drillhole_limits(neighborhood)
-
@model_serializer(mode="wrap")
def _serialize(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
result = handler(self)
diff --git a/packages/evo-compute/src/evo/compute/tasks/geostatistics/idw.py b/packages/evo-compute/src/evo/compute/tasks/geostatistics/idw.py
index b33b12b77..89f68ef39 100644
--- a/packages/evo-compute/src/evo/compute/tasks/geostatistics/idw.py
+++ b/packages/evo-compute/src/evo/compute/tasks/geostatistics/idw.py
@@ -42,17 +42,16 @@
from evo.common import IContext, IFeedback
from evo.objects import ObjectSchema
from evo.objects.typed import BaseObject, object_from_reference
-from pydantic import BaseModel, Field, SerializerFunctionWrapHandler, field_validator, model_serializer
+from pydantic import BaseModel, Field, SerializerFunctionWrapHandler, model_serializer
from ..common import (
AnySourceAttribute,
AnyTargetAttribute,
Filter,
- SearchNeighborhood,
)
from ..common.results import TaskTarget
from ..common.runner import TaskRunner
-from ..common.search import _reject_kriging_only_drillhole_limits
+from .search import SearchNeighborhood
__all__ = [
"IDWParameters",
@@ -135,11 +134,6 @@ class IDWParameters(BaseModel):
``target["filter"]`` by the custom serialiser.
"""
- @field_validator("neighborhood")
- @classmethod
- def _check_neighborhood(cls, neighborhood: SearchNeighborhood) -> SearchNeighborhood:
- return _reject_kriging_only_drillhole_limits(neighborhood)
-
@model_serializer(mode="wrap")
def _serialize(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
result = handler(self)
diff --git a/packages/evo-compute/src/evo/compute/tasks/geostatistics/knn.py b/packages/evo-compute/src/evo/compute/tasks/geostatistics/knn.py
index 32dd286f9..24aebfc17 100644
--- a/packages/evo-compute/src/evo/compute/tasks/geostatistics/knn.py
+++ b/packages/evo-compute/src/evo/compute/tasks/geostatistics/knn.py
@@ -40,17 +40,16 @@
from evo.common import IContext, IFeedback
from evo.objects import ObjectSchema
from evo.objects.typed import BaseObject, object_from_reference
-from pydantic import BaseModel, Field, SerializerFunctionWrapHandler, field_validator, model_serializer
+from pydantic import BaseModel, Field, SerializerFunctionWrapHandler, model_serializer
from ..common import (
AnySourceAttribute,
AnyTargetAttribute,
Filter,
- SearchNeighborhood,
)
from ..common.results import TaskTarget
from ..common.runner import TaskRunner
-from ..common.search import _reject_kriging_only_drillhole_limits
+from .search import SearchNeighborhood
__all__ = [
"KNNParameters",
@@ -123,11 +122,6 @@ class KNNParameters(BaseModel):
``target["filter"]`` by the custom serialiser.
"""
- @field_validator("neighborhood")
- @classmethod
- def _check_neighborhood(cls, neighborhood: SearchNeighborhood) -> SearchNeighborhood:
- return _reject_kriging_only_drillhole_limits(neighborhood)
-
@model_serializer(mode="wrap")
def _serialize(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
result = handler(self)
diff --git a/packages/evo-compute/src/evo/compute/tasks/geostatistics/kriging.py b/packages/evo-compute/src/evo/compute/tasks/geostatistics/kriging.py
index fb03cefe3..3048cf7e6 100644
--- a/packages/evo-compute/src/evo/compute/tasks/geostatistics/kriging.py
+++ b/packages/evo-compute/src/evo/compute/tasks/geostatistics/kriging.py
@@ -62,13 +62,13 @@
CreateAttribute,
Filter,
GeoscienceObjectReference,
- SearchNeighborhood,
UpdateAttribute,
attribute_spec,
)
from ..common.results import TaskAttribute, TaskTarget
from ..common.runner import TaskRunner
from ..common.source_target import AnyTypedAttribute
+from .search import SearchNeighborhood
__all__ = [
# Kriging-specific (users import from evo.compute.tasks.kriging)
diff --git a/packages/evo-compute/src/evo/compute/tasks/geostatistics/search.py b/packages/evo-compute/src/evo/compute/tasks/geostatistics/search.py
new file mode 100644
index 000000000..215a60891
--- /dev/null
+++ b/packages/evo-compute/src/evo/compute/tasks/geostatistics/search.py
@@ -0,0 +1,266 @@
+# Copyright © 2025 Bentley Systems, Incorporated
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Search neighborhood models for geostatistics compute tasks."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, Literal, Self
+
+from evo.objects.typed.types import Ellipsoid
+from pydantic import (
+ AliasChoices,
+ BaseModel,
+ ConfigDict,
+ Field,
+ SerializerFunctionWrapHandler,
+ ValidatorFunctionWrapHandler,
+ model_serializer,
+ model_validator,
+)
+
+__all__ = [
+ "SearchNeighborhood",
+ "SimpleSearchNeighborhood",
+]
+
+
+class SimpleSearchNeighborhood(BaseModel):
+ """Basic search neighborhood with spatial ellipsoid and sample count bounds.
+
+ Used by geostatistics tasks whose search accepts only an ellipsoid and
+ overall ``min_samples`` / ``max_samples`` bounds (such as simulation and
+ spatial tie-breaking tasks).
+
+ Example::
+
+ >>> neighborhood = SimpleSearchNeighborhood(
+ ... ellipsoid=Ellipsoid(
+ ... ranges=EllipsoidRanges(major=200.0, semi_major=150.0, minor=100.0),
+ ... rotation=Rotation(dip_azimuth=45.0, dip=0.0, pitch=0.0),
+ ... ),
+ ... max_samples=20,
+ ... )
+ """
+
+ model_config = ConfigDict(extra="forbid")
+
+ ellipsoid: Ellipsoid
+ """The ellipsoid defining the spatial extent to search for samples."""
+
+ max_samples: int = Field(ge=1)
+ """The maximum number of samples to use for each evaluation point."""
+
+ min_samples: int | None = Field(None, ge=1)
+ """The minimum number of samples required, between 1 and ``max_samples``.
+
+ If fewer are found, the point may be skipped.
+ """
+
+ @model_validator(mode="wrap")
+ @classmethod
+ def _enforce_exact_tier(cls, data: Any, handler: ValidatorFunctionWrapHandler) -> Self:
+ if isinstance(data, SimpleSearchNeighborhood) and type(data) is not cls:
+ return handler(data.model_dump())
+ return handler(data)
+
+ @model_validator(mode="after")
+ def _check_sample_limits(self) -> Self:
+ if self.min_samples is not None and self.min_samples > self.max_samples:
+ raise ValueError(f"min_samples ({self.min_samples}) cannot exceed max_samples ({self.max_samples}).")
+ return self
+
+ @model_serializer(mode="wrap")
+ def _serialize(self, handler: SerializerFunctionWrapHandler):
+ return {key: value for key, value in handler(self).items() if value is not None}
+
+
+class SearchNeighborhood(SimpleSearchNeighborhood):
+ """Extended search neighborhood with octant, quadrant, and drillhole controls.
+
+ Extends :class:`SimpleSearchNeighborhood` with sector (octant / quadrant)
+ and drillhole quotas for estimation and declustering tasks (Kriging, IDW,
+ KNN, and Declustering).
+
+ Example::
+
+ >>> search = SearchNeighborhood(
+ ... ellipsoid=Ellipsoid(
+ ... ranges=EllipsoidRanges(major=200.0, semi_major=150.0, minor=100.0),
+ ... rotation=Rotation(dip_azimuth=45.0, dip=0.0, pitch=0.0),
+ ... ),
+ ... max_samples=20,
+ ... )
+ >>>
+ >>> # Octant search, using at most 3 samples from each drillhole across at most 6 drillholes:
+ >>> search = SearchNeighborhood(
+ ... ellipsoid=Ellipsoid(ranges=EllipsoidRanges(major=200.0, semi_major=150.0, minor=100.0)),
+ ... max_samples=24,
+ ... max_samples_per_octant=3,
+ ... max_empty_octants=4,
+ ... max_samples_per_drillhole=3,
+ ... max_drillholes=6,
+ ... )
+ """
+
+ max_empty_octants: int | None = Field(None, ge=0, le=8)
+ """The maximum number of empty octants (sectors) allowed when searching for samples.
+
+ Omit, or use 8, to disable the octant check.
+ """
+
+ max_samples_per_octant: int | None = Field(None, ge=1)
+ """The maximum number of samples to use from each octant."""
+
+ max_empty_quadrants: int | None = Field(None, ge=0, le=4)
+ """The maximum number of empty quadrants (2D sectors, ignoring Z) allowed when searching for samples.
+
+ Omit, or use 4, to disable the quadrant check.
+ """
+
+ max_samples_per_quadrant: int | None = Field(None, ge=1)
+ """The maximum number of samples to use from each quadrant (2D sectors, ignoring Z)."""
+
+ max_samples_per_drillhole: int | None = Field(None, ge=1)
+ """The maximum number of samples to use from each drillhole. Requires a downhole intervals source object."""
+
+ max_drillholes: int | None = Field(
+ None,
+ ge=1,
+ validation_alias=AliasChoices("max_drillholes", "max_drillholes_per_estimate"),
+ )
+ """The maximum number of drillholes used in each estimate. Requires a downhole intervals source object."""
+
+ min_drillholes: int | None = Field(
+ None,
+ ge=0,
+ validation_alias=AliasChoices("min_drillholes", "min_drillholes_per_estimate"),
+ )
+ """The minimum number of distinct drillholes required per estimate.
+
+ Omitted (disabled) when ``None`` or ``0``. Requires a downhole intervals source object.
+ """
+
+ drillhole_limit_scope: Literal["global", "quadrant", "octant"] | None = None
+ """Scope at which ``max_samples_per_drillhole`` is applied.
+
+ ``"global"`` (or ``None``) applies ``max_samples_per_drillhole`` across the whole
+ neighborhood and is omitted on the wire. ``"quadrant"`` and ``"octant"`` apply
+ ``max_samples_per_drillhole`` within each sector and require ``max_samples_per_drillhole``
+ to be set.
+ """
+
+ @property
+ def max_drillholes_per_estimate(self) -> int | None:
+ """Backwards-compatible alias for :attr:`max_drillholes`."""
+ return self.max_drillholes
+
+ @model_validator(mode="before")
+ @classmethod
+ def _normalize_legacy_aliases(cls, data: Any) -> Any:
+ if isinstance(data, Mapping):
+ normalized: dict[str, Any] | None = None
+ for canonical, legacy in (
+ ("max_drillholes", "max_drillholes_per_estimate"),
+ ("min_drillholes", "min_drillholes_per_estimate"),
+ ):
+ if canonical in data and legacy in data:
+ if data[canonical] != data[legacy]:
+ raise ValueError(
+ f"Conflicting values for {canonical!r} ({data[canonical]!r}) "
+ f"and {legacy!r} ({data[legacy]!r})."
+ )
+ if normalized is None:
+ normalized = dict(data)
+ normalized.pop(legacy, None)
+ if normalized is not None:
+ return normalized
+ return data
+
+ @model_validator(mode="after")
+ def _check_extended_limits(self) -> Self:
+ if self.drillhole_limit_scope in ("quadrant", "octant") and self.max_samples_per_drillhole is None:
+ raise ValueError(
+ f"drillhole_limit_scope={self.drillhole_limit_scope!r} requires max_samples_per_drillhole to be set."
+ )
+
+ if self.min_drillholes is not None and self.max_drillholes is not None:
+ if self.min_drillholes > self.max_drillholes:
+ raise ValueError(
+ f"min_drillholes ({self.min_drillholes}) cannot exceed max_drillholes ({self.max_drillholes})."
+ )
+
+ match self.drillhole_limit_scope:
+ case "quadrant":
+ scope_sectors = 4
+ case "octant":
+ scope_sectors = 8
+ case _:
+ scope_sectors = 1
+
+ sample_ceilings: list[tuple[int, str]] = [(self.max_samples, f"max_samples ({self.max_samples})")]
+ if self.max_samples_per_octant is not None:
+ octant_ceiling = 8 * self.max_samples_per_octant
+ sample_ceilings.append((octant_ceiling, f"8 * max_samples_per_octant ({octant_ceiling})"))
+ if self.max_samples_per_quadrant is not None:
+ quadrant_ceiling = 4 * self.max_samples_per_quadrant
+ sample_ceilings.append((quadrant_ceiling, f"4 * max_samples_per_quadrant ({quadrant_ceiling})"))
+ if self.max_drillholes is not None and self.max_samples_per_drillhole is not None:
+ drillhole_ceiling = self.max_drillholes * self.max_samples_per_drillhole * scope_sectors
+ if scope_sectors == 1:
+ label = f"max_drillholes * max_samples_per_drillhole ({drillhole_ceiling})"
+ else:
+ label = (
+ f"max_drillholes * max_samples_per_drillhole * {scope_sectors} "
+ f"({self.drillhole_limit_scope} sectors = {drillhole_ceiling})"
+ )
+ sample_ceilings.append((drillhole_ceiling, label))
+
+ if self.min_samples is not None:
+ for ceiling, label in sample_ceilings:
+ if self.min_samples > ceiling:
+ raise ValueError(f"min_samples ({self.min_samples}) cannot exceed {label}.")
+
+ if self.min_drillholes is not None and self.min_drillholes > 0:
+ for ceiling, label in sample_ceilings:
+ if self.min_drillholes > ceiling:
+ raise ValueError(f"min_drillholes ({self.min_drillholes}) cannot exceed {label}.")
+
+ if self.max_empty_octants is not None:
+ required_octants = 8 - self.max_empty_octants
+ for ceiling, label in sample_ceilings:
+ if required_octants > ceiling:
+ raise ValueError(
+ f"max_empty_octants={self.max_empty_octants} requires at least {required_octants} "
+ f"occupied octants, which exceeds {label}."
+ )
+
+ if self.max_empty_quadrants is not None:
+ required_quadrants = 4 - self.max_empty_quadrants
+ for ceiling, label in sample_ceilings:
+ if required_quadrants > ceiling:
+ raise ValueError(
+ f"max_empty_quadrants={self.max_empty_quadrants} requires at least {required_quadrants} "
+ f"occupied quadrants, which exceeds {label}."
+ )
+
+ return self
+
+ @model_serializer(mode="wrap")
+ def _serialize(self, handler: SerializerFunctionWrapHandler):
+ return {
+ key: value
+ for key, value in handler(self).items()
+ if value is not None
+ and not (key == "min_drillholes" and value == 0)
+ and not (key == "drillhole_limit_scope" and value == "global")
+ }
diff --git a/packages/evo-compute/src/evo/compute/tasks/geostatistics/simulation_report.py b/packages/evo-compute/src/evo/compute/tasks/geostatistics/simulation_report.py
index 580c20aa0..25f9fffbc 100644
--- a/packages/evo-compute/src/evo/compute/tasks/geostatistics/simulation_report.py
+++ b/packages/evo-compute/src/evo/compute/tasks/geostatistics/simulation_report.py
@@ -21,7 +21,7 @@
Example::
- >>> from evo.compute.tasks import run, SearchNeighborhood
+ >>> from evo.compute.tasks import run, SimpleSearchNeighborhood
>>> from evo.compute.tasks.geostatistics.simulation_report import (
... SimulationReportParameters,
... SimulationReportBlockDiscretization,
@@ -36,7 +36,7 @@
... block_simulations=grid.attributes["block_sims"],
... block_simulations_normal_score=grid.attributes["block_sims_ns"],
... variogram_model=variogram_url,
- ... neighborhood=SearchNeighborhood(...),
+ ... neighborhood=SimpleSearchNeighborhood(...),
... block_discretization=SimulationReportBlockDiscretization(nx=2, ny=2, nz=2),
... number_of_simulations=50,
... random_seed=38239342,
@@ -49,16 +49,15 @@
from typing import ClassVar, Literal
from evo.common import IContext
-from pydantic import BaseModel, Field, field_validator
+from pydantic import BaseModel, Field
from ..common import (
AttributeExpression,
GeoscienceObjectReference,
- SearchNeighborhood,
)
from ..common.runner import TaskRunner
-from ..common.search import _reject_sector_and_drillhole_limits
from .conditioned_simulator import TailExtrapolationParams
+from .search import SimpleSearchNeighborhood
__all__ = [
"SimReportContext",
@@ -167,7 +166,7 @@ class SimulationReportParameters(BaseModel):
... block_simulations=grid.attributes["block_sims"],
... block_simulations_normal_score=grid.attributes["block_sims_ns"],
... variogram_model=variogram_url,
- ... neighborhood=SearchNeighborhood(...),
+ ... neighborhood=SimpleSearchNeighborhood(...),
... number_of_simulations=50,
... random_seed=38239342,
... )
@@ -198,7 +197,7 @@ class SimulationReportParameters(BaseModel):
variogram_model: GeoscienceObjectReference
"""Reference URL to the variogram model object."""
- neighborhood: SearchNeighborhood
+ neighborhood: SimpleSearchNeighborhood
"""Search neighborhood parameters for kriging within the report."""
block_discretization: SimulationReportBlockDiscretization = Field(
@@ -227,11 +226,6 @@ class SimulationReportParameters(BaseModel):
report_mean_thresholds: SimReportThresholds | None = None
"""Optional thresholds for mean comparison validation."""
- @field_validator("neighborhood")
- @classmethod
- def _check_neighborhood(cls, neighborhood: SearchNeighborhood) -> SearchNeighborhood:
- return _reject_sector_and_drillhole_limits(neighborhood)
-
# =============================================================================
# Simulation Report Result Types
diff --git a/packages/evo-compute/tests/geostatistics/test_break_ties_tasks.py b/packages/evo-compute/tests/geostatistics/test_break_ties_tasks.py
index a8ad8442f..4ddec8efc 100644
--- a/packages/evo-compute/tests/geostatistics/test_break_ties_tasks.py
+++ b/packages/evo-compute/tests/geostatistics/test_break_ties_tasks.py
@@ -14,6 +14,7 @@
from unittest import IsolatedAsyncioTestCase, TestCase
from unittest.mock import AsyncMock, MagicMock, patch
+import pytest
from evo.objects import ObjectReference
from evo.objects.typed.attributes import BlockModelPendingAttribute, PendingAttribute
from pydantic import ValidationError
@@ -21,6 +22,7 @@
from evo.compute.tasks import (
CreateAttribute,
SearchNeighborhood,
+ SimpleSearchNeighborhood,
Source,
Target,
UpdateAttribute,
@@ -105,7 +107,7 @@ def test_runner_types(self):
# ---------------------------------------------------------------------------
-class TestBreakTiesParametersSerialization(TestCase):
+class TestBreakTiesParametersSerialization:
def _params(self, **kwargs) -> BreakTiesParameters:
defaults = dict(
source=Source(object=POINTSET_URL, attribute="locations.attributes[?name=='grade']"),
@@ -120,14 +122,14 @@ def _dump(self, params: BreakTiesParameters) -> dict:
def test_source_serializes_correctly(self):
d = self._dump(self._params())
- self.assertEqual(d["source"]["object"], POINTSET_URL)
- self.assertEqual(d["source"]["attribute"], "locations.attributes[?name=='grade']")
+ assert d["source"]["object"] == POINTSET_URL
+ assert d["source"]["attribute"] == "locations.attributes[?name=='grade']"
def test_target_create_serializes_correctly(self):
d = self._dump(self._params())
- self.assertEqual(d["target"]["object"], TARGET_URL)
- self.assertEqual(d["target"]["attribute"]["operation"], "create")
- self.assertEqual(d["target"]["attribute"]["name"], "grade_bt")
+ assert d["target"]["object"] == TARGET_URL
+ assert d["target"]["attribute"]["operation"] == "create"
+ assert d["target"]["attribute"]["name"] == "grade_bt"
def test_target_update_serializes_correctly(self):
params = self._params(
@@ -136,37 +138,43 @@ def test_target_update_serializes_correctly(self):
)
)
d = self._dump(params)
- self.assertEqual(d["target"]["attribute"]["operation"], "update")
- self.assertEqual(d["target"]["attribute"]["reference"], "locations.attributes[?name=='grade']")
+ assert d["target"]["attribute"]["operation"] == "update"
+ assert d["target"]["attribute"]["reference"] == "locations.attributes[?name=='grade']"
- def test_neighborhood_serializes_correctly(self):
- d = self._dump(self._params())
+ def test_neighborhood_serializes_and_describes_simple_wire_schema(self):
+ params = self._params()
+ assert type(params.neighborhood) is SimpleSearchNeighborhood
+ d = self._dump(params)
nbh = d["neighborhood"]
- self.assertIn("ellipsoid", nbh)
- self.assertEqual(nbh["max_samples"], 20)
+ assert "ellipsoid" in nbh
+ assert nbh["max_samples"] == 20
ellipsoid = nbh["ellipsoid"]
- self.assertEqual(ellipsoid["ellipsoid_ranges"]["major"], 200.0)
- self.assertEqual(ellipsoid["ellipsoid_ranges"]["semi_major"], 150.0)
- self.assertEqual(ellipsoid["ellipsoid_ranges"]["minor"], 100.0)
+ assert ellipsoid["ellipsoid_ranges"]["major"] == 200.0
+ assert ellipsoid["ellipsoid_ranges"]["semi_major"] == 150.0
+ assert ellipsoid["ellipsoid_ranges"]["minor"] == 100.0
+
+ schema = BreakTiesParameters.model_json_schema()
+ nbh_schema = schema["$defs"]["SimpleSearchNeighborhood"]
+ assert set(nbh_schema["properties"]) == {"ellipsoid", "max_samples", "min_samples"}
def test_min_samples_included_when_set(self):
params = self._params(
- neighborhood=SearchNeighborhood(
+ neighborhood=SimpleSearchNeighborhood(
ellipsoid=Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100)),
max_samples=20,
min_samples=4,
)
)
d = self._dump(params)
- self.assertEqual(d["neighborhood"]["min_samples"], 4)
+ assert d["neighborhood"]["min_samples"] == 4
def test_min_samples_absent_when_not_set(self):
d = self._dump(self._params())
- self.assertNotIn("min_samples", d["neighborhood"])
+ assert "min_samples" not in d["neighborhood"]
- def test_search_limits_are_refused(self):
+ def test_disabled_drillhole_defaults_on_search_neighborhood_are_accepted(self):
ellipsoid = Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100))
- dumped_defaults = self._dump(
+ dumped = self._dump(
self._params(
neighborhood=SearchNeighborhood(
ellipsoid=ellipsoid,
@@ -176,32 +184,33 @@ def test_search_limits_are_refused(self):
)
)
)
- self.assertNotIn("min_drillholes", dumped_defaults["neighborhood"])
- self.assertNotIn("drillhole_limit_scope", dumped_defaults["neighborhood"])
-
- for kwargs, expected in [
- ({"max_drillholes": 4}, "does not support max_drillholes"),
- ({"max_drillholes_per_estimate": 4}, "does not support max_drillholes"),
- ({"min_drillholes": 2}, "does not support min_drillholes"),
- (
- {"max_samples_per_drillhole": 2, "drillhole_limit_scope": "quadrant"},
- "does not support max_samples_per_drillhole, drillhole_limit_scope",
- ),
- ]:
- with self.subTest(**kwargs), self.assertRaisesRegex(ValidationError, expected):
- self._params(neighborhood=SearchNeighborhood(ellipsoid=ellipsoid, max_samples=20, **kwargs))
+ assert set(dumped["neighborhood"]) == {"ellipsoid", "max_samples"}
+
+ @pytest.mark.parametrize(
+ ("kwargs", "expected_field"),
+ [
+ ({"max_drillholes": 4}, "max_drillholes"),
+ ({"max_drillholes_per_estimate": 4}, "max_drillholes"),
+ ({"min_drillholes": 2}, "min_drillholes"),
+ ({"max_samples_per_drillhole": 2, "drillhole_limit_scope": "quadrant"}, "drillhole_limit_scope"),
+ ],
+ )
+ def test_search_limits_are_refused(self, kwargs: dict, expected_field: str):
+ ellipsoid = Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100))
+ with pytest.raises(ValidationError, match=expected_field):
+ self._params(neighborhood=SearchNeighborhood(ellipsoid=ellipsoid, max_samples=20, **kwargs))
def test_default_seed(self):
d = self._dump(self._params())
- self.assertEqual(d["seed"], 38239342)
+ assert d["seed"] == 38239342
def test_custom_seed(self):
d = self._dump(self._params(seed=12345))
- self.assertEqual(d["seed"], 12345)
+ assert d["seed"] == 12345
def test_neighborhood_with_rotation(self):
params = self._params(
- neighborhood=SearchNeighborhood(
+ neighborhood=SimpleSearchNeighborhood(
ellipsoid=Ellipsoid(
ranges=EllipsoidRanges(major=300, semi_major=200, minor=100),
rotation=Rotation(dip_azimuth=45.0, dip=30.0, pitch=0.0),
@@ -211,8 +220,8 @@ def test_neighborhood_with_rotation(self):
)
d = self._dump(params)
rotation = d["neighborhood"]["ellipsoid"]["rotation"]
- self.assertEqual(rotation["dip_azimuth"], 45.0)
- self.assertEqual(rotation["dip"], 30.0)
+ assert rotation["dip_azimuth"] == 45.0
+ assert rotation["dip"] == 30.0
def test_pending_attribute_target(self):
mock_obj = MagicMock()
@@ -223,9 +232,9 @@ def test_pending_attribute_target(self):
params = self._params(target=pending)
d = self._dump(params)
- self.assertEqual(d["target"]["object"], TARGET_URL)
- self.assertEqual(d["target"]["attribute"]["operation"], "create")
- self.assertEqual(d["target"]["attribute"]["name"], "new_grade_bt")
+ assert d["target"]["object"] == TARGET_URL
+ assert d["target"]["attribute"]["operation"] == "create"
+ assert d["target"]["attribute"]["name"] == "new_grade_bt"
def test_block_model_pending_attribute_target(self):
mock_bm = MagicMock()
@@ -234,8 +243,8 @@ def test_block_model_pending_attribute_target(self):
params = self._params(target=bm_pending)
d = self._dump(params)
- self.assertEqual(d["target"]["attribute"]["operation"], "create")
- self.assertEqual(d["target"]["attribute"]["name"], "bt_attr")
+ assert d["target"]["attribute"]["operation"] == "create"
+ assert d["target"]["attribute"]["name"] == "bt_attr"
# ---------------------------------------------------------------------------
diff --git a/packages/evo-compute/tests/geostatistics/test_conditional_turning_bands_tasks.py b/packages/evo-compute/tests/geostatistics/test_conditional_turning_bands_tasks.py
index a07d349d9..9395ef401 100644
--- a/packages/evo-compute/tests/geostatistics/test_conditional_turning_bands_tasks.py
+++ b/packages/evo-compute/tests/geostatistics/test_conditional_turning_bands_tasks.py
@@ -14,11 +14,12 @@
import unittest
from unittest.mock import AsyncMock, MagicMock, patch
+import pytest
from evo.objects import ObjectReference
from evo.objects.typed.attributes import Attribute, BlockModelAttribute, PendingAttribute
from pydantic import ValidationError
-from evo.compute.tasks import SearchNeighborhood
+from evo.compute.tasks import SearchNeighborhood, SimpleSearchNeighborhood
from evo.compute.tasks.common import (
AllOfFilter,
AnyOfFilter,
@@ -144,77 +145,77 @@ def test_out_of_range_rejected(self):
# ---------------------------------------------------------------------------
-class TestConditionalTurningBandsParametersSerialization(unittest.TestCase):
+class TestConditionalTurningBandsParametersSerialization:
def test_required_fields_present(self):
- d = _dump(_params())
- self.assertEqual(d["source"], POINTSET_URL)
- self.assertEqual(d["source_attribute"], "locations.attributes[?name=='grade']")
- self.assertEqual(d["target"], GRID_URL)
- self.assertEqual(d["distribution"], DISTRIBUTION_URL)
- self.assertEqual(d["variogram_model"], VARIOGRAM_URL)
+ params = _params()
+ assert type(params.neighborhood) is SimpleSearchNeighborhood
+ d = _dump(params)
+ assert d["source"] == POINTSET_URL
+ assert d["source_attribute"] == "locations.attributes[?name=='grade']"
+ assert d["target"] == GRID_URL
+ assert d["distribution"] == DISTRIBUTION_URL
+ assert d["variogram_model"] == VARIOGRAM_URL
def test_defaults(self):
d = _dump(_params())
- self.assertEqual(d["kriging_method"], "simple")
- self.assertEqual(d["number_of_lines"], 500)
- self.assertEqual(d["realizations"], 1)
- self.assertEqual(d["random_seed"], 38239342)
+ assert d["kriging_method"] == "simple"
+ assert d["number_of_lines"] == 500
+ assert d["realizations"] == 1
+ assert d["random_seed"] == 38239342
def test_block_discretization_default(self):
d = _dump(_params())
bd = d["block_discretization"]
- self.assertEqual(bd["nx"], 1)
- self.assertEqual(bd["ny"], 1)
- self.assertEqual(bd["nz"], 1)
+ assert bd["nx"] == 1
+ assert bd["ny"] == 1
+ assert bd["nz"] == 1
def test_block_discretization_custom(self):
d = _dump(_params(block_discretization=BlockDiscretization(nx=5, ny=5, nz=3)))
bd = d["block_discretization"]
- self.assertEqual(bd["nx"], 5)
- self.assertEqual(bd["nz"], 3)
+ assert bd["nx"] == 5
+ assert bd["nz"] == 3
def test_custom_realizations(self):
d = _dump(_params(realizations=10))
- self.assertEqual(d["realizations"], 10)
+ assert d["realizations"] == 10
def test_custom_number_of_lines(self):
d = _dump(_params(number_of_lines=250))
- self.assertEqual(d["number_of_lines"], 250)
+ assert d["number_of_lines"] == 250
def test_ordinary_kriging_method(self):
d = _dump(_params(kriging_method="ordinary"))
- self.assertEqual(d["kriging_method"], "ordinary")
-
- def test_realizations_out_of_range_rejected(self):
- with self.assertRaises(ValidationError):
- _params(realizations=0)
- with self.assertRaises(ValidationError):
- _params(realizations=101)
-
- def test_number_of_lines_out_of_range_rejected(self):
- with self.assertRaises(ValidationError):
- _params(number_of_lines=0)
- with self.assertRaises(ValidationError):
- _params(number_of_lines=1001)
-
- def test_search_limits_are_refused(self):
+ assert d["kriging_method"] == "ordinary"
+
+ @pytest.mark.parametrize("realizations", [0, 101])
+ def test_realizations_out_of_range_rejected(self, realizations: int):
+ with pytest.raises(ValidationError):
+ _params(realizations=realizations)
+
+ @pytest.mark.parametrize("number_of_lines", [0, 1001])
+ def test_number_of_lines_out_of_range_rejected(self, number_of_lines: int):
+ with pytest.raises(ValidationError):
+ _params(number_of_lines=number_of_lines)
+
+ @pytest.mark.parametrize(
+ ("kwargs", "expected_field"),
+ [
+ ({"max_empty_octants": 2}, "max_empty_octants"),
+ ({"max_drillholes": 4}, "max_drillholes"),
+ ({"min_drillholes": 2}, "min_drillholes"),
+ ({"max_samples_per_drillhole": 2, "drillhole_limit_scope": "quadrant"}, "drillhole_limit_scope"),
+ ],
+ )
+ def test_search_limits_are_refused(self, kwargs: dict, expected_field: str):
ellipsoid = Ellipsoid(ranges=EllipsoidRanges(major=70, semi_major=70, minor=5))
- for kwargs, expected in [
- ({"max_empty_octants": 2}, "does not support max_empty_octants"),
- ({"max_drillholes": 4}, "does not support max_drillholes"),
- ({"min_drillholes": 2}, "does not support min_drillholes"),
- (
- {"max_samples_per_drillhole": 2, "drillhole_limit_scope": "quadrant"},
- "does not support max_samples_per_drillhole, drillhole_limit_scope",
- ),
- ]:
- with self.subTest(**kwargs), self.assertRaisesRegex(ValidationError, expected):
- _params(neighborhood=SearchNeighborhood(ellipsoid=ellipsoid, max_samples=40, **kwargs))
+ with pytest.raises(ValidationError, match=expected_field):
+ _params(neighborhood=SearchNeighborhood(ellipsoid=ellipsoid, max_samples=40, **kwargs))
def test_no_filters_by_default(self):
d = _dump(_params())
- self.assertNotIn("filter", d)
- self.assertNotIn("source_filter", d)
+ assert "filter" not in d
+ assert "source_filter" not in d
def test_target_filter_single_condition(self):
params = _params(
@@ -228,9 +229,9 @@ def test_target_filter_single_condition(self):
)
d = _dump(params)
where = d["filter"]["where"]
- self.assertEqual(where["type"], "condition")
- self.assertEqual(where["operator"], "in")
- self.assertEqual(where["values"], ["LMS1", "LMS2"])
+ assert where["type"] == "condition"
+ assert where["operator"] == "in"
+ assert where["values"] == ["LMS1", "LMS2"]
def test_source_filter_numeric_condition(self):
params = _params(
@@ -244,8 +245,8 @@ def test_source_filter_numeric_condition(self):
)
d = _dump(params)
where = d["source_filter"]["where"]
- self.assertEqual(where["operator"], "greater_than")
- self.assertEqual(where["threshold"], 0.5)
+ assert where["operator"] == "greater_than"
+ assert where["threshold"] == 0.5
def test_composite_all_of_filter(self):
params = _params(
@@ -268,8 +269,8 @@ def test_composite_all_of_filter(self):
)
d = _dump(params)
where = d["filter"]["where"]
- self.assertEqual(where["type"], "all_of")
- self.assertEqual(len(where["filters"]), 2)
+ assert where["type"] == "all_of"
+ assert len(where["filters"]) == 2
def test_composite_any_of_filter(self):
params = _params(
@@ -292,7 +293,7 @@ def test_composite_any_of_filter(self):
)
d = _dump(params)
where = d["source_filter"]["where"]
- self.assertEqual(where["type"], "any_of")
+ assert where["type"] == "any_of"
def test_both_filter_and_source_filter(self):
params = _params(
@@ -312,8 +313,8 @@ def test_both_filter_and_source_filter(self):
),
)
d = _dump(params)
- self.assertIn("filter", d)
- self.assertIn("source_filter", d)
+ assert "filter" in d
+ assert "source_filter" in d
# ---------------------------------------------------------------------------
diff --git a/packages/evo-compute/tests/geostatistics/test_conditioned_simulator_tasks.py b/packages/evo-compute/tests/geostatistics/test_conditioned_simulator_tasks.py
index 48feca611..0d8385c88 100644
--- a/packages/evo-compute/tests/geostatistics/test_conditioned_simulator_tasks.py
+++ b/packages/evo-compute/tests/geostatistics/test_conditioned_simulator_tasks.py
@@ -6,11 +6,12 @@
import unittest
from unittest.mock import AsyncMock, MagicMock, patch
+import pytest
from evo.objects import ObjectReference
from evo.objects.typed.attributes import Attribute, BlockModelAttribute, PendingAttribute
from pydantic import ValidationError
-from evo.compute.tasks import SearchNeighborhood
+from evo.compute.tasks import SearchNeighborhood, SimpleSearchNeighborhood
from evo.compute.tasks.common import (
AllOfFilter,
CreateAttribute,
@@ -130,45 +131,47 @@ def test_custom(self):
# ---------------------------------------------------------------------------
-class TestConSimParametersSerialization(unittest.TestCase):
+class TestConSimParametersSerialization:
def test_basic(self):
- d = _dump(_params())
- self.assertEqual(d["source_object"], POINTSET_URL)
- self.assertEqual(d["source_attribute"], "locations.attributes[?name=='grade']")
- self.assertEqual(d["target_object"], GRID_URL)
- self.assertEqual(d["variogram_model"], VARIOGRAM_URL)
+ params = _params()
+ assert type(params.neighborhood) is SimpleSearchNeighborhood
+ d = _dump(params)
+ assert d["source_object"] == POINTSET_URL
+ assert d["source_attribute"] == "locations.attributes[?name=='grade']"
+ assert d["target_object"] == GRID_URL
+ assert d["variogram_model"] == VARIOGRAM_URL
def test_defaults(self):
d = _dump(_params())
- self.assertEqual(d["kriging_method"], "simple")
- self.assertEqual(d["number_of_lines"], 500)
- self.assertEqual(d["number_of_simulations"], 1)
- self.assertEqual(d["random_seed"], 38239342)
- self.assertEqual(d["number_of_simulations_to_save"], 5)
- self.assertFalse(d["perform_validation"])
+ assert d["kriging_method"] == "simple"
+ assert d["number_of_lines"] == 500
+ assert d["number_of_simulations"] == 1
+ assert d["random_seed"] == 38239342
+ assert d["number_of_simulations_to_save"] == 5
+ assert d["perform_validation"] is False
def test_block_discretization_default(self):
d = _dump(_params())
- self.assertEqual(d["block_discretization"]["nx"], 1)
-
- def test_search_limits_are_refused(self):
+ assert d["block_discretization"]["nx"] == 1
+
+ @pytest.mark.parametrize(
+ ("kwargs", "expected_field"),
+ [
+ ({"max_samples_per_drillhole": 3}, "max_samples_per_drillhole"),
+ ({"max_drillholes": 4}, "max_drillholes"),
+ ({"min_drillholes": 2}, "min_drillholes"),
+ ({"max_samples_per_drillhole": 2, "drillhole_limit_scope": "octant"}, "drillhole_limit_scope"),
+ ],
+ )
+ def test_search_limits_are_refused(self, kwargs: dict, expected_field: str):
ellipsoid = Ellipsoid(ranges=EllipsoidRanges(major=300, semi_major=200, minor=100))
- for kwargs, expected in [
- ({"max_samples_per_drillhole": 3}, "does not support max_samples_per_drillhole"),
- ({"max_drillholes": 4}, "does not support max_drillholes"),
- ({"min_drillholes": 2}, "does not support min_drillholes"),
- (
- {"max_samples_per_drillhole": 2, "drillhole_limit_scope": "octant"},
- "does not support max_samples_per_drillhole, drillhole_limit_scope",
- ),
- ]:
- with self.subTest(**kwargs), self.assertRaisesRegex(ValidationError, expected):
- _params(neighborhood=SearchNeighborhood(ellipsoid=ellipsoid, max_samples=24, **kwargs))
+ with pytest.raises(ValidationError, match=expected_field):
+ _params(neighborhood=SearchNeighborhood(ellipsoid=ellipsoid, max_samples=24, **kwargs))
def test_custom_simulations(self):
d = _dump(_params(number_of_simulations=10, number_of_simulations_to_save=3))
- self.assertEqual(d["number_of_simulations"], 10)
- self.assertEqual(d["number_of_simulations_to_save"], 3)
+ assert d["number_of_simulations"] == 10
+ assert d["number_of_simulations_to_save"] == 3
def test_distribution_params(self):
params = _params(
@@ -179,11 +182,11 @@ def test_distribution_params(self):
),
)
d = _dump(params)
- self.assertEqual(d["distribution"]["tail_extrapolation"]["upper"]["power"], 0.5)
+ assert d["distribution"]["tail_extrapolation"]["upper"]["power"] == 0.5
def test_distribution_without_tail_extrapolation_omits_key(self):
d = _dump(_params(distribution=DistributionParams(weights="declustering_weights")))
- self.assertEqual(d["distribution"], {"weights": "declustering_weights"})
+ assert d["distribution"] == {"weights": "declustering_weights"}
def test_tail_extrapolation_without_lower_omits_key(self):
params = _params(
@@ -192,7 +195,7 @@ def test_tail_extrapolation_without_lower_omits_key(self):
),
)
d = _dump(params)
- self.assertEqual(d["distribution"]["tail_extrapolation"], {"upper": {"power": 0.5, "max": 100.0}})
+ assert d["distribution"]["tail_extrapolation"] == {"upper": {"power": 0.5, "max": 100.0}}
def test_tail_extrapolation_with_lower(self):
params = _params(
@@ -204,7 +207,7 @@ def test_tail_extrapolation_with_lower(self):
),
)
d = _dump(params)
- self.assertEqual(d["distribution"]["tail_extrapolation"]["lower"], {"power": 0.3, "min": 0.0})
+ assert d["distribution"]["tail_extrapolation"]["lower"] == {"power": 0.3, "min": 0.0}
def test_loss_calculation_params(self):
params = _params(
@@ -222,13 +225,13 @@ def test_loss_calculation_params(self):
)
d = _dump(params)
lc = d["loss_calculation"]
- self.assertEqual(len(lc["material_categories"]), 2)
- self.assertEqual(lc["processing_cost"], 20.0)
+ assert len(lc["material_categories"]) == 2
+ assert lc["processing_cost"] == 20.0
def test_location_wise_quantiles(self):
params = _params(location_wise_quantiles=[0.1, 0.5, 0.9])
d = _dump(params)
- self.assertEqual(d["location_wise_quantiles"], [0.1, 0.5, 0.9])
+ assert d["location_wise_quantiles"] == [0.1, 0.5, 0.9]
def test_report_context(self):
params = _params(
@@ -239,15 +242,15 @@ def test_report_context(self):
),
)
d = _dump(params)
- self.assertTrue(d["perform_validation"])
- self.assertEqual(d["report_context"]["title"], "Simulation QC")
+ assert d["perform_validation"] is True
+ assert d["report_context"]["title"] == "Simulation QC"
def test_report_mean_thresholds(self):
params = _params(
report_mean_thresholds=ReportMeanThresholds(acceptable=0.02, marginal=0.05),
)
d = _dump(params)
- self.assertEqual(d["report_mean_thresholds"]["acceptable"], 0.02)
+ assert d["report_mean_thresholds"]["acceptable"] == 0.02
def test_filter_single_condition(self):
params = _params(
@@ -257,10 +260,10 @@ def test_filter_single_condition(self):
)
d = _dump(params)
where = d["filter"]["where"]
- self.assertEqual(where["type"], "condition")
- self.assertEqual(where["operator"], "in")
- self.assertEqual(where["values"], ["LMS1", "LMS2"])
- self.assertEqual(where["attribute"], "attributes[?name=='domain']")
+ assert where["type"] == "condition"
+ assert where["operator"] == "in"
+ assert where["values"] == ["LMS1", "LMS2"]
+ assert where["attribute"] == "attributes[?name=='domain']"
def test_source_filter_numeric(self):
params = _params(
@@ -274,8 +277,8 @@ def test_source_filter_numeric(self):
)
d = _dump(params)
where = d["source_filter"]["where"]
- self.assertEqual(where["operator"], "greater_than_or_equal_to")
- self.assertEqual(where["threshold"], 0.5)
+ assert where["operator"] == "greater_than_or_equal_to"
+ assert where["threshold"] == 0.5
def test_filter_composite_all_of(self):
params = _params(
@@ -290,21 +293,26 @@ def test_filter_composite_all_of(self):
)
d = _dump(params)
where = d["filter"]["where"]
- self.assertEqual(where["type"], "all_of")
- self.assertEqual(len(where["filters"]), 2)
- self.assertEqual(where["filters"][0]["values"], [1, 2])
-
- def test_filter_condition_requires_matching_payload(self):
- with self.assertRaises(ValueError):
- FilterCondition(attribute="attributes[?name=='domain']", operator="in", threshold=1.0)
- with self.assertRaises(ValueError):
- FilterCondition(attribute="attributes[?name=='grade']", operator="greater_than", values=[1])
+ assert where["type"] == "all_of"
+ assert len(where["filters"]) == 2
+ assert where["filters"][0]["values"] == [1, 2]
+
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"attribute": "attributes[?name=='domain']", "operator": "in", "threshold": 1.0},
+ {"attribute": "attributes[?name=='grade']", "operator": "greater_than", "values": [1]},
+ ],
+ )
+ def test_filter_condition_requires_matching_payload(self, kwargs: dict):
+ with pytest.raises(ValueError):
+ FilterCondition(**kwargs)
def test_probability_and_mean_above_cutoff(self):
params = _params(probability_above_cutoff=[0.5, 1.0], mean_above_cutoff=[0.5])
d = _dump(params)
- self.assertEqual(d["probability_above_cutoff"], [0.5, 1.0])
- self.assertEqual(d["mean_above_cutoff"], [0.5])
+ assert d["probability_above_cutoff"] == [0.5, 1.0]
+ assert d["mean_above_cutoff"] == [0.5]
# ---------------------------------------------------------------------------
diff --git a/packages/evo-compute/tests/geostatistics/test_declustering_tasks.py b/packages/evo-compute/tests/geostatistics/test_declustering_tasks.py
index ebbd3368b..ab3f7e99e 100644
--- a/packages/evo-compute/tests/geostatistics/test_declustering_tasks.py
+++ b/packages/evo-compute/tests/geostatistics/test_declustering_tasks.py
@@ -14,6 +14,7 @@
from unittest import IsolatedAsyncioTestCase, TestCase
from unittest.mock import AsyncMock, MagicMock, patch
+import pytest
from pydantic import ValidationError
from evo.compute.tasks import (
@@ -106,7 +107,7 @@ def test_runner_types(self):
# ---------------------------------------------------------------------------
-class TestDeclusteringParametersSerialization(TestCase):
+class TestDeclusteringParametersSerialization:
def _params(self, **kwargs) -> DeclusteringParameters:
defaults = dict(
source=POINTSET_URL,
@@ -122,22 +123,22 @@ def _dump(self, params: DeclusteringParameters) -> dict:
def test_source_serializes_correctly(self):
d = self._dump(self._params())
- self.assertEqual(d["source"]["object"], POINTSET_URL)
+ assert d["source"]["object"] == POINTSET_URL
def test_source_accepts_raw_url(self):
params = self._params(source=POINTSET_URL)
- self.assertIsInstance(params.source, DeclusteringSource)
- self.assertEqual(str(params.source.object), POINTSET_URL)
+ assert isinstance(params.source, DeclusteringSource)
+ assert str(params.source.object) == POINTSET_URL
def test_grid_serializes_correctly(self):
d = self._dump(self._params())
- self.assertEqual(d["grid"]["object"], GRID_URL)
+ assert d["grid"]["object"] == GRID_URL
def test_target_create_serializes_correctly(self):
d = self._dump(self._params())
- self.assertEqual(d["target"]["object"], TARGET_URL)
- self.assertEqual(d["target"]["attribute"]["operation"], "create")
- self.assertEqual(d["target"]["attribute"]["name"], "weights")
+ assert d["target"]["object"] == TARGET_URL
+ assert d["target"]["attribute"]["operation"] == "create"
+ assert d["target"]["attribute"]["name"] == "weights"
def test_target_update_serializes_correctly(self):
params = self._params(
@@ -146,70 +147,68 @@ def test_target_update_serializes_correctly(self):
)
)
d = self._dump(params)
- self.assertEqual(d["target"]["attribute"]["operation"], "update")
+ assert d["target"]["attribute"]["operation"] == "update"
def test_neighborhood_serializes_correctly(self):
d = self._dump(self._params())
nbh = d["neighborhood"]
- self.assertIn("ellipsoid", nbh)
- self.assertEqual(nbh["max_samples"], 20)
+ assert "ellipsoid" in nbh
+ assert nbh["max_samples"] == 20
- def test_search_limits_in_neighborhood(self):
+ @pytest.mark.parametrize("scope", ["quadrant", "octant"])
+ def test_search_limits_in_neighborhood(self, scope: str):
search = SearchNeighborhood(
ellipsoid=Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100)),
max_samples=20,
max_samples_per_octant=2,
max_samples_per_drillhole=3,
max_drillholes=5,
+ min_drillholes=2,
+ drillhole_limit_scope=scope,
+ )
+ d = self._dump(self._params(neighborhood=search))
+ assert d["neighborhood"]["max_samples_per_octant"] == 2
+ assert d["neighborhood"]["max_samples_per_drillhole"] == 3
+ assert d["neighborhood"]["max_drillholes"] == 5
+ assert d["neighborhood"]["min_drillholes"] == 2
+ assert d["neighborhood"]["drillhole_limit_scope"] == scope
+
+ defaults = SearchNeighborhood(
+ ellipsoid=Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100)),
+ max_samples=20,
min_drillholes=0,
drillhole_limit_scope="global",
)
- d = self._dump(self._params(neighborhood=search))
- self.assertEqual(d["neighborhood"]["max_samples_per_octant"], 2)
- self.assertEqual(d["neighborhood"]["max_samples_per_drillhole"], 3)
- self.assertEqual(d["neighborhood"]["max_drillholes"], 5)
- self.assertNotIn("min_drillholes", d["neighborhood"])
- self.assertNotIn("drillhole_limit_scope", d["neighborhood"])
-
- def test_kriging_only_drillhole_limits_rejected(self):
- ellipsoid = Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100))
- for limits in [
- {"min_drillholes": 2},
- {"max_samples_per_drillhole": 2, "drillhole_limit_scope": "quadrant"},
- {"max_samples_per_drillhole": 2, "drillhole_limit_scope": "octant"},
- ]:
- with self.subTest(**limits), self.assertRaisesRegex(ValidationError, "only supported by Kriging"):
- self._params(neighborhood=SearchNeighborhood(ellipsoid=ellipsoid, max_samples=20, **limits))
+ d_defaults = self._dump(self._params(neighborhood=defaults))
+ assert "min_drillholes" not in d_defaults["neighborhood"]
+ assert "drillhole_limit_scope" not in d_defaults["neighborhood"]
def test_default_power_is_idw(self):
params = self._params()
- self.assertEqual(params.power, 2.0)
+ assert params.power == 2.0
def test_default_power_in_serialized_output(self):
d = self._dump(self._params())
- self.assertEqual(d["power"], 2.0)
+ assert d["power"] == 2.0
def test_custom_power(self):
d = self._dump(self._params(power=3.0))
- self.assertEqual(d["power"], 3.0)
+ assert d["power"] == 3.0
def test_knn_mode_power_none(self):
params = self._params(power=None)
- self.assertIsNone(params.power)
+ assert params.power is None
def test_knn_power_none_preserved_with_exclude_none(self):
"""When power=None, serialization must explicitly include power: null."""
d = self._dump(self._params(power=None))
- self.assertIn("power", d)
- self.assertIsNone(d["power"])
-
- def test_negative_power_rejected(self):
- with self.assertRaises(ValidationError):
- self._params(power=-1.0)
+ assert "power" in d
+ assert d["power"] is None
- def test_zero_power_rejected(self):
- with self.assertRaises(ValidationError):
- self._params(power=0.0)
+ @pytest.mark.parametrize("power", [-1.0, 0.0])
+ def test_nonpositive_power_rejected(self, power: float):
+ with pytest.raises(ValidationError):
+ self._params(power=power)
def test_neighborhood_with_rotation(self):
params = self._params(
@@ -223,8 +222,8 @@ def test_neighborhood_with_rotation(self):
)
d = self._dump(params)
rotation = d["neighborhood"]["ellipsoid"]["rotation"]
- self.assertEqual(rotation["dip_azimuth"], 45.0)
- self.assertEqual(rotation["dip"], 30.0)
+ assert rotation["dip_azimuth"] == 45.0
+ assert rotation["dip"] == 30.0
# ---------------------------------------------------------------------------
diff --git a/packages/evo-compute/tests/geostatistics/test_idw_tasks.py b/packages/evo-compute/tests/geostatistics/test_idw_tasks.py
index 4f13c01aa..2717a9eb8 100644
--- a/packages/evo-compute/tests/geostatistics/test_idw_tasks.py
+++ b/packages/evo-compute/tests/geostatistics/test_idw_tasks.py
@@ -14,6 +14,7 @@
import unittest
from unittest.mock import AsyncMock, MagicMock, patch
+import pytest
from pydantic import ValidationError
from evo.compute.tasks import SearchNeighborhood
@@ -111,40 +112,39 @@ def test_runner_types(self):
# ---------------------------------------------------------------------------
-class TestIDWParametersSerialization(unittest.TestCase):
+class TestIDWParametersSerialization:
def test_basic_fields_present(self):
d = _dump(_params())
- self.assertEqual(d["source"]["object"], POINTSET_URL)
- self.assertEqual(d["source"]["attribute"], "locations.attributes[?name=='grade']")
- self.assertEqual(d["target"]["object"], GRID_URL)
- self.assertIn("neighborhood", d)
- self.assertEqual(d["power"], 2.0)
+ assert d["source"]["object"] == POINTSET_URL
+ assert d["source"]["attribute"] == "locations.attributes[?name=='grade']"
+ assert d["target"]["object"] == GRID_URL
+ assert "neighborhood" in d
+ assert d["power"] == 2.0
def test_power_is_serialized(self):
d = _dump(_params(power=3.0))
- self.assertEqual(d["power"], 3.0)
+ assert d["power"] == 3.0
- def test_power_must_be_positive(self):
- with self.assertRaises(ValidationError):
- _params(power=0.0)
- with self.assertRaises(ValidationError):
- _params(power=-1.0)
+ @pytest.mark.parametrize("power", [0.0, -1.0])
+ def test_power_must_be_positive(self, power: float):
+ with pytest.raises(ValidationError):
+ _params(power=power)
- def test_different_power_values(self):
- for power in (0.5, 1.0, 2.0, 3.5):
- d = _dump(_params(power=power))
- self.assertAlmostEqual(d["power"], power)
+ @pytest.mark.parametrize("power", [0.5, 1.0, 2.0, 3.5])
+ def test_different_power_values(self, power: float):
+ d = _dump(_params(power=power))
+ assert d["power"] == pytest.approx(power)
def test_neighborhood_fields(self):
d = _dump(_params())
nbr = d["neighborhood"]
- self.assertIn("ellipsoid", nbr)
- self.assertEqual(nbr["max_samples"], 20)
+ assert "ellipsoid" in nbr
+ assert nbr["max_samples"] == 20
def test_new_attribute_target(self):
d = _dump(_params(target=Target.new_attribute(GRID_URL, "result")))
- self.assertEqual(d["target"]["attribute"]["operation"], "create")
- self.assertEqual(d["target"]["attribute"]["name"], "result")
+ assert d["target"]["attribute"]["operation"] == "create"
+ assert d["target"]["attribute"]["name"] == "result"
def test_update_attribute_target(self):
from evo.compute.tasks.common.source_target import Target as _Target
@@ -154,13 +154,13 @@ def test_update_attribute_target(self):
attribute=UpdateAttribute(operation="update", name="existing", reference="attributes[?key=='abc']"),
)
d = _dump(_params(target=target))
- self.assertEqual(d["target"]["attribute"]["operation"], "update")
- self.assertEqual(d["target"]["attribute"]["reference"], "attributes[?key=='abc']")
+ assert d["target"]["attribute"]["operation"] == "update"
+ assert d["target"]["attribute"]["reference"] == "attributes[?key=='abc']"
def test_no_filter_by_default(self):
d = _dump(_params())
- self.assertNotIn("filter", d.get("target", {}))
- self.assertNotIn("filter", d.get("source", {}))
+ assert "filter" not in d.get("target", {})
+ assert "filter" not in d.get("source", {})
def test_target_filter_injected_into_target(self):
params = _params(
@@ -174,10 +174,10 @@ def test_target_filter_injected_into_target(self):
)
d = _dump(params)
f = d["target"]["filter"]
- self.assertEqual(f["where"]["attribute"], "attributes[?name=='domain']")
- self.assertEqual(f["where"]["operator"], "in")
- self.assertEqual(f["where"]["values"], ["LMS1", "LMS2"])
- self.assertNotIn("filter", d["source"])
+ assert f["where"]["attribute"] == "attributes[?name=='domain']"
+ assert f["where"]["operator"] == "in"
+ assert f["where"]["values"] == ["LMS1", "LMS2"]
+ assert "filter" not in d["source"]
def test_target_filter_with_integer_keys(self):
params = _params(
@@ -190,7 +190,7 @@ def test_target_filter_with_integer_keys(self):
)
)
d = _dump(params)
- self.assertEqual(d["target"]["filter"]["where"]["values"], [1, 2, 3])
+ assert d["target"]["filter"]["where"]["values"] == [1, 2, 3]
def test_source_filter_injected_into_source(self):
params = _params(
@@ -200,8 +200,8 @@ def test_source_filter_injected_into_source(self):
)
d = _dump(params)
f = d["source"]["filter"]
- self.assertEqual(f["where"]["threshold"], 0.0)
- self.assertNotIn("filter", d["target"])
+ assert f["where"]["threshold"] == 0.0
+ assert "filter" not in d["target"]
def test_filter_excluded_from_top_level(self):
"""source_filter / target_filter must not appear at the top-level; only inside source/target."""
@@ -211,8 +211,8 @@ def test_filter_excluded_from_top_level(self):
)
)
d = _dump(params)
- self.assertNotIn("target_filter", d)
- self.assertNotIn("source_filter", d)
+ assert "target_filter" not in d
+ assert "source_filter" not in d
def test_min_samples_in_neighborhood(self):
search = SearchNeighborhood(
@@ -221,68 +221,64 @@ def test_min_samples_in_neighborhood(self):
min_samples=4,
)
d = _dump(_params(neighborhood=search))
- self.assertEqual(d["neighborhood"]["min_samples"], 4)
+ assert d["neighborhood"]["min_samples"] == 4
def test_search_limits_in_neighborhood(self):
search = SearchNeighborhood(
ellipsoid=Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100)),
max_samples=20,
max_empty_quadrants=1,
+ max_samples_per_drillhole=2,
max_drillholes=4,
- min_drillholes=0,
- drillhole_limit_scope="global",
+ min_drillholes=2,
+ drillhole_limit_scope="quadrant",
)
d = _dump(_params(neighborhood=search))
- self.assertEqual(d["neighborhood"]["max_empty_quadrants"], 1)
- self.assertEqual(d["neighborhood"]["max_drillholes"], 4)
- self.assertNotIn("max_drillholes_per_estimate", d["neighborhood"])
- self.assertNotIn("min_drillholes", d["neighborhood"])
- self.assertNotIn("drillhole_limit_scope", d["neighborhood"])
+ assert d["neighborhood"]["max_empty_quadrants"] == 1
+ assert d["neighborhood"]["max_samples_per_drillhole"] == 2
+ assert d["neighborhood"]["max_drillholes"] == 4
+ assert d["neighborhood"]["min_drillholes"] == 2
+ assert d["neighborhood"]["drillhole_limit_scope"] == "quadrant"
+ assert "max_drillholes_per_estimate" not in d["neighborhood"]
legacy = SearchNeighborhood(
ellipsoid=Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100)),
max_samples=20,
max_drillholes_per_estimate=4,
+ min_drillholes=0,
+ drillhole_limit_scope="global",
)
d_legacy = _dump(_params(neighborhood=legacy))
- self.assertEqual(d_legacy["neighborhood"]["max_drillholes"], 4)
- self.assertNotIn("max_drillholes_per_estimate", d_legacy["neighborhood"])
+ assert d_legacy["neighborhood"]["max_drillholes"] == 4
+ assert "max_drillholes_per_estimate" not in d_legacy["neighborhood"]
+ assert "min_drillholes" not in d_legacy["neighborhood"]
+ assert "drillhole_limit_scope" not in d_legacy["neighborhood"]
- def test_kriging_only_drillhole_limits_rejected(self):
- ellipsoid = Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100))
- for limits in [
- {"min_drillholes": 2},
- {"max_samples_per_drillhole": 2, "drillhole_limit_scope": "quadrant"},
- {"max_samples_per_drillhole": 2, "drillhole_limit_scope": "octant"},
- ]:
- with self.subTest(**limits), self.assertRaisesRegex(ValidationError, "only supported by Kriging"):
- _params(neighborhood=SearchNeighborhood(ellipsoid=ellipsoid, max_samples=20, **limits))
-
- def test_sample_limit_boundaries_in_neighborhood(self):
- ellipsoid = Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100))
- d = _dump(_params(neighborhood={"ellipsoid": ellipsoid, "max_samples": 1}))
- self.assertEqual(d["neighborhood"]["max_samples"], 1)
- self.assertNotIn("min_samples", d["neighborhood"])
-
- for max_samples, min_samples in [(1, 1), (20, 1), (20, 20)]:
- with self.subTest(max_samples=max_samples, min_samples=min_samples):
- d = _dump(
- _params(
- neighborhood={"ellipsoid": ellipsoid, "max_samples": max_samples, "min_samples": min_samples}
- )
- )
- self.assertEqual(d["neighborhood"]["max_samples"], max_samples)
- self.assertEqual(d["neighborhood"]["min_samples"], min_samples)
-
- def test_invalid_sample_limits_rejected(self):
+ @pytest.mark.parametrize(("max_samples", "min_samples"), [(1, 1), (20, 1), (20, 20)])
+ def test_sample_limit_boundaries_in_neighborhood(self, max_samples: int, min_samples: int):
ellipsoid = Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100))
- for limits in [
+ d_single = _dump(_params(neighborhood={"ellipsoid": ellipsoid, "max_samples": 1}))
+ assert d_single["neighborhood"]["max_samples"] == 1
+ assert "min_samples" not in d_single["neighborhood"]
+
+ d = _dump(
+ _params(neighborhood={"ellipsoid": ellipsoid, "max_samples": max_samples, "min_samples": min_samples})
+ )
+ assert d["neighborhood"]["max_samples"] == max_samples
+ assert d["neighborhood"]["min_samples"] == min_samples
+
+ @pytest.mark.parametrize(
+ "limits",
+ [
{"max_samples": 0},
{"max_samples": 20, "min_samples": 0},
{"max_samples": 20, "min_samples": 21},
- ]:
- with self.subTest(**limits), self.assertRaises(ValidationError):
- _params(neighborhood={"ellipsoid": ellipsoid, **limits})
+ ],
+ )
+ def test_invalid_sample_limits_rejected(self, limits: dict):
+ ellipsoid = Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100))
+ with pytest.raises(ValidationError):
+ _params(neighborhood={"ellipsoid": ellipsoid, **limits})
# ---------------------------------------------------------------------------
diff --git a/packages/evo-compute/tests/geostatistics/test_knn_tasks.py b/packages/evo-compute/tests/geostatistics/test_knn_tasks.py
index ab44ff615..cd7b45965 100644
--- a/packages/evo-compute/tests/geostatistics/test_knn_tasks.py
+++ b/packages/evo-compute/tests/geostatistics/test_knn_tasks.py
@@ -14,6 +14,7 @@
import unittest
from unittest.mock import AsyncMock, MagicMock, patch
+import pytest
from pydantic import ValidationError
from evo.compute.tasks import SearchNeighborhood
@@ -110,19 +111,19 @@ def test_runner_types(self):
# ---------------------------------------------------------------------------
-class TestKNNParametersSerialization(unittest.TestCase):
+class TestKNNParametersSerialization:
def test_basic_fields_present(self):
d = _dump(_params())
- self.assertEqual(d["source"]["object"], POINTSET_URL)
- self.assertEqual(d["source"]["attribute"], "locations.attributes[?name=='grade']")
- self.assertEqual(d["target"]["object"], GRID_URL)
- self.assertIn("neighborhood", d)
+ assert d["source"]["object"] == POINTSET_URL
+ assert d["source"]["attribute"] == "locations.attributes[?name=='grade']"
+ assert d["target"]["object"] == GRID_URL
+ assert "neighborhood" in d
def test_neighborhood_fields(self):
d = _dump(_params())
nbr = d["neighborhood"]
- self.assertIn("ellipsoid", nbr)
- self.assertEqual(nbr["max_samples"], 20)
+ assert "ellipsoid" in nbr
+ assert nbr["max_samples"] == 20
def test_search_limits_in_neighborhood(self):
search = SearchNeighborhood(
@@ -130,57 +131,59 @@ def test_search_limits_in_neighborhood(self):
max_samples=20,
max_empty_octants=2,
max_samples_per_quadrant=5,
+ max_samples_per_drillhole=2,
max_drillholes=4,
+ min_drillholes=2,
+ drillhole_limit_scope="octant",
+ )
+ d = _dump(_params(neighborhood=search))
+ assert d["neighborhood"]["max_empty_octants"] == 2
+ assert d["neighborhood"]["max_samples_per_quadrant"] == 5
+ assert d["neighborhood"]["max_samples_per_drillhole"] == 2
+ assert d["neighborhood"]["max_drillholes"] == 4
+ assert d["neighborhood"]["min_drillholes"] == 2
+ assert d["neighborhood"]["drillhole_limit_scope"] == "octant"
+
+ defaults = SearchNeighborhood(
+ ellipsoid=Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100)),
+ max_samples=20,
min_drillholes=0,
drillhole_limit_scope="global",
)
- d = _dump(_params(neighborhood=search))
- self.assertEqual(d["neighborhood"]["max_empty_octants"], 2)
- self.assertEqual(d["neighborhood"]["max_samples_per_quadrant"], 5)
- self.assertEqual(d["neighborhood"]["max_drillholes"], 4)
- self.assertNotIn("min_drillholes", d["neighborhood"])
- self.assertNotIn("drillhole_limit_scope", d["neighborhood"])
+ d_defaults = _dump(_params(neighborhood=defaults))
+ assert "min_drillholes" not in d_defaults["neighborhood"]
+ assert "drillhole_limit_scope" not in d_defaults["neighborhood"]
- def test_kriging_only_drillhole_limits_rejected(self):
- ellipsoid = Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100))
- for limits in [
- {"min_drillholes": 2},
- {"max_samples_per_drillhole": 2, "drillhole_limit_scope": "quadrant"},
- {"max_samples_per_drillhole": 2, "drillhole_limit_scope": "octant"},
- ]:
- with self.subTest(**limits), self.assertRaisesRegex(ValidationError, "only supported by Kriging"):
- _params(neighborhood=SearchNeighborhood(ellipsoid=ellipsoid, max_samples=20, **limits))
-
- def test_sample_limit_boundaries_in_neighborhood(self):
+ @pytest.mark.parametrize(("max_samples", "min_samples"), [(1, 1), (20, 1), (20, 20)])
+ def test_sample_limit_boundaries_in_neighborhood(self, max_samples: int, min_samples: int):
ellipsoid = Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100))
- d = _dump(_params(neighborhood={"ellipsoid": ellipsoid, "max_samples": 1}))
- self.assertEqual(d["neighborhood"]["max_samples"], 1)
- self.assertNotIn("min_samples", d["neighborhood"])
-
- for max_samples, min_samples in [(1, 1), (20, 1), (20, 20)]:
- with self.subTest(max_samples=max_samples, min_samples=min_samples):
- d = _dump(
- _params(
- neighborhood={"ellipsoid": ellipsoid, "max_samples": max_samples, "min_samples": min_samples}
- )
- )
- self.assertEqual(d["neighborhood"]["max_samples"], max_samples)
- self.assertEqual(d["neighborhood"]["min_samples"], min_samples)
-
- def test_invalid_sample_limits_rejected(self):
- ellipsoid = Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100))
- for limits in [
+ d_single = _dump(_params(neighborhood={"ellipsoid": ellipsoid, "max_samples": 1}))
+ assert d_single["neighborhood"]["max_samples"] == 1
+ assert "min_samples" not in d_single["neighborhood"]
+
+ d = _dump(
+ _params(neighborhood={"ellipsoid": ellipsoid, "max_samples": max_samples, "min_samples": min_samples})
+ )
+ assert d["neighborhood"]["max_samples"] == max_samples
+ assert d["neighborhood"]["min_samples"] == min_samples
+
+ @pytest.mark.parametrize(
+ "limits",
+ [
{"max_samples": 0},
{"max_samples": 20, "min_samples": 0},
{"max_samples": 20, "min_samples": 21},
- ]:
- with self.subTest(**limits), self.assertRaises(ValidationError):
- _params(neighborhood={"ellipsoid": ellipsoid, **limits})
+ ],
+ )
+ def test_invalid_sample_limits_rejected(self, limits: dict):
+ ellipsoid = Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100))
+ with pytest.raises(ValidationError):
+ _params(neighborhood={"ellipsoid": ellipsoid, **limits})
def test_new_attribute_target(self):
d = _dump(_params(target=Target.new_attribute(GRID_URL, "result")))
- self.assertEqual(d["target"]["attribute"]["operation"], "create")
- self.assertEqual(d["target"]["attribute"]["name"], "result")
+ assert d["target"]["attribute"]["operation"] == "create"
+ assert d["target"]["attribute"]["name"] == "result"
def test_update_attribute_target(self):
from evo.compute.tasks.common.source_target import Target as _Target
@@ -190,13 +193,13 @@ def test_update_attribute_target(self):
attribute=UpdateAttribute(operation="update", name="existing", reference="attributes[?key=='abc']"),
)
d = _dump(_params(target=target))
- self.assertEqual(d["target"]["attribute"]["operation"], "update")
- self.assertEqual(d["target"]["attribute"]["reference"], "attributes[?key=='abc']")
+ assert d["target"]["attribute"]["operation"] == "update"
+ assert d["target"]["attribute"]["reference"] == "attributes[?key=='abc']"
def test_no_filter_by_default(self):
d = _dump(_params())
- self.assertNotIn("filter", d.get("target", {}))
- self.assertNotIn("filter", d.get("source", {}))
+ assert "filter" not in d.get("target", {})
+ assert "filter" not in d.get("source", {})
def test_target_filter_injected_into_target(self):
params = _params(
@@ -210,10 +213,10 @@ def test_target_filter_injected_into_target(self):
)
d = _dump(params)
f = d["target"]["filter"]
- self.assertEqual(f["where"]["attribute"], "attributes[?name=='domain']")
- self.assertEqual(f["where"]["operator"], "in")
- self.assertEqual(f["where"]["values"], ["LMS1", "LMS2"])
- self.assertNotIn("filter", d["source"])
+ assert f["where"]["attribute"] == "attributes[?name=='domain']"
+ assert f["where"]["operator"] == "in"
+ assert f["where"]["values"] == ["LMS1", "LMS2"]
+ assert "filter" not in d["source"]
def test_target_filter_with_integer_keys(self):
params = _params(
@@ -226,7 +229,7 @@ def test_target_filter_with_integer_keys(self):
)
)
d = _dump(params)
- self.assertEqual(d["target"]["filter"]["where"]["values"], [1, 2])
+ assert d["target"]["filter"]["where"]["values"] == [1, 2]
def test_source_filter_injected_into_source(self):
params = _params(
@@ -236,8 +239,8 @@ def test_source_filter_injected_into_source(self):
)
d = _dump(params)
f = d["source"]["filter"]
- self.assertEqual(f["where"]["threshold"], 0.0)
- self.assertNotIn("filter", d["target"])
+ assert f["where"]["threshold"] == 0.0
+ assert "filter" not in d["target"]
def test_filter_excluded_from_top_level(self):
"""source_filter / target_filter must not appear at the top-level; only inside source/target."""
@@ -247,8 +250,8 @@ def test_filter_excluded_from_top_level(self):
)
)
d = _dump(params)
- self.assertNotIn("target_filter", d)
- self.assertNotIn("source_filter", d)
+ assert "target_filter" not in d
+ assert "source_filter" not in d
def test_source_construct_shorthand(self):
"""Source accepts (object_url, attribute) via Source(...)."""
@@ -259,7 +262,7 @@ def test_source_construct_shorthand(self):
neighborhood=_search(),
)
d = _dump(params)
- self.assertEqual(d["source"]["attribute"], "grade")
+ assert d["source"]["attribute"] == "grade"
# ---------------------------------------------------------------------------
diff --git a/packages/evo-compute/tests/geostatistics/test_kriging_tasks.py b/packages/evo-compute/tests/geostatistics/test_kriging_tasks.py
index 4973212a0..9da7074be 100644
--- a/packages/evo-compute/tests/geostatistics/test_kriging_tasks.py
+++ b/packages/evo-compute/tests/geostatistics/test_kriging_tasks.py
@@ -15,6 +15,7 @@
from unittest import TestCase
from unittest.mock import MagicMock
+import pytest
from evo.objects import ObjectReference
from evo.objects.typed.attributes import (
Attribute,
@@ -1132,8 +1133,8 @@ def test_integer_rejected(self):
Source(object=12345, attribute="grade")
-class TestSearchNeighborhoodAlias(TestCase):
- """Tests for the search/neighborhood alias on KrigingParameters."""
+class TestSearchNeighborhoodAlias:
+ """Tests for the search/neighborhood and method/kriging_method aliases on KrigingParameters."""
def _make_params(self, **kwargs):
"""Create KrigingParameters with default values, overridable via kwargs."""
@@ -1154,25 +1155,25 @@ def test_search_serializes_as_neighborhood_with_by_alias(self):
"""When by_alias=True, the neighborhood field should serialize as 'neighborhood'."""
params = self._make_params()
params_dict = params.model_dump(mode="json", by_alias=True, exclude_none=True)
- self.assertIn("neighborhood", params_dict)
- self.assertNotIn("search", params_dict)
- self.assertIn("kriging_method", params_dict)
- self.assertNotIn("method", params_dict)
+ assert "neighborhood" in params_dict
+ assert "search" not in params_dict
+ assert "kriging_method" in params_dict
+ assert "method" not in params_dict
def test_always_serializes_neighborhood_and_kriging_method_without_by_alias(self):
"""Even when by_alias=False (default), canonical 'neighborhood' and 'kriging_method' keys are emitted."""
params = self._make_params()
params_dict = params.model_dump()
- self.assertIn("neighborhood", params_dict)
- self.assertNotIn("search", params_dict)
- self.assertIn("kriging_method", params_dict)
- self.assertNotIn("method", params_dict)
+ assert "neighborhood" in params_dict
+ assert "search" not in params_dict
+ assert "kriging_method" in params_dict
+ assert "method" not in params_dict
def test_kriging_method_canonical_and_legacy_alias(self):
"""KrigingParameters accepts both kriging_method=... and method=... and exposes both attributes."""
default_params = self._make_params()
- self.assertIsInstance(default_params.kriging_method, OrdinaryKriging)
- self.assertIs(default_params.method, default_params.kriging_method)
+ assert isinstance(default_params.kriging_method, OrdinaryKriging)
+ assert default_params.method is default_params.kriging_method
via_canonical = KrigingParameters(
source=Source(object=POINTSET_URL, attribute="grade"),
@@ -1184,16 +1185,16 @@ def test_kriging_method_canonical_and_legacy_alias(self):
),
kriging_method=KrigingMethod.simple(mean=42.5),
)
- self.assertIsInstance(via_canonical.kriging_method, SimpleKriging)
- self.assertEqual(via_canonical.kriging_method.mean, 42.5)
- self.assertIs(via_canonical.method, via_canonical.kriging_method)
- self.assertEqual(via_canonical.model_dump()["kriging_method"], {"type": "simple", "mean": 42.5})
+ assert isinstance(via_canonical.kriging_method, SimpleKriging)
+ assert via_canonical.kriging_method.mean == 42.5
+ assert via_canonical.method is via_canonical.kriging_method
+ assert via_canonical.model_dump()["kriging_method"] == {"type": "simple", "mean": 42.5}
via_legacy = self._make_params(method=KrigingMethod.simple(mean=12.0))
- self.assertIsInstance(via_legacy.kriging_method, SimpleKriging)
- self.assertEqual(via_legacy.method.mean, 12.0)
- self.assertIs(via_legacy.method, via_legacy.kriging_method)
- self.assertEqual(via_legacy.model_dump()["kriging_method"], {"type": "simple", "mean": 12.0})
+ assert isinstance(via_legacy.kriging_method, SimpleKriging)
+ assert via_legacy.method.mean == 12.0
+ assert via_legacy.method is via_legacy.kriging_method
+ assert via_legacy.model_dump()["kriging_method"] == {"type": "simple", "mean": 12.0}
def test_search_limits_are_sent_in_the_neighborhood(self):
search = SearchNeighborhood(
@@ -1206,11 +1207,11 @@ def test_search_limits_are_sent_in_the_neighborhood(self):
drillhole_limit_scope="octant",
)
params_dict = self._make_params(search=search).model_dump(mode="json", by_alias=True, exclude_none=True)
- self.assertEqual(params_dict["neighborhood"]["max_samples_per_octant"], 2)
- self.assertEqual(params_dict["neighborhood"]["max_samples_per_drillhole"], 3)
- self.assertEqual(params_dict["neighborhood"]["max_drillholes"], 6)
- self.assertEqual(params_dict["neighborhood"]["min_drillholes"], 2)
- self.assertEqual(params_dict["neighborhood"]["drillhole_limit_scope"], "octant")
+ assert params_dict["neighborhood"]["max_samples_per_octant"] == 2
+ assert params_dict["neighborhood"]["max_samples_per_drillhole"] == 3
+ assert params_dict["neighborhood"]["max_drillholes"] == 6
+ assert params_dict["neighborhood"]["min_drillholes"] == 2
+ assert params_dict["neighborhood"]["drillhole_limit_scope"] == "octant"
default_drillholes = SearchNeighborhood(
ellipsoid=Ellipsoid(ranges=EllipsoidRanges(major=100, semi_major=100, minor=50)),
@@ -1222,16 +1223,16 @@ def test_search_limits_are_sent_in_the_neighborhood(self):
default_dict = self._make_params(search=default_drillholes).model_dump(
mode="json", by_alias=True, exclude_none=True
)
- self.assertEqual(default_dict["neighborhood"]["max_drillholes"], 5)
- self.assertNotIn("max_drillholes_per_estimate", default_dict["neighborhood"])
- self.assertNotIn("min_drillholes", default_dict["neighborhood"])
- self.assertNotIn("drillhole_limit_scope", default_dict["neighborhood"])
+ assert default_dict["neighborhood"]["max_drillholes"] == 5
+ assert "max_drillholes_per_estimate" not in default_dict["neighborhood"]
+ assert "min_drillholes" not in default_dict["neighborhood"]
+ assert "drillhole_limit_scope" not in default_dict["neighborhood"]
def test_can_construct_with_field_name_search(self):
"""Users should be able to construct KrigingParameters with search=..."""
params = self._make_params()
- self.assertIsNotNone(params.neighborhood)
- self.assertIs(params.search, params.neighborhood)
+ assert params.neighborhood is not None
+ assert params.search is params.neighborhood
def test_can_construct_with_alias_neighborhood(self):
"""Users should also be able to construct with neighborhood=..."""
@@ -1245,37 +1246,39 @@ def test_can_construct_with_alias_neighborhood(self):
variogram=VARIOGRAM_URL,
neighborhood=search,
)
- self.assertIs(params.neighborhood, search)
- self.assertIs(params.search, search)
+ assert params.neighborhood is search
+ assert params.search is search
- def test_sample_limit_boundaries_in_neighborhood(self):
+ @pytest.mark.parametrize(("max_samples", "min_samples"), [(1, 1), (20, 1), (20, 20)])
+ def test_sample_limit_boundaries_in_neighborhood(self, max_samples: int, min_samples: int):
ellipsoid = Ellipsoid(ranges=EllipsoidRanges(major=100, semi_major=100, minor=50))
default_min = self._make_params(search={"ellipsoid": ellipsoid, "max_samples": 1}).model_dump(
mode="json", by_alias=True, exclude_none=True
)
- self.assertEqual(default_min["neighborhood"]["max_samples"], 1)
- self.assertNotIn("min_samples", default_min["neighborhood"])
-
- for max_samples, min_samples in [(1, 1), (20, 1), (20, 20)]:
- with self.subTest(max_samples=max_samples, min_samples=min_samples):
- dumped = self._make_params(
- search={"ellipsoid": ellipsoid, "max_samples": max_samples, "min_samples": min_samples}
- ).model_dump(mode="json", by_alias=True, exclude_none=True)
- self.assertEqual(dumped["neighborhood"]["max_samples"], max_samples)
- self.assertEqual(dumped["neighborhood"]["min_samples"], min_samples)
-
- def test_invalid_sample_limits_rejected(self):
+ assert default_min["neighborhood"]["max_samples"] == 1
+ assert "min_samples" not in default_min["neighborhood"]
+
+ dumped = self._make_params(
+ search={"ellipsoid": ellipsoid, "max_samples": max_samples, "min_samples": min_samples}
+ ).model_dump(mode="json", by_alias=True, exclude_none=True)
+ assert dumped["neighborhood"]["max_samples"] == max_samples
+ assert dumped["neighborhood"]["min_samples"] == min_samples
+
+ @pytest.mark.parametrize("field_name", ["search", "neighborhood"])
+ @pytest.mark.parametrize(
+ "limits",
+ [
+ {"max_samples": 0},
+ {"max_samples": 20, "min_samples": 0},
+ {"max_samples": 20, "min_samples": 21},
+ ],
+ )
+ def test_invalid_sample_limits_rejected(self, field_name: str, limits: dict):
ellipsoid = Ellipsoid(ranges=EllipsoidRanges(major=100, semi_major=100, minor=50))
- for field_name in ("search", "neighborhood"):
- for limits in [
- {"max_samples": 0},
- {"max_samples": 20, "min_samples": 0},
- {"max_samples": 20, "min_samples": 21},
- ]:
- with self.subTest(field=field_name, **limits), self.assertRaises(ValidationError):
- KrigingParameters(
- source=Source(object=POINTSET_URL, attribute="grade"),
- target=Target.new_attribute(GRID_URL, "kriged_grade"),
- variogram=VARIOGRAM_URL,
- **{field_name: {"ellipsoid": ellipsoid, **limits}},
- )
+ with pytest.raises(ValidationError):
+ KrigingParameters(
+ source=Source(object=POINTSET_URL, attribute="grade"),
+ target=Target.new_attribute(GRID_URL, "kriged_grade"),
+ variogram=VARIOGRAM_URL,
+ **{field_name: {"ellipsoid": ellipsoid, **limits}},
+ )
diff --git a/packages/evo-compute/tests/geostatistics/test_simulation_report_tasks.py b/packages/evo-compute/tests/geostatistics/test_simulation_report_tasks.py
index d98ac9bd9..8c5f1b64b 100644
--- a/packages/evo-compute/tests/geostatistics/test_simulation_report_tasks.py
+++ b/packages/evo-compute/tests/geostatistics/test_simulation_report_tasks.py
@@ -14,11 +14,12 @@
import unittest
from unittest.mock import AsyncMock, MagicMock, patch
+import pytest
from evo.objects import ObjectReference
from evo.objects.typed.attributes import Attribute, BlockModelAttribute, PendingAttribute
from pydantic import ValidationError
-from evo.compute.tasks import SearchNeighborhood
+from evo.compute.tasks import SearchNeighborhood, SimpleSearchNeighborhood
from evo.compute.tasks.common import Ellipsoid, EllipsoidRanges
from evo.compute.tasks.common.runner import TaskRegistry
from evo.compute.tasks.geostatistics.conditioned_simulator import TailExtrapolationParams, UpperTailParams
@@ -124,75 +125,84 @@ def test_runner_types(self):
# ---------------------------------------------------------------------------
-class TestSimulationReportParametersSerialization(unittest.TestCase):
+class TestSimulationReportParametersSerialization:
def test_flat_fields(self):
d = _dump(_params())
- self.assertEqual(d["simulation_source"], POINTSET_URL)
- self.assertEqual(d["source_attribute"], "locations.attributes[0]")
- self.assertEqual(d["simulation_target"], GRID_URL)
- self.assertEqual(d["point_simulations"], "cell_attributes[0]")
- self.assertEqual(d["point_simulations_normal_score"], "cell_attributes[1]")
- self.assertEqual(d["block_simulations"], "cell_attributes[2]")
- self.assertEqual(d["block_simulations_normal_score"], "cell_attributes[3]")
- self.assertEqual(d["variogram_model"], VARIOGRAM_URL)
+ assert d["simulation_source"] == POINTSET_URL
+ assert d["source_attribute"] == "locations.attributes[0]"
+ assert d["simulation_target"] == GRID_URL
+ assert d["point_simulations"] == "cell_attributes[0]"
+ assert d["point_simulations_normal_score"] == "cell_attributes[1]"
+ assert d["block_simulations"] == "cell_attributes[2]"
+ assert d["block_simulations_normal_score"] == "cell_attributes[3]"
+ assert d["variogram_model"] == VARIOGRAM_URL
def test_neighborhood(self):
- d = _dump(_params())
- self.assertIn("ellipsoid", d["neighborhood"])
- self.assertEqual(d["neighborhood"]["max_samples"], 20)
+ params = _params()
+ assert type(params.neighborhood) is SimpleSearchNeighborhood
+ d = _dump(params)
+ assert "ellipsoid" in d["neighborhood"]
+ assert d["neighborhood"]["max_samples"] == 20
+
+ schema = SimulationReportParameters.model_json_schema()
+ assert set(schema["$defs"]["SimpleSearchNeighborhood"]["properties"]) == {
+ "ellipsoid",
+ "max_samples",
+ "min_samples",
+ }
- def test_search_limits_are_refused(self):
+ @pytest.mark.parametrize(
+ ("kwargs", "expected_field"),
+ [
+ ({"max_samples_per_quadrant": 4}, "max_samples_per_quadrant"),
+ ({"max_drillholes": 4}, "max_drillholes"),
+ ({"min_drillholes": 2}, "min_drillholes"),
+ ({"max_samples_per_drillhole": 2, "drillhole_limit_scope": "octant"}, "drillhole_limit_scope"),
+ ],
+ )
+ def test_search_limits_are_refused(self, kwargs: dict, expected_field: str):
ellipsoid = Ellipsoid(ranges=EllipsoidRanges(major=200.0, semi_major=150.0, minor=100.0))
- for kwargs, expected in [
- ({"max_samples_per_quadrant": 4}, "does not support max_samples_per_quadrant"),
- ({"max_drillholes": 4}, "does not support max_drillholes"),
- ({"min_drillholes": 2}, "does not support min_drillholes"),
- (
- {"max_samples_per_drillhole": 2, "drillhole_limit_scope": "octant"},
- "does not support max_samples_per_drillhole, drillhole_limit_scope",
- ),
- ]:
- with self.subTest(**kwargs), self.assertRaisesRegex(ValidationError, expected):
- _params(neighborhood=SearchNeighborhood(ellipsoid=ellipsoid, max_samples=20, **kwargs))
+ with pytest.raises(ValidationError, match=expected_field):
+ _params(neighborhood=SearchNeighborhood(ellipsoid=ellipsoid, max_samples=20, **kwargs))
def test_block_discretization_defaults(self):
d = _dump(_params())
- self.assertEqual(d["block_discretization"]["nx"], 1)
- self.assertEqual(d["block_discretization"]["ny"], 1)
- self.assertEqual(d["block_discretization"]["nz"], 1)
+ assert d["block_discretization"]["nx"] == 1
+ assert d["block_discretization"]["ny"] == 1
+ assert d["block_discretization"]["nz"] == 1
def test_block_discretization_custom(self):
d = _dump(_params(block_discretization=SimulationReportBlockDiscretization(nx=3, ny=3, nz=3)))
- self.assertEqual(d["block_discretization"]["nx"], 3)
+ assert d["block_discretization"]["nx"] == 3
def test_number_of_simulations(self):
d = _dump(_params())
- self.assertEqual(d["number_of_simulations"], 50)
+ assert d["number_of_simulations"] == 50
def test_kriging_method_default(self):
d = _dump(_params())
- self.assertEqual(d["kriging_method"], "simple")
+ assert d["kriging_method"] == "simple"
def test_number_of_lines_default(self):
d = _dump(_params())
- self.assertEqual(d["number_of_lines"], 500)
+ assert d["number_of_lines"] == 500
def test_distribution_optional(self):
d = _dump(_params())
- self.assertNotIn("distribution", d)
+ assert "distribution" not in d
def test_distribution_with_weights(self):
d = _dump(_params(distribution=SimulationReportDistribution(weights="declustering_weights")))
- self.assertEqual(d["distribution"]["weights"], "declustering_weights")
+ assert d["distribution"]["weights"] == "declustering_weights"
def test_distribution_without_tail_extrapolation_omits_key(self):
d = _dump(_params(distribution=SimulationReportDistribution(weights="declustering_weights")))
- self.assertEqual(d["distribution"], {"weights": "declustering_weights"})
+ assert d["distribution"] == {"weights": "declustering_weights"}
def test_distribution_with_tail_extrapolation(self):
tail = TailExtrapolationParams(upper=UpperTailParams(power=0.5, max=100.0))
d = _dump(_params(distribution=SimulationReportDistribution(tail_extrapolation=tail)))
- self.assertEqual(d["distribution"]["tail_extrapolation"], {"upper": {"power": 0.5, "max": 100.0}})
+ assert d["distribution"]["tail_extrapolation"] == {"upper": {"power": 0.5, "max": 100.0}}
def test_report_context(self):
d = _dump(
@@ -203,19 +213,19 @@ def test_report_context(self):
)
)
)
- self.assertEqual(d["report_context"]["title"], "Test Report")
- self.assertEqual(d["report_context"]["details"][0]["label"], "Variable")
+ assert d["report_context"]["title"] == "Test Report"
+ assert d["report_context"]["details"][0]["label"] == "Variable"
def test_report_mean_thresholds(self):
d = _dump(_params(report_mean_thresholds=SimReportThresholds(acceptable=0.05, marginal=0.10)))
- self.assertAlmostEqual(d["report_mean_thresholds"]["acceptable"], 0.05)
- self.assertAlmostEqual(d["report_mean_thresholds"]["marginal"], 0.10)
+ assert d["report_mean_thresholds"]["acceptable"] == pytest.approx(0.05)
+ assert d["report_mean_thresholds"]["marginal"] == pytest.approx(0.10)
def test_none_optional_fields_excluded(self):
d = _dump(_params())
- self.assertNotIn("distribution", d)
- self.assertNotIn("report_context", d)
- self.assertNotIn("report_mean_thresholds", d)
+ assert "distribution" not in d
+ assert "report_context" not in d
+ assert "report_mean_thresholds" not in d
# ---------------------------------------------------------------------------
diff --git a/packages/evo-compute/tests/test_tasks.py b/packages/evo-compute/tests/test_tasks.py
index e0e50d91a..02102f775 100644
--- a/packages/evo-compute/tests/test_tasks.py
+++ b/packages/evo-compute/tests/test_tasks.py
@@ -15,10 +15,11 @@
import unittest
from unittest.mock import AsyncMock, MagicMock, patch
+import pytest
from evo.objects.exceptions import SchemaIDFormatError
from pydantic import ValidationError
-from evo.compute.tasks import SearchNeighborhood, run
+from evo.compute.tasks import SearchNeighborhood, SimpleSearchNeighborhood, run
from evo.compute.tasks.common import Ellipsoid, EllipsoidRanges, Rotation
from evo.compute.tasks.common.results import TaskAttribute, TaskResultList, TaskTarget
from evo.compute.tasks.common.runner import TaskRegistry, run_tasks
@@ -307,8 +308,8 @@ def test_raises_for_invalid_url(self):
_convert_object_reference("not_a_url")
-class TestSearchNeighborhood(unittest.TestCase):
- """Tests for sample, octant, quadrant, drillhole limits and wire schema on SearchNeighborhood."""
+class TestSearchNeighborhood:
+ """Tests for SimpleSearchNeighborhood and SearchNeighborhood models, re-exports, and wire schemas."""
LIMITS = {
"max_empty_octants": 4,
@@ -328,48 +329,78 @@ def _search(self, max_samples: int = 24, **limits) -> SearchNeighborhood:
**limits,
)
+ @pytest.mark.parametrize(
+ "module_name",
+ [
+ "evo.compute.tasks",
+ "evo.compute.tasks.common",
+ "evo.compute.tasks.common.search",
+ "evo.compute.tasks.geostatistics",
+ "evo.compute.tasks.geostatistics.search",
+ ],
+ )
+ def test_reexports_share_canonical_classes(self, module_name: str):
+ from importlib import import_module
+
+ module = import_module(module_name)
+ assert module.SearchNeighborhood is SearchNeighborhood
+ assert module.SimpleSearchNeighborhood is SimpleSearchNeighborhood
+ assert issubclass(SearchNeighborhood, SimpleSearchNeighborhood)
+
def test_limits_are_omitted_unless_set(self):
search = self._search()
- self.assertIsNone(search.min_samples)
- self.assertIsNone(search.max_drillholes)
- self.assertIsNone(search.min_drillholes)
- self.assertIsNone(search.drillhole_limit_scope)
- self.assertEqual(set(search.model_dump(mode="json")), {"ellipsoid", "max_samples"})
+ assert search.min_samples is None
+ assert search.max_drillholes is None
+ assert search.min_drillholes is None
+ assert search.drillhole_limit_scope is None
+ assert set(search.model_dump(mode="json")) == {"ellipsoid", "max_samples"}
+
+ simple = SimpleSearchNeighborhood(
+ ellipsoid=Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100)),
+ max_samples=24,
+ )
+ assert simple.min_samples is None
+ assert set(simple.model_dump(mode="json")) == {"ellipsoid", "max_samples"}
- def test_sample_limit_boundaries_are_accepted(self):
+ @pytest.mark.parametrize(("max_samples", "min_samples"), [(1, 1), (20, 1), (20, 20)])
+ def test_sample_limit_boundaries_are_accepted(self, max_samples: int, min_samples: int):
single = self._search(max_samples=1).model_dump(mode="json")
- self.assertEqual(single["max_samples"], 1)
- self.assertNotIn("min_samples", single)
+ assert single["max_samples"] == 1
+ assert "min_samples" not in single
- for max_samples, min_samples in [(1, 1), (20, 1), (20, 20)]:
- with self.subTest(max_samples=max_samples, min_samples=min_samples):
- dumped = self._search(max_samples=max_samples, min_samples=min_samples).model_dump(mode="json")
- self.assertEqual(dumped["max_samples"], max_samples)
- self.assertEqual(dumped["min_samples"], min_samples)
+ dumped = self._search(max_samples=max_samples, min_samples=min_samples).model_dump(mode="json")
+ assert dumped["max_samples"] == max_samples
+ assert dumped["min_samples"] == min_samples
- def test_invalid_sample_limits_are_refused(self):
- for kwargs in [
+ @pytest.mark.parametrize("cls", [SimpleSearchNeighborhood, SearchNeighborhood])
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
{"max_samples": 0},
{"max_samples": -1},
{"max_samples": 20, "min_samples": 0},
{"max_samples": 20, "min_samples": -1},
{"max_samples": 20, "min_samples": 21},
{"max_samples": 1, "min_samples": 2},
- ]:
- with self.subTest(**kwargs), self.assertRaises(ValidationError):
- self._search(**kwargs)
+ ],
+ )
+ def test_invalid_sample_limits_are_refused(self, cls: type[SimpleSearchNeighborhood], kwargs: dict):
+ ellipsoid = Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100))
+ with pytest.raises(ValidationError):
+ cls(ellipsoid=ellipsoid, **kwargs)
def test_limits_are_sent_when_set(self):
dumped = self._search(**self.LIMITS).model_dump(mode="json")
- self.assertEqual({name: dumped[name] for name in self.LIMITS}, self.LIMITS)
+ assert {name: dumped[name] for name in self.LIMITS} == self.LIMITS
def test_zero_empty_sectors_is_sent(self):
dumped = self._search(max_empty_octants=0, max_empty_quadrants=0).model_dump(mode="json")
- self.assertEqual(dumped["max_empty_octants"], 0)
- self.assertEqual(dumped["max_empty_quadrants"], 0)
+ assert dumped["max_empty_octants"] == 0
+ assert dumped["max_empty_quadrants"] == 0
- def test_limits_outside_the_service_bounds_are_refused(self):
- for name, value in [
+ @pytest.mark.parametrize(
+ ("name", "value"),
+ [
("max_empty_octants", -1),
("max_empty_octants", 9),
("max_empty_quadrants", -1),
@@ -382,29 +413,41 @@ def test_limits_outside_the_service_bounds_are_refused(self):
("min_drillholes", -1),
("min_drillholes_per_estimate", -1),
("drillhole_limit_scope", "sector"),
- ]:
- with self.subTest(name=name, value=value), self.assertRaises(ValidationError):
- self._search(**{name: value})
+ ("unexpected_field", 1),
+ ],
+ )
+ def test_limits_outside_the_service_bounds_are_refused(self, name: str, value: object):
+ with pytest.raises(ValidationError):
+ self._search(**{name: value})
def test_max_drillholes_backwards_compatibility(self):
via_canonical = self._search(max_drillholes=6)
- self.assertEqual(via_canonical.max_drillholes, 6)
- self.assertEqual(via_canonical.max_drillholes_per_estimate, 6)
+ assert via_canonical.max_drillholes == 6
+ assert via_canonical.max_drillholes_per_estimate == 6
dumped_canonical = via_canonical.model_dump(mode="json", by_alias=True, exclude_none=True)
- self.assertEqual(dumped_canonical["max_drillholes"], 6)
- self.assertNotIn("max_drillholes_per_estimate", dumped_canonical)
+ assert dumped_canonical["max_drillholes"] == 6
+ assert "max_drillholes_per_estimate" not in dumped_canonical
via_legacy = self._search(max_drillholes_per_estimate=6)
- self.assertEqual(via_legacy.max_drillholes, 6)
- self.assertEqual(via_legacy.max_drillholes_per_estimate, 6)
+ assert via_legacy.max_drillholes == 6
+ assert via_legacy.max_drillholes_per_estimate == 6
dumped_legacy = via_legacy.model_dump(mode="json", by_alias=True, exclude_none=True)
- self.assertEqual(dumped_legacy["max_drillholes"], 6)
- self.assertNotIn("max_drillholes_per_estimate", dumped_legacy)
+ assert dumped_legacy["max_drillholes"] == 6
+ assert "max_drillholes_per_estimate" not in dumped_legacy
- with self.assertRaises(AttributeError):
+ with pytest.raises(AttributeError):
via_canonical.max_drillholes_per_estimate = 4 # type: ignore[misc]
- def test_conflicting_drillhole_aliases_are_rejected(self):
+ @pytest.mark.parametrize(
+ "conflicting",
+ [
+ {"max_drillholes": 6, "max_drillholes_per_estimate": 4},
+ {"max_drillholes": None, "max_drillholes_per_estimate": 4},
+ {"min_drillholes": 2, "min_drillholes_per_estimate": 3},
+ {"min_drillholes": 0, "min_drillholes_per_estimate": 2},
+ ],
+ )
+ def test_conflicting_drillhole_aliases_are_rejected(self, conflicting: dict):
ellipsoid = Ellipsoid(ranges=EllipsoidRanges(major=200, semi_major=150, minor=100))
equal = SearchNeighborhood.model_validate(
{
@@ -416,52 +459,46 @@ def test_conflicting_drillhole_aliases_are_rejected(self):
"min_drillholes_per_estimate": 2,
}
)
- self.assertEqual(equal.max_drillholes, 6)
- self.assertEqual(equal.min_drillholes, 2)
+ assert equal.max_drillholes == 6
+ assert equal.min_drillholes == 2
- for conflicting in [
- {"max_drillholes": 6, "max_drillholes_per_estimate": 4},
- {"max_drillholes": None, "max_drillholes_per_estimate": 4},
- {"min_drillholes": 2, "min_drillholes_per_estimate": 3},
- {"min_drillholes": 0, "min_drillholes_per_estimate": 2},
- ]:
- with self.subTest(**conflicting), self.assertRaisesRegex(ValidationError, "Conflicting values"):
- SearchNeighborhood.model_validate({"ellipsoid": ellipsoid, "max_samples": 24, **conflicting})
-
- def test_min_drillholes_omitted_when_none_or_zero_and_emitted_when_positive(self):
- for kwargs in [{}, {"min_drillholes": None}, {"min_drillholes": 0}, {"min_drillholes_per_estimate": 0}]:
- with self.subTest(**kwargs):
- dumped = self._search(**kwargs).model_dump(mode="json", by_alias=True, exclude_none=True)
- self.assertNotIn("min_drillholes", dumped)
- self.assertNotIn("min_drillholes_per_estimate", dumped)
-
- for kwargs in [{"min_drillholes": 3}, {"min_drillholes_per_estimate": 3}]:
- with self.subTest(**kwargs):
- dumped = self._search(**kwargs).model_dump(mode="json", by_alias=True, exclude_none=True)
- self.assertEqual(dumped["min_drillholes"], 3)
- self.assertNotIn("min_drillholes_per_estimate", dumped)
-
- def test_drillhole_limit_scope_omitted_when_global_and_requires_samples_per_drillhole(self):
- for scope in (None, "global"):
- with self.subTest(scope=scope):
- dumped = self._search(drillhole_limit_scope=scope).model_dump(
- mode="json", by_alias=True, exclude_none=True
- )
- self.assertNotIn("drillhole_limit_scope", dumped)
-
- for scope in ("quadrant", "octant"):
- with self.subTest(scope=scope):
- with self.assertRaisesRegex(ValidationError, "requires max_samples_per_drillhole"):
- self._search(drillhole_limit_scope=scope)
-
- dumped = self._search(max_samples_per_drillhole=2, drillhole_limit_scope=scope).model_dump(
- mode="json", by_alias=True, exclude_none=True
- )
- self.assertEqual(dumped["drillhole_limit_scope"], scope)
- self.assertEqual(dumped["max_samples_per_drillhole"], 2)
-
- def test_contradictory_neighborhood_bounds_are_rejected(self):
- valid_cases = [
+ with pytest.raises(ValidationError, match="Conflicting values"):
+ SearchNeighborhood.model_validate({"ellipsoid": ellipsoid, "max_samples": 24, **conflicting})
+
+ @pytest.mark.parametrize(
+ "kwargs",
+ [{}, {"min_drillholes": None}, {"min_drillholes": 0}, {"min_drillholes_per_estimate": 0}],
+ )
+ def test_min_drillholes_omitted_when_none_or_zero(self, kwargs: dict):
+ dumped = self._search(**kwargs).model_dump(mode="json", by_alias=True, exclude_none=True)
+ assert "min_drillholes" not in dumped
+ assert "min_drillholes_per_estimate" not in dumped
+
+ @pytest.mark.parametrize("kwargs", [{"min_drillholes": 3}, {"min_drillholes_per_estimate": 3}])
+ def test_min_drillholes_emitted_when_positive(self, kwargs: dict):
+ dumped = self._search(**kwargs).model_dump(mode="json", by_alias=True, exclude_none=True)
+ assert dumped["min_drillholes"] == 3
+ assert "min_drillholes_per_estimate" not in dumped
+
+ @pytest.mark.parametrize("scope", [None, "global"])
+ def test_drillhole_limit_scope_omitted_when_global(self, scope: str | None):
+ dumped = self._search(drillhole_limit_scope=scope).model_dump(mode="json", by_alias=True, exclude_none=True)
+ assert "drillhole_limit_scope" not in dumped
+
+ @pytest.mark.parametrize("scope", ["quadrant", "octant"])
+ def test_drillhole_limit_scope_requires_samples_per_drillhole(self, scope: str):
+ with pytest.raises(ValidationError, match="requires max_samples_per_drillhole"):
+ self._search(drillhole_limit_scope=scope)
+
+ dumped = self._search(max_samples_per_drillhole=2, drillhole_limit_scope=scope).model_dump(
+ mode="json", by_alias=True, exclude_none=True
+ )
+ assert dumped["drillhole_limit_scope"] == scope
+ assert dumped["max_samples_per_drillhole"] == 2
+
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
{"max_samples": 8, "min_samples": 8, "max_samples_per_octant": 1},
{"max_samples": 8, "min_samples": 8, "max_samples_per_quadrant": 2},
{"max_samples": 20, "min_drillholes": 4, "max_drillholes": 4},
@@ -489,12 +526,14 @@ def test_contradictory_neighborhood_bounds_are_rejected(self):
"drillhole_limit_scope": "quadrant",
},
{"max_samples": 4, "max_empty_quadrants": 0, "max_drillholes": 2, "max_samples_per_drillhole": 2},
- ]
- for kwargs in valid_cases:
- with self.subTest(valid=kwargs):
- self._search(**kwargs)
+ ],
+ )
+ def test_consistent_neighborhood_bounds_are_accepted(self, kwargs: dict):
+ assert self._search(**kwargs) is not None
- invalid_cases = [
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
{"max_samples": 20, "min_samples": 9, "max_samples_per_octant": 1},
{"max_samples": 20, "min_samples": 9, "max_samples_per_quadrant": 2},
{"max_samples": 20, "min_samples": 7, "max_drillholes": 3, "max_samples_per_drillhole": 2},
@@ -521,12 +560,19 @@ def test_contradictory_neighborhood_bounds_are_rejected(self):
{"max_samples": 20, "max_empty_octants": 0, "max_drillholes": 2, "max_samples_per_drillhole": 2},
{"max_samples": 3, "max_empty_quadrants": 0},
{"max_samples": 20, "max_empty_quadrants": 0, "max_drillholes": 1, "max_samples_per_drillhole": 3},
- ]
- for kwargs in invalid_cases:
- with self.subTest(invalid=kwargs), self.assertRaises(ValidationError):
- self._search(**kwargs)
+ ],
+ )
+ def test_contradictory_neighborhood_bounds_are_rejected(self, kwargs: dict):
+ with pytest.raises(ValidationError):
+ self._search(**kwargs)
+
+ @pytest.mark.parametrize("mode", ["validation", "serialization"])
+ def test_model_json_schema_describes_wire_payload(self, mode: str):
+ simple_schema = SimpleSearchNeighborhood.model_json_schema(mode=mode)
+ assert set(simple_schema["properties"]) == {"ellipsoid", "max_samples", "min_samples"}
+ assert simple_schema["required"] == ["ellipsoid", "max_samples"]
+ assert simple_schema["additionalProperties"] is False
- def test_model_json_schema_describes_wire_payload_and_round_trips(self):
expected_fields = {
"ellipsoid",
"max_samples",
@@ -540,21 +586,22 @@ def test_model_json_schema_describes_wire_payload_and_round_trips(self):
"min_drillholes",
"drillhole_limit_scope",
}
- for mode in ("validation", "serialization"):
- with self.subTest(mode=mode):
- schema = SearchNeighborhood.model_json_schema(mode=mode)
- self.assertEqual(set(schema["properties"]), expected_fields)
- self.assertEqual(schema["required"], ["ellipsoid", "max_samples"])
- ellipsoid_schema = schema["properties"]["ellipsoid"]
- self.assertIn("ellipsoid_ranges", ellipsoid_schema["properties"])
- self.assertIn("rotation", ellipsoid_schema["properties"])
- self.assertNotIn("ranges", ellipsoid_schema["properties"])
- self.assertNotIn("_rotation", ellipsoid_schema["properties"])
- self.assertEqual(
- set(ellipsoid_schema["properties"]["ellipsoid_ranges"]["properties"]),
- {"major", "semi_major", "minor"},
- )
+ schema = SearchNeighborhood.model_json_schema(mode=mode)
+ assert set(schema["properties"]) == expected_fields
+ assert schema["required"] == ["ellipsoid", "max_samples"]
+ assert schema["additionalProperties"] is False
+ ellipsoid_schema = schema["properties"]["ellipsoid"]
+ assert "ellipsoid_ranges" in ellipsoid_schema["properties"]
+ assert "rotation" in ellipsoid_schema["properties"]
+ assert "ranges" not in ellipsoid_schema["properties"]
+ assert "_rotation" not in ellipsoid_schema["properties"]
+ assert set(ellipsoid_schema["properties"]["ellipsoid_ranges"]["properties"]) == {
+ "major",
+ "semi_major",
+ "minor",
+ }
+ def test_wire_payload_round_trips(self):
original = SearchNeighborhood(
ellipsoid=Ellipsoid(
ranges=EllipsoidRanges(major=200.0, semi_major=150.0, minor=100.0),
@@ -565,7 +612,7 @@ def test_model_json_schema_describes_wire_payload_and_round_trips(self):
)
wire = original.model_dump(mode="json", by_alias=True, exclude_none=True)
round_tripped = SearchNeighborhood.model_validate(wire)
- self.assertEqual(round_tripped.model_dump(mode="json", by_alias=True, exclude_none=True), wire)
+ assert round_tripped.model_dump(mode="json", by_alias=True, exclude_none=True) == wire
from_attr_dict = SearchNeighborhood.model_validate(
{
@@ -573,9 +620,11 @@ def test_model_json_schema_describes_wire_payload_and_round_trips(self):
"max_samples": 20,
}
)
- self.assertEqual(from_attr_dict.ellipsoid.ranges.major, 200.0)
+ assert from_attr_dict.ellipsoid.ranges.major == 200.0
- for bad_ellipsoid in [
+ @pytest.mark.parametrize(
+ "bad_ellipsoid",
+ [
{
"ellipsoid_ranges": {"major": 200.0, "semi_major": 150.0, "minor": 100.0},
"ranges": {"major": 100.0, "semi_major": 150.0, "minor": 100.0},
@@ -583,9 +632,11 @@ def test_model_json_schema_describes_wire_payload_and_round_trips(self):
{"ellipsoid_ranges": None},
{"ellipsoid_ranges": {"major": 200.0, "semi_major": 150.0, "minor": 100.0}, "rotation": "none"},
{1: 2},
- ]:
- with self.subTest(bad_ellipsoid=bad_ellipsoid), self.assertRaises(ValidationError):
- SearchNeighborhood.model_validate({"ellipsoid": bad_ellipsoid, "max_samples": 20})
+ ],
+ )
+ def test_invalid_ellipsoid_mappings_raise_validation_error(self, bad_ellipsoid: dict):
+ with pytest.raises(ValidationError):
+ SearchNeighborhood.model_validate({"ellipsoid": bad_ellipsoid, "max_samples": 20})
class TestRunTasksDispatch(unittest.IsolatedAsyncioTestCase):
diff --git a/packages/evo-objects/pyproject.toml b/packages/evo-objects/pyproject.toml
index 304cb419d..341edf604 100644
--- a/packages/evo-objects/pyproject.toml
+++ b/packages/evo-objects/pyproject.toml
@@ -1,7 +1,7 @@
[project]
name = "evo-objects"
description = "Python SDK for using the Seequent Evo Geoscience Object API"
-version = "0.7.0"
+version = "0.7.1"
requires-python = ">=3.11.5"
license-files = ["LICENSE.md"]
dynamic = ["readme"]
diff --git a/packages/evo-objects/src/evo/objects/typed/types.py b/packages/evo-objects/src/evo/objects/typed/types.py
index b9df3fad7..604e168bf 100644
--- a/packages/evo-objects/src/evo/objects/typed/types.py
+++ b/packages/evo-objects/src/evo/objects/typed/types.py
@@ -11,13 +11,18 @@
from __future__ import annotations
+import copy
+from collections.abc import Mapping
from dataclasses import dataclass
+from functools import singledispatch
from numbers import Real
from typing import Annotated, Any, overload
import numpy as np
import numpy.typing as npt
import pydantic
+from pydantic.json_schema import JsonSchemaValue
+from pydantic_core import core_schema
# Import basic geometry types from evo.common and re-export
from evo.common.crs import EpsgCode, parse_crs
@@ -298,6 +303,84 @@ def from_array_like(cls, value: EllipsoidRanges | FloatArrayLike3) -> EllipsoidR
return cls(*_validate_array_like(value, kind=Real, positive=True))
+_ELLIPSOID_JSON_SCHEMA: dict[str, Any] = {
+ "type": "object",
+ "title": "Ellipsoid",
+ "additionalProperties": False,
+ "required": ["ellipsoid_ranges", "rotation"],
+ "properties": {
+ "ellipsoid_ranges": {
+ "type": "object",
+ "title": "Ellipsoid Ranges",
+ "additionalProperties": False,
+ "required": ["major", "semi_major", "minor"],
+ "properties": {
+ "major": {"type": "number", "exclusiveMinimum": 0, "title": "Major"},
+ "semi_major": {"type": "number", "exclusiveMinimum": 0, "title": "Semi Major"},
+ "minor": {"type": "number", "exclusiveMinimum": 0, "title": "Minor"},
+ },
+ },
+ "rotation": {
+ "type": "object",
+ "title": "Rotation",
+ "additionalProperties": False,
+ "properties": {
+ "dip_azimuth": {"type": "number", "minimum": 0, "maximum": 360, "default": 0, "title": "Dip Azimuth"},
+ "dip": {"type": "number", "minimum": 0, "maximum": 180, "default": 0, "title": "Dip"},
+ "pitch": {"type": "number", "minimum": 0, "maximum": 360, "default": 0, "title": "Pitch"},
+ },
+ },
+ },
+}
+
+
+def _build_rotation(*, dip_azimuth: float = 0.0, dip: float = 0.0, pitch: float = 0.0) -> Rotation:
+ return Rotation(dip_azimuth=dip_azimuth, dip=dip, pitch=pitch)
+
+
+@singledispatch
+def _parse_ellipsoid_ranges(raw: Any) -> EllipsoidRanges:
+ try:
+ return EllipsoidRanges.from_array_like(raw)
+ except TypeError as exc:
+ raise ValueError(str(exc)) from exc
+
+
+@_parse_ellipsoid_ranges.register(EllipsoidRanges)
+def _(raw: EllipsoidRanges) -> EllipsoidRanges:
+ return EllipsoidRanges.from_array_like(raw)
+
+
+@_parse_ellipsoid_ranges.register(Mapping)
+def _(raw: Mapping[str, Any]) -> EllipsoidRanges:
+ try:
+ return EllipsoidRanges(**raw)
+ except TypeError as exc:
+ raise ValueError(str(exc)) from exc
+
+
+@singledispatch
+def _parse_rotation(raw: Any) -> Rotation | None:
+ try:
+ return Rotation.from_array_like(raw)
+ except TypeError as exc:
+ raise ValueError(str(exc)) from exc
+
+
+@_parse_rotation.register(type(None))
+@_parse_rotation.register(Rotation)
+def _(raw: Rotation | None) -> Rotation | None:
+ return raw
+
+
+@_parse_rotation.register(Mapping)
+def _(raw: Mapping[str, Any]) -> Rotation:
+ try:
+ return _build_rotation(**raw)
+ except TypeError as exc:
+ raise ValueError(str(exc)) from exc
+
+
@dataclass
class Ellipsoid:
"""An ellipsoid defining a spatial region.
@@ -321,7 +404,7 @@ def __init__(
rotation: Rotation | FloatArrayLike3 | None = None,
):
self.ranges = EllipsoidRanges.from_array_like(ranges)
- self._rotation = Rotation.from_array_like(rotation) if rotation is not None else None
+ self._rotation = Rotation.from_array_like(rotation) if rotation is not None else Rotation(0.0, 0.0, 0.0)
@property
def rotation(self) -> Rotation:
@@ -338,6 +421,52 @@ def to_dict(self) -> dict[str, Any]:
},
}
+ @classmethod
+ def from_dict(cls, data: Mapping[str, Any]) -> Ellipsoid:
+ """Construct an :class:`Ellipsoid` from a wire-shaped mapping.
+
+ Accepts ``ellipsoid_ranges`` (or ``ranges``) and an optional ``rotation``
+ mapping whose omitted angles default to ``0``.
+ """
+ unknown = set(data) - {"ellipsoid_ranges", "ranges", "rotation"}
+ if unknown:
+ raise ValueError(f"Unexpected ellipsoid field(s): {', '.join(sorted(map(str, unknown)))}.")
+ if "ellipsoid_ranges" not in data and "ranges" not in data:
+ raise ValueError("Ellipsoid mapping requires 'ellipsoid_ranges' (or 'ranges').")
+ if "ellipsoid_ranges" in data and "ranges" in data:
+ wire_ranges = _parse_ellipsoid_ranges(data["ellipsoid_ranges"])
+ attr_ranges = _parse_ellipsoid_ranges(data["ranges"])
+ if wire_ranges.to_dict() != attr_ranges.to_dict():
+ raise ValueError("Conflicting 'ellipsoid_ranges' and 'ranges' values on ellipsoid.")
+ ranges = wire_ranges
+ elif "ellipsoid_ranges" in data:
+ ranges = _parse_ellipsoid_ranges(data["ellipsoid_ranges"])
+ else:
+ ranges = _parse_ellipsoid_ranges(data["ranges"])
+ return cls(ranges=ranges, rotation=_parse_rotation(data.get("rotation")))
+
+ @classmethod
+ def __get_pydantic_core_schema__(
+ cls, _source_type: Any, _handler: pydantic.GetCoreSchemaHandler
+ ) -> core_schema.CoreSchema:
+ def _validate(value: Any) -> Ellipsoid:
+ if isinstance(value, cls):
+ return value
+ if isinstance(value, Mapping):
+ return cls.from_dict(value)
+ raise ValueError(f"Expected an Ellipsoid or mapping, got {type(value).__name__}.")
+
+ return core_schema.no_info_plain_validator_function(
+ _validate,
+ serialization=core_schema.plain_serializer_function_ser_schema(cls.to_dict),
+ )
+
+ @classmethod
+ def __get_pydantic_json_schema__(
+ cls, _core_schema: core_schema.CoreSchema, _handler: pydantic.GetJsonSchemaHandler
+ ) -> JsonSchemaValue:
+ return copy.deepcopy(_ELLIPSOID_JSON_SCHEMA)
+
def scaled(self, factor: float) -> "Ellipsoid":
return Ellipsoid(
ranges=self.ranges.scaled(factor),
diff --git a/packages/evo-objects/tests/typed/test_types.py b/packages/evo-objects/tests/typed/test_types.py
index 0d9c0dd85..1c51f9d0e 100644
--- a/packages/evo-objects/tests/typed/test_types.py
+++ b/packages/evo-objects/tests/typed/test_types.py
@@ -15,8 +15,9 @@
import numpy as np
import numpy.testing as npt
+import pytest
from parameterized import parameterized
-from pydantic import TypeAdapter, ValidationError
+from pydantic import BaseModel, TypeAdapter, ValidationError
from evo.common import EpsgCode as CommonEpsgCode
from evo.objects.typed import (
@@ -464,3 +465,86 @@ def test_wireframe_with_rotation(self):
x2, y2, z2 = ell_rot.wireframe_points()
# Rotated should have different coordinates
self.assertFalse(np.allclose(x1, x2, equal_nan=True))
+
+
+class _EllipsoidContainer(BaseModel):
+ ellipsoid: Ellipsoid
+
+
+class TestEllipsoidPydantic:
+ """Tests for Ellipsoid.from_dict and Pydantic validation, serialization, and JSON schema."""
+
+ @pytest.mark.parametrize(
+ "original",
+ [
+ Ellipsoid(ranges=EllipsoidRanges(major=200.0, semi_major=150.0, minor=100.0)),
+ Ellipsoid(
+ ranges=EllipsoidRanges(major=200.0, semi_major=150.0, minor=100.0),
+ rotation=Rotation(dip_azimuth=45.0, dip=30.0, pitch=15.0),
+ ),
+ ],
+ )
+ def test_wire_round_trip_and_json_schema(self, original: Ellipsoid):
+ container = _EllipsoidContainer(ellipsoid=original)
+ dumped = container.model_dump(mode="json")
+ assert dumped == {"ellipsoid": original.to_dict()}
+
+ reloaded = _EllipsoidContainer.model_validate(dumped)
+ assert reloaded == container
+ assert reloaded.ellipsoid == original
+ assert Ellipsoid.from_dict(original.to_dict()) == original
+
+ for mode in ("validation", "serialization"):
+ schema = _EllipsoidContainer.model_json_schema(mode=mode)["properties"]["ellipsoid"]
+ assert schema["required"] == ["ellipsoid_ranges", "rotation"]
+ assert set(schema["properties"]) == {"ellipsoid_ranges", "rotation"}
+ assert set(schema["properties"]["ellipsoid_ranges"]["properties"]) == {"major", "semi_major", "minor"}
+
+ @pytest.mark.parametrize(
+ ("payload", "expected_rotation"),
+ [
+ (
+ {"ellipsoid_ranges": {"major": 200.0, "semi_major": 150.0, "minor": 100.0}},
+ Rotation(0.0, 0.0, 0.0),
+ ),
+ (
+ {"ranges": {"major": 200.0, "semi_major": 150.0, "minor": 100.0}, "rotation": {"dip_azimuth": 60.0}},
+ Rotation(60.0, 0.0, 0.0),
+ ),
+ (
+ {"ellipsoid_ranges": (200.0, 150.0, 100.0), "rotation": (10.0, 20.0, 30.0)},
+ Rotation(10.0, 20.0, 30.0),
+ ),
+ ],
+ )
+ def test_valid_ellipsoid_mappings(self, payload, expected_rotation):
+ parsed = _EllipsoidContainer.model_validate({"ellipsoid": payload}).ellipsoid
+ assert parsed.ranges == EllipsoidRanges(200.0, 150.0, 100.0)
+ assert parsed.rotation == expected_rotation
+
+ @pytest.mark.parametrize(
+ "bad_payload",
+ [
+ "not_an_ellipsoid",
+ {},
+ {"ellipsoid_ranges": None},
+ {"ellipsoid_ranges": {"major": 200.0, "semi_major": 150.0}},
+ {"ellipsoid_ranges": {"major": 200.0, "semi_major": 150.0, "minor": 100.0, "extra": 1.0}},
+ {
+ "ellipsoid_ranges": {"major": 200.0, "semi_major": 150.0, "minor": 100.0},
+ "ranges": {"major": 100.0, "semi_major": 150.0, "minor": 100.0},
+ },
+ {
+ "ellipsoid_ranges": {"major": 200.0, "semi_major": 150.0, "minor": 100.0},
+ "rotation": {"extra": 10.0},
+ },
+ {
+ "ellipsoid_ranges": {"major": 200.0, "semi_major": 150.0, "minor": 100.0},
+ "rotation": "none",
+ },
+ {1: 2},
+ ],
+ )
+ def test_invalid_ellipsoid_payloads_raise_validation_error(self, bad_payload):
+ with pytest.raises(ValidationError):
+ _EllipsoidContainer.model_validate({"ellipsoid": bad_payload})
diff --git a/uv.lock b/uv.lock
index 1e2a03667..05685fafc 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1077,7 +1077,7 @@ test = [
[[package]]
name = "evo-objects"
-version = "0.7.0"
+version = "0.7.1"
source = { editable = "packages/evo-objects" }
dependencies = [
{ name = "evo-sdk-common", extra = ["jmespath"] },