{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n\n# Importing network from GMNS\n\nIn this example, we import a simple network in GMNS format.\nThe source files of this network are publicly available in the GMNS GitHub repository itself.\nHere's the repository: https://github.com/zephyr-data-specs/GMNS\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Imports\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from uuid import uuid4\nfrom os.path import join\nfrom tempfile import gettempdir\nfrom aequilibrae.project import Project\nfrom aequilibrae.parameters import Parameters\nimport folium"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We load the example file from the GMNS GitHub repository\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "link_file = \"https://raw.githubusercontent.com/zephyr-data-specs/GMNS/development/Small_Network_Examples/Arlington_Signals/link.csv\"\nnode_file = \"https://raw.githubusercontent.com/zephyr-data-specs/GMNS/development/Small_Network_Examples/Arlington_Signals/node.csv\"\nuse_group_file = \"https://raw.githubusercontent.com/zephyr-data-specs/GMNS/development/Small_Network_Examples/Arlington_Signals/use_group.csv\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We create the example project inside our temp folder\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fldr = join(gettempdir(), uuid4().hex)\n\nproject = Project()\nproject.new(fldr)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "In this cell, we modify the AequilibraE parameters.yml file so it contains additional\nfields to be read in the GMNS link and/or node tables. Remember to always keep the\n\"required\" key set to False, since we are adding a non-required field.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "new_link_fields = {\n    \"bridge\": {\"description\": \"bridge flag\", \"type\": \"text\", \"required\": False},\n    \"tunnel\": {\"description\": \"tunnel flag\", \"type\": \"text\", \"required\": False},\n}\nnew_node_fields = {\n    \"port\": {\"description\": \"port flag\", \"type\": \"text\", \"required\": False},\n    \"hospital\": {\"description\": \"hospital flag\", \"type\": \"text\", \"required\": False},\n}\n\npar = Parameters()\npar.parameters[\"network\"][\"gmns\"][\"link\"][\"fields\"].update(new_link_fields)\npar.parameters[\"network\"][\"gmns\"][\"node\"][\"fields\"].update(new_node_fields)\npar.write_back()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "As it is specified that the geometries are in the coordinate system EPSG:32619,\nwhich is different than the system supported by AequilibraE (EPSG:4326), we inform\nthe srid in the method call:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "project.network.create_from_gmns(\n    link_file_path=link_file, node_file_path=node_file, use_group_path=use_group_file, srid=32619\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Now, let's plot a map. This map can be compared with the images of the README.md\nfile located in this example repository on GitHub:\nhttps://github.com/zephyr-data-specs/GMNS/blob/development/Small_Network_Examples/Arlington_Signals/README.md\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "links = project.network.links.data\nnodes = project.network.nodes.data\n\n# We create our Folium layers\nnetwork_links = folium.FeatureGroup(\"links\")\nnetwork_nodes = folium.FeatureGroup(\"nodes\")\nlayers = [network_links, network_nodes]\n\n# We do some Python magic to transform this dataset into the format required by Folium\n# We are only getting link_id and link_type into the map, but we could get other pieces of info as well\nfor i, row in links.iterrows():\n    points = row.geometry.wkt.replace(\"LINESTRING \", \"\").replace(\"(\", \"\").replace(\")\", \"\").split(\", \")\n    points = \"[[\" + \"],[\".join([p.replace(\" \", \", \") for p in points]) + \"]]\"\n    # we need to take from x/y to lat/long\n    points = [[x[1], x[0]] for x in eval(points)]\n\n    _ = folium.vector_layers.PolyLine(\n        points, popup=f\"<b>link_id: {row.link_id}</b>\", tooltip=f\"{row.modes}\", color=\"black\", weight=2\n    ).add_to(network_links)\n\n# And now we get the nodes\n\nfor i, row in nodes.iterrows():\n    point = (row.geometry.y, row.geometry.x)\n\n    _ = folium.vector_layers.CircleMarker(\n        point,\n        popup=f\"<b>link_id: {row.node_id}</b>\",\n        tooltip=f\"{row.modes}\",\n        color=\"red\",\n        radius=5,\n        fill=True,\n        fillColor=\"red\",\n        fillOpacity=1.0,\n    ).add_to(network_nodes)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We get the center of the region\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "curr = project.conn.cursor()\ncurr.execute(\"select avg(xmin), avg(ymin) from idx_links_geometry\")\nlong, lat = curr.fetchone()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We create the map\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "map_gmns = folium.Map(location=[lat, long], zoom_start=17)\n\n# Add all layers\nfor layer in layers:\n    layer.add_to(map_gmns)\n\n# And Add layer control before we display it\nfolium.LayerControl().add_to(map_gmns)\nmap_gmns"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "project.close()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.9.16"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}