question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Issues following example docs

See original GitHub issue

Hi @anitagraser

I have been working through the examples at https://anitagraser.github.io/movingpandas/

It all works well except for the last couple of examples embedded in the images at the end of the page (for calculating stops and splits):

import pandas as pd
import geopandas as gp
import psycopg2
import movingpandas as mpd
from datetime import timedelta

con = psycopg2.connect(database="gis", user="docker", password="xxxxxxxxx",
    host="db", sslmode="require")

sql = "select geom, id, device, event_datetime from owntracks.event order by event_datetime ASC"

df = gp.GeoDataFrame.from_postgis(sql, con, geom_col='geom' )

df.plot()
<AxesSubplot:>

output_4_1

traj = mpd.Trajectory(df, 1)
traj.plot()
<AxesSubplot:>





![output_6_1](https://user-images.githubusercontent.com/178003/136838243-33b1d04c-b6d5-43f7-9a3b-9be060c6d7b6.png)

traj.hvplot(geo=True, tiles=‘OSM’, line_width=5, frame_width=300, frame_height=300)

df.columns
Index(['geom', 'id', 'device', 'event_datetime'], dtype='object')
df
<div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; }
.dataframe tbody tr th {
    vertical-align: top;
}

.dataframe thead th {
    text-align: right;
}
</style>
geom id device event_datetime
0 POINT (xxx,yyy) 8807 TP 2021-09-21 18:41:26
1 POINT (xxx,yyy) 8814 TP 2021-09-21 18:41:26
2 POINT (xxx,yyy) 59819 TP 2021-09-21 18:41:26
3 POINT (xxx,yyy) 8849 TP 2021-09-21 18:41:26
4 POINT (xxx,yyy) 8869 TP 2021-09-21 18:41:26
... ... ... ... ...
67954 POINT (xxx,yyy) 68106 TP 2021-10-11 19:18:44
67955 POINT (xxx,yyy) 68107 TP 2021-10-11 19:18:52
67956 POINT (xxx,yyy) 68108 TP 2021-10-11 19:18:57
67957 POINT (xxx,yyy) 68109 TP 2021-10-11 19:19:19
67958 POINT (xxx,yyy) 68110 TP 2021-10-11 19:19:19

67959 rows × 4 columns

</div>
df = df.set_index('event_datetime')
tc = mpd.TrajectoryCollection(df, 'device')

daily = mpd.TemporalSplitter(tc).split(mode='day')
daily_lengths = [traj.get_length() for traj in daily]
daily_t = [traj.get_start_time() for traj in daily]
daily_lengths = pd.DataFrame(daily_lengths, index=daily_t, columns=['length'])
daily_lengths.hvplot(title='Daily trajectory length')
stops = mpd.TrajectoryStopDetector(traj).get_stop_segments(min_duration=timedelta(seconds=60), max_diameter=100)
    ---------------------------------------------------------------------------

    TypeError                                 Traceback (most recent call last)

![output_6_1](https://user-images.githubusercontent.com/178003/136837828-7e33ee95-99a4-4ceb-b414-f26ddb4051a7.png)
![output_4_1](https://user-images.githubusercontent.com/178003/136837832-2fa3cd33-ac43-43b3-a0b4-3411f83b84f4.png)
    /tmp/ipykernel_235/1649748576.py in <module>
    ----> 1 stops = mpd.TrajectoryStopDetector(traj).get_stop_segments(min_duration=timedelta(seconds=60), max_diameter=100)
    

    /opt/conda/lib/python3.9/site-packages/movingpandas/trajectory_stop_detector.py in get_stop_segments(self, max_diameter, min_duration)
        113         >>> mpd.TrajectoryStopDetector(traj).get_stop_segments(min_duration=timedelta(seconds=60), max_diameter=100)
        114         """
    --> 115         stop_time_ranges = self.get_stop_time_ranges(max_diameter, min_duration)
        116         return TrajectoryCollection(convert_time_ranges_to_segments(self.traj, stop_time_ranges))
        117 


    /opt/conda/lib/python3.9/site-packages/movingpandas/trajectory_stop_detector.py in get_stop_time_ranges(self, max_diameter, min_duration)
         41         """
         42         if isinstance(self.traj, Trajectory):
    ---> 43             return self._process_traj(self.traj, max_diameter, min_duration)
         44         elif isinstance(self.traj, TrajectoryCollection):
         45             return self._process_traj_collection(max_diameter, min_duration)


    /opt/conda/lib/python3.9/site-packages/movingpandas/trajectory_stop_detector.py in _process_traj(self, traj, max_diameter, min_duration)
         80                 segment_begin = segment_times[0]
         81                 if not is_stopped and previously_stopped:
    ---> 82                     if segment_end - segment_begin >= min_duration:  # detected end of a stop
         83                         detected_stops.append(TemporalRangeWithTrajId(segment_begin, segment_end, traj.id))
         84                         segment_geoms = []


    TypeError: '>=' not supported between instances of 'int' and 'datetime.timedelta'
split = mpd.StopSplitter(traj).split(min_duration=timedelta(seconds=60), max_diameter=100)

    ---------------------------------------------------------------------------

    TypeError                                 Traceback (most recent call last)

    /tmp/ipykernel_235/971365991.py in <module>
    ----> 1 split = mpd.StopSplitter(traj).split(min_duration=timedelta(seconds=60), max_diameter=100)
    

    /opt/conda/lib/python3.9/site-packages/movingpandas/trajectory_splitter.py in split(self, **kwargs)
         41         """
         42         if isinstance(self.traj, Trajectory):
    ---> 43             return self._split_traj(self.traj, **kwargs)
         44         elif isinstance(self.traj, TrajectoryCollection):
         45             return self._split_traj_collection(**kwargs)


    /opt/conda/lib/python3.9/site-packages/movingpandas/trajectory_splitter.py in _split_traj(self, traj, max_diameter, min_duration, min_length)
        175     def _split_traj(self, traj, max_diameter, min_duration, min_length=0):
        176         stop_detector = TrajectoryStopDetector(traj)
    --> 177         stop_time_ranges = stop_detector.get_stop_time_ranges(max_diameter, min_duration)
        178         between_stops = self.get_time_ranges_between_stops(traj, stop_time_ranges)
        179         result = convert_time_ranges_to_segments(traj, between_stops)


    /opt/conda/lib/python3.9/site-packages/movingpandas/trajectory_stop_detector.py in get_stop_time_ranges(self, max_diameter, min_duration)
         41         """
         42         if isinstance(self.traj, Trajectory):
    ---> 43             return self._process_traj(self.traj, max_diameter, min_duration)
         44         elif isinstance(self.traj, TrajectoryCollection):
         45             return self._process_traj_collection(max_diameter, min_duration)


    /opt/conda/lib/python3.9/site-packages/movingpandas/trajectory_stop_detector.py in _process_traj(self, traj, max_diameter, min_duration)
         80                 segment_begin = segment_times[0]
         81                 if not is_stopped and previously_stopped:
    ---> 82                     if segment_end - segment_begin >= min_duration:  # detected end of a stop
         83                         detected_stops.append(TemporalRangeWithTrajId(segment_begin, segment_end, traj.id))
         84                         segment_geoms = []


    TypeError: '>=' not supported between instances of 'int' and 'datetime.timedelta'


In terms of the data, the table schema looks like this:

                                              Table "owntracks.event"
     Column      |            Type             | Collation | Nullable |                   Default                   
-----------------+-----------------------------+-----------+----------+---------------------------------------------
 id              | integer                     |           | not null | nextval('owntracks.event_id_seq'::regclass)
 geom            | geometry(Point,4326)        |           |          | 
 battery         | integer                     |           | not null | 
 velocity        | double precision            |           |          | 
 altitude        | double precision            |           | not null | 
 course          | double precision            |           |          | 
 device          | character varying(2)        |           | not null | 
 insert_datetime | timestamp without time zone |           | not null | now()
 event_datetime  | timestamp without time zone |           |          | 
 trigger         | character varying(1)        |           |          | 
 battery_status  | integer                     |           |          | 
 in_regions      | text                        |           |          | 
 ssid            | text                        |           |          | 
 bssid           | text                        |           |          | 
 topic           | text                        |           | not null | 'none'::text
 osm_road_id     | integer                     |           |          | 
 has_road        | boolean                     |           | not null | false
Indexes:
    "osm__geom_idx" gist (geom)
    "owntracks_event_geom_idx" gist (geom)
Triggers:
    nearest_road_to_event_trigger BEFORE INSERT OR UPDATE ON owntracks.event FOR EACH ROW EXECUTE FUNCTION nearest_road_to_event_trigger()


Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
Ali-Ozturkcommented, Oct 18, 2021

I think the input DataFrame may be missing the required DateTimeIndex. Can you double-check if you did to_datetime and set_index, as shown in the tutorials?

gdf = read_file('../data/geolife_small.gpkg')
gdf['t'] = pd.to_datetime(gdf['t'])
gdf = gdf.set_index('t')

Hello Anitagraser,

This has solved my issues thank you!

0reactions
anitagrasercommented, Oct 18, 2021

I think the input DataFrame may be missing the required DateTimeIndex. Can you double-check if you did to_datetime and set_index, as shown in the tutorials?

gdf = read_file('../data/geolife_small.gpkg')
gdf['t'] = pd.to_datetime(gdf['t'])
gdf = gdf.set_index('t')
Read more comments on GitHub >

github_iconTop Results From Across the Web

Common Problems with Google Docs - Zapier Help
Common Problems with Google Docs · My settings in Google Docs are not being respected when using the Create Document actions · My...
Read more >
Troubleshoot Google Docs, Sheets, Slides & Forms error ...
If you get an error message such as "Something went wrong. Reload" or "Unable to load file" preventing you from making edits on...
Read more >
Configuring issue templates for your repository - GitHub Docs
Under your repository name, click Settings. Repository settings button; In the "Features" section, under "Issues," click Set up templates. Start template setup ...
Read more >
Issues API - GitLab Docs
Interact with GitLab Issues using the REST API. If a user is not a member of a private project, a GET request on...
Read more >
Customer Care procedures & support activities - Google Cloud
Google Cloud posts information about known issues affecting its services as ... The following examples demonstrate possible reasons for escalating a case:.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found