#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 23 12:32:23 2025

@author: thosvarley
"""
from sys import exit
import os
import numpy as np
import matplotlib.pyplot as plt
import jpype as jp
from sklearn.decomposition import PCA
from scipy.spatial.distance import pdist, squareform
from scipy.stats import multivariate_normal, zscore
from ripser import ripser

# %%

# Library - jump to the end of this.

# Getting JVM Running
jarLocation = "/home/thosvarley/.local/share/JIDT/infodynamics.jar"
if not (os.path.isfile(jarLocation)):
    exit(
        "infodynamics.jar not found (expected at "
        + os.path.abspath(jarLocation)
        + ") - are you running from demos/python?"
    )

# Start the JVM (add the "-Xmx" option with say 1024M if you get crashes due to not enough memory space)
if (
    jp.isJVMStarted() == False
):  # jp.startJVM is stupid and won't naturally check if the JVM is running.
    jp.startJVM(jp.getDefaultJVMPath(), "-ea", "-Djava.class.path=" + jarLocation)

# %% FUNCTIONS


# Various useful functions.
def jidt_oinfo(data: np.ndarray) -> float:
    """
    Wrapper function for the Kraskov JIDT O-information.
    """
    oinfo_calc_class = jp.JPackage(
        "infodynamics.measures.continuous.kraskov"
    ).OInfoCalculatorKraskov
    oinfo_calc = oinfo_calc_class()

    oinfo_calc.initialise(data.shape[1])

    oinfo_calc.setProperty("k", "4")
    # oinfo_calc.setProperty("NORM_TYPE", "EUCLIDEAN") # Uncomment to change from default of the maximum  norm
    oinfo_calc.setProperty("NORMALISE", "false")

    oinfo_calc.setObservations(jp.JArray(jp.JDouble, 2)(data.tolist()))

    return oinfo_calc.computeAverageLocalOfObservations()


def jidt_mi(X: np.ndarray, Y: np.ndarray) -> float:
    """
    Wrapper function for the Kraskov JIDT MI
    """
    mi_calc_class = jp.JPackage(
        "infodynamics.measures.continuous.kraskov"
    ).MutualInfoCalculatorMultiVariateKraskov1
    mi_calc = mi_calc_class()
    # 2. Set any properties to non-default values:
    mi_calc.setProperty("NORMALISE", "false")
    mi_calc.setProperty("k", "4")
    # 3. Initialise the calculator for (re-)use:
    mi_calc.initialise()
    # 4. Supply the sample data:
    mi_calc.setObservations(X, Y)
    # 5. Compute the estimate:
    return mi_calc.computeAverageLocalOfObservations()


def jidt_total_correlation(data: np.ndarray) -> float:

    tc_calc_class = jp.JPackage(
        "infodynamics.measures.continuous.kraskov"
    ).MultiInfoCalculatorKraskov1
    tc_calc = tc_calc_class()
    tc_calc.initialise(data.shape[1])

    tc_calc.setProperty("k", "4")
    # oinfo_calc.setProperty("NORM_TYPE", "EUCLIDEAN") # Uncomment to change from default of the maximum  norm
    tc_calc.setProperty("NORMALISE", "false")
    tc_calc.setObservations(jp.JArray(jp.JDouble, 2)(data.tolist()))

    return tc_calc.computeAverageLocalOfObservations()


def jidt_dual_total_correlation(data: np.ndarray) -> float:

    tc_calc_class = jp.JPackage(
        "infodynamics.measures.continuous.kraskov"
    ).DualTotalCorrelationCalculatorKraskov
    tc_calc = tc_calc_class()
    tc_calc.initialise(data.shape[1])

    tc_calc.setProperty("k", "4")
    # oinfo_calc.setProperty("NORM_TYPE", "EUCLIDEAN") # Uncomment to change from default of the maximum  norm
    tc_calc.setProperty("NORMALISE", "false")
    tc_calc.setObservations(jp.JArray(jp.JDouble, 2)(data.tolist()))

    return tc_calc.computeAverageLocalOfObservations()


def point_cloud_distance(data: np.ndarray) -> np.ndarray:
    """
    Gets the Euclidean distance from the origin.
    Useful for constructing the sphere.
    """
    return np.sqrt((data**2).sum(axis=-1))


def rotate_point_cloud(point_cloud: np.ndarray, angles: tuple) -> np.ndarray:
    """
    Rotates a 3D point cloud around the X, Y, Z axes.
    Angles is a 3-tuple given the (yaw, pitch, roll).
    """
    alpha, beta, gamma = angles

    alpha = np.radians(alpha)
    beta = np.radians(beta)
    gamma = np.radians(gamma)

    yaw = np.array(
        [
            [np.cos(alpha), -np.sin(alpha), 0],
            [np.sin(alpha), np.cos(alpha), 0],
            [0, 0, 1],
        ]
    )

    pitch = np.array(
        [[np.cos(beta), 0, np.sin(beta)], [0, 1, 0], [-np.sin(beta), 0, np.cos(beta)]]
    )

    roll = np.array(
        [
            [1, 0, 0],
            [0, np.cos(gamma), -np.sin(gamma)],
            [0, np.sin(gamma), np.cos(gamma)],
        ]
    )

    rotation_matrix = yaw @ pitch @ roll

    return point_cloud @ rotation_matrix


# %% INITIALIZE PCA

pca = PCA()

# %% ONE-DIMENSIONAL LINE

one_d_line = np.linspace(start=-1, stop=1, num=10_000)
one_d_line = np.vstack(
    (one_d_line, one_d_line, one_d_line)  # All dimensions are copies of each-other.
).T
one_d_line = one_d_line  # + (np.random.randn(10_000,3) / 25) # Low variance noise.
oinfo_line = jidt_oinfo(one_d_line)

one_d_line_pc = pca.fit_transform(one_d_line)
oinfo_line_pc = jidt_oinfo(one_d_line_pc)

# %% THREE-DIMENSIONAL SPHERE

sphere = np.random.randn(10_000, 3)
norm = point_cloud_distance(sphere)
sphere = sphere / norm[:, None]  # + (np.random.randn(10_000,3) / 25)

oinfo_sphere = jidt_oinfo(sphere)
sphere_pc = pca.fit_transform(sphere)

oinfo_sphere_pc = jidt_oinfo(sphere_pc)

# %% TWO-DIMENSIONAL PLANE

two_d_plane = np.random.uniform(low=-1, high=1, size=(10_000, 2))
noise = np.zeros(10_000)  # noise = np.random.randn(10_000) / 25
two_d_plane = np.vstack((two_d_plane.T, noise)).T
two_d_plane = rotate_point_cloud(two_d_plane, angles=(45, 45, 45))

two_d_plane_pc = pca.fit_transform(two_d_plane)

oinfo_plane = jidt_oinfo(two_d_plane)
oinfo_plane_pc = abs(jidt_oinfo(two_d_plane_pc))

# %% TREFOIL

# Create a figure and 3D axes
# Generate the trefoil knot coordinates
t = np.random.rand(10_000) * 2 * np.pi  # np.linspace(0, 2 * np.pi, 10_000)
x = np.sin(t) + 2 * np.sin(2 * t)
y = np.cos(t) - 2 * np.cos(2 * t)
z = -np.sin(3 * t)

trefoil = np.vstack((x, y, z)).T
# trefoil += np.random.randn(10_000,3) / 100

# Adding a random rotation to the trefoil
trefoil = rotate_point_cloud(trefoil, (45, 45, 45))

oinfo_trefoil = jidt_oinfo(trefoil)

trefoil_pc = pca.fit_transform(trefoil)

oinfo_trefoil_pc = jidt_oinfo(trefoil_pc)

# %% P,Q-KNOT

p, q = (3, 5)

t = np.random.uniform(0, 2 * np.pi, 10_000)  # np.linspace(0, 2 * np.pi, 10_000)
x = (2 + np.cos(q * t)) * np.cos(p * t)
y = (2 + np.cos(q * t)) * np.sin(p * t)
z = np.sin(q * t)

knot = np.vstack((x, y, z)).T

knot = rotate_point_cloud(knot, (45, 45, 45))

oinfo_knot = jidt_oinfo(knot)

knot_pc = pca.fit_transform(knot)
oinfo_knot_pc = jidt_oinfo(knot_pc)

# %% TORUS

theta = np.random.uniform(0, 2 * np.pi, 10_000)
phi = np.random.uniform(0, 2 * np.pi, 10_000)

r = 0.5
R = 1

x = (R + r * np.cos(phi)) * np.cos(theta)
y = (R + r * np.cos(phi)) * np.sin(theta)
z = r * np.sin(phi)

torus = np.vstack((x, y, z)).T
torus = rotate_point_cloud(torus, (45, 45, 45))

oinfo_torus = jidt_oinfo(torus)

torus_pc = pca.fit_transform(torus)
oinfo_torus_pc = jidt_oinfo(torus_pc)

# %% MULTI-PANEL FIGURE

shapes = [
    one_d_line,
    one_d_line_pc,
    two_d_plane,
    two_d_plane_pc,
    sphere,
    sphere_pc,
    torus,
    torus_pc,
    trefoil,
    trefoil_pc,
    knot,
    knot_pc,
]

titles = [
    round(oinfo_line, 3),
    round(oinfo_line_pc, 3),
    round(oinfo_plane, 3),
    round(oinfo_plane_pc, 3),
    round(oinfo_sphere, 3),
    round(oinfo_sphere_pc, 3),
    round(oinfo_torus, 3),
    round(oinfo_torus_pc, 3),
    round(oinfo_trefoil, 3),
    round(oinfo_trefoil_pc, 3),
    round(oinfo_knot, 3),
    round(oinfo_knot_pc, 3),
]

fig = plt.figure(dpi=300, figsize=(10, 10))

s = 0.1
alpha = 0.5
for i in range(1, 13):

    ax = fig.add_subplot(3, 4, i, projection="3d")
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.set_zticklabels([])

    ax.set_xlabel(r"$X_1$", labelpad=-15)
    ax.set_ylabel(r"$X_2$", labelpad=-15)
    ax.set_zlabel(r"$X_3$", labelpad=-15)

    shape = shapes[i - 1]

    ax.scatter(shape[:, 0], shape[:, 1], shape[:, 2], s=s, alpha=alpha)

    if i > 8:
        ax.set_xlim([-3, 3])
        ax.set_ylim([-3, 3])
        ax.set_zlim([-3, 3])
    else:
        ax.set_xlim([-1, 1])
        ax.set_ylim([-1, 1])
        ax.set_zlim([-1, 1])

    if i % 2 == 1:
        subtitle = r"Rot. $(45^{\circ}, 45^{\circ}, 45^{\circ})$"
    else:
        subtitle = "Post-PCA"

    ax.set_title(
        r"$\mathcal{O}\approx$" + "{0} nat\n{1}".format(titles[i - 1], subtitle)
    )

fig.tight_layout()
fig.savefig("3d_figures.png", bbox_inches="tight")
