Coverage for python/lsst/daf/butler/script/ingest_files.py: 24%

54 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2025-11-06 01:33 -0800

1# This file is part of daf_butler. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (http://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# This software is dual licensed under the GNU General Public License and also 

10# under a 3-clause BSD license. Recipients may choose which of these licenses 

11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt, 

12# respectively. If you choose the GPL option then the following text applies 

13# (but note that there is still no warranty even if you opt for BSD instead): 

14# 

15# This program is free software: you can redistribute it and/or modify 

16# it under the terms of the GNU General Public License as published by 

17# the Free Software Foundation, either version 3 of the License, or 

18# (at your option) any later version. 

19# 

20# This program is distributed in the hope that it will be useful, 

21# but WITHOUT ANY WARRANTY; without even the implied warranty of 

22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

23# GNU General Public License for more details. 

24# 

25# You should have received a copy of the GNU General Public License 

26# along with this program. If not, see <http://www.gnu.org/licenses/>. 

27from __future__ import annotations 

28 

29__all__ = ("ingest_files",) 

30 

31import logging 

32from collections import defaultdict 

33from typing import TYPE_CHECKING, Any 

34 

35from astropy.table import Table 

36 

37from lsst.resources import ResourcePath 

38from lsst.utils import doImport 

39 

40from .._butler import Butler 

41from .._dataset_ref import DatasetIdGenEnum, DatasetRef 

42from .._file_dataset import FileDataset 

43 

44if TYPE_CHECKING: 

45 from .._dataset_type import DatasetType 

46 from ..dimensions import DimensionUniverse 

47 

48log = logging.getLogger(__name__) 

49 

50 

51def ingest_files( 

52 repo: str, 

53 dataset_type: str, 

54 run: str, 

55 table_file: str, 

56 data_id: tuple[str, ...] = (), 

57 formatter: str | None = None, 

58 id_generation_mode: str = "UNIQUE", 

59 prefix: str | None = None, 

60 transfer: str = "auto", 

61 track_file_attrs: bool = True, 

62) -> None: 

63 """Ingest files from a table. 

64 

65 Parameters 

66 ---------- 

67 repo : `str` 

68 URI string of the Butler repo to use. 

69 dataset_type : `str` 

70 The name of the dataset type for the files to be ingested. This 

71 dataset type must exist. 

72 run : `str` 

73 The run in which the files should be ingested. 

74 table_file : `str` 

75 Path to a table file to read. This file can be in any format that 

76 can be read by Astropy so long as Astropy can determine the format 

77 itself. 

78 data_id : `tuple` of `str` 

79 Tuple of strings of the form ``keyword=value`` that can be used 

80 to define dataId elements that are fixed for all ingested files 

81 found in the table file. This allows those columns to be missing 

82 from the table file. Dimensions given here override table columns. 

83 formatter : `str`, optional 

84 Fully-qualified python class name for the `Formatter` to use 

85 to read the ingested files. If `None` the formatter is read from 

86 datastore configuration based on the dataset type. 

87 id_generation_mode : `str`, optional 

88 Mode to use for generating IDs. Should map to `DatasetGenIdEnum`. 

89 prefix : `str`, optional 

90 Prefix to use when resolving relative paths in table files. The default 

91 is to use the current working directory. 

92 transfer : `str`, optional 

93 Transfer mode to use for ingest. 

94 track_file_attrs : `bool`, optional 

95 Control whether file attributes such as the size or checksum should 

96 be tracked by the datastore. Whether this parameter is honored 

97 depends on the specific datastore implementation. 

98 """ 

99 # Check that the formatter can be imported -- validate this as soon 

100 # as possible before we read a potentially large table file. 

101 if formatter: 

102 doImport(formatter) 

103 else: 

104 formatter = None 

105 

106 # Force empty string prefix (from click) to None for API compatibility. 

107 if not prefix: 

108 prefix = None 

109 

110 # Convert the dataset ID gen mode string to enum. 

111 id_gen_mode = DatasetIdGenEnum.__members__[id_generation_mode] 

112 

113 # Create the butler with the relevant run attached. 

114 butler = Butler.from_config(repo, run=run) 

115 

116 datasetType = butler.get_dataset_type(dataset_type) 

117 

118 # Convert the k=v strings into a dataId dict. 

119 universe = butler.dimensions 

120 common_data_id = parse_data_id_tuple(data_id, universe) 

121 

122 # Read the table assuming that Astropy can work out the format. 

123 uri = ResourcePath(table_file, forceAbsolute=False) 

124 with uri.as_local() as local_file: 

125 table = Table.read(local_file.ospath) 

126 

127 datasets = extract_datasets_from_table( 

128 table, common_data_id, datasetType, run, formatter, prefix, id_gen_mode 

129 ) 

130 

131 butler.ingest(*datasets, transfer=transfer, record_validation_info=track_file_attrs) 

132 

133 

134def extract_datasets_from_table( 

135 table: Table, 

136 common_data_id: dict, 

137 datasetType: DatasetType, 

138 run: str, 

139 formatter: str | None = None, 

140 prefix: str | None = None, 

141 id_generation_mode: DatasetIdGenEnum = DatasetIdGenEnum.UNIQUE, 

142) -> list[FileDataset]: 

143 """Extract datasets from the supplied table. 

144 

145 Parameters 

146 ---------- 

147 table : `astropy.table.Table` 

148 Table containing the datasets. The first column is assumed to be 

149 the file URI and the remaining columns are dimensions. 

150 common_data_id : `dict` 

151 Data ID values that are common to every row in the table. These 

152 take priority if a dimension in this dataId is also present as 

153 a column in the table. 

154 datasetType : `DatasetType` 

155 The dataset type to be associated with the ingested data. 

156 run : `str` 

157 The name of the run that will be receiving these datasets. 

158 formatter : `str`, optional 

159 Fully-qualified python class name for the `Formatter` to use 

160 to read the ingested files. If `None` the formatter is read from 

161 datastore configuration based on the dataset type. 

162 prefix : `str`, optional 

163 Prefix to be used for relative paths. Can be `None` for current 

164 working directory. 

165 id_generation_mode : `DatasetIdGenEnum`, optional 

166 The mode to use when creating the dataset IDs. 

167 

168 Returns 

169 ------- 

170 datasets : `list` of `FileDataset` 

171 The `FileDataset` objects corresponding to the rows in the table. 

172 The number of elements in this list can be smaller than the number 

173 of rows in the file because one file can appear in multiple rows 

174 with different dataIds. 

175 """ 

176 # The file is the first column and everything else is assumed to 

177 # be dimensions so we need to know the name of that column. 

178 file_column = table.colnames[0] 

179 

180 # Handle multiple dataIds per file by grouping by file. 

181 refs_by_file = defaultdict(list) 

182 n_dataset_refs = 0 

183 for row in table: 

184 # Convert the row to a dataId, remembering to extract the 

185 # path column. 

186 dataId = dict(row) 

187 path = dataId.pop(file_column) 

188 

189 # The command line can override a column. 

190 dataId.update(common_data_id) 

191 

192 # Create the dataset ref that is to be ingested. 

193 ref = DatasetRef(datasetType, dataId, run=run, id_generation_mode=id_generation_mode) # type: ignore 

194 

195 # Convert path to absolute (because otherwise system will 

196 # assume relative to datastore root and that is almost certainly 

197 # never the right default here). 

198 path_uri = ResourcePath(path, root=prefix, forceAbsolute=True) 

199 

200 refs_by_file[path_uri].append(ref) 

201 n_dataset_refs += 1 

202 

203 datasets = [ 

204 FileDataset( 

205 path=file_uri, 

206 refs=refs, 

207 formatter=formatter, 

208 ) 

209 for file_uri, refs in refs_by_file.items() 

210 ] 

211 

212 log.info("Ingesting %d dataset ref(s) from %d file(s)", n_dataset_refs, len(datasets)) 

213 

214 return datasets 

215 

216 

217def parse_data_id_tuple(data_ids: tuple[str, ...], universe: DimensionUniverse) -> dict[str, Any]: 

218 """Convert any additional k=v strings in the dataId tuple to dict 

219 form. 

220 

221 Parameters 

222 ---------- 

223 data_ids : `tuple` of `str` 

224 Strings of keyword=value pairs defining a data ID. 

225 universe : `DimensionUniverse` 

226 The relevant universe. 

227 

228 Returns 

229 ------- 

230 data_id : `dict` 

231 Data ID transformed from string into dictionary. 

232 """ 

233 data_id: dict[str, Any] = {} 

234 for id_str in data_ids: 

235 dimension_str, value = id_str.split("=") 

236 

237 try: 

238 dimension = universe.dimensions[dimension_str] 

239 except KeyError: 

240 raise ValueError(f"DataID dimension '{dimension_str}' is not known to this universe.") from None 

241 

242 # Cast the value to the right python type (since they will be 

243 # strings at this point). 

244 value = dimension.primaryKey.getPythonType()(value) 

245 

246 data_id[dimension_str] = value 

247 return data_id