brainrender

repository·main·Indexed 20 days ago

https://github.com/brainglobe/brainrender

A Python library for creating high-quality 3D neuro-anatomical renderings. It enables the combination of publicly available brain atlases with experimental data, such as cell coordinates, in a unified 3D space. Key features include the Scene class for visualization management, the Atlas class for loading brain datasets, and tools for adding brain regions, 3D labels, and Points actors. It also supports generating animations and videos via VideoMaker and Animation classes.

Tokens
9.9K
Snippets
44
Records
48
Agent score
71%

What's inside brainrender

  1. Quickstart: Create a 3D neuro-anatomical rendering

    main

    This example demonstrates the standard workflow for using brainrender:

    1. Initialize a Scene with a specific atlas (e.g., allen_mouse_25um).
    2. Add brain regions using scene.add_brain_region().
    3. Create experimental data actors, such as Points from brainrender.actors.
    4. Add actors to the scene using scene.add().
    5. Add text labels to regions using scene.add_label().
    6. Render the final visualization with scene.render().
    import random
    import numpy as np
    from brainrender import Scene
    from brainrender.actors import Points
    
    def get_n_random_points_in_region(region, N):
        """
        Gets N random points inside (or on the surface) of a mesh
        """
        region_bounds = region.mesh.bounds()
        X = np.random.randint(region_bounds[0], region_bounds[1], size=10000)
        Y = np.random.randint(region_bounds[2], region_bounds[3], size=10000)
        Z = np.random.randint(region_bounds[4], region_bounds[5], size=10000)
        pts = [[x, y, z] for x, y, z in zip(X, Y, Z)]
    
        ipts = region.mesh.inside_points(pts).coordinates
        return np.vstack(random.choices(ipts, k=N))
    
    # Display the Allen Brain mouse atlas.
    scene = Scene(atlas_name="allen_mouse_25um", title="Cells in primary visual cortex")
    
    # Display a brain region
    primary_visual = scene.add_brain_region("VISp", alpha=0.2)
    
    # Get a numpy array with (fake) coordinates of some labelled cells
    coordinates = get_n_random_points_in_region(primary_visual, 2000)
    
    # Create a Points actor
    cells = Points(coordinates)
    
    # Add to scene
    scene.add(cells)
    
    # Add label to the brain region
    scene.add_label(primary_visual, "Primary visual cortex")
    
    # Display the figure.
    scene.render()
  2. How keyframes and callbacks work in Animation

    main

    In the Animation class, keyframes define the state of the scene at specific timestamps. Between keyframes, the class automatically interpolates camera parameters and zoom levels.

    KeyframeCallback Concept: A callback is a function called during a keyframe. It allows you to modify the scene dynamically (e.g., making an object disappear) as the video plays.

    Callback Signature:

    def my_callback(scene, frame_number, tot_frames, **kwargs) -> dict | None:
        # Perform scene actions here
        scene.remove_actor('some_actor')
        # Optionally return a dictionary of camera parameters to override interpolation
        return {'azimuth': 90}

    When a callback returns a dictionary, those camera parameters are used for that frame instead of the interpolated values.

  3. Initialize a Scene

    main

    The Scene class is the main entry point for managing a 3D environment in brainrender. It coordinates actors (3D objects), brain regions, and the overall appearance. When initializing a Scene, you can specify an atlas, whether to include the brain root mesh, and if an orientation inset should be shown.

    Key Parameters:

    • root (bool): If True, the brain root mesh is added to the scene. Defaults to True.
    • atlas_name (str | None): The name of the brainglobe atlas to use.
    • check_latest (bool): If True, checks that the atlas is the latest version.
    • inset (bool): If True, shows a small inset with the brain's orientation. Defaults to True.
    • title (str | None): Adds a title to the top of the window.
    • screenshots_folder (str | Path | None): Directory where screenshots will be saved. Defaults to the current working directory.
    • plotter (vedo.Plotter | None): An existing vedo.Plotter instance to use. If None, a new one is created.
    • title_color (str): Color of the title text. Defaults to "k" (black).
    from brainrender import Scene
    
    # Basic scene with a specific atlas
    scene = Scene(atlas_name='mouse', title='My Brain Render')
  4. Embed brainrender scenes in Jupyter Notebooks

    main

    To embed a rendered scene directly within a Jupyter Notebook, you must use the 'k3d' backend.

    Important Limitations:

    • Not all brainrender functionalities are supported when using the embedded mode.
    • The title parameter in Scene() will not be displayed.

    Workflow for embedding:

    1. Set vedo.settings.default_backend = 'k3d'.
    2. Initialize the Scene.
    3. Set scene.jupyter = True.
    4. Call scene.render() to prepare the scene (this prepares actors but does not display them).
    5. Use vedo.Plotter().show(*scene.renderables) to actually display the embedded scene.
    import vedo
    vedo.settings.default_backend = 'k3d'
    
    from brainrender import Scene
    scene = Scene(atlas_name='mpin_zfish_1um', title='Embedded')
    scene.add_brain_region('tectum')
    
    # Enable embedding
    scene.jupyter = True
    
    # Prepare the scene
    scene.render()
    
    # Display the scene using vedo's Plotter
    from vedo import Plotter
    plt = Plotter()
    plt.show(*scene.renderables)
  5. Use brainrender in a Jupyter notebook

    main

    To use brainrender within a Jupyter notebook, you must configure the vedo backend to use k3d before initializing your scene. By default, many brainrender features (like the cartoon shader) are not compatible with notebook backends.

    If you attempt to run unsupported methods in a notebook, you will receive an error message suggesting the following setup:

    import vedo
    vedo.settings.default_backend = 'k3d'

    Note that some features may be unavailable when using the k3d backend. For full feature support, run your code in a standard Python script or an interactive terminal.

    import vedo
    vedo.settings.default_backend = 'k3d'
    # Now initialize your brainrender scene
  6. Render brainrender scenes in a separate pop-up window

    main

    To render your scene in a new, separate window instead of embedding it in a notebook, set the vedo default backend to 'vtk' before initializing your Scene. This approach ensures full access to all brainrender features.

    Note: You can close the pop-up window by pressing the 'Esc' key.

    import vedo
    vedo.settings.default_backend = 'vtk'
    
    from brainrender import Scene
    popup_scene = Scene(atlas_name='allen_mouse_50um', title='popup')
    
    popup_scene.add_brain_region('VISp')
    popup_scene.render()  # press 'Esc' to close
  7. Add brain regions to a Scene

    main

    Use scene.add_brain_region(region_name, ...) to add a specific anatomical structure from the loaded atlas to your scene. You can control transparency using the alpha parameter.

    primary_visual = scene.add_brain_region("VISp", alpha=0.2)
  8. Initialize a Scene

    main

    The Scene object is the central container for your 3D rendering. When initializing, you can specify the atlas_name (e.g., "allen_mouse_25um") and a title for the window.

    from brainrender import Scene
    scene = Scene(atlas_name="allen_mouse_25um", title="My Scene")
  9. Use the Points actor for coordinate data

    main

    To visualize experimental data like cell locations, use the Points actor from brainrender.actors. It accepts a numpy array of coordinates.

    from brainrender.actors import Points
    import numpy as np
    
    # coordinates is a numpy array of [x, y, z] points
    cells = Points(coordinates)
    scene.add(cells)
  10. Use check_file_exists decorator

    main

    The @check_file_exists decorator ensures that the first argument passed to a function is a valid path to an existing file. If the file does not exist, it raises a FileNotFoundError.

    Raises:

    • FileNotFoundError: If Path(args[0]).exists() is False.
    from brainrender._io import check_file_exists
    
    @check_file_exists
    def process_data(filepath):
        # This will only run if filepath exists
        pass