diff --git a/autofit/mapper/prior_model/representative.py b/autofit/mapper/prior_model/representative.py index 799b18db8..ac6d9f716 100644 --- a/autofit/mapper/prior_model/representative.py +++ b/autofit/mapper/prior_model/representative.py @@ -1,4 +1,5 @@ from collections import defaultdict +import re from typing import List @@ -84,8 +85,15 @@ def _find_groups(path_value_tuples, position): names = list(map(int, names)) representative_key = integers_representative_key(names) except ValueError: + suffixes = [re.fullmatch(r"(\D+)(\d+)", name) for name in names] + if all(suffixes) and len({match[1] for match in suffixes}) == 1: + names = sorted( + names, key=lambda name: (int(re.search(r"\d+$", name)[0]), name) + ) + else: + names = sorted(names) representative_key = ( - f"{min(names)} - {max(names)}" if len(set(names)) > 1 else names[0] + f"{names[0]} - {names[-1]}" if len(set(names)) > 1 else names[0] ) paths.append(((*before, representative_key, *after), value)) diff --git a/test_autofit/mapper/info/test_representation.py b/test_autofit/mapper/info/test_representation.py index 8a3028011..a8cddce0e 100644 --- a/test_autofit/mapper/info/test_representation.py +++ b/test_autofit/mapper/info/test_representation.py @@ -43,3 +43,24 @@ def test_prefix(): info_paths = [((0, i, 1), 2) for i in range(3)] groups = find_groups(info_paths) assert groups == [(("0", "0 - 2", 1), 2)] + + +def test_named_numeric_ranges(): + for prefix, count in (("lens_", 30), ("source_", 20)): + paths = [((f"{prefix}{i}", "centre"), 1) for i in reversed(range(count))] + assert find_groups(paths) == [ + ((f"{prefix}0 - {prefix}{count - 1}", "centre"), 1) + ] + + +def test_named_range_fallbacks(): + for names, expected in [ + (["beta", "alpha"], "alpha - beta"), + (["lens_9", "source_20"], "lens_9 - source_20"), + (["lens_9", "lens_9"], "lens_9"), + (["lens_02", "lens_2", "lens_10"], "lens_02 - lens_10"), + (["1", "2", "4"], "1 - 2, 4"), + ]: + assert find_groups([((name, "centre"), 1) for name in names]) == [ + ((expected, "centre"), 1) + ]