WrightTools.kit module

General-purpose tool kit.

class WrightTools.kit.INI(filepath)[source]

Bases: object

Handle communication with an INI file.

__init__(filepath)[source]

Create an INI handler object.

Parameters:filepath (string) – Filepath.
add_section(section)[source]

Add section.

Parameters:section (string) – Section to add.
clear()[source]

Remove all contents from file. Use with extreme caution.

Warning

This is a destructive action.

dictionary

Get a python dictionary of contents.

get_options(section)[source]

List the options in a section.

Parameters:section (string) – The section to investigate.
Returns:The options within the given section.
Return type:list of strings
has_option(section, option)[source]

Test if file has option.

Parameters:
  • section (string) – Section.
  • option (string) – Option.
Returns:

Return type:

boolean

has_section(section)[source]

Test if file has section.

Parameters:section (string) – Section.
Returns:
Return type:boolean
read(section, option)[source]

Read from file.

Parameters:
  • section (string) – Section.
  • option (string) – Option.
Returns:

Value.

Return type:

string

sections

List of sections.

write(section, option, value)[source]

Write to file.

Parameters:
  • section (string) – Section.
  • option (string) – Option.
  • value (string) – Value.
class WrightTools.kit.Spline(xi, yi, k=3, s=1000, ignore_nans=True)[source]

Bases: object

Spline.

__init__(xi, yi, k=3, s=1000, ignore_nans=True)[source]

Initialize.

Parameters:
  • xi (1D array) – x points.
  • yi (1D array) – y points.
  • k (integer (optional)) – Degree of smoothing. Must be between 1 and 5 (inclusive). Default is 3.
  • s (integer (optional)) –

    Positive smoothing factor used to choose the number of knots. Number of knots will be increased until the smoothing condition is satisfied:

    ``sum((w[i] * (y[i]-spl(x[i])))**2, axis=0) <= s``
    

    If 0, spline will interpolate through all data points. Default is 1000.

  • ignore_nans (boolean (optional)) – Toggle removle of nans. Default is True.

Note

Use k=1 and s=0 for a linear interplation.

class WrightTools.kit.TimeStamp(at=None, timezone='local')[source]

Bases: object

Class for representing a moment in time.

RFC3339

RFC3339.

RFC5322

RFC5322.

__init__(at=None, timezone='local')[source]

Create a TimeStamp object.

Parameters:
  • at (float (optional)) – Seconds since epoch (unix time). If None, current time will be used. Default is None.
  • timezone (string or integer (optional)) – String (one in {‘local’, ‘utc’} or seconds offset from UTC. Default is local.
unix

float – Seconds since epoch (unix time).

date

string – Date.

hms

string – Hours, minutes, seconds.

human

string – Representation of the timestamp meant to be human readable.

legacy

string – Legacy WrightTools timestamp representation.

RFC3339

stringRFC3339 representation (recommended for most applications).

RFC5322

stringRFC5322 representation.

path

string – Representation of the timestamp meant for inclusion in filepaths.

date

year-month-day.

hms

Get time formated.

HH:MM:SS

human

Human-readable timestamp.

path

Timestamp for placing into filepaths.

class WrightTools.kit.Timer(verbose=True)[source]

Bases: object

Context manager for timing code.

>>> with Timer():
...     your_code()
__init__(verbose=True)[source]

Initialize self. See help(type(self)) for accurate signature.

WrightTools.kit.closest_pair(arr, give='indicies')[source]

Find the pair of indices corresponding to the closest elements in an array.

If multiple pairs are equally close, both pairs of indicies are returned. Optionally returns the closest distance itself.

I am sure that this could be written as a cheaper operation. I wrote this as a quick and dirty method because I need it now to use on some relatively small arrays. Feel free to refactor if you need this operation done as fast as possible. - Blaise 2016-02-07

Parameters:
  • arr (numpy.ndarray) – The array to search.
  • give ({'indicies', 'distance'} (optional)) – Toggle return behavior. If ‘distance’, returns a single float - the closest distance itself. Default is indicies.
Returns:

List containing lists of two tuples: indicies the nearest pair in the array.

>>> arr = np.array([0, 1, 2, 3, 3, 4, 5, 6, 1])
>>> closest_pair(arr)
[[(1,), (8,)], [(3,), (4,)]]

Return type:

list of lists of two tuples

WrightTools.kit.diff(xi, yi, order=1)[source]

Take the numerical derivative of a 1D array.

Output is mapped onto the original coordinates using linear interpolation. Expects monotonic xi values.

Parameters:
  • xi (1D array-like) – Coordinates.
  • yi (1D array-like) – Values.
  • order (positive integer (optional)) – Order of differentiation.
Returns:

Numerical derivative. Has the same shape as the input arrays.

Return type:

1D numpy array

WrightTools.kit.discover_dimensions(arr, cols)[source]

Discover the dimensions of a flattened multidimensional array.

Parameters:
  • arr (2D numpy ndarray) – Array in [col, value].
  • cols (dictionary) – Dictionary with column names as keys, and idx, tolerance and units as values.
Returns:

expression: points

Return type:

dictionary

WrightTools.kit.fft(xi, yi, axis=0)[source]

Take the 1D FFT of an N-dimensional array and return “sensible” properly shifted arrays.

Parameters:
  • xi (numpy.ndarray) – 1D array over which the points to be FFT’ed are defined
  • yi (numpy.ndarray) – ND array with values to FFT
  • axis (int) – axis of yi to perform FFT over
Returns:

  • xi (1D numpy.ndarray) – 1D array. Conjugate to input xi. Example: if input xi is in the time domain, output xi is in frequency domain.
  • yi (ND numpy.ndarray) – FFT. Has the same shape as the input array (yi).

WrightTools.kit.flatten_list(items, seqtypes=(<class 'list'>, <class 'tuple'>), in_place=True)[source]

Flatten an irregular sequence.

Works generally but may be slower than it could be if you can make assumptions about your list.

Source

Parameters:
  • items (iterable) – The irregular sequence to flatten.
  • seqtypes (iterable of types (optional)) – Types to flatten. Default is (list, tuple).
  • in_place (boolean (optional)) – Toggle in_place flattening. Default is True.
Returns:

Flattened list.

Return type:

list

Examples

>>> l = [[[1, 2, 3], [4, 5]], 6]
>>> wt.kit.flatten_list(l)
[1, 2, 3, 4, 5, 6]
WrightTools.kit.get_index(lis, argument)[source]

Find the index of an item, given either the item or index as an argument.

Particularly useful as a wrapper for arguments like channel or axis.

Parameters:
  • lis (list) – List to parse.
  • argument (int or object) – Argument.
Returns:

Index of chosen object.

Return type:

int

WrightTools.kit.get_path_matching(name)[source]

Get path matching a name.

Parameters:name (string) – Name to search for.
Returns:Full filepath.
Return type:string
WrightTools.kit.glob_handler(extension, folder=None, identifier=None)[source]

Return a list of all files matching specified inputs.

Parameters:
  • extension (string) – File extension.
  • folder (string (optional)) – Folder to search within. Default is None (current working directory).
  • identifier (string) – Unique identifier. Default is None.
Returns:

Full path of matching files.

Return type:

list of strings

WrightTools.kit.intersperse(lis, value)[source]

Put value between each existing item in list.

Parameters:
  • lis (list) – List to intersperse.
  • value (object) – Value to insert.
Returns:

interspersed list

Return type:

list

WrightTools.kit.joint_shape(*args)[source]

Given a set of arrays, return the joint shape.

Parameters:args (array-likes) –
Returns:Joint shape.
Return type:tuple of int
WrightTools.kit.leastsqfitter(p0, datax, datay, function, verbose=False, cov_verbose=False)[source]

Conveniently call scipy.optmize.leastsq().

Returns fit parameters and their errors.

Parameters:
  • p0 (list) – list of guess parameters to pass to function
  • datax (array) – array of independent values
  • datay (array) – array of dependent values
  • function (function) – function object to fit data to. Must be of the callable form function(p, x)
  • verbose (bool) – toggles printing of fit time, fit params, and fit param errors
  • cov_verbose (bool) – toggles printing of covarience matrix
Returns:

  • pfit_leastsq (list) – list of fit parameters. s.t. the error between datay and function(p, datax) is minimized
  • perr_leastsq (list) – list of fit parameter errors (1 std)

WrightTools.kit.mono_resolution(grooves_per_mm, slit_width, focal_length, output_color, output_units='wn')[source]

Calculate the resolution of a monochromator.

Parameters:
  • grooves_per_mm (number) – Grooves per millimeter.
  • slit_width (number) – Slit width in microns.
  • focal_length (number) – Focal length in mm.
  • output_color (number) – Output color in nm.
  • output_units (string (optional)) – Output units. Default is wn.
Returns:

Resolution.

Return type:

float

WrightTools.kit.nm_width(center, width, units='wn')[source]

Given a center and width, in energy units, get back a width in nm.

Parameters:
  • center (number) – Center (in energy units).
  • width (number) – Width (in energy units).
  • units (string (optional)) – Input units. Default is wn.
Returns:

Width in nm.

Return type:

number

WrightTools.kit.orthogonal(*args)[source]

Determine if a set of arrays are orthogonal.

Parameters:args (array-likes or array shapes) –
Returns:Array orthogonality condition.
Return type:bool
WrightTools.kit.remove_nans_1D(*args)[source]

Remove nans in a set of 1D arrays.

Removes indicies in all arrays if any array is nan at that index. All input arrays must have the same size.

Parameters:args (1D arrays) –
Returns:Tuple of 1D arrays in same order as given, with nan indicies removed.
Return type:tuple
WrightTools.kit.share_nans(*arrs)[source]

Take a list of nD arrays and return a new list of nD arrays.

The new list is in the same order as the old list. If one indexed element in an old array is nan then every element for that index in all new arrays in the list is then nan.

Parameters:*arrs (nD arrays.) –
Returns:List of nD arrays in same order as given, with nan indicies syncronized.
Return type:list
WrightTools.kit.smooth_1D(arr, n=10)[source]

Smooth 1D data by ‘running average’.

Parameters:n (int) – number of points to average
WrightTools.kit.string2identifier(s)[source]

Turn a string into a valid python identifier.

Currently only allows ASCII letters and underscore. Illegal characters are replaced with underscore. This is slightly more opinionated than python 3 itself, and may be refactored in future (see PEP 3131).

Parameters:s (string) – string to convert
Returns:valid python identifier.
Return type:str
WrightTools.kit.symmetric_sqrt(x, out=None)[source]

Compute the ‘symmetric’ square root: sign(x) * sqrt(abs(x)).

Parameters:
  • x (array_like or number) – Input array.
  • out (ndarray, None, or tuple of ndarray and None (optional)) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
Returns:

Symmetric square root of arr.

Return type:

np.ndarray

WrightTools.kit.timestamp_from_RFC3339(RFC3339)[source]

Generate a Timestamp object from a RFC3339 formatted string.

Parameters:RFC3339 (string) – RFC3339 formatted string.
Returns:
Return type:WrightTools.kit.TimeStamp
WrightTools.kit.unique(arr, tolerance=1e-06)[source]

Return unique elements in 1D array, within tolerance.

Parameters:
  • arr (array_like) – Input array. This will be flattened if it is not already 1D.
  • tolerance (number (optional)) – The tolerance for uniqueness.
Returns:

The sorted unique values.

Return type:

array

WrightTools.kit.valid_index(index, shape)[source]

Get a valid index for a broadcastable shape.

Parameters:
  • index (tuple) – Given index.
  • shape (tuple of int) – Shape.
Returns:

Valid index.

Return type:

tuple

WrightTools.kit.zoom2D(xi, yi, zi, xi_zoom=3.0, yi_zoom=3.0, order=3, mode='nearest', cval=0.0)[source]

Zoom a 2D array, with axes.

Parameters:
  • xi (1D array) – x axis points.
  • yi (1D array) – y axis points.
  • zi (2D array) – array values. Shape of (x, y).
  • xi_zoom (float (optional)) – Zoom factor along x axis. Default is 3.
  • yi_zoom (float (optional)) – Zoom factor along y axis. Default is 3.
  • order (int (optional)) – The order of the spline interpolation, between 0 and 5. Default is 3.
  • mode ({'constant', 'nearest', 'reflect', or 'wrap'}) – Points outside the boundaries of the input are filled according to the given mode. Default is nearest.
  • cval (scalar (optional)) – Value used for constant mode. Default is 0.0.