{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n\n# Import GTFS\n\nIn this example, we import a GTFS feed to our model and perform map matching. \n\nWe use data from Coquimbo, a city in La Serena Metropolitan Area in Chile.\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 import remove\nfrom os.path import join\nfrom tempfile import gettempdir\n\nimport folium\nimport pandas as pd\nfrom aequilibrae.project.database_connection import database_connection\n\nfrom aequilibrae.transit import Transit\nfrom aequilibrae.utils.create_example import create_example"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's create an empty project on an arbitrary folder.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fldr = join(gettempdir(), uuid4().hex)\n\nproject = create_example(fldr, \"coquimbo\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "As the Coquimbo example already has a complete GTFS model, we shall remove its public transport  \ndatabase for the sake of this example.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "remove(join(fldr, \"public_transport.sqlite\"))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's import the GTFS feed.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "dest_path = join(fldr, \"gtfs_coquimbo.zip\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Now we create our Transit object and import the GTFS feed into our model.\nThis will automatically create a new public transport database.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "data = Transit(project)\n\ntransit = data.new_gtfs_builder(agency=\"LISANCO\", file_path=dest_path)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "To load the data, we must choose one date. We're going to continue with 2016-04-13 but feel free \nto experiment with any other available dates. Transit class has a function allowing you to check\ndates for the GTFS feed. It should take approximately 2 minutes to load the data.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "transit.load_date(\"2016-04-13\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Now we execute the map matching to find the real paths.\nDepending on the GTFS size, this process can be really time-consuming.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "transit.set_allow_map_match(True)\ntransit.map_match()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Finally, we save our GTFS into our model.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "transit.save_to_disk()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Now we will plot one of the route's patterns we just imported\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "conn = database_connection(\"transit\")\n\nlinks = pd.read_sql(\n    \"SELECT pattern_id, ST_AsText(geometry) geom FROM routes WHERE geom IS NOT NULL AND pattern_id == 10001003000;\", \n    con=conn)\n\nstops = pd.read_sql(\"\"\"SELECT stop_id, ST_X(geometry) X, ST_Y(geometry) Y FROM stops\"\"\", con=conn)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "gtfs_links = folium.FeatureGroup(\"links\")\ngtfs_stops = folium.FeatureGroup(\"stops\")\n\nlayers = [gtfs_links, gtfs_stops]\n\nfor i, row in links.iterrows():\n    points = row.geom.replace(\"MULTILINESTRING\", \"\").replace(\"(\", \"\").replace(\")\", \"\").split(\", \")\n    points = \"[[\" + \"],[\".join([p.replace(\" \", \", \") for p in points]) + \"]]\"\n    points = [[x[1], x[0]] for x in eval(points)]\n\n    _ = folium.vector_layers.PolyLine(points, popup=f\"<b>link_id: {row.pattern_id}</b>\", color=\"red\", weight=2).add_to(\n        gtfs_links\n    )\n\nfor i, row in stops.iterrows():\n    point = (row.Y, row.X)\n\n    _ = folium.vector_layers.CircleMarker(\n        point,\n        popup=f\"<b>link_id: {row.stop_id}</b>\",\n        color=\"black\",\n        radius=3,\n        fill=True,\n        fillColor=\"black\",\n        fillOpacity=1.0,\n    ).add_to(gtfs_stops)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We create the map\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "map_osm = folium.Map(location=[-29.9633719, -71.3242825], zoom_start=13)\n\n# add all layers\nfor layer in layers:\n    layer.add_to(map_osm)\n\n# And Add layer control before we display it\nfolium.LayerControl().add_to(map_osm)\nmap_osm"
      ]
    },
    {
      "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
}