#!/usr/bin/env python
# encoding=utf-8

# named sting because: if you're a cell,
# every breath you take, every step you make,
# we'll be watching you
# © tim smith 2014, tim.smith@uci.edu
# released under the terms of the wtfpl http://wtfpl.net

import pandas as pd
from StringIO import StringIO
import ggplot as gg

def read_mtrack2(filename):
    with open(filename) as f:
        buf = f.readlines()
    if '\n' in buf:
    	# there might be an extra table at the end that we don't care about
    	buf = buf[:buf.index('\n')]
    buf = ''.join(buf)
    iobuf = StringIO(buf)
    # row 0 is headers and data starts on row 2 so skip row 1
    df = pd.read_csv(iobuf, sep='\t', skiprows=[1])
    # df.replace(to_replace=' ', value=float('NaN'), inplace=True)
    df = df.convert_objects(convert_numeric=True)
    return df

def displacement_plot(df):
    # throw out flag columns
    df = df[df.columns[[not i.startswith('Flag') for i in df.columns]]]
    # fill NA's backwards and then forwards
    df.bfill(inplace=True)
    df.ffill(inplace=True)
    # get X and Y columns
    melted = pd.melt(df, id_vars='Frame')
    melted['Axis'] = melted['variable'].apply(lambda x: x[0])
    melted['Object'] = melted['variable'].apply(lambda x: int(x[1:]))
    df = melted.groupby(['Object', 'Frame', 'Axis']).sum().unstack()['value']
    df = df.reset_index()
    # df.to_csv('intermediate.csv', index_label=False)
    def center_transform(x):
        mydf = x.copy()
        mydf['cX'] = x['X'] - x['X'].iloc[0]
        mydf['cY'] = x['Y'] - x['Y'].iloc[0]
        return mydf
    centered = df.groupby('Object').apply(center_transform)
    centered['cY'] = -centered['cY']
    centered['Object'] = centered['Object'].map(str)

    g = gg.ggplot(centered, gg.aes(x='cX', y='cY', color='Object')) + gg.geom_line()

    return g

def save_plot(tsv_in, png_out):
    df = read_mtrack2(tsv_in)
    g = displacement_plot(df)
    gg.ggsave(g, png_out)

if __name__ == '__main__':
    import sys
    save_plot(sys.argv[1], sys.argv[1] + '.png')


@@ -807,50 +807,8 @@
 ue)%0A
-    return df%0A%0Adef displacement_plot(df):%0A
     
@@ -1314,124 +1314,391 @@
     
-# df.to_csv('intermediate.csv', index_label=False)%0A    def center_transform(x):%0A        mydf = x.copy()%0A        mydf
+return df%0A%0Adef read_manual_track(filename):%0A    df = pd.read_csv(filename, sep='%5Ct', encoding='mac-roman')%0A    df.rename(columns=%7Bu'Track n%C2%B0': 'Object',%0A                       u'Slice n%C2%B0': 'Frame'%7D,%0A              inplace=True)%0A    for col in %5B'Object', 'Frame'%5D:%0A        df%5Bcol%5D = df%5Bcol%5D.astype(int)%0A    print df%0A    return df%0A%0Adef center(df):%0A    def center_transform(x):%0A        x
 %5B'cX
@@ -1734,20 +1734,17 @@
         
-mydf
+x
 %5B'cY'%5D =
@@ -1787,12 +1787,9 @@
 urn 
-mydf
+x
 %0A   
@@ -1890,57 +1890,160 @@
     
-centered%5B'Object'%5D = centered%5B'Object'%5D.map(str)%0A
+return centered%0A%0Adef displacement_plot(centered):%0A    centered%5B'Object'%5D = centered%5B'Object'%5D.map(str)%0A    centered = centered.sort(%5B'Frame', 'Object'%5D)
 %0A   
@@ -2121,16 +2121,15 @@
 eom_
-line
+path
 ()%0A
-%0A
     
@@ -2170,16 +2170,29 @@
 g_out):%0A
+    try:%0A    
     df =
@@ -2213,16 +2213,145 @@
 tsv_in)%0A
+    except Exception:%0A        df = read_manual_track(tsv_in)%0A    centered = center(df)%0A    centered.to_csv(tsv_in + '.centered')%0A
     g = 
@@ -2368,18 +2368,24 @@
 nt_plot(
+centere
 d
-f
 )%0A    gg

Add manual tracking support, refactor plots