Example #1
0
class RuntimeDependency(Declarative):
    """Extension to the 'runtime-dependencies' extensions point of the
    TaskManagerPlugin.

    Attributes
    ----------
    id : unicode
        Unique Id.

    walk_members : list(str)
        List of members for the walk method of the ComplexTask.

    walk_kwargs : dict(str: callable)
        Dict of name: callables for the walk method of the ComplexTask.

    collect : callable(workbench, flatten_walk)
        Callable in charge of collecting the identified build dependencies.
        It should take as arguments the workbench of the application, a dict
        in the format {name: set()} and the calling plugin id. It should return
        a dict holding the dependencies (as dictionaries) in categories. If
        there is no dependence for a given category this category should be
        absent from the dict.
        The input falt_walk should be left untouched. In case of failure it
        should raise a value error.


    """
    id = d_(Unicode())

    walk_members = d_(List(Str()))

    walk_callables = d_(Dict(Str(), Callable()))

    collect = d_(Callable())
Example #2
0
class ExperimentActionBase(Declarative):

    # Name of event that triggers command
    event = d_(Unicode())

    dependencies = List()

    match = Callable()

    # Defines order of invocation. Less than 100 invokes before default. Higher
    # than 100 invokes after default. Note that if concurrent is True, then
    # order of execution is not guaranteed.
    weight = d_(Int(50))

    # Arguments to pass to command by keyword
    kwargs = d_(Dict())

    def _default_dependencies(self):
        return get_dependencies(self.event)

    def _default_match(self):
        code = compile(self.event, 'dynamic', 'eval')
        if len(self.dependencies) == 1:
            return partial(simple_match, self.dependencies[0])
        else:
            return partial(eval, code)

    def __str__(self):
        return f'{self.event} (weight={self.weight}; kwargs={self.kwargs})'
Example #3
0
class Measurement(LogicalChannel):
    '''
    A class for measurement channels.
    Measurements are special because they can be different types:
    autodyne which needs an IQ pair or hetero/homodyne which needs just a marker channel.
    '''
    meas_type = Enum(
        'autodyne',
        'homodyne').tag(desc='Type of measurement (autodyne, homodyne)')

    autodyne_freq = Float(0.0).tag(
        desc=
        'use to bake the modulation into the pulse, so that it has constant phase'
    )
    frequency = Float(0.0).tag(
        desc='use frequency to asssociate modulation with the channel')
    pulse_params = Dict(
        default={
            'length': 100e-9,
            'amp': 1.0,
            'shape_fun': PulseShapes.tanh,
            'cutoff': 2,
            'sigma': 1e-9
        })
    gate_chan = Instance((str, LogicalMarkerChannel))
    trig_chan = Instance((str, LogicalMarkerChannel))
    receiver_chan = Instance((str, ReceiverChannel))

    def __init__(self, **kwargs):
        super(Measurement, self).__init__(**kwargs)
        if self.trig_chan is None:
            self.trig_chan = LogicalMarkerChannel(label='digitizerTrig')
Example #4
0
class ParameterProxyBase(Atom):
    _params = Dict()

    def __str__(self):
        return "ParameterProxy[" + ",".join(
            "{0}={1}".format(k, getattr(self, k))
            for k in self._params.keys()) + "]"
Example #5
0
class Date(HTMLObject):

    tag = E.INPUT

    text = d_(Unicode())
    id = d_(Unicode())

    date = d_(Dict())

    def initialize(self):
        super(Date, self).initialize()

    def buildHTML(self, *args):
        self.addTags()
        self.addText(self.text)
        self.addAttributes()

        if self.id:
            self.addAttributes(type = "date", id = self.id)

        return super(Date, self).buildHTML(*args)

    #@observe(('date'))
    def _update_web(self, change):
        super(Date, self)._update_web(change)
Example #6
0
class Measurement(LogicalChannel):
    '''
    A class for measurement channels. 
    Measurments are special because they can be different types:
    autodyne which needs an IQ pair or hetero/homodyne which needs just a marker channel. 
    '''
    measType = Enum(
        'autodyne',
        'homodyne').tag(desc='Type of measurment (autodyne, homodyne)')
    autodyneFreq = Float()
    pulseParams = Dict(
        default={
            'length': 100e-9,
            'amp': 1.0,
            'shapeFun': PulseShapes.tanh,
            'buffer': 0.0,
            'cutoff': 2,
            'sigma': 1e-9
        })
    gateChan = Instance((unicode, LogicalMarkerChannel))

    def __init__(self, **kwargs):
        super(Measurement, self).__init__(**kwargs)
        if self.gateChan is None:
            self.gateChan = LogicalMarkerChannel(label=kwargs['label'] +
                                                 '-gate')
Example #7
0
class NoSQLModelManager(ModelManager):
    """A descriptor so you can use this somewhat like Django's models.
    Assuming your using motor or txmongo.

    Examples
    --------
    MyModel.objects.find_one({'_id':'someid})

    """

    #: Table proxy cache
    proxies = Dict()

    def __get__(self, obj, cls=None):
        """Handle objects from the class that owns the manager"""
        cls = cls or obj.__class__
        if not issubclass(cls, Model):
            return self  # Only return the collection when used from a Model
        proxy = self.proxies.get(cls)
        if proxy is None:
            proxy = self.proxies[cls] = NoSQLDatabaseProxy(
                table=self.database[cls.__model__]
            )
        return proxy

    def _default_database(self):
        raise EnvironmentError(
            "No database has been set. Use "
            "NoSQLModelManager.instance().database = <db>"
        )
Example #8
0
class User(AbstractUser):
    id = Typed(int).tag(primary_key=True, name="user_id")
    name = Str().tag(length=200)
    active = Bool()
    age = Int()
    settings = Dict()
    rating = Instance(float).tag(nullable=True)
Example #9
0
    class Read_Extension_Test(Read_File):
        """a test class for extending Read_File"""
        data=Dict()

        def read(self):
            self.data={"file_path": self.file_path}
            return super(Read_Extension_Test, self).read()
Example #10
0
class DocksRenderController(VTKRenderController):
    """ Docks model
    """

    backgrounds = Dict()

    def __init__(self, view=None, bgColor=None, callbacks=None):
        """
        default init
        """
        super(DocksRenderController, self).__init__(view=view, bgColor=bgColor, callbacks=callbacks)
        self.addActors(visquad())

    def set_background(self, background):
        """
        set models background
        """
        self.bgColor = background
        if self.view:
            deferred_call(self.view.render)

    def set_interactor_style(self, style):
        """
        set interactor style
        """
        self.setInteractorStyle(style)
Example #11
0
class Read_HDF5(Filer):
    data = Dict()

    def open_and_read(self):
        with File(self.file_path, 'r') as f:
            self.data = self.reread(
                f)  #print key, item.keys(), isinstance(item, Group)
            print "Read data from file: {0}".format(self.file_path)
        return self.data

    def reread(self, g, md=dict()):
        """recursively reads all data into a dictionary"""
        for key, item in g.iteritems():
            md[key] = dict()

            if isinstance(item, Group):
                md[key] = self.reread(item, md[key])
            else:
                md[key]['data'] = item[:]
            if item.attrs.keys() != []:
                md[key]['attrs'] = dict()
                for akey, aitem in item.attrs.iteritems():
                    md[key]['attrs'][akey] = aitem
        return md

    def read_txt(self):
        self.data = {"data": loadtxt(self.file_path)}
        return self.data
Example #12
0
class GlobalConfig(Atom):
    domain_name = Str()
    setup_name = Str()
    user_name = Str()
    platform_name = Str()

    config_directory = Str()
    data_directory = Str()
    record_directory = Str()

    components_path = Str()
    logging_config = Str()
    py_logging_config = Str()

    plugins = Dict()
    devices = Dict()
Example #13
0
class ProxyResolver(Atom):
    """ An object which resolves requests for proxy objects.

    """
    #: A dictionary of factories functions to use when resolving the
    #: proxy. The function should take no arguments, and return the
    #: proxy class when called.
    factories = Dict()

    def resolve(self, name):
        """ Resolve the given name to a proxy calls.

        For example, 'Field' should resolve to a class which implements
        the ProxyField interface.

        Parameters
        ----------
        name : str
            The name of the proxy object to resolve.

        Returns
        -------
        result : type or None
            A class which implements the proxy interface, or None if
            no class can be found for the given name.

        """
        factory = self.factories.get(name)
        if factory is not None:
            return factory()
Example #14
0
class GraphicsNode(GraphicsSceneGraphNode):

    #: options to be set before rendering
    gl_options = d_(Dict())
    antialias = d_(Bool(True))

    @observe("gl_options", "antialias")
    def _gn_trigger_update(self, change):
        self.trigger_update()

    def setup_gl(self):
        for k, v in self.gl_options.items():
            if v is None:
                continue

            if isinstance(k, basestring):
                func = getattr(GL, k)
                func(*v)
            else:
                if v is True:
                    glEnable(k)
                else:
                    glDisable(k)

    def render_node(self, context):
        self.setup_gl()
Example #15
0
class StoreRecordSource(BaseRecordSource):

    fields = Dict()

    def _default_max_record_count(self):
        return len(self.reference_timestamps)

    # XXX missing reference_interval

    def __iter__(self):
        if len(self.cached_records) > 0:
            for cached_record in self.cached_records:
                yield cached_record
            return

        rcls = self.record_class
        fields = self.fields
        field_names = fields.keys()
        for idx, ts in enumerate(self.reference_timestamps):
            attrs = dict(timestamp=ts)
            for field_name in field_names:
                attrs[field_name] = fields[field_name][idx]

            record = rcls(**attrs)
            self.cached_records.append(record)
            yield record
Example #16
0
class Markdown(Raw):
    """ A block for rendering Markdown source. """

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

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

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

    #: Disallow raw HTMl
    safe_mode = d_(Bool())

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

    #: Tab size
    tab_length = d_(Int(4))

    @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)
Example #17
0
class OccFillet(OccOperation, ProxyFillet):
    
    shape_types = Dict(default={
        'rational':ChFi3d_Rational, 
        'angular':ChFi3d_QuasiAngular, 
        'polynomial':ChFi3d_Polynomial
    })
    
    def update_shape(self, change={}):
        d = self.declaration
        
        #: Get the shape to apply the fillet to
        children = [c for c in self.children()]
        if not children:
            raise ValueError("Fillet must have a child shape to operate on.")
        child = children[0]
        s = child.shape.Shape()
        shape = BRepFilletAPI_MakeFillet(s)#,self.shape_types[d.shape])
        
        edges = d.edges if d.edges else child.topology.edges()
        for edge in edges:
            shape.Add(d.radius, edge)
        #if not shape.HasResult():
        #    raise ValueError("Could not compute fillet, radius possibly too small?")
        self.shape = shape
        
    def set_shape(self, shape):
        self._queue_update({})
        
    def set_radius(self, r):
        self._queue_update({})
        
    def set_edges(self, edges):
        self._queue_update({})
Example #18
0
class Console(Container):
    """ Console widget """
    proxy = Typed(ProxyConsole)
    
    #: Font family, leave blank for default
    font_family = d_(Unicode())
    
    #: Font size, leave 0 for default
    font_size = d_(Int(0))
    
    #: Default console size in characters
    console_size = d_(Coerced(Size,(81,25)))
    
    #: Buffer size, leave 0 for default
    buffer_size = d_(Int(0))
    
    #: Display banner like version, etc..
    display_banner = d_(Bool(False))
    
    #: Code completion type
    #: Only can be set ONCE
    completion = d_(Enum('ncurses','plain', 'droplist'))
    
    #: Run the line or callabla
    execute = d_(Instance(object))
    
    #: Push variables to the console
    #: Note this is WRITE ONLY
    scope = d_(Dict(),readable=False)
    
    @observe('font_family','font_size','console_size','buffer_size',
             'scope','display_banner','execute','completion')
    def _update_proxy(self, change):
        super(Console, self)._update_proxy(change)
Example #19
0
 class DictAtom(Atom):
     untyped = Dict()
     keytyped = Dict(Int())
     valuetyped = Dict(value=Int())
     fullytyped = Dict(Int(), Int())
     untyped_default = Dict(default={1: 1})
     keytyped_default = Dict(Int(), default={1: 1})
     valuetyped_default = Dict(value=Int(), default={1: 1})
     fullytyped_default = Dict(Int(), Int(), default={1: 1})
Example #20
0
class Bookmark(Atom):
    #: Name of it
    name = Unicode()

    #: Bible
    bible = ForwardInstance(lambda: Bible)

    #: Book
    book = Instance(Book)

    #: Chapter
    chapter = Instance(Chapter)

    #: Verse
    #verse = Instance(Verse)

    #: Save / load state
    state = Dict()

    def __init__(self, *args, **kwargs):
        super(Bookmark, self).__init__(*args, **kwargs)
        if kwargs.get('state') is None:
            #: If we're not loading from state
            self.state = {
                'bible': self.bible.version.key,
                'book': self.book.name,
                'chapter': self.chapter.number,
                #'verse': self.verse.number
            }

    def _default_name(self):
        return u"{} {}".format(self.book.name, self.chapter.number)

    def _default_bible(self):
        try:
            #: Prevent loading two bibles if it was bookmarked in a different bible
            bible = AppState.instance().bible
            if bible is not None:
                return bible
            return AppState.instance().get_bible(self.state['bible'])
        except KeyError:
            return None

    def _default_book(self):
        if not self.bible:
            return None
        try:
            return self.bible.get_book(self.state['book'])
        except KeyError:
            return None

    def _default_chapter(self):
        if not self.book:
            return None
        try:
            #: They're supposed to be in order
            return self.book.chapters[self.state['chapter'] - 1]
        except KeyError:
            return None
Example #21
0
class User(NoSQLModel):
    name = Str()
    email = Str()
    active = Bool()
    settings = Dict()

    def _default_settings(self):
        return {"font-size": 16, "theme": "maroon"}
Example #22
0
class LogicalMarkerChannel(LogicalChannel):
    '''
    A class for digital channels for gating sources or triggering other things.
    '''
    pulseParams = Dict(default={
        'shapeFun': PulseShapes.square,
        'length': 100e-9
    })
Example #23
0
class Figure(PlotElement):
    """Figure holding possibly multiple axes on a grid."""

    #: Set of axes on a grid.
    axes_set = Dict(str, Axes)

    #: Position of the axes on the grid
    grid = Dict(str, GridPosition)

    def initialize(self, resolver):
        """Initialize the proxy of the figure and the axes."""
        self._resolver = resolver
        super().initialize(resolver)
        for axes in self.axes_set.values():
            axes.figure = self
            axes.backend_name = self.backend_name
            axes.initialize(resolver)

    def finalize(self):
        """Finalize the proxy of the figure."""
        for axes in self.axes_set.values():
            axes.figure = self
            axes.finalize()
        super().finalize()

    def add_axes(self,
                 id: str,
                 position: GridPosition,
                 axes: Optional[Axes] = None) -> Axes:
        """Add an axes to the figure"""
        axes = axes or Axes()
        self.axes_set[id] = axes
        self.grid[id] = position
        if self._resolver:
            axes.initialize(self._resolver)

        return axes

    def remove_axes(self, id: str):
        """"""
        pass  # FIXME not needed as long as we have a single axes per figure

    # --- Private API

    #: Reference to the backend resolver needed to dynamically add axes
    _resolver = Typed(BackendResolver)
Example #24
0
class PatternTemplate(UTQLSchemaEntity):

    name = Str()
    displayName = Str()
    description = Str()

    nodes = Dict()

    constraints = List()

    input_edges = List()
    output_edges = List()

    type_registry = Dict()
    references = Dict()

    dataflow_config = Typed(DataflowConfiguration)
Example #25
0
class OccPipe(OccOperation, ProxyPipe):
    reference = set_default('https://dev.opencascade.org/doc/refman/html/'
                            'class_b_rep_offset_a_p_i___make_pipe.html')

    #: References to observed shapes
    _old_spline = Instance(OccShape)
    _old_profile = Instance(OccShape)

    fill_modes = Dict(
        default={
            'corrected_frenet': GeomFill_IsCorrectedFrenet,
            'fixed': GeomFill_IsFixed,
            'frenet': GeomFill_IsFrenet,
            'constant_normal': GeomFill_IsConstantNormal,
            'darboux': GeomFill_IsDarboux,
            'guide_ac': GeomFill_IsGuideAC,
            'guide_plan': GeomFill_IsGuidePlan,
            'guide_ac_contact': GeomFill_IsGuideACWithContact,
            'guide_plan_contact': GeomFill_IsGuidePlanWithContact,
            'discrete_trihedron': GeomFill_IsDiscreteTrihedron
        })

    def update_shape(self, change=None):
        d = self.declaration

        if d.spline and d.profile:
            spline, profile = d.spline, d.profile
        elif d.spline:
            spline = d.spline
            profile = self.get_first_child().shape
        elif d.profile:
            profile = d.profile
            spline = self.get_first_child().shape
        else:
            shapes = [
                c.shape for c in self.children() if isinstance(c, OccShape)
            ]
            spline, profile = shapes[0:2]

        args = [coerce_shape(spline), coerce_shape(profile)]

        # Make sure spline is a wire
        if isinstance(args[0], TopoDS_Edge):
            args[0] = BRepBuilderAPI_MakeWire(args[0]).Wire()

        if d.fill_mode:
            args.append(self.fill_modes[d.fill_mode])
        pipe = BRepOffsetAPI_MakePipe(*args)
        self.shape = pipe.Shape()

    def set_spline(self, spline):
        self.update_shape()

    def set_profile(self, profile):
        self.update_shape()

    def set_fill_mode(self, mode):
        self.update_shape()
class TaskCheckModel(Atom):
    """Simple dialog displaying the errors messages resulting from a failed
    check.

    Attributes
    ----------
    check_dict_result : dict(str, str)
        Dictionnary storing the path of the task in which a check failed and
        the associated message.
    name_to_path_dict : dict(str, str)
        Dictionnary mapping the name of the tasks in which a check failed to its
        path.
    selected_check : str
        Name of the task the user selected from `failed_check_list`.
    full_path : str
        Path of the selected task.
    message : str
        Message associated to the selected task.
    """
    check_dict_result = Dict(Str(), Str())
    name_to_path_dict = Dict(Str(), Str())

    selected_check = Str()
    full_path = Str()
    message = Str()

    def __init__(self, check_dict_result):
        super(TaskCheckModel, self).__init__()
        self.check_dict_result = check_dict_result
        self.name_to_path_dict = {
            key.rpartition('/')[-1]: key
            for key in self.check_dict_result.keys()
        }
        self.selected_check = self.name_to_path_dict.keys()[0]
        self.full_path = self.name_to_path_dict[self.selected_check]
        self.message = self.check_dict_result[self.full_path]

    @observe('selected_check')
    def _update(self, change):
        """Automatically set the `full_path` and `message` attribute when the
        user select a new failed check.
        """
        new = change['value']
        self.full_path = self.name_to_path_dict[new]
        self.message = self.check_dict_result[self.full_path]
Example #27
0
class ViewerSelectionEvent(Atom):
    #: Selected shape or shapes
    selection = List()

    #: Parameters such as coodrinates or selection area
    parameters = Tuple()

    #: Selection callback parameters
    options = Dict()
class RequestPattern(AbstractPattern):
    nodes = Dict()

    constraints = List()

    input_edges = List()
    output_edges = List()

    dataflow_config = Typed(DataflowConfiguration)
Example #29
0
class RenderViewController(VTKRenderController):
    """ render view controller
    """

    backgrounds = Dict()
    extract_model = Value()
    shrink_factor = Int()
    radius = Int()

    def __init__(self, view=None, bgColor=None, callbacks=None):
        """
        default init
        """
        super(RenderViewController, self).__init__(view=view, bgColor=bgColor, callbacks=callbacks)
        self.shrink_factor = 55
        self.radius = 25
        self.extract_model = ExtractModel(shrink_factor=self.shrink_factor/100., radius=self.radius/100.)
        self.addActors(self.extract_model.get_actors())

    def set_background(self, background):
        """
        set models background
        """
        self.bgColor = background
        if self.view:
            deferred_call(self.view.render)

    def set_interactor_style(self, style):
        """
        set interactor style
        """
        self.setInteractorStyle(style)

    def on_close(self):
        """
        on close
        """
        pass

    def _observe_shrink_factor(self, change):
        """ observe change in shrink factor """
        if change:
            type_ = change.get('type')
            if type_ != 'create':
                value = change['value']
                self.extract_model.shrink_geom.SetShrinkFactor(value/100.)
                deferred_call(self.view.render)

    def _observe_radius(self, change):
        """ observe change in radius """
        if change:
            type_ = change.get('type')
            if type_ != 'create':
                value = change['value']
                self.extract_model.sphere_geom_1.SetRadius(value/100.)
                self.extract_model.sphere_geom_2.SetRadius(value/100.)
                deferred_call(self.view.render)
Example #30
0
class IconTheme(Declarative):
    """Declaration of an icon theme.

    An icon theme should provide the following icons  as far as the main
    application is concerned:
    - folder-open
    -
    -
    -

    """
    #: Unique id of the icon theme.
    id = d_(Str())

    @d_func
    def get_icon(self, manager, icon_id):
        """Generate an icon corresponding to an id.

        By default an icon theme simply check its children Icons and ask it to
        generate the actual icon.

        Parameters
        ----------
        manager : IconManagerPlugin
            Reference to the plugin manager.

        icon_id : unicode
            Id of the icon which should be generated.

        Returns
        -------
        icon : enaml.icon.Icon or None
            Icon matching the id or None if no icon match the provided id.

        """
        if not self._icons and self.children:
            self._refresh_children_icons()

        if icon_id in self._icons:
            return self._icons[icon_id].get_icon(manager, self)

        else:
            return None

    # --- Private API ---------------------------------------------------------

    #: Map of id: icon as declared as children to this theme.
    _icons = Dict()

    def _refresh_children_icons(self):
        """Refresh the mapping of the icons contributed as children.

        """
        # HINT when reparenting enaml does not properly update the children
        for c in [c for c in self.children if c.parent is self]:
            if isinstance(c, Icon):
                self._icons[c.id] = c