Ejemplo n.º 1
0
def normalize_pts(pts1, pts2):
    #print pts1
    A = pts1[:, 0:2]
    B = pts2[:, 0:2]

    assert len(A) == len(B)

    N = A.shape[0]  # total points

    # find centroids
    centroid_A = rmsd.centroid(A)
    centroid_B = rmsd.centroid(B)

    # centre the points
    AA = A - centroid_A
    BB = B - centroid_B
    
    #get optimal rotation matrix
    R = rmsd.kabsch(AA, BB)
    # Apply transformation
    AA1 = np.dot(AA, R)
    angle1 = math.atan2(R[1][0], R[1][1])
    
    #try flippin' it
    AA[:, 1] *= -1
    #get optimal rotation matrix
    R = rmsd.kabsch(AA, BB)
    # Apply transformation
    AA2 = np.dot(AA, R)#get optimal rotation matrix
    angle2 = math.atan2(R[1][0], R[1][1])
    
    #go with whichever one is better
    a2diff = np.abs(pts2[:,2]-(pts1[:,2]-angle2))
    a1diff = np.abs(pts2[:,2]-(pts1[:,2]+angle1))
    #angle differences are fun!
    for i in range(0, len(a1diff)):
        while (a2diff[i] > np.pi):
            a2diff[i] -= 2*np.pi
        while (a1diff[i] > np.pi):
            a1diff[i] -= 2*np.pi
    print np.degrees(a2diff), np.degrees(a1diff)
    if (np.sum(np.abs(a1diff)) > np.sum(np.abs(a2diff))):
        pts1[:, 0:2] = AA2 + centroid_B
        # rotate the rotations (backwards, since we mirrored the thing)
        pts1[:, 2] -= angle2
        return rmsd.rmsd(AA2, BB)
    else:
        pts1[:, 0:2] = AA1 + centroid_B
        # rotate the rotations
        pts1[:, 2] += angle1
        return rmsd.rmsd(AA1, BB)
Ejemplo n.º 2
0
def rmsd_distance(atoms_list,
                  coordinates_list,
                  translation=False,
                  rotation=False):

    N = len(atoms_list)

    kernel = np.zeros((N, N))

    # Lower triangular

    for i in range(N):
        for j in range(i):

            coord_i = coordinates_list[i]
            coord_j = coordinates_list[j]

            # unique pairs
            if translation:
                coord_i = coord_i - rmsd.centroid(coord_i)
                coord_j = coord_j - rmsd.centroid(coord_j)

            if rotation:
                kernel[i, j] = rmsd.kabsch_rmsd(coord_i, coord_j)
            else:
                kernel[i, j] = rmsd.rmsd(coord_i, coord_j)

            kernel[j, i] = kernel[i, j]

    # np.fill_diagonal(kernel, 0.0)
    # iu2 = np.triu_indices(N, 1)
    # il2 = np.tril_indices(N, -1)
    # kernel[iu2] = kernel[il2]

    return kernel
Ejemplo n.º 3
0
def compute_similarity(site_a, site_b):
    """
    Compute the similarity between two given ActiveSite instances.

    Input: two ActiveSite instances
    Output: the similarity between them (a floating point number)
    """
    site_a_coords = []
    #unpack the ActiveSite class to extract the atom coords of interest
    for i in range(0, len(site_a.residues)):  #loop through all residues
        for j in range(
                0, len(site_a.residues[i].atoms)
        ):  #I chose to loop through all atoms instead of the backbone atoms because all atoms improved the shilhouette mean score
            a = site_a.residues[i].atoms[j].coords
            site_a_coords.append(a)
    site_b_coords = []
    #unpack the site_b and save the coords
    for i in range(0, len(site_b.residues)):
        for j in range(0, len(site_b.residues[i].atoms)):
            b = site_b.residues[i].atoms[j].coords
            site_b_coords.append(b)
    #compute the Root-mean-square deviation
    #low RMSD values (close to 0) are similar structures, compared to higher RMSD values (>>1) are dissimilar
    #RMSD values are never negative
    #Generally, the RMSD calculation is the square root of the standard deviation
    #in atomic structures, the RMSD calculation is the square root of the distance between two atoms with x,y,z coords
    #the package implemented here performs rotations to find the lowest RMSD
    similarity = rmsd.rmsd(site_a_coords, site_b_coords)

    return similarity
Ejemplo n.º 4
0
def test_network(nwtype, restrplt):
    pdb = path.join(curdir, "data", "networks", "%s.pdb" % (restrplt))
    pose = next(privileged_residues.util.models_from_pdb(pdb))

    selector = pyrosetta.rosetta.core.select.residue_selector.ChainSelector(
        "A")
    pres = privileged_residues.PrivilegedResidues()

    ref_sel = pyrosetta.rosetta.core.select.residue_selector.ChainSelector("X")
    selected = ref_sel.apply(pose)
    ref_res = pose.residue(list(selected).index(True))
    ref_coords = np.stack([
        ref_res.atom(n).xyz()
        for n in chemical.functional_groups[ref_res.name()].atoms
    ])

    min_rmsd = 1000.

    for (hash, p) in pres.search(pose, [nwtype], selector):
        res = p.residue(1)
        coords = np.stack([
            res.atom(n).xyz()
            for n in chemical.functional_groups[res.name()].atoms
        ])

        RMSD = rmsd(ref_coords, coords)

        if (RMSD < min_rmsd):
            min_rmsd = RMSD

        if (RMSD < 0.25):
            return

    print("Minimum RMSD across matched structures: %.3f" % min_rmsd)
    assert (False)
Ejemplo n.º 5
0
def get_mappings(ref, structure):

	n = len(structure)
	cs = itertools.permutations(range(n), 3)

	keeps = {}

	for c in cs:
		Q = rmsd.kabsch(ref[:3], structure[list(c)]).T
		assert np.linalg.det(Q) > 0.5

		rotated = np.dot(structure, Q.T)
		ds = scipy.spatial.distance.cdist(rotated, ref)

		_, res = scipy.optimize.linear_sum_assignment(ds)
		res = invert_array(res)
		obj = rmsd.rmsd(rotated[res], structure)
		if obj > 1E-3:
			continue

		key = tuple(res)
		if key not in keeps:
			keeps[key] = Q

	return keeps
Ejemplo n.º 6
0
def test_pdb(example_path="examples", threshold=0.001):
    """
    A simple test for the PDB functionality
    :return: True if all test passed
    """
    p_atoms, P = rmsd.get_coordinates(example_path+'/ci2_1.pdb', 'pdb')
    q_atoms, Q = rmsd.get_coordinates(example_path+'/ci2_2.pdb', 'pdb')

    n_rmsd = rmsd.rmsd(P, Q)
    Pc = rmsd.centroid(P)
    Qc = rmsd.centroid(Q)
    P -= Pc
    Q -= Qc

    k_rmsd = rmsd.kabsch_rmsd(P, Q)
    q_rmsd = rmsd.quaternion_rmsd(P, Q)

    if abs(n_rmsd - 26.975) > threshold:
        print('Failed to calculate normal RMSD, result: {0}'.format(n_rmsd))
        return False
    if abs(k_rmsd - 11.777) > threshold:
        print('Failed to calculate Kabsch RMSD, result: {0}'.format(k_rmsd))
        return False
    if abs(q_rmsd - 11.777) > threshold:
        print('Failed to calculate quaternion RMSD, result: {0}'.format(q_rmsd))
        return False
    if abs(q_rmsd - k_rmsd) > threshold ** 2:
        print('Failed to yield similar Kabsch and quaternion RMSD, result: {0} vs {1}'.format(k_rmsd, q_rmsd))
        return False
    return True
Ejemplo n.º 7
0
def rms(config, compare: Tuple[str, str], out: click.File):
    """Calculate the root mean squared deviation between two structures using quaternions.
    Based on a Fortran implementation by Chaok Seok, Evangelos
    Coutsias, and Ken Dill."""

    from rmsd import rmsd

    mol1 = ksr.constructMolecule(geometry=compare[0])
    nat1 = mol1.get_number_of_atoms()
    mol2 = ksr.constructMolecule(geometry=compare[1])
    nat2 = mol2.get_number_of_atoms()

    # for RMSD comparison both coordinates need the same atom count
    if nat1 != nat2:
        click.echo(
            "Error: number of atoms do not match in {} and in {}".format(
                compare[0], compare[1]
            ),
            file=out,  # type: ignore
        )
        errorbye(out)

    coord1 = mol1.get_positions()
    coord2 = mol2.get_positions()

    # get RMSD error and rotation matrix u
    error, u = rmsd(nat1, coord1, coord2)

    verbosePrinter(config.verbose, "RMSD {} Angstrom".format(error), out)
    verbosePrinter(config.verbose, "Rotation Matrix", out)
    click.echo(u, file=out)  # type: ignore

    return error, u
Ejemplo n.º 8
0
    def normalize_pts(self, pts1, pts2):
        #print pts1
        A = pts1[:, 0:2]
        B = pts2[:, 0:2]

        assert len(A) == len(B)

        N = A.shape[0]  # total points

        # find centroids
        centroid_A = rmsd.centroid(A)
        centroid_B = rmsd.centroid(B)

        # centre the points
        AA = A - centroid_A
        BB = B - centroid_B

        #get optimal rotation matrix
        R = rmsd.kabsch(AA, BB)
        # Apply transformation
        AA1 = np.dot(AA, R)
        angle1 = math.atan2(R[1][0], R[1][1])

        pts1[:, 0:2] = AA1 + centroid_B
        # rotate the rotations
        pts1[:, 2] -= angle1
        return rmsd.rmsd(AA1, BB)
Ejemplo n.º 9
0
def alin(A,B):
	A -= rmsd.centroid(A)
	B -= rmsd.centroid(B)
	#print (B)
	U = rmsd.kabsch(A, B)
	A = np.dot(A, U)

	return A, B, rmsd.rmsd(A,B)
    def run(self, residues1: SetOfResidues, residues2: SetOfResidues,
            get_centered_c_alpha_coords: GetCenteredCAlphaCoords,
            get_rotation_matrix: GetRotationMatrix) -> float:
        P, Q = map(get_centered_c_alpha_coords, (residues1, residues2))

        # following code from rmsd.kabsch_rmsd()
        P = np.dot(P, get_rotation_matrix(residues1, residues2))
        return rmsd.rmsd(P, Q)
Ejemplo n.º 11
0
def crmsd_kabsch(A, B):
    # Translate
    A -= rmsd.centroid(A)
    B -= rmsd.centroid(B)

    # Rotate
    U = rmsd.kabsch(A, B)
    A = np.dot(A, U)

    return rmsd.rmsd(A, B)
Ejemplo n.º 12
0
def test_rmsd_pdb():

    filename_1 = pathlib.PurePath(RESOURCE_PATH, "ci2_1.pdb")
    filename_2 = pathlib.PurePath(RESOURCE_PATH, "ci2_2.pdb")

    p_atoms, p_coord = rmsd.get_coordinates_pdb(filename_1)
    q_atoms, q_coord = rmsd.get_coordinates_pdb(filename_2)

    pure_rmsd = rmsd.rmsd(p_coord, q_coord)

    np.testing.assert_almost_equal(26.9750, pure_rmsd, decimal=3)
Ejemplo n.º 13
0
def test_rmsd_xyz():

    filename_1 = pathlib.PurePath(RESOURCE_PATH, "ethane.xyz")
    filename_2 = pathlib.PurePath(RESOURCE_PATH, "ethane_mini.xyz")

    p_atoms, p_coord = rmsd.get_coordinates_xyz(filename_1)
    q_atoms, q_coord = rmsd.get_coordinates_xyz(filename_2)

    pure_rmsd = rmsd.rmsd(p_coord, q_coord)

    np.testing.assert_almost_equal(0.33512, pure_rmsd, decimal=3)
Ejemplo n.º 14
0
def test_arbitrary_shuffles():
    """Given an original geometry and a shuffled geometry derived
    from the original one, the Hungarian method should be able to
    fully reconstruct the original order of atoms."""

    benz, _ = get_geoms()
    coords_by_type, inds_by_type = benz.coords_by_type
    atom_num = len(benz.atoms)
    initial_order = np.arange(atom_num)
    atom_arr = np.array(benz.atoms)
    c3d = benz.coords3d.copy()

    for i in range(10):
        shuffled_geom = shuffle_geometry(benz)

        org_rmsd = rmsd.rmsd(benz.coords3d, shuffled_geom.coords3d)
        matched_geom = match_geom_atoms(benz, shuffled_geom, hydrogen=True)
        matched_rmsd = rmsd.rmsd(benz.coords3d, matched_geom.coords3d)
        print(f"RMSD(shuffled) {org_rmsd:.2f} "
              f"RMSD(matched) {matched_rmsd:.2f}")
        assert np.allclose(matched_rmsd, 0.0)
Ejemplo n.º 15
0
    def calc_rmsd(self):
        """
        Calculate normal, translated, and rotated RMSD.

        """
        tmp_1, tmp_2 = self.coord_1.copy(), self.coord_2.copy()

        self.rmsd_normal = rmsd.rmsd(self.coord_1, self.coord_2)

        # Manipulate recenter
        self.coord_1 -= rmsd.centroid(self.coord_1)
        self.coord_2 -= rmsd.centroid(self.coord_2)

        self.rmsd_translate = rmsd.rmsd(self.coord_1, self.coord_2)

        # Rotate
        rotation_matrix = rmsd.kabsch(self.coord_1, self.coord_2)
        self.coord_1 = np.dot(self.coord_1, rotation_matrix)

        self.rmsd_rotate = rmsd.rmsd(self.coord_1, self.coord_2)

        self.coord_1, self.coord_2 = tmp_1, tmp_2
Ejemplo n.º 16
0
def test_match(dummy, selector):
    pr = PrivilegedResidues(path.join(path.dirname(__file__), "data/DUMMY.zarr/"))

    res = dummy.residue(2)
    expected_coords = np.array([res.xyz(atom) for atom in rsd_to_fxnl_grp[res.name3()].atoms])

    for (_, match) in pr.search(dummy, selector, groups=["sc_bb"]):
        rmatch = match.residue(1)
        coords = np.array([rmatch.xyz(atom) for atom in functional_groups[rmatch.name()].atoms])

        if (rmsd(coords, expected_coords) < 0.1):
            return

    assert()
Ejemplo n.º 17
0
def calculate_rmsd(mol_id,
                   geometry_id1=None,
                   geometry_id2=None,
                   heavy_atoms_only=False):

    # These cause circular import errors if we put them at the top of the file
    from ._girder import GirderClient
    from ._calculation import GirderMolecule

    # Allow the user to pass in a GirderMolecule instead of an id
    if isinstance(mol_id, GirderMolecule):
        mol_id = mol_id._id

    if geometry_id1 is None:
        cjson1 = GirderClient().get('/molecules/%s/cjson' % mol_id)
    else:
        cjson1 = GirderClient().get('/molecules/%s/geometries/%s/cjson' %
                                    (mol_id, geometry_id1))

    if geometry_id2 is None:
        cjson2 = GirderClient().get('/molecules/%s/cjson' % mol_id)
    else:
        cjson2 = GirderClient().get('/molecules/%s/geometries/%s/cjson' %
                                    (mol_id, geometry_id2))

    coords1 = cjson1['atoms']['coords']['3d']
    coords1_triplets = zip(coords1[0::3], coords1[1::3], coords1[2::3])
    A = np.array([x for x in coords1_triplets])

    coords2 = cjson2['atoms']['coords']['3d']
    coords2_triplets = zip(coords2[0::3], coords2[1::3], coords2[2::3])
    B = np.array([x for x in coords2_triplets])

    if heavy_atoms_only:
        atomic_numbers = cjson1['atoms']['elements']['number']
        heavy_indices = [i for i, n in enumerate(atomic_numbers) if n != 1]

        A = A.take(heavy_indices, 0)
        B = B.take(heavy_indices, 0)

    # Translate
    A -= rmsd.centroid(A)
    B -= rmsd.centroid(B)

    # Rotate
    U = rmsd.kabsch(A, B)
    A = np.dot(A, U)

    return rmsd.rmsd(A, B)
Ejemplo n.º 18
0
def calc_rmsd(coords1, coords2):
    """Calculate root-mean square deviation.

    Parameters
    ----------
    coords1 : list(list(str,int,int,int))
        The coordinates for the first
        molecule (conformer).
    coords2 : list(list(str,int,int,int))
        The coordinates for the second
        molecule (conformer).

    Notes
    -----
    The coordinates are given as follows:
    atom name, x coord, y coord, z coord
    Example for carbon monoxide:
    [[C, 0.0, 0.0, 0.0],[O, 1.0, 0.0, 0.0]]
    The distances are in Angstroms.

    Returns
    -------
    rmsd : float
        The rmsd between two molecular
        geometries. This rmsd is calculated
        after applying centering and a
        rotation matrix (calculated via
        the Kabsch algorithm).

    """
    # trivial check
    assert len(coords1) == len(coords2)
    # first turn lists into numpy arrays (otherwise
    # cannot perform some rmsd operations)
    # and excise atom names (not needed for rmsd)
    mol1 = np.array([[coords1[i][1], coords1[i][2], coords1[i][3]] for i in range(len(coords1))])
    mol2 = np.array([[coords2[i][1], coords2[i][2], coords2[i][3]] for i in range(len(coords2))])
    # first center each molecule
    mol1 -= rmsd.centroid(mol1)
    mol2 -= rmsd.centroid(mol2)
    # calculate the rotation matrix
    rot_matrix = rmsd.kabsch(mol1, mol2)
    # apply the rotation matrix
    mol1 = np.dot(mol1, rot_matrix)
    # finally get the rmsd
    return rmsd.rmsd(mol1, mol2)
Ejemplo n.º 19
0
 def set_metric(self,metric_type):
   metric_type = metric_type.upper()
   if   (metric_type[:4] == 'RMSD'): 
     self.metric = rmsd.rmsd()
   elif (metric_type[:4] == 'OGTO'):
     if len(metric_type) > 4 :
       sigma = float(metric_type[5:])
       self.metric = ogto.ogto(sigma)
     else :
       self.metric = ogto.ogto()
   elif (metric_type[:4] == 'SOAP'):
     self.metric = soap.soap()
   else:
     print "!!! unknown metric type:",metric_type,"!!!"
     sys.exit()
   print "> metric type:",self.metric.tag()
   sys.stdout.flush()
Ejemplo n.º 20
0
def find(structures, generators=None):

	generators = np.array(generators)
	structures = [structure[1:] for structure in structures]
	ref = structures[0]

	data = []
	for j, structure in enumerate(structures):

		for i, q in enumerate(generators):
			U = quat_utils.quaternion_to_rotation_matrix(q)
			rotated = np.dot(structure, U.T)
			ds = scipy.spatial.distance.cdist(ref, rotated)
			_, mapping = scipy.optimize.linear_sum_assignment(ds)
			obj = rmsd.rmsd(ref, rotated[mapping])
			if obj > 1E-3:
				continue

			data += [(i, j, mapping, q)]

	indices, js, _, qs = zip(*sorted(data))
	print js

	assert indices == tuple(range(len(indices)))
	for index, js, mapping, q in sorted(data):

		mapping = [0] + list(np.array(mapping) + 1)
		print "{" + ", ".join([str(e).rjust(2) for e in mapping]) + "},"#, q

	_qs = []
	for q in qs:
		t = [1, 0.1, 0.01, 0.001]
		if np.dot(-q, t) > np.dot(q, t):
			q = -q
		_qs += [(np.dot(q, t), tuple(q))]
	_qs = sorted(_qs, reverse=True)
	qs = np.array([e[1] for e in _qs])
	for q in qs:
		print "{" + ", ".join([("%.14f" % e).rjust(18) for e in q]) + "},"
Ejemplo n.º 21
0
def normalize_pts_old(pts1, pts2, win):
    #print pts1
    A = pts1[:, 0:2]
    B = pts2[:, 0:2]

    assert len(A) == len(B)

    N = A.shape[0]  # total points

    # find centroids
    centroid_A = rmsd.centroid(A)
    centroid_B = rmsd.centroid(B)

    # centre the points
    AA = A - centroid_A
    BB = B - centroid_B
    
    #get optimal rotation matrix
    R = rmsd.kabsch(AA, BB)
    # Apply transformation
    AA1 = np.dot(AA, R)
    angle1 = math.atan2(R[1][0], R[1][1])
    
    i=0
    for pt in pts1:
        pt_graphics = Point(int(pt[0]-centroid_A[0]+centroid_B[0]), int(pt[1]-centroid_A[1]+centroid_B[1]))
        cir = Circle(pt_graphics, 8)
        cir.setOutline('green')
        cir.draw(win)
        line = Line(pt_graphics, Point(pt_graphics.x+8*np.cos(-pt[2]), pt_graphics.y+8*np.sin(-pt[2])))
        line.draw(win)
        text = Text(pt_graphics, str(i))
        i += 1
        text.draw(win)
    
    pts1[:, 0:2] = AA1 + centroid_B
    # rotate the rotations
    pts1[:, 2] -= angle1
    return rmsd.rmsd(AA1, BB)
Ejemplo n.º 22
0
def main():
    '''
    Run the main function.
    '''
    # First, parse command line arguments
    pdbpath, xtcpath = parse_arguments()

    # Get numpy array of coordinates for trajectory
    # Again, note the pdb files must be 'go'models and not full-atom models
    coordinates = xtc2numpyarray(xtcpath, pdbpath)

    # Get numpy array of coordinates for reference structure
    ref_coordinates = pdb2numpyarray(pdbpath)

    # Iterate through the frames of the trajectory and calculate the RMS 
    # deviation relative to the ref_coordinates
    rmsd_list = []
    for frame in coordinates:

        # This module is from the rmsd.py script that must be in the same directory
        # as this script
        r = rmsd.rmsd(frame, ref_coordinates)
        rmsd_list.append(r) 
        numpy.savetxt("rmsd.txt", rmsd_list)
Ejemplo n.º 23
0
def filter_clash_minimize(pose,
                          hits,
                          clash_cutoff=35.0,
                          rmsd_cutoff=0.5,
                          sfx=None,
                          mmap=None,
                          limit=0):
    """Filter match output for clashes, then minimize the remaining
    structures against the target pose.

    Parameters
    ----------
    pose : pyrosetta.Pose
        Target structure.
    hits : np.ndarray
        Set of functional group matches against positions in the target.
    clash_cutoff : float
        Maximum tolerated increase in score terms during clash checking.
    sfx : pyrosetta.rosetta.core.scoring.ScoreFunction, optional
        Scorefunction to use during minimization. If left as None, a
        default scorefunction is constructed.
    mmap : pyrosetta.rosetta.protocols.minimization_packing.MinMover, optional
        Movemap to use during minimization. If left as None, a default
        movemap is constructed.

    Yields
    ------
    pyrosetta.Pose
        Next target structure and matched functional group, minimized
        and in complex.
    """
    if (not sfx):
        sfx = scoring.ScoreFunctionFactory.create_score_function("beta_nov16")

        sfx.set_weight(scoring.hbond_bb_sc, 2.0)
        sfx.set_weight(scoring.hbond_sc, 2.0)

    if (not mmap):
        mmap = MoveMap()

        mmap.set_bb(False)
        mmap.set_chi(False)
        mmap.set_jump(1, True)

    minmov = MinMover(mmap, sfx, "dfpmin_armijo_nonmonotone", 0.01, False)

    for n, (hash, match) in enumerate(hits):
        proto_pose = pose.clone()
        proto_pose.append_pose_by_jump(match, len(proto_pose.residues))

        sfx(proto_pose)

        fa_rep = proto_pose.energies().total_energies()[scoring.fa_rep]
        fa_elec = proto_pose.energies().total_energies()[scoring.fa_elec]

        if (fa_rep + fa_elec > clash_cutoff):
            continue

        minmov.apply(proto_pose)
        minimized = proto_pose.split_by_chain(proto_pose.num_chains())

        ori_coords = np.array(
            [atom.xyz() for res in match.residues for atom in res.atoms()])
        min_coords = np.array(
            [atom.xyz() for res in minimized.residues for atom in res.atoms()])

        if (rmsd(ori_coords, min_coords) < rmsd_cutoff):
            yield (hash, minimized)

        if (limit and n + 1 >= limit):
            break

    return []
Ejemplo n.º 24
0
metric/s from Bartok's SOAP similarity measure
"""
import sys
import math
import os
import numpy as np
lib_path = os.path.abspath('..')
sys.path.append(lib_path)
import util
import soap
import rmsd
import ogto

###################################################################
d = soap.soap()
g = rmsd.rmsd()
o = ogto.ogto()
c1 = [[1.1, 1, 1], 
      [1, -1, -1], 
      [-1, 1, -1], 
      [-1, -1, 1]]
c1 = [[2.2, 2, 2], 
      [2, -2, -2], 
      [-2, 2, -2], 
      [-2, -2, 2]]
c2 = [[1.1, 1.1, 1.1], 
      [1.1, -1.1, -1.1], 
      [-1.1, 1.1, -1.1], 
      [-1.1, -1.1, 1.1]]
#-------------------------------
c1 = [[ 1.23,  1.43,  1.43], 
Ejemplo n.º 25
0
              [2.0, 1.5]])

# Same "molecule"
B = np.array([[1.0, 1.0],
              [1.0, 2.0],
              [2.0, 1.5]])

B *= 1.4

# Translate
B -= 3

# Rotate
B = np.dot(B, rotation_matrix(90))

print("Normal RMSD", rmsd.rmsd(A, B))
save_plot(A, B, "plot_beginning.png")

# Manipulate
A -= rmsd.centroid(A)
B -= rmsd.centroid(B)

print("Centered RMSD", rmsd.rmsd(A, B))
save_plot(A, B, "plot_centered.png")

U = rmsd.kabsch(A, B)
A = np.dot(A, U)

print("Translated RMSD", rmsd.rmsd(A, B))
save_plot(A, B, "plot_translated.png")
Ejemplo n.º 26
0
def getrmsd(mol1, mol2):
    U_noH = rmsd.kabsch(mol1[2], mol2[2])
    Temp_noH = np.dot(mol1[2], U_noH)
    return rmsd.rmsd(Temp_noH, mol2[2])
Ejemplo n.º 27
0
    def chainRMSD(self, chain_):
        """ Calculates RMSD using https://github.com/charnley/rmsd
			param chain_ : chain being compared
		"""
        return (rmsd.rmsd(self.getPosArray(), chain_.getPosArray()))
Ejemplo n.º 28
0
              [2.0, 1.5]])

# Same "molecule"
B = np.array([[1.0, 1.0],
              [1.0, 2.0],
              [2.0, 1.5]])

B *= 1.4

# Translate
B -= 3

# Rotate
B = np.dot(B, rotation_matrix(90))

print("Normal RMSD", rmsd.rmsd(A, B))
save_plot(A, B, "plot_beginning")

# Manipulate
A -= rmsd.centroid(A)
B -= rmsd.centroid(B)

print("Translated RMSD", rmsd.rmsd(A, B))
save_plot(A, B, "plot_translated")

U = rmsd.kabsch(A, B)
A = np.dot(A, U)

print("Rotated RMSD", rmsd.rmsd(A, B))
save_plot(A, B, "plot_rotated")
Ejemplo n.º 29
0
def residue_dist(residue_a, residue_b):
    a_coords = backbone_coords(residue_a)
    b_coords = backbone_coords(residue_b)
    dist = rmsd.rmsd(a_coords, b_coords)
    return dist
Ejemplo n.º 30
0
    f2 = np.array([0, 1, 0])
    c3 = np.array([[1, 1, 1], [1, -1, -1.01], [-1, 1, -1], [-1, -1, 1]])
    f3 = np.array([0, 0, 1])
    c4 = np.array([[1, 2, 1], [1, -1, -1.01], [-1, 1, -1], [-1, -1, 1]])
    f4 = np.array([1, 0, 1])
    print "c1\n", c1
    print "f1 ", f1
    print "c2\n", c2
    print "f2 ", f2
    print "c3\n", c3
    print "f3 ", f3
    print "c4\n", c4
    print "f4 ", f4

    import rmsd
    m = rmsd.rmsd()
    [d12, R12] = m.distance(c1, c2)
    [d13, R13] = m.distance(c1, c3)
    [d14, R14] = m.distance(c1, c4)
    [d23, R23] = m.distance(c2, c3)
    [d24, R24] = m.distance(c2, c4)
    [d34, R34] = m.distance(c3, c4)

    Ds = np.array([[0, d12, d13, d14], [d12, 0, d23, d24], [d13, d23, 0, d34],
                   [d14, d24, d34, 0]])

    print "using an inverse quadratic"
    rbf = inverse_quadratic()
    print "relative distances/adjacency matrix\n", Ds
    fs = np.array([f1, f2, f3, f4])
    print "(rotated) force values\n", fs
Ejemplo n.º 31
0
def calc_rmsd(acf):
    """
    Calculate root mean squared displacement of atoms in complex, RMSD.

    Parameters
    ----------
    acf : list
        Atomic labels and coordinates of full complex.
        
    Returns
    -------
    rmsd_normal : int or float
        Normal RMSD,
    rmsd_translate : int or float
        Translate RMSD (re-centered),
    rmsd_rotate : int or float
        Kabsch RMSD (rotated),
    
    References
    ----------
    https://github.com/charnley/rmsd

    Examples
    --------
    >>> comp1.xyz
    Fe        10.187300000     5.746300000     5.615000000
    O         8.494000000     5.973500000     4.809100000
    O         9.652600000     6.422900000     7.307900000
    N        10.803800000     7.531900000     5.176200000
    N         9.622900000     3.922100000     6.008300000
    N        12.006500000     5.556200000     6.349700000
    N        10.804600000     4.947100000     3.921900000
    >>> comp2.xyz
    Fe        12.093762780     2.450541280     3.420711630
    O        12.960362780     2.295241280     1.728611630
    O        13.487662780     1.618241280     4.423011630
    N        12.852262780     4.317441280     3.989411630
    N        10.930762780     0.769741280     2.931511630
    N        10.787862780     2.298741280     5.107111630
    N        10.677362780     3.796041280     2.542411630
    >>> complex = [comp1, comp2]  # comp1 and comp2 are lists of coordinates of two complex
    >>> calc_rmsd(complex)
    RMSD between two complexes
    **************************
    Normal RMSD       : 5.015001
    Re-centered RMSD  : 2.665076
    Rotated RMSD      : 1.592468

    """
    strct_1 = acf[0]
    strct_2 = acf[1]

    atom_strc_1, coord_strct_1 = strct_1
    atom_strc_2, coord_strct_2 = strct_2

    rmsd_normal = rmsd.rmsd(coord_strct_1, coord_strct_2)

    # Manipulate recenter
    coord_strct_1 -= rmsd.centroid(coord_strct_1)
    coord_strct_2 -= rmsd.centroid(coord_strct_2)

    rmsd_translate = rmsd.rmsd(coord_strct_1, coord_strct_2)

    # Rotate
    U = rmsd.kabsch(coord_strct_1, coord_strct_2)
    coord_strct_1 = np.dot(coord_strct_1, U)

    rmsd_rotate = rmsd.rmsd(coord_strct_1, coord_strct_2)

    return rmsd_normal, rmsd_translate, rmsd_rotate
Ejemplo n.º 32
0
 def connectRMSD(self, connect_):
     return (rmsd.rmsd(self.getConnectPos(), connect_.getConnectPos()))
Ejemplo n.º 33
0
z_angle = np.pi / 5
R = euler2mat(x_angle, y_angle, z_angle, 'sxyz')
'''
a = np.array([0, 0, 0])
b = np.array([10, 10, 0])
c = np.array([20, 0, 0])
'''
A = 10 * np.random.rand(50, 3)
B = np.dot(A, R)
extra = 10*np.random.rand(10, 3)
#B = np.append(B, extra, axis = 0)
B += random.uniform(-10, 10)
#np.random.shuffle(B)
#A, B = generate_set(A, B)
plot3d(A, B)
print("Normal RMSD", rmsd.rmsd(A, B))

# Manipulate
A -= rmsd.centroid(A)
B -= rmsd.centroid(B)
plot3d(A, B)
print("Translated RMSD", rmsd.rmsd(A, B))

markA = A[0:3, :]
markB = B[0:3, :]
U = rmsd.kabsch(markA, markB)
A = np.dot(A, U)

plot3d(A, B)
print("Rotated RMSD", rmsd.rmsd(A, B))
import numpy as np

file1 = './opted_mols/2-Mn-OtBu_opted.xyz'
with open(file1, 'r') as f1:
    n = int(f1.readline())
    f1.readline()
    coord = []
    for _ in range(n):
        coord.append(list(map(float, f1.readline().split()[1::])))

coord = np.array(coord)
coord2 = np.array([c + np.array([1, 1, 4]) for c in coord])

coord -= rmsd.centroid(coord)
coord2 -= rmsd.centroid(coord2)
print(rmsd.rmsd(coord, coord2))

phi, psi = pi / 10, pi / 4
coord3 = np.array([
    np.array([
        c[0] * (1), c[1] * cos(psi) + c[2] * sin(psi),
        -c[1] * sin(psi) + c[2] * cos(psi)
    ]) for c in coord
])

coord3 -= rmsd.centroid(coord3)
rotate = rmsd.kabsch(coord3, coord)

coord3 = np.dot(coord3, rotate)

print(rmsd.rmsd(coord, coord3))