Exemple #1
0
class Colorbar(PlotElement):
    """Colorbar for a 2D plot."""

    #: Reference to the parent axes.
    axes = ForwardTyped(lambda: Axes)

    #: Position at which the colorbar should be created.
    location = Enum("right", "top", "left", "bottom")

    #: Should that axis be autoscaled
    auto_scaling = Bool()

    #: List of 2 tuple representing a possibly discountinuous axis.
    limits = List(tuple)

    #: Label of the axis
    label = Str()

    #: Tick labels.
    tick_labels = List(str)

    #: Font used for the label
    label_font = Dict(str)

    #: Font used for the tick labels
    tick_labels_font = Dict(str)

    #:
    aspect_ratio = Int(20)
Exemple #2
0
class ExecutionInfos(Atom):
    """Information necessary for engine to execute a task.

    This object is also used by the engine to provide feedback about the
    execution of the task.

    """
    #: Id used to identify the task in logger messages.
    id = Unicode()

    #: Task to execute.
    task = Value()

    #: Build dependencies. This allow to rebuild the task if necessary.
    build_deps = Dict()

    #: Runtime dependencies of the task.
    runtime_deps = Dict()

    #: List of entries for which the engine should send updates during
    #: processing.
    observed_entries = List()

    #: Boolean indicating whether the engine should run the checks of the task.
    checks = Bool(True)

    #: Boolean set by the engine, indicating whether or not the task was
    #: successfully executed.
    success = Bool()

    #: Errors which occured during the execution of the task if any.
    errors = Dict()
Exemple #3
0
class DatabaseNode(Atom):
    """ Helper class to differentiate nodes and dict in database

    """
    data = Dict()

    meta = Dict()
Exemple #4
0
class Dummy(Model):
    _private = Int()
    computed = Int().tag(store=False)
    id = Int()
    enabled = Bool()
    string = Bool()
    list_of_int = List(int)
    list_of_str = List(str)
    list_of_any = List()
    list_of_tuple = List(Tuple())
    list_of_tuple_of_float = List(Tuple(float))
    tuple_of_any = Tuple()
    tuple_of_number = Tuple((float, int))
    tuple_of_int_or_model = Tuple((int, Model))
    tuple_of_forwarded = Tuple(ForwardTyped(lambda: NotYetDefined))
    set_of_any = Tuple()
    set_of_number = Set(float)
    set_of_model = Set(AbstractModel)
    dict_of_any = Dict()
    dict_of_str_any = Dict(str)
    dict_of_str_int = Dict(str, int)
    typed_int = Typed(int)
    typed_dict = Typed(dict)
    instance_of_model = Instance(AbstractModel)
    forwarded_instance = ForwardInstance(lambda: NotYetDefined)
    coerced_int = Coerced(int)
    prop = Property(lambda self: True)
    tagged_prop = Property(lambda self: 0).tag(store=True)
class RequestLoader(Atom):

    pattern_directory = Str()
    namespaces = Dict(UTQL_NAMESPACES)

    pattern_templates = Dict()

    def _default_pattern_templates(self):
        if not os.path.isdir(self.pattern_directory):
            log.error("Invalid pattern directory: %s" % self.pattern_directory)
            return {}

        pattern_templates = {}
        for filename in find_all_patterns(
                root_path=os.path.abspath(self.pattern_directory)):
            log.info("Parsing pattern-file: %s" % filename)
            result = parse_utql_pattern(filename, self.namespaces)
            if result is not None:
                for k, v in result.items():
                    pattern_templates[k] = v

        return pattern_templates

    def load_request(self, filename):
        return parse_utql_request(filename, self.namespaces)

    def process_request(self, request):
        template_keys = self.pattern_templates.keys()
        for pattern in request.patterns:
            if pattern.name not in template_keys:
                log.warning(
                    "Pattern: %s not in template library - skipping...")
                continue
            template = self.pattern_templates[pattern.name]
Exemple #6
0
class PlotView(Control):
    hug_width = set_default('ignore')
    hug_height = set_default('ignore')
    proxy = Typed(ProxyPlotView)
    data = d_(ContainerList())
    setup = d_(Callable(lambda graph: None))

    title = d_(Str())
    labels = d_(Dict(Str(), Str()))

    axis_scales = d_(Dict(Str(), Float()))

    #background_color = d_(Str())
    #foreground = d_(Str())

    antialiasing = d_(Bool(True))
    aspect_locked = d_(Bool(True))

    grid = d_(Tuple(item=Bool(), default=(False, False)))
    grid_alpha = d_(FloatRange(low=0.0, high=1.0, value=0.5))

    multi_axis = d_(Bool(True))

    @observe('data', 'title', 'labels', 'multi_axis', 'antialiasing',
             'axis_scales', 'grid', 'grid_alpha')
    def _update_proxy(self, change):
        """ An observer which sends state change to the proxy.
        """
        # The superclass handler implementation is sufficient.
        super(PlotView, self)._update_proxy(change)
Exemple #7
0
class Axis(PlotElement):
    """Axis of a plot."""

    #: Reference to the parent axes.
    axes = ForwardTyped(lambda: Axes)

    #: Should that axis be autoscaled
    auto_scaling = Bool()

    #: List of 2 tuple representing a possibly discountinuous axis.
    limits = List(tuple)

    #: Is the axis direction inverted.
    inverted = Bool()

    #: Label of the axis
    label = Str()

    #: Tick labels.
    tick_labels = List(str)

    #: Font used for the label
    label_font = Dict(str)

    #: Font used for the tick labels
    tick_labels_font = Dict(str)

    #: Intercept position of this axis with the other axis in data coordinate.
    #: Setting this values will have an impact only if there are only 2 active
    #: axes in the axes_set.
    intercept = Float()
Exemple #8
0
class CalibrationWizard(Atom):
    name = Str()
    title = Str()

    # deprecated
    modules_namespace = Str()

    facade_handler = Enum('inprocess', 'subprocess')

    root_directory = Str()

    calibration_directory = Str()
    dfg_directory = Str()
    results_directory = Str()

    report_filename = Str('calibration_report.yaml')

    modules = List()
    datasources = Dict()
    calibsources = Dict()

    # could be implemented using calibsources ...
    calibration_init_files = Dict()

    # subclass needed ?
    haptic_device = Typed(PhantomHapticDevice)
Exemple #9
0
class OccOffset(OccOperation, ProxyOffset):
    reference = set_default('https://dev.opencascade.org/doc/refman/html/'
                            'class_b_rep_offset_a_p_i___make_offset.html')
    
    offset_modes = Dict(default={
        'skin': BRepOffset_Skin,
        'pipe': BRepOffset_Pipe,
        'recto_verso': BRepOffset_RectoVerso
    })
    
    join_types = Dict(default={
        'arc': GeomAbs_Arc,
        'tangent': GeomAbs_Tangent,
        'intersection': GeomAbs_Intersection,
    })
    
    def get_shape(self):
        """ Return shape to apply the chamfer to. """
        for child in self.children():
            return child
        
    def update_shape(self, change={}):
        d = self.declaration
        
        #: Get the shape to apply the fillet to
        s = self.get_shape()
        
        if isinstance(s.shape, BRepBuilderAPI_MakeWire):
            shape = BRepOffsetAPI_MakeOffset(
                s.shape.Wire(),
                self.join_types[d.join_type]
            )
            shape.Perform(d.offset)
            self.shape = shape
        else:
            self.shape = BRepOffsetAPI_MakeOffsetShape(
                s.shape.Shape(),
                d.offset,
                d.tolerance,
                self.offset_modes[d.offset_mode],
                d.intersection,
                False,
                self.join_types[d.join_type]
            )
        
    def set_offset(self, offset):
        self._queue_update({})
        
    def set_offset_mode(self, mode):
        self._queue_update({})
        
    def set_join_type(self, mode):
        self._queue_update({})
        
    def set_intersection(self, enabled):
        self._queue_update({})
Exemple #10
0
class DatabaseNode(Atom):
    """Helper class to differentiate nodes and dict in database

    """
    #: Reference to the parent node.
    parent = ForwardTyped(lambda: DatabaseNode)

    #: Actual data hold by this node.
    data = Dict()

    #: Metadata associated with this node such as access exceptions.
    meta = Dict()
Exemple #11
0
class HttpRequest(Atom):
    """ The request object created for fetch calls. 
    It's based on the design of Tornado's HttpRequest.
    
    """
    #: Request url
    url = Unicode()

    #: Request method
    method = Unicode('get')

    #: Request headers
    headers = Dict()

    #: Retry count
    retries = Int()

    #: Request parameter data
    data = Dict()

    #: Content type
    content_type = Unicode("application/x-www-urlencoded")

    #: Raw request body
    body = Unicode()

    #: Response created
    response = ForwardInstance(lambda: HttpResponse)

    #: Called when complete
    callback = Callable()

    #: Streaming callback
    streaming_callback = Callable()

    #: Start time
    start_time = Float()

    def __init__(self, *args, **kwargs):
        """ Build the request as configured.
        
        """
        super(HttpRequest, self).__init__(*args, **kwargs)
        self.start_time = time.time()
        self.response = HttpResponse(request=self)
        self.init_request()

    def init_request(self):
        """ Initialize the request using whatever native means necessary 
        
        """
        raise NotImplementedError
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()
Exemple #13
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
Exemple #14
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)
Exemple #15
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()) + "]"
Exemple #16
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')
Exemple #17
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()
Exemple #18
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
Exemple #19
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')
Exemple #20
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)
Exemple #21
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>"
        )
Exemple #22
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)
Exemple #23
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({})
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()
Exemple #25
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)
Exemple #26
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})'
Exemple #27
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)
Exemple #28
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()
Exemple #29
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())
Exemple #30
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})