Ejemplo n.º 1
0
 def __fill_basics(obj, intr):
     label = get(obj.trait.inits.kwd, 'label', obj.trait.name)
     if not label:
         label = obj.trait.name
     intr.update({
         'default': (obj.value or obj.trait.value) if hasattr(obj, 'value') else obj.trait.value,
         'description': get(obj.trait.inits.kwd, 'doc'),
         'label': label.capitalize(),
         'name': obj.trait.name,
         'locked': obj.trait.inits.kwd.get('locked', False),
         'required': obj.trait.inits.kwd.get('required', True)
     })
Ejemplo n.º 2
0
 def __get_basics(obj):
     label = get(obj.trait.inits.kwd, 'label', obj.trait.name)
     if not label:
         label = obj.trait.name
     default = (obj.value or obj.trait.value) if hasattr(
         obj, 'value') else obj.trait.value
     description = get(obj.trait.inits.kwd, 'doc')
     label = label.capitalize()
     name = obj.trait.name
     locked = obj.trait.inits.kwd.get('locked', False)
     required = obj.trait.inits.kwd.get('required', True)
     return name, label, description, default, required, locked
Ejemplo n.º 3
0
    def __handle_nonmapped_subtypes(ownr, obj, intr):
        """ Populate options for each subtype. This fills in models etc"""
        for opt in TYPE_REGISTER.subclasses(
                ownr, KWARG_AVOID_SUBCLASSES in obj.trait.inits.kwd):
            if hasattr(obj, 'value') and obj.value is not None and isinstance(
                    obj.value, opt):
                ## fill option currently selected with attributes from instance
                opt = obj.value
                opt_class = opt.__class__
            else:
                opt_class = opt
            opt.trait.bound = INTERFACE_ATTRIBUTES_ONLY

            description = multiline_math_directives_to_matjax(
                opt_class.__doc__)

            intr['options'].append({
                'name':
                get(opt, '_ui_name', opt_class.__name__),
                'value':
                str_class_name(opt_class, short_form=True),
                'class':
                str_class_name(opt_class, short_form=False),
                'description':
                description,
                'attributes':
                opt.interface['attributes']
            })
Ejemplo n.º 4
0
 def __get__(self, inst, cls):
     """
     Called when an attribute of Type is retrieved on another class/instance.
     """
     if inst is None:
         return self
     if self.trait.bound:
         ### Return simple DB field or cached value
         return get(inst, '__' + self.trait.name, None)
     else:
         return self
Ejemplo n.º 5
0
 def __get__(self, inst, cls):
     """
     Called when an attribute of Type is retrieved on another class/instance.
     """
     if inst is None:
         return self
     if self.trait.bound:
         ### Return simple DB field or cached value
         return get(inst, '__' + self.trait.name, None)
     else:
         return self
Ejemplo n.º 6
0
    def _get_cached_data(self, inst):
        """
        Overwrite method from library mode array to read from storage when needed.
        """
        cached_data = get(inst, '__' + self.trait.name, None)

        if ((cached_data is None or cached_data.size == 0) and self.trait.file_storage != FILE_STORAGE_NONE
            and TvbProfile.current.TRAITS_CONFIGURATION.use_storage and inst.trait.use_storage
            and isinstance(inst, mapped.MappedTypeLight)):
            ### Data not already loaded, and storage usage
            cached_data = self._read_from_storage(inst)
            setattr(inst, '__' + self.trait.name, cached_data)

        ## Data already loaded, or no storage is used
        return cached_data
Ejemplo n.º 7
0
    def _get_cached_data(self, inst):
        """
        Overwrite method from library mode array to read from storage when needed.
        """
        cached_data = get(inst, '__' + self.trait.name, None)

        if ((cached_data is None or cached_data.size == 0) and self.trait.file_storage != FILE_STORAGE_NONE
            and TvbProfile.current.TRAITS_CONFIGURATION.use_storage and inst.trait.use_storage
            and isinstance(inst, mapped.MappedTypeLight)):
            ### Data not already loaded, and storage usage
            cached_data = self._read_from_storage(inst)
            setattr(inst, '__' + self.trait.name, cached_data)

        ## Data already loaded, or no storage is used
        return cached_data
Ejemplo n.º 8
0
    def __handle_nonmapped_subtypes(ownr, obj):
        """ Populate options for each subtype. This fills in models etc"""
        options = []
        for opt in TYPE_REGISTER.subclasses(
                ownr, KWARG_AVOID_SUBCLASSES in obj.trait.inits.kwd):
            if hasattr(obj, 'value') and obj.value is not None and isinstance(
                    obj.value, opt):
                ## fill option currently selected with attributes from instance
                opt = obj.value
                opt_class = opt.__class__
            else:
                opt_class = opt

            opt.trait.bound = INTERFACE_ATTRIBUTES_ONLY

            description = multiline_math_directives_to_matjax(
                opt_class.__doc__)
            name = get(opt, '_ui_name', opt_class.__name__)
            value = str_class_name(opt_class, short_form=True)
            type_ = str_class_name(opt_class, short_form=False)
            attributes = opt.interface_experimental
            options.append(
                itr.TypeNode(name, value, type_, description, attributes))
        return options
Ejemplo n.º 9
0
    def __new__(mcs, name, bases, dikt):
        """
        MetaType.__new__ creates a new class, but is typically involved
        *implicitly* either by declaring the __metaclass__ attribute

            class Type(object):
                __metaclass__ = MetaType

        or by subclassing Type:

            class Foo(Type):
                pass

        but in both cases, this method is called to produce the new class object.

        To setup a trait attribute, we :
            - check if it's a type, if so, instantiate
            - tell the attr it's name on owner class 
            - setup private attr with attr.value 
            - augment owner class doc-string with trait description 
            - add trait to information on class 
        """

        # if we're wrapping a class, pop that out
        wraps = dikt.pop('wraps', set([]))
        wraps_defaults = dikt.pop('defaults', ())

        # make new class
        newcls = super(MetaType, mcs).__new__(mcs, name, bases, dikt)
        # add new class to type register
        TYPE_REGISTER.append(newcls)

        # prep class doc string
        doc = get(dikt, '__doc__', 'traited class ' + name)
        doc += "\n    **traits on this class:**\n"

        # build traits info on newcls' attrs
        if hasattr(newcls, 'trait'):
            trait = newcls.trait.copy()
        else:
            trait = TraitsInfo(newcls)

        for key in filter(ispublic, dir(newcls)):
            attr = getattr(newcls, key)
            if isinstance(attr, MetaType) or isinstance(attr, Type):
                if isinstance(attr, MetaType):
                    attr = attr()
                try:
                    attr = deepcopy(attr)
                except Exception:
                    attr = copy(attr)
                attr.trait.name = key
                setattr(newcls, key, attr)
                doc += "\n\t``%s`` (%s)\n" % (
                    key, str(attr.trait.inits.kwd.get('label', "")))
                doc += "\t\t| %s\n" % str(attr.trait.inits.kwd.get(
                    'doc', "")).replace("\n", " ")
                doc += "\t\t| ``default``:  %s \n" % str(
                    attr.trait.inits.kwd.get('default', None)).replace(
                        "\n", " ")
                specified_range = attr.trait.inits.kwd.get('range', None)
                if specified_range:
                    doc += "\t\t| ``range``: low = %s ; high = %s \n\t\t\n" % (
                        str(specified_range.lo), str(specified_range.hi))
                trait[key] = attr

        # add info to new class
        if wraps:
            trait.wraps = wraps
        if wraps_defaults:
            trait.wraps_defaults = wraps_defaults
        newcls.trait = trait

        # bind traits unless told otherwise
        for attr in newcls.trait.itervalues():
            attr.trait.bound = attr.trait.inits.kwd.get('bind', True)

        newcls.__doc__ = doc
        return newcls
Ejemplo n.º 10
0
    def __get__(self, inst, ownr):

        obj = inst if inst else ownr
        if not obj.trait.bound:
            return {}

        label = get(obj.trait.inits.kwd, 'label', obj.trait.name)
        if not label:
            label = obj.trait.name
        intr = {'default': (obj.value or obj.trait.value) if hasattr(obj, 'value') else obj.trait.value,
                'description': get(obj.trait.inits.kwd, 'doc'),
                'label': self.label(label),
                'name': obj.trait.name,
                'locked': obj.trait.inits.kwd.get('locked', False),
                'required': obj.trait.inits.kwd.get('required', True)}

        range_value = obj.trait.inits.kwd.get('range', False)
        if range_value:
            intr['minValue'] = range_value.lo
            intr['maxValue'] = range_value.hi
            intr['stepValue'] = range_value.step
            
        noise_configurable = obj.trait.inits.kwd.get('configurable_noise', None)
        if noise_configurable is not None:
            intr['configurableNoise'] = noise_configurable

        if KWARG_FILTERS_UI in obj.trait.inits.kwd:
            intr[KWARG_FILTERS_UI] = json.dumps([ui_filter.to_dict() for ui_filter in
                                                 obj.trait.inits.kwd[KWARG_FILTERS_UI]])

        if hasattr(obj, 'dtype'):
            intr['elementType'] = getattr(obj, 'dtype')

        if get(obj.trait, 'wraps', False):
            if isinstance(obj.trait.wraps, tuple):
                intr['type'] = str(obj.trait.wraps[0].__name__)
            else:
                intr['type'] = str(obj.trait.wraps.__name__)

            if intr['type'] == 'dict' and isinstance(intr['default'], dict):
                intr['attributes'], intr['elementType'] = self.__prepare_dictionary(intr['default'])
                if len(intr['attributes']) < 1:
                    ## Dictionary without any sub-parameter
                    return {}

        ##### ARRAY specific processing ########################################
        if 'Array' in [str(i.__name__) for i in ownr.mro()]:
            intr['type'] = 'array'
            intr['elementType'] = str(inst.dtype)
            intr['quantifier'] = 'manual'
            if obj.trait.value is not None and isinstance(obj.trait.value, numpy.ndarray):
                # Make sure arrays are displayed in a compatible form: [1, 2, 3]
                intr['default'] = str(obj.trait.value.tolist())

        ##### TYPE & subclasses specifics ######################################
        elif ('Type' in [str(i.__name__) for i in ownr.mro()]
              and (obj.__module__ != 'tvb.basic.traits.types_basic'
                   or 'Range' in [str(i.__name__) for i in ownr.mro()])
              or 'Enumerate' in [str(i.__name__) for i in ownr.mro()]):

            # Populate Attributes for current entity
            attrs = sorted(getattr(obj, 'trait').values(), key=lambda entity: entity.trait.order_number)
            attrs = [val.interface for val in attrs if val.trait.order_number >= 0]
            attrs = [attr for attr in attrs if attr is not None and len(attr) > 0]
            intr['attributes'] = attrs

            if obj.trait.bound == INTERFACE_ATTRIBUTES_ONLY:
                # We need to do this, to avoid infinite loop on attributes 
                # of class Type with no subclasses
                return intr

            if obj.trait.select_multiple:
                intr['type'] = 'selectMultiple'
            else:
                intr['type'] = 'select'

            ##### MAPPED_TYPE specifics ############################################
            if 'MappedType' in [str(i.__name__) for i in ownr.mro()]:
                intr['datatype'] = True
                #### For simple DataTypes, cut options and attributes
                intr['options'] = []
                if not ownr._ui_complex_datatype:
                    intr['attributes'] = []
                    ownr_class = ownr.__class__
                else:
                    ownr_class = ownr._ui_complex_datatype
                if 'MetaType' in ownr_class.__name__:
                    ownr_class = ownr().__class__
                intr['type'] = ownr_class.__module__ + '.' + ownr_class.__name__

            else:
        ##### TYPE (not MAPPED_TYPE) again ####################################
                intr['attributes'] = []
                # Build options list
                intr['options'] = []
                if 'Enumerate' in obj.__class__.__name__:
                    for val in obj.trait.options:
                        intr['options'].append({'name': val,
                                                'value': val})
                    intr['default'] = obj.trait.value
                    return intr
                else:
                    for opt in TYPE_REGISTER.subclasses(ownr, KWARG_AVOID_SUBCLASSES in obj.trait.inits.kwd):
                        if hasattr(obj, 'value') and obj.value is not None and isinstance(obj.value, opt):
                            ## fill option currently selected with attributes from instance
                            opt = obj.value
                            opt_class = opt.__class__
                        else:
                            opt_class = opt
                        opt.trait.bound = INTERFACE_ATTRIBUTES_ONLY
                        intr['options'].append({'name': get(opt, '_ui_name', opt_class.__name__),
                                                'value': str_class_name(opt_class, short_form=True),
                                                'class': str_class_name(opt_class, short_form=False),
                                                'description': opt_class.__doc__,
                                                'attributes': opt.interface['attributes']})

            if intr['default'] is not None and intr['default'].__class__:
                intr['default'] = str(intr['default'].__class__.__name__)
                if intr['default'] == 'RandomState':
                    intr['default'] = 'RandomStream'
            else:
                intr['default'] = None

        return intr
Ejemplo n.º 11
0
 def _get_cached_data(self, inst):
     """
     Just read from instance since we don't have storage in library mode.
     """
     return get(inst, '__' + self.trait.name, None)
 def _get_cached_data(self, inst):
     """
     Just read from instance since we don't have storage in library mode.
     """
     return get(inst, '__' + self.trait.name, None)
Ejemplo n.º 13
0
    def __new__(mcs, name, bases, dikt):
        """
        MetaType.__new__ creates a new class, but is typically involved
        *implicitly* either by declaring the __metaclass__ attribute

            class Type(object):
                __metaclass__ = MetaType

        or by subclassing Type:

            class Foo(Type):
                pass

        but in both cases, this method is called to produce the new class object.

        To setup a trait attribute, we :
            - check if it's a type, if so, instantiate
            - tell the attr it's name on owner class 
            - setup private attr with attr.value 
            - augment owner class doc-string with trait description 
            - add trait to information on class 
        """

        # if we're wrapping a class, pop that out
        wraps = dikt.pop('wraps', set([]))
        wraps_defaults = dikt.pop('defaults', ())

        # make new class
        newcls = super(MetaType, mcs).__new__(mcs, name, bases, dikt)
        # add new class to type register
        TYPE_REGISTER.append(newcls)

        # prep class doc string
        doc = get(dikt, '__doc__', 'traited class ' + name)
        doc += "\n    **traits on this class:**\n"

        # build traits info on newcls' attrs
        if hasattr(newcls, 'trait'):
            trait = newcls.trait.copy()
        else:
            trait = TraitsInfo(newcls)

        for key in filter(ispublic, dir(newcls)):
            attr = getattr(newcls, key)
            if isinstance(attr, MetaType) or isinstance(attr, Type):
                if isinstance(attr, MetaType):
                    attr = attr()
                attr = deepcopy(attr)
                attr.trait.name = key
                setattr(newcls, key, attr)
                doc += "\n\t``%s`` (%s)\n" % (key, str(attr.trait.inits.kwd.get('label', "")))
                doc += "\t\t| %s\n" % str(attr.trait.inits.kwd.get('doc', "")).replace("\n", " ")
                doc += "\t\t| ``default``:  %s \n" % str(attr.trait.inits.kwd.get('default', None)).replace("\n", " ")
                specified_range = attr.trait.inits.kwd.get('range', None)
                if specified_range:
                    doc += "\t\t| ``range``: low = %s ; high = %s \n\t\t\n" % (str(specified_range.lo),
                                                                               str(specified_range.hi))
                trait[key] = attr

        # add info to new class
        if wraps:
            trait.wraps = wraps
        if wraps_defaults:
            trait.wraps_defaults = wraps_defaults
        newcls.trait = trait

        # bind traits unless told otherwise
        for attr in newcls.trait.itervalues():
            attr.trait.bound = attr.trait.inits.kwd.get('bind', True)

        newcls.__doc__ = doc
        return newcls