Esempio n. 1
0
class WaitingTask(SimpleTask):
    """Simple Task whose execution can be controlled using events.

    """
    check_flag = Bool(True).tag(pref=True)
    sync_port = Value(()).tag(pref=True)
    sock_id = Unicode().tag(pref=True)

    def check(self, *args, **kwargs):
        super(WaitingTask, self).check(*args, **kwargs)
        return self.check_flag, {'test': 1}

    def perform(self):
        with socket.socket() as s:
            while True:
                if s.connect_ex(('localhost', self.sync_port)) == 0:
                    break
                sleep(0.01)
            s.sendall(self.sock_id.encode('utf-8'))
            s.recv(4096)
            s.sendall('Waiting'.encode('utf-8'))
            s.recv(4096)
Esempio n. 2
0
class Person(Atom):
    """A simple class representing a person object."""

    last_name = Str()

    first_name = Str()

    age = Range(low=0)

    debug = Bool(False)

    @observe("age")
    def debug_print(self, change):
        """Prints out a debug message whenever the person's age changes."""
        if self.debug:
            templ = "{first} {last} is {age} years old."
            s = templ.format(
                first=self.first_name,
                last=self.last_name,
                age=self.age,
            )
            print(s)
class SwipeRefreshLayout(ViewGroup):
    """SwipeRefreshLayout is a view group that displays
    child views in relative positions.

    """

    #: Enabled
    enabled = d_(Bool(True))

    #: Must be a
    indicator_color = d_(Str())

    #: Must be a
    indicator_background_color = d_(Str())

    #: Set the distance to trigger a sync in dips
    trigger_distance = d_(Int())

    #: Triggered when the user swipes
    refreshed = d_(Event())

    #: A reference to the proxy object.
    proxy = Typed(ProxySwipeRefreshLayout)

    # -------------------------------------------------------------------------
    # Observers
    # -------------------------------------------------------------------------
    @observe(
        "enabled",
        "indicator_color",
        "indicator_background_color",
        "trigger_distance",
    )
    def _update_proxy(self, change):

        if change["type"] == "event":
            self.proxy.set_refreshed(True)
        else:
            super()._update_proxy(change)
Esempio n. 4
0
class Splitter(ConstraintsWidget):
    """ A widget which displays its children in separate resizable
    compartements that are connected with a resizing bar.

    A Splitter can have an arbitrary number of Container children.

    """
    #: The orientation of the Splitter. 'horizontal' means the children
    #: are laid out left to right, 'vertical' means top to bottom.
    orientation = d_(Enum('horizontal', 'vertical'))

    #: Whether the child widgets resize as a splitter is being dragged
    #: (True), or if a simple indicator is drawn until the drag handle
    #: is released (False). The default is True.
    live_drag = d_(Bool(True))

    #: A splitter expands freely in height and width by default.
    hug_width = set_default('ignore')
    hug_height = set_default('ignore')

    #: A reference to the ProxySplitter object.
    proxy = Typed(ProxySplitter)

    def split_items(self):
        """ Get the split item children defined on the splitter.

        """
        return [c for c in self.children if isinstance(c, SplitItem)]

    #--------------------------------------------------------------------------
    # Observers
    #--------------------------------------------------------------------------
    @observe(('orientation', 'live_drag'))
    def _update_proxy(self, change):
        """ An observer which sends state change to the proxy.

        """
        # The superclass handler implementation is sufficient.
        super(Splitter, self)._update_proxy(change)
Esempio n. 5
0
class Snackbar(ToolkitObject):
    """ A toast is a view containing a quick little message for the user.
    """

    #: Text to display
    #: if this node has a child view this is ignored
    text = d_(Unicode())

    #: Text to display in the action button
    action_text = d_(Unicode())

    #: Color for the action text button
    action_text_color = d_(Unicode())

    #: Duration to display in ms or 0 for infinite
    duration = d_(Int(3000))

    #: Alias for the action is clicked
    clicked = d_(Event(), writable=False)

    #: When an action occurs such as swiped out, clicked, timed out, etc..
    action = d_(Event(basestring), writable=False)

    #: Show the snackbar for the given duration
    show = d_(Bool())

    #: A reference to the proxy object.
    proxy = Typed(ProxySnackbar)

    # -------------------------------------------------------------------------
    # Observers
    # -------------------------------------------------------------------------
    @observe('text', 'duration', 'action_text', 'action_text_color', 'show')
    def _update_proxy(self, change):
        """ An observer which sends the state change to the proxy.

        """
        # The superclass implementation is sufficient.
        super(Snackbar, self)._update_proxy(change)
Esempio n. 6
0
class SetRFPulsedTask(InstrumentTask):
    """Set the frequency of the signal delivered by a RF source.

    """
    # Whether to start the source in pulsed mode
    pulsed = Bool(False).tag(pref=True)

    def check(self, *args, **kwargs):
        """Checks if the instrument is connected

        """
        test, traceback = super(SetRFPulsedTask, self).check(*args, **kwargs)
        return test, traceback

    def perform(self):
        """Default interface for simple sources.

        """
        if self.pulsed:
            self.driver.pm_state = 'ON'
        else:
            self.driver.pm_state = 'OFF'
Esempio n. 7
0
class Fit1D(FitObject):
    'class for fitting 1d datasets'

    parent = ForwardInstance(lambda: ap.data.XYDataObject)
    plot = ForwardInstance(lambda: ap.plot.Plot1D)

    fitted = Bool(
        default=False
    )  # boolean which indicates if current model and data are fitted

    _model = Value()
    result = Value()

    _fit = Typed(Fit)

    def __init__(self, parent, *args, **kwargs):
        self.parent = parent
        super(Fit1D, self).__init__(*args, **kwargs)

        self.result = None

    def add_model(self, model):
        if self._model: del self._model

        if isinstance(model, str):
            self._model = get_model(model, self.parent.x, self.parent.y)
        else:
            self._model = model

        self.fitted = False

    @observe('parent.x', 'parent.x_updated', 'parent.y', 'parent.y_updated')
    def _data_updated(self, change):
        self.fitted = False

    def execute(self, *options, **kwoptions):
        self._fit = Fit(self._model, self.parent.x, self.parent.y)
        self.result = self._fit.execute(*options, **kwoptions)
Esempio n. 8
0
class Channel(Atom):
    '''
    Every channel has a label and some printers.
    '''
    label = Str()
    enabled = Bool(True)

    def __repr__(self):
        return str(self)

    def __str__(self):
        return "{0}: {1}".format(self.__class__.__name__, self.label)

    def json_encode(self):
        jsonDict = self.__getstate__()

        #Strip out pass-through properties
        for k, m in self.members().items():
            if isinstance(m, Property):
                del jsonDict[k]

        #Turn instruments back into unicode labels
        for member in [
                "AWG", "generator", "physChan", "gateChan", "source", "target"
        ]:
            if member in jsonDict:
                obj = jsonDict.pop(member)
                if obj:
                    jsonDict[member] = obj.label

        #We want the name of shape functions
        if "pulseParams" in jsonDict:
            pulseParams = deepcopy(jsonDict.pop("pulseParams"))
            if "shapeFun" in pulseParams:
                pulseParams["shapeFun"] = pulseParams["shapeFun"].__name__
            jsonDict["pulseParams"] = pulseParams

        return jsonDict
Esempio n. 9
0
class ExtractEpochs(EpochInput):

    queue = d_(Typed(deque, {}))

    buffer_size = d_(Float(0)).tag(metadata=True)

    #: Defines the size of the epoch (if NaN, this is automatically drawn from
    #: the information provided by the queue).
    epoch_size = d_(Float(0)).tag(metadata=True)

    #: Defines the extra time period to capture beyond the epoch duration.
    poststim_time = d_(Float(0).tag(metadata=True))

    complete = Bool(False)

    def mark_complete(self):
        self.complete = True

    def configure_callback(self):
        #if self.epoch_size == 0:
            #raise ValueError('Epoch size not configured')
        if np.isinf(self.epoch_size):
            m = f'ExtractEpochs {self.name} has an infinite epoch size'
            raise ValueError(m)
        cb = super().configure_callback()
        return extract_epochs(self.fs, self.queue, self.epoch_size,
                              self.poststim_time, self.buffer_size, cb,
                              self.mark_complete).send

    def _get_duration(self):
        return self.epoch_size + self.poststim_time

    # force change notification for duration
    def _observe_epoch_size(self, event):
        self.notify('duration', self.duration)

    def _observe_poststim_time(self, event):
        self.notify('duration', self.duration)
Esempio n. 10
0
class BooleanOperation(Operation):
    """ A base class for a boolean operation on two or more shapes.

    Attributes
    ----------

    shape1: Shape
        The first shape argument of the operation.
    shape2: Shape
        The second shape argument of the operation.

    """

    shape1 = d_(Instance(object))

    shape2 = d_(Instance(object))

    #: Unify using ShapeUpgrade_UnifySameDomain
    unify = d_(Bool(False))

    @observe('shape1', 'shape2', 'unify')
    def _update_proxy(self, change):
        super(BooleanOperation, self)._update_proxy(change)
Esempio n. 11
0
class CustomBlastDB(Atom):
    """Represents parameters of a BLAST database.

    """
    fasta = Unicode('test')
    query = Unicode('query')
    sp_only = Bool(False)
    target_name = Unicode()

    def run(self):
        paths = env.get_db_locations()

        try:
            result = subprocess.check_output([
                'makeblastdb', '-in', self.fasta, '-dbtype', 'prot',
                '-parse_seqids', '-title', self.target_name, '-out',
                self.target_name
            ],
                                             cwd=paths[0],
                                             stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
            result = e.output
        return unicode(result)
Esempio n. 12
0
class Button(TextView):
    """ A simple control for displaying a button.

    """
    #: Button is clickable by default
    clickable = set_default(True)

    #: Use a flat style
    flat = d_(Bool())

    #: A reference to the proxy object.
    proxy = Typed(ProxyButton)

    # -------------------------------------------------------------------------
    # Observers
    # -------------------------------------------------------------------------
    @observe('flat')
    def _update_proxy(self, change):
        """ An observer which sends the state change to the proxy.

        """
        # The superclass implementation is sufficient.
        super(Button, self)._update_proxy(change)
Esempio n. 13
0
class FlexboxLayoutParams(FlexParams):
    """ A model for flexbox layout parameters """
    #: How to align children along the cross axis of their container
    align_items = Enum('stretch', 'flex_start', 'flex_end', 'center')

    #: Control how multiple lines of content are aligned within a
    #: container which uses FlexWrap
    align_content = Enum('flex_start', 'flex_end', 'center', 'space_between',
                         'space_around')

    #: Should the layout be a column or a row.
    flex_direction = Enum('row', 'column', 'row_reversed', 'column_reversed')

    #: Wrap or nowrap
    flex_wrap = Bool()

    #: How to align children within the main axis of a container
    justify_content = Enum('flex_start', 'flex_end', 'center', 'space_between',
                           'space_around')

    #: The Position property tells Flexbox how you want your item to be
    #: positioned within its parent.
    position = Enum('relative', 'absolute')
Esempio n. 14
0
class GroupedEpochFFTPlot(EpochGroupMixin, BasePlot):

    waveform_averages = d_(Int(1))
    apply_calibration = d_(Bool(True))

    def _default_name(self):
        return self.source_name + '_grouped_epoch_fft_plot'

    def _cache_x(self, event=None):
        # Cache the frequency points. Must be in units of log for PyQtGraph.
        # TODO: This could be a utility function stored in the parent?
        if self.source.fs and self.duration:
            self._x = get_x_fft(self.source.fs,
                                self.duration / self.waveform_averages)

    def _y(self, epoch):
        y = super()._y(epoch)
        psd = util.psd(y,
                       self.source.fs,
                       waveform_averages=self.waveform_averages)
        if self.apply_calibration:
            return self.source.calibration.get_db(self._x, psd)
        return util.db(psd)
Esempio n. 15
0
class BFGigEStreamChannel(BFProperty):
    """Class containing the Configuration properties for a Blackfly camera.

    Use this as a basis for other settings classes from blackfly.  If you mirror
    the structure in the reference manual it will make it easy to make the
    server.
    """

    networkInterfaceIndex = Int(0)
    # hostPort = Int(0)
    doNotFragment = Bool(False)
    packetSize = Int(1224)
    interPacketDelay = Int(100)

    # destinationIpAddress = Int()
    # sourcePort = ()

    def __init__(self, name, experiment, description=''):
        """Add in the properties that need to be sent to the camera."""
        super(BFGigEStreamChannel, self).__init__(name, experiment,
                                                  description)
        # things not in the property list are not sent to the camera
        self.properties += ['packetSize', 'interPacketDelay']
Esempio n. 16
0
class CheckTask(SimpleTask):
    """
    """

    check_called = Bool()

    perform_called = Int()

    perform_value = Value()

    time = Float(0.01)

    def check(self, *args, **kwargs):

        self.check_called = True
        return True, {}

    def perform(self, value=None):

        self.perform_called += 1
        self.perform_value = value
        # Simply allow thread switching
        sleep(self.time)
Esempio n. 17
0
class Parameter(ContextItem):
    '''
    A context item that can be evaluated dynamically, but cannot be included as
    part of a selector.  This is typically used for settings that must be
    determined before values are drawn from the selectors (e.g., probability of
    a go trial).
    '''
    # Default value of the context item when used as part of a selector.
    default = d_(Value())

    expression = d_(Str()).tag(preference=True)

    # Defines the span over which the item's value does not change:
    # * experiment - the value cannot change once the experiment begins
    # * trial - The value cannot change once a trial begins. This is the only
    #   type of item that can be roved using a selector.
    # * arbitrary - The value can be changd at any time but it does not make
    #   sense for it to be a roving item.
    scope = d_(Enum('trial', 'experiment', 'arbitrary'))

    # Is the value of this item managed by a selector?
    rove = d_(Bool()).tag(preference=True)

    def _default_expression(self):
        return str(self.default)

    def _default_dtype(self):
        return np.array(self.default).dtype.str

    def _default_label(self):
        return self.name

    def to_expression(self, value):
        return str(value)

    def set_value(self, value):
        self.expression = self.to_expression(value)
Esempio n. 18
0
class HttpResponse(Atom):
    """ The response object returned to an AsyncHttpClient fetch callback.
    It is based on the the tornado HttpResponse object.
    
    """

    #: Request that created this response
    request = Instance(HttpRequest)

    #: Numeric HTTP status code
    code = Int()

    #: Reason phrase for the status code
    reason = Unicode()

    #: Response headers list of strings
    headers = Dict()

    #: Result success
    ok = Bool()

    #: Response body
    #: Note: if a streaming_callback is given to the request
    #: then this is NOT used and will be empty
    body = Unicode()

    #: Size
    content_length = Int()

    #: Error message
    error = Instance(HttpError)

    #: Progress
    progress = Int()

    #: Done time
    request_time = Float()
Esempio n. 19
0
class Output(BaseOutput):

    # These two are defined as properties because it's theoretically possible
    # for the output to transform these (e.g., an output could upsample
    # children or "equalize" something before passing it along).
    fs = Property().tag(metadata=True)
    calibration = Property().tag(metadata=True)
    filter_delay = Property().tag(metadata=True)

    # TODO: clean this up. it's sort of hackish.
    token = d_(Typed(Declarative)).tag(metadata=True)

    # Can the user configure properties (such as the token) via the GUI?
    configurable = d_(Bool(True))

    callbacks = List()

    def connect(self, cb):
        self.callbacks.append(cb)

    def notify(self, data):
        if not self.callbacks:
            return
        # Correct for filter delay
        d = data.copy()
        d['t0'] += self.filter_delay
        for cb in self.callbacks:
            cb(d)

    def _get_filter_delay(self):
        return self.target.filter_delay

    def _get_fs(self):
        return self.channel.fs

    def _get_calibration(self):
        return self.channel.calibration
Esempio n. 20
0
class DummyMonitor(BaseMonitor):
    """Dummy monitor used for testing.

    """
    running = Bool()

    monitored_entries = set_default(['default_path'])

    received_news = List()

    def start(self):
        self.running = True

    def stop(self):
        self.running = False

    def refresh_monitored_entries(self, entries=None):
        """Do nothing when refreshing.

        """
        pass

    def handle_database_entries_change(self, news):
        """Add all entries to the monitored ones.

        """
        if news[0] == 'added':
            self.monitored_entries = self.monitored_entries + [news[1]]

    def handle_database_nodes_change(self, news):
        """Simply ignore nodes updates.

        """
        pass

    def process_news(self, news):
        self.received_news.append(news)
Esempio n. 21
0
class Markdown(Raw):
    """ A block for rendering Markdown source. """

    #: Extensions to use when rendering
    extensions = d_(
        List(default=[
            "markdown.extensions.codehilite",
            "markdown.extensions.fenced_code",
        ])).tag(attr=False)

    #: Configuration for them
    extension_configs = d_(
        Dict(default={
            'markdown.extensions.codehilite': {
                'css_class': 'highlight'
            },
        })).tag(attr=False)

    #: Disallow raw HTMl
    safe_mode = d_(Bool()).tag(attr=False)

    #: Output format
    output_format = d_(
        Enum("xhtml1", "xhtml5", "xhtml", "html4", "html5",
             "html")).tag(attr=False)

    #: Tab size
    tab_length = d_(Int(4)).tag(attr=False)

    #: Reference to the proxy
    proxy = Typed(ProxyMarkdown)

    @observe('extensions', 'extension_configs', 'safe_mode', 'output_format',
             'tab_length')
    def _update_proxy(self, change):
        """ The superclass implementation is sufficient. """
        super(Markdown, self)._update_proxy(change)
Esempio n. 22
0
class AbstractConfig(Atom):
    """Root class for all config objects.

    """
    #: Exopy_pulses manager, necessary to retrieve item(pulse/sequence)
    #: implementations.
    manager = ForwardTyped(pulses_manager)

    #: Class of the item to create.
    sequence_class = Subclass(Item)

    #: Root of the sequence in which an item will be added.
    root = Typed(Item)

    #: Bool indicating if the build can be done.
    ready = Bool(False)

    def check_parameters(self, change):
        """Check if enough parameters have been provided to build the item.

        This method should set the ready flag every time it is called, setting
        it to True if everything is allright, False otherwise.

        """
        raise NotImplementedError()

    def build_sequence(self):
        """This method use the user parameters to build the item object.

        Returns
        -------
        item : Item | None
            Item object built using the user parameters. Ready to be
            inserted in a sequence. None if errors occured.

        """
        raise NotImplementedError()
class StreamInterpolator(Atom):
    filespec = Typed(StreamFileSpec)
    is_reference = Bool(False)
    selector = Enum(*RECORD_SELECTORS)
    latency = Float(0.0)

    streamfile = Typed(StreamFile)

    @property
    def fieldname(self):
        return self.filespec.fieldname

    @property
    def datatype(self):
        return self.filespec.datatype

    @property
    def is_array(self):
        return self.filespec.is_array

    @property
    def timestamps(self):
        return self.streamfile.timestamps

    @property
    def interval(self):
        return self.streamfile.interval

    @property
    def record_count(self):
        return self.streamfile.count

    def _default_streamfile(self):
        return self.filespec.getStreamFile()

    def get(self, idx, dts):
        return self.streamfile.get(idx, dts - self.latency, self.selector)
Esempio n. 24
0
class Toast(ToolkitObject):
    """ A toast is a view containing a quick little message for the user.
    
    """

    #: Text to display
    #: if this node has a child view this is ignored
    text = d_(Unicode())

    #: Duration to display in ms
    duration = d_(Int(1000))

    #: x position
    x = d_(Int())

    #: y position
    y = d_(Int())

    #: Position
    gravity = d_(Coerced(int, coercer=coerce_gravity))

    #: Show the notification for the given duration
    show = d_(Bool())

    #: A reference to the proxy object.
    proxy = Typed(ProxyToast)

    # -------------------------------------------------------------------------
    # Observers
    # -------------------------------------------------------------------------
    @observe('text', 'duration', 'show', 'gravity', 'x', 'y')
    def _update_proxy(self, change):
        """ An observer which sends the state change to the proxy.

        """
        # The superclass implementation is sufficient.
        super(Toast, self)._update_proxy(change)
Esempio n. 25
0
class Clock(Atom):
    """ A clock so widgets can observe each field as required. """
    year = Int()
    month = Int()
    day = Int()
    hour = Int()
    minute = Int()
    second = Int()
    running = Bool(True)
    now = Instance(datetime, factory=lambda: datetime.now())

    def _observe_running(self, change):
        if self.running:
            timed_call(0, self.tick)

    def _observe_now(self, change):
        t = self.now
        self.year, self.month, self.day = t.year, t.month, t.day
        self.hour, self.minute, self.second = t.hour, t.minute, t.second
        if self.running:
            timed_call(1000, self.tick)

    def tick(self):
        self.now = datetime.now()
Esempio n. 26
0
class SetRFPowerTask(InterfaceableTaskMixin, InstrumentTask):
    """Set the power of the signal delivered by the source.

    """
    # Target power (dynamically evaluated)
    power = Unicode().tag(pref=True, feval=LOOP_REAL)

    # Whether to start the source if its output is off.
    auto_start = Bool(False).tag(pref=True)

    database_entries = set_default({'power': -10})

    def i_perform(self, power=None):
        """

        """
        if self.auto_start:
            self.driver.output = 'On'

        if power is None:
            power = self.format_and_eval_string(self.power)

        self.driver.power = power
        self.write_in_database('power', power)
Esempio n. 27
0
class PlotElement(Atom):
    """Element of plot interacting with the backend through a proxy."""

    #: Name of the backend to use
    backend_name = Str()

    #: Backend specific proxy
    proxy = Typed(PlotElementProxy)

    #: Control the visibility of the element.
    visibility = Bool(True)

    def initialize(self, resolver):
        """Initialize the element by creating the proxy."""
        proxy = resolver.resolve_proxy(self)
        proxy.activate()
        self.observe("visibility", update_proxy)

    def finalize(self):
        """Finalize the element by destroying the proxy."""
        self.unobserve("visibility", update_proxy)
        self.proxy.deactivate()
        del self.proxy.element
        del self.proxy
Esempio n. 28
0
class DropFirstMeasurementsFilter(Analysis):
    """This analysis allows the user to drop the first N measurements in an
    iteration, to ensure that all measurements are done at equivalent conditions
    ."""

    version = '2014.06.12'
    enable = Bool()
    filter_level = Int()
    N = Int()

    def __init__(self, name, experiment, description=''):
        super(DropFirstMeasurementsFilter,
              self).__init__(name, experiment, description)
        self.properties += ['version', 'enable', 'filter_level', 'N']

    def analyzeMeasurement(self, measurementResults, iterationResults,
                           experimentResults):
        if self.enable:
            i = measurementResults.attrs['measurement']
            if i < self.N:
                # User chooses whether or not to delete data.
                # max takes care of ComboBox returning -1 for no selection
                logger.info('dropping measurement {} of {}'.format(i, self.N))
                return max(0, self.filter_level)
Esempio n. 29
0
class Plot1DLine(Plot1D):
    """"""

    #: Color of the plot
    color = ColorMember()

    #: Weight of the line
    line_weight = Float(1.0)

    #: Style of the line
    line_style = Str()

    #: Should markers be displayed
    markers_enabled = Bool()

    #: Size of the markers
    markers_size = Float()

    #: Shape of the marker
    # FIXME complete
    marker_shape = Enum((
        "*",
        "+",
    ))
Esempio n. 30
0
class SeekBar(ProgressBar):
    """ A simple control for displaying read-only text.

    """

    #: Sets the amount of progress changed via the arrow keys.
    key_progress_increment = d_(Int())

    #: Specifies whether the track should be split by the thumb.
    split_track = d_(Bool())

    #: A reference to the SeekBar object.
    proxy = Typed(ProxySeekBar)

    # -------------------------------------------------------------------------
    # Observers
    # -------------------------------------------------------------------------
    @observe('key_progress_increment', 'split_track')
    def _update_proxy(self, change):
        """ An observer which sends the state change to the proxy.

        """
        # The superclass implementation is sufficient.
        super(SeekBar, self)._update_proxy(change)