Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added an example within the documentation for custom readers supporting pandas DataFrames. #707

Merged
merged 25 commits into from
Mar 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
435883a
Added a new example within the documentation in docs/examples for the…
BenjaminFraser Aug 31, 2022
15e2bef
Added pandas as a dependency to setup.py, under extras_require['dev']…
BenjaminFraser Aug 31, 2022
c77e80e
Changed setup.py to setup.cfg to align with latest main branch of Sto…
BenjaminFraser Oct 22, 2022
775161f
Added setup.cfg file to replace setup.py.
BenjaminFraser Oct 22, 2022
9c31b1e
Merged changes from main to local branch.
BenjaminFraser Oct 22, 2022
cc9bbd7
Added pandas dependency to setup.cfg
BenjaminFraser Oct 22, 2022
b5e72c9
Updated references to Stone Soup throughout documentation to be two-w…
BenjaminFraser Oct 22, 2022
8295311
Added demonstration of ground truth reader by outputting first iterat…
BenjaminFraser Oct 22, 2022
1b50fee
Corrected 'ground truth' to 'detection' within doc string description…
BenjaminFraser Oct 22, 2022
2db60ee
Added support for fields that are already in DateTime format within _…
BenjaminFraser Oct 22, 2022
9fb4eaf
Added new pandas readers to reader directory within new file 'pandas_…
BenjaminFraser Oct 22, 2022
776a3cc
Corrected at top of file as part of imports - added 'as pd' for impor…
BenjaminFraser Oct 22, 2022
33cb12a
Removed unnecesary whitespace from blank lines within pandas_readers.py
BenjaminFraser Oct 22, 2022
3f2dd7b
Added import modf from math standard library, as required for functio…
BenjaminFraser Oct 22, 2022
20b9417
Added Detection import from stonesoup types.detection as required wit…
BenjaminFraser Oct 22, 2022
95d7ee2
Added Detection import to documentation example for custom pandas dat…
BenjaminFraser Oct 22, 2022
ea8f82b
Added test_pandas_reader.py for testing newly added pandas_reader.py …
BenjaminFraser Oct 22, 2022
0a53b39
Corrected issues with tests for pandas_reader.py within reader direct…
BenjaminFraser Oct 22, 2022
a838e0c
Improved tests for pandas_reader.py within stonesoup/reader/tests dir…
BenjaminFraser Oct 22, 2022
21337ef
Minor formatting refinements to pass flake8 tests. Whitespace removed…
BenjaminFraser Oct 22, 2022
f4786d8
Added various minor formatting fixes for flake8 testing requirements.
BenjaminFraser Oct 22, 2022
8705dac
Further fixes / corrections to adhere to flake8 tests.
BenjaminFraser Oct 22, 2022
90d2c96
Added additional tests to include full coverage of classes defined in…
BenjaminFraser Oct 23, 2022
af4c77b
Added further tweak to test_gt_df_multi_per_timestep() test within te…
BenjaminFraser Oct 23, 2022
bd854e4
Remove OS and IDE specific gitignores and settings
sdhiscocks Feb 21, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
295 changes: 295 additions & 0 deletions docs/examples/Custom_Pandas_Dataloader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,295 @@
"""
Use of Custom Readers that support Pandas DataFrames
====================================================
This is a demonstration of using customised readers that
support data contained within Pandas DataFrames, rather than
loading directly from a .csv file using :class:`~.CSVGroundTruthReader` or
:class:`~.CSVDetectionReader`.

The benefit is that this allows us to use the versatile data loading
capabilities of pandas to read from many different data source types
as needed, including .csv, JSON, XML, Parquet, HDF5, .txt, .zip and more.
The resulting DataFrame can then simply be fed into the defined
`DataFrameGroundTruthReader` or `DataFrameDetectionReader` for further processing
in Stone Soup as required.
"""

# %%
# Software dependencies
# ---------------------
# Before beginning this example, you need to ensure that Pandas is installed,
# which is a fast, powerful and flexible open-source data analysis tool in Python.
# The easiest way to install pandas (if not done so already), is to run pip install
# from a terminal window within the desired environment:
#
# .. code::
#
# pip install pandas

# %%
# The main dependencies and imports for this example are included below:

import numpy as np
import pandas as pd

from math import modf

from stonesoup.base import Property
from stonesoup.buffered_generator import BufferedGenerator
from stonesoup.reader.base import GroundTruthReader, DetectionReader, Reader
from stonesoup.types.detection import Detection
from stonesoup.types.groundtruth import GroundTruthPath, GroundTruthState

from typing import Sequence, Collection

from datetime import datetime, timedelta
from dateutil.parser import parse


# %%
# Data Frame Reader
# ^^^^^^^^^^^^^^^^^
# Similarly to Stone Soup's :class:`~._CSVFrameReader`, we'll define a `_DataFrameReader`
# class that inherits from the base :class:`~.Reader` class to read a DataFrame containing
# state vector fields, a time field, and additional metadata fields (all other columns
# by default). The only difference between this class and the :class:`~._CSVFrameReader`
# class is that we have no path attribute (the DataFrame is already loaded in memory).

class _DataFrameReader(Reader):
state_vector_fields: Sequence[str] = Property(
doc='List of columns names to be used in state vector')
time_field: str = Property(
doc='Name of column to be used as time field')
time_field_format: str = Property(
default=None, doc='Optional datetime format')
timestamp: bool = Property(
default=False, doc='Treat time field as a timestamp from epoch')
metadata_fields: Collection[str] = Property(
default=None, doc='List of columns to be saved as metadata, default all')

def _get_metadata(self, row):
if self.metadata_fields is None:
local_metadata = dict(row)
for key in list(local_metadata):
if key == self.time_field or key in self.state_vector_fields:
del local_metadata[key]
else:
local_metadata = {field: row[field]
for field in self.metadata_fields
if field in row}
return local_metadata

def _get_time(self, row):
if self.time_field_format is not None:
time_field_value = datetime.strptime(row[self.time_field], self.time_field_format)
elif self.timestamp:
fractional, timestamp = modf(float(row[self.time_field]))
time_field_value = datetime.utcfromtimestamp(int(timestamp))
time_field_value += timedelta(microseconds=fractional * 1E6)
else:
time_field_value = row[self.time_field]

if not isinstance(time_field_value, datetime):
time_field_value = parse(time_field_value, ignoretz=True)

return time_field_value


# %%
# Data Ground Truth Reader
# ^^^^^^^^^^^^^^^^^^^^^^^^
# With the help of our `_DataFrameReader` class, we can now define a custom
# `DataFrameGroundTruthReader`. This is similar to :class:`~.CSVGroundTruthReader` and
# inherits from the base `GroundTruthReader` class. A key difference is that we
# include an instance attribute for the dataframe containing our data.
#
# We also define a custom generator function (groundtruth_paths_gen) that uses the decorator
# `@BufferedGenerator.generator_method`. The generator needs to return a time and a set of
# detections, like so:

class DataFrameGroundTruthReader(GroundTruthReader, _DataFrameReader):
"""A custom reader for pandas DataFrames containing truth data.

The DataFrame must have colums containing all fields needed to generate the
ground truth state. Those states with the same ID will be put into
a :class:`~.GroundTruthPath` in sequence, and all paths that are updated at the same time
are yielded together, and such assumes file is in time order.

Parameters
----------
"""
dataframe: pd.DataFrame = Property(doc="DataFrame containing the ground truth data.")
path_id_field: str = Property(doc='Name of column to be used as path ID')

@BufferedGenerator.generator_method
def groundtruth_paths_gen(self):
""" Generator method for providing each row of ground truth data. """
groundtruth_dict = {}
updated_paths = set()
previous_time = None
for row in self.dataframe.to_dict(orient="records"):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a thought, but wondering if you could take advantage of pandas to group by time field (and path_id field), such that you can simplify the logic below (i.e. no need for the previous_time code)?

Copy link
Contributor Author

@BenjaminFraser BenjaminFraser Oct 23, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm sure we could do this easily enough, although I've not included it in the current commit yet. Before doing this, I could do with confirming the precise functionality to avoid accidentally changing the current generator logic.

If we simply order by path_id and time, and then iteratively yield each time and updated_paths (detections for DataFrameDetectionReader), is that doing exactly the same functionality as the current groundtruth_paths_gen (and detections_gen)?


time = self._get_time(row)
if previous_time is not None and previous_time != time:
yield previous_time, updated_paths
updated_paths = set()
previous_time = time

state = GroundTruthState(np.array([[row[col_name]] for col_name
in self.state_vector_fields],
dtype=np.float_),
timestamp=time,
metadata=self._get_metadata(row))

id_ = row[self.path_id_field]
if id_ not in groundtruth_dict:
groundtruth_dict[id_] = GroundTruthPath(id=id_)
groundtruth_path = groundtruth_dict[id_]
groundtruth_path.append(state)
updated_paths.add(groundtruth_path)

# Yield remaining
yield previous_time, updated_paths


# %%
# With our `DataFrameGroundTruthReader` defined, we can test it on a simple example. Let's
# do a basic 3D simulation to create an example dataframe, from which we can test our class:

from stonesoup.models.transition.linear import CombinedLinearGaussianTransitionModel, \
ConstantVelocity

q_x = 0.05
q_y = 0.05
q_z = 0.05
start_time = datetime.now()
transition_model = CombinedLinearGaussianTransitionModel([ConstantVelocity(q_x),
ConstantVelocity(q_y),
ConstantVelocity(q_z)])
truth = GroundTruthPath([GroundTruthState([0, 1, 0, 1, 0, 1], timestamp=start_time)])

times = []
x, y, z = [], [], []
vel_x, vel_y, vel_z = [], [], []

num_steps = 25
for k in range(1, num_steps + 1):

time = start_time+timedelta(seconds=k)

next_state = GroundTruthState(
transition_model.function(truth[k-1], noise=True,
time_interval=timedelta(seconds=1)),
timestamp=time)
truth.append(next_state)

times.append(time)
x.append(next_state.state_vector[0])
vel_x.append(next_state.state_vector[1])
y.append(next_state.state_vector[2])
vel_y.append(next_state.state_vector[3])
z.append(next_state.state_vector[4])
vel_z.append(next_state.state_vector[5])

truth_df = pd.DataFrame({'time': times,
'x': x,
'y': y,
'z': z,
'vel_x': vel_x,
'vel_y': vel_y,
'vel_z': vel_z,
'track_id': 0})

truth_df.head(5)

# %%
# Note that the process above is just an example for providing a simple dataframe to use,
# and is not generally something we would need to do (since we already have the GroundTruthPath).
# The dataframe above is just used to show the workings of our newly defined
# `DataFrameGroundTruthReader`. In practice, we can use any dataframe containing
# our Cartesian positions or longitude and latitude co-ordinates. Note that if we
# are using longitude and latitude inputs, we would also need to transform these
# using :class:`~.LongLatToUTMConverter` or equivalent.
#
# We can now initialise our DataFrameGroundTruthReader using this example DataFrame like so:

# read ground truth data from pandas dataframe
ground_truth_reader = DataFrameGroundTruthReader(
dataframe=truth_df,
state_vector_fields=['x', 'vel_x', 'y', 'vel_y', 'z', 'vel_z'],
time_field='time',
path_id_field='track_id')

BenjaminFraser marked this conversation as resolved.
Show resolved Hide resolved

# %%
# Let's demonstrate the ground truth reader generating output for one iteration:

next(iter(ground_truth_reader))


# %%
# Another benefit of this ground truth reader is that we now have convenient access to the original
# dataframe, using the .dataframe attribute, like so:

ground_truth_reader.dataframe.head(3)


# %%
# DataFrame Detection Reader
# ^^^^^^^^^^^^^^^^^^^^^^^^^^
# Similarly to our `DataFrameGroundTruthReader`, we can develop a custom `DataFrameDetectionReader`
# that can read in DataFrames containing detections through subclassing from Stone Soup's
# `DetectionReader` class, along with our custom `_DataFrameReader` class above.
# Again, this closely resembles the existing `CSVDetectionReader` class within the Stone Soup
# library, except we include a instance attribute 'dataframe', and modify our detections_gen
# function to work with dataframes rather than .csv files. This can be seen below:

class DataFrameDetectionReader(DetectionReader, _DataFrameReader):
"""A custom detection reader for DataFrames containing detections.

DataFrame must have headers with the appropriate fields needed to generate
the detection. Detections at the same time are yielded together, and such assume file is in
time order.

Parameters
----------
"""
dataframe: pd.DataFrame = Property(doc="DataFrame containing the detection data.")

@BufferedGenerator.generator_method
def detections_gen(self):
detections = set()
previous_time = None
for row in self.dataframe.to_dict(orient="records"):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could possibly also group by time field here.


time = self._get_time(row)
if previous_time is not None and previous_time != time:
yield previous_time, detections
detections = set()
previous_time = time

detections.add(Detection(
np.array([[row[col_name]] for col_name in self.state_vector_fields],
dtype=np.float_),
timestamp=time,
metadata=self._get_metadata(row)))

# Yield remaining
yield previous_time, detections


# %%
# We can instantiate this using our example DataFrame above like so:

detection_reader = DataFrameDetectionReader(
dataframe=truth_df,
state_vector_fields=['x', 'vel_x', 'y', 'vel_y', 'z', 'vel_z'],
time_field='time')

# %%
# Following this, we can now perform any desired follow-up task such as simulation or tracking
# as covered in the other Stone Soup examples, tutorials and demonstrations. As discussed
# previously, the huge benefits of using a custom DataFrame reader like this is that we can
# read any type of data supported by the pandas library, which gives us a huge range of
# options. This strategy also saves us the overhead of manually specifying custom Stone
# Soup Reader classes for each format of data.
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ dev =
flake8<5
folium
h5py
pandas
pillow
plotly
pytest-flake8
Expand Down
Loading