Exemple #1
0
class Node(pynetsym.Node):
    state = Enum('S', 'I', 'R')
    recovery_rate = Float(1.0)
    infection_rate = Float(1.0)

    infected_fraction = Float

    def initialize(self, state):
        self.state = state
        if state == 'I':
            self.send(Activator.name, 'infected', node=self.id)

    def infect(self):
        if self.state == 'S':
            self.state = 'I'
            self.send(Activator.name, 'infected', node=self.id)

    def activate(self):
        if self.state == 'I':
            for node in self.neighbors():
                if random.random() < self.infection_rate:
                    self.send(node, 'infect')
            if random.random() < self.recovery_rate:
                self.state = 'R'
                self.send(Activator.name, 'not_infected', node=self.id)
        elif self.state in ('R', 'S'):
            pass
        else:
            self.send_log('I should not get here.')
Exemple #2
0
class Node(pynetsym.Node):
    state = Enum('S', 'I', 'R')
    recovery_rate = Float(1.0)
    infection_rate = Float(1.0)
    spread_out = False

    def initialize(self, state):
        self.state = state
        if state == 'I':
            self.send(Activator.name, 'infected', node=self.id)

    def infect(self):
        if self.state == 'S':
            self.state = 'I'
            self.send(Activator.name, 'infected', node=self.id)

    def activate(self):
        if self.state == 'I':
            if not self.spread_out or self.infection_rate < 1.0:
                for node in self.neighbors():
                    if random.random() < self.infection_rate:
                        self.send(node, 'infect')
                self.spread_out = True
            if random.random() < self.recovery_rate:
                self.state = 'R'
                self.send(Activator.name, 'not_infected', node=self.id)
Exemple #3
0
    def test_traits_shared_transient(self):
        # Regression test for a bug in traits where the same _metadata
        # dictionary was shared between different trait types.
        class LazyProperty(TraitType):
            def get(self, obj, name):
                return 1729

        self.assertFalse(Float().transient)
        LazyProperty().as_ctrait()
        self.assertFalse(Float().transient)
Exemple #4
0
class PAFTest(HasTraits):
    context = Instance(ParametricModelingContext)
    parameters = Instance(Parameters)
    update = Button
    r = Float(1.)
    a = Float(100.)

    view = View(
        Item("parameters", editor=PAFContextEditorFactory(context='context')),
        Item("update"), Item("a"), Item("r"))

    def _update_changed(self):
        self.parameters.a = self.a
        self.parameters.r = self.r
class NewModelBDialog(NewModelDialog):
    """Create a dialog requesting the parameters to create Model B."""

    model_name = Str(MODEL_B_NAME)

    nclasses = Int(5)

    nannotators = Int(8)

    # prior strength multiplies the dirichlet parameters alpha
    prior_strength = Float(1.0)

    parameters_group = VGroup(
        Item(name='nclasses',
             editor=RangeEditor(mode='spinner', low=2, high=1000),
             label='Number of annotation classes:',
             width=100),
        Item(name='nannotators',
             editor=RangeEditor(mode='spinner', low=2, high=1000),
             label='Number of annotators:',
             width=100),
        Item(name='prior_strength',
             editor=RangeEditor(mode='slider',
                                low=0.0, low_label='null ',
                                high=3.0, high_label=' high',
                                label_width=50),
             label='Informativeness of prior:')
    )
Exemple #6
0
class FloatWithRangeEditor(HasTraits):
    """Dialog containing a RangeEditor in 'spinner' mode for an Int.
    """

    number = Float(5.0)

    traits_view = View(Item('number', editor=RangeEditor(low=0.0, high=12.0)),
                       buttons=['OK'])
 def wrapper(self, *arg):
     t1 = time.time()
     self.valid = func(self, *arg)
     t2 = time.time()
     dt = t2 - t1
     if 'duration' not in self.traits():
         self.add_trait('duration', Float())
     self.duration = dt
Exemple #8
0
class CalibrationObject(HasTraits):
    tweak_dict = Dict
    cx = Float
    cy = Float
    rx = Float
    ry = Float

    rotation = Property(depends_on='rx,ry,_rotation')
    _rotation = Float
    center = Property(depends_on='cx,cy')
    scale = Float(1)

    def _set_rotation(self, rot):
        self._rotation = rot

    def _get_rotation(self):
        # if not (self.rx and self.rx):
        #     return self._rotation
        rot = self._rotation
        if not rot:
            rot = self.calculate_rotation(self.rx, self.ry)
        return rot

    def _get_center(self):
        return self.cx, self.cy

    def set_right(self, x, y):
        self.rx = x
        self.ry = y
        self._rotation = 0

    def set_center(self, x, y):
        self.cx = x
        self.cy = y

    def calculate_rotation(self, x, y, sense='east'):
        def rotation(a, b):
            return calc_rotation(self.cx, self.cy, a, b)

        if sense == 'west':
            print('x={}, y={}, cx={}, cy={}'.format(x, y, self.cx, self.cy))
            if y > self.cy:
                rot = calc_rotation(self.cx, self.cy, x, y) - 180
            else:
                rot = calc_rotation(self.cx, self.cy, x, y) + 180
        elif sense == 'north':
            if x > self.cx:
                rot = rotation(x, -y)
            else:
                rot = rotation(y, -x)
        elif sense == 'south':
            rot = rotation(-y, x)
        else:
            rot = rotation(x, y)

        return rot
class MandelbrotParameters(HasTraits):
    """ Stores the parameters needed to visualize the Mandelbrot set.
    """

    # The number of points on each dimension of the grid.
    grid_size = Int(500)

    # Left limit for the x coordinates.
    xmin = Float(-2.0)

    # Right limit for the x coordinates.
    xmax = Float(1.0, auto_set=False)

    # Bottom limit for the y coordinates.
    ymin = Float(-1.5, auto_set=False)

    # Upper limit for the y coordinates.
    ymax = Float(1.5, auto_set=False)

    # Convenience property that returns a tuple with the bounds on the x axis.
    x_bounds = Property
    def _get_x_bounds(self):
        return (self.xmin, self.xmax)

    # 1D array with the x coordinates of the boundaries of the grid element.
    x_coords = Property
    def _get_x_coords(self):
        # The coordinates have 1 more element than the number of points in
        # the grid, because they represent the locations of pixel boundaries.
        return numpy.linspace(self.xmin, self.xmax, self.grid_size+1)

    # Convenience property that returns a tuple with the bounds on the y axis.
    y_bounds = Property(depends_on='ymin,ymax')
    def _get_y_bounds(self):
        return (self.ymin, self.ymax)

    # 1D array with the y coordinates of the boundaries of the grid element.
    y_coords = Property(depends_on='ymin,ymax')
    def _get_y_coords(self):
        # The coordinates have 1 more element than the number of points in
        # the grid, because they represent the locations of pixel boundaries.
        return numpy.linspace(self.ymin, self.ymax, self.grid_size+1)
Exemple #10
0
class DummyParent(HasTraits):

    number = Int()

    number2 = Int()

    instance = Instance(Dummy, allow_none=True)

    instance2 = Instance(Dummy)

    income = Float()

    dummies = List(Dummy)
    def test_complex_baseclass(self):
        # Given
        class Base(HasTraits):
            x = Int

        class_name = "MyClass"
        bases = (Base, )
        class_dict = {"attr": "something", "my_trait": Float()}

        # When
        update_traits_class_dict(class_name, bases, class_dict)

        # Then
        self.assertEqual(class_dict[InstanceTraits], {})
        self.assertEqual(class_dict[ListenerTraits], {})
        self.assertIs(class_dict[BaseTraits]["x"],
                      class_dict[ClassTraits]["x"])
        self.assertIs(
            class_dict[BaseTraits]["my_trait"],
            class_dict[ClassTraits]["my_trait"],
        )
Exemple #12
0
    def test_trait_added_match_func_correct(self):
        # Test the match function supplied to TraitAddedObserver is consistent
        # with the filter.
        instance = DummyParent()
        integer_observer = create_observer(
            filter=lambda name, trait: type(trait.trait_type) is Int,
            notify=True,
        )
        handler = mock.Mock()
        call_add_or_remove_notifiers(
            object=instance,
            graph=create_graph(integer_observer),
            handler=handler,
        )

        # when
        # This trait does not satisfy the filter
        instance.add_trait("another_number", Float())
        instance.another_number += 1

        # then
        self.assertEqual(handler.call_count, 0)
Exemple #13
0
class BoardWrapper(HasTraits):
    pins = List(PinWrapper)
    digital_pins = List(PinWrapper)
    analog_pins = List(PinWrapper)
    defines = List(GuiDefine)
    port_type = Enum('serial',
                     [
                         'none',
                         'serial',
                     ]
                     )
    serial_device = Enum(_auto_detect_serial_unix())
    baudrate = Int(115200)
    sleep_after_connect = Int(2)
    timeout = Int(1)
    uptime = Float()
    tree = None
    vcc = Float()
    avr_name = Str()
    arduino_version = Str()
    firmware_build_time = Str()
    gcc_version = Str()
    libc_version = Str()
    libc_date = Str()

    connected = Bool(False)
    connect = Button()
    disconnect = Button()

    def _connect_fired(self):
            try:
                connection = SerialManager(device=self.serial_device,
                                           baudrate=self.baudrate,
                                           sleep_after_connect=self.sleep_after_connect,
                                           timeout=self.timeout)
                connection.open()
                print ArduinoApi(connection=connection).millis()
            except Exception as e:
                traceback.print_exc()
                message(traceback.format_exc(), buttons=['OK'])
                return

            a = self.tree = ArduinoTree(connection=connection)

            d = a.define.as_dict
            s = [GuiDefine(name=k, value=str(v)) for k, v in d.items()]
            s.sort(key=lambda x: x.name)
            self.defines = s
            self.digital_pins = [PinWrapper(pin=a.pin.get(x))
                                 for x in a.pin.names_digital]
            self.analog_pins = [PinWrapper(pin=a.pin.get(x))
                                for x in a.pin.names_analog]
            self.pins = self.digital_pins + self.analog_pins

            fw = a.firmware_info
            self.arduino_version = fw.get('arduino_version')
            self.firmware_build_time = str(fw.get('compile_datetime'))
            self.avr_name = fw.get('avr_name')
            self.gcc_version = fw.get('gcc_version')
            self.libc_version = fw.get('libc_version')
            self.libc_date = str(fw.get('libc_date'))
            self.connected = True

    def _disconnect_fired(self):
            self.digital_pins = []
            self.analog_pins = []
            self.pins = []
            self.defines = []
            self.avr_name = ''
            self.arduino_version = ''
            self.firmware_build_time = ''
            self.gcc_version = ''
            self.libc_version = ''
            self.libc_date = ''

            self.tree.connection.close()
            del self.tree
            self.tree = None
            self.connected = False

    update_interval = Int(1000, desc='interval in msec')
    update_enable = Bool(True)

    def update(self):
        if self.update_enable and self.connected and self.tree:
            for x in self.pins:
                x.update()
            self.uptime = self.tree.api.millis() / 1000.0
            self.vcc = self.tree.vcc.read() if self.tree.vcc else -1
        time.sleep(self.update_interval / 1000.0)

    traits_view = View(
        Tabbed(
            Group(
                HGroup(
                    Group(
                        button('connect', enabled_when='not connected'),
                        button('disconnect', enabled_when='connected'),
                        Item(
                            'port_type', enabled_when='not connected', width=300,
                        ),
                        Group(
                            'serial_device',
                            'baudrate',
                            'sleep_after_connect',
                            'timeout',
                            visible_when='port_type=="serial"',
                            enabled_when='not connected',
                        ),
                    ),
                    Group(
                        'avr_name',
                        'arduino_version',
                        'firmware_build_time',
                        'gcc_version',
                        'libc_version',
                        'libc_date',
                        #                     'baudrate',
                        #                     'sleep_after_connect',
                        # visible_when='port_type=="serial"',
                        springy=True,
                    ),
                ),
                label='connection',
            ),
            Group(
                'uptime',
                'vcc',
                label='misc',
            ),
            Item(name='digital_pins',
                      editor=ListEditor(
                     style='custom',
                 ),
                 style='readonly',
                 show_label=False,
                 ),
            Item(name='analog_pins',
                      editor=ListEditor(
                 style='custom',
                 ),
                 style='readonly',
                 show_label=False,
                 ),
            Group(
                  'update_enable',
                Item(name='update_interval',
                     editor=RangeEditor(
                     mode='slider',
                     low=1,
                     high=1000,
                     ),
                     style='custom',
                     ),
                label='settings',
            ),
            Item('defines',
                show_label=False,
                editor=ListEditor(
#                     auto_size=False,
#                     editable=False,
#                     configurable=False,
                 style='custom',
                ),
                style='readonly',
                 )
        ),
        width=800,
        height=600,
        buttons=['Undo', 'Revert', 'OK', 'Cancel'],
        kind='live',
        resizable=True,
        handler=Handler(),
    )
Exemple #14
0
class CreateAcqpFileInputSpec(BaseInterfaceInputSpec):
    total_readout = Float(0.0)
Exemple #15
0
class PosteriorPlot(PyannoPlotContainer):
    # data to be displayed
    posterior = Array

    ### plot-related traits
    plot_width = Float

    def _plot_width_default(self):
        return 450 if is_display_small() else 500

    plot_height = Float

    def _plot_height_default(self):
        return 600 if is_display_small() else 750

    colormap_low = Float(0.0)
    colormap_high = Float(1.0)

    origin = Str('top left')

    plot_container = Instance(HPlotContainer)
    plot_posterior = Instance(Plot)

    def _create_colormap(self):
        if self.colormap_low is None:
            self.colormap_low = self.posterior.min()

        if self.colormap_high is None:
            self.colormap_high = self.posterior.max()

        colormap = Reds(
            DataRange1D(low=self.colormap_low, high=self.colormap_high))

        return colormap

    def _plot_container_default(self):
        data = self.posterior
        nannotations, nclasses = data.shape

        # create a plot data object
        plot_data = ArrayPlotData()
        plot_data.set_data("values", data)

        # create the plot
        plot = Plot(plot_data, origin=self.origin)

        img_plot = plot.img_plot("values",
                                 interpolation='nearest',
                                 xbounds=(0, nclasses),
                                 ybounds=(0, nannotations),
                                 colormap=self._create_colormap())[0]
        ndisp = 55
        img_plot.y_mapper.range.high = ndisp
        img_plot.y_mapper.domain_limits = ((0, nannotations))

        self._set_title(plot)
        plot.padding_top = 80

        # create x axis for labels
        label_axis = self._create_increment_one_axis(plot, 0.5, nclasses,
                                                     'top')
        label_axis.title = 'classes'
        self._add_index_axis(plot, label_axis)

        plot.y_axis.title = 'items'

        # tweak plot aspect
        goal_aspect_ratio = 2.0
        plot_width = (goal_aspect_ratio * self.plot_height * nclasses / ndisp)
        self.plot_width = min(max(plot_width, 200), 400)
        plot.aspect_ratio = self.plot_width / self.plot_height

        # add colorbar
        colormap = img_plot.color_mapper
        colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range),
                            color_mapper=colormap,
                            plot=img_plot,
                            orientation='v',
                            resizable='',
                            width=15,
                            height=250)
        colorbar.padding_top = plot.padding_top
        colorbar.padding_bottom = int(self.plot_height - colorbar.height -
                                      plot.padding_top)
        colorbar.padding_left = 0
        colorbar.padding_right = 30

        # create a container to position the plot and the colorbar side-by-side
        container = HPlotContainer(use_backbuffer=True)
        container.add(plot)
        container.add(colorbar)
        container.bgcolor = 0xFFFFFF  # light gray: 0xEEEEEE

        # add pan tools
        img_plot.tools.append(
            PanTool(img_plot,
                    constrain=True,
                    constrain_direction="y",
                    speed=7.))

        self.decorate_plot(container, self.posterior)
        self.plot_posterior = plot
        return container

    def add_markings(self,
                     mark_classes,
                     mark_name,
                     marker_shape,
                     delta_x,
                     delta_y,
                     marker_size=5,
                     line_width=1.,
                     marker_color='white'):
        plot = self.plot_posterior
        nannotations = plot.data.arrays['values'].shape[0]

        y_name = mark_name + '_y'
        x_name = mark_name + '_x'

        valid = is_valid(mark_classes)
        y_values = np.arange(nannotations)[valid] + delta_y + 0.5
        x_values = mark_classes[valid].astype(float) + delta_x + 0.5

        plot.data.set_data(y_name, y_values)
        plot.data.set_data(x_name, x_values)

        plot.plot((x_name, y_name),
                  type='scatter',
                  name=mark_name,
                  marker=marker_shape,
                  marker_size=marker_size,
                  color='transparent',
                  outline_color=marker_color,
                  line_width=line_width)

    def remove_markings(self, mark_name):
        self.plot_posterior.delplot(mark_name)

    def _create_resizable_view(self):
        # resizable_view factory, as I need to compute the height of the plot
        # from the number of annotations, and I couldn't find any other way to
        # do that

        # "touch" posterior_plot to have it initialize
        self.plot_container

        if is_display_small():
            height = 760
        else:
            height = 800

        resizable_plot_item = (Item(
            'plot_container',
            editor=ComponentEditor(),
            resizable=True,
            show_label=False,
            width=self.plot_width,
            height=self.plot_height,
        ))

        resizable_view = View(VGroup(
            Include('instructions_group'),
            resizable_plot_item,
        ),
                              width=450,
                              height=height,
                              resizable=True)

        return resizable_view

    def traits_view(self):
        return self._create_resizable_view()

    pan_instructions = Str

    def _pan_instructions_default(self):
        return 'Left-click and drag to navigate items'

    instructions_group = VGroup(
        HGroup(Spring(),
               Item('instructions', style='readonly', show_label=False),
               Spring()),
        HGroup(Spring(),
               Item('pan_instructions', style='readonly', show_label=False),
               Spring()))
class MatrixPlot(PyannoPlotContainer):

    # data to be displayed
    matrix = Array

    #### plot-related traits
    colormap_low = Float(None)
    colormap_high = Float(None)
    origin = Str('top left')

    matrix_plot_container = Instance(HPlotContainer)

    def _create_colormap(self):
        if self.colormap_low is None:
            self.colormap_low = self.matrix.min()

        if self.colormap_high is None:
            self.colormap_high = self.matrix.max()

        if self.colormap_low >= 0.0:
            colormap_factory = Reds
        else:
            colormap_factory = reverse(RdBu)

        colormap = colormap_factory(
            DataRange1D(low=self.colormap_low, high=self.colormap_high))

        return colormap

    def _matrix_plot_container_default(self):
        matrix = np.nan_to_num(self.matrix)
        width = matrix.shape[0]

        # create a plot data object and give it this data
        plot_data = ArrayPlotData()
        plot_data.set_data("values", matrix)

        # create the plot
        plot = Plot(plot_data, origin=self.origin)

        img_plot = plot.img_plot("values",
                                 interpolation='nearest',
                                 xbounds=(0, width),
                                 ybounds=(0, width),
                                 colormap=self._create_colormap())[0]

        #### fix axes
        self._remove_grid_and_axes(plot)

        axis = self._create_increment_one_axis(plot, 0.5, width, 'bottom')
        self._add_value_axis(plot, axis)

        axis = self._create_increment_one_axis(
            plot,
            0.5,
            width,
            'left',
            ticks=[str(i) for i in range(width - 1, -1, -1)])
        self._add_index_axis(plot, axis)

        #### tweak plot attributes
        self._set_title(plot)
        plot.aspect_ratio = 1.
        # padding [left, right, up, down]
        plot.padding = [0, 0, 25, 25]

        # create the colorbar, handing in the appropriate range and colormap
        colormap = img_plot.color_mapper
        colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range),
                            color_mapper=colormap,
                            plot=img_plot,
                            orientation='v',
                            resizable='v',
                            width=20,
                            padding=[0, 20, 0, 0])
        colorbar.padding_top = plot.padding_top
        colorbar.padding_bottom = plot.padding_bottom

        # create a container to position the plot and the colorbar side-by-side
        container = HPlotContainer(use_backbuffer=True)
        container.add(plot)
        container.add(colorbar)
        container.bgcolor = 0xFFFFFF

        self.decorate_plot(container, self.matrix)
        return container

    resizable_plot_item = Item('matrix_plot_container',
                               editor=ComponentEditor(),
                               resizable=True,
                               show_label=False,
                               width=600,
                               height=400)

    traits_plot_item = Instance(Item)

    def _traits_plot_item_default(self):
        return Item('matrix_plot_container',
                    editor=ComponentEditor(),
                    resizable=False,
                    show_label=False,
                    height=-200,
                    width=-200)
Exemple #17
0
class PinInfo(HasTraits):
    pin_nr = PinTrait()
    R = Float()
    node = Any()
    group = Str()