encodermap.plot package#
Submodules#
encodermap.plot.dashboard module#
EncoderMap’s dashboard. Explore and understand your MD data.
- class Dashboard[source]#
Bases:
object
- _encodermap_logo = 'https://raw.githubusercontent.com/AG-Peter/encodermap/main/pic/logo_cube_300.png'#
- property app_layout#
- property debug#
- property layout#
- property local#
- property placeholder#
- 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 '#
- 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
- 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.
- _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
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)
ball_and_stick (bool)
histogram_type (Union[None, Literal['free_energy', 'density']])
superpose (bool)
ref_align_string (str)
base_traj (Optional[Trajectory])
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.
- 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:
- 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()
. UseNone
to automatically select best.
- Return type:
None
- interactive_path_visualization(traj, lowd, path)[source]#
- Parameters:
traj (SingleTraj)
lowd (ndarray | DataFrame)
path (ndarray)
- 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]#
- 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.
- 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:
trajs (SingleTraj | TrajEnsemble)
parameter (Literal['common_str', 'frame', 'encoded_frame', 'traj_num', 'topology', 'free_energy'] | str)
type (Literal['scatter', 'heatmap'])
x (ndarray | None)
y (ndarray | None)
contourtype (Literal['contour', 'contourf'])
col (str)
nbins (int)
alpha (float)
z_name_overwrite (str)
show (bool)
cbar (bool)
- 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
- class BezierBuilder(control_polygon, ax_main, ax_bernstein=None)[source]#
Bases:
object
Bézier curve interactive builder.
- property ind#
- class MenuItem(fig, xy, width, height, labelstr, props={}, hoverprops={}, on_select=None, standalone=False)[source]#
Bases:
Rectangle
,Artist
- 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
- class ModeButton(*args, **kwargs)[source]#
Bases:
MenuItem
- 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
- 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.
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
- _unpack_cluster_info(trajs, main_path, selector, dummy_traj, align_string, col, display, progbar)[source]#
- Parameters:
trajs (TrajEnsemble)
main_path (Union[Path, str])
selector (Any)
dummy_traj (TrajEnsemble)
align_string (str)
col (str)
display (Any)
progbar (Any)
- Return type:
- 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