def test_from_df(): df = traja.generate(n=599581) df = df.filter(items=['x', 'y']) save_path = 'temp/test' warmup_steps = 50 # Run 1 timeseries_method = 'last_timestep' model = traja.models.LSTM(input_size=2, hidden_size=2, num_layers=3, output_size=2, dropout=0, bidirectional=False) writer = delve.writers.CSVandPlottingWriter(save_path, fontsize=16, primary_metric='test_accuracy') saturation = delve.CheckLayerSat(save_path, [writer], model, stats=['embed'], timeseries_method=timeseries_method) sequence_length = 2000 train_fraction = .25 batch_size = 50 shift = 2 train_loader, test_loader = traja.models.get_timeseries_data_loaders(df, sequence_length, train_fraction, batch_size, shift) trainer = traja.models.Trainer(model, train_loader, test_loader, epochs=6, optimizer="adam", warmup_steps=warmup_steps) trainer.train() pass
def test_color_dark(): df = traja.generate(n=10) index = pd.DatetimeIndex(range(10)) df.index = index traja.plot(df, interactive=False) ax = plt.gca() traja.color_dark(df.x, ax)
def test_plot_clustermap(): trjs = [traja.generate(seed=i) for i in range(20)] # Calculate displacement displacements = [trj.traja.calc_displacement() for trj in trjs] traja.plot_clustermap(displacements)
def test_plot_actogram(): df = traja.generate(n=10) index = pd.DatetimeIndex(range(10)) df.index = index activity = traja.calc_displacement(df) activity.name = "activity" traja.plotting.plot_actogram(df.x, interactive=False)
def test_plot_actogram(): df = traja.generate(n=1000) index = pd.date_range("2018-01-01", periods=1000, freq="T") df.index = index activity = traja.calc_displacement(df) activity.name = "activity" traja.plotting.plot_actogram(df.x, interactive=False)
def test_color_dark(): df = traja.generate(n=10) index = pd.DatetimeIndex(range(10)) df.index = index ax = plt.gca() try: traja.color_dark(df.x, ax) except ValueError as e: # catch unexplained datetime value error in travis if "view limit minimum" in str(e): pass
""" Average direction for each grid cell ==================================== See the flow between grid cells. """ import traja df = traja.generate(seed=0) ############################################################################### # Average Flow (3D) # ----------------- # Flow can be plotted by specifying the `kind` parameter of :func:`traja.plotting.plot_flow` # or by calling the respective functions. import traja traja.plotting.plot_surface(df, bins=32) ############################################################################### # Quiver # ------ # Quiver plot # Additional arguments can be specified as a dictionary to `quiverplot_kws`. traja.plotting.plot_quiver(df, bins=32) ############################################################################### # Contour # ------- # Parameters `filled` and `quiver` are both enabled by default and can be
import os import numpy as np import pandas as pd import traja df = traja.generate(n=20) def test_from_df(): df = pd.DataFrame({"x": [1, 2, 3], "y": [2, 3, 4]}) trj = traja.parsers.from_df(df) np.testing.assert_allclose(df, trj) assert isinstance(trj, traja.TrajaDataFrame) def test_read_file(): datapath = os.path.join(traja.__path__[0], "tests", "data", "3527.csv") trj = traja.parsers.read_file(datapath) assert isinstance(trj, traja.TrajaDataFrame) assert "Frame" in trj assert "Time" in trj assert "TrackId" in trj assert "x" in trj assert "y" in trj assert "ValueChanged" in trj
df = traja.TrajaDataFrame({'x': [0, 1, 2, 3, 4], 'y': [1, 3, 2, 4, 5]}) ############################################################################### # Plotting with Traja # ===================== # # We start out by plotting a basic sime series trajectory using the ``traja`` # accessor and ``.plot()`` method. df.traja.plot() ############################################################################### # Generate Random Walks # ===================== # # Also, random walks can be generated using ``generate``. df = traja.generate(n=1000, random=True, fps=30) df.traja.plot() ############################################################################### # Traja can re-scale data with any units df.traja.scale(100) df.spatial_units = 'cm' df.traja.plot() ############################################################################### # Rediscretize step lengths # ========================= # # ``rediscretize`` method allows resampling the trajectory into an arbitrary step # length ``R``.
""" Comparing ----------------------------------- traja allows comparing trajectories using various methods. """ import traja df = traja.generate(angular_error_sd=0.5) ############################################################################### # Fast Dynamic Time Warping of Trajectories # ========================================= # # Fast dynamic time warping can be performed using the optional package # ``fastdtw``. It can be installed with ``pip install fastdtw``. # Source article: `link <https://cs.fit.edu/~pkc/papers/tdm04.pdf>`_. import numpy as np rotated = traja.utils.rotate(df, angle=np.pi / 10) rotated.traja.plot() ############################################################################### # Compare trajectories point-wise # ========================================= # dist = traja.utils.distance(df.traja.xy, rotated.traja.xy) print(f"Distance between the two trajectories is {dist}")
""" Comparing --------- traja allows comparing trajectories using various methods. """ import traja df = traja.generate(seed=0) df.traja.plot() ############################################################################### # Fast Dynamic Time Warping of Trajectories # ========================================= # # Fast dynamic time warping can be performed using ``fastdtw``. # Source article: `link <https://cs.fit.edu/~pkc/papers/tdm04.pdf>`_. import numpy as np rotated = traja.rotate(df, angle=np.pi / 10) rotated.traja.plot() ############################################################################### # Compare trajectories hierarchically # =================================== # Hierarchical agglomerative clustering allows comparing trajectories as actograms # and finding nearest neighbors. This is useful for comparing circadian rhythms, # for example. # Generate random trajectories trjs = [traja.generate(seed=i) for i in range(20)]
""" Plotting Multiple Trajectories ------------------------------ Plotting multiple trajectories is easy with :meth:`~traja.frame.TrajaCollection.plot`. """ import traja from traja import TrajaCollection # Create a dictionary of DataFrames, with 'id' as key. dfs = {idx: traja.generate(idx, seed=idx) for idx in range(10, 15)} # Create a TrajaCollection. trjs = TrajaCollection(dfs) # Note: A TrajaCollection can also be instantiated with a DataFrame, containing and id column, # eg, TrajaCollection(df, id_col="id") # 'colors' also allows substring matching, eg, {"car":"red", "person":"blue"} lines = trjs.plot( colors={10: "red", 11: "blue", 12: "blue", 13: "orange", 14: "purple"} )
""" Animate trajectories ------------------------------- traja allows animating trajectories. """ import traja df = traja.generate(1000, seed=0) ############################################################################### # Plot a animation of trajectory # ============================== # An animation is generated using :func:`~traja.plotting.animate`. anim = traja.plotting.animate(df) # save=True saves to 'trajectory.mp4' #################################################################################### # .. raw:: html # # <iframe width="560" height="315" src="https://www.youtube.com/embed/-_-Ay9phB5k" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
""" 3D Plotting with traja ---------------------- Plot trajectories with time in the vertical axis. Note: Adjust matplotlib args ``dist``, ``labelpad``, ``aspect`` and ``adjustable``` as needed. """ import traja df = traja.TrajaDataFrame({"x": [0, 1, 2, 3, 4], "y": [1, 3, 2, 4, 5]}) trj = traja.generate() ax = trj.traja.plot_3d(dist=15, labelpad=32, title="Traja 3D Plot") ######## # Colors # ------- # # `Matplotlib cmaps<https://matplotlib.org/examples/color/colormaps_reference.html>`_ are available trj.traja.plot_3d(dist=15, labelpad=32, title="Traja 3D Plot", cmap="jet")
def test_generate(): df = traja.generate(n=20) actual = df.traja.xy[:3] expected = np.array([[0.0, 0.0], [1.162_605_74, 1.412_179_34], [1.861_836_8, 2.727_243_73]]) npt.assert_allclose(actual, expected, rtol=1e-1)
from traja.dataset import dataset from traja.dataset.example import jaguar from traja.models.generative_models.vae import MultiModelVAE from traja.models.train import HybridTrainer from traja.plotting import plot_prediction matplotlib.use("Agg") import matplotlib.pyplot as plt import pandas as pd import traja warnings.filterwarnings("ignore", category=UserWarning, module="matplotlib") df = traja.generate(n=10) def test_stylize_axes(): collection = traja.plot(df, interactive=False) traja.plotting.stylize_axes(collection.axes) def test_sans_serif(): traja.plotting.sans_serif() def test_plot_3d(): traja.plot_3d(df, interactive=False)
df = traja.TrajaDataFrame({'x':[0,1,2,3,4],'y':[1,3,2,4,5]}) ############################################################################### # Plotting with Traja # ===================== # # We start out by plotting a basic sime series trajectory using the ``traja`` # accessor and ``.plot()`` method. df.traja.plot() ############################################################################### # Generate Random Walks # ===================== # # Also, random walks can be generated using ``generate``. df = traja.generate(n=1000, fps=30) df.traja.plot() ############################################################################### # Traja can re-scale data with any units df.traja.scale(100) df.spatial_units='cm' df.traja.plot() ############################################################################### # Rediscretize step lengths # ========================= # # ``rediscretize`` method allows resampling the trajectory into an arbitrary step # length ``R``.
""" Average direction for each grid cell ==================================== See the flow between grid cells. """ import traja df = traja.generate() ############################################################################### # Average Flow (3D) # ----------------- # Flow can be plotted by specifying the `kind` parameter of :func:`traja.plotting.plot_flow` # or by calling the respective functions. import traja traja.plotting.plot_surface(df, bins=32) ############################################################################### # Quiver # ------ # Quiver plot # Additional arguments can be specified as a dictionary to `quiverplot_kws`. traja.plotting.plot_quiver(df, bins=32) ############################################################################### # Contour # ------- # Parameters `filled` and `quiver` are both enabled by default and can be
import numpy as np import numpy.testing as npt import pytest from pandas.util.testing import assert_series_equal import traja df = traja.generate(n=20, convex_hull=True) def test_polar_to_z(): df_copy = df.copy() polar = traja.cartesian_to_polar(df_copy.traja.xy) z = traja.polar_to_z(*polar) z_actual = z[:10] z_expected = np.array([ 0.0 + 0.0j, 1.162_605_74 + 1.412_179_34j, 1.861_836_8 + 2.727_243_73j, 1.860_393_36 + 4.857_966_96j, -0.096_486_29 + 5.802_456_77j, -1.735_291_68 + 4.940_704_34j, -4.189_217_4 + 4.951_826_17j, -5.712_624_22 + 4.177_006j, -7.567_193_14 + 3.404_176_98j, -9.415_289_13 + 2.743_725_89j, ]) npt.assert_allclose(z_actual, z_expected)