util#

General-purpose utilities used throughout Pangolin.

This foundational module does not import or use other parts of Pangolin.

type pangolin.util.PyTree = T | Sequence[PyTree] | Mapping[Any, PyTree]#

Statically checkable approximation of a JAX PyTree whose leaves have type T.

Unlike jaxtyping.PyTree, which is runtime-only, this alias lets static checkers enforce T. The recursive interfaces are read-only so concrete container types are preserved. JAX’s runtime registry remains authoritative. None is accepted only when it is included in T.

pangolin.util.comma_separated(stuff, fun=None, parens=True, spaces=False)[source]#

Join a sequence into a comma-separated string.

Parameters:
  • stuff (Sequence[Any]) – Strings to join.

  • fun (Callable[[Any], str] | None) – Optional conversion applied to each item before joining.

  • parens (bool) – Whether to surround the result with parentheses.

  • spaces (bool) – Whether to add a space after each comma.

Return type:

str

Examples

>>> comma_separated(['a', 'b', 'c'])
'(a,b,c)'
>>> comma_separated(['a', 'b', 'c'], lambda s: s + "0")
'(a0,b0,c0)'
>>> comma_separated(['a', 'b', 'c'], parens=False)
'a,b,c'
>>> comma_separated(['a', 'b', 'c'], lambda s: s + "0", parens=False)
'a0,b0,c0'
>>> comma_separated(['a', 'b', 'c'], spaces=True)
'(a, b, c)'
>>> comma_separated(['a', 'b', 'c'], lambda s: s + "0", spaces=True)
'(a0, b0, c0)'
pangolin.util.num_not_none(*args)[source]#

Count the arguments that are not None.

Examples

>>> num_not_none(1)
1
>>> num_not_none(1,2)
2
>>> num_not_none(1,None)
1
>>> num_not_none(None,1,None)
1
>>> num_not_none(None,"cat","dog",77,None)
3
Parameters:

args (Any)

Return type:

int

pangolin.util.all_unique(a)[source]#

Return whether every item in a sequence is unique.

The items must be hashable.

Examples

>>> all_unique([1, 2, 3])
True
>>> all_unique([1, 2, 1])
False
Parameters:

a (Sequence[Any])

Return type:

bool

pangolin.util.intersects(A, B)[source]#

Return whether two iterables contain a common item.

The items must be hashable.

Examples

>>> intersects([1, 2, 3], [3, 4, 5])
True
>>> intersects(['apple', 'banana'], ['orange', 'grape'])
False
Parameters:
  • A (Iterable[Any])

  • B (Iterable[Any])

Return type:

bool

pangolin.util.nth_index(lst, item, n)[source]#

Return the index of the n-th occurrence of an item.

Occurrences are numbered from zero. An IndexError is raised if the requested occurrence does not exist.

Examples

>>> nth_index(['a', 'b', 'a'], 'a', 1)
2
Parameters:
  • lst (Sequence[Any])

  • item (Any)

  • n (int)

Return type:

int

pangolin.util.first_index(lst, condition)[source]#

Return the index of the first item satisfying a condition.

An Exception is raised if no item satisfies the condition.

Examples

>>> first_index([1, 4, 7], lambda x: x > 3)
1
Parameters:
  • lst (Sequence[Any])

  • condition (Callable[[Any], bool])

Return type:

int

pangolin.util.first(lst, cond, default=None)[source]#

Return the first item satisfying a condition, or a default value.

Examples

>>> first([1, 4, 7], lambda x: x > 3)
4
>>> first([1, 4, 7], lambda x: x > 10, default='missing')
'missing'
Parameters:
  • lst (Iterable[Any])

  • cond (Callable[[Any], bool])

  • default (Any)

Return type:

Any

pangolin.util.swapped_list(lst, i, j)[source]#

Return a shallow copy of a list with two items exchanged.

Examples

>>> swapped_list(['a', 'b', 'c'], 0, 2)
['c', 'b', 'a']
Parameters:
  • lst (list[Any])

  • i (int)

  • j (int)

Return type:

list[Any]

pangolin.util.replace_in_sequence(seq: list[Any], i: int, new: Any) → list[Any][source]#
pangolin.util.replace_in_sequence(seq: tuple[Any, ...], i: int, new: Any) → tuple[Any, ...]

Return a list or tuple with one item replaced, preserving its type.

Examples

>>> replace_in_sequence(('a', 'b', 'c'), 1, 'x')
('a', 'x', 'c')
Parameters:
  • seq (list[Any] | tuple[Any, ...])

  • i (int)

  • new (Any)

Return type:

list[Any] | tuple[Any, …]

pangolin.util.reverse_dict(d)[source]#

Exchange the keys and values of a dictionary.

Later keys win when the input contains duplicate values.

Examples

>>> reverse_dict({'a': 1, 'b': 2})
{1: 'a', 2: 'b'}
Parameters:

d (dict[Any, Any])

Return type:

dict[Any, Any]

pangolin.util.node_names(nodes, namespace)[source]#

Find all names of selected objects in a namespace and its nested containers.

Parameters:
  • nodes (Iterable) – Objects to name, matched by identity, without traversing their parents. Objects must be hashable and distinct objects must not compare equal, as for DAG nodes and RVs.

  • namespace (Mapping[str, object]) – Mapping from names to values, such as locals(). Dictionary values, lists, and tuples are searched recursively in iteration order. Other values are leaves; dictionary keys are used in paths but are not searched. Containers must be acyclic and must not change during traversal.

Returns:

dict – Each matched object maps to all its names in depth-first namespace traversal order. Names use list/tuple indices and the repr of dictionary keys, for example states[0] or params['scale']. Missing objects are omitted. Shared containers are traversed once; their relative paths are reused for every occurrence. Selected objects are treated as leaves, even if they are themselves containers. Repeated names for the same object are retained, but a name shared by distinct selected objects is rejected.

Raises:

ValueError – If a cycle is encountered in the searched containers, or a name refers to two distinct selected objects.

Return type:

dict[N, list[str]]

Examples

>>> x, y = object(), object()
>>> names = node_names([x, y], {"states": [x, x, y], "x": x})
>>> names[x]
['states[0]', 'states[1]', 'x']
>>> names[y]
['states[2]']
>>> shared = {"scale": (y,)}
>>> node_names([y], {"a": shared, "b": shared})[y]
["a['scale'][0]", "b['scale'][0]"]
>>> node_names([x], {"count": 3})
{}
pangolin.util.unzip(source, strict=False)[source]#

Transpose a sequence of tuples, reversing zip.

Examples

>>> tuple(unzip([(1, 'a'), (2, 'b')]))
((1, 2), ('a', 'b'))
Parameters:
  • source (Sequence[tuple[Any, ...]])

  • strict (bool)

Return type:

zip

pangolin.util.starts_with(main, prefix)[source]#

Return whether a sequence begins with another sequence.

Examples

>>> starts_with([1, 2, 3], [1, 2])
True
Parameters:
  • main (Sequence[Any])

  • prefix (Sequence[Any])

Return type:

bool

pangolin.util.num2str(id)[source]#

Encode a nonnegative integer using lowercase letters as base-26 digits.

Examples

>>> [num2str(i) for i in (0, 25, 26, 676)]
['a', 'z', 'ba', 'baa']
Parameters:

id (int)

Return type:

str

pangolin.util.camel_case_to_snake_case(name)[source]#

Convert a CamelCase name to snake_case.

Examples

>>> camel_case_to_snake_case('NormalPrec')
'normal_prec'
Parameters:

name (str)

Return type:

str

pangolin.util.is_shape_tuple(a)[source]#

Return whether an object is a tuple containing only integers.

Examples

>>> is_shape_tuple((2, 3, 4))
True
>>> is_shape_tuple([2, 3, 4])
False
Parameters:

a (Any)

Return type:

bool

pangolin.util.is_numeric_numpy_array(x)[source]#

Return whether a NumPy array has an integer or floating-point dtype.

Examples

>>> is_numeric_numpy_array(np.array([1.0, 2.0]))
True
>>> is_numeric_numpy_array(np.array(['a', 'b']))
False
Parameters:

x (ndarray)

Return type:

bool

pangolin.util.most_specific_class(*args, base_classes=())[source]#

Find the single most-specific class shared by the given classes.

The candidates are the runtime classes of args plus base_classes. A ValueError is raised if no candidate is a subclass of every other candidate.

Examples

>>> most_specific_class(1, True)
<class 'bool'>
Parameters:
  • args (Any)

  • base_classes (tuple[type, ...])

Return type:

type

class pangolin.util.VarNames[source]#

Assign a stable, unique string name to each object encountered.

Examples

>>> var_names = VarNames()
>>> var_names['bob']
'v0v'
>>> var_names['alice']
'v1v'
>>> var_names['bob']
'v0v'
>>> var_names['carlos']
'v2v'
>>> var_names['alice']
'v1v'
>>> var_names['bob']
'v0v'
class pangolin.util.WriteOnceDict[source]#

Dictionary that rejects attempts to overwrite an existing key.

Examples

>>> d = WriteOnceDict()
>>> d['a'] = 2
>>> d['a']
2
>>> d['b'] = 3
>>> d['b']
3
>>> d['a'] = 1
Traceback (most recent call last):
ValueError: Cannot overwrite existing key a in WriteOnceDict
class pangolin.util.WriteOnceDefaultDict(default_factory)[source]#

Write-once dictionary that creates missing values on first access.

Accessing a missing key calls default_factory with that key and stores the result. Once a key has been written or accessed, its value cannot be changed.

Parameters:

default_factory (Callable[[Any], Any]) – Function used to create values for missing keys.

Examples

>>> d = WriteOnceDefaultDict(lambda s : len(s))
>>> d['cat'] = 5
>>> d['bob']
3
>>> d['cat']
5
>>> d['bob'] = 5 # raises an error (as expected)
Traceback (most recent call last):
ValueError: Cannot overwrite existing key bob in WriteOnceDefaultDict
pangolin.util.is_leaf_with_none(xi)[source]#

Return whether a PyTree node is None.

Pass this predicate to JAX PyTree functions when None must be retained as a leaf instead of treated as an empty tree.

Examples

>>> is_leaf_with_none(None)
True
>>> is_leaf_with_none(0)
False
Parameters:

xi (Any)

Return type:

bool

pangolin.util.tree_map_with_none_as_leaf(f, tree, *rest)[source]#

Map over PyTrees while treating None as a leaf.

This behaves like jax.tree_util.tree_map(), except that None nodes are passed to f instead of treated as empty trees.

Parameters:
  • f (Callable[[...], Any]) – Function applied to corresponding leaves.

  • tree (PyTree) – PyTree that supplies the first argument to f.

  • rest (PyTree) – Additional PyTrees that supply subsequent arguments to f.

Return type:

PyTree

Examples

>>> f = lambda x: 0 if x is None else len(x)
>>> tree = ["cat", ("bear", None)]
>>> jax.tree_util.tree_map(f, tree)
[3, (4, None)]
>>> tree_map_with_none_as_leaf(f, tree)
[3, (4, 0)]
>>> f2 = lambda leaf, seq: f(leaf) + len(seq)
>>> tree1 = ["cat", ("bear", None)]
>>> tree2 = [[1,2,3,4,5], ([], [1,2,3,4,5])]
>>> tree_map_with_none_as_leaf(f2, tree1, tree2)
[8, (4, 5)]
pangolin.util.tree_flatten_with_none_as_leaf(x)[source]#

Flatten a PyTree while retaining None as a leaf.

Examples

>>> leaves, treedef = tree_flatten_with_none_as_leaf([1, None])
>>> leaves
[1, None]
>>> jax.tree_util.tree_unflatten(treedef, leaves)
[1, None]
Parameters:

x (PyTree)

Return type:

tuple[list[Any], Any]

pangolin.util.tree_flatten_with_path_with_none_as_leaf(x)[source]#

Flatten a PyTree with paths while retaining None as a leaf.

Examples

>>> path_leaves, _ = tree_flatten_with_path_with_none_as_leaf({"x": [1, None]})
>>> [(jax.tree_util.keystr(path), leaf) for path, leaf in path_leaves]
[("['x'][0]", 1), ("['x'][1]", None)]
Parameters:

x (PyTree)

Return type:

tuple[list[tuple[Any, Any]], Any]

pangolin.util.tree_map_recurse_at_leaf(f, tree, *remaining_trees, is_leaf=None)[source]#

Map over PyTrees, recursing into later trees where the first has a leaf.

If tree has a leaf where a remaining tree has a subtree, that leaf is broadcast to every corresponding leaf in the remaining subtree. The result has the expanded structure of the remaining trees.

Parameters:
  • f (Callable[[...], Any]) – Function applied to corresponding leaves.

  • tree (PyTree) – Primary PyTree, whose leaves trigger recursive broadcasting.

  • remaining_trees (PyTree) – PyTrees whose corresponding subtrees determine the expanded structure.

  • is_leaf (Callable[[Any], bool] | None) – Optional predicate used by both the outer and inner PyTree mappings.

Return type:

PyTree

Notes

If tree has a subtree where a remaining tree has a leaf, JAX raises a ValueError for the structural mismatch.

Examples

>>> tree1 = {'c': 5, 'd': 6}
>>> tree2 = {'c': 2, 'd': 3}
>>> tree_map_recurse_at_leaf(lambda l1, l2: l1 * l2, tree1, tree2)
{'c': 10, 'd': 18}
>>> tree1 = {'a': 10, 'b': 20}
>>> tree2 = {'a': {'x': 1, 'y': 2}, 'b': 3}
>>> tree_map_recurse_at_leaf(lambda l1, l2: l1 * l2, tree1, tree2)
{'a': {'x': 10, 'y': 20}, 'b': 60}
>>> tree1 = {'data': 100, 'config': None}
>>> tree2 = {'data': {'val': 1, 'factor': 2}, 'config': 'default'}
>>> tree_map_recurse_at_leaf(
...     lambda l1, l2: f"{l1}_{l2}" if l1 is None else l1 * l2,
...     tree1, tree2, is_leaf=lambda x: x is None
... )
{'config': 'None_default', 'data': {'factor': 200, 'val': 100}}
pangolin.util.tree_map_recurse_at_leaf_with_none_as_leaf(f, tree, *remaining_trees)[source]#

Recursively broadcast a PyTree mapping while retaining None leaves.

This is tree_map_recurse_at_leaf() with is_leaf_with_none() selected as its leaf predicate.

Examples

>>> pytree1 = (0,[1,2])
>>> pytree2 = ("dog", ["cat", None])
>>> tree_map_recurse_at_leaf_with_none_as_leaf(lambda a,b: a, pytree1, pytree2)
(0, [1, 2])
>>> pytree1 = 3
>>> pytree2 = {"cat": 0, "dog": 2}
>>> tree_map_recurse_at_leaf_with_none_as_leaf(lambda a,b: a, pytree1, pytree2)
{'cat': 3, 'dog': 3}
Parameters:
  • f (Callable[[...], Any])

  • tree (PyTree)

  • remaining_trees (PyTree)

Return type:

PyTree

pangolin.util.flatten_fun(f, *args, is_leaf=None)[source]#

Adapt a PyTree function to accept and return flat lists of leaves.

args establish the input structure and evaluate f once to establish its output structure. The returned callables respectively evaluate the flat function, flatten new inputs, and reconstruct outputs.

Parameters:
  • f (Callable[[...], TypeAliasForwardRef('PyTree')]) – Function to adapt.

  • args (Any) – Representative arguments establishing the expected input structure.

  • is_leaf (Callable[[Any], bool] | None) – Optional PyTree leaf predicate.

Return type:

tuple[Callable, Callable, Callable]

Examples

>>> def process(state, scale):
...     return {"x": state["x"] * scale, "y": state["y"] * scale}
>>> flat_f, flatten_input, unflatten_output = flatten_fun(
...     process, {"x": 1.0, "y": 2.0}, 5.0
... )
>>> flat_input = flatten_input({"x": 10.0, "y": 20.0}, 2.0)
>>> flat_input
[10.0, 20.0, 2.0]
>>> flat_output = flat_f(flat_input)
>>> flat_output
[20.0, 40.0]
>>> unflatten_output(flat_output)
{'x': 20.0, 'y': 40.0}
pangolin.util.dual_flatten(pytree1, pytree2, *, allow_prefix=True)[source]#

Flatten two PyTrees after broadcasting the first to the second.

By default, pytree1 may have the same structure as pytree2 or a structure that is a prefix of it. Set allow_prefix=False to require identical structures. None is retained as a leaf.

Parameters:
  • pytree1 (PyTree[Leaf1]) – The first PyTree.

  • pytree2 (PyTree[Leaf2]) – The second PyTree, whose structure determines the flattened result when prefix broadcasting is enabled.

  • allow_prefix (bool) – Whether leaves in pytree1 may broadcast over corresponding subtrees in pytree2.

Return type:

tuple[list[Leaf1], list[Leaf2]]

Examples

>>> pytree1 = (0,[1,2])
>>> pytree2 = ("dog",["cat", "owl"])
>>> dual_flatten(pytree1, pytree2)
([0, 1, 2], ['dog', 'cat', 'owl'])
>>> pytree1 = (None,[1,2])
>>> pytree2 = ("dog", ["cat", None])
>>> dual_flatten(pytree1, pytree2)
([None, 1, 2], ['dog', 'cat', None])
>>> pytree1 = (None, 3)
>>> pytree2 = ("dog", ["cat", None])
>>> dual_flatten(pytree1, pytree2)
([None, 3, 3], ['dog', 'cat', None])
pangolin.util.same_tree(x, y, is_leaf=None)[source]#

Return whether two PyTrees have equal structures and leaves.

Array leaves are compared by value regardless of whether they are NumPy or JAX arrays, and numeric dtype differences are ignored.

Parameters:
  • x (PyTree) – First PyTree.

  • y (PyTree) – Second PyTree.

  • is_leaf (Callable[[Any], bool] | None) – Optional PyTree leaf predicate.

Return type:

bool

Examples

>>> same_tree({'x': np.array([1, 2])}, {'x': jnp.array([1.0, 2.0])})
True
>>> same_tree([1, 2], (1, 2))
False
pangolin.util.tree_allclose(a, b, **kwargs)[source]#

Return whether corresponding leaves of identical PyTrees are close.

Each pair of leaves is compared with numpy.allclose(). A ValueError is raised when the PyTree structures differ.

Parameters:
  • a (PyTree) – First PyTree.

  • b (PyTree) – Second PyTree.

  • kwargs (Any) – Options forwarded to numpy.allclose().

Return type:

bool

Examples

>>> tree1 = {'a': jnp.array([1.0, 2.0]), 'b': (jnp.array(3.0),)}
>>> tree2 = {'a': jnp.array([1.000001, 2.0]), 'b': (jnp.array(3.0),)}
>>> tree_allclose(tree1, tree2, atol=1e-5)
True
>>> tree3 = {'a': jnp.array([1.0, 2.5]), 'b': (jnp.array(3.0),)}
>>> tree_allclose(tree1, tree3)
False
pangolin.util.map_inside_tree(f, tree)[source]#

Map a function over the leading axis of every array leaf in a PyTree.

None leaves are passed unchanged to every call and retained unchanged in the result. All non-None input leaves must have the same leading size.

Parameters:
  • f (Callable[[TypeAliasForwardRef('PyTree')], TypeAliasForwardRef('PyTree')]) – Function applied to each leading-axis slice of the PyTree.

  • tree (PyTree) – PyTree containing arrays and optional None leaves.

Return type:

PyTree

Examples

>>> def f(t):
...     a, (b, c) = t
...     return (a + b, a * b), c
>>> tree = np.array([1, 2]), (np.array([3, 4]), np.array([5, 6]))
>>> map_inside_tree(f, tree)
((array([4, 6]), array([3, 8])), array([5, 6]))
>>> def f(t):
...     a, (b, c) = t
...     return (a + b, c), None
>>> tree = np.array([1, 2]), (np.array([3, 4]), None)
>>> map_inside_tree(f, tree)
((array([4, 6]), None), None)
pangolin.util.assert_all_leaves_instance_of(tree, type, is_leaf=None)[source]#

Assert that every leaf in a PyTree is an instance of a class.

Examples

>>> assert_all_leaves_instance_of({'x': 1, 'y': [2, 3]}, int)
Parameters:
  • tree (PyTree)

  • type (type | tuple[type, ...])

  • is_leaf (Callable[[Any], bool] | None)

Return type:

None

pangolin.util.assert_all_leaves_instance_of_with_none(tree, type)[source]#

Assert that every leaf, including None, is an instance of a class.

Examples

>>> assert_all_leaves_instance_of_with_none([1, None], (int, type(None)))
Parameters:
  • tree (PyTree)

  • type (type | tuple[type, ...])

Return type:

None

pangolin.util.assert_is_sequence_of(seq, type)[source]#

Assert that an object is a sequence whose items share a class.

Examples

>>> assert_is_sequence_of([1, 2, 3], int)
Parameters:
  • seq (Sequence[Any])

  • type (type | tuple[type, ...])

Return type:

None

pangolin.util.assimilate_vals(vars, vals)[source]#

Convert observed values to arrays shaped like corresponding variables.

The structure of vars determines whether a Python container in vals represents a PyTree branch or one array-valued leaf. A ValueError is raised when the structures or leaf shapes cannot be matched.

Parameters:
  • vars (PyTree) – PyTree whose leaves provide the required shapes.

  • vals (PyTree) – Values to convert to JAX arrays.

Return type:

PyTree[jnp.ndarray]

Examples

>>> variables = {'x': jnp.zeros((2,))}
>>> values = assimilate_vals(variables, {'x': [1.0, 2.0]})
>>> np.asarray(values['x']).tolist()
[1.0, 2.0]
pangolin.util.flatten_args(vars, given_vars=None, given_vals=None)[source]#

Flatten requested variables and shape-checked observed variables/values.

The two returned reconstruction functions rebuild the original vars and given_vars structures from flat sequences.

Parameters:
  • vars (PyTree) – Variables whose values will be calculated.

  • given_vars (PyTree) – Variables whose values are observed.

  • given_vals (PyTree) – Observed values corresponding to given_vars.

Return type:

tuple[list[Any], list[Any], list[Any], Callable, Callable]

Examples

>>> variables = {'x': jnp.zeros(())}
>>> given_variables = (jnp.zeros((2,)),)
>>> result = flatten_args(variables, given_variables, ([1.0, 2.0],))
>>> flat_vars, flat_given, flat_vals, unflatten_vars, unflatten_given = result
>>> len(flat_vars), len(flat_given), np.asarray(flat_vals[0]).tolist()
(1, 1, [1.0, 2.0])
>>> list(unflatten_vars(flat_vars))
['x']
pangolin.util.fixed_arity(fun)[source]#

Return the number of parameters in a fixed positional signature.

A fixed positional signature may contain only positional-only and positional-or-keyword parameters, and none may have default values.

Parameters:

fun (Callable) – Callable whose signature to inspect.

Returns:

int – Number of parameters in fun.

Raises:

TypeError – If fun has a default value, variadic parameter, or keyword-only parameter.

Return type:

int

Examples

>>> def add(x, y):
...     return x + y
>>> fixed_arity(add)
2
>>> def optional(x=0):
...     return x
>>> fixed_arity(optional)
Traceback (most recent call last):
...
TypeError: optional has no fixed positional signature: 'x' has a default
>>> def variadic(*xs):
...     return xs
>>> fixed_arity(variadic)
Traceback (most recent call last):
...
TypeError: variadic has no fixed positional signature: 'xs' is not a fixed positional parameter
pangolin.util.get_positional_args(target_func, *args, **kwargs)[source]#

Convert mixed arguments into positional order for a callable.

Default values are included in the result. The returned list produces the same call for functions whose parameters can all be supplied positionally.

Parameters:
  • target_func (Callable) – Callable whose signature determines the argument order.

  • args (Any) – Positional arguments to bind.

  • kwargs (Any) – Keyword arguments to bind.

Raises:
  • ValueError – If target_func declares a keyword-only parameter.

  • TypeError – If the supplied arguments do not match the callable’s signature.

Return type:

list[Any]

Examples

>>> def add_five_numbers(a, b, c, d, e):
...     return a + b + c + d + e
>>> # Case 1: All arguments provided positionally
>>> get_positional_args(add_five_numbers, 1, 2, 3, 4, 5)
[1, 2, 3, 4, 5]
>>> # Case 2: Mixed positional and keyword arguments
>>> get_positional_args(add_five_numbers, 1, 2, 3, e=5, d=4)
[1, 2, 3, 4, 5]
>>> # Case 3: All arguments provided as keywords
>>> get_positional_args(add_five_numbers, a=10, b=20, c=30, d=40, e=50)
[10, 20, 30, 40, 50]
>>> # Case 4: Function with default arguments
>>> def greet(name, greeting="Hello"):
...     return f"{greeting}, {name}!"
>>> get_positional_args(greet, "Alice")
['Alice', 'Hello']
>>> get_positional_args(greet, "Bob", greeting="Hi")
['Bob', 'Hi']
>>> get_positional_args(greet, name="Charlie", greeting="Greetings")
['Charlie', 'Greetings']
>>> # Case 5: Verification that the transformed arguments yield the same result
>>> def multiply(x, y, z):
...     return x * y * z
>>> original_args = (2,)
>>> original_kwargs = {'z': 5, 'y': 3}
>>> transformed = get_positional_args(multiply, *original_args, **original_kwargs)
>>> multiply(*original_args, **original_kwargs) == multiply(*transformed)
True
>>> # Case 6: Attempting to transform a function with keyword-only arguments (raises ValueError)
>>> def func_with_kw_only(a, b, *, kw_only_arg, default_kw_only=10):
...     pass
>>> try:
...     get_positional_args(func_with_kw_only, 1, 2, kw_only_arg=3)
... except ValueError as e:
...     print(e)
Function 'func_with_kw_only' has keyword-only arguments (kw_only_arg), which is not allowed by this transformer.
>>> # Case 7: Missing a required argument (raises TypeError)
>>> try:
...     get_positional_args(add_five_numbers, 1, 2, 3)
... except TypeError as e:
...     # Use '...' to match any varying parts of the error message
...     # and check for a key phrase.
...     assert "missing a required argument" in str(e)
...     print(e.__class__.__name__ + ": " + str(e))
TypeError: ...
>>> # Case 8: Providing an unexpected argument (raises TypeError)
>>> try:
...     get_positional_args(add_five_numbers, 1, 2, 3, 4, 5, extra_arg=6)
... except TypeError as e:
...     print(e.__class__.__name__ + ": " + str(e))
TypeError: ... an unexpected keyword argument 'extra_arg'
pangolin.util.dag_lines(nodes, parents, label_fn=<class 'str'>, number_parents='auto')[source]#

Return a Unicode DAG drawing as a list of lines.

Parameters:
  • nodes (Sequence[Any]) – Distinct, hashable nodes in topological order.

  • parents (Sequence[Sequence[Any]]) – Parent nodes for each corresponding node.

  • label_fn (Callable[[Any], str]) – Function that produces a single-line label for each node.

  • number_parents (Literal['off', 'on', 'auto']) – Whether to number no edges, all edges, or only edges whose parent order would otherwise be ambiguous. An annotated edge is marked ⁎ instead of a position when its parent occurs more than once.

Return type:

list[str]

Examples

>>> dag_lines(['A', 'B'], [[], ['A']])
['○ A', '│', '○ B']
pangolin.util.render_dag(nodes, parents, label_fn=<class 'str'>, number_parents='auto')[source]#

Print a Unicode rendering of a DAG.

Each node is plotted on its own text row. Consecutive node rows have a routing row between them, plus a separate numbering row when parent-order digits would otherwise collide with a bend. Each node occupies a text column, and the character immediately to its right is that column’s routing lane.

Characters used: ○ │ ─ └ ├ ┐ ┴ ┼, the space, the digits 0-9 where edges are numbered, and ⁎ where one edge represents repeated occurrences of the same parent.

Invariants

  • Lines only travel down and to the right, so no arrowheads are needed.

  • A node is never placed in a column left of any parent. Every edge therefore travels only down and right.

  • The leftmost parent turns directly onto the child’s row: ├ if its trunk continues to later children, └ if this is its last child.

  • A terminating interior parent joins the child’s horizontal route directly with ┴.

  • A continuing interior parent branches right and down with ├┐ on the routing row. Its original trunk crosses the child’s horizontal route at ┼, while the branch joins through ┴ in the adjacent routing lane.

  • ┼ always means a pure crossing; joins always use ┴.

  • A parent already in the child’s column enters the ○ vertically.

  • Parent annotations appear only on connector rows, labels only on node rows.

Placement#

Columns are created on demand and numbered from 0. Nodes are placed one at a time in the given order. Place each node N in the lowest-numbered column k such that:

  1. k is at or right of the column of every parent of N;

  2. no node already in column k has an un-plotted child other than N.

A new column at the far right satisfies both conditions, so placement never fails.

Condition 2 also guarantees that no two parents of N share a column: the earlier of them would have had N un-plotted when the later was placed.

Rendering#

Column k occupies character position 2k, and position 2k+1 is its routing lane. Node rows are separated by one routing row. A numbered node that also needs a bend gets an additional straight numbering row before its routing row.

A column is live from the row of its most recent node until the row of that node’s last un-plotted child, inclusive; otherwise it is dead. Rule 2 guarantees a live column’s pending line belongs to its most recent node and that only that node’s sole remaining child may reuse the column. Hence a │ entering a ○ from directly above is always an edge, and its absence is always the absence of one.

A straight connector row contains │ at position 2k for every live column k and spaces elsewhere. A bend row starts the same way, then replaces the │ of each continuing interior parent with ├ and places ┐ in its routing lane.

Node rows: let N sit at column c, and let m be the lowest column holding a parent of N. If N has no parents, or m == c, no horizontal is drawn; otherwise fill positions 2m+1 .. 2c-1 with ─. Then position 2k of each column k is:

k == c                           ○
k == m                           ├   line continues below
                                 └   this row is its last child
m < k < c, terminating parent    ┴
m < k < c, continuing parent     ┼   its branch joins at 2k+1 with ┴
m < k < c, live, not a parent    ┼
m < k < c, dead                  ─
k < m or k > c                   │ if live, else space

A continuing interior parent’s edge to N does not join at its trunk. On the preceding bend row, ├┐ copies that edge into position 2k+1; the short vertical branch then joins the child’s horizontal through ┴. The trunk itself passes through ┼ unchanged. Thus ┼ never conceals a merge.

A line ends only at the row of its node’s last child, so any column between m and c whose line ends on this row is necessarily a parent of N. That is why a terminating interior parent can use ┴ directly without ambiguity.

Parent order#

An annotation appears immediately right of a parent’s vertical line. A subscript digit gives that parent’s position in the child’s parents entry. ⁎ means the same parent occupies multiple positions, which a single dependency edge cannot distinguish. number_parents selects which nodes are annotated:

'off'    none
'on'     every node with at least one distinct parent
'auto'   only nodes whose parent order or multiplicity would be lost

The bare drawing loses information when the columns of the parents, read in listed order, are not strictly increasing. A decrease means parent order differs from left-to-right order; an equality means the same parent occurs again. auto annotates exactly these cases. An unannotated fan-in under auto is therefore the positive assertion that its parents are distinct and listed from left to right.

Digits read left to right in column order, which need not be parent order: │₁│₀ means the column-0 parent is listed second. Under auto that mismatch or a repeated parent is the only reason annotations are present. For example, │⁎│₁ means the left parent occurs more than once while the right parent occupies position 1. Consult the original parent list when the exact positions represented by ⁎ matter.

The annotation is unambiguous:

  • At most one distinct parent of N occupies any column, so at most one annotation lands in each slot.

  • A parent’s line is live at the row of every one of its children, so a digit always sits immediately right of the │ it annotates.

  • If N has no bends, annotations use its sole connector row. If N has bends, a separate straight annotation row precedes the bend row, so an annotation never displaces ┐.

  • Annotations never make the drawing wider than the label column: the rightmost possible annotation remains one character left of the label.

Labels#

Let W be the largest column index used. Every node row is padded with spaces to position 2W + 2 and the label follows, so all labels are vertically aligned one space right of the rightmost possible ○. Connector rows carry no trailing whitespace, node rows none after the label, and the output ends with a single newline.

param nodes:

The nodes of the DAG in topological order (each node appears after all of its parents). Nodes must be distinct and hashable; they are compared by equality.

param parents:

One entry per node: the parents of that node, given as nodes. len(parents) must equal len(nodes), and every parent must appear earlier in nodes than the node it parents. Repeated entries are treated as one dependency edge. When that edge is annotated, ⁎ indicates that it represents multiple parent positions.

param label_fn:

Maps a node to its label, which must be a single-line string (default: str).

param number_parents:

When to annotate edges with their position in the child’s parent list (default: 'auto', which annotates only where the drawing would otherwise lose order or multiplicity). An annotated node must have at most ten parent positions.

raises ValueError:

If number_parents is not one of 'off', 'on' or 'auto'; if len(parents) != len(nodes); if nodes contains duplicates; or if a parent is missing from nodes or does not precede its child. Additionally, if a node that is annotated has more than ten parent positions. This is checked per node and only where annotations are actually emitted.

See also

dag_lines

the same drawing returned as a list of lines.

Notes

Width is O(n) in the worst case (n mutually unrelated chains need n columns), and because labels are globally aligned, one wide drawing pushes every label right.

The routing grammar deliberately avoids mixed-weight box-drawing glyphs. Every ┼ is a pure crossing, and every connection to a horizontal route is shown separately with ┴.

Examples

Except where noted, these use the default 'auto' mode.

>>> nodes = ["A"]
>>> parents = [[]]
>>> render_dag(nodes, parents)
○ A
>>> nodes = ["A", "B", "C"]
>>> parents = [[], ["A"], ["B"]]
>>> render_dag(nodes, parents)
○ A
│
○ B
│
○ C
>>> nodes = ["A", "B", "C"]
>>> parents = [[], ["A"], ["A"]]
>>> render_dag(nodes, parents)
○   A
│
├─○ B
│
○   C
>>> nodes = ["A", "B", "C"]
>>> parents = [[], [], ["A", "B"]]
>>> render_dag(nodes, parents)
○   A
│
│ ○ B
│ │
└─○ C
>>> nodes = ["A", "B", "C"]
>>> parents = [[], ["A"], ["A", "B"]]
>>> render_dag(nodes, parents)
○   A
│
├─○ B
│ │
└─○ C

The simplest DAG that auto annotates: D lists B, whose column is 1, before C, whose column is 0.

>>> nodes = ["A", "B", "C", "D"]
>>> parents = [[], ["A"], ["A"], ["B", "C"]]
>>> render_dag(nodes, parents)
○   A
│
├─○ B
│ │
○ │ C
│₁│₀
└─○ D

An interior parent that continues to a later child bends right before the child row. Its trunk then crosses through ┼ while its branch joins through ┴.

>>> nodes = ["A", "B", "C", "D"]
>>> parents = [[], ["A"], ["A", "B"], ["A", "B", "C"]]
>>> render_dag(nodes, parents)
○     A
│
├─○   B
│ ├┐
├─┼┴○ C
│ │ │
└─┴─○ D

A pure crossing: B’s line passes under C’s row without touching it.

>>> nodes = ["A", "B", "C", "D", "E"]
>>> parents = [[], [], ["A"], ["A"], ["B"]]
>>> render_dag(nodes, parents)
○     A
│
│ ○   B
│ │
├─┼─○ C
│ │
○ │   D
  │
  ○   E

The contrasting case: B is a parent of C and continues on to D.

>>> nodes = ["A", "B", "C", "D"]
>>> parents = [[], [], ["A", "B"], ["B"]]
>>> render_dag(nodes, parents)
○     A
│
│ ○   B
│ ├┐
└─┼┴○ C
  │
  ○   D

A fan-in from three roots, where every parent’s line ends.

>>> nodes = ["A", "B", "C", "D"]
>>> parents = [[], [], [], ["A", "B", "C"]]
>>> render_dag(nodes, parents)
○     A
│
│ ○   B
│ │
│ │ ○ C
│ │ │
└─┴─○ D

The empty DAG prints nothing.

>>> render_dag([], [])

Labels come from label_fn, and alignment follows the widest column.

>>> render_dag([1, 2, 3], [[], [1], [1]], "node {}".format)
○   node 1
│
├─○ node 2
│
○   node 3

Parent order

Reversing D’s parent list from the example above puts them in column order, and auto falls silent:

>>> nodes = ["A", "B", "C", "D"]
>>> parents = [[], ["A"], ["A"], ["C", "B"]]
>>> render_dag(nodes, parents)
○   A
│
├─○ B
│ │
○ │ C
│ │
└─○ D

Which is what 'off' produces for either ordering, and is exactly the ambiguity auto exists to close:

>>> render_dag(nodes, [[], ["A"], ["A"], ["B", "C"]], number_parents='off')
○   A
│
├─○ B
│ │
○ │ C
│ │
└─○ D

'on' numbers every edge, including the sole edge of a single-parent node:

>>> render_dag(["A", "B", "C"], [[], ["A"], ["B"]], number_parents='on')
○ A
│₀
○ B
│₀
○ C
>>> nodes = ["A", "B", "C"]
>>> parents = [[], [], ["A", "B"]]
>>> render_dag(nodes, parents, number_parents='on')
○   A
│
│ ○ B
│₀│₁
└─○ C

The widest case: digits fill every separator, still one short of the label column.

>>> nodes = ["A", "B", "C", "D"]
>>> parents = [[], ["A"], ["A", "B"], ["A", "B", "C"]]
>>> render_dag(nodes, parents, number_parents='on')
○     A
│₀
├─○   B
│₀│₁
│ ├┐
├─┼┴○ C
│₀│₁│₂
└─┴─○ D

A crossed column gets no digit, since it is not a parent:

>>> nodes = ["A", "B", "C", "D", "E"]
>>> parents = [[], [], ["A"], ["A"], ["B"]]
>>> render_dag(nodes, parents, number_parents='on')
○     A
│
│ ○   B
│₀│
├─┼─○ C
│₀│
○ │   D
  │₀
  ○   E

Modes are spelled out; the former boolean is no longer accepted.

>>> render_dag(["A"], [[]], number_parents=True)
Traceback (most recent call last):
    ...
ValueError: number_parents must be one of ('off', 'on', 'auto'), not True

Eleven parents cannot be numbered with single digits. Under 'auto' this DAG draws without complaint, since its parents are already in column order and no digits are needed.

>>> nodes = list(range(12))
>>> parents = [[] for _ in range(11)] + [list(range(11))]
>>> render_dag(nodes, parents, number_parents='on')
Traceback (most recent call last):
    ...
ValueError: node 11 has 11 parents; numbering allows at most 10

A repeated parent produces one dependency edge. auto and on mark that edge with ⁎ to show that it supplies multiple parent positions; off shows the bare dependency DAG.

>>> render_dag(["A", "B"], [[], ["A", "A"]])
○ A
│⁎
○ B
>>> render_dag(["A", "B"], [[], ["A", "A"]], number_parents='off')
○ A
│
○ B
Parameters:
  • nodes (Sequence[Any])

  • parents (Sequence[Sequence[Any]])

  • label_fn (Callable[[Any], str])

  • number_parents (Literal['off', 'on', 'auto'])

Return type:

None