def get_average_local_polarization(t, number_of_neighbours = 1):
    if t.number_of_individuals == 1:
        return('nan')
    else:
       indices = ttsocial.give_indices(t.s, number_of_neighbours)
       en = ttsocial.restrict(t.e,indices)[...,1:,:]
       local_polarization = tt.norm(tt.collective.polarization(en))
       return np.nanmean(local_polarization, axis = -1) 
Beispiel #2
0
    def from_positions(cls,
                       t,
                       interpolate_nans=True,
                       smooth_sigma=0,
                       only_past=True,
                       unit_length=None,
                       frame_rate=None,
                       arena_radius=None):
        trajectories = Namespace()
        trajectories.raw = t.copy()
        if interpolate_nans:
            tt.interpolate_nans(t)

        radius, center_x, center_y, unit_length = \
            tt.center_trajectories_and_normalise(t, unit_length=unit_length,
                                                 forced_radius=arena_radius)
        if smooth_sigma > 0:
            t_smooth = tt.smooth(t, sigma=smooth_sigma, only_past=only_past)
        else:
            t_smooth = t

        if only_past:
            [trajectories.s, trajectories.v, trajectories.a] = \
                tt.velocity_acceleration_backwards(t_smooth)
        else:
            [trajectories.s, trajectories.v, trajectories.a] = \
                tt.velocity_acceleration(t_smooth)

        trajectories.speed = tt.norm(trajectories.v)
        trajectories.acceleration = tt.norm(trajectories.a)
        trajectories.distance_to_center = tt.norm(trajectories.s)
        trajectories.e = tt.normalise(trajectories.v)
        trajectories.tg_acceleration = tt.dot(trajectories.a, trajectories.e)
        trajectories.curvature = tt.curvature(trajectories.v, trajectories.a)
        trajectories.normal_acceleration = \
            np.square(trajectories.speed)*trajectories.curvature
        traj = cls(trajectories)
        traj.params = {
            "frame_rate": frame_rate,
            "center_x": center_x,  # Units: unit_length
            "center_y": center_y,  # Units: unit length
            "radius": radius,  # Units: unit length
            "unit_length": unit_length
        }  # Units: pixels
        return traj
Beispiel #3
0
 def test_ang_mom_antiparallel(self, num_dims_point):
     # Random point to measure angular momentum
     if num_dims_point == 2:
         point = np.random.randn(2)
     elif num_dims_point == 1:
         point = np.random.randn(50, 2)
     # Random locations (but all in the same point)
     locations = np.stack([np.random.randn(50, 2)] * 10, axis=1)
     ang_momentum = tt.norm(
         angular_momentum(self.v_antiparallel, locations, center=point))
     assert pytest.approx(ang_momentum, 1e-16) == 0
Beispiel #4
0
def polarization(v):
    """Calculates (the normalised) polarization vector

    Reduction is performed on the penultimate dimension, which
    for normal trajectories (3 dims) means individuals, so a
    single polarisation is calculated per frame.

    For trajectories with neighbours (4 dims), means neighbours,
    so a polarisation is calculated per focal.
    """
    norm_v = tt.norm(v, keepdims=True)
    return np.sum(v, axis=-2) / np.sum(norm_v, axis=-2)
Beispiel #5
0
def local_polarization(tr, n=1, x=1):
    if n < x:
        return (np.nan, np.nan)
    if tr.number_of_individuals == 1:
        return (np.nan, np.nan)
    if x >= tr.number_of_individuals:
        return (np.nan, np.nan)
    else:
        indices = ttsocial.give_indices(
            tr.s, n)  # indices of the closest n neighbors
        a = ttsocial.restrict(
            tr.e, indices
        )  # normalized velocity (direction) vectors of focal individual and closest n neighbors
        b = np.multiply(
            a[:, :, 0, :],
            a[:, :,
              x, :])  #polarization between focal and xth closest individual
        c = np.sum(b, axis=2)  #dot product of vectors.
        lp = tt.norm(tt.collective.polarization(a))
        #return(c)
        return (np.nanmean(lp), np.nanmean(c))
def local_polarization_func(tr, n=1, x=1):  #shape returns tr.s.shape -2
    if n < x:
        return (np.nan, np.nan)
    if tr.number_of_individuals == 1:
        return (np.nan, np.nan)
    if x >= tr.number_of_individuals:
        return (np.nan, np.nan)
    else:
        indices = ttsocial.neighbour_indices(
            tr.s[1:-1], n)  # indices of the closest n neighbors
        a = ttsocial.restrict(
            tr.e[1:-1], indices
        )  # normalized velocity (direction) vectors of focal individual and closest n neighbors
        b = np.multiply(
            a[:, :, 0, :],
            a[:, :,
              x, :])  #polarization between focal and xth closest individual
        c = np.sum(b, axis=2)  #dot product of vectors.
        lp = tt.norm(tt.collective.polarization(a))
        #return(c)
        return (np.nanmean(lp[~filter_speed(tr, 5).mask]),
                np.nanmean(c[~filter_speed(tr, 5).mask]))
Beispiel #7
0
def polarization(v):
    """ Calculates (the normalised) polarization of the vectors
    """
    norm_v = tt.norm(v, keepdims=True)
    return sum_across_individuals(v) / sum_across_individuals(norm_v)
Beispiel #8
0
from trajectorytools.constants import dir_of_data

if __name__ == "__main__":

    # Loading a npy file and using trajectorytools normal API
    test_trajectories_file = os.path.join(dir_of_data, "test_trajectories.npy")
    t = np.load(test_trajectories_file, allow_pickle=True)
    tt.interpolate_nans(t)
    t = tt.smooth(t, sigma=0.5)
    s_, v_, a_ = tt.velocity_acceleration(t)

    n = t.shape[1]
    print("Number of fish: ", n)
    n_to_plot = 4

    v = tt.norm(v_)
    a = tt.norm(a_)

    fig, ax_hist = plt.subplots(5)
    for i in range(n_to_plot):
        ax_hist[i].hist(v[:, i])

    e_ = tt.normalise(v_)
    fig, ax = plt.subplots(2)
    for i in range(n_to_plot):
        ax[0].plot(v[:, i])
        ax[1].plot(a[:, i])

    fig, ax_trajectories = plt.subplots()
    for i in range(n_to_plot):
        ax_trajectories.plot(s_[:, i, 0], s_[:, i, 1])
 def distance_to(self, point):
     return tt.norm(self.s - point)
 def acceleration(self):
     return tt.norm(self.a)
Beispiel #11
0
 def displacement_with_gliding(tr, bout, focal):
     return tt.norm(tr.s[bout[2], focal] - tr.s[bout[0], focal])
Beispiel #12
0
 def test_pol_antiparallel(self):
     pol = tt.norm(polarization(self.v_antiparallel))
     assert pytest.approx(pol, 1e-16) == 0
Beispiel #13
0
 def test_parallel(self):
     pol = tt.norm(polarization(self.v_same))
     assert pytest.approx(pol, 1e-16) == 1
Beispiel #14
0
def global_polarization(tr):
    polarization_order_parameter = tt.norm(tt.collective.polarization(tr.e))
    return (polarization_order_parameter)
         trajectories_file_path = '../../data/temp_collective/roi/'+str(i)+'/' +str(j)+'/GS_'+str(j)+'_T_'+str(i)+'_roi_'+str(k+1)+'/trajectories.npy'
     else:
         trajectories_file_path = '../../data/temp_collective/roi/'+str(i)+'/' +str(j)+'/GS_'+str(j)+'_T_'+str(i)+'_roi_'+str(k+1)+'/trajectories_wo_gaps.npy'
     try:
         tr = tt.Trajectories.from_idtrackerai(trajectories_file_path, 		           center=True).normalise_by('body_length')
         tr.new_time_unit(tr.params['frame_rate'], 'seconds')
     except FileNotFoundError:
         print(i,j,k)
         print('File not found')
         continue
      
     average_replicate_speed[k] = np.nanmean(tr.speed)
     average_replicate_acceleration[k] = np.nanmean(tr.acceleration)
     average_replicate_annd[k] = annd(tr)
     average_replicate_spikes[k] = spikes(tr)
     average_replicate_polarization[k] = np.nanmean(tt.norm(tt.collective.polarization(tr.e)))
     difference_total_accurate_replicate[k] = startles_total(tr) - accurate_startles(tr, i, j, k+1)
     average_replicate_latency[k] = latency(tr,i,j,k+1)
     #average_replicate_local_polarization[k] = get_average_local_polarization(tr,1)
     
     
 average_speed[ii,jj] = np.nanmean(average_replicate_speed)
 std_speed[ii,jj] = np.nanstd(average_replicate_speed)
 average_acceleration[ii,jj] = np.nanmean(average_replicate_acceleration)
 std_acceleration[ii,jj] = np.nanstd(average_replicate_acceleration)
 annd_values[ii,jj] = np.nanmean(average_replicate_annd)
 std_annd_values[ii,jj] = np.nanstd(average_replicate_annd)
 spikes_number[ii,jj] = np.nanmean(average_replicate_spikes)
 std_spikes_number[ii,jj] = np.nanstd(average_replicate_spikes)
 polarization[ii,jj] = np.nanmean(average_replicate_polarization)
 std_polarization[ii,jj] = np.nanstd(average_replicate_polarization)
 def speed(self):
     return tt.norm(self.v)
Beispiel #17
0
import os
import numpy as np
import matplotlib as mpl

import trajectorytools as tt
import trajectorytools.plot as ttplot
import trajectorytools.animation as ttanimation
import trajectorytools.socialcontext as ttsocial
from trajectorytools.constants import dir_of_data

if __name__ == '__main__':
    test_trajectories_file = os.path.join(dir_of_data, 'test_trajectories.npy')
    t = np.load(test_trajectories_file)
    tt.center_trajectories_and_normalise(t)
    tt.interpolate_nans(t)
    [s_, v_] = tt.smooth_several(t, derivatives=[0, 1])
    speed = tt.norm(v_)
    colornorm = mpl.colors.Normalize(vmin=speed.min(),
                                     vmax=speed.max(),
                                     clip=True)
    mapper = mpl.cm.ScalarMappable(norm=colornorm, cmap=mpl.cm.hot)
    color = mapper.to_rgba(speed)
    anim1 = ttanimation.scatter_vectors(s_, velocities=v_, k=10)
    anim2 = ttanimation.scatter_ellipses_color(s_, v_, color)

    anim = anim1 + anim2
    anim.prepare()
    anim.show()
Beispiel #18
0
 def displacement(tr, bout, focal):
     return tt.norm(tr.s[bout[1], focal] - tr.s[bout[0], focal])