Coverage for src/hdmf/backends/io.py: 98%
85 statements
« prev ^ index » next coverage.py v7.2.5, created at 2023-08-18 20:49 +0000
« prev ^ index » next coverage.py v7.2.5, created at 2023-08-18 20:49 +0000
1from abc import ABCMeta, abstractmethod
2import os
3from pathlib import Path
5from ..build import BuildManager, GroupBuilder
6from ..container import Container, HERDManager
7from .errors import UnsupportedOperation
8from ..utils import docval, getargs, popargs
9from warnings import warn
12class HDMFIO(metaclass=ABCMeta):
14 @staticmethod
15 @abstractmethod
16 def can_read(path):
17 """Determines whether a given path is readable by this HDMFIO class"""
18 pass
20 @docval({'name': 'manager', 'type': BuildManager,
21 'doc': 'the BuildManager to use for I/O', 'default': None},
22 {"name": "source", "type": (str, Path),
23 "doc": "the source of container being built i.e. file path", 'default': None},
24 {'name': 'herd_path', 'type': str,
25 'doc': 'The path to the HERD', 'default': None},)
26 def __init__(self, **kwargs):
27 manager, source, herd_path = getargs('manager', 'source', 'herd_path', kwargs)
28 if isinstance(source, Path): 28 ↛ 29line 28 didn't jump to line 29, because the condition on line 28 was never true
29 source = source.resolve()
30 elif (isinstance(source, str) and
31 not (source.lower().startswith("http://") or
32 source.lower().startswith("https://") or
33 source.lower().startswith("s3://"))):
34 source = os.path.abspath(source)
36 self.__manager = manager
37 self.__built = dict()
38 self.__source = source
39 self.herd_path = herd_path
40 self.herd = None
41 self.open()
43 @property
44 def manager(self):
45 '''The BuildManager this instance is using'''
46 return self.__manager
48 @property
49 def source(self):
50 '''The source of the container being read/written i.e. file path'''
51 return self.__source
53 @docval(returns='the Container object that was read in', rtype=Container)
54 def read(self, **kwargs):
55 """Read a container from the IO source."""
56 f_builder = self.read_builder()
57 if all(len(v) == 0 for v in f_builder.values()):
58 # TODO also check that the keys are appropriate. print a better error message
59 raise UnsupportedOperation('Cannot build data. There are no values.')
60 container = self.__manager.construct(f_builder)
61 container.read_io = self
62 if self.herd_path is not None:
63 from hdmf.common import HERD
64 try:
65 self.herd = HERD.from_zip(path=self.herd_path)
66 if isinstance(container, HERDManager): 66 ↛ 75line 66 didn't jump to line 75, because the condition on line 66 was never false
67 container.link_resources(herd=self.herd)
68 except FileNotFoundError:
69 msg = "File not found at {}. HERD not added.".format(self.herd_path)
70 warn(msg)
71 except ValueError:
72 msg = "Check HERD separately for alterations. HERD not added."
73 warn(msg)
75 return container
77 @docval({'name': 'container', 'type': Container, 'doc': 'the Container object to write'}, allow_extra=True)
78 def write(self, **kwargs):
79 """Write a container to the IO source."""
80 container = popargs('container', kwargs)
81 f_builder = self.__manager.build(container, source=self.__source, root=True)
82 self.write_builder(f_builder, **kwargs)
84 if self.herd_path is not None:
85 herd = container.get_linked_resources()
86 if herd is not None:
87 herd.to_zip(path=self.herd_path)
88 else:
89 msg = "Could not find linked HERD. Container was still written to IO source."
90 warn(msg)
92 @docval({'name': 'src_io', 'type': 'HDMFIO', 'doc': 'the HDMFIO object for reading the data to export'},
93 {'name': 'container', 'type': Container,
94 'doc': ('the Container object to export. If None, then the entire contents of the HDMFIO object will be '
95 'exported'),
96 'default': None},
97 {'name': 'write_args', 'type': dict, 'doc': 'arguments to pass to :py:meth:`write_builder`',
98 'default': dict()},
99 {'name': 'clear_cache', 'type': bool, 'doc': 'whether to clear the build manager cache',
100 'default': False})
101 def export(self, **kwargs):
102 """Export from one backend to the backend represented by this class.
104 If `container` is provided, then the build manager of `src_io` is used to build the container, and the resulting
105 builder will be exported to the new backend. So if `container` is provided, `src_io` must have a non-None
106 manager property. If `container` is None, then the contents of `src_io` will be read and exported to the new
107 backend.
109 The provided container must be the root of the hierarchy of the source used to read the container (i.e., you
110 cannot read a file and export a part of that file.
112 Arguments can be passed in for the `write_builder` method using `write_args`. Some arguments may not be
113 supported during export.
115 Example usage:
117 .. code-block:: python
119 old_io = HDF5IO('old.nwb', 'r')
120 with HDF5IO('new_copy.nwb', 'w') as new_io:
121 new_io.export(old_io)
123 NOTE: When implementing export support on custom backends. Export does not update the Builder.source
124 on the Builders. As such, when writing LinkBuilders we need to determine if LinkBuilder.source
125 and LinkBuilder.builder.source are the same, and if so the link should be internal to the
126 current file (even if the Builder.source points to a different location).
127 """
128 src_io, container, write_args, clear_cache = getargs('src_io', 'container', 'write_args', 'clear_cache', kwargs)
129 if container is None and clear_cache:
130 # clear all containers and builders from cache so that they can all get rebuilt with export=True.
131 # constructing the container is not efficient but there is no elegant way to trigger a
132 # rebuild of src_io with new source.
133 container = src_io.read()
134 if container is not None:
135 # check that manager exists, container was built from manager, and container is root of hierarchy
136 if src_io.manager is None:
137 raise ValueError('When a container is provided, src_io must have a non-None manager (BuildManager) '
138 'property.')
139 old_bldr = src_io.manager.get_builder(container)
140 if old_bldr is None:
141 raise ValueError('The provided container must have been read by the provided src_io.')
142 if old_bldr.parent is not None:
143 raise ValueError('The provided container must be the root of the hierarchy of the '
144 'source used to read the container.')
146 # NOTE in HDF5IO, clear_cache is set to True when link_data is False
147 if clear_cache:
148 # clear all containers and builders from cache so that they can all get rebuilt with export=True
149 src_io.manager.clear_cache()
150 else:
151 # clear only cached containers and builders where the container was modified
152 src_io.manager.purge_outdated()
153 bldr = src_io.manager.build(container, source=self.__source, root=True, export=True)
154 else:
155 bldr = src_io.read_builder()
156 self.write_builder(builder=bldr, **write_args)
158 @abstractmethod
159 @docval(returns='a GroupBuilder representing the read data', rtype='GroupBuilder')
160 def read_builder(self):
161 ''' Read data and return the GroupBuilder representing it '''
162 pass
164 @abstractmethod
165 @docval({'name': 'builder', 'type': GroupBuilder, 'doc': 'the GroupBuilder object representing the Container'},
166 allow_extra=True)
167 def write_builder(self, **kwargs):
168 ''' Write a GroupBuilder representing an Container object '''
169 pass
171 @abstractmethod
172 def open(self):
173 ''' Open this HDMFIO object for writing of the builder '''
174 pass
176 @abstractmethod
177 def close(self):
178 ''' Close this HDMFIO object to further reading/writing'''
179 pass
181 def __enter__(self):
182 return self
184 def __exit__(self, type, value, traceback):
185 self.close()
187 def __del__(self):
188 self.close()