from conmorph.connections import RecurrentInhibition
import numpy as np

from conmorph.util import load_spec
from interneuron_polarity.model.morphology.volume import get_distance_from_to

labels=["polar", "circular"]

ex_ex_connections = [RecurrentInhibition.load("../../data/{:s}_recurrent_inhibition.pickle".format(label)) for label
                     in labels]

model = load_spec("morphological_model.json")

density_ex = model["excitatory_neurons"]["density"]
density_in = model["inhibitory_neurons"]["density"]
volume = 4.0/3*np.pi* model["inhibitory_neurons"]["long_axis"]*model["inhibitory_neurons"]["short_axis"]**2


distance_step = 5
max_distance = model["inhibitory_neurons"]["long_axis"]*2
distance_bins = np.arange(0, max_distance, distance_step)
offsets= [-4, 4]
bin_width = 2

filename="../../data/first_order_connectivity_"
np.save("{:s}{:s}.npy".format(filename, "distance_bins"), distance_bins)

def print_statistics(distances):
    print("Number of connections per neuron: {:d}".format(len(distances)))
    print("Mean distance: {:.1f}".format(np.mean(distances)))
    print("Std distance: {:.1f}".format(np.std(distances)))
    print("Min distance: {:.1f}".format(np.min(distances)))
    print("Max distance: {:.1f}".format(np.max(distances)))

for conn, label, off in zip(ex_ex_connections, labels, offsets):
    assert isinstance(conn, RecurrentInhibition)
    distances = conn.get_distances_to_neighbors()
    print(label)
    print_statistics(distances)
    print()

    distance_histo, _ = np.histogram(distances, distance_bins)

    number_of_available_neighbors, _ = np.histogram(get_distance_from_to(conn.positions, conn.positions), distance_bins)
    number_of_available_neighbors[0] = number_of_available_neighbors[0]-conn.n_ex

    average_number_of_connections = distance_histo / number_of_available_neighbors
    np.save("{:s}{:s}.npy".format(filename, label), average_number_of_connections)

