4. Miscellaneous utilities — wanglib.util

This file provides useful utilities for the wanglib package.

exception wanglib.util.InstrumentError

Raise this when talking to instruments fails.

class wanglib.util.Serial(*args, **kwargs)

Extension of PySerial‘s serial.Serial class that implements a few extra features:

  • an ask() method
  • a readall() method
  • auto-appended termination characters
  • in/out logging.

To log whatever’s written or read to a serial port, pass a filename into the log kwarg:

>>> port = Serial('/dev/ttyS0', log='wtf.log')

To automatically append a newline to each command, specify term_chars:

>>> port.term_chars = '/n'

This can also be supplied as a keyword argument.

ask(query, lag=0.05)

Write to the bus, then read response.

This doesn’t seem to work very well.


Automatically read all the bytes from the serial port.

if term_chars is set, this will continue to read until the terminating bytes are received. This can be provided as a keyword argument.


start logging read/write data to file.

wanglib.util.averager(func, n, lag=0.1)

Given a function func, returns an implementation of that function that just repeats it n times, and returns an average of the result.

  • func (function) – function returning a measurement
  • n (int) – number of times to call func.
  • lag (float) – seconds to sleep between measurements.

the average of the n measurements.

This is useful when scanning. For example, if scanning a spectrum with the lockin like so:

>>> gen = scanner(wls, set=tr.set_wl, get=li.get_x)

We can implement a version that averages three lockin measurements with a 0.3s delay like so:

>>> acq = averager(li.get_x, 3, lag=0.3)
>>> gen = scanner(wls, set=tr.set_wl, get=acq)
wanglib.util.gaussian(p, x)

gaussian function.

p is a 4-component parameter vector defining:

0 -- a baseline offset
1 -- the area between curve and baseline
2 -- the location of the maximum
3 -- the standard deviation
wanglib.util.monitor(function, lag=0.3, absolute=False)

Periodically yield output of a function, along with timestamp. Compatible with wanglib.pylab_extensions.live_plot.plotgen().

  • function (function) – function to call
  • lag (float) – interval between calls to function (default 0.3 seconds)
  • absolute (boolean) – if True, yielded x values are seconds since epoch. otherwise, time since first yield.

a generator object yielding t,y pairs.

wanglib.util.notraceback(*args, **kwds)

Context manager to swallow keyboard interrupt.

Execute any infinitely-looping process in this context, like:

>>> from time import sleep
>>> with notraceback():
...     while True:
...         sleep(0.1)

If you are planning to interrupt it anyway then you are not interested in the traceback and this prevents your output from being cluttered.


convert string to number. decide whether to convert to int or float.

wanglib.util.save(fname, array)

Save a Numpy array to file.

  • fname – Filename, as a string
  • array – Numpy array to save.

Unlike numpy.save(), this function will raise ValueError if overwriting an existing file.

class wanglib.util.saver(name, verbose=False)

Sequential file saver.

after initializing saver with the base filename, use the save() method to save arrays to sequentially-numbered files.

>>> s = saver('foo')
>>> s.save(arange(5)) # saves to 'foo000.npy'
>>> s.save(arange(2)) # saves to 'foo001.npy'

Save an array to the next file in the sequence.

wanglib.util.scanner(xvals, set, get, lag=0.3)

Generic scan generator - useful for spectra, delay scans, whatever. Compatible with wanglib.pylab_extensions.live_plot.plotgen().

  • xvals (iterable) – values of x over which to scan.
  • set (function) – Function to call on each step that advances the independent variable to the next value of xvals. This function should take that value as an argument.
  • get (function) – Function to call on each step that performs the measurement. The return value of this function should be the measurement result.
  • lag (float) – seconds to sleep between setting and measuring

a generator object yielding x,y pairs.

Example: while scanning triax wavelength, measure lockin x

>>> from triax.instruments.lockins import egg5110
>>> from triax.instruments.spex750m import triax320
>>> from wanglib.pylab_extensions import plotgen
>>> tr = triax320()
>>> li = egg5110(instrument(plx,12))
>>> wls = arange(770, 774, .1)
>>> gen = scanner(wls, set=tr.set_wl, get=li.get_x)
>>> result = plotgen(gen)

Sometimes we will want to set/measure an attribute of an object on each step, instead of calling a method. In this case, we can provide an (object, attribute_name) tuple in lieu of a function for set or get. For example, in place of the gen used above, we could do:

>>> gen = scanner(wls, set=(tr,'wl'), get=(li,'x'))

Avoid this if you can, though.

wanglib.util.sciround(number, sigfigs=1)

Round a number to a desired significant figure precision.

>>> sciround(.000671438, 3)

replace CR+LF with the words “CR” and “LF”. useful for debugging.