%matplotlib inline

from matplotlib import pyplot as plt
import numpy
import csv

data = open('../data/data.csv', 'r').readlines()
fieldnames = ['x', 'y', 'z', 'unmasked', 'synapses']
reader = csv.reader(data)
reader.next()

rows = [[int(col) for col in row] for row in reader]
sorted_x = sorted(list(set([r[0] for r in rows])))
sorted_y = sorted(list(set([r[1] for r in rows])))
sorted_z = sorted(list(set([r[2] for r in rows])))

total = sum([r[4] for r in rows])

volume = numpy.zeros((len(sorted_x), len(sorted_y), len(sorted_z)))

"""
Explanation: Rejecting $H_o$ (Uniform Distribution), and further Assumptions
We aim to show that the distribution of synapses in each bin ($\theta_i$) is non-uniform.
$ F = \texttt{Multinomial}([\theta_0, \theta_1, \dots, \theta_n]) \in F_o$

$H_o: \theta_0 = \theta_1 = \dots = \theta_n$: The distribution is uniform.
$H_A: \theta_0 \ne \theta_1 \ne \dots \ne \theta_n$: The distribution is non-uniform.

<!-- $$\chi^2 = \frac{\|E_i - O_i\|^2_2}{E_i}$$ -->
End of explanation
"""


for r in range(total):
    volume[numpy.random.randint(len(sorted_x)), numpy.random.randint(len(sorted_y)), numpy.random.randint(len(sorted_z))] += 1

real_volume = numpy.zeros((len(sorted_x), len(sorted_y), len(sorted_z)))
for r in rows:
    real_volume[sorted_x.index(r[0]), sorted_y.index(r[1]), sorted_z.index(r[2])] = r[-1]

"""
Explanation: Emulate the Distribution
End of explanation
"""


plt.imshow(numpy.amax(volume, axis=2), interpolation='nearest')
plt.show()

plt.imshow(numpy.amax(real_volume, axis=2), interpolation='nearest')
plt.show()

"""
Explanation: The diagram below is what our volume's max-intensity projection would look like if it were perfectly uniform. Qualitatively, it's clear that our data do not follow this distribution in space in any dimension:
End of explanation
"""


data = open('../data/data.csv', 'r').readlines()
fieldnames = ['x', 'y', 'z', 'unmasked', 'synapses']
reader = csv.reader(data)
reader.next()

rows = [[int(col) for col in row] for row in reader]

unmaskedSynapses = ([r[-1] for r in rows if r[-2] != 0])
unmaskedSynapsesNoZero = ([r[-1] for r in rows if r[-2] != 0 if r[-1] !=0])

#including zeros
plt.hist(unmaskedSynapses, bins=50)
plt.show()

#throwing away zeros
plt.hist(unmaskedSynapsesNoZero, bins=50)
plt.show()

"""
Explanation: We make the following assumptions about our data:

All supervoxels are the same realspace size
We can discount the edges of our data, as we expect these areas to be under edge-effect
The data is distributed in a non-uniform manner

Formalization:
End of explanation
"""


