Coverage for src / file_tree / template.py: 88%
770 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-27 12:14 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-27 12:14 +0000
1"""Define Placeholders and Template interface."""
3import itertools
4import os
5import re
6import string
7from collections import defaultdict
8from collections.abc import MutableMapping
9from fnmatch import fnmatch
10from functools import cmp_to_key, lru_cache
11from glob import glob
12from itertools import chain, combinations, product
13from pathlib import Path
14from typing import (
15 Any,
16 Collection,
17 Dict,
18 FrozenSet,
19 Generator,
20 Iterable,
21 Iterator,
22 List,
23 Optional,
24 Sequence,
25 Set,
26 Tuple,
27)
29import numpy as np
30import pandas as pd
31import xarray
32from parse import compile, extract_format
34MISSING = np.nan
37def is_missing(value):
38 """Whether a placeholder value marks missing value (i.e., None or np.nan)."""
39 return value is None or (isinstance(value, float) and np.isnan(value))
42def is_singular(value):
43 """Whether a value is singular or has multiple options."""
44 if isinstance(value, str):
45 return True
46 try:
47 iter(value)
48 return False
49 except TypeError:
50 return True
53class Placeholders(MutableMapping):
54 """Dictionary-like object containing the placeholder values.
56 It understands about sub-trees
57 (i.e., if "<sub_tree>/<placeholder>" does not exist it will return "<placeholder>" instead).
58 """
60 def __init__(self, *args, **kwargs):
61 """Create a new Placeholders as any dictionary."""
62 self.mapping = {}
63 self.linkages: Dict[str, FrozenSet[str]] = {}
64 self.update(dict(*args, **kwargs))
66 def copy(self) -> "Placeholders":
67 """Create copy of placeholder values."""
68 p = Placeholders()
69 p.mapping = dict(self.mapping)
70 p.linkages = dict(self.linkages)
71 return p
73 def __getitem__(self, key: str):
74 """Get placeholder values respecting sub-tree placeholders."""
75 actual_key = self.find_key(key)
76 if actual_key is None:
77 raise KeyError(f"No parameter value available for {key}")
78 if actual_key in self.linkages:
79 return self.mapping[self.linkages[actual_key]][actual_key]
80 return self.mapping[actual_key]
82 def __delitem__(self, key):
83 """Delete placeholder values represented by key."""
84 if isinstance(key, tuple):
85 key = frozenset(key)
86 del self.mapping[key]
87 if isinstance(key, frozenset):
88 for k in key:
89 del self.linkages[k]
91 def __setitem__(self, key, value):
92 """Overwrite placeholder value taking adjusting linked placeholders if needed."""
93 if isinstance(key, tuple): # create linked placeholders
94 if len(key) != len(value):
95 raise ValueError(
96 f"Attempting to set linked placeholders for {key}, "
97 + f"but {value} has a different number of elements than {key}"
98 )
99 if any([len(value[0]) != len(v) for v in value]):
100 raise ValueError(
101 f"Attempting to set linked placeholders for {key}, "
102 + f"but not all elements in {value} have the same length."
103 )
104 value = {k: v for k, v in zip(key, value)}
105 key = frozenset(key)
106 if isinstance(key, frozenset):
107 assert isinstance(value, dict)
108 for k in list(key):
109 if k in self.linkages:
110 unmatched_keys = [
111 unmatched
112 for unmatched in self.linkages[k]
113 if unmatched not in key
114 ]
115 if len(unmatched_keys) > 0:
116 matched_keys = [
117 matched for matched in self.linkages[k] if matched in key
118 ]
119 old_values = list(
120 zip(*[self[matched] for matched in matched_keys])
121 )
122 linked_values = {
123 new_key: [] for new_key in [*key, *unmatched_keys]
124 }
125 for index, new_value in enumerate(
126 zip(*[value[matched] for matched in matched_keys])
127 ):
128 already_seen_linked_matches = set()
129 for index2, old_value in enumerate(old_values):
130 if old_value != new_value:
131 continue
132 linked_matches = tuple(
133 self[unmatched][index2]
134 for unmatched in unmatched_keys
135 )
136 print(f"Linked matches: {linked_matches}")
138 if linked_matches in already_seen_linked_matches:
139 continue
140 already_seen_linked_matches.add(linked_matches)
142 for match, v in zip(matched_keys, new_value):
143 linked_values[match].append(v)
144 for unmatch, v in zip(unmatched_keys, linked_matches):
145 linked_values[unmatch].append(v)
146 if len(already_seen_linked_matches) == 0:
147 for match, v in zip(matched_keys, new_value):
148 linked_values[match].append(v)
149 for unmatched in unmatched_keys:
150 linked_values[unmatched].append(MISSING)
151 for _ in range(max(1, len(already_seen_linked_matches))):
152 for k in key:
153 if k in matched_keys:
154 continue
155 print(value[k])
156 linked_values[k].append(value[k][index])
158 self[frozenset([*key, *unmatched_keys])] = linked_values
159 return
160 self.mapping[key] = {k: tuple(v) for (k, v) in value.items()}
161 for k in list(key):
162 if k in self.mapping:
163 del self.mapping[k]
164 if k in self.linkages:
165 if self.linkages[k] in self.mapping and self.linkages[k] != key:
166 del self.mapping[self.linkages[k]]
167 del self.linkages[k]
168 self.linkages[k] = key
169 elif key in self.linkages:
170 old_values = self.mapping[self.linkages[key]]
171 if is_singular(value):
172 nvalue = old_values[key].count(value)
173 self.unlink(*old_values.keys())
174 if nvalue == 0:
175 for skey in old_values:
176 del self.mapping[skey]
177 self.mapping[key] = value
178 elif nvalue == 1:
179 idx = old_values[key].index(value)
180 for skey in old_values:
181 self.mapping[skey] = old_values[skey][idx]
182 else:
183 idx = [i for i, v in enumerate(old_values[key]) if v == value]
184 for skey in old_values:
185 if key == skey:
186 self.mapping[key] = value
187 else:
188 self.mapping[skey] = tuple(old_values[skey][i] for i in idx)
189 self.link(*[skey for skey in old_values if skey != key])
190 else:
191 self[frozenset([key])] = {key: value}
192 return
193 else:
194 self.mapping[key] = value
196 def __iter__(self):
197 """Iterate over all placeholder keys that actually have values."""
198 for key in self.mapping:
199 if not is_missing(self.mapping[key]):
200 yield key
202 def __len__(self):
203 """Return number of keys in the mapping."""
204 return len([k for k, v in self.mapping.items() if not is_missing(v)])
206 def __repr__(self):
207 """Text representation of placeholder values."""
208 return f"Placeholders({self.mapping})"
210 def find_key(self, key: str) -> Optional[str]:
211 """Find the actual key containing the value.
213 Will look for:
215 - not missing value for the key itself
216 - not missing value for any parent (i.e, for key "A/B", will look for "B" as well)
217 - otherwise will return None
219 Args:
220 key (str): placeholder name
222 Returns:
223 None if no value for the key is available, otherwise the key used to index the value
224 """
225 if not isinstance(key, str):
226 key = frozenset(key)
227 elif key in self.linkages:
228 return key
229 if not is_missing(self.mapping.get(key, MISSING)):
230 return key
231 elif "/" in key:
232 _, *parts = key.split("/")
233 new_key = "/".join(parts)
234 return self.find_key(new_key)
235 else:
236 return None
238 def missing_keys(self, all_keys: Collection[str], top_level=True) -> Set[str]:
239 """Identify any placeholder keys in `all_keys` that are not defined.
241 If `top_level` is True (default), any sub-tree information is removed from the missing keys.
242 """
243 not_defined = {key for key in all_keys if self.find_key(key) is None}
244 if not top_level:
245 return not_defined
246 return {key.split("/")[-1] for key in not_defined}
248 def split(self) -> Tuple["Placeholders", "Placeholders"]:
249 """Split all placeholders into those with a single value or those with multiple values.
251 Placeholders are considered to have multiple values if they are equivalent to 1D-arrays (lists, tuples, 1D ndarray, etc.).
252 Anything else is considered a single value (string, int, float, etc.).
254 Returns:
255 Tuple with two dictionaries:
257 1. placeholders with single values
258 2. placehodlers with multiple values
259 """
260 single_placeholders = Placeholders()
261 multi_placeholders = Placeholders()
262 for name, value in self.mapping.items():
263 if isinstance(name, frozenset) or not is_singular(value):
264 multi_placeholders[name] = value
265 else:
266 single_placeholders[name] = value
267 return single_placeholders, multi_placeholders
269 def iter_over(self, keys) -> Generator["Placeholders", None, None]:
270 """Iterate over the placeholder names.
272 Args:
273 keys (Sequence[str]): sequence of placeholder names to iterate over
275 Raises:
276 KeyError: Raised if any of the provided `keys` does not have any value.
278 Yields:
279 yield Placeholders object, where each of the listed keys only has a single possible value
280 """
281 actual_keys = [self.linkages.get(self.find_key(key), key) for key in keys]
282 unfilled = {orig for orig, key in zip(keys, actual_keys) if key is None}
283 if len(unfilled) > 0:
284 raise KeyError(f"Can not iterate over undefined placeholders: {unfilled}")
286 unique_keys = []
287 iter_values = {}
288 for key in actual_keys:
289 if key not in unique_keys:
290 if isinstance(key, frozenset): # linked placeholder
291 unique_keys.append(key)
292 iter_values[key] = [
293 {k: self[k][idx] for k in key}
294 for idx in range(len(self[list(key)[0]]))
295 ]
296 elif not is_singular(self[key]): # iterable placeholder
297 unique_keys.append(key)
298 iter_values[key] = self[key]
300 for values in product(*[iter_values[k] for k in unique_keys]):
301 new_vars = Placeholders(self)
302 for key, value in zip(unique_keys, values):
303 if isinstance(key, frozenset):
304 del new_vars[key] # break the placeholders link
305 new_vars.update(value)
306 else:
307 new_vars[key] = value
308 yield new_vars
310 def link(self, *keys):
311 """
312 Link the placeholders represented by `keys`.
314 When iterating over linked placeholders the i-th tree
315 will contain the i-th element from all linked placeholders,
316 instead of the tree containing all possible combinations of placeholder values.
318 This can be thought of using `zip` for linked variables and
319 `itertools.product` for unlinked ones.
320 """
321 actual_keys = set()
322 for key in keys:
323 if key in self.linkages:
324 actual_keys.update(self.linkages[key])
325 else:
326 actual_keys.add(key)
327 self[frozenset(actual_keys)] = {key: self[key] for key in actual_keys}
329 def unlink(self, *keys):
330 """
331 Unlink the placeholders represented by `keys`.
333 See :meth:`link` for how linking affects the iteration
334 through placeholders with multiple values.
336 Raises a ValueError if the placeholders are not actually linked.
337 """
338 if keys not in self:
339 raise ValueError(f"{keys} were not linked, so cannot unlink them")
340 new_vars = {k: self[k] for k in keys}
341 del self[keys]
342 self.update(new_vars)
344 def to_string(
345 self,
346 ):
347 """Convert the placeholders to a string representation."""
348 lines = []
349 all_keys = sorted(
350 [
351 *self.linkages.keys(),
352 *[k for k in self.mapping.keys() if not isinstance(k, frozenset)],
353 ]
354 )
355 for key in sorted(all_keys):
356 value = self[key]
357 if is_missing(value):
358 continue
359 if np.array(value).ndim == 1:
360 lines.append(
361 f"{key} = {', '.join(['<MISSING>' if is_missing(v) else str(v) for v in value])}"
362 )
363 else:
364 lines.append(
365 f"{key} = {'<MISSING>' if is_missing(value) else str(value)}"
366 )
367 for key in self.mapping.keys():
368 if isinstance(key, frozenset):
369 lines.append(f"&LINK {', '.join(sorted(key))}")
370 return "\n".join(lines)
373class MyDataArray:
374 """Wrapper around xarray.DataArray for internal usage.
376 It tries to delay creating the DataArray object as long as possible
377 (as using them for small arrays is slow...).
378 """
380 def __init__(self, data, coords=None):
381 """Create a new DataArray look-a-like."""
382 self.as_xarray = coords is None
383 if self.as_xarray:
384 assert isinstance(data, xarray.DataArray)
385 self.data_array = data
386 else:
387 self.data = data
388 self.coords = coords
390 def map(self, func) -> "MyDataArray":
391 """Apply `func` to each element of array."""
392 if self.as_xarray:
393 return MyDataArray(
394 xarray.apply_ufunc(func, self.data_array, vectorize=True)
395 )
396 else:
397 return MyDataArray(
398 np.array([func(d) for d in self.data.flat]).reshape(self.data.shape),
399 self.coords,
400 )
402 def to_xarray(
403 self,
404 ) -> xarray.DataArray:
405 """Convert to a real xarray.DataArray."""
406 if self.as_xarray:
407 return self.data_array
408 else:
409 return xarray.DataArray(
410 self.data, [_to_index(name, values) for name, values in self.coords]
411 )
413 @staticmethod
414 def concat(parts, new_index) -> "MyDataArray":
415 """Combine multiple DataArrays."""
416 if len(parts) == 0:
417 return MyDataArray(np.array([]), [])
418 to_xarray = any(p.as_xarray for p in parts) or any(
419 len(p.coords) != len(parts[0].coords)
420 or any(
421 np.all(name1 != name2)
422 for (name1, _), (name2, _) in zip(p.coords, parts[0].coords)
423 )
424 for p in parts
425 )
426 if to_xarray:
427 return MyDataArray(
428 xarray.concat([p.to_xarray() for p in parts], _to_index(*new_index))
429 )
430 else:
431 new_data = np.stack([p.data for p in parts], axis=0)
432 new_coords = list(parts[0].coords)
433 new_coords.insert(0, new_index)
434 return MyDataArray(new_data, new_coords)
437def _to_index(name, values):
438 """Convert to index for MyDataArray."""
439 if isinstance(name, str):
440 return pd.Index(values, name=name)
441 else:
442 return ("-".join(sorted(name)), pd.MultiIndex.from_tuples(values, names=name))
445class Template:
446 """Represents a single template in the FileTree."""
448 def __init__(self, parent: Optional["Template"], unique_part: str):
449 """Create a new child template in `parent` directory with `unique_part` filename."""
450 self.parent = parent
451 self.unique_part = unique_part
453 @property
454 def as_path(self) -> Path:
455 """Return the full path with no placeholders filled in."""
456 if self.parent is None:
457 return Path(self.unique_part)
458 return self.parent.as_path.joinpath(self.unique_part)
460 @property
461 def as_string(self):
462 """Return the full path with no placeholders filled in."""
463 if self.parent is None:
464 return str(self.unique_part)
465 return os.path.join(self.parent.as_string, str(self.unique_part))
467 def __str__(self):
468 """Return string representation of template."""
469 return f"Template({self.as_string})"
471 def children(self, templates: Iterable["Template"]) -> List["Template"]:
472 """Find children from a sequence of templates.
474 Args:
475 templates: sequence of possible child templates.
477 Returns:
478 list of children templates
479 """
480 res = []
482 def add_if_child(possible_child):
483 if isinstance(possible_child, DuplicateTemplate):
484 for t in possible_child.templates:
485 add_if_child(t)
486 elif possible_child.parent is self and possible_child not in res:
487 res.append(possible_child)
489 for t in templates:
490 add_if_child(t)
491 return sorted(res, key=lambda t: t.unique_part)
493 def as_multi_line(
494 self, other_templates: Dict["Template", Set[str]], indentation=4
495 ) -> str:
496 """Generate a string describing this and any child templates.
498 Args:
499 other_templates (Dict[Template, Set[str]]):
500 templates including all the child templates and itself.
501 indentation (int, optional):
502 number of spaces to use as indentation. Defaults to 4.
504 Returns:
505 str: multi-line string that can be processed by :meth:`file_tree.FileTree.read`
506 """
507 result = self._as_multi_line_helper(other_templates, indentation)
509 is_top_level = "" in other_templates[self]
510 if not is_top_level and self.parent is None:
511 return "!" + result
512 else:
513 return result
515 def _as_multi_line_helper(
516 self,
517 other_templates: Dict["Template", Set[str]],
518 indentation=4,
519 _current_indentation=0,
520 ) -> str:
521 leaves = []
522 branches = []
523 for t in sorted(
524 self.children(other_templates.keys()), key=lambda t: t.unique_part
525 ):
526 if len(t.children(other_templates.keys())) == 0:
527 leaves.append(t)
528 else:
529 branches.append(t)
531 is_top_level = "" in other_templates[self]
532 if is_top_level:
533 base_line = "."
534 assert _current_indentation == 0 and self.parent is None
535 _current_indentation = -indentation
536 else:
537 base_line = _current_indentation * " " + self.unique_part
539 all_keys = set(other_templates[self])
540 if is_top_level and all_keys == {""}:
541 lines = []
542 elif len(all_keys) == 1 and list(all_keys)[0] == self.guess_key():
543 lines = [base_line]
544 else:
545 if is_top_level:
546 all_keys.remove("")
547 lines = [base_line + f" ({','.join(sorted(all_keys))})"]
549 already_done = set()
550 for t in leaves + branches:
551 if t not in already_done:
552 lines.append(
553 t._as_multi_line_helper(
554 other_templates, indentation, indentation + _current_indentation
555 )
556 )
557 already_done.add(t)
558 return "\n".join(lines)
560 @property
561 def _parts(
562 self,
563 ):
564 return TemplateParts.parse(self.as_string)
566 def placeholders(self, valid=None) -> List[str]:
567 """Return a list of the placeholder names.
569 Args:
570 valid: Collection of valid placeholder names.
571 An error is raised if any other placeholder is detected.
572 By default all placeholder names are fine.
574 Returns:
575 List[str]: placeholder names in order that they appear in the template
576 """
577 return self._parts.ordered_placeholders(valid)
579 def format_single(
580 self, placeholders: Placeholders, check=True, keep_optionals=False, glob=True
581 ) -> str:
582 """Format the template with the placeholders filled in.
584 Only placeholders with a single value are considered.
586 Args:
587 placeholders (Placeholders): values to fill into the placeholder
588 check (bool): check for missing placeholders if set to True
589 keep_optionals: if True keep optional parameters that have not been set (will cause the check to fail)
590 glob: setting for pattern matching
592 Raises:
593 KeyError: if any placeholder is missing
595 Returns:
596 str: filled in template
597 """
598 single_placeholders, _ = placeholders.split()
599 template = self._parts.fill_single_placeholders(single_placeholders)
600 if not keep_optionals:
601 template = template.remove_optionals()
602 if check:
603 unfilled = template.required_placeholders()
604 if len(unfilled) > 0:
605 raise KeyError(f"Missing placeholder values for {unfilled}")
606 return pattern_match(str(template), glob)
608 def format_mult(
609 self,
610 placeholders: Placeholders,
611 check=False,
612 filter=False,
613 matches=None,
614 glob=False,
615 ) -> xarray.DataArray:
616 """Replace placeholders in template with the provided placeholder values.
618 Args:
619 placeholders: mapping from placeholder names to single or multiple vaalues
620 check: skip check for missing placeholders if set to True
621 filter: filter out non-existing files if set to True
622 matches: Optional pre-generated list of any matches to the template.
623 glob: keyword determining the pattern matching behaviour
625 Raises:
626 KeyError: if any placeholder is missing
628 Returns:
629 xarray.DataArray: array with possible resolved paths.
630 If `filter` is set to True the non-existent paths are replaced by None
631 """
632 parts = self._parts
633 resolved = parts.resolve(placeholders)
634 if check:
635 for template in resolved.data.flatten():
636 unfilled = template.required_placeholders()
637 if len(unfilled) > 0:
638 raise KeyError(f"Missing placeholder values for {unfilled}")
640 def _match_single(t):
641 try:
642 return pattern_match(str(t), glob)
643 except FileNotFoundError:
644 if filter:
645 return ""
646 raise
648 paths = resolved.map(_match_single)
649 if not filter:
650 return paths.to_xarray()
651 placeholder_dict = dict(placeholders)
652 path_matches = [
653 str(
654 parts.fill_single_placeholders(
655 Placeholders({**placeholder_dict, **match})
656 ).remove_optionals()
657 )
658 for match in (
659 self.all_matches(placeholders) if matches is None else matches
660 )
661 ]
662 return paths.map(
663 lambda p: (
664 p
665 if any(
666 (fnmatch(p, m) if is_glob_pattern(m) else p == m)
667 for m in path_matches
668 )
669 else ""
670 )
671 ).to_xarray()
673 def optional_placeholders(
674 self,
675 ) -> Set[str]:
676 """Find all placeholders that are only within optional blocks (i.e., they do not require a value).
678 Returns:
679 Set[str]: names of optional placeholders
680 """
681 return self._parts.optional_placeholders()
683 def required_placeholders(
684 self,
685 ) -> Set[str]:
686 """Find all placeholders that are outside of optional blocks (i.e., they do require a value).
688 Returns:
689 Set[str]: names of required placeholders
690 """
691 return self._parts.required_placeholders()
693 def guess_key(
694 self,
695 ) -> str:
696 """Propose a short name for the template.
698 The proposed short name is created by:
700 - taking the basename (i.e., last component) of the path
701 - removing the first '.' and everything beyond (to remove the extension)
703 .. warning::
705 If there are multiple dots within the path's basename,
706 this might remove far more than just the extension.
708 Returns:
709 str: proposed short name for this template (used if user does not provide one)
710 """
711 parts = self.as_path.parts
712 if len(parts) == 0:
713 return ""
714 else:
715 return parts[-1].split(".")[0]
717 def add_precursor(self, text) -> "Template":
718 """Return a new Template with any placeholder names in the unique part now preceded by `text`.
720 Used for adding sub-trees
721 """
722 parts = TemplateParts.parse(self.unique_part).parts
723 updated = "".join([str(p.add_precursor(text)) for p in parts])
724 return Template(self.parent, updated)
726 def get_all_placeholders(
727 self, placeholders: Placeholders, link=None, return_matches=False
728 ) -> Placeholders:
729 """Fill placeholders with possible values based on what is available on disk.
731 Args:
732 placeholders: New values for undefined placeholders in template.
733 link: template keys that should be linked together in the output.
734 return_matches: if True, also returns any matches to the template, which can be passed on to `format_mult`.
736 Returns:
737 Set of placeholders updated based on filed existing on disk that match this template.
738 """
739 if link is None:
740 link = []
741 elif len(link) > 0 and isinstance(link[0], str):
742 link = [link]
743 # link is now a sequence of sequence of strings
745 all_to_link = [name for single in link for name in single]
746 template_keys = {
747 *self.optional_placeholders(),
748 *self.required_placeholders(),
749 }
751 undefined = set()
752 placeholder_with_linked = placeholders.copy()
753 for name in all_to_link:
754 if placeholder_with_linked.find_key(name) is None:
755 placeholder_with_linked[name] = ""
756 undefined.add(name)
757 undefined.update(placeholders.missing_keys(template_keys))
759 matches = self.all_matches(placeholders, undefined)
761 undefined_values = defaultdict(set)
762 for match in matches:
763 for name, value in match.items():
764 if placeholders.find_key(name) is None and name not in all_to_link:
765 undefined_values[name].add(value)
767 def cmp(item1, item2):
768 if is_missing(item1):
769 return -1
770 if is_missing(item2):
771 return 1
772 if item1 < item2:
773 return -1
774 if item1 > item2:
775 return 1
776 return 0
778 res = Placeholders(
779 {k: sorted(v, key=cmp_to_key(cmp)) for k, v in undefined_values.items()}
780 )
781 for to_link in link:
782 res[tuple(to_link)] = list(
783 zip(
784 *sorted(
785 {
786 tuple(Placeholders(match).get(key, None) for key in to_link)
787 for match in matches
788 }
789 )
790 )
791 )
792 if return_matches:
793 return (res, matches)
794 return res
796 def all_matches(
797 self, placeholders: Placeholders, keys_to_fill: Optional[Collection[str]] = None
798 ) -> List[Dict[str, Any]]:
799 """Return a sequence of all possible variable values for `keys_to_fill` matching existing files on disk.
801 Only variable values matching existing placeholder values (in `placeholders`) are returned
802 (undefined placeholders are unconstrained).
803 """
804 if keys_to_fill is None:
805 keys_to_fill = placeholders.missing_keys(
806 {
807 *self.required_placeholders(),
808 *self.optional_placeholders(),
809 }
810 )
812 single_vars, multi_vars = placeholders.split()
813 res = []
815 def check_name_with_edit(match, name):
816 value = match[name]
817 if name in single_vars and single_vars.find_key(name) == name:
818 return value == single_vars[name]
819 if name in multi_vars and multi_vars.find_key(name) == name:
820 return value in multi_vars[name]
821 if name in keys_to_fill:
822 return True
823 del match[name]
824 _, *parts = name.split("/")
825 parent_name = "/".join(parts)
826 if parent_name in match:
827 return match[parent_name] == value
828 match[parent_name] = value
829 return check_name_with_edit(match, parent_name)
831 for match in self._parts.fill_single_placeholders(single_vars).all_matches(
832 multi_vars
833 ):
834 match.update(single_vars)
835 if not all(
836 check_name_with_edit(match, name) for name in list(match.keys())
837 ):
838 continue
839 res.append(match)
840 return res
842 def rich_line(self, all_keys):
843 """Produce a line for rendering using rich."""
844 from rich.text import Text
846 keys = all_keys[self]
847 base = self.guess_key()
848 unique_part = str(self.unique_part)
849 if base in keys:
850 keys.remove(base)
851 if len(base) > 0:
852 parts = unique_part.split(base)
853 unique_part = Text(parts[0])
854 for other_string_part in parts[1:]:
855 unique_part.append(base, style="cyan")
856 unique_part.append(other_string_part)
857 else:
858 unique_part = Text(unique_part)
859 if len(keys) == 0:
860 return unique_part
861 text = Text(unique_part)
862 text.append(" (")
863 skeys = sorted(keys)
864 text.append(skeys[0], style="cyan")
865 for key in skeys[1:]:
866 text.append(", ")
867 text.append(key, style="cyan")
868 text.append(")")
869 return text
872class DuplicateTemplate:
873 """Represents the case where a single key points to multiple templates."""
875 def __init__(self, *templates: Template):
876 """Create a new DuplicateTemplate with the provided templates."""
877 self._templates = list(templates)
879 def add_template(self, template: Template):
880 """Add another conflicting template."""
881 self._templates.append(template)
883 @property
884 def templates(
885 self,
886 ):
887 """Return the list of templates matching the given key."""
888 return tuple(self._templates)
891def extract_placeholders(template, filename, known_vars=None):
892 """
893 Extract the placeholder values from the filename.
895 :param template: template matching the given filename
896 :param filename: filename
897 :param known_vars: already known placeholders
898 :return: dictionary from placeholder names to string representations
899 (unused placeholders set to None)
900 """
901 return TemplateParts.parse(template).extract_placeholders(filename, known_vars)
904class Part:
905 """
906 Individual part of a template.
908 3 subclasses are defined:
910 - :class:`Literal`:
911 piece of text
912 - :class:`Required`:
913 required placeholder to fill in
914 (between curly brackets)
915 - :class:`OptionalPart`:
916 part of text containing optional placeholders
917 (between square brackets)
918 """
920 def fill_single_placeholders(
921 self, placeholders: Placeholders, ignore_type=False
922 ) -> Sequence["Part"]:
923 """Fill in the given placeholders."""
924 return (self,)
926 def optional_placeholders(
927 self,
928 ) -> Set[str]:
929 """Return all placeholders in optional parts."""
930 return set()
932 def required_placeholders(
933 self,
934 ) -> Set[str]:
935 """Return all required placeholders."""
936 return set()
938 def contains_optionals(self, placeholders: Optional[Set["Part"]] = None):
939 """Return True if this part contains the optional placeholders."""
940 return False
942 def append_placeholders(self, placeholders: List[str], valid=None):
943 """Append the placeholders in this part to the provided list in order."""
944 pass
946 def add_precursor(self, text: str) -> "Part":
947 """Prepend any placeholder names by `text`."""
948 return self
950 def for_defined(self, placeholder_names: Set[str]) -> List["Part"]:
951 """Return the template string assuming the placeholders in `placeholder_names` are defined.
953 Removes any optional parts, whose placeholders are not in `placeholder_names`.
954 """
955 return [self]
957 def remove_precursors(self, placeholders=None):
958 """Remove precursor from placeholder key."""
959 return self
962class Literal(Part):
963 """Piece of text in template without placeholders."""
965 def __init__(self, text: str):
966 """
967 Literal part is defined purely by the text it contains.
969 :param text: part of the template
970 """
971 self.text = text
973 def __str__(self):
974 """Return this part of the template as a string."""
975 return self.text
977 def __eq__(self, other):
978 """Check if text matches other `Literal`."""
979 if not isinstance(other, Literal):
980 return NotImplemented
981 return self.text == other.text
984class Required(Part):
985 """Placeholder part of template that requires a value."""
987 def __init__(self, var_name, var_formatting=None):
988 """
989 Create required part of template (between curly brackets).
991 Required placeholder part of template is defined by placeholder name and its format
993 :param var_name: name of placeholder
994 :param var_formatting: how to format the placeholder
995 """
996 self.var_name = var_name
997 self.var_formatting = var_formatting
999 def __str__(self):
1000 """Return this part of the template as a string."""
1001 if self.var_formatting is None or len(self.var_formatting) == 0:
1002 return "{" + self.var_name + "}"
1003 else:
1004 return "{" + self.var_name + ":" + self.var_formatting + "}"
1006 def fill_single_placeholders(self, placeholders: Placeholders, ignore_type=False):
1007 """Fill placeholder values into template obeying typing."""
1008 value = placeholders.get(self.var_name, MISSING)
1009 if is_missing(value):
1010 return (self,)
1011 else:
1012 if not ignore_type and len(self.var_formatting) > 0:
1013 format_type = extract_format(self.var_formatting, [])["type"]
1014 if format_type in list(r"dnbox"):
1015 value = int(value)
1016 elif format_type in list(r"f%eg"):
1017 value = float(value)
1018 elif format_type in ["t" + ft for ft in "iegachs"] and isinstance(
1019 value, str
1020 ):
1021 from dateutil import parser
1023 value = parser(value)
1024 res = TemplateParts.parse(
1025 format(value, "" if ignore_type else self.var_formatting)
1026 )
1027 if len(res.parts) == 1:
1028 return res.parts
1029 return res.fill_single_placeholders(
1030 placeholders, ignore_type=ignore_type
1031 ).parts
1033 def required_placeholders(
1034 self,
1035 ):
1036 """Return variable names."""
1037 return {self.var_name}
1039 def append_placeholders(self, placeholders, valid=None):
1040 """Add placeholder name to list of placeholders in template."""
1041 if valid is not None and self.var_name not in valid:
1042 raise ValueError(f"Placeholder {self.var_name} is not defined")
1043 placeholders.append(self.var_name)
1045 def add_precursor(self, text: str) -> "Required":
1046 """Prepend any placeholder names by `text`."""
1047 return Required(text + self.var_name, self.var_formatting)
1049 def remove_precursors(self, placeholders=None):
1050 """Remove precursor from placeholder key."""
1051 if placeholders is None:
1052 new_name = self.var_name.split("/")[-1]
1053 else:
1054 key = placeholders.find_key(self.var_name)
1055 new_name = self.var_name if key is None else key
1056 return Required(new_name, self.var_formatting)
1058 def __eq__(self, other):
1059 """Check whether `other` placeholder matches this one."""
1060 if not isinstance(other, Required):
1061 return NotImplemented
1062 return (self.var_name == other.var_name) & (
1063 self.var_formatting == other.var_formatting
1064 )
1067class OptionalPart(Part):
1068 """Optional part of a template (i.e., between square brackets)."""
1070 def __init__(self, sub_template: "TemplateParts"):
1071 """
1072 Create optional part of template (between square brackets).
1074 Optional part can contain literal and required parts
1076 :param sub_template: part of the template within square brackets
1077 """
1078 self.sub_template = sub_template
1080 def __str__(self):
1081 """Return string representation of optional part."""
1082 return "[" + str(self.sub_template) + "]"
1084 def fill_single_placeholders(self, placeholders: Placeholders, ignore_type=False):
1085 """Fill placeholders into text within optional part."""
1086 new_opt = self.sub_template.fill_single_placeholders(
1087 placeholders, ignore_type=ignore_type
1088 )
1089 if len(new_opt.required_placeholders()) == 0:
1090 return (Literal(str(new_opt)),)
1091 return (OptionalPart(new_opt),)
1093 def optional_placeholders(self):
1094 """Return sequence of any placeholders in the optional part of the template."""
1095 return self.sub_template.required_placeholders()
1097 def contains_optionals(self, placeholders=None):
1098 """Check if this optional part contains any placeholders not listed in `placeholders`."""
1099 if placeholders is None and len(self.optional_placeholders()) > 0:
1100 return True
1101 return len(self.optional_placeholders().intersection(placeholders)) > 0
1103 def append_placeholders(self, placeholders, valid=None):
1104 """Add any placeholders in the optional part to `placeholders` list."""
1105 try:
1106 placeholders.extend(self.sub_template.ordered_placeholders(valid=valid))
1107 except ValueError:
1108 pass
1110 def add_precursor(self, text: str) -> "OptionalPart":
1111 """Prepend precursor `text` to any placeholders in the optional part."""
1112 return OptionalPart(
1113 TemplateParts([p.add_precursor(text) for p in self.sub_template.parts])
1114 )
1116 def for_defined(self, placeholder_names: Set[str]) -> List["Part"]:
1117 """
1118 Return the template string assuming the placeholders in `placeholder_names` are defined.
1120 Removes any optional parts, whose placeholders are not in `placeholder_names`.
1121 """
1122 if len(self.optional_placeholders().difference(placeholder_names)) > 0:
1123 return []
1124 return list(self.sub_template.parts)
1126 def remove_precursors(self, placeholders=None):
1127 """Remove precursor from placeholder key."""
1128 return OptionalPart(self.sub_template.remove_precursors(placeholders))
1130 def __eq__(self, other):
1131 """Check whether two optional parts match."""
1132 if not isinstance(other, OptionalPart):
1133 return NotImplemented
1134 return self.sub_template == other.sub_template
1137class TemplateParts:
1138 """Representation of full template as sequence of `Part` objects."""
1140 optional_re = re.compile(r"(\[.*?\])")
1141 requires_re = re.compile(r"(\{.*?\})")
1143 def __init__(self, parts: Sequence[Part]):
1144 """Create new TemplateParts based on sequence."""
1145 if isinstance(parts, str):
1146 raise ValueError(
1147 "Input to Template should be a sequence of parts; "
1148 + "did you mean to call `TemplateParts.parse` instead?"
1149 )
1150 self.parts = tuple(parts)
1152 @staticmethod
1153 @lru_cache(1000)
1154 def parse(text: str) -> "TemplateParts":
1155 """Parse a template string into its constituent parts.
1157 Args:
1158 text: template as string.
1160 Raises:
1161 ValueError: raised if a parsing error is
1163 Returns:
1164 TemplateParts: object that contains the parts of the template
1165 """
1166 parts: List[Part] = []
1167 for optional_parts in TemplateParts.optional_re.split(text):
1168 if (
1169 len(optional_parts) > 0
1170 and optional_parts[0] == "["
1171 and optional_parts[-1] == "]"
1172 ):
1173 if "[" in optional_parts[1:-1] or "]" in optional_parts[1:-1]:
1174 raise ValueError(
1175 f"Can not parse {text}, because unmatching square brackets were found"
1176 )
1177 parts.append(OptionalPart(TemplateParts.parse(optional_parts[1:-1])))
1178 else:
1179 for required_parts in TemplateParts.requires_re.split(optional_parts):
1180 if (
1181 len(required_parts) > 0
1182 and required_parts[0] == "{"
1183 and required_parts[-1] == "}"
1184 ):
1185 if ":" in required_parts:
1186 var_name, var_type = required_parts[1:-1].split(":")
1187 else:
1188 var_name, var_type = required_parts[1:-1], ""
1189 parts.append(Required(var_name, var_type))
1190 else:
1191 parts.append(Literal(required_parts))
1192 return TemplateParts(parts)
1194 def __str__(self):
1195 """Return the template as a string."""
1196 return os.path.normpath("".join([str(p) for p in self.parts]))
1198 def optional_placeholders(
1199 self,
1200 ) -> Set[str]:
1201 """Set of optional placeholders."""
1202 if len(self.parts) == 0:
1203 return set()
1204 optionals = set.union(*[p.optional_placeholders() for p in self.parts])
1205 return optionals.difference(self.required_placeholders())
1207 def required_placeholders(
1208 self,
1209 ) -> Set[str]:
1210 """Set of required placeholders."""
1211 if len(self.parts) == 0:
1212 return set()
1213 return set.union(*[p.required_placeholders() for p in self.parts])
1215 def ordered_placeholders(self, valid=None) -> List[str]:
1216 """Sequence of all placeholders in order (can contain duplicates)."""
1217 ordered_vars: List[str] = []
1218 for p in self.parts:
1219 p.append_placeholders(ordered_vars, valid=valid)
1220 return ordered_vars
1222 def fill_known(self, placeholders: Placeholders, ignore_type=False) -> MyDataArray:
1223 """Fill in the known placeholders.
1225 Any optional parts, where all placeholders have been filled
1226 will be automatically replaced.
1227 """
1228 single, multi = placeholders.split()
1229 return self.remove_precursors(placeholders)._fill_known_helper(
1230 single, multi, ignore_type=ignore_type
1231 )
1233 def _fill_known_helper(
1234 self, single: Placeholders, multi: Placeholders, ignore_type=False
1235 ) -> MyDataArray:
1236 """Do work for `fill_known`."""
1237 new_template = self.fill_single_placeholders(single, ignore_type=ignore_type)
1238 for name in new_template.ordered_placeholders():
1239 use_name = multi.find_key(name)
1240 if use_name is None:
1241 continue
1242 new_multi = multi.copy()
1243 if use_name in multi.linkages:
1244 values = multi[multi.linkages[use_name]]
1245 keys = tuple(sorted(values.keys()))
1246 index = (keys, zip(*[values[k] for k in keys]))
1247 del new_multi[new_multi.linkages[use_name]]
1248 else:
1249 values = {use_name: list(multi[name])}
1250 index = (use_name, values[use_name])
1251 del new_multi[use_name]
1252 assert use_name is not None
1254 parts = []
1255 new_single = single.copy()
1256 for idx in range(len(values[use_name])):
1257 new_vals = {n: v[idx] for n, v in values.items()}
1258 new_single.mapping.update(new_vals)
1259 parts.append(
1260 new_template._fill_known_helper(
1261 new_single, new_multi, ignore_type=ignore_type
1262 )
1263 )
1265 return MyDataArray.concat(parts, index)
1266 return MyDataArray(np.array(new_template), [])
1268 def fill_single_placeholders(
1269 self, placeholders: Placeholders, ignore_type=False
1270 ) -> "TemplateParts":
1271 """
1272 Fill in placeholders with singular values.
1274 Assumes that all placeholders are in fact singular.
1275 """
1276 res = [
1277 p.fill_single_placeholders(placeholders, ignore_type=ignore_type)
1278 for p in self.parts
1279 ]
1280 return TemplateParts(list(chain(*res)))
1282 def remove_optionals(self, optionals=None) -> "TemplateParts":
1283 """
1284 Remove any optionals containing the provided placeholders.
1286 By default all optionals are removed.
1287 """
1288 return TemplateParts(
1289 [p for p in self.parts if not p.contains_optionals(optionals)]
1290 )
1292 def all_matches(self, placeholders_values: Placeholders) -> List[Dict[str, Any]]:
1293 """Find all potential matches to existing templates.
1295 It accepts a list of placeholders that have multiple possible values.
1297 Returns a list with the possible combination of values for the placeholders.
1298 """
1299 required = self.required_placeholders()
1300 optional = self.optional_placeholders()
1301 matches = []
1302 already_globbed = {}
1304 fill_keys = [
1305 key
1306 for key in [*required, *optional]
1307 if (
1308 key in placeholders_values
1309 and any(os.path.sep in str(value) for value in placeholders_values[key])
1310 )
1311 ]
1312 for all_iter in placeholders_values.iter_over(fill_keys):
1313 already_filled, _ = all_iter.split()
1315 for defined_optionals in [
1316 c for n in range(len(optional) + 1) for c in combinations(optional, n)
1317 ]:
1318 glob_placeholders = Placeholders(
1319 **{req: "*" for req in required},
1320 **{opt: "*" for opt in defined_optionals},
1321 )
1322 glob_placeholders.update(already_filled)
1323 new_glob = str(
1324 self.fill_single_placeholders(
1325 glob_placeholders, ignore_type=True
1326 ).remove_optionals()
1327 )
1328 while "**" in new_glob:
1329 new_glob = new_glob.replace("**", "*")
1330 if new_glob not in already_globbed:
1331 already_globbed[new_glob] = glob(new_glob)
1332 res = []
1333 vars = required.union(defined_optionals)
1334 for p in self.fill_single_placeholders(already_filled).parts:
1335 res.extend(p.for_defined(vars))
1336 parser = TemplateParts(res).get_parser()
1337 for fn in already_globbed[new_glob]:
1338 try:
1339 placeholders = parser(fn)
1340 except ValueError:
1341 continue
1342 placeholders.update(already_filled)
1343 for var_name in optional:
1344 if var_name not in placeholders:
1345 placeholders[var_name] = MISSING
1346 matches.append(placeholders)
1347 return matches
1349 def resolve(self, placeholders, ignore_type=False) -> MyDataArray:
1350 """
1351 Resolve the template given a set of placeholders.
1353 :param placeholders: mapping of placeholder names to values
1354 :param ignore_type: if True, ignore the type formatting when
1355 filling in placeholders
1356 :return: cleaned string
1357 """
1358 return self.fill_known(placeholders, ignore_type=ignore_type).map(
1359 lambda t: t.remove_optionals()
1360 )
1362 def optional_subsets(
1363 self,
1364 ) -> Iterator["TemplateParts"]:
1365 """Yield template sub-sets with every combination optional placeholders."""
1366 optionals = self.optional_placeholders()
1367 for n_optional in range(len(optionals) + 1):
1368 for exclude_optional in itertools.combinations(optionals, n_optional):
1369 yield self.remove_optionals(exclude_optional)
1371 def extract_placeholders(self, filename, known_vars=None):
1372 """
1373 Extract the placeholder values from the filename.
1375 :param filename: filename
1376 :param known_vars: already known placeholders
1377 :return: dictionary from placeholder names to string representations
1378 (unused placeholders set to MISSING)
1379 """
1380 if known_vars is not None:
1381 template = self.fill_known(known_vars)
1382 else:
1383 template = self
1384 while "//" in filename:
1385 filename = filename.replace("//", "/")
1387 required = template.required_placeholders()
1388 optional = template.optional_placeholders()
1389 results = []
1390 for to_fill in template.optional_subsets():
1391 sub_re = str(
1392 to_fill.fill_known(
1393 {var: r"(\S+)" for var in required.union(optional)},
1394 )
1395 )
1396 while "//" in sub_re:
1397 sub_re = sub_re.replace("//", "/")
1398 sub_re = sub_re.replace(".", r"\.")
1399 match = re.match(sub_re, filename)
1400 if match is None:
1401 continue
1403 extracted_value = {}
1404 ordered_vars = to_fill.ordered_placeholders()
1405 assert len(ordered_vars) == len(match.groups())
1407 failed = False
1408 for var, value in zip(ordered_vars, match.groups()):
1409 if var in extracted_value:
1410 if value != extracted_value[var]:
1411 failed = True
1412 break
1413 else:
1414 extracted_value[var] = value
1415 if failed or any("/" in value for value in extracted_value.values()):
1416 continue
1417 for name in template.optional_placeholders():
1418 if name not in extracted_value:
1419 extracted_value[name] = MISSING
1420 if known_vars is not None:
1421 extracted_value.update(known_vars)
1422 results.append(extracted_value)
1423 if len(results) == 0:
1424 raise ValueError("{} did not match {}".format(filename, template))
1426 def score(placeholders):
1427 """
1428 Assign score to possible reconstructions of the placeholder values.
1430 The highest score is given to the set of placeholders that:
1432 1. has used the largest amount of optional placeholders
1433 2. has the shortest text within the placeholders (only used if equal at 1
1434 """
1435 number_used = len([v for v in placeholders.values() if not is_missing(v)])
1436 length_hint = sum(
1437 [len(v) for v in placeholders.values() if not is_missing(v)]
1438 )
1439 return number_used * 1000 - length_hint
1441 best = max(results, key=score)
1442 for var in results:
1443 if best != var and score(best) == score(var):
1444 raise KeyError(
1445 "Multiple equivalent ways found to parse {} using {}".format(
1446 filename, template
1447 )
1448 )
1449 return best
1451 def get_parser(self):
1452 """Create function that will parse a filename based on this template."""
1453 if any(isinstance(p, OptionalPart) for p in self.parts):
1454 raise ValueError(
1455 "Can not parse filename when there are optional parts in the template"
1456 )
1457 mapping = {
1458 old_key: "".join(new_key)
1459 for old_key, new_key in zip(
1460 self.required_placeholders(),
1461 itertools.product(*[string.ascii_letters] * 3),
1462 )
1463 }
1464 reverse = {new_key: old_key for old_key, new_key in mapping.items()}
1465 cleaned = str(
1466 TemplateParts(
1467 [
1468 (
1469 Required(mapping[p.var_name], p.var_formatting)
1470 if isinstance(p, Required)
1471 else p
1472 )
1473 for p in self.parts
1474 ]
1475 )
1476 ).replace("?", "{:1}")
1478 if is_glob_pattern(cleaned):
1479 nreplace = cleaned.count("*")
1480 parsers = []
1482 for replace_with in product(*([["", "{}"]] * nreplace)):
1483 this_string = cleaned
1484 for r in replace_with:
1485 this_string = this_string.replace("*", r, 1)
1486 parsers.append(compile(this_string, case_sensitive=True).parse)
1488 def parser(filename):
1489 for p in parsers:
1490 result = p(filename)
1491 if result is not None:
1492 return result
1493 return None
1495 else:
1496 parser = compile(cleaned, case_sensitive=True).parse
1498 def parse_filename(filename):
1499 """Parse filename based on template."""
1500 result = parser(filename)
1501 if result is None:
1502 raise ValueError(
1503 f"template string ({str(self)}) does not mach filename ({filename})"
1504 )
1505 named = result.named
1506 if any(isinstance(value, str) and "/" in value for value in named.values()):
1507 raise ValueError("Placeholder can not span directories")
1508 return {reverse[key]: value for key, value in named.items()}
1510 return parse_filename
1512 def remove_precursors(self, placeholders=None):
1513 """Replace keys to those existing in the placeholders.
1515 If no placeholders provided all precursors are removed.
1516 """
1517 return TemplateParts([p.remove_precursors(placeholders) for p in self.parts])
1519 def __eq__(self, other):
1520 """Check whether other template matches this one."""
1521 if not isinstance(other, TemplateParts):
1522 return NotImplemented
1523 return (len(self.parts) == len(other.parts)) and all(
1524 p1 == p2 for p1, p2 in zip(self.parts, other.parts)
1525 )
1528def is_glob_pattern(path):
1529 """Check if the given path is a glob-like pattern."""
1530 return "*" in path or "?" in path
1533def pattern_match(path, glob_cmd):
1534 """
1535 Apply glob-like pattern matching to given `path`.
1537 The `path` will be returned directly if `path` does not contain any `*`, `?`, or `[]` or `glob_cmd` is False.
1538 Otherwise pattern matching using the python `glob` library is used.
1539 """
1540 if not (glob_cmd and is_glob_pattern(path)):
1541 return path
1543 matches = sorted(glob(path))
1544 if callable(glob_cmd):
1545 try:
1546 res = glob_cmd(matches)
1547 except Exception:
1548 if len(matches) == 0:
1549 raise FileNotFoundError(
1550 f"No file was found to match pattern `{path}`. The `FileTree.glob` function raised the underlying error."
1551 )
1552 if len(matches) > 1:
1553 raise FileNotFoundError(
1554 f"Multiple ({len(matches)}) files were found to match pattern `{path}`. The `FileTree.glob` function raised the underlying error."
1555 )
1556 raise
1557 if not isinstance(res, str):
1558 raise ValueError(
1559 f"The `FileTree.glob` function should return a single path as a string, not `{res}`."
1560 )
1561 return res
1562 else:
1563 if len(matches) == 0:
1564 raise FileNotFoundError(
1565 f"No file was found to match pattern `{path}`. Set `FileTree.glob` to False to return the pattern rather than a file matching the pattern."
1566 )
1567 if glob_cmd in (True, "default"):
1568 if len(matches) > 1:
1569 raise FileNotFoundError(
1570 f"Multiple ({len(matches)}) files were found to match pattern `{path}`. Set `FileTree.glob` to False to return the pattern rather than a file matching the pattern. You can also set it to 'first' or 'last' to get the first or last match."
1571 )
1572 return matches[0]
1573 elif glob_cmd == "first":
1574 return matches[0]
1575 elif glob_cmd == "last":
1576 return matches[-1]
1577 raise ValueError(
1578 "`FileTree.glob` should be set to callable or one of `False`, `True`, 'default', 'first', or 'last'. Invalid value of `{glob_cmd}` given."
1579 )