11"""Grid class."""
2+ from __future__ import annotations
23
34import math
4- from typing import Callable , Dict , Optional , Text , Tuple , Union
5+ from typing import Callable
56
67import joblib
7- import matplotlib .pyplot as plt
88import numpy as np
9- from matplotlib .pyplot import figure
109from pandas import DataFrame
1110from shapely .geometry import Polygon
1211
1716 INDEX_GRID_LON ,
1817 LATITUDE ,
1918 LONGITUDE ,
20- POLYGON ,
2119 TRAJ_ID ,
2220)
2321from pymove .utils .conversions import lat_meters
@@ -30,9 +28,9 @@ class Grid:
3028
3129 def __init__ (
3230 self ,
33- data : Union [ DataFrame , Dict ] ,
34- cell_size : Optional [ float ] = None ,
35- meters_by_degree : Optional [ float ] = None
31+ data : DataFrame | dict ,
32+ cell_size : float | None = None ,
33+ meters_by_degree : float | None = None
3634 ):
3735 """
3836 Creates a virtual grid from the trajectories.
@@ -58,7 +56,7 @@ def __init__(
5856 ValueError
5957 If one of data or cell grid is not provided
6058 """
61- self .last_operation : Dict = dict ()
59+ self .last_operation : dict = dict ()
6260 if meters_by_degree is None :
6361 meters_by_degree = lat_meters (- 3.71839 )
6462 if isinstance (data , dict ):
@@ -69,7 +67,7 @@ def __init__(
6967 raise ValueError ('Must pass either data or cell size.' )
7068 self .grid_polygon = None
7169
72- def get_grid (self ) -> Dict :
70+ def get_grid (self ) -> dict :
7371 """
7472 Returns the grid object in a dict format.
7573
@@ -91,7 +89,7 @@ def get_grid(self) -> Dict:
9189 'cell_size_by_degree' : self .cell_size_by_degree ,
9290 }
9391
94- def _grid_from_dict (self , dict_grid : Dict ):
92+ def _grid_from_dict (self , dict_grid : dict ):
9593 """
9694 Coverts the dict grid to a Grid object.
9795
@@ -218,8 +216,8 @@ def create_update_index_grid_feature(
218216 def convert_two_index_grid_to_one (
219217 self ,
220218 data : DataFrame ,
221- label_grid_lat : Text = INDEX_GRID_LAT ,
222- label_grid_lon : Text = INDEX_GRID_LON ,
219+ label_grid_lat : str = INDEX_GRID_LAT ,
220+ label_grid_lon : str = INDEX_GRID_LON ,
223221 ):
224222 """
225223 Converts grid lat-lon ids to unique values.
@@ -241,7 +239,7 @@ def convert_two_index_grid_to_one(
241239 def convert_one_index_grid_to_two (
242240 self ,
243241 data : DataFrame ,
244- label_grid_index : Text = INDEX_GRID ,
242+ label_grid_index : str = INDEX_GRID ,
245243 ):
246244 """
247245 Converts grid lat-lon ids to unique values.
@@ -360,7 +358,7 @@ def create_all_polygons_to_all_point_on_grid(
360358 self .last_operation = end_operation (operation )
361359 return datapolygons
362360
363- def point_to_index_grid (self , event_lat : float , event_lon : float ) -> Tuple [int , int ]:
361+ def point_to_index_grid (self , event_lat : float , event_lon : float ) -> tuple [int , int ]:
364362 """
365363 Locate the coordinates x and y in a grid of point (lat, long).
366364
@@ -394,7 +392,7 @@ def point_to_index_grid(self, event_lat: float, event_lon: float) -> Tuple[int,
394392
395393 return indexes_lat_y , indexes_lon_x
396394
397- def save_grid_pkl (self , filename : Text ):
395+ def save_grid_pkl (self , filename : str ):
398396 """
399397 Save a grid with new file .pkl.
400398
@@ -409,7 +407,7 @@ def save_grid_pkl(self, filename: Text):
409407 joblib .dump (self .get_grid (), f )
410408 self .last_operation = end_operation (operation )
411409
412- def read_grid_pkl (self , filename : Text ) -> 'Grid' :
410+ def read_grid_pkl (self , filename : str ) -> 'Grid' :
413411 """
414412 Read grid dict from a file .pkl.
415413
@@ -431,74 +429,6 @@ def read_grid_pkl(self, filename: Text) -> 'Grid':
431429 self .last_operation = end_operation (operation )
432430 return grid
433431
434- def show_grid_polygons (
435- self ,
436- data : DataFrame ,
437- markersize : float = 10 ,
438- linewidth : float = 2 ,
439- figsize : Tuple [int , int ] = (10 , 10 ),
440- return_fig : bool = True ,
441- save_fig : bool = False ,
442- name : Text = 'grid.png' ,
443- ) -> Optional [figure ]:
444- """
445- Generate a visualization with grid polygons.
446-
447- Parameters
448- ----------
449- data : DataFrame
450- Input trajectory data
451- markersize : float, optional
452- Represents visualization size marker, by default 10
453- linewidth : float, optional
454- Represents visualization size line, by default 2
455- figsize : tuple(int, int), optional
456- Represents the size (float: width, float: height) of a figure,
457- by default (10, 10)
458- return_fig : bool, optional
459- Represents whether or not to save the generated picture, by default True
460- save_fig : bool, optional
461- Wether to save the figure, by default False
462- name : str, optional
463- Represents name of a file, by default 'grid.png'
464-
465- Returns
466- -------
467- figure
468- The generated picture or None
469-
470- Raises
471- ------
472- If the dataframe does not contains the POLYGON feature
473- IndexError
474- If there is no user with the id passed
475-
476- """
477- if POLYGON not in data :
478- raise KeyError ('POLYGON feature not in dataframe' )
479-
480- data .dropna (subset = [POLYGON ], inplace = True )
481-
482- operation = begin_operation ('show_grid_polygons' )
483-
484- fig = plt .figure (figsize = figsize )
485-
486- for _ , row in data .iterrows ():
487- xs , ys = row [POLYGON ].exterior .xy
488- plt .plot (ys , xs , 'g' , linewidth = linewidth , markersize = markersize )
489- xs_start , ys_start = data .iloc [0 ][POLYGON ].exterior .xy
490- xs_end , ys_end = data .iloc [- 1 ][POLYGON ].exterior .xy
491- plt .plot (ys_start , xs_start , 'bo' , markersize = markersize * 1.5 )
492- plt .plot (ys_end , xs_end , 'bX' , markersize = markersize * 1.5 ) # start point
493-
494- if save_fig :
495- plt .savefig (fname = name )
496-
497- self .last_operation = end_operation (operation )
498-
499- if return_fig :
500- return fig
501-
502432 def __repr__ (self ) -> str :
503433 """
504434 String representation of grid.
@@ -512,5 +442,5 @@ def __repr__(self) -> str:
512442 grid_size_lon_x: grid longitude size
513443 cell_size_by_degree: grid cell size
514444 """
515- text = ['{ }: {}' . format ( k , v ) for k , v in self .get_grid ().items ()]
445+ text = [f' { k } : { v } ' for k , v in self .get_grid ().items ()]
516446 return '\n ' .join (text )
0 commit comments