Tools functions

Below is a list of the general tools developed for the MJOLNIR software package.

KwargChecker

Function to check if given key-word is in the list of accepted Kwargs.

my_timer_N

Timer function to measure time consumbtion of function.

beautifyArgs

Beautify arguments and keyword arguments.

binEdges

Generate binning of values array with minimum bin size of tolerance.

fileListGenerator

Function to generate list of data files.

RoundBinning

Bin points to nearest delta value in D dimensions and reorder Data.

invert

Invert non-square matrices as described on https://en.wikipedia.org/wiki/Generalized_inverse.

minMax

Return minimal and maximal of list.

unitVector

Returns vector of unit length

rotMatrix

Generalized rotation matrix.

Rot

Create 2D rotation matrix

clockwiseangle_and_distance

Sort points clockwise.

vectorAngle

calculate angle between V1 and V2.

generateLabel

Format a scattering vector with individual letters.

writeToSpinWFile

Write fitted values for spin wave(s) into a SpinW readable format.

Functions in the _tools module

_tools.DSpacing(TwoTheta, Energy=None, Wavelength=None, K=None, degrees=True)[source]

Calculate d spacing [AA] from scattering angle [deg or rad] and one of the following [Energy [meV], Wavelength [AA], K[1/AA]].

_tools.EnergyK(k)[source]

Calculate length of k [1/AA] from energy [meV]

_tools.EnergyWavelength(wavelength)[source]

Calculate wavelength [AA] from energy [meV]

_tools.KEnergy(energy)[source]

Calculate energy [meV] from length of k [1/AA]

_tools.KWavelength(wavelength)[source]

Calculate wave vector k vactor [1/AA] from wavelength [AA]

_tools.KwargChecker(function=None, include=None)[source]

Function to check if given key-word is in the list of accepted Kwargs. If not directly therein, checks capitalization. If still not match raises error with suggestion of closest argument.

Parameters

func (-) – Function to be decorated.

Raises

- AttributeError

class _tools.PointerArray(attribute, datafiles)[source]

Array-like object designed to facilitate data acquisition from a list of differently sized list of data files having the same attributes.

Parameters
  • attribute (-) – Name of wanted attribute existing on the data

  • datafiles (-) – List of pointers to the data files

_tools.Rot(theta, deg=True)[source]

Create 2D rotation matrix

Parameters

theta (-) – Rotation angle (by default in degrees)

Kwargs:

  • deg (bool): Whether or not number provided is degree or radian (default True)

Returns

  • 2x2 rotation matrix definde with -sin in row 0 column 1

_tools.RoundBinning(X, deltas, Data=None)[source]

Bin points to nearest delta value in D dimensions and reorder Data.

Parameters
  • X (-) – Input points in shape (D,N) for D dimensions.

  • deltas (-) – binning size(s)

Kwargs:

  • Data (list/array): List of data or data list of shape (N) to be binned like X (default None).

Returns

ND list of binned unique positions of points

  • indices (list): Inverse indices from which points-array can be created from unique points

  • count (list): Number of points going into each bin

Return type

  • BinnedPoints (list)

(- returnData: Rebinned data as according to points being binned)

Algorithm takes the data points and rebins them into points closest to delta in N dimensions. If deltas=[0.05,0.05] and 2D points are given, points will be binned to closest 0.05 (…-0.1,-0.05,0.0,0.05,0.1…) in both directions. Data lists are also reshuffeled to match.

_tools.ScatteringAngle(d, Energy=None, Wavelength=None, K=None, degrees=True)[source]

Calculate scattering angle [deg or rad] from d [AA] and one of the following [Energy [meV], Wavelength [AA], K[1/AA]].

_tools.WavelengthEnergy(energy)[source]

Calculate energy [meV] from wavelength [AA]

_tools.WavelengthK(k)[source]

Calcualte wavelength [AA] from wave vector k vactor [1/AA]

_tools.beautifyArgs(args=(), kwargs={})[source]

Beautify arguments and keyword arguments. Returns formated string with arguments and keyword argumenets seperated with commas as called in a function

_tools.binEdges(values, tolerance, startPoint=None, endPoint=None)[source]

Generate binning of values array with minimum bin size of tolerance. Binning starts at values[0]-tolerance/2.0 and ends at values[-1]+tolerance/2.0.

Parameters
  • values (-) – 1D array to be binned.

  • tolerance (-) – Minimum length of bin sizes.

Kwargs:

  • startPoint (float): Minimum position from wicht to start (default None)

  • endPoint (float): Maximal end bin position (default None)

Returns

  • bins (array)

_tools.calRefVector(points)[source]

Calcualte reference vector as vector pointing from mean point to geometric center. For half moon shape this is anti-radially.

Parameters

points (-) – list of points for which reference vector is calcualted, shape is 2xN

Returns

Reference vector

Return type

vector

_tools.calculateAbsoluteNormalization(sampleMass=None, sampleChemicalFormula=None, sampleMolarMass=None, formulaUnitsPerUnitCell=1, sampleGFactor=2, correctVanadium=False, vanadiumChemicalFormula='V', vanadiumMass=15.25, vanadiumMolarMass=None, vanadiumMonitor=100000, vanadiumSigmaIncoherent=5.08, vanadiumGFactor=2.0, vanadiumUnitsPerUnitCell=1.0)[source]

Calculate absolute normalization relative to Vanadium

Parameters

sampleMass (-) – Mass of sample in grams

Kwargs:

  • sampleChemicalFormula (string): Chemical formula

  • sampleMolarMass (float): Molar mass of sample in g/mol

  • formulaUnitsPerUnitCell (float): Number of units per unit cell (default 1)

  • sampleGFactor (float): Magnetic G factor for sample (defalt 2.0)

  • sampleDebyeWaller (float): DebyeWaller factor of sample (default 1)

  • correctVanadium (bool): Whether to scale normalization with Vanadium or if this has been performed in normalziation tables (default False)

  • vanadiumMass (float): Mass of vanadium used in normalization in gram (default 15.25)

  • vanadiumMolarMass (float): Molar mass of vanadium (default None)

  • vanadiumMonitor (int): Monitor count used in normalization scan (default 100000)

  • vanadiumSigmaIncoherent (float): Incoherent scattering strength of Vanadium (default 5.08)

Returns

Relative normalization of sample to Vanadium scan

Return type

  • normalizationFactor (float)

_tools.calculateMolarMass(sampleChemicalFormula, formulaUnitsPerUnitCell=1, returnElements=False)[source]

Calculate Molar mass given chemical formula and number of formula units per cell

Parameters

sampleChemicalFormula (-) – Chemical formula

Kwargs:

  • formulaUnitsPerUnitCell (int): Number of units per unitcell (default 1)

  • returnElements (bool): If true return also list of elements

Returns

  • MolarMass (float)

Raises

- AttributeError

Based on https://stackoverflow.com/questions/18517779/make-outer-tokens-change-inner-tokens-in-a-chemical-formula-using-pyparsing/18555142#18555142 with the added feature of floats being allowed

_tools.clockwiseangle_and_distance(point, origin=[0, 0], refvec=[0, 1])[source]

Sort points clockwise. Taken from https://stackoverflow.com/questions/41855695/sorting-list-of-two-dimensional-coordinates-by-clockwise-angle-using-python

Parameters

point (-) – List of points in 2D of size 2xN

Kwargs:

  • origin (list): Location of origin from which the points are to be sorted (default [0,0])

  • refvec (list): Vector direction for definition of zero point (default [0,1])

_tools.fileListGenerator(numberString, folder, year=2018, format=None, instrument='CAMEA')[source]

Function to generate list of data files.

Parameters
  • numberString (-) – List if numbers separated with comma and dashes for sequences.

  • folder (-) – Folder of wanted data files.

Kwargs:

  • year (int): Year of wanted data files (default 2018)

  • format (str): format of data files (default None, but CAMEA if instrument is provided)

  • instrument (str): Instrument to be used to determine format string (default CAMEA)

Returns

List containing the full file string for each number provided.

Return type

  • list of strings

Example

>>> numberString = '201-205,207-208,210,212'
>>> files = fileListGenerator(numberString,'data/',2018)
['data/camea2018n000201.hdf', 'data/camea2018n000202.hdf',
'data/camea2018n000203.hdf', 'data/camea2018n000204.hdf',
'data/camea2018n000205.hdf', 'data/camea2018n000207.hdf',
'data/camea2018n000208.hdf', 'data/camea2018n000210.hdf',
'data/camea2018n000212.hdf']
_tools.findFlattenedIndex(sample, bins)[source]

Rewriting of numpy binning algorithm

Parameters
  • sample (-) – Position to be binned, of size N x D, where D is the dimensionality

  • bins (-) – Bins into which to perform the binning, of length D, where D is the dimensionality

_tools.generateLabel(vec, labels=['H', 'K', 'L'])[source]

Format a scattering vector with individual letters.

Parameters

vec (-) – Vector to be formated.

Kwargs:

  • lables (list): Letters to use for formating (default [‘H’,’K’,’L’])

_tools.generateLabelDirection(vec, labels=['H', 'K', 'L'])[source]

Format a scattering vector with letters according to the first non-zero direction.

Parameters

vec (-) – Vector to be formated.

Kwargs:

  • lables (list): Letters to use for formating (default [‘H’,’K’,’L’])

_tools.getNext(l, delete=True)[source]

get elements in itterator and delete list depending on flag

Parameters

l (-) – List or liste-like to loop over

Kwargs: delete (bool): If true, itteratively delete elements in list, else keep elements (default True)

_tools.histogramdd(sample, bins, weights, returnCounts=False)[source]

Restricted version of numpys multidimensional histogram function.

Parameters
  • sample (-) – Position in m-dimensional space

  • bins (-) – List of bins

  • weights (-) – List of weights where each entry has the length n

Kwargs:

  • returnCounts (bool): if True return also number of entries in each bin (default False)

_tools.invert(M)[source]

Invert non-square matrices as described on https://en.wikipedia.org/wiki/Generalized_inverse.

Parameters

M (-) – Matrix in question.

Returns

  • Left or right inverse matrix depending on shape of provided matrix.

_tools.minMax(x, axis=None)[source]

Return minimal and maximal of list.

Parameters

x (-) – Object from which min and max is to be found.

Kwargs:

  • axis (int): Axis or axes along which to operate (default 0)

Returns

Minimal value

  • max: Maximal value

Return type

  • min

_tools.my_timer_N(N=0)[source]

Timer function to measure time consumbtion of function.

Kwargs:

  • N (int): Number of itterations to perform.

Raises

- AttributeError

_tools.rotMatrix(v, theta, deg=True)[source]

Generalized rotation matrix.

Parameters
  • v (-) – Rotation axis around which matrix rotates

  • theta (-) – Rotation angle (by default in degrees)

Kwargs:

  • deg (bool): Whether or not angle is in degrees or radians (Default True)

Returns

  • 3x3 matrix rotating points around vector v by amount theta.

_tools.unitVector(v)[source]

Returns vector of unit length

_tools.vectorAngle(V1, V2)[source]

calculate angle between V1 and V2.

Parameters
  • V1 (-) – List or array of numbers

  • V2 (-) – List or array of numbers

Returns

Angle in degrees between the two vectors

Return type

  • theta (float)

_tools.writeToSpinWFile(file, position, spinWaveEnergy, spinWaveWidth, spinWaveAmplitude, EMin, EMax, spinWaveEnergyErr=None)[source]

Write fitted values for spin wave(s) into a SpinW readable format.

Parameters
  • files (-) – File into which the spin waves is to be saved

  • position (-) – HKL position of spin wave(s)

  • spinWaveEnergy (-) – Array with energy position of spin wave. For multiple spin waves fill with 0 if wave not found

  • spinWaveWidth (-) – Standard deviation of spin wave(s). For multiple spin waves fill with 0 if wave not found

  • spinWaveAmplitude (-) – Amplitude of spin wave(s). For multiple spin waves fill with 0 if wave not found

  • EMin (-) – Lowest energy measured in data [meV]

  • EMin – Highest energy measured in data [meV]

n is the number of spin waves m is the number of data points measured