Skip to content

Commit 2e30dd5

Browse files
committed
changed typing style to python 3.10
1 parent c517a05 commit 2e30dd5

26 files changed

+773
-770
lines changed

pymove/core/dask.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""DaskMoveDataFrame class."""
2+
from __future__ import annotations
23

3-
from typing import TYPE_CHECKING, Dict, List, Text, Union
4+
from typing import TYPE_CHECKING
45

56
import dask
67
import numpy as np
@@ -27,11 +28,11 @@ class DaskMoveDataFrame(DataFrame, MoveDataFrameAbstractModel):
2728

2829
def __init__(
2930
self,
30-
data: Union[DataFrame, List, Dict],
31-
latitude: Text = LATITUDE,
32-
longitude: Text = LONGITUDE,
33-
datetime: Text = DATETIME,
34-
traj_id: Text = TRAJ_ID,
31+
data: DataFrame | list | dict,
32+
latitude: str = LATITUDE,
33+
longitude: str = LONGITUDE,
34+
datetime: str = DATETIME,
35+
traj_id: str = TRAJ_ID,
3536
n_partitions: int = 1,
3637
):
3738
"""
@@ -501,8 +502,8 @@ def to_csv(self, *args, **kwargs):
501502
raise NotImplementedError('To be implemented')
502503

503504
def convert_to(
504-
self, new_type: Text
505-
) -> Union[MoveDataFrame, 'PandasMoveDataFrame', 'DaskMoveDataFrame']:
505+
self, new_type: str
506+
) -> MoveDataFrame | 'PandasMoveDataFrame' | 'DaskMoveDataFrame':
506507
"""
507508
Convert an object from one type to another specified by the user.
508509
@@ -530,7 +531,7 @@ def convert_to(
530531
else:
531532
return self
532533

533-
def get_type(self) -> Text:
534+
def get_type(self) -> str:
534535
"""
535536
Returns the type of the object.
536537

pymove/core/dataframe.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
"""MoveDataFrame class."""
2-
3-
from typing import Dict, List, Text, Union
2+
from __future__ import annotations
43

54
from dateutil.parser._parser import ParserError
65
from pandas.core.frame import DataFrame
@@ -21,12 +20,12 @@ class MoveDataFrame:
2120
@staticmethod
2221
def __new__(
2322
self,
24-
data: Union[DataFrame, Dict, List],
25-
latitude: Text = LATITUDE,
26-
longitude: Text = LONGITUDE,
27-
datetime: Text = DATETIME,
28-
traj_id: Text = TRAJ_ID,
29-
type_: Text = TYPE_PANDAS,
23+
data: DataFrame | dict | list,
24+
latitude: str = LATITUDE,
25+
longitude: str = LONGITUDE,
26+
datetime: str = DATETIME,
27+
traj_id: str = TRAJ_ID,
28+
type_: str = TYPE_PANDAS,
3029
n_partitions: int = 1,
3130
):
3231
"""
@@ -125,8 +124,8 @@ def validate_move_data_frame(data: DataFrame):
125124

126125
@staticmethod
127126
def format_labels(
128-
current_id: Text, current_lat: Text, current_lon: Text, current_datetime: Text
129-
) -> Dict:
127+
current_id: str, current_lat: str, current_lon: str, current_datetime: str
128+
) -> dict:
130129
"""
131130
Format the labels for the PyMove lib pattern labels output lat, lon and datatime.
132131

pymove/core/grid.py

Lines changed: 15 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
"""Grid class."""
2+
from __future__ import annotations
23

34
import math
4-
from typing import Callable, Dict, Optional, Text, Tuple, Union
5+
from typing import Callable
56

67
import joblib
7-
import matplotlib.pyplot as plt
88
import numpy as np
9-
from matplotlib.pyplot import figure
109
from pandas import DataFrame
1110
from shapely.geometry import Polygon
1211

@@ -17,7 +16,6 @@
1716
INDEX_GRID_LON,
1817
LATITUDE,
1918
LONGITUDE,
20-
POLYGON,
2119
TRAJ_ID,
2220
)
2321
from 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

Comments
 (0)