@@ -28,6 +28,7 @@ def __init__(
2828 metric : Callable [[NDArray ], float ] | str | None = None ,
2929 heuristic : Callable [[NDArray ], float ] | str | None = None ,
3030 verbose : bool = False ,
31+ dim : int | None = None ,
3132 ):
3233 """
3334 Abstract base class for graphs
@@ -39,17 +40,25 @@ def __init__(
3940 :type heuristic: callable or str, optional
4041 :param verbose: print diagnostic information as vertices/edges are
4142 added, defaults to False
43+ :param dim: required length of every vertex's ``coord``, defaults to
44+ None (unconstrained -- vertices may have coordinates of any
45+ length, or none at all)
46+ :type dim: int, optional
47+ :raises ValueError: ``dim`` is given but is not a positive integer
4248
4349 This is the common base class of :class:`UGraph` and :class:`DGraph`
4450 and should not be instantiated directly.
4551
46- :seealso: :class:`UGraph` :class:`DGraph`
52+ :seealso: :class:`UGraph` :class:`DGraph` :meth:`add_vertex`
4753 """
54+ if dim is not None and dim <= 0 :
55+ raise ValueError (f"dim must be a positive integer, got { dim !r} " )
4856 # we use a list and a dict, the list respects the order of adding
4957 self ._vertexlist : list [BaseVertex ] = []
5058 self ._vertexdict : dict [str , BaseVertex ] = {}
5159 self ._edgelist : set [Edge ] = set ()
5260 self ._verbose = verbose
61+ self ._dim = dim
5362 self ._ncomponents = 0
5463 self ._connectivitychange = False
5564 if metric is None :
@@ -249,6 +258,8 @@ def add_vertex(
249258 :param name: name of vertex, defaults to "#i"
250259 :type name: str, optional
251260 :raises TypeError: ``coord`` is a ``BaseVertex`` of the wrong kind
261+ :raises ValueError: the graph was constructed with ``dim``, and
262+ ``coord`` is given but its length doesn't match
252263 :return: the added vertex
253264 :rtype: BaseVertex subclass
254265
@@ -276,6 +287,18 @@ def add_vertex(
276287 >>> v2 = g.add_vertex(UVertex(coord=[1,1], name='v2'))
277288 >>> print(v2.name)
278289
290+ If the graph was constructed with a required ``dim`` (see
291+ :meth:`_BaseGraph.__init__`), every embedded vertex must have a
292+ coordinate of exactly that length -- adding one of the wrong length
293+ raises ``ValueError``:
294+
295+ .. runblock:: pycon
296+
297+ >>> from pgraph import UGraph
298+ >>> g = UGraph(dim=6)
299+ >>> v1 = g.add_vertex(coord=[0, 0, 0, 0, 0, 0], name='pose1')
300+ >>> print(v1)
301+
279302 :seealso: :meth:`vertex_copy`
280303 """
281304 if isinstance (coord , self ._vertex_cls ):
@@ -288,6 +311,16 @@ def add_vertex(
288311 else :
289312 vertex = self ._vertex_cls (coord , name = name )
290313
314+ if (
315+ self ._dim is not None
316+ and vertex .coord is not None
317+ and len (vertex .coord ) != self ._dim
318+ ):
319+ raise ValueError (
320+ f"vertex coord has length { len (vertex .coord )} , "
321+ f"but this graph requires dim={ self ._dim } "
322+ )
323+
291324 if name is None :
292325 name = vertex .name
293326 if name is None :
0 commit comments