Skip to content

Commit

Permalink
actor getattr and tests fiz
Browse files Browse the repository at this point in the history
  • Loading branch information
FedeClaudi committed Oct 27, 2020
1 parent aac0c29 commit 32dd43d
Show file tree
Hide file tree
Showing 9 changed files with 62 additions and 58 deletions.
4 changes: 0 additions & 4 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.3.0 # Use the ref you want to point at
hooks:
- id: check-added-large-files
- repo: https://github.com/python/black
rev: 19.10b0
hooks:
Expand Down
2 changes: 1 addition & 1 deletion brainrender/Utils/actors_funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ def edit_actor(
if color:
actor.color(c=color)
if line:
set_line(actor, **line_kwargs)
set_line(actor.mesh, **line_kwargs)
if upsample:
actor.subdivide(N=1)
if downsample:
Expand Down
20 changes: 0 additions & 20 deletions brainrender/Utils/scene_utils.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import numpy as np
import inspect
from vedo import Mesh, Text, Sphere
import random

from brainrender.atlases.atlas import Atlas
import brainrender
from brainrender.Utils.camera import check_camera_param
from brainrender.colors import get_random_colors
Expand Down Expand Up @@ -38,24 +36,6 @@ def parse_add_actors_inputs(actors, name, br_class):
return actors, names, br_classes


def get_scene_atlas(atlas, base_dir, atlas_kwargs={}, **kwargs):
"""
Return an instance of an Atlas class.
"""
if atlas is None:
atlas = brainrender.DEFAULT_ATLAS

if isinstance(atlas, str):
return Atlas(atlas, base_dir=base_dir, **atlas_kwargs, **kwargs,)
elif inspect.isclass(atlas):
return atlas(**atlas_kwargs)
else:
raise ValueError(
"The `atlas` argument should be None, a string with atlas name or a class"
)


def get_scene_camera(camera, atlas):
"""
Gets a working camera.
Expand Down
15 changes: 13 additions & 2 deletions brainrender/actor.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import pyinspect as pi
from vedo import Mesh
from io import StringIO
from rich.console import Console
from pyinspect._colors import orange, mocassin, salmon
Expand All @@ -8,7 +7,7 @@
from brainrender.Utils.scene_utils import make_actor_label


class Actor(Mesh):
class Actor(object):
_skip = ["Ruler", "silhouette"]

_needs_label = False
Expand All @@ -20,6 +19,18 @@ def __init__(self, mesh, name=None, br_class=None):
self.name = name
self.br_class = br_class

def __getattr__(self, attr):
"""
If an unknown attribute is called, try `self.mesh.attr`
"""
if attr == "__rich__":
return None
print(attr)
if hasattr(self.__dict__["mesh"], attr):
return getattr(self.__dict__["mesh"], attr)
else:
raise AttributeError(f"{self} doesn not have attribute {attr}")

def __repr__(self):
return f"brainrender.Actor: {self.name}-{self.br_class}"

Expand Down
34 changes: 30 additions & 4 deletions brainrender/atlases/atlas.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import os
from bg_atlasapi.bg_atlas import BrainGlobeAtlas
from pyinspect.classes import Enhanced

import inspect
import brainrender
from brainrender.Utils.paths_manager import Paths
from brainrender.atlases.aba import ABA
Expand All @@ -18,6 +18,25 @@
from brainrender.colors import check_colors
from brainrender.Utils.atlases_utils import parse_neurons_colors
from brainrender.morphology.utils import get_neuron_actors_with_morphapi
from brainrender.actor import Actor


def get_scene_atlas(atlas, base_dir, atlas_kwargs={}, **kwargs):
"""
Return an instance of an Atlas class.
"""
if atlas is None:
atlas = brainrender.DEFAULT_ATLAS

if isinstance(atlas, str):
return Atlas(atlas, base_dir=base_dir, **atlas_kwargs, **kwargs,)
elif inspect.isclass(atlas):
return atlas(**atlas_kwargs)
else:
raise ValueError(
"The `atlas` argument should be None, a string with atlas name or a class"
)


class Atlas(BrainGlobeAtlas, Paths, ABA, Enhanced):
Expand Down Expand Up @@ -289,9 +308,16 @@ def get_neurons(
if not isinstance(neurons, (list, tuple)):
neurons = [neurons]

clean_neurons = []
for n in neurons:
if isinstance(n, (tuple, list)):
clean_neurons.extend(list(n))
else:
clean_neurons.append(n)

# ---------------------------------- Render ---------------------------------- #
_neurons_actors = []
for neuron in neurons:
for neuron in clean_neurons:
neuron_actors = {"soma": None, "dendrites": None, "axon": None}

# Deal with neuron as filepath
Expand All @@ -314,7 +340,7 @@ def get_neurons(
)

# Deal with neuron as single actor
elif isinstance(neuron, Mesh):
elif isinstance(neuron, (Actor, Mesh)):
# A single actor was passed, maybe it's the entire neuron
neuron_actors["soma"] = neuron # store it as soma
pass
Expand Down Expand Up @@ -357,7 +383,7 @@ def get_neurons(
# Check that we don't have anything weird in neuron_actors
for key, act in neuron_actors.items():
if act is not None:
if not isinstance(act, Mesh):
if not isinstance(act, (Actor, Mesh)):
raise ValueError(
f"Neuron actor {key} is {type(act)} but should be a vedo Mesh. Not: {act}"
)
Expand Down
19 changes: 12 additions & 7 deletions brainrender/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,14 @@ def __init__(
vedosettings.screenshotTransparentBackground = False
vedosettings.useFXAA = True

@property
def to_render(self):
return [
a.mesh
for a in flatten(self.actors) + flatten(self.actors_labels)
if a.mesh is not None
]

def _make_custom_axes(self):
"""
When using `ruler` axes (vedy style 7), we need to
Expand Down Expand Up @@ -137,7 +145,7 @@ def _make_custom_axes(self):
plt.renderer.AddActor(rulax)
plt.axes_instances[0] = rulax

return
return plt

def _correct_axes(self):
"""
Expand Down Expand Up @@ -246,7 +254,7 @@ def render(
args_dict["offscreen"] = True

if self.make_custom_axes:
self._make_custom_axes()
self.plotter = self._make_custom_axes()
self.make_custom_axes = False

# Correct axes orientations
Expand All @@ -259,10 +267,7 @@ def render(
self.apply_render_style()

self.is_rendered = True
to_render = [
a.mesh for a in flatten(self.actors) + flatten(self.actors_labels)
]
show(*to_render, **args_dict)
show(*self.to_render, **args_dict)

def close(self):
closePlotter()
Expand All @@ -281,7 +286,7 @@ def export_for_web(self, filepath="brexport.html"):

# Create new plotter and save to file
plt = Plotter()
plt.add(self.actors)
plt.add(self.to_render)
plt = plt.show(interactive=False)
plt.camera[-2] = -1

Expand Down
11 changes: 5 additions & 6 deletions brainrender/scene.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,15 @@
Text2D,
closePlotter,
Plane,
Mesh,
)
import numpy as np
import pyinspect as pi
from pyinspect._colors import dimorange, orange, mocassin, salmon
from rich import print as rprint
import sys

from brainrender.atlases.atlas import get_scene_atlas
from brainrender.Utils.scene_utils import (
get_scene_atlas,
get_cells_colors_from_metadata,
parse_add_actors_inputs,
)
Expand Down Expand Up @@ -124,7 +123,7 @@ def __repr__(self):
return f"A `brainrender.scene.Scene` with {len(self)} actors."

def __add__(self, other):
if isinstance(other, Mesh):
if isinstance(other, Actor):
self.add_actor(other)
elif isinstance(other, (Path, str)):
self.add_from_file(str(other))
Expand Down Expand Up @@ -813,7 +812,7 @@ def render(self, _interactive=True):
for scene in self.scenes:
scene.apply_render_style()
actors.append(scene.actors)
mv.add(scene.actors)
mv.add([act.mesh for act in scene.actors])

mv.show(
actors[0],
Expand Down Expand Up @@ -884,8 +883,8 @@ def render(self, _interactive=True, **kwargs):
actors = []
for i, scene in enumerate(self.scenes):
scene.apply_render_style()
actors.append(scene.actors)
mv.add(scene.actors)
actors.append(scene.to_render)
mv.add(scene.to_render)

for i, scene.actors in enumerate(actors):
mv.show(scene.actors, at=i, interactive=False)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_scene.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ def test_get_random_points(scene):
get_n_random_points_in_region(scene.atlas, "MOs", 100)
get_n_random_points_in_region(scene.atlas, "MOp", 100, hemisphere="right")
ca1 = scene.add_brain_regions("CA1")
get_n_random_points_in_region(scene.atlas, ca1, 100)
get_n_random_points_in_region(scene.atlas, ca1.mesh, 100)


def test_add_from_file(scene):
Expand Down
13 changes: 0 additions & 13 deletions tests/test_scene_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,13 @@
sagittal_camera,
top_camera,
)
from brainrender.colors import colorMap

import pytest


@pytest.mark.slow
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
Expand Down Expand Up @@ -86,21 +83,11 @@ def test_animated_scene():
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
Expand Down

0 comments on commit 32dd43d

Please sign in to comment.