pyrexMD.misc

pyrexMD.misc.classes

Hint

This module is a collection of general classes which are used frequently to streamline pyrexMD.

class pyrexMD.misc.classes.CONFIG(dict_=None, **kwargs)[source]

Bases: object

Class to store config data.

deepcopy()[source]

Return deep copy of object.

deepcopy_without(keys)[source]

Return deep copy of cfg object but without passed keys.

Parameters

keys (str, list, tuple) –

str: single key
list, tuple: multiple keys

items()[source]

Return dict items (key-value pairs).

keys()[source]

Return dict keys.

pop(key)[source]

remove key from dict and return its value

print_config()[source]

Print and return stored data in table format with “key” and “value” columns.

update_by_alias(alias='', key='', key_ndx=None, **kwargs)[source]

Update key value for an alias if alias is in kwargs.

Detailed Example:
default = {“colors”: [“g”, “r”],
“ms”: 1}
alias_dict = {“color_positive”: “teal”,
“color_negative”: “orange”,
“markersize”: 5}
cfg = misc.CONFIG(default, **alias_dict)
cfg.print_config()
>> key value
colors [‘g’, ‘r’]
ms 1
color_positive teal
color_negative orange
markersize 5

cfg.update_by_alias(alias=”markersize”, key=”ms”, **alias_dict)
cfg.update_by_alias(alias=”color_positive”, key=”colors”, key_ndx=0, **alias_dict)
cfg.update_by_alias(alias=”color_negative”, key=”colors”, key_ndx=1, **alias_dict)
cfg.print_config()
>> key value
colors [‘teal’, ‘orange’]
ms 5
color_positive teal
color_negative orange
markersize 5
update_config(dict_=None, **kwargs)[source]

Update config object by passing a dict, kwargs or both.

values()[source]

Return dict values.

exception pyrexMD.misc.classes.Error[source]

Bases: Exception

Base class for exceptions

class pyrexMD.misc.classes.HiddenPrints(verbose=False)[source]

Bases: object

Class to hide print commands.

Parameters

verbose (bool) –

True: show prints
False: hide prints (default)

Example

with HiddenPrints():
print(“This print is hidden”)
with HiddenPrints(verbose=True):
print(“This print is shown”)
This print is shown
class pyrexMD.misc.classes.HiddenPrints_ALL(verbose=False)[source]

Bases: object

Class to hide all stdout and stderr prints.

Parameters

verbose (bool) –

True: show prints
False: hide prints (default)

Example

with HiddenPrints_ALL():
print(“This print is hidden”)
with HiddenPrints(verbose=True):
print(“This print is shown”)
This print is shown
class pyrexMD.misc.classes.TIMER[source]

Bases: object

exception pyrexMD.misc.classes.dtypeError(arg, dtype)[source]

Bases: Exception

Base class for dtype exceptions

Example

>> misc.dtypeError(“source”, “str”)
TypeError: <source> must be str
pyrexMD.misc.classes.timeit(timer=None, msg='elapsed time:')[source]

Test elapsed time of a process

Parameters
  • timer (None, TIMER CLASS) –

  • msg (str) – message

Returns

timer (TIMER CLASS)

Example

t = TIMER()
timeit(t)
<code>
timeit(t)

pyrexMD.misc.func

Hint

This module is a collection of miscellaneous functions which are used frequently. Included functions may contain modified versions of small existing functions to extend their default behavior in order to streamline pyrexMD.

pyrexMD.misc.func.autodetect_header(fin)[source]

Autodetects header.

Parameters

fin (str) – input file (path)

Returns

header_rows (int)

pyrexMD.misc.func.cd(path, verbose=True)[source]

Change directory.

Parameters
  • path (str) – directory path

  • verbose (bool) – print message (‘Changed directory to: …’)

Returns

realpath (str)

realpath of changed directory

pyrexMD.misc.func.cp(source, target, create_dir=True, verbose=True)[source]

Copy file(s) from <source> to <target>. Will overwrite existing files and directories.

Parameters
  • source (str, list, array) – source path or list of source paths

  • target (str) – target path

  • create_dir (bool) –

  • verbose (bool) –

Returns

target (str)

target realpath

pyrexMD.misc.func.cprint(msg, color=None, on_color=None, attr=None, **kwargs)[source]

Modified function of termcolor.cprint(). Apply colored print.

Parameters
  • msg (str) –

  • color (None, str) – “grey”, “red”, “green”, “yellow”, “blue”, “magenta”, “cyan”, “white”

  • on_color (None, str) – “on_grey”, “on_red”, “on_green”, “on_yellow”, “on_blue”, “on_magenta”, “on_cyan”, “on_white”

  • attr (None, list) –

    attributes list
    bold, dark, underline, blink, reverse, concealed

Keyword Arguments
  • cprint_color (None, str) – alias for color (with higher priority)

  • sep (str) – string inserted between values, default a space.

  • end (str) – string appended after the last value, default a newline.

  • file (str) – a file-like object (stream); defaults to the current sys.stdout.

  • flush (bool) – whether to forcibly flush the stream.

pyrexMD.misc.func.flatten_array(x)[source]

Returns flattened array of x.

Parameters

x (array, array of arrays) –

Returns

flattened_array (array)

pyrexMD.misc.func.get_PDBid(ref)[source]

Obtains PDB id from ref by splitting its path and searching for alpha numerical (alnum) strings with length 4.

Parameters

ref (str, universe, atomgrp) – reference structure

Returns

PDBid (str)

if ref path contains one unique alnum string with length 4

PDBid (list)

if ref path contains multiple unique alnum strings with length 4

None (None)

else

pyrexMD.misc.func.get_base(_str)[source]

Get base (i.e. everything except extension) of string “_str”.

Parameters

_str (str) –

Returns

base (str)

base of _str

Example

>> get_base(“random_plot.png”)
“random_plot”
pyrexMD.misc.func.get_cutoff_array(array, cut_min=None, cut_max=None)[source]

Applies cutoff on array and returns array with values within cutoff range as well as the corresponding indices.

Parameters
  • array (array/list) –

  • cut_min (None, int, float) – min value for cutoff

  • cut_max (None, int, float) – max value for cutoff

Returns

cutoff_array (array, list)

array with values within cutoff

cutoff_array_ndx (array, list)

coresponding indices to map correctly

Example

array = list(range(10,20))
cut_min, cut_max = 12, 16
cutoff_array, cutoff_array_ndx = misc.get_cutoff_array(array, cut_min, cut_max)
print(cutoff_array)
>> [12, 13, 14, 15, 16]
print(cutoff_array_ndx)
>> [2, 3, 4, 5, 6]
pyrexMD.misc.func.get_extension(_str)[source]

Get “.ext” (extension) of string “_str”.

Parameters

_str (str) –

Returns

ext (str)

extension of _str

Example

>> get_extension(“random_plot.png”)
“.png”
pyrexMD.misc.func.get_filename(path, search_file=True)[source]

get filename (removes prefix of realpath of <path>).

Parameters
  • path (str) –

  • search_file (bool) –

    True: use <path> as search pattern to search for existing file
    -> remove prefix if only 1 match found to obtain existing filename
    False: just remove prefix of given <path>

Returns

filename (str)

pyrexMD.misc.func.get_percentile(data, p, prec=2, **kwargs)[source]

Alias function of np.percentile(). Get value (or score) below which p% of the observations may be found.

Parameters
  • data (array-like) –

  • p (int, float) – percent value ~ range 0-100

  • prec (None, int) – rounding precision

Returns

percentile (int, float)

pyrexMD.misc.func.get_precision(number)[source]

Returns leading precision of number.

  • convert float to string

  • find position of decimal point relative to the length of the string

Parameters

number (int, float) –

Returns

precision (int)

Example

>> get_precision(5.00000)
1
>> get_precision(5.12300)
3
pyrexMD.misc.func.get_quantile(data, p, prec=2, **kwargs)[source]

Alias function of np.quantile(). Get value (or score) below which p% of the observations may be found.

Parameters
  • data (array-like) –

  • p (int, float) – percent value ~ range 0-1

  • prec (None, int) – rounding precision

Returns

quantile (int, float)

pyrexMD.misc.func.get_ranked_array(array, reverse=False, verbose=True, **kwargs)[source]

Returns ranked array (decreasing order) and the corresponding element indices of the input array.

Parameters
  • array (array, list) – array-like object

  • reverse (bool) –

    False: decending ranking order (high to low)
    True: ascending ranking order (low to high)

  • verbose (bool) – print table with RANKED_VALUES, RANKED_NDX

Keyword Arguments
  • prec (None, int) –

    None: rounding off
    int: rounding on

  • spacing (int) –

    spacing between columns (via “”.expandtabs(spacing))
    8: default t width

  • verbose_stop (None, int) – stop printing after N lines

Returns

RANKED_VALUES (array)

ranked values

RANKED_NDX (array)

corresponding indices

Example

>> A = np.array([1, 3, 2, 4])
>> get_ranked_array(A, verbose=False)
(array([4, 3, 2, 1]), array([3, 1, 2, 0]))
pyrexMD.misc.func.get_slice_indices(list1, list2)[source]

Get slice indices of two lists (mainlist and sublist) where sublist is a slice of mainlist, e.g: sublist = mainlist[slice_ndx1:slice_ndx2]

Parameters
  • list1 (list, array) – mainlist or sublist

  • list2 (list, array) – mainlist or sublist

Returns

slice_ndx1 (int)

first slice index (“start”)

slice_ndx2 (int)

second slice index (“end”)

pyrexMD.misc.func.get_sorted_array(array, reverse=False, verbose=True, **kwargs)[source]

Returns sorted array (increasing order) and the coresponding element indices of the input array.

Parameters

array (array, list) – array-like object

Returns

SORTED_VALUES (array)

sorted array

SORTED_NDX (array)

corresponding indices

reverse (bool):
False: ascending ranking order (low to high)
True: decending ranking order (high to low)

verbose (bool): print table with RANKED_VALUES, RANKED_NDX

Keyword Arguments
  • prec (None, int) –

    None: rounding off
    int: rounding on

  • spacing (int) –

    spacing between columns (via “”.expandtabs(spacing))
    8: default t width

  • verbose_stop (None, int) – stop printing after N lines

Example

>> A = np.array([1, 3, 2, 4])
>> get_sorted_array(A)
(array([1, 2, 3, 4]), array([0, 2, 1, 3]))
pyrexMD.misc.func.get_subarray(array, ndx_sel)[source]

Returns subarray of <array> for items with indices <ndx_sel>.

Parameters
  • array (array, list) – array-like object

  • ndx_sel (array, list) – index selection

Returns

subarray (array)

subarray of array

pyrexMD.misc.func.get_subarray_start_ndx(array, subarray)[source]

Returns start index of <array> at which <subarray> matches.

Parameters
  • array (list, array) –

  • subarray (list, arr) –

Returns

start_ndx (None, int)
None: arrays do not match
int: starting index of <array> at which <subarray> matches

pyrexMD.misc.func.get_substrings(string, seperators=['/', '_', '.', ':', ';', ' '], reverse=False)[source]

get substrings of string by removing each seperator.

Parameters
  • string (str) –

  • seperators (list) –

  • reverse (bool) – return substrings in reversed order

Returns

substrings (list)

list of substrings

Example

>> get_substrings(“split/this_string.into:parts”)
[‘split’, ‘this’, ‘string’, ‘into’, ‘parts’]
>> get_substrings(“split/this_string.into:parts”, reverse=True)
[‘parts’, ‘into’, ‘string’, ‘this’, ‘split’]
pyrexMD.misc.func.insert_str(str1, str2, sep, loc='after')[source]

Insert str2 in str1.

Parameters
  • str1 (str) – base string

  • str2 (str) – append string

  • sep (str) – seperator

  • loc (str) – insert location: ‘before’ or ‘after’ first seperator in str1

Returns

_str (str)

new string

pyrexMD.misc.func.joinpath(filedir, filename, create_dir=True, realpath=True)[source]

Returns joined path of (filedir + filename).

Special case:

filename contains relative or absolute path: ignore filedir input

Reason:

intention is to save/load file under the path “filename”

Parameters
  • filedir (str) – relative or absolute path of file directory

  • filename (str) – filename or relative/absolute filepath

  • create_dir (bool) – create filedir (w/o creating parent directories)

  • realpath (bool) – return realpath

Returns

file_path (str)

pyrexMD.misc.func.mkdir(path, verbose=True)[source]

Make directory.

Parameters
  • path (str) – directory path

  • verbose (bool) – print message (‘New folder created: …’)

Returns

realpath (str)

realpath to new directory

Example

>> cwd = /home/user/
>> mkdir(‘Test1’)
New folder created: /home/user/Test1
>>mkdir(‘../Test2’)
New folder created: /home/Test2
pyrexMD.misc.func.norm_array(array, start_value=0)[source]

norm array

  • starts with <start_value>

  • deltaValue is fixed to 1 (i.e. array[i]- array[i+1] = 1)

Parameters

array (list, array) –

Returns

normed_array (list, array)

pyrexMD.misc.func.percent(num, div, prec=2)[source]

Returns the percentage of num/div as float

Parameters
  • num (int) – numerator

  • div (int) – divisor

  • prec (None, int) – rounding precision

Returns

p (float)

p = 100 * num/div

pyrexMD.misc.func.print_table(data=[], prec=3, spacing=8, dtype=None, verbose=True, verbose_stop=30, warn=True, **kwargs)[source]

Prints each item of “data” elementwise next to each other as a table.

Parameters
  • data (list of lists) – table content, where each list corresponds to one column

  • prec (None, int) –

    None: rounding off
    int: rounding on

  • spacing (int) –

    spacing between columns (via “”.expandtabs(spacing))
    8: default t width

  • dtype (None, dtype) – dtype of table values after rounding

  • verbose (bool) – print table

  • verbose_stop (None, int) – stop printing after N lines.

  • warn (bool) – print/supress message “misc.print_table(): printed only N entries (set by verbose_stop parameter).”

Returns

table_str (str)

table formatted string. Can be used to save log files.

Example

letters = [“A”, “B”, “C”]
numbers = [1, 2, 3]
table = misc.print_table([letters, numbers])
>> A 1
B 2
C 3

# save table as log file:
with open(“table.log”, “w”) as fout:
fout.write(table)
pyrexMD.misc.func.read_DCA_file(DCA_fin, n_DCA, usecols=(0, 1), skiprows='auto', filter_DCA=True, RES_range=[None, None])[source]

Read DCA file and return DCA pairs IJ.

Parameters
  • DCA_fin (str) – DCA input file (path)

  • n_DCA (int) – number of used DCA contacts

  • usecols (tuple, list) – columns containing the RES pairs in DCA_fin

  • skiprows ('auto', int) –

    ignore header rows of DCA_fin
    ’auto’ or -1: auto detect

  • filter_DCA (bool) –

    True: ignore DCA pairs with abs(i-j) < 4
    False: use all DCA pairs w/o applying filter

  • RES_range (None) –

    Use RES within [RES_min, RES_max] range.
    None: do not narrow down RES range

Returns

DCA_PAIRS (list)

DCA pairs IJ

DCA_PAIRS_RES_range (list)

[RES_min, RES_max] of DCA_PAIRS (not input RES_range values)

pyrexMD.misc.func.read_file(fin, sep=None, usecols=(0, 1), n_rows=None, skiprows='auto', dtype=<class 'float'>)[source]

Read file and return tuple of np.arrays with data for specified columns.

Parameters
  • fin (str) – input file (path)

  • sep (None, str) –

    seperator of columns.
    None: whitespace

  • usecols (int, sequence) – data columns

  • n_rows (None, int) – lenght of returned data (AFTER skipping rows)

  • skiprows (None, 'auto', int) –

    ignore header rows of fin
    ’auto’ or -1: auto detect

  • dtype (dtype cls, list, tuple) –

    data type of returned np.array
    dtype cls: all data types are same
    list/tuple of dtype cls: specify dtype of each data column

    valid dtypes:
    str, int, float, complex

Returns

data_array (array)

if usecols is int ~ data of one column specified in usecols

data_list (list)

if usecols is list ~ data of each column specified in usecols

Example

# single columns per fin
X = read_file(‘data.txt’, usecols=0)
Y = read_file(‘data.txt’, usecols=1)
# multiple columns per fin
X,Y = read_file(‘data.txt’, usecols=(0,1))
pyrexMD.misc.func.rm(path, pattern=None, verbose=True)[source]

Alias function of remove(). Remove file(s) from path.

Note

pattern can be implemented into path variable directly.

Parameters
  • path (str) – directory path

  • pattern (None, str) –

    pattern
    None: check for files with path only
    str: check for files with joined path of path + pattern

  • verbose (bool) – print message (‘removed file: … ‘)

pyrexMD.misc.func.round_down(number, base=1)[source]
Parameters
  • number (float/int) –

  • base (float/int) –

Example

for i in range(11):
print(i, round_down(i,5))
(0, 0)
(1, 0)
(2, 0)
(3, 0)
(4, 0)
(5, 5) # does not round down if remainder is zero
(6, 5)
(7, 5)
(8, 5)
(9, 5)
(10, 10)
pyrexMD.misc.func.round_object(object, prec=3, dtype=None)[source]
Parameters
  • object (list, array) –

    single list/array
    list of lists/arrays
    array of lists/arrays

  • prec (int) – rounding precision

  • dtype (None, dtype) – return object values as specific data type

Returns

new_object (list, array)

same structure as object, but with rounded values.

pyrexMD.misc.func.round_to_base(number, base=1)[source]

Round up or down depending on smallest difference to base.

Parameters
  • number (float/int) –

  • base (float/int) –

pyrexMD.misc.func.round_up(number, base=1)[source]
Parameters
  • number (float/int) –

  • base (float/int) –

Example

for i in range(11):
print(i, round_up(i,5))
(0, 0)
(1, 5)
(2, 5)
(3, 5)
(4, 5)
(5, 5) # does not round up if remainder is zero
(6, 10)
(7, 10)
(8, 10)
(9, 10)
(10, 10)
pyrexMD.misc.func.save_table(data=[], filename='', header='', default_dir='./logs', prec=3, verbose=True, verbose_stop=None, **kwargs)[source]

Executes misc.print_table() and saves the returned table string as a log file.

Parameters
  • data (list of lists) – table content, where each list corresponds to one column

  • filename (str) – filename or realpath

  • header (str) – header for log file, e.g. column descriptions

  • default_dir (str) –

  • prec (None, int) –

    None: rounding off
    int: rounding on

  • verbose (bool) –

  • verbose_stop (None, int) –

Keyword Arguments

save_as (str) – alias of filename

Returns

realpath (str)

path to log file

pyrexMD.misc.func.split_lists(A, n, remap=False)[source]

split list A into two lists B1 and B2 according to A = B1 + B2, where B2 contains every n-th element of A.

Parameters
  • A (int, list, array) –

    int: initialize A according to: A = list(range(A))
    list, array: input list A which should be split

  • n (int) – split every n-th element of A into B2

  • remap (bool) – remap Bi according to: Bi = range(0, len(Bi))

Returns

A (list)

input list A

B1 (list)

partial list B1

B2 (list)

partial list B2 (contains every n-th element of A)

pyrexMD.misc.plot

Hint

This module is a collection of plot-related functions which are used frequently. Included functions may contain modified versions of small existing functions to extend their default behavior in order to streamline pyrexMD.

pyrexMD.misc.plot.INIT_append_docstrings()[source]

Some functions in this module have split up docstrings. The intention of this design choice is to assure that docstrings which rely on each other are matching and always up to date. This function is executed ONCE upon initialization of the module and appends the missing parts.

pyrexMD.misc.plot.add_cbar(ax, cbar_ax=None, cmap=None, bounds='auto', location='right', orientation='vertical', **kwargs)[source]

Draw colorbar relative to existing ax.

Parameters
  • ax (matplotlib.axes._subplots.Axes) –

  • cbar_ax (None/matplotlib.axes._axes.Axes) –

    colorbar ax
    None: add new cbar_ax relative to existing ax
    matplotlib.axes._axes.Axes: use passed cbar_ax (can be created using misc.add_cbar_ax()).

  • cmap (None, LinearSegmentedColormap) – output of create_cmap()

  • bounds (str, list) –

    str: “auto”: apply bounds based on kws ‘orientation’ and ‘location’.
    list: [x0, y0, height, width] using axes coordinates.
    Ignores kws ‘orientation’ and ‘location’.

  • location (str) – “right”, “bottom”, “left”, “top”

  • orientation (str) – “vertical”, “horizontal”

Keyword Arguments
  • vmin (None, float) – colorbar min value

  • vmax (None, float) – colorbar max value

  • cbar_label/label (None, str) –

  • cbar_fontweight/fontweight (None, str) – “bold”, “normal”

  • cbar_location/location (None, str) – “right”, “bottom”, “left”, “top”

  • cbar_orientation/orientation (None, str) – “vertical”, “horizontal”

Returns

cbar (matplotlib.colorbar.Colorbar)

color bar

pyrexMD.misc.plot.add_cbar_ax(ax, bounds='auto', location='right', orientation='vertical')[source]

Add colorbar ax relative to existing ax.

Parameters
  • ax (matplotlib.axes._subplots.Axes) –

  • bounds (str,list) –

    str: “auto”: apply bounds based on kws ‘orientation’ and ‘location’.
    list: [x0, y0, height, width] using axes coordinates.
    Ignores kws ‘orientation’ and ‘location’.

  • location (str) – “right”, “bottom”, “left”, “top”

  • orientation (str) – “vertical”, “horizontal”

Returns

cbar_ax (matplotlib.axes._axes.Axes)

colorbar ax

pyrexMD.misc.plot.align_limits(ref_ax, target_ax, apply_on='y', new_lim=[])[source]
  • Read limits of ref_ax and asign them to target_ax

  • if “new_lim” is passed: assign new values to both ref_ax and target_ax

Parameters
  • ref_ax (matplotlib.axes._subplots.Axes) –

  • target_ax (matplotlib.axes._subplots.Axes) –

  • apply_on (str) – ‘x’, ‘y’, ‘xy’

  • new_lim (list) – assign new values to both ref_ax and target_ax

pyrexMD.misc.plot.align_ticklabels(ref_ax, target_ax, apply_on='y', new_ticklabels=[])[source]
  • Read ticklabels of ref_ax and asign them to target_ax

  • if “new_ticklabels” is passed: assign new values to both ref_ax and target_ax

Parameters
  • ref_ax (matplotlib.axes._subplots.Axes) –

  • target_ax (matplotlib.axes._subplots.Axes) –

  • apply_on (str) – ‘x’, ‘y’, ‘xy’

  • new_ticklabels (list) – assign new values to both ref_ax and target_ax

pyrexMD.misc.plot.align_ticks(ref_ax, target_ax, apply_on='y', new_ticks=[])[source]
  • Read ticks of ref_ax and asign them to target_ax

  • if “new_ticks” is passed: assign new values to both ref_ax and target_ax

Parameters
  • ref_ax (matplotlib.axes._subplots.Axes) –

  • target_ax (matplotlib.axes._subplots.Axes) –

  • apply_on (str) – ‘x’, ‘y’, ‘xy’

  • new_ticks (list) – assign new values to both ref_ax and target_ax

pyrexMD.misc.plot.apply_shared_axes(ax, grid)[source]
  • removes xticklabels of all axes except for bottom row.

  • removes yticklabels of all axes except for left column.

Parameters
  • ax (class, list) – ax or list of axes ~ matplotlib.axes._subplots.Axes

  • grid (list) – grid of figure (example: grid=[2,2] for 2x2 figure or grid =[3,2] for 3x2 figure)

pyrexMD.misc.plot.autoapply_limits(fig_or_ax, margin=0.05)[source]

Apply plt.xlim() and plt.ylim() on each axis object based on its xmin, xmax, ymin, ymax values.

Note

  • use only after plotting data

  • currently works only with Line2D data

Parameters
  • fig_or_ax (matplotlib.figure.Figure/matplotlib.axes._subplots.Axes) –

  • margin (float) – extra margin on upper limits, where margin=0.01 equals 1% of xmax and ymax

Returns

xlim (list)

if fig_or_ax is axis

ylim (list)

if fig_or_ax is axis

XLIM (list of lists)

if fig_or_ax is figure

YLIM (list of lists)

if fig_or_ax is figure

Example

>> fig, ax = misc.figure(grid=[2,2], hr=[1,1], wr=[2,1])
>> plt.sca(ax[0])
>> plt.plot([0,1,2], [0,4,4])
>> plt.plot([0,1,2], [0,10,10])
>> autoapply_limits(fig, margin=0.05)
([[0, 2.1], [0, 0], [0, 0], [0, 0]],
[[0,10.5], [0, 0], [0, 0], [0, 0]])
pyrexMD.misc.plot.cbar_set_ticks_position(cbar, location)[source]

Set ticks position of colorbar.

Parameters
  • cbar (matplotlib.colorbar.Colorbar) –

  • location (str) – “right”, “bottom”, “left”, “top”

pyrexMD.misc.plot.convert_ticklabels(axes, multiplier, apply_on='y', prec=0)[source]

Read ticklabels of axes and multiply with “multiplier”

Parameters
  • axes (list of matplotlib.axes._subplots.Axes) –

  • multiplier (int/float) – multiplier for conversion, ie: new_tickvalue = multiplier * old_tickvalue

  • apply_on (str) – ‘x’, ‘y’, ‘xy’

  • prec (int) –

    precision
    0: use integers with no decimal precision
    n: float with n decimal precision

pyrexMD.misc.plot.create_cmap(seq, vmin=None, vmax=None, ax=None)[source]

Return a LinearSegmentedColormap

Parameters
  • seq (sequence) – sequence of color strings and floats. The floats describe the color thresholds and should be increasing and in the interval (0,1).

  • vmin (float) – min value of cmap

  • vmax (float) – max value of cmap

  • ax (None, ax) – figure ax for adding colorbar

Returns

cmap (LinearSegmentedColormap)

Example

seq = [“lightblue”, 2/6, “lightgreen”, 3/6, “yellow”, 4/6, “orange”, 5/6, “red”] cmap = misc.create_cmap(seq, vmin=0, vmax=12)

pyrexMD.misc.plot.figure(num=None, figsize=(6.5, 4), dpi=None, grid=[1, 1], hr=[], wr=[], palette=None, n_colors=None, context='notebook', style='ticks', font_scale=0, despine=True, offset=0, **kwargs)[source]

Top level container for all the plot elements. Modified version of plt.figure() with gridspec and seaborn elements. “Example” below shows how to plot data by using misc.figure() and plt.sca() # set current axis

Parameters
  • num (int) – figure.number (to reuse the figure canvas)

  • figsize (tuple) –

  • dpi (None, int) –

    dpi settings of figure
    if monitor dpi is 100 and figure dpi is 300, then figure will be displayed
    on the monitor 3x larger (compared to printed version with e.g. 300 dpi printer).

  • grid (list) – nrows, ncols ~ height x width

  • hr (list) – height ratio of rows

  • wr (list) –

  • font_scale (float) –

  • palette (None, str, list, tuple) –

    None: use current palette
    str: name of the palette, see seaborn documentation
    list: list of colors
    tuple: tuple of colors

  • n_colors (None, int) –

    None: use default number of color cycles based on palette
    int: remap number of color cycles for the palette

  • context (None, dict, str) –

    Affects sizes and widths of the plot, e.g. labelsize,
    linesize, etc. See return values of sns.plotting_context() to get
    all valid dict settings.
    str:’notebook’: scaled by 1.0
    ’paper’: scaled by 0.8
    ’talk’: scaled by 1.3
    ’poster’: scaled by 1.6

  • style (None, dict, str) –

    Affects aesthetic style of the plots, e.g. axes color,
    grid display, etc. See return values of sns.axes_style() to get all
    valid dict settings.
    str:’ticks’, ‘dark’, ‘white’, ‘darkgrid’, ‘whitegrid’

  • despine (bool) –

    Remove the top and right spines from all axes. See sns.despine()
    documentation for individual axis spine removal.

  • offset (dict/int) –

    Absolute distance of spines. Use a dict to offset individual spines,
    e.g. offset={“bottom”:0, “left”:20}.

Returns

fig (class)

matplotlib.figure.Figure

ax (class, list)

ax or list of axes ~ matplotlib.axes._subplots.Axes

Example

fig, ax = misc.figure(grid=[2,2], hr=[1,1], wr=[2,1])
plt.sca(ax[0])
plt.plot([0,1,2], [0,4,4])
plt.plot([0,1,2], [0,10,10])
plt.sca(ax[2])
plt.plot([0,-1,-2], [0,-4,-4])
plt.plot([0,-1,-2], [0,-10,-10])
pyrexMD.misc.plot.hide_figure(fig_or_ax=None, num=None, close=True)[source]

Alias function of hide_plot(). “Hide” figure by setting its size to (0, 0) inches. If number is passed, apply on figure with that number.

Parameters
  • fig_or_ax (None, matplotlib.figure.Figure/matplotlib.axes._subplots.Axes) –

  • num (None, int) – if integer is passed, hide figure with this number

  • close (bool) – if True, close figure instead of just hiding

pyrexMD.misc.plot.hide_plot(fig_or_ax=None, num=None, close=True)

Alias function of hide_plot(). “Hide” figure by setting its size to (0, 0) inches. If number is passed, apply on figure with that number.

Parameters
  • fig_or_ax (None, matplotlib.figure.Figure/matplotlib.axes._subplots.Axes) –

  • num (None, int) – if integer is passed, hide figure with this number

  • close (bool) – if True, close figure instead of just hiding

pyrexMD.misc.plot.legend(labels=[''], handlecolors=[''], handlelength=1, handletextpad=None, loc=None, **kwargs)[source]

Alias function of plt.legend() with most frequently used parameters.

Parameters
  • labels (sequence of strings) –

  • handlescolors (list) –

  • handlelength (None/int/float) –

  • handletextpad (None/int/float) –

  • loc (str) –

    Location String Location Code
    ——————————-
    ‘best’ 0
    ’upper right’ 1
    ’upper left’ 2
    ’lower left’ 3
    ’lower right’ 4
    ’right’ 5
    ’center left’ 6
    ’center right’ 7
    ’lower center’ 8
    ’upper center’ 9
    ’center’ 10

Keyword Arguments
  • title (str) –

  • edgecolor (str) –

  • fancybox (bool) –

    True: legendbox with round edges
    False: legendbox with normal edges

class pyrexMD.misc.plot.number_base_factorization(num)[source]

Bases: object

Class to get 10base factorization of any number, e.g. 123 = 3*10^0 + 2*10^1 + 1*10^2

Example

>> x = number_base_factorization(123)
>> x() # show content of x
self.number: 123
self.sign: +
self.digits: [1, 2, 3]
self.pos_base10_factors: [3, 2, 1]
self.neg_base10_factors: None
pyrexMD.misc.plot.pickle_dump(obj, filename='', pickledir='./pickle', overwrite=True, verbose=True, **kwargs)[source]
bug: can’t dump figures which used the misc.add_cbar() or misc.add_cbar_ax() function

because of the use of ax.inset_axes().

Create pickle directory and pickle.dump object as “<pickledir>/<filename>.pickle”

Special cases:

  • filename contains relative path: ignores pickledir input

  • filename contains absolute path: ignores pickledir input

Reason:

intention is to dump file under the path “filename”

Parameters
  • obj (matplotlib.figure.Figure/<any object>) –

  • filename (str) –

    filename, hardcoded to add “.pickle” extension.
    Can be relative or absolute path including the filename.

  • pickledir (str) – default pickle directory

  • overwrite (bool) – overwrite pickle dumped file if it already exists

  • verbose (bool) –

Keyword Arguments

save_as (str) – alias of filename

Returns

filepath (str)

realpath of dumped .pickle file

pyrexMD.misc.plot.pickle_load(filename, pickledir='./pickle', plot=False)[source]

pickle.load figure from “<pickledir>/<filename>.pickle”. If the pickle file contains figure data, auto detects the figure type (i.e. it created using plt.plot(), plt.bar() or plt.barh()).

Warning

%matplotlib notebook backend leaves empty space below figure in jupyter notebook when closing figs which were loaded via pickle files.

Parameters
  • filename (str) – realpath to .pickle file or filename within pickledir

  • pickledir (str) – default pickle directory

  • plot (bool) –

Returns

ax_data (dict)

if pickle file is a figure object

line_data (list)

if pickle file is a figure object

rect_data (list)

if pickle file is a figure object

object (?)

else

Note

ax_data (dict)

dictionary containing specific axis data, see table below

key

value

description

ax_type (str)

“line plot”

ax was created using plt.plot()

“bar plot”

ax was created using plt.bar()

“barh plot”

ax was created using plt.barh()

xlim/ylim

tuple

content of ax.get_xlim()

xscale/yscale

str

content of ax.get_xscale()

xticks/yticks

array

content of ax.get_xticks()

x/yticklabels

list

text content of ax.get_xticklabels()

line_data (list)

list of dicts, which contain data about <matplotlib.lines.Line2D> objects with viable Keyword Args as shown in the table below

alpha

ls (linestyle)

mac (marker edgecolor)

xdata

color

lw (linewidth)

mfc (marker facecolor)

ydata

label

marker

ms (markersize)

rect_data (list)

list of dicts, which contain data about <matplotlib.patches.Rectangle> objects with viable Keyword Args as shown in the table below

alpha

fill

width

bbox

height

xy

bbox_points

label

ec (edgecolor)

ls (linestyle)

fc (facecolor)

lw (linewidth)

Hint

xy are the userland coordinates starting from bottom left rectangle corner (rectangle is defined by xy, width, height)

Example

ax_data, line_data, rect_data = pickle_load( < filename > )
# acces data
line_data[0][“xdata”]
line_data[0][“color”]
pyrexMD.misc.plot.pickle_plot(pickle_files=[], import_settings=True, xscale='auto', yscale='auto', align_ylim=True, hist_minorticks=False, **kwargs)[source]

Creates multifigure from loading pickle_files

Warning

data is first loaded -> creates a figure -> closed. However in jupyter %matplotlib notebook backend leaves empty space below figure when closing figs which were loaded via pickle. The empty space is only visible in the notebook (i.e. saving a pickle_plot figure is working fine.)

Parameters
  • pickle_files (str,list of str) – path to pickle file(s) containing the (sub)figure data

  • import_settings (bool) – apply settings (for line and rectangle objects) from imported pickle_files

  • xscale (str) –

    ‘auto’, ‘linear’, ‘log’, ‘symlog’, ‘logit’
    ’auto’: apply xscale of the used pickle_files

  • yscale (str) –

    ‘auto’, ‘linear’, ‘log’, ‘symlog’, ‘logit’
    ’auto’: apply yscale of the used pickle_files

  • align_ylim (bool) – align y axis limits of figures on the same row

  • hist_minorticks (bool) – turns minorticks (~logscale) for hist figure on/off

Hint

Args and Keyword Args of misc.figure() are valid.

Returns

fig (class)

matplotlib.figure.Figure

ax (class, list)

ax or list of axes ~ matplotlib.axes._subplots.Axes

pyrexMD.misc.plot.save_fig(filename, filedir='', create_dir=True, dpi=300)

general helpfunction

  • save current figure

  • print message “Saved figure as: …”

Parameters
  • filename (None, str) –

    None: do not save figure
    str: file name or realpath to file

  • filedir (str) – file directory

  • create_dir (bool) – create directory if it does not exist yet

  • dpi (int) – dpi settings

Returns

realpath (str)

realpath to saved figure

pyrexMD.misc.plot.savefig(filename, filedir='', create_dir=True, dpi=300)[source]

general helpfunction

  • save current figure

  • print message “Saved figure as: …”

Parameters
  • filename (None, str) –

    None: do not save figure
    str: file name or realpath to file

  • filedir (str) – file directory

  • create_dir (bool) – create directory if it does not exist yet

  • dpi (int) – dpi settings

Returns

realpath (str)

realpath to saved figure

pyrexMD.misc.plot.scatter(x, y, z=None, **kwargs)[source]

Creates scatter plot. Applies cmap for z values if z is passed.

Parameters
  • x (array) –

  • y (array) –

  • z (None, array) –

Keyword Arguments
  • figsize (tuple) – Defaults to (6.6, 5.6)

  • aspect ('auto', 'equal', int) –

    aspect ratio of figure. Defaults to ‘auto’.
    ’auto’: fill the position rectangle with data.
    ’equal’: synonym for aspect=1, i.e. same scaling for x and y.
    int: a circle will be stretched such that the height is int times the width.

  • marker (None, str) –

  • ms (None, int) – marker size

  • cmap (str) –

    colormap name, e.g. ‘virids’, ‘plasma’, ‘inferno’, ‘summer’, ‘winter’, ‘cool’, etc.
    You can reverse the cmap by appending ‘_r’ to the name.

  • vmin (None, float) – min value of cmap and colorbar

  • vmax (None, float) – max value of cmap and colorbar

  • cbar_label (None, str) –

  • xlabel (None, str) –

  • ylabel (None, str) –

Returns

fig (class)

matplotlib.figure.Figure

ax (class, list)

ax or list of axes ~ matplotlib.axes._subplots.Axes

pyrexMD.misc.plot.set_logscale_ticks(ax, apply_on='x', vmax=None, minorticks=True, **kwargs)[source]

Apply logscale ticks on ax. If vmax is specified, sets vmax as upper limit.

Parameters
  • ax (matplotlib.axes._subplots.Axes) –

  • apply_on (str) – “x”, “y”, “xy”

  • vmin (None, int, float) – highest logscale tick value

  • minorticks (bool) – display minorticks on/off

Keyword Arguments
  • xmin (None, int, float) –

  • xmax (None, int, float) –

  • ymin (None, int, float) –

  • ymax (None, int, float) –

pyrexMD.misc.plot.set_pad(fig_or_ax, xpad=None, ypad=None)[source]

Set pad (spacing) between axis and axis labels

Parameters
  • fig_or_ax (matplotlib.figure.Figure/matplotlib.axes._subplots.Axes) –

  • xpad (None, float) –

    spacing between xaxis and its labels
    None: use current settings

  • ypad (None, float) –

    spacing between yaxis and its labels
    None: use current settings

pyrexMD.misc.plot.setup_logscale_ticks(vmax)[source]

Setup majorticks and minorticks for logscale with ticks <= vmax.

Parameters

vmax (int, float) –

Returns

majorticks (list)

ticks at 1, 10, 100, 1000, etc.

minorticks (list):

ticks at 2, 3, 4,…, 8, 9, 20,30,40,…,80,90, etc.

pyrexMD.misc.plot.setup_ticks(vmin, vmax, major_base, minor_base=None)[source]

Setup axis ticks of a plot in vmin <= ticks <= vmax.

Parameters
  • vmin (int, float) –

  • vmax (int, float) –

  • major_base (int, float) –

  • minor_base (int, float) –

Returns

majorticks (list)

list with majorticks

minorticks (list)

list with minorticks