Ejemplo n.º 1
0
def rediscretize_points(trj: TrajaDataFrame,
                        R: Union[float, int],
                        time_out=False):
    """Returns a ``TrajaDataFrame`` rediscretized to a constant step length `R`.

    Args:
      trj (:class:`traja.frame.TrajaDataFrame`): Trajectory
      R (float): Rediscretized step length (eg, 0.02)
      time_out (bool): Include time corresponding to time intervals in output

    Returns:
      rt (:class:`numpy.ndarray`): rediscretized trajectory

    """
    if not isinstance(R, (float, int)):
        raise TypeError(f"R should be float or int, but is {type(R)}")

    results = _rediscretize_points(trj, R, time_out)
    rt = results["rt"]
    if len(rt) < 2:
        raise RuntimeError(
            f"Step length {R} is too large for path (path length {len(trj)})")
    rt = traja.from_xy(rt)
    if time_out:
        rt["time"] = results["time"]
    return rt
Ejemplo n.º 2
0
def plot_xy(xy: np.ndarray, *args: Optional, **kwargs: Optional):
    """Plot trajectory from xy values.

    Args:

        xy (np.ndarray) : xy values of dimensions N x 2
        *args           : Plot args
        **kwargs        : Plot kwargs
    """
    trj = traja.from_xy(xy)
    trj.traja.plot(*args, **kwargs)
Ejemplo n.º 3
0
def rediscretize_points(trj: TrajaDataFrame, R: Union[float, int]):
    """Returns a ``TrajaDataFrame`` rediscretized to a constant step length `R`.

    Args:
      trj (:class:`traja.frame.TrajaDataFrame`): Trajectory
      R (float): Rediscretized step length (eg, 0.02)

    Returns:
      rt (:class:`numpy.ndarray`): rediscretized trajectory

    """
    rt = _rediscretize_points(trj, R)

    if len(rt) < 2:
        raise RuntimeError(
            f"Step length {R} is too large for path (path length {len(self._trj)})"
        )
    rt = traja.from_xy(rt)
    return rt
Ejemplo n.º 4
0
def traj_from_coords(
    track: Union[np.ndarray, pd.DataFrame],
    x_col=1,
    y_col=2,
    time_col: Optional[str] = None,
    fps: Union[float, int] = 4,
    spatial_units: str = "m",
    time_units: str = "s",
) -> TrajaDataFrame:
    """Create TrajaDataFrame from coordinates.

    Args:
        track:  N x 2 numpy array or pandas DataFrame with x and y columns
        x_col: column index or x column name
        y_col: column index or y column name
        time_col: name of time column
        fps: Frames per seconds
        spatial_units: default m, optional
        time_units: default s, optional

    Returns:
        trj: TrajaDataFrame

    .. doctest::

        >> xy = np.random.random((1000, 2))
        >> trj = traja.traj_from_coord(xy)
        >> assert trj.shape == (1000,4) # columns x, y, time, dt

    """
    if not isinstance(track, traja.TrajaDataFrame):
        if isinstance(track, np.ndarray) and track.shape[1] == 2:
            trj = traja.from_xy(track)
        elif isinstance(track, pd.DataFrame):
            trj = traja.TrajaDataFrame(track)
    else:
        trj = track
    trj.traja.spatial_units = spatial_units
    trj.traja.time_units = time_units

    def rename(col, name, trj):
        if isinstance(col, int):
            trj.rename(columns={col: name})
        else:
            if col not in trj:
                raise Exception(f"Missing column {col}")
            trj.rename(columns={col: name})
        return trj

    # Ensure column names are as expected
    trj = rename(x_col, "x", trj)
    trj = rename(y_col, "y", trj)
    if time_col is not None:
        trj = rename(time_col, "time", trj)

    # Allocate times if they aren't already known
    if "time" not in trj:
        if fps is None:
            raise Exception((
                "Cannot create a trajectory without times: either fps or a time column must be specified"
            ))
        # Assign times to each frame, starting at 0
        trj["time"] = pd.Series(np.arange(0, len(trj)) / fps)

    # Get displacement time for each coordinate, with the first point at time 0
    trj["dt"] = trj.time - trj.time.iloc[0]

    return trj
Ejemplo n.º 5
0
def test_from_xy():
    df_copy = df.copy()
    expected = traja.from_xy(df_copy.traja.xy).values
    actual = df_copy.traja.xy
    npt.assert_allclose(expected, actual)