dpet package
Subpackages
Submodules
dpet.comparison module
- dpet.comparison.all_vs_all_comparison(ensembles: List[Ensemble], score: str, featurization_params: dict = {}, bootstrap_iters: int = None, bootstrap_frac: float = 1.0, bootstrap_replace: bool = True, bins: Union[int, str] = 50, random_seed: int = None, verbose: bool = False) dict
Compare all pair of ensembles using divergence scores. Implemented scores are approximate average Jensen–Shannon divergence (JSD) over several kinds of molecular features. The lower these scores are, the higher the similarity between the probability distribution of the features of the ensembles. JSD scores here range from a minimum of 0 to a maximum of log(2) ~= 0.6931.
- Parameters:
ensembles (List[Ensemble]) – Ensemble objectes to analyze.
score (str) – Type of score used to compare ensembles. Choices: adaJSD (carbon Alfa Distance Average JSD), ramaJSD (RAMAchandran average JSD) and ataJSD (Alpha Torsion Average JSD). adaJSD scores the average JSD over all Ca-Ca distance distributions of residue pairs with sequence separation > 1. ramaJSD scores the average JSD over the phi-psi angle distributions of all residues. ataJSD scores the average JSD over all alpha torsion angles, which are the angles formed by four consecutive Ca atoms in a protein.
featurization_params (dict, optional) – Optional dictionary to customize the featurization process for the above features.
bootstrap_iters (int, optional) – Number of bootstrap iterations. By default its value is None. In this case, IDPET will directly compare each pair of ensemble $i$ and $j$ by using all of their conformers and perform the comparison only once. On the other hand, if providing an integer value to this argument, each pair of ensembles $i$ and $j$ will be compared bootstrap_iters times by randomly selecting (bootstrapping) conformations from them. Additionally, each ensemble will be auto-compared with itself by subsampling conformers via bootstrapping. Then IDPET will perform a statistical test to establish if the inter-ensemble ($i != j$) scores are significantly different from the intra-ensemble ($i == j$) scores. The tests work as follows: for each ensemble pair $i != j$ IDPET will get their inter-ensemble comparison scores obtained in bootstrapping. Then, it will get the bootstrapping scores from auto-comparisons of ensemble $i$ and $j$ and the scores with the higher mean here are selected as reference intra-ensemble scores. Finally, the inter-ensemble and intra-ensemble scores are compared via a one-sided Mann-Whitney U test with the alternative hypothesis being: inter-ensemble scores are stochastically greater than intra-ensemble scores. The p-values obtained in these tests will additionally be returned. For small protein structural ensembles (less than 500 conformations) most comparison scores in IDPET are not robust estimators of divergence/distance. By performing bootstrapping, you can have an idea of how the size of your ensembles impacts the comparison. Use values >= 50 when comparing ensembles with very few conformations (less than 100). When comparing large ensembles (more than 1,000-5,000 conformations) you can safely avoid bootstrapping.
bootstrap_frac (float, optional) – Fraction of the total conformations to sample when bootstrapping. Default value is 1.0, which results in bootstrap samples with the same number of conformations of the original ensemble.
bootstrap_replace (bool, optional) – If True, bootstrap will sample with replacement. Default is True.
bins (Union[int, str], optional) – Number of bins or bin assignment rule for JSD comparisons. See the documentation of dpet.comparison.get_num_comparison_bins for more information.
random_seed (int, optional) – Random seed used when performing bootstrapping.
verbose (bool, optional) – If True, some information about the comparisons will be printed to stdout.
- Returns:
results –
- Aa dictionary containing the following key-value pairs:
- scores: a (M, M, B) NumPy array storing the comparison
scores, where M is the number of ensembles being compared and B is the number of bootstrap iterations (B will be 1 if bootstrapping was not performed).
- p_values: a (M, M) NumPy array storing the p-values
obtained in the statistical test performed when using a bootstrapping strategy (see the bootstrap_iters) method. Returned only when performing a bootstrapping strategy.
- Return type:
dict
- dpet.comparison.calc_freqs(x, bins)
- dpet.comparison.calc_jsd(p_h, q_h)
Calculates JSD between distribution p and q. p_h: histogram frequencies for sample p. q_h: histogram frequencies for sample q.
- dpet.comparison.calc_kld_for_jsd(x_h, m_h)
Calculates KLD between distribution x and m. x_h: histogram frequencies for sample p or q. m_h: histogram frequencies for m = 0.5*(p+q).
- dpet.comparison.check_feature_matrices(func)
- dpet.comparison.confidence_interval(theta_boot, theta_hat=None, confidence_level=0.95, method='percentile')
Returns bootstrap confidence intervals. Adapted from: https://github.com/scipy/scipy/blob/v1.14.0/scipy/stats/_resampling.py
- dpet.comparison.get_adaJSD_matrix(ens_1: Union[Ensemble, Trajectory], ens_2: Union[Ensemble, Trajectory], bins: Union[str, int] = 'auto', return_bins: bool = False, featurization_params: dict = {}, *args, **kwargs)
Utility function to calculate the adaJSD score between two ensembles and return a matrix with JSD scores for each pair of Ca-Ca distances.
- Parameters:
ens_1 (Union[Ensemble, mdtraj.Trajectory]) – Two Ensemble objects storing the ensemble data to compare.
ens_2 (Union[Ensemble, mdtraj.Trajectory]) – Two Ensemble objects storing the ensemble data to compare.
arguments (Remaining) –
------------------- – See dpet.comparison.score_adaJSD for more information.
Output –
------ – If return_bins is False, it will return a tuple containing the adaJSD score and a (N, N) NumPy array (where N is the number of residues of the protein in the ensembles being compared) containing the JSD scores of individual Ca-Ca distances. If return_bins is True, it will return also the bin value used in all the comparisons.
- dpet.comparison.get_ataJSD_profile(ens_1: Union[Ensemble, Trajectory], ens_2: Union[Ensemble, Trajectory], bins: Union[str, int], return_bins: bool = False, *args, **kwargs)
Utility function to calculate the ataJSD score between two ensembles and return a profile with JSD scores for each alpha angle in the proteins.
- Parameters:
ens_1 (Union[Ensemble, mdtraj.Trajectory]) – Two Ensemble objects storing the ensemble data to compare.
ens_2 (Union[Ensemble, mdtraj.Trajectory]) – Two Ensemble objects storing the ensemble data to compare.
arguments (Remaining) –
------------------- – See dpet.comparison.score_ataJSD for more information.
Output –
------ – If return_bins is False, it will return a tuple containing the ataJSD score and a (N-3, ) NumPy array (where N is the number of residues of the protein in the ensembles being compared) containing the JSD scores of individual alpha angles. If return_bins is True, it will return also the bin value used in all the comparisons.
- dpet.comparison.get_num_comparison_bins(bins: Union[str, int], x: List[ndarray] = None)
Get the number of bins to be used in comparison between two ensembles using an histogram-based score (such as a JSD approximation).
- Parameters:
bins (Union[str, int]) –
Determines the number of bins to be used. When providing an int, the same value will simply be returned. When providing a string, the following rules to determine bin value will be applied: auto: applies sqrt if the size of the smallest ensemble is <
dpet.comparison.min_samples_auto_hist. If it >= than this value, returns dpet.comparison.num_default_bins.
- sqrt: applies the square root rule for determining bin number using
the size of the smallest ensemble (https://en.wikipedia.org/wiki/Histogram#Square-root_choice).
- sturges: applies Sturge’s formula for determining bin number using
the size of the smallest ensemble (https://en.wikipedia.org/wiki/Histogram#Sturges’s_formula).
x (List[np.ndarray], optional) – List of M feature matrices (one for each ensembles) of shape (N_i, *). N_i values are the number of structures in each ensemble. The minimum N_i will be used to apply bin assignment rule when the bins argument is a string.
- Returns:
num_bins – Number of bins.
- Return type:
int
- dpet.comparison.get_ramaJSD_profile(ens_1: Union[Ensemble, Trajectory], ens_2: Union[Ensemble, Trajectory], bins: Union[str, int], return_bins: bool = False, *args, **kwargs)
Utility function to calculate the ramaJSD score between two ensembles and return a profile with JSD scores for the Ramachandran plots of pair of corresponding residue in the proteins.
- Parameters:
ens_1 (Union[Ensemble, mdtraj.Trajectory]) – Two Ensemble objects storing the ensemble data to compare.
ens_2 (Union[Ensemble, mdtraj.Trajectory]) – Two Ensemble objects storing the ensemble data to compare.
arguments (Remaining) –
------------------- – See dpet.comparison.score_ramaJSD for more information.
Output –
------ – If return_bins is False, it will return a tuple containing the ramaJSD score and a (N-2, ) NumPy array (where N is the number of residues of the protein in the ensembles being compared) containing the JSD scores of individual residues. If return_bins is True, it will return also the bin value used in all the comparisons.
- dpet.comparison.percentile_func(a, q)
- dpet.comparison.process_all_vs_all_output(comparison_out: dict, confidence_level: float = 0.95)
Takes as input a dictionary produced as output of the all_vs_all_comparison function. If a bootstrap analysis was performed in all_vs_all_comparison, this function will assign bootstrap confidence intervals.
- dpet.comparison.score_adaJSD(ens_1: Union[Ensemble, Trajectory], ens_2: Union[Ensemble, Trajectory], bins: Union[str, int] = 'auto', return_bins: bool = False, return_scores: bool = False, featurization_params: dict = {}, *args, **kwargs)
Utility function to calculate the adaJSD (carbon Alfa Distance Average JSD) score between two ensembles. The score evaluates the divergence between distributions of Ca-Ca distances of the ensembles.
- Parameters:
ens_1 (Union[Ensemble, mdtraj.Trajectory],) – Two Ensemble or mdtraj.Trajectory objects storing the ensemble data to compare.
ens_2 (Union[Ensemble, mdtraj.Trajectory],) – Two Ensemble or mdtraj.Trajectory objects storing the ensemble data to compare.
bins (Union[str, int], optional) – Determines the number of bins to be used when constructing histograms. See dpet.comparison.get_num_comparison_bins for more information.
return_bins (bool, optional) – If True, returns the number of bins used in the calculation.
return_scores (bool, optional) – If True, returns the a tuple with with (avg_score, all_scores), where all_scores is an array with all the F scores (one for each feature) used to compute the average score.
featurization_params (dict, optional) – Optional dictionary to customize the featurization process to calculate Ca-Ca distances. See the Ensemble.get_features function for more information.
output (Remaining arguments and) –
------------------------------ – See dpet.comparison.score_avg_jsd for more information.
- dpet.comparison.score_ataJSD(ens_1: Union[Ensemble, Trajectory], ens_2: Union[Ensemble, Trajectory], bins: Union[str, int], return_bins: bool = False, return_scores: bool = False, *args, **kwargs)
Utility function to calculate the ataJSD (Alpha Torsion Average JSD) score between two ensembles. The score evaluates the divergence between distributions of alpha torsion angles (the angles formed by four consecutive Ca atoms in a protein) of the ensembles.
- Parameters:
ens_1 (Union[Ensemble, mdtraj.Trajectory]) – Two Ensemble objects storing the ensemble data to compare.
ens_2 (Union[Ensemble, mdtraj.Trajectory]) – Two Ensemble objects storing the ensemble data to compare.
output (Remaining arguments and) –
------------------------------ – See dpet.comparison.score_avg_jsd for more information.
- dpet.comparison.score_avg_2d_angle_jsd(array_1: ndarray, array_2: ndarray, bins: int, return_scores: bool = False, return_bins: bool = False, *args, **kwargs)
Takes as input two (*, F, 2) bidimensional feature matrices and computes an average JSD score over all F bidimensional features by discretizing them in 2d histograms. The features in this functions are supposed to be angles whose values range from -math.pi to math.pi. For example, int the score_ramaJSD function the F features represent the phi-psi values of F residues in a protein of length L=F+2 (first and last residues don’t have both phi and psi values).
- Parameters:
p_data (np.ndarray) – NumPy arrays of shape (*, F, 2) containing samples from F bi-dimensional distributions to be compared.
q_data (np.ndarray) – NumPy arrays of shape (*, F, 2) containing samples from F bi-dimensional distributions to be compared.
bins (Union[int, str], optional) – Determines the number of bins to be used when constructing histograms. See dpet.comparison.get_num_comparison_bins for more information. The range spanned by the bins will be -math.pi to math.pi. Note that the effective number of bins used in the functio will be the square of the number returned by dpet.comparison.get_num_comparison_bins, since we are building a 2d histogram.
return_bins (bool, optional) – If True, returns the square root of the effective number of bins used in the calculation.
- Returns:
results – If return_bins is False, only returns a float value for the JSD score. The score will range from 0 (no common support) to log(2) (same distribution). If return_bins is True, returns a tuple with the JSD score and the number of bins. If return_scores is True it will also return the F scores used to compute the average JSD score.
- Return type:
Union[float, Tuple[float, np.ndarray]]
- dpet.comparison.score_avg_jsd(m1, m2, *args, **kwargs)
- dpet.comparison.score_histogram_jsd(p_data: ndarray, q_data: ndarray, limits: Union[str, Tuple[int]], bins: Union[int, str] = 'auto', return_bins: bool = False) Union[float, Tuple[float, ndarray]]
Scores an approximation of Jensen-Shannon divergence by discretizing in a histogram the values two 1d samples provided as input.
- Parameters:
p_data (np.ndarray) – NumPy arrays of shape (*, ) containing samples from two mono-dimensional distribution to be compared.
q_data (np.ndarray) – NumPy arrays of shape (*, ) containing samples from two mono-dimensional distribution to be compared.
limits (Union[str, Tuple[int]]) –
Define the method to calculate the minimum and maximum values of the range spanned by the bins. Accepted values are:
- ”m”: will use the minimum and maximum values observed by
concatenating samples in p_data and q_data.
- ”p”: will use the minimum and maximum values observed by
concatenating samples in p_data. If q_data contains values outside that range, new bins of the same size will be added to cover all values of q. Currently, this is not used in any IDPET functionality. Note that the bins argument will determine only the bins originally spanned by p_data.
- ”a”: limits for scoring angular features. Will use a
(-math.pi, math.pi) range for scoring such features.
- (float, float): provide a custom range. Currently, not used in any
IDPET functionality.
bins (Union[int, str], optional) – Determines the number of bins to be used when constructing histograms. See dpet.comparison.get_num_comparison_bins for more information. The range spanned by the bins will be define by the limits argument.
return_bins (bool, optional) – If True, returns the bins used in the calculation.
- Returns:
results – If return_bins is False, only returns a float value for the JSD score. The score will range from 0 (no common support) to log(2) (same distribution). If return_bins is True, returns a tuple with the JSD score and the number of bins.
- Return type:
Union[float, Tuple[float, np.ndarray]]
- dpet.comparison.score_ramaJSD(ens_1: Union[Ensemble, Trajectory], ens_2: Union[Ensemble, Trajectory], bins: int, return_scores: bool = False, return_bins: bool = False)
Utility unction to calculate the ramaJSD (Ramachandran plot average JSD) score between two ensembles. The score evaluates the divergence between distributions of phi-psi torsion angles of every residue in the ensembles.
- Parameters:
ens_1 (Union[Ensemble, mdtraj.Trajectory]) – Two Ensemble objects storing the ensemble data to compare.
ens_2 (Union[Ensemble, mdtraj.Trajectory]) – Two Ensemble objects storing the ensemble data to compare.
output (Remaining arguments and) –
------------------------------ – See dpet.comparison.score_avg_jsd for more information.
- dpet.comparison.sqrt_rule(n)
- dpet.comparison.sturges_rule(n)
dpet.dimensionality_reduction module
- class dpet.dimensionality_reduction.DimensionalityReduction
Bases:
ABC
- abstract fit(data: ndarray)
Fit the dimensionality reduction model to the data.
- Parameters:
data (np.ndarray) – The input data array of shape (n_samples, n_features).
Notes
This method fits the dimensionality reduction model to the input data.
- abstract fit_transform(data: ndarray) ndarray
Fit the dimensionality reduction model to the data and then transform it.
- Parameters:
data (np.ndarray) – The input data array of shape (n_samples, n_features).
- Returns:
The transformed data array of shape (n_samples, n_components).
- Return type:
np.ndarray
Notes
This method fits the dimensionality reduction model to the input data and then transforms it.
- abstract transform(data: ndarray) ndarray
Transform the input data using the fitted dimensionality reduction model.
- Parameters:
data (np.ndarray) – The input data array of shape (n_samples, n_features) to be transformed.
- Returns:
The transformed data array of shape (n_samples, n_components).
- Return type:
np.ndarray
Notes
This method transforms the input data using the fitted dimensionality reduction model.
- class dpet.dimensionality_reduction.DimensionalityReductionFactory
Bases:
object
Factory class for creating instances of various dimensionality reduction algorithms.
- get_reducer(method, \*args, \*\*kwargs)
Get an instance of the specified dimensionality reduction algorithm.
- static get_reducer(method, *args, **kwargs) DimensionalityReduction
Get an instance of the specified dimensionality reduction algorithm.
- Parameters:
method (str) – Name of the dimensionality reduction method.
*args – Positional arguments to pass to the constructor of the selected method.
**kwargs – Keyword arguments to pass to the constructor of the selected method.
- Returns:
Instance of the specified dimensionality reduction algorithm.
- Return type:
- class dpet.dimensionality_reduction.KPCAReduction(circular: bool = False, num_dim: int = 10, gamma: float = None)
Bases:
DimensionalityReduction
Class for performing dimensionality reduction using Kernel PCA (KPCA) algorithm.
- Parameters:
circular (bool, optional) – Whether to use circular metrics for angular features. Default is False.
num_dim (int, optional) – Number of dimensions for the reduced space. Default is 10.
gamma (float, optional) – Kernel coefficient. Default is None.
- fit(data)
Fit the dimensionality reduction model to the data.
- Parameters:
data (np.ndarray) – The input data array of shape (n_samples, n_features).
Notes
This method fits the dimensionality reduction model to the input data.
- fit_transform(data) ndarray
Fit the dimensionality reduction model to the data and then transform it.
- Parameters:
data (np.ndarray) – The input data array of shape (n_samples, n_features).
- Returns:
The transformed data array of shape (n_samples, n_components).
- Return type:
np.ndarray
Notes
This method fits the dimensionality reduction model to the input data and then transforms it.
- transform(data) ndarray
Transform the input data using the fitted dimensionality reduction model.
- Parameters:
data (np.ndarray) – The input data array of shape (n_samples, n_features) to be transformed.
- Returns:
The transformed data array of shape (n_samples, n_components).
- Return type:
np.ndarray
Notes
This method transforms the input data using the fitted dimensionality reduction model.
- class dpet.dimensionality_reduction.PCAReduction(num_dim: int = 10)
Bases:
DimensionalityReduction
Principal Component Analysis (PCA) for dimensionality reduction.
- Parameters:
num_dim (int, optional) – Number of components to keep. Default is 10.
- fit(data: ndarray)
Fit the dimensionality reduction model to the data.
- Parameters:
data (np.ndarray) – The input data array of shape (n_samples, n_features).
Notes
This method fits the dimensionality reduction model to the input data.
- fit_transform(data: ndarray) ndarray
Fit the dimensionality reduction model to the data and then transform it.
- Parameters:
data (np.ndarray) – The input data array of shape (n_samples, n_features).
- Returns:
The transformed data array of shape (n_samples, n_components).
- Return type:
np.ndarray
Notes
This method fits the dimensionality reduction model to the input data and then transforms it.
- transform(data: ndarray) ndarray
Transform the input data using the fitted dimensionality reduction model.
- Parameters:
data (np.ndarray) – The input data array of shape (n_samples, n_features) to be transformed.
- Returns:
The transformed data array of shape (n_samples, n_components).
- Return type:
np.ndarray
Notes
This method transforms the input data using the fitted dimensionality reduction model.
- class dpet.dimensionality_reduction.TSNEReduction(perplexity_vals: List[float] = [30], metric: str = 'euclidean', circular: bool = False, n_components: int = 2, learning_rate: float = 'auto', range_n_clusters: List[int] = range(2, 10))
Bases:
DimensionalityReduction
Class for performing dimensionality reduction using t-SNE algorithm.
- Parameters:
perplexity_vals (List[float], optional) – List of perplexity values. Default is [30].
metric (str, optional) – Metric to use. Default is “euclidean”.
circular (bool, optional) – Whether to use circular metrics. Default is False.
n_components (int, optional) – Number of dimensions of the embedded space. Default is 2.
learning_rate (float, optional) – Learning rate. Default is 100.0.
range_n_clusters (List[int], optional) – Range of cluster values. Default is range(2, 10, 1).
- fit(data: ndarray)
Fit the dimensionality reduction model to the data.
- Parameters:
data (np.ndarray) – The input data array of shape (n_samples, n_features).
Notes
This method fits the dimensionality reduction model to the input data.
- fit_transform(data: ndarray) ndarray
Fit the dimensionality reduction model to the data and then transform it.
- Parameters:
data (np.ndarray) – The input data array of shape (n_samples, n_features).
- Returns:
The transformed data array of shape (n_samples, n_components).
- Return type:
np.ndarray
Notes
This method fits the dimensionality reduction model to the input data and then transforms it.
- transform(data: ndarray) ndarray
Transform the input data using the fitted dimensionality reduction model.
- Parameters:
data (np.ndarray) – The input data array of shape (n_samples, n_features) to be transformed.
- Returns:
The transformed data array of shape (n_samples, n_components).
- Return type:
np.ndarray
Notes
This method transforms the input data using the fitted dimensionality reduction model.
- class dpet.dimensionality_reduction.UMAPReduction(num_dim: int = 2, n_neighbors: List[int] = [15], circular=False, min_dist: float = 0.1, metric: str = 'euclidean', range_n_clusters: List[int] = range(2, 10))
Bases:
DimensionalityReduction
Class for performing dimensionality reduction using Uniform Manifold Approximation and Projection (UMAP) algorithm.
- Parameters:
num_dim (int, optional) – Number of dimensions for the reduced space. Default is 2.
n_neighbors (List[int], optional) – Number of neighbors to consider for each point in the input data. Default is [20, 30, 40].
min_dist (float, optional) – The minimum distance between embedded points. Default is 0.1.
metric (str, optional) – The metric to use for distance calculation. Default is ‘euclidean’.
range_n_clusters (range or List, optional) – Range of cluster values to consider for silhouette scoring. Default is range(2, 10, 1).
- cluster(embedding, n_neighbor) List[Tuple]
Perform clustering using KMeans algorithm for each number of clusters in the specified range.
- Returns:
A list of tuples containing the number of clusters and the corresponding silhouette score for each clustering result.
- Return type:
List[Tuple]
- fit(data)
Fit the dimensionality reduction model to the data.
- Parameters:
data (np.ndarray) – The input data array of shape (n_samples, n_features).
Notes
This method fits the dimensionality reduction model to the input data.
- fit_transform(data) ndarray
Fit the dimensionality reduction model to the data and then transform it.
- Parameters:
data (np.ndarray) – The input data array of shape (n_samples, n_features).
- Returns:
The transformed data array of shape (n_samples, n_components).
- Return type:
np.ndarray
Notes
This method fits the dimensionality reduction model to the input data and then transforms it.
- transform(data) ndarray
Transform the input data using the fitted dimensionality reduction model.
- Parameters:
data (np.ndarray) – The input data array of shape (n_samples, n_features) to be transformed.
- Returns:
The transformed data array of shape (n_samples, n_components).
- Return type:
np.ndarray
Notes
This method transforms the input data using the fitted dimensionality reduction model.
- dpet.dimensionality_reduction.unit_vector_distance(a0: ndarray, a1: ndarray, sqrt: bool = True)
Compute the sum of distances between two (*, N) arrays storing the values of N angles.
- dpet.dimensionality_reduction.unit_vector_kernel(a1, a2, gamma)
Compute unit vector kernel.
- dpet.dimensionality_reduction.unit_vectorize(a: ndarray) ndarray
Convert an array with (*, N) angles in an array with (*, N, 2) sine and cosine values for the N angles.
dpet.ensemble module
- class dpet.ensemble.Ensemble(code: str, data_path: str = None, top_path: str = None, database: str = None, chain_id: str = None, residue_range: Tuple = None)
Bases:
object
Represents a molecular dynamics ensemble.
- Parameters:
code (str) – The code identifier of the ensemble.
data_path (str, optional) – The path to the data file associated with the ensemble. It could be a path to one multi-model pdb file , a path to a folder contain pdb files for each model, or .xtc , .dcd trajectory files. Default is None.
top_path (str, optional) – The path to the topology file associated with the ensemble. In case of having trajectory file. Default is None.
database (str, optional) – The database from which to download the ensemble. Options are ‘ped’ and ‘atlas’. Default is None.
chain_id (str, optional) – Chain identifier used to select a single chain to analyze in case multiple chains are loaded. Default is None.
residue_range (Tuple, optional) – A tuple indicating the start and end of the residue range (inclusive), using 1-based indexing. Default is None.
Notes
If the database is ‘atlas’, the ensemble code should be provided as a PDB ID with a chain identifier separated by an underscore. Example: ‘3a1g_B’.
If the database is ‘ped’, the ensemble code should be in the PED ID format, which consists of a string starting with ‘PED’ followed by a numeric identifier, and ‘e’ followed by another numeric identifier. Example: ‘PED00423e001’.
The residue_range parameter uses 1-based indexing, meaning the first residue is indexed as 1.
- extract_features(featurization: str, *args, **kwargs)
Extract features from the trajectory using the specified featurization method.
- Parameters:
featurization (str) – The method to use for feature extraction. Supported options: ‘ca_dist’, ‘phi_psi’, ‘a_angle’, ‘tr_omega’, ‘tr_phi’, and ‘ca_phi_psi’.
min_sep (int, optional) – The minimum sequence separation for angle calculations. Required for certain featurization methods.
max_sep (int, optional) – The maximum sequence separation for angle calculations. Required for certain featurization methods.
Notes
This method extracts features from the trajectory using the specified featurization method and updates the ensemble’s features attribute.
- get_chains_from_pdb()
Extracts unique chain IDs from a PDB file.
- Raises:
FileNotFoundError – If the specified PDB file or directory does not exist, or if no PDB file is found in the directory.
ValueError – If the specified file is not a PDB file and the path is not a directory.
- get_features(featurization: str, normalize: bool = False, *args, **kwargs) Sequence
Get features from the trajectory using the specified featurization method.
- Parameters:
featurization (str) – The method to use for feature extraction. Supported options: ‘ca_dist’, ‘phi_psi’, ‘a_angle’, ‘tr_omega’, ‘tr_phi’, ‘rg’, ‘prolateness’, ‘asphericity’, ‘sasa’, ‘end_to_end’.
min_sep (int) – The minimum sequence separation for angle calculations.
max_sep (int) – The maximum sequence separation for angle calculations.
- Returns:
features – The extracted features.
- Return type:
Sequence
Notes
This method extracts features from the trajectory using the specified featurization method.
- get_num_residues()
- load_trajectory(data_dir: str)
Load a trajectory for the ensemble.
- Parameters:
data_dir (str) – The directory where the trajectory data is located or where generated trajectory files will be saved.
Notes
This method loads a trajectory for the ensemble based on the specified data path. It supports loading from various file formats such as PDB, DCD, and XTC. If the data path points to a directory, it searches for PDB files within the directory and generates a trajectory from them. If the data path points to a single PDB file, it loads that file and generates a trajectory. If the data path points to a DCD or XTC file along with a corresponding topology file (TOP), it loads both files to construct the trajectory. Additional processing steps include checking for coarse-grained models, selecting a single chain (if applicable), and selecting residues of interest based on certain criteria.
- normalize_features(mean: float, std: float)
Normalize the extracted features using the provided mean and standard deviation.
- Parameters:
mean (float) – The mean value used for normalization.
std (float) – The standard deviation used for normalization.
Notes
This method normalizes the ensemble’s features using the provided mean and standard deviation.
- random_sample_trajectory(sample_size: int)
Randomly sample frames from the original trajectory.
- Parameters:
sample_size (int) – The number of frames to sample from the original trajectory.
Notes
This method samples frames randomly from the original trajectory and updates the ensemble’s trajectory attribute.
dpet.ensemble_analysis module
- class dpet.ensemble_analysis.EnsembleAnalysis(ensembles: List[Ensemble], output_dir: str)
Bases:
object
Data analysis pipeline for ensemble data.
Initializes with a list of ensemble objects and a directory path for storing data.
- Parameters:
ensembles (List[Ensemble])) – List of ensembles.
output_dir (str) – Directory path for storing data.
- comparison_scores(score: str, featurization_params: dict = {}, bootstrap_iters: int = None, bootstrap_frac: float = 1.0, bootstrap_replace: bool = True, bins: Union[int, str] = 50, random_seed: int = None, verbose: bool = False) Tuple[ndarray, List[str]]
Compare all pair of ensembles using divergence/distance scores. See dpet.comparison.all_vs_all_comparison for more information.
- property ens_codes: List[str]
Get the ensemble codes.
- Returns:
A list of ensemble codes.
- Return type:
List[str]
- execute_pipeline(featurization_params: Dict, reduce_dim_params: Dict, subsample_size: int = None)
- Execute the data analysis pipeline end-to-end. The pipeline includes:
Download from database (optional)
Generate trajectories
Randomly sample a number of conformations from trajectories (optional)
Perform feature extraction
Perform dimensionality reduction
- Parameters:
featurization_params (Dict) – Parameters for feature extraction. The only required parameter is “featurization”, which can be “phi_psi”, “ca_dist”, “a_angle”, “tr_omega” or “tr_phi”. Other method-specific parameters are optional.
reduce_dim_params (Dict) – Parameters for dimensionality reduction. The only required parameter is “method”, which can be “pca”, “tsne” or “kpca”.
subsample_size (int, optional) – Optional parameter that specifies the trajectory subsample size. Default is None.
- exists_coarse_grained() bool
Check if at least one of the loaded ensembles is coarse-grained after loading trajectories.
- Returns:
True if at least one ensemble is coarse-grained, False otherwise.
- Return type:
bool
- extract_features(featurization: str, normalize: bool = False, *args, **kwargs) Dict[str, ndarray]
Extract the selected feature.
- Parameters:
featurization (str) – Choose between “phi_psi”, “ca_dist”, “a_angle”, “tr_omega”, “tr_phi”, “rmsd”.
normalize (bool, optional) – Whether to normalize the data. Only applicable to the “ca_dist” method. Default is False.
min_sep (int or None, optional) – Minimum separation distance for “ca_dist”, “tr_omega”, and “tr_phi” methods. Default is 2.
max_sep (int, optional) – Maximum separation distance for “ca_dist”, “tr_omega”, and “tr_phi” methods. Default is None.
- Returns:
A dictionary where keys are ensemble IDs and values are the corresponding feature arrays.
- Return type:
Dict[str, np.ndarray]
- property features: Dict[str, ndarray]
Get the features associated with each ensemble.
- Returns:
A dictionary where keys are ensemble IDs and values are the corresponding feature arrays.
- Return type:
Dict[str, np.ndarray]
- get_features(featurization: str, normalize: bool = False, *args, **kwargs) Dict[str, ndarray]
Extract features for each ensemble without modifying any fields in the EnsembleAnalysis class.
- featurizationstr
The type of featurization to be applied. Supported options are “phi_psi”, “tr_omega”, “tr_phi”, “ca_dist”, “a_angle”, “rg”, “prolateness”, “asphericity”, “sasa”, “end_to_end” and “flory_exponent”.
- min_sepint, optional
Minimum sequence separation distance for “ca_dist”, “tr_omega”, and “tr_phi” methods. Default is 2.
- max_sepint or None, optional
Maximum sequence separation distance for “ca_dist”, “tr_omega”, and “tr_phi” methods. Default is None.
- normalizebool, optional
Whether to normalize the extracted features. Normalization is only supported when featurization is “ca_dist”. Default is False.
- Dict[str, np.ndarray]
A dictionary containing the extracted features for each ensemble, where the keys are ensemble IDs and the values are NumPy arrays containing the features.
- ValueError:
If featurization is not supported, or if normalization is requested for a featurization method other than “ca_dist”. If normalization is requested and features from ensembles have different sizes. If coarse-grained models are used with featurization methods that require atomistic detail.
- get_features_summary_dataframe(selected_features: List[str] = ['rg', 'asphericity', 'prolateness', 'sasa', 'end_to_end', 'flory_exponent'], show_variability: bool = True) DataFrame
Create a summary DataFrame for each ensemble.
The DataFrame includes the ensemble code and the average for each feature.
- Parameters:
selected_features (List[str], optional) – List of feature extraction methods to be used for summarizing the ensembles. Default is [“rg”, “asphericity”, “prolateness”, “sasa”, “end_to_end”, “flory_exponent”].
show_variability (bool, optional) – If True, include a column a measurment of variability for each feature (e.g.: standard deviation or error).
- Returns:
DataFrame containing the summary statistics (average and std) for each feature in each ensemble.
- Return type:
pd.DataFrame
- Raises:
ValueError – If any feature in the selected_features is not a supported feature extraction method.
- load_trajectories() Dict[str, Trajectory]
Load trajectories for all ensembles.
This method iterates over each ensemble in the ensembles list and downloads data files if they are not already available. Trajectories are then loaded for each ensemble.
- Returns:
A dictionary where keys are ensemble IDs and values are the corresponding MDTraj trajectories.
- Return type:
Dict[str, mdtraj.Trajectory]
Note
This method assumes that the output_dir attribute of the class specifies the directory where trajectory files will be saved or extracted.
- random_sample_trajectories(sample_size: int)
Sample a defined random number of conformations from the ensemble trajectory.
- Parameters:
sample_size (int) – Number of conformations sampled from the ensemble.
- property reduce_dim_data: Dict[str, ndarray]
Get the transformed data associated with each ensemble.
- Returns:
A dictionary where keys are ensemble IDs and values are the corresponding feature arrays.
- Return type:
Dict[str, np.ndarray]
- reduce_features(method: str, fit_on: List[str] = None, *args, **kwargs) ndarray
Perform dimensionality reduction on the extracted features.
- Parameters:
method (The following optional parameters apply based on the selected reduction) – Choose between “pca”, “tsne”, “kpca” and “umap”.
fit_on (List[str], optional) – if method is “pca” or “kpca”, specifies on which ensembles the models should be fit. The model will then be used to transform all ensembles.
Parameters (Additional) –
--------------------- –
method –
pca (-) –
- num_dimint, optional
Number of components to keep. Default is 10.
tsne (-) –
- perplexity_valsList[float], optional
List of perplexity values. Default is range(2, 10, 2).
- metricstr, optional
Metric to use. Default is “euclidean”.
- circularbool, optional
Whether to use circular metrics. Default is False.
- n_componentsint, optional
Number of dimensions of the embedded space. Default is 2.
- learning_ratefloat, optional
Learning rate. Default is 100.0.
- range_n_clustersList[int], optional
Range of cluster values. Default is range(2, 10, 1).
kpca (-) –
- circularbool, optional
Whether to use circular metrics. Default is False.
- num_dimint, optional
Number of components to keep. Default is 10.
- gammafloat, optional
Kernel coefficient. Default is None.
- Returns:
np.ndarray – Returns the transformed data.
For more information on each method, see the corresponding documentation –
- property trajectories: Dict[str, Trajectory]
Get the trajectories associated with each ensemble.
- Returns:
A dictionary where keys are ensemble IDs and values are the corresponding MDTraj trajectories.
- Return type:
Dict[str, mdtraj.Trajectory]
dpet.visualization module
- class dpet.visualization.Visualization(analysis: EnsembleAnalysis)
Bases:
object
Visualization class for ensemble analysis.
- Parameters:
analysis (EnsembleAnalysis) – An instance of EnsembleAnalysis providing data for visualization.
- alpha_angles(bins: int = 50, save: bool = False, ax: Axes = None) Axes
Plot the distribution of alpha angles.
- Parameters:
bins (int) – The number of bins for the histogram. Default is 50.
save (bool, optional) – If True, the plot will be saved as an image file. Default is False.
ax (plt.Axes, optional) – The axes on which to plot. Default is None, which creates a new figure and axes.
- Returns:
The Axes object containing the plot.
- Return type:
plt.Axes
- asphericity(bins: int = 50, hist_range: Tuple = None, violin_plot: bool = True, location: str = 'mean', save: bool = False, color: str = 'blue', multiple_hist_ax: bool = False, ax: Union[None, Axes, ndarray, List[Axes]] = None) Axes
Plot asphericity distribution in each ensemble. Asphericity is calculated based on the gyration tensor.
- Parameters:
bins (int, optional) – The number of bins for the histogram. Default is 50.
hist_range (Tuple, optional) – A tuple with a min and max value for the histogram. Default is None, which corresponds to using the min a max value across all data.
violin_plot (bool, optional) – If True, a violin plot is visualized. Default is True.
location (str, optional) – Select between “median” or “mean” or “both” to show in violin plot. Default value is “mean”.
save (bool, optional) – If True, the plot will be saved as an image file. Default is False.
color (str, optional) – Color of the violin plot. Default is blue.
multiple_hist_ax (bool, optional) – If True, each histogram will be plotted on separate axes. Default is False.
ax (Union[None, plt.Axes, np.ndarray, List[plt.Axes]], optional) – The axes on which to plot. Default is None, which creates a new figure and axes.
- Returns:
The Axes object containing the plot.
- Return type:
plt.Axes
- average_distance_maps(ticks_fontsize: int = 14, cbar_fontsize: int = 14, title_fontsize: int = 14, dpi: int = 96, use_ylabel: bool = True, save: bool = False, ax: Union[None, List[List[Axes]], List[Axes]] = None) List[Axes]
Plot the average distance maps for selected ensembles.
- Parameters:
ticks_fontsize (int, optional) – Font size for tick labels on the plot axes. Default is 14.
cbar_fontsize (int, optional) – Font size for labels on the color bar. Default is 14.
title_fontsize (int, optional) – Font size for titles of individual subplots. Default is 14.
dpi (int, optional) – Dots per inch (resolution) of the output figure. Default is 96.
use_ylabel (bool, optional) – If True, y-axis labels are displayed on the subplots. Default is True.
save (bool, optional) – If True, the plot will be saved as an image file. Default is False.
ax (Union[None, List[List[plt.Axes]], List[plt.Axes]], optional) – A list or 2D list of Axes objects to plot on. Default is None, which creates new axes.
- Returns:
Returns a 1D list of Axes objects representing the subplot grid.
- Return type:
List[plt.Axes]
Notes
This method plots the average distance maps for selected ensembles, where each distance map represents the average pairwise distances between residues in a protein structure.
- ca_com_distances(min_sep: int = 2, max_sep: Optional[int] = None, get_names: bool = True, inverse: bool = False, save: bool = False, ax: Union[None, Axes, ndarray, List[Axes]] = None) List[Axes]
Plot the distance maps comparing the center of mass (COM) and alpha-carbon (CA) distances within each ensemble.
- min_sepint, optional
Minimum separation distance between atoms to consider. Default is 2.
- max_sepint or None, optional
Maximum separation distance between atoms to consider. Default is None, which means no maximum separation.
- get_namesbool, optional
Whether to get the residue names for the features. Default is True.
- inversebool, optional
Whether to compute the inverse distances. Default is False.
- figsizetuple, optional
Figure size in inches (width, height). Default is (6, 2.5).
- savebool, optional
If True, save the plot as an image file. Default is False.
- List[plt.Axes]
A list containing Axes objects corresponding to the plots for CA and COM distances.
This method plots the average distance maps for the center of mass (COM) and alpha-carbon (CA) distances within each ensemble. It computes the distance matrices for COM and CA atoms and then calculates their mean values to generate the distance maps. The plots include color bars indicating the distance range.
- comparison_matrix(score: str, featurization_params: dict = {}, bootstrap_iters: int = None, bootstrap_frac: float = 1.0, bootstrap_replace: bool = True, confidence_level: float = 0.95, significance_level: float = 0.05, bins: Union[int, str] = 50, random_seed: int = None, verbose: bool = False, ax: Union[None, Axes] = None, figsize: Tuple[int] = (6.0, 5.0), dpi: int = 100, cmap: str = 'viridis_r', title: str = None, cbar_label: str = None, textcolors: Union[str, tuple] = ('black', 'white')) dict
Generates and visualizes the pairwise comparison matrix for the ensembles. This function computes the comparison matrix using the specified score type and feature. It then visualizes the matrix using a heatmap.
score, featurization_params, bootstrap_iters, bootstrap_frac, bootstrap_replace, bins, random_seed, verbose:
See the documentation of EnsembleAnalysis.comparison_scores for more information about these arguments.
- ax: Union[None, plt.Axes], optional
Axes object where to plot the comparison heatmap. If None (the default value) is provided, a new Figure will be created.
- figsize: Tuple[int], optional
The size of the figure for the heatmap. Default is (6.00, 5.0). Only takes effect if ax is not None.
- dpi: int, optional
DPIs of the figure for the heatmap. Default is 100. Only takes effect if ax is not None.
confidence_level, significance_level, cmap, title, cbar_label, textcolors:
See the documentation of dpet.visualization.plot_comparison_matrix for more information about these arguments.
- results: dict
- A dictionary containing the following keys:
ax: the Axes object with the comparison matrix heatmap. scores: comparison matrix. See EnsembleAnalysis.comparison_scores
for more information.
codes: codes of the ensembles that were compared. fig: Figure object, only returned when a new figure is created
inside this function.
The comparison matrix is annotated with the scores, and the axes are labeled with the ensemble labels.
- contact_prob_maps(log_scale: bool = True, avoid_zero_count: bool = False, threshold: float = 0.8, dpi: int = 96, save: bool = False, cmap_color: str = 'Blues', ax: Union[None, List[Axes], ndarray] = None) Union[List[Axes], ndarray]
- dimensionality_reduction_scatter(color_by: str = 'rg', save: bool = False, ax: Union[None, List[Axes]] = None, kde_by_ensemble: bool = False, size: int = 10, plotly=False, n_comp=2) List[Axes]
Plot the results of dimensionality reduction using the method specified in the analysis.
- Parameters:
color_by (str, optional) – The feature extraction method used for coloring points in the scatter plot. Options are “rg”, “prolateness”, “asphericity”, “sasa”, and “end_to_end”. Default is “rg”.
save (bool, optional) – If True, the plot will be saved in the data directory. Default is False.
ax (Union[None, List[plt.Axes]], optional) – A list of Axes objects to plot on. Default is None, which creates new axes.
kde_by_ensemble (bool, optional) – If True, the KDE plot will be generated for each ensemble separately. If False, a single KDE plot will be generated for the concatenated ensembles. Default is False.
- Returns:
List containing Axes objects for the scatter plot of original labels, clustering labels, and feature-colored labels, respectively.
- Return type:
List[plt.Axes]
- Raises:
NotImplementedError – If the dimensionality reduction method specified in the analysis is not supported.
- end_to_end_distances(rg_norm: bool = False, bins: int = 50, hist_range: Tuple = None, violin_plot: bool = True, location: str = 'mean', dpi=96, save: bool = False, color: str = 'blue', multiple_hist_ax=False, ax: Union[None, Axes, ndarray, List[Axes]] = None) Union[Axes, List[Axes]]
Plot end-to-end distance distributions.
- Parameters:
rg_norm (bool, optional) – Normalize end-to-end distances on the average radius of gyration.
bins (int, optional) – The number of bins for the histogram. Default is 50.
hist_range (Tuple, optional) – A tuple with a min and max value for the histogram. Default is None, which corresponds to using the min a max value across all data.
violin_plot (bool, optional) – If True, a violin plot is visualized. Default is True.
location (str, optional) – Select between “median” or “mean” or “both” to show in violin plot. Default value is “mean”
save (bool, optional) – If True, the plot will be saved as an image file. Default is False.
ax (Union[None, plt.Axes, np.ndarray, List[plt.Axes]], optional) – The axes on which to plot. Default is None, which creates a new figure and axes.
color (str, optional) – Change the color of the violin plot
multiple_hist_ax (bool, optional) – If True, it will plot each histogram in a different axis.
- Returns:
The Axes object or a list of Axes objects containing the plot(s).
- Return type:
Union[plt.Axes, List[plt.Axes]]
- global_sasa(bins: int = 50, hist_range: Tuple = None, violin_plot: bool = True, location: str = 'mean', save: bool = False, dpi=96, color: str = 'blue', multiple_hist_ax: bool = False, ax: Union[None, Axes, ndarray, List[Axes]] = None) Axes
Plot the distribution of SASA for each conformation within the ensembles.
- Parameters:
bins (int, optional) – The number of bins for the histogram. Default is 50.
hist_range (Tuple, optional) – A tuple with a min and max value for the histogram. Default is None, which corresponds to using the min a max value across all data.
violin_plot (bool, optional) – If True, a violin plot is visualized. Default is True.
location (str, optional) – Select between “median” or “mean” or “both” to show in violin plot. Default is “mean”.
save (bool, optional) – If True, the plot will be saved in the data directory. Default is False.
color (str, optional) – Color of the violin plot. Default is blue.
multiple_hist_ax (bool, optional) – If True, it will plot each histogram in a different axis.
ax (Union[None, plt.Axes, np.ndarray, List[plt.Axes]], optional) – The matplotlib Axes object on which to plot. If None, a new Axes object will be created. Default is None.
- Returns:
The Axes object containing the plot.
- Return type:
plt.Axes
- pca_1d_histograms(save: bool = False, sel_dim=1, ax: Union[None, List[Axes]] = None) List[Axes]
Plot 1D histogram when the dimensionality reduction method is “pca” or “kpca”.
- Parameters:
save (bool, optional) – If True the plot will be saved in the data directory. Default is False.
ax (Union[None, List[plt.Axes]], optional) – A list of Axes objects to plot on. Default is None, which creates new axes.
selected_dim (int, optional) – To select the specific component (dimension) for which you want to visualize the histogram distribution. Default is 1.
- Returns:
A list of plt.Axes objects representing the subplots created.
- Return type:
List[plt.Axes]
- pca_2d_landscapes(save: bool = False, ax: Union[None, List[Axes]] = None) List[Axes]
Plot 2D landscapes when the dimensionality reduction method is “pca” or “kpca”.
- Parameters:
save (bool, optional) – If True the plot will be saved in the data directory. Default is False.
ax (Union[None, List[plt.Axes]], optional) – A list of Axes objects to plot on. Default is None, which creates new axes.
- Returns:
A list of plt.Axes objects representing the subplots created.
- Return type:
List[plt.Axes]
- pca_cumulative_explained_variance(save: bool = False, ax: Union[None, Axes] = None) Axes
Plot the cumulative variance. Only applicable when the dimensionality reduction method is “pca”.
- Parameters:
save (bool, optional) – If True, the plot will be saved in the data directory. Default is False.
ax (Union[None, plt.Axes], optional) – An Axes object to plot on. Default is None, which creates a new axes.
- Returns:
The Axes object for the cumulative explained variance plot.
- Return type:
plt.Axes
- pca_residue_correlation(sel_dims: List[int], save: bool = False, ax: Union[None, List[Axes]] = None) List[Axes]
Plot the correlation between residues based on PCA weights.
- Parameters:
sel_dims (List[int]) – A list of indices specifying the PCA dimensions to include in the plot.
save (bool, optional) – If True, the plot will be saved as an image file. Default is False.
ax (Union[None, List[plt.Axes]], optional) – A list of Axes objects to plot on. Default is None, which creates new axes.
- Returns:
A list of plt.Axes objects representing the subplots created.
- Return type:
List[plt.Axes]
Notes
This method generates a correlation plot showing the weights of pairwise residue distances for selected PCA dimensions. The plot visualizes the correlation between residues based on the PCA weights.
The analysis is only valid on PCA and kernel PCA dimensionality reduction with ‘ca_dist’ feature extraction.
- pca_rg_correlation(save: bool = False, ax: Union[None, List[Axes]] = None) List[Axes]
Examine and plot the correlation between PC dimension 1 and the amount of Rg. Typically high correlation can be detected in case of IDPs/IDRs .
- Parameters:
save (bool, optional) – If True, the plot will be saved in the data directory. Default is False.
ax (Union[None, List[plt.Axes]], optional) – A list of Axes objects to plot on. Default is None, which creates new axes.
- Returns:
A list of plt.Axes objects representing the subplots created.
- Return type:
List[plt.Axes]
- per_residue_mean_sasa(figsize: Tuple[int, int] = (15, 5), pointer: List[int] = None, save: bool = False, ax: Union[None, Axes] = None) Axes
Plot the average solvent-accessible surface area (SASA) for each residue among all conformations in an ensemble.
- Parameters:
figsize (Tuple[int, int], optional) – Tuple specifying the size of the figure. Default is (15, 5).
pointer (List[int], optional) – List of desired residues to highlight with vertical dashed lines. Default is None.
save (bool, optional) – If True, the plot will be saved as an image file. Default is False.
ax (Union[None, plt.Axes], optional) – The matplotlib Axes object on which to plot. If None, a new Axes object will be created. Default is None.
- Returns:
Axes object containing the plot.
- Return type:
plt.Axes
- plot_histogram_grid(feature: str = 'ca_dist', ids: Union[ndarray, List[list]] = None, n_rows: int = 2, n_cols: int = 3, subplot_width: int = 2.0, subplot_height: int = 2.2, bins: Union[str, int] = None, dpi: int = 90) Axes
Plot a grid if histograms for distance or angular features. Can only be be used when analyzing ensembles of proteins with same number of residues. The function will create a new matplotlib figure for histogram grid.
- Parameters:
feature (str, optional) – Feature to analyze. Must be one of ca_dist (Ca-Ca distances), a_angle (alpha angles), phi or psi (phi or psi backbone angles).
ids (Union[list, List[list]], optional) – Residue indices (integers starting from zero) to define the residues to analyze. For angular features it must be a 1d list with N indices of the residues. For distance features it must be 2d list/array of shape (N, 2) in which N is the number of residue pairs to analyze are 2 their indices. Each of the N indices (or pair of indices) will be plotted in an histogram of the grid. If this argument is not provided, random indices will be sampled, which is useful for quickly comparing the distance or angle distributions of multiple ensembles.
n_rows (int, optional) – Number of rows in the histogram grid.
n_cols (int, optional) – Number of columns in the histogram grid.
subplot_width (int, optional) – Use to specify the Matplotlib width of the figure. The size of the figure will be calculated as: figsize = (n_cols*subplot_width, n_rows*subplot_height).
subplot_height (int, optional) – See the subplot_width argument.
bins (Union[str, int], optional) – Number of bins in all the histograms.
dpi (int, optional) – DPI of the figure.
- Returns:
ax – The Axes object for the histogram grid.
- Return type:
plt.Axes
- plot_rama_grid(ids: Union[ndarray, List[list]] = None, n_rows: int = 2, n_cols: int = 3, subplot_width: int = 2.0, subplot_height: int = 2.2, dpi: int = 90) Axes
Plot a grid if Ramachandran plots for different residues. Can only be be used when analyzing ensembles of proteins with same number of residues. The function will create a new matplotlib figure for the scatter plot grid.
- Parameters:
ids (Union[list, List[list]], optional) – Residue indices (integers starting from zero) to define the residues to analyze. For angular features it must be a 1d list with N indices of the residues. Each of the N indices will be plotted in an scatter plot in the grid. If this argument is not provided, random indices will be sampled, which is useful for quickly comparing features of multiple ensembles.
n_rows (int, optional) – Number of rows in the scatter grid.
n_cols (int, optional) – Number of columns in the scatter grid.
subplot_width (int, optional) – Use to specify the Matplotlib width of the figure. The size of the figure will be calculated as: figsize = (n_cols*subplot_width, n_rows*subplot_height).
subplot_height (int, optional) – See the subplot_width argument.
dpi (int, optional) – DPI of the figure.
- Returns:
ax – The Axes object for the scatter plot grid.
- Return type:
plt.Axes
- prolateness(bins: int = 50, hist_range: Tuple = None, violin_plot: bool = True, location: str = 'mean', save: bool = False, color: str = 'blue', multiple_hist_ax: bool = False, ax: Union[None, Axes, ndarray, List[Axes]] = None) Axes
Plot prolateness distribution in each ensemble. Prolateness is calculated based on the gyration tensor.
- Parameters:
bins (int, optional) – The number of bins for the histogram. Default is 50.
hist_range (Tuple, optional) – A tuple with a min and max value for the histogram. Default is None, which corresponds to using the min a max value across all data.
violin_plot (bool, optional) – If True, a violin plot is visualized. Default is True.
location (str, optional) – Select between “median”, “mean”, or “both” to show in violin plot. Default is “mean”.
save (bool, optional) – If True, the plot will be saved as an image file. Default is False.
color (str, optional) – Color of the violin plot. Default is blue.
multiple_hist_ax (bool, optional) – If True, each histogram will be plotted on separate axes. Default is False.
ax (Union[None, plt.Axes, np.ndarray, List[plt.Axes]], optional) – The axes on which to plot. Default is None, which creates a new figure and axes.
- Returns:
The Axes object containing the plot.
- Return type:
plt.Axes
- radius_of_gyration(bins: int = 50, hist_range: Tuple = None, multiple_hist_ax: bool = False, violin_plot: bool = False, location: str = 'mean', dpi: int = 96, save: bool = False, ax: Union[None, Axes, ndarray, List[Axes]] = None, color: str = 'blue') Union[Axes, List[Axes]]
Plot the distribution of the radius of gyration (Rg) within each ensemble.
- Parameters:
bins (int, optional) – The number of bins for the histogram. Default is 50.
hist_range (Tuple, optional) – A tuple with a min and max value for the histogram. Default is None, which corresponds to using the min and max value across all data.
multiple_hist_ax (bool, optional) – If True, it will plot each histogram in a different axis.
violin_plot (bool, optional) – If True, a violin plot is visualized. Default is False.
location (str, optional) – Select between “median” or “mean” or “both” to show in violin plot. Default value is “mean”
dpi (int, optional) – The DPI (dots per inch) of the output figure. Default is 96.
save (bool, optional) – If True, the plot will be saved as an image file. Default is False.
ax (Union[None, plt.Axes, np.ndarray, List[plt.Axes]], optional) – The axes on which to plot. If None, new axes will be created. Default is None.
- Returns:
Returns a single Axes object or a list of Axes objects containing the plot(s).
- Return type:
Union[plt.Axes, List[plt.Axes]]
Notes
This method plots the distribution of the radius of gyration (Rg) within each ensemble in the analysis.
The Rg values are binned according to the specified number of bins (bins) and range (hist_range) and displayed as histograms. Additionally, dashed lines representing the mean and median Rg values are overlaid on each histogram.
- ramachandran_plots(two_d_hist: bool = True, linespaces: Tuple = (- 180, 180, 80), save: bool = False, ax: Union[None, Axes, ndarray, List[Axes]] = None) Union[List[Axes], Axes]
Ramachandran plot. If two_d_hist=True it returns a 2D histogram for each ensemble. If two_d_hist=False it returns a simple scatter plot for all ensembles in one plot.
- Parameters:
two_d_hist (bool, optional) – If True, it returns a 2D histogram for each ensemble. Default is True.
linespaces (tuple, optional) – You can customize the bins for 2D histogram. Default is (-180, 180, 80).
save (bool, optional) – If True, the plot will be saved as an image file. Default is False.
ax (Union[None, plt.Axes, np.ndarray, List[plt.Axes]], optional) – The axes on which to plot. If None, new axes will be created. Default is None.
- Returns:
If two_d_hist=True, returns a list of Axes objects representing the subplot grid for each ensemble. If two_d_hist=False, returns a single Axes object representing the scatter plot for all ensembles.
- Return type:
Union[List[plt.Axes], plt.Axes]
- relative_dssp_content(dssp_code='H', save: bool = False, ax: Axes = None) Axes
Plot the relative ss content in each ensemble for each residue.
- Parameters:
save (bool, optional) – If True, the plot will be saved in the data directory. Default is False.
ax (plt.Axes, optional) – The axes on which to plot. Default is None, which creates a new figure and axes.
dssp_code (str, optional) – The selected dssp code , it could be selected between ‘H’ for Helix, ‘C’ for Coil and ‘E’ for strand. It works based on the simplified DSSP codes
- Returns:
The Axes object containing the plot.
- Return type:
plt.Axes
- rg_vs_asphericity(save: bool = False, ax: Axes = None) Axes
Plot the Rg versus Asphericity and get the pearson correlation coefficient to evaluate the correlation between Rg and Asphericity.
- Parameters:
save (bool, optional) – If True, the plot will be saved in the data directory. Default is False.
ax (plt.Axes, optional) – The axes on which to plot. Default is None, which creates a new figure and axes.
- Returns:
The Axes object containing the plot.
- Return type:
plt.Axes
- rg_vs_prolateness(save: bool = False, ax: Axes = None) Axes
Plot the Rg versus Prolateness and get the Pearson correlation coefficient to evaluate the correlation between Rg and Prolateness.
- Parameters:
save (bool, optional) – If True, the plot will be saved in the data directory. Default is False.
ax (plt.Axes, optional) – The axes on which to plot. Default is None, which creates a new figure and axes.
- Returns:
The Axes object containing the plot.
- Return type:
plt.Axes
- ss_flexibility(pointer: List[int] = None, figsize: Tuple[int, int] = (15, 5), save: bool = False, ax: Union[None, Axes] = None) Axes
Generate a plot of the site-specific flexibility parameter.
This plot shows the site-specific measure of disorder, which is sensitive to local flexibility based on the circular variance of the Ramachandran angles φ and ψ for each residue in the ensemble. The score ranges from 0 for identical dihedral angles for all conformers at the residue i to 1 for a uniform distribution of dihedral angles at the residue i.
- Parameters:
pointer (List[int], optional) – A list of desired residues. Vertical dashed lines will be added to point to these residues. Default is None.
figsize (Tuple[int, int], optional) – The size of the figure. Default is (15, 5).
save (bool, optional) – If True, save the plot as an image file. Default is False.
ax (Union[None, plt.Axes], optional) – The matplotlib Axes object on which to plot. If None, a new Axes object will be created. Default is None.
- Returns:
The matplotlib Axes object containing the plot.
- Return type:
plt.Axes
- ss_order(pointer: List[int] = None, figsize: Tuple[int, int] = (15, 5), save: bool = False, ax: Union[None, Axes] = None) Axes
Generate a plot of the site-specific order parameter.
This plot shows the site-specific order parameter, which abstracts from local chain flexibility. The parameter is still site-specific, as orientation correlations in IDRs and IDPs decrease with increasing sequence distance.
- Parameters:
pointer (List[int], optional) – A list of desired residues. Vertical dashed lines will be added to point to these residues. Default is None.
figsize (Tuple[int, int], optional) – The size of the figure. Default is (15, 5).
save (bool, optional) – If True, the plot will be saved as an image file. Default is False.
ax (Union[None, plt.Axes], optional) – The matplotlib Axes object on which to plot. If None, a new Axes object will be created. Default is None.
- Returns:
The matplotlib Axes object containing the plot.
- Return type:
plt.Axes
- dpet.visualization.plot_comparison_matrix(ax: Axes, comparison_out: ndarray, codes: List[str], confidence_level: float = 0.95, significance_level: float = 0.05, cmap: str = 'viridis_r', title: str = 'New Comparison', cbar_label: str = 'score', textcolors: Union[str, tuple] = ('black', 'white'))
Plot a matrix with all-vs-all comparison scores of M ensembles as a heatmap. If plotting the results of a regular all-vs-all analysis (no bootstraping involved), it will just plot the M x M comparison scores, with empty values on the diagonal. If plotting the results of an all-vs-all analysis with bootstrapping it will plot the M x M confidence intervals for the scores. The intervals are obtained by using the ‘percentile’ method. Additionally, it will plot an asterisk for those non-diagonal entries in for which the inter-ensemble scores are significantly higher than the intra-ensemble scores according to a Mann–Whitney U test.
- Parameters:
ax (plt.Axes) – Axes object where the heatmap should be created.
comparison_out (dict) – A dictionary containing the output of the comparison_scores method of the dpet.ensemble_analysis.EnsembleAnalysis class. It must contain the following key-value pairs: scores: NumPy array with shape (M, M, B) containing the comparison scores for M ensembles and B bootstrap iterations. If no bootstrap analysis was performed, B = 1, otherwise it will be B > 1. p_values (optional): used only when a bootstrap analysis was performed. A (M, M) NumPy array storiging the p-values obtained by comparing with a statistical test the inter-ensemble and intra-ensemble comparison scores.
codes (List[str]) – List of strings with the codes of the ensembles.
confidence_level (float, optional) – Condifence level for the bootstrap intervals of the comparison scores.
significance_level (float, optional) – Significance level for the statistical test used to compare inter and intra-ensemble comparison scores.
cmap (str, optional) – Matplotlib colormap name to use in the heatmap.
title (str, optional) – Title of the heatmap.
cbar_label (str, optional) – Label of the colorbar.
textcolors (Union[str, tuple], optional) – Color of the text for each cell of the heatmap, specified as a string. By providing a tuple with two elements, the two colors will be applied to cells with color intensity above/below a certain threshold, so that ligher text can be plotted in darker cells and darker text can be plotted in lighter cells.
- Returns:
ax – The same updated Axes object from the input. The comparison_out will be updated to store confidence intervals if performing a bootstrap analysis.
- Return type:
plt.Axes
Notes
The comparison matrix is annotated with the scores, and the axes are labeled with the ensemble labels.
- dpet.visualization.plot_histogram(ax: Axes, data: List[ndarray], labels: List[str], bins: Union[int, List] = 50, range: Tuple = None, title: str = 'Histogram', xlabel: str = 'x', ylabel: str = 'Density')
Plot an histogram for different features.
- Parameters:
ax (plt.Axes) – Matplotlib axis object where the histograms will be for plotted.
data (List[np.array]) – List of NumPy array storing the data to be plotted.
labels (List[str]) – List of strings with the labels of the arrays.
bins – Number of bins.
range (Tuple, optional) – A tuple with a min and max value for the histogram. Default is None, which corresponds to using the min a max value across all data.
title (str, optional) – Title of the axis object.
xlabel (str, optional) – Label of the horizontal axis.
ylabel (str, optional) – Label of the vertical axis.
- Returns:
Axis objects for the histogram plot of original labels.
- Return type:
plt.Axes
- dpet.visualization.plot_violins(ax: Axes, data: List[ndarray], labels: List[str], location: str = 'mean', title: str = 'Histogram', xlabel: str = 'x', color: str = 'blue')
Make a violin plot.
- Parameters:
ax (plt.Axes) – Matplotlib axis object where the histograms will be for plotted.
data (List[np.array]) – List of NumPy array storing the data to be plotted.
labels (List[str]) – List of strings with the labels of the arrays.
location (str, optional) – Select between “median” or “mean” to show in violin plot. Default value is “mean”
title (str, optional) – Title of the axis object.
xlabel (str, optional) – Label of the horizontal axis.
- Returns:
Axis objects for the histogram plot of original labels.
- Return type:
plt.Axes