Ejemplo n.º 1
0
def test_quick():
    x, y, z = ipyvolume.examples.xyz()
    p3.volshow(x*y*z)
    ipyvolume.quickvolshow(x*y*z, lighting=True)
    ipyvolume.quickvolshow(x*y*z, lighting=True, level=1, opacity=1, level_width=1)


    x, y, z, u, v, w = np.random.random((6, 100))
    ipyvolume.quickscatter(x, y, z)
    ipyvolume.quickquiver(x, y, z, u, v, w)
Ejemplo n.º 2
0
    def init_kelp_vis(self):
        self.kelp_header = ipw.HTML("<b>Kelp</b>")
        with self.log_area:
            self.kelp_controls, self.kelp_figure = ipv.quickvolshow(
                np.zeros([3, 3, 3])
            ).children

            self.kelp_figure.xlabel = 'x'
            self.kelp_figure.xlim = [
                self.kelp.grid.x.minval,
                self.kelp.grid.x.maxval
            ]

            # z-axis is flipped
            self.kelp_figure.ylabel = 'z'
            self.kelp_figure.ylim = [
                self.kelp.grid.z.maxval,
                self.kelp.grid.z.minval
            ]

            self.kelp_figure.zlabel = 'y'
            self.kelp_figure.zlim = [
                self.kelp.grid.y.minval,
                self.kelp.grid.y.maxval
            ]


        self.calculate_kelp_button = ipw.Button(
            description="Calculate Kelp"
        )
        self.load_kelp_button = ipw.Button(
            description="Load Kelp"
        )
Ejemplo n.º 3
0
    def init_elements(self):
        self.log_widget = ipw.Output()

        self.controller, self.fig = ipv.quickvolshow(np.zeros([3,3,3])).children

        self.theta_slider = ipw.IntSlider(
            min=0,
            max=self.ntheta-1,
            description='theta',
            #continuous_update=False
        )

        self.phi_slider = ipw.IntSlider(
            min=0,
            max=self.nphi-1,
            description='phi',
            #continuous_update=False
        )

        self.reset_button = ipw.Button(description='Reset Radiance')
        self.update_button = ipw.Button(description='Update Plots')

        self.heatmap = HeatMapWidget(
            #x=self.light.grid.theta.vals,
            #y=self.light.grid.phi.vals,
            x=np.arange(self.light.grid.theta.num),
            y=np.arange(self.light.grid.phi.num),
            labels=dict(
                x='theta',
                y='phi'
            )
        )

        self.stats = ipw.HTML()
Ejemplo n.º 4
0
    def init_light_vis(self):
        self.light_header = ipw.HTML("<b>Irradiance</b>")
        with self.log_area:
            self.light_controls, self.light_figure = ipv.quickvolshow(
                np.zeros([3, 3, 3])
            ).children

            self.light_figure.xlabel = 'x'
            self.light_figure.xlim = [
                self.light.grid.x.minval,
                self.light.grid.x.maxval
            ]

            # z-axis is flipped
            self.light_figure.ylabel = 'z'
            self.light_figure.ylim = [
                self.light.grid.z.maxval,
                self.light.grid.z.minval
            ]

            self.light_figure.zlabel = 'y'
            self.light_figure.zlim = [
                self.light.grid.y.minval,
                self.light.grid.y.maxval
            ]

        self.calculate_light_button = ipw.Button(
            description='Calculate Light'
        )
        self.load_light_button = ipw.Button(
            description="Load Light"
        )
Ejemplo n.º 5
0
def show_ipv(data: np.ndarray):
    """
    Show a 3d visualization of 3d numpy array
    :param data: The numpy array to show
    :return: The ipyvolume figure
    """
    import ipyvolume as ipv
    return ipv.quickvolshow(data)
Ejemplo n.º 6
0
def volshow(volume):
    """
    Use jupyter notebook to visualize 3d volumes.
    :param volume: 3d numpy array
    :return:
    """
    import scipy.ndimage
    sampled = scipy.ndimage.zoom(volume, 0.3, order=2)

    fig = ipv.quickvolshow(sampled, level=[0.24, 0.29], opacity=[0.09, 0.14])
    ipv.pylab.style.use(axis_off)
    return fig
Ejemplo n.º 7
0
def my_volshow_1channel(volume,
                        view=(0, 0, 0),
                        rotation=(0, 0, 0, 'XYZ'),
                        perspective=None,
                        **kwargs):
    """Customized volume show function, with specified camera position and angle.
    
    Args:
        volume: volume data
        view: camera position
        rotation: camera angle
    """

    ipv.quickvolshow(volume, **kwargs)
    ipv.show()

    # wait for plot to be generated (JavaScript)
    time.sleep(0.6)

    # set camera position and angle
    set_perspective(view=view, rotation=rotation, perspective=perspective)
Ejemplo n.º 8
0
def ball(rmax=3, rmin=0, shape=128, limits=[-4, 4], display=True, **kwargs):
    __, __, __, 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
    if display:
        return ipyvolume.quickvolshow(data=data.T, **kwargs)
    else:
        return data.T
Ejemplo n.º 9
0
def volume(filename=None,
           data=None,
           colormap="viridis",
           nbins=256,
           save=None,
           **kwargs):
    """
    Make a 3D volume rendering using ipyvolume
    """

    try:
        import ipyvolume as ipv
    except ImportError:
        print("Volume rendering makes use of the ipyvolume package which was "
              "not found on this system. Install using pip install ipyvolume.")

    if data is None:
        data = load(filename, ids=True, tofs=True, **kwargs)

    t = np.linspace(0.0, 7.2e4, nbins + 1)
    z, xe, ye = np.histogram2d(
        data.ids,
        data.tofs / 1.0e3,
        bins=[np.arange(-0.5, data.nx * data.ny + 0.5), t])
    z = np.transpose(z.reshape(data.ny, data.nx, nbins), axes=[2, 1, 0])
    ipv.quickvolshow(z,
                     extent=[[data.x[0, 0] * 100.0, data.x[0, -1] * 100.0],
                             [data.y[0, 0] * 100.0, data.y[-1, 0] * 100.0],
                             [t[0], t[-1]]])
    ipv.pylab.xlabel("x [cm]")
    ipv.pylab.ylabel("y [cm]")
    ipv.pylab.zlabel("Tof [us]")
    if save is not None:
        ipv.pylab.save(save)
    else:
        ipv.show()

    return
Ejemplo n.º 10
0
    def show_volume(self, renderer: str = 'itkwidgets', **kwargs) -> None:
        """Show volume using `itkwidgets` or `ipyvolume`.

        Extra keyword arguments (`kwargs`) are passed to
        `itkwidgets.view` or `ipyvolume.quickvolshow`.
        """
        if renderer in ('ipyvolume', 'ipv'):
            import ipyvolume as ipv
            return ipv.quickvolshow(self.image, **kwargs)
        elif renderer in ('itkwidgets', 'itk', 'itkw'):
            import itkwidgets as itkw
            return itkw.view(self.image)
        else:
            raise ValueError(f'No such renderer: {renderer!r}')
Ejemplo n.º 11
0
 def show3d(self, channel=0, controls=False, **kwargs):
     with warnings.catch_warnings():
         warnings.filterwarnings('ignore')
         v = self.v[channel] if len(self.v.shape) > 3 else self.v
         ipv.quickvolshow(v, controls=controls, **kwargs)
         ipv.show()
Ejemplo n.º 12
0
 def display(self):
     return ipv.quickvolshow(self.volume)
Ejemplo n.º 13
0
# -*- coding: utf-8 -*-

from logging import getLogger

import ipyvolume as ipv
from niwidgets import NiftiWidget
import numpy as np

logger = getLogger(__name__)

if __name__ == '__main__':
    ddd = np.random.random((100, 100, 100))
    ipv.quickvolshow(ddd)

    my_widget = NiftiWidget(fname)
    my_widget.nifti_plotter()

    pass
Ejemplo n.º 14
0
from astropy.io import fits

# +
hdu1 = fits.open('../Ratios-for-Alba/ratio-6583-6563.fits')[0]
hdu2 = fits.open('../Ratios-for-Alba/ratio-5007-4861.fits')[0]
hdu3 = fits.open('../Ratios-for-Alba/ratio-9069-6731.fits')[0]
x = hdu1.data.ravel()
y = hdu2.data.ravel() 
z = hdu3.data.ravel()

xyzrange = [0.0, 0.7], [0.0, 5.0], [0, 25]
H, edges = np.histogramdd(np.stack((x, y, z)).T, bins=[150, 150, 150], range=xyzrange)

# + {"scrolled": false}
ipv.quickvolshow(H.T, lighting=True, level=[0.08, 0.2, 0.50], opacity=[0.04, 0.05, 0.10], level_width=0.05)

# +
hdu1 = fits.open('../Ratios-for-Alba/ratio-6583-6563.fits')[0]
hdu2 = fits.open('../Ratios-for-Alba/ratio-5007-4861.fits')[0]
hdu3 = fits.open('../Ratios-for-Alba/ratio-7330-6583.fits')[0]
x = hdu1.data.ravel()
y = hdu2.data.ravel() 
z = hdu3.data.ravel()

xyzrange = [0.0, 0.7], [0.0, 5.0], [0, 0.2]
H, edges = np.histogramdd(np.stack((x, y, z)).T, bins=[150, 150, 150], range=xyzrange)
# -

ipv.quickvolshow(H.T, lighting=True, level=[0.08, 0.2, 0.50], opacity=[0.04, 0.05, 0.10], level_width=0.05)
Ejemplo n.º 15
0
 def volume_plot(self):
     "Transform so that the new y is the old -z for IPyVolume."
     return ipv.quickvolshow(np.swapaxes(self.irradiance[:, :, ::-1], 1, 2))
Ejemplo n.º 16
0
Archivo: model.py Proyecto: SKIRT/PTS
def plot_galaxy_components(components, draw=True, show=True, shape=128, unit="pc", width=700, height=800, style='light', **kwargs):

    """
    This function ....
    :param components:
    :param draw:
    :param show:
    :param shape:
    :param unit:
    :param width:
    :param height:
    :param style:
    :param kwargs:
    :return:
    """

    # Determine the limits
    limits = determine_model_limits(components, unit, symmetric=True)

    # Debugging
    log.debug("Plot limits: " + str(limits))

    # Create coordinate data
    x, y, z, r, theta, phi = xyz(shape=shape, limits=limits, spherical=True)
    data = r * 0

    # Loop over the components
    for name in components:

        # Debugging
        log.debug("Computing the density of the " + name + " component ...")

        component = components[name]
        density = component.density_function(normalize=True)(x, y, z)
        data += density

    # DRAW FIGURE
    if draw:

        # :param lighting: boolean, to use lighting or not, if set to false, lighting parameters will be overriden
        # :param data_min: minimum value to consider for data, if None, computed using np.nanmin
        # :param data_max: maximum value to consider for data, if None, computed using np.nanmax
        # :param tf: transfer function (see ipyvolume.transfer_function, or use the argument below)
        # :param stereo: stereo view for virtual reality (cardboard and similar VR head mount)
        # :param width: width of rendering surface
        # :param height: height of rendering surface
        # :param ambient_coefficient: lighting parameter
        # :param diffuse_coefficient: lighting parameter
        # :param specular_coefficient: lighting parameter
        # :param specular_exponent: lighting parameter
        # :param downscale: downscale the rendering for better performance, for instance when set to 2, a 512x512 canvas will show a 256x256 rendering upscaled, but it will render twice as fast.
        # :param level: level(s) for the where the opacity in the volume peaks, maximum sequence of length 3
        # :param opacity: opacity(ies) for each level, scalar or sequence of max length 3
        # :param level_width: width of the (gaussian) bumps where the opacity peaks, scalar or sequence of max length 3
        # :param kwargs: extra argument passed to Volume and default transfer function

        # DEFAULT:

        # lighting=False, data_min=None, data_max=None, tf=None, stereo=False,
        # width=400, height=500,
        # ambient_coefficient=0.5, diffuse_coefficient=0.8,
        # specular_coefficient=0.5, specular_exponent=5,
        # downscale=1,
        # level=[0.1, 0.5, 0.9], opacity=[0.01, 0.05, 0.1], level_width=0.1,

        level = [0.2]
        #opacity = [0.05, 0.0, 0.0]
        opacity = [0.08, 0.0, 0.0]
        level_width = 0.2
        level_width = [level_width] * 3

        kwargs = dict()
        kwargs["width"] = width
        kwargs["height"] = height
        kwargs["stereo"] = False
        kwargs["level"] = level
        kwargs["opacity"] = opacity
        kwargs["level_width"] = level_width
        kwargs["downscale"] = 1

        # Create transfer function arguments
        tf_kwargs = {}

        # Clip off lists
        min_length = min(len(level), len(level_width), len(opacity))
        level = list(level[:min_length])
        opacity = list(opacity[:min_length])
        level_width = list(level_width[:min_length])
        # append with zeros
        while len(level) < 3:
            level.append(0)
        while len(opacity) < 3:
            opacity.append(0)
        while len(level_width) < 3:
            level_width.append(0)
        for i in range(1,4):
            tf_kwargs["level"+str(i)] = level[i-1]
            tf_kwargs["opacity"+str(i)] = opacity[i-1]
            tf_kwargs["width"+str(i)] = level_width[i-1]
        tf = TransferFunctionWidgetJs3(**tf_kwargs)

        # Set the transfer function
        kwargs["tf"] = tf

        # Set style
        if style == "dark": kwargs["style"] = dark
        elif style == "light": kwargs["style"] = light
        elif style == "minimal": kwargs["style"] = minimal
        else: raise ValueError("Invalid style: " + style)

        # Create the volume plot
        vol = ipyvolume.quickvolshow(data=data.T, **kwargs)
        #vol = p3.volshow(data=data, **kwargs)

        # SHOW?
        if show:
            #p3.volshow()
            vol.show()
        return vol

    # ONLY RETURN THE DATA
    else: return data
Ejemplo n.º 17
0
Archivo: model.py Proyecto: rag9704/PTS
def plot_galaxy_components(components,
                           draw=True,
                           show=True,
                           shape=128,
                           unit="pc",
                           width=700,
                           height=800,
                           style='light',
                           **kwargs):
    """
    This function ....
    :param components:
    :param draw:
    :param show:
    :param shape:
    :param unit:
    :param width:
    :param height:
    :param style:
    :param kwargs:
    :return:
    """

    # Determine the limits
    limits = determine_model_limits(components, unit, symmetric=True)

    # Debugging
    log.debug("Plot limits: " + str(limits))

    # Create coordinate data
    x, y, z, r, theta, phi = xyz(shape=shape, limits=limits, spherical=True)
    data = r * 0

    # Loop over the components
    for name in components:

        # Debugging
        log.debug("Computing the density of the " + name + " component ...")

        component = components[name]
        density = component.density_function(normalize=True)(x, y, z)
        data += density

    # DRAW FIGURE
    if draw:

        # :param lighting: boolean, to use lighting or not, if set to false, lighting parameters will be overriden
        # :param data_min: minimum value to consider for data, if None, computed using np.nanmin
        # :param data_max: maximum value to consider for data, if None, computed using np.nanmax
        # :param tf: transfer function (see ipyvolume.transfer_function, or use the argument below)
        # :param stereo: stereo view for virtual reality (cardboard and similar VR head mount)
        # :param width: width of rendering surface
        # :param height: height of rendering surface
        # :param ambient_coefficient: lighting parameter
        # :param diffuse_coefficient: lighting parameter
        # :param specular_coefficient: lighting parameter
        # :param specular_exponent: lighting parameter
        # :param downscale: downscale the rendering for better performance, for instance when set to 2, a 512x512 canvas will show a 256x256 rendering upscaled, but it will render twice as fast.
        # :param level: level(s) for the where the opacity in the volume peaks, maximum sequence of length 3
        # :param opacity: opacity(ies) for each level, scalar or sequence of max length 3
        # :param level_width: width of the (gaussian) bumps where the opacity peaks, scalar or sequence of max length 3
        # :param kwargs: extra argument passed to Volume and default transfer function

        # DEFAULT:

        # lighting=False, data_min=None, data_max=None, tf=None, stereo=False,
        # width=400, height=500,
        # ambient_coefficient=0.5, diffuse_coefficient=0.8,
        # specular_coefficient=0.5, specular_exponent=5,
        # downscale=1,
        # level=[0.1, 0.5, 0.9], opacity=[0.01, 0.05, 0.1], level_width=0.1,

        level = [0.2]
        #opacity = [0.05, 0.0, 0.0]
        opacity = [0.08, 0.0, 0.0]
        level_width = 0.2
        level_width = [level_width] * 3

        kwargs = dict()
        kwargs["width"] = width
        kwargs["height"] = height
        kwargs["stereo"] = False
        kwargs["level"] = level
        kwargs["opacity"] = opacity
        kwargs["level_width"] = level_width
        kwargs["downscale"] = 1

        # Create transfer function arguments
        tf_kwargs = {}

        # Clip off lists
        min_length = min(len(level), len(level_width), len(opacity))
        level = list(level[:min_length])
        opacity = list(opacity[:min_length])
        level_width = list(level_width[:min_length])
        # append with zeros
        while len(level) < 3:
            level.append(0)
        while len(opacity) < 3:
            opacity.append(0)
        while len(level_width) < 3:
            level_width.append(0)
        for i in range(1, 4):
            tf_kwargs["level" + str(i)] = level[i - 1]
            tf_kwargs["opacity" + str(i)] = opacity[i - 1]
            tf_kwargs["width" + str(i)] = level_width[i - 1]
        tf = TransferFunctionWidgetJs3(**tf_kwargs)

        # Set the transfer function
        kwargs["tf"] = tf

        # Set style
        if style == "dark": kwargs["style"] = dark
        elif style == "light": kwargs["style"] = light
        elif style == "minimal": kwargs["style"] = minimal
        else: raise ValueError("Invalid style: " + style)

        # Create the volume plot
        vol = ipyvolume.quickvolshow(data=data.T, **kwargs)
        #vol = p3.volshow(data=data, **kwargs)

        # SHOW?
        if show:
            #p3.volshow()
            vol.show()
        return vol

    # ONLY RETURN THE DATA
    else:
        return data
Ejemplo n.º 18
0
 def show3d(self, channel=0, controls=False, **kwargs):
     v = self.v[channel] if len(self.v.shape) > 3 else self.v
     ipv.quickvolshow(v, controls=controls, **kwargs)
     ipv.show()