Source code for mpt4py.geometry.union.union
import numpy as np
from typing import Tuple, List
from mpt4py.base import Vector
from mpt4py.geometry.convexset import ConvexSet
[docs]
class ConvexSetUnion:
r"""Represents a general union of convex sets.
"""
def __init__(self, *convex_sets: ConvexSet):
r"""Initializes the union of convex sets.
Args:
*convex_sets: Convex sets to be included in the union.
"""
if not all(isinstance(convex_set, ConvexSet) for convex_set in convex_sets):
raise TypeError("All elements must be instances of ConvexSet.")
if not all(convex_set.dim == convex_sets[0].dim for convex_set in convex_sets):
raise ValueError("All convex sets must have the same dimension of representation.")
self._cvxsets = list(convex_sets)
@property
def num_sets(self) -> int:
r"""Returns the number of convex sets in the union."""
return len(self._cvxsets)
def __len__(self) -> int:
r"""Returns the number of convex sets in the union."""
return self.num_sets
def __getitem__(self, index: int) -> ConvexSet:
r"""Returns the convex set at the specified index."""
if index < 0 or index >= len(self._cvxsets):
raise IndexError("Index out of range.")
return self._cvxsets[index]
def __iter__(self):
r"""Returns an iterator over the convex sets in the union."""
return iter(self._cvxsets)
def __repr__(self):
return f"Union of {len(self._cvxsets)} convex sets."
@property
def dim(self) -> int:
r"""Returns the dimension of the convex sets in the union."""
if len(self._cvxsets) == 0:
raise ValueError("The union is empty.")
return self._cvxsets[0].dim
[docs]
def remove(self, index: int):
r"""Removes the convex set at the specified index."""
if index < 0 or index >= len(self._cvxsets):
raise IndexError("Index out of range.")
del self._cvxsets[index]
[docs]
def add(self, set: ConvexSet):
r"""Adds a convex set to the union."""
if not isinstance(set, ConvexSet):
raise TypeError("The element must be an instance of ConvexSet.")
self._cvxsets.append(set)
def __contains__(self, x: Vector) -> bool:
r"""Checks if the point x is in the union of convex sets."""
isin, _ = self.contains(x, fastbreak=True)
return isin
[docs]
def contains(self, x: Vector, fastbreak: bool = False) -> Tuple[bool, List[int]]:
"""Test if the point x is in the union of convex sets.
Args:
x (Vector): A point with the same dimension as the convex sets.
fastbreak (bool): Do a quick stop in the consecutive search when x is contained in the first set it founds. Defaults to False.
Returns:
Tuple[bool, List[int]]: whether x is in the union of convex sets or not, and the indices of the sets that contain x.
"""
if not isinstance(x, np.ndarray):
raise TypeError("x must be an instance of Vector.")
if len(x) != self._cvxsets[0].dim:
raise ValueError("x must have the same dimension as the convex sets.")
contained = []
for i, cvxset in enumerate(self._cvxsets):
if x in cvxset:
contained.append(i)
if fastbreak:
break
return len(contained) > 0, contained