Skip to content

Commit

Permalink
Update docs, paper, plotting
Browse files Browse the repository at this point in the history
  • Loading branch information
JustinShenk committed May 19, 2021
1 parent 7e8590c commit f3e122c
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 14 deletions.
12 changes: 12 additions & 0 deletions docs/examples/plot_autocorrelation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
"""
Autocorrelation plotting with traja
-----------------------------------
Plot autocorrelation of a trajectory with :meth:`traja.plotting.plot_autocorrelation`
Wrapper for pandas :meth:`pandas.plotting.autocorrelation_plot`.
"""
import traja

trj = traja.generate()
trj.traja.plot_autocorrelation('x')
15 changes: 15 additions & 0 deletions docs/examples/plot_pca.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"""
Plot PCA with traja
-----------------------------------
Plot PCA of a trip grid with :meth:`traja.plotting.plot_pca`
Wrapper for pandas :meth:`pandas.plotting.autocorrelation_plot`.
"""
import traja

# Load sample jaguar dataset with trajectories for 9 animals
df = traja.dataset.example.jaguar()

# Bin trajectory into a trip grid then perform PCA
traja.plotting.plot_pca(df, id_col="ID", bins=(8,8))
12 changes: 12 additions & 0 deletions docs/examples/plot_periodogram.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
"""
Periodogram plot with traja
-----------------------------------
Plot periodogram or power spectrum with :meth:`traja.plotting.plot_periodogram`.
Wrapper for pandas :meth:`scipy.signal.periodogram`.
"""
import traja

trj = traja.generate()
trj.traja.plot_periodogram('x')
9 changes: 1 addition & 8 deletions paper/paper.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ Periodic behaviors are a consequence of the circadian rhythm aswell as observing

### Autocorrelation
Autocorrelation is the correlation of a signal with a delayed copy of itself as a function of the decay. Basically, it is similarity of observations as a function of the time lag between them.
It is computed with autocorrelation and plotted as shown in Figure [5](#fig:autocorrelation){reference-type="ref" reference="fig:autocorrelation"}.
An example is shown in Figure [5](#fig:autocorrelation){reference-type="ref" reference="fig:autocorrelation"}.

![Autocorrelation of the y-dimension reveals daily (1440 minutes) periodic behavior[]{label="fig:autocorrelation"}](./images/autocorrelation_E1.png){#fig:autocorrelation width=80%}

Expand All @@ -194,18 +194,11 @@ width=80%}

This requires converting the trajectory to a trip grid (see Figure 1) and performing PCA on the grid in 2D (Figure [7](#fig:pca){reference-type="ref" reference="fig:pca"}) or 3D (Figure [8](#fig:3dpca){reference-type="ref" reference="fig:3dpca"}). Structure in the data is visible if light and dark time periods are compared.

### Linear Discriminant Analysis
Linear Discriminant Analysis (LDA) is a method for identifying a manifold separating two or more labelled groups. It searches for a linear transformation of the data by maximising the between-class variance and minimising the within-class variance. It has been used to identify symmetry of heavy object lifting trajectories [@jeong_linear_2016]. It behaves similar to PCA in some cases (Figure [9](#fig:LDA){reference-type="ref" reference="fig:LDA"})

![3D PCA of Fortasyn trajectory data. Daily trajectories (day and night)
were binned into 8x8 grids before applying
PCA.[]{label="fig:3dpca"}](./images/pca_fortasyn-period-3d.png){#fig:3dpca
width=80%}

![LDA of Fortasyn trajectory
data.[]{label="fig:LDA"}](./images/lda_fortasyn-period.png){#fig:LDA
width=80%}

### Clustering
Clustering of trajectories is an extensive topic with applications in geospatial data, vehicle and pedestrian classification, as well as molecular identification. K-Means clustering is an iterative unsupervised learning method that assigns a label to data points based on a distance function [@bishop_pattern_2006] (Figure [10]).

Expand Down
35 changes: 29 additions & 6 deletions traja/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,9 @@
"plot_contour",
"plot_clustermap",
"plot_flow",
"plot_quiver",
"plot_periodogram",
"plot_pca",
"plot_periodogram",
"plot_quiver",
"plot_stream",
"plot_surface",
"plot_transition_graph",
Expand Down Expand Up @@ -540,33 +541,55 @@ def plot_autocorrelation(
return plt.gcf()


def plot_pca(trj: TrajaDataFrame, id_col: str="id", bins: tuple = (8,8)):
def plot_pca(trj: TrajaDataFrame, id_col: str="id", bins: tuple = (8,8), three_dims: bool = False, ax = None):
"""Plot PCA comparing animals ids by trip grids.
Args:
trj - Trajectory
id_col - column representing animal IDs
bins - shape for binning trajectory into a trip grid
three_dims - 3D plot. Default: False (2D plot)
ax - Matplotlib axes (optional)
Returns:
fig - Figure
"""
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler


DIMS = 3 if three_dims else 2

# Bin trajectories to trip grids
grids = []
for ID in trj[id_col].unique():
animal = trj[trj.ID==ID]
animal.drop(columns=[id_col],inplace=True)
grid = animal.traja.trip_grid(bins = bins, hist_only=True)[0]
grids.append(grid.flatten())

# Standardize the data
gridsarr = np.array(grids)
pca = PCA(n_components=2)
X_r = pca.fit(gridsarr).transform(gridsarr)
X = StandardScaler().fit_transform(gridsarr)

# PCA projection
pca = PCA(n_components=DIMS)
X_r = pca.fit(X).transform(X)

# Create plot axes
if DIMS == 3:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
if not ax:
_, ax = plt.subplots()

# Visualize 2D projection
for idx, animal in enumerate(X_r):
plt.scatter(X_r[idx, 0], X_r[idx, 1], color=f'C{idx}', alpha=.8, lw=2, label=idx)
if DIMS == 2:
ax.scatter(X_r[idx, 0], X_r[idx, 1], color=f'C{idx}', alpha=.8, lw=2, label=idx)
elif DIMS == 3:
ax.scatter(X_r[idx, 0], X_r[idx, 1], ax.scatter[idx,2], color=f'C{idx}', alpha=.8, lw=2, label=idx)

plt.title("PCA")
plt.legend(title=id_col, loc='best', shadow=False, scatterpoints=1)
Expand Down

0 comments on commit f3e122c

Please sign in to comment.