Spaces:
Sleeping
Sleeping
fix-viewer (#2)
Browse files- Replace xarray-ome with iohub native xarray support (142ef3afc8b6d75e56a17c8b493dff8a40faa450)
- Pin iohub to v0.3.2 from PyPI instead of git main (2ab73ce279d103d3d1e268169e7aa8a0602c70bb)
Files changed (3)
- demo_utils.py+14-35
- optimize_demo.py+6-6
- requirements.txt+1-2
20 unmodified lines21222324252627101 unmodified lines12913013113213313413513613711 unmodified lines14915015115215315415515615715815916016116216316416516616716816917017117217317417517615 unmodified lines1921931941951961971981 unmodified line200201202203204205206207208209210211212103 unmodified lines316317318319320321322323324325326128 unmodified lines45545645745845946046120 unmodified linesimport torchimport xarray as xrfrom numpy.typing import NDArrayfrom xarray_ome import open_ome_datasetfrom waveorder import utilfrom waveorder.models import isotropic_thin_3d101 unmodified linesplate, row: str, column: str, field: str, resolution: int = 0) -> xr.DataArray:"""Load a specific FOV from HCS plate using hybrid iohub + xarray-ome approach.Uses iohub for navigation, then xarray-ome for fast data loading.Parameters----------11 unmodified linesReturns-------xr.DataArrayImage data with labeled dimensions (T, C, Z, Y, X)"""# Navigate to position using iohub (fast)position_key = f"{row}/{column}/{field}"position = plate[position_key]# Get full zarr path from position (handle both Zarr V2 and V3)store = position.zgroup.storeif hasattr(store, 'path'):base_path = Path(store.path) # Zarr V2 (DirectoryStore)elif hasattr(store, 'root'):base_path = Path(store.root) # Zarr V3 (LocalStore)else:raise RuntimeError(f"Unknown store type: {type(store)}")position_path = base_path / position.zgroup.path# Load with xarray-ome (fast and reliable)fov_dataset = open_ome_dataset(position_path, resolution=resolution, validate=False)data_xr = fov_dataset["image"]return data_xr# === Data Loading ===15 unmodified linesReturns-------xr.DataArrayImage data with labeled dimensions (T, C, Z, Y, X)"""zarr_path = Path(zarr_path)fov_path = Path(fov_path)1 unmodified lineprint(f"Loading zarr store from: {zarr_path}")print(f"Accessing FOV: {fov_path}")# Load as xarray Datasetfov_dataset: xr.Dataset = open_ome_dataset(zarr_path / fov_path, resolution=resolution, validate=False)# Extract the image DataArraydata_xr = fov_dataset["image"]print(f"Loaded data shape: {dict(data_xr.sizes)}")print(f"Dimensions: {list(data_xr.dims)}")103 unmodified lines# Build selection dictionary for indexed dimensionssel_dict = {}if t is not None:sel_dict["T"] = int(t)if c is not None:sel_dict["C"] = int(c)if z is not None:sel_dict["Z"] = int(z)# Extract slice using xarray's labeled indexingslice_xr = data_xr.isel(**sel_dict) if sel_dict else data_xr128 unmodified linesfor dim in info["dims"]:coords = info["coords"][dim]if len(coords) > 0:print(f" {dim}: [{coords[0]:.2f} ... {coords[-1]:.2f}] (n={len(coords)})")# Print memory size estimatetotal_elements = np.prod(list(info["sizes"].values()))20 unmodified lines21222324252627101 unmodified lines12913013113213313413511 unmodified lines14714814915015115215315415515615715 unmodified lines1731741751761771781791 unmodified line181182183184185186187188103 unmodified lines292293294295296297298299300301302128 unmodified lines43143243343443543643743843944020 unmodified linesimport torchimport xarray as xrfrom numpy.typing import NDArrayfrom iohub import open_ome_zarrfrom waveorder import utilfrom waveorder.models import isotropic_thin_3d101 unmodified linesplate, row: str, column: str, field: str, resolution: int = 0) -> xr.DataArray:"""Load a specific FOV from HCS plate using iohub.Parameters----------11 unmodified linesReturns-------xr.DataArrayImage data with labeled dimensions (t, c, z, y, x)"""position_key = f"{row}/{column}/{field}"position = plate[position_key]return position.to_xarray()# === Data Loading ===15 unmodified linesReturns-------xr.DataArrayImage data with labeled dimensions (t, c, z, y, x)"""zarr_path = Path(zarr_path)fov_path = Path(fov_path)1 unmodified lineprint(f"Loading zarr store from: {zarr_path}")print(f"Accessing FOV: {fov_path}")position = open_ome_zarr(str(zarr_path / fov_path), mode="r")data_xr = position.to_xarray()print(f"Loaded data shape: {dict(data_xr.sizes)}")print(f"Dimensions: {list(data_xr.dims)}")103 unmodified lines# Build selection dictionary for indexed dimensionssel_dict = {}if t is not None:sel_dict["t"] = int(t)if c is not None:sel_dict["c"] = int(c)if z is not None:sel_dict["z"] = int(z)# Extract slice using xarray's labeled indexingslice_xr = data_xr.isel(**sel_dict) if sel_dict else data_xr128 unmodified linesfor dim in info["dims"]:coords = info["coords"][dim]if len(coords) > 0:try:print(f" {dim}: [{coords[0]:.2f} ... {coords[-1]:.2f}] (n={len(coords)})")except (ValueError, TypeError):print(f" {dim}: [{coords[0]} ... {coords[-1]}] (n={len(coords)})")# Print memory size estimatetotal_elements = np.prod(list(info["sizes"].values()))
158 unmodified lines15916016116216316416566 unmodified lines23223323423523623723837 unmodified lines276277278279280281282246 unmodified lines52953053153253353453511 unmodified lines547548549550551552553554158 unmodified linesnew_pixel_scales = (Config.PIXEL_SIZE_Z, Config.PIXEL_SIZE_YX, Config.PIXEL_SIZE_YX)# Update Z sliderz_max = new_data_xr.sizes["Z"] - 1new_z = min(current_z, z_max)print(f"✅ Loaded: {dict(new_data_xr.sizes)}")66 unmodified linesUses slider parameters directly for a single fast reconstruction."""# Extract full Z-stack for timepoint 0 (for reconstruction)zyx_stack = data_xr_state.isel(T=0, C=Config.CHANNEL).values# Get current Z-slice for comparison (left side of ImageSlider)original_normalized = extract_2d_slice(37 unmodified linesiteration history, iteration slider, and SLIDER UPDATES."""# Extract full Z-stack for timepoint 0 (for reconstruction)zyx_stack = data_xr_state.isel(T=0, C=Config.CHANNEL).values# Get current Z-slice for comparison (left side of ImageSlider)original_normalized = extract_2d_slice(246 unmodified linesdata_xr,t=0,c=Config.CHANNEL,z=data_xr.sizes["Z"] // 2,normalize=True,verbose=False,)11 unmodified linesgr.Markdown("### 🎛️ Navigation")z_slider = gr.Slider(minimum=0,maximum=data_xr.sizes["Z"] - 1,value=data_xr.sizes["Z"] // 2,step=1,label="Z-slice",scale=1,158 unmodified lines15916016116216316416566 unmodified lines23223323423523623723837 unmodified lines276277278279280281282246 unmodified lines52953053153253353453511 unmodified lines547548549550551552553554158 unmodified linesnew_pixel_scales = (Config.PIXEL_SIZE_Z, Config.PIXEL_SIZE_YX, Config.PIXEL_SIZE_YX)# Update Z sliderz_max = new_data_xr.sizes["z"] - 1new_z = min(current_z, z_max)print(f"✅ Loaded: {dict(new_data_xr.sizes)}")66 unmodified linesUses slider parameters directly for a single fast reconstruction."""# Extract full Z-stack for timepoint 0 (for reconstruction)zyx_stack = data_xr_state.isel(t=0, c=Config.CHANNEL).values# Get current Z-slice for comparison (left side of ImageSlider)original_normalized = extract_2d_slice(37 unmodified linesiteration history, iteration slider, and SLIDER UPDATES."""# Extract full Z-stack for timepoint 0 (for reconstruction)zyx_stack = data_xr_state.isel(t=0, c=Config.CHANNEL).values# Get current Z-slice for comparison (left side of ImageSlider)original_normalized = extract_2d_slice(246 unmodified linesdata_xr,t=0,c=Config.CHANNEL,z=data_xr.sizes["z"] // 2,normalize=True,verbose=False,)11 unmodified linesgr.Markdown("### 🎛️ Navigation")z_slider = gr.Slider(minimum=0,maximum=data_xr.sizes["z"] - 1,value=data_xr.sizes["z"] // 2,step=1,label="Z-slice",scale=1,
2 unmodified lines3456789102 unmodified lines# Install waveorder from gradio-demo branchgit+https://github.com/mehta-lab/waveorder.git@gradio-demogit+https://github.com/ianhi/xarray-ome.git@maingit+https://github.com/czbiohub-sf/iohub.git@v0.3.0a2# Gradio for web interfacegradio>=6.0.22 unmodified lines34567892 unmodified lines# Install waveorder from gradio-demo branchgit+https://github.com/mehta-lab/waveorder.git@gradio-demoiohub==0.3.2# Gradio for web interfacegradio>=6.0.2
demo_utils.py+14-35
optimize_demo.py+6-6
requirements.txt+1-2