當前位置: 首頁>>代碼示例>>Python>>正文


Python mdtraj.Trajectory方法代碼示例

本文整理匯總了Python中mdtraj.Trajectory方法的典型用法代碼示例。如果您正苦於以下問題:Python mdtraj.Trajectory方法的具體用法?Python mdtraj.Trajectory怎麽用?Python mdtraj.Trajectory使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在mdtraj的用法示例。


在下文中一共展示了mdtraj.Trajectory方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: write_nonequilibrium_trajectory

# 需要導入模塊: import mdtraj [as 別名]
# 或者: from mdtraj import Trajectory [as 別名]
def write_nonequilibrium_trajectory(nonequilibrium_trajectory, trajectory_filename):
        """
        Write the results of a nonequilibrium switching trajectory to a file. The trajectory is written to an
        mdtraj hdf5 file.

        Parameters
        ----------
        nonequilibrium_trajectory : md.Trajectory
            The trajectory resulting from a nonequilibrium simulation
        trajectory_filename : str
            The full filepath for where to store the trajectory

        Returns
        -------
        True : bool
        """
        if nonequilibrium_trajectory is not None:
            nonequilibrium_trajectory.save_hdf5(trajectory_filename)

        return True 
開發者ID:choderalab,項目名稱:perses,代碼行數:22,代碼來源:feptasks.py

示例2: write_equilibrium_trajectory

# 需要導入模塊: import mdtraj [as 別名]
# 或者: from mdtraj import Trajectory [as 別名]
def write_equilibrium_trajectory(trajectory: md.Trajectory, trajectory_filename: str) -> float:
    """
    Write the results of an equilibrium simulation to disk. This task will append the results to the given filename.
    Parameters
    ----------
    trajectory : md.Trajectory
        the trajectory resulting from an equilibrium simulation
    trajectory_filename : str
        the name of the trajectory file to which we should append
    Returns
    -------
    True
    """
    if not os.path.exists(trajectory_filename):
        trajectory.save_hdf5(trajectory_filename)
        _logger.debug(f"{trajectory_filename} does not exist; instantiating and writing to.")
    else:
        _logger.debug(f"{trajectory_filename} exists; appending.")
        written_traj = md.load_hdf5(trajectory_filename)
        concatenated_traj = written_traj.join(trajectory)
        concatenated_traj.save_hdf5(trajectory_filename)

    return True 
開發者ID:choderalab,項目名稱:perses,代碼行數:25,代碼來源:feptasks.py

示例3: write_equilibrium_trajectory

# 需要導入模塊: import mdtraj [as 別名]
# 或者: from mdtraj import Trajectory [as 別名]
def write_equilibrium_trajectory(trajectory: md.Trajectory, trajectory_filename: str) -> float:
    """
    Write the results of an equilibrium simulation to disk. This task will append the results to the given filename.

    Arguments
    ----------
    trajectory : md.Trajectory
        the trajectory resulting from an equilibrium simulation
    trajectory_filename : str
        the name of the trajectory file to which we should append

    Returns
    -------
    True
    """
    if not os.path.exists(trajectory_filename):
        trajectory.save_hdf5(trajectory_filename)
        _logger.debug(f"{trajectory_filename} does not exist; instantiating and writing to.")
    else:
        _logger.debug(f"{trajectory_filename} exists; appending.")
        written_traj = md.load_hdf5(trajectory_filename)
        concatenated_traj = written_traj.join(trajectory)
        concatenated_traj.save_hdf5(trajectory_filename)

    return True 
開發者ID:choderalab,項目名稱:perses,代碼行數:27,代碼來源:utils.py

示例4: write_nonequilibrium_trajectory

# 需要導入模塊: import mdtraj [as 別名]
# 或者: from mdtraj import Trajectory [as 別名]
def write_nonequilibrium_trajectory(nonequilibrium_trajectory, trajectory_filename):
    """
    Write the results of a nonequilibrium switching trajectory to a file. The trajectory is written to an
    mdtraj hdf5 file.

    Arguments
    ----------
    nonequilibrium_trajectory : md.Trajectory
        The trajectory resulting from a nonequilibrium simulation
    trajectory_filename : str
        The full filepath for where to store the trajectory

    Returns
    -------
    True : bool
    """
    if nonequilibrium_trajectory is not None:
        nonequilibrium_trajectory.save_hdf5(trajectory_filename)

    return True 
開發者ID:choderalab,項目名稱:perses,代碼行數:22,代碼來源:utils.py

示例5: generate_dummy_trajectory

# 需要導入模塊: import mdtraj [as 別名]
# 或者: from mdtraj import Trajectory [as 別名]
def generate_dummy_trajectory(xyz, box):
    """Convert xyz coordinates and box vectors into an MDTraj Trajectory (with Topology)."""
    try:
        import mdtraj as md
        import pandas as pd
    except ImportError as e:
        print("Error: generate_dummy_trajectory() requires mdtraj and pandas!")
        raise(e)

    n_atoms = len(xyz)
    data = []

    for i in range(n_atoms):
        data.append(dict(serial=i, name="H", element="H", resSeq=i + 1, resName="UNK", chainID=0))

    data = pd.DataFrame(data)
    unitcell_lengths = box * np.ones((1, 3))
    unitcell_angles = 90 * np.ones((1, 3))
    top = md.Topology.from_dataframe(data, np.zeros((0, 2), dtype='int'))
    traj = md.Trajectory(xyz, top, unitcell_lengths=unitcell_lengths, unitcell_angles=unitcell_angles)

    return traj 
開發者ID:choderalab,項目名稱:openmmtools,代碼行數:24,代碼來源:testsystems.py

示例6: test_kmedoids

# 需要導入模塊: import mdtraj [as 別名]
# 或者: from mdtraj import Trajectory [as 別名]
def test_kmedoids(self):
        '''
        Check that pure kmedoid clustering is behaving as expected on
        md.Trajectory objects.
        '''

        N_CLUSTERS = 5

        result = kmedoids.kmedoids(
            self.trj,
            distance_method='rmsd',
            n_clusters=N_CLUSTERS,
            n_iters=50)

        # kcenters will always produce the same number of clusters on
        # this input data (unchanged by kmedoids updates)
        self.assertEqual(len(np.unique(result.assignments)), N_CLUSTERS)

        self.assertAlmostEqual(
            np.average(result.distances), 0.085, delta=0.01)
        self.assertAlmostEqual(
            np.std(result.distances), 0.019, delta=0.005) 
開發者ID:bowman-lab,項目名稱:enspara,代碼行數:24,代碼來源:test_cluster.py

示例7: concatenate_trjs

# 需要導入模塊: import mdtraj [as 別名]
# 或者: from mdtraj import Trajectory [as 別名]
def concatenate_trjs(trj_list, atoms=None, n_procs=None):
    """Convert a list of trajectories into a single trajectory building
    a concatenated array in parallel.

    Parameters
    ----------
    trj_list : array-like, shape=(n_trjs,)
        The list of md.Trajectory objects
    atoms : str, default=None
        A selection in the MDTraj DSL for atoms to slice out from each
        trajectory in `trj_list`. If none, no slice is performed.
    n_procs : int, default=None
        Number of parallel processes to use when performing this
        operation.

    Returns
    -------
    trj : md.Trajectory
        A concatenated trajectory
    """

    example_center = trj_list[0]
    if atoms is not None:
        example_center = example_center.atom_slice(
            example_center.top.select(atoms))

    lengths = [len(t) for t in trj_list]
    intervals = np.cumsum(np.array([0] + lengths))
    full_shape, shared_xyz = shared_array_like_trj(lengths, example_center)

    with closing(mp.Pool(processes=n_procs, initializer=_init,
                         initargs=(shared_xyz,))) as p:
        func = partial(_slice_and_insert_xyz, atoms=atoms,
                       arr_shape=full_shape)
        p.map(func, [(intervals[i], intervals[i+1], t)
                     for i, t in enumerate(trj_list)])
    p.join()

    xyz = _tonumpyarray(shared_xyz).reshape(full_shape)
    return md.Trajectory(xyz, topology=example_center.top) 
開發者ID:bowman-lab,項目名稱:enspara,代碼行數:42,代碼來源:load.py

示例8: compute_neighbor_list

# 需要導入模塊: import mdtraj [as 別名]
# 或者: from mdtraj import Trajectory [as 別名]
def compute_neighbor_list(coords, neighbor_cutoff, max_num_neighbors,
                          periodic_box_size):
  """Computes a neighbor list from atom coordinates."""
  N = coords.shape[0]
  import mdtraj
  traj = mdtraj.Trajectory(coords.reshape((1, N, 3)), None)
  box_size = None
  if periodic_box_size is not None:
    box_size = np.array(periodic_box_size)
    traj.unitcell_vectors = np.array(
        [[[box_size[0], 0, 0], [0, box_size[1], 0], [0, 0, box_size[2]]]],
        dtype=np.float32)
  neighbors = mdtraj.geometry.compute_neighborlist(traj, neighbor_cutoff)
  neighbor_list = {}
  for i in range(N):
    if max_num_neighbors is not None and len(neighbors[i]) > max_num_neighbors:
      delta = coords[i] - coords.take(neighbors[i], axis=0)
      if box_size is not None:
        delta -= np.round(delta / box_size) * box_size
      dist = np.linalg.norm(delta, axis=1)
      sorted_neighbors = list(zip(dist, neighbors[i]))
      sorted_neighbors.sort()
      neighbor_list[i] = [
          sorted_neighbors[j][1] for j in range(max_num_neighbors)
      ]
    else:
      neighbor_list[i] = list(neighbors[i])
  return neighbor_list 
開發者ID:deepchem,項目名稱:deepchem,代碼行數:30,代碼來源:atomic_coordinates.py

示例9: traj_frame_to_sampler_state

# 需要導入模塊: import mdtraj [as 別名]
# 或者: from mdtraj import Trajectory [as 別名]
def traj_frame_to_sampler_state(traj: md.Trajectory, frame_number: int,box_vectors):
    xyz = traj.xyz[frame_number, :, :]
    box_vectors = traj.openmm_boxes(frame_number)
    sampler_state = states.SamplerState(unit.Quantity(xyz, unit=unit.nanometers))
    return sampler_state 
開發者ID:choderalab,項目名稱:perses,代碼行數:7,代碼來源:run_nonequilibrium.py

示例10: traj_frame_to_sampler_state

# 需要導入模塊: import mdtraj [as 別名]
# 或者: from mdtraj import Trajectory [as 別名]
def traj_frame_to_sampler_state(traj: md.Trajectory, frame_number: int):
    xyz = traj.xyz[frame_number, :, :]
    box_vectors = traj.openmm_boxes(frame_number)
    sampler_state = states.SamplerState(unit.Quantity(xyz, unit=unit.nanometers), box_vectors=box_vectors)
    return sampler_state 
開發者ID:choderalab,項目名稱:perses,代碼行數:7,代碼來源:run_rj_neq.py

示例11: extract_molecule

# 需要導入模塊: import mdtraj [as 別名]
# 或者: from mdtraj import Trajectory [as 別名]
def extract_molecule(complex_pdb_path: str, resname: str) -> md.Trajectory:
    """
    This method extracts the host from the host-guest solvated complex

    Parameters
    ----------
    complex_pdb_path : str
        The path to the PDB complex
    resname : str
        The name of the residue to save
    
    Returns
    -------
    subset_traj : md.Trajectory
        The subsetted trajectory of interest.
    """
    traj = md.load(complex_pdb_path)

    #Extract the specified resname indices
    selected_indices = traj.top.select("resname=='{}'".format(resname))

    #Subset the topology to contain just the selected residue
    subset_topology = traj.top.subset(selected_indices)

    #subset the positions
    subset_positions = traj.xyz[0, selected_indices]
    
    #create a new Trajectory object with just the selected residue
    subset_traj = md.Trajectory(subset_positions, subset_topology)

    return subset_traj 
開發者ID:choderalab,項目名稱:perses,代碼行數:33,代碼來源:prepare_host_guest.py

示例12: convert_mdtraj_to_oemol

# 需要導入模塊: import mdtraj [as 別名]
# 或者: from mdtraj import Trajectory [as 別名]
def convert_mdtraj_to_oemol(traj: md.Trajectory) -> oechem.OEMol:
    """
    This method converts an mdtraj Trajectory to an OEMol via saving as a PDBfile
    and reading in with OpenEye. Although this seems hacky, it seems less error-prone
    than trying to manually construct the OEMol.

    Parameters
    ----------
    mdtraj: md.Trajectory
        The trajectory to turn into an OEMol
    
    Returns
    -------
    mol : oechem.OEMol
        The trajectory represented as an OEMol
    """
    #create a temporary file with a PDB suffix and save with MDTraj
    pdb_file = tempfile.NamedTemporaryFile(delete=False, suffix=".pdb")
    traj.save(pdb_file.name)
    pdb_file.close()
    
    #Now use the openeye oemolistream to read in this file as an OEMol:
    ifs = oechem.oemolistream()
    ifs.open(pdb_file.name)
    ifs.SetFormat(oechem.OEFormat_PDB)
    
    mol = oechem.OEMol()
    oechem.OEReadMolecule(ifs, mol)
    
    #close the stream and delete the temporary pdb file
    ifs.close()
    os.unlink(pdb_file.name)

    return mol 
開發者ID:choderalab,項目名稱:perses,代碼行數:36,代碼來源:prepare_host_guest.py

示例13: write_trajectory

# 需要導入模塊: import mdtraj [as 別名]
# 或者: from mdtraj import Trajectory [as 別名]
def write_trajectory(positions, topology, outputfile='trajectory.pdb',center=True,offline=None):
    if offline != None:
        traj = md.Trajectory(positions[0::offline],topology)
    else:
        traj = md.Trajectory(positions, topology)
    if center == True:
        traj.center_coordinates()
    traj.save_pdb(outputfile)

    return 
開發者ID:choderalab,項目名稱:perses,代碼行數:12,代碼來源:extract_trajectory.py

示例14: get_nonequilibrium_trajectory

# 需要導入模塊: import mdtraj [as 別名]
# 或者: from mdtraj import Trajectory [as 別名]
def get_nonequilibrium_trajectory(self, direction, trajectory_index):
        """
        Get a nonequilibrium trajectory corresponding to a particular direction (forward, 0->1, reverse 1->0),
        and run index.

        Parameters
        ----------
        direction : str
           "forward" or "reverse"
        trajectory_index : int
            Iteration number of protocol

        Returns
        -------
        nonequilibrium_trajectory : md.Trajectory
            the nonequilibrium trajectory
        """
        if direction=='forward':
            lambda_state = 0
        elif direction=='reverse':
            lambda_state = 1
        else:
            raise ValueError("direction must be either forward or reverse")

        nonequilibrium_trajectory_filename = self._neq_traj_filenames[lambda_state][trajectory_index]

        return md.load(nonequilibrium_trajectory_filename) 
開發者ID:choderalab,項目名稱:perses,代碼行數:29,代碼來源:plotting_tools.py

示例15: lambda_zero_traj

# 需要導入模塊: import mdtraj [as 別名]
# 或者: from mdtraj import Trajectory [as 別名]
def lambda_zero_traj(self):
        """
        Get the equilibrium trajectory corresponding to lambda=0

        Returns
        -------
        lambda_zero_traj : md.Trajectory object
            The equilibrium trajectory at lambda=0
        """
        lambda_zero_filename = self._trajectory_filename[0]
        return md.load(lambda_zero_filename) 
開發者ID:choderalab,項目名稱:perses,代碼行數:13,代碼來源:plotting_tools.py


注:本文中的mdtraj.Trajectory方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。