Spaces:
Runtime error
Runtime error
import gradio as gr | |
import flowio | |
import matplotlib.pyplot as plt | |
import io | |
import pandas as pd | |
# Function to parse FCS file and extract data and metadata | |
def parse_fcs(file): | |
# Use flowio to parse the FCS file | |
fcs_data = flowio.FlowData(file.name) | |
# Extract channel names and data | |
channel_names = [channel['PnN'] for channel in fcs_data.channels] | |
data = pd.DataFrame(fcs_data.events, columns=channel_names) | |
return data, channel_names | |
# Function to plot the data based on selected x and y parameters | |
def plot_dot(file, x_param, y_param): | |
if not file: | |
return "Please upload an FCS file." | |
try: | |
data, columns = parse_fcs(file) | |
if x_param not in columns or y_param not in columns: | |
return "Invalid parameters selected. Please choose valid parameters from the dropdown." | |
# Create the plot | |
plt.figure(figsize=(8, 6)) | |
plt.scatter(data[x_param], data[y_param], s=1, alpha=0.5, color="blue") | |
plt.xlabel(x_param) | |
plt.ylabel(y_param) | |
plt.title("Flow Cytometry Dot Plot") | |
plt.grid(True) | |
# Save plot to a BytesIO object | |
buf = io.BytesIO() | |
plt.savefig(buf, format="png") | |
buf.seek(0) | |
plt.close() | |
# Save the plot as a temporary file for display | |
temp_file = "/tmp/dot_plot.png" | |
with open(temp_file, "wb") as f: | |
f.write(buf.getbuffer()) | |
return temp_file | |
except Exception as e: | |
return f"Error: {e}" | |
# Function to dynamically update parameter options after file upload | |
def get_parameters(file): | |
if not file: | |
return [], [] | |
try: | |
_, columns = parse_fcs(file) | |
return gr.Dropdown.update(choices=columns), gr.Dropdown.update(choices=columns) | |
except Exception as e: | |
return [f"Error: {e}"], [f"Error: {e}"] | |
# Create Gradio interface | |
with gr.Blocks() as app: | |
gr.Markdown("# Flow Cytometry Dot Plot Viewer") | |
with gr.Row(): | |
fcs_file = gr.File(label="Upload FCS File") | |
with gr.Row(): | |
x_param = gr.Dropdown(label="X Parameter", choices=[], interactive=True) | |
y_param = gr.Dropdown(label="Y Parameter", choices=[], interactive=True) | |
plot_btn = gr.Button("Generate Plot") | |
plot_output = gr.Image(type="filepath", label="Dot Plot") | |
# Update parameter dropdowns on file upload | |
fcs_file.change(get_parameters, inputs=[fcs_file], outputs=[x_param, y_param]) | |
# Generate plot on button click | |
plot_btn.click(plot_dot, inputs=[fcs_file, x_param, y_param], outputs=plot_output) | |
# Run the app | |
app.launch() |