How to use the traittypes.Array function in traittypes

To help you get started, we’ve selected a few traittypes examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jaantollander / crowddynamics / crowddynamics / traits.py View on Github external
- Array: (str, numpy.dtype, shape)
    """
    if is_trait(trait):
        if isinstance(trait, Int):
            return name, np.int64
        elif isinstance(trait, Float):
            return name, np.float64
        elif isinstance(trait, Complex):
            return name, np.complex128
        elif isinstance(trait, Bool):
            return name, np.bool_
        elif isinstance(trait, Unicode):
            raise NotImplementedError
        elif isinstance(trait, Enum):
            raise NotImplementedError
        elif isinstance(trait, Array):
            return name, trait.dtype, trait.default_value.shape
        else:
            raise InvalidValue('Trait conversion is not supported for: '
                               '{}'.format(trait))
    else:
        raise InvalidType('Trait should be instance of {}'.format(TraitType))
github K3D-tools / K3D-jupyter / k3d / objects.py View on Github external
Attributes:
        heights: `array_like`.
            2D scalar field of Z values.
        color: `int`.
            Packed RGB color of the resulting mesh (0xff0000 is red, 0xff is blue).
        wireframe: `bool`.
            Whether mesh should display as wireframe.
        flat_shading: `bool`.
            Whether mesh should display with flat shading.
        model_matrix: `array_like`.
            4x4 model transform matrix.
    """

    type = Unicode(read_only=True).tag(sync=True)
    heights = Array(dtype=np.float32).tag(sync=True, **array_serialization_wrap('heights'))
    color = Int(min=0, max=0xffffff).tag(sync=True)
    wireframe = Bool().tag(sync=True)
    flat_shading = Bool().tag(sync=True)
    model_matrix = Array(dtype=np.float32).tag(sync=True, **array_serialization_wrap('model_matrix'))

    def __init__(self, **kwargs):
        super(Surface, self).__init__(**kwargs)

        self.set_trait('type', 'Surface')


class Text(Drawable):
    """
    Text rendered using KaTeX with a 3D position.

    Attributes:
github bloomberg / bqplot / bqplot / interacts.py View on Github external
A 2x2 array containing the coordinates 
        [[selected_x[0], selected_y[0]],
         [selected_x[1], selected_y[1]]]
    brushing: bool (default: False)
        boolean attribute to indicate if the selector is being dragged.
        It is True when the selector is being moved and False when it is not.
        This attribute can be used to trigger computationally intensive code
        which should be run only on the interval selection being completed as
        opposed to code which should be run whenever selected is changing.
    color: Color or None (default: None)
        Color of the rectangle representing the brush selector.
    """
    clear = Bool().tag(sync=True)
    brushing = Bool().tag(sync=True)
    selected_x = Array(None, allow_none=True).tag(sync=True, **array_serialization)
    selected_y = Array(None, allow_none=True).tag(sync=True, **array_serialization)
    selected = Array(None, allow_none=True)
    color = Color(None, allow_none=True).tag(sync=True)

    # This is for backward compatibility for code that relied on selected
    # instead of select_x and selected_y
    @observe('selected_x', 'selected_y')
    def _set_selected(self, change):
        if self.selected_x is None or len(self.selected_x) == 0 or \
           self.selected_y is None or len(self.selected_y) == 0:
            self.selected = None
        else:
            self.selected = np.array([[self.selected_x[0], self.selected_y[0]],
                             [self.selected_x[1], self.selected_y[1]]])

    @observe('selected')
    def _set_selected_xy(self, change):
github glue-viz / bqplot-image-gl / bqplot_image_gl / imagegl.py View on Github external
from bqplot.traits import (array_serialization, array_squeeze)
from traitlets import (Int, Unicode, List, Enum, Dict, Bool, Float,
                       Instance, TraitError, validate)
from bqplot.marks import shape

@widgets.register
class ImageGL(bqplot.Mark):
    """An example widget."""
    _view_name = Unicode('ImageGLView').tag(sync=True)
    _model_name = Unicode('ImageGLModel').tag(sync=True)
    _view_module = Unicode('bqplot-image-gl').tag(sync=True)
    _model_module = Unicode('bqplot-image-gl').tag(sync=True)
    _view_module_version = Unicode('^0.2.0').tag(sync=True)
    _model_module_version = Unicode('^0.2.0').tag(sync=True)

    image = Array().tag(sync=True,
                        scaled=True,
                        rtype='Color',
                        atype='bqplot.ColorAxis',
                        **array_serialization)
    interpolation = Unicode('nearest', allow_none=True).tag(sync=True)
    opacity = Float(1.0).tag(sync=True)
    x = Array(default_value=(0, 1)).tag(sync=True, scaled=True,
                                        rtype='Number',
                                        atype='bqplot.Axis',
                                        **array_serialization)\
        .valid(array_squeeze, shape(2))
    y = Array(default_value=(0, 1)).tag(sync=True, scaled=True,
                                        rtype='Number',
                                        atype='bqplot.Axis',
                                        **array_serialization)\
        .valid(array_squeeze, shape(2))
github bloomberg / bqplot / bqplot / interacts.py View on Github external
[[selected_x[0], selected_y[0]],
         [selected_x[1], selected_y[1]]]
    brushing: bool (default: False)
        boolean attribute to indicate if the selector is being dragged.
        It is True when the selector is being moved and False when it is not.
        This attribute can be used to trigger computationally intensive code
        which should be run only on the interval selection being completed as
        opposed to code which should be run whenever selected is changing.
    color: Color or None (default: None)
        Color of the rectangle representing the brush selector.
    """
    clear = Bool().tag(sync=True)
    brushing = Bool().tag(sync=True)
    selected_x = Array(None, allow_none=True).tag(sync=True, **array_serialization)
    selected_y = Array(None, allow_none=True).tag(sync=True, **array_serialization)
    selected = Array(None, allow_none=True)
    color = Color(None, allow_none=True).tag(sync=True)

    # This is for backward compatibility for code that relied on selected
    # instead of select_x and selected_y
    @observe('selected_x', 'selected_y')
    def _set_selected(self, change):
        if self.selected_x is None or len(self.selected_x) == 0 or \
           self.selected_y is None or len(self.selected_y) == 0:
            self.selected = None
        else:
            self.selected = np.array([[self.selected_x[0], self.selected_y[0]],
                             [self.selected_x[1], self.selected_y[1]]])

    @observe('selected')
    def _set_selected_xy(self, change):
        value = self.selected
github power-system-simulation-toolbox / psst / psst / case / bus.py View on Github external
import traittypes as tt

M = 1e10


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
github QuantStack / ipygany / ipygany / ipygany.py View on Github external
if data.name == data_name:
                    return data[component_name]
            raise KeyError('Data {} not found.'.format(data_name))

        if isinstance(data_name, int):
            return self.data[data_name][component_name]

        raise KeyError('Invalid key {}.'.format(key))


class PolyMesh(Block):
    """A polygon-based 3-D Mesh widget."""

    _model_name = Unicode('PolyMeshModel').tag(sync=True)

    triangle_indices = Array(default_value=array(UINT32)).tag(sync=True, **array_serialization)

    def __init__(self, vertices=[], triangle_indices=[], data=[], **kwargs):
        """Construct a PolyMesh.

        A PolyMesh is a triangle-based mesh. ``vertices`` is the array of points, ``triangle_indices`` is the array of triangle
        indices.
        """
        vertices = np.asarray(vertices).flatten()
        triangle_indices = np.asarray(triangle_indices).flatten()

        # If there are no triangle indices, assume vertices are given in the right order for constructing the triangles.
        if triangle_indices.size == 0:
            triangle_indices = np.arange(vertices.size, dtype=np.uint32)

        super(PolyMesh, self).__init__(
            vertices=vertices, triangle_indices=triangle_indices, data=data, **kwargs
github power-system-simulation-toolbox / psst / psst / case / generator.py View on Github external
maximum_real_power = t.CFloat(default_value=0, min=0, help='Capacity of Generator (MW)')
    minimum_real_power = t.CFloat(default_value=0, min=0, help='Minimum generation (MW)')
    maximum_imag_power = t.CFloat(default_value=0, help='Maximum reactive generation (MVAR)')
    minimum_imag_power = t.CFloat(default_value=0, help='Minimum reactive generation (MVAR)')
    initial_real_power = t.CFloat(default_value=0, min=0, help='Initial power generation (MW)')
    initial_imag_power = t.CFloat(default_value=0, min=0, help='Initial power generation (MVAR)')
    initial_status = t.CBool(default_value=True, min=0, help='Initial status (bool)')
    startup_time = t.CInt(default_value=0, min=0, help='Startup time (hrs)')
    shutdown_time = t.CInt(default_value=0, min=0, help='Shutdown time (hrs)')
    nsegments = t.CInt(
        default_value=2,
        min=MINIMUM_COST_CURVE_SEGMENTS,
        max=MAXIMUM_COST_CURVE_SEGMENTS,
        help='Number of data points for piecewise linear'
    )
    cost_curve_points = tt.Array(default_value=[0, 0, 0], minlen=(MINIMUM_COST_CURVE_SEGMENTS + 1), maxlen=(MAXIMUM_COST_CURVE_SEGMENTS + 1))
    cost_curve_values = tt.Array(default_value=[0, 0, 0], minlen=(MINIMUM_COST_CURVE_SEGMENTS + 1), maxlen=(MAXIMUM_COST_CURVE_SEGMENTS + 1))
    noload_cost = t.CFloat(default_value=0, min=0, help='No-Load Cost of a Generator ($/hr)')
    startup_cost = t.CFloat(default_value=0, min=0, help='Startup Cost of a Generator ($/hr)')
    inertia = t.CFloat(allow_none=True, default_value=None, min=0, help='Inertia of generator (NotImplemented)')
    droop = t.CFloat(allow_none=True, default_value=None, min=0, help='Droop of generator (NotImplemented)')

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

    @property
    def _npoints(self):
        return self.nsegments + 1

    @property
    def ramp_rate(self):
        raise AttributeError(
github K3D-tools / K3D-jupyter / k3d / transfer_function_editor.py View on Github external
class TF_editor(widgets.DOMWidget):
    _view_name = Unicode('TransferFunctionView').tag(sync=True)
    _model_name = Unicode('TransferFunctionModel').tag(sync=True)
    _view_module = Unicode('k3d').tag(sync=True)
    _model_module = Unicode('k3d').tag(sync=True)

    _view_module_version = Unicode(version).tag(sync=True)
    _model_module_version = Unicode(version).tag(sync=True)

    # readonly (specified at creation)
    height = Int().tag(sync=True)

    # read-write
    color_map = Array(dtype=np.float32).tag(sync=True, **array_serialization_wrap('color_map'))
    opacity_function = Array(dtype=np.float32).tag(sync=True, **array_serialization_wrap('opacity_function'))

    def __init__(self, height, color_map, opacity_function, *args, **kwargs):
        super(TF_editor, self).__init__()

        self.height = height

        with self.hold_trait_notifications():
            self.color_map = color_map
            self.opacity_function = opacity_function

        self.outputs = []

    def display(self, **kwargs):
        output = widgets.Output()

        with output:
github bloomberg / bqplot / bqplot / marks.py View on Github external
count: number of elements in the bin hovered on
        bin_start: start point of the bin
        bin-end: end point of the bin
        index: index of the bin
    """
    # Mark decoration
    icon = 'fa-signal'
    name = 'Histogram'

    # Scaled attributes
    sample = Array([]).tag(sync=True, display_name='Sample',
                           scaled=True, rtype='Number',
                           atype='bqplot.Axis',
                           **array_serialization)\
        .valid(array_squeeze, array_dimension_bounds(1, 1))
    count = Array([], read_only=True).tag(sync=True,
                                          display_name='Count',
                                          scaled=True,
                                          rtype='Number',
                                          atype='bqplot.Axis',
                                          **array_serialization)\
        .valid(array_squeeze)
    normalized = Bool().tag(sync=True)

    # Other attributes
    scales_metadata = Dict({
        'sample': {'orientation': 'horizontal', 'dimension': 'x'},
        'count': {'orientation': 'vertical', 'dimension': 'y'}
    }).tag(sync=True)

    bins = Int(10).tag(sync=True, display_name='Number of bins')
    midpoints = List(read_only=True).tag(sync=True, display_name='Mid points')