Exemple #1
0
def Fig2():
    fig = plt.figure()

    path_006 = mydir + '/data/Box1Fig/Sample_006/'
    path_012 = mydir + '/data/Box1Fig/Sample_012/'
    path_264 = mydir + '/data/Box1Fig/Sample_264/'
    plate_006 = FCPlate.from_dir(ID='Demo Plate', path = path_006, parser='name')
    plate_012 = FCPlate.from_dir(ID='Demo Plate', path = path_012, parser='name')
    plate_264 = FCPlate.from_dir(ID='Demo Plate', path = path_264, parser='name')
    plate_006 = plate_006.dropna()
    plate_012 = plate_012.dropna()
    plate_264 = plate_264.dropna()
    plate_006 = plate_006.transform('hlog', channels=['FSC-A', 'SSC-A', \
        'FSC PMT-A','PI (YG)-A', 'FITC-A', 'Pacific Blue-A', 'APC-A'])
    plate_012 = plate_012.transform('hlog', channels=['FSC-A', 'SSC-A', \
        'FSC PMT-A','PI (YG)-A', 'FITC-A', 'Pacific Blue-A', 'APC-A'])
    plate_264 = plate_264.transform('hlog', channels=['FSC-A', 'SSC-A', \
        'FSC PMT-A','PI (YG)-A', 'FITC-A', 'Pacific Blue-A', 'APC-A'])
    threshold_006 = getDAPIgate(plate_006)
    threshold_012 = getDAPIgate(plate_012)
    threshold_264 = getDAPIgate(plate_264)
    gate_006 = ThresholdGate(threshold_006, 'Pacific Blue-A', region='above')
    gate_012 = ThresholdGate(threshold_012, 'Pacific Blue-A', region='above')
    gate_264 = ThresholdGate(threshold_264, 'Pacific Blue-A', region='above')
    gated_sample_006 = plate_006['A8'].gate(gate_006)
    gated_sample_012 = plate_012['A8'].gate(gate_012)
    gated_sample_264 = plate_264['A8'].gate(gate_264)
    RSG_006 = gated_sample_006.data[['FITC-A']].values
    RSG_012 = gated_sample_012.data[['FITC-A']].values
    RSG_264 = gated_sample_264.data[['FITC-A']].values
    #colors = ['#FF6347', '#FFA500', '#87CEEB']

    plt.hist(RSG_006, 40, fc='#87CEEB', histtype='bar', alpha=0.5, normed=True)
    plt.hist(RSG_012, 40, fc='#FFA500', histtype='bar', alpha=0.5, normed=True)
    plt.hist(RSG_264, 40, fc='#FF6347', histtype='bar', alpha=0.5, normed=True)

    plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
    #plt.title('The distribution of reductase \n acivity in a microbial population', \
    #    fontsize = 20, weight = 'heavy')
    plt.xlabel('Metabolic activity', fontsize = 18)
    plt.ylabel('Frequency', fontsize = 18)
    plt.arrow(2500, 0.00075, 3400, 0, width=0.00004, \
        head_width=0.00012, head_length=450,  length_includes_head=True, \
        shape='full', color = '#87CEEB')
    plt.arrow(5350, 0.00064, -3400, 0, width=0.00004, \
        head_width=0.00012, head_length=450,  length_includes_head=True, \
        shape='full', color = '#FF6347')

    plt.xlim(0, 8000)
    plt.ylim(0, 0.001)
    fig.tight_layout()
    plt.gca().invert_xaxis()
    plt.text(4800, 0.00055 , 'Initiation', color = '#FF6347', fontsize = 18, weight = 'heavy')
    plt.text(5050, 0.0008, 'Resucitation', color = '#87CEEB', fontsize = 18, weight = 'heavy')
    fig_name = mydir + '/figures/Fig2.png'
    fig.savefig(fig_name, bbox_inches = "tight", pad_inches = 0.4, dpi = 600)
    plt.close()
Exemple #2
0
def get_dist_data():
    makeFigFolders(analysis = 'RSG')
    OUT1 = open(git_path +'/data/FlowSummary.txt', 'w+')
    print>> OUT1, 'Sample', 'Mean', 'Std', 'Median', 'Skew'
    for sample in samples:
        sample_name = 'Sample_' + sample
        path = data_path + 'Sample_' + sample + '/'
        files = os.listdir(path)
        remove = ['misc', '.DS_Store']
        files1 = [i for i in files if i not in remove]
        files_split = [re.split(r'[._]',x)[3] for x in files1]

        path = data_path + 'Sample_' + sample + '/'
        plate = FCPlate.from_dir(ID='Demo Plate', path = path, parser='name')
        plate = plate.dropna()
        plate = plate.transform('hlog', channels=['FSC-A', 'SSC-A', \
            'FSC PMT-A','PI (YG)-A', 'FITC-A', 'Pacific Blue-A', 'APC-A'])
        DAPI_threshold = getDAPIgate(plate)
        DAPI_gate = ThresholdGate(DAPI_threshold, 'Pacific Blue-A', region='above')
        intersection_gate = DAPI_gate
        DAPI_gated_A9 = plate['A8'].gate(intersection_gate)
        # RSG
        RSG = DAPI_gated_A9.data[['FITC-A']].values

        print>> OUT1, sample_name, str(np.mean(RSG)), str(np.std(RSG)), \
            str(np.median(RSG)), str(stats.skew(RSG)[0])

    OUT1.close()
Exemple #3
0
def get_RSG_movie():
    # Set up formatting for the movie files
    Writer = animation.writers['ffmpeg']
    writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
    number_of_frames = len(samples)
    for sample in samples:
        print sample
        path = data_path + 'Sample_' + sample + '/'
        plate = FCPlate.from_dir(ID='Demo Plate', path = path, parser='name')
        plate = plate.dropna()
        plate = plate.transform('hlog', channels=['FSC-A', 'SSC-A', \
            'FSC PMT-A','PI (YG)-A', 'FITC-A', 'Pacific Blue-A', 'APC-A'])
        threshold = getDAPIgate(plate)
        gate = ThresholdGate(threshold, 'Pacific Blue-A', region='above')
        gated_sample = plate['A8'].gate(gate)
        RSG = gated_sample.data[['FITC-A']].values


        l, = plt.plot([], [], 'r-')
        plt.xlim(0, 1)
        plt.ylim(0, 1)
        plt.xlabel('x')
        plt.title('test')
        line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l),
                                           interval=50, blit=True)
        line_ani.save('lines.mp4', writer=writer)


        def update_hist(num, data):
            plt.cla()
            plt.hist(data[num])

        fig = plt.figure()
        hist = plt.hist(RSG, 30, fc='gray', histtype='stepfilled', alpha=0.3, normed=True)
Exemple #4
0
def gating(cell_type, date=False, Mut=False, rep=0):
    """ Creates and returns the cell type gate on CD4+ cells. """
    if not Mut:
        cell1 = QuadGate(vert[cell_type][0],
                         channels[cell_type],
                         region=regionSpec[cell_type][0],
                         name=(cell_type + "1"))
        cell2 = QuadGate(vert[cell_type][1],
                         channels[cell_type],
                         region=regionSpec[cell_type][1],
                         name=(cell_type + "2"))
    else:
        cell1 = import_gates_pSTAT(date, cell_type, rep)
    if regionSpec_[cell_type] is not None:
        cd45 = ThresholdGate(6300, ("BL3-H"),
                             region=regionSpec_[cell_type],
                             name="cd45")
        gate = cell1 & cell2 & cd4() & cd45
    else:
        if cell_type in ("nk", "nkt", "bnk", "cd"):
            if Mut:
                gate = cell1
            else:
                gate = cell1 & cell2
        else:
            if Mut:
                gate = cell1 & cd4monMut()
            else:
                gate = cell1 & cell2 & cd4()
    return gate
Exemple #5
0
    def threshold_gate(self, channel_name=''):
        if not channel_name:
            channel_name = self.channel_names[0]

        # Check if file already exists
        if CHECK_IF_FILE_EXIST:
            if self.check_if_images_exist('threshold_gate'):
                return True

        # Create a threshold gates
        y2_gate = ThresholdGate(1000.0, channel_name, region='above')

        # Gate
        gated_sample = self.sample.gate(y2_gate)

        # Plot
        ax1 = subplot(121)
        self.sample.plot(channel_name,
                         gates=[y2_gate],
                         bins=self.bins,
                         alpha=0.9)
        y2_gate.plot(color='k', linewidth=4, linestyle='-')
        title('Original Sample')

        ax2 = subplot(122, sharey=ax1, sharex=ax1)
        gated_sample.plot(channel_name,
                          gates=[y2_gate],
                          bins=self.bins,
                          color='y',
                          alpha=0.9)
        title('Gated Sample')

        tight_layout()
        png_file = os.path.join(SHARED_PLOTTING_DIR,
                                self.get_file_name('threshold_gate.png'))
        print(png_file)
        grid(True)
        savefig(png_file)
        self.response['threshold_gate'] = self.get_file_name(
            'threshold_gate.png')
Exemple #6
0
    def plate_gated_median_fluorescence(self,
                                        channel_name1='',
                                        channel_name2=''):
        if not channel_name1:
            channel_name1 = self.channel_names[0]
            channel_name2 = self.channel_names[1]

        # Check if file already exists
        if CHECK_IF_FILE_EXIST:
            if self.check_if_images_exist('plate_gated_median_fluorescence'):
                return True

        # Load plate
        plate = FCPlate.from_dir(ID='Demo Plate',
                                 path=SHARED_RAW_DIR,
                                 parser='name')
        plate = plate.transform('hlog',
                                channels=[channel_name1, channel_name2],
                                b=500.0)

        # Clear prev sub plot
        subplots(clear=True)

        # Drop empty cols / rows
        plate = plate.dropna()

        # Create a threshold gates
        y2_gate = ThresholdGate(1000.0, channel_name1, region='above')

        # Plot
        plate = plate.gate(y2_gate)

        output = plate.apply(self.__calculate_median_Y2)

        plot_heat_map(output,
                      include_values=True,
                      show_colorbar=True,
                      cmap=cm.Reds)
        title('Heat map of median RFP fluorescence on plate')

        png_file = os.path.join(
            SHARED_PLOTTING_DIR,
            self.get_file_name('plate_gated_median_fluorescence.png'))
        print(png_file)
        grid(False)
        savefig(png_file)
        self.response['plate_gated_median_fluorescence'] = self.get_file_name(
            'plate_gated_median_fluorescence.png')
Exemple #7
0
    def plate_gated_counts(self, channel_name1='', channel_name2=''):
        if not channel_name1:
            channel_name1 = self.channel_names[0]
            channel_name2 = self.channel_names[1]

        # Check if file already exists
        if CHECK_IF_FILE_EXIST:
            if self.check_if_images_exist('plate_gated_counts'):
                return True

        # Plot - Counting fluorescent events¶
        self.sample.plot([channel_name1, channel_name2],
                         kind='scatter',
                         alpha=0.6,
                         color='gray')

        # Clear prev sub plot
        subplots(clear=True)

        # Load plate
        plate = FCPlate.from_dir(ID='Demo Plate',
                                 path=SHARED_RAW_DIR,
                                 parser='name')
        plate = plate.transform('hlog',
                                channels=[channel_name1, channel_name2],
                                b=500.0)

        # Drop empty cols / rows
        plate = plate.dropna()

        # Create a threshold gates
        y2_gate = ThresholdGate(1000.0, channel_name1, region='above')

        # Plot
        plate = plate.gate(y2_gate)
        plot_heat_map(plate.counts(),
                      include_values=True,
                      show_colorbar=True,
                      cmap=cm.Oranges)
        title('Heat map of fluorescent counts on plate')

        png_file = os.path.join(SHARED_PLOTTING_DIR,
                                self.get_file_name('plate_gated_counts.png'))
        print(png_file)
        grid(False)
        savefig(png_file)
        self.response['plate_gated_counts'] = self.get_file_name(
            'plate_gated_counts.png')
Exemple #8
0
def animate(i):
    sample = samples[i]
    path = data_path + 'Sample_' + sample + '/'
    plate = FCPlate.from_dir(ID='Demo Plate', path=path, parser='name')
    plate = plate.dropna()
    plate = plate.transform('hlog', channels=['FSC-A', 'SSC-A', \
        'FSC PMT-A','PI (YG)-A', 'FITC-A', 'Pacific Blue-A', 'APC-A'])
    threshold = getDAPIgate(plate)
    gate = ThresholdGate(threshold, 'Pacific Blue-A', region='above')
    gated_sample = plate['A8'].gate(gate)
    RSG = gated_sample.data[['FITC-A']].values

    # simulate new data coming in
    n, bins = np.histogram(RSG, 40, normed=True)
    top = bottom + n
    verts[1::5, 1] = top
    verts[2::5, 1] = top
    #t = ax.annotate(sample + ' hours',(7900,1200)) # add text
    time_text.set_text(sample + ' hours')
    return [patch, time_text]
Exemple #9
0
def get_RSG_hist():
    folder_path = git_path + '/figures/flow_figs/RSG'
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
    fig1 = plt.figure()
    for sample in samples:
        print sample
        path = data_path + 'Sample_' + sample + '/'
        plate = FCPlate.from_dir(ID='Demo Plate', path = path, parser='name')
        plate = plate.dropna()
        plate = plate.transform('hlog', channels=['FSC-A', 'SSC-A', \
            'FSC PMT-A','PI (YG)-A', 'FITC-A', 'Pacific Blue-A', 'APC-A'])
        threshold = getDAPIgate(plate)
        gate = ThresholdGate(threshold, 'Pacific Blue-A', region='above')
        gated_sample = plate['A8'].gate(gate)
        RSG = gated_sample.data[['FITC-A']].values

        fig, ax = plt.subplots()
        ax.hist(RSG, 30, fc='gray', histtype='stepfilled', alpha=0.3, normed=True)
        axes.set_xlim([0,10000])
        plt.savefig(git_path + '/figures/flow_figs/RSG/RSG_Sample_' + sample + '.png')
        plt.close()
Exemple #10
0
figure()
tsample.plot(['B1-A', 'Y2-A'], cmap=cm.Oranges, colorbar=False)

# Plotting 2D scatter plots

figure()
tsample.plot(['B1-A', 'Y2-A'], kind='scatter', color='red', s=1, alpha=0.3)

# Gating

from FlowCytometryTools import ThresholdGate, PolyGate

# Creating gates programmatically

y2_gate = ThresholdGate(1000.0, ['Y2-A'], region='above')
b1_gate = ThresholdGate(2000.0, ['B1-A'], region='above')

# Plotting gates

figure()
tsample.plot(['Y2-A'], gates=[y2_gate], bins=100)
title('Gate Plotted')

# Applying gates

gated_sample = tsample.gate(y2_gate)
print(gated_sample.get_data().shape[0])

# The gated_sample is also an instance of FCMeasurement
figure()
Exemple #11
0
                 ('FSC-A', 'SSC-A'),
                 region='in',
                 name='gate1')
gate2 = PolyGate([(2.102e+04, 7.858e+04), (1.157e+05, 8.865e+04),
                  (1.477e+05, 7.507e+04), (1.414e+05, 6.456e+04),
                  (1.884e+04, 6.368e+04), (1.884e+04, 6.368e+04)],
                 ('SSC-H', 'SSC-W'),
                 region='in',
                 name='gate2')
Comps = Comps.gate(gate1).gate(gate2)
#Comps1 = Comps1.gate(gate1)

#%% Gating individual samples
from FlowCytometryTools import ThresholdGate

gatePB = ThresholdGate(4.024e+00, ('Pacific Blue-A'), region='above')
Comps.samples[3] = Comps.samples[3].gate(gatePB)
#%% calculate compensation matrix

IdxMatch = [0, 3, 4, 1]  #make diagonal, index of channel in samples
IndBlank = 2

meansMatrix = Comps.aSinhmeans().as_matrix()[IdxMatch].T
BGMatrix = np.tile(Comps.aSinhmeans().as_matrix()[IndBlank],
                   (np.shape(meansMatrix)[1], 1)).T
Hu = meansMatrix - BGMatrix

SpilloverM = Hu / Hu.diagonal()
SpilloverM = np.matrix(SpilloverM)
from numpy.linalg import inv
Exemple #12
0
        metaxls = pd.ExcelFile(metadataDir)
        metadata = {
            sheet: metaxls.parse(sheet, index_col=0)
            for sheet in metaxls.sheet_names
        }  #import all sheets in metadata file into a dict, property name=keys, metadata df = values

        #plateNameCore = '' #for debugging
        fcsFolderDir = plateNameCore + '_FCS'
        datadir = os.path.join(dataRootDir, dataFolderDir, fcsFolderDir)
        plate = FCPlate.from_dir(ID='Plate',
                                 path=datadir,
                                 parser=cf.fcsNameParser,
                                 position_mapper='name')

        # Gating
        fsc_gate = ThresholdGate(1000.0, ['FSC-H'], region='above')
        ssc_gate = ThresholdGate(1000.0, ['SSC-H'], region='above')

        rfpA_gate = ThresholdGate(1.0, ['RFP2-A'], region='above')
        fscssc_gate = CompositeGate(fsc_gate, 'and', ssc_gate)
        plate = plate.gate(fscssc_gate)
        plate = plate.gate(rfpA_gate)

        # Produces 96 well layout for intuitive observation
        # Calculate Median from data
        def calculate_median_Y2(well):
            return well.data['RFP2-H'].median()

        dfAll = {}
        dfAll['RFP'] = plate.apply(calculate_median_Y2)
        dfAll['Count'] = plate.counts()
Exemple #13
0
def cd4monMut():
    """ Function for gating CD4+ cells (generates T cells) - for monomeric Mut Experiments. """
    cd41 = ThresholdGate(6400.0, ("VL4-H"), region="above", name="cd41")
    cd42 = ThresholdGate(8000.0, ("VL4-H"), region="below", name="cd42")
    cd4_gate = cd41 & cd42
    return cd4_gate
Exemple #14
0
def cd4():
    """ Function for gating CD4+ cells (generates T cells). """
    cd41 = ThresholdGate(6.514e03, ("VL4-H"), region="above", name="cd41")
    cd42 = ThresholdGate(7.646e03, ("VL4-H"), region="below", name="cd42")
    cd4_gate = cd41 & cd42
    return cd4_gate
Exemple #15
0
import FlowCytometryTools
from FlowCytometryTools import FCMeasurement
from FlowCytometryTools import ThresholdGate

# Locate sample data included with this package
datadir = os.path.join(FlowCytometryTools.__path__[0], 'tests', 'data', 'Plate01')
datafile = os.path.join(datadir, 'RFP_Well_A3.fcs')

# datafile = '[insert path to your own fcs file]' 

# Load data
tsample = FCMeasurement(ID='Test Sample', datafile=datafile)
tsample = tsample.transform('hlog', channels=['Y2-A', 'B1-A', 'V2-A'], b=500.0)

# Create a threshold gates
y2_gate = ThresholdGate(1000.0, 'Y2-A', region='above')

# Gate
gated_sample = tsample.gate(y2_gate)

# Plot
ax1 = subplot(121);
tsample.plot('Y2-A', gates=[y2_gate], bins=100, alpha=0.9);
y2_gate.plot(color='k', linewidth=4, linestyle='-')
title('Original Sample');

ax2 = subplot(122, sharey=ax1, sharex=ax1);
gated_sample.plot('Y2-A', gates=[y2_gate], bins=100, color='y', alpha=0.9);
title('Gated Sample');

tight_layout()
                            region='in',
                            name='singles')
singles_flow_data = non_debris_gated_flow_data.gate(singles_polygate)

# Transform data
tsingles_flow_data = singles_flow_data.transform(
    'hlog',
    channels=[
        'Alexa Fluor 405-A', 'Alexa Fluor 405-H', 'Alexa Fluor 405-W',
        'Alexa Fluor 488-A', 'Alexa Fluor 488-H', 'Alexa Fluor 488-W'
    ],
    b=500.0)

# Continue gating data
cfp_expressing_gate = ThresholdGate(2000.0,
                                    'Alexa Fluor 405-A',
                                    region='above')
cfp_expressing_flow_data = tsingles_flow_data.gate(cfp_expressing_gate)
non_cfp_expressing_gate = ThresholdGate(2000.0,
                                        'Alexa Fluor 405-A',
                                        region='below')
non_cfp_expressing_flow_data = tsingles_flow_data.gate(non_cfp_expressing_gate)
cfp_expressing_cell_cycle_polygate = PolyGate([(65000, 23000), (115000, 23000),
                                               (115000, 120000),
                                               (65000, 120000)],
                                              ['CyChrome-W', 'CyChrome-A'],
                                              region='in',
                                              name='cell cycle')
cfp_expressing_cell_cycle_flow_data = cfp_expressing_flow_data.gate(
    cfp_expressing_cell_cycle_polygate)
non_cfp_expressing_cell_cycle_polygate = PolyGate([(65000, 23000),
def calculate_cell_cycle_status():

    # Gate for G1 and G2 peaks (CFP expressing)
    cfp_cell_cycle_g1_gate = ThresholdGate(65000.0,
                                           'CyChrome-A',
                                           region='below')
    cfp_cell_cycle_g1_flow_data = cfp_expressing_cell_cycle_flow_data.gate(
        cfp_cell_cycle_g1_gate)
    cfp_cell_cycle_g2_gate = ThresholdGate(89000.0,
                                           'CyChrome-A',
                                           region='above')
    cfp_cell_cycle_g2_flow_data = cfp_expressing_cell_cycle_flow_data.gate(
        cfp_cell_cycle_g2_gate)

    # Gate for S phase, isolating the data between G1 and G2 peaks (CFP expressing)
    cfp_cell_cycle_s_a_gate = ThresholdGate(65000.0,
                                            'CyChrome-A',
                                            region='above')
    cfp_cell_cycle_s_flow_data = cfp_expressing_cell_cycle_flow_data.gate(
        cfp_cell_cycle_s_a_gate)
    cfp_cell_cycle_s_b_gate = ThresholdGate(89000.0,
                                            'CyChrome-A',
                                            region='below')
    cfp_cell_cycle_s_flow_data = cfp_cell_cycle_s_flow_data.gate(
        cfp_cell_cycle_s_b_gate)

    cfp_cells_in_g1 = cfp_cell_cycle_g1_flow_data.shape[0]
    cfp_cells_in_g2 = cfp_cell_cycle_g2_flow_data.shape[0]
    cfp_cells_in_s = cfp_cell_cycle_s_flow_data.shape[0]

    cfp_total_cells = cfp_cells_in_g1 + cfp_cells_in_g2 + cfp_cells_in_s

    cfp_percent_g1 = 100 * (cfp_cells_in_g1 / cfp_total_cells)
    cfp_percent_g2 = 100 * (cfp_cells_in_g2 / cfp_total_cells)
    cfp_percent_s = 100 * (cfp_cells_in_s / cfp_total_cells)

    print 'CFP expressing cells in G1: ' + str(cfp_percent_g1) + ' %'
    print 'CFP expressing cells in G2: ' + str(cfp_percent_g2) + ' %'
    print 'CFP expressing cells in S: ' + str(cfp_percent_s) + ' %'

    print '-------------------------------'

    # Gate for G1 and G2 peaks (non-GFP expressing)
    non_cfp_cell_cycle_g1_gate = ThresholdGate(65000.0,
                                               'CyChrome-A',
                                               region='below')
    non_cfp_cell_cycle_g1_flow_data = non_cfp_expressing_cell_cycle_flow_data.gate(
        non_cfp_cell_cycle_g1_gate)
    non_cfp_cell_cycle_g2_gate = ThresholdGate(89000.0,
                                               'CyChrome-A',
                                               region='above')
    non_cfp_cell_cycle_g2_flow_data = non_cfp_expressing_cell_cycle_flow_data.gate(
        non_cfp_cell_cycle_g2_gate)

    # Gate for S phase, isolating the data between G1 and G2 peaks (non-GFP expressing)
    non_cfp_cell_cycle_s_a_gate = ThresholdGate(65000.0,
                                                'CyChrome-A',
                                                region='above')
    non_cfp_cell_cycle_s_flow_data = non_cfp_expressing_cell_cycle_flow_data.gate(
        non_cfp_cell_cycle_s_a_gate)
    non_cfp_cell_cycle_s_b_gate = ThresholdGate(89000.0,
                                                'CyChrome-A',
                                                region='below')
    non_cfp_cell_cycle_s_flow_data = non_cfp_cell_cycle_s_flow_data.gate(
        non_cfp_cell_cycle_s_b_gate)

    non_cfp_cells_in_g1 = non_cfp_cell_cycle_g1_flow_data.shape[0]
    non_cfp_cells_in_g2 = non_cfp_cell_cycle_g2_flow_data.shape[0]
    non_cfp_cells_in_s = non_cfp_cell_cycle_s_flow_data.shape[0]

    non_cfp_total_cells = non_cfp_cells_in_g1 + non_cfp_cells_in_g2 + non_cfp_cells_in_s

    non_cfp_percent_g1 = 100 * (non_cfp_cells_in_g1 / non_cfp_total_cells)
    non_cfp_percent_g2 = 100 * (non_cfp_cells_in_g2 / non_cfp_total_cells)
    non_cfp_percent_s = 100 * (non_cfp_cells_in_s / non_cfp_total_cells)

    print 'Non-CFP expressing cells in G1: ' + str(non_cfp_percent_g1) + ' %'
    print 'Non-CFP expressing cells in G2: ' + str(non_cfp_percent_g2) + ' %'
    print 'Non-CFP expressing cells in S: ' + str(non_cfp_percent_s) + ' %'
Exemple #18
0
        cutoffs.append(DAPI_gate)
    cutoff = np.mean(cutoffs)
    return cutoff


fig, ax = plt.subplots()

# histogram our data with numpy

path1 = data_path + 'Sample_' + samples[0] + '/'
plate1 = FCPlate.from_dir(ID='Demo Plate', path=path1, parser='name')
plate1 = plate1.dropna()
plate1 = plate1.transform('hlog', channels=['FSC-A', 'SSC-A', \
    'FSC PMT-A','PI (YG)-A', 'FITC-A', 'Pacific Blue-A', 'APC-A'])
threshold = getDAPIgate(plate1)
gate1 = ThresholdGate(threshold, 'Pacific Blue-A', region='above')
gated_sample1 = plate1['A8'].gate(gate1)
RSG1 = gated_sample1.data[['FITC-A']].values
n, bins = np.histogram(RSG1, 40, normed=True)

# get the corners of the rectangles for the histogram
left = np.array(bins[:-1])
right = np.array(bins[1:])
bottom = np.zeros(len(left))
top = bottom + n
nrects = len(left)

# here comes the tricky part -- we have to set up the vertex and path
# codes arrays using moveto, lineto and closepoly

# for each rect: 1 for the MOVETO, 3 for the LINETO, 1 for the
Exemple #19
0
def makeFigure():
    """Get a list of the axis objects and create a figure"""

    ax, f = getSetup((10, 8), (3, 4), multz={8: 1, 10: 1})
    subplotLabel(ax)

    Tcell_pathname = path_here + "/data/flow/2019-11-08 monomer IL-2 Fc signaling/CD4 T cells - IL2-060 mono, IL2-060 dimeric"
    NK_CD8_pathname = path_here + "/data/flow/2019-11-08 monomer IL-2 Fc signaling/NK CD8 T cells - IL2-060 mono, IL2-060 dimeric"

    Tcell_sample, _ = importF2(Tcell_pathname, "A")
    NK_CD8_sample, _ = importF2(NK_CD8_pathname, "A")

    Tcell_sample = combineWells(Tcell_sample).subsample(0.2)
    NK_CD8_sample = combineWells(NK_CD8_sample).subsample(0.2)

    Tcell_sample = applyMatrix(Tcell_sample,
                               compMatrix('2019-11-08', '1', 'A'))
    NK_CD8_sample = applyMatrix(NK_CD8_sample,
                                compMatrix('2019-11-08', '1', 'B'))

    Tcell_sample = Tcell_sample.transform(
        "tlog", channels=['VL1-H', 'VL4-H', 'BL1-H',
                          'BL3-H'])  # Tlog transformations
    NK_CD8_sample = NK_CD8_sample.transform(
        "tlog", channels=['RL1-H', 'VL4-H', 'BL1-H',
                          'BL2-H'])  # Tlog transformations

    cd4_gate = ThresholdGate(6500.0, ['VL4-H'],
                             region='above') & ThresholdGate(8000.0, ['VL4-H'],
                                                             region='below')
    ax[0] = Tcell_sample.plot(['VL4-H'], gates=cd4_gate, ax=ax[0])  # CD4
    plt.title("Singlet Lymphocytes")
    #ax.set(xlabel= "CD4", ylabel="Events")
    plt.grid()

    sampleCD4 = Tcell_sample.gate(cd4_gate)
    Treg_gate = PolyGate([(4.2e3, 7.2e3), (6.5e03, 7.2e03), (6.5e03, 5.3e03),
                          (4.9e03, 5.3e03), (4.2e03, 5.7e03)],
                         ('VL1-H', 'BL1-H'),
                         region='in',
                         name='treg')
    Thelp_gate = PolyGate([(1.8e03, 3.1e03), (1.8e03, 4.9e03),
                           (6.0e03, 4.9e03), (6.0e03, 3.1e03)],
                          ('VL1-H', 'BL1-H'),
                          region='in',
                          name='thelper')

    _ = sampleCD4.plot(['VL1-H', 'BL1-H'],
                       gates=[Treg_gate, Thelp_gate],
                       gate_colors=['red', 'red'],
                       cmap=cm.jet,
                       ax=ax[1])  # CD4
    plt.title("CD4+ Cells")
    plt.xlabel("CD25")
    plt.ylabel("FOXP3")
    plt.grid()

    #CD8+ Cells
    CD3CD8gate = PolyGate([(7.5e3, 8.4e3), (4.7e3, 8.4e3), (4.7e03, 6.5e03),
                           (7.5e03, 6.5e03)], ('VL4-H', 'RL1-H'),
                          region='in',
                          name='treg')
    _ = NK_CD8_sample.plot(['VL4-H', 'RL1-H'],
                           gates=CD3CD8gate,
                           gate_colors='red',
                           cmap=cm.jet,
                           ax=ax[2])  # CD3, CD8
    plt.title("Singlet Lymphocytes")
    plt.xlabel("CD3")
    plt.ylabel("CD8")
    plt.grid()

    # NK Cells
    NKgate = PolyGate([(4.8e3, 5.1e3), (5.9e3, 5.1e3), (5.9e03, 6.1e03),
                       (4.8e03, 6.1e03)], ('VL4-H', 'BL1-H'),
                      region='in',
                      name='treg')
    CD56brightgate = PolyGate([(4.8e3, 6.3e3),
                               (5.9e3, 6.3e3), (5.9e03, 7.3e03),
                               (4.8e03, 7.3e03)], ('VL4-H', 'BL1-H'),
                              region='in',
                              name='treg')
    _ = NK_CD8_sample.plot(['VL4-H', 'BL1-H'],
                           gates=[NKgate, CD56brightgate],
                           gate_colors=['red', 'red'],
                           cmap=cm.jet,
                           ax=ax[3])  # CD3, CD56
    plt.title("Singlet Lymphocytes")
    plt.xlabel("CD3")
    plt.ylabel("CD56")
    plt.grid()

    # Gating for live cells
    sample1A, _, _ = importF("4-23", "1", "A", 1, "IL2R", None)
    sample2B, _, _ = importF("4-23", "1", "B", 2, "IL2R", None)
    sample3C, _, _ = importF("4-23", "1", "C", 3, "IL2R", None)
    panel1 = sample1A.transform(
        "tlog", channels=['VL6-H', 'VL4-H', 'BL1-H', 'VL1-H',
                          'BL3-H']).subsample(0.2)
    panel2 = sample2B.transform("tlog", channels=['VL4-H',
                                                  'BL3-H']).subsample(0.2)
    panel3 = sample3C.transform("tlog", channels=['VL6-H', 'VL4-H',
                                                  'BL3-H']).subsample(0.2)

    cd3cd4_gate = PolyGate([(5.0e03, 7.3e03), (5.3e03, 5.6e03),
                            (8.0e03, 5.6e03), (8.0e03, 7.3e03)],
                           ('VL4-H', 'VL6-H'),
                           region='in',
                           name='cd3cd4')
    _ = panel1.plot(['VL4-H', 'VL6-H'],
                    gates=cd3cd4_gate,
                    gate_colors=['red'],
                    cmap=cm.jet,
                    ax=ax[4])  # CD3, CD4
    plt.title("Singlet Lymphocytes")
    plt.xlabel("CD3")
    plt.ylabel("CD4")
    plt.grid()

    samplecd3cd4 = panel1.gate(cd3cd4_gate)
    thelp_gate = PolyGate([(0.2e03, 6.8e03), (0.2e03, 4.4e03),
                           (3.7e03, 4.4e03), (5.7e03, 5.9e03),
                           (5.7e03, 6.8e03)], ('VL1-H', 'BL1-H'),
                          region='in',
                          name='thelp')
    treg_gate = PolyGate([(3.8e03, 4.4e03), (3.8e03, 3.0e03), (6.5e03, 2.9e03),
                          (6.5e03, 5.0e03), (5.7e03, 5.8e03)],
                         ('VL1-H', 'BL1-H'),
                         region='in',
                         name='treg')
    _ = samplecd3cd4.plot(['VL1-H', 'BL1-H'],
                          gates=[thelp_gate, treg_gate],
                          gate_colors=['red', 'red'],
                          cmap=cm.jet,
                          ax=ax[5])  # CD3, CD4
    plt.title("CD3+CD4+ cells")
    plt.xlabel("CD25")
    plt.ylabel("CD127")
    plt.grid()

    nk_gate = PolyGate([(3.3e3, 5.4e3), (5.3e3, 5.4e3), (5.3e3, 7.3e3),
                        (3.3e3, 7.3e3)], ('VL4-H', 'BL3-H'),
                       region='in',
                       name='nk')
    nkt_gate = PolyGate([(5.6e3, 5.1e3), (7.6e3, 5.1e3), (7.6e3, 7.1e3),
                         (5.6e3, 7.1e3)], ('VL4-H', 'BL3-H'),
                        region='in',
                        name='nkt')
    _ = panel2.plot(['VL4-H', 'BL3-H'],
                    gates=[nk_gate, nkt_gate],
                    gate_colors=['red', 'red'],
                    cmap=cm.jet,
                    ax=ax[6])  # CD56 vs. CD3
    samplenk = panel2.gate(nk_gate)
    samplenkt = panel2.gate(nkt_gate)
    plt.title("Singlet Lymphocytes")
    plt.xlabel("CD3")
    plt.ylabel("CD56")
    plt.grid()

    cd8_gate = PolyGate([(4.2e3, 5.7e3), (8.1e3, 5.7e3), (8.1e3, 8.0e3),
                         (4.2e3, 8.0e3)], ('VL4-H', 'VL6-H'),
                        region='in',
                        name='cd8')
    _ = panel3.plot(['VL4-H', 'VL6-H'],
                    gates=cd8_gate,
                    gate_colors=['red'],
                    cmap=cm.jet,
                    ax=ax[7])  # CD8 vs. CD3
    plt.title("Singlet Lymphocytes")
    plt.xlabel("CD3")
    plt.ylabel("CD8")

    for i, axs in enumerate(ax):
        if i == 0:
            print(" ")
            # weird error replace later, axs is not correct object type
            # axs.set(xlabel='CD4',ylabel='Events')
        elif i == 1:
            axs.set_title('T Cell Gating')
            axs.set(xlabel='CD25', ylabel='FOXP3')
        elif i == 2:
            axs.set_title('CD8+ Cells Gating')
            axs.set(xlabel='CD3', ylabel='CD8')
        elif i == 3:
            axs.set_title('NK Cells Gating')
            axs.set(xlabel='CD3', ylabel='CD56')
        elif i == 4:
            axs.set_title('CD3+CD4+ Gating')
            axs.set(xlabel='CD3', ylabel='CD4')
        elif i == 5:
            axs.set_title('T reg and T Helper Gating')
            axs.set(xlabel='CD25', ylabel='CD127')
        elif i == 6:
            axs.set_title('NK and NKT Gating')
            axs.set(xlabel='CD3', ylabel='CD56')
        elif i == 7:
            axs.set_title('CD3+CD8+ Gating')
            axs.set(xlabel='CD3', ylabel='CD8')
        if i != 0:
            axs.grid()

    receptorPlot(ax[8])
    IL2RahiLoPlot(ax[9])

    return f
from FlowCytometryTools import FCMeasurement, ThresholdGate
import os, FlowCytometryTools
from pylab import *

# Locate sample data included with this package
datadir = os.path.join(FlowCytometryTools.__path__[0], 'tests', 'data', 'Plate01')
datafile = os.path.join(datadir, 'RFP_Well_A3.fcs')

# datafile = '[insert path to your own fcs file]' 

# Load data
tsample = FCMeasurement(ID='Test Sample', datafile=datafile)
tsample = tsample.transform('hlog', channels=['Y2-A', 'B1-A', 'V2-A'], b=500.0)

# Create a threshold gates
y2_gate = ThresholdGate(1000.0, 'Y2-A', region='above')

# Gate
gated_sample = tsample.gate(y2_gate)

# Plot
ax1 = subplot(121);
tsample.plot('Y2-A', gates=[y2_gate], bins=100, alpha=0.9);
y2_gate.plot(color='k', linewidth=4, linestyle='-')
title('Original Sample');

ax2 = subplot(122, sharey=ax1, sharex=ax1);
gated_sample.plot('Y2-A', gates=[y2_gate], bins=100, color='y', alpha=0.9);
title('Gated Sample');

tight_layout()
from GoreUtilities import plot_heat_map
import os, FlowCytometryTools
from pylab import *
import matplotlib.pyplot as plt

# Locate sample data included with this package
datadir = os.path.join(FlowCytometryTools.__path__[0], 'tests', 'data', 'Plate01')

# datadir = '[insert path to your own folder with fcs files.]'
# Make sure that the files follow the correct naming convention for the 'name' parser.
# Alternatively, change the parser (see tutorial online for further information).

# Load plate
plate = FCPlate.from_dir(ID='Demo Plate', path=datadir, parser='name')
plate = plate.transform('hlog', channels=['Y2-A', 'B1-A'], b=500.0)

# Drop empty cols / rows
plate = plate.dropna()

# Create a threshold gates
from FlowCytometryTools import ThresholdGate
y2_gate = ThresholdGate(1000.0, 'Y2-A', region='above')

# Plot
plate = plate.gate(y2_gate)
plot_heat_map(plate.counts(), include_values=True, show_colorbar=True,
        cmap=cm.Oranges)
title('Heat map of fluorescent counts on plate')

#show() # <-- Uncomment when running as a script.
Exemple #22
0
def testCounts():
    tubes = ['A8']
    for sample in samples:
        print sample
        path = data_path + 'Sample_' + sample + '/'
        files = os.listdir(path)
        remove = ['misc', '.DS_Store']
        files1 = [i for i in files if i not in remove]
        files_split = [re.split(r'[._]',x)[3] for x in files1]
        if 'H' in files_split:
            for tube in tubes:
                file_folder_path = git_path + '/figures/flow_figs/' + tube
                if not os.path.exists(file_folder_path):
                    os.makedirs(file_folder_path)

                file_folder_sample_path = git_path + '/figures/flow_figs/' + \
                    tube +'/Sample_' + sample + '/'
                if not os.path.exists(file_folder_sample_path):
                    os.makedirs(file_folder_sample_path)

                plate = FCPlate.from_dir(ID='Demo Plate', path = path, parser='name')
                plate = plate.dropna()
                plate = plate.transform('hlog', channels=['FSC-A', 'SSC-A', \
                    'FSC PMT-A','PI (YG)-A', 'FITC-A', 'Pacific Blue-A', 'APC-A'])
                threshold = getDAPIgate(plate)
                gate = ThresholdGate(threshold, 'Pacific Blue-A', region='above')
                gated_sample = plate[tube].gate(gate)
                FSC_A = gated_sample.data[['FSC-A']].values
                SSC_A = gated_sample.data[['SSC-A']].values
                PI = gated_sample.data[['PI (YG)-A']].values
                FITC = gated_sample.data[['FITC-A']].values
                FSC_H = gated_sample.data[['FSC-H']].values
                SSC_H = gated_sample.data[['SSC-H']].values
                FSC_PMT_A = gated_sample.data[['FSC PMT-A']].values
                FSC_PMT_H = gated_sample.data[['FSC PMT-H']].values
                Pacific_blue = gated_sample.data[['Pacific Blue-A']].values
                APC = gated_sample.data[['APC-A']].values

                fig = plt.figure()
                ax = fig.add_subplot(111, projection='3d')
                ax.scatter(FITC, Pacific_blue, APC , zdir='z', alpha = 0.2)
                ax.set_xlabel('FITC')
                ax.set_ylabel('Pacific blue')
                ax.set_zlabel('APC')

                name = tube + '_FITC_APC_PacificBlue_' + sample
                plt.savefig(file_folder_sample_path + name + '.png')
                plt.close()

                fig = plt.figure()
                ax = fig.add_subplot(111)
                ax.scatter(APC, FITC, alpha = 0.2)
                ax.set_xlabel('APC')
                ax.set_ylabel('FITC')

                name = tube +'_APC_FITC_' + sample
                plt.savefig(file_folder_sample_path + name + '.png')
                plt.close()


                fig = plt.figure()
                ax = fig.add_subplot(111)
                ax.scatter(Pacific_blue, FITC, alpha = 0.2)
                ax.set_xlabel('Pacific blue')
                ax.set_ylabel('FITC')

                name = tube + '_PacificBlue_FITC_' + sample
                plt.savefig(file_folder_sample_path + name + '.png')
                plt.close()

                fig = plt.figure()
                ax = fig.add_subplot(111)
                ax.scatter(FSC_A, SSC_A, alpha = 0.2)
                ax.set_xlabel('FSC-A')
                ax.set_ylabel('SSC-A')

                name = tube + '_FSC_A_SSC_A_' + sample
                plt.savefig(file_folder_sample_path + name + '.png')
                plt.close()

                fig = plt.figure()
                ax = fig.add_subplot(111)
                ax.scatter(FSC_H, SSC_H, alpha = 0.2)
                ax.set_xlabel('FSC-H')
                ax.set_ylabel('SSC-H')
                #plt.axhline(y = 250000, linewidth=2, color='darkgrey', ls='--')

                name = tube + '_FSC_H_SSC_H_' + sample
                plt.savefig(file_folder_sample_path + name + '.png')
                plt.close()

                fig = plt.figure()
                ax = fig.add_subplot(111)
                ax.scatter(FSC_PMT_A, FSC_PMT_H, alpha = 0.2)
                ax.set_xlabel('FSC PMT-A')
                ax.set_ylabel('FSC PMT-H')

                name = tube + '_FSC_PMT_A_FSC_PMT_H_' + sample
                plt.savefig(file_folder_sample_path + name + '.png')
                plt.close()
Exemple #23
0
from scipy.sparse import hstack
import numpy as np
from scipy.stats import gaussian_kde

plate = FCPlate.from_dir(
    ID='Demo Plate',
    path=
    '/Users/WRShoemaker/github/Task2/FlowCyto/20151203/CTC_FVD_Hoechst_test120315/',
    parser='name')
plate = plate.transform('hlog',
                        channels=[
                            'FSC-A', 'SSC-A', 'PI (B)-A', 'Alexa Fluor 488-A',
                            'Pacific Blue-A'
                        ])
plate = plate.dropna()
gate = ThresholdGate(2000.0, 'Pacific Blue-A', region='below')
gated_sample_beads_A3 = plate['A3'].gate(gate)

plateData = plate['A3'].data[['Pacific Blue-A', 'PI (B)-A']]

CTCnumpy = gated_sample_beads_A3[['PI (B)-A']].values
DNAnumpy = gated_sample_beads_A3[['Pacific Blue-A']].values


def get_kdens_choose_kernel(xlist, expand, kernel=0.5):
    """ Finds the kernel density function across a vector of values """
    xlist = xlist[np.logical_not(np.isnan(xlist))]
    density = gaussian_kde(xlist)
    n = len(xlist)
    if expand == False:
        xs = np.linspace(min(xlist), max(xlist), n)
Exemple #24
0
    # Our transformation goes here
    for channel in channelLst:
        new_data[channel] = np.log10(original_data[channel])
    new_data = new_data.dropna()  # Removes all NaN entries
    new_sample.data = new_data
    return new_sample


# //////////////////////////////////////////////
# threshold gating to remove all negative FSC and SSC events
preP1th_value1 = 10.0**1.6699667767116002
preP1th_channel1 = 'FSC-A'
preP1th_value2 = 10.0**2.8012542209507507
preP1th_channel2 = 'SSC-A'
preP1gate1 = ThresholdGate(preP1th_value1, preP1th_channel1, region='above')
preP1gate2 = ThresholdGate(preP1th_value2, preP1th_channel2, region='above')
preP1gate = preP1gate1 & preP1gate2

preP1_sample = sample.gate(preP1gate)
print 'profile after preP1 gating'
print preP1_sample.data.describe()
print ''

preP1log = custom_log(preP1_sample, ['FSC-A', 'SSC-A'])
print 'profile after preP1 gating and log10 for FSC and SSC'
print preP1log.data.describe()
print ''

# //////////////////////////////////////////////
# P1 gating based on FSC and SSC (Log10 space)