Debian Codegraph @

pymeasure/instruments/validators.py

raw
1 #
2 # This file is part of the PyMeasure package.
3 #
4 # Copyright (c) 2013-2024 PyMeasure Developers
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 # of this software and associated documentation files (the "Software"), to deal
8 # in the Software without restriction, including without limitation the rights
9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the Software is
11 # furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 # THE SOFTWARE.
23 #
24
25 from decimal import Decimal
26
27
28 def strict_range(value, values):
29 """ Provides a validator function that returns the value
30 if its value is less than or equal to the maximum and
31 greater than or equal to the minimum of ``values``.
32 Otherwise it raises a ValueError.
33
34 :param value: A value to test
35 :param values: A range of values (range, list, etc.)
36 :raises: ValueError if the value is out of the range
37 """
38 if min(values) <= value <= max(values):
39 return value
40 else:
41 raise ValueError('Value of {:g} is not in range [{:g},{:g}]'.format(
42 value, min(values), max(values)
43 ))
44
45
46 def strict_discrete_range(value, values, step):
47 """ Provides a validator function that returns the value
48 if its value is less than the maximum and greater than the
49 minimum of the range and is a multiple of step.
50 Otherwise it raises a ValueError.
51
52 :param value: A value to test
53 :param values: A range of values (range, list, etc.)
54 :param step: Minimum stepsize (resolution limit)
55 :raises: ValueError if the value is out of the range
56 """
57 # use Decimal type to provide correct decimal compatible floating
58 # point arithmetic compared to binary floating point arithmetic
59 if (strict_range(value, values) == value and
60 Decimal(str(value)) % Decimal(str(step)) == 0):
61 return value
62 else:
63 raise ValueError('Value of {:g} is not a multiple of {:g}'.format(
64 value, step
65 ))
66
67
68 def strict_discrete_set(value, values):
69 """ Provides a validator function that returns the value
70 if it is in the discrete set. Otherwise it raises a ValueError.
71
72 :param value: A value to test
73 :param values: A set of values that are valid
74 :raises: ValueError if the value is not in the set
75 """
76 if value in values:
77 return value
78 else:
79 raise ValueError('Value of {} is not in the discrete set {}'.format(
80 value, values
81 ))
82
83
84 def truncated_range(value, values):
85 """ Provides a validator function that returns the value
86 if it is in the range. Otherwise it returns the closest
87 range bound.
88
89 :param value: A value to test
90 :param values: A set of values that are valid
91 """
92 if min(values) <= value <= max(values):
93 return value
94 elif value > max(values):
95 return max(values)
96 else:
97 return min(values)
98
99
100 def modular_range(value, values):
101 """ Provides a validator function that returns the value
102 if it is in the range. Otherwise it returns the value,
103 modulo the max of the range.
104
105 :param value: a value to test
106 :param values: A set of values that are valid
107 """
108 return value % max(values)
109
110
111 def modular_range_bidirectional(value, values):
112 """ Provides a validator function that returns the value
113 if it is in the range. Otherwise it returns the value,
114 modulo the max of the range. Allows negative values.
115
116 :param value: a value to test
117 :param values: A set of values that are valid
118 """
119 if value > 0:
120 return value % max(values)
121 else:
122 return -1 * (abs(value) % max(values))
123
124
125 def truncated_discrete_set(value, values):
126 """ Provides a validator function that returns the value
127 if it is in the discrete set. Otherwise, it returns the smallest
128 value that is larger than the value.
129
130 :param value: A value to test
131 :param values: A set of values that are valid
132 """
133 # Force the values to be sorted
134 values = list(values)
135 values.sort()
136 for v in values:
137 if value <= v:
138 return v
139
140 return values[-1]
141
142
143 def joined_validators(*validators):
144 """Returns a validator function that represents a list of validators joined together.
145
146 A value passed to the validator is returned if it passes any validator (not all of them).
147 Otherwise it raises a ValueError.
148
149 Note: the joined validator expects ``values`` to be a sequence of ``values``
150 appropriate for the respective validators (often sequences themselves).
151
152 :Example:
153
154 >>> from pymeasure.instruments.validators import strict_discrete_set, strict_range
155 >>> from pymeasure.instruments.validators import joined_validators
156 >>> joined_v = joined_validators(strict_discrete_set, strict_range)
157 >>> values = [['MAX','MIN'], range(10)]
158 >>> joined_v(5, values)
159 5
160 >>> joined_v('MAX', values)
161 'MAX'
162 >>> joined_v('NONSENSE', values)
163 Traceback (most recent call last):
164 ...
165 ValueError: Value of NONSENSE does not match any of the joined validators
166
167 :param validators: an iterable of other validators
168 """
169
170 def validate(value, values):
171 for validator, vals in zip(validators, values):
172 try:
173 return validator(value, vals)
174 except (ValueError, TypeError):
175 pass
176 raise ValueError(f"Value of {value} does not match any of the joined validators")
177
178 return validate
179
180
181 def discreteTruncate(number, discreteSet):
182 """ Truncates the number to the closest element in the positive discrete set.
183 Returns False if the number is larger than the maximum value or negative.
184 """
185 if number < 0:
186 return False
187 discreteSet.sort()
188 for item in discreteSet:
189 if number <= item:
190 return item
191 return False