""" Utilities for learning pipeline."""
from __future__ import print_function
import copy
import dill
import hashlib
import itertools
import third_party.deep_bingham.bingham_distribution as ms
import math
import numpy as np
import os
import scipy
import scipy.integrate as integrate
import scipy.special
import sys
import torch

from pathos.multiprocessing import ProcessingPool as Pool
from pathos.multiprocessing import cpu_count

def convert_euler_to_quaternion(roll, yaw, pitch):
    """Converts roll, yaw, pitch to a quaternion.
    """

    # roll (z), yaw (y), pitch (x)

    cy = math.cos(math.radians(roll) * 0.5)
    sy = math.sin(math.radians(roll) * 0.5)

    cp = math.cos(math.radians(yaw) * 0.5)
    sp = math.sin(math.radians(yaw) * 0.5)

    cr = math.cos(math.radians(pitch) * 0.5)
    sr = math.sin(math.radians(pitch) * 0.5)

    w = cy * cp * cr + sy * sp * sr
    x = cy * cp * sr - sy * sp * cr
    y = sy * cp * sr + cy * sp * cr
    z = sy * cp * cr - cy * sp * sr

    quat = np.array([w, x, y, z])
    quat = quat / np.linalg.norm(quat)
    return quat


def radians(degree_tensor):
    """
    Method to convert a torch tensor of angles in degree format to radians.

    Arguments:
        degree_tensor (torch.Tensor): Tensor consisting of angles in degree format.
    
    Returns:
        radian_tensor (torch.Tensor): Tensor consisting of angles in radian format.
    """
    radian_tensor = degree_tensor/180 * math.pi
    return radian_tensor


def generate_coordinates(coords):
    """
    A function that returns all  possible triples of coords

    Parameters:
    coords: a numpy array of coordinates

    Returns:
    x: the first  coordinate of possible triples
    y: the second coordinate of possible triples
    z  the third coordinate of possible triples
    """
    x = coords.reshape(-1, 1).repeat(1, len(coords) * len(coords)).flatten()
    y = coords.reshape(-1, 1).repeat(1, len(coords)).flatten().repeat(len(coords))
    z = coords.reshape(-1, 1).flatten().repeat(len(coords)*len(coords))

    return x, y, z


def ensure_dir_exists(path):
    """ Checks if a directory exists and creates it otherwise. """
    if not os.path.exists(path):
        os.makedirs(path)


def load_lookup_table(path):
    """
    Loads lookup table from dill serialized file.

    Returns a table specific tuple. For the Bingham case, the tuple containins:
        table_type (str):
        options (dict): The options used to generate the lookup table.
        res_tensor (numpy.ndarray): The actual lookup table data.
        coords (numpy.ndarray): Coordinates at which lookup table was evaluated.

    For the von Mises case, it contains:
        options (dict): The options used to generate the lookup table.
        res_tensor (numpy.ndarray): The actual lookup table data.
    """
    assert os.path.exists(path), "Lookup table file not found."
    with open(path, "rb") as dillfile:
        return dill.load(dillfile)


def eaad_von_mises(kappas, integral_options=None):
    """ Expected Absolute Angular Deviation of Bingham Random Vector

    Arguments:
        kappas: Von Mises kappa parameters for roll, pitch, yaw.
        integral_options: Options to pass on to the scipy integrator for
            computing the eaad and the bingham normalization constant.
    """
    def aad(quat_a, quat_b):
        acos_val = np.arccos(np.abs(np.dot(quat_a, quat_b)))
        diff_ang = 2.0 * acos_val
        return diff_ang

    if integral_options is None:
        integral_options = {"epsrel": 1e-2, "epsabs": 1e-2}

    param_mu = np.array([0., 0., 0.])  # radians
    quat_mu = convert_euler_to_quaternion(
        math.degrees(param_mu[0]), math.degrees(param_mu[1]),
        math.degrees(param_mu[2])
    )
    param_kappa = kappas

    direct_norm_const = 8.0 * (np.pi ** 3) \
        * scipy.special.iv(0, param_kappa[0]) \
        * scipy.special.iv(0, param_kappa[1]) \
        * scipy.special.iv(0, param_kappa[2])

    def integrand_aad(phi1, phi2, phi3):
        return np.exp(param_kappa[0] * np.cos(phi1)) \
               * np.exp(param_kappa[1] * np.cos(phi2)) \
               * np.exp(param_kappa[2] * np.cos(phi3)) \
               * aad(quat_mu,
                     convert_euler_to_quaternion(
                         math.degrees(phi1), math.degrees(phi2),
                         math.degrees(phi3)
                     ))

    eaad_int = integrate.tplquad(
        integrand_aad,
        0.0, 2.0 * np.pi,  # phi3
        lambda x: 0.0, lambda x:  2. * np.pi,  # phi2
        lambda x, y: 0.0, lambda x, y: 2. * np.pi,  # phi1
        **integral_options
    )

    return eaad_int[0]/direct_norm_const


def eaad_bingham(bingham_z, integral_options=None):
    """ Expected Absolute Angular Deviation of Bingham Random Vector

    Arguments:
        bingham_z: Bingham dispersion parameter in the format expected by the
            manstats BinghamDistribution class.
        integral_options: Options to pass on to the scipy integrator for
            computing the eaad and the bingham normalization constant.
    """

    def aad(quat_a, quat_b):
        # acos_val = np.arccos(np.dot(quat_a, quat_b))
        # diff_ang = 2 * np.min([acos_val, np.pi - acos_val])
        acos_val = np.arccos(np.abs(np.dot(quat_a, quat_b)))
        diff_ang = 2 * acos_val
        return diff_ang

    if integral_options is None:
        integral_options = {"epsrel": 1e-4, "epsabs": 1e-4}

    bd = ms.BinghamDistribution(
        np.eye(4), bingham_z,
        {"norm_const_mode": "numerical",
         "norm_const_options": integral_options}
    )

    def integrand_transformed(x):
        # To avoid unnecessary divisions, this term does not contain the
        # normalization constant. At the end, the result of the integration is
        # divided by it.
        return aad(x, bd.mode) \
               * np.exp(np.dot(x, np.dot(np.diag(bingham_z), x)))

    def integrand(phi1, phi2, phi3):
        sp1 = np.sin(phi1)
        sp2 = np.sin(phi2)
        return integrand_transformed(np.array([
            sp1 * sp2 * np.sin(phi3),
            sp1 * sp2 * np.cos(phi3),
            sp1 * np.cos(phi2),
            np.cos(phi1)
        ])) * (sp1 ** 2.) * sp2

    eaad_int = integrate.tplquad(
        integrand,
        0.0, 2.0 * np.pi,  # phi3
        lambda x: 0.0, lambda x: np.pi,  # phi2
        lambda x, y: 0.0, lambda x, y: np.pi,  # phi1
        **integral_options
    )

    return eaad_int[0] / bd.norm_const


def build_bd_lookup_table(table_type, options, path=None):
    """
    Builds a lookup table for interpolating the bingham normalization
    constant.  If a lookup table with the given options already exists, it is
    loaded and returned instead of building a new one.

    Arguments:
        table_type: Type of lookup table used. May be 'uniform' or 'nonuniform'
        options: Dict cotaining type specific options.
            If type is "uniform" this dict must contain:
                "bounds" = Tuple (lower_bound, upper_bound) representing bounds.
                "num_points" = Number of points per dimension.
            If type is "nonuniform" this dict must contain a key "coords" which
            is a numpy arrays representing the coordinates at which the
            interpolation is evaluated.
        path: absolute path for the lookup table (optional). The default is to
            create a hash based on the options and to use this for constructing
            a file name and placing the file in the precomputed folder.
    """
    hash_obj = hashlib.sha256()
    hash_obj.update(table_type.encode('utf-8'))
    hash_obj.update(dill.dumps(options))
    config_hash = hash_obj.hexdigest()

    if not path:
        path = os.path.dirname(__file__) \
               + "/../precomputed/lookup_{}.dill".format(config_hash)

    # Load existing table or create new one.
    if os.path.exists(path):
        with open(path, "rb") as dillfile:
            (serialized_type, serialized_options, res_table, coords) \
                = dill.load(dillfile)
            hash_obj = hashlib.sha256()
            hash_obj.update(serialized_type)
            hash_obj.update(dill.dumps(serialized_options))
            file_config_hash = hash_obj.hexdigest()
            assert file_config_hash == config_hash, \
                "Serialized lookup table does not match given type & options."

    elif table_type == "uniform":
        # Number of points per axis.
        (lbound, rbound) = options["bounds"]
        num_points = options["num_points"]

        assert num_points > 1, \
            "Grid must have more than one point per dimension."

        nc_options = {"epsrel": 1e-3, "epsabs": 1e-7}

        coords = np.linspace(lbound, rbound, num_points)

        res_table = _compute_bd_lookup_table(coords, nc_options)

        with open(path, "wb") as dillfile:
            dill.dump((table_type, options, res_table, coords), dillfile)

    elif table_type == "nonuniform":
        nc_options = {"epsrel": 1e-3, "epsabs": 1e-7}

        coords = options["coords"]

        res_table = _compute_bd_lookup_table(coords, nc_options)

        with open(path, "wb") as dillfile:
            dill.dump((table_type, options, res_table, coords), dillfile)

    else:
        sys.exit("Unknown lookup table type")

    return res_table


def build_vm_lookup_table(options, path=None):
    """
    Builds a lookup table for interpolating the bingham normalization
    constant.  If a lookup table with the given options already exists, it is
    loaded and returned instead of building a new one.

    Arguments:
        options: Dict cotaining table options. It must contain a key "coords"
            which is a numpy arrays representing the coordinates at which the
            interpolation is evaluated.
        path: absolute path for the lookup table (optional). The default is to
            create a hash based on the options and to use this for constructing
            a file name and placing the file in the precomputed folder.
    """
    hash_obj = hashlib.sha256()
    hash_obj.update(dill.dumps(options))
    config_hash = hash_obj.hexdigest()

    if not path:
        path = os.path.dirname(__file__) \
            + "/../precomputed/lookup_{}.dill".format(config_hash)

    # Load existing table or create new one.
    if os.path.exists(path):
        with open(path, "rb") as dillfile:
            (serialized_options, res_table) \
                = dill.load(dillfile)
            hash_obj = hashlib.sha256()
            hash_obj.update(dill.dumps(serialized_options))
            file_config_hash = hash_obj.hexdigest()
            assert file_config_hash == config_hash, \
                "Serialized lookup table does not match given type & options."

    else:
        coords = options["coords"]
        res_table = _compute_vm_lookup_table(coords)

        with open(path, "wb") as dillfile:
            dill.dump((options, res_table), dillfile)

    return res_table


def _compute_bd_lookup_table(coords, nc_options):
    num_points = len(coords)
    
    pool = Pool(max(cpu_count()//2, 1))

    def nc_wrapper(idx):
        pt_idx = point_indices[idx]

        # Indexing pt_idx in the order 2,1,0 vs. 0,1,2 has no impact
        # on the result as the Bingham normalization constant is agnostic to it.
        # However, the numpy integration that is used to compute it, combines
        # numerical 2d and 1d integration which is why the order matters for the
        # actual computation time.
        #
        # TODO: Make pymanstats choose best order automatically.
        norm_const = ms.BinghamDistribution.normalization_constant(
            np.array(
                [coords[pt_idx[2]], coords[pt_idx[1]], coords[pt_idx[0]], 0.]),
            "numerical", nc_options)
        print("Computing NC for Z=[{}, {}, {}, 0.0]: {}".format(
            coords[pt_idx[2]], coords[pt_idx[1]], coords[pt_idx[0]],
            norm_const))
        return norm_const

    point_indices = list(itertools.combinations_with_replacement(
        range(0, num_points), 3))
    results = pool.map(nc_wrapper, range(len(point_indices)))

    res_tensor = -np.ones((num_points, num_points, num_points))
    for idx_pos, pt_idx in enumerate(point_indices):
        res_tensor[pt_idx[0], pt_idx[1], pt_idx[2]] = results[idx_pos]
        res_tensor[pt_idx[0], pt_idx[2], pt_idx[1]] = results[idx_pos]
        res_tensor[pt_idx[1], pt_idx[0], pt_idx[2]] = results[idx_pos]
        res_tensor[pt_idx[1], pt_idx[2], pt_idx[0]] = results[idx_pos]
        res_tensor[pt_idx[2], pt_idx[0], pt_idx[1]] = results[idx_pos]
        res_tensor[pt_idx[2], pt_idx[1], pt_idx[0]] = results[idx_pos]

    return res_tensor


class AverageMeter(object):
    """Computes and stores the averages over a numbers or dicts of numbers.

    For the dict, this class assumes that no new keys are added during
    the computation.
    """

    def __init__(self):
        self.last_val = 0
        self.avg = 0 
        self.count = 0 

    def update(self, val, n=1):
        self.last_val = val
        n = float(n)
        if type(val) == dict:
            if self.count == 0:
                self.avg = copy.deepcopy(val)
            else:
                for key in val:
                    self.avg[key] *= self.count / (self.count + n)
                    self.avg[key] += val[key] * n / (self.count + n)
        else:
            self.avg *= self.count / (self.count + n)
            self.avg += val * n / (self.count + n)

        self.count += n
        self.last_val = val


def _compute_vm_lookup_table(coords):
    num_points = len(coords)

    pool = Pool()

    def nc_wrapper(idx):
        cur_pt_idx = point_indices[idx]

        log_norm_const = np.log(8.0) + (3. * np.log(np.pi)) \
            + np.log(scipy.special.iv(0, coords[cur_pt_idx[0]])) \
            + np.log(scipy.special.iv(0, coords[cur_pt_idx[1]])) \
            + np.log(scipy.special.iv(0, coords[cur_pt_idx[2]]))

        print("Computing NC for kappas=[{}, {}, {}]: {}".format(
            coords[cur_pt_idx[2]], coords[cur_pt_idx[1]], coords[cur_pt_idx[0]],
            log_norm_const))
        return log_norm_const

    point_indices = list(itertools.combinations_with_replacement(
        range(0, num_points), 3))
    results = pool.map(nc_wrapper, range(len(point_indices)))

    res_tensor = -np.ones((num_points, num_points, num_points))
    for idx_pos, pt_idx in enumerate(point_indices):
        res_tensor[pt_idx[0], pt_idx[1], pt_idx[2]] = results[idx_pos]
        res_tensor[pt_idx[0], pt_idx[2], pt_idx[1]] = results[idx_pos]
        res_tensor[pt_idx[1], pt_idx[0], pt_idx[2]] = results[idx_pos]
        res_tensor[pt_idx[1], pt_idx[2], pt_idx[0]] = results[idx_pos]
        res_tensor[pt_idx[2], pt_idx[0], pt_idx[1]] = results[idx_pos]
        res_tensor[pt_idx[2], pt_idx[1], pt_idx[0]] = results[idx_pos]

    return res_tensor


def vec_to_bingham_z_many(y):
    z = -torch.exp(y).cumsum(1)[:, [2, 1, 0]].unsqueeze(0)
    return z 


def vec_to_bingham_z(y):
    z = -torch.exp(y).cumsum(0)[[2, 1, 0]].unsqueeze(0)
    if not all(z[0][:-1] <= z[0][1:]):
        print(z)
    return z

[((40, 11, 40, 33), 'numpy.array', 'np.array', ({(40, 20, 40, 32): '[w, x, y, z]'}, {}), '([w, x, y, z])', True, 'import numpy as np\n'), ((98, 11, 98, 31), 'os.path.exists', 'os.path.exists', ({(98, 26, 98, 30): 'path'}, {}), '(path)', False, 'import os\n'), ((119, 15, 119, 37), 'numpy.array', 'np.array', ({(119, 24, 119, 36): '[0.0, 0.0, 0.0]'}, {}), '([0.0, 0.0, 0.0])', True, 'import numpy as np\n'), ((141, 15, 147, 5), 'scipy.integrate.tplquad', 'integrate.tplquad', ({(142, 8, 142, 21): 'integrand_aad', (143, 8, 143, 11): '0.0', (143, 13, 143, 24): '2.0 * np.pi', (144, 8, 144, 21): 'lambda x: 0.0', (144, 23, 144, 44): 'lambda x: 2.0 * np.pi', (145, 8, 145, 24): 'lambda x, y: 0.0', (145, 26, 145, 49): 'lambda x, y: 2.0 * np.pi'}, {}), '(integrand_aad, 0.0, 2.0 * np.pi, lambda x: 0.0, lambda x:\n    2.0 * np.pi, lambda x, y: 0.0, lambda x, y: 2.0 * np.pi, **integral_options\n    )', True, 'import scipy.integrate as integrate\n'), ((195, 15, 201, 5), 'scipy.integrate.tplquad', 'integrate.tplquad', ({(196, 8, 196, 17): 'integrand', (197, 8, 197, 11): '0.0', (197, 13, 197, 24): '2.0 * np.pi', (198, 8, 198, 21): 'lambda x: 0.0', (198, 23, 198, 38): 'lambda x: np.pi', (199, 8, 199, 24): 'lambda x, y: 0.0', (199, 26, 199, 44): 'lambda x, y: np.pi'}, {}), '(integrand, 0.0, 2.0 * np.pi, lambda x: 0.0, lambda x: np.\n    pi, lambda x, y: 0.0, lambda x, y: np.pi, **integral_options)', True, 'import scipy.integrate as integrate\n'), ((225, 15, 225, 31), 'hashlib.sha256', 'hashlib.sha256', ({}, {}), '()', False, 'import hashlib\n'), ((235, 7, 235, 27), 'os.path.exists', 'os.path.exists', ({(235, 22, 235, 26): 'path'}, {}), '(path)', False, 'import os\n'), ((293, 15, 293, 31), 'hashlib.sha256', 'hashlib.sha256', ({}, {}), '()', False, 'import hashlib\n'), ((302, 7, 302, 27), 'os.path.exists', 'os.path.exists', ({(302, 22, 302, 26): 'path'}, {}), '(path)', False, 'import os\n'), ((395, 11, 395, 17), 'pathos.multiprocessing.ProcessingPool', 'Pool', ({}, {}), '()', True, 'from pathos.multiprocessing import ProcessingPool as Pool\n'), ((41, 18, 41, 38), 'numpy.linalg.norm', 'np.linalg.norm', ({(41, 33, 41, 37): 'quat'}, {}), '(quat)', True, 'import numpy as np\n'), ((80, 11, 80, 31), 'os.path.exists', 'os.path.exists', ({(80, 26, 80, 30): 'path'}, {}), '(path)', False, 'import os\n'), ((81, 8, 81, 25), 'os.makedirs', 'os.makedirs', ({(81, 20, 81, 24): 'path'}, {}), '(path)', False, 'import os\n'), ((100, 15, 100, 34), 'dill.load', 'dill.load', ({(100, 25, 100, 33): 'dillfile'}, {}), '(dillfile)', False, 'import dill\n'), ((121, 8, 121, 33), 'math.degrees', 'math.degrees', ({(121, 21, 121, 32): 'param_mu[0]'}, {}), '(param_mu[0])', False, 'import math\n'), ((121, 35, 121, 60), 'math.degrees', 'math.degrees', ({(121, 48, 121, 59): 'param_mu[1]'}, {}), '(param_mu[1])', False, 'import math\n'), ((122, 8, 122, 33), 'math.degrees', 'math.degrees', ({(122, 21, 122, 32): 'param_mu[2]'}, {}), '(param_mu[2])', False, 'import math\n'), ((129, 10, 129, 45), 'scipy.special.iv', 'scipy.special.iv', ({(129, 27, 129, 28): '(0)', (129, 30, 129, 44): 'param_kappa[2]'}, {}), '(0, param_kappa[2])', False, 'import scipy\n'), ((173, 8, 173, 17), 'numpy.eye', 'np.eye', ({(173, 15, 173, 16): '4'}, {}), '(4)', True, 'import numpy as np\n'), ((186, 14, 186, 26), 'numpy.sin', 'np.sin', ({(186, 21, 186, 25): 'phi1'}, {}), '(phi1)', True, 'import numpy as np\n'), ((187, 14, 187, 26), 'numpy.sin', 'np.sin', ({(187, 21, 187, 25): 'phi2'}, {}), '(phi2)', True, 'import numpy as np\n'), ((227, 20, 227, 39), 'dill.dumps', 'dill.dumps', ({(227, 31, 227, 38): 'options'}, {}), '(options)', False, 'import dill\n'), ((294, 20, 294, 39), 'dill.dumps', 'dill.dumps', ({(294, 31, 294, 38): 'options'}, {}), '(options)', False, 'import dill\n'), ((350, 18, 350, 63), 'numpy.ones', 'np.ones', ({(350, 26, 350, 62): '(num_points, num_points, num_points)'}, {}), '((num_points, num_points, num_points))', True, 'import numpy as np\n'), ((414, 18, 414, 63), 'numpy.ones', 'np.ones', ({(414, 26, 414, 62): '(num_points, num_points, num_points)'}, {}), '((num_points, num_points, num_points))', True, 'import numpy as np\n'), ((26, 18, 26, 36), 'math.radians', 'math.radians', ({(26, 31, 26, 35): 'roll'}, {}), '(roll)', False, 'import math\n'), ((27, 18, 27, 36), 'math.radians', 'math.radians', ({(27, 31, 27, 35): 'roll'}, {}), '(roll)', False, 'import math\n'), ((29, 18, 29, 35), 'math.radians', 'math.radians', ({(29, 31, 29, 34): 'yaw'}, {}), '(yaw)', False, 'import math\n'), ((30, 18, 30, 35), 'math.radians', 'math.radians', ({(30, 31, 30, 34): 'yaw'}, {}), '(yaw)', False, 'import math\n'), ((32, 18, 32, 37), 'math.radians', 'math.radians', ({(32, 31, 32, 36): 'pitch'}, {}), '(pitch)', False, 'import math\n'), ((33, 18, 33, 37), 'math.radians', 'math.radians', ({(33, 31, 33, 36): 'pitch'}, {}), '(pitch)', False, 'import math\n'), ((128, 10, 128, 45), 'scipy.special.iv', 'scipy.special.iv', ({(128, 27, 128, 28): '(0)', (128, 30, 128, 44): 'param_kappa[1]'}, {}), '(0, param_kappa[1])', False, 'import scipy\n'), ((231, 15, 231, 40), 'os.path.dirname', 'os.path.dirname', ({(231, 31, 231, 39): '__file__'}, {}), '(__file__)', False, 'import os\n'), ((238, 18, 238, 37), 'dill.load', 'dill.load', ({(238, 28, 238, 36): 'dillfile'}, {}), '(dillfile)', False, 'import dill\n'), ((239, 23, 239, 39), 'hashlib.sha256', 'hashlib.sha256', ({}, {}), '()', False, 'import hashlib\n'), ((256, 17, 256, 56), 'numpy.linspace', 'np.linspace', ({(256, 29, 256, 35): 'lbound', (256, 37, 256, 43): 'rbound', (256, 45, 256, 55): 'num_points'}, {}), '(lbound, rbound, num_points)', True, 'import numpy as np\n'), ((298, 15, 298, 40), 'os.path.dirname', 'os.path.dirname', ({(298, 31, 298, 39): '__file__'}, {}), '(__file__)', False, 'import os\n'), ((305, 18, 305, 37), 'dill.load', 'dill.load', ({(305, 28, 305, 36): 'dillfile'}, {}), '(dillfile)', False, 'import dill\n'), ((306, 23, 306, 39), 'hashlib.sha256', 'hashlib.sha256', ({}, {}), '()', False, 'import hashlib\n'), ((317, 12, 317, 53), 'dill.dump', 'dill.dump', ({(317, 22, 317, 42): '(options, res_table)', (317, 44, 317, 52): 'dillfile'}, {}), '((options, res_table), dillfile)', False, 'import dill\n'), ((338, 12, 339, 78), 'numpy.array', 'np.array', ({(339, 16, 339, 77): '[coords[pt_idx[2]], coords[pt_idx[1]], coords[pt_idx[0]], 0.0]'}, {}), '([coords[pt_idx[2]], coords[pt_idx[1]], coords[pt_idx[0]], 0.0])', True, 'import numpy as np\n'), ((112, 36, 112, 58), 'numpy.dot', 'np.dot', ({(112, 43, 112, 49): 'quat_a', (112, 51, 112, 57): 'quat_b'}, {}), '(quat_a, quat_b)', True, 'import numpy as np\n'), ((127, 10, 127, 45), 'scipy.special.iv', 'scipy.special.iv', ({(127, 27, 127, 28): '(0)', (127, 30, 127, 44): 'param_kappa[0]'}, {}), '(0, param_kappa[0])', False, 'import scipy\n'), ((165, 36, 165, 58), 'numpy.dot', 'np.dot', ({(165, 43, 165, 49): 'quat_a', (165, 51, 165, 57): 'quat_b'}, {}), '(quat_a, quat_b)', True, 'import numpy as np\n'), ((241, 28, 241, 58), 'dill.dumps', 'dill.dumps', ({(241, 39, 241, 57): 'serialized_options'}, {}), '(serialized_options)', False, 'import dill\n'), ((261, 12, 261, 73), 'dill.dump', 'dill.dump', ({(261, 22, 261, 62): '(table_type, options, res_table, coords)', (261, 64, 261, 72): 'dillfile'}, {}), '((table_type, options, res_table, coords), dillfile)', False, 'import dill\n'), ((274, 8, 274, 45), 'sys.exit', 'sys.exit', ({(274, 17, 274, 44): '"""Unknown lookup table type"""'}, {}), "('Unknown lookup table type')", False, 'import sys\n'), ((307, 28, 307, 58), 'dill.dumps', 'dill.dumps', ({(307, 39, 307, 57): 'serialized_options'}, {}), '(serialized_options)', False, 'import dill\n'), ((325, 20, 325, 31), 'pathos.multiprocessing.cpu_count', 'cpu_count', ({}, {}), '()', False, 'from pathos.multiprocessing import cpu_count\n'), ((379, 27, 379, 45), 'copy.deepcopy', 'copy.deepcopy', ({(379, 41, 379, 44): 'val'}, {}), '(val)', False, 'import copy\n'), ((403, 21, 403, 63), 'scipy.special.iv', 'scipy.special.iv', ({(403, 38, 403, 39): '(0)', (403, 41, 403, 62): 'coords[cur_pt_idx[2]]'}, {}), '(0, coords[cur_pt_idx[2]])', False, 'import scipy\n'), ((137, 25, 137, 43), 'math.degrees', 'math.degrees', ({(137, 38, 137, 42): 'phi1'}, {}), '(phi1)', False, 'import math\n'), ((137, 45, 137, 63), 'math.degrees', 'math.degrees', ({(137, 58, 137, 62): 'phi2'}, {}), '(phi2)', False, 'import math\n'), ((138, 25, 138, 43), 'math.degrees', 'math.degrees', ({(138, 38, 138, 42): 'phi3'}, {}), '(phi3)', False, 'import math\n'), ((271, 12, 271, 73), 'dill.dump', 'dill.dump', ({(271, 22, 271, 62): '(table_type, options, res_table, coords)', (271, 64, 271, 72): 'dillfile'}, {}), '((table_type, options, res_table, coords), dillfile)', False, 'import dill\n'), ((402, 21, 402, 63), 'scipy.special.iv', 'scipy.special.iv', ({(402, 38, 402, 39): '(0)', (402, 41, 402, 62): 'coords[cur_pt_idx[1]]'}, {}), '(0, coords[cur_pt_idx[1]])', False, 'import scipy\n'), ((134, 41, 134, 53), 'numpy.cos', 'np.cos', ({(134, 48, 134, 52): 'phi3'}, {}), '(phi3)', True, 'import numpy as np\n'), ((183, 41, 183, 59), 'numpy.diag', 'np.diag', ({(183, 49, 183, 58): 'bingham_z'}, {}), '(bingham_z)', True, 'import numpy as np\n'), ((400, 25, 400, 36), 'numpy.log', 'np.log', ({(400, 32, 400, 35): '(8.0)'}, {}), '(8.0)', True, 'import numpy as np\n'), ((401, 21, 401, 63), 'scipy.special.iv', 'scipy.special.iv', ({(401, 38, 401, 39): '(0)', (401, 41, 401, 62): 'coords[cur_pt_idx[0]]'}, {}), '(0, coords[cur_pt_idx[0]])', False, 'import scipy\n'), ((132, 39, 132, 51), 'numpy.cos', 'np.cos', ({(132, 46, 132, 50): 'phi1'}, {}), '(phi1)', True, 'import numpy as np\n'), ((133, 41, 133, 53), 'numpy.cos', 'np.cos', ({(133, 48, 133, 52): 'phi2'}, {}), '(phi2)', True, 'import numpy as np\n'), ((192, 12, 192, 24), 'numpy.cos', 'np.cos', ({(192, 19, 192, 23): 'phi1'}, {}), '(phi1)', True, 'import numpy as np\n'), ((400, 45, 400, 58), 'numpy.log', 'np.log', ({(400, 52, 400, 57): 'np.pi'}, {}), '(np.pi)', True, 'import numpy as np\n'), ((427, 9, 427, 21), 'torch.exp', 'torch.exp', ({(427, 19, 427, 20): 'y'}, {}), '(y)', False, 'import torch\n'), ((432, 9, 432, 21), 'torch.exp', 'torch.exp', ({(432, 19, 432, 20): 'y'}, {}), '(y)', False, 'import torch\n'), ((189, 24, 189, 36), 'numpy.sin', 'np.sin', ({(189, 31, 189, 35): 'phi3'}, {}), '(phi3)', True, 'import numpy as np\n'), ((190, 24, 190, 36), 'numpy.cos', 'np.cos', ({(190, 31, 190, 35): 'phi3'}, {}), '(phi3)', True, 'import numpy as np\n'), ((191, 18, 191, 30), 'numpy.cos', 'np.cos', ({(191, 25, 191, 29): 'phi2'}, {}), '(phi2)', True, 'import numpy as np\n')]