# Enable plotting support, etc. One could've folded this into the generic IPython
# configuration but I prefer to make it explicit.
%pylab inline
rcParams['figure.figsize'] = (16, 12)

"""
Explanation: Python notebook example
This is an example of running Python from a notebook. Note that we use some custom packages installed via the requirements.txt file. One of these came from a University git repository.
End of explanation
"""


import trafficutils.io as tio

"""
Explanation: We're going to use the trafficutils library to try to load a representation of England's major road network from the UK Highways agency. Firstly, let's import the appropriate function:
End of explanation
"""


help(tio.load_traffic_network)

"""
Explanation: Let's check the documentation for the function we're going to use:
End of explanation
"""


from requests import get

NETWORK_XML_URL="http://hatrafficinfo.dft.gov.uk/feeds/datex/England/PredefinedLocationLinks/content.xml"
network_xml_req = get(NETWORK_XML_URL)
assert network_xml_req.status_code == 200 # OK
network_xml = network_xml_req.content

from io import BytesIO
G = tio.load_traffic_network(BytesIO(network_xml))

"""
Explanation: OK, let's use requests to download the XML document and then we'll pass it to load_traffic_network as a BytesIO object.
End of explanation
"""


print('nodes:', G.number_of_nodes())
print('edges:', G.number_of_edges())

"""
Explanation: How many nodes and links do we have?
End of explanation
"""


from networkx import draw_networkx, draw_networkx_edges

# The pos keyword argument is a dictionary mapping nodes to their (x, y) positions.
# Since the nodes are the (longitude, latitude) pairs we can just use the nodes as
# their own positions.
draw_networkx_edges(G, pos=dict((n,n) for n in G.nodes_iter()))
axis('equal')
grid('on')

"""
Explanation: Let's try plotting it:
End of explanation
"""


import pyproj

wgs84 = pyproj.Proj(init='epsg:4326')
bng = pyproj.Proj(init='epsg:27700')

draw_networkx_edges(G, pos=dict((n, pyproj.transform(wgs84, bng, *n)) for n in G.nodes_iter()))
axis('equal')
grid('on')

"""
Explanation: It's a bit squashed what with the projection being raw latitudes and longitudes. Use the pyproj package to map from WGS84 latitude/longitude to the British National Grid.
End of explanation
"""


