Debian Codegraph @

skrf/vi/vna/vna.py

raw symbols SCIP
1 """
2 .. module:: skrf.vi.vna.vna
3 =================================================
4 vna (:mod:`skrf.vi.vna.vna`)
5 =================================================
6
7 Provides the VNA base class
8 """
9
10 from __future__ import annotations
11
12 from typing import TYPE_CHECKING
13
14 if TYPE_CHECKING:
15 pass
16
17 import functools
18 import inspect
19 import re
20 from enum import Enum, auto
21
22 import numpy as np
23 import pyvisa
24
25 from ..scpi_errors import SCPIError
26 from ..validators import Validator
27
28
29 def _format_cmd(cmd: str, **kwargs) -> str:
30 def sub(match_obj):
31 prefix = match_obj.group("prefix")
32 attr = match_obj.group("attr")
33
34 if prefix:
35 obj = kwargs[prefix]
36 return str(getattr(obj, attr))
37 else:
38 return str(kwargs[attr])
39
40 param_re = re.compile(r"\<(?:(?P<prefix>\w+):)?(?P<attr>\w+)\>")
41 return re.sub(param_re, sub, cmd)
42
43
44 class ValuesFormat(Enum):
45 """How values are written to and queried from the instrument"""
46
47 #: 32 bits per value
48 BINARY_32 = auto()
49 #: 64 bits per value
50 BINARY_64 = auto()
51 #: Transferred as ASCII (e.g. representing numbers as strings)
52 ASCII = auto()
53
54
55 class Channel:
56 """
57 A single channel of the instrument.
58
59 This is only for those instruments which support channels, and should be
60 subclassed in those instrument classes.
61
62 .. warning::
63 This class should not be instantiated directly
64 """
65
66 def __init__(self, parent, cnum: int | None = None, cname: str | None = None) -> None:
67 self.parent = parent
68 self.cnum = cnum
69 self.name = cname
70
71 self.read = self.parent.read
72 self.read_values = self.parent.read_values
73 self.write = self.parent.write
74 self.write_values = self.parent.write_values
75 self.query = self.parent.query
76 self.query_values = self.parent.query_values
77
78
79 class VNA:
80 _scpi = True # Set to false in subclasses that don't use SCPI
81
82 def __init__(self, address: str, backend: str = "@py", timeout: int | None = None) -> None:
83 rm = pyvisa.ResourceManager(backend)
84 self._resource = rm.open_resource(address, timeout=timeout)
85
86 # Reading and setting the query values format is instrument specific
87 # and must be done for each subclass. We default to using ASCII
88 self._values_fmt: ValuesFormat = ValuesFormat.ASCII
89
90 if self._scpi:
91 self._setup_scpi()
92
93 self.echo = False
94
95 def __init_subclass__(cls):
96 if "Channel" in [c[0] for c in inspect.getmembers(cls, inspect.isclass)]:
97 cls._add_channel_support()
98
99 @classmethod
100 def _add_channel_support(cls):
101 def create_channel(self, cnum: int, cname: str) -> None:
102 ch_id = f"ch{cnum}"
103 if hasattr(self, ch_id):
104 raise RuntimeError(f"Channel {cnum} already exists")
105
106 new_channel = self.Channel(self, cnum, cname)
107 setattr(self, ch_id, new_channel)
108
109 def delete_channel(self, cnum: str) -> None:
110 ch_id = f"ch{cnum}"
111 if not hasattr(self, ch_id):
112 return
113 ch = getattr(self, ch_id)
114 if hasattr(ch, "_on_delete"):
115 ch._on_delete()
116 delattr(self, ch_id)
117
118 def _channels(self) -> list[Channel]:
119 return [getattr(self, ch) for ch in dir(self) if re.fullmatch(r"ch\d+", ch)]
120
121 def __getattr__(self, k):
122 if not hasattr(self.Channel, k):
123 raise AttributeError(f"{type(self).__name__} has no attribute {k}")
124 return getattr(self.active_channel, k)
125
126 cls.create_channel = create_channel
127 cls.delete_channel = delete_channel
128 cls.channels = property(_channels)
129 cls.__getattr__ = __getattr__
130
131 def _setup_scpi(self) -> None:
132 self.__class__.wait_for_complete = lambda self: self.query("*OPC?")
133 self.__class__.status = property(lambda self: self.query("*STB?"))
134 self.__class__.options = property(lambda self: self.query("*OPT?"))
135 self.__class__.id = property(lambda self: self.query("*IDN?"))
136 self.__class__.clear_errors = lambda self: self.write("*CLS")
137
138 def errcheck(self) -> None:
139 err = self.query("SYST:ERR?")
140 errno = int(err.split(",")[0])
141 if errno == 0:
142 return
143 else:
144 raise SCPIError(errno)
145
146 self.__class__.check_errors = errcheck
147
148 @staticmethod
149 def command(
150 get_cmd: str | None = None,
151 set_cmd: str | None = None,
152 doc: str | None = None,
153 validator: Validator | None = None,
154 values: bool = False,
155 values_container: type | None = np.array,
156 complex_values: bool = False,
157 ) -> property:
158 """
159 Create a property for the instrument.
160
161 This method is used to add a property to an instrument. These properties
162 can be read-only, write-only, read-write, and can validate values before
163 sending to the instrument as well as validate responses from the
164 instrument to return proper types.
165
166 Parameters
167 ----------
168 get_cmd
169 Command sent to the instrument to request data
170 set_cmd
171 Command sent to the instrument to set data
172 doc
173 The docstring for the property
174 validator
175 The :class:`Validator` that will be used to transform data to the
176 proper format before sending and after querying
177 values
178 Whether or not this command is using a `Sequence` to set data, or
179 expects a `Sequence` in response.
180 values_container:
181 If values is true, you set set this to the type of container the
182 values should be returned in. For example, this is np.array by
183 default, meaning instead of return a `list`, you will get a numpy
184 array.
185 complex_values:
186 If the values expected from the instrument are complex. If so, the
187 values will be converted from [real[0], imag[0], real[1], imag[1], ...]
188 to [complex(real[0], imag[0]), complex(real[1], imag[1]), ...]
189
190 Returns
191 -------
192 property
193 The property constructed from the parameters passed. Should be set
194 to a class variable
195 """
196
197 def fget(self, get_cmd=get_cmd, validator=validator):
198 if get_cmd is None:
199 raise LookupError("Property cannot be read")
200
201 cmd = _format_cmd(get_cmd, self=self)
202 if values:
203 arg = self.query_values(cmd, container=values_container, complex_values=complex_values)
204 else:
205 arg = self.query(cmd)
206
207 if hasattr(self, "wait_for_complete"):
208 self.wait_for_complete()
209
210 if validator:
211 return validator.validate_output(arg)
212 else:
213 return arg
214
215 def fset(self, arg, set_cmd=set_cmd, validator=validator):
216 if set_cmd is None:
217 raise LookupError("Property cannot be set")
218
219 if validator:
220 arg = validator.validate_input(arg)
221
222 cmd = _format_cmd(set_cmd, self=self, arg=arg)
223 self.write(cmd)
224
225 if hasattr(self, "wait_for_complete"):
226 self.wait_for_complete()
227
228 fget.__doc__ = doc
229 # TODO: Potentially add the validator docstring to add the verbosity to
230 # the generated docs, but keep the code less verbose?
231
232 return property(fget=fget, fset=fset)
233
234 @property
235 def timeout(self) -> int | None:
236 return self._resource.timeout
237
238 @timeout.setter
239 def timeout(self, timeout: int | None) -> None:
240 self._resource.timeout = timeout
241
242 def read(self, **kwargs) -> None:
243 if isinstance(self._resource, pyvisa.resources.MessageBasedResource):
244 fn = self._resource.read
245 elif isinstance(self._resource, pyvisa.resources.RegisterBasedResource):
246 raise NotImplementedError()
247 else:
248 raise RuntimeError("unreachable")
249
250 return fn(**kwargs)
251
252 def read_values(self, **kwargs) -> None: # noqa: B027
253 pass
254
255 def write(self, cmd, **kwargs) -> None:
256 if self.echo:
257 print(cmd)
258
259 if isinstance(self._resource, pyvisa.resources.MessageBasedResource):
260 fn = self._resource.write
261 elif isinstance(self._resource, pyvisa.resources.RegisterBasedResource):
262 raise NotImplementedError()
263 else:
264 raise RuntimeError("unreachable")
265
266 fn(cmd, **kwargs)
267
268 def write_values(self, cmd, values, complex_values: bool = False, **kwargs) -> None:
269 if self.echo:
270 print(cmd)
271
272 if complex_values:
273 values = np.array([(x.real, x.imag) for x in values]).flatten()
274
275 if isinstance(self._resource, pyvisa.resources.MessageBasedResource):
276 if self._values_fmt == ValuesFormat.ASCII:
277 fn = self._resource.write_ascii_values
278 elif self._values_fmt == ValuesFormat.BINARY_32:
279 fn = self._resource.write_binary_values
280 elif self._values_fmt == ValuesFormat.BINARY_64:
281 fn = functools.partial(self._resource.write_binary_values, datatype="d")
282
283 elif isinstance(self._resource, pyvisa.resources.RegisterBasedResource):
284 raise NotImplementedError()
285 else:
286 raise RuntimeError("unreachable")
287
288 return fn(cmd, values, **kwargs)
289
290 def query(self, cmd, **kwargs) -> None:
291 if self.echo:
292 print(cmd)
293
294 if isinstance(self._resource, pyvisa.resources.MessageBasedResource):
295 fn = self._resource.query
296 elif isinstance(self._resource, pyvisa.resources.RegisterBasedResource):
297 raise NotImplementedError()
298 else:
299 raise RuntimeError("unreachable")
300
301 return fn(cmd, **kwargs)
302
303 def query_values(self, cmd, complex_values: bool = False, **kwargs) -> None:
304 if self.echo:
305 print(cmd)
306
307 if isinstance(self._resource, pyvisa.resources.MessageBasedResource):
308 if self._values_fmt == ValuesFormat.ASCII:
309 fn = self._resource.query_ascii_values
310 elif self._values_fmt == ValuesFormat.BINARY_32:
311 fn = self._resource.query_binary_values
312 elif self._values_fmt == ValuesFormat.BINARY_64:
313 fn = functools.partial(self._resource.query_binary_values, datatype="d")
314 elif isinstance(self._resource, pyvisa.resources.RegisterBasedResource):
315 raise NotImplementedError()
316 else:
317 raise RuntimeError("unreachable")
318
319 vals = fn(cmd, **kwargs)
320
321 if complex_values:
322 vals = np.vectorize(complex)(vals[::2], vals[1::2])
323
324 return vals