コード例 #1
0
class BoxAnnotation(SceneAnnotation):
    name = "box_outline"
    data = traitlets.Instance(BoxData)
    box_width = traitlets.CFloat(0.05)
    box_color = traitlets.Tuple(
        traitlets.CFloat(),
        traitlets.CFloat(),
        traitlets.CFloat(),
        default_value=(1.0, 1.0, 1.0),
    )
    box_alpha = traitlets.CFloat(1.0)

    def draw(self, scene, program):
        each = self.data.vertex_array.each
        GL.glDrawArrays(GL.GL_TRIANGLES, 0, each)

    def render_gui(self, imgui, renderer, scene):
        changed = super(BoxAnnotation, self).render_gui(imgui, renderer, scene)
        _, bw = imgui.slider_float("Width", self.box_width, 0.001, 0.250)
        if _:
            self.box_width = bw
        changed = changed or _
        _, ba = imgui.slider_float("Alpha", self.box_alpha, 0.0, 1.0)
        if _:
            self.box_alpha = ba
        changed = changed or _
        return changed

    def _set_uniforms(self, scene, shader_program):
        shader_program._set_uniform("box_width", self.box_width)
        shader_program._set_uniform("box_alpha", self.box_alpha)
        shader_program._set_uniform("box_color", np.array(self.box_color))
コード例 #2
0
class AnimationWidget(widgets.DOMWidget):
    """
    A widget that periodic increment a value

    :param value: A float between 0 and 1
    :param run: boolean with the state of the timer. True, the timer is enable

    Produces the following signal. A sampling rate, the value is interpolated
    with the equation val = 1/Period * t
    1- ^  ____
       | /
       |/
    0- |----->
          |
        period 
    """
    _view_name = traitlets.Unicode('AnimationView').tag(sync=True)
    _model_name = traitlets.Unicode('AnimationModel').tag(sync=True)
    _view_module = traitlets.Unicode('animation-widget').tag(sync=True)
    _model_module = traitlets.Unicode('animation-widget').tag(sync=True)
    # Signal value
    value = traitlets.CFloat(0.0).tag(sync=True)
    # Boolean timer is active
    run = traitlets.CBool(False).tag(sync=True)
    # Signal period (in ms)
    period = traitlets.CFloat(5000).tag(sync=True)
    # Number of samples in period
    nbsamples = traitlets.CInt(100).tag(sync=True)
    # Loop
    loop = traitlets.CBool(False).tag(sync=True)
コード例 #3
0
class OrthographicRayBlaster(RayBlaster):
    center = traittypes.Array().valid(check_dtype("f4"), check_shape(3))
    forward = traittypes.Array().valid(check_dtype("f4"), check_shape(3))
    up = traittypes.Array().valid(check_dtype("f4"), check_shape(3))
    east = traittypes.Array().valid(check_dtype("f4"), check_shape(3))
    width = traitlets.CFloat(1.0)
    height = traitlets.CFloat(1.0)
    nx = traitlets.CInt(512)
    ny = traitlets.CInt(512)

    @traitlets.default("east")
    def _default_east(self):
        return np.cross(self.forward, self.up)

    def __init__(self, *args, **kwargs):
        super(OrthographicRayBlaster, self).__init__(*args, **kwargs)

        # here origin is not the center, but the bottom left
        self._directions = np.zeros((self.nx, self.ny, 3), dtype="f4")
        self._directions[:] = self.forward[None, None, :]
        self.directions = self._directions.view().reshape(
            (self.nx * self.ny, 3))

        self._origins = np.zeros((self.nx, self.ny, 3), dtype="f4")
        offset_x, offset_y = np.mgrid[-self.width / 2:self.width / 2:self.nx *
                                      1j, -self.height / 2:self.height /
                                      2:self.ny * 1j, ]
        self._origins[:] = (self.center + offset_x[..., None] * self.east +
                            offset_y[..., None] * self.up)
        self.origins = self._origins.view().reshape((self.nx * self.ny, 3))
コード例 #4
0
ファイル: scale.py プロジェクト: rjrajivjha/altair_scale
class BandScale(DiscreteScale):

    type = T.Unicode('band')
    align = T.CFloat()
    padding = T.Float()
    paddingInner = T.CFloat()
    paddingOuter = T.CFloat()
コード例 #5
0
class VizHistogramState(VizBaseState):
    x_expression = traitlets.Unicode()
    x_slice = traitlets.CInt(None, allow_none=True)
    type = traitlets.CaselessStrEnum(['count', 'min', 'max', 'mean'], default_value='count')
    aux = traitlets.Unicode(None, allow_none=True)
    groupby = traitlets.Unicode(None, allow_none=True)
    groupby_normalize = traitlets.Bool(False, allow_none=True)
    x_min = traitlets.CFloat(None, allow_none=True)
    x_max = traitlets.CFloat(None, allow_none=True)
    grid = traitlets.Any().tag(**serialize_numpy)
    grid_sliced = traitlets.Any().tag(**serialize_numpy)
    x_centers = traitlets.Any().tag(**serialize_numpy)
    x_shape = traitlets.CInt(None, allow_none=True)
    #centers = traitlets.Any()
    
    def __init__(self, ds, **kwargs):
        super(VizHistogramState, self).__init__(ds, **kwargs)
        self.observe(lambda x: self.signal_slice.emit(self), ['x_slice'])
        self.observe(lambda x: self.calculate_limits(), ['x_expression', 'type', 'aux'])
        # no need for recompute
        # self.observe(lambda x: self.calculate_grid(), ['groupby', 'shape', 'groupby_normalize'])
        # self.observe(lambda x: self.calculate_grid(), ['groupby', 'shape', 'groupby_normalize'])
        
        self.observe(lambda x: self._update_grid(), ['x_min', 'x_max', 'shape'])
        if self.x_min is None and self.x_max is None:
            self.calculate_limits()
        else:
            self._calculate_centers()

    def bin_parameters(self):
        yield self.x_expression, self.x_shape or self.shape, (self.x_min, self.x_max), self.x_slice

    def state_get(self):
        #         return {name: self.trait_metadata('grid', 'serialize', ident)(getattr(self, name) for name in self.trait_names()}
        state = {}
        for name in self.trait_names():
            serializer = self.trait_metadata(name, 'serialize', ident)
            value = serializer(getattr(self, name))
            state[name] = value
        return state

    def state_set(self, state):
        for name in self.trait_names():
            if name in state:
                deserializer = self.trait_metadata(name, 'deserialize', ident)
                value = deserializer(state[name])
                setattr(self, name, value)
                                                                      
    def calculate_limits(self):
        self._calculate_limits('x', 'x_expression')
        self.signal_regrid.emit(None) # TODO this is also called in the ctor, unnec work
    
    def limits_changed(self, change):
        self.signal_regrid.emit(None) # TODO this is also called in the ctor, unnec work

    @vaex.jupyter.debounced()
    def _update_grid(self):
        self._calculate_centers()
        self.signal_regrid.emit(None)
コード例 #6
0
class BackendBase(widgets.Widget):
    dim = 2
    limits = traitlets.List(traitlets.Tuple(traitlets.CFloat(), traitlets.CFloat()))

    @staticmethod
    def wants_colors():
        return True

    def update_vectors(self, vcount, vgrids, vcount_limits):
        pass
コード例 #7
0
ファイル: transferfunction.py プロジェクト: zlinzju/ipyvolume
class TransferFunctionJsBumps(TransferFunction):
    _model_name = Unicode('TransferFunctionJsBumpsModel').tag(sync=True)
    _model_module = Unicode('ipyvolume').tag(sync=True)
    levels = traitlets.List(traitlets.CFloat(),
                            default_value=[0.1, 0.5, 0.8]).tag(sync=True)
    opacities = traitlets.List(traitlets.CFloat(),
                               default_value=[0.01, 0.05, 0.1]).tag(sync=True)
    widths = traitlets.List(traitlets.CFloat(),
                            default_value=[0.1, 0.1, 0.1]).tag(sync=True)

    def control(self, max_opacity=0.2):
        return widgets.VBox()
コード例 #8
0
ファイル: idobject.py プロジェクト: chrisjsewell/pandas3js
class Icosahedron(GeometricObject):
    """ a spherical object

    Examples
    --------
    
    >>> object = Circle()
    >>> object.position
    (0.0, 0.0, 0.0)

    """
    radius = trait.CFloat(1).tag(sync=True)
    detail = trait.CFloat(0).tag(sync=True)
コード例 #9
0
ファイル: idobject.py プロジェクト: chrisjsewell/pandas3js
class Circle(GeometricObject):
    """ a spherical object

    Examples
    --------
    
    >>> object = Circle()
    >>> object.position
    (0.0, 0.0, 0.0)

    """
    radius = trait.CFloat(1).tag(sync=True)
    segments = trait.CFloat(36).tag(sync=True)
コード例 #10
0
ファイル: idobject.py プロジェクト: chrisjsewell/pandas3js
class Box(GeometricObject):
    """ a spherical object

    Examples
    --------
    
    >>> object = Box()
    >>> object.position
    (0.0, 0.0, 0.0)

    """
    width = trait.CFloat(1).tag(sync=True)
    height = trait.CFloat(1).tag(sync=True)
    depth = trait.CFloat(1).tag(sync=True)
コード例 #11
0
ファイル: volume.py プロジェクト: ubaidsayyed54/ipyvolume
class VolumeRendererThree(widgets.DOMWidget):
    """Widget class representing a volume (rendering) using three.js"""
    _view_name = Unicode('VolumeRendererThreeView').tag(sync=True)
    _view_module = Unicode('ipyvolume').tag(sync=True)
    _model_name = Unicode('VolumeRendererThreeModel').tag(sync=True)
    _model_module = Unicode('ipyvolume').tag(sync=True)

    data = Array(default_value=None,
                 allow_none=True).tag(sync=True,
                                      **array_cube_png_serialization)
    data_min = traitlets.CFloat().tag(sync=True)
    data_max = traitlets.CFloat().tag(sync=True)
    tf = traitlets.Instance(TransferFunction, allow_none=True).tag(
        sync=True, **ipywidgets.widget_serialization)
    angle1 = traitlets.Float(0.1).tag(sync=True)
    angle2 = traitlets.Float(0.2).tag(sync=True)

    scatters = traitlets.List(traitlets.Instance(Scatter), [],
                              allow_none=False).tag(
                                  sync=True, **ipywidgets.widget_serialization)

    animation = traitlets.Float(1000.0).tag(sync=True)

    ambient_coefficient = traitlets.Float(0.5).tag(sync=True)
    diffuse_coefficient = traitlets.Float(0.8).tag(sync=True)
    specular_coefficient = traitlets.Float(0.5).tag(sync=True)
    specular_exponent = traitlets.Float(5).tag(sync=True)
    stereo = traitlets.Bool(False).tag(sync=True)
    fullscreen = traitlets.Bool(False).tag(sync=True)

    width = traitlets.CInt(500).tag(sync=True)
    height = traitlets.CInt(400).tag(sync=True)
    downscale = traitlets.CInt(1).tag(sync=True)
    show = traitlets.Unicode("Volume").tag(sync=True)  # for debugging

    xlim = traitlets.List(traitlets.CFloat,
                          default_value=[0, 1],
                          minlen=2,
                          maxlen=2).tag(sync=True)
    ylim = traitlets.List(traitlets.CFloat,
                          default_value=[0, 1],
                          minlen=2,
                          maxlen=2).tag(sync=True)
    zlim = traitlets.List(traitlets.CFloat,
                          default_value=[0, 1],
                          minlen=2,
                          maxlen=2).tag(sync=True)

    style = traitlets.Dict(default_value=default_style).tag(sync=True)
コード例 #12
0
class FieldDef(BaseObject):
    """Wrapper for Vega-Lite FieldDef definition.
    
    Attributes
    ----------
    aggregate: AggregateOp
        Aggregation function for the field .
    bin: Union(Bool, Bin)
        Flag for binning a `quantitative` field, or a bin property object for binning parameters.
    field: Unicode
        Name of the field from which to pull a data value.
    timeUnit: TimeUnit
        Time unit for a `temporal` field .
    title: Unicode
        Title for axis or legend.
    type: Type
        The encoded field's type of measurement.
    value: Union(CFloat, Unicode, Bool)
        A constant value in visual domain.
    """
    aggregate = AggregateOp(allow_none=True, default_value=None, help="""Aggregation function for the field .""")
    bin = T.Union([T.Bool(allow_none=True, default_value=None), T.Instance(Bin, allow_none=True, default_value=None)])
    field = T.Unicode(allow_none=True, default_value=None, help="""Name of the field from which to pull a data value.""")
    timeUnit = TimeUnit(allow_none=True, default_value=None, help="""Time unit for a `temporal` field .""")
    title = T.Unicode(allow_none=True, default_value=None, help="""Title for axis or legend.""")
    type = Type(allow_none=True, default_value=None, help="""The encoded field's type of measurement.""")
    value = T.Union([T.CFloat(allow_none=True, default_value=None), T.Unicode(allow_none=True, default_value=None), T.Bool(allow_none=True, default_value=None)])
    
    def __init__(self, aggregate=None, bin=None, field=None, timeUnit=None, title=None, type=None, value=None, **kwargs):
        kwds = dict(aggregate=aggregate, bin=bin, field=field, timeUnit=timeUnit, title=title, type=type, value=value)
        kwargs.update({k:v for k, v in kwds.items() if v is not None})
        super(FieldDef, self).__init__(**kwargs)
コード例 #13
0
ファイル: tilesource.py プロジェクト: asford/tilesource
class DirectTile(StrictHasTraits, object):
    name = traitlets.Bytes()
    urltemplate = traitlets.Bytes()
    opacity = traitlets.CFloat(max=1.0, min=0.0, default_value=1.0)

    @property
    def storage_key(self):
        return self.name

    @ndb.tasklet
    def render_async(self, tile):
        tile_url = self.urltemplate.format(**tile)
        context = ndb.get_context()
        result = yield context.urlfetch(tile_url)
        if result.status_code != 200:
            logging.error("error fetching: %r result: %s", tile_url, result)
            raise ValueError("error fetching: %r result: %s" %
                             (tile_url, result))

        raise ndb.Return(
            Image.open(io.BytesIO(result.content)).convert("RGBA"))

    def render(self, tile):
        tile_url = self.urltemplate.format(**tile)
        result = requests.get(tile_url)
        if result.status_code != 200:
            logging.error("error fetching: %r result: %s", tile_url, result)
            raise ValueError("error fetching: %r result: %s" %
                             (tile_url, result))

        return Image.open(io.BytesIO(result.content)).convert("RGBA")
コード例 #14
0
class OneOfFilter(BaseObject):
    """Wrapper for Vega-Lite OneOfFilter definition.
    
    Attributes
    ----------
    field: Unicode
        Field to be filtered.
    oneOf: List(Union(Unicode, CFloat, Bool, DateTime))
        A set of values that the `field`'s value should be a member of, for a data item included in the filtered data.
    timeUnit: TimeUnit
        time unit for the field to be filtered.
    """
    field = T.Unicode(allow_none=True,
                      default_value=None,
                      help="""Field to be filtered.""")
    oneOf = T.List(
        T.Union([
            T.Unicode(allow_none=True, default_value=None),
            T.CFloat(allow_none=True, default_value=None),
            T.Bool(allow_none=True, default_value=None),
            T.Instance(DateTime, allow_none=True, default_value=None)
        ]),
        allow_none=True,
        default_value=None,
        help=
        """A set of values that the `field`'s value should be a member of, for a data item included in the filtered data."""
    )
    timeUnit = TimeUnit(allow_none=True,
                        default_value=None,
                        help="""time unit for the field to be filtered.""")

    def __init__(self, field=None, oneOf=None, timeUnit=None, **kwargs):
        kwds = dict(field=field, oneOf=oneOf, timeUnit=timeUnit)
        kwargs.update({k: v for k, v in kwds.items() if v is not None})
        super(OneOfFilter, self).__init__(**kwargs)
コード例 #15
0
class SceneData(traitlets.HasTraits):
    """A class that defines a collection of GPU-managed data.

    This class contains the largest common set of features that can be used
    OpenGL rendering: a set of vertices and a set of vertex attributes.  Note
    that this is distinct from the shader, which can be swapped out and
    provided with these items.

    """

    name = traitlets.Unicode()
    vertex_array = traitlets.Instance(VertexArray)
    textures = traitlets.List(trait=traitlets.Instance(Texture))

    min_val = traitlets.CFloat(0.0)
    max_val = traitlets.CFloat(1.0)
コード例 #16
0
ファイル: rangefilter.py プロジェクト: yush3n9/altair
class RangeFilter(BaseObject):
    """Wrapper for Vega-Lite RangeFilter definition.
    
    Attributes
    ----------
    field: Unicode
        Field to be filtered.
    range: List(Union(CFloat, DateTime))
        Array of inclusive minimum and maximum values for a field value of a data item to be included in the filtered data.
    timeUnit: TimeUnit
        time unit for the field to be filtered.
    """
    field = T.Unicode(allow_none=True,
                      default_value=None,
                      help="""Field to be filtered.""")
    range = T.List(
        T.Union([
            T.CFloat(allow_none=True, default_value=None),
            T.Instance(DateTime, allow_none=True, default_value=None)
        ]),
        allow_none=True,
        default_value=None,
        maxlen=2,
        minlen=2,
        help=
        """Array of inclusive minimum and maximum values for a field value of a data item to be included in the filtered data."""
    )
    timeUnit = TimeUnit(allow_none=True,
                        default_value=None,
                        help="""time unit for the field to be filtered.""")

    def __init__(self, field=None, range=None, timeUnit=None, **kwargs):
        kwds = dict(field=field, range=range, timeUnit=timeUnit)
        kwargs.update({k: v for k, v in kwds.items() if v is not None})
        super(RangeFilter, self).__init__(**kwargs)
コード例 #17
0
class LonLatInput(widgets.Text):
    """
    Input for entering lon, lat as comma-separated string

    Link to ``model``, not ``value``! ``model`` is the 2-list of floats,
    ``value`` is the displayed string value.

    Use ``model_is_latlon`` to reverse the order between the ``model`` and the ``value``.
    """

    model = traitlets.List(traitlets.CFloat(),
                           default_value=(0.0, 0.0),
                           minlen=2,
                           maxlen=2)
    model_is_latlon = traitlets.Bool(False)
    description = traitlets.Unicode("Lat, lon (WGS84):").tag(sync=True)
    continuous_update = traitlets.Bool(False).tag(sync=True)

    @traitlets.observe("value")
    def _sync_view_to_model(self, change):
        new = change["new"]
        values = [part.strip() for part in new.split(",")]
        if self.model_is_latlon:
            values.reverse()
        self.model = values

    @traitlets.observe("model")
    def _sync_model_to_view(self, change):
        new = change["new"]
        string = "{:.4f}, {:.4f}".format(
            # https://xkcd.com/2170/
            *(reversed(new) if self.model_is_latlon else new))
        self.value = string
コード例 #18
0
ファイル: idobject.py プロジェクト: chrisjsewell/pandas3js
class Gimbal(GeometricObject):
    """ a gimbal object pointing to basis vectors
    
    default: a red, b green, c orange, 

    Examples
    --------
    
    >>> gimbal = Gimbal()
    >>> gimbal.position
    (0.0, 0.0, 0.0)
    >>> gimbal.a
    (1.0, 0.0, 0.0)
    >>> gimbal.a_color
    'red'

    >>> try:
    ...     gimbal.linewidth = ''
    ... except:
    ...     print('not valid')
    not valid
        
    """
    a = Vector3(default_value=(1, 0, 0), help='vector a').tag(sync=True)
    b = Vector3(default_value=(0, 1, 0), help='vector b').tag(sync=True)
    c = Vector3(default_value=(0, 0, 1), help='vector c').tag(sync=True)
    a_color = Color('red').tag(sync=True)
    b_color = Color('green').tag(sync=True)
    c_color = Color('orange').tag(sync=True)
    linewidth = trait.CFloat(1, min=0.0).tag(sync=True)
コード例 #19
0
class ImageOutput(Output):
    """Output an image in RAM

    Attributes
    ----------
    format : TYPE
        Description
    image : TYPE
        Description
    vmax : TYPE
        Description
    vmin : TYPE
        Description
    """

    format = tl.CaselessStrEnum(values=['png'],
                                default_value='png').tag(attr=True)
    mode = tl.Unicode(default_value="image").tag(attr=True)
    vmin = tl.CFloat(allow_none=True, default_value=np.nan).tag(attr=True)
    vmax = tl.CFloat(allow_none=True, default_value=np.nan).tag(attr=True)
    image = tl.Bytes(allow_none=True, default_value=None)

    def __init__(self,
                 node,
                 name,
                 format=None,
                 mode=None,
                 vmin=None,
                 vmax=None):
        kwargs = {}
        if format is not None:
            kwargs['format'] = format
        if mode is not None:
            kwargs['mode'] = mode
        if vmin is not None:
            kwargs['vmin'] = vmin
        if vmax is not None:
            kwargs['vmax'] = vmax

        super(ImageOutput, self).__init__(node=node, name=name, **kwargs)

    # TODO: docstring?
    def write(self, output, coordinates):
        self.image = get_image(output,
                               format=self.format,
                               vmin=self.vmin,
                               vmax=self.vmax)
コード例 #20
0
ファイル: transferfunction.py プロジェクト: wolfv/ipyvolume
class TransferFunctionJsBumps(TransferFunction):
    _model_name = Unicode('TransferFunctionJsBumpsModel').tag(sync=True)
    _model_module = Unicode('ipyvolume').tag(sync=True)
    levels = traitlets.List(traitlets.CFloat(),
                            default_value=[0.1, 0.5, 0.8]).tag(sync=True)
    opacities = traitlets.List(traitlets.CFloat(),
                               default_value=[0.01, 0.05, 0.1]).tag(sync=True)
    widths = traitlets.List(traitlets.CFloat(),
                            default_value=[0.1, 0.1, 0.1]).tag(sync=True)

    def control(self, max_opacity=0.2):
        return ipywidgets.VBox()
        l1 = ipywidgets.FloatSlider(min=0,
                                    max=1,
                                    step=0.001,
                                    value=self.level1)
        l2 = ipywidgets.FloatSlider(min=0,
                                    max=1,
                                    step=0.001,
                                    value=self.level2)
        l3 = ipywidgets.FloatSlider(min=0,
                                    max=1,
                                    step=0.001,
                                    value=self.level3)
        o1 = ipywidgets.FloatSlider(min=0,
                                    max=max_opacity,
                                    step=0.001,
                                    value=self.opacity1)
        o2 = ipywidgets.FloatSlider(min=0,
                                    max=max_opacity,
                                    step=0.001,
                                    value=self.opacity2)
        o3 = ipywidgets.FloatSlider(min=0,
                                    max=max_opacity,
                                    step=0.001,
                                    value=self.opacity2)
        ipywidgets.jslink((self, 'level1'), (l1, 'value'))
        ipywidgets.jslink((self, 'level2'), (l2, 'value'))
        ipywidgets.jslink((self, 'level3'), (l3, 'value'))
        ipywidgets.jslink((self, 'opacity1'), (o1, 'value'))
        ipywidgets.jslink((self, 'opacity2'), (o2, 'value'))
        ipywidgets.jslink((self, 'opacity3'), (o3, 'value'))
        return ipywidgets.VBox([
            ipywidgets.HBox([ipywidgets.Label(value="levels:"), l1, l2, l3]),
            ipywidgets.HBox([ipywidgets.Label(value="opacities:"), o1, o2, o3])
        ])
コード例 #21
0
ファイル: volume.py プロジェクト: silky/ipyvolume
class Figure(widgets.DOMWidget):
    """Widget class representing a volume (rendering) using three.js"""
    _view_name = Unicode('FigureView').tag(sync=True)
    _view_module = Unicode('ipyvolume').tag(sync=True)
    _model_name = Unicode('FigureModel').tag(sync=True)
    _model_module = Unicode('ipyvolume').tag(sync=True)

    volume_data = Array(default_value=None, allow_none=True).tag(sync=True, **create_array_cube_png_serialization('volume_data'))
    data_min = traitlets.CFloat().tag(sync=True)
    data_max = traitlets.CFloat().tag(sync=True)
    tf = traitlets.Instance(TransferFunction, allow_none=True).tag(sync=True, **ipywidgets.widget_serialization)
    angle1 = traitlets.Float(0.1).tag(sync=True)
    angle2 = traitlets.Float(0.2).tag(sync=True)

    scatters = traitlets.List(traitlets.Instance(Scatter), [], allow_none=False).tag(sync=True, **ipywidgets.widget_serialization)

    animation = traitlets.Float(1000.0).tag(sync=True)
    animation_exponent = traitlets.Float(.5).tag(sync=True)

    ambient_coefficient = traitlets.Float(0.5).tag(sync=True)
    diffuse_coefficient = traitlets.Float(0.8).tag(sync=True)
    specular_coefficient = traitlets.Float(0.5).tag(sync=True)
    specular_exponent = traitlets.Float(5).tag(sync=True)
    stereo = traitlets.Bool(False).tag(sync=True)
    screen_capture_enabled = traitlets.Bool(False).tag(sync=True)
    screen_capture_mime_type = traitlets.Unicode(default_value='image/png').tag(sync=True)
    screen_capture_data = traitlets.Unicode(default_value=None, allow_none=True).tag(sync=True)
    fullscreen = traitlets.Bool(False).tag(sync=True)

    camera_control = traitlets.Unicode(default_value='trackball').tag(sync=True)

    width = traitlets.CInt(500).tag(sync=True)
    height = traitlets.CInt(400).tag(sync=True)
    downscale = traitlets.CInt(1).tag(sync=True)
    show = traitlets.Unicode("Volume").tag(sync=True) # for debugging

    xlim = traitlets.List(traitlets.CFloat, default_value=[0, 1], minlen=2, maxlen=2).tag(sync=True)
    ylim = traitlets.List(traitlets.CFloat, default_value=[0, 1], minlen=2, maxlen=2).tag(sync=True)
    zlim = traitlets.List(traitlets.CFloat, default_value=[0, 1], minlen=2, maxlen=2).tag(sync=True)

    xlabel = traitlets.Unicode("x").tag(sync=True)
    ylabel = traitlets.Unicode("y").tag(sync=True)
    zlabel = traitlets.Unicode("z").tag(sync=True)

    style = traitlets.Dict(default_value=ipyvolume.style.default).tag(sync=True)
コード例 #22
0
class MaxAbsScaler(Transformer):
    ''' Scale features by their maximum absolute value.

    Example:

    >>> import vaex
    >>> df = vaex.from_arrays(x=[2,5,7,2,15], y=[-2,3,0,0,10])
    >>> df
     #    x    y
     0    2   -2
     1    5    3
     2    7    0
     3    2    0
     4   15   10
    >>> scaler = vaex.ml.MaxAbsScaler(features=['x', 'y'])
    >>> scaler.fit_transform(df)
     #    x    y    absmax_scaled_x    absmax_scaled_y
     0    2   -2           0.133333               -0.2
     1    5    3           0.333333                0.3
     2    7    0           0.466667                0
     3    2    0           0.133333                0
     4   15   10           1                       1
    '''
    prefix = traitlets.Unicode(default_value="absmax_scaled_",
                               help=help_prefix).tag(ui='Text')
    absmax_ = traitlets.List(
        traitlets.CFloat(),
        help='Tha maximum absolute value of a feature.').tag(output=True)

    def fit(self, df):
        '''
        Fit MinMaxScaler to the DataFrame.

        :param df: A vaex DataFrame.
        '''

        absmax = df.max(['abs(%s)' % k for k in self.features]).tolist()
        # Check if the absmax_ value is 0, in which case replace with 1
        self.absmax_ = [value if value != 0 else 1 for value in absmax]

    def transform(self, df):
        '''
        Transform a DataFrame with a fitted MaxAbsScaler.

        :param df: A vaex DataFrame.

        :return copy: a shallow copy of the DataFrame that includes the scaled features.
        :rtype: DataFrame
        '''

        copy = df.copy()
        for i, feature in enumerate(self.features):
            name = self.prefix + feature
            expr = copy[feature]
            expr = expr / self.absmax_[i]
            copy[name] = expr
        return copy
コード例 #23
0
ファイル: api.py プロジェクト: mindis/altair
class FacetCoordinate(Shelf):
    # TODO: supported types for aggregate
    # TODO: min and max for padding
    # TODO: min for height

    aggregate = T.Enum(['count'], default_value=None, allow_none=True)
    padding = T.CFloat(0.1)
    axis = T.Instance(Axis, default_value=None, allow_none=True)
    height = T.CInt(150)
コード例 #24
0
class TextAnnotation(SceneAnnotation):

    name = "text_annotation"
    data = traitlets.Instance(TextCharacters)
    text = traitlets.CUnicode()
    draw_instructions = traitlets.List()
    origin = traitlets.Tuple(traitlets.CFloat(),
                             traitlets.CFloat(),
                             default_value=(-1, -1))
    scale = traitlets.CFloat(1.0)

    @traitlets.observe("text")
    def _observe_text(self, change):
        text = change["new"]
        lines = text.split("\n")
        draw_instructions = []
        y = 0
        for line in reversed(lines):
            x = 0
            dy = 0
            for c in line:
                e = self.data.characters[c]
                draw_instructions.append((x, y, e.texture, e.vbo_offset))
                dy = max(dy, e.vert_advance)
                x += e.hori_advance
            y += dy
        self.draw_instructions = draw_instructions

    def _set_uniforms(self, scene, shader_program):
        pass

    def draw(self, scene, program):
        viewport = np.array(GL.glGetIntegerv(GL.GL_VIEWPORT), dtype="f4")
        program._set_uniform("viewport", viewport)
        each = self.data.vertex_array.each
        for x, y, tex, vbo_offset in self.draw_instructions:
            with tex.bind(0):
                program._set_uniform("x_offset", float(x))
                program._set_uniform("y_offset", float(y))
                program._set_uniform("x_origin", self.origin[0])
                program._set_uniform("y_origin", self.origin[1])
                program._set_uniform("scale", self.scale)
                GL.glDrawArrays(GL.GL_TRIANGLES, vbo_offset * each, each)
コード例 #25
0
ファイル: state.py プロジェクト: zerolugithub/vaex
class VizBase2dState(VizBaseState):
    x_expression = traitlets.Unicode()
    y_expression = traitlets.Unicode()
    x_slice = traitlets.CInt(None, allow_none=True)
    y_slice = traitlets.CInt(None, allow_none=True)
    type = traitlets.CaselessStrEnum(['count', 'min', 'max', 'mean'],
                                     default_value='count')
    aux = traitlets.Unicode(None, allow_none=True)
    groupby = traitlets.Unicode(None, allow_none=True)
    x_shape = traitlets.CInt(None, allow_none=True)
    y_shape = traitlets.CInt(None, allow_none=True)

    x_min = traitlets.CFloat()
    x_max = traitlets.CFloat()
    y_min = traitlets.CFloat()
    y_max = traitlets.CFloat()

    def __init__(self, ds, **kwargs):
        super(VizBase2dState, self).__init__(ds, **kwargs)
        self.observe(lambda x: self.calculate_limits(),
                     ['x_expression', 'y_expression', 'type', 'aux'])
        self.observe(lambda x: self.signal_slice.emit(self),
                     ['x_slice', 'y_slice'])
        # no need for recompute
        #self.observe(lambda x: self.calculate_grid(), ['groupby', 'shape', 'groupby_normalize'])
        self.observe(self.limits_changed, ['x_min', 'x_max', 'y_min', 'y_max'])
        self.calculate_limits()

    def bin_parameters(self):
        yield self.x_expression, self.x_shape or self.shape, (
            self.x_min, self.x_max), self.x_slice
        yield self.y_expression, self.y_shape or self.shape, (
            self.y_min, self.y_max), self.y_slice

    def calculate_limits(self):
        self._calculate_limits('x', 'x_expression')
        self._calculate_limits('y', 'y_expression')
        self.signal_regrid.emit(self)

    def limits_changed(self, change):
        self._calculate_centers()
        self.signal_regrid.emit(self)
コード例 #26
0
ファイル: facetgridconfig.py プロジェクト: yush3n9/altair
class FacetGridConfig(BaseObject):
    """Wrapper for Vega-Lite FacetGridConfig definition.
    
    Attributes
    ----------
    color: Unicode
        
    offset: CFloat
        
    opacity: CFloat
        
    """
    color = T.Unicode(allow_none=True, default_value=None)
    offset = T.CFloat(allow_none=True, default_value=None)
    opacity = T.CFloat(allow_none=True, default_value=None)

    def __init__(self, color=None, offset=None, opacity=None, **kwargs):
        kwds = dict(color=color, offset=offset, opacity=opacity)
        kwargs.update({k: v for k, v in kwds.items() if v is not None})
        super(FacetGridConfig, self).__init__(**kwargs)
コード例 #27
0
ファイル: scale.py プロジェクト: rjrajivjha/altair_scale
class Scale(T.HasTraits):

    name = T.Unicode('')
    type = T.Unicode('')
    domain = T.Union([T.List, T.Tuple])
    domainMax = T.CFloat()
    domainMin = T.CFloat()
    domainMid = T.CFloat()
    domainRaw = T.Union([T.List, T.Tuple])
    range = T.Union([
        T.List, T.Tuple,
        T.Enum([
            'width', 'height', 'symbol', 'category', 'diverging', 'ordinal',
            'ramp', 'heatmap'
        ])
    ])
    reverse = T.Bool()
    round = T.Bool()

    def __call__(self, *args, **kwargs):
        raise NotImplementedError(
            'Scale operation not implemented, use a subclass.')
コード例 #28
0
class UnitSpec(BaseObject):
    """Wrapper for Vega-Lite UnitSpec definition.
    
    Attributes
    ----------
    config: Config
        Configuration object.
    data: Data
        An object describing the data source.
    description: Unicode
        An optional description of this mark for commenting purpose.
    encoding: UnitEncoding
        A key-value mapping between encoding channels and definition of fields.
    height: CFloat
        
    mark: Mark
        The mark type.
    name: Unicode
        Name of the visualization for later reference.
    transform: Transform
        An object describing filter and new field calculation.
    width: CFloat
        
    """
    config = T.Instance(Config, allow_none=True, default_value=None, help="""Configuration object.""")
    data = T.Instance(Data, allow_none=True, default_value=None, help="""An object describing the data source.""")
    description = T.Unicode(allow_none=True, default_value=None, help="""An optional description of this mark for commenting purpose.""")
    encoding = T.Instance(UnitEncoding, allow_none=True, default_value=None, help="""A key-value mapping between encoding channels and definition of fields.""")
    height = T.CFloat(allow_none=True, default_value=None)
    mark = Mark(allow_none=True, default_value=None, help="""The mark type.""")
    name = T.Unicode(allow_none=True, default_value=None, help="""Name of the visualization for later reference.""")
    transform = T.Instance(Transform, allow_none=True, default_value=None, help="""An object describing filter and new field calculation.""")
    width = T.CFloat(allow_none=True, default_value=None)
    
    def __init__(self, config=None, data=None, description=None, encoding=None, height=None, mark=None, name=None, transform=None, width=None, **kwargs):
        kwds = dict(config=config, data=data, description=description, encoding=encoding, height=height, mark=mark, name=name, transform=transform, width=width)
        kwargs.update({k:v for k, v in kwds.items() if v is not None})
        super(UnitSpec, self).__init__(**kwargs)
コード例 #29
0
class Bus(t.HasTraits):
    '''Bus Model'''

    name = t.CUnicode(default_value='Bus1', help='Name of Generator (str)')
    bus_type = t.Enum(
        values=['SWING', 'PQ', 'PV'],
        default_value='PQ',
        help='Bus type',
    )
    real_power_demand = tt.Array(default_value=[0.0],
                                 minlen=1,
                                 help='Active power demand (MW)')
    imag_power_demand = tt.Array(default_value=[0.0],
                                 minlen=1,
                                 help='Reactive power demand (MVAR)')
    shunt_conductance = t.CFloat(default_value=0,
                                 help='Shunt Conductance (TODO: units)')
    shunt_susceptance = t.CFloat(default_value=0,
                                 help='Shunt Susceptance (TODO: units)')
    area = t.CUnicode(default_value='0', help='Area the bus is located in')
    voltage_magnitude = t.CFloat(default_value=1.0,
                                 help='Voltage magnitude (p.u.)')
    voltage_angle = t.CFloat(default_value=0.0, help='Voltage angle (deg)')
    base_voltage = t.CFloat(default_value=230, help='Base voltage (kV)')
    zone = t.CUnicode(default_value='0', help='Zone the bus is located in')
    maximum_voltage = t.CFloat(default_value=1.05, help='Maximum voltage')
    minimum_voltage = t.CFloat(default_value=0.95, help='Minimum voltage')

    def __init__(self, **kwargs):

        v = kwargs.pop('real_power_demand', None)
        v = self._coerce_value_to_list({'value': v})
        kwargs['real_power_demand'] = v

        v = kwargs.pop('imag_power_demand', None)
        v = self._coerce_value_to_list({'value': v})
        kwargs['imag_power_demand'] = v

        super(Bus, self).__init__(**kwargs)

    @t.validate('real_power_demand', 'imag_power_demand')
    def _coerce_value_to_list(self, proposal):
        v = proposal['value']
        if (v is not None and (isinstance(v, int) or isinstance(v, float))):
            v = [
                v,
            ]
        elif v is None:
            v = [
                0.0,
            ]

        return v
コード例 #30
0
ファイル: idobject.py プロジェクト: chrisjsewell/pandas3js
class GeometricObject(IDObject):
    """ a geometric object
    x,y,z should represent the centre of volume
    
    Examples
    --------
    
    >>> gobject = GeometricObject()
    >>> gobject.position
    (0.0, 0.0, 0.0)
    
    """
    position = Vector3(default_value=(0, 0, 0),
                       help='cartesian coordinate of pivot').tag(sync=True)

    visible = trait.Bool(True).tag(sync=True)
    color = Color('red').tag(sync=True)
    transparency = trait.CFloat(1, min=0.0, max=1.0).tag(sync=True)

    label = trait.CUnicode('-').tag(sync=True).tag(sync=True)
    label_visible = trait.Bool(False).tag(sync=True)
    label_color = Color('red').tag(sync=True)
    label_transparency = trait.CFloat(1, min=0.0, max=1.0).tag(sync=True)