### Developer installation Source: https://ipyvolume.readthedocs.io/en/latest/install.html Steps for installing the library from source for development. ```bash $ git clone https://github.com/maartenbreddels/ipyvolume.git $ cd ipyvolume $ pip install -e . $ jupyter nbextension install --py --symlink --sys-prefix ipyvolume $ jupyter nbextension enable --py --sys-prefix ipyvolume ``` -------------------------------- ### Volume rendering - Basic setup Source: https://ipyvolume.readthedocs.io/en/latest/examples/lighting.html Sets up a figure and a volume example without explicit material or lighting. ```python import ipyvolume as ipv # no material and lighting ipv.figure() volume = ipv.examples.example_ylm(shape=64, show=False) s = ipv.scatter(x=32, y=32, z=50, size=30, marker='sphere', color="green"); volume.tf.level1 = 0.24 volume.tf.opacity1 = 0.1 volume.brightness = 2 ipv.show() ``` -------------------------------- ### Install using pip Source: https://ipyvolume.readthedocs.io/en/latest/install.html Standard installation using pip. ```bash $ pip install ipyvolume ``` -------------------------------- ### Developer workflow: Watch for changes Source: https://ipyvolume.readthedocs.io/en/latest/install.html Command to start a watcher for the JavaScript source code during development. ```bash $ (cd js; npm run watch) ``` -------------------------------- ### Pip as user installation (with warning) Source: https://ipyvolume.readthedocs.io/en/latest/install.html User-specific installation using pip, with a strong warning against this practice. ```bash $ pip install ipyvolume --user $ jupyter nbextension enable --py --user ipyvolume $ jupyter nbextension enable --py --user widgetsnbextension ``` -------------------------------- ### Install using Conda/Anaconda Source: https://ipyvolume.readthedocs.io/en/latest/install.html Installation using conda, specifying the conda-forge channel. ```bash $ conda install -c conda-forge ipyvolume ``` -------------------------------- ### Style Usage Example Source: https://ipyvolume.readthedocs.io/en/latest/api.html Examples showing how to apply different styles to the ipyvolume visualization using the `style.use` method. ```python >>> import ipyvolume as ipv >>> ipv.style.use('light']) >>> ipv.style.use('seaborn-darkgrid']) >>> ipv.style.use(['seaborn-darkgrid', {'axes.x.color':'orange'}]) ``` -------------------------------- ### Install Jupyter Lab extension Source: https://ipyvolume.readthedocs.io/en/latest/install.html Steps to install the Jupyter Lab extension, including nodejs. ```bash $ conda install -c conda-forge nodejs # or some other way to have a recent node $ jupyter labextension install @jupyter-widgets/jupyterlab-manager $ jupyter labextension install ipyvolume $ jupyter labextension install jupyter-threejs ``` -------------------------------- ### IntText Widget Example Source: https://ipyvolume.readthedocs.io/en/latest/examples/popup.html An example of creating an IntText widget. ```python import ipywidgets as widgets int_widget = widgets.IntText(description="index", value=2) int_widget ``` -------------------------------- ### Load example volume Source: https://ipyvolume.readthedocs.io/en/latest/examples/slice.html Loads the 'head' example volume and displays the figure. ```python import ipyvolume as ipv fig = ipv.figure() volume = ipv.examples.head(show=False, description="Patient X") ipv.show() ``` -------------------------------- ### Ambient light example Source: https://ipyvolume.readthedocs.io/en/latest/examples/lighting.html Demonstrates adding ambient light for global illumination. ```python scene() light = ipv.light_ambient(intensity=0.4); ``` -------------------------------- ### Spot light example Source: https://ipyvolume.readthedocs.io/en/latest/examples/lighting.html Demonstrates a spotlight, which produces a directed cone of light and can cast shadows. ```python scene() ipv.light_hemisphere(intensity=0.2) l = ipv.light_spot(position=[0, 3, 2]); ``` -------------------------------- ### Movie Creation Example Source: https://ipyvolume.readthedocs.io/en/latest/api.html Example demonstrating how to create an animated GIF by rotating a figure around the y-axis using the `movie` function. ```python >>> def set_angles(fig, i, fraction): >>> fig.angley = fraction*np.pi*2 >>> # 4 second movie, that rotates around the y axis >>> p3.movie('test2.gif', set_angles, fps=20, frames=20*4, endpoint=False) ``` -------------------------------- ### Container Initialization Example Source: https://ipyvolume.readthedocs.io/en/latest/_modules/traitlets/traitlets.html Shows how to initialize a Container trait, including handling cases where only a default value is provided. ```python class Container(Instance): """An instance of a container (list, set, etc.) To be subclassed by overriding klass. """ klass = None _cast_types = () _valid_defaults = SequenceTypes _trait = None _literal_from_string_pairs = ("[]", "()") def __init__(self, trait=None, default_value=Undefined, **kwargs): """Create a container trait type from a list, set, or tuple. The default value is created by doing ``List(default_value)``, which creates a copy of the ``default_value``. ``trait`` can be specified, which restricts the type of elements in the container to that TraitType. If only one arg is given and it is not a Trait, it is taken as ``default_value``: ``c = List([1, 2, 3])`` Parameters ---------- trait : TraitType [ optional ] the type for restricting the contents of the Container. If unspecified, types are not checked. default_value : SequenceType [ optional ] The default value for the Trait. Must be list/tuple/set, and will be cast to the container type. allow_none : bool [ default False ] Whether to allow the value to be None **kwargs : any further keys for extensions to the Trait (e.g. config) """ # allow List([values]): if trait is not None and default_value is Undefined and not is_trait(trait): default_value = trait ``` -------------------------------- ### Enable extensions for pre-notebook 5.3 Source: https://ipyvolume.readthedocs.io/en/latest/install.html Commands to list and enable extensions for older Jupyter notebook versions. ```bash $ jupyter nbextention list ``` ```bash $ jupyter nbextension enable --py --sys-prefix ipyvolume $ jupyter nbextension enable --py --sys-prefix widgetsnbextension ``` -------------------------------- ### link Example Source: https://ipyvolume.readthedocs.io/en/latest/_modules/traitlets/traitlets.html Example of linking traits between objects. ```python >>> c = link((src, "value"), (tgt, "value")) >>> src.value = 5 # updates other objects as well ``` -------------------------------- ### Dict Trait Examples Source: https://ipyvolume.readthedocs.io/en/latest/_modules/traitlets/traitlets.html Examples demonstrating the usage of the Dict trait for validating dictionary keys and values. ```python >>> d = Dict(Unicode()) a dict whose values must be text >>> d2 = Dict(per_key_traits={"n": Integer(), "s": Unicode()}) d2['n'] must be an integer d2['s'] must be text >>> d3 = Dict(value_trait=Integer(), key_trait=Unicode()) d3's keys must be text d3's values must be integers ``` -------------------------------- ### Installation commands Source: https://ipyvolume.readthedocs.io/en/latest/index.html Provides commands for installing ipyvolume using pip and enabling Jupyter extensions. ```bash pip install ipyvolume jupyter nbextension enable --py --sys-prefix ipyvolume jupyter nbextension enable --py --sys-prefix widgetsnbextension ``` -------------------------------- ### Enable ipywidgets for older notebooks Source: https://ipyvolume.readthedocs.io/en/latest/install.html Commands to ensure ipywidgets and related extensions are enabled for older notebook versions. ```bash $ jupyter nbextension enable --py --sys-prefix widgetsnbextension $ jupyter nbextension enable --py --sys-prefix pythreejs $ jupyter nbextension enable --py --sys-prefix ipywebrtc $ jupyter nbextension enable --py --sys-prefix ipyvolume ``` -------------------------------- ### Style Class Example Source: https://ipyvolume.readthedocs.io/en/latest/_modules/ipyvolume/pylab.html Examples of how to use the style.use method to set visualization styles. ```python import ipyvolume as ipv ipv.style.use('light') ipv.style.use('seaborn-darkgrid') ipv.style.use(['seaborn-darkgrid', {'axes.x.color':'orange'}]) ``` -------------------------------- ### Animation example - Data loading Source: https://ipyvolume.readthedocs.io/en/latest/examples/lighting.html Loads an animated stream dataset and prints its shape. ```python import ipyvolume as ipv import ipyvolume.datasets stream = ipyvolume.datasets.animated_stream.fetch() print("shape of steam data", stream.data.shape) # first dimension contains x, y, z, vx, vy, vz, then time, then particle ``` -------------------------------- ### Animation example - Ambient light Source: https://ipyvolume.readthedocs.io/en/latest/examples/lighting.html Adds ambient light to the animation scene. ```python ipv.light_ambient(intensity=0.4); ``` -------------------------------- ### CaselessStrEnum Example Source: https://ipyvolume.readthedocs.io/en/latest/_modules/traitlets/traitlets.html Demonstrates the CaselessStrEnum class, which allows for case-insensitive string enum comparisons. ```python class CaselessStrEnum(Enum): """An enum of strings where the case should be ignored.""" def __init__(self, values, default_value=Undefined, **kwargs): super().__init__(values, default_value=default_value, **kwargs) def validate(self, obj, value): if not isinstance(value, str): self.error(obj, value) for v in self.values: if v.lower() == value.lower(): return v self.error(obj, value) def _info(self, as_rst=False): """ Returns a description of the trait.""" none = (' or %s' % ('`None`' if as_rst else 'None') if self.allow_none else '') return 'any of %s (case-insensitive)%s' % (self._choices_str(as_rst), none) def info(self): return self._info(as_rst=False) def info_rst(self): return self._info(as_rst=True) ``` -------------------------------- ### Hemisphere light example Source: https://ipyvolume.readthedocs.io/en/latest/examples/lighting.html Shows how to use hemisphere light, which fades from sky to ground color. ```python scene() ipv.light_hemisphere(intensity=1); ``` -------------------------------- ### ipyvolume.examples Module Code Source: https://ipyvolume.readthedocs.io/en/latest/_modules/ipyvolume/examples.html Source code for the ipyvolume.examples module, including helper functions and example visualizations. ```python """Some examples for quick testing/demonstrations. All function accept `show` and `draw` arguments * If `draw` is `True` it will return the widgets (Scatter, Volume, Mesh) * If `draw` is `False`, it will return the data * if `show` is `False`, `ipv.show()` will not be called. """ import warnings import numpy as np from numpy import cos, sin, pi try: import scipy.ndimage import scipy.special except: pass # it's ok, it's not crucial # __all__ = ["example_ylm"] [docs]def xyz(shape=128, limits=[-3, 3], spherical=False, sparse=True, centers=False): dim = 3 try: shape[0] except: shape = [shape] * dim try: limits[0][0] # pylint: disable=unsubscriptable-object except: limits = [limits] * dim if centers: v = [ slice(vmin + (vmax - vmin) / float(N) / 2, vmax - (vmax - vmin) / float(N) / 4, (vmax - vmin) / float(N)) for (vmin, vmax), N in zip(limits, shape) ] else: v = [ slice(vmin, vmax + (vmax - vmin) / float(N) / 2, (vmax - vmin) / float(N - 1)) for (vmin, vmax), N in zip(limits, shape) ] if sparse: x, y, z = np.ogrid.__getitem__(v) else: x, y, z = np.mgrid.__getitem__(v) if spherical: r = (x ** 2 + y**2 + z**2)**0.5 theta = np.arctan2(y, x) phi = np.arccos(z / r) return x, y, z, r, theta, phi else: return x, y, z [docs]def example_ylm(m=0, n=2, shape=128, limits=[-4, 4], draw=True, show=True, **kwargs): """Show a spherical harmonic.""" import ipyvolume.pylab as p3 __, __, __, r, theta, phi = xyz(shape=shape, limits=limits, spherical=True) radial = np.exp(-(r - 2) ** 2) data = np.abs(scipy.special.sph_harm(m, n, theta, phi) ** 2) * radial # pylint: disable=no-member if draw: vol = p3.volshow(data=data, **kwargs) if show: p3.show() return vol else: return data # return ipyvolume.volshow(data=data.T, **kwargs) [docs]def ball(rmax=3, rmin=0, shape=128, limits=[-4, 4], draw=True, show=True, **kwargs): """Show a ball.""" import ipyvolume.pylab as p3 __, __, __, r, _theta, _phi = xyz(shape=shape, limits=limits, spherical=True) data = r * 0 data[(r < rmax) & (r >= rmin)] = 0.5 if "data_min" not in kwargs: kwargs["data_min"] = 0 if "data_max" not in kwargs: kwargs["data_max"] = 1 data = data.T if draw: vol = p3.volshow(data=data, **kwargs) if show: p3.show() return vol else: return data ``` -------------------------------- ### Scene setup function Source: https://ipyvolume.readthedocs.io/en/latest/examples/lighting.html Defines a function to create a basic ipyvolume scene with a scatter plot and a Klein bottle. ```python def scene(): f = ipv.figure() ipv.xyzlim(-1, 1) x = np.array([0.1, 0.5], dtype=np.float32) ipv.material_phong() s = ipv.scatter(x, x, x, marker="sphere", size=10); k = ipv.examples.klein_bottle(show=False) ipv.xyzlim(2) m = ipv.plot_plane('bottom') ipv.show() return f ``` -------------------------------- ### Point light example Source: https://ipyvolume.readthedocs.io/en/latest/examples/lighting.html Shows a point light that originates from a single point and spreads outward, capable of casting shadows. ```python scene() ipv.light_hemisphere(intensity=0.2) l = ipv.light_point(position=[0., 1.6, 1.0]); ``` -------------------------------- ### Animation example - Quiver plot Source: https://ipyvolume.readthedocs.io/en/latest/examples/lighting.html Creates a quiver plot from the animated stream data and sets up lighting and animation controls. ```python fig = ipv.figure() # instead of doing x=stream.data[0], y=stream.data[1], ... vz=stream.data[5], use *stream.data # limit to 50 timesteps to avoid having a huge notebook ipv.material_physical() # q = ipv.quiver(*stream.data[:,0:200:10,:2000:10], color="red", size=7) q = ipv.quiver(*stream.data, color="red", size=7) ipv.style.use("dark") # looks better m = ipv.plot_plane('bottom') m = ipv.plot_plane('back') m = ipv.plot_plane('left') ipv l = ipv.light_directional(position=[20, 50, 20], shadow_camera_orthographic_size=1, far=140, near=0.1); ipv.animation_control(q, interval=200) ipv.show() ``` -------------------------------- ### Directional light example Source: https://ipyvolume.readthedocs.io/en/latest/examples/lighting.html Illustrates directional light, which illuminates equally from a given direction and can cast shadows. ```python f = scene() ipv.light_ambient(intensity=0.4) ipv.light_directional(position=[3, 10, 3]); ``` -------------------------------- ### Gaussian Scatter Plot Example Source: https://ipyvolume.readthedocs.io/en/latest/_modules/ipyvolume/examples.html This function demonstrates how to create a scatter plot of N random Gaussian distributed points. ```python import ipyvolume as ipv rng = np.random.RandomState(seed) # pylint: disable=no-member x, y, z = rng.normal(size=(3, N)) if draw: if color: mesh = ipv.scatter(x, y, z, marker=marker, color=color, description=description, **kwargs) else: mesh = ipv.scatter(x, y, z, marker=marker, description=description, **kwargs) if show: # ipv.squarelim() ipv.show() return mesh else: return x, y, z ``` -------------------------------- ### Adding a Texture (Commented Out) Source: https://ipyvolume.readthedocs.io/en/latest/examples/slice.html Example code (commented out) for creating a 2D heatmap texture using vaex and matplotlib. ```python ## Uncomment to try # import vaex # import matplotlib.pylab as plt # import PIL.Image # df = vaex.from_arrays(x=scatter.x, y=scatter.y) # fig2d = plt.figure() # ax = fig2d.add_axes([0, 0, 1, 1]) # df.viz.heatmap(df.x, df.y, shape=64, show=False, colorbar=False, tight_layout=False) # fig2d.axes[0].axis('off'); # plt.draw() # image = PIL.Image.frombytes('RGB', fig2d.canvas.get_width_height(), fig2d.canvas.tostring_rgb()) # plt.close() # image ``` -------------------------------- ### Transfer Function Example Source: https://ipyvolume.readthedocs.io/en/latest/_modules/ipyvolume/examples.html This code snippet demonstrates how to create and use a transfer function for volumetric data visualization. ```python f = interp1d(x, rgb[:, channel], kind=kind) ynew = f(xnew) tf_data[:, channel] = ynew alphas = [[0, 0], [0, 40], [0.2, 60], [0.05, 63], [0, 80], [0.9, 82], [1.0, 256]] x = np.array([k[1] * 1.0 for k in alphas]) y = np.array([k[0] * 1.0 for k in alphas]) f = interp1d(x, y, kind=kind) ynew = f(xnew) tf_data[:, 3] = ynew tf = ipv.TransferFunction(rgba=tf_data.astype(np.float32)) head_data = ipv.datasets.head.fetch().data head_data = head_data.transpose((1, 0, 2))[::-1, ::-1, ::-1] if draw: vol = ipv.volshow(head_data, tf=tf, max_shape=max_shape, description=description) if show: ipv.show() return vol else: return head_data ``` -------------------------------- ### Tagging Metadata Source: https://ipyvolume.readthedocs.io/en/latest/_modules/traitlets/traitlets.html Example of the tag method, which sets metadata and returns the trait instance, allowing for convenient tagging during initialization. ```python def tag(self, **metadata): """Sets metadata and returns self. This allows convenient metadata tagging when initializing the trait, such as: >>> Int(0).tag(config=True, sync=True) """ maybe_constructor_keywords = set(metadata.keys()).intersection({'help','allow_none', 'read_only', 'default_value'}) if maybe_constructor_keywords: warn('The following attributes are set in using `tag`, but seem to be constructor keywords arguments: %s ' maybe_constructor_keywords, UserWarning, stacklevel=2) self.metadata.update(metadata) return self ``` -------------------------------- ### parse_notifier_name Examples Source: https://ipyvolume.readthedocs.io/en/latest/_modules/traitlets/traitlets.html Examples of how to use the parse_notifier_name function. ```python >>> parse_notifier_name([]) [All] >>> parse_notifier_name("a") ['a'] >>> parse_notifier_name(["a", "b"]) ['a', 'b'] >>> parse_notifier_name(All) [All] ``` -------------------------------- ### Conda installation Source: https://ipyvolume.readthedocs.io/en/latest/index.html Provides the command for installing ipyvolume using conda. ```bash conda install -c conda-forge ipyvolume ``` -------------------------------- ### HasDescriptors setup_instance Source: https://ipyvolume.readthedocs.io/en/latest/_modules/traitlets/traitlets.html The setup_instance method for HasDescriptors, initializing instance attributes and descriptors. ```python def setup_instance(*args, **kwargs): """ This is called **before** self.__init__ is called. """ # Pass self as args[0] to allow "self" as keyword argument self = args[0] args = args[1:] self._cross_validation_lock = False cls = self.__class__ for key in dir(cls): # Some descriptors raise AttributeError like zope.interface's # __provides__ attributes even though they exist. This causes # AttributeErrors even though they are listed in dir(cls). try: value = getattr(cls, key) except AttributeError: pass else: if isinstance(value, BaseDescriptor): value.instance_init(self) ``` -------------------------------- ### directional_link Example Source: https://ipyvolume.readthedocs.io/en/latest/_modules/traitlets/traitlets.html Example demonstrating how to use directional_link to link traits between objects. ```python >>> c = directional_link((src, "value"), (tgt, "value")) >>> src.value = 5 # updates target objects >>> tgt.value = 6 # does not update source object ``` -------------------------------- ### SciType Valid Example Source: https://ipyvolume.readthedocs.io/en/latest/_modules/traittypes/traittypes.html Example of registering trait validators for shape constraints. ```python import inspect import warnings from traitlets import TraitType, TraitError, Undefined, Sentinel class _DelayedImportError(object): def __init__(self, package_name): self.package_name = package_name def __getattribute__(self, name): package_name = super(_DelayedImportError, self).__getattribute__('package_name') raise RuntimeError('Missing dependency: %s' % package_name) try: import numpy as np except ImportError: np = _DelayedImportError('numpy') Empty = Sentinel('Empty', 'traittypes', """ Used in traittypes to specify that the default value should be an empty dataset """) class SciType(TraitType): """A base trait type for numpy arrays, pandas dataframes, pandas series, xarray datasets and xarray dataarrays.""" def __init__(self, **kwargs): super(SciType, self).__init__(**kwargs) self.validators = [] def valid(self, *validators): """ Register new trait validators Validators are functions that take two arguments. - The trait instance - The proposed value Validators return the (potentially modified) value, which is either assigned to the HasTraits attribute or input into the next validator. They are evaluated in the order in which they are provided to the `valid` function. Example ------- .. code:: python # Test with a shape constraint def shape(*dimensions): def validator(trait, value): if value.shape != dimensions: raise TraitError('Expected an of shape %s and got and array with shape %s' % (dimensions, value.shape)) else: return value return validator class Foo(HasTraits): bar = Array(np.identity(2)).valid(shape(2, 2)) foo = Foo() foo.bar = [1, 2] # Should raise a TraitError """ self.validators.extend(validators) return self def validate(self, obj, value): """Validate the value against registered validators.""" try: for validator in self.validators: value = validator(self, value) return value except (ValueError, TypeError) as e: raise TraitError(e) class Array(SciType): """A numpy array trait type.""" info_text = 'a numpy array' dtype = None def validate(self, obj, value): if value is None and not self.allow_none: self.error(obj, value) if value is None or value is Undefined: return super(Array, self).validate(obj, value) try: r = np.asarray(value, dtype=self.dtype) if isinstance(value, np.ndarray) and r is not value: warnings.warn( 'Given trait value dtype \"%s\" does not match required type \"%s\". ' 'A coerced copy has been created.' % ( np.dtype(value.dtype).name, np.dtype(self.dtype).name)) value = r except (ValueError, TypeError) as e: raise TraitError(e) return super(Array, self).validate(obj, value) def set(self, obj, value): new_value = self._validate(obj, value) old_value = obj._trait_values.get(self.name, self.default_value) obj._trait_values[self.name] = new_value if not np.array_equal(old_value, new_value): obj._notify_trait(self.name, old_value, new_value) def __init__(self, default_value=Empty, allow_none=False, dtype=None, **kwargs): self.dtype = dtype if default_value is Empty: default_value = np.array(0, dtype=self.dtype) elif default_value is not None and default_value is not Undefined: default_value = np.asarray(default_value, dtype=self.dtype) super(Array, self).__init__(default_value=default_value, allow_none=allow_none, **kwargs) def make_dynamic_default(self): if self.default_value is None or self.default_value is Undefined: return self.default_value else: return np.copy(self.default_value) class PandasType(SciType): """A pandas dataframe or series trait type.""" info_text = 'a pandas dataframe or series' klass = None def validate(self, obj, value): if value is None and not self.allow_none: self.error(obj, value) if value is None or value is Undefined: return super(PandasType, self).validate(obj, value) try: value = self.klass(value) except (ValueError, TypeError) as e: raise TraitError(e) return super(PandasType, self).validate(obj, value) def set(self, obj, value): new_value = self._validate(obj, value) ``` -------------------------------- ### Plot Plane Example Source: https://ipyvolume.readthedocs.io/en/latest/_modules/ipyvolume/pylab.html Example of plotting a plane at the back of the viewbox. ```python fig = gcf() xmin, xmax = fig.xlim ymin, ymax = fig.ylim zmin, zmax = fig.zlim if where == "back": x = [xmin, xmax, xmax, xmin] y = [ymin, ymin, ymax, ymax] z = [zmin, zmin, zmin, zmin] ``` -------------------------------- ### Import ipyvolume and vaex.ml Source: https://ipyvolume.readthedocs.io/en/latest/examples/popup.html Imports necessary libraries for using vaex with ipyvolume. ```python import ipyvolume as ipv import vaex.ml ``` -------------------------------- ### observe method Source: https://ipyvolume.readthedocs.io/en/latest/_modules/traitlets/traitlets.html Setup a handler to be called when a trait changes. This is used to setup dynamic notifications of trait changes. ```python def observe(self, handler, names=All, type='change'): """Setup a handler to be called when a trait changes. This is used to setup dynamic notifications of trait changes. Parameters ---------- handler : callable A callable that is called when a trait changes. Its signature should be ``handler(change)``, where ``change`` is a dictionary. The change dictionary at least holds a 'type' key. * ``type``: the type of notification. Other keys may be passed depending on the value of 'type'. In the case where type is 'change', we also have the following keys: * ``owner`` : the HasTraits instance * ``old`` : the old value of the modified trait attribute * ``new`` : the new value of the modified trait attribute * ``name`` : the name of the modified trait attribute. names : list, str, All If names is All, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name. type : str, All (default: 'change') The type of notification to filter by. If equal to All, then all notifications are passed to the observe handler. """ names = parse_notifier_name(names) for n in names: self._add_notifiers(handler, n, type) ``` -------------------------------- ### HasTraits setup_instance Source: https://ipyvolume.readthedocs.io/en/latest/_modules/traitlets/traitlets.html The setup_instance method for HasTraits, initializing trait-related attributes. ```python def setup_instance(*args, **kwargs): # Pass self as args[0] to allow "self" as keyword argument self = args[0] args = args[1:] self._trait_values = {} self._trait_notifiers = {} self._trait_validators = {} super(HasTraits, self).setup_instance(*args, **kwargs) ``` -------------------------------- ### plot_trisurf Example Source: https://ipyvolume.readthedocs.io/en/latest/_modules/ipyvolume/pylab.html Example of plotting a rectangle in the z==2 plane using plot_trisurf. ```python >>> plot_trisurf([0, 0, 3., 3.], [0, 4., 0, 4.], 2, triangles=[[0, 2, 3], [0, 3, 1]]) ``` -------------------------------- ### Tweak material settings Source: https://ipyvolume.readthedocs.io/en/latest/pythreejs.html Demonstrates how to modify material properties, such as making the material invisible. ```python scatter.material.visible = False ``` -------------------------------- ### example_ylm Source: https://ipyvolume.readthedocs.io/en/latest/api.html Show a spherical harmonic. ```python ipyvolume.examples.example_ylm(_m=0, n=2, shape=128, limits=[-4, 4], draw=True, show=True, **kwargs_) ``` -------------------------------- ### plot_trisurf example Source: https://ipyvolume.readthedocs.io/en/latest/api.html Example demonstrating how to plot a rectangle in the z==2 plane using plot_trisurf, defining triangles by vertex indices. ```python >>> plot_trisurf([0, 0, 3., 3.], [0, 4., 0, 4.], 2, triangles=[[0, 2, 3], [0, 3, 1]]) ``` -------------------------------- ### Traitlets Import Source: https://ipyvolume.readthedocs.io/en/latest/examples/popup.html Imports the traitlets library. ```python import traitlets ``` -------------------------------- ### show Source: https://ipyvolume.readthedocs.io/en/latest/api.html Display (like in IPython.display.dispay(…)) the current figure. ```python ipyvolume.pylab.show(extra_widgets=[]) ``` -------------------------------- ### _register_validator method Source: https://ipyvolume.readthedocs.io/en/latest/_modules/traitlets/traitlets.html Setup a handler to be called when a trait should be cross validated. This is used to setup dynamic notifications for cross-validation. If a validator is already registered for any of the provided names, a TraitError is raised and no new validator is registered. ```python def _register_validator(self, handler, names): """Setup a handler to be called when a trait should be cross validated. This is used to setup dynamic notifications for cross-validation. If a validator is already registered for any of the provided names, a TraitError is raised and no new validator is registered. """ pass ``` -------------------------------- ### Import necessary libraries and generate data Source: https://ipyvolume.readthedocs.io/en/latest/examples/scales.html Imports ipyvolume, bqplot.scales, numpy, and ipywidgets. Generates sample data with x-axis on a logarithmic scale. ```python import ipyvolume as ipv import bqplot.scales import numpy as np import ipywidgets as widgets N = 500 x, y, z = np.random.normal(0, 1, (3, N)) x = 10**x r = np.sqrt(np.log10(x)**2 + y**2 + z**2) ``` -------------------------------- ### on_trait_change method Source: https://ipyvolume.readthedocs.io/en/latest/_modules/traitlets/traitlets.html DEPRECATED: Setup a handler to be called when a trait changes. This method is used to setup dynamic notifications of trait changes. Static handlers can be created by creating methods on a HasTraits subclass with the naming convention '_[traitname]_changed'. ```python def on_trait_change(self, handler=None, name=None, remove=False): """DEPRECATED: Setup a handler to be called when a trait changes. This is used to setup dynamic notifications of trait changes. Static handlers can be created by creating methods on a HasTraits subclass with the naming convention '_[traitname]_changed'. Thus, to create static handler for the trait 'a', create the method '_a_changed(self, name, old, new)' (fewer arguments can be used, see below). If `remove` is True and `handler` is not specified, all change handlers for the specified name are uninstalled. Parameters ---------- handler : callable, None A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new), handler(name, old, new), or handler(name, old, new, self). name : list, str, None If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name. remove : bool If False (the default), then install the handler. If True then unintall it. """ warn("on_trait_change is deprecated in traitlets 4.1: use observe instead", DeprecationWarning, stacklevel=2) if name is None: name = All if remove: self.unobserve(_callback_wrapper(handler), names=name) else: self.observe(_callback_wrapper(handler), names=name) ``` -------------------------------- ### trait_events Source: https://ipyvolume.readthedocs.io/en/latest/_modules/traitlets/traitlets.html Get a dict of all the event handlers of this class. ```python @classmethod def trait_events(cls, name=None): """Get a ``dict`` of all the event handlers of this class. Parameters ---------- name : str (default: None) The name of a trait of this class. If name is ``None`` then all the event handlers of this class will be returned instead. Returns ------- The event handlers associated with a trait name, or all event handlers. """ events = {} for k, v in getmembers(cls): if isinstance(v, EventHandler): if name is None: events[k] = v elif name in v.trait_names: events[k] = v elif hasattr(v, 'tags'): if cls.trait_names(**v.tags): events[k] = v return events ``` -------------------------------- ### gcf Source: https://ipyvolume.readthedocs.io/en/latest/api.html Get current figure, or create a new one. ```python ipyvolume.pylab.gcf() ``` -------------------------------- ### HasDescriptors __new__ Source: https://ipyvolume.readthedocs.io/en/latest/_modules/traitlets/traitlets.html The __new__ method for HasDescriptors, handling instance creation and setup. ```python new_meth = super(HasDescriptors, cls).__new__ if new_meth is object.__new__: inst = new_meth(cls) else: inst = new_meth(cls, *args, **kwargs) inst.setup_instance(*args, **kwargs) return inst ``` -------------------------------- ### Load Iris Dataset with Vaex Source: https://ipyvolume.readthedocs.io/en/latest/examples/popup.html Loads the Iris dataset using vaex.ml. ```python df = vaex.ml.datasets.load_iris() df ``` -------------------------------- ### view Source: https://ipyvolume.readthedocs.io/en/latest/api.html Set camera angles and distance, and return the current view settings. ```python ipyvolume.pylab.view(azimuth=None, elevation=None, distance=None) ``` -------------------------------- ### Default Value Representation Source: https://ipyvolume.readthedocs.io/en/latest/_modules/traitlets/traitlets.html A simple method to get the string representation of the default value. ```python def default_value_repr(self): return repr(self.default_value) ``` -------------------------------- ### Volume visualization Source: https://ipyvolume.readthedocs.io/en/latest/index.html Demonstrates how to visualize a 3D numpy array as a volume using `ipyvolume.widgets.quickvolshow`. ```python import numpy as np import ipyvolume as ipv V = np.zeros((128,128,128)) # our 3d array # outer box V[30:-30,30:-30,30:-35] = 0.75 V[35:-35,35:-35,35:-35] = 0.0 # inner box V[50:-50,50:-50,50:-50] = 0.25 V[55:-55,55:-55,55:-55] = 0.0 ipv.quickvolshow(V, level=[0.25, 0.75], opacity=0.03, level_width=0.1, data_min=0, data_max=1) ``` -------------------------------- ### Deprecated set_metadata Method Source: https://ipyvolume.readthedocs.io/en/latest/_modules/traitlets/traitlets.html Example of the deprecated set_metadata method, showing its usage and the warning it raises. ```python def set_metadata(self, key, value): """DEPRECATED: Set a metadata key/value. Use .metadata[key] = value instead. """ if key == 'help': msg = "use the instance .help string directly, like x.help = value" else: msg = "use the instance .metadata dictionary directly, like x.metadata[key] = value" warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2) self.metadata[key] = value ``` -------------------------------- ### Import necessary libraries Source: https://ipyvolume.readthedocs.io/en/latest/examples/bqplot.html Import numpy and vaex for data manipulation. ```python import numpy as np import vaex ``` -------------------------------- ### Deprecated get_metadata Method Source: https://ipyvolume.readthedocs.io/en/latest/_modules/traitlets/traitlets.html Example of the deprecated get_metadata method, showing its usage and the warning it raises. ```python def get_metadata(self, key, default=None): """DEPRECATED: Get a metadata value. Use .metadata[key] or .metadata.get(key, default) instead. """ if key == 'help': msg = "use the instance .help string directly, like x.help" else: msg = "use the instance .metadata dictionary directly, like x.metadata[key] or x.metadata.get(key, default)" warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2) return self.metadata.get(key, default) ```