def roi_barplot(mask, mask_name, contrasts, labels, results_path, title_extra=''):
    roi_data = pd.DataFrame(np.zeros(shape=(mask.sum(), len(contrasts))),
                            columns=labels)
    for idx, img in enumerate([contrast_path.format(c) for c in contrasts]):
        roi_data[labels[idx]] = rm.extract_data_in_mask(img, mask)
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    fig.suptitle(mask_name+'\n'+title_extra)
    sns.barplot(data=roi_data, ax=ax)
    fig.savefig(os.path.join(results_path, mask_name+'.png'))
    plt.close()
def roi_histogram(mask, mask_name, imgs, results_path, title_extra=''):
    roi_data = []
    for idx, img in enumerate(imgs):
        roi_data.append(rm.extract_data_in_mask(img, mask))
    roi_data = np.concatenate(roi_data)

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    fig.suptitle(mask_name+'\n'+title_extra)
    sns.distplot(roi_data, ax=ax)
    fig.savefig(os.path.join(results_path, mask_name+'.png'))
    plt.close()
def roi_statistical_model(mask, mask_name, contrasts, labels, factors,
                          results_path, model_desc):
    # factors should be a pandas dataframe with named columns
    # factors correspond to labels by idx
    roi_data = pd.DataFrame(np.zeros(shape=(mask.sum()*len(contrasts),
                                            len(factors.columns)+3)),
                            columns=['condition']+factors.columns.tolist() + \
                                    ['voxel', 'beta']
                           )
    counter = 0
    print 'preparing data in ' + mask_name
    for idx, img in enumerate([contrast_path.format(c) for c in contrasts]):
        data_cat = [labels[idx]] + factors.loc[idx].tolist()
        for v_idx, beta in enumerate(rm.extract_data_in_mask(img, mask)):
            row = data_cat + [v_idx, beta[0]]
            roi_data.loc[counter] = row
            counter += 1
    print 'computing model: ' + model_desc + ' in ' + mask_name
    regress = sm.ols(model_desc, data=roi_data).fit()
    f = open(os.path.join(results_path, mask_name+'.txt'), 'w')
    f.write(regress.summary().as_text())
    f.close()
    contrasts = [20, 40]

    assert(len(contrasts) == len(labels))
    gm_img = os.path.join('pipelines', 'preprocessing', subject,
                          'highres001_graymatter_mask_bold_native.nii')
    gm_mask = rm.get_roi_mask(gm_img)
    diff_map = contrast_path.format(40)
    inter_map = contrast_path.format(20)
    df2 = 219*8 - 32
    pedges = [1, 0.01, 0.009, 0.008, 0.007, 0.006, 0.005, 0.004, 0.003, 0.002, 0.001, 0]
    pedges.reverse()
    for roi in rm.get_rois_mask_in_native_space(sub_id):
        if not os.path.exists(os.path.join(results_path, *roi[2])):
            os.makedirs(os.path.join(results_path, *roi[2]))
        gm_adj_roi = gm_mask * roi[0]
        diff = np.ravel(rm.extract_data_in_mask(diff_map, gm_adj_roi))
        inter = np.ravel(rm.extract_data_in_mask(inter_map, gm_adj_roi))
        diffp = [-np.log10(sst.f.sf(x, 15, df2)) for x in diff]
        interp = [-np.log10(sst.f.sf(x, 9, df2)) for x in inter]
        # fig = plt.figure()
        # ax = fig.add_subplot(111)
        extra_text = str([math.ceil(x) for x in rm.get_roi_center(roi[3], roi[4])[3]])
        g = sns.jointplot(x=np.array(diffp), y=np.array(interp), kind='scatter', stat_func=None, xlim=(0,np.max(diffp)+1), ylim=(0,np.max(interp)+1)).set_axis_labels("-log10(p_value) number difference", "-log10(p_value) interaction")
        # , xlim=(0,1), ylim=(0,1)
        # plt.show()

        # H, xedges, yedges = np.histogram2d(interp, diffp, bins=(pedges, pedges),
        #                                    normed=False)
        # fig = plt.figure()
        # ax = fig.add_subplot(111)
        extra_text = str([math.ceil(x) for x in rm.get_roi_center(roi[3], roi[4])[3]])