#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 23 18:52:52 2024

@author: tvarley
"""

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 23 14:18:38 2024

@author: tvarley
"""

import os
import sys

import numpy as np
import pandas as pd
import jpype as jp

from itertools import combinations
from random import shuffle

# %%

# Getting JVM Running
jarLocation = "/users/t/f/tfvarley/.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)


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_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()


# %%
in_dir = "/gpfs1/home/t/f/tfvarley/Code/kraskov_o/data/"

argv = int(sys.argv[1])

single_scan = False 
if single_scan == True:
    files = [
        "123925_bold_s1.npz"
    ]  # , "123925_bold_s2.npz", "123925_bold_s3.npz", "123925_bold_s0.npz"]
else:
    files = [
        "123925_bold_s1.npz",
        "123925_bold_s2.npz",
        "123925_bold_s3.npz",
        "123925_bold_s0.npz",
    ]

data = np.hstack([np.load(in_dir + file)["arr_0"] for file in files])

idxs = list(combinations(range(200), 3))
shuffle(idxs)

nulls = np.zeros(10_000)
counter = 0


# %%
for i in range(argv * 10_000, (argv + 1) * 10_000):

    if i < len(idxs):

        idx = idxs[i]

        data_null = data[idx, :]
        data_null[1] = np.roll(data_null[1], 1100)
        data_null[2] = np.roll(data_null[2], 2200)

        if single_scan == True:
            data_null = data_null[:, :1100]

        nulls[counter] = jidt_oinfo(data_null.T)

    counter += 1

# %%
if single_scan == True:
    out_dir = "/gpfs1/home/t/f/tfvarley/Code/kraskov_o/scripts/triads_null_1/"
else:
    out_dir = "/gpfs1/home/t/f/tfvarley/Code/kraskov_o/scripts/triads_null_4/"

np.savez_compressed(out_dir + "triads_null_{0}.npz".format(str(argv).zfill(3)), nulls)
