예제 #1
0
def test_mouselight():
    from brainrender.Utils.MouseLightAPI.mouselight_api import MouseLightAPI
    from brainrender.Utils.MouseLightAPI.mouselight_info import mouselight_api_info, mouselight_fetch_neurons_metadata

    # Fetch metadata for neurons with some in the secondary motor cortex
    neurons_metadata = mouselight_fetch_neurons_metadata(
        filterby='soma', filter_regions=['MOs'])

    # Then we can download the files and save them as a .json file
    ml_api = MouseLightAPI()
    neurons_files = ml_api.download_neurons(
        neurons_metadata[:2]
    )  # just saving the first couple neurons to speed things up

    # Show neurons and ZI in the same scene:
    scene = Scene()
    scene.add_neurons(
        neurons_files,
        soma_color='orangered',
        dendrites_color='orangered',
        axon_color='darkseagreen',
        neurite_radius=8
    )  # add_neurons takes a lot of arguments to specify how the neurons should look
    # make sure to check the source code to see all available optionsq

    scene.add_brain_regions(['MOs'], alpha=0.15)
    scene.render(camera='coronal')
예제 #2
0
def NeuronsScene3():
    scene = Scene()

    neurons_metadata = mouselight_fetch_neurons_metadata(
        filterby='soma', filter_regions=['VAL'])
    neurons_files = mlapi.download_neurons(neurons_metadata[2:6])
    scene.add_neurons(neurons_files,
                      soma_color='deepskyblue',
                      force_to_hemisphere="right")

    scene.add_brain_regions(['VAL'],
                            use_original_color=False,
                            colors='palegreen',
                            alpha=.9)
    mos = scene.actors['regions']['VAL']
    scene.edit_actors([mos], wireframe=True)

    streamlines_files, data = streamlines_api.download_streamlines_for_region(
        "VAL")
    scene.add_streamlines(data[:1],
                          color="palegreen",
                          show_injection_site=False,
                          alpha=.2,
                          radius=10)

    scene.render()
예제 #3
0
    def _make_root(self, rootpath):
        """
            Creates a root mesh by merging the mesh corresponding to each neuron,
            then saves it as an obj file at rootpath
        """
        raise NotImplementedError(
            "Create root method not supported yet, sorry")

        print(f"Creating root mesh for atlas {self.atlas_name}")
        temp_scene = Scene(
            atlas=Celegans,
            add_root=False,
            display_inset=False,
            atlas_kwargs=dict(data_folder=self.data_folder),
        )

        temp_scene.add_neurons(self.neurons_names)
        temp_scene.render(interactive=False)
        temp_scene.close()

        root = merge(*temp_scene.actors["neurons"]).clean().cap()
        # root = mesh2Volume(root, spacing=(0.02, 0.02, 0.02)).isosurface()

        points = Points(root.points()).smoothMLS2D(f=0.8).clean(tol=0.005)

        root = recoSurface(points, dims=100, radius=0.2)

        # Save
        write(root, rootpath)

        del temp_scene
        return root
예제 #4
0
def BrainRegionsScene():
    scene = Scene()
    scene.add_brain_regions(['TH', 'VP'], use_original_color=True, alpha=1)

    act = scene.actors['regions']['TH']
    scene.edit_actors([act], wireframe=True)

    scene.render()
예제 #5
0
def CartoonStyleScene():
    if brainrender.SHADER_STYLE != 'cartoon':
        raise ValueError('Set cartoon style at imports')

    scene = Scene(camera='coronal', add_root=False)
    scene.add_brain_regions(['PAG', 'SCm', 'SCs'],
                            use_original_color=True,
                            alpha=1)
    # scene.add_brain_regions(['VISl', 'VISpl', 'VISpm', 'VISam', 'VISal', 'VISa'], use_original_color=True, alpha=.4)

    scene.render()
예제 #6
0
def StreamlinesScene():
    streamlines_files, data = streamlines_api.download_streamlines_for_region("PAG") 

    scene = Scene()
    scene.add_streamlines(data[3], color="powderblue", show_injection_site=False, alpha=.3, radius=10)
    scene.add_brain_regions(['PAG'], use_original_color=False, colors='powderblue', alpha=.9)
    mos = scene.actors['regions']['PAG']
    scene.edit_actors([mos], wireframe=True) 

    set_camera(scene)
    scene.render() 
예제 #7
0
def NeuronsScene2():
    scene = Scene()

    neurons_metadata = mouselight_fetch_neurons_metadata(filterby='soma', filter_regions=['MOp5'])
    neurons_files =  mlapi.download_neurons(neurons_metadata[2:6]) 
    scene.add_neurons(neurons_files, soma_color='deepskyblue', force_to_hemisphere="right")

    streamlines_files, data = streamlines_api.download_streamlines_for_region("MOp") 
    scene.add_streamlines(data[:1], color="palegreen", show_injection_site=False, alpha=.2, radius=10)

    set_camera(scene)
    scene.render()
예제 #8
0
def NeuronsScene(show_regions = False):
    scene = Scene()

    fl = 'Examples/example_files/one_neuron.json'
    scene.add_neurons(fl, soma_color='darkseagreen', force_to_hemisphere="right",)

    if show_regions:
        scene.add_brain_regions(['ZI', 'PAG', 'MRN', 'NPC', "VTA", "STN", "PPT", "SCm", "HY"], 
                        use_original_color=True, alpha=.5)

    set_camera(scene)
    scene.render() 
예제 #9
0
def CellsScene():
    # Load and clean data
    data = pd.read_csv('/Users/federicoclaudi/Downloads/41593_2019_354_MOESM3_ESM.csv')
    data = data[['genotype', 'Xpos', 'Ypos', 'z.position']]
    data.columns = ['genotype', 'x', 'y', 'z']

    # Visualise data
    scene = Scene()
    scene.add_cells(data)

    set_camera(scene)
    scene.render() 
예제 #10
0
def test_streamlines():
    scene = Scene()

    filepaths, data = scene.atlas.download_streamlines_for_region("CA1")

    scene.add_brain_regions(['CA1'], use_original_color=True, alpha=.2)

    scene.add_streamlines(data,
                          color="darkseagreen",
                          show_injection_site=False)

    scene.render(camera='sagittal', zoom=1, interactive=False)
    scene.close()
예제 #11
0
def ConnectivityScene():
    scene = Scene()
    p0 = scene.get_region_CenterOfMass("ZI")

    # Then we se these coordinates to get tractography data, note: any set of X,Y,Z coordinates would do. 
    tract = aba.get_projection_tracts_to_target(p0=p0)

    scene.add_tractography(tract, display_injection_structure=False, color_by="region", 
                        display_injection_volume=True, others_alpha=.25)
    scene.add_brain_regions(['ZI'], colors="ivory", alpha=1)

    set_camera(scene)
    scene.render()
예제 #12
0
def load_regions_into_brainrender(list_of_regions, alpha=0.8, shading="flat"):
    """
    Loads a list of .obj files into brainrender
    :param list_of_regions: List of .obj files to be loaded
    :param alpha: Object transparency
    :param shading: Object shading type ("flat", "giroud" or "phong").
    Defaults to "phong"
    """
    scene = Scene()
    for obj_file in list_of_regions:
        load_obj_into_brainrender(scene,
                                  obj_file,
                                  alpha=alpha,
                                  shading=shading)
    scene.render()
예제 #13
0
def test_fish_neurons():
    api = MpinMorphologyAPI()
    # api.download_dataset()
    neurons_ids = api.get_neurons_by_structure(837)[:5]
    neurons = api.load_neurons(neurons_ids)

    neurons = [
        neuron.create_mesh(soma_radius=1, neurite_radius=1)[1]
        for neuron in neurons
    ]

    scene = Scene(atlas="mpin_zfish_1um", add_root=True, camera="sagittal2")
    scene.add_neurons(neurons)
    scene.render(interactive=False)
    scene.close()
예제 #14
0
def test_neurons():
    scene = Scene()
    
    mlapi = MouseLightAPI()

    # Fetch metadata for neurons with some in the secondary motor cortex
    neurons_metadata = mlapi.fetch_neurons_metadata(filterby='soma', filter_regions=['MOs'])

    # Then we can download the files and save them as a .json file
    neurons =  mlapi.download_neurons(neurons_metadata[:5])

    scene = Scene(title='One color')
    scene.add_neurons(neurons, color='salmon', display_axon=True, neurite_radius=6)
    scene.render(interactive=False)
    scene.close()
예제 #15
0
def ElectrodesArrayScene():
    scene = Scene(add_root=False, camera='sagittal')
    z_offset = -1500
    scene.add_brain_regions(['VAL'], use_original_color=True, alpha=.5)
    scene.add_brain_regions(['TH'],
                            use_original_color=True,
                            alpha=.5,
                            wireframe=True)

    # scene.add_optic_cannula('VAL')

    # for x_offset in [-200, -500, -800, -1100]:
    #     scene.add_optic_cannula('VAL', z_offset=z_offset, x_offset=x_offset, alpha=1,
    #                 radius=50, y_offset=-500, color='blackboard')

    scene.render()
예제 #16
0
def test_streamlines():
    from brainrender.Utils.parsers.streamlines import StreamlinesAPI

    # Download streamlines data for injections in the CA1 field of the hippocampus
    streamlines_api = StreamlinesAPI()
    filepaths, data = streamlines_api.download_streamlines_for_region("CA1")

    # Start by creating a scene
    scene = Scene()

    scene.add_brain_regions(['CA1'], use_original_color=True, alpha=.2)

    # you can pass either the filepaths or the data
    scene.add_streamlines(data, color="darkseagreen", show_injection_site=False)

    scene.render(interactive=False, camera='sagittal', zoom=1)
    scene.close()
예제 #17
0
def test_tractography():
    from brainrender.Utils.ABA.connectome import ABA
    # Create a scene
    scene = Scene()

    # Get the center of mass of the region of interest
    p0 = scene.get_region_CenterOfMass("ZI")

    # Get projections to that point
    analyzer = ABA()
    tract = analyzer.get_projection_tracts_to_target(p0=p0)

    # Add the brain regions and the projections to it
    scene.add_brain_regions(['ZI'], alpha=.4, use_original_color=True)
    scene.add_tractography(tract, display_injection_structure=False, color_by="region")

    scene.render(interactive=False, )
    scene.close()
예제 #18
0
def test_camera():
    # Create a scene
    scene = Scene(camera='top')  # specify that you want a view from the top

    # render
    scene.render()

    # Now render but with a different view
    scene.render(camera='sagittal', zoom=1)

    # Now render but with specific camera parameters
    bespoke_camera = dict(
        position=[801.843, -1339.564, 8120.729],
        focal=[9207.34, 2416.64, 5689.725],
        viewup=[0.36, -0.917, -0.171],
        distance=9522.144,
        clipping=[5892.778, 14113.736],
    )
예제 #19
0
def main(regions, atlas=None, cartoon=False, debug=False, file=None):
    # Set look
    if cartoon:
        brainrender.SHADER_STYLE = "cartoon"

    # Create scene
    scene = Scene(atlas=atlas)

    # Add brain regions
    if regions is not None and len(regions) > 0:
        acts = scene.add_brain_regions(list(regions))

        # Add silhouettes
        if cartoon:
            if isinstance(acts, list):
                scene.add_silhouette(*acts)
            else:
                scene.add_silhouette(acts)

    # Add data from file
    if file is not None:
        if file.endswith(".h5"):
            scene.add_cells_from_file(file)
        else:
            try:
                scene.add_from_file(file)
            except Exception as e:
                raise ValueError(
                    f"Failed to load data from file onto scene: {file}\n{e}"
                )

    # If debug set interactive = Off and close scene
    if not debug:
        interactive = True
    else:
        interactive = False

    # Render and close
    scene.render(interactive=interactive)

    if debug:
        scene.close()
예제 #20
0
def StreamlinesScene2():
    scene = Scene()

    streamlines_files, data = streamlines_api.download_streamlines_for_region("VAL") 
    scene.add_streamlines(data, color="palegreen", show_injection_site=False, alpha=.3, radius=10)

    streamlines_files, data = streamlines_api.download_streamlines_for_region("VM") 
    scene.add_streamlines(data, color="palevioletred", show_injection_site=False, alpha=.3, radius=10)

    
    scene.add_brain_regions(['VAL'], use_original_color=False, colors='palegreen', alpha=.9, hemisphere='right')
    mos = scene.actors['regions']['VAL']
    scene.edit_actors([mos], wireframe=True) 

    scene.add_brain_regions(['VM'], use_original_color=False, colors='palevioletred', alpha=.9, hemisphere='right')
    mos = scene.actors['regions']['VM']
    scene.edit_actors([mos], wireframe=True) 

    set_camera(scene)
    scene.render() 
예제 #21
0
brainrender.SHADER_STYLE = 'cartoon'

from brainrender.scene import Scene
import numpy as np
from vtkplotter import Plane

scene = Scene(use_default_key_bindings=True)

# Add some actors
root = scene.actors['root']
th = scene.add_brain_regions(['STR', 'TH'], alpha=.5)

# Specify position, size and orientation of the plane
pos = scene.atlas._root_midpoint
sx, sy = 15000, 15000
norm = [0, 1, 1]
plane = scene.atlas.get_plane_at_point(pos, norm, sx, sy, color='lightblue')

# Cut
scene.cut_actors_with_plane(
    plane,
    close_actors=
    False,  # set close_actors to True close the holes left by cutting
    showplane=True,
    actors=scene.actors['root'])

sil = root.silhouette().lw(1).c('k')
scene.add_vtkactor(sil)

scene.render(camera='top')
	with open(fp) as f:
		temp = json.load(f)

	print(len(temp['neurons']))

	x = temp['neurons'][0]['soma']['x']
	y = temp['neurons'][0]['soma']['y']
	z = temp['neurons'][0]['soma']['z']

	return (x,y,z)

for k,vlist in groups.items():
	if k not in [1,3,2,12]:
		screenshot_params = dict(
		folder = './screenshots/single_cell_views',
		name='top_cluster_{0}'.format(k),
		)
		scene = Scene(display_inset=False, screenshot_kwargs=screenshot_params)
		for i,neuron in enumerate(vlist):
			if neuron not in left_neurons:
				fp = cell_filepaths[neuron]
			else:
				fp = cell_filepaths[neuron].split('.json')[0] + '_reversed.json'
			scene.add_neurons(fp, soma_color=cmap[i], render_axons=True, render_dendrites=True, dendrites_color=cmap[i], 
	                axon_color=cmap[i], neurite_radius=18)
			# pos = get_point(fp)
			# print(pos)
			# scene.add_sphere_at_point(pos=pos, radius= 75, color=cmap[i])	
		scene.render(interactive=False,camera='top', zoom=1)
		scene.take_screenshot()
		
예제 #23
0
brainrender.SHOW_AXES = True

# Create Scene
scene = Scene()

# add brain regions
mos, hy = scene.add_brain_regions(["MOs", "HY"], alpha=0.2)
mos.wireframe()
hy.wireframe()

# Get center of mass of the two regions
p1 = scene.atlas.get_region_CenterOfMass("MOs")
p2 = scene.atlas.get_region_CenterOfMass("HY")

# Use the ruler class to display the distance between the two points
"""
    Brainrender units are in micrometers. To display the distance
    measure instead we will divide by a factor of 1000 using 
    the unit_scale argument.
"""

# Add a ruler form the brain surface
scene.add_ruler_from_surface(p2)

# Add a ruler between the two regions
scene.add_actor(ruler(p1, p2, unit_scale=0.01, units="mm"))

# render
scene.render()
예제 #24
0
# ------------------------------- Create frames ------------------------------ #
# Create frames
prev_streamlines = []
for step in tqdm(np.arange(N_FRAMES)):
    if step % N_frames_for_change == 0:  # change neurons every N framse

        # reset neurons from previous set of neurons
        for mesh in prev_streamlines:
            mesh.alpha(minalpha)
            mesh.color(darkcolor)
        prev_streamlines = []

        # highlight new neurons
        streamlines = choices(scene.actors['tracts'], k=N_streamlines_in_frame)
        for n, mesh in enumerate(streamlines):
            # color = colorMap(n, 'Reds', vmin=-2, vmax=N_streamlines_in_frame+3)
            mesh.alpha(.7)
            mesh.color('orangered')
            prev_streamlines.append(mesh)

    # Move scene camera between 3 cameras
    if step < 150:
        scene.plotter.moveCamera(cam1, cam2, frac[step])
    else:
        scene.plotter.moveCamera(cam3, cam2, frac[step])

    # Update rendered window
    time.sleep(.1)
    scene.render(zoom=zoom[step], interactive=False, video=True)
예제 #25
0
"""
    This tutorial shows you how to render efferent mesoscale connectivity
    data from the Allen mouse connectome project as streamlines coloring
    each injection's streamline individually. 

"""

from brainrender.scene import Scene
from brainrender.colors import makePalette

# Start by creating a scene with the allen brain atlas atlas
scene = Scene(title="streamlines")

# Download streamlines data for injections in the CA1 field of the hippocampus
filepaths, data = scene.atlas.download_streamlines_for_region("CA1")

scene.add_brain_regions(["CA1"], use_original_color=True, alpha=0.2)

# you can pass either the filepaths or the data
colors = makePalette(len(data), "salmon", "lightgreen")
scene.add_streamlines(data, color=colors, show_injection_site=False)

scene.render(camera="sagittal", zoom=1)
예제 #26
0
class AllenMorphology(Paths):
    """ Handles the download and visualisation of neuronal morphology data from the Allen database. """
    def __init__(self, *args, scene_kwargs={}, **kwargs):
        """
			Initialise API interaction and fetch metadata of neurons in the Allen Database. 
		"""
        if not connected_to_internet():
            raise ConnectionError(
                "You will need to be connected to the internet to use the AllenMorphology class"
            )

        Paths.__init__(self, *args, **kwargs)
        self.scene = Scene(add_root=False, display_inset=False, **scene_kwargs)

        # Create a Cache for the Cell Types Cache API
        self.ctc = CellTypesCache(
            manifest_file=os.path.join(self.morphology_allen, 'manifest.json'))

        # Get a list of cell metadata for neurons with reconstructions, download if necessary
        self.neurons = pd.DataFrame(
            self.ctc.get_cells(species=[CellTypesApi.MOUSE],
                               require_reconstruction=True))
        self.n_neurons = len(self.neurons)
        if not self.n_neurons:
            raise ValueError(
                "Something went wrong and couldn't get neurons metadata from Allen"
            )

        self.downloaded_neurons = self.get_downloaded_neurons()

    def get_downloaded_neurons(self):
        """ 
			Get's the path to files of downloaded neurons
		"""
        return [
            os.path.join(self.morphology_allen, f)
            for f in os.listdir(self.morphology_allen) if ".swc" in f
        ]

    def download_neurons(self, ids):
        """
			Download neurons

		:param ids: list of integers with neurons IDs

		"""
        if isinstance(ids, np.ndarray):
            ids = list(ids)
        if not isinstance(ids, (list)): ids = [ids]

        neurons = []
        for neuron_id in ids:
            neuron_file = os.path.join(self.morphology_allen,
                                       "{}.swc".format(neuron_id))
            neurons.append(
                self.ctc.get_reconstruction(neuron_id, file_name=neuron_file))

        return neurons

    def parse_neurons_swc_allen(self, morphology, color='blackboard', alpha=1):
        """
		SWC parser for Allen neuron's morphology data, they're a bit different from the Mouse Light SWC

		:param morphology: data with morphology
		:param neuron_number: int, number of the neuron being rendered.

		"""
        # Create soma actor
        radius = 1
        neuron_actors = [
            shapes.Sphere(pos=get_coords(morphology.soma)[::-1],
                          c=color,
                          r=radius * 3)
        ]

        # loop over trees
        for tree in morphology._tree_list:

            tree = pd.DataFrame(tree)
            branching_points = [
                t.id for i, t in tree.iterrows()
                if len(t.children) > 2 and t.id < len(tree)
            ]

            branch_starts = []
            for bp in branching_points:
                branch_starts.extend(tree.iloc[bp].children)

            for bp in branch_starts:
                parent = tree.iloc[tree.iloc[bp].parent]
                branch = [(parent.x, parent.y, parent.z)]
                point = tree.iloc[bp]

                while True:
                    branch.append((point.x, point.y, point.z))

                    if not point.children:
                        break
                    else:
                        try:
                            point = tree.iloc[point.children[0]]
                        except:
                            break

                # Create actor
                neuron_actors.append(
                    shapes.Tube(branch, r=radius, c='red', alpha=1, res=24))

        actor = merge(*neuron_actors)
        actor.color(color)
        actor.alpha(alpha)
        return actor

    # # Todo load/save neurons??
    def load_save_neuron(self, neuron_file, neuron=None):
        neuron_name = os.path.split(neuron_file)[-1].split('.swc')[0]

        savepath = os.path.join(self.morphology_cache, neuron_name + '.vtk')

        if neuron is None and os.path.isfile(savepath):
            return load(savepath)
        elif neuron is None:
            return None
        elif neuron is not None:
            neuron.write(savepath)

    def parse_neuron_swc(self,
                         filepath,
                         color='blackboard',
                         alpha=1,
                         radius_multiplier=.1,
                         overwrite=False):
        """
		Given an swc file, render the neuron

		:param filepath: str with path to swc file
		:param neuron_number: numnber of neuron being rendered

		"""
        # See if we rendered this neuron already
        if not overwrite:
            loaded = self.load_save_neuron(filepath)
            if loaded is not None:
                return loaded.color(color)

        print(f"Parsing swc file: {filepath}")
        # details on swc files: http://www.neuronland.org/NLMorphologyConverter/MorphologyFormats/SWC/Spec.html
        _sample = namedtuple("sample", "sampleN structureID x y z r parent"
                             )  # sampleN structureID x y z r parent

        if not os.path.isfile(filepath) or not ".swc" in filepath.lower():
            raise ValueError("unrecognized file path: {}".format(filepath))

        try:
            return self.parse_neurons_swc_allen(filepath)
        except:
            pass  #  the .swc file fas not generate with by allen

        f = open(filepath)
        content = f.readlines()
        f.close()
        content = [
            sample.replace("\n", "") for sample in content if sample[0] != '#'
        ]
        content = [sample for sample in content if len(sample) > 3]

        # crate empty dicts for soma axon and dendrites
        data = dict(id=[],
                    parentNumber=[],
                    radius=[],
                    sampleNumber=[],
                    x=[],
                    y=[],
                    z=[])

        # start looping around samples
        for sample in content:
            s = _sample(
                *[float(samp) for samp in sample.lstrip().rstrip().split(" ")])

            # append data to dictionary
            data['id'] = s.structureID
            data['parentNumber'].append(int(s.parent))
            data['radius'].append(s.r)
            data['x'].append(s.x)
            data['y'].append(s.y)
            data['z'].append(s.z)
            data['sampleNumber'].append(int(s.sampleN))

        # Get branches and soma
        print("		reconstructing neurites trees")
        data = pd.DataFrame(data)
        radius = data['radius'].values[0] * radius_multiplier

        soma = data.iloc[0]
        soma = shapes.Sphere(pos=[soma.x, soma.y, soma.z],
                             c=color,
                             r=radius * 4)
        neuron_actors = [soma]

        branches_end, branches_start = [], []  # Get branches start and end
        for parent in data.parentNumber.values:
            sons = data.loc[data.parentNumber == parent]
            if len(sons) > 1:
                branches_end.append(parent)
                for i, son in sons.iterrows():
                    branches_start.append(son.sampleNumber)

        print("		creating actors")
        for start in branches_start:
            node = data.loc[data.sampleNumber == start]
            parent = data.loc[data.sampleNumber == node.parentNumber.values[0]]

            branch = [(parent.x.values[0], parent.y.values[0],
                       parent.z.values[0])]
            while True:
                branch.append(
                    (node.x.values[0], node.y.values[0], node.z.values[0]))

                node = data.loc[data.parentNumber ==
                                node.sampleNumber.values[0]]
                if not len(node): break
                if node.sampleNumber.values[0] in branches_end:
                    branch.append(
                        (node.x.values[0], node.y.values[0], node.z.values[0]))
                    break

            neuron_actors.append(
                shapes.Tube(branch, r=radius, c='red', alpha=1, res=24))

        # Merge actors and save
        actor = merge(*neuron_actors)
        actor.color(color)
        actor.alpha(alpha)

        self.load_save_neuron(filepath, neuron=actor)
        return actor

    def add_neuron(self,
                   neuron,
                   shadow_axis=None,
                   shadow_offset=-20,
                   **kwargs):
        if isinstance(neuron, list):
            neurons = neuron
        else:
            if isinstance(neuron, str):
                if os.path.isdir(neuron):
                    neurons = listdir(neuron)
            else:
                neurons = [neuron]

        actors = []
        for neuron in neurons:
            if isinstance(neuron, str):
                neuron = self.parse_neuron_swc(neuron, **kwargs)
            elif isinstance(neuron, Morphology):
                neuron = self.parse_neurons_swc_allen(neuron, **kwargs)

            actor = self.scene.add_vtkactor(neuron)

            # scals = actor.points()[:, 1]
            # alphas = np.linspace(0.82, .83, 250)
            # actor.pointColors(scals, alpha=alphas, cmap="Greens_r")

            # actor.points()[:, 0] += np.random.normal(0, 2000)
            # actor.points()[:, 2] += np.random.normal(0, 2000)

            if shadow_axis == 'x':
                actor.addShadow(x=shadow_offset)
            elif shadow_axis == 'y':
                actor.addShadow(y=shadow_offset)
            elif shadow_axis == 'z':
                actor.addShadow(z=shadow_offset)

            actors.append(neuron)

        return actors

    def render(self, **kwargs):
        self.scene.render(**kwargs)
예제 #27
0
def test_scene_creation_ignore_root_and_inset():
    s = Scene(add_root=False, display_inset=False)
    s.render(interactive=False)
    s.close()
예제 #28
0
"""
import brainrender
brainrender.USE_MORPHOLOGY_CACHE = True
from brainrender.scene import Scene
from brainrender.Utils.MouseLightAPI.mouselight_api import MouseLightAPI
from brainrender.Utils.MouseLightAPI.mouselight_info import mouselight_api_info, mouselight_fetch_neurons_metadata

# Fetch metadata for neurons with some in the secondary motor cortex
neurons_metadata = mouselight_fetch_neurons_metadata(filterby='soma',
                                                     filter_regions=['MOs'])

# Then we can download the files and save them as a .json file
ml_api = MouseLightAPI()
neurons_files = ml_api.download_neurons(
    neurons_metadata[:2]
)  # just saving the first couple neurons to speed things up

# Show neurons and ZI in the same scene:
scene = Scene()
scene.add_neurons(
    neurons_files,
    soma_color='orangered',
    dendrites_color='orangered',
    axon_color='darkseagreen',
    neurite_radius=8
)  # add_neurons takes a lot of arguments to specify how the neurons should look
# make sure to check the source code to see all available optionsq

scene.add_brain_regions(['MOs'], alpha=0.15)
scene.render(camera='coronal')
예제 #29
0
def test_animated_scene():
    # --------------------------------- Variables -------------------------------- #
    minalpha = 0.01  # transparency of background neurons
    darkcolor = "lightgray"  # background neurons color

    N_FRAMES = 50
    N_neurons = 4  # number of neurons to show in total, if -1 all neurons are shown but it might take a while to render them at first
    N_neurons_in_frame = (
        2  # number of neurons to be highlighted in a given frame
    )
    N_frames_for_change = 15  # every N frames which neurons are shown changes

    # Variables to specify camera position at each frame
    zoom = np.linspace(1, 1.5, N_FRAMES)
    frac = np.zeros_like(
        zoom)  # for camera transition, interpolation value between cameras
    frac[:10] = np.linspace(0, 1, 10)
    frac[10:] = np.linspace(1, 0, len(frac[10:]))

    # -------------------------------- Fetch data -------------------------------- #

    # Then we can download the files and save them as a .json file
    ml_api = MouseLightAPI()
    # Fetch metadata for neurons with some in the secondary motor cortex
    neurons_metadata = ml_api.fetch_neurons_metadata(filterby="soma",
                                                     filter_regions=["MOs"])

    neurons_files = ml_api.download_neurons(neurons_metadata[:N_neurons])

    # ------------------------------- Create scene ------------------------------- #
    scene = Scene(display_inset=False, use_default_key_bindings=True)

    neurons_actors = scene.add_neurons(neurons_files,
                                       neurite_radius=12,
                                       alpha=0)

    # Create new cameras
    cam1 = buildcam(sagittal_camera)

    cam2 = buildcam(
        dict(
            position=[-16624.081, -33431.408, 33527.412],
            focal=[6587.835, 3849.085, 5688.164],
            viewup=[0.634, -0.676, -0.376],
            distance=51996.653,
            clipping=[34765.671, 73812.327],
        ))

    cam3 = buildcam(
        dict(
            position=[1862.135, -4020.792, -36292.348],
            focal=[6587.835, 3849.085, 5688.164],
            viewup=[0.185, -0.97, 0.161],
            distance=42972.44,
            clipping=[29629.503, 59872.10],
        ))

    # ------------------------------- Create frames ------------------------------ #
    # Create frames
    prev_neurons = []
    for step in track(np.arange(N_FRAMES),
                      total=N_FRAMES,
                      description="Generating frames..."):
        if step % N_frames_for_change == 0:  # change neurons every N framse

            # reset neurons from previous set of neurons
            for neuron in prev_neurons:
                for component, actor in neuron.items():
                    actor.alpha(minalpha)
                    actor.color(darkcolor)
            prev_neurons = []

            # highlight new neurons
            neurons = choices(neurons_actors, k=N_neurons_in_frame)
            for n, neuron in enumerate(neurons):
                color = colorMap(n,
                                 "Greens_r",
                                 vmin=-2,
                                 vmax=N_neurons_in_frame + 3)
                for component, actor in neuron.items():
                    actor.alpha(1)
                    actor.color(color)
                prev_neurons.append(neuron)

        # Move scene camera between 3 cameras
        scene.plotter.moveCamera(cam1, cam2, frac[step])
        if frac[step] == 1:
            cam1 = cam3

        # Update rendered window
        time.sleep(0.1)
        scene.render(zoom=zoom[step], interactive=False, video=True)
    scene.close()
예제 #30
0
brainrender.SHADER_STYLE = "cartoon"
from brainrender.scene import Scene

screenshot_params = dict(
    folder="./screenshots",
    name="tutorial",
)

# Create a scene
scene = Scene(
    screenshot_kwargs=screenshot_params
)  # use screenshot_params to specify where the screenshots will be saved

scene.add_brain_regions(["TH"])

# render
scene.render(
    camera="top", interactive=False
)  # if interactive is false the program won't stop when the scene is rendered
# which means that the next line will be executed
scene.take_screenshot()
time.sleep(1)

# Take another screenshot from a different angle
scene.render(camera="coronal", interactive=False, zoom=0.5)
scene.take_screenshot(
)  # screenshots are saved with a timestamp in the name so you won't be overwriting the previous one.

# Render interactively. You can then press 's' to take a screenshot
scene.render()