Coverage for python/lsst/pipe/base/tests/mocks/_data_id_match.py: 35%
59 statements
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-23 10:54 +0000
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-23 10:54 +0000
1# This file is part of pipe_base.
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/>.
28from __future__ import annotations
30__all__ = ["DataIdMatch"]
32import operator
33from collections.abc import Callable
34from typing import Any
36import astropy.time
37from lsst.daf.butler import DataId
38from lsst.daf.butler.registry.queries.expressions.parser import Node, ParserYacc, TreeVisitor # type: ignore
41class _DataIdMatchTreeVisitor(TreeVisitor):
42 """Expression tree visitor which evaluates expression using values from
43 `~lsst.daf.butler.DataId`.
44 """
46 def __init__(self, dataId: DataId):
47 self.dataId = dataId
49 def visitNumericLiteral(self, value: str, node: Node) -> Any:
50 # docstring is inherited from base class
51 try:
52 return int(value)
53 except ValueError:
54 return float(value)
56 def visitStringLiteral(self, value: str, node: Node) -> Any:
57 # docstring is inherited from base class
58 return value
60 def visitTimeLiteral(self, value: astropy.time.Time, node: Node) -> Any:
61 # docstring is inherited from base class
62 return value
64 def visitRangeLiteral(self, start: int, stop: int, stride: int | None, node: Node) -> Any:
65 # docstring is inherited from base class
66 if stride is None:
67 return range(start, stop + 1)
68 else:
69 return range(start, stop + 1, stride)
71 def visitIdentifier(self, name: str, node: Node) -> Any:
72 # docstring is inherited from base class
73 return self.dataId[name]
75 def visitUnaryOp(self, operator_name: str, operand: Any, node: Node) -> Any:
76 # docstring is inherited from base class
77 operators: dict[str, Callable[[Any], Any]] = {
78 "NOT": operator.not_,
79 "+": operator.pos,
80 "-": operator.neg,
81 }
82 return operators[operator_name](operand)
84 def visitBinaryOp(self, operator_name: str, lhs: Any, rhs: Any, node: Node) -> Any:
85 # docstring is inherited from base class
86 operators = {
87 "OR": operator.or_,
88 "AND": operator.and_,
89 "+": operator.add,
90 "-": operator.sub,
91 "*": operator.mul,
92 "/": operator.truediv,
93 "%": operator.mod,
94 "=": operator.eq,
95 "!=": operator.ne,
96 "<": operator.lt,
97 ">": operator.gt,
98 "<=": operator.le,
99 ">=": operator.ge,
100 }
101 return operators[operator_name](lhs, rhs)
103 def visitIsIn(self, lhs: Any, values: list[Any], not_in: bool, node: Node) -> Any:
104 # docstring is inherited from base class
105 is_in = True
106 for value in values:
107 if not isinstance(value, range):
108 value = [value]
109 if lhs in value:
110 break
111 else:
112 is_in = False
113 if not_in:
114 is_in = not is_in
115 return is_in
117 def visitParens(self, expression: Any, node: Node) -> Any:
118 # docstring is inherited from base class
119 return expression
121 def visitTupleNode(self, items: tuple[Any, ...], node: Node) -> Any:
122 # docstring is inherited from base class
123 raise NotImplementedError()
125 def visitFunctionCall(self, name: str, args: list[Any], node: Node) -> Any:
126 # docstring is inherited from base class
127 raise NotImplementedError()
129 def visitPointNode(self, ra: Any, dec: Any, node: Node) -> Any:
130 # docstring is inherited from base class
131 raise NotImplementedError()
134class DataIdMatch:
135 """Class that can match DataId against the user-defined string expression.
137 Parameters
138 ----------
139 expression : `str`
140 User-defined expression, supports syntax defined by daf_butler
141 expression parser. Maps identifiers in the expression to the values of
142 DataId.
143 """
145 def __init__(self, expression: str):
146 parser = ParserYacc()
147 self.expression = expression
148 self.tree = parser.parse(expression)
150 def match(self, dataId: DataId) -> bool:
151 """Match DataId contents against the expression.
153 Parameters
154 ----------
155 dataId : `~lsst.daf.butler.DataId`
156 DataId that is matched against an expression.
158 Returns
159 -------
160 match : `bool`
161 Result of expression evaluation.
163 Raises
164 ------
165 KeyError
166 Raised when identifier in expression is not defined for given
167 `~lsst.daf.butler.DataId`.
168 TypeError
169 Raised when expression evaluates to a non-boolean type or when
170 operation in expression cannot be performed on operand types.
171 NotImplementedError
172 Raised when expression includes valid but unsupported syntax, e.g.
173 function call.
174 """
175 visitor = _DataIdMatchTreeVisitor(dataId)
176 result = self.tree.visit(visitor)
177 if not isinstance(result, bool):
178 raise TypeError(f"Expression '{self.expression}' returned non-boolean object {type(result)}")
179 return result