|
| 1 | +from itertools import chain |
| 2 | +from warnings import warn |
| 3 | + |
| 4 | + |
| 5 | +def tree(latticejson, name=None): |
| 6 | + lattices = latticejson["lattices"] |
| 7 | + |
| 8 | + def _tree(name, prefix=""): |
| 9 | + string = f"{name}\n" |
| 10 | + if name in lattices: |
| 11 | + *other, last = lattices[name] |
| 12 | + for child in other: |
| 13 | + string += f"{prefix}├─── {_tree(child, prefix + '│ ')}" |
| 14 | + string += f"{prefix}└─── {_tree(last, prefix + ' ')}" |
| 15 | + return string |
| 16 | + |
| 17 | + return _tree(latticejson["root"] if name is None else name) |
| 18 | + |
| 19 | + |
| 20 | +def sort_lattices(latticejson, root=None, keep_unused=False): |
| 21 | + """Returns a sorted dict of lattice objects.""" |
| 22 | + lattices = latticejson["lattices"] |
| 23 | + lattices_set = set(lattices) |
| 24 | + lattices_sorted = {} |
| 25 | + |
| 26 | + def _sort_lattices(name): |
| 27 | + lattices_set.remove(name) |
| 28 | + for child in lattices[name]: |
| 29 | + if child in lattices_set: |
| 30 | + _sort_lattices(child) |
| 31 | + lattices_sorted[name] = lattices[name] |
| 32 | + |
| 33 | + _sort_lattices(root if root is not None else latticejson["root"]) |
| 34 | + if keep_unused: |
| 35 | + while len(lattices_set) > 0: |
| 36 | + _sort_lattices(lattices_set.pop()) |
| 37 | + else: |
| 38 | + for lattice in lattices_set: |
| 39 | + warn(f"Discard unused lattice '{lattice}'.") |
| 40 | + return lattices_sorted |
| 41 | + |
| 42 | + |
| 43 | +def remove_unused(latticejson, root=None, warn_unused=False): |
| 44 | + """Remove unused objects starting from the `root` lattice. Also sorts lattices.""" |
| 45 | + if root is None: |
| 46 | + root = latticejson["root"] |
| 47 | + elements = latticejson["elements"] |
| 48 | + lattices = latticejson["lattices"] |
| 49 | + elements_set = set(elements) |
| 50 | + lattices_set = set(lattices) |
| 51 | + elements_new = {} |
| 52 | + lattices_new = {} |
| 53 | + |
| 54 | + def _remove_unused(name): |
| 55 | + try: |
| 56 | + elements_set.remove(name) |
| 57 | + except KeyError: |
| 58 | + pass |
| 59 | + else: |
| 60 | + elements_new[name] = elements[name] |
| 61 | + return |
| 62 | + |
| 63 | + try: |
| 64 | + lattices_set.remove(name) |
| 65 | + except KeyError: |
| 66 | + pass |
| 67 | + else: |
| 68 | + lattice = lattices[name] |
| 69 | + for child in lattice: |
| 70 | + _remove_unused(child) |
| 71 | + lattices_new[name] = lattices[name] |
| 72 | + |
| 73 | + _remove_unused(root) |
| 74 | + latticejson_new = latticejson.copy() |
| 75 | + latticejson_new["root"] = root |
| 76 | + latticejson_new["elements"] = elements_new |
| 77 | + latticejson_new["lattices"] = lattices_new |
| 78 | + if warn_unused: |
| 79 | + for obj in chain(elements_set, lattices_set): |
| 80 | + warn(f"Discard unused object '{obj}'.") |
| 81 | + return latticejson_new |
0 commit comments