### Install and build project dependencies Source: https://github.com/google/neuroglancer/blob/master/README.md Commands to set up the environment and install necessary Node.js packages. ```bash nvm install stable ``` ```bash npm i ``` -------------------------------- ### Run Example with IPython Source: https://github.com/google/neuroglancer/blob/master/python/README.md Run an example script using the IPython magic command %run -i for interactive mode. ```ipython %run -i python.py ``` -------------------------------- ### Normal Installation from Local Checkout Source: https://github.com/google/neuroglancer/blob/master/python/README.md Perform a normal installation from a local checkout of the neuroglancer git repository. This requires Node.js and a C++ compiler. ```shell pip install . ``` -------------------------------- ### Editable Installation with uv Source: https://github.com/google/neuroglancer/blob/master/python/README.md Set up an editable installation for development purposes using uv. Changes to .py files take effect on import, but client changes require rebuilding. ```shell uv sync ``` -------------------------------- ### Install Neuroglancer from PyPI Source: https://github.com/google/neuroglancer/blob/master/python/README.md Install the latest published package from PyPI using pip. ```shell pip install neuroglancer ``` -------------------------------- ### Run Example Interactively Source: https://github.com/google/neuroglancer/blob/master/python/README.md Run an example script using the Python interpreter in interactive mode. This prevents the server from exiting immediately. ```shell uv run python -i example.py ``` -------------------------------- ### Run development server and tests Source: https://github.com/google/neuroglancer/blob/master/README.md Commands to start the local development server or execute the unit test suite. ```bash npm run dev-server ``` ```bash npm test ``` -------------------------------- ### Install Neuroglancer from GitHub Source: https://github.com/google/neuroglancer/blob/master/examples/README.md Use this command to install Neuroglancer directly from its GitHub repository as a project dependency. ```shell npm install google/neuroglancer ``` -------------------------------- ### HTTP Kvstore URL Example Source: https://github.com/google/neuroglancer/blob/master/docs/datasource/index.md Use this URL format to access a file served by an HTTP server. ```url https://*host*/*path* ``` -------------------------------- ### Initialize Neuroglancer Viewer in Vite Source: https://github.com/google/neuroglancer/blob/master/examples/vite/vite-project-source/index.html Use this setup to initialize the default viewer. Ensure the neuroglancer package is installed in your project dependencies. ```javascript import "neuroglancer"; import { setupDefaultViewer } from "neuroglancer/unstable/ui/default_viewer_setup.js"; setupDefaultViewer(); ``` -------------------------------- ### Initialize Neuroglancer in Vite Source: https://github.com/google/neuroglancer/blob/master/examples/vite/vite-project-built/index.html Use this setup to initialize the default viewer. Ensure the neuroglancer package is installed in your project dependencies. ```javascript import "neuroglancer"; import { setupDefaultViewer } from "neuroglancer/unstable/ui/default_viewer_setup.js"; setupDefaultViewer(); ``` -------------------------------- ### S3 Kvstore URL Example Source: https://github.com/google/neuroglancer/blob/master/docs/datasource/index.md Use this URL format to access a file on S3. ```url s3://*bucket*/*path* ``` -------------------------------- ### Verify Python Code Quality Source: https://github.com/google/neuroglancer/blob/master/CONTRIBUTING.md Install nox and run the lint, format, and typecheck sessions for Python code. ```shell pip install nox nox -s lint format mypy ``` -------------------------------- ### Install Neuroglancer from Git Repository Source: https://github.com/google/neuroglancer/blob/master/python/README.md Install the latest version directly from the Neuroglancer git repository using pip. This requires Node.js and a C++ compiler. ```shell pip install git+https://github.com/google/neuroglancer ``` -------------------------------- ### N5 Physical Units JSON Example Source: https://github.com/google/neuroglancer/blob/master/src/datasource/n5/index.rst Example of specifying physical units and resolution for a 3-D array in N5 metadata. ```json { "resolution": [4, 4, 30], "units": ["nm", "nm", "nm"] } ``` -------------------------------- ### Create a Neuroglancer Viewer Source: https://github.com/google/neuroglancer/blob/master/python/examples/jupyter-notebook-demo.ipynb Initializes a Neuroglancer viewer, starting a web server to serve the client and handle data and state updates. Ensure the notebook kernel is running for the viewer link to be valid. ```python viewer = neuroglancer.Viewer() ``` -------------------------------- ### S3 Kvstore with Zip Adapter URL Example Source: https://github.com/google/neuroglancer/blob/master/docs/datasource/index.md Access a file within a zipfile on S3 using an S3 kvstore with a zip kvstore adapter. ```url s3://*bucket*/*path*.zip|zip:path/within/zipfile.nii ``` -------------------------------- ### Initialize Neuroglancer Viewer Source: https://context7.com/google/neuroglancer/llms.txt Creates a synchronized Neuroglancer viewer instance. This starts a local web server and provides a URL for browser access. Custom server configurations can be applied using command-line arguments. ```python import neuroglancer import neuroglancer.cli import argparse # Basic viewer initialization viewer = neuroglancer.Viewer() print(viewer.get_viewer_url()) # Output: http://127.0.0.1:PORT/v/TOKEN/ # With custom server configuration ap = argparse.ArgumentParser() neuroglancer.cli.add_server_arguments(ap) args = neuroglancer.cli.handle_server_arguments(ap.parse_args(['--bind-address', '0.0.0.0', '--bind-port', '8080'])) viewer = neuroglancer.Viewer() print(viewer) # Prints the viewer URL ``` -------------------------------- ### Nested Zip Adapters URL Example Source: https://github.com/google/neuroglancer/blob/master/docs/datasource/index.md Access a file within a nested zipfile structure on S3 using multiple zip kvstore adapters. ```url s3://*bucket*/*path*.zip|zip:inner/zipfile.zip|zip:path/in/nested/inner/zipfile.nii ``` -------------------------------- ### Install Specific Git Commit Source: https://github.com/google/neuroglancer/blob/master/python/README.md Install a specific commit from the Neuroglancer git repository using pip. ```shell pip install git+https://github.com/google/neuroglancer@XXXXXXXXX ``` -------------------------------- ### Upload Package Artifacts to PyPI Source: https://github.com/google/neuroglancer/blob/master/python/release_procedure.md Install the twine utility and upload the generated source distribution and binary wheels from the 'dist/' directory to the Python Package Index. ```shell pip install twine twine upload dist/* ``` -------------------------------- ### N5 Attributes JSON Example Source: https://github.com/google/neuroglancer/blob/master/src/datasource/n5/README.md Example of an attributes.json file for an N5 dataset, including dimensions, data type, block size, compression, axes, and coordinate arrays. ```json { "dimensions": [10000, 10000, 5], "dataType": "uint8", "blockSize": [512, 512, 1], "compression": { "type": "raw" }, "axes": ["x", "y", "c"], "coordinateArrays": { "c": ["A", "B", "C", "D", "E"] } } ``` -------------------------------- ### Compressed Morton Code Generation Example Source: https://github.com/google/neuroglancer/blob/master/src/datasource/precomputed/volume.rst Illustrates the step-by-step process of generating compressed Morton codes by spacing and shifting coordinate bits for interleaving. ```text y = ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- --dc ba98 7654 3210 after spacing with constant 2 bits since Y has smallest range:: y = ---- ---- ---- ---- ---- ---- d--c --b- -a-- 9--8 --7- -6-- 5--4 --3- -2-- 1--0 after shifting by 1 for future interleaving to get morton code:: y = ---- ---- ---- ---- ---- ---d --c- -b-- a--9 --8- -7-- 6--5 --4- -3-- 2--1 --0- Start with a Z coordinate that for this example has a max of 24 bits:: z = ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 7654 3210 fedc ba98 7654 3210 after spacing out Z with 24 bits max; note compression of MSB due to X and Y dropout:: z = ---- ---- ---- 7654 3210 f-e- d--c --b- -a-- 9--8 --7- -6-- 5--4 --3- -2-- 1--0 after shifting by 2 for future interleaving:: z = ---- ---- --76 5432 10f- e-d- -c-- b--a --9- -8-- 7--6 --5- -4-- 3--2 --1- -0-- Now if you OR the final X, Y, and Z you see no collisions:: x = ---- ---- ---- ---- ---f -e-- d--c --b- -a-- 9--8 --7- -6-- 5--4 --3- -2-- 1--0 y = ---- ---- ---- ---- ---- ---d --c- -b-- a--9 --8- -7-- 6--5 --4- -3-- 2--1 --0- z = ---- ---- --76 5432 10f- e-d- -c-- b--a --9- -8-- 7--6 --5- -4-- 3--2 --1- -0-- ``` ```text While the above may be the simplest way to understand compressed Morton codes, the algorithm can be implemented more simply by iteratively going bit by bit from LSB to MSB and keeping track of the interleaved output bit. Specifically, given the coordinates ``g`` for a grid cell, where ``0 <= g < grid_size``, the compressed Morton code is computed as follows: 1. Set ``j := 0``. 2. For ``i`` from ``0`` to ``n-1``, where ``n`` is the number of bits needed to encode the grid cell coordinates: - For ``dim`` in ``0, 1, 2`` (corresponding to ``x``, ``y``, ``z``): - If ``2**i < grid_size[dim]``: - Set output bit ``j`` of the compressed Morton code to bit ``i`` of ``g[dim]``. - Set ``j := j + 1``. ``` -------------------------------- ### Run Headless Tests with Firefox on xvfb (Linux) Source: https://github.com/google/neuroglancer/blob/master/python/README.md Run Neuroglancer tests headlessly using Firefox within xvfb on Linux. Requires xvfb to be installed. ```shell sudo apt-get install xvfb # On Debian-based systems uvx nox -s test_xvfb -- --browser firefox # Run tests using Firefox in xvfb ``` -------------------------------- ### N5 Top-Level Attributes JSON Example Source: https://github.com/google/neuroglancer/blob/master/src/datasource/n5/index.rst Example of top-level attributes.json for a multiscale N5 dataset, defining downsampling factors for multiple resolution levels. ```json { "downsamplingFactors": [ [1, 1, 1], [2, 2, 1], [4, 4, 1] ] } ``` -------------------------------- ### N5 Pixel Resolution JSON Example Source: https://github.com/google/neuroglancer/blob/master/src/datasource/n5/index.rst Alternative method for specifying physical units and resolution using the 'pixelResolution' attribute in N5 metadata. This method is less recommended. ```json { "pixelResolution": { "unit": "nm", "dimensions": [4, 4, 30] } } ``` -------------------------------- ### Link Local Neuroglancer Checkout Source: https://github.com/google/neuroglancer/blob/master/examples/README.md Link a local checkout of the Neuroglancer repository to your project for development. This allows direct consumption of TypeScript sources, requiring appropriate transpilation setup. ```shell npm link neuroglancer ``` ```shell npm install file:/local/path/to/neuroglancer ``` -------------------------------- ### Initialize LocalVolume and ImageLayer Source: https://github.com/google/neuroglancer/blob/master/python/examples/jupyter-notebook-demo.ipynb Creates a local volume and adds it as an overlay layer with a custom shader. ```python volume = neuroglancer.LocalVolume( a, dimensions=neuroglancer.CoordinateSpace( names=['x', 'y', 'z'], units='nm', scales=[8, 8, 8], ), voxel_offset=[3000, 3000, 3000]) with viewer.txn() as s: s.layers['overlay'] = neuroglancer.ImageLayer( source=volume, # Define a custom shader to display this mask array as red+alpha. shader=""" void main() { float v = toNormalized(getDataValue(0)) * 255.0; emitRGBA(vec4(v, 0.0, 0.0, v)); } """, ) ``` -------------------------------- ### Configure Firefox WebGL settings Source: https://github.com/google/neuroglancer/blob/master/README.md Settings to adjust in about:config to resolve WebGL initialization failures. ```text webgl.disable-fail-if-major-performance-caveat = true webgl.force-enabled = true webgl.msaa-force = true ``` -------------------------------- ### N5 Attributes JSON Example Source: https://github.com/google/neuroglancer/blob/master/src/datasource/n5/index.rst Example of attributes.json for a multiscale N5 dataset, specifying data type, dimensions, block size, compression, and downsampling factors for a specific resolution level. ```json { "dataType": "uint8", "dimensions": [1000, 1000, 1000], "blockSize": [100, 100, 100], "compression": {"type": "raw"}, "downsamplingFactors": [2, 2, 1] } ``` -------------------------------- ### Get Default Annotation Color Source: https://github.com/google/neuroglancer/blob/master/src/annotation/rendering.md Retrieves the color defined in the UI or layer JSON state. ```glsl vec3 defaultColor(); ``` -------------------------------- ### Configure Basic ImageLayer Source: https://context7.com/google/neuroglancer/llms.txt Displays volumetric image data with specified opacity and blend mode. Requires a neuroglancer.LocalVolume source. ```python import neuroglancer import numpy as np viewer = neuroglancer.Viewer() dimensions = neuroglancer.CoordinateSpace(names=["x", "y", "z"], units="nm", scales=[10, 10, 10]) data = np.random.randint(0, 255, size=(100, 100, 100), dtype=np.uint8) with viewer.txn() as state: state.dimensions = dimensions # Basic image layer state.layers["grayscale"] = neuroglancer.ImageLayer( source=neuroglancer.LocalVolume(data=data, dimensions=dimensions), opacity=1.0, blend="default", # Options: "default", "additive" ) ``` -------------------------------- ### Configure Viewer State with txn() Source: https://context7.com/google/neuroglancer/llms.txt Use the txn() context manager for atomic state modifications. This includes setting global dimensions, viewer position, display options, layout, and adding image layers. ```python import neuroglancer import numpy as np viewer = neuroglancer.Viewer() data = np.random.randint(0, 255, size=(100, 100, 100), dtype=np.uint8) dimensions = neuroglancer.CoordinateSpace(names=["x", "y", "z"], units="nm", scales=[10, 10, 10]) with viewer.txn() as state: # Set global dimensions state.dimensions = dimensions # Set viewer position state.position = [50, 50, 50] # Configure display options state.cross_section_scale = 10 # Zoom level for cross-sections state.projection_scale = 1000 # Zoom level for 3D projection state.show_slices = True state.show_axis_lines = True state.show_scale_bar = True # Set layout state.layout = "4panel" # Options: "xy", "xz", "yz", "4panel", "3d", etc. # Add an image layer state.layers.append( name="image", layer=neuroglancer.ImageLayer( source=neuroglancer.LocalVolume(data=data, dimensions=dimensions), opacity=0.5, shader=""" void main() { emitGrayscale(toNormalized(getDataValue())); } """, ), ) print(viewer.state.position) # Access current state ``` -------------------------------- ### Deploy to Google App Engine Source: https://github.com/google/neuroglancer/blob/master/ngauth_server/README.md Deploys the application to Google App Engine for the specified project. This command assumes the application code and configuration are ready. ```shell gcloud app deploy --project YOUR_PROJECT_ID ``` -------------------------------- ### Create Static Library for gmock_main Source: https://github.com/google/neuroglancer/blob/master/python/CMakeLists.txt Builds a static library named 'gmock_main' which includes the main function for Google Mock tests. This simplifies test execution by providing a default entry point. ```cmake add_library(gmock_main STATIC ${CMAKE_CURRENT_BINARY_DIR}/third_party/src/googletest/googlemock/src/gmock_main.cc ) ``` -------------------------------- ### Build and Run Neuroglancer Server Source: https://github.com/google/neuroglancer/blob/master/ngauth_server/README.md Build and run the Neuroglancer server using Go. You can specify an alternative port using the PORT environment variable, ensuring the redirect URI is correctly configured. ```shell go run . ``` -------------------------------- ### Authenticate with Google Cloud SDK Source: https://github.com/google/neuroglancer/blob/master/ngauth_server/README.md Logs in the user and sets up Application Default Credentials for the Google Cloud SDK. These are necessary for gcloud commands to authenticate with Google Cloud services. ```shell gcloud auth login gcloud auth application-default login ``` -------------------------------- ### Configure Data Source Protocols in Neuroglancer Source: https://context7.com/google/neuroglancer/llms.txt Demonstrates how to add various volumetric data sources to a viewer using protocols like precomputed, n5, zarr, and nifti. ```python import neuroglancer viewer = neuroglancer.Viewer() dimensions = neuroglancer.CoordinateSpace(names=["x", "y", "z"], units="nm", scales=[10, 10, 10]) with viewer.txn() as state: state.dimensions = dimensions # Precomputed format from Google Cloud Storage state.layers["gcs"] = neuroglancer.ImageLayer( source="precomputed://gs://neuroglancer-public-data/kasthuri2011/image", ) # Precomputed format from Amazon S3 state.layers["s3"] = neuroglancer.ImageLayer( source="precomputed://s3://bucket-name/path/to/data", ) # HTTP/HTTPS source state.layers["http"] = neuroglancer.ImageLayer( source="precomputed://https://example.com/data", ) # N5 format state.layers["n5"] = neuroglancer.ImageLayer( source="n5://gs://bucket/dataset.n5", ) # Zarr v3 format state.layers["zarr"] = neuroglancer.ImageLayer( source="zarr://gs://bucket/dataset.zarr", ) # NIfTI file state.layers["nifti"] = neuroglancer.ImageLayer( source="nifti://https://example.com/brain.nii.gz", ) # Deep Zoom image state.layers["deepzoom"] = neuroglancer.ImageLayer( source="deepzoom://https://example.com/image.dzi", ) # Nested sources with zip adapter state.layers["zip"] = neuroglancer.ImageLayer( source="precomputed://s3://bucket/archive.zip|zip:path/within/archive", ) ``` -------------------------------- ### Build Binary Wheels with Cibuildwheel Source: https://github.com/google/neuroglancer/blob/master/python/release_procedure.md Build binary wheels for supported platforms and Python versions. This command is typically run in a CI environment. The wheels are written to the 'dist/' directory. ```shell ./python/build_tools/cibuildwheel.sh ``` -------------------------------- ### GCS CORS Policy Configuration Source: https://github.com/google/neuroglancer/blob/master/src/datasource/file_protocols.md Configure a CORS policy for GCS buckets when using the S3-compatible XML API with the `gs+xml://` protocol. This example specifies allowed methods, origins, and headers. ```json [ { "maxAgeSeconds": 3600, "method": ["GET"], "origin": ["*"], "responseHeader": ["Content-Type", "Range"] } ] ``` -------------------------------- ### Configure Neuroglancer Layouts Source: https://context7.com/google/neuroglancer/llms.txt Use the `viewer.txn()` context manager to update layout configurations. Supports preset layouts like '4panel' and custom row/column arrangements with flex sizing. ```python import neuroglancer viewer = neuroglancer.Viewer() dimensions = neuroglancer.CoordinateSpace(names=["x", "y", "z"], units="nm", scales=[10, 10, 10]) with viewer.txn() as state: state.dimensions = dimensions # Simple preset layouts state.layout = "4panel" # XY, XZ, YZ, and 3D views # Other presets: "xy", "xz", "yz", "3d", "xy-3d", "xz-3d", "yz-3d" # Custom row layout state.layout = neuroglancer.row_layout([ neuroglancer.LayerGroupViewer(layout="xy"), neuroglancer.LayerGroupViewer(layout="3d"), ]) # Custom column layout state.layout = neuroglancer.column_layout([ neuroglancer.LayerGroupViewer(layout="xy"), neuroglancer.LayerGroupViewer(layout="xz"), neuroglancer.LayerGroupViewer(layout="yz"), ]) # Nested layout with flex sizing state.layout = neuroglancer.row_layout([ neuroglancer.column_layout([ neuroglancer.LayerGroupViewer(layout="xy", flex=2), neuroglancer.LayerGroupViewer(layout="xz", flex=1), ]), neuroglancer.LayerGroupViewer(layout="3d", flex=1), ]) ``` -------------------------------- ### Add Google Test External Project Source: https://github.com/google/neuroglancer/blob/master/python/CMakeLists.txt Integrates the Google Test framework as an external project, specifying its repository and build commands. This setup ensures that Google Test is available for use in the project's tests. ```cmake ExternalProject_Add( googletest PREFIX ${CMAKE_CURRENT_BINARY_DIR}/third_party GIT_REPOSITORY https://github.com/google/googletest.git UPDATE_COMMAND "" CONFIGURE_COMMAND "" BUILD_COMMAND "" INSTALL_COMMAND "" TEST_COMMAND "") ``` -------------------------------- ### Example GLSL Shader with UI Controls Source: https://github.com/google/neuroglancer/blob/master/src/sliceview/image_layer_rendering.md This GLSL fragment shader demonstrates the use of Neuroglancer's custom `#uicontrol` directives for channel selection, color, brightness, and contrast. It defines variables that can be manipulated interactively from the UI. ```glsl #uicontrol int channel slider(min=0, max=4) #uicontrol vec3 color color(default="red") #uicontrol float brightness slider(min=-1, max=1) #uicontrol float contrast slider(min=-3, max=3, step=0.01) void main() { emitRGB(color * (toNormalized(getDataValue(channel)) + brightness) * exp(contrast)); } ``` -------------------------------- ### Declare Git Dependency in setup.py Source: https://github.com/google/neuroglancer/blob/master/python/README.md Declare a dependency on a specific git version of neuroglancer within a Python package's setup.py file. ```python setup( name='', ..., install_requires=[ ..., 'neuroglancer @ git+https://github.com/google/neuroglancer@XXXXXXXXX', ], ) ``` -------------------------------- ### Build Binary Wheels Locally on Linux Source: https://github.com/google/neuroglancer/blob/master/python/release_procedure.md Optionally, build binary wheels specifically for Linux locally. Note that macOS builds have system-wide effects and are not recommended for local execution. ```shell ./python/build_tools/cibuildwheel.sh --platform linux ``` -------------------------------- ### Create Static Library for gmock Source: https://github.com/google/neuroglancer/blob/master/python/CMakeLists.txt Builds a static library named 'gmock' from the Google Mock source files. This library depends on the 'gtest' library and provides mocking capabilities. ```cmake add_library(gmock STATIC ${CMAKE_CURRENT_BINARY_DIR}/third_party/src/googletest/googlemock/src/gmock-all.cc ) ``` -------------------------------- ### Run tests with Chrome Source: https://github.com/google/neuroglancer/blob/master/python/README.md Executes the test suite using the Chrome browser. ```bash uvx nox -s test -- --browser chrome ``` -------------------------------- ### Display Viewer Link Source: https://github.com/google/neuroglancer/blob/master/python/examples/jupyter-notebook-demo.ipynb Prints a link to the Neuroglancer viewer. This link is only valid while the notebook kernel is running. Be cautious about sharing this link as it can expose authentication credentials. ```python viewer ``` -------------------------------- ### Create secrets directory Source: https://github.com/google/neuroglancer/blob/master/ngauth_server/README.md Creates a directory named 'secrets' to store configuration data. ```shell mkdir secrets ``` -------------------------------- ### Check TypeScript/JavaScript Linting and Formatting Source: https://github.com/google/neuroglancer/blob/master/CONTRIBUTING.md Run these commands to verify that TypeScript and JavaScript files adhere to project linting and formatting standards. ```shell npm run lint:check npm run format:check ``` -------------------------------- ### Configure 3D Layout Source: https://github.com/google/neuroglancer/blob/master/python/examples/jupyter-notebook-demo.ipynb Sets the viewer layout to 3D and adjusts the projection scale. ```python with viewer.txn() as s: s.layout = '3d' s.projection_scale = 3000 ``` -------------------------------- ### Apply CoordinateSpaceTransform for Data Alignment Source: https://context7.com/google/neuroglancer/llms.txt Shows how to apply affine transformations and scaling to data layers using CoordinateSpaceTransform. ```python import neuroglancer import numpy as np viewer = neuroglancer.Viewer() dimensions = neuroglancer.CoordinateSpace(names=["x", "y", "z"], units="nm", scales=[10, 10, 10]) data = np.random.randint(0, 255, size=(100, 100, 100), dtype=np.uint8) with viewer.txn() as state: state.dimensions = dimensions # Original data without transform state.layers["original"] = neuroglancer.ImageLayer( source=neuroglancer.LocalVolume(data=data, dimensions=dimensions), ) # Transformed data with shear matrix state.layers["transformed"] = neuroglancer.ImageLayer( source=neuroglancer.LayerDataSource( url=neuroglancer.LocalVolume(data=data, dimensions=dimensions), transform=neuroglancer.CoordinateSpaceTransform( output_dimensions=dimensions, # 3x4 affine matrix: [rotation/scale | translation] matrix=[ [1, 0.5, 0, 100], # x' = x + 0.5*y + 100 [0, 1, 0, 50], # y' = y + 50 [0, 0, 1, 0], # z' = z ], ), ), ) # Scaling transform state.layers["scaled"] = neuroglancer.ImageLayer( source=neuroglancer.LayerDataSource( url=neuroglancer.LocalVolume(data=data, dimensions=dimensions), transform=neuroglancer.CoordinateSpaceTransform( output_dimensions=neuroglancer.CoordinateSpace( names=["x", "y", "z"], units="nm", scales=[20, 20, 20], # 2x scaling ), ), ), ) ``` -------------------------------- ### Configure Local and Remote Annotation Layers Source: https://context7.com/google/neuroglancer/llms.txt Set up annotation layers with inline or remote data sources. Supports various annotation types like points, lines, and bounding boxes. Requires `neuroglancer` import. ```python import neuroglancer viewer = neuroglancer.Viewer() dimensions = neuroglancer.CoordinateSpace(names=["x", "y", "z"], units="nm", scales=[10, 10, 10]) with viewer.txn() as state: state.dimensions = dimensions # Local annotation layer with inline annotations state.layers["annotations"] = neuroglancer.LocalAnnotationLayer( dimensions=dimensions, annotation_color="#ffff00", annotations=[ neuroglancer.PointAnnotation( id="point1", point=[50, 50, 50], description="Sample point", ), neuroglancer.LineAnnotation( id="line1", point_a=[10, 10, 10], point_b=[90, 90, 90], ), neuroglancer.AxisAlignedBoundingBoxAnnotation( id="bbox1", point_a=[20, 20, 20], point_b=[80, 80, 80], ), neuroglancer.EllipsoidAnnotation( id="ellipsoid1", center=[50, 50, 50], radii=[20, 30, 40], ), ], shader=""" void main() { setColor(defaultColor()); setPointMarkerSize(10.0); } """, ) # Remote annotation layer from precomputed source state.layers["remote_annotations"] = neuroglancer.AnnotationLayer( source="precomputed://gs://bucket/annotations", annotation_properties=[ neuroglancer.AnnotationPropertySpec(id="size", type="float32", default=5.0), neuroglancer.AnnotationPropertySpec(id="color", type="rgb", default="#ff0000"), ], ) ``` -------------------------------- ### Build Source Distribution (sdist) Source: https://github.com/google/neuroglancer/blob/master/python/release_procedure.md Generate the source distribution archive for the package. The sdist is written to the 'dist/' directory. ```shell python setup.py sdist --format=gztar ``` -------------------------------- ### Process BOSS Auth Callback Source: https://github.com/google/neuroglancer/blob/master/src/datasource/boss/bossauth.html Extracts authentication parameters from the URL hash and sends them to the opener window. Requires the page to be opened by a window that expects a postMessage response. ```javascript let auth = new URL(document.location).hash .substring(1) .split("&") .map((el) => el.split("=")) .reduce((pre, cur) => { pre[cur[0]] = cur[1]; return pre; }, {}); auth.service = "bossAuthCallback"; opener.postMessage(JSON.stringify(auth), location.origin); ``` -------------------------------- ### Configure Side-by-Side Layout Source: https://github.com/google/neuroglancer/blob/master/python/examples/jupyter-notebook-demo.ipynb Organizes layers into side-by-side viewer groups. ```python with viewer.txn() as s: s.layout = neuroglancer.row_layout( [neuroglancer.LayerGroupViewer(layers=['image', 'overlay']), neuroglancer.LayerGroupViewer(layers=['segmentation'])]) ``` ```python with viewer.txn() as s: s.layout = neuroglancer.row_layout( [neuroglancer.LayerGroupViewer(layers=['image']), neuroglancer.LayerGroupViewer(layers=['segmentation'])]) ``` -------------------------------- ### Define Custom Command for gmock-all.cc Source: https://github.com/google/neuroglancer/blob/master/python/CMakeLists.txt Defines a custom command to generate the 'gmock-all.cc' source file. This command depends on the 'googletest' external project, ensuring the source file is available before compilation. ```cmake add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/third_party/src/googletest/googlemock/src/gmock-all.cc DEPENDS googletest) ``` -------------------------------- ### Run tests with Firefox Source: https://github.com/google/neuroglancer/blob/master/python/README.md Executes the test suite using the Firefox browser. ```bash uvx nox -s test -- --browser firefox ``` -------------------------------- ### Configure Multi-channel RGB ImageLayer Source: https://context7.com/google/neuroglancer/llms.txt Displays multi-channel RGB image data using a custom shader to emit RGB values. Ensure the data dimensions include a channel dimension. ```python import neuroglancer import numpy as np viewer = neuroglancer.Viewer() dimensions = neuroglancer.CoordinateSpace(names=["x", "y", "z"], units="nm", scales=[10, 10, 10]) rgb_data = np.random.randint(0, 255, size=(3, 100, 100, 100), dtype=np.uint8) rgb_dimensions = neuroglancer.CoordinateSpace( names=["c^", "x", "y", "z"], units=["", "nm", "nm", "nm"], scales=[1, 10, 10, 10], ) with viewer.txn() as state: state.dimensions = dimensions state.layers["rgb"] = neuroglancer.ImageLayer( source=neuroglancer.LocalVolume(data=rgb_data, dimensions=rgb_dimensions), shader=""" void main() { emitRGB(vec3( toNormalized(getDataValue(0)), toNormalized(getDataValue(1)), toNormalized(getDataValue(2)) )); } """, ) ``` -------------------------------- ### Load and Process Volume Data with TensorStore Source: https://github.com/google/neuroglancer/blob/master/python/examples/jupyter-notebook-demo.ipynb Opens a volume from Google Cloud Storage using TensorStore and creates a thresholded numpy array. The numpy array reference is maintained as long as the layer exists in the viewer. ```python import tensorstore as ts image_vol = await ts.open({'driver': 'neuroglancer_precomputed', 'kvstore': 'gs://neuroglancer-public-data/flyem_fib-25/image/'}) a = np.zeros((200,200,200), np.uint8) def make_thresholded(threshold): a[...] = image_vol[3000:3200,3000:3200,3000:3200][...,0].read().result() > threshold make_thresholded(110) ``` -------------------------------- ### Configure ImageLayer with Volume Rendering Source: https://context7.com/google/neuroglancer/llms.txt Enables volume rendering for an ImageLayer. Customize gain and depth samples for rendering quality. Requires a neuroglancer.LocalVolume source. ```python import neuroglancer import numpy as np viewer = neuroglancer.Viewer() dimensions = neuroglancer.CoordinateSpace(names=["x", "y", "z"], units="nm", scales=[10, 10, 10]) data = np.random.randint(0, 255, size=(100, 100, 100), dtype=np.uint8) with viewer.txn() as state: state.dimensions = dimensions state.layers["volume"] = neuroglancer.ImageLayer( source=neuroglancer.LocalVolume(data=data, dimensions=dimensions), volume_rendering=True, volume_rendering_gain=0.5, volume_rendering_depth_samples=128, ) ``` -------------------------------- ### Byte Range KVStore URL Syntax Source: https://github.com/google/neuroglancer/blob/master/src/kvstore/byte_range/index.rst Defines the URL syntax for accessing a specific byte range within a file-based key-value store. ```APIDOC ## Byte Range URL Syntax ### Description The byte range key-value store adapter allows an individual byte range within a file to be specified. ### URL Syntax `{base-kvstore-url}|byte-range:{start}-{end}` ### Parameters - **base-kvstore-url** (string) - Required - The URL of the base file-based key-value store. - **start** (integer) - Required - The inclusive start byte offset. - **end** (integer) - Required - The exclusive end byte offset. ### Example `gs://bucket/path/to/data|byte-range:1000-2000` ### Capabilities - **Byte Range Reads**: Supported - **Listing**: Not applicable ``` -------------------------------- ### Implement Custom Actions and Key Bindings Source: https://context7.com/google/neuroglancer/llms.txt Enable interactive Python callbacks from the Neuroglancer browser interface by defining custom actions and binding them to keyboard or mouse events. Requires `neuroglancer` and `webbrowser`. ```python import neuroglancer import webbrowser viewer = neuroglancer.Viewer() # Define a custom action callback def on_point_selected(action_state): print(f"Mouse position: {action_state.mouse_voxel_coordinates}") print(f"Selected values: {action_state.selected_values}") # Access layer-specific selection for layer_name, selection in action_state.selected_values.items(): if selection.value is not None: print(f" {layer_name}: segment {selection.value}") # Register the action viewer.actions.add("select-point", on_point_selected) # Bind action to a key with viewer.config_state.txn() as config: config.input_event_bindings.viewer["keyt"] = "select-point" config.input_event_bindings.viewer["control+click0"] = "select-point" # Display status message config.status_messages["welcome"] = "Press 't' to select a point" webbrowser.open(viewer.get_viewer_url()) ``` -------------------------------- ### Create Static Library for compress_segmentation Source: https://github.com/google/neuroglancer/blob/master/python/CMakeLists.txt Builds a static library named 'compress_segmentation' from its source file. This library likely contains core functionality for segmentation compression. ```cmake add_library(compress_segmentation STATIC ext/src/compress_segmentation.cc) ``` -------------------------------- ### GLSL UI Control Directive Syntax Source: https://github.com/google/neuroglancer/blob/master/src/sliceview/image_layer_rendering.md Illustrates the general syntax for Neuroglancer's `#uicontrol` directives, showing variations with and without parameters, and with specified control types. ```glsl #uicontrol #uicontrol (=, ...) #uicontrol #uicontrol (=, ...) ``` -------------------------------- ### Define Custom Command for gmock_main.cc Source: https://github.com/google/neuroglancer/blob/master/python/CMakeLists.txt Defines a custom command to generate the 'gmock_main.cc' source file. This command depends on the 'googletest' external project, ensuring the source file is available before compilation. ```cmake add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/third_party/src/googletest/googlemock/src/gmock_main.cc DEPENDS googletest) ```