From ea7149e0785e9f4631b7618e07ca58c5bac3e1f5 Mon Sep 17 00:00:00 2001 From: Jesper Friis Date: Mon, 16 Oct 2023 09:22:20 +0200 Subject: [PATCH] Added utioity function get_referred_instances() --- bindings/python/utils.py | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/bindings/python/utils.py b/bindings/python/utils.py index e62c31665..27275fa40 100644 --- a/bindings/python/utils.py +++ b/bindings/python/utils.py @@ -516,7 +516,42 @@ def infer_dimensions(meta, values, strict=True): missing_dims = dimnames.difference(dims.keys()) raise CannotInferDimensionError( f"insufficient number of properties provided to infer dimensions: " - f"{missing_dims}" + f"{missing_dims} for metadata: {meta.uri}" ) return dims + + +def get_referred_instances(inst, include_meta=False): + """Return a set with all instances that are directly or indirectly + referred to by `inst`. + + If `include_meta` is true, also return metadata. + """ + references = set() + _get_referred_instances(inst, include_meta, references) + return references + + +def _get_referred_instances(inst, include_meta, references): + """Recursive help function for get_referred_instances().""" + if inst is None or inst in references: + return + references.add(inst) + if isinstance(inst, dlite.Collection): + for i in inst.get_instances(): + _get_referred_instances(i, include_meta, references) + else: + for prop in inst.meta.properties["properties"]: + if prop.type == "ref": + if prop.ndims: + for i in inst[prop.name]: + _get_referred_instances( + i, include_meta, references + ) + else: + _get_referred_instances( + inst[prop.name], include_meta, references + ) + if include_meta: + _get_referred_instances(inst.meta, include_meta, references)