Selected Files Summary:
No files selected yet. Files will appear here once selected.
Processing Output:
Results will appear here after processing.
No files selected yet. Files will appear here once selected.
Results will appear here after processing.
Processing files... Please wait.
" download_section.style.display = "none" try: # Get all file inputs and column inputs file_data = [] all_items = set() for i in range(1, 11): file_input = js.document.getElementById(f"file{i}") col_input = js.document.getElementById(f"col{i}") if file_input.files.length > 0 and col_input.value: file = file_input.files.item(0) col_num = int(col_input.value) - 1 # Convert to 0-based index # Read the Excel file output_div.innerHTML += f"Reading {file.name}...
" # Read file content file_content = await file.arrayBuffer() file_bytes = file_content.to_bytes() # Read Excel file df = pd.read_excel(BytesIO(file_bytes)) # Get the column name if col_num < len(df.columns): col_name = df.columns[col_num] items = set(df.iloc[:, col_num].dropna().astype(str).unique()) all_items.update(items) file_data.append({ 'filename': file.name, 'col_index': col_num, 'col_name': col_name, 'items': items }) output_div.innerHTML += f"Found {len(items)} unique items in {file.name}, column {col_name}
" else: output_div.innerHTML += f"Error: Column {col_num+1} does not exist in {file.name}
" return if not file_data: output_div.innerHTML += "No valid files and columns selected.
" return # Create the presence matrix output_div.innerHTML += "Creating presence matrix...
" # Convert to sorted list for consistent ordering all_items = sorted(all_items) # Create a DataFrame for the presence matrix with YES/NO values matrix_data = {} for data in file_data: col_header = f"{data['filename']} - {data['col_name']}" matrix_data[col_header] = ['YES' if item in data['items'] else 'NO' for item in all_items] # Add the items as the first column global presence_df presence_df = pd.DataFrame(matrix_data, index=all_items) presence_df.reset_index(inplace=True) presence_df.rename(columns={'index': 'Item'}, inplace=True) # Add count column (count of YES values) yes_no_matrix = presence_df.iloc[:, 1:].applymap(lambda x: 1 if x == 'YES' else 0) presence_df['Total_Overlap'] = yes_no_matrix.sum(axis=1) # Prepare upset plot data output_div.innerHTML += "Preparing upset plot data...
" prepare_upset_data(file_data, all_items) # Create Excel file with formulas output_div.innerHTML += "Generating Excel file with formulas...
" # Create a BytesIO object to hold the Excel file excel_buffer = BytesIO() with pd.ExcelWriter(excel_buffer, engine='openpyxl') as writer: presence_df.to_excel(writer, sheet_name='Presence Matrix', index=False) # Get the workbook and worksheet workbook = writer.book worksheet = writer.sheets['Presence Matrix'] # Add formula headers for each column for col_idx, col_name in enumerate(presence_df.columns[1:], 2): # Start from column B if col_name != 'Total_Overlap': # Add formula to count YES values for each column formula_row = 1 formula_col = col_idx formula = f'=SUMPRODUCT(SUBTOTAL(103, OFFSET({worksheet.cell(row=3, column=formula_col).coordinate}:{worksheet.cell(row=len(presence_df)+2, column=formula_col).coordinate}, ROW({worksheet.cell(row=3, column=formula_col).coordinate}:{worksheet.cell(row=len(presence_df)+2, column=formula_col).coordinate})-ROW({worksheet.cell(row=3, column=formula_col).coordinate}), 0, 1)), --({worksheet.cell(row=3, column=formula_col).coordinate}:{worksheet.cell(row=len(presence_df)+2, column=formula_col).coordinate}="YES"))' worksheet.cell(row=formula_row, column=formula_col, value=formula) # Prepare the file for download excel_buffer.seek(0) excel_data = excel_buffer.getvalue() # Store the Excel data in a global variable for download global excel_file_data excel_file_data = excel_data # Enable download button js.document.getElementById("downloadMatrixBtn").onclick = download_matrix js.document.getElementById("viewUpsetPlotBtn").onclick = show_upset_plot download_section.style.display = "block" output_div.innerHTML += f"Processing complete! Found {len(all_items)} unique items across {len(file_data)} files.
" except Exception as e: output_div.innerHTML += f"Error: {str(e)}
" js.console.error(str(e)) # Function to prepare upset plot data def prepare_upset_data(file_data, all_items): # Create binary matrix for upset plot binary_data = [] set_names = [] for data in file_data: set_name = f"{data['filename']} - {data['col_name']}" set_names.append(set_name) binary_data.append([1 if item in data['items'] else 0 for item in all_items]) # Calculate intersection sizes intersection_data = [] for r in range(1, len(set_names) + 1): for combo in combinations(range(len(set_names)), r): # Calculate size of intersection mask = np.ones(len(all_items), dtype=bool) for idx in combo: mask = mask & (np.array(binary_data[idx]) == 1) intersection_size = np.sum(mask) if intersection_size > 0: intersection_data.append({ 'sets': [set_names[i] for i in combo], 'size': int(intersection_size) }) global upset_data upset_data = { 'set_names': set_names, 'intersections': intersection_data } # Function to download the matrix def download_matrix(): global excel_file_data blob = js.Blob.new([excel_file_data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}) url = js.URL.createObjectURL(blob) # Create a temporary link and trigger download a = js.document.createElement('a') a.href = url a.download = 'upsetplot_matrix.xlsx' js.document.body.appendChild(a) a.click() js.document.body.removeChild(a) js.URL.revokeObjectURL(url) # Function to show the upset plot def show_upset_plot(): global upset_data # Prepare data for Plotly upset plot set_names = upset_data['set_names'] intersections = upset_data['intersections'] # Create the upset plot in a new tab plot_window = js.window.open('', '_blank') plot_window.document.write(f"""