MISC Module

This module contains miscellaneous functions for the calculation of several properties, and generally for the handling of NMR spectra.

klassez.misc.avg_antidiag(X)[source]

Given a matrix X without any specific structure, finds the closest Hankel matrix in the Frobenius norm sense by averaging the antidiagonals.

Parameters:
X2darray

Input matrix

Returns:
Xp2darray

Hankel matrix obtained from X

klassez.misc.binomial_triangle(n)[source]

Calculates the n-th row of the binomial triangle. The first row is n=1, not n=0.

Parameters:
nint

Row index

Returns:
row1darray

The n-th row of binomial triangle.

Examples

>>> binomial_triangle(4)
1 3 3 1
klassez.misc.calcres(fqscale)[source]

Calculates the frequency resolution of an axis scale, i.e. how many Hz is a “tick”.

Parameters:
fqscale1darray

Scale to be processed

Returns:
resfloat

The resolution of the scale

klassez.misc.cmap2list(cmap, N=10, start=0, end=1)[source]

Extract the colors from a colormap and returns it as a list.

Parameters:
cmapmatplotlib.Colormap Object

The colormap from which you want to extract the list of colors

Nint

Number of samples to extract

startfloat

Start point of the sampling. 0 = beginning of the cmap; 1 = end of the cmap.

endfloat

End point of the sampling. 0 = beginning of the cmap; 1 = end of the cmap.

Returns:
colorslist

List of the extracted colors.

klassez.misc.data2wav(data, filename='audiofile', cutoff=None, rate=44100)[source]

Converts an array of data in a .wav file. The data are converted in float32 format, then normalized to fit the (-1, 1) interval

Parameters:
data: ndarray

Data to listen to

filename: str

Filename for the .wav file, without extension

cutoff: float or None

Clipping borders for the audio. If None, no clipping is performed

rate: int

Sample rate in samples/sec

klassez.misc.detect_jumps(a)[source]

Detects where array a changes value.

Parameters:
a1darray

Mask

Returns:
startslist

Left border of the windows /pt

endslist

Right border of the windows /pt

klassez.misc.edit_checkboxes(checkbox, xadj=0, yadj=0, dim=100, color=None)[source]

Edit the size of the box to be checked, and adjust the lines accordingly.

Parameters:
checkboxmatplotlib.widgets.CheckBox Object

The checkbox to edit

xadjfloat

modifier value for bottom left corner x-coordinate of the rectangle, in checkbox.ax coordinates

yadjfloat

modifier value for bottom left corner y-coordinate of the rectangle, in checkbox.ax coordinates

dimfloat

Area of the square, in pixels. Default value is 25

colorstr or list or None

If it is not None, change color to the lines

klassez.misc.expformat(num, df=3)[source]

Converts numbers like 2e-5 to $2 \times 10^{-5}$, i.e. that will be displayed as \(2 \times 10^{-5}\) in elements that can render latex text.

Parameters:
numfloat

Number to convert

dfint

Number of decimal figures to consider

Returns:
str_numstr

Processed string

klassez.misc.find_nearest(array, value)[source]

Finds the value in array which is the nearest to value .

Parameters:
array1darray

Self-explanatory

valuefloat

Value to be found

Returns:
valfloat

The closest value in array tovalue

klassez.misc.freq2ppm(x, B0=701.125, o1p=0)[source]

Converts x from Hz to ppm.

Parameters:
xfloat

Value to be converted

B0float

Field frequency, in MHz. Default: 700 MHz

o1pfloat

Carrier frequency, in ppm. Default: 0.

Returns:
yfloat

The converted value

klassez.misc.get_datadir_filename(in_file, isexp=True)[source]

Computes the attributes datadir and filename to feed in the Spectra classes.

If in_file is a dictionary of acqusition parameters, datadir is the current working directory and filename='dict'. In any other case, datadir is the absolute path to the directory that contains the raw FID, and filename is the name of the last directory. Example: if the path to the FID is /path/to/dataset/expno/fid, datadir = '/path/to/dataset/expno/fid', filename = expno.

Parameters:
in_filestr or Path or dict

Path to the dataset (also relative works) or dictionary of acquisition parameters

isexpbool

For the correct computation of the filename, you have to specify if it is a real (True) or simulated (False) dataset

Returns:
datadirstr

Absolute path to the dataset

filenamestr

Filename of the spectrum

klassez.misc.get_extent(data)[source]

Compute the extent of an array as np.max(data) - np.min(data).

Parameters:
datandarray

Input data

Returns:
extentfloat

max(data) - min(data)

klassez.misc.get_ylim(data_inp, x=None, lims=None)[source]

Calculates the y-limits of ax as follows:

  • Bottom: min(data) - 0.05 * ``height

  • Top: max(data) + 0.05 * ``height

where height = max(data) - min(data).

Parameters:
data_inpndarray or list

Input data. If it is a list, data_inp is converted to array.

x1darray

Scale on where to evaluate the limits. If None, the point index scale is used

limstuple or None

Limits on x to consider for the evaluation of the limits. If None, the whole array is used.

Returns:
limstuple

Bottom, Top

klassez.misc.hankel(data, n=None)[source]

Computes a Hankel matrix from data. If data is a 1darray of length N, computes the correspondant Hankel matrix of dimensions (N-n+1, n). If data is a 2darray, computes the closest Hankel matrix in the Frobenius norm sense by averaging the values on the antidiagonals.

Parameters:
data1darray or 2darray

Vector to be Hankel-ized, of length N

nint

Number of columns that the Hankel matrix will have

Returns:
H2darray

Hankel matrix of dimensions (N-n+1, n)

klassez.misc.hz2pt(fqscale, hz)[source]

Converts hz from frequency units to points, on the basis of its scale.

Parameters:
fqscale1darray

Scale to be processed

hzfloat

Value to be converted

Returns:
ptfloat

The frequency value converted in points

klassez.misc.in2px(*in_args)[source]

Converts a sequence of numbers from inches to pixels by multiplying times 96.

Parameters:
in_argssequence of floats

Values in inches to convert

Returns:
px_argstuple of ints

Values in pixels

klassez.misc.key_to_limits(keys)[source]

Converts the key of a dictionary that identifies for a ppm range to the actual limits to be used.

Parameters:
keysstr or list of str

Format of the string to process: 'ppm1:ppm2'

Returns:
limitsndarray

Limits of the form [[ppm1, ppm2] for _ in len(keys)]

klassez.misc.lenslice(a)[source]

Calculates the length of a slice, i.e. the length an array would have when sliced with this slice.

Parameters:
aslice

Slice of which to calculate the length

Returns:
lengthint

Length of the slice

klassez.misc.limits_to_key(limits)[source]

Converts the key of a dictionary that identifies for a ppm range to the actual limits to be used.

Parameters:
limitsndarray

Limits of the form [[ppm1, ppm2] for _ in len(keys)]

Returns:
keysstr or list of str

Format of the string to process: 'ppm1:ppm2'

klassez.misc.listsqueeze(lst)[source]

Removes empty annidated lists.

Parameters:
lstilist

List to process

Returns:
alist

Squeezed list

klassez.misc.load_ser(path, TD1=1, BYTORDA=0, DTYPA=0, cplx=True)[source]

Reads a binary file and transforms it in an array. The parameters BYTORDA and DTYPA can be found in the acqus file.

BYTORDA = 1

big endian

‘>’

BYTORDA = 0

little endian

‘<’

DTYPA = 0

int32

‘i4’

DTYPA = 2

float64

‘f8’

Parameters:
pathstr

Path to the file to read

TD1int

Number of experiments in the indirect dimension

BYTORDAint

Endianness of data

DTYPAint

Data type format

cplxbool

If True, the input data are interpreted as complex, which means that in the direct dimension there will be real and imaginary parts alternated.

Returns:
data2darray

Array of data.

klassez.misc.makeacqus_1D(dic)[source]

Given a NMRGLUE dictionary from a 1D spectrum (generated by nmrglue.bruker.read()), this function builds the acqus file with only the “important” parameters.

Parameters:
dicdict

NMRglue dictionary returned by ng.bruker.read

Returns:
acqusdict

Dictionary with only few parameters

klassez.misc.makeacqus_1D_jeol(dic)[source]

Given a dictionary from a 1D spectrum (generated by jeol_parser.parse), this function builds the acqus file with only the “important” parameters.

Parameters:
dicdict

Dictionary generated with jeol_parser.parse

Returns:
acqusdict

Dictionary with only few parameters

klassez.misc.makeacqus_1D_oxford(dic)[source]

Given a NMRGLUE dictionary from a 1D spectrum (generated by nmrglue.jcampdx.read()), this function builds the acqus file with only the “important” parameters.

Parameters:
dicdict

NMRglue dictionary returned by ng.jcampdx.read

Returns:
acqusdict

Dictionary with only few parameters

klassez.misc.makeacqus_1D_spinsolve(dic)[source]

Given a NMRGLUE dictionary from a 1D spectrum (generated by nmrglue.spinsolve.read()), this function builds the acqus file with only the “important” parameters. Be sure to get the info from all the configuration files!

Parameters:
dicdict

NMRglue dictionary returned by ng.spinsolve.read

Returns:
acqusdict

Dictionary with only few parameters

klassez.misc.makeacqus_1D_varian(dic)[source]

Given a NMRGLUE dictionary from a 1D spectrum (generated by nmrglue.varian.read()), this function builds the acqus file with only the “important” parameters.

Parameters:
dicdict

NMRglue dictionary returned by ng.varian.read

Returns:
acqusdict

Dictionary with only few parameters

klassez.misc.makeacqus_2D(dic)[source]

Given a NMRGLUE dictionary from a 2D spectrum (generated by nmrglue.bruker.read() ), this function builds the acqus file with only the “important” parameters.

Parameters:
dicdict

NMRglue dictionary returned by ng.bruker.read

Returns:
acqusdict

Dictionary with only few parameters

klassez.misc.makeacqus_pp3D(dic)[source]

Given a NMRGLUE dictionary from a 3D spectrum with two pseudo dimensions, (generated by nmrglue.bruker.read ), this function builds the acqus file with only the “important” parameters.

Parameters:
dicdict

NMRglue dictionary returned by ng.bruker.read()

Returns:
acqusdict

Dictionary with only few parameters

klassez.misc.mathformat(ax, axis='y', limits=(-2, 2))[source]

Apply exponential formatting to the given axis of the given figure panel. The offset text size is uniformed to the tick labels’ size.

Parameters:
ax: matplotlib.Subplot Object

Panel of the figure to edit

axis: str

‘x’, ‘y’ or ‘both’.

limits: tuple

tuple of ints that indicate the order of magnitude range outside which the exponential format is applied.

klassez.misc.merge_dict(*dics)[source]

Merge a sequence of dictionaries in a single dictionary.

Parameters:
dicssequence of dict

Dictionaries to merge

Returns:
merged_dictdict

Merged dictionary

klassez.misc.molfrac(n)[source]

Computes the “molar fraction” x of the array n. Also computes the total amount.

Parameters:
nlist or 1darray

list of values

Returns:
xlist or 1darray

molar fraction array

Nfloat

sum of all the elements in n

klassez.misc.nuc_format(nuc)[source]

Converts the 'nuc' key you may find in acqus in the formatted label, e.g. '13C' -> '$^{13}$C'

Parameters:
nucstr

Unformatted string

Returns:
fnucstr

Formatted string.

klassez.misc.polyn(x, c)[source]

Computes p(x), polynomion of degree n-1, where n is the number of provided coefficients.

Parameters:
x1darray

Scale upon which to build the polynomion

clist or 1darray

Sequence of the polynomion coeffiecient, starting from the 0-th order coefficient

Returns:
px1darray

Polynomion of degree n-1.

klassez.misc.ppm2freq(x, B0=701.125, o1p=0)[source]

Converts x from ppm to Hz.

Parameters:
xfloat

Value to be converted

B0float

Field frequency, in MHz. Default: 700 MHz

o1pfloat

Carrier frequency, in ppm. Default: 0.

Returns:
yfloat

The converted value

klassez.misc.ppmfind(ppm_scale, value)[source]

Finds the exact value in ppm_scale.

Parameters:
ppm_scale1darray

Self-explanatory

valuefloat

The value to be found

Returns:
indexint

The index correspondant to V in ppm_scale

value_exactfloat

The closest value to value in ppm_scale

klassez.misc.pretty_scale(ax, limits, axis='x', n_major_ticks=10, *, minor_each=5, fmt=None)[source]

This function computes a pretty scale for your plot. Calculates and sets a scale made of n_major_ticks numbered ticks, spaced by minor_each unnumbered ticks. After that, the plot borders are trimmed according to the given limits.

Parameters:
axmatplotlib.AxesSubplot object

Panel of the figure of which to calculate the scale

limitstuple

limits to apply of the given axis. (left, right)

axisstr

‘x’ for x-axis, ‘y’ for y-axis, ‘z’ for z-axis

n_major_ticksint

Number of numbered ticks in the final scale. An oculated choice gives very pleasant results.

minor_eachint

Number of divisions for each interval between two major ticks

fmtstr

String-formatting for the numbers on the axis. Should be given as e.g. ‘.3f’

klassez.misc.px2in(*px_args)[source]

Converts a sequence of numbers from inches to pixels by multiplying times 96.

Parameters:
px_argssequence of ints

Values in pixels to convert

Returns:
in_argstuple of floats

Values in inches

klassez.misc.read_fid_acqus_1D(in_file, spect='bruker')[source]

Uses nmrglue to read inside in_file in search for 1D NMR data. Returns the complex FID and the dictionaries of setup parameters.

Parameters:
in_filestr or Path

Path where to find the data

spectstr

Data format. Valid options are: 'bruker', 'varian', 'magritek', 'oxford', 'jeol'

Returns:
fid1darray

FID of the dataset

acqusdict

Dictionary of acquisition parameters, required by klassez

ngdicdict

Complete set of acquisition, processing, and setup parameters.

klassez.misc.read_fid_acqus_2D(in_file, spect='bruker')[source]

Uses nmrglue to read inside in_file in search for 2D NMR data. Returns the complex FID and the dictionaries of setup parameters.

Parameters:
in_filestr or Path

Path where to find the data

spectstr

Data format. Valid options are: 'bruker' only.

Returns:
fid1darray

FID of the dataset

acqusdict

Dictionary of acquisition parameters, required by klassez

ngdicdict

Complete set of acquisition, processing, and setup parameters.

klassez.misc.readlistfile(datafile)[source]

Takes as input the path of a file containing one entry for each row. Returns a list of the aforementioned entries.

Parameters:
datafilestr

Path to a file that contains one entry for each row

Returns:
fileslist

List of the entries contained in the file

klassez.misc.set_fontsizes(ax, fontsize=10)[source]

Automatically adjusts the fontsizes of all the figure elements. In particular:

  • title = fontsize

  • axis labels = fontsize - 2

  • ticks labels = fontsize - 3

  • legend entries = fontsize - 4

Parameters:
axmatplotlib.Subplot Object

Subplot of interest

fontsizefloat

Starting fontsize

klassez.misc.set_ylim(ax, data_inp, x=None, lims=None)[source]

Sets the y-limits of ax by calling klassez.misc.get_ylim() to compute the values.

Parameters:
axmatplotlib.Subplot Object

Panel of the figure where to apply this scale

data_inpndarray or list

Input data. If it is a list, data_inp is converted to array.

x1darray

Scale on where to evaluate the limits. If None, the point index scale is used

limstuple or None

Limits on x to consider for the evaluation of the limits. If None, the whole array is used.

Returns:
None
klassez.misc.show_cmap(cmap, N=10, start=0, end=1, filename=None, ext='svg', dpi=300)[source]

Plot the colors extracted from a colormap.

Parameters:
cmapmatplotlib.Colormap Object

The colormap from which you want to extract the list of colors

Nint

Number of samples to extract

startfloat

Start point of the sampling. 0 = beginning of the cmap; 1 = end of the cmap.

endfloat

End point of the sampling. 0 = beginning of the cmap; 1 = end of the cmap.

filenamestr or None

Filename of the figure to be saved. If None, the figure is shown instead

extstr

Format for the figure to be saved

dpiint

Resolution of the figure in dots per inches

klassez.misc.split_acqus_2D(acqus)[source]

Split the acqus dictionary of a 2D spectrum into two separate 1D-like acqus dictionaries.

Parameters:
acqusdict

acqus dictionary of a 2D spectrum

Returns:
acqu1sdict

acqus dictionary of the indirect dimension

acqu2sdict

acqus dictionary of the direct dimension

klassez.misc.split_procs_2D(procs)[source]

Split the procs dictionary of a 2D spectrum into two separate 1D-like procs dictionaries.

Parameters:
procsdict

procs dictionary of a 2D spectrum

Returns:
proc1sdict

procs dictionary of the indirect dimension

proc2sdict

procs dictionary of the direct dimension

klassez.misc.sum_overlay(y1, y2, x0, x=None)[source]

Compute the sum of two arrays y1 and y2 of different dimensions. The sum starts at x0 (on the scale x) as left anchor point.

Parameters:
y11darray

Original array

y21darray

Array to sum

x0float

Value on the x scale as left anchor point

x1darray

Reference scale. If None, the index points is used.

Returns:
ym1darray

Summed arrays

klassez.misc.trim_data(ppm_scale, y, lims=None)[source]

Trims the frequency scale and correspondant 1D dataset y from sx (ppm) to dx (ppm).

Parameters:
ppm_scale1darray

ppm scale of the spectrum

y1darray

spectrum

limstuple

ppm values where to start and stop trimming

Returns:
xtrim1darray

Trimmed ppm scale

ytrim1darray

Trimmed spectrum

klassez.misc.trim_data_2D(x_scale, y_scale, data, xlim=None, ylim=None)[source]

Trims data and the scales according to xlim and ylim. Returns the trimmed data and the correspondant trimmed scales.

Parameters:
x_scale: 1darray

Scale for the rows of data

y_scale: 1darray

Scale for the columns of data

data: 2darray

Data to be trimmed

xlim: tuple

Limits for x_scale (L, R)

ylim: tuple

Limits for y_scale (L, R)

Returns:
trimmed_x: 1darray

Trimmed x_scale

trimmed_y: 1darray

Trimmed y_scale

trimmed_data: 2darray

Trimmed data

klassez.misc.unhankel(H)[source]

Concatenates the first row and the last column of the matrix H, which should have Hankel-like structure, so to build the array of independent parameters.

Parameters:
H2darray

Hankel-like matrix

Returns:
h1darray

First row and last column, concatenated

klassez.misc.write_acqus_1D(acqus, path='sim_in_1D')[source]

Writes the input file for a simulated spectrum, basing on a dictionary of parameters.

Parameters:
acqusdict

The dictionary containing the parameters for the simulation

pathstr, optional

Directory where the file will be saved.

klassez.misc.write_acqus_2D(acqus, path='sim_in_2D')[source]

Writes the input file for a simulated spectrum, basing on a dictionary of parameters.

Parameters:
acqusdict

The dictionary containing the parameters for the simulation

pathstr, optional

Directory where the file will be saved.

klassez.misc.write_ser(fid, path=None, BYTORDA=0, DTYPA=0, overwrite=True, filename=None, cplx=True)[source]

Writes the FID file in directory path, in a TopSpin-readable way (i.e. little endian, int32). The binary file is named ‘fid’ if 1D, ‘ser’ if multiD. The parameters BYTORDA and DTYPA can be found in the acqus file.

BYTORDA = 1

big endian

‘>’

BYTORDA = 0

little endian

‘<’

DTYPA = 0

int32

‘i4’

DTYPA = 2

float64

‘f8’

Parameters:
fidndarray

FID array to be written

pathstr or Path

Directory where to save the file. If None, the current working directory is used

BYTORDAint

little/big endian

DTYPAint

int/float

overwritebool

Overwrite existing directory

filenamestr

Name for the file

klassez.misc.zero_crossing(array, after=False)[source]

Find the indices where the elements in the array change sign. The identified positions are the ones before the sign changes. This behavior can be modified by setting after=True.

Parameters:
array1darray

Data to analyze

afterbool

If True, returns the indices of the element after the sign change; if False, the indices before.

Returns:
zerocross1darray

Position of the zero-crossing, according to ‘after’