<jupyter_start><jupyter_text>Create a new (initially empty) viewer.  This starts a webserver in a background thread, which serves a copy of the Neuroglancer client, and which also can serve local volume data and handles sending and receiving Neuroglancer state updates.<jupyter_code>viewer = neuroglancer.Viewer()<jupyter_output><empty_output><jupyter_text>Print a link to the viewer (only valid while the notebook kernel is running). Note that while the Viewer is running, anyone with the link can obtain any authentication credentials that the neuroglancer Python module obtains. Therefore, be very careful about sharing the link, and keep in mind that sharing the notebook will likely also share viewer links.<jupyter_code>viewer<jupyter_output><empty_output><jupyter_text>Add some example layers using the precomputed data source (HHMI Janelia FlyEM FIB-25 dataset).<jupyter_code>with viewer.txn() as s:
  s.layers['image'] = neuroglancer.ImageLayer(source='precomputed://gs://neuroglancer-public-data/flyem_fib-25/image')
  s.layers['segmentation'] = neuroglancer.SegmentationLayer(source='precomputed://gs://neuroglancer-public-data/flyem_fib-25/ground_truth', selected_alpha=0.3)<jupyter_output><empty_output><jupyter_text>Display a numpy array as an additional layer.  A reference to the numpy array is kept only as long as the layer remains in the viewer. Move the viewer position.<jupyter_code>with viewer.txn() as s:
    s.voxel_coordinates = [3000, 3000, 3000]<jupyter_output><empty_output><jupyter_text>Hide the segmentation layer.<jupyter_code>with viewer.txn() as s:
    s.layers['segmentation'].visible = False
import cloudvolume
image_vol = cloudvolume.CloudVolume('https://storage.googleapis.com/neuroglancer-public-data/flyem_fib-25/image', mip=0, bounded=True, progress=False)
a = np.zeros((200,200,200), np.uint8)
def make_thresholded(threshold):
  a[...] = np.transpose(image_vol[3000:3200,3000:3200,3000:3200][...,0], (2,1,0)) > threshold
make_thresholded(110)
# This volume handle can be used to notify the viewer that the data has changed.
volume = neuroglancer.LocalVolume(a, voxel_size=[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));
}
""",
    )<jupyter_output><empty_output><jupyter_text>Modify the overlay volume, and call `invalidate()` to notify the Neuroglancer client.<jupyter_code>make_thresholded(100)
volume.invalidate()<jupyter_output><empty_output><jupyter_text>Select a couple segments.<jupyter_code>with viewer.txn() as s:
    s.layers['segmentation'].segments.update([1752, 88847])
    s.layers['segmentation'].visible = True<jupyter_output><empty_output><jupyter_text>Print the neuroglancer viewer state.  The Neuroglancer Python library provides a set of Python objects that wrap the JSON-encoded viewer state.  `viewer.state` returns a read-only snapshot of the state.  To modify the state, use the `viewer.txn()` function, or `viewer.set_state`.<jupyter_code>viewer.state<jupyter_output><empty_output><jupyter_text>Print the set of selected segments.|<jupyter_code>viewer.state.layers['segmentation'].segments<jupyter_output><empty_output><jupyter_text>Update the state by calling `set_state` directly.<jupyter_code>import copy
new_state = copy.deepcopy(viewer.state)
new_state.layers['segmentation'].segments.add(10625)
viewer.set_state(new_state)<jupyter_output><empty_output><jupyter_text>Bind the 't' key in neuroglancer to a Python action.<jupyter_code>num_actions = 0
def my_action(s):
    global num_actions
    num_actions += 1
    with viewer.config_state.txn() as st:
      st.status_messages['hello'] = ('Got action %d: mouse position = %r' %
                                     (num_actions, s.mouse_voxel_coordinates))
    print('Got my-action')
    print('  Mouse position: %s' % (s.mouse_voxel_coordinates,))
    print('  Layer selected values: %s' % (s.selected_values,))
viewer.actions.add('my-action', my_action)
with viewer.config_state.txn() as s:
    s.input_event_bindings.viewer['keyt'] = 'my-action'
    s.status_messages['hello'] = 'Welcome to this example'<jupyter_output><empty_output><jupyter_text>Change the view layout to 3-d.<jupyter_code>with viewer.txn() as s:
    s.layout = '3d'
    s.perspective_zoom = 300<jupyter_output><empty_output><jupyter_text>Take a screenshot (useful for creating publication figures, or for generating videos).  While capturing the screenshot, we hide the UI and specify the viewer size so that we get a result independent of the browser size.<jupyter_code>with viewer.config_state.txn() as s:
    s.show_ui_controls = False
    s.show_panel_borders = False
    s.viewer_size = [1000, 1000]
from ipywidgets import Image
screenshot_image = Image(value=viewer.screenshot().screenshot.image)
with viewer.config_state.txn() as s:
    s.show_ui_controls = True
    s.show_panel_borders = True
    s.viewer_size = None
screenshot_image<jupyter_output><empty_output><jupyter_text>Change the view layout to show the segmentation side by side with the image, rather than overlayed.  This can also be done from the UI by dragging and dropping.  The side by side views by default have synchronized position, orientation, and zoom level, but this can be changed.<jupyter_code>with viewer.txn() as s:
    s.layout = neuroglancer.row_layout(
        [neuroglancer.LayerGroupViewer(layers=['image', 'overlay']),
         neuroglancer.LayerGroupViewer(layers=['segmentation'])])<jupyter_output><empty_output><jupyter_text>Remove the overlay layer.<jupyter_code>with viewer.txn() as s:
    s.layout = neuroglancer.row_layout(
        [neuroglancer.LayerGroupViewer(layers=['image']),
         neuroglancer.LayerGroupViewer(layers=['segmentation'])])<jupyter_output><empty_output><jupyter_text>Create a publicly sharable URL to the viewer state (only works for external data sources, not layers served from Python).  The Python objects for representing the viewer state (`neuroglancer.ViewerState` and friends) can also be used independently from the interactive Python-tied viewer to create Neuroglancer links.<jupyter_code>print(neuroglancer.to_url(viewer.state))<jupyter_output><empty_output><jupyter_text>Stop the Neuroglancer web server, which invalidates any existing links to the Python-tied viewer.<jupyter_code>neuroglancer.stop()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10501375726077652, 'fraction_numerical': 0.018495872821767043, 'mean_word_length': 5.731481481481482, 'pattern_counts': {'":': 0, '<': 69, '<?xml version=': 0, '>': 70, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '17', 'dir': 'jupyter-structured-clean-dedup', 'id': '37493', 'license': 'Apache-2.0', 'n_tokens_mistral': 2202, 'n_tokens_neox': 2059, 'n_words': 558, 'path': 'python/examples/jupyter-notebook-demo.ipynb', 'repo_name': 'vime/neuroglancer', 'size': '6542'}