import networkx as nx
import numpy as np
import pickle
from scipy.spatial import KDTree
from latlon_to_spatial import latlonstospace

datadir = '../../Data/'
metadatadir = datadir + 'Metadata/'
nodeorder = np.load(metadatadir + 'nodeorder.npy')

generators = pickle.load(open(metadatadir + 'generator_database_no_affiliation.pickle'))
entsoe_grid = nx.read_gpickle(metadatadir + 'entsoe_2009_v3.gpickle')
nodepos = nx.get_node_attributes(entsoe_grid,'pos')
nodelatlon = np.array([nodepos[n] for n in nodeorder])
nodespos = latlonstospace(nodelatlon[:,1],nodelatlon[:,0])

#Fast lookup of node position
nodetree = KDTree(nodespos)

generatororder = generators.keys()
generatorlatlon = np.array([generators[g]['location'] for g in generatororder])
generatorspos = latlonstospace(generatorlatlon[:,1],generatorlatlon[:,0])
distances, nodeidx = nodetree.query(generatorspos)
for gen,n in zip(generators, nodeorder[nodeidx] ):
	generators[gen]['origin'] = n


pickle.dump(generators,open(metadatadir + 'generator_database_affiliation.pickle','w'))

@@ -377,22 +377,23 @@
  + '
-entsoe_2009_v3
+network_postfit
 .gpi
@@ -444,16 +444,17 @@
 oe_grid,
+ 
 'pos')%0An
@@ -546,19 +546,21 @@
 atlon%5B:,
+ 
 1%5D,
+ 
 nodelatl
@@ -568,14 +568,16 @@
 n%5B:,
+ 
 0%5D)%0A%0A#
+ 
 Fast
@@ -794,19 +794,21 @@
 atlon%5B:,
+ 
 1%5D,
+ 
 generato
@@ -817,16 +817,17 @@
 atlon%5B:,
+ 
 0%5D)%0Adist
@@ -881,16 +881,17 @@
 for gen,
+ 
 n in zip
@@ -921,17 +921,16 @@
 nodeidx%5D
- 
 ):%0A%09gene
@@ -980,16 +980,17 @@
 erators,
+ 
 open(met
@@ -1040,14 +1040,15 @@
 pickle',
+ 
 'w'))%0A

update network filename, pep8