Example #1
0
 def test_with_superposition_equal(self, p_first, p_last):
     align.alignto(p_first, p_last)
     A = p_first.positions
     B = p_last.positions
     rmsd = rms.rmsd(A, B)
     rmsd_superposition = rms.rmsd(A, B, center=True, superposition=True)
     assert_almost_equal(rmsd, rmsd_superposition, decimal=6)
Example #2
0
 def test_with_superposition_equal(self):
     align.alignto(self.p_first, self.p_last)
     A = self.p_first.positions
     B = self.p_last.positions
     rmsd = rms.rmsd(A, B)
     rmsd_superposition = rms.rmsd(A, B, center=True, superposition=True)
     assert_almost_equal(rmsd, rmsd_superposition)
Example #3
0
 def test_with_superposition_equal(self):
     align.alignto(self.p_first, self.p_last)
     A = self.p_first.positions
     B = self.p_last.positions
     rmsd = rms.rmsd(A, B)
     rmsd_superposition = rms.rmsd(A, B, center=True, superposition=True)
     assert_almost_equal(rmsd, rmsd_superposition)
Example #4
0
 def test_with_superposition_equal(self, p_first, p_last):
     align.alignto(p_first, p_last)
     A = p_first.positions
     B = p_last.positions
     rmsd = rms.rmsd(A, B)
     rmsd_superposition = rms.rmsd(A, B, center=True, superposition=True)
     assert_almost_equal(rmsd, rmsd_superposition, decimal=6)
Example #5
0
def Calculate_ddRMSD(ABMD, Ini_ref, End_ref):
    '''
    Parameters: 
        ABMD: Full traj
	    Ini_ref: Initial frame
        End_ref: Target frame
        rmsd_ab: rmsd between start and end frame
    Returns:
        time: time coordinate for one traj
	    ddRMSD: ddRMSD along time
    '''
    Ini_temp = Ini_ref.select_atoms('name CA')
    End_temp = End_ref.select_atoms('name CA')
    align.alignto(Ini_temp, End_temp)
    Ini_position = Ini_temp.positions
    End_position = End_temp.positions
    rmsd_ab = rmsd(Ini_position, End_position)
    RMSD_ini = RMSD(ABMD, Ini_ref, select='name CA')
    RMSD_ini.run()
    RMSD_end = RMSD(ABMD, End_ref, select='name CA')
    RMSD_end.run()
    rmsd_ini = RMSD_ini.rmsd.T
    rmsd_end = RMSD_end.rmsd.T
    time = rmsd_ini[1]
    ddRMSD = (rmsd_ini[2] - rmsd_end[2]) / rmsd_ab
    return time, ddRMSD, rmsd_ini, rmsd_end
Example #6
0
def mdaalignto(universe, reference, selection='all'):
    """
    Align universe to reference.

    Uses `MDAnalysis.analysis.align.alignto <https://www.mdanalysis.org/docs/documentation_pages/analysis/align.html?highlight=alignto#MDAnalysis.analysis.align.alignto>`_.

    Parameters
    ----------
    universe, reference, selection
        Same as in ``MDAnalysis.analysis.align.alignto`` function.

    Raises
    ------
    ZeroDivisionError
        If selection gives empty selection.
    """  # noqa: E501
    try:
        mdaalign.alignto(universe, reference, select=selection)
    except (ValueError, ZeroDivisionError) as err:
        log.debug(err, exc_info=True)
        errmsg = (
            f'Could not perform alignment due to {err}, '
            'most likely the alignment selection does not match '
            'any possible selection in the system. You selection : '
            f'\'{selection}\'.'
            )
        log.info(errmsg)
        raise err
Example #7
0
def capping(ref, ace, nma, output):
    resids = ref.select_atoms("all").resids
    resid_min, resid_max = min(resids), max(resids)

    for r in ace.residues:
        r.resid += resid_min - max(ace.atoms.resids)
    for r in nma.residues:
        r.resid = resid_max

    # TODO pick the first residue in the protein (how should we cap the chains?)
    # TODO consider a case when the protein resid is 1 and all peptide has to be shifted by +1, put that in docs as a
    #  post-processing step
    alignto(ace, ref, select={
            "mobile": "resid {0} and backbone".format(resid_min),
            "reference": "resid {0} and backbone".format(resid_min)},
            strict=True)
    alignto(nma, ref, select={
            "mobile": "resid {0} and backbone and not (resname NMA NME)".format(resid_max),
            "reference": "resid {0} and (backbone or name OT2)".format(resid_max)},
            strict=True)

    #  TODO remove the Hydrogen closest to ACE's oxygen
    nma.residues.resids = 16
    u = Merge(ace.select_atoms("resname ACE"),
              ref.select_atoms(
                  "not (resid {0} and name HT*) and not (resid {1} and (name HT* OT1))"
                  "".format(resid_min, resid_max)),
              nma.select_atoms("resname NME NMA"))
    u.trajectory.ts.dimensions = ref.trajectory.ts.dimensions
    u.atoms.write(output)
    return u
Example #8
0
def capping(ref, ace, nma, output):
    resids = ref.select_atoms("all").resids
    resid_min, resid_max = min(resids), max(resids)

    for r in ace.residues:
        r.resid += resid_min - max(ace.atoms.resids)
    for r in nma.residues:
        r.resid = resid_max

    # TODO pick the first residue in the protein (how should we cap the chains?)
    # TODO consider a case when the protein resid is 1 and all peptide has to be shifted by +1, put that in docs as a
    #  post-processing step
    alignto(ace, ref, select={
            "mobile": "resid {0} and backbone".format(resid_min),
            "reference": "resid {0} and backbone".format(resid_min)},
            strict=True)
    alignto(nma, ref, select={
            "mobile": "resid {0} and backbone and not (resname NMA NME)".format(resid_max),
            "reference": "resid {0} and (backbone or name OT2)".format(resid_max)},
            strict=True)

    #  TODO remove the Hydrogen closest to ACE's oxygen
    nma.residues.resids = 16
    u = Merge(ace.select_atoms("resname ACE"),
              ref.select_atoms(
                  "not (resid {0} and name HT*) and not (resid {1} and (name HT* OT1))"
                  "".format(resid_min, resid_max)),
              nma.select_atoms("resname NME NMA"))
    u.trajectory.ts.dimensions = ref.trajectory.ts.dimensions
    u.atoms.write(output)
    return u
	def cap_protein(self):
		"""
		CAMPARI requires all proteins to be capped with ACE and NME. Most don't have that. Add it if needed.
		This function requires "ace.pdb" and "nme.pdb". I can provide them upon request.

		"""
		from MDAnalysis.analysis.align import alignto
	
		ref = mda.Universe(pdb)
		ace = mda.Universe("ace.pdb")
		nme = mda.Universe("nme.pdb")
	
		resids = ref.select_atoms("all").resids
		resid_min, resid_max = min(resids), max(resids)
		
		alignto(ace, ref, select={"mobile": "resname ALA and backbone", 
					  "reference": "resid {0} and backbone".format(resid_min)})
		alignto(nme, ref, select={"mobile": "resname ALA and backbone",
					  "reference": "resid {0} and backbone".format(resid_max)})

		A = ace.select_atoms('resname ACE')
		N = nme.select_atoms('resname NME')

		uni = self.merge_structures(ace,ref,nme)
		self.name += '_capped'
		uni.atoms.write(self.name+'.pdb')

		return uni
Example #10
0
def compare_models(u, ucg_base, mappings, spacing, probe):
    # Prepare the AA structure
    mda.lib.mdamath.make_whole(u.atoms)
    orient(u)
    radii_aa = np.array([AA_VDW_RADII[elem] for elem in u.atoms.types])

    # Create a naive mapped CG structure so we can align the real CG structure
    centers = np.stack(
        [u.atoms[mapping].center_of_geometry() for mapping in mappings])
    ucg_centers = mda.Universe(ucg_base._topology, centers[None, :])

    # Prepare the CG structure
    maa.alignto(ucg_base, ucg_centers)
    radii_cg = np.repeat(TRADIUS, len(ucg_base.atoms))

    # Build the mesh
    total_coords = np.vstack([u.atoms.positions, ucg_base.atoms.positions])
    total_radii = np.hstack([radii_aa, radii_cg])
    mesh = build_mesh(total_coords, total_radii, spacing, probe)

    # Compute the AA volume
    aa_grid = bool_grid(u.atoms.positions, mesh, radii_aa, probe)
    aa_volume = aa_grid.sum() * spacing**3

    # Compute the CG volume
    cg_grid = bool_grid(ucg_base.atoms.positions, mesh, radii_cg, probe)
    cg_volume = cg_grid.sum() * spacing**3

    # Compute the mismatch
    mismatch = get_score(aa_grid, cg_grid) * spacing**3

    diff_grid = aa_grid.astype(int) - cg_grid.astype(int)

    return aa_volume, cg_volume, mismatch, diff_grid
Example #11
0
 def test_rmsd_custom_weights(self):
     weights = np.zeros(self.universe.atoms.n_atoms)
     ca = self.universe.atoms.CA
     weights[ca.indices] = 1
     rmsd = align.alignto(self.universe, self.reference, select='name CA')
     rmsd_weights = align.alignto(self.universe, self.reference, weights=weights)
     assert_almost_equal(rmsd[1], rmsd_weights[1], 6)
Example #12
0
 def test_rmsd_custom_weights(self, universe, reference):
     weights = np.zeros(universe.atoms.n_atoms)
     ca = universe.select_atoms('name CA')
     weights[ca.indices] = 1
     rmsd = align.alignto(universe, reference, select='name CA')
     rmsd_weights = align.alignto(universe, reference, weights=weights)
     assert_almost_equal(rmsd[1], rmsd_weights[1], 6)
Example #13
0
 def test_toggle_atom_nomatch_mismatch_atoms(self, universe, reference):
     # mismatching number of atoms, but same number of residues
     u = universe.select_atoms('resname ALA and name CA')
     u += universe.select_atoms('resname ALA and name O')[-1]
     ref = reference.select_atoms('resname ALA and name CA')
     with pytest.raises(SelectionError):
         align.alignto(u, ref, select='all', match_atoms=False)
Example #14
0
def capping(ref, ace, nma, output):
    resids = ref.selectAtoms("all").resids()
    resid_min, resid_max = min(resids), max(resids)

    # There is probably some cache i need to update both the atom and residues
    for a in ace.atoms:
        a.resid += resid_min - max(ace.atoms.resids())
    for r in ace.residues:
        r.id += resid_min - max(ace.atoms.resids())
    for a in nma.atoms:
        a.resid = resid_max
    for r in nma.residues:
        r.id = resid_max

    # TODO pick the first residue in the protein (how should we cap the chains?)
    # TODO consider a case when the protein resid is 1 and all peptide has to be shifted by +1, put that in docs as a
    #  post-processing step
    alignto(ace, ref, select={
        "mobile": "resid {} and backbone".format(resid_min),
        "reference": "resid {} and backbone".format(resid_min)})
    alignto(nma, ref, select={
        "mobile": "resid {} and backbone and not (resname NMA or resname NME)".format(resid_max),
        "reference": "resid {} and (backbone or name OT2)".format(resid_max)})

    #  TODO remove the Hydrogen closest to ACE's oxygen
    u = Merge(ace.selectAtoms("resname ACE"),
              ref.selectAtoms(
                  "not (resid {} and name HT*) and not (resid {} and (name HT* or name OT1))".format(resid_min,
                                                                                                     resid_max)),
              nma.selectAtoms("resname NME or resname NMA"))
    u.trajectory.ts.dimensions = ref.trajectory.ts.dimensions
    u.atoms.write(output)
    return u
Example #15
0
def com_com_distances_axis_align(universe, mda_selection_pairs, align_struct_universe, align_sel_string, fstart=0,
                                 fend=-1, fstep=1, axis='z'):
    """Center of mass to Center of mass distance in one dimension (along an axis) after structure alignment.
    This function computes the distance between the centers of mass between pairs of MDAnalysis atoms selections
    across the the MD trajectory, but only uses the 1d coordinate of the specified axis, and aligns the structure
    to some selection of atoms of a reference structure.

    Args:
        universe (MDAnalysis.Universe): The MDAnalysis universe object to run the analysis on.
        mda_selection_pairs (list): A list of 2 element lists or tuples containing pairs of MDAnalsysis
           atom selection objects to compute the distance between.
        align_struct_universe (MDAnalsysi.Universe): The MDAnalsysis universe object of the reference structure to
           align the system to.
        align_sel_string (str): A MDAnalysis selection string to use for the structure alignment.
        fstart (int): Optional, the first frame to include in the analysis. Default: 0 (or the first frame)
        fend (int): Optional, the last frame to include in the analysis. Default: -1 (or the last frame)
        fstep (int): Optional, the interval between frames in the analysis when looping from fstart to fend.
            Default: 1 (or every frame)
        axis (str): Optional, the 1d axis to compute the distance in. Default: 'z' (or the z axis)

    Returns:
        (np.array), (list): Returns two outputs. The first is an Numpy array with the timeseries simulation times
            corresponding to the frames in the analysis. The second is list of Numpy arrays with the distances; the
            order in the list corresponds to the atom selection pairs in the mda_selection_pairs input.
    """

    dir_ind = 2
    if axis is 'x':
        dir_ind = 0
    elif axis is 'y':
        dir_ind = 1
    #indices = mda_selection.indices
    fstart, fend = _adjust_frame_range_for_slicing(fstart, fend, len(universe.trajectory))
    times = []
    pair_dists = []
    for pair in mda_selection_pairs:
        pair_dists.append([])
    for frame in universe.trajectory[fstart:fend:fstep]:
        times.append(frame.time)
        # now do the alignment
        align.alignto(universe, align_struct_universe, select=align_sel_string, mass_weighted=True)
        i = 0
        for pair in mda_selection_pairs:
            sel_1 = pair[0]
            sel_2 = pair[1]
            com_1 = sel_1.atoms.center_of_mass()
            com_2 = sel_2.atoms.center_of_mass()
            norm_val_1 = com_1[dir_ind]
            norm_val_2 = com_2[dir_ind]
            dist = np.abs(norm_val_2 - norm_val_1)
            pair_dists[i].append(dist)
            i+=1
    times = np.array(times)
    i=0
    for vals in pair_dists:
        pair_dists[i] = np.array(vals)
        i+=1
    return times, pair_dists
Example #16
0
    def test_alignto_partial_universe():
        u_bound = mda.Universe(ALIGN_BOUND)
        u_free = mda.Universe(ALIGN_UNBOUND)
        selection = 'segid B'

        segB_bound = u_bound.select_atoms(selection)
        segB_free = u_free.select_atoms(selection)
        segB_free.translate(segB_bound.centroid() - segB_free.centroid())

        align.alignto(u_free, u_bound, select=selection)
        assert_array_almost_equal(segB_bound.positions, segB_free.positions, decimal=3)
Example #17
0
    def test_alignto_partial_universe(self, universe, reference):
        u_bound = mda.Universe(ALIGN_BOUND)
        u_free = mda.Universe(ALIGN_UNBOUND)
        selection = 'segid B'

        segB_bound = u_bound.select_atoms(selection)
        segB_free = u_free.select_atoms(selection)
        segB_free.translate(segB_bound.centroid() - segB_free.centroid())

        align.alignto(u_free, u_bound, select=selection)
        assert_array_almost_equal(segB_bound.positions, segB_free.positions,
                                  decimal=3)
Example #18
0
 def test_rmsd(self, universe, reference):
     universe.trajectory[0]  # ensure first frame
     bb = universe.select_atoms('backbone')
     first_frame = bb.positions
     universe.trajectory[-1]
     last_frame = bb.positions
     assert_almost_equal(rms.rmsd(first_frame, first_frame), 0.0, 5,
                         err_msg="error: rmsd(X,X) should be 0")
     # rmsd(A,B) = rmsd(B,A) should be exact but spurious failures in the
     # 9th decimal have been observed (see Issue 57 comment #1) so we relax
     # the test to 6 decimals.
     rmsd = rms.rmsd(first_frame, last_frame, superposition=True)
     assert_almost_equal(
         rms.rmsd(last_frame, first_frame, superposition=True), rmsd, 6,
         err_msg="error: rmsd() is not symmetric")
     assert_almost_equal(rmsd, 6.820321761927005, 5,
                         err_msg="RMSD calculation between 1st and last AdK frame gave wrong answer")
     # test masses as weights
     last_atoms_weight = universe.atoms.masses
     A = universe.trajectory[0]
     B = reference.trajectory[-1]
     rmsd = align.alignto(universe, reference, weights='mass')
     rmsd_sup_weight = rms.rmsd(A, B, weights=last_atoms_weight, center=True,
                                superposition=True)
     assert_almost_equal(rmsd[1], rmsd_sup_weight, 6)
Example #19
0
 def test_toggle_atom_nomatch(self, universe, reference):
     selection = ('resname ALA and name CA', 'resname ALA and name O')
     rmsd = align.alignto(universe,
                          reference,
                          select=selection,
                          match_atoms=False)
     assert rmsd[0] > 0.01
Example #20
0
 def test_toggle_atom_mismatch_kwarg_error(self, universe, reference):
     selection = ('resname ALA and name CA', 'resname ALA and name O')
     with pytest.raises(SelectionError):
         rmsd = align.alignto(universe,
                              reference,
                              select=selection,
                              match_atoms=True)
Example #21
0
def main():
    """Entry to validate_pbc.py"""

    if len(sys.argv) < 3:
        print "Please provide at least a reference file and a trajectory" \
              " for validation"
        sys.exit(1)

    argv = sys.argv[1:]
    ref_name = argv.pop(0)

    for xtc_name in argv:
        print "checking file " + xtc_name
        judger = True
        ref = Universe(ref_name)
        xtc = Universe(ref_name, xtc_name)

        total = 0.0
        count = 0

        for frame in xtc.trajectory:
            rmsd = alignto(xtc, ref, select='protein and name CA')
            if rmsd[1] > THRESHOLD:
                print "At " + str(frame.frame) + " violates the criterion."
                print "trajectory file " + xtc_name + " is invalid."
                judger = False
                break
            total += rmsd[1]
            count += 1

        if judger:
            print "pass" + " - " + "average rmsd: " + str(total / count)
Example #22
0
 def test_rmsd(self):
     self.universe.trajectory[0]  # ensure first frame
     bb = self.universe.select_atoms('backbone')
     first_frame = bb.positions
     self.universe.trajectory[-1]
     last_frame = bb.positions
     assert_almost_equal(rms.rmsd(first_frame, first_frame), 0.0, 5,
                         err_msg="error: rmsd(X,X) should be 0")
     # rmsd(A,B) = rmsd(B,A) should be exact but spurious failures in the
     # 9th decimal have been observed (see Issue 57 comment #1) so we relax
     # the test to 6 decimals.
     rmsd = rms.rmsd(first_frame, last_frame, superposition=True)
     assert_almost_equal(rms.rmsd(last_frame, first_frame,
                                  superposition=True),
                         rmsd, 6,
                         err_msg="error: rmsd() is not symmetric")
     assert_almost_equal(rmsd, 6.820321761927005, 5,
                         err_msg="RMSD calculation between 1st and last "
                         "AdK frame gave wrong answer")
     # test masses as weights
     last_atoms_weight = self.universe.atoms.masses
     A = self.universe.trajectory[0]
     B = self.reference.trajectory[-1]
     rmsd = align.alignto(self.universe, self.reference, weights='mass')
     rmsd_sup_weight = rms.rmsd(A, B,  weights=last_atoms_weight,
                                center=True, superposition=True)
     assert_almost_equal(rmsd[1], rmsd_sup_weight, 6)
Example #23
0
 def process(self):
     rmsd = align.alignto(self.processor.universe,
                          self.refuni,
                          select=self.fitsel)
     xyz = self.processor.currsnap._pos
     self.sumcoords += xyz
     self.sumcoords2 += xyz * xyz
Example #24
0
def align_to_template(pdb_file, ref_file, pdb_output): 
    """
    align frame to target 
    """
    pdb = mda.Universe(pdb_file) 
    ref = mda.Universe(ref_file)
    _ = align.alignto(pdb, ref, select='protein and name CA')
    pdb.atoms.write(pdb_output)
Example #25
0
    def test_subselection_alignto(self, universe, reference, subselection,
                                  expectation):

        with expectation:
            rmsd = align.alignto(universe,
                                 reference,
                                 subselection=subselection)
            assert_almost_equal(rmsd[1], 0.0, decimal=9)
Example #26
0
def Calculate_RMSD(Ini_ref, End_ref):
    '''
    Parameters: 
	    Ini_ref: Initial frame
        End_ref: Target frame
    Returns:
        rmsd_ab: rmsd between start and end frame
	    Ini_position: Coord of initial frame
        End_position: Coord of target frame
    '''
    Ini_temp = Ini_ref.select_atoms('name CA')
    End_temp = End_ref.select_atoms('name CA')
    align.alignto(Ini_temp, End_temp)
    Ini_position = Ini_temp.positions
    End_position = End_temp.positions
    rmsd_ab = rmsd(Ini_position, End_position)
    return rmsd_ab, Ini_position, End_position
Example #27
0
 def test_rmsd_custom_mass_weights(self):
     last_atoms_weight = self.universe.atoms.masses
     A = self.universe.trajectory[0]
     B = self.reference.trajectory[-1]
     rmsd = align.alignto(self.universe, self.reference, weights=self.reference.atoms.masses)
     rmsd_sup_weight = rms.rmsd(A, B,  weights=last_atoms_weight,
                                center=True, superposition=True)
     assert_almost_equal(rmsd[1], rmsd_sup_weight, 6)
Example #28
0
 def test_rmsd_custom_mass_weights(self, universe, reference):
     last_atoms_weight = universe.atoms.masses
     A = universe.trajectory[0]
     B = reference.trajectory[-1]
     rmsd = align.alignto(universe, reference,
                          weights=reference.atoms.masses)
     rmsd_sup_weight = rms.rmsd(A, B, weights=last_atoms_weight, center=True,
                                superposition=True)
     assert_almost_equal(rmsd[1], rmsd_sup_weight, 6)
Example #29
0
def align_protein(mobile, ref, out='aligned', out_path='.'):
    mobile_uni = mda.Universe(mobile)
    ref_uni = mda.Universe(ref)
    print('aligning')
    ret = align.alignto(mobile_uni, ref_uni, select="backbone")
    print(ret)
    file_name = mobile.split('/')[-1].split('.')[0]
    mobile_uni.atoms.write('{}/{}_{}.gro'.format(out_path, file_name, out))
    return
Example #30
0
def capping(ref, ace, nma, output):
    resids = ref.selectAtoms("all").resids()
    resid_min, resid_max = min(resids), max(resids)

    # There is probably some cache i need to update both the atom and residues
    for a in ace.atoms:
        a.resid += resid_min - max(ace.atoms.resids())
    for r in ace.residues:
        r.id += resid_min - max(ace.atoms.resids())
    for a in nma.atoms:
        a.resid = resid_max
    for r in nma.residues:
        r.id = resid_max

    # TODO pick the first residue in the protein (how should we cap the chains?)
    # TODO consider a case when the protein resid is 1 and all peptide has to be shifted by +1, put that in docs as a
    #  post-processing step
    alignto(ace,
            ref,
            select={
                "mobile": "resid {} and backbone".format(resid_min),
                "reference": "resid {} and backbone".format(resid_min)
            })
    alignto(nma,
            ref,
            select={
                "mobile":
                "resid {} and backbone and not (resname NMA or resname NME)".
                format(resid_max),
                "reference":
                "resid {} and (backbone or name OT2)".format(resid_max)
            })

    #  TODO remove the Hydrogen closest to ACE's oxygen
    u = Merge(
        ace.selectAtoms("resname ACE"),
        ref.selectAtoms(
            "not (resid {} and name HT*) and not (resid {} and (name HT* or name OT1))"
            .format(resid_min, resid_max)),
        nma.selectAtoms("resname NME or resname NMA"))
    u.trajectory.ts.dimensions = ref.trajectory.ts.dimensions
    u.atoms.write(output)
    return u
Example #31
0
 def test_rmsd_deprecated(self):
     last_atoms_weight = self.universe.atoms.masses
     A = self.universe.trajectory[0]
     B = self.reference.trajectory[-1]
     with warnings.catch_warnings(record=True) as warn:
         warnings.simplefilter('always')
         rmsd = align.alignto(self.universe, self.reference, mass_weighted=True)
     assert_equal(len(warn), 1)
     rmsd_sup_weight = rms.rmsd(A, B,  weights=last_atoms_weight,
                                center=True, superposition=True)
     assert_almost_equal(rmsd[1], rmsd_sup_weight, 6)
Example #32
0
    def process(self):
        rmsd = align.alignto(self.processor.universe,
                             self.refuni,
                             select=self.sel)[1]
        self.records.append(MDRecord(self.processor.currtime, rmsd * 0.1))

        if self.domobile:
            rmsd = np.sqrt(
                np.mean((self.refsel.positions - self.trjsel.positions)**2))
            self.mobrecords.append(
                MDRecord(self.processor.currtime, rmsd * 0.1))
Example #33
0
 def test_rmsd_deprecated(self):
     last_atoms_weight = self.universe.atoms.masses
     A = self.universe.trajectory[0]
     B = self.reference.trajectory[-1]
     with warnings.catch_warnings(record=True) as warn:
         warnings.simplefilter('always')
         rmsd = align.alignto(self.universe,
                              self.reference,
                              mass_weighted=True)
     assert_equal(len(warn), 1)
     rmsd_sup_weight = rms.rmsd(A,
                                B,
                                weights=last_atoms_weight,
                                center=True,
                                superposition=True)
     assert_almost_equal(rmsd[1], rmsd_sup_weight, 6)
Example #34
0
    def process(self):
        if not self.nowhole:
            if len(self.protsel) > 0:
                xyz = pbc.make_whole_xyz(self.protsel.get_positions(),
                                         self.processor.currbox)
                self.protsel.set_positions(xyz)
            for res in self.residues:
                xyz = pbc.make_whole_xyz(res.get_positions(),
                                         self.processor.currbox)
                res.set_positions(xyz)
        if not self.nocenter:
            self._center()
        if not self.noalign:
            rmsd = align.alignto(self.processor.universe,
                                 self.refuni,
                                 select=self.bbmask)[1]
            self.records.append(MDRecord(self.processor.currtime, rmsd))

        self.writer.write(self.processor.currsnap)
Example #35
0
def d(top, trr, selections):
    u = mda.Universe(top)

    ref = mda.Universe(top)

    rmsd = []

    for l in trr:
        u.trajectory = mda.Universe(l).trajectory

        rmsd.extend([(i.data['step'], i.data['step']*i.dt/10000, *[align.alignto(u.select_atoms(s), ref.select_atoms(s))[1]\
                      for s in selections]) for i in u.trajectory])
        u.trajectory.close()

    cols = [
        ' '.join([w.title() if w.islower() else w for w in s.split()])
        for s in selections
    ]
    df = pd.DataFrame(rmsd, columns=('Step', 'Time', *cols))
    return df.set_index(['Step', 'Time'])
Example #36
0
def _rmsd(layer):
	#mol is an md universe
	print("Loading Trajectory 2x")
	beg = time.time()
	mol_ref = MD.Universe(pdb_file, dcd_file)
	mol_trg = MD.Universe(pdb_file, dcd_file)
	#res,name_file_dcd,mol=args
	print(' This took ' + str(time.time()-beg) + ' seconds')

	#### building selection ####
	res_list = range(res_tip - layer - 4, res_tip - layer + 4)
	res_list += range(res_tip + layer - 4, res_tip + layer + 4)
	sel_ref = mol_ref.selectAtoms('backbone and resid ' + str(res_list[0]))
	sel_trg = mol_trg.selectAtoms('backbone and resid ' + str(res_list[0]))
	for res in res_list[1:]:
		sel_ref += mol_ref.selectAtoms('backbone and resid ' + str(res))
		sel_trg += mol_trg.selectAtoms('backbone and resid ' + str(res))
	
	############################


	rmsd_matrix = []

	for f1 in range(0,mol_ref.trajectory.numframes,skip):
		print('working on frame ' + str(f1))
		mol_ref.trajectory[f1]
#		ref = sel_ref.coordinates()
#		ref = ref.atoms.CA.coordiantes() - ref.atoms.CA.CenterOfMass()
		rmsd = []
		for f2 in range(f1+1,mol_trg.trajectory.numframes, skip):
			mol_trg.trajectory[f2]
			rmsd.append(MDA.alignto(sel_trg, sel_ref)[1])
		rmsd_matrix.append(rmsd)

	for rmsd in rmsd_matrix:
		print rmsd
Example #37
0
pdb_file = sys.argv[1]
dcd_file = sys.argv[2]

print "Loading trajectory"
ref = MDA.Universe(pdb_file)
mol = MDA.Universe(pdb_file, dcd_file)

mol_all = mol.selectAtoms('all')
ref_all = ref.selectAtoms('all')

rmsd_list = []

if "-a" in sys.argv:
	dataout = open(name_file_dcd + 'rmsd.A.txt', 'w')
	for frame in mol.trajectory:
		MDAaa.alignto(mol, ref, select = 'backbone', mass_weighted = True)
		rmsd_list.append(MDAaa.rmsd(mol_all.coordinates(),ref_all.coordinates()))
else:
	dataout = open(name_file_dcd + 'rmsd.txt', 'w')
	for frame in mol.trajectory:
                rmsd_list.append(MDAaa.rmsd(mol_all.coordinates(),ref_all.coordinates()))
	
output = ''

for i in range(len(rmsd_list)):
	output += str(i) + '\t' + '%.5f' % rmsd_list[i] + '\n'

dataout.write(output)
dataout.close()

Example #38
0
 def different_atoms():
     a = u.atoms[10:20]
     b = u.atoms[10:17] + u.atoms[18:21]
     return align.alignto(a, b)
Example #39
0
 def different_size():
     a = u.atoms[10:100]
     b = u.atoms[10:101]
     return align.alignto(a, b)
    trajfile1 = sys.argv[2]
    trajfile2 = sys.argv[3]
    tol = float(sys.argv[4])

    u1 = mda.Universe(topfile, trajfile1)
    u2 = mda.Universe(topfile, trajfile2)

    n1 = 0
    for ts in u1.trajectory:
        n1 += 1

    n2 = 0
    for ts in u1.trajectory:
        n2 += 1

    if  n1 != n2:
        print "Error: only {0} snapshots in first file but {1} in second.".format(n1,n2)
        exit(1)

    u1.trajectory.rewind()
    u2.trajectory.rewind()
    for i in range(n1):
       if i > 0:
           u1.trajectory.next()
           u2.trajectory.next()

       before,after = alignto(u1,u2)
       if after > tol:
           print "Error: at snapshot {0} the two coordinate sets have an RMSD greater than {1} (value={2}).".format(i, tol, after)
           exit(1)
Example #41
0
def mass_density_profile_multi_align(universe, mda_selections, align_struct_universe, align_sel_string, fstart=0, fend=-1,
                                     fstep=1, axis='z', nbins=100, reference=0.0, refsel=None):
    lat_ind = [0, 1]
    dir_ind = 2
    if axis is 'x':
        dir_ind = 0
        lat_ind = [1, 2]
    elif axis is 'y':
        dir_ind = 1
        lat_ind = [0, 2]
    #indices = mda_selection.indices

    # build the mass array
    masses = {}
    for key in mda_selections.keys():
        natoms = len(mda_selections[key])
        masses[key] = np.zeros(natoms)
        a = 0
        for atom in mda_selections[key]:
            masses[key][a] = atom.mass
            a  += 1

    nframes = len(universe.trajectory)
    # adjust the end point for slicing
    if fend != -1:
        fend += 1
    if fend == (nframes - 1) and fstart == (nframes - 1):
        fend += 1
    if fend == fstart:
        fend += 1
    if fstart < 0:
        fstart += nframes
    if fend < 0:
        fend += nframes + 1

    # get the maximum box dimension along axis
    bzm = 0.0
    nframes = 0
    sel_z = []
    system_sel = universe.select_atoms('all')
    for frame in universe.trajectory[fstart:fend:fstep]:
        #get the unaligned system com and axis coordinate
        system_com = system_sel.atoms.center_of_mass()
        system_z = system_com[dir_ind]
        #now do the alignment and get new com and axis coordinates
        align.alignto(universe, align_struct_universe, select=align_sel_string, mass_weighted=True)
        system_com_a = system_sel.atoms.center_of_mass()
        system_z_a = system_com_a[dir_ind]
        dz_a = system_z_a - system_z
        bzc = frame.dimensions[dir_ind]
        if bzc > bzm:
            bzm = bzc
        ref_sel_z = 0.0
        if refsel is not None:
            ref_com = refsel.center_of_mass()
            ref_sel_z = ref_com[dir_ind]
            sel_z.append(-ref_sel_z)
        nframes += 1
    shiftzmax = 0.0
    shiftzmin = 0.0
    if refsel is not None:
        # reference=sel_z_avg/nframes
        shiftzmax = min(sel_z)
        shiftzmin = max(sel_z)
    # build the profile axis
    minz = 0.0 + dz_a + shiftzmin - 0.15*(bzm)
    maxz = bzm + dz_a + shiftzmax + 0.15*(bzm)
    edges = np.linspace(minz, maxz, (nbins + 1), endpoint=True)
    incr = edges[1] - edges[0]
    incr_h = incr / 2.0
    centers = np.zeros(nbins)
    nedges = len(edges)
    for i in xrange(1, nedges):
        j = i - 1
        centers[j] = edges[j] + incr_h

    if refsel is None:
        sel_z = np.zeros(nframes)
    else:
        sel_z = np.array(sel_z)
    f = 0
    out_counts = {}
    for key in mda_selections.keys():
        out_counts[key] = np.zeros(nbins)
    for frame in universe.trajectory[fstart:fend:fstep]:

        bx = frame.dimensions[lat_ind[0]]
        by = frame.dimensions[lat_ind[1]]
        # now do the alignment
        align.alignto(universe, align_struct_universe, select=align_sel_string, mass_weighted=True)
        binvolume = incr * bx * by
        for key in mda_selections.keys():
            indices = mda_selections[key].indices
            counts_f = np.zeros(nbins)
            sel_pos = frame.positions[indices]
            zpos = sel_pos[:, dir_ind]
            sel_z_curr = sel_z[f]
            zpos += sel_z_curr
            push_index = (zpos - minz) / incr
            j = 0
            for i in push_index:
                ii = int(np.floor(i))
                if ii >= nbins:
                    ii = nbins - 1
                elif ii < 0:
                    ii = 0
                counts_f[ii] += masses[key][j]
                j += 1
            counts_f /= binvolume
            out_counts[key] += counts_f
        f += 1
    nframes = float(nframes)
    for key in mda_selections.keys():

        out_counts[key] /= nframes
    centers -= reference

    return centers, out_counts
Example #42
0
	if len(seq_list) > 2:
		print "Alignment must contain 2 sequences only. Order is important... Ref, Target"
		sys.exit()
	else:
		alndic, alnlis = bitk.alnpos_dic(seq_dic[seq_list[0]], seq_dic[seq_list[1]])
else:
	pick = ''

ref = MD.Universe(pdb1)
trg = MD.Universe(pdb2)

output = ''

if aln == 0 or '-useressel' in sys.argv:
	if '-skipaln' not in sys.argv:
		MDA.alignto(trg, ref, mass_weighted=True)
	
	if '-useressel' in sys.argv:
		ressel = alnlis
	else:
		ressel = ref.residues.resids()

	for res in ressel:
                refcrd = ref.selectAtoms("backbone and resid " + str(res)).coordinates()
                trgcrd = trg.selectAtoms("backbone and resid " + str(res)).coordinates()
                rmsd = MDA.rmsd(refcrd, trgcrd)
        	if pick == 'ref':
		        print(str(res) + ' * ' + str(rmsd))
        	        output = str(res) + ' * ' + str(rmsd) + '\n'
		else:
			print(str(alndic[res]) + ' * ' + str(rmsd))
Example #43
0
 def different_atoms():
     a = u.atoms[10:20]
     b = u.atoms[10:17] + u.atoms[18:21]
     return align.alignto(a, b)
Example #44
0
 def different_size():
     a = u.atoms[10:100]
     b = u.atoms[10:101]
     return align.alignto(a, b)