# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: py36
#     language: python
#     name: py36
# ---

import argparse
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import re
from matplotlib.backends.backend_pdf import PdfPages

parser = argparse.ArgumentParser()
parser.add_argument('infile', type=str)



# ## Import data
# The test data was exported from FlowJo v9 table editor using the "Save" button to save as a tab-delimited text file. TSV is necessary in this case, because FlowJo uses commas in the gate descriptions.

df = pd.read_table(filepath_or_buffer="jw112_cytokine_test.tsv", encoding="mac_roman")

# **Note:** There is an import error when encoding is not specified - changing the encoding to `"mac_roman"` within the `pd.read_table()` call allowed import, but might not be applicable to all platforms. It might be useful to include an encoding conversion step using something like `chardet`.

# Drop mean and standard deviation rows
df = df.drop(df.tail(2).index)

# ## Add grouping variables as new column(s)
# I will try to add grouping variables using a function to repeat a sequence of strings and add as a new column.

genotypes = ['KO', 'WT', 'KO', 'WT', 'KO']
organs = ["Spleen", "PP", "coLP"]

df.insert(1, "genotype", np.tile(genotypes, 3))
df.insert(2, "organ", np.repeat(organs, 5))

df.tail()


# ## Reformat column names to remove leading gate hierarchy
# We want to leave only the current and parent gates, which is basically everything to the right of the second-to-last "/" in the name. It should be easy enough to trim this with regex.

def trimColnameDepth(df, pattern=None):
    '''Trim column names according to a regex pattern. 
    Returns the first match to the regex as a list of new column names.
    If no match, returns unaltered column name.'''
    trimmed = []
    if not pattern: # Default pattern if none provided
        pattern = re.compile(r"\/([^\/]+\/[^\/]+$)")
    for c in df.columns:
        match = pattern.search(c) # Look for a match to the pattern
        if match:
            trimmed.append(match.group(1))
        else:
            trimmed.append(c)
    return(trimmed)


def regexDepth(d):
    '''Generates a regex pattern to trim gating paths to a specified depth d.'''
    string = "[^\/]+$" # Default pattern, depth 0
    unit = "[^\/]+\/" # Incremental unit of depth to add to regex
    if d == 0:
        return(re.compile("\/(" + string + ")"))
    else:
        return(re.compile("\/(" + "".join(np.repeat(unit, d)) + string + ")"))


df.columns = trimColnameDepth(df, regexDepth(1))

# ## Plot some data
# This is a simple test of what the plots should hopefully look like.

np.sort(df['genotype'].unique())

g = sns.catplot(data=df, x="organ", y="Q5: IL-13–, IL-4+,Freq. of Parent", 
             hue="genotype", hue_order=["WT", "KO"], dodge=True, kind="bar",
               linewidth=1.5, facecolor=(1, 0, 1, 0),
                 errcolor=".2", edgecolor="0.2",
               capsize=0.2, ci="sd", legend=False)
sns.swarmplot(data=df, x="organ", y="Q5: IL-13–, IL-4+,Freq. of Parent", 
             hue="genotype", hue_order=["WT", "KO"], dodge=True, s=8, ax=g.ax)
plt.show()

# Here I've used matplotlib's `PdfPages` to output a graph of every parameter into 2x2 grids on a landscape letter-size PDF page. Works pretty well! Still need to figure out how to remove the legend for the barplots, since it's redundant with the 

## Output 4 plots per 8.5 x 11 page in landscape
with PdfPages("test.pdf") as pdf:
    ppp = 4 # Plots per page
    for i, var in enumerate(df.columns[3:]):
        if i % ppp == 0:
            fig = plt.figure(figsize=(11, 8.5), dpi=100)
            fig.subplots_adjust(hspace=0.3)
            ax = fig.add_subplot(2, 2, i % ppp + 1)
        else:
            ax = fig.add_subplot(2, 2, i % ppp + 1) 
        sns.catplot(data=df, x="organ", y=var, 
                 hue="genotype", hue_order=np.sort(df['genotype'].unique()), dodge=True, kind="bar",
                   linewidth=1.5, facecolor=(1, 0, 1, 0),
                     errcolor=".2", edgecolor="0.5",
                    errwidth=1.5,
                   capsize=0.2, ci="sd", ax=ax, legend=False)
        ax.legend()
        sns.swarmplot(data=df, x="organ", y=var, 
                 hue="genotype", hue_order=np.sort(df['genotype'].unique()), dodge=True, s=8, ax=ax)
        ax.set_title(var)
        if (i+1) % ppp == 0:
            pdf.savefig(fig)
            plt.close()
        else:
            plt.close()
    if (i+1) % ppp != 0:
        pdf.savefig(fig)


def makePlots(df, filename):
    with PdfPages(filename) as pdf:
    ppp = 4 # Plots per page
    for i, var in enumerate(df.columns[3:]):
        if i % ppp == 0:
            fig = plt.figure(figsize=(11, 8.5), dpi=100)
            fig.subplots_adjust(hspace=0.3)
            ax = fig.add_subplot(2, 2, i % ppp + 1)
        else:
            ax = fig.add_subplot(2, 2, i % ppp + 1) 
        sns.catplot(data=df, x="organ", y=var, 
                 hue="genotype", dodge=True, kind="bar",
                   linewidth=1.5, facecolor=(1, 0, 1, 0),
                     errcolor=".2", edgecolor="0.5",
                    errwidth=1.5,
                   capsize=0.2, ci="sd", ax=ax, legend=False)
        ax.legend()
        sns.swarmplot(data=df, x="organ", y=var, 
                 hue="genotype", dodge=True, s=8, ax=ax)
        ax.set_title(var)
        if (i+1) % ppp == 0:
            pdf.savefig(fig)
            plt.close()
        else:
            plt.close()
    if (i+1) % ppp != 0:
        pdf.savefig(fig)

StarcoderdataJupyterScriptsDedupFiltered