Coverage for python/lsst/daf/butler/script/queryDataIds.py: 18%

54 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2022-11-19 01:58 -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 program is free software: you can redistribute it and/or modify 

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

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

12# (at your option) any later version. 

13# 

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

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

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

17# GNU General Public License for more details. 

18# 

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

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

21from __future__ import annotations 

22 

23import logging 

24from collections.abc import Iterable 

25from typing import TYPE_CHECKING 

26 

27import numpy as np 

28from astropy.table import Table as AstropyTable 

29 

30from .._butler import Butler, DataCoordinate 

31from ..cli.utils import sortAstropyTable 

32 

33if TYPE_CHECKING: 33 ↛ 34line 33 didn't jump to line 34, because the condition on line 33 was never true

34 from lsst.daf.butler import DimensionGraph 

35 

36_LOG = logging.getLogger(__name__) 

37 

38 

39class _Table: 

40 """Aggregates DataIds and creates an astropy table with one DataId per 

41 row. Eliminates duplicate rows. 

42 

43 Parameters 

44 ---------- 

45 dataIds : `iterable` [ ``DataId`` ] 

46 The DataIds to add to the table. 

47 """ 

48 

49 def __init__(self, dataIds: Iterable[DataCoordinate]): 

50 # use dict to store dataIds as keys to preserve ordering 

51 self.dataIds = dict.fromkeys(dataIds) 

52 

53 def getAstropyTable(self, order: bool) -> AstropyTable: 

54 """Get the table as an astropy table. 

55 

56 Parameters 

57 ---------- 

58 order : `bool` 

59 If True then order rows based on DataIds. 

60 

61 Returns 

62 ------- 

63 table : `astropy.table.Table` 

64 The dataIds, sorted by spatial and temporal columns first, and then 

65 the rest of the columns, with duplicate dataIds removed. 

66 """ 

67 # Should never happen; adding a dataset should be the action that 

68 # causes a _Table to be created. 

69 if not self.dataIds: 

70 raise RuntimeError("No DataIds were provided.") 

71 

72 dataId = next(iter(self.dataIds)) 

73 dimensions = list(dataId.full.keys()) 

74 columnNames = [str(item) for item in dimensions] 

75 

76 # Need to hint the column types for numbers since the per-row 

77 # constructor of Table does not work this out on its own and sorting 

78 # will not work properly without. 

79 typeMap = {float: np.float64, int: np.int64} 

80 columnTypes = [typeMap.get(type(value)) for value in dataId.full.values()] 

81 

82 rows = [[value for value in dataId.full.values()] for dataId in self.dataIds] 

83 

84 table = AstropyTable(np.array(rows), names=columnNames, dtype=columnTypes) 

85 if order: 

86 table = sortAstropyTable(table, dimensions) 

87 return table 

88 

89 

90def queryDataIds( 

91 repo: str, 

92 dimensions: Iterable[str], 

93 datasets: tuple[str, ...], 

94 where: str | None, 

95 collections: Iterable[str], 

96 order_by: tuple[str, ...], 

97 limit: int, 

98 offset: int, 

99) -> tuple[AstropyTable | None, str | None]: 

100 # Docstring for supported parameters is the same as Registry.queryDataIds 

101 

102 butler = Butler(repo) 

103 

104 if datasets and collections and not dimensions: 

105 # Determine the dimensions relevant to all given dataset types. 

106 # Since we are going to AND together all dimensions, we can not 

107 # seed the result with an empty set. 

108 graph: DimensionGraph | None = None 

109 dataset_types = list(butler.registry.queryDatasetTypes(datasets)) 

110 for dataset_type in dataset_types: 

111 if graph is None: 

112 # Seed with dimensions of first dataset type. 

113 graph = dataset_type.dimensions 

114 else: 

115 # Only retain dimensions that are in the current 

116 # set AND the set from this dataset type. 

117 graph = graph.intersection(dataset_type.dimensions) 

118 _LOG.debug("Dimensions now %s from %s", set(graph.names), dataset_type.name) 

119 

120 # Break out of the loop early. No additional dimensions 

121 # can be added to an empty set when using AND. 

122 if not graph: 

123 break 

124 

125 if not graph: 

126 names = [d.name for d in dataset_types] 

127 return None, f"No dimensions in common for specified dataset types ({names})" 

128 dimensions = set(graph.names) 

129 _LOG.info("Determined dimensions %s from datasets option %s", dimensions, datasets) 

130 

131 results = butler.registry.queryDataIds( 

132 dimensions, datasets=datasets, where=where, collections=collections 

133 ) 

134 

135 if order_by: 

136 results = results.order_by(*order_by) 

137 if limit > 0: 

138 new_offset = offset if offset > 0 else None 

139 results = results.limit(limit, new_offset) 

140 

141 if results.count() > 0 and len(results.graph) > 0: 

142 table = _Table(results) 

143 return table.getAstropyTable(not order_by), None 

144 else: 

145 return None, "\n".join(results.explain_no_results())