import numpy as np
from scipy.stats import norm
from thunder import SourceExtraction
from thunder.extraction import OverlapBlockMerger

"""
Explanation: Running and evaluating a feature algorithm
In this notebook we run a feaure-based algorithm on a training data set and evaluate performance.
Setup environment
End of explanation
"""


import matplotlib.pyplot as plt
%matplotlib inline
from thunder import Colorize
image = Colorize.image

"""
Explanation: Setup plotting
End of explanation
"""


path = 's3://neuro.datasets/challenges/neurofinder/02.00/'

"""
Explanation: Load data
set the path
End of explanation
"""


data = tsc.loadImages(path + 'images', startIdx=0, stopIdx=100)
data.cache()
data.count();

"""
Explanation: load and cache the raw data (we only load first 100 time points because we're on a single node)
End of explanation
"""


truth = tsc.loadSources(path + 'sources/sources.json')

"""
Explanation: load the sources
End of explanation
"""


im = data.mean()

"""
Explanation: estimate the mean
End of explanation
"""


model = SourceExtraction('localmax')
sources = model.fit(data)

image(sources.masks(im.shape, base=truth, color='random', outline=True), size=10)

"""
Explanation: Run a feature method
End of explanation
"""


recall, precision, score = truth.similarity(sources, metric='distance', minDistance=5)

print('recall: %.2f' % recall)
print('precision: %.2f' % precision)
print('score: %.2f' % score)

"""
Explanation: estimate score (fraction of matches based on centroid distance)
End of explanation
"""


overlap, exactness = tuple(np.nanmean(truth.overlap(sources, method='rates', minDistance=5), axis=0))

print('overlap: %.2f' % overlap)
print('exactness: %.2f' % exactness)

"""
Explanation: estimate overlap and excess (based on degree of overlap for matching sources)
End of explanation
"""


