Example #1
0
def figure1j(info, path):
    if not os.path.exists(path):
        os.makedirs(path)

    fig = plt.figure()
    sessions = info.groupby(level=['subject'])
    xticks = []
    xticklabels = []
    barplotwidth = 4
    for i, (subject, sinfo) in enumerate(sessions):
        subjectpath = os.path.join(activitymovies.datafolder, subject)
        days = sinfo.index.levels[1][sinfo.index.labels[1]]
        act = activitytables.read_subjects(subjectpath, days=days)
        cr = activitytables.read_subjects(subjectpath,
                                          days=days,
                                          selector=activitytables.crossings)
        offset = i * barplotwidth

        stact = act[act.stepstate3]
        stcr = cr[cr.stepstate3]
        stfeatures = activitytables.stepfeature(stact, stcr, 4, 3)
        stskipfrequency = 1 - float(len(stfeatures)) / len(stcr)

        uact = act[~act.stepstate3]
        ucr = cr[~cr.stepstate3]
        ufeatures = activitytables.stepfeature(uact, ucr, 4, 3)
        uskipfrequency = 1 - float(len(ufeatures)) / len(ucr)
        plt.bar((-1 + offset, offset), (stskipfrequency, uskipfrequency),
                color=['b', 'r'],
                width=1,
                hold=True)

        xticks.append(offset)
        xticklabels.append(subject.replace('JPAK_', ''))

    p1 = plt.Rectangle((0, 0), 1, 1, fc="b")
    p2 = plt.Rectangle((0, 0), 1, 1, fc="r")
    plt.legend([p1, p2], ['stable', 'unstable'],
               bbox_to_anchor=(0., 1.02, 1., .102),
               loc=3,
               ncol=2,
               mode="expand",
               borderaxespad=0.)

    plt.xlabel('subject (JPAK)')
    plt.ylabel('p(skipping)')
    plt.xticks(xticks, xticklabels)
    plt.xlim(-2, len(sessions) * barplotwidth - 1)
    #plt.title(str.format('4th step contact frequency',subject))
    fname = str.format("all_animals_4thstep_frequency.png", subject)
    fpath = os.path.join(path, fname)
    plt.savefig(fpath)
    plt.close(fig)
def figure1l(info,path):
    if not os.path.exists(path):
        os.makedirs(path)
        
    sessions = info.groupby(level=['subject'])
    for subject,sinfo in sessions:
        fig = plt.figure()
        subjectpath = os.path.join(activitymovies.datafolder,subject)
        days = sinfo.index.levels[1][sinfo.index.labels[1]]
        act = activitytables.read_subjects(subjectpath,days=days)
        cr = activitytables.read_subjects(subjectpath,days=days,
                                          selector=activitytables.crossings)
        
        axScatter = plt.subplot2grid((3,3),(1,0),rowspan=2,colspan=2)
        axHistx = plt.subplot2grid((3,3),(0,0),colspan=2)
        axHisty = plt.subplot2grid((3,3),(1,2),rowspan=2)
        axes = (axScatter,axHistx,axHisty)
        stepoffset = stepcenter_cm[3][1]
        bins = 50
        xlim = (20-stepoffset,30-stepoffset)
        ylim = (-1,9)
        alpha = 0.75
                                          
        stact = act[act.stepstate3]
        stcr = cr[cr.stepstate3]
        stfeatures = activitytables.stepfeature(stact,stcr,4,3)
        leftwards = stfeatures.side == 'leftwards'
        stfeatures.xhead[leftwards] = max_width_cm - stfeatures.xhead[leftwards]
        stfeatures.xhead -= stepoffset
        activityplots.scatterhist(stfeatures.xhead,stfeatures.yhead,color='b',
                                  bins=bins,axes=axes,xlim=xlim,ylim=ylim,
                                  histalpha=alpha)
        
        uact = act[~act.stepstate3]
        ucr = cr[~cr.stepstate3]
        ufeatures = activitytables.stepfeature(uact,ucr,4,3)
        leftwards = ufeatures.side == 'leftwards'
        ufeatures.xhead[leftwards] = max_width_cm - ufeatures.xhead[leftwards]
        ufeatures.xhead -= stepoffset
        activityplots.scatterhist(ufeatures.xhead,ufeatures.yhead,color='r',
                                  bins=bins,axes=axes,xlim=xlim,ylim=ylim,
                                  histalpha=alpha)
        axScatter.set_xlabel('x (cm)')
        axScatter.set_ylabel('y (cm)')
        axScatter.legend(['stable', 'unstable'],loc=2)
        
        axHistx.set_title(str.format('{0} nose position on contact',subject))
        fname = str.format("{0}_nose_stable_unstable.png",subject)
        fpath = os.path.join(path,fname)
        plt.savefig(fpath)
        plt.close(fig)
def figure1k1(info,path):
    if not os.path.exists(path):
        os.makedirs(path)
        
    sessions = info.groupby(level=['subject','session'])
    for (subject,session),sinfo in sessions:
        subjectpath = os.path.join(activitymovies.datafolder,subject)
        sact = activitytables.read_subjects(subjectpath,days=[session])
        scr = activitytables.read_subjects(subjectpath,days=[session],
                                           selector = activitytables.crossings)
        features = activitytables.stepfeature(sact,scr,4,3)
        leftwards = features.side == 'leftwards'
        features.xhead[leftwards] = max_width_cm - features.xhead[leftwards]
        median = np.sort(features.xhead)[len(features)/2+1]
        median = features[features.xhead == median].iloc[-1,:]
        
        vidpaths = activitymovies.getmoviepath(sinfo)
        timepaths = activitymovies.gettimepath(info)
        movie = [video.video(mpath,mtimepath)
                 for mpath,mtimepath in zip(vidpaths,timepaths)][0]
        medianframe = movie.frame(sact.index.get_loc(median.name))
        flip = median.side == 'rightwards'
        stepindex = 3 if flip else 4
        medianframe = activitytables.cropstep(medianframe,stepindex,flip=flip)
        
        fname = str.format("{0}_session_{1}_median_step_posture.png",
                           subject, session)
        fpath = os.path.join(path,subject)
        if not os.path.exists(fpath):
            os.makedirs(fpath)
        fpath = os.path.join(fpath,fname)
        cv2.imwrite(fpath,medianframe)
def figure1j(info,path):
    if not os.path.exists(path):
        os.makedirs(path)
        
    fig = plt.figure()
    sessions = info.groupby(level=['subject'])
    xticks = []
    xticklabels = []
    barplotwidth = 4
    for i,(subject,sinfo) in enumerate(sessions):
        subjectpath = os.path.join(activitymovies.datafolder,subject)
        days = sinfo.index.levels[1][sinfo.index.labels[1]]
        act = activitytables.read_subjects(subjectpath,days=days)
        cr = activitytables.read_subjects(subjectpath,days=days,
                                          selector=activitytables.crossings)
        offset = i * barplotwidth
                                          
        stact = act[act.stepstate3]
        stcr = cr[cr.stepstate3]
        stfeatures = activitytables.stepfeature(stact,stcr,4,3)
        stskipfrequency = 1 - float(len(stfeatures)) / len(stcr)
        
        uact = act[~act.stepstate3]
        ucr = cr[~cr.stepstate3]
        ufeatures = activitytables.stepfeature(uact,ucr,4,3)
        uskipfrequency = 1 - float(len(ufeatures)) / len(ucr)
        plt.bar((-1 + offset,offset),(stskipfrequency,uskipfrequency),
                color=['b','r'],width=1,hold=True)
        
        xticks.append(offset)
        xticklabels.append(subject.replace('JPAK_',''))

    p1 = plt.Rectangle((0, 0), 1, 1, fc="b")
    p2 = plt.Rectangle((0, 0), 1, 1, fc="r")
    plt.legend([p1,p2],['stable', 'unstable'],
               bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
               ncol=2, mode="expand", borderaxespad=0.)
    
    plt.xlabel('subject (JPAK)')
    plt.ylabel('p(skipping)')
    plt.xticks(xticks,xticklabels)
    plt.xlim(-2,len(sessions) * barplotwidth - 1)
    #plt.title(str.format('4th step contact frequency',subject))
    fname = str.format("all_animals_4thstep_frequency.png",subject)
    fpath = os.path.join(path,fname)
    plt.savefig(fpath)
    plt.close(fig)
def __getclips__(act,cr,info,rowidx=slice(None)):
    features = []
    moviepath = activitymovies.getmoviepath(info)
    for (subject,session),group in cr.groupby(level=['subject','session']):
        steps = activitytables.stepfeature(act,group,4,3).iloc[rowidx,:]
        steps['subject'] = subject
        steps['session'] = session
        steps.reset_index(inplace=True)
        steps.set_index(['subject','session'],inplace=True)
        features.append(steps[['frame','side']].join(moviepath))
    return pd.concat(features)
Example #6
0
def __getclips__(act, cr, info, rowidx=slice(None)):
    features = []
    moviepath = activitymovies.getmoviepath(info)
    for (subject, session), group in cr.groupby(level=['subject', 'session']):
        steps = activitytables.stepfeature(act, group, 4, 3).iloc[rowidx, :]
        steps['subject'] = subject
        steps['session'] = session
        steps.reset_index(inplace=True)
        steps.set_index(['subject', 'session'], inplace=True)
        features.append(steps[['frame', 'side']].join(moviepath))
    return pd.concat(features)
Example #7
0
def figure2e(act, cr, rr, info, path):
    if not os.path.exists(path):
        os.makedirs(path)

    features = []
    cr = cr[cr.stepstate3 == False]
    for (subject, session), group in cr.groupby(level=['subject', 'session']):
        #step = activitytables.stepframeindices(act,group,4,3)
        step = activitytables.stepfeature(act, group, 4, 3).iloc[0:1, :]
        step['subject'] = subject
        step['session'] = session
        step.reset_index(inplace=True)
        step.set_index(['subject', 'session'], inplace=True)
        steprr = step.join(rr, rsuffix='reward')
        timetoreward = steprr.timereward - steprr.time
        timetoreward = timetoreward[timetoreward > 0]
        features.append((subject, timetoreward.min()))

    fig = plt.figure()
    n = [(m[1].values[0] /
          np.timedelta64(1, 's') if m[1] is not np.nan else np.nan, m[0], 5)
         for m in features]
    data = pd.DataFrame(n, columns=['timetoreward', 'subject', 'session'])
    data.set_index(['subject', 'session'], inplace=True)
    result = activitytables.groupbylesionvolumes(data, info)

    ncontrols = sum((1 for m in result.index.labels[1] if m == 0))
    nlesions = sum((1 for m in result.index.labels[1] if m == 1))
    clabels = ['C' + chr(ord('a') + i) for i in range(ncontrols)]
    llabels = ['L' + chr(ord('a') + i) for i in range(nlesions)]

    plt.bar(range(len(result)),
            result.timetoreward,
            color=['b'] * 11 + ['r'] * 11)
    plt.xlim(-1, len(result) + 1)
    plt.xticks(np.arange(len(result)) + 0.4, clabels + llabels)
    plt.xlabel('subject')
    plt.ylabel('time to reward (s)')
    plt.title('time to first reward after manipulation')
    p1 = plt.Rectangle((0, 0), 1, 1, fc="b")
    p2 = plt.Rectangle((0, 0), 1, 1, fc="r")
    plt.legend([p1, p2], ['control', 'lesion'])

    fname = str.format("manipulation_first_reward_time.png", subject)
    fpath = os.path.join(path, fname)
    plt.savefig(fpath)
    plt.close(fig)
def figure2e(act,cr,rr,info,path):
    if not os.path.exists(path):
        os.makedirs(path)
        
    features = []
    cr = cr[cr.stepstate3 == False]
    for (subject,session),group in cr.groupby(level=['subject','session']):
        #step = activitytables.stepframeindices(act,group,4,3)
        step = activitytables.stepfeature(act,group,4,3).iloc[0:1,:]
        step['subject'] = subject
        step['session'] = session
        step.reset_index(inplace=True)
        step.set_index(['subject','session'],inplace=True)
        steprr = step.join(rr,rsuffix='reward')
        timetoreward = steprr.timereward - steprr.time
        timetoreward = timetoreward[timetoreward > 0]
        features.append((subject,timetoreward.min()))
        
    fig = plt.figure()        
    n = [(m[1].values[0]/np.timedelta64(1,'s') if m[1] is not np.nan else np.nan,
          m[0],5) for m in features]
    data = pd.DataFrame(n,columns=['timetoreward','subject','session'])
    data.set_index(['subject','session'],inplace=True)
    result = activitytables.groupbylesionvolumes(data,info)
    
    ncontrols = sum((1 for m in result.index.labels[1] if m == 0))
    nlesions = sum((1 for m in result.index.labels[1] if m == 1))
    clabels = ['C' + chr(ord('a') + i) for i in range(ncontrols)]
    llabels = ['L' + chr(ord('a') + i) for i in range(nlesions)]
    
    plt.bar(range(len(result)),result.timetoreward,color=['b']*11 + ['r']*11)
    plt.xlim(-1,len(result) + 1)
    plt.xticks(np.arange(len(result)) + 0.4,clabels+llabels)
    plt.xlabel('subject')
    plt.ylabel('time to reward (s)')
    plt.title('time to first reward after manipulation')
    p1 = plt.Rectangle((0, 0), 1, 1, fc="b")
    p2 = plt.Rectangle((0, 0), 1, 1, fc="r")
    plt.legend([p1,p2],['control', 'lesion'])
    
    fname = str.format("manipulation_first_reward_time.png",subject)
    fpath = os.path.join(path,fname)
    plt.savefig(fpath)
    plt.close(fig)
Example #9
0
def figure1k1(info, path):
    if not os.path.exists(path):
        os.makedirs(path)

    sessions = info.groupby(level=['subject', 'session'])
    for (subject, session), sinfo in sessions:
        subjectpath = os.path.join(activitymovies.datafolder, subject)
        sact = activitytables.read_subjects(subjectpath, days=[session])
        scr = activitytables.read_subjects(subjectpath,
                                           days=[session],
                                           selector=activitytables.crossings)
        features = activitytables.stepfeature(sact, scr, 4, 3)
        leftwards = features.side == 'leftwards'
        features.xhead[leftwards] = max_width_cm - features.xhead[leftwards]
        median = np.sort(features.xhead)[len(features) / 2 + 1]
        median = features[features.xhead == median].iloc[-1, :]

        vidpaths = activitymovies.getmoviepath(sinfo)
        timepaths = activitymovies.gettimepath(info)
        movie = [
            video.video(mpath, mtimepath)
            for mpath, mtimepath in zip(vidpaths, timepaths)
        ][0]
        medianframe = movie.frame(sact.index.get_loc(median.name))
        flip = median.side == 'rightwards'
        stepindex = 3 if flip else 4
        medianframe = activitytables.cropstep(medianframe,
                                              stepindex,
                                              flip=flip)

        fname = str.format("{0}_session_{1}_median_step_posture.png", subject,
                           session)
        fpath = os.path.join(path, subject)
        if not os.path.exists(fpath):
            os.makedirs(fpath)
        fpath = os.path.join(fpath, fname)
        cv2.imwrite(fpath, medianframe)
Example #10
0
def figure1l(info, path):
    if not os.path.exists(path):
        os.makedirs(path)

    sessions = info.groupby(level=['subject'])
    for subject, sinfo in sessions:
        fig = plt.figure()
        subjectpath = os.path.join(activitymovies.datafolder, subject)
        days = sinfo.index.levels[1][sinfo.index.labels[1]]
        act = activitytables.read_subjects(subjectpath, days=days)
        cr = activitytables.read_subjects(subjectpath,
                                          days=days,
                                          selector=activitytables.crossings)

        axScatter = plt.subplot2grid((3, 3), (1, 0), rowspan=2, colspan=2)
        axHistx = plt.subplot2grid((3, 3), (0, 0), colspan=2)
        axHisty = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
        axes = (axScatter, axHistx, axHisty)
        stepoffset = stepcenter_cm[3][1]
        bins = 50
        xlim = (20 - stepoffset, 30 - stepoffset)
        ylim = (-1, 9)
        alpha = 0.75

        stact = act[act.stepstate3]
        stcr = cr[cr.stepstate3]
        stfeatures = activitytables.stepfeature(stact, stcr, 4, 3)
        leftwards = stfeatures.side == 'leftwards'
        stfeatures.xhead[
            leftwards] = max_width_cm - stfeatures.xhead[leftwards]
        stfeatures.xhead -= stepoffset
        activityplots.scatterhist(stfeatures.xhead,
                                  stfeatures.yhead,
                                  color='b',
                                  bins=bins,
                                  axes=axes,
                                  xlim=xlim,
                                  ylim=ylim,
                                  histalpha=alpha)

        uact = act[~act.stepstate3]
        ucr = cr[~cr.stepstate3]
        ufeatures = activitytables.stepfeature(uact, ucr, 4, 3)
        leftwards = ufeatures.side == 'leftwards'
        ufeatures.xhead[leftwards] = max_width_cm - ufeatures.xhead[leftwards]
        ufeatures.xhead -= stepoffset
        activityplots.scatterhist(ufeatures.xhead,
                                  ufeatures.yhead,
                                  color='r',
                                  bins=bins,
                                  axes=axes,
                                  xlim=xlim,
                                  ylim=ylim,
                                  histalpha=alpha)
        axScatter.set_xlabel('x (cm)')
        axScatter.set_ylabel('y (cm)')
        axScatter.legend(['stable', 'unstable'], loc=2)

        axHistx.set_title(str.format('{0} nose position on contact', subject))
        fname = str.format("{0}_nose_stable_unstable.png", subject)
        fpath = os.path.join(path, fname)
        plt.savefig(fpath)
        plt.close(fig)