{
  "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": [
        ".. seealso::\n    Several functions, methods, classes and modules are used in this example:\n\n    * :func:`aequilibrae.transit.Transit`\n    * :func:`aequilibrae.transit.lib_gtfs.GTFSRouteSystemBuilder`\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Imports\nfrom uuid import uuid4\nfrom os import remove\nfrom os.path import join\nfrom tempfile import gettempdir\n\nimport folium\nimport geopandas as gpd\nimport pandas as pd\n\nfrom aequilibrae.project.database_connection import database_connection\nfrom aequilibrae.transit import Transit\nfrom aequilibrae.utils.create_example import create_example"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Let's create an empty project on an arbitrary folder.\nfldr = 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\")\n\n# Now we execute the map matching to find the real paths.\n# Depending on the GTFS size, this process can be really time-consuming.\n\n# transit.set_allow_map_match(True)\n# transit.map_match()\n\n# Finally, we save our GTFS into our model.\ntransit.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\npatterns = pd.read_sql(\"SELECT pattern_id, ST_AsText(geometry) geom FROM routes;\", con=conn)\nstops = pd.read_sql(\"\"\"SELECT stop_id, ST_X(geometry) X, ST_Y(geometry) Y FROM stops\"\"\", con=conn)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We turn the patterns and stops DataFrames into GeoDataFrames so we can plot them more easily.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "patterns = gpd.GeoDataFrame(patterns, geometry=gpd.GeoSeries.from_wkt(patterns[\"geom\"]), crs=4326)\nstops = gpd.GeoDataFrame(stops, geometry=gpd.GeoSeries.from_xy(stops[\"X\"], stops[\"Y\"]), crs=4326)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "And plot out data!\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "map = patterns.explore(color=[\"#146DB3\", \"#EB9719\"], style_kwds={\"weight\": 4}, name=\"links\")\nmap = stops.explore(m=map, color=\"black\", style_kwds={\"radius\": 2, \"fillOpacity\": 1.0}, name=\"stops\")\n\nfolium.LayerControl().add_to(map)\nmap"
      ]
    },
    {
      "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.10.18"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}