<gh_stars>0
""" mds.py

Core math logic for MDS.

"""

import src.utils

import numpy as np
import numpy.linalg as linalg
import scipy.linalg


def coordinate_matrix(adj_arr: np.array, dims: int = 3) -> np.array:
    d_sq = np.square(adj_arr)
    n = adj_arr.shape[0]
    j = np.identity(n) - (1 / n) * np.ones((n, 1)).dot(np.ones((1, n)))
    b = -0.5 * j.dot(d_sq.dot(j))
    eigvals, eigvecs = linalg.eig(b)
    sort_order = eigvals.argsort()[::-1]
    eigvals = eigvals[sort_order][:dims]
    eigvecs = eigvecs[:, sort_order][:, :dims]

    return eigvecs.dot(scipy.linalg.sqrtm(np.diag(eigvals)))


if __name__ == "__main__":
    tetrahedron = np.array([[0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 0, 1], [1, 1, 1, 0]])
    coords = coordinate_matrix(tetrahedron, dims=3)

    import json
    import os

    import jinja2

    tmpl = jinja2.Environment(
        loader=jinja2.FileSystemLoader(os.getenv("PYTHONPATH"))
    ).get_template("src/templates/scatter3d.html")
    print(tmpl.render(data=json.dumps(coords.tolist())))

    # print(json.dumps(coords.tolist(), indent=4))
    # import matplotlib.pyplot as plt

    # plt.scatter(coords[:, 0], coords[:, 1])
    # plt.show()


""" mds.py

Core math logic for MDS.

"""

import src.utils

import numpy as np
import numpy.linalg as linalg
import scipy.linalg


def coordinate_matrix(adj_arr: np.array, dims: int = 3) -> np.array:
    d_sq = np.square(adj_arr)
    n = adj_arr.shape[0]
    j = np.identity(n) - (1 / n) * np.ones((n, 1)).dot(np.ones((1, n)))
    b = -0.5 * j.dot(d_sq.dot(j))
    eigvals, eigvecs = linalg.eig(b)
    sort_order = eigvals.argsort()[::-1]
    eigvals = eigvals[sort_order][:dims]
    eigvecs = eigvecs[:, sort_order][:, :dims]

    return eigvecs.dot(scipy.linalg.sqrtm(np.diag(eigvals)))


if __name__ == "__main__":
    tetrahedron = np.array([[0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 0, 1], [1, 1, 1, 0]])
    coords = coordinate_matrix(tetrahedron, dims=3)

    import json
    import os

    import jinja2

    tmpl = jinja2.Environment(
        loader=jinja2.FileSystemLoader(os.getenv("PYTHONPATH"))
    ).get_template("src/templates/scatter3d.html")
    print(tmpl.render(data=json.dumps(coords.tolist())))

    # print(json.dumps(coords.tolist(), indent=4))
    # import matplotlib.pyplot as plt

    # plt.scatter(coords[:, 0], coords[:, 1])
    # plt.show()
mds.py  Core math logic for MDS. # print(json.dumps(coords.tolist(), indent=4)) # import matplotlib.pyplot as plt # plt.scatter(coords[:, 0], coords[:, 1]) # plt.show()