Coverage for src / file_tree / file_tree.py: 87%
463 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"""Defines the main FileTree object, which will be the main point of interaction."""
3import os
4import string
5import warnings
6from collections import defaultdict
7from difflib import get_close_matches
8from functools import cmp_to_key
9from pathlib import Path
10from shutil import copyfile
11from typing import Any, Collection, Dict, Generator, Optional, Sequence, Set, Union
12from warnings import warn
14import numpy as np
15import rich
16import xarray
18from .template import DuplicateTemplate, Placeholders, Template, is_singular, is_missing
21class FileTree:
22 """Represents a structured directory.
24 The many methods can be split into 4 categories
26 1. The template interface. Each path (file or directory) is represented by a :class:`Template <file_tree.template.Template>`,
27 which defines the filename with any unknown parts (e.g., subject ID) marked by placeholders.
28 Templates are accessed based on their key.
30 - :meth:`get_template`: used to access a template based on its key.
31 - :meth:`template_keys`: used to list all the template keys.
32 - :meth:`add_template`: used to add a new template or overwrite an existing one.
33 - :meth:`add_subtree`: can be used to add all the templates from a different tree to this one.
34 - :meth:`override`: overrides some of the templates in this FileTree with that of another FileTree.
35 - :meth:`filter_templates`: reduce the filetree to a user-provided list of templates and its parents
37 2. The placeholder interface. Placeholders represent values to be filled into the placeholders.
38 Each placeholder can be either undefined, have a singular value, or have a sequence of possible values.
40 - You can access the :class:`placeholders dictionary-like object <file_tree.template.Placeholders>` directly through `FileTree.placeholders`
41 - :meth:`update`: returns a new FileTree with updated placeholders or updates the placeholders in the current one.
42 - :meth:`update_glob`: sets the placeholder values based on which files/directories exist on disk.
43 - :meth:`iter_vars`: iterate over all possible values for the selected placeholders.
44 - :meth:`iter`: iterate over all possible values for the placeholders that are part of a given template.
46 3. Getting the actual filenames based on filling the placeholder values into the templates.
48 - :meth:`get`: Returns a valid path by filling in all the placeholders in a template.
49 For this to work all placeholder values should be defined and singular.
50 - :meth:`get_mult`: Returns array of all possible valid paths by filling in the placeholders in a template.
51 Placeholder values can be singular or a sequence of possible values.
52 - :meth:`get_mult_glob`: Returns array with existing paths on disk.
53 Placeholder values can be singular, a sequence of possible values, or undefined.
54 In the latter case possible values for that placeholder are determined by checking the disk.
55 - :meth:`fill`: Returns new FileTree with any singular values filled into the templates and removed from the placeholder dict.
57 4. Input/output
59 - :meth:`report`: create a pretty overview of the filetree
60 - :meth:`run_app`: opens a terminal-based App to explore the filetree interactively
61 - :meth:`empty`: creates empty FileTree with no templates or placeholder values.
62 - :meth:`read`: reads a new FileTree from a file.
63 - :meth:`from_string`: reads a new FileTree from a string.
64 - :meth:`write`: writes a FileTree to a file.
65 - :meth:`to_string`: writes a FileTree to a string.
66 """
68 def __init__(
69 self,
70 templates: Dict[str, Template],
71 placeholders: Union[Dict[str, Any], Placeholders],
72 return_path=False,
73 glob=True,
74 ):
75 """Create a new FileTree with provided templates/placeholders."""
76 self._templates = templates
77 self.placeholders = Placeholders(placeholders)
78 self.return_path = return_path
79 self.glob = glob
80 if not (glob in (False, True, "default", "first", "last") or callable(glob)):
81 raise ValueError(
82 f"Invalid value for `glob` ({glob}). Please note that from v1.6 `glob` is now a setting in `FileTree` and can no longer be used as a placeholder name."
83 )
85 # create new FileTree objects
86 @classmethod
87 def empty(
88 cls, top_level: Union[str, Template] = ".", return_path=False, glob=True
89 ) -> "FileTree":
90 """Create a new empty FileTree containing only a top-level directory.
92 Args:
93 top_level: Top-level directory that other templates will use as a reference. Defaults to current directory.
94 return_path: if True, returns filenames as Path objects rather than strings.
95 glob: determines whether to allow filename pattern matching in the templates. Globbing is only applied if there are `*` or `?` characters in the template. Possible values are:
96 - `False`: do not do any pattern matching (identical to <= v1.5 behaviour).
97 - `True`/"default": return filename if there is a single match. Raise an error otherwise. This is the default behaviour in v1.6 or later.
98 - "first"/"last": return the first or last match (based on alphabetical ordering). An error is raised if there are no matches.
99 - callable: return the match returned by the callable. The input to the callable is a list of all the matching filenames (possibly of zero length).
101 Returns:
102 empty FileTree
103 """
104 if not isinstance(top_level, Template):
105 top_level = Template(None, top_level)
106 return cls({"": top_level}, {}, return_path=return_path, glob=glob)
108 @classmethod
109 def read(
110 cls,
111 name: str,
112 top_level: Union[str, Template] = ".",
113 return_path=False,
114 glob=True,
115 **placeholders,
116 ) -> "FileTree":
117 """Read a filetree based on the given name.
119 # noqa DAR101
121 Args:
122 name: name of the filetree. Interpreted as:
124 - a filename containing the tree definition if "name" or "name.tree" exist on disk
125 - one of the trees in `tree_directories` if one of those contains "name" or "name.tree"
126 - one of the tree in the plugin FileTree modules
128 top_level: top-level directory name. Defaults to current directory. Set to parent template for sub-trees.
129 return_path: if True, returns filenames as Path objects rather than strings.
130 glob: determines whether to allow filename pattern matching in the templates. Globbing is only applied if there are `*` or `?` characters in the template. Possible values are:
131 - `False`: do not do any pattern matching (identical to <= v1.5 behaviour).
132 - `True`/"default": return filename if there is a single match. Raise an error otherwise. This is the default behaviour in v1.6 or later.
133 - "first"/"last": return the first or last match (based on alphabetical ordering). An error is raised if there are no matches.
134 - callable: return the match returned by the callable. The input to the callable is a list of all the matching filenames (possibly of zero length).
135 placeholders: maps placeholder names to their values
137 Raises:
138 ValueError: if FileTree is not found.
140 Returns:
141 FileTree: tree matching the definition in the file
142 """
143 from . import parse_tree
145 if "directory" in placeholders:
146 warnings.warn(
147 f"Setting the 'directory' placeholder to {placeholders['directory']}. "
148 + "This differs from the behaviour of the old filetree in fslpy, which used the `directory` keyword to set the top-level directory. "
149 + "If you want to do that, please use the new `top_level` keyword instead of `directory`."
150 )
151 found_tree = parse_tree.search_tree(name)
152 if isinstance(found_tree, Path):
153 with open(found_tree, "r") as f:
154 text = f.read()
155 with parse_tree.extra_tree_dirs([found_tree.parent]):
156 return cls.from_string(
157 text, top_level, return_path=return_path, glob=glob, **placeholders
158 )
159 elif isinstance(found_tree, str):
160 return cls.from_string(
161 found_tree,
162 top_level,
163 return_path=return_path,
164 glob=glob,
165 **placeholders,
166 )
167 elif isinstance(found_tree, FileTree):
168 new_tree = cls.empty(top_level, return_path, glob=glob)
169 new_tree.add_subtree(found_tree, fill=False)
170 return new_tree.update(**placeholders)
171 raise ValueError(
172 f"Type of object ({type(found_tree)}) returned when searching for FileTree named '{name}' was not recognised"
173 )
175 @classmethod
176 def from_string(
177 cls,
178 definition: str,
179 top_level: Union[str, Template] = ".",
180 return_path=False,
181 glob=True,
182 **placeholders,
183 ) -> "FileTree":
184 """Create a FileTree based on the given definition.
186 Args:
187 definition: A FileTree definition describing a structured directory
188 top_level: top-level directory name. Defaults to current directory. Set to parent template for sub-trees.
189 return_path: if True, returns filenames as Path objects rather than strings.
190 glob: determines whether to allow filename pattern matching in the templates. Globbing is only applied if there are `*` or `?` characters in the string. Possible values are:
191 - `False`: do not do any pattern matching (identical to <= v1.5 behaviour).
192 - `True`/"default": return filename if there is a single match. Raise an error otherwise. This is the default behaviour in v1.6 or later.
193 - "first"/"last": return the first or last match (based on alphabetical ordering). An error is raised if there are no matches.
194 - callable: return the match returned by the callable. The input to the callable is a list of all the matching filenames (possibly of zero length).
195 placeholders: key->value pairs setting initial value for any placeholders.
197 Returns:
198 FileTree: tree matching the definition in the file
199 """
200 from . import parse_tree
202 res = parse_tree.read_file_tree_text(definition.splitlines(), top_level).update(
203 inplace=True, **placeholders
204 )
205 res.return_path = return_path
206 res.glob = glob
207 return res
209 def copy(
210 self,
211 ) -> "FileTree":
212 """Create a copy of the tree.
214 The dictionaries (templates, placeholders) are copied, but the values within them are not.
216 Returns:
217 FileTree: new tree object with identical templates, sub-trees and placeholders
218 """
219 new_tree = type(self)(
220 dict(self._templates),
221 Placeholders(self.placeholders),
222 self.return_path,
223 self.glob,
224 )
225 return new_tree
227 # template interface
228 def get_template(self, key: str, error_duplicate=True) -> Template:
229 """Return the template corresponding to `key`.
231 Raises:
232 KeyError: if no template with that identifier is available # noqa DAR402
233 ValueError: if multiple templates with that identifier are available (suppress using `error_duplicate=False`)
235 Args:
236 key (str): key identifying the template.
237 error_duplicate (bool): set to False to return a `DuplicateTemplate` object rather than raising an error
239 Returns:
240 Template: description of pathname with placeholders not filled in
241 """
242 try:
243 value = self._templates[key]
244 if error_duplicate and isinstance(value, DuplicateTemplate):
245 templates = ", ".join([str(t.as_path) for t in value.templates])
246 raise ValueError(
247 f"There are multiple templates matching key '{key}': {templates}"
248 )
249 return value
250 except KeyError:
251 pass
252 matches = get_close_matches(key, self.template_keys())
253 if len(matches) == 0:
254 raise KeyError(f"Template key '{key}' not found in FileTree.")
255 else:
256 raise KeyError(
257 f"Template key '{key}' not found in FileTree; did you mean {' or '.join(sorted(matches))}?"
258 )
260 @property
261 def top_level(
262 self,
263 ):
264 """Top-level directory.
266 Within the template dictionary this top-level directory is represented with an empty string
267 """
268 as_string = self.get_template("").unique_part
269 if self.return_path:
270 return Path(as_string)
271 return str(as_string)
273 @top_level.setter
274 def top_level(self, value: str):
275 self.get_template("").unique_part = str(value)
277 def add_template(
278 self,
279 template_path: str,
280 key: Optional[Union[str, Sequence[str]]] = None,
281 parent: Optional[str] = "",
282 overwrite=False,
283 ) -> Template:
284 """Update the FileTree with the new template.
286 Args:
287 template_path: path name with respect to the parent (or top-level if no parent provided)
288 key: key(s) to access this template in the future. Defaults to result from :meth:`Template.guess_key <file_tree.template.Template.guess_key>`
289 (i.e., the path basename without the extension).
290 parent: if defined, `template_path` will be interpreted as relative to this template.
291 By default the top-level template is used as reference.
292 To create a template unaffiliated with the rest of the tree, set `parent` to None.
293 Such a template should be an absolute path or relative to the current directory and can be used as parent for other templates
294 overwrite: if True, overwrites any existing template rather than raising a ValueError. Defaults to False.
296 Returns:
297 Template: the newly added template object
298 """
299 if parent is None:
300 parent_template = None
301 elif isinstance(parent, Template):
302 parent_template = parent
303 else:
304 parent_template = self.get_template(parent)
305 new_template = Template(parent_template, template_path)
306 if (
307 parent_template is not None
308 and new_template.as_path == parent_template.as_path
309 ):
310 new_template = parent_template
311 return self._add_actual_template(new_template, key, overwrite=overwrite)
313 def _add_actual_template(
314 self,
315 template: Template,
316 keys: Optional[Union[str, Sequence[str]]] = None,
317 overwrite=False,
318 ):
319 if keys is None:
320 keys = template.guess_key()
321 if isinstance(keys, Path):
322 keys = str(keys)
323 if isinstance(keys, str):
324 keys = [keys]
325 for key in keys:
326 if key in self._templates:
327 old_template = self.get_template(key, error_duplicate=overwrite)
328 if not overwrite:
329 if isinstance(old_template, DuplicateTemplate):
330 old_template.add_template(template)
331 else:
332 self._templates[key] = DuplicateTemplate(old_template, template)
333 continue
335 for potential_child in self._templates.values():
336 if potential_child.parent is old_template:
337 potential_child.parent = template
338 self._templates[key] = template
339 return template
341 def override(
342 self,
343 new_filetree: "FileTree",
344 required: Collection[str] = (),
345 optional: Collection[str] = (),
346 ):
347 """Overide some templates and all placeholders in this filetree with templates from `new_filetree`.
349 A new `FileTree` is returned with all the template keys in `required` replaced or added.
350 Template keys in `optional` will also be replaced or added if they are present in `new_filetree`.
352 Any placeholders defined in `new_filetree` will be transfered as well.
354 Without supplying any keys to `required` or `optional` the new `FileTree` will be identical to this one.
355 """
356 if isinstance(required, str):
357 required = [required]
358 if isinstance(optional, str):
359 optional = [optional]
360 all_keys = set(required).union(optional)
362 old_duplicate_keys = self.template_keys(skip_duplicates=False).difference(
363 self.template_keys(skip_duplicates=True)
364 )
365 duplicates = [key for key in all_keys if key in old_duplicate_keys]
366 if len(duplicates) > 0:
367 raise ValueError(
368 "Some of the keys to be replaced in the original FileTree are duplicates: %s",
369 ", ".join(duplicates),
370 )
372 new_available_keys = new_filetree.template_keys(skip_duplicates=False)
373 undefined = [key for key in required if key not in new_available_keys]
374 if len(undefined) > 0:
375 raise ValueError(
376 "Some required keys are missing from the input FileTree: %s",
377 ", ".join(undefined),
378 )
380 new_duplicate_keys = new_available_keys.difference(
381 new_filetree.template_keys(skip_duplicates=True)
382 )
383 duplicates = [key for key in all_keys if key in new_duplicate_keys]
384 if len(duplicates) > 0:
385 raise ValueError(
386 "Some of the keys to be used in the input FileTree are duplicates: %s",
387 ", ".join(duplicates),
388 )
390 res_filetree = self.copy()
391 res_filetree.placeholders.update(new_filetree.placeholders)
392 for key in all_keys:
393 if key in new_available_keys:
394 res_filetree._add_actual_template(
395 new_filetree.get_template(key), key, overwrite=True
396 )
397 return res_filetree
399 @property
400 def _iter_templates(
401 self,
402 ) -> Dict[Template, Set[str]]:
403 result = defaultdict(set)
405 def add_parent(t: Template):
406 if t.parent is None or t.parent in result:
407 return
408 result[t.parent]
409 add_parent(t.parent)
411 for key, possible in self._templates.items():
412 if isinstance(possible, DuplicateTemplate):
413 for template in possible.templates:
414 result[template].add(key)
415 add_parent(template)
416 else:
417 result[possible].add(key)
418 add_parent(possible)
419 return dict(result)
421 def template_keys(self, only_leaves=False, skip_duplicates=True):
422 """Return the keys of all the templates in the FileTree.
424 Each key will be returned for templates with multiple keys.
426 Args
427 only_leaves (bool, optional): set to True to only return templates that do not have any children.
428 skip_duplicates (bool, optional): set to False to include keys that point to multiple templates.
429 """
430 if skip_duplicates:
431 keys = {k for (k, v) in self._templates.items() if isinstance(v, Template)}
432 else:
433 keys = set(self._templates.keys())
434 if not only_leaves:
435 return keys
436 elif not skip_duplicates:
437 raise ValueError("Cannot select only leaves when not skipping duplicates.")
439 parents = {
440 t.parent for t in self._iter_templates.keys() if t.parent is not None
441 }
442 return {key for key in keys if self.get_template(key) not in parents}
444 def add_subtree(
445 self,
446 sub_tree: "FileTree",
447 precursor: Union[Optional[str], Sequence[Optional[str]]] = (None,),
448 parent: Optional[Union[str, Template]] = "",
449 fill=None,
450 ) -> None:
451 """Update the templates and the placeholders in place with those in sub_tree.
453 The top-level directory of the sub-tree will be replaced by the `parent` (unless set to None).
454 The sub-tree templates will be available with the key "<precursor>/<original_key>",
455 unless the precursor is None in which case they will be unchanged (which can easily lead to errors due to naming conflicts).
457 What happens with the placeholder values of the sub-tree depends on whether the precursor is None or not:
459 - if the precursor is None, any singular values are directly filled into the sub-tree templates.
460 Any placeholders with multiple values will be added to the top-level variable list (error is raised in case of conflicts).
461 - if the precursor is a string, the templates are updated to look for "<precursor>/<original_placeholder>" and
462 all sub-tree placeholder values are also prepended with this precursor.
463 Any template values with "<precursor>/<key>" will first look for that full key, but if that is undefined
464 they will fall back to "<key>" (see :class:`Placeholders <file_tree.template.Placeholders>`).
466 The net effect of either of these procedures is that the sub-tree placeholder values will be used in that sub-tree,
467 but will not affect templates defined elsewhere in the parent tree.
468 If a placeholder is undefined in a sub-tree, it will be taken from the parent placeholder values (if available).
470 Args:
471 sub_tree: tree to be added to the current one
472 precursor: name(s) of the sub-tree. Defaults to just adding the sub-tree to the main tree without precursor
473 parent: key of the template used as top-level directory for the sub tree.
474 Defaults to top-level directory of the main tree.
475 Can be set to None for an independent tree.
476 fill: whether any defined placeholders should be filled in before adding the sub-tree. By default this is True if there is no precursor and false otherwise
478 Raises:
479 ValueError: if there is a conflict in the template names.
480 """
481 if isinstance(precursor, str) or precursor is None:
482 precursor = [precursor]
483 for name in precursor:
484 sub_tree_fill = sub_tree
485 if name is None:
486 add_string = ""
487 if (fill is None) or fill:
488 sub_tree_fill = sub_tree.fill()
489 else:
490 add_string = name + "/"
491 if fill:
492 sub_tree_fill = sub_tree.fill()
494 to_assign = dict(sub_tree_fill._iter_templates)
495 sub_top_level = [k for (k, v) in to_assign.items() if "" in v][0]
497 if parent is None:
498 new_top_level = Template(None, sub_top_level.unique_part)
499 elif isinstance(parent, Template):
500 new_top_level = parent
501 else:
502 new_top_level = self.get_template(parent)
503 if name is None:
504 if parent is None:
505 for letter in string.ascii_letters:
506 label = f"tree_top_{letter}"
507 if (
508 label not in sub_tree_fill.template_keys()
509 and label not in self.template_keys()
510 ):
511 self._add_actual_template(new_top_level, label)
512 break
513 else:
514 self._add_actual_template(new_top_level, add_string)
516 been_assigned = {sub_top_level: new_top_level}
517 del to_assign[sub_top_level]
518 while len(to_assign) > 0:
519 for old_template, keys in list(to_assign.items()):
520 if old_template.parent is None:
521 parent_template = None
522 elif old_template.parent in been_assigned:
523 parent_template = been_assigned[old_template.parent]
524 else:
525 continue
526 new_template = Template(
527 parent_template, old_template.unique_part
528 ).add_precursor(add_string)
529 for key in keys:
530 self._add_actual_template(new_template, add_string + key)
531 been_assigned[old_template] = new_template
532 del to_assign[old_template]
534 if name is None:
535 conflict = {
536 key
537 for key in sub_tree_fill.placeholders.keys()
538 if key in self.placeholders
539 }
540 if len(conflict) > 0:
541 raise ValueError(
542 f"Sub-tree placeholder values for {conflict} conflict with those set in the parent tree."
543 )
544 for old_key, old_value in sub_tree_fill.placeholders.items():
545 if isinstance(old_key, str):
546 self.placeholders[add_string + old_key] = old_value
547 else:
548 self.placeholders[frozenset(add_string + k for k in old_key)] = {
549 add_string + k: v for k, v in old_value.items()
550 }
552 def filter_templates(
553 self, template_names: Collection[str], check=True
554 ) -> "FileTree":
555 """Create new FileTree containing just the templates in `template_names` and their parents.
557 Args:
558 template_names: names of the templates to keep.
559 check: if True, check whether all template names are actually part of the FileTree
561 Raises:
562 KeyError: if any of the template names are not in the FileTree (unless `check` is set to False).
564 Returns:
565 FileTree containing requested subset of templates.
566 """
567 all_keys = self.template_keys()
568 if check:
569 undefined = {name for name in template_names if name not in all_keys}
570 if len(undefined) > 0:
571 raise KeyError("Undefined template names found in filter: ", undefined)
573 new_filetree = FileTree(
574 {}, self.placeholders.copy(), return_path=self.return_path, glob=self.glob
575 )
577 already_added = set()
579 def add_template(template: Template):
580 if template in already_added:
581 return
582 if template.parent is not None:
583 add_template(template.parent)
584 new_filetree._add_actual_template(template, self._iter_templates[template])
585 already_added.add(template)
587 for name in template_names:
588 if name not in all_keys:
589 continue
590 add_template(self.get_template(name))
592 return new_filetree
594 # placeholders interface
595 def update(self, inplace=False, **placeholders) -> "FileTree":
596 """Update the placeholder values to be filled into the templates.
598 Args:
599 inplace (bool): if True change the placeholders in-place (and return the FileTree itself);
600 by default a new FileTree is returned with the updated values without altering this one.
601 **placeholders (Dict[str, Any]): maps placeholder names to their new values (None to mark placeholder as undefined)
603 Returns:
604 FileTree: Tree with updated placeholders (same tree as the current one if inplace is True)
605 """
606 new_tree = self if inplace else self.copy()
607 new_tree.placeholders.update(placeholders)
608 return new_tree
610 def update_glob(
611 self,
612 template_key: Union[str, Sequence[str]],
613 inplace=False,
614 link: Union[None, Sequence[str], Sequence[Sequence[str]]] = None,
615 ) -> "FileTree":
616 """Update any undefined placeholders based on which files exist on disk for template.
618 Args:
619 template_key (str or sequence of str): key(s) of the template(s) to use
620 inplace (bool): if True change the placeholders in-place (and return the FileTree itself);
621 by default a new FileTree is returned with the updated values without altering this one.
622 link (sequences of str): template keys that should be linked together in the output.
624 Returns:
625 FileTree: Tree with updated placeholders (same tree as the current one if inplace is True)
626 """
627 if link is None:
628 link = []
629 elif len(link) > 0 and isinstance(link[0], str):
630 link = [link]
631 link_as_frozenset = [frozenset(link_value) for link_value in link]
633 if isinstance(template_key, str):
634 template_key = [template_key]
635 new_placeholders: Dict[str, Set[str]] = defaultdict(set)
636 new_links = [set() for _ in range(len(link))]
637 for key in template_key:
638 template = self.get_template(key)
639 from_template = template.get_all_placeholders(self.placeholders, link=link)
640 for name, values in from_template.items():
641 if isinstance(name, frozenset):
642 index = link_as_frozenset.index(name)
643 values_as_tuples = zip(*[values[key] for key in link[index]])
644 new_links[index].update(values_as_tuples)
645 else:
646 new_placeholders[name] = new_placeholders[name].union(values)
648 def cmp(item1, item2):
649 if is_missing(item1):
650 return -1
651 if is_missing(item2):
652 return 1
653 if item1 < item2:
654 return -1
655 if item1 > item2:
656 return 1
657 return 0
659 new_tree = self if inplace else self.copy()
660 new_tree.placeholders.update(
661 {k: sorted(v, key=cmp_to_key(cmp)) for k, v in new_placeholders.items()},
662 )
663 for key, value in zip(link, new_links):
664 new_tree.placeholders[tuple(key)] = list(zip(*sorted(value)))
665 return new_tree
667 # Extract paths
668 def get(self, key: str, make_dir=False, glob=None) -> Union[str, Path]:
669 """Return template with placeholder values filled in.
671 Args:
672 key (str): identifier for the template
673 make_dir (bool, optional): If set to True, create the parent directory of the returned path.
674 glob: determines whether to allow filename pattern matching in the templates. By default the value set when creating the file-tree is used (see `FileTree.glob`). Globbing is only applied if there are `*` or `?` in the template. Possible values are:
675 - `False`: do not do any pattern matching (identical to <= v1.5 behaviour). Use this to get the raw string including any `*` or `?` characters
676 - `True`/"default": return filename if there is a single match. Raise an error otherwise.
677 - "first"/"last": return the first or last match (based on alphabetical ordering). An error is raised if there are no matches.
678 - callable: return the match returned by the callable. The input to the callable is a list of all the matching filenames (possibly of zero length).
680 Returns:
681 Path: Filled in template as Path object.
682 Returned as a `pathlib.Path` object if `FileTree.return_path` is True.
683 Otherwise a string is returned.
684 """
685 path = self.get_template(key).format_single(
686 self.placeholders, glob=self.glob if glob is None else glob
687 )
688 if make_dir:
689 Path(path).parent.mkdir(parents=True, exist_ok=True)
690 if self.return_path:
691 return Path(path)
692 return path
694 def get_mult(
695 self, key: Union[str, Sequence[str]], filter=False, make_dir=False, glob=None
696 ) -> Union[xarray.DataArray, xarray.Dataset]:
697 """Return array of paths with all possible values filled in for the placeholders.
699 Singular placeholder values are filled into the template directly.
700 For each placeholder with multiple values a dimension is added to the output array.
701 This dimension will have the name of the placeholder and labels corresponding to the possible values (see http://xarray.pydata.org/en/stable/).
702 The precense of required, undefined placeholders will lead to an error
703 (see :meth:`get_mult_glob` or :meth:`update_glob` to set these placeholders based on which files exist on disk).
705 Args:
706 key (str, Sequence[str]): identifier(s) for the template.
707 filter (bool, optional): If Set to True, will filter out any non-existent files.
708 If the return type is strings, non-existent entries will be empty strings.
709 If the return type is Path objects, non-existent entries will be None.
710 Note that the default behaviour is opposite from :meth:`get_mult_glob`.
711 make_dir (bool, optional): If set to True, create the parent directory for each returned path.
712 glob: determines whether to allow filename pattern matching in the templates. By default the value set when creating the file-tree is used (see `FileTree.glob`). Globbing is only applied if there are `*` or `?` in the template. Possible values are:
713 - `False`: do not do any pattern matching (identical to <= v1.5 behaviour). Use this to get the raw string including any `*` or `?` characters
714 - `True`/"default": return filename if there is a single match. Raise an error otherwise.
715 - "first"/"last": return the first or last match (based on alphabetical ordering). An error is raised if there are no matches.
716 - callable: return the match returned by the callable. The input to the callable is a list of all the matching filenames (possibly of zero length).
718 Returns:
719 xarray.DataArray, xarray.Dataset: For a single key returns all possible paths in an xarray DataArray.
720 For multiple keys it returns the combination of them in an xarray Dataset.
721 Each element of in the xarray is a `pathlib.Path` object if `FileTree.return_path` is True.
722 Otherwise the xarray will contain the paths as strings.
723 """
724 if isinstance(key, str):
725 paths = self.get_template(key).format_mult(
726 self.placeholders,
727 filter=filter,
728 glob=self.glob if glob is None else glob,
729 )
730 paths.name = key
731 if make_dir:
732 for path in paths.data.flat:
733 if path is not None:
734 Path(path).parent.mkdir(parents=True, exist_ok=True)
735 if self.return_path:
736 return xarray.apply_ufunc(
737 lambda p: None if p == "" else Path(p), paths, vectorize=True
738 )
739 return paths
740 else:
741 return xarray.merge(
742 [self.get_mult(k, filter=filter, make_dir=make_dir) for k in key],
743 join="exact",
744 )
746 def get_mult_glob(
747 self, key: Union[str, Sequence[str]], glob=None
748 ) -> Union[xarray.DataArray, xarray.Dataset]:
749 """Return array of paths with all possible values filled in for the placeholders.
751 Singular placeholder values are filled into the template directly.
752 For each placeholder with multiple values a dimension is added to the output array.
753 This dimension will have the name of the placeholder and labels corresponding to the possible values (see http://xarray.pydata.org/en/stable/).
754 The possible values for undefined placeholders will be determined by which files actually exist on disk.
756 The same result can be obtained by calling `self.update_glob(key).get_mult(key, filter=True)`.
757 However calling this method is more efficient, because it only has to check the disk for which files exist once.
759 Args:
760 key (str, Sequence[str]): identifier(s) for the template.
761 glob: determines whether to allow filename pattern matching in the templates. By default the value set when creating the file-tree is used (see `FileTree.glob`). Globbing is only applied if there are `*` or `?` in the template. Possible values are:
762 - `False`: do not do any pattern matching (identical to <= v1.5 behaviour). Use this to get the raw string including any `*` or `?` characters
763 - `True`/"default": return filename if there is a single match. Raise an error otherwise.
764 - "first"/"last": return the first or last match (based on alphabetical ordering). An error is raised if there are no matches.
765 - callable: return the match returned by the callable. The input to the callable is a list of all the matching filenames (possibly of zero length).
767 Returns:
768 xarray.DataArray, xarray.Dataset: For a single key returns all possible paths in an xarray DataArray.
769 For multiple keys it returns the combination of them in an xarray Dataset.
770 Each element of in the xarray is a `pathlib.Path` object if `FileTree.return_path` is True.
771 Otherwise the xarray will contain the paths as strings.
772 """
773 if isinstance(key, str):
774 template = self.get_template(key)
775 matches = template.all_matches(self.placeholders)
777 new_placeholders = Placeholders(self.placeholders)
778 updates, matches = template.get_all_placeholders(
779 self.placeholders, return_matches=True
780 )
781 new_placeholders.update(updates)
783 paths = template.format_mult(
784 new_placeholders,
785 filter=True,
786 matches=matches,
787 glob=self.glob if glob is None else glob,
788 )
789 paths.name = key
790 if self.return_path:
791 return paths
792 res = xarray.apply_ufunc(
793 lambda p: "" if p is None else str(p), paths, vectorize=True
794 )
795 return res
796 else:
797 return xarray.merge(
798 [self.get_mult_glob(k, glob) for k in key],
799 join="outer",
800 fill_value=None if self.return_path else "",
801 )
803 def fill(self, keep_optionals=True) -> "FileTree":
804 """Fill in singular placeholder values.
806 Args:
807 keep_optionals: if True keep optional parameters that have not been set
809 Returns:
810 FileTree: new tree with singular placeholder values filled into the templates and removed from the placeholder dict
811 """
812 new_tree = FileTree(
813 {}, self.placeholders.split()[1], self.return_path, glob=self.glob
814 )
815 to_assign = dict(self._iter_templates)
816 template_mappings = {None: None}
817 while len(to_assign) > 0:
818 for old_template, keys in list(to_assign.items()):
819 if old_template.parent in template_mappings:
820 new_parent = template_mappings[old_template.parent]
821 else:
822 continue
823 new_template = Template(
824 new_parent,
825 str(
826 Template(None, old_template.unique_part).format_single(
827 self.placeholders,
828 check=False,
829 keep_optionals=keep_optionals,
830 glob=False,
831 )
832 ),
833 )
834 template_mappings[old_template] = new_template
835 new_tree._add_actual_template(new_template, keys)
836 del to_assign[old_template]
837 return new_tree
839 # iteration
840 def iter_vars(
841 self, placeholders: Sequence[str]
842 ) -> Generator["FileTree", None, None]:
843 """Iterate over the user-provided placeholders.
845 A single file-tree is yielded for each possible value of the placeholders.
847 Args:
848 placeholders (Sequence[str]): sequence of placeholder names to iterate over
850 Yields:
851 FileTrees, where each placeholder only has a single possible value
852 """
853 for sub_placeholders in self.placeholders.iter_over(placeholders):
854 yield FileTree(
855 self._templates, sub_placeholders, self.return_path, glob=self.glob
856 )
858 def iter(
859 self, template: str, check_exists: bool = False
860 ) -> Generator["FileTree", None, None]:
861 """Iterate over trees containng all possible values for template.
863 Args:
864 template (str): short name identifier of the template
865 check_exists (bool): set to True to only return trees for which the template actually exists
867 Yields:
868 FileTrees, where each placeholder in given template only has a single possible value
869 """
870 placeholders = self.get_template(template).placeholders(
871 valid=self.placeholders.keys()
872 )
873 for tree in self.iter_vars(placeholders):
874 if not check_exists or Path(tree.get(template)).exists:
875 yield tree
877 # convert to string
878 def to_string(self, indentation=4) -> str:
879 """Convert FileTree into a valid filetree definition.
881 An identical FileTree can be created by running :meth:`from_string` on the resulting string.
883 Args:
884 indentation (int, optional): Number of spaces to use for indendation. Defaults to 4.
886 Returns:
887 String representation of FileTree.
888 """
889 lines = [self.placeholders.to_string()]
891 top_level = sorted(
892 [
893 template
894 for template in self._iter_templates.keys()
895 if template.parent is None
896 ],
897 key=lambda k: ",".join(self._iter_templates[k]),
898 )
899 already_done = set()
900 for t in top_level:
901 if t not in already_done:
902 lines.append(
903 t.as_multi_line(self._iter_templates, indentation=indentation)
904 )
905 already_done.add(t)
906 return "\n\n".join(lines)
908 def write(self, filename, indentation=4):
909 """Write the FileTree to a disk as a text file.
911 The first few lines will contain the placeholders.
912 The remaining lines will contain the actual FileTree with all the templates (including sub-trees).
913 The top-level directory is not stored in the file and hence will need to be provided when reading the tree from the file.
915 Args:
916 filename (str or Path): where to store the file (directory should exist already)
917 indentation (int, optional): Number of spaces to use in indendation. Defaults to 4.
918 """
919 with open(filename, "w") as f:
920 f.write(self.to_string(indentation=indentation))
922 def report(self, fill=True, pager=False):
923 """Print a formatted report of the filetree to the console.
925 Prints a report of the file-tree to the terminal with:
926 - table with placeholders and their values
927 - tree of templates with template keys marked in cyan
929 Args:
930 fill (bool, optional): by default any fixed placeholders are filled in before printing the tree (using :meth:`fill`). Set to False to disable this.
931 pager (bool, optional): if set to True, the report will be filed into a pager (recommended if the output is very large)
932 """
933 if fill:
934 self = self.fill()
936 if pager:
937 from rich.console import Console
939 printer = Console()
940 with printer.pager():
941 for part in self._generate_rich_report():
942 printer.print(part)
943 else:
944 for part in self._generate_rich_report():
945 rich.print(part)
947 def _generate_rich_report(self):
948 """Generate a sequence of Rich renderables to produce report."""
949 from rich.table import Table
950 from rich.tree import Tree
952 single_vars = {}
953 multi_vars = {}
954 linked_vars = []
955 for key, value in self.placeholders.items():
956 if value is None:
957 continue
958 if isinstance(key, frozenset):
959 linked_vars.append(sorted(key))
960 for linked_key, linked_value in value.items():
961 multi_vars[linked_key] = linked_value
962 elif np.array(value).ndim == 1:
963 multi_vars[key] = value
964 else:
965 single_vars[key] = value
966 if len(single_vars) > 0:
967 single_var_table = Table("name", "value", title="Defined placeholders")
968 for key in sorted(single_vars.keys()):
969 single_var_table.add_row(key, single_vars[key])
970 yield single_var_table
971 if len(multi_vars) > 0:
972 multi_var_table = Table(
973 "name", "value", title="Placeholders with multiple options"
974 )
975 for key in sorted(multi_vars.keys()):
976 multi_var_table.add_row(key, ", ".join(str(v) for v in multi_vars[key]))
977 yield multi_var_table
979 if len(linked_vars) > 0:
980 yield "Linked variables:\n" + (
981 "\n".join([", ".join(v) for v in linked_vars])
982 )
984 def add_children(t: Template, tree: Optional[Tree]):
985 for child in sorted(
986 t.children(self._iter_templates.keys()), key=lambda t: t.as_string
987 ):
988 child_tree = tree.add(child.rich_line(self._iter_templates))
989 add_children(child, child_tree)
991 top_level = sorted(
992 [
993 template
994 for template in self._iter_templates.keys()
995 if template.parent is None
996 ],
997 key=lambda t: ",".join(self._iter_templates[t]),
998 )
999 already_done = set()
1000 for t in top_level:
1001 if t not in already_done:
1002 base_tree = Tree(t.rich_line(self._iter_templates))
1003 add_children(t, base_tree)
1004 yield base_tree
1006 def run_app(
1007 self,
1008 ):
1009 """
1010 Open a terminal-based App to explore the filetree interactively.
1012 The resulting app runs directly in the terminal,
1013 so it should work when ssh'ing to some remote cluster.
1015 There will be two panels:
1017 - The left panel will show all the templates in a tree format.
1018 Template keys are shown in cyan.
1019 For each template the number of files that exist on disc out of the total number is shown
1020 colour coded based on completeness (red: no files; yellow: some files; blue: all files).
1021 Templates can be selected by hovering over them.
1022 Clicking on directories with hide/show their content.
1023 - The right panel will show for the selected template the complete template string
1024 and a table showing for which combination of placeholders the file is present/absent
1025 (rows for absent files are colour-coded red).
1026 """
1027 from . import app
1029 app.FileTreeViewer(self).run()
1032def convert(
1033 src_tree: FileTree,
1034 target_tree: Optional[FileTree] = None,
1035 keys=None,
1036 symlink=False,
1037 overwrite=False,
1038 glob_placeholders=None,
1039):
1040 """
1041 Copy or link files defined in `keys` from the `src_tree` to the `target_tree`.
1043 Given two example trees
1045 - source::
1047 subject = A,B
1049 sub-{subject}
1050 data
1051 T1w.nii.gz
1052 FLAIR.nii.gz
1054 - target::
1056 subject = A,B
1058 data
1059 sub-{subject}
1060 {subject}-T1w.nii.gz (T1w)
1061 {subject}-T2w.nii.gz (T2w)
1063 And given pre-existing data matching the source tree::
1065 .
1066 ├── sub-A
1067 │ └── data
1068 │ ├── FLAIR.nii.gz
1069 │ └── T1w.nii.gz
1070 └── sub-B
1071 └── data
1072 ├── FLAIR.nii.gz
1073 └── T1w.nii.gz
1075 We can do the following conversions:
1077 - `convert(source, target)`:
1078 copies all matching keys from `source` to `target`.
1079 This will only copy the "T1w.nii.gz" files, because they are the only match in the template keys.
1080 Note that the `data` template key also matches between the two trees, but this template is not a leaf, so is ignored.
1081 - `convert(source, target, keys=['T1w', ('FLAIR', 'T2w')])`:
1082 copies the "T1w.nii.gz" files from `source` to `target` and
1083 copies the "FLAIR.nii.gz" in `source` to "T2w..nii.gz" in `target`.
1084 - `convert(source.update(subject='B'), source.update(subject='C'))`:
1085 creates a new "data/sub-C" directory and
1086 copies all the data from "data/sub-B" into that directory.
1087 - `convert(source, keys=[('FLAIR', 'T1w')], overwrite=True)`:
1088 copies the "FLAIR.nii.gz" into the "T1w.nii.gz" files overwriting the originals.
1090 Warnings are raised in two cases:
1092 - if a source file is missing
1093 - if a target file already exists and `overwrite` is False
1095 Args:
1096 src_tree: prepopulated filetree with the source files
1097 target_tree: filetree that will be populated. Defaults to same as `src_tree`.
1098 keys: collection of template keys to transfer from `src_tree` to `target_tree`. Defaults to all templates keys shared between `src_tree` and `target_tree`.
1099 symlink: if set to true links the files rather than copying them
1100 overwrite: if set to True overwrite any existing files
1101 glob_placeholders: Placeholders that should be treated as wildcards. This is meant for placeholders that have different values for each filename.
1103 Raises:
1104 ValueError: if the conversion can not be carried out. If raised no data will be copied/linked.
1105 """
1106 if target_tree is None and keys is None:
1107 raise ValueError("Conversion requires either `target_tree` or `keys` to be set")
1108 src_tree = src_tree.copy()
1109 if target_tree is None:
1110 target_tree = src_tree
1111 target_tree = target_tree.copy()
1112 if keys is None:
1113 keys = set(src_tree.template_keys(only_leaves=True)).intersection(
1114 target_tree.template_keys(only_leaves=True)
1115 )
1116 if glob_placeholders is None:
1117 glob_placeholders = set()
1118 for p in glob_placeholders:
1119 if p in src_tree.placeholders:
1120 raise ValueError(
1121 f"Placeholder {p} has been selected for globbing, however values were set for it in source tree"
1122 )
1123 if p in target_tree.placeholders:
1124 raise ValueError(
1125 f"Placeholder {p} has been selected for globbing, however values were set for it in target tree"
1126 )
1128 full_keys = {
1129 (
1130 (key_definition, key_definition)
1131 if isinstance(key_definition, str)
1132 else key_definition
1133 )
1134 for key_definition in keys
1135 }
1136 for src_key, target_key in full_keys:
1137 # ensure template placeholders are consistent between source and target tree
1138 for placeholder in (
1139 src_tree.get_template(src_key).placeholders()
1140 + target_tree.get_template(target_key).placeholders()
1141 ):
1142 if placeholder in glob_placeholders:
1143 continue
1144 if placeholder not in src_tree.placeholders:
1145 if placeholder not in target_tree.placeholders:
1146 raise ValueError(
1147 f"Can not convert template {src_key}, because no values have been set for {placeholder}"
1148 )
1149 src_tree.placeholders[placeholder] = target_tree.placeholders[
1150 placeholder
1151 ]
1152 elif placeholder not in target_tree.placeholders:
1153 target_tree.placeholders[placeholder] = src_tree.placeholders[
1154 placeholder
1155 ]
1156 nsrc = (
1157 -1
1158 if is_singular(src_tree.placeholders[placeholder])
1159 else len(src_tree.placeholders[placeholder])
1160 )
1161 ntarget = (
1162 -1
1163 if is_singular(target_tree.placeholders[placeholder])
1164 else len(target_tree.placeholders[placeholder])
1165 )
1166 if nsrc != ntarget:
1167 raise ValueError(
1168 f"Number of possible values for {placeholder} do not match between source and target tree"
1169 )
1171 # ensure non-singular placeholders match
1172 src_non_singular = {
1173 p
1174 for p in src_tree.get_template(src_key).placeholders()
1175 if p not in glob_placeholders and not is_singular(src_tree.placeholders[p])
1176 }
1177 target_non_singular = {
1178 p
1179 for p in target_tree.get_template(target_key).placeholders()
1180 if p not in glob_placeholders
1181 and not is_singular(target_tree.placeholders[p])
1182 }
1184 diff = src_non_singular.difference(target_non_singular).difference(
1185 glob_placeholders
1186 )
1187 if len(diff) > 0:
1188 raise ValueError(
1189 f"Placeholders {diff} in source template {src_key} has no equivalent in target template {target_key}"
1190 )
1191 diff = target_non_singular.difference(src_non_singular)
1192 if len(diff) > 0:
1193 raise ValueError(
1194 f"Placeholders {diff} in target template {target_key} has no equivalent in source template {src_key}"
1195 )
1197 # all checks have passed; let's get to work
1198 to_warn_about = ([], [])
1200 transfer_filenames = []
1202 for src_key, target_key in sorted(full_keys):
1203 iter_placeholders = sorted(
1204 {
1205 p
1206 for p in src_tree.get_template(src_key).placeholders()
1207 if p not in glob_placeholders
1208 and not is_singular(src_tree.placeholders[p])
1209 }
1210 )
1211 for single_src_tree, single_target_tree in zip(
1212 src_tree.iter_vars(iter_placeholders),
1213 target_tree.iter_vars(iter_placeholders),
1214 ):
1215 if len(glob_placeholders) == 0:
1216 src_fn = single_src_tree.get(src_key)
1217 target_fn = single_target_tree.get(target_key)
1218 else:
1219 try:
1220 src_trees = list(single_src_tree.update_glob(src_key).iter(src_key))
1221 except ValueError:
1222 to_warn_about[0].append(
1223 single_src_tree.get_template(src_key).format_single(
1224 single_src_tree.placeholders, check=False
1225 )
1226 )
1227 continue
1228 if len(src_trees) > 1:
1229 raise ValueError(
1230 f"Multiple matching filenames were found when globbing {src_key} ({single_src_tree.get(src_key)})"
1231 )
1233 keys = {
1234 key: src_trees[0].placeholders[key]
1235 for key in glob_placeholders
1236 if key in src_trees[0].placeholders
1237 }
1238 src_fn = single_src_tree.update(**keys).get(src_key)
1239 target_fn = single_target_tree.update(**keys).get(src_key)
1241 transfer_filenames.append((Path(src_fn), Path(target_fn)))
1242 if len(to_warn_about[0]) > 0:
1243 warn(
1244 f"Following source files were not found during FileTree conversion: {to_warn_about[0]}"
1245 )
1246 if len(to_warn_about[1]) > 0:
1247 warn(
1248 f"Following target files already existed during FileTree conversion: {to_warn_about[1]}"
1249 )
1250 for fn1, fn2 in transfer_filenames:
1251 _convert_file(
1252 fn1,
1253 fn2,
1254 to_warn_about,
1255 symlink=symlink,
1256 overwrite=overwrite,
1257 )
1260def _convert_file(
1261 source: Path, target: Path, to_warn_about, symlink=False, overwrite=False
1262):
1263 """
1264 Copy or link `source` file to `target` file.
1266 Helper function for :func:`convert`
1267 """
1268 if not source.exists():
1269 to_warn_about[0].append(str(source))
1270 return
1271 if target.exists():
1272 if not overwrite:
1273 to_warn_about[1].append(str(target))
1274 return
1275 os.remove(target)
1276 target.parent.mkdir(parents=True, exist_ok=True)
1277 if not symlink:
1278 copyfile(source, target, follow_symlinks=False)
1279 elif source.is_absolute():
1280 target.symlink_to(source)
1281 else:
1282 target.symlink_to(os.path.relpath(source, target.parent))