encodermap.plot package#

Submodules#

encodermap.plot.dashboard module#

EncoderMap’s dashboard. Explore and understand your MD data.

class Dashboard[source]#

Bases: object

property app_layout#
property debug#
property layout#
property local#
property navbar#
property placeholder#
run(*args, **kwargs)[source]#
update_theme(theme)[source]#
class DebugPage[source]#

Bases: object

property layout#
static run_code(value, state)[source]#
property text_area#
class LocalUploadTraj(main)[source]#

Bases: object

_placeholder = '    trajs = ["/path/to/traj1.xtc", "/path/to/traj2.xtc"]\n    tops = ["/path/to/traj1.pdb", "/path/to/traj2.pdb"]\n    common_str = ["traj1, "traj2"]\n    '#
load_trajs(upload_n_clicks, reset_n_clicks, linear_dimers_n_clicks, n_click_1am7, main_store, list_of_contents, list_of_names, list_of_dates, textarea_value, project_value)[source]#
class ProjectionPage(main)[source]#

Bases: InteractivePlotting

interact(click_on_plot, select_in_plot, relayoutdata, main_store)[source]#

Interactive elements:

  • Click on Scatter Point

  • Buttons:
    • switch between cluster and scatter

    • cluster

    • generate

  • slider

  • dropdown

  • Progress

Return type:

tuple[P, FigureWidget, Any]

property molStyles#
class ReplaceOpenWithStringIO[source]#

Bases: object

Tricks MDTraj to write the output into a StringIO object.

Inside a context-manager, this class will redefine the builtin oprn() function and overwrite the os.path.exists() function to use it as a sort-of str object.

close()[source]#
lower()[source]#

Functions will think, this is a str’s builtin lower() function.

Return type:

str

read()[source]#

Read from the StringIO object.

Return type:

str

write(*args, **kwargs)[source]#

Write into the StringIO object.

Return type:

None

class TopPage(main)[source]#

Bases: object

display_custom_aas(top)[source]#
display_plot(top_value, radio_value, dummy, rangeslider_value)[source]#
Return type:

Any

display_top(json_values, top_value, n_clicks, main_store, dummy)[source]#
fill_dropdown(main_store, search_value)[source]#
get_options()[source]#
class TrajPage(main)[source]#

Bases: object

display_traj(*args, **kwargs)[source]#
display_trajs(main_store, dummy)[source]#
parse_trajs(data)[source]#
traj_loaded_layout(traj_num=-1)[source]#
Parameters:

traj_num (int)

_redefine_open()[source]#

Redefines the open() builtin to trick MDTraj to use ReplaceOpenWithStringIO.

MDTraj can’t save to a StringIO object, because it checks the str provided in the filename argument for the extension and decides the format based on that (even using the save_pdb() function checks the extension). As StringIO objects can’t be used like a string this function together with _redefine_os_path_exists and ReplaceOpenWithStringIO are used to trick MDtraj.

Return type:

None

_redefine_os_path_exists()[source]#

Redefines the os.path.exists() function to trick MDTRaj to use ReplaceOpenWithStringIO

Return type:

None

traj_to_pdb(traj)[source]#

Converts an MDTraj Trajectory into a dict, that can be understood by dashbio’s NglMolViewer.

Parameters:

traj (md.Trajectory) – The MDTraj trajectory.

Returns:

The json-type data for

dashbio’s NglMolViewer.

Return type:

list[dict[str, Union[str, bool, dict[str, str]]]]

encodermap.plot.interactive_plotting module#

class InteractivePlotting(autoencoder=None, trajs=None, lowd_data=None, highd_data=None, align_string='name CA', top=None, ball_and_stick=False, histogram_type='free_energy', superpose=True, ref_align_string='name CA', base_traj=None)[source]#

Bases: object

EncoderMap’s interactive plotting for jupyter notebooks.

Instantiating this class will display an interactive display in your notebook. The display will look like this:

┌─────────────────────┐ ┌───────────┐
│Display              │ │Top        │
└─────────────────────┘ └───────────┘
┌─────────────┐ ┌───┐ ┌─────────────┐
│             │ │   │ │             │
│             │ │ T │ │             │
│  Main       │ │ R │ │  Molecular  │
│  Plotting   │ │ A │ │  Conform.   │
│  Area       │ │ C │ │  Area       │
│             │ │ E │ │             │
│             │ │   │ │             │
└─────────────┘ └───┘ └─────────────┘
┌───┐ ┌─────────────────────────────┐
│   │ │Progress Bar                 │
└───┘ └─────────────────────────────┘
┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌───────────────────┐
│C│ │G│ │S│ │D│ │Slider             │
└─┘ └─┘ └─┘ └─┘ └───────────────────┘
┌────────────────┐  ┌───────────────┐
│                │  │               │
│ Data           │  │               │
│ Overview       │  │               │
│                │  │               │
│                │  │               │
└────────────────┘  └───────────────┘
The components do the following:
  • Display:

    This part will display debug information.

  • Top (Top selector):

    Select which topology to use when creating new molecular conformations from the autoencoder network.

  • Main plotting area:

    In this area, a scatter plot will be displayed. The coordinates of the scatter plot will be taken from the low-dimensional projection of the trajectories. The data for this plotting area can be taken from different sources. See the _lowd_parser docstring for information on how the lowd data is selected. Clicking on a point in the scatter plot displays the conformation of that point.

  • TRACE:

    Displays the high-dimensinal data of selected points or clusters.

  • Molecular conformation area:

    Displays molecular conformations.

  • Progress Bar:

    Displays progress.

  • C (Cluster button):

    After selecting point in the main plotting area with the lasso tool, hit this button to display the molecular conformations of the selected cluster.

  • G (Generate Button):

    Switch to density using the density button. Then, you can draw a freeform path into the Main plotting area. Pressing the generate button will generate the appropriate molecular conformations. If your data has multiple conformations, you can choose which conformation to use for decoding with the top selector.

  • S (Save button):

    Writes either a cluster or generated path to your disk. Uses the main_path of the autoencoder (the same directory as the training data will be stored).

  • D (Density button):

    Switch the main plotting area to Density.

  • Slider:

    In scatter mode this slider defines how many structures to select from a cluster for representation in the molecular conformations window. In density mode, this slider defines how many points along the user-drawn path should be sampled.

Parameters:
  • autoencoder (Optional[AutoencoderClass])

  • trajs (Optional[Union[str, list[str], TrajEnsemble, SingleTraj]])

  • lowd_data (Optional[np.ndarray])

  • highd_data (Optional[np.ndarray])

  • align_string (str)

  • top (Optional[Union[str, list[str], Topology]])

  • ball_and_stick (bool)

  • histogram_type (Union[None, Literal['free_energy', 'density']])

  • superpose (bool)

  • ref_align_string (str)

  • base_traj (Optional[Trajectory])

_cluster_col: str = '_user_selected_points'#
_cluster_method: Literal['stack', 'join'] = 'join'#
_help_url: str = 'https://github.com/AG-Peter/encodermap'#
_max_filepath_len: int = 50#
_max_slider_len: int = 200#
_nbins: int = 50#
advance_path(n)[source]#
cluster(b)[source]#
property density: Any#
classmethod from_project(project_name)[source]#
Parameters:

project_name (Literal['linear_dimers'])

generate(b)[source]#
help(n)[source]#
on_canvas_mouse_down(x, y)[source]#
on_canvas_mouse_move(x, y)[source]#
on_canvas_mouse_up(x, y)[source]#
on_select(trace, points, selector)[source]#
save(b)[source]#
property scatter: Any#

The scatter plot using the low-dimensional data.

Type:

go.Scattergl

scatter_on_click(trace, points, selector)[source]#
stride: int = 10#
switch_between_density_and_scatter(b)[source]#

encodermap.plot.jinja_template module#

This is a template for a README.md generated when a user writes a cluster to disk.

encodermap.plot.plotting module#

Convenience functions for Plotting.

animate_lowd_trajectory(n=1, potential=False, n_frames=200)[source]#
Parameters:
Return type:

None

distance_histogram(data, periodicity, sigmoid_parameters, axes=None, low_d_max=5, bins='auto')[source]#

Plots the histogram of all pairwise distances in the data.

It also shows the sigmoid function and its normalized derivative.

Parameters:
  • data (np.ndarray) – 2-dimensional numpy array. Columns should iterate over the dimensions of the datapoints, i.e. the dimensionality of the data. The rows should iterate over datapoints.

  • periodicity (float) – Periodicity of the data. Use float(“inf”) for non-periodic data.

  • sigmoid_parameters (tuple) – Tuple of sketchmap sigmoid parameters in shape (Sigma, A, B, sigma, a, b).

  • axes (Union[np.ndarray, None], optional) – A numpy array of two matplotlib.axes objects or None. If None is provided, the axes will be created. Defaults to None.

  • low_d_max (int, optional) – Upper limit for plotting the low_d sigmoid. Defaults to 5.

  • bins (Union[str, int], optional) – Number of bins for histogram. Use ‘auto’ to let matplotlib decide how many bins to use. Defaults to ‘auto’.

Returns:

A tuple containing the following:
  • plt.axes: A matplotlib.pyplot axis used to plot the high-d distance

    sigmoid.

  • plt.axes: A matplotlib.pyplot axis used to plot the high-d distance

    histogram (a twinx of the first axis).

  • plt.axes: A matplotlib.pyplot axis used to plot the lowd sigmoid.

Return type:

tuple

distance_histogram_interactive(data, periodicity, low_d_max=5.0, n_values=1000, bins='auto', initial_guess=None, renderer=None, parameters=None)[source]#

Interactive version of distance_histogram.

Note:

Parameters:
  • data (np.ndarray) – 2-dimensional numpy array. Columns should iterate over the dimensions of the datapoints, i.e. the dimensionality of the data. The rows should iterate over datapoints.

  • periodicity (float) – Periodicity of the data. Use float(“inf”) for non-periodic data.

  • low_d_max (float) – Upper limit for plotting the low_d sigmoid. Defaults to 5.0.

  • n_values (int) – The number of x-values to use for the plotting of the sigmoid functions. Used in np.linspace(min, max, n_values). Defaults to 1000.

  • bins (Union[Literal["auto"], int]) – Number of bins for histogram. Use ‘auto’ to let numpy decide how many bins to use. Defaults to ‘auto’.

  • initial_guess (Optional[tuple[float, ...]]) – Tuple of sketchmap sigmoid parameters n shape (highd_sigma, highd_a, highd_b, lowd_sigma, lowd_a, lowd_b). If None is provided, the default values: (4.5, 12, 6, 1, 2, 6) are chosen. Defaults to None.

  • parameters (AnyParameters) – An instance of encodermap.Parameters, or encodermap.ADCParameters, to which the sigmoid parameters will be set.

  • renderer (Literal['colab', 'plotly_mimetype+notebook'] | None) – What renderer to use for fig.show(). Use None to automatically select best.

Return type:

None

interactive_path_visualization(traj, lowd, path)[source]#
Parameters:
Return type:

GridBox

plot_ball_and_stick(traj, frame_subsample=slice(None, None, 100), highlight='atoms', atom_indices=None, custom_colors=None, add_angle_arcs=True, animation=False, persistent_hover=False, flatten=False, renderer=None)[source]#
Parameters:
Return type:

None

plot_dssp(traj, simplified=True, subsample=None, residue_subsample=25)[source]#
Parameters:
Return type:

Figure

plot_end2end(traj, selstr='name CA', subsample=None, rolling_avg_window=5)[source]#
Parameters:
Return type:

Figure

plot_free_energy(x, y, bins=100, weights=None, kT=1.0, avoid_zero_count=False, minener_zero=True, transpose=True, cbar=False, cbar_label='free energy / kT', colorbar_x=None)[source]#

Plots free energy using plotly.

Parameters:
  • x (np.ndarray) – The x coordinates of the data.

  • y (np.ndarray) – The y coordinates of the data.

  • bins (int) – The number of bins passed to np.histogram2d.

  • weights (np.ndarray) – The weights passed to np.histogram2d.

  • avoid_zero_count (bool) – Avoid zero counts by lifting all histogram elements to the minimum value before computing the free energy. If False, zero histogram counts would yield infinity in the free energy.

  • kT (float) – The value of kT in the desired energy unit. By default, energies are computed in kT (setting 1.0). If you want to measure the energy in kJ/mol at 298 K, use kT=2.479 and change the cbar_label accordingly. Defaults to 1.0.

  • minener_zero (bool) – Shifts the energy minimum to zero. Defaults to False.

  • transpose (bool) – Whether to transpose the output.

  • cbar (bool) – Whether to display a colorbar. Dewfaults to False.

  • cbar_label (str) – The label of the colorbar. Defaults to ‘free energy / kT’.

  • colorbar_x (Optional[float]) – Sets the x position with respect to xref of the color bar (in plot fraction). When xref is “paper”, None becomes 1.02 when orientation is “v” and 0.5 when orientation is “h”. When xref is “container”, None becaomses 1 when orientation is “v” and 0.5 when orientation is “h”. Must be between 0 and 1 if xref is “container” and between “-2” and 3 if xref is “paper”.

Return type:

None

plot_ramachandran(angles, subsample=None)[source]#

Plots a Ramachandran plot using plotly.

Parameters:
  • angles (Union[tuple[np.ndarray, np.ndarray], np.ndarray, "SingleTraj"]) – Either a tuple of np.ndarray in which case it is assumed that the arrays are ordere like (psi, phi). Or an array of shape (2, n_frames, n_angles), in which case it is unpacked into psi and phi angles.

  • subsample (Optional[Union[int, slice, np.ndarray]]) – Any way to subsample the data along the time-axis. Can be int (one frame), slice (more frames, defined by start, stop, step) or np.ndarray (more frames defined by their integer index).

Return type:

None

plot_raw_data(xyz, frame_slice=slice(0, 5, None), atom_slice=slice(0, 50, 5))[source]#

Plots the raw data of a trajectory as xyz slices in a 3D plot.

Conventions:
  • x: The cartesian coordinates.

  • y: The atom.

  • z: The frame.

Parameters:
  • xyz (Union[np.ndarray], "SingleTraj"]) – Can be either a numpy array with shape (n_frames, n_atoms, 3) or a SingleTraj object.

  • frame_slice (slice) – A slice to select the frames you want.

  • atom_slice (slice) – A slice to select the atoms you want.

Return type:

Figure

plot_trajs_by_parameter(trajs, parameter='common_str', type='scatter', x=None, y=None, contourtype='countour', col='lowd', nbins=100, alpha=0.8, z_name_overwrite='', show=True, cbar=True)[source]#
Parameters:
Return type:

Figure

encodermap.plot.utils module#

Utils for plotting. Ideas and Code taken from the matplotlib documentation. Menu: https://matplotlib.org/3.1.0/gallery/widgets/menu.html LassoSelector: https://matplotlib.org/3.1.1/gallery/widgets/lasso_selector_demo_sgskip.html PolygonSelector: https://matplotlib.org/3.1.3/gallery/widgets/polygon_selector_demo.html Bezier: https://gist.github.com/gavincangan/b88a978e878e9bb1c0f8804e3af8de3c

Bernstein(n, k)[source]#

Bernstein polynomial.

Bezier(points, num=200)[source]#

Build Bézier curve from points.

class BezierBuilder(control_polygon, ax_main, ax_bernstein=None)[source]#

Bases: object

Bézier curve interactive builder.

disconnect()[source]#
property ind#
class DummyTool[source]#

Bases: object

disconnect()[source]#
class Menu(ax, items=['Reset', 'Write', 'Set Points'])[source]#

Bases: object

add_items(items)[source]#
get_coords(no_items, gap_space=0.05)[source]#
on_move(event)[source]#
class MenuItem(fig, xy, width, height, labelstr, props={}, hoverprops={}, on_select=None, standalone=False)[source]#

Bases: Rectangle, Artist

check_select(event)[source]#
draw(renderer)[source]#

Overwriting Base Class method to include labelstr

set(*, agg_filter=<UNSET>, alpha=<UNSET>, angle=<UNSET>, animated=<UNSET>, antialiased=<UNSET>, axes=<UNSET>, bounds=<UNSET>, capstyle=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, color=<UNSET>, data=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, fill=<UNSET>, gid=<UNSET>, hatch=<UNSET>, height=<UNSET>, hover=<UNSET>, hover_props=<UNSET>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, mouseover=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, width=<UNSET>, x=<UNSET>, xy=<UNSET>, y=<UNSET>, zorder=<UNSET>)#

Set multiple properties at once.

Supported properties are

Properties:

agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: scalar or None angle: unknown animated: bool antialiased or aa: bool or None axes: unknown bounds: (left, bottom, width, height) capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color: color data: unknown edgecolor or ec: color or None facecolor or fc: color or None figure: unknown fill: bool gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} height: unknown hover: unknown hover_props: unknown in_layout: bool joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float or None mouseover: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: unknown url: str visible: bool width: unknown x: unknown xy: (float, float) y: unknown zorder: float

set_axes(axes)[source]#

Overwriting Base Class method to include labelstr

set_data(x, y)[source]#

Overwriting Base Class method to include labelstr

set_figure(figure)[source]#

Overwriting Base Class method to include labelstr

set_hover(event)[source]#

Check the hover status of MenuItem

set_hover_props(check)[source]#
set_transform(transform)[source]#

Overwriting Base Class method to include labelstr

class ModeButton(*args, **kwargs)[source]#

Bases: MenuItem

check_select(event, overwrite=False)[source]#
set(*, agg_filter=<UNSET>, alpha=<UNSET>, angle=<UNSET>, animated=<UNSET>, antialiased=<UNSET>, axes=<UNSET>, bounds=<UNSET>, capstyle=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, color=<UNSET>, data=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, fill=<UNSET>, gid=<UNSET>, hatch=<UNSET>, height=<UNSET>, hover=<UNSET>, hover_props=<UNSET>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, mouseover=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, width=<UNSET>, x=<UNSET>, xy=<UNSET>, y=<UNSET>, zorder=<UNSET>)#

Set multiple properties at once.

Supported properties are

Properties:

agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: scalar or None angle: unknown animated: bool antialiased or aa: bool or None axes: unknown bounds: (left, bottom, width, height) capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color: color data: unknown edgecolor or ec: color or None facecolor or fc: color or None figure: unknown fill: bool gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} height: unknown hover: unknown hover_props: unknown in_layout: bool joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float or None mouseover: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: unknown url: str visible: bool width: unknown x: unknown xy: (float, float) y: unknown zorder: float

set_hover(event)[source]#

Check the hover status of MenuItem

class Props(**kwargs)[source]#

Bases: object

Class to contain the properties of MenuItems.

Each MenuItem contains two copies of this class. One for props when the mouse cursor hovers over them. One for the rest of times. Can be used as class or as dict.

labelcolor#

The color of the text.

Type:

str

labelcolor_rgb#

The RGBA value of labelcolor.

Type:

tuple

bgcolor#

The color of the background.

Type:

str

bgcolor_rgb#

The RGBA value of bgcolor.

Type:

tuple

fontsize#

The fontsize.

Type:

int

alpha#

The alpha value of the background.

Type:

float

defaults#

Class Variable of default values.

Type:

dict

Examples

>>> props = Props()
>>> props.labelcolor
'black'
property bgcolor_rgb#
defaults = {'alpha': 0.2, 'bgcolor': 'blue', 'fontsize': 15, 'labelcolor': 'black'}#
property labelcolor_rgb#
class SelectFromCollection(ax, collection, alpha_other=0.3, selector=<class 'matplotlib.widgets.LassoSelector'>)[source]#

Bases: object

Select indices from a matplotlib collection using LassoSelector.

Selected indices are saved in the ind attribute. This tool fades out the points that are not part of the selection (i.e., reduces their alpha values). If your collection has alpha < 1, this tool will permanently alter the alpha values.

Note that this tool selects collection objects based on their origins (i.e., offsets).

Parameters:
  • ax (matplotlib.axes.Axes) – Axes to interact with.

  • collection (matplotlib.collections.Collection) – Subclass of collection you want to select from.

  • alpha_other (float) – To highlight a selection, this tool sets all selected points to an alpha value of 1 and non-selected points to alpha_other. Needs to fulfill 0 <= alpha_other <= 1

disconnect()[source]#
onselect(verts)[source]#
class StatusMenu(ax)[source]#

Bases: Menu

add_items(items)[source]#
on_click(event)[source]#
set_idle()[source]#

Sets the idle status. Called at __init__ and when nothing is pressed.

_check_all_templates_defined(template, info_dict)[source]#
_create_readme(main_path, now, info_dict)[source]#
_get_system_info()[source]#
Return type:

dict[str, Any]

_unpack_cluster_info(trajs, main_path, selector, dummy_traj, align_string, col, display, progbar)[source]#
Parameters:
Return type:

tuple[int, Path]

abc_to_rgb(A=0.0, B=0.0, C=0.0)[source]#

Map values A, B, C (all in domain [0,1]) to suitable red, green, blue values.

correct_missing_uniques(uniques, sorted_, progbar=None)[source]#

Takes a list of DSSP letters and counts and adds zeros for all missing letters in sorted_.

Parameters:
  • uniques (list of np.ndarray) – A list of np.ndarrays. For every frame the DSSP letters and their respective counts should be provided. So for example [‘H’, 151] or [‘H’, ‘E’, 75, 76].

  • sorted (np.ndarray) – The sorted list of DSSP letters. This list will be used to update every frame. So The using [‘H’, ‘E’, ‘C’], the two examples from above will become [‘H’, ‘E’, ‘C’, 151, 0, 0] or [‘H’, ‘E’, ‘C’, 75, 76, 0], respectively.

  • progbar (tqdm) – A tqdm progbar. Defaults to None

Returns:

The corrected uniques.

Return type:

np.ndarray

digitize_dssp(trajs, dssp, imshow=True, bins=100, progbar=None)[source]#

Digitizes the DSSP array

Module contents#