Debian Codegraph @

pymeasure/instruments/fakes.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 import re
26 import time
27 import numpy as np
28
29 from pymeasure.adapters import FakeAdapter
30 from pymeasure.instruments import Instrument
31 from pymeasure.instruments.validators import strict_discrete_set
32
33
34 class FakeInstrument(Instrument):
35 """ Provides a fake implementation of the Instrument class
36 for testing purposes.
37 """
38
39 def __init__(self, adapter=None, name="Fake Instrument", includeSCPI=False, **kwargs):
40 super().__init__(
41 FakeAdapter(**kwargs),
42 name,
43 includeSCPI=includeSCPI,
44 **kwargs
45 )
46
47 @staticmethod
48 def control(get_command, set_command, docs,
49 validator=lambda v, vs: v, values=(), map_values=False,
50 get_process=lambda v: v, set_process=lambda v: v,
51 check_set_errors=False, check_get_errors=False,
52 **kwargs):
53 """Fake Instrument.control.
54
55 Strip commands and only store and return values indicated by
56 format strings to mimic many simple commands.
57 This is analogous how the tests in test_instrument are handled.
58 """
59
60 # Regex search to find first format specifier in the command
61 fmt_spec_pattern = r'(%[\w.#-+ *]*[diouxXeEfFgGcrsa%])'
62 match = re.findall(fmt_spec_pattern, set_command)
63 if match:
64 # format_specifier = match.group(0)
65 format_specifier = ','.join(match)
66 else:
67 format_specifier = ''
68 # To preserve as much functionality as possible, call the real
69 # control method with modified get_command and set_command.
70 return Instrument.control(get_command="",
71 set_command=format_specifier,
72 docs=docs,
73 validator=validator,
74 values=values,
75 map_values=map_values,
76 get_process=get_process,
77 set_process=set_process,
78 check_set_errors=check_set_errors,
79 check_get_errors=check_get_errors,
80 **kwargs)
81
82
83 class SwissArmyFake(FakeInstrument):
84 """Dummy instrument class useful for testing.
85
86 Like a Swiss Army knife, this class provides multi-tool functionality in the form of streams
87 of multiple types of fake data. Data streams that can currently be generated by this class
88 include 'voltages', sinusoidal 'waveforms', and mono channel 'image data'.
89 """
90
91 def __init__(self, name="Mock instrument", wait=.1, **kwargs):
92 super().__init__(
93 name=name,
94 includeSCPI=False,
95 **kwargs
96 )
97 self._wait = wait
98 self._tstart = 0
99 self._voltage = 10
100 self._output_voltage = 0
101 self._time = 0
102 self._wave = self.wave
103 self._units = {'voltage': 'V',
104 'output_voltage': 'V',
105 'time': 's',
106 'wave': 'a.u.'}
107 # mock image attributes
108 self._w = 1920
109 self._h = 1080
110 self._frame_format = "mono_8"
111
112 @property
113 def time(self):
114 """Control the elapsed time."""
115 if self._tstart == 0:
116 self._tstart = time.time()
117 self._time = time.time() - self._tstart
118 return self._time
119
120 @time.setter
121 def time(self, value):
122 if value == 0:
123 self._tstart = 0
124 else:
125 while self.time < value:
126 time.sleep(0.001)
127
128 @property
129 def wave(self):
130 """Measure a waveform."""
131 return float(np.sin(self.time))
132
133 @property
134 def voltage(self):
135 """Measure the voltage."""
136 time.sleep(self._wait)
137 return self._voltage
138
139 @property
140 def output_voltage(self):
141 """Control the voltage."""
142 return self._output_voltage
143
144 @output_voltage.setter
145 def output_voltage(self, value):
146 time.sleep(self._wait)
147 self._output_voltage = value
148
149 @property
150 def frame_width(self):
151 """Control frame width in pixels."""
152 time.sleep(self._wait)
153 return self._w
154
155 @frame_width.setter
156 def frame_width(self, w):
157 time.sleep(self._wait)
158 self._w = w
159
160 @property
161 def frame_height(self):
162 """Control frame height in pixels."""
163 time.sleep(self._wait)
164 return self._h
165
166 @frame_height.setter
167 def frame_height(self, h):
168 time.sleep(self._wait)
169 self._h = h
170
171 @property
172 def frame_format(self):
173 """Control the format for image data returned from the get_frame() method.
174 Allowed values are:
175 mono_8: single channel 8-bit image.
176 mono_16: single channel 16-bit image.
177 """
178 time.sleep(self._wait)
179 return self._frame_format
180
181 @frame_format.setter
182 def frame_format(self, form):
183 allowed_formats = ["mono_8", "mono_16"]
184 strict_discrete_set(form, allowed_formats)
185 self._frame_format = form
186
187 @property
188 def frame(self):
189 """Get a new image frame."""
190 im_format_maxval_dict = {"8": 255, "16": 65535}
191 im_format_type_dict = {"8": np.uint8, "16": np.uint16}
192 bit_depth = self.frame_format.split("_")[1]
193 time.sleep(self._wait)
194 return np.array(
195 im_format_maxval_dict[bit_depth] * np.random.rand(self.frame_height, self.frame_width),
196 dtype=im_format_type_dict[bit_depth]
197 )