Dataset Viewer
Auto-converted to Parquet
text
stringlengths
1
843k
import reflex as rx config = rx.Config( app_name="Calculadora", )
import reflex as rx class State(rx.State): expression: str = "" result: str = "" def add_to_expression(self, value: str): self.expression += value def clear(self): self.expression = "" self.result = "" def calculate(self): try: self.result = str(eval(self.expression)) except Exception: self.result = "Error" def calculator() -> rx.Component: buttons = [ "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+" ] return rx.center( rx.vstack( rx.text("Calculadora", font_size="2xl", color="black"), rx.box(rx.text(State.expression, color="black"), height="40px"), rx.box(rx.text(State.result, color="green"), height="40px"), rx.grid( *[ rx.button( b, on_click=( State.calculate if b == "=" else lambda b=b: State.add_to_expression(b) ), width="60px", height="60px", font_size="xl" ) for b in buttons ], columns="4", gap=2, ), rx.button("C", on_click=State.clear, color_scheme="red"), spacing="4" ), padding="20px", bg="white", ) app = rx.App() app.add_page(calculator, title="Calculadora", route="/")
null
import reflex as rx config = rx.Config( app_name="pyama_web", )
import os import numpy as np import numba as nb import scipy import h5py import skimage as sk import cv2 import pandas as pd import re import math # import matplotlib.pyplot as plt import pathlib import scipy.ndimage as smg from nd2reader import ND2Reader STRUCT3 = np.ones((3,3), dtype=np.bool_) STRUCT5 = np.ones((5,5), dtype=np.bool_) STRUCT5[[0,0,-1,-1], [0,-1,0,-1]] = False @nb.njit def window_std(img: np.ndarray) -> float: """ Calculate unnormed variance of 'img' Refer to https://en.wikipedia.org/wiki/Variance#Unbiased_sample_variance Refer to Pyama https://github.com/SoftmatterLMU-RaedlerGroup/pyama/tree/master Parameters: img (np.ndarray): Input image Returns: float: Unnormed variance of the image """ return np.sum((img - np.mean(img))**2) @nb.njit def generic_filter(img: np.ndarray, fun: callable, size: int = 3, reflect: bool = False) -> np.ndarray: """ Apply filter to image. Parameters: img (np.ndarray): The image to be filtered fun (callable): The filter function to be applied, must accept subimage of 'img' as only argument and return a scalar. "Fun" stands for function and callable should stand for function in Python size (int): The size (side length) of the kernel. Must be an odd integer reflect (bool): Switch for border mode: True for 'reflect', False for 'mirror'. Reflect and Mirror should be filling the borders of the img. Returns: np.ndarray: Filtered image as a np.float64 array with same shape as 'img' Raises: ValueError: If 'size' is not an odd integer """ if size % 2 != 1: raise ValueError("'size' must be an odd integer") height, width = img.shape s2 = size // 2 # Set up temporary image for correct border handling img_temp = np.empty((height+2*s2, width+2*s2), dtype=np.float64) img_temp[s2:-s2, s2:-s2] = img if reflect: img_temp[:s2, s2:-s2] = img[s2-1::-1, :] img_temp[-s2:, s2:-s2] = img[:-s2-1:-1, :] img_temp[:, :s2] = img_temp[:, 2*s2-1:s2-1:-1] img_temp[:, -s2:] = img_temp[:, -s2-1:-2*s2-1:-1] else: img_temp[:s2, s2:-s2] = img[s2:0:-1, :] img_temp[-s2:, s2:-s2] = img[-2:-s2-2:-1, :] img_temp[:, :s2] = img_temp[:, 2*s2:s2:-1] img_temp[:, -s2:] = img_temp[:, -s2-2:-2*s2-2:-1] # Create and populate result image filtered_img = np.empty_like(img, dtype=np.float64) for y in range(height): for x in range(width): filtered_img[y, x] = fun(img_temp[y:y+2*s2+1, x:x+2*s2+1]) return filtered_img def binarize_frame(img: np.ndarray, mask_size: int = 3) -> np.ndarray: """ Coarse segmentation of phase-contrast image frame Refer to OpenCV tutorials for more information on binarization/thresholding techniques. Parameters: img (np.ndarray): The image to be binarized mask_size (int): The size of the mask to be used in the binarization process (mask refers to kernel size in image processing) Returns: np.ndarray: Binarized image of frame """ # Get logarithmic standard deviation at each pixel std_log = generic_filter(img, window_std, size=mask_size) std_log[std_log>0] = (np.log(std_log[std_log>0]) - np.log(mask_size**2 - 1)) / 2 # Get width of histogram modulus counts, edges = np.histogram(std_log, bins=200) bins = (edges[:-1] + edges[1:]) / 2 hist_max = bins[np.argmax(counts)] sigma = np.std(std_log[std_log <= hist_max]) # Apply histogram-based threshold img_bin = std_log >= hist_max + 3 * sigma # Remove noise img_bin = smg.binary_dilation(img_bin, structure=STRUCT3) img_bin = smg.binary_fill_holes(img_bin) img_bin &= smg.binary_opening(img_bin, iterations=2, structure=STRUCT5) img_bin = smg.binary_erosion(img_bin, border_value=1) return img_bin def csv_output(out_dir: str, pos: list, mins: float, use_square_rois: bool = True) -> None: """ Generate CSV output for tracked positions Parameters: out_dir (str): Output directory path pos (list): List of positions to process mins (float): Minutes per frame use_square_rois (bool): Whether to use square ROIs Returns: None """ folders = get_tracked_folders(out_dir,pos) for folder in folders: csv_output_position(folder[0],folder[1],mins,use_square_rois) def csv_output_position(pos: int, pos_path: pathlib.Path, mins: float, use_square_rois: bool) -> None: """ Generate CSV output for a single position Parameters: pos (int): Position number pos_path (pathlib.Path): Path to position directory mins (float): Minutes per frame use_square_rois (bool): Whether to use square ROIs Returns: None """ tracks_path = pos_path.joinpath('tracks.csv') tracks = pd.read_csv(tracks_path.absolute(),index_col=0) data_path = pos_path.joinpath('data.h5') with h5py.File(data_path.absolute(), "r") as data: frames = range(data.attrs['frame_min'],data.attrs['frame_max']+1) fl_channel_names = data.attrs['fl_channel_names'] excel_path = pos_path.joinpath('output.xlsx') particles = [int(p) for p in tracks['particle'].unique()] particles.sort() print("Starting Data Export for position:",str(pos)) with pd.ExcelWriter(excel_path.absolute()) as writer: if use_square_rois == True and 'square_area' in tracks: area = csv_get_table(particles,tracks,frames,mins,'square_area') else: area = csv_get_table(particles,tracks,frames,mins,'area') area.to_excel(writer, sheet_name='Area', index=False) for i in range(len(fl_channel_names)): col_name = 'brightness_' + str(i) if use_square_rois == True and 'square_' + col_name in tracks: brightness = csv_get_table(particles,tracks,frames,mins,'square_' + col_name) else: brightness = csv_get_table(particles,tracks,frames,mins,col_name) brightness.to_excel(writer, sheet_name=fl_channel_names[i], index=False) table_to_image(pos_path,particles,brightness,fl_channel_names[i]) print('Done') def table_to_image(pos_path: pathlib.Path, particles: list, table: pd.DataFrame, name: str) -> None: """ Convert table data to image and save it. This is a post-processing step. These converts the table data to the fluorescent tracks image. Parameters: pos_path (pathlib.Path): Path to position directory particles (list): List of particle IDs table (pd.DataFrame): Data table name (str): Name for the output file """ # Import matplotlib and set backend at the start of the function import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt # Create figure without displaying it fig = plt.figure() for p in particles: plt.plot(table['time'].values, table[str(p)].values, color='gray', alpha=0.5) plt.xlabel('Time (Frame)') plt.ylabel('Brightness (Pixelsum)') plt.title(name) plt.tight_layout() # Save figure and close it fig.savefig(pos_path.joinpath(name + '.png').absolute()) plt.close(fig) def csv_get_table(particles: list, tracks: pd.DataFrame, frames: list, mins: float, col: str) -> pd.DataFrame: """ Post-processing step that converts from TrackPy to Pyama format. Extract data from tracks and create a table. Parameters: particles (list): List of particle IDs tracks (pd.DataFrame): Tracking data frames (list): List of frame numbers mins (float): Minutes per frame col (str): Column name to extract Returns: pd.DataFrame: Extracted data table """ keys = [] keys.append('time') for p in particles: keys.append(str(p)) data = {} for key in keys: data[key] = [] print('Fetching Data:', col) for f in frames: #print('Frame',f) data['time'].append(f * mins / 60) for p in particles: t = tracks[(tracks['particle'] == p) & (tracks['frame'] == f)] if len(t) > 0: data[str(p)].append(t.iloc[0][col]) else: # change this behaviour if memory during tracking is used data[str(p)].append(0) return pd.DataFrame(data) def square_roi(out_dir: str, pos: list, micron_size: float) -> None: """ Post-processing step where the micron_size defines the length of the squares. Apply square ROI to tracked positions Parameters: out_dir (str): Output directory path pos (list): List of positions to process micron_size (float): Size of ROI in microns Returns: None """ folders = get_tracked_folders(out_dir,pos) print(folders) for folder in folders: square_roi_position(folder[0],folder[1],micron_size) def square_roi_position(pos: int, pos_path: pathlib.Path, micron_size: float) -> None: """ Post-processing step where the micron_size defines the length of the squares. Apply square ROI to a single position. Parameters: pos (int): Position number pos_path (pathlib.Path): Path to position directory micron_size (float): Size of ROI in microns Returns: None """ tracks_path = pos_path.joinpath('tracks.csv') tracks = pd.read_csv(tracks_path.absolute(),index_col=0) data_path = pos_path.joinpath('data.h5') data = h5py.File(data_path.absolute(), "r") size = math.ceil(micron_size / data.attrs['pixel_microns']) width,height = data.attrs['width'],data.attrs['height'] print("Starting Square ROIs for position:",str(pos)) for frame in sorted(tracks['frame'].unique()): frame_data_index = frame-data.attrs['frame_min'] print("Frame",str(int(frame))) # t = tracks[(tracks['frame'] == frame) & (tracks['enabled'] == True)] true_values = [1, '1', '1.0', 1.0, True, 'True', 'true', 'TRUE'] # Convert true_values to lowercase strings true_values_lower = [str(v).lower() for v in true_values] # Create the enabled condition: # 1. Convert the enabled column to string # 2. Convert all values to lowercase # 3. Check if they're in our true_values list enabled_condition = tracks['enabled'].astype(str).str.lower().isin(true_values_lower) # Apply both conditions to filter the dataframe t = tracks[ (tracks['frame'] == frame) & (enabled_condition)] for index, record in t.iterrows(): x = int((record['bbox_x1'] + record['bbox_x2']) // 2) y = int((record['bbox_y1'] + record['bbox_y2']) // 2) x1 = max(0,x - size) y1 = max(0,y - size) x2 = min(height-1,x + size) y2 = min(width-1,y + size) tracks.loc[(tracks['frame'] == frame) & (tracks['particle'] == record['particle']), 'square_area'] = (x2-x1) * (y2-y1) for i in range(len(data.attrs['fl_channels'])): im_slice = data['fluorescence'][int(frame_data_index),i][x1:x2,y1:y2] tracks.loc[(tracks['frame'] == frame) & (tracks['particle'] == record['particle']), 'square_brightness_' + str(i)] = im_slice.sum() data.close() tracks.to_csv(tracks_path.absolute()) print("Done") # to be deprecated since the function above is the only one being used. def square_roi_position_old(nd2_path: str, out_dir: str, pos: int, micron_size: float) -> None: """ Old version of square ROI application to a single position Parameters: nd2_path (str): Path to ND2 file out_dir (str): Output directory path pos (int): Position number micron_size (float): Size of ROI in microns Returns: None """ if not pathlib.Path(nd2_path).is_file(): print("Invalid ND2 Path") return nd2 = ND2Reader(nd2_path) pos_dir = position_path(out_dir,pos) if pos_dir is None: print("Could not find directory") return tracks_path = pos_dir.joinpath('tracks.csv') if not tracks_path.is_file(): print("Could not find features.csv") return tracks = pd.read_csv(tracks_path.absolute()) # pixel_microns: the amount of microns per pixel size = math.ceil(micron_size / nd2.metadata['pixel_microns']) data_path = pos_dir.joinpath('data.h5') if not data_path.is_file(): print("Could not find data.h5") return tracks['square_mass'] = 0 data = h5py.File(data_path.absolute(), "r") width,height = nd2.metadata['width'],nd2.metadata['height'] print("Starting Square ROIs for position " + str(pos)) for frame in sorted(tracks['frame'].unique()): frame_data_index = frame-data.attrs['frame_min'] print("Frame " + str(int(frame))) t = tracks[(tracks['frame'] == frame) & (tracks['enabled'] == True)] #t = tracks[(tracks['frame'] == frame)] fl_image = data['bg_corr'][int(frame_data_index)] for index, record in t.iterrows(): x = int((record['bbox_x1'] + record['bbox_x2']) // 2) y = int((record['bbox_y1'] + record['bbox_y2']) // 2) x1 = max(0,x - size) y1 = max(0,y - size) x2 = min(height-1,x + size) y2 = min(width-1,y + size) im_slice = fl_image[x1:x2,y1:y2] tracks.loc[(tracks['frame'] == frame) & (tracks['particle'] == record['particle']), 'square_mass'] = im_slice.sum() data.close() tracks.to_csv(tracks_path.absolute()) print("Done") def get_position_folders(out_dir: str) -> list: """ Get a list of position folders from the output directory Parameters: out_dir (str): Output directory path Returns: list: List of tuples containing position number and path """ folders = [] for path in pathlib.Path(out_dir).iterdir(): if not path.is_dir(): continue if not re.search('^XY0*\\d+$', path.name): continue number_str = path.name[2:].lstrip('0') pos = int(number_str) if number_str else 0 folders.append((pos,path)) return folders def get_tracking_folders(out_dir: str, pos: list) -> list: """ Get a list of tracking folders for specified positions Parameters: out_dir (str): Output directory path pos (list): List of position numbers Returns: list: List of tuples containing position number and path """ pos = list(set(pos)) pos_folders = get_position_folders(out_dir) if len(pos) > 0: pos_folders = [p for p in pos_folders if p[0] in pos] folders = [] for folder in pos_folders: features_path = folder[1].joinpath('features.csv') if not features_path.is_file(): print("Position " + str(folder[0]) + ":", "Could not find features.csv") continue data_path = folder[1].joinpath('data.h5') if not data_path.is_file(): print("Position " + str(folder[0]) + ":", "Could not find data.h5") continue folders.append(folder) return folders def get_tracked_folders(out_dir: str, pos: list) -> list: """ Get a list of tracked folders for specified positions Parameters: out_dir (str): Output directory path pos (list): List of position numbers Returns: list: List of tuples containing position number and path """ pos = list(set(pos)) pos_folders = get_position_folders(out_dir) if len(pos) > 0: pos_folders = [p for p in pos_folders if p[0] in pos] folders = [] for folder in pos_folders: features_path = folder[1].joinpath('features.csv') if not features_path.is_file(): print("Position " + str(folder[0]) + ":", "Could not find features.csv") continue data_path = folder[1].joinpath('data.h5') if not data_path.is_file(): print("Position " + str(folder[0]) + ":", "Could not find data.h5") continue tracks_path = folder[1].joinpath('tracks.csv') if not tracks_path.is_file(): print("Position " + str(folder[0]) + ":", "Could not find tracks.csv") continue folders.append(folder) return folders def tracking_pyama(out_dir: str, pos: list, expand: int = 0) -> None: """ Perform Pyama tracking on specified positions and saves them into the output directory Parameters: out_dir (str): Output directory path pos (list): List of position numbers expand (int): Expansion factor for labels Returns: None """ folders = get_tracking_folders(out_dir,pos) for folder in folders: track_position_pyama(folder[0],folder[1],expand) def track_position_pyama(pos: int, pos_path: pathlib.Path, expand: int) -> None: """ Perform Pyama tracking on a single position. data.h5 contains the segmentation and the background corrected fluorescence images. features.csv contains the features of the particles. Bounding boxes, integrated fluorescence. The track is being saved as tracks.csv file Parameters: pos (int): Position number pos_path (pathlib.Path): Path to position directory expand (int): Expansion factor for labels Returns: None """ features_path = pos_path.joinpath('features.csv') features = pd.read_csv(features_path.absolute(),index_col=0) data_path = pos_path.joinpath('data.h5') data = h5py.File(data_path.absolute(), "r") data_labels = data['labels'] min_track_length = data.attrs['frame_max']-data.attrs['frame_min']+1 tracks = [] frames = features['frame'].unique() frames.sort() print("Starting Pyama Tracking for position " + str(pos)) for frame in frames: print("Frame " + str(frame)) frame_data_index = frame-data.attrs['frame_min'] frame_features = features[features['frame'] == frame] if len(tracks) == 0: for index, row in frame_features.iterrows(): tracks.append([row]) else: matched_labels = [] frame_labels = data_labels[frame_data_index] prev_labels = data_labels[frame_data_index-1] # Add optional label expansion here if expand > 0: frame_labels = sk.segmentation.expand_labels(frame_labels,expand) prev_labels = sk.segmentation.expand_labels(prev_labels,expand) # Add frames left to check if len(track) + frames_left < min_frames remove_indices = [] for i in range(len(tracks)): track = tracks[i] prev_row = track[len(track)-1] # no memory so ignore any lost if frame - prev_row['frame'] > 1: remove_indices.append(i) # dont add track to completed (we only want entire tracks) continue #frame_labels = data_labels[frame_data_index] #prev_labels = data_labels[frame_data_index-1] # Add optional label expansion here #if expand > 0: #frame_labels = sk.segmentation.expand_labels(frame_labels,expand) #prev_labels = sk.segmentation.expand_labels(prev_labels,expand) label_slice = frame_labels[prev_labels == prev_row['label']] found_labels = sorted(np.unique(label_slice)) if len(found_labels) > 0 and found_labels[0] == 0: found_labels.pop(0) if len(found_labels) == 0: # No match for this track continue #print(found_labels) local_matches = [] for label in found_labels: row = frame_features[frame_features['label'] == label].iloc[0] # already found parent if row['label'] in matched_labels: continue local_matches.append({'s': row['area'], 'r': row}) if len(local_matches) > 0: local_matches = sorted(local_matches, key=lambda r: r['s'], reverse=True) selected_match = local_matches[0] track.append(selected_match['r']) matched_labels.append(selected_match['r']['label']) # Remove tracks that can be ignored if len(remove_indices) > 0: remove_indices.reverse() for index in remove_indices: tracks.pop(index) unmatched_rows = frame_features[~np.isin(frame_features['label'],matched_labels)] for index, row in unmatched_rows.iterrows(): tracks.append([row]) data.close() result_data = [] particle_id = 0 for track in tracks: if len(track) < min_track_length: continue for row in track: row['particle'] = particle_id row['enabled'] = True result_data.append(row) particle_id += 1 tracks = pd.DataFrame(result_data) # Find large particles and disable large_particles = tracks[tracks['area'] > 10000]['particle'].unique() tracks.loc[np.isin(tracks['particle'], large_particles), 'enabled'] = False tracks_path = pos_path.joinpath('tracks.csv') tracks.to_csv(tracks_path.absolute()) print("Done") def position_path(out_dir: str, pos: int) -> pathlib.Path: """ Get the path for a specific position Parameters: out_dir (str): Output directory path pos (int): Position number Returns: pathlib.Path: Path to the position directory """ for path in pathlib.Path(out_dir).iterdir(): if not path.is_dir(): continue if not re.search('XY0*' + str(pos) + '$', path.name): continue return path return None def pyama_segmentation(img: np.ndarray) -> np.ndarray: """ Perform Pyama segmentation on an image Parameters: img (np.ndarray): Input image Returns: np.ndarray: Labeled segmentation of the image """ binary_segmentation = binarize_frame(img) # remove small objects MIN_SIZE=1000 sk.morphology.remove_small_objects(binary_segmentation,min_size=1000,out=binary_segmentation) # convert binary mask to labels (1,2,3,...) return sk.measure.label(binary_segmentation, connectivity=1) def segment_positions(nd2_path: str, out_dir: str, pos: list, seg_channel: int, fl_channels: list, frame_min: int = None, frame_max: int = None, bg_corr: bool = True) -> None: """ Segment positions from an ND2 file Parameters: nd2_path (str): Path to ND2 file out_dir (str): Output directory path pos (list): List of position numbers seg_channel (int): Segmentation channel index fl_channels (list): List of fluorescence channel indices frame_min (int): Minimum frame number frame_max (int): Maximum frame number bg_corr (bool): Whether to perform background correction Returns: None """ if not pathlib.Path(nd2_path).is_file(): print("Invalid ND2 Path") return fl_channels = list(set(fl_channels)) pos = list(set(pos)) # remove duplicates nd2 = ND2Reader(nd2_path) if seg_channel < 0 or seg_channel > len(nd2.metadata['channels']) - 1: print("Invalid Segmentation Channel") return for c in fl_channels: if c < 0 or c > len(nd2.metadata['channels']) - 1: print("Invalid Fluorescence Channel") return positions = list(nd2.metadata['fields_of_view']) if len(pos) > 0: positions = [p for p in positions if p in pos] if len(positions) == 0: print("Invalid Positions") return fl_channel_names = [nd2.metadata['channels'][c] for c in fl_channels] try: # Check and calculate padding max_field = max(nd2.metadata['fields_of_view']) if max_field > 0: padding = int(np.ceil(np.log10(max_field))) else: # Save metadata to a text file with open("metadata_output.txt", "w") as file: file.write(str(nd2.metadata)) print("Warning: fields_of_view contains zero or negative values.") padding = 0 # or any default you prefer except KeyError: print("Error: 'fields_of_view' key not found in metadata.") padding = 0 # or any default you prefer frames = list(nd2.metadata['frames']) if frame_min is not None: if frame_min not in frames: print('Invalid frame_min') return else: frame_min = frames[0] if frame_max is not None: if frame_max not in frames: print('Invalid frame_max') return else: frame_max = frames[-1] if frame_max < frame_min: print('frame_max must be greater or equal to frame_min') return frames = [f for f in frames if frame_min <= f <= frame_max] width, height, num_frames = nd2.metadata['width'], nd2.metadata['height'], len(frames) print('Segmentation Channel: ' + nd2.metadata['channels'][seg_channel]) print('Fluorescence Channels: ' + ', '.join(fl_channel_names)) for pos in positions: print(f"Segmenting position {pos}") pos_dir = pathlib.Path(out_dir).joinpath(f'XY{str(pos).zfill(padding)}') pos_dir.mkdir(parents=True, exist_ok=True) file_path = pos_dir.joinpath('data.h5') feature_keys = ['x', 'y'] + [f'brightness_{i}' for i in range(len(fl_channels))] + ['area', 'frame', 'label', 'bbox_x1', 'bbox_x2', 'bbox_y1', 'bbox_y2'] feature_data = {key: [] for key in feature_keys} with h5py.File(file_path.absolute(), "w") as file_handle: data_labels = file_handle.create_dataset('labels', (num_frames, height, width), dtype=np.uint16, chunks=(1, height, width)) data_fl = file_handle.create_dataset('fluorescence', (num_frames, len(fl_channels), height, width), dtype=np.float64, chunks=(1, 1, height, width)) file_handle.attrs['frame_min'] = frame_min file_handle.attrs['frame_max'] = frame_max file_handle.attrs['seg_channel'] = seg_channel file_handle.attrs['fl_channels'] = fl_channels file_handle.attrs['fl_channel_names'] = fl_channel_names file_handle.attrs['width'] = nd2.metadata['width'] file_handle.attrs['height'] = nd2.metadata['height'] file_handle.attrs['pixel_microns'] = nd2.metadata['pixel_microns'] for index, frame in enumerate(frames): frame_image = nd2.get_frame_2D(t=frame, c=seg_channel, v=pos) binary_segmentation = binarize_frame(frame_image) sk.morphology.remove_small_objects(binary_segmentation, min_size=1000, out=binary_segmentation) label_segmentation = sk.measure.label(binary_segmentation, connectivity=1) frame_fl_images = [] for c in fl_channels: frame_fl_image = nd2.get_frame_2D(t=frame, c=c, v=pos) if bg_corr: frame_fl_image = background_correction(frame_fl_image, label_segmentation, 5, 5, 0.5) frame_fl_images.append(frame_fl_image) props = sk.measure.regionprops(label_segmentation) print(f"Frame {frame}: {len(props)} features") for prop in props: if prop.bbox[0] == 0 or prop.bbox[1] == 0 or prop.bbox[2] == height or prop.bbox[3] == width: label_segmentation[label_segmentation == prop.label] = 0 continue x, y = prop.centroid feature_data['x'].append(x) feature_data['y'].append(y) for i, fl_image in enumerate(frame_fl_images): feature_data[f'brightness_{i}'].append(fl_image[tuple(prop.coords.T)].sum()) feature_data['area'].append(prop.area) feature_data['frame'].append(frame) feature_data['label'].append(prop.label) feature_data['bbox_x1'].append(prop.bbox[0]) feature_data['bbox_y1'].append(prop.bbox[1]) feature_data['bbox_x2'].append(prop.bbox[2] - 1) feature_data['bbox_y2'].append(prop.bbox[3] - 1) data_labels[index, :, :] = label_segmentation for i, fl_image in enumerate(frame_fl_images): data_fl[index, i, :, :] = fl_image features_path = pos_dir.joinpath('features.csv') features = pd.DataFrame(feature_data) features.to_csv(features_path.absolute()) print("Done") def background_spline(image, img_mask, countX, countY, overlap): """ Creates a background model using a grid of sampling points and spline interpolation. Used for background correction of microscopy images by modeling systematic illumination variations. Part of the pipeline for processing fluorescence data. Parameters: image (np.ndarray): Input microscopy image img_mask (np.ndarray): Binary mask of regions to exclude (e.g. cells) countX (int): Number of grid points in X direction countY (int): Number of grid points in Y direction overlap (float): Overlap between grid windows (0-1) Returns: np.ndarray: Interpolated background map same size as input image """ # Get image dimensions h,w = image.shape # Calculate size of sampling windows based on grid density and overlap sizeX = int(w/((countX - (countX-1)*overlap)*2)) sizeY = int(h/((countY - (countY-1)*overlap)*2)) # Create grid points for sampling background pointsX = np.linspace(sizeX,w-(sizeX),countX).astype(int) pointsY = np.linspace(sizeY,h-(sizeY),countY).astype(int) # Create masked array to ignore foreground objects masked_img = np.ma.masked_array(image, mask=img_mask) # Sample background at each grid point pos = [] vals = [] for ix in range(len(pointsX)): for iy in range(len(pointsY)): x = pointsX[ix] y = pointsY[iy] # Get sampling window boundaries x1,x2 = max(0,x-sizeX),min(w-1,x+sizeX) y1,y2 = max(0,y-sizeY),min(h-1,y+sizeY) # Extract window and calculate statistics sub_image = masked_img[y1:y2,x1:x2] vals.append([np.ma.mean(sub_image),np.ma.median(sub_image),np.ma.var(sub_image)]) pos.append([x,y,ix,iy]) # Convert to numpy arrays vals = np.array(vals) pos = np.array(pos) # Create support points for spline interpolation using median values fit_support = np.empty((countX, countY)) for i in range(len(pos)): fit_support[pos[i,2],pos[i,3]] = vals[i,1] # Interpolate background using bicubic spline bg_spline = scipy.interpolate.RectBivariateSpline(x=pointsX, y=pointsY, z=fit_support) return bg_spline(x=range(w), y=range(h)).T def background_correction(image,img_mask,countX,countY,overlap = 0.1): """ """ h,w = image.shape patch = background_spline(image,img_mask,countX,countY,overlap) bg_mean = patch.mean() bg_interp = patch.copy() A = np.divide(bg_interp, bg_mean) bg_interp = np.subtract(image, bg_interp) bg_interp = np.divide(bg_interp, np.median(A, axis=0, keepdims=True)) return bg_interp def moonraedler_dir(): p = pathlib.Path('/project/ag-moonraedler') if p.is_dir(): return p.absolute() p = pathlib.Path('//z-sv-dfsroot.ad.physik.uni-muenchen.de/dfsextern/project/ag-moonraedler') if p.is_dir(): return p.absolute()
import cv2 import numpy as np import tifffile from io import BytesIO import base64 from PIL import Image def read_tiff(file_path, channel=0): """ Reads a TIFF file and returns the data as a numpy array. """ tif = tifffile.TiffFile(file_path) tif_data = tif.asarray()[channel] return tif_data def map_uint16_to_uint8(img, lower_bound=None, upper_bound=None): ''' Map a 16-bit image trough a lookup table to convert it to 8-bit. Parameters ---------- img: numpy.ndarray[np.uint16] image that should be mapped lower_bound: int, optional lower bound of the range that should be mapped to ``[0, 255]``, value must be in the range ``[0, 65535]`` and smaller than `upper_bound` (defaults to ``numpy.min(img)``) upper_bound: int, optional upper bound of the range that should be mapped to ``[0, 255]``, value must be in the range ``[0, 65535]`` and larger than `lower_bound` (defaults to ``numpy.max(img)``) Returns ------- numpy.ndarray[uint8] ''' if not(0 <= lower_bound < 2**16) and lower_bound is not None: raise ValueError( '"lower_bound" must be in the range [0, 65535]') if not(0 <= upper_bound < 2**16) and upper_bound is not None: raise ValueError( '"upper_bound" must be in the range [0, 65535]') if lower_bound is None: lower_bound = np.min(img) if upper_bound is None: upper_bound = np.max(img) if lower_bound >= upper_bound: raise ValueError( '"lower_bound" must be smaller than "upper_bound"') lut = np.concatenate([ np.zeros(lower_bound, dtype=np.uint16), np.linspace(0, 255, upper_bound - lower_bound).astype(np.uint16), np.ones(2**16 - upper_bound, dtype=np.uint16) * 255 ]) return lut[img].astype(np.uint8) def get_channel_image(tiff_data, channel): """ Returns the image for the specified channel as a base64 encoded string. """ # Get the channel data channel_data = tiff_data[:, :, channel] # Normalize the data to 0-255 range channel_data = (channel_data - np.min(channel_data)) / (np.max(channel_data) - np.min(channel_data)) * 255 # Convert the data to uint8 type channel_data = channel_data.astype(np.uint8) # Convert the data to a base64 encoded string return tifffile.imwrite(channel_data) def numpy_to_b64_string(image): rawBytes = BytesIO() im = Image.fromarray(image) im.save(rawBytes, format="JPEG") rawBytes.seek(0) image = base64.b64encode(rawBytes.getvalue()) img_str = image.decode('utf-8') return img_str def extract_overlay(image_path, vmin_bf_channel=0, vmax_bf_channel=40000, vmin_overlay_red_channel=4, vmax_overlay_red_channel=400, path=True): if path is True: tiff = tifffile.TiffFile(image_path) else: tiff = image_path red = cv2.cvtColor(map_uint16_to_uint8(tiff.asarray()[1], lower_bound=vmin_overlay_red_channel, upper_bound=vmax_overlay_red_channel), cv2.COLOR_GRAY2BGR) red[:,:,2]=0 red[:,:,1]=0 gray = cv2.cvtColor(map_uint16_to_uint8(tiff.asarray()[0], lower_bound=vmin_bf_channel, upper_bound=vmax_bf_channel), cv2.COLOR_GRAY2BGR) result = cv2.add((red), (gray)) return result
from flask import Flask, render_template, request, redirect, url_for, jsonify from src.pyama_web.backend.gui import CellViewer import src.pyama_web.core.pyama_util as pyama_util import os class App: def __init__(self): self.app = Flask(__name__) self.cell_viewer = None def routes(self): @self.app.route('/test') def test(): return 'test' @self.app.route('/') def index(): return render_template('index.html') @self.app.route('/select_paths', methods=['POST']) def select_paths(): data = request.json nd2_path = data['nd2_path'] out_path = data['out_path'] redirect_to = data['redirect_to'] if not nd2_path or not out_path: return jsonify({'error': 'Both ND2 path and output path must be selected'}), 400 init_type = 'view' if redirect_to == 'view' else 'analysis' self.cell_viewer = CellViewer(nd2_path=nd2_path, output_path=out_path, init_type=init_type) self.cell_viewer.nd2_path = nd2_path self.cell_viewer.output_path = out_path if redirect_to == 'view': return jsonify({'redirect': url_for('view')}) elif redirect_to == 'analysis': return jsonify({'redirect': url_for('analysis')}) else: return jsonify({'redirect': url_for('index')}) @self.app.route('/view', methods=['GET', 'POST']) def view(): if self.cell_viewer is None: return redirect(url_for('index')) self.cell_viewer.position_changed() current_particle_index = self.cell_viewer.particle_index() return render_template('view.html', channel_image=self.cell_viewer.return_image(), n_positions=len(self.cell_viewer.positions), n_channels=self.cell_viewer.channel_max, n_frames=self.cell_viewer.frame_max, all_particles_len=self.cell_viewer.all_particles_len, current_particle_index=current_particle_index, brightness_plot=self.cell_viewer.brightness_plot, disabled_particles=self.cell_viewer.disabled_particles) @self.app.route('/preprocess', methods=['GET', 'POST']) def processing(): return render_template('preprocess.html') @self.app.route('/documentation', methods=['GET', 'POST']) def documentation(): svg = "static/images/UserTutorial.svg" return render_template('documentation.html', svg=svg) @self.app.route('/update_image', methods=['GET', 'POST']) def update_image(): new_position = int(request.form['position']) new_channel = int(request.form['channel']) new_frame = int(request.form['frame']) new_particle = int(request.form['particle']) if new_position != self.cell_viewer.position: self.cell_viewer.position = self.cell_viewer.position_options[new_position] self.cell_viewer.position_changed() if new_particle != self.cell_viewer.particle: self.cell_viewer.particle = self.cell_viewer.all_particles[new_particle] self.cell_viewer.particle_changed() self.cell_viewer.channel = new_channel self.cell_viewer.frame = new_frame self.cell_viewer.get_channel_image() self.cell_viewer.draw_outlines() return jsonify({ 'channel_image': self.cell_viewer.return_image(), 'brightness_plot': self.cell_viewer.brightness_plot, 'all_particles_len': self.cell_viewer.all_particles_len, 'particle_enabled': self.cell_viewer.particle_enabled, 'current_particle': self.cell_viewer.particle, 'disabled_particles': self.cell_viewer.disabled_particles }) @self.app.route('/update_particle_enabled', methods=['POST']) def update_particle_enabled(): data = request.json enabled = data['enabled'] if self.cell_viewer: self.cell_viewer.particle_enabled = enabled self.cell_viewer.particle_enabled_changed() return jsonify({ 'channel_image': self.cell_viewer.return_image(), 'brightness_plot': self.cell_viewer.brightness_plot, 'all_particles_len': self.cell_viewer.all_particles_len, 'disabled_particles': self.cell_viewer.disabled_particles }) return jsonify({'error': 'Cell viewer not initialized'}), 400 @self.app.route('/do_segmentation', methods=['POST']) def do_segmentation(): data = request.json nd2_path = self.cell_viewer.nd2_path out_dir = self.cell_viewer.output_path positions = list(range(data['position_min'], data['position_max'] + 1)) frame_min = data['frame_min'] frame_max = data['frame_max'] segmentation_channel = [] fluorescence_channels = [] for i in range(self.cell_viewer.channel_max + 1): channel_type = data[f'channel_{i}'] if channel_type == 'Brightfield': segmentation_channel.append(i) elif channel_type == 'Fluorescent': fluorescence_channels.append(i) segmentation_channel = segmentation_channel[0] if len(segmentation_channel) == 1 else segmentation_channel pyama_util.segment_positions(nd2_path, out_dir, positions, segmentation_channel, fluorescence_channels, frame_min=frame_min, frame_max=frame_max) return jsonify({'status': 'success'}) @self.app.route('/do_tracking', methods=['POST']) def do_tracking(): data = request.json out_dir = self.cell_viewer.output_path positions = list(range(data['position_min'], data['position_max'] + 1)) expand_labels = data['expand_labels'] pyama_util.tracking_pyama(out_dir, positions, expand=expand_labels) return jsonify({'status': 'success'}) @self.app.route('/do_square_rois', methods=['POST']) def do_square_rois(): data = request.json out_dir = self.cell_viewer.output_path positions = list(range(data['position_min'], data['position_max'] + 1)) square_um_size = data['square_size'] pyama_util.square_roi(out_dir, positions, square_um_size) return jsonify({'status': 'success'}) @self.app.route('/do_export', methods=['POST']) def do_export(): data = request.json out_dir = self.cell_viewer.output_path positions = list(range(data['position_min'], data['position_max'] + 1)) minutes = data['minutes'] try: pyama_util.csv_output(out_dir, positions, minutes) return jsonify({'status': 'success'}) except Exception as e: return jsonify({'status': 'error', 'message': str(e)}), 400 @self.app.route('/analysis') def analysis(): if self.cell_viewer is None: return redirect(url_for('index')) n_positions = len(self.cell_viewer.nd2.metadata['fields_of_view'])+1 return render_template('analysis.html', n_positions=n_positions, n_channels=self.cell_viewer.channel_max, n_frames=self.cell_viewer.frame_max) @self.app.route('/list_directory', methods=['GET']) def list_directory(): path = request.args.get('path', '/') try: items = os.listdir(path) return jsonify({ 'path': path, 'items': [{'name': item, 'isDirectory': os.path.isdir(os.path.join(path, item))} for item in items] }) except Exception as e: return jsonify({'error': str(e)}), 400 @self.app.route('/select_folder', methods=['POST']) def select_folder(): path = request.json['path'] # Here you can add logic to handle the selected folder return jsonify({'message': f'Folder selected: {path}'}) def load_paths(self, file_path): with open(file_path, mode='r') as file: paths = [line.strip() for line in file] return paths def run(self): self.app.run(host='0.0.0.0', port=8000, debug=True) app_instance = App() app_instance.routes() flask_app = app_instance.app if __name__ == '__main__': app_instance.run()
import os import re import cv2 import h5py import numpy as np import pandas as pd import plotly.graph_objs as go from plotly.subplots import make_subplots from nd2reader import ND2Reader import plotly.io as pio from time import sleep from io import BytesIO import base64 from PIL import Image import pathlib import warnings warnings.filterwarnings("ignore", category=np.VisibleDeprecationWarning) def are_all_enabled(group): """ Check if all values in the group are equal to 1. Returns True if all values are 1, False otherwise. """ return (group == 1).all() def numpy_to_b64_string(image): rawBytes = BytesIO() im = Image.fromarray(image) im.save(rawBytes, format="JPEG") rawBytes.seek(0) image = base64.b64encode(rawBytes.getvalue()) img_str = image.decode('utf-8') return img_str class CellViewer: def __init__(self, nd2_path, output_path, init_type='view'): self.output_path = pathlib.Path(output_path) self.output_path = output_path self.nd2 = ND2Reader(nd2_path) self.file = None self.COLOR_GRAY = '#808080' self.COLOR_RED = 'Red' self.COLOR_ORANGE = '#FF8C00' self.OPACITY_SELECTED = 1 self.OPACITY_DEFAULT = 0.5 self.frame_change_suppress = False self.particle = None self.position = None self.key_down = {} self.disabled_particles = [] # Only run position-related initialization if init_type is 'view' if init_type == 'view': # parse valid positions self.get_positions() #print(self.positions) self.frame_min = 0 self.frame_max = self.nd2.metadata['num_frames']-1 self.frame = self.frame_min self.channel = 0 self.channel_min = 0 self.channel_max = len(self.nd2.metadata['channels'])-1 #self.max_pixel_value = np.iinfo(np.uint16).max self.max_pixel_value = 10000 self.image_size = 400 self.outline_kernel = np.array([[0,0,1,0,0],[0,1,1,1,0],[1,1,0,1,1],[0,1,1,1,0],[0,0,1,0,0]]) # Replacing widgets from the show() method: self.brightness_figure = go.Figure() self.brightness_figure.update_layout(title='Brightness', height=1200) self.brightness_lines = go.Scatter(x=[], y=[], mode='lines') self.brightness_cursor_line = go.Scatter(x=[0,0], y=[0,1], mode='lines', line=dict(color=self.COLOR_RED)) self.area_figure = go.Figure() self.area_figure.update_layout(title='Area') self.area_lines = go.Scatter(x=[], y=[], mode='lines') self.area_cursor_line = go.Scatter(x=[0,0], y=[0,1], mode='lines', line=dict(color=self.COLOR_RED)) controls_widgets = [] if init_type == 'view': self.position_options = [] for pos in self.positions: self.position_options.append((str(pos[0]), pos)) # Example: if self.positions is [(0, 'XY00'), (1, 'XY01')] # then position_options = [('0', (0, 'XY00')), ('1', (1, 'XY01'))] # position_options is a list of tuples, where the first element is a string and the second element is a tuple self.position = self.position_options[0] # Replacing widgets.Dropdown, widgets.IntSlider, and widgets.Checkbox with dictionaries self.position_dropdown = {'type': 'Dropdown', 'description': 'Position:', 'options': self.position_options} self.max_value_slider = {'type': 'IntSlider', 'min': 0, 'max': np.iinfo(np.uint16).max, 'description': 'Max Pixel Value (Contrast)', 'value': self.max_pixel_value} self.frame_slider = {'type': 'IntSlider', 'description': 'Frame', 'value': self.frame} self.channel_slider = {'type': 'IntSlider', 'min': self.channel_min, 'max': self.channel_max, 'description': 'Channel', 'value': self.channel} self.particle_dropdown = {'type': 'Dropdown'} self.enabled_checkbox = {'type': 'Checkbox', 'description': 'Cell Enabled', 'value': False} self.area_figure.update_layout(height=300) self.brightness_plot = self.plotly_to_json(self.brightness_figure) def plotly_to_json(self, fig): return pio.to_json(fig) def get_positions(self): # Will only get positions that have the necessary files (data.h5, features.csv, tracks.csv) self.positions = [] folders = self.get_subdirs(self.output_path) for folder in folders: match = re.search(r'^XY0*(\d+)$', folder) if not match: continue pos_files = self.get_files(os.path.join(self.output_path,folder)) self.pos_files = pos_files if not 'data.h5' in pos_files: continue if not 'features.csv' in pos_files: continue if not 'tracks.csv' in pos_files: continue #print(pos_files) # Create tuple with position number and folder name pos = (int(match.group(1)), folder) self.positions.append(pos) self.positions = sorted(self.positions, key=lambda p: p[0], reverse=False) def get_subdirs(self, directory): return [d for d in os.listdir(directory) if os.path.isdir(os.path.join(directory,d))] def get_files(self, directory): return [d for d in os.listdir(directory) if os.path.isfile(os.path.join(directory,d))] def get_track_data(self, particle, field): t = self.all_tracks[self.all_tracks['particle'] == particle] return t['frame'].values, t[field].values def update_plots(self): # sleep(0.150) particle_index = self.particle_index() def is_enabled(value): enabled_values = {1, '1', '1.0', 1.0, True, 'True'} value_str = str(value).lower() enabled_values_str = {str(v).lower() for v in enabled_values} return value_str in enabled_values_str particle_states = [] ix=0 for particle in self.all_particles: # Get just the first frame's enabled value for this particle particle_data = self.all_tracks[self.all_tracks['particle'] == particle] enabled_value = particle_data['enabled'].iloc[0] # Get first value particle_states.append(1 if is_enabled(enabled_value) else 0) if particle_index == particle: if particle_states[-1] == 1: self.particle_enabled = True else: self.particle_enabled = False if particle_states[-1] == 0: self.disabled_particles.append(float(ix)) ix+=1 # Initialize empty lists for area data area_x = [] area_y = [] # Add enabled areas except selected particle for i in range(self.all_particles_len): if particle_states[i] == 1 and i != particle_index: try: area_x.append(self.area_x[i]) area_y.append(self.area_y[i]) except IndexError: print("IndexError at particle", i) # print("area_x shape and length:", (area_x[0]).shape, len(area_x)) # Add the selected particle area area_x.append(self.area_x[particle_index]) area_y.append(self.area_y[particle_index]) # Initialize empty lists for brightness data brightness_x = [] brightness_y = [] # Add enabled brightness values except selected particle for i in range(self.all_particles_len): # if particle_states[i] == 1 and i != particle_index: try: brightness_x.append(self.brightness_x[i]) brightness_y.append(self.brightness_y[i]) except IndexError: print("IndexError at particle", i," (brightness)") # Add the selected particle brightness # brightness_x.append(self.brightness_x[particle_index]) # brightness_y.append(self.brightness_y[particle_index]) opacities = [self.OPACITY_DEFAULT] * len(brightness_x) opacities = particle_states colors = [self.COLOR_GRAY] * len(brightness_x) if self.particle_enabled == True: colors[particle_index] = self.COLOR_RED opacities[particle_index] = self.OPACITY_SELECTED else: colors[particle_index] = self.COLOR_ORANGE opacities[particle_index] = self.OPACITY_SELECTED # Update brightness tracks self.brightness_figure.data = [] for i in range(len(brightness_x)): self.brightness_figure.add_trace(go.Scatter(x=brightness_x[i], y=brightness_y[i], mode='lines', line=dict(color=colors[i]), opacity=opacities[i], name=f'Trace {i}')) self.brightness_figure.add_trace(go.Scatter(x=brightness_x[particle_index], y=brightness_y[particle_index], mode='lines', line=dict(color=colors[particle_index]), opacity=opacities[particle_index], name=f'Trace {particle_index} (Highlighted)')) # self.brightness_figure.add_trace(self.brightness_cursor_line) # Update area tracks self.area_figure.data = [] for i in range(len(area_x)): self.area_figure.add_trace(go.Scatter(x=area_x[i], y=area_y[i], mode='lines', line=dict(color=colors[i]), opacity=opacities[i])) self.area_figure.add_trace(self.area_cursor_line) self.brightness_plot = self.plotly_to_json(self.brightness_figure) def position_changed(self): self.data_dir = os.path.join(self.output_path,self.position[1][1]) if self.file is not None: self.file.close() self.file = h5py.File(os.path.join(self.data_dir,'data.h5'), "r") self.frame_min = self.file.attrs['frame_min'] self.frame_max = self.file.attrs['frame_max'] self.frame = self.frame_min self.brightness_figure = go.Figure() self.brightness_figure.update_layout(title='Brightness') self.brightness_lines = go.Scatter(x=[], y=[], mode='lines') self.brightness_cursor_line = go.Scatter(x=[0,0], y=[0,1], mode='lines', line=dict(color=self.COLOR_RED)) self.area_figure = go.Figure() self.area_figure.update_layout(title='Area') self.area_lines = go.Scatter(x=[], y=[], mode='lines') self.area_cursor_line = go.Scatter(x=[0,0], y=[0,1], mode='lines', line=dict(color=self.COLOR_RED)) self.brightness_figure.update_layout(title=self.file.attrs['fl_channel_names'][0]) # set Brightnesses names for plots file_handle.attrs['fl_channel_names'] self.all_tracks = pd.read_csv(os.path.join(self.data_dir,'tracks.csv')) self.all_particles = list(self.all_tracks['particle'].unique()) self.all_particles_len = len(self.all_particles) self.brightness_x = [] self.brightness_y = [] for p in self.all_particles: x,y = self.get_track_data(p, 'brightness_0') self.brightness_x.append(x) self.brightness_y.append(y) # print("brightness_x length:", (len(self.brightness_x))) self.area_x = [] self.area_y = [] for p in self.all_particles: x,y = self.get_track_data(p, 'area') self.area_x.append(x) self.area_y.append(y) # print("area_x length:", (len(self.area_x))) colors = [self.COLOR_GRAY] * len(self.all_particles) colors[len(self.all_particles)-1] = self.COLOR_RED opacities = [self.OPACITY_DEFAULT] * len(self.all_particles) opacities[len(self.all_particles)-1] = self.OPACITY_SELECTED self.update_cursors() # self.brightness_figure.add_trace(self.brightness_lines) # self.brightness_figure.add_trace(self.brightness_cursor_line) self.area_figure.add_trace(self.area_lines) self.area_figure.add_trace(self.area_cursor_line) self.particle = None dropdown_options = [] for particle in self.all_particles: dropdown_options.append((str(particle), particle)) self.particle_dropdown['options'] = dropdown_options self.particle_dropdown['description'] = 'Cell (' + str(len(self.all_particles)) + '): ' # Stop slider from updating on every change & edit slider values # self.frame_change_suppress = True # if self.frame_min > self.frame_slider.max: # self.frame_slider.max = self.frame_max # self.frame_slider.min = self.frame_min # else: # self.frame_slider.min = self.frame_min # self.frame_slider.max = self.frame_max # self.frame_slider.value = self.frame # self.frame_change_suppress = False # Will be called if position actually changed (not initial) if self.particle is None: self.particle = self.particle_dropdown['options'][0][1] self.particle_changed() #self.update_cursors() else: self.frame_changed() self.brightness_plot = self.plotly_to_json(self.brightness_figure) # enable / disable current particle and save tracks to file def particle_enabled_changed(self): if self.particle_enabled == True: index_csv = 1 else: index_csv = 0 # self.all_tracks.loc[self.all_tracks['particle'] == self.particle, 'enabled'] = self.particle_enabled self.all_tracks.loc[self.all_tracks['particle'] == self.particle, 'enabled'] = index_csv self.all_tracks.to_csv(self.data_dir + '/tracks.csv') self.update_plots() self.draw_outlines() self.update_image() def particle_index(self): # print(f'Index current particle {self.all_particles.index(self.particle)}') return self.all_particles.index(self.particle) def particle_changed(self): def is_enabled(value): enabled_values = {1, '1', '1.0', 1.0, True, 'True'} value_str = str(value).lower() enabled_values_str = {str(v).lower() for v in enabled_values} return value_str in enabled_values_str enabled_value = self.all_tracks[self.all_tracks['particle'] == self.particle]['enabled'].iloc[0] enabled = is_enabled(enabled_value) # enabled = len(self.all_tracks[(self.all_tracks['particle'] == self.particle) & ((self.all_tracks['enabled'] == True))]) > 0 # set both so no update to file is applied self.particle_enabled = enabled self.enabled_checkbox['value'] = enabled self.update_plots() self.particle_tracks = self.all_tracks[self.all_tracks['particle'] == self.particle] # Get new Position for image self.x = int(self.particle_tracks['x'].values.mean()) - self.image_size self.y = int(self.particle_tracks['y'].values.mean()) - self.image_size self.x = max(0,min(self.nd2.metadata['height'] - 2*self.image_size, self.x)) self.y = max(0,min(self.nd2.metadata['width'] - 2*self.image_size, self.y)) self.get_channel_image() self.draw_outlines() self.update_image() def particle_dropdown_changed(self, change): if change['new'] is not self.particle: self.particle = change['new'] self.particle_changed() def position_dropdown_changed(self, change): if change['new'] is not self.position: self.position = change['new'] self.position_changed() def frame_slider_changed(self, change): if self.frame_change_suppress: return if change['new'] is not self.frame: self.frame = change['new'] self.frame_changed() def max_pixel_slider_changed(self, change): if change['new'] is not self.frame: self.max_pixel_value = change['new'] self.max_pixel_value_changed() def update_cursors(self): # Move Brightness Cursor self.brightness_cursor_line.x = [self.frame, self.frame] self.brightness_cursor_line.y = [0, 1] # Move Area Cursor self.area_cursor_line.x = [self.frame, self.frame] self.area_cursor_line.y = [0, 1] def frame_changed(self): self.update_cursors() self.get_channel_image() self.draw_outlines() self.update_image() def channel_changed(self): self.get_channel_image() self.update_image() def max_pixel_value_changed(self): self.get_channel_image() self.update_image() def channel_slider_changed(self, change): if change['new'] is not self.channel: self.channel = change['new'] self.channel_changed() def enabled_checkbox_changed(self, change): if change['new'] is not self.particle_enabled: self.particle_enabled = change['new'] self.particle_enabled_changed() def adjust_image(self, image, max_value): img = image.copy().astype(np.float64) img[img >= max_value] = np.iinfo(np.uint16).max img[img < max_value] /= max_value img[img < max_value] *= np.iinfo(np.uint16).max return img def get_channel_image(self): img = self.nd2.get_frame_2D(v=int(self.position[0]),c=self.channel,t=self.frame)[self.x:self.x+2*self.image_size,self.y:self.y+2*self.image_size] # There seems to be an issue with the arguments. Apparently v should be the position, but it's not working. # Instead, v seems to be the input for the frame. # img = self.nd2.get_frame_2D(v=0,c=self.channel,t=self.frame)[self.x:self.x+2*self.image_size,self.y:self.y+2*self.image_size] pixel_val = self.max_pixel_value if self.channel == 0: pixel_val = 40000 adjusted = self.adjust_image(img,pixel_val) self.channel_image = cv2.cvtColor(cv2.convertScaleAbs(adjusted, alpha=1./256., beta=-.49999),cv2.COLOR_GRAY2RGB) def update_image(self): img = self.combine_images(self.outline_image,self.channel_image,self.outline_mask) _, img_enc = cv2.imencode('.jpg', img) # self.image.value = img_enc.tobytes() def return_image(self): img = self.combine_images(self.outline_image,self.channel_image,self.outline_mask) return numpy_to_b64_string(img) # _, img_enc = cv2.imencode('.jpg', img) # self.image.value = img_enc.tobytes() def get_outline(self, img): f64_img = img.astype(np.float64) filter_img = cv2.filter2D(src=f64_img, ddepth=-1,kernel=self.outline_kernel) / self.outline_kernel.sum() filter_img[filter_img == f64_img] = 0 mask = (f64_img != filter_img) & (filter_img > 0) filter_img[mask] = img[mask] return filter_img.astype(img.dtype) def combine_images(self,a,b,m): mask = cv2.cvtColor(m,cv2.COLOR_GRAY2RGB) inv_mask = cv2.bitwise_not(mask) ma = cv2.bitwise_and(a,mask) mb = cv2.bitwise_and(b,inv_mask) return cv2.add(ma,mb) def get_particle_label(self): tracks = self.all_tracks[(self.all_tracks['frame'] == self.frame) & (self.all_tracks['particle'] == self.particle)] if len(tracks) == 0: return None return int(tracks.iloc[0]['label']) def draw_outlines(self): if self.frame < self.frame_min or self.frame > self.frame_max: self.outline_mask = np.zeros((self.image_size*2,self.image_size*2),dtype=np.uint8) self.outline_image = np.zeros((self.image_size*2,self.image_size*2,3),dtype=np.uint8) return all_labels = self.file['labels'][self.frame-self.frame_min] [self.x:self.x+2*self.image_size,self.y:self.y+2*self.image_size] outlines = self.get_outline(all_labels) image_shape = (self.channel_image.shape[0],self.channel_image.shape[1],3) overlay = np.zeros(image_shape,dtype=np.uint8) o = np.zeros(image_shape,dtype=np.uint8) frame_tracks = self.all_tracks[self.all_tracks['frame'] == self.frame] true_values = [1, '1', '1.0', 1.0, True, 'True', 'true', 'TRUE'] # Convert true_values to lowercase strings true_values_lower = [str(v).lower() for v in true_values] enabled_condition = ~frame_tracks['enabled'].astype(str).str.lower().isin(true_values_lower) # Get unique labels for disabled tracks enabled_labels = frame_tracks[~enabled_condition]['label'].unique() # enabled_labels = frame_tracks[frame_tracks['enabled'] == True]['label'].unique() tracked_labels = frame_tracks['label'].unique() # all tracked cells o = cv2.rectangle(o, (0,0), (image_shape[0],image_shape[1]), (255,0,0), -1) # Red m1 = np.isin(outlines, tracked_labels).astype(np.uint8)*255 overlay = self.combine_images(o,overlay,m1) # enabled cells o = cv2.rectangle(o, (0,0), (image_shape[0],image_shape[1]), (0,255,0), -1) # Green m2 = np.isin(outlines, enabled_labels).astype(np.uint8)*255 overlay = self.combine_images(o,overlay,m2) # Selected cell label = self.get_particle_label() if label is not None: if self.particle_enabled == True: o = cv2.rectangle(o, (0,0), (image_shape[0],image_shape[1]), (0,0,255), -1) # Dark Blue else: o = cv2.rectangle(o, (0,0), (image_shape[0],image_shape[1]), (0,140,255), -1) m3 = (outlines == label).astype(np.uint8)*255 overlay = self.combine_images(o,overlay,m3) self.outline_image = overlay #self.combine_images(overlay,self.image_data,m1) self.outline_mask = m1 def handle_keydown(self, event): if event['key'] in self.key_down and self.key_down[event['key']] == True: return self.key_down[event['key']] = True ctrl = event['ctrlKey'] if event['key'] == 'ArrowLeft': if ctrl: self.frame_slider['value'] = max(self.frame_min, self.frame - 10) else: self.frame_slider['value'] = max(self.frame_min, self.frame - 1) elif event['key'] == 'ArrowRight': if ctrl: self.frame_slider['value'] = min(self.frame_max, self.frame + 10) else: self.frame_slider['value'] = min(self.frame_max, self.frame + 1) elif event['key'] == 'c': channel = self.channel_slider['value'] + 1 if channel > self.channel_max: channel = self.channel_min self.channel_slider['value'] = channel elif event['key'] == 'ArrowUp': index = self.particle_index() if index < len(self.all_particles) - 1: self.particle_dropdown['value'] = self.all_particles[index+1] elif event['key'] == 'ArrowDown': index = self.particle_index() if index > 0: self.particle_dropdown['value'] = self.all_particles[index-1] elif event['key'] == 'Enter' and ctrl: self.enabled_checkbox['value'] = not self.enabled_checkbox['value'] def handle_keyup(self, event): self.key_down[event['key']] = False
# %% import src.pyama_web.core.pyama_util as pyama_util import src.pyama_web.backend.gui as gui AG_MOON = str(pyama_util.moonraedler_dir()) # %% # Segment position(s) # Path to ND2 File nd2_path = AG_MOON + '/Judith/Students/Simon_Master/230505_TF73_HuH7.nd2' # Output directory (will create a new folder per position in here) out_dir = AG_MOON + '/SPrins/Pyama_Test/Multi_FL_Test' # Positions to evaluate (zero based so position 1 would be 0, 2 would be 1 etc) # Comma seperated inside square brackets e.g. [1,2,3] # Empty brackets for all positions e.g. [] positions = [70,71] # Starting frame zero based # Set to None to ignore frame_min = None # End frame zero based (zero based) # Set to None to ignore frame_max = None # Channel to use for segmentation (zero based) segmentation_channel = 0 # Channel(s) to use for fluorescence tracks (zero based) # Comma separated inside square brackets fluorescence_channels = [1,2] pyama_util.segment_positions(nd2_path,out_dir,positions, segmentation_channel, fluorescence_channels,frame_min=frame_min,frame_max=frame_max) # %% # CellViewer GUI # Keybinds: # c: rotate through channels # arrowkey (left/right): previous/next frame # ctl + arrowkey (left/right): same as above but 10 frames instead of just 1 # arrowkey (down/up): previous/next cell # ctrl + enter: toggle cell (enabled/disabled) nd2_dir = AG_MOON + '/Judith/Students/Simon_Master/230505_TF73_HuH7.nd2' out_dir = AG_MOON + '/SPrins/Pyama_Test/Multi_FL_Test' gui.CellViewer(nd2_dir, out_dir).show() # %% # Track position(s) # Output directory (same as for segmentation) out_dir = AG_MOON + '/SPrins/Pyama_Test/Multi_FL_Test' # Positions to evaluate (zero based so position 1 would be 0, 2 would be 1 etc) # Folder names inside output directory are already zero based so XY001 would be 1 but the second position of the file # Comma seperated inside square brackets e.g. [1,2,3] # Empty brackets for all positions e.g. [] (will look for all folders in output directory that have been segmented and perform tracking on them) positions = [70,71] # Expand labels during tracking (can help if cells move a lot so that overlap between frames is not guaranteed) # Grows the labels for tracking by the amount of pixels in each direction expand_labels = 0 pyama_util.tracking_pyama(out_dir,positions,expand=expand_labels) # %% # Perform square ROIs "segmentation" for position(s) # Output directory (same as for segmentation) out_dir = AG_MOON + '/SPrins/Pyama_Test/Multi_FL_Test' # Positions to evaluate (same as tracking) positions = [70,71] # size in um of box to use for squares (width,height = 2*square_um_size) square_um_size = 30 pyama_util.square_roi(out_dir,positions,square_um_size) # %% # Convert position output to excel file for position(s) (old pyama output format) # Output directory (same as for segmentation) out_dir = AG_MOON + '/SPrins/Pyama_Test/Multi_FL_Test' # Positions to evaluate (same as tracking) positions = [70,71] # How many minutes are between each frame (for time in output) minutes_per_frame = 5 pyama_util.csv_output(out_dir,positions,minutes_per_frame) # %%
"""Welcome to Reflex! This file outlines the steps to create a basic app.""" import reflex as rx from rxconfig import config class State(rx.State): """The app state.""" ... def index() -> rx.Component: # Welcome Page (Index) return rx.container( rx.color_mode.button(position="top-right"), rx.vstack( rx.heading("Welcome to Reflex!", size="9"), rx.text( "Get started by editing ", rx.code(f"{config.app_name}/{config.app_name}.py"), size="5", ), rx.link( rx.button("Check out our docs!"), href="https://reflex.dev/docs/getting-started/introduction/", is_external=True, ), spacing="5", justify="center", min_height="85vh", ), rx.logo(), ) app = rx.App() app.add_page(index)
null
import reflex as rx config = rx.Config(app_name="app")
import reflex as rx from app.state import ProjectileState from app.components.input_form import input_form from app.components.trajectory_plot import ( trajectory_plot_component, ) from rxconfig import config def index() -> rx.Component: return rx.el.div( rx.el.div( rx.el.h1( "Projectile Trajectory Calculator", class_name="text-4xl font-extrabold text-center my-8 text-transparent bg-clip-text bg-gradient-to-r from-indigo-600 to-purple-600", ), rx.el.div( rx.el.div( input_form(), class_name="w-full md:w-1/3 lg:w-1/4 p-4", ), rx.el.div( rx.cond( ProjectileState.trajectory_data.length() > 1, trajectory_plot_component(), rx.el.div( rx.el.p( "Enter parameters and click 'Calculate Trajectory' to visualize the path.", class_name="text-gray-600 text-center p-10 text-lg", ), class_name="flex items-center justify-center h-[450px] bg-white rounded-lg shadow-md", ), ), class_name="w-full md:w-2/3 lg:w-3/4 p-4", ), class_name="flex flex-col md:flex-row", ), class_name="container mx-auto p-4", ), on_mount=ProjectileState.calculate_default_trajectory, class_name="min-h-screen bg-gradient-to-br from-gray-100 to-slate-200", ) app = rx.App(theme=rx.theme(appearance="light")) app.add_page(index)
import reflex as rx import numpy as np from typing import TypedDict, List as TypingList class TrajectoryPoint(TypedDict): x: float y: float class ProjectileState(rx.State): initial_velocity: float = 20.0 launch_angle_deg: float = 45.0 initial_height: float = 0.0 gravity: float = 9.81 time_step: float = 0.05 trajectory_data: TypingList[TrajectoryPoint] = [] max_height: float = 0.0 total_range: float = 0.0 time_of_flight: float = 0.0 error_message: str = "" @rx.var def max_height_str(self) -> str: return f"{self.max_height:.2f}" @rx.var def total_range_str(self) -> str: return f"{self.total_range:.2f}" @rx.var def time_of_flight_str(self) -> str: return f"{self.time_of_flight:.2f}" @rx.event def handle_form_submit(self, form_data: dict): self.error_message = "" try: self.initial_velocity = float( form_data["initial_velocity"] ) self.launch_angle_deg = float( form_data["launch_angle"] ) initial_height_str = form_data.get( "initial_height", "0.0" ) self.initial_height = float( initial_height_str if initial_height_str else "0.0" ) if self.initial_velocity <= 0: self.error_message = ( "Initial velocity must be positive." ) self._reset_outputs() return if not 0 <= self.launch_angle_deg <= 90: self.error_message = "Launch angle must be between 0 and 90 degrees." self._reset_outputs() return if self.initial_height < 0: self.error_message = ( "Initial height cannot be negative." ) self._reset_outputs() return except ValueError: self.error_message = "Invalid input. Please enter numeric values." self._reset_outputs() return except KeyError as e: self.error_message = f"Missing required field: {e}. Please fill all fields." self._reset_outputs() return self._calculate_trajectory() def _reset_outputs(self): self.trajectory_data = [] self.max_height = 0.0 self.total_range = 0.0 self.time_of_flight = 0.0 def _calculate_trajectory(self): self._reset_outputs() angle_rad = np.deg2rad(self.launch_angle_deg) v0x = self.initial_velocity * np.cos(angle_rad) v0y = self.initial_velocity * np.sin(angle_rad) if self.initial_height == 0 and ( self.launch_angle_deg == 0 or (v0y <= 0 and v0x == 0) ): self.trajectory_data = [ TrajectoryPoint(x=0, y=0) ] self.max_height = 0.0 self.total_range = 0.0 self.time_of_flight = 0.0 return t = 0.0 x = 0.0 y_current = self.initial_height current_max_height = self.initial_height self.trajectory_data.append( TrajectoryPoint(x=x, y=y_current) ) abs_v0y = abs(v0y) if self.gravity > 0: time_to_peak_if_positive_v0y = ( abs_v0y / self.gravity if v0y > 0 else 0 ) height_at_peak = ( self.initial_height + abs_v0y * time_to_peak_if_positive_v0y - 0.5 * self.gravity * time_to_peak_if_positive_v0y**2 if v0y > 0 else self.initial_height ) time_from_peak_to_ground = ( np.sqrt(2 * height_at_peak / self.gravity) if height_at_peak >= 0 else 0 ) max_sim_time = ( time_to_peak_if_positive_v0y + time_from_peak_to_ground ) * 1.5 + 5 * self.time_step if max_sim_time <= self.time_step: max_sim_time = 100 * self.time_step else: max_sim_time = ( 1000 * self.time_step if v0y <= 0 else ( 2 * self.initial_height / abs(v0y) if abs(v0y) > 0 else 1000 * self.time_step ) ) while True: t += self.time_step x = v0x * t y_new = ( self.initial_height + v0y * t - 0.5 * self.gravity * t**2 ) current_max_height = max( current_max_height, y_new ) if y_new < 0: y_prev = self.trajectory_data[-1]["y"] t_prev = t - self.time_step if y_prev > 0: t_fraction = y_prev / (y_prev - y_new) t_impact = ( t_prev + t_fraction * self.time_step ) x_impact = v0x * t_impact self.trajectory_data.append( TrajectoryPoint(x=x_impact, y=0.0) ) self.time_of_flight = t_impact self.total_range = x_impact else: self.trajectory_data.append( TrajectoryPoint( x=self.trajectory_data[-1]["x"], y=0.0, ) ) self.time_of_flight = t_prev self.total_range = self.trajectory_data[ -1 ]["x"] break self.trajectory_data.append( TrajectoryPoint(x=x, y=y_new) ) if t > max_sim_time: self.error_message = "Simulation time exceeded safety limit. Trajectory may be incomplete." self.time_of_flight = t self.total_range = x break self.max_height = current_max_height if len(self.trajectory_data) < 2: self.trajectory_data.append( TrajectoryPoint( x=self.total_range + 0.01, y=0.0 ) ) @rx.event def calculate_default_trajectory(self): self._calculate_trajectory()
null
import reflex as rx from app.state import ProjectileState def input_form() -> rx.Component: return rx.el.form( rx.el.div( rx.el.label( "Initial Velocity (m/s):", class_name="block text-sm font-medium text-gray-700", ), rx.el.input( name="initial_velocity", type="number", default_value=ProjectileState.initial_velocity.to_string(), placeholder="e.g., 20", step="0.1", required=True, class_name="mt-1 block w-full px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm", ), class_name="mb-4", ), rx.el.div( rx.el.label( "Launch Angle (degrees):", class_name="block text-sm font-medium text-gray-700", ), rx.el.input( name="launch_angle", type="number", default_value=ProjectileState.launch_angle_deg.to_string(), placeholder="e.g., 45", step="0.1", min="0", max="90", required=True, class_name="mt-1 block w-full px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm", ), class_name="mb-4", ), rx.el.div( rx.el.label( "Initial Height (m):", class_name="block text-sm font-medium text-gray-700", ), rx.el.input( name="initial_height", type="number", default_value=ProjectileState.initial_height.to_string(), placeholder="e.g., 0", step="0.1", min="0", required=True, class_name="mt-1 block w-full px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm", ), class_name="mb-4", ), rx.el.button( "Calculate Trajectory", type="submit", class_name="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-semibold py-2 px-4 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500", ), on_submit=ProjectileState.handle_form_submit, reset_on_submit=True, class_name="p-6 bg-gray-100 rounded-lg shadow-md", )
import reflex as rx from app.state import ProjectileState def trajectory_plot_component() -> rx.Component: return rx.el.div( rx.recharts.scatter_chart( rx.recharts.cartesian_grid( stroke_dasharray="3 3", stroke="#cccccc" ), rx.recharts.x_axis( rx.recharts.label( value="Distance (m)", position="insideBottom", dy=10, fill="#374151", ), type="number", data_key="x", domain=["auto", "auto"], allow_data_overflow=True, stroke="#4b5563", ), rx.recharts.y_axis( rx.recharts.label( value="Height (m)", angle=-90, position="insideLeft", dx=-5, fill="#374151", ), type="number", data_key="y", domain=[0, "auto"], allow_data_overflow=True, stroke="#4b5563", ), rx.recharts.scatter( data_key="y", name="Trajectory", fill="#4f46e5", line=True, shape="circle", ), rx.recharts.tooltip( cursor={"strokeDasharray": "3 3"} ), rx.recharts.legend( wrapper_style={"paddingTop": "10px"} ), data=ProjectileState.trajectory_data, height=450, margin={ "left": 20, "right": 20, "top": 25, "bottom": 20, }, class_name="bg-white p-4 rounded-lg shadow-md w-full", ), rx.el.div( rx.el.h3( "Trajectory Metrics", class_name="text-xl font-semibold mt-6 mb-3 text-gray-800", ), rx.el.div( rx.el.p( f"Max Height: {ProjectileState.max_height_str} m", class_name="text-md text-gray-700 py-1", ), rx.el.p( f"Total Range: {ProjectileState.total_range_str} m", class_name="text-md text-gray-700 py-1", ), rx.el.p( f"Time of Flight: {ProjectileState.time_of_flight_str} s", class_name="text-md text-gray-700 py-1", ), class_name="mt-4 p-4 bg-gray-100 rounded-lg shadow-sm", ), class_name="w-full", ), rx.cond( ProjectileState.error_message != "", rx.el.div( ProjectileState.error_message, class_name="mt-4 p-3 bg-red-100 text-red-700 border border-red-300 rounded-md shadow-sm", ), rx.fragment(), ), class_name="w-full", )
null
import reflex as rx config = rx.Config( app_name="app1", )
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
8