コード例 #1
0
def plot_2D_comparison(batch_case,
                       network_tupla,
                       title,
                       savepath,
                       method="f0"):
    best_index = batch_case[1].index(min(batch_case[1]))
    weight_list = np.asarray([a for a in batch_case[0]])
    best_weights = weight_list[best_index]
    original_coords = network_tupla[1]
    base_coords = nt.get_spectral_coordinates(nx.laplacian_matrix(
        network_tupla[0]).todense(),
                                              dim=2)
    if method == "f0":
        after_coords = nt.get_spectral_coordinates(
            nx.laplacian_matrix(network_tupla[0]).todense(),
            mod_matrix=nt.create_inverse_mod_matrix(best_weights),
            dim=2)
    elif method == "f1":
        after_coords = nt.get_spectral_coordinates(
            laplacian=nt.create_customized_laplacian(network_tupla[0],
                                                     best_weights),
            dim=2)
    elif method == "f2":
        after_coords = nt.get_spectral_coordinates(
            laplacian=nt.create_weighted_laplacian(network_tupla[0],
                                                   best_weights),
            dim=2)
    else:
        assert False
    base_coords = pd.DataFrame(rmsd.kabsch_rotate(base_coords.values,
                                                  original_coords.values),
                               columns=["x", "y", "z"])
    after_coords = pd.DataFrame(rmsd.kabsch_rotate(after_coords.values,
                                                   original_coords.values),
                                columns=["x", "y", "z"])
    plt.scatter(original_coords["x"],
                original_coords["y"],
                color='C0',
                marker='.',
                label="Originali",
                s=50)
    plt.scatter(base_coords["x"],
                base_coords["y"],
                color='C2',
                marker='x',
                label="SD di base",
                s=10)
    plt.scatter(after_coords["x"],
                after_coords["y"],
                s=10,
                color='C1',
                marker='*',
                label="SD con modifica")
    plt.title("")
    plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=3)
    plt.xlabel("$X$")
    plt.ylabel("$Y$")
    plt.tight_layout()
    plt.savefig(savepath, dpi=DPI)
    plt.clf()
コード例 #2
0
def rmsd_and_max(P, Q):
    '''
    ** ADAPTED FROM THE PYTHON RMSD LIBRARY **

    Rotate matrix P unto Q using Kabsch algorithm and calculate the RMSD.
    Returns RMSD and max deviation.

    Parameters
    ----------
    P : array
        (N,D) matrix, where N is points and D is dimension.
    Q : array
        (N,D) matrix, where N is points and D is dimension.

    Returns
    -------
    rmsd : float
        root-mean squared deviation
    max_delta : float
        maximum deviation value
    '''

    Q = Q - Q.mean(axis=0)
    P = P - P.mean(axis=0)
    P = kabsch_rotate(P, Q)

    diff = Q - P
    rmsd = np.sqrt((diff * diff).sum() / len(diff))
    max_delta = np.linalg.norm(diff, axis=1).max()

    return rmsd, max_delta
コード例 #3
0
ファイル: Kick.py プロジェクト: sheepforce/pysisyphus
 def get_input_geom(self, geom):
     kick = self.get_kick()
     new_geom = geom.copy()
     new_coords = new_geom.coords + kick
     # Rotate the newly generated coordinates on the initial
     # coordinates.
     # TODO: this may be not needed as we align+match later on ...
     new_coords = rmsd.kabsch_rotate(new_coords.reshape(-1, 3),
                                     self.initial_coords3d).flatten()
     new_geom.coords = new_coords
     return new_geom
コード例 #4
0
def test_kabash_rotate_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)

    new_p_coord = rmsd.kabsch_rotate(p_coord, q_coord)

    np.testing.assert_array_almost_equal([10.6822, -2.8867, 12.6977],
                                         new_p_coord[0],
                                         decimal=3)
コード例 #5
0
def plot_network_and_spectral_basic(network,
                                    coordinates,
                                    title="",
                                    savepath="",
                                    showfig="False",
                                    view_thet=30,
                                    view_phi=30):
    basic_coordinates = get_spectral_coordinates(
        nx.laplacian_matrix(network).todense(), dim=3)
    basic_coordinates = pd.DataFrame(rmsd.kabsch_rotate(
        basic_coordinates.values, coordinates.values),
                                     columns=["x", "y", "z"])
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(coordinates["x"],
               coordinates["y"],
               coordinates["z"],
               label="Originale")
    ax.scatter(basic_coordinates["x"],
               basic_coordinates["y"],
               basic_coordinates["z"],
               label="Spectral Basic")
    for edge in list(network.edges):
        ax.plot(
            (coordinates.iloc[edge[0]]["x"], coordinates.iloc[edge[1]]["x"]),
            (coordinates.iloc[edge[0]]["y"], coordinates.iloc[edge[1]]["y"]),
            (coordinates.iloc[edge[0]]["z"], coordinates.iloc[edge[1]]["z"]),
            c="grey",
            alpha=0.7)
        ax.plot((basic_coordinates.iloc[edge[0]]["x"],
                 basic_coordinates.iloc[edge[1]]["x"]),
                (basic_coordinates.iloc[edge[0]]["y"],
                 basic_coordinates.iloc[edge[1]]["y"]),
                (basic_coordinates.iloc[edge[0]]["z"],
                 basic_coordinates.iloc[edge[1]]["z"]),
                c="red",
                alpha=0.4)
    ax.legend()
    ax.set_xlabel("X")
    ax.set_ylabel("Y")
    ax.set_zlabel("Z")
    if title != "":
        ax.set_title(title)
    if showfig:
        ax.view_init(view_thet, view_phi)
        plt.show()
    if savepath != "":
        ax.view_init(view_thet, view_phi)
        plt.savefig(savepath, dpi=300)
        plt.clf()
コード例 #6
0
ファイル: FragmentKick.py プロジェクト: sheepforce/pysisyphus
 def get_input_geom(self, geom):
     kicked_frags = list()
     for i, fc in enumerate(self.frag_coords):
         if i in self.fix_fragments:
             kicked_frag = fc
         else:
             kicked_frag = self.kick_fragment(fc)
         kicked_frags.append(kicked_frag)
     new_coords3d = np.concatenate(kicked_frags)
     # As the fragments are not necessarily defined in order, especially
     # when we generate the second fragment automatically, we have to
     # sort the coordinates, so they are in the original order. E.g. the
     # fragments ((4, 3), (2, 1, 0)) would result 'new_coords3d' with the
     # coordinates of atom 4 at index 0, coordinates of atom 3 at index 1, etc.
     new_coords3d = new_coords3d[self.sort_inds]
     new_coords = rmsd.kabsch_rotate(new_coords3d,
                                     self.initial_coords3d).flatten()
     new_geom = Geometry(self.atoms, new_coords)
     return new_geom
コード例 #7
0
ファイル: structures.py プロジェクト: psyche11/atomium
    def superimpose_onto(self, other):
        """Superimoses this structure onto another - it will be translated so
        that its center of mass matches the other structure's, then rotated so
        as to minimise the RMSD.

        The other structure must have the same number of atoms.

        :param AtomStructure other: The structure to superimpose onto. This\
        structure does not move."""

        center, other_center = self.center_of_mass, other.center_of_mass
        self.translate(-center[0], -center[1], -center[2])
        atoms, other_atoms = zip(*self.pairing_with(other).items())
        P = np.array([[*atom.location] for atom in atoms])
        Q = [(a.x - other_center[0], a.y - other_center[1],
              a.z - other_center[2]) for a in other_atoms]
        P = rmsd.kabsch_rotate(P, Q)
        for atom, row in zip(atoms, P):
            atom.move_to(*row)
        self.translate(other_center[0], other_center[1], other_center[2])
コード例 #8
0
def find_rotation_matrix(ax, ay, az, imu_ax, imu_ay, imu_az):
    print("Finding rotation matrix...")
    rx = 0
    ry = 0
    rz = 0

    diff_a = []
    imu_a = []

    # Kabsch algorithm setup
    for i in range(np.minimum(len(ax), len(imu_ax))):
        diff_a.append([ax[i] / 9.81, ay[i] / 9.81, az[i] / 9.81])
    for i in range(np.minimum(len(ax), len(imu_ax))):
        imu_a.append([imu_ax[i], imu_ay[i], imu_az[i]])

    diff_a = np.array(diff_a)
    imu_a = np.array(imu_a)

    print("Rotation matrix: ", rmsd.kabsch(diff_a, imu_a))
    print("RMSD: ", rmsd.kabsch_rmsd(diff_a, imu_a))
    # diff_a -= rmsd.centroid(diff_a)
    # imu_a -= rmsd.centroid(imu_a)
    # print("Rotation matrix after translation: ", rmsd.kabsch(diff_a, imu_a))
    # print("RMSD after translation: ", rmsd.kabsch_rmsd(diff_a, imu_a))

    rotated_a = rmsd.kabsch_rotate(diff_a, imu_a)
    r_ax = []
    r_ay = []
    r_az = []
    for i in range(len(rotated_a)):
        r_ax.append(rotated_a[i][0])
        r_ay.append(rotated_a[i][1])
        r_az.append(rotated_a[i][2])

    x_axis = np.array(range(len(r_ax)))
    plt.figure(5)
    plt.title("Rotated Differentiated Acceleration")
    plt.plot(x_axis, r_ax, label='x', color='red')
    plt.plot(x_axis, r_ay, label='y', color='green')
    plt.plot(x_axis, r_az, label='z', color='blue')
    plt.legend()
コード例 #9
0
def find_rotation_matrix(pos_data, IMU_data, filename):
    print("Finding rotation matrix...")
    rx = 0
    ry = 0
    rz = 0

    lshank_diff_a = []
    lshank_imu_a = []
    lthigh_diff_a = []
    lthigh_imu_a = []
    rshank_diff_a = []
    rshank_imu_a = []
    rthigh_diff_a = []
    rthigh_imu_a = []

    # Kabsch algorithm setup
    for i in range(len(pos_data[0])):
        lshank_diff_a.append([pos_data[0][i], pos_data[1][i], pos_data[2][i]])
        lthigh_diff_a.append([pos_data[3][i], pos_data[4][i], pos_data[5][i]])
        rshank_diff_a.append([pos_data[6][i], pos_data[7][i], pos_data[8][i]])
        rthigh_diff_a.append(
            [pos_data[9][i], pos_data[10][i], pos_data[11][i]])
    for i in range(len(IMU_data[0]) - 2):
        lshank_imu_a.append(
            [IMU_data[0][i], IMU_data[1][i], IMU_data[2][i] + 20])
        lthigh_imu_a.append(
            [IMU_data[3][i], IMU_data[4][i], IMU_data[5][i] + 20])
        rshank_imu_a.append(
            [IMU_data[6][i], IMU_data[7][i], IMU_data[8][i] + 20])
        rthigh_imu_a.append(
            [IMU_data[9][i], IMU_data[10][i], IMU_data[11][i] + 20])

    # diff_a = np.array(diff_a)
    # imu_a = np.array(imu_a)

    # lshank
    print("Rotation matrix for LShank: ",
          rmsd.kabsch(lshank_diff_a, lshank_imu_a))
    print("RMSD for LShank: ", rmsd.kabsch_rmsd(lshank_diff_a, lshank_imu_a))
    rotated_a = rmsd.kabsch_rotate(lshank_diff_a, lshank_imu_a)
    np.save(filename + "_LShank.npy", rotated_a)
    r_ax = []
    r_ay = []
    r_az = []
    for i in range(len(rotated_a)):
        r_ax.append(rotated_a[i][0])
        r_ay.append(rotated_a[i][1])
        r_az.append(rotated_a[i][2])

    x_axis = np.array(range(len(r_ax)))
    fig = plt.figure(5)
    ax = fig.add_subplot(313)
    ax.set_title("Rotated Differentiated Acceleration -- LShank")
    ax.plot(x_axis, r_ax, label='x', color='red')
    ax.plot(x_axis, r_ay, label='y', color='green')
    ax.plot(x_axis, r_az, label='z', color='blue')
    ax.legend()

    # lthigh
    print("Rotation matrix for LThigh: ",
          rmsd.kabsch(lthigh_diff_a, lthigh_imu_a))
    print("RMSD for LThigh: ", rmsd.kabsch_rmsd(lthigh_diff_a, lthigh_imu_a))
    rotated_a = rmsd.kabsch_rotate(lthigh_diff_a, lthigh_imu_a)
    np.save(filename + "_LThigh.npy", rotated_a)
    r_ax = []
    r_ay = []
    r_az = []
    for i in range(len(rotated_a)):
        r_ax.append(rotated_a[i][0])
        r_ay.append(rotated_a[i][1])
        r_az.append(rotated_a[i][2])

    x_axis = np.array(range(len(r_ax)))
    fig = plt.figure(6)
    ax = fig.add_subplot(313)
    ax.set_title("Rotated Differentiated Acceleration -- LThigh")
    ax.plot(x_axis, r_ax, label='x', color='red')
    ax.plot(x_axis, r_ay, label='y', color='green')
    ax.plot(x_axis, r_az, label='z', color='blue')
    ax.legend()

    # rshank
    print("Rotation matrix for RShank: ",
          rmsd.kabsch(rshank_diff_a, rshank_imu_a))
    print("RMSD for RShank: ", rmsd.kabsch_rmsd(rshank_diff_a, rshank_imu_a))
    rotated_a = rmsd.kabsch_rotate(rshank_diff_a, rshank_imu_a)
    np.save(filename + "_RShank.npy", rotated_a)
    r_ax = []
    r_ay = []
    r_az = []
    for i in range(len(rotated_a)):
        r_ax.append(rotated_a[i][0])
        r_ay.append(rotated_a[i][1])
        r_az.append(rotated_a[i][2])

    x_axis = np.array(range(len(r_ax)))
    fig = plt.figure(7)
    ax = fig.add_subplot(313)
    ax.set_title("Rotated Differentiated Acceleration -- RShank")
    ax.plot(x_axis, r_ax, label='x', color='red')
    ax.plot(x_axis, r_ay, label='y', color='green')
    ax.plot(x_axis, r_az, label='z', color='blue')
    ax.legend()

    # rthigh
    print("Rotation matrix for RThigh: ",
          rmsd.kabsch(rthigh_diff_a, rthigh_imu_a))
    print("RMSD for RThigh: ", rmsd.kabsch_rmsd(rthigh_diff_a, rthigh_imu_a))
    rotated_a = rmsd.kabsch_rotate(rthigh_diff_a, rthigh_imu_a)
    np.save(filename + "_RThigh.npy", rotated_a)
    r_ax = []
    r_ay = []
    r_az = []
    for i in range(len(rotated_a)):
        r_ax.append(rotated_a[i][0])
        r_ay.append(rotated_a[i][1])
        r_az.append(rotated_a[i][2])

    x_axis = np.array(range(len(r_ax)))
    fig = plt.figure(8)
    ax = fig.add_subplot(313)
    ax.set_title("Rotated Differentiated Acceleration -- RThigh")
    ax.plot(x_axis, r_ax, label='x', color='red')
    ax.plot(x_axis, r_ay, label='y', color='green')
    ax.plot(x_axis, r_az, label='z', color='blue')
    ax.legend()
コード例 #10
0
def plot_3D_comparison(batch_case,
                       network_tupla,
                       title,
                       savepath,
                       method="f0",
                       angle=30):
    best_index = batch_case[1].index(min(batch_case[1]))
    weight_list = np.asarray([a for a in batch_case[0]])
    best_weights = weight_list[best_index]
    original_coords = network_tupla[1]
    base_coords = nt.get_spectral_coordinates(nx.laplacian_matrix(
        network_tupla[0]).todense(),
                                              dim=3)
    if method == "f0":
        after_coords = nt.get_spectral_coordinates(
            nx.laplacian_matrix(network_tupla[0]).todense(),
            mod_matrix=nt.create_inverse_mod_matrix(best_weights),
            dim=3)
    elif method == "f1":
        after_coords = nt.get_spectral_coordinates(
            laplacian=nt.create_customized_laplacian(network_tupla[0],
                                                     best_weights),
            dim=3)
    elif method == "f2":
        after_coords = nt.get_spectral_coordinates(
            laplacian=nt.create_weighted_laplacian(network_tupla[0],
                                                   best_weights),
            dim=3)
    else:
        assert False
    base_coords = pd.DataFrame(rmsd.kabsch_rotate(base_coords.values,
                                                  original_coords.values),
                               columns=["x", "y", "z"])
    after_coords = pd.DataFrame(rmsd.kabsch_rotate(after_coords.values,
                                                   original_coords.values),
                                columns=["x", "y", "z"])
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(original_coords["x"],
               original_coords["y"],
               original_coords["z"],
               color='C0',
               marker='.',
               label="Originali")
    ax.scatter(base_coords["x"],
               base_coords["y"],
               base_coords["z"],
               color='C2',
               marker='x',
               label="SD base")
    ax.scatter(after_coords["x"],
               after_coords["y"],
               after_coords["z"],
               color='C1',
               marker='*',
               label="SD con modifica")
    ax.set_title("")
    ax.legend()
    ax.set_xlabel("$X$")
    ax.set_ylabel("$Y$")
    ax.set_zlabel("$Z$")
    ax.view_init(30, angle)
    plt.tight_layout()
    plt.savefig(savepath, dpi=DPI)
    plt.clf()
コード例 #11
0
def plot_protein_network(network,
                         distance_matrix,
                         threshold,
                         coords_original,
                         coords_modified=pd.DataFrame(),
                         spectral_basic=False,
                         title="",
                         savepath="",
                         showfig=True,
                         view_thet=30,
                         view_phi=30):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    # Make network to be plotted (low threshold)
    plt_network = make_network_from_distance_matrix(distance_matrix, threshold)
    # Plot original coords
    ax.scatter(coords_original["x"],
               coords_original["y"],
               coords_original["z"],
               label="Originale",
               c="C0")
    for edge in list(plt_network.edges):
        ax.plot((coords_original.iloc[edge[0]]["x"],
                 coords_original.iloc[edge[1]]["x"]),
                (coords_original.iloc[edge[0]]["y"],
                 coords_original.iloc[edge[1]]["y"]),
                (coords_original.iloc[edge[0]]["z"],
                 coords_original.iloc[edge[1]]["z"]),
                c="grey",
                alpha=0.7)
    # If any, plot given coords
    if not coords_modified.empty:
        print("given coords")
        # APPLY THE RMSD (you never know...)
        coords_modified = pd.DataFrame(rmsd.kabsch_rotate(
            coords_modified.values, coords_original.values),
                                       columns=["x", "y", "z"])
        score_modified = rmsd.kabsch_rmsd(coords_modified.values,
                                          coords_original.values)
        ax.scatter(coords_modified["x"],
                   coords_modified["y"],
                   coords_modified["z"],
                   label="SD Perturbato, RMSD = {:.6f}".format(score_modified),
                   c="C1")
        for edge in list(plt_network.edges):
            ax.plot((coords_modified.iloc[edge[0]]["x"],
                     coords_modified.iloc[edge[1]]["x"]),
                    (coords_modified.iloc[edge[0]]["y"],
                     coords_modified.iloc[edge[1]]["y"]),
                    (coords_modified.iloc[edge[0]]["z"],
                     coords_modified.iloc[edge[1]]["z"]),
                    c="red",
                    alpha=0.4)
    # Do you also want the spectral basic?
    if spectral_basic:
        print("spectral_basic")
        coords_basic = nt.get_spectral_coordinates(
            nx.laplacian_matrix(network).todense(),
            mod_matrix=np.diag([1 / a[1] for a in list(network.degree)]),
            dim=3)
        coords_basic = pd.DataFrame(rmsd.kabsch_rotate(coords_basic.values,
                                                       coords_original.values),
                                    columns=["x", "y", "z"])
        score_basic = rmsd.kabsch_rmsd(coords_basic.values,
                                       coords_original.values)
        ax.scatter(coords_basic["x"],
                   coords_basic["y"],
                   coords_basic["z"],
                   label="SD Originale, RMSD = {:.6f}".format(score_basic),
                   c="C2")
        for edge in list(plt_network.edges):
            ax.plot((coords_basic.iloc[edge[0]]["x"],
                     coords_basic.iloc[edge[1]]["x"]),
                    (coords_basic.iloc[edge[0]]["y"],
                     coords_basic.iloc[edge[1]]["y"]),
                    (coords_basic.iloc[edge[0]]["z"],
                     coords_basic.iloc[edge[1]]["z"]),
                    c="green",
                    alpha=0.4)
    ax.legend()
    ax.set_xlabel("X $[\\AA]$")
    ax.set_ylabel("Y $[\\AA]$")
    ax.set_zlabel("Z $[\\AA]$")
    if title != "":
        ax.set_title(title)
    if showfig:
        ax.view_init(view_thet, view_phi)
        plt.show()
    if savepath != "":
        ax.view_init(view_thet, view_phi)
        plt.savefig(savepath, dpi=300)
        plt.clf()
    fig.close()