soft-matter / trackpy

Python particle tracking toolkit
http://soft-matter.github.io/trackpy
Other
443 stars 131 forks source link

Feature request: Filter tracks by x or y displacement #713

Closed Rory235 closed 1 year ago

Rory235 commented 1 year ago

I have a series of tracks in my data set that are perfectly straight due to some bypass flow.

It would be great if I could filter the tracks based on the displacement in the x and/or y axis, either on a frame by frame basis, or the total track length.

Rory235 commented 1 year ago

Think I might be able to do this with Pandas and NumPy, will update if I can

Rory235 commented 1 year ago

Filtering by gradient doesn't work, going to try 2D tortuosity.

Rory235 commented 1 year ago

So this bit of code can be used to filter tracks based on the tortuoisity (a measure of how wiggly the line is)

for k in table0.particle.drop_duplicates():
    # Extract lines related to particle #k
    subdf = table0[table0.particle == k].copy()
    # Add columns containing operands of the curve lenght calculation
    subdf['Sum_y'] = subdf['y'].shift(-1) - subdf['y']
    subdf['Sum_x'] = subdf['x'].shift(-1) - subdf['x']
    subdf['y^2'] = subdf['Sum_y'] * subdf['Sum_y']
    subdf['x^2'] = subdf['Sum_x'] * subdf['Sum_x']
    subdf['x+y'] = subdf['x^2'] + subdf['y^2']
    subdf['segment_length']= subdf['x+y'] ** (0.5)
    # Calculate curve lenght
    table0.loc[table0.particle == k, "curved_length"] = subdf['segment_length'].sum()
    # Extract first and last lines (test)
    start_x = subdf.iloc[0].at["x"]
    start_y = subdf.iloc[0].at["y"]
    end_x = subdf.iloc[-1].at["x"]
    end_y = subdf.iloc[-1].at["y"]
    distance = (((end_y - start_y)**2 + (end_x - start_x)**2) ** 0.5)
    table0.loc[table0.particle == k, "distance"] = distance
table0["tortuoisty"] = table0["curved_length"] / table0["distance"]
table1 = table0[(table0['tortuoisty'] >= 1.5)]
nkeim commented 1 year ago

Thanks for sharing the solution to this problem! It's great to have more examples of how to work with trajectory data using Pandas.