Debian Codegraph @

skrf/vi/validators.py

raw symbols SCIP
1 """
2 .. module:: skrf.vi.validators
3 ==============================
4 validators (:mod:`skrf.vi.validators`)
5 ==============================
6
7 .. autosummary::
8 """
9 from __future__ import annotations
10
11 from typing import TYPE_CHECKING
12
13 if TYPE_CHECKING:
14 from collections.abc import Sequence
15 from typing import Any
16
17 import re
18 from abc import ABC, abstractmethod
19 from enum import Enum
20
21
22 class ValidationError(Exception):
23 pass
24
25
26 class Validator(ABC):
27 @abstractmethod
28 def validate_input(self, arg) -> Any:
29 """Try to convert arg to a valid value and return. Used to ensure
30 commands sent to the instrument are the proper format."""
31 pass
32
33 def validate_output(self, arg) -> Any:
34 """Try to convert arg to a valid value and return. Used to convert
35 responses from the instrument to something useful. By default,
36 this just calls validate_input, but can be overwritten in subclasses.
37 (See EnumValidator)"""
38 return self.validate_input(arg)
39
40
41 class IntValidator(Validator):
42 def __init__(self, min: int | None = None, max: int | None = None) -> None:
43 self.min = min
44 self.max = max
45
46 def validate_input(self, arg) -> int:
47 try:
48 arg = int(arg)
49 except ValueError as err:
50 raise ValidationError(f"Could not convert {arg} to an int") from err
51
52 if self.min is not None or self.max is not None:
53 self.check_bounds(arg)
54
55 return arg
56
57 def check_bounds(self, arg):
58 try:
59 if self.min is not None:
60 assert arg >= self.min
61 except AssertionError as err:
62 raise ValidationError(f"{arg} < {self.min}") from err
63
64 try:
65 if self.max is not None:
66 assert arg <= self.max
67 except AssertionError as err:
68 raise ValidationError(f"{arg} > {self.max}") from err
69
70
71 class FloatValidator(Validator):
72 def __init__(
73 self,
74 min: float | None = None,
75 max: float | None = None,
76 decimal_places: int=50
77 ) -> None:
78 self.min = min
79 self.max = max
80 self.dec_places = decimal_places
81
82 def validate_input(self, arg) -> float:
83 try:
84 arg = float(arg)
85 except ValueError as err:
86 raise ValidationError(f"Could not convert {arg} to a float") from err
87
88 if self.min is not None or self.max is not None:
89 self.check_bounds(arg)
90
91 return round(arg, self.dec_places)
92
93 def check_bounds(self, arg):
94 try:
95 if self.min is not None:
96 assert arg >= self.min
97 except AssertionError as err:
98 raise ValidationError(f"{arg} < {self.min}") from err
99
100 try:
101 if self.max is not None:
102 assert arg <= self.max
103 except AssertionError as err:
104 raise ValidationError(f"{arg} > {self.max}") from err
105
106
107 class FreqValidator(Validator):
108 freq_re = re.compile(r"(?P<val>\d+\.?\d*)\s*(?P<si_prefix>[kMG])?(?:[hH][zZ])?")
109 si = {"k": 1e3, "M": 1e6, "G": 1e9}
110
111 def validate_input(self, arg) -> int:
112 if isinstance(arg, str):
113 f = re.fullmatch(self.freq_re, arg)
114 if f is None:
115 raise ValidationError("Invalid frequency string")
116 return int(float(f["val"]) * self.si.get(f["si_prefix"], 1))
117
118 else:
119 try:
120 return int(arg)
121 except ValueError as err:
122 raise ValidationError("Could not convert {arg} to an int") from err
123
124 def validate_output(self, arg) -> int:
125 try:
126 f = float(arg)
127 return int(f)
128 except ValueError as err:
129 raise ValidationError(f"Response from instrument ({arg}) could not be converted to an int") from err
130
131
132 class EnumValidator(Validator):
133 def __init__(self, enum: Enum) -> None:
134 self.Enum = enum
135
136 def validate_input(self, arg) -> Any:
137 if isinstance(arg, Enum):
138 return arg.value
139 else:
140 try:
141 return self.Enum(arg).value
142 except ValueError as err:
143 raise ValidationError(f"{arg} is not a valid {self.Enum.__name__}") from err
144
145 def validate_output(self, arg) -> Any:
146 try:
147 return self.Enum(arg)
148 except ValueError as err:
149 raise ValidationError(f"Got unexpected response {arg}") from err
150
151
152 class SetValidator(Validator):
153 def __init__(self, valid: Sequence) -> None:
154 dtype = type(valid[0])
155 if not all(isinstance(x, dtype) for x in valid):
156 raise ValueError("All elements of set must be of the same type.")
157
158 self.valid = valid
159 self.dtype = dtype
160
161 def validate_input(self, arg) -> Any:
162 arg = self.dtype(arg)
163 if arg in self.valid:
164 return arg
165 else:
166 raise ValidationError(f"{arg} is not in {self.valid}")
167
168
169 class DictValidator(Validator):
170 def __init__(self, arg_string: str, response_pattern: re.Pattern | str) -> None:
171 self.arg_string = arg_string
172 if isinstance(response_pattern, str):
173 self.pattern = re.compile(response_pattern)
174 else:
175 self.pattern = response_pattern
176
177 def validate_input(self, arg) -> str:
178 try:
179 return self.arg_string.format(**arg)
180 except KeyError as e:
181 raise ValidationError(f"Missing expected argument '{e}'") from e
182
183 def validate_output(self, arg) -> dict:
184 match = self.pattern.fullmatch(arg)
185 if match:
186 return match.groupdict()
187 else:
188 raise ValidationError(
189 "Response did not fit regex. "
190 f"Response: {arg} Pattern: {self.pattern.pattern}"
191 )
192
193 class DelimitedStrValidator(Validator):
194 def __init__(self, dtype: type =str , sep: str = ',') -> None:
195 self.dtype = dtype
196 self.sep = sep
197
198 def validate_input(self, arg: Sequence) -> str:
199 if not all(isinstance(x, self.dtype) for x in arg):
200 raise ValidationError("All elements must be of type {self.dtype}.")
201
202 return self.sep.join(str(x) for x in arg)
203
204 def validate_output(self, arg: str) -> list:
205 arg = arg.replace('"', '')
206 return [self.dtype(val) for val in arg.split(self.sep)]
207
208 class BooleanValidator(Validator):
209 truthy = ['1', 'on', 'true']
210 falsey = ['0', 'off', 'false']
211
212 def __init__(
213 self,
214 true_response: str | None = None,
215 false_response: str | None = None,
216 true_setting: str='1',
217 false_setting: str='0'
218 ):
219 if true_response:
220 self.truthy.append(true_response.lower())
221 if false_response:
222 self.falsey.append(false_response.lower())
223
224 self.true_val = true_setting
225 self.false_val = false_setting
226
227 def validate_input(self, arg) -> str:
228 if str(arg).lower() in self.truthy:
229 return self.true_val
230 elif str(arg).lower() in self.falsey:
231 return self.false_val
232 else:
233 raise ValidationError('Argument must be a truthy or falsey value')
234
235 def validate_output(self, arg) -> bool:
236 return str(arg).lower() in self.truthy