Coverage for src/hdmf/backends/io.py: 97%
79 statements
« prev ^ index » next coverage.py v7.2.5, created at 2023-07-10 23:48 +0000
« prev ^ index » next coverage.py v7.2.5, created at 2023-07-10 23:48 +0000
1from abc import ABCMeta, abstractmethod
2import os
3from pathlib import Path
5from ..build import BuildManager, GroupBuilder
6from ..container import Container, ExternalResourcesManager
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': 'external_resources_path', 'type': str,
25 'doc': 'The path to the ExternalResources', 'default': None},)
26 def __init__(self, **kwargs):
27 manager, source, external_resources_path = getargs('manager', 'source', 'external_resources_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.external_resources_path = external_resources_path
40 self.external_resources = 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.external_resources_path is not None:
63 from hdmf.common import ExternalResources
64 try:
65 self.external_resources = ExternalResources.from_norm_tsv(path=self.external_resources_path)
66 if isinstance(container, ExternalResourcesManager): 66 ↛ 75line 66 didn't jump to line 75, because the condition on line 66 was never false
67 container.link_resources(external_resources=self.external_resources)
68 except FileNotFoundError:
69 msg = "File not found at {}. ExternalResources not added.".format(self.external_resources_path)
70 warn(msg)
71 except ValueError:
72 msg = "Check ExternalResources separately for alterations. ExternalResources not added."
73 warn(msg)
75 return container
77 @docval({'name': 'container', 'type': Container, 'doc': 'the Container object to write'},
78 allow_extra=True)
79 def write(self, **kwargs):
80 """Write a container to the IO source."""
81 container = popargs('container', kwargs)
82 f_builder = self.__manager.build(container, source=self.__source, root=True)
83 self.write_builder(f_builder, **kwargs)
85 @docval({'name': 'src_io', 'type': 'HDMFIO', 'doc': 'the HDMFIO object for reading the data to export'},
86 {'name': 'container', 'type': Container,
87 'doc': ('the Container object to export. If None, then the entire contents of the HDMFIO object will be '
88 'exported'),
89 'default': None},
90 {'name': 'write_args', 'type': dict, 'doc': 'arguments to pass to :py:meth:`write_builder`',
91 'default': dict()},
92 {'name': 'clear_cache', 'type': bool, 'doc': 'whether to clear the build manager cache',
93 'default': False})
94 def export(self, **kwargs):
95 """Export from one backend to the backend represented by this class.
97 If `container` is provided, then the build manager of `src_io` is used to build the container, and the resulting
98 builder will be exported to the new backend. So if `container` is provided, `src_io` must have a non-None
99 manager property. If `container` is None, then the contents of `src_io` will be read and exported to the new
100 backend.
102 The provided container must be the root of the hierarchy of the source used to read the container (i.e., you
103 cannot read a file and export a part of that file.
105 Arguments can be passed in for the `write_builder` method using `write_args`. Some arguments may not be
106 supported during export.
108 Example usage:
110 .. code-block:: python
112 old_io = HDF5IO('old.nwb', 'r')
113 with HDF5IO('new_copy.nwb', 'w') as new_io:
114 new_io.export(old_io)
116 NOTE: When implementing export support on custom backends. Export does not update the Builder.source
117 on the Builders. As such, when writing LinkBuilders we need to determine if LinkBuilder.source
118 and LinkBuilder.builder.source are the same, and if so the link should be internal to the
119 current file (even if the Builder.source points to a different location).
120 """
121 src_io, container, write_args, clear_cache = getargs('src_io', 'container', 'write_args', 'clear_cache', kwargs)
122 if container is None and clear_cache:
123 # clear all containers and builders from cache so that they can all get rebuilt with export=True.
124 # constructing the container is not efficient but there is no elegant way to trigger a
125 # rebuild of src_io with new source.
126 container = src_io.read()
127 if container is not None:
128 # check that manager exists, container was built from manager, and container is root of hierarchy
129 if src_io.manager is None:
130 raise ValueError('When a container is provided, src_io must have a non-None manager (BuildManager) '
131 'property.')
132 old_bldr = src_io.manager.get_builder(container)
133 if old_bldr is None:
134 raise ValueError('The provided container must have been read by the provided src_io.')
135 if old_bldr.parent is not None:
136 raise ValueError('The provided container must be the root of the hierarchy of the '
137 'source used to read the container.')
139 # NOTE in HDF5IO, clear_cache is set to True when link_data is False
140 if clear_cache:
141 # clear all containers and builders from cache so that they can all get rebuilt with export=True
142 src_io.manager.clear_cache()
143 else:
144 # clear only cached containers and builders where the container was modified
145 src_io.manager.purge_outdated()
146 bldr = src_io.manager.build(container, source=self.__source, root=True, export=True)
147 else:
148 bldr = src_io.read_builder()
149 self.write_builder(builder=bldr, **write_args)
151 @abstractmethod
152 @docval(returns='a GroupBuilder representing the read data', rtype='GroupBuilder')
153 def read_builder(self):
154 ''' Read data and return the GroupBuilder representing it '''
155 pass
157 @abstractmethod
158 @docval({'name': 'builder', 'type': GroupBuilder, 'doc': 'the GroupBuilder object representing the Container'},
159 allow_extra=True)
160 def write_builder(self, **kwargs):
161 ''' Write a GroupBuilder representing an Container object '''
162 pass
164 @abstractmethod
165 def open(self):
166 ''' Open this HDMFIO object for writing of the builder '''
167 pass
169 @abstractmethod
170 def close(self):
171 ''' Close this HDMFIO object to further reading/writing'''
172 pass
174 def __enter__(self):
175 return self
177 def __exit__(self, type, value, traceback):
178 self.close()
180 def __del__(self):
181 self.close()