import subprocess
from collections import namedtuple

import matplotlib.pyplot as plt
import scipy as sp
from jinja2 import Template


Node = namedtuple('Node', ['name', 'text'])
Edge = namedtuple('Edge', ['start', 'end'])
t = Template("""digraph {
 {% for node in nodes %}
 {{ node.name }} [label="{{ node.text }}"]\
 {% endfor %}
 {% for edge in edges %}\
 {{ edge.start }} -> {{ edge.end }}
 {% endfor %}\
}""")


nr_vertices = 10
feature_space_dimension = 2
feature_vectors = sp.rand(feature_space_dimension, nr_vertices)
feature_vectors[feature_vectors < 1/3] = -1
feature_vectors[(feature_vectors > 1/3) * (feature_vectors < 2/3)] = 0
feature_vectors[feature_vectors > 2/3] = 1
plt.matshow(feature_vectors)
plt.colorbar()
plt.savefig('/home/emmanuel/tmp/feature_vectors.png')

def fv2label(vec):
    return ''.join('+' if v == 1 else '-' if v == -1 else '0' for v in vec)

def it(d, s, e):
    for k in range(s,e):
        if d == 0:
            yield (k,)
        for other in it(d-1, k+1, e):
            yield (k,) + other

def optimize(feature_vectors, n):
    target_indices = list(range(feature_vectors.shape[1]))
    del target_indices[n]
    possible_targets = feature_vectors[:,target_indices]
    for k in range(3):
        for trial in it(k, 0, possible_targets.shape[1]):
            if (possible_targets[:,trial].sum(1) == feature_vectors[:,n]).all():
                return [target_indices[t] for t in trial]


nodes = [Node(k,fv2label(v)) for k, v in enumerate(feature_vectors.T)]
edges = []


s = t.render(nodes=nodes, edges=edges)
dot_file = '/home/emmanuel/tmp/exp_net.dot'
with open(dot_file, "w") as f:
    f.write(s)
print(s)
for extension in ['pdf', 'png']:
    res = subprocess.call(['fdp', '-T' + extension, '-o',
                           '/home/emmanuel/tmp/fever_net.' + extension, dot_file])


