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) → list[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) → bool[source]

Test if file has option.

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

Return type:

boolean

has_section(section) → bool[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

Seconds since epoch (unix time).

Type:float
date

Date.

Type:string
hms

Hours, minutes, seconds.

Type:string
human

Representation of the timestamp meant to be human readable.

Type:string
legacy

Legacy WrightTools timestamp representation.

Type:string
RFC3339

RFC3339 representation (recommended for most applications).

Type:string
RFC5322

RFC5322 representation.

Type:string
path

Representation of the timestamp meant for inclusion in filepaths.

Type:string
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) → numpy.ndarray[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) → collections.OrderedDict[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.enforce_mask_shape(mask, shape)[source]

Reduce a boolean mask to fit a given shape.

Parameters:
  • mask (ndarray with bool dtype) – The mask which is to be reduced
  • shape (tuple of int) – Shape which broadcasts to the mask shape.
Returns:

Return type:

A boolean mask, collapsed along axes where the shape given has one element.

WrightTools.kit.fft(xi, yi, axis=0) → tuple[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.fluence(power_mW, color, beam_radius, reprate_Hz, pulse_width, color_units='wn', beam_radius_units='mm', pulse_width_units='fs_t', area_type='even') → tuple[source]

Calculate the fluence of a beam.

Parameters:
  • power_mW (number) – Time integrated power of beam.
  • color (number) – Color of beam in units.
  • beam_radius (number) – Radius of beam in units.
  • reprate_Hz (number) – Laser repetition rate in inverse seconds (Hz).
  • pulse_width (number) – Pulsewidth of laser in units
  • color_units (string (optional)) – Valid wt.units color unit identifier. Default is wn.
  • beam_radius_units (string (optional)) – Valid wt.units distance unit identifier. Default is mm.
  • pulse_width_units (number) – Valid wt.units time unit identifier. Default is fs.
  • area_type (string (optional)) – Type of calculation to accomplish for Gaussian area. Currently nothing other than the default of even is implemented.
Returns:

Fluence in uj/cm2, photons/cm2, and peak intensity in GW/cm2

Return type:

tuple

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) → tuple[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.mask_reduce(mask)[source]

Reduce a boolean mask, removing all false slices in any dimension.

Parameters:mask (ndarray with bool dtype) – The mask which is to be reduced
Returns:
Return type:A boolean mask with no all False slices.
WrightTools.kit.mono_resolution(grooves_per_mm, slit_width, focal_length, output_color, output_units='wn') → float[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') → float[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) → bool[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.pairwise(iterable)[source]

s -> (s0,s1), (s1,s2), (s2, s3), …

Originally from itertools docs

Parameters:iterable (iterable) – Iterable from which to produce pairs
Returns:Generator which producis pairwise tuples
Return type:generator
WrightTools.kit.remove_nans_1D(*args) → tuple[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) → tuple[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, smooth_type='flat') → numpy.ndarray[source]

Smooth 1D data using a window function.

Edge effects will be present.

Parameters:
  • arr (array_like) – Input array, 1D.
  • n (int (optional)) – Window length.
  • smooth_type ({'flat', 'hanning', 'hamming', 'bartlett', 'blackman'} (optional)) – Type of window function to convolve data with. ‘flat’ window will produce a moving average smoothing.
Returns:

Smoothed 1D array.

Return type:

array_like

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.svd(a, i=None) → tuple[source]

Singular Value Decomposition.

Factors the matrix a as u * np.diag(s) * v, where u and v are unitary and s is a 1D array of a’s singular values.

Parameters:
  • a (array_like) – Input array.
  • i (int or slice (optional)) – What singular value “slice” to return. Default is None which returns unitary 2D arrays.
Returns:

Decomposed arrays in order u, v, s

Return type:

tuple

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) → numpy.ndarray[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) → tuple[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.