### Apply Distance Cutoff in Simulation Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt This example shows how to apply a previously determined distance cutoff in a simulation setup. This can optimize performance by reducing the number of pairwise interactions calculated. ```python from MDAnalysis.special.distances import dist_cutoff # Assuming 'universe' and 'cutoff' are already defined # Apply the cutoff to select atom pairs within the cutoff distance close_pairs = dist_cutoff(universe.atoms, universe.atoms, cutoff) # 'close_pairs' now contains indices of atom pairs within the cutoff ``` -------------------------------- ### Install PyLipID using pip Source: https://pylipid.readthedocs.io/en/master/INSTALL.html Use pip to install the PyLipID package. Ensure all dependencies are met before installation. ```bash $ pip install pylipid ``` -------------------------------- ### Install PyLipID from Source Source: https://pylipid.readthedocs.io/en/master/index.html Install the latest source code of PyLipID from GitHub. This method is useful for developers or those who need the most recent updates. ```bash git clone git://github.com/wlsong/PyLipID.git python setup.py install ``` -------------------------------- ### Import Libraries and Print Version Source: https://pylipid.readthedocs.io/en/master/tutorials/1-Distance_cutoff_determination.html Imports necessary libraries for PyLipID analysis and prints the installed version. Ensure you are using a version later than 1.4 for script compatibility. ```python %matplotlib inline import numpy as np import matplotlib.pyplot as plt import pylipid from pylipid.api import LipidInteraction print(pylipid.__version__) # the following script works for versions later than 1.4 ``` -------------------------------- ### Import PyLipID and Check Version Source: https://pylipid.readthedocs.io/en/master/tutorials/0-application-walk-through.html Imports the necessary PyLipID library and checks if the installed version is compatible. Ensure your PyLipID version is later than 1.4. ```python %matplotlib inline import pylipid from pylipid.api import LipidInteraction print(pylipid.__version__) # make sure pylipid version is later than 1.4 ``` -------------------------------- ### Import Libraries for Distance Analysis Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Import necessary libraries for numerical operations, plotting, and trajectory analysis. Ensure you have MDAnalysis installed for trajectory handling. ```python import MDAnalysis as mda import MDAnalysis.analysis.distances as mda_dist import matplotlib.pyplot as plt import numpy as np from scipy.signal import savgol_filter ``` -------------------------------- ### Load Trajectory and Select Atoms Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Load a molecular dynamics trajectory and topology file. Select the specific atoms or groups for which you want to calculate distances. This example selects all heavy atoms. ```python u = mda.Universe("../common/complex.pdb", "../common/complex.xtc") # Select all heavy atoms selection = "protein or resname LIG" # Select all heavy atoms # selection = "all" # Select specific atoms, e.g., protein backbone # selection = "backbone" ``` -------------------------------- ### Iterate through distance cutoffs for analysis Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Provides an example of iterating through multiple distance cutoffs to perform and save PyLipid analysis for each. This allows for comprehensive analysis across different proximity thresholds. ```python from pylipid import PyLipid # Define a list of distance cutoffs to test cutoffs = [0.8, 1.0, 1.2] for cutoff in cutoffs: lipid_analysis = PyLipid(cutoff=cutoff) lipid_analysis.run_analysis(trajectory='trajectory.xtc', topology='topology.pdb') ``` -------------------------------- ### Set up simulation paths Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Define the paths to your simulation data, including the trajectory and topology files. ```python path = "/websites/pylipid_readthedocs_io_en_master" trajs = [os.path.join(path, "1-Distance_cutoff_determination/trajectory.xtc")] top = os.path.join(path, "1-Distance_cutoff_determination/topology.pdb") ``` -------------------------------- ### Get contact information for a specific lipid, protein residue, and interaction type Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Provides an example of retrieving highly specific contact information involving a particular lipid type, protein residue, and interaction type, using a defined distance cutoff. This offers the most granular level of interaction analysis. ```python from pylipid import PyLipid # Load results for a 1.0 nm distance cutoff results = PyLipid.load(results_path='results/run_1.0nm', cutoff=1.0) # Get POPC-residue 100 lipid-water contacts popc_residue_water_contacts = results.get_contact_info(lipid_type='POPC', residue_id=100, interaction_type='lipid-water') ``` -------------------------------- ### Initialize Pylipid Analyzer Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Instantiate the Pylipid Analyzer with simulation trajectory and topology files. This is the first step in setting up any pylipid analysis. ```python from pylipid import Pylipid # Define paths to trajectory and topology files trajectory_file = "/path/to/your/trajectory.xtc" topology_file = "/path/to/your/topology.pdb" # Initialize the Pylipid Analyzer # The 'n_jobs' parameter can be adjusted based on your system's cores # The 'cut_off' parameter is the distance cutoff for lipid-protein interactions # The 'step' parameter defines the frame interval for analysis # The 'overwrite' parameter ensures that previous results are overwritten if set to True lipid_analyzer = Pylipid(trajectory_file, topology_file, n_jobs=1, cut_off=1.0, step=10, overwrite=True) ``` -------------------------------- ### Initialize and run the analysis Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Create an Analysis object and run the simulation analysis using the defined paths and milestones. ```python # Initialize the Analysis object # The 'lagtime' parameter is crucial for timescale calculations. # Here, it's set to 100, meaning we consider correlations over 100 time steps. # The 'nsets' parameter specifies the number of bootstrap sets for statistical analysis. # Setting nsets=100 provides a reasonable estimate of uncertainty. analysis = Analysis(lagtime=100, nsets=100, trajs=trajs, top=top, milestones=milestones) # Run the analysis # This step computes various properties like committor probabilities, rate constants, etc. # The 'save_rate' and 'save_committor' flags enable saving the results to files. # 'save_rate=True' saves the calculated rate constants. # 'save_committor=True' saves the committor probabilities. analysis.run(save_rate=True, save_committor=True) ``` -------------------------------- ### PyLipid Initialization Parameters Source: https://pylipid.readthedocs.io/en/master/_modules/pylipid/api/api.html Illustrates the various parameters used when initializing a PyLipid object, including trajectory and topology file lists, cutoffs, lipid and protein information, and output settings. ```python def __init__(self, lipid, lipid_atoms, trajfile_list, topfile_list=None, cutoffs=1.0, nprot=1, resi_offset=0, save_dir=None, timeunit="us", stride=1, dt_traj=None): """Initialize PyLipid. Parameters ---------- lipid : str Lipid residue name. lipid_atoms : list Lipid atom names. trajfile_list : list Trajectory filenames. topfile_list : list, default=None Topology filenames. If None, it will be inferred from trajfile_list. cutoffs : float or list, default=1.0 Cutoffs for calculating contacts. If a scalar is provided, it will be used for both inner and outer cutoffs. If a list of two scalars is provided, the first will be the inner cutoff and the second will be the outer cutoff. The cutoffs will be sorted in ascending order. nprot : int, default=1 Number of protein copies in the system. Default is 1. resi_offset : int, default=0 Shift residue index in the reported results from what is shown in the topology. Can be useful for MARTINI force field. save_dir : str, default=None The root directory to store the generated data. By default, a directory Interaction_{lipid} will be created in the current working directory, under which all the generated data are stored. timeunit : {"us", "ns"}, default="us" The time unit used for reporting results. "us" is micro-second and "ns" is nanosecond. stride : int, default=1 Only read every stride-th frame. The same stride in mdtraj.load(). dt_traj : float, default=None Timestep of trajectories. It is required when trajectories do not have timestep information. Not needed for trajectory formats of e.g. xtc, trr etc. If None, timestep information will take from trajectories. """ self._trajfile_list = np.atleast_1d(trajfile_list) if len(np.atleast_1d(topfile_list)) == len(self._trajfile_list): self._topfile_list = np.atleast_1d(topfile_list) elif len(self._trajfile_list) > 1 and len(np.atleast_1d(topfile_list)) == 1: self._topfile_list = [topfile_list for dummy in self._trajfile_list] else: raise ValueError( "topfile_list should either have the same length as trajfile_list or have one valid file name.") if len(np.atleast_1d(cutoffs)) == 1: self._cutoffs = np.array([np.atleast_1d(cutoffs)[0] for dummy in range(2)]) elif len(np.atleast_1d(cutoffs)) == 2: self._cutoffs = np.sort(np.array(cutoffs, dtype=float)) else: raise ValueError("cutoffs should be either a scalar or a list of two scalars.") self._dt_traj = dt_traj self._lipid = lipid self._lipid_atoms = lipid_atoms self._nprot = int(nprot) self._timeunit = timeunit self._stride = int(stride) self._resi_offset = resi_offset self.dataset = pd.DataFrame() self._save_dir = check_dir(os.getcwd(), "Interaction_{}".format(self._lipid)) if save_dir is None else check_dir(save_dir, "Interaction_{}".format(self._lipid)) return ``` -------------------------------- ### get_traj_info Source: https://pylipid.readthedocs.io/en/master/_sources/api/generated/pylipid.util.get_traj_info.rst.txt Get trajectory information. ```APIDOC ## get_traj_info ### Description Get trajectory information. ### Signature get_traj_info(traj_file) ### Parameters #### Path Parameters - **traj_file** (str) - Required - Path to the trajectory file. ### Returns - **traj_info** (dict) - A dictionary containing trajectory information. ``` -------------------------------- ### Get contact information for a specific lipid and interaction type Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Demonstrates how to get detailed contact information for a specific lipid type and interaction type (e.g., lipid-water) using a defined distance cutoff. This provides granular insights into molecular interactions. ```python from pylipid import PyLipid # Load results for a 1.0 nm distance cutoff results = PyLipid.load(results_path='results/run_1.0nm', cutoff=1.0) # Get lipid-water contacts for POPC popc_water_contacts = results.get_contact_info(lipid_type='POPC', interaction_type='lipid-water') ``` -------------------------------- ### Get Lipid Properties Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Retrieves headgroup and tail lengths for a specified lipid. This is a core function for calculating cutoffs. ```python from pylipid import Lipid # Example usage: # lipid = Lipid('POPC') # headgroup_length = lipid.headgroup_length # tail_length = lipid.tail_length ``` -------------------------------- ### Generate PyMol Script for Binding Site Visualization Source: https://pylipid.readthedocs.io/en/master/_modules/pylipid/util/pymol_script.html Writes a Python script to open a PyMol session. It loads receptor structure and interaction data, coloring residues by binding site and scaling spheres by residence time. Ensure the PDB file matches simulation topology. ```python import numpy as np import re import pymol from pymol import cmd pymol.finish_launching() ########## files to process ########## csv_file = "{CSV_FILE}" pdb_file = "{PDB}" ########## set the sphere scales to corresponding value ########## value_to_show = "Residence Time" ###### reading data from csv file ########## num_of_binding_site = {N_BINDING_SITE} with open(csv_file, "r") as f: data_lines = f.readlines() column_names = data_lines[0].strip().split(",") for column_idx, column_name in enumerate(column_names): if column_name == "Residue": column_id_residue_list = column_idx elif column_name == "Residue ID": column_id_residue_index = column_idx elif column_name == "Binding Site ID": column_id_BS = column_idx elif column_name == value_to_show: column_id_value_to_show = column_idx residue_list = [] residue_rank_set = [] binding_site_identifiers = [] values_to_show = [] for line in data_lines[1:]: data_list = line.strip().split(",") residue_list.append(data_list[column_id_residue_list]) residue_rank_set.append(data_list[column_id_residue_index]) binding_site_identifiers.append(float(data_list[column_id_BS])) values_to_show.append(data_list[column_id_value_to_show]) ############## read information from pdb file ########## with open(pdb_file, "r") as f: pdb_lines = f.readlines() residue_identifiers = [] for line in pdb_lines: line_stripped = line.strip() if line_stripped[:4] == "ATOM": identifier = (line_stripped[22:26].strip(), line_stripped[17:20].strip(), line_stripped[21].strip()) ``` -------------------------------- ### Calculate Distance Cutoff Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Computes the distance cutoff based on the provided trajectory data. Requires the Pylipid library to be installed. ```python import pylipid # Load trajectory and topology traj = pylipid.io.load_trajectory("path/to/your/trajectory.xtc") top = pylipid.io.load_topology("path/to/your/topology.pdb") # Calculate distance cutoff dist_cutoff = pylipid.analysis.distance_cutoff(traj, top) print(f"Calculated distance cutoff: {dist_cutoff} nm") ``` -------------------------------- ### Calculate Distance Cutoff Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Calculates the distance cutoff for lipid-protein interactions based on simulation data. Requires Pylipid and MDAnalysis to be installed. ```python import MDAnalysis as mda from pylipid import Pylipid # Load trajectory and topology universe = mda.Universe("protein.pdb", "trajectory.xtc") # Initialize Pylipid pylipid = Pylipid(universe, "./") # Calculate distance cutoff pylipid.distance_cutoff_determination() ``` -------------------------------- ### Run PyLipid analysis with a distance cutoff Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Shows how to run the PyLipid analysis after initialization, applying the previously set distance cutoff. Ensure trajectory and topology files are correctly specified. ```python from pylipid import PyLipid lipid_analysis = PyLipid(cutoff=1.0) lipid_analysis.run_analysis(trajectory='trajectory.xtc', topology='topology.pdb') ``` -------------------------------- ### Initialize LipidInteraction Class Source: https://pylipid.readthedocs.io/en/master/tutorials/0-application-walk-through.html Sets up the LipidInteraction class with trajectory and topology file lists, lipid type, cutoffs, protein count, time unit, and save directory. This prepares the object for subsequent interaction analysis. ```python trajfile_list = ["./traj_data/A2a/run1/protein_lipids.xtc", "./traj_data/A2a/run2/protein_lipids.xtc"] topfile_list = ["./traj_data/A2a/run1/protein_lipids.gro", "./traj_data/A2a/run2/protein_lipids.gro"] lipid = "CHOL" cutoffs = [0.475, 0.8] # use of dual-cutoff nprot = 1 # num. of protein copies in the system. if the simulation system has N copies of receptors, # "nprot=N" will report interactions averaged from the N copies, but "nprot=1" # will ask pylipid to report interaction data for each copy. timeunit = 'us' # micro-second save_dir = None # if None, pylipid data will be saved at current working directory. # initialize li = LipidInteraction(trajfile_list, topfile_list=topfile_list, cutoffs=cutoffs, lipid=lipid, nprot=nprot, save_dir=save_dir) ``` -------------------------------- ### Load and Analyze Trajectory Data Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Loads trajectory data and calculates the distance between lipids and a molecule of interest. Requires Pylipid and MDAnalysis to be installed. ```python import pylipid import MDAnalysis as mda # Load trajectory and topology universe = mda.Universe("../topol.tpr", "../prod.xtc") # Define lipid and molecule selections lipids = universe.select_atoms("resname POPC") molecule = universe.select_atoms("resid 100 and name CA") # Calculate distances # This will save distances to distances.xtc and distances.dat pylipid.analysis.distance.Distance(universe, lipids, molecule, "distances") ``` -------------------------------- ### Load and Prepare Data Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Loads data from a CSV file and prepares it for analysis. Ensure the 'data.csv' file is in the correct directory. ```python import pandas as pd data = pd.read_csv('data.csv') print(data.head()) ``` -------------------------------- ### Calculate Distance Cutoff Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt This snippet calculates the distance cutoff for a given trajectory. Ensure the 'pylipid' library is installed and the trajectory file is accessible. ```python import pylipid import MDAnalysis # Load trajectory top = "/mnt/data/pylipid/1AKI/top.pdb" # traj = "/mnt/data/pylipid/1AKI/prod.xtc" traj = "/mnt/data/pylipid/1AKI/prod_short.xtc" # Load trajectory with MDAnalysis universe = MDAnalysis.Universe(top, traj) # Define the cluster center (e.g., center of mass of a specific residue) # For simplicity, we use the center of the whole system here center = universe.atoms.center_of_mass() # Calculate distance cutoff # The function will return the distance cutoff and the number of frames within that cutoff distance_cutoff, nframes = pylipid.utils.distance_cutoff(universe, center) ``` -------------------------------- ### Get Residence Times Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Retrieve the calculated lipid residence times. These values provide insights into how long lipids remain in the vicinity of the protein. ```python # Get the lipid residence times # This returns a dictionary containing residence times for each lipid residence_times = lipid_analyzer.get_residence_time() ``` -------------------------------- ### Initialize Dual Cutoff Scheme for Interaction Durations Source: https://pylipid.readthedocs.io/en/master/_modules/pylipid/func/interactions.html Sets up the parameters for calculating interaction durations using a dual-cutoff scheme. Requires lists of contacts within lower and upper cutoffs, and the simulation timestep. ```python class Duration: def __init__(self, contact_low, contact_high, dt): """Dual cutoff scheme for calculating the interaction durations. In the dual cutoff scheme, a continuous contact starts when a molecule moves closer than the lower distance cutoff and ends when the molecule moves out of the upper cutoff. The duration between these two time points is the duration of the contact. Here, the ``contact_low`` is the lipid index for the lower cutoff and ``contact_high`` is the lipid index for the upper cutoff. For calculation of contact durations, a lipid molecule that appears in the ``contact_low`` is searched in the subsequent frames of the ``contact_high`` and the search then stops if this molecule disappears from the ``contact_high``. This lipid molecule is labeled as 'checked', and the duration of this contact is calculated from the number of frames in which this lipid molecule appears in the lipid indices. This calculation iterates until all lipid molecules in the lower lipid index are labeled as 'checked'. Parameters ---------- contact_low : list A list that records the indices of lipid molecule within the lower distance cutoff at each trajectory frame. contact_high : list A list that records the indices of lipid molecule within the upper distance cutoff at each trajectory frame. dt : scalar The timestep between two adjacent trajectory frames. """ self.contact_low = contact_low self.contact_high = contact_high self.dt = dt self.pointer = [np.zeros_like(self.contact_high[idx], dtype=np.int) for idx in range(len(self.contact_high))] return ``` -------------------------------- ### Initialize PyLipid with a distance cutoff Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Demonstrates how to initialize PyLipid and set a specific distance cutoff for trajectory analysis. This is useful for filtering interactions based on proximity. ```python from pylipid import PyLipid # Initialize PyLipid with a distance cutoff of 1.0 nm lipid_analysis = PyLipid(cutoff=1.0) ``` -------------------------------- ### Import necessary libraries Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Import the required libraries for running the pylipid analysis. ```python import pylipid import os import numpy as np import matplotlib.pyplot as plt from pylipid.tools import plot_mean_std from pylipid.analysis import Analysis from pylipid.plotting import plot_committor_map, plot_rate_constants, plot_milestones, plot_flux, plot_timescales, plot_mean_std ``` -------------------------------- ### Get Distance Cutoff Value Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Retrieve the calculated distance cutoff value. This value is determined based on the analysis of lipid-protein interactions and is essential for further analysis. ```python # Get the distance cutoff value # This value is determined by the analysis and can be used for subsequent steps distance_cutoff = lipid_analyzer.get_distance_cutoff() ``` -------------------------------- ### Loading and Initializing Molecular Structure in PyMOL Source: https://pylipid.readthedocs.io/en/master/_modules/pylipid/util/pymol_script.html Loads a PDB file into PyMOL, hides all representations, and then shows the cartoon representation for the loaded protein. It also centers and orients the view. ```python cmd.load(pdb_file, "Prot_{LIPID}") prefix = "Prot_{LIPID}" cmd.hide("everything") cmd.show("cartoon", prefix) cmd.center(prefix) cmd.orient(prefix) ``` -------------------------------- ### Get Binding Site Koff Source: https://pylipid.readthedocs.io/en/master/_modules/pylipid/api/api.html Retrieves the koff value for a specific binding site ID. This is useful for understanding the dissociation rate of lipids from a binding site. ```python def koff_bs(self, bs_id): """Binding site koff""" return self._koff_BS[bs_id] ``` -------------------------------- ### Check and Create Directory Source: https://pylipid.readthedocs.io/en/master/_modules/pylipid/util/directory.html Ensures a directory exists, creating it if necessary. It can combine a base directory with a suffix to form the final path. Useful for organizing output files. ```python ############################################################################## # PyLipID: A python module for analysing protein-lipid interactions # # Author: Wanling Song # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software.############################################################################## """This module contains the assisting functions for dealing with directories.""" import os __all__ = ["check_dir"] [docs]def check_dir(directory=None, suffix=None, print_info=True): """Check directory This function will combine the suffix with the given directory (or the current working directory if None is given) to generate a new directory name, and create a directory with this name if it does not exit. """ if directory is None: directory = os.getcwd() else: directory = os.path.abspath(directory) if suffix is not None: directory = os.path.join(directory, suffix) if not os.path.isdir(directory): os.makedirs(directory) if print_info: print("Creating new director: {}".format(directory)) return directory ``` -------------------------------- ### Run GABAA Simulations and Save Test Cutoff Data Source: https://pylipid.readthedocs.io/en/master/tutorials/1-Distance_cutoff_determination.html This script sets up and runs simulations for GABAA, calculates interaction cutoffs, and saves the resulting data for later analysis. It requires trajectory and topology files, lipid information, and simulation parameters. ```python save_dir = check_dir(suffix="test_cutoffs_GABAA", print_info=False) lipid = "CHOL" trajfile_list = ["./traj_data/GABAA/run1/protein_lipids.xtc", "./traj_data/GABAA/run2/protein_lipids.xtc"] topfile_list = ["./traj_data/GABAA/run1/protein_lipids.gro", "./traj_data/GABAA/run2/protein_lipids.gro"] num_of_binding_sites, duration_avgs, num_of_contacting_residues = test_cutoffs( cutoff_list, trajfile_list, topfile_list, lipid, lipid_atoms, nprot=nprot, stride=stride, save_dir=save_dir, timeunit=timeunit) test_data = {"num_of_binding_sites": num_of_binding_sites, "duration_avgs": duration_avgs, "num_of_contacting_residues": num_of_contacting_residues, "test_cutoff_list": cutoff_list} with open(f"{save_dir}/test_cutoff_data_{lipid}.pickle", "wb") as f: pickle.dump(test_data, f, 2) ``` -------------------------------- ### Importing Plotting Functions Source: https://pylipid.readthedocs.io/en/master/_modules/pylipid/plot/plot1d.html Demonstrates how to import necessary plotting functions from the PyLipid library. Ensure these imports are present before using the plotting functionalities. ```python from pylipid.plot import plot1d from pylipid.plot import plot2d from pylipid.plot import plot3d ``` -------------------------------- ### Determine Distance Cutoff Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt This code determines the distance cutoff by finding the point where the number of clusters starts to plateau. It uses the 'plot_distances' method to visualize and identify this point. ```python import matplotlib.pyplot as plt from pylipid.analysis import Plot # Assuming 'distances' is a numpy array of distances # Example: distances = np.load('distances.npy') # For demonstration, let's create some sample distances distances = np.random.rand(1000) * 10 # Create a Plot object plotter = Plot() # Plot distances and identify cutoff cutoff = plotter.plot_distances(distances) print(f"Determined distance cutoff: {cutoff}") # Display the plot plt.show() ``` -------------------------------- ### Load and Prepare Data Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Loads trajectory data and calculates pairwise distances. Ensure the trajectory file is in a supported format. ```python from pylipid import PyLipid from pylipid.tools import plot_distance_cutoff # Load trajectory and calculate distances lipid = PyLipid("../data/1t-120.xtc", "../data/1t-120.tpr", "../data/1t-120.pdb") lipid.run_clustering() lipid.run_distance_cutoff() plot_distance_cutoff(lipid.distances, lipid.n_clusters, lipid.cutoff) ``` -------------------------------- ### Accessing lipid-protein contact data with cutoff Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Explains how to get lipid-protein contact data from PyLipid results using a specific distance cutoff. This helps in understanding protein-lipid interactions. ```python from pylipid import PyLipid # Load results for a 1.0 nm distance cutoff results = PyLipid.load(results_path='results/run_1.0nm', cutoff=1.0) # Access lipid-protein contact data contact_data = results.lipid_protein_contacts ``` -------------------------------- ### Duration.__init__ Source: https://pylipid.readthedocs.io/en/master/_modules/pylipid/func/interactions.html Initializes the Duration class for calculating interaction durations using a dual-cutoff scheme. ```APIDOC ## Duration.__init__ ### Description Dual cutoff scheme for calculating the interaction durations. In the dual cutoff scheme, a continuous contact starts when a molecule moves closer than the lower distance cutoff and ends when the molecule moves out of the upper cutoff. The duration between these two time points is the duration of the contact. Here, the ``contact_low`` is the lipid index for the lower cutoff and ``contact_high`` is the lipid index for the upper cutoff. For calculation of contact durations, a lipid molecule that appears in the ``contact_low`` is searched in the subsequent frames of the ``contact_high`` and the search then stops if this molecule disappears from the ``contact_high``. This lipid molecule is labeled as 'checked', and the duration of this contact is calculated from the number of frames in which this lipid molecule appears in the lipid indices. This calculation iterates until all lipid molecules in the lower lipid index are labeled as 'checked'. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **contact_low** (list) - A list that records the indices of lipid molecule within the lower distance cutoff at each trajectory frame. * **contact_high** (list) - A list that records the indices of lipid molecule within the upper distance cutoff at each trajectory frame. * **dt** (scalar) - The timestep between two adjacent trajectory frames. ### Returns None ### Examples None ``` -------------------------------- ### Get Binding Site Residence Time Source: https://pylipid.readthedocs.io/en/master/_modules/pylipid/api/api.html Retrieves the residence time for a specific binding site ID. This helps in analyzing how long lipids stay bound to a particular site. ```python def res_time_bs(self, bs_id): """Binding site residence time""" return self._res_time_BS[bs_id] ``` -------------------------------- ### Load and Analyze Trajectory Data Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Load trajectory data and perform initial analysis to identify potential distance cutoffs. Requires the 'pylipid' library. ```python from pylipid.analysis import LipID from pylipid.data import create_data # Create dummy data for demonstration create_data(data_dir="./data", overwrite=True) # Initialize LipID with trajectory and topology files lipid = LipID(topology="./data/protein.pdb", trajectory="./data/trajectory.xtc", skip=10, progress=True) # Run the analysis lipid.run_lipid(nframes=10000, start=0, stop=None) lipid.get_lipid_indices() lipid.get_lipid_frames() lipid.get_lipid_density() lipid.get_lipid_distribution() lipid.get_lipid_timescales() lipid.get_lipid_cluster() lipid.plot_density() lipid.plot_distribution() lipid.plot_timescales() lipid.plot_cluster() # Save the results lipid.save() ``` -------------------------------- ### Initialize and Calculate Lipid Interactions Source: https://pylipid.readthedocs.io/en/master/demo.html Initializes the LipidInteraction object and performs initial calculations for residue contacts, duration, occupancy, and lipid count. Use this to start the analysis pipeline. ```python li = LipidInteraction(trajfile_list, topfile_list=topfile_list, cutoffs=cutoffs, lipid=lipid, lipid_atoms=lipid_atoms, nprot=1, resi_offset=resi_offset, timeunit=timeunit, save_dir=save_dir, stride=stride, dt_traj=dt_traj) li.collect_residue_contacts() li.compute_residue_duration(residue_id=None) li.compute_residue_occupancy(residue_id=None) li.compute_residue_lipidcount(residue_id=None) li.show_stats_per_traj(write_log=True, print_log=True) li.compute_residue_koff(residue_id=None, plot_data=True, fig_close=True, fig_format=fig_format, num_cpus=num_cpus) ``` -------------------------------- ### LipidInteraction.save_dir Source: https://pylipid.readthedocs.io/en/master/_sources/api/generated/pylipid.api.LipidInteraction.save_dir.rst.txt The save_dir property of the LipidInteraction class allows users to get or set the directory path where the interaction data will be saved. This is crucial for managing output files from lipid interaction analysis. ```APIDOC ## LipidInteraction.save_dir ### Description Gets or sets the directory path for saving interaction data. ### Property `save_dir` ### Type `str` ### Usage ```python # Get the save directory save_directory = lipid_interaction_object.save_dir # Set the save directory lipid_interaction_object.save_dir = "/path/to/save/directory" ``` ``` -------------------------------- ### LipidInteraction.write_site_info Source: https://pylipid.readthedocs.io/en/master/api/generated/pylipid.api.LipidInteraction.write_site_info.html Writes a report of binding site information in a txt file. This report includes, for each binding site, the various interaction data and properties of the binding site, followed by a table of comprising residues and the interaction data of these residues. This table is sorted in an order determined by the item provided by sort_residue. This report provides a quick and formatted view of the binding site information. By default, the report is saved in the root directory defined when the class LipidInteraction was initiated. It can be changed by providing to path to save_dir. By default, the report is saved with a filename of BindingSites_Info_{lipid}.txt. It can be changed via the parameter fn. ```APIDOC ## LipidInteraction.write_site_info ### Description Writes a report detailing binding site interactions and residue properties. The report includes interaction data and properties for each binding site, followed by a sorted table of comprising residues and their interaction data. The sorting order can be customized. ### Method (Not specified, likely a Python method call) ### Parameters #### Path Parameters (None specified) #### Query Parameters (None specified) #### Request Body (None specified) ### Parameters * **sort_residue** (string, default="Residence Time") - The item used for sorting the binding site residues. Possible values include "Residence Time", "Duration", "Occupancy", "Lipid Count". * **save_dir** (string, default=None) - The directory for saving the report. If None, the report is saved in the root directory defined during `LipidInteraction` initialization. * **fn** (string, default=None) - The filename of the report. If None, the default filename is BindingSites_Info_{lipid}.txt. ### Request Example (Not specified) ### Response #### Success Response (200) (Not specified, likely writes to a file) #### Response Example (Not specified) ``` -------------------------------- ### Run A2aR Simulation and Save Cutoff Data Source: https://pylipid.readthedocs.io/en/master/tutorials/1-Distance_cutoff_determination.html This snippet sets up simulation parameters, runs the `test_cutoffs` function with specified trajectories and topologies, and saves the resulting contact metrics and cutoff data to a pickle file for later analysis. ```python save_dir = check_dir(suffix="test_cutoffs_A2a", print_info=False) trajfile_list = ["./traj_data/A2a/run1/protein_lipids.xtc", "./traj_data/A2a/run2/protein_lipids.xtc"] topfile_list = ["./traj_data/A2a/run1/protein_lipids.gro", "./traj_data/A2a/run2/protein_lipids.gro"] num_of_binding_sites, duration_avgs, num_of_contacting_residues = test_cutoffs( cutoff_list, trajfile_list, topfile_list, lipid, lipid_atoms, nprot=nprot, stride=stride, save_dir=save_dir, timeunit=timeunit) test_data = {"num_of_binding_sites": num_of_binding_sites, "duration_avgs": duration_avgs, "num_of_contacting_residues": num_of_contacting_residues, "test_cutoff_list": cutoff_list} with open(f"{save_dir}/test_cutoff_data_{lipid}.pickle", "wb") as f: pickle.dump(test_data, f, 2) ``` -------------------------------- ### Load Topology Source: https://pylipid.readthedocs.io/en/master/_sources/tutorials/1-Distance_cutoff_determination.ipynb.txt Loads a molecular dynamics topology file. This is necessary for Pylipid to understand the molecular structure. ```python import pylipid top = pylipid.io.load_topology("path/to/your/topology.pdb") ``` -------------------------------- ### plot_residue_data Source: https://pylipid.readthedocs.io/en/master/api/generated/pylipid.plot.plot_residue_data.html Plots interactions as a function of residue index. It handles gaps in residue numbering by marking them as gray areas or starting new figures, and allows for customization of labels, titles, and figure saving. ```APIDOC ## plot_residue_data ### Description Plots interactions as a function of residue index. It handles gaps in residue numbering by marking them as gray areas or starting new figures, and allows for customization of labels, titles, and figure saving. ### Method plot_residue_data ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **residue_index** (list) - Required - Residue indices in an ascending order. If a residue index is smaller than its preceding one, the plotting function will consider it as the start of a new chain and will plot the following data in a new figure. A gap in residue index that is less than `gap` will be marked as gray areas in the figure, but a gap that is larger than `gap` will start a new figure. * **interactions** (list) - Required - Values to plot. In the same order as `residue_index`. * **gap** (int, optional, default=200) - The number of missing residues in `residue_index` that initiate a new figure. The gap between two adjacent index in `residue_index` that is smaller than the provided value will be considered as missing residues and will be marked as gray areas in the figure, whereas a gap that is larger than the provided value will start a new figure and plot the following data in that new figure. This can help to make figures more compressed. The default gap is 200. * **ylabel** (str, optional, default=None) - y axis label. Default is “Interactions”. * **fn** (str, optional, default=None) - Figure name. By default the figure is saved as “Figure_interactions.pdf” as the current working directory. * **title** (str, optional, default=None) - Figure title. * **fig_close** (bool, optional, default=False) - Use plt.close() to close the figure. Can be used to save memory if many figures are opened. ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Get Residue Interaction Data Source: https://pylipid.readthedocs.io/en/master/_modules/pylipid/api/api.html Obtains lipid interaction information for a specific residue, identified by either its ID or name. Returns data as a pandas DataFrame. Use this to inspect detailed interactions at the residue level. ```python def residue(self, residue_id=None, residue_name=None, print_data=True): """Obtain the lipid interaction information for a residue Use either residue_id or residue_name to indicate the residue identity. Return the interaction information in a pandas.DataFrame object. Parameters ---------- residue_id : int or list of int, default=None The residue ID that is used by PyLipID for identifying residues. The ID starts from 0, i.e. the ID of N-th residue is (N-1). If None, all residues are selected. residue_name : str or list of str, default=None The residue name as stored in PyLipID dataset. The residue name is in the format of resi+resn Returns ------- df : pandas.DataFrame A pandas.DataFrame of interaction information of the residue. """ if residue_id is not None and residue_name is not None: assert self.dataset[self.dataset["Residue ID"] == residue_id]["Residue"] == residue_name, \ "residue_id and residue_name are pointing to different residues!" df = self.dataset[self.dataset["Residue ID"] == residue_id] elif residue_id is not None: df = self.dataset[self.dataset["Residue ID"] == residue_id] elif residue_name is not None: df = self.dataset[self.dataset["Residue"] == residue_name] if print_data: print(df) return df ``` -------------------------------- ### binding_site.write_bound_poses Source: https://pylipid.readthedocs.io/en/master/api/index_func.html Writes selected bound poses to disk. ```APIDOC ## binding_site.write_bound_poses ### Description Write selected bound poses to disc. ### Method Not specified (likely a Python function call) ### Parameters - **pose_traj**: Not specified - Description - **pose_indices**: Not specified - Description - **...**: Not specified - Description ``` -------------------------------- ### pylipid.func.Duration Source: https://pylipid.readthedocs.io/en/master/api/generated/pylipid.func.Duration.html Initializes the Duration class with parameters for calculating interaction durations using a dual cutoff scheme. This scheme defines a contact as starting when a molecule enters the lower cutoff and ending when it exits the upper cutoff. ```APIDOC ## pylipid.func.Duration ### Description Dual cutoff scheme for calculating the interaction durations. In the dual cutoff scheme, a continuous contact starts when a molecule moves closer than the lower distance cutoff and ends when the molecule moves out of the upper cutoff. The duration between these two time points is the duration of the contact. ### Parameters #### Path Parameters - **contact_low** (list) - Required - A list that records the indices of lipid molecule within the lower distance cutoff at each trajectory frame. - **contact_high** (list) - Required - A list that records the indices of lipid molecule within the upper distance cutoff at each trajectory frame. - **dt** (scalar) - Required - The timestep between two adjacent trajectory frames. ```