| 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 logging |
| 26 |
import re |
| 27 |
from math import inf, isfinite, isinf |
| 28 |
from warnings import warn |
| 29 |
|
| 30 |
from pymeasure.adapters import Adapter |
| 31 |
from pymeasure.instruments import Instrument, Channel |
| 32 |
from pymeasure.instruments.validators import (joined_validators, |
| 33 |
strict_discrete_set, |
| 34 |
strict_range) |
| 35 |
|
| 36 |
|
| 37 |
log = logging.getLogger(__name__) |
| 38 |
log.addHandler(logging.NullHandler()) |
| 39 |
|
| 40 |
|
| 41 |
def deprecated_strict_range(value, values): |
| 42 |
warn("This property is deprecated, use meth:`move_raw` instead.", |
| 43 |
FutureWarning) |
| 44 |
return strict_range(value, values) |
| 45 |
|
| 46 |
|
| 47 |
def strict_length(value, values): |
| 48 |
if len(value) != values: |
| 49 |
raise ValueError( |
| 50 |
f"Value {value} does not have an appropriate length of {values}") |
| 51 |
return value |
| 52 |
|
| 53 |
|
| 54 |
def truncated_int_array(value, values): |
| 55 |
ret = [] |
| 56 |
for i, v in enumerate(value): |
| 57 |
if values[0] <= v <= values[1]: |
| 58 |
if float(v).is_integer(): |
| 59 |
ret.append(int(v)) |
| 60 |
else: |
| 61 |
raise ValueError(f"Entry {v} at index {i} has no integer value") |
| 62 |
elif float(v).is_integer(): |
| 63 |
ret.append(max(min(values[1], v), values[0])) |
| 64 |
else: |
| 65 |
raise ValueError(f"Entry {v} at index {i} has no integer value and" |
| 66 |
f"is out of the boundaries {values}") |
| 67 |
return ret |
| 68 |
|
| 69 |
|
| 70 |
truncated_int_array_strict_length = joined_validators(strict_length, |
| 71 |
truncated_int_array) |
| 72 |
|
| 73 |
|
| 74 |
class Axis(Channel): |
| 75 |
""" Represents a single open loop axis of the Attocube ANC350 |
| 76 |
|
| 77 |
:param axis: axis identifier, integer from 1 to 7 |
| 78 |
:param controller: ANC300Controller instance used for the communication |
| 79 |
""" |
| 80 |
|
| 81 |
serial_nr = Instrument.measurement("getser", |
| 82 |
"Get the serial number of the axis.") |
| 83 |
|
| 84 |
voltage = Instrument.control( |
| 85 |
"getv", "setv %.3f", |
| 86 |
"""Control the amplitude of the stepping voltage in volts from 0 to 150 V.""", |
| 87 |
validator=strict_range, values=[0, 150], check_set_errors=True) |
| 88 |
|
| 89 |
frequency = Instrument.control( |
| 90 |
"getf", "setf %.3f", |
| 91 |
"""Control the frequency of the stepping motion in Hertz from 1 to 10000 Hz.""", |
| 92 |
validator=strict_range, values=[1, 10000], |
| 93 |
cast=int, check_set_errors=True) |
| 94 |
|
| 95 |
mode = Instrument.control( |
| 96 |
"getm", "setm %s", |
| 97 |
"""Control axis mode. This can be 'gnd', 'inp', 'cap', 'stp', 'off', |
| 98 |
'stp+', 'stp-'. Available modes depend on the actual axis model.""", |
| 99 |
validator=strict_discrete_set, |
| 100 |
values=['gnd', 'inp', 'cap', 'stp', 'off', 'stp+', 'stp-'], |
| 101 |
check_set_errors=True) |
| 102 |
|
| 103 |
offset_voltage = Instrument.control( |
| 104 |
"geta", "seta %.3f", |
| 105 |
"""Control offset voltage in Volts from 0 to 150 V.""", |
| 106 |
validator=strict_range, values=[0, 150], check_set_errors=True) |
| 107 |
|
| 108 |
pattern_up = Instrument.control( |
| 109 |
"getpu", "setpu %s", |
| 110 |
"""Control step up pattern of the piezo drive. 256 values ranging from 0 |
| 111 |
to 255 representing the sequence of output voltages within one |
| 112 |
step of the piezo drive. This property can be set, the set value |
| 113 |
needs to be an array with 256 integer values. """, |
| 114 |
validator=truncated_int_array_strict_length, |
| 115 |
values=[256, [0, 255]], |
| 116 |
set_process=lambda a: " ".join("%d" % v for v in a), |
| 117 |
separator='\r\n', cast=int, check_set_errors=True) |
| 118 |
|
| 119 |
pattern_down = Instrument.control( |
| 120 |
"getpd", "setpd %s", |
| 121 |
"""Control step down pattern of the piezo drive. 256 values ranging from 0 |
| 122 |
to 255 representing the sequence of output voltages within one |
| 123 |
step of the piezo drive. This property can be set, the set value |
| 124 |
needs to be an array with 256 integer values. """, |
| 125 |
validator=truncated_int_array_strict_length, |
| 126 |
values=[256, [0, 255]], |
| 127 |
set_process=lambda a: " ".join("%d" % v for v in a), |
| 128 |
separator='\r\n', cast=int, check_set_errors=True) |
| 129 |
|
| 130 |
output_voltage = Instrument.measurement( |
| 131 |
"geto", |
| 132 |
"""Measure the output voltage in volts.""") |
| 133 |
|
| 134 |
capacity = Instrument.measurement( |
| 135 |
"getc", |
| 136 |
"""Measure the saved capacity value in nF of the axis.""") |
| 137 |
|
| 138 |
stepu = Instrument.setting( |
| 139 |
"stepu %d", |
| 140 |
"""Set the steps upwards for N steps. Mode must be 'stp' and N must be |
| 141 |
positive. 0 causes a continuous movement until stop is called. |
| 142 |
|
| 143 |
.. deprecated:: 0.13.0 Use meth:`move_raw` instead. |
| 144 |
""", |
| 145 |
validator=deprecated_strict_range, |
| 146 |
values=[0, inf], |
| 147 |
check_set_errors=True, |
| 148 |
) |
| 149 |
|
| 150 |
stepd = Instrument.setting( |
| 151 |
"stepd %d", |
| 152 |
"""Set the steps downwards for N steps. Mode must be 'stp' and N must be |
| 153 |
positive. 0 causes a continuous movement until stop is called. |
| 154 |
|
| 155 |
.. deprecated:: 0.13.0 Use meth:`move_raw` instead. |
| 156 |
""", |
| 157 |
validator=deprecated_strict_range, |
| 158 |
values=[0, inf], |
| 159 |
check_set_errors=True, |
| 160 |
) |
| 161 |
|
| 162 |
def insert_id(self, command): |
| 163 |
"""Insert the channel id in a command replacing `placeholder`. |
| 164 |
|
| 165 |
Add axis id to a command string at the correct position after the |
| 166 |
initial command, but before a potential value. |
| 167 |
""" |
| 168 |
cmdparts = command.split() |
| 169 |
cmdparts.insert(1, self.id) |
| 170 |
return ' '.join(cmdparts) |
| 171 |
|
| 172 |
def stop(self): |
| 173 |
""" Stop any motion of the axis """ |
| 174 |
self.write('stop') |
| 175 |
self.check_set_errors() |
| 176 |
|
| 177 |
def move_raw(self, steps): |
| 178 |
"""Move 'steps' steps in the direction given by the sign of the |
| 179 |
argument. This method assumes the mode of the axis is set to 'stp' and |
| 180 |
it is non-blocking, i.e. it will return immediately after sending the |
| 181 |
command. |
| 182 |
|
| 183 |
:param steps: integer value of steps to be performed. A positive |
| 184 |
sign corresponds to upwards steps, a negative sign to downwards |
| 185 |
steps. The values of +/-inf trigger a continuous movement. The axis |
| 186 |
can be halted by the stop method. |
| 187 |
""" |
| 188 |
if isfinite(steps) and abs(steps) > 0: |
| 189 |
if steps > 0: |
| 190 |
self.write(f"stepu {steps:d}") |
| 191 |
else: |
| 192 |
self.write(f"stepd {abs(steps):d}") |
| 193 |
elif isinf(steps): |
| 194 |
if steps > 0: |
| 195 |
self.write("stepu c") |
| 196 |
else: |
| 197 |
self.write("stepd c") |
| 198 |
else: # ignore zero and nan values |
| 199 |
return |
| 200 |
self.check_set_errors() |
| 201 |
|
| 202 |
def move(self, steps, gnd=True): |
| 203 |
"""Move 'steps' steps in the direction given by the sign of the |
| 204 |
argument. This method will change the mode of the axis automatically |
| 205 |
and ground the axis on the end if 'gnd' is True. The method is blocking |
| 206 |
and returns only when the movement is finished. |
| 207 |
|
| 208 |
:param steps: finite integer value of steps to be performed. A positive |
| 209 |
sign corresponds to upwards steps, a negative sign to downwards |
| 210 |
steps. |
| 211 |
:param gnd: bool, flag to decide if the axis should be grounded after |
| 212 |
completion of the movement |
| 213 |
""" |
| 214 |
if not isfinite(steps): |
| 215 |
raise ValueError("Only finite number of steps are allowed.") |
| 216 |
self.mode = 'stp' |
| 217 |
# perform the movement |
| 218 |
self.move_raw(steps) |
| 219 |
# wait for the move to finish |
| 220 |
self.wait_for(abs(steps) / self.frequency) |
| 221 |
# ask if movement finished |
| 222 |
self.ask('stepw') |
| 223 |
if gnd: |
| 224 |
self.mode = 'gnd' |
| 225 |
|
| 226 |
def measure_capacity(self): |
| 227 |
""" Obtains a new measurement of the capacity. The mode of the axis |
| 228 |
returns to 'gnd' after the measurement. |
| 229 |
|
| 230 |
:returns capacity: the freshly measured capacity in nF. |
| 231 |
""" |
| 232 |
self.mode = 'cap' |
| 233 |
# wait for the measurement to finish |
| 234 |
self.wait_for(1) |
| 235 |
# ask if really finished |
| 236 |
self.ask('capw') |
| 237 |
return self.capacity |
| 238 |
|
| 239 |
|
| 240 |
class ANC300Controller(Instrument): |
| 241 |
""" Attocube ANC300 Piezo stage controller with several axes |
| 242 |
|
| 243 |
:param adapter: The VISA resource name of the controller |
| 244 |
(e.g. "TCPIP::<address>::<port>::SOCKET") or a created Adapter. |
| 245 |
The instruments default communication port is 7230. |
| 246 |
:param axisnames: a list of axis names which will be used to create |
| 247 |
properties with these names |
| 248 |
:param passwd: password for the attocube standard console |
| 249 |
:param query_delay: default delay between sending and reading in s (default 0.05) |
| 250 |
:param host: host address of the instrument (e.g. 169.254.0.1) |
| 251 |
|
| 252 |
.. deprecated:: 0.11.2 |
| 253 |
The 'host' argument is deprecated. Use 'adapter' argument instead. |
| 254 |
|
| 255 |
:param kwargs: Any valid key-word argument for VISAAdapter |
| 256 |
""" |
| 257 |
version = Instrument.measurement( |
| 258 |
"ver", """ Get the version number and instrument identification. """ |
| 259 |
) |
| 260 |
|
| 261 |
controllerBoardVersion = Instrument.measurement( |
| 262 |
"getcser", """ Get the serial number of the controller board. """ |
| 263 |
) |
| 264 |
|
| 265 |
_reg_value = re.compile(r"\w+\s+=\s+([\w\.]+)") |
| 266 |
|
| 267 |
def __init__( |
| 268 |
self, |
| 269 |
adapter=None, |
| 270 |
name="attocube ANC300 Piezo Controller", |
| 271 |
axisnames="", |
| 272 |
passwd="", |
| 273 |
query_delay=0.05, |
| 274 |
**kwargs, |
| 275 |
): |
| 276 |
adapter = self.handle_deprecated_host_arg(adapter, kwargs) |
| 277 |
|
| 278 |
if not isinstance(name, str): |
| 279 |
warn( |
| 280 |
f"ANC300Controller.__init__: `name` was provided was {type(name)} but should be a " |
| 281 |
+ "string. This is likely because `name` was added as a keyword argument. " |
| 282 |
+ "All positional arguments after `adapter` should be provided as keyword argument" |
| 283 |
+ " (i.e. `axisnames=['x', 'y']`).", |
| 284 |
FutureWarning |
| 285 |
) |
| 286 |
|
| 287 |
self.query_delay = query_delay |
| 288 |
self.termination_str = "\r\n" |
| 289 |
|
| 290 |
super().__init__( |
| 291 |
adapter, |
| 292 |
name, |
| 293 |
includeSCPI=False, |
| 294 |
read_termination=self.termination_str, |
| 295 |
write_termination=self.termination_str, |
| 296 |
**kwargs |
| 297 |
) |
| 298 |
|
| 299 |
self._axisnames = axisnames |
| 300 |
for i, axis in enumerate(axisnames): |
| 301 |
setattr(self, axis, self.add_child(Axis, id=str(i + 1))) |
| 302 |
|
| 303 |
self.wait_for() |
| 304 |
# clear messages sent upon opening the connection, |
| 305 |
# this contains some non-ascii characters! |
| 306 |
self.adapter.flush_read_buffer() |
| 307 |
# send password and check authorization |
| 308 |
self.write(passwd) |
| 309 |
self.wait_for() |
| 310 |
super().read() # ignore echo of password |
| 311 |
auth_msg = super().read() |
| 312 |
if auth_msg != 'Authorization success': |
| 313 |
raise Exception(f"Attocube authorization failed '{auth_msg}'") |
| 314 |
# switch console echo off |
| 315 |
self.ask('echo off') |
| 316 |
|
| 317 |
def check_set_errors(self): |
| 318 |
"""Check for errors after having set a property and log them. |
| 319 |
|
| 320 |
Called if :code:`check_set_errors=True` is set for that property. |
| 321 |
|
| 322 |
:return: List of error entries. |
| 323 |
""" |
| 324 |
try: |
| 325 |
self.read() |
| 326 |
except Exception as exc: |
| 327 |
log.exception("Setting a property failed.", exc_info=exc) |
| 328 |
raise |
| 329 |
else: |
| 330 |
return [] |
| 331 |
|
| 332 |
def ground_all(self): |
| 333 |
""" Grounds all axis of the controller. """ |
| 334 |
for attr in self._axisnames: |
| 335 |
attribute = getattr(self, attr) |
| 336 |
if isinstance(attribute, Axis): |
| 337 |
attribute.mode = 'gnd' |
| 338 |
|
| 339 |
def stop_all(self): |
| 340 |
""" Stop all movements of the axis. """ |
| 341 |
for attr in self._axisnames: |
| 342 |
attribute = getattr(self, attr) |
| 343 |
if isinstance(attribute, Axis): |
| 344 |
attribute.stop() |
| 345 |
|
| 346 |
def handle_deprecated_host_arg(self, adapter, kwargs): |
| 347 |
""" |
| 348 |
This function formats user input to the __init__ function to be compatible with the |
| 349 |
current definition of the __init__ function. This is used to support outdated (deprecated) |
| 350 |
code. and separated out to make it easier to remove in the future. To whoever removes this: |
| 351 |
This function should be removed and the `adapter` argument in the __init__ method should |
| 352 |
be made non-optional. |
| 353 |
|
| 354 |
:param dict kwargs: keyword arguments passed to the __init__ function, |
| 355 |
including the deprecated `host` argument. |
| 356 |
:return str: resource string for the VISAAdapter |
| 357 |
""" |
| 358 |
host = kwargs.pop("host", None) |
| 359 |
if not (host or adapter): |
| 360 |
raise TypeError("ANC300Controller: missing 'adapter' argument") |
| 361 |
|
| 362 |
if not adapter: |
| 363 |
# because the host argument is deprecated, prompt for the desired |
| 364 |
# argument which is the adapter argument. |
| 365 |
warn("The 'host' argument is deprecated. Use 'adapter' instead.", FutureWarning) |
| 366 |
adapter = host |
| 367 |
|
| 368 |
if isinstance(adapter, str): |
| 369 |
if adapter.find("::") > -1: |
| 370 |
# adapter is a resource string, so use it |
| 371 |
return adapter |
| 372 |
# otherwise, `adapter` can only be a (deprecated) hostname, so display a |
| 373 |
# deprecation warning and create the resource string |
| 374 |
warn( |
| 375 |
"Using a hostname is deprecated. Use a full VISA resource string instead.", |
| 376 |
FutureWarning, |
| 377 |
) |
| 378 |
return f"TCPIP::{adapter}::7230::SOCKET" |
| 379 |
elif isinstance(adapter, Adapter): |
| 380 |
return adapter |
| 381 |
raise TypeError("ANC300Controller: 'adapter' argument must be a string or Adapter") |
| 382 |
|
| 383 |
def _extract_value(self, reply): |
| 384 |
""" preprocess_reply function for the Attocube console. This function |
| 385 |
tries to extract <value> from 'name = <value> [unit]'. If <value> can |
| 386 |
not be identified the original string is returned. |
| 387 |
|
| 388 |
:param reply: reply string |
| 389 |
:returns: string with only the numerical value, or the original string |
| 390 |
""" |
| 391 |
r = self._reg_value.search(reply) |
| 392 |
if r: |
| 393 |
return r.groups()[0] |
| 394 |
else: |
| 395 |
return reply |
| 396 |
|
| 397 |
def read(self): |
| 398 |
"""Read after setting a value.""" |
| 399 |
lines = [] |
| 400 |
while True: |
| 401 |
lines.append(super().read()) |
| 402 |
if lines[-1] in ["OK", "ERROR"]: |
| 403 |
break |
| 404 |
msg = self.termination_str.join(lines[:-1]) |
| 405 |
if lines[-1] != 'OK': |
| 406 |
self.adapter.flush_read_buffer() |
| 407 |
raise ValueError("ANC300Controller: Error after previous " |
| 408 |
f"command with message {msg}") |
| 409 |
return self._extract_value(msg) |
| 410 |
|
| 411 |
def wait_for(self, query_delay=None): |
| 412 |
"""Wait for some time. Used by 'ask' to wait before reading. |
| 413 |
|
| 414 |
:param query_delay: Delay between writing and reading in seconds. |
| 415 |
None means :attr:`query_delay`. |
| 416 |
""" |
| 417 |
super().wait_for(self.query_delay if query_delay is None else query_delay) |