# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # Stop Detection
#
# <img align="right" src="https://anitagraser.github.io/movingpandas/pics/movingpandas.png">
#
# [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/anitagraser/movingpandas/master?filepath=tutorials/4-stop-detection.ipynb)
#
# **<p style="color:#e31883">This notebook demonstrates the current development version of MovingPandas.</p>**
#
# For tutorials using the latest release visit https://github.com/anitagraser/movingpandas-examples.
#

# ## Setup

# +
import pandas as pd
import geopandas as gpd
from datetime import datetime, timedelta

import sys
sys.path.append("..")
import movingpandas as mpd
print(mpd.__version__)

import warnings
warnings.simplefilter("ignore")
# -

FSIZE = 350

# ## Loading Geolife Sample

# %%time
df = gpd.read_file('data/demodata_geolife.gpkg')
print("Finished reading {} rows".format(len(df)))

traj_collection = mpd.TrajectoryCollection(df, 'trajectory_id', t='t')
traj_collection

# ## Stop Detection with a SingleTrajectory
#
# There are no definitive answers when it comes to detecting / extracting stops from movement trajectories. Due to tracking inaccuracies, movement speed rarely goes to true zero. GPS tracks, for example, tend to keep moving around the object's stop location. 
#
# Suitable stop definitions are also highly application dependent. For example, an application may be interested in analyzing trip purposes. To do so, analysts would be interested in stops that are longer than, for example, 5 minutes and may try to infer the purpose of the stop from the stop location and time. Shorter stops, such as delays at traffic lights, however would not be relevant for this appication. 
#
# In the MovingPandas **TrajectoryStopDetector** implementation, a stop is detected if the movement stays within an area of specified size for at least the specified duration.

my_traj = traj_collection.trajectories[0]
my_traj

detector = mpd.TrajectoryStopDetector(my_traj)

traj_plot = my_traj.hvplot(title='Trajectory {}'.format(my_traj.id), line_width=7.0, tiles='CartoLight', color='slategray', frame_width=FSIZE, frame_height=FSIZE) 
traj_plot

# ### Stop duration

# %%time
stop_durations = detector.get_stop_time_ranges(min_duration=timedelta(seconds=60), max_diameter=100)

for x in stop_durations: 
    print(x)

# ### Stop points

# %%time
stop_points = detector.get_stop_points(min_duration=timedelta(seconds=60), max_diameter=100)

stop_points

stop_point_plot = traj_plot * stop_points.hvplot(geo=True, size='duration_s', color='deeppink')
stop_point_plot

# ### Stop segments

# %%time
stops = detector.get_stop_segments(min_duration=timedelta(seconds=60), max_diameter=100)

stops

stop_segment_plot = stop_point_plot * stops.hvplot( size=200, line_width=7.0, tiles=None, color='orange') 
stop_segment_plot

# ### Split at stops

# %%time
split = mpd.StopSplitter(my_traj).split(min_duration=timedelta(seconds=60), max_diameter=100)

split

for segment in split:
    print(segment)

stop_segment_plot + split.hvplot(title='Trajectory {} split at stops'.format(my_traj.id), line_width=7.0, tiles='CartoLight', frame_width=FSIZE, frame_height=FSIZE) 

# ## Stop Detection for TrajectoryCollections
#
# The process is the same as for individual trajectories.

# %%time
detector = mpd.TrajectoryStopDetector(traj_collection)
stops = detector.get_stop_segments(min_duration=timedelta(seconds=120), max_diameter=100)
len(stops)

traj_map = traj_collection.hvplot( frame_width=FSIZE, frame_height=FSIZE, line_width=7.0, tiles='CartoLight', color='slategray')

( traj_map * 
 stops.hvplot( size=200, line_width=7.0, tiles=None, color='deeppink') *
 stops.get_start_locations().hvplot(geo=True, size=200, color='deeppink') )

stop_points = detector.get_stop_points(min_duration=timedelta(seconds=120), max_diameter=100)

# +
map1 = ( traj_map * stop_points.hvplot(geo=True, size=200, color='traj_id', title=f'Traj_id type {type(stop_points.iloc[0].traj_id)}'))

stop_points.traj_id = stop_points.traj_id.astype('str')
map2 = ( traj_map * stop_points.hvplot(geo=True, size=200, color='traj_id', title=f'Traj_id type {type(stop_points.iloc[0].traj_id)}'))

map1 + map2
# -

# ## Continue exploring MovingPandas
#
# 1. [Getting started](1-getting-started.ipynb)
# 1. [Reading data from files](2-reading-data-from-files.ipynb)
# 1. [Trajectory aggregation (flow maps)](3-generalization-and-aggregation.ipynb)
# 1. [Stop detection](4-stop-detection.ipynb)

StarcoderdataJupyterScriptsDedupFiltered