示例#1
0
    def _sync_view(self, name, object, metadata, direction):
        info = self.info
        for trait_name, trait in object.traits(**{metadata: is_str}).items():
            for sync in getattr(trait, metadata).split(","):
                try:
                    editor_id, editor_name = [
                        item.strip() for item in sync.split(".")
                    ]
                except:
                    raise TraitError(
                        "The '%s' metadata for the '%s' trait in "
                        "the '%s' context object should be of the form: "
                        "'id1.trait1[,...,idn.traitn]." %
                        (metadata, trait_name, name))

                editor = getattr(info, editor_id, None)
                if editor is not None:
                    editor.sync_value("%s.%s" % (name, trait_name),
                                      editor_name, direction)
                else:
                    raise TraitError(
                        "No editor with id = '%s' was found for "
                        "the '%s' metadata for the '%s' trait in the '%s' "
                        "context object." %
                        (editor_id, metadata, trait_name, name))
示例#2
0
    def validate_bounds(self, obj, name, value):
        """ Validate that the value is in range.

        .. note:: Any exceptions that may take place are converted to
            TraitErrors.

        """
        low, high = self.get_bounds(obj)
        if low is None:
            low = value
        if high is None:
            high = value
        
        is_inside_bounds = False
        try:
            is_inside_bounds = (low <= value <= high)
        except Exception as raised_exception:
            if isinstance(raised_exception, TraitError):
                raise raised_exception
            else:
                msg = ('Bound checking of {0} caused a the following Python '
                       'Exception: {1}'.format(value, raised_exception))
                raise TraitError(msg)
        
        if not is_inside_bounds:
            msg = ('The assigned date value must be bounded between {0} '
                   ' and {1}. Got {2} instead.'.format(low, high, value))
            raise TraitError(msg)

        return value
示例#3
0
 def get_ip_weights(self, int_triangles, int_order):
     '''Get the array of integration points'''
     gps = []
     points, triangles = int_triangles
     if triangles.shape[1] == 1:  # 0D - points
         if int_order == 1:
             gps.append(1.)
         else:
             raise TraitError('does not make sense')
     elif triangles.shape[1] == 2:  # 1D - lines
         if int_order == 1:
             for id in triangles:
                 r_pnt = points[ix_(id)]
                 J_det_ip = norm(r_pnt[1] - r_pnt[0]) * 0.5
                 gp = 2. * J_det_ip
                 gps.append(gp)
         elif int_order == 2:
             for id in triangles:
                 r_pnt = points[ix_(id)]
                 J_det_ip = norm(r_pnt[1] - r_pnt[0]) * 0.5
                 gps += J_det_ip, J_det_ip
         else:
             raise NotImplementedError
     elif triangles.shape[1] == 3:  # 2D - triangles
         if int_order == 1:
             for id in triangles:
                 r_pnt = points[ix_(id)]
                 J_det_ip = self._get_J_det_ip(r_pnt)
                 gp = 1. * J_det_ip
                 # print "gp ",gp
                 gps.append(gp)
         elif int_order == 2:
             raise NotImplementedError
         elif int_order == 3:
             for id in triangles:
                 r_pnt = points[ix_(id)]
                 J_det_ip = self._get_J_det_ip(r_pnt)
                 gps += -0.5625 * J_det_ip, \
                         0.52083333333333337 * J_det_ip, \
                         0.52083333333333337 * J_det_ip, \
                         0.52083333333333337 * J_det_ip
         elif int_order == 4:
             raise NotImplementedError
         elif int_order == 5:
             for id in triangles:
                 r_pnt = points[ix_(id)]
                 J_det_ip = self._get_J_det_ip(r_pnt)
                 gps += 0.225 * J_det_ip, 0.1323941527 * J_det_ip, \
                         0.1323941527 * J_det_ip, 0.1323941527 * J_det_ip, \
                         0.1259391805 * J_det_ip, 0.1259391805 * J_det_ip, \
                         0.1259391805 * J_det_ip
         else:
             raise NotImplementedError
     elif triangles.shape[1] == 4:  # 3D - tetrahedrons
         raise NotImplementedError
     else:
         raise TraitError('unsupported geometric form with %s nodes ' %
                          triangles.shape[1])
     return array(gps, dtype='float_')
示例#4
0
    def validate_name(self, name):
        """ Validate name against the known names and any_name flag.
        Returns name if validation passes.
        Raises TraitError otherwise.
        """
        name = name.strip()

        if self.any_name and len(name) == 0:
            raise TraitError('name must be specified')

        if not (self.any_name or name in self.known_names):
            raise TraitError('invalid name %s' % name)

        return name
示例#5
0
 def validate(self, object, name, value):
     """ Validates that the value is a valid font descriptor string.
     """
     try:
         point_size = family = style = weight = underline = ''
         facename = ['']
         for word in value.split():
             lword = word.lower()
             if lword in font_families:
                 family = ' ' + lword
             elif lword in font_styles:
                 style = ' ' + lword
             elif lword in font_weights:
                 weight = ' ' + lword
             elif lword == 'underline':
                 underline = ' ' + lword
             elif lword not in font_noise:
                 try:
                     int(lword)
                     point_size = lword + ' pt'
                 except:
                     facename.append(word)
         fontstr = ('%s%s%s%s%s%s' %
                    (point_size, family, style, weight, underline,
                     ' '.join(facename))).strip()
         return fontstr
     except Exception:
         pass
     raise TraitError(object, name, 'a font descriptor string', repr(value))
示例#6
0
    def __init__(self, editor):
        """Initializes the object."""
        super().__init__(editor=editor)

        # Set up the field width for each item:
        width = editor.factory.width

        # Set up the correct style for each filed:
        style = "simple"
        if editor.readonly:
            style = "readonly"

        # Get the array we are mirroring:
        object = editor.value

        # Determine the correct trait type to use for each element:
        trait = Float()

        if object.dtype.kind == "i":
            trait = Int()

        if len(object.shape) == 1:
            self.view = self._one_dim_view(object, style, width, trait)
        elif len(object.shape) == 2:
            self.view = self._two_dim_view(object, style, width, trait)
        else:
            raise TraitError("Only 1D or 2D arrays supported")
示例#7
0
    def setattr(self, info, object, name, value):
        """ Handles setting a specified object trait's value.

        Parameters
        ----------
        object : object
            The object whose attribute is being set
        name : string
            The name of the attribute being set
        value
            The value to which the attribute is being set
        """
        if not info.initialized:
            return

        if name == 'units':
            # Convert units label to units object.
            if not unit_manager.is_compatible(value, object.family_name):
                raise TraitError()

            value = unit_parser.parse_unit(value, suppress_warnings=False)

        super(QuantityViewHandler, self).setattr(info, object, name, value)

        return
示例#8
0
def str_cast_to_int(object, name, value):
    """ A function that validates the value is a str and then converts
    it to an int using its length.
    """
    if not isinstance(value, str):
        raise TraitError("Not a string!")
    return len(value)
示例#9
0
    def _get_field_data(self):

        if self.var_eval == None:
            return

        shape = self.field_arr.shape[1:]
        # print "shape ", self.var, " ",shape
        if shape == ():  # TODO: subdomain where all elems are dactivated
            return
        # recognize data type (1,) = scalar
        if shape == (2, 2):  # 2D tensor - transform to 3d and flatten
            ff = zeros((self.field_arr.shape[0], 3, 3), float_)
            ff[:, :2, :2] = self.field_arr
            field = ff.reshape(self.field_arr.shape[0], 9)
        elif shape == (3, 3):  # 3D tensor - flatten
            field = self.field_arr.reshape(self.field_arr.shape[0], 9)
        elif shape == (2, ):  # 2D vector - transform to 3d
            field = zeros((self.field_arr.shape[0], 3), float_)
            field[:, :2] = self.field_arr
        elif shape == (1, ) or shape == (3, ):
            field = self.field_arr  # is scalar or 3D vector  does not need treatment
        else:
            raise TraitError('wrong field format of tracer %s: %s' %
                             (self.var, shape))

        return field
示例#10
0
 def validate(self, object, name, value):
     """ Validates that the value is a valid font descriptor string.
     """
     try:
         point_size = family = style = weight = underline = ""
         facename = [""]
         for word in value.split():
             lword = word.lower()
             if lword in font_families:
                 family = " " + lword
             elif lword in font_styles:
                 style = " " + lword
             elif lword in font_weights:
                 weight = " " + lword
             elif lword == "underline":
                 underline = " " + lword
             elif lword not in font_noise:
                 try:
                     int(lword)
                     point_size = lword + " pt"
                 except:
                     facename.append(word)
         fontstr = ("%s%s%s%s%s%s" % (
             point_size,
             family,
             style,
             weight,
             underline,
             " ".join(facename),
         )).strip()
         return fontstr
     except Exception:
         pass
     raise TraitError(object, name, "a font descriptor string", repr(value))
示例#11
0
def str_to_font(object, name, value):
    "Converts a (somewhat) free-form string into a valid Font object."
    # FIXME: Make this less free-form and more well-defined.
    try:
        point_size = 10
        family = SWISS
        style = NORMAL
        weight = NORMAL
        underline = 0
        face_name = []
        for word in value.split():
            lword = word.lower()
            if lword in font_families:
                family = font_families[lword]
            elif lword in font_styles:
                style = font_styles[lword]
            elif lword in font_weights:
                weight = font_weights[lword]
            elif lword == 'underline':
                underline = 1
            elif lword not in font_noise:
                try:
                    point_size = int(lword)
                except:
                    face_name.append(word)
        return Font(face_name=" ".join(face_name),
                    size=point_size,
                    family=family,
                    weight=weight,
                    style=style,
                    underline=underline)
    except:
        pass
    raise TraitError(object, name, 'a font descriptor string', repr(value))
示例#12
0
    def __init__(self, *args, **traits):
        """ Map posiitonal arguments to traits.

        If one value is provided it is taken as the value for all sides.
        If two values are provided, then the first argument is used for
        left and right, while the second is used for top and bottom.
        If 4 values are provided, then the arguments are mapped to
        left, right, top, and bottom, respectively.
        """
        n = len(args)
        if n > 0:
            if n == 1:
                left = right = top = bottom = args[0]
            elif n == 2:
                left = right = args[0]
                top = bottom = args[1]
            elif n == 4:
                left, right, top, bottom = args
            else:
                raise TraitError("0, 1, 2 or 4 arguments expected, but %d "
                                 "specified" % n)
            traits.update({
                "left": left,
                "right": right,
                "top": top,
                "bottom": bottom
            })

        super().__init__(**traits)
示例#13
0
    def __init__(self, editor):
        """ Initializes the object.
        """
        # Save the reference to the editor:
        self.editor = editor

        # Set up the field width for each item:
        width = editor.factory.width

        # Set up the correct style for each filed:
        style = 'simple'
        if editor.readonly:
            style = 'readonly'

        # Get the array we are mirroring:
        object = editor.value

        # Determine the correct trait type to use for each element:
        trait = Float

        if object.dtype.type == 'i':
            trait = Int

        if len(object.shape) == 1:
            self.view = self._one_dim_view(object, style, width, trait)
        elif len(object.shape) == 2:
            self.view = self._two_dim_view(object, style, width, trait)
        else:
            raise TraitError('Only 1D or 2D arrays supported')
示例#14
0
def enum_values_changed(values):
    """ Recomputes the mappings for a new set of enumeration values.
    """

    if isinstance(values, dict):
        data = [(six.text_type(v), n) for n, v in values.items()]
        if len(data) > 0:
            data.sort(key=itemgetter(0))
            col = data[0][0].find(':') + 1
            if col > 0:
                data = [(n[col:], v) for n, v in data]
    elif not isinstance(values, SequenceTypes):
        handler = values
        if isinstance(handler, CTrait):
            handler = handler.handler
        if not isinstance(handler, BaseTraitHandler):
            raise TraitError("Invalid value for 'values' specified")
        if handler.is_mapped:
            data = [(six.text_type(n), n) for n in handler.map.keys()]
            data.sort(key=itemgetter(0))
        else:
            data = [(six.text_type(v), v) for v in handler.values]
    else:
        data = [(six.text_type(v), v) for v in values]

    names = [x[0] for x in data]
    mapping = {}
    inverse_mapping = {}
    for name, value in data:
        mapping[name] = value
        inverse_mapping[value] = name

    return (names, mapping, inverse_mapping)
示例#15
0
    def get_default_value(self):
        '''Take the default value'''

        keys = list(self.map.keys())
        if self._default_key == None:
            if len(keys) > 1:
                return (0, list(self.map.keys())[0])
            else:
                return (0, None)
                raise TraitError('invalid key, no entries in database extension %s' % \
                    (self.map.klass,))
        if self._default_key in keys:
            return (0, self._default_key)

        raise TraitError('assigned default value must be one of %s but a value of %s was received' % \
            (list(self.map.keys()), self._default_key))
示例#16
0
文件: image.py 项目: enthought/pyface
    def add_path(self, volume_name, path=None):
        """ Adds the directory specified by **path** as a *virtual* volume
            called **volume_name**. All image files contained within path
            define the contents of the volume. If **path** is None, the
            *images* contained in the 'images' subdirectory of the same
            directory as the caller are is used as the path for the *virtual*
            volume..
        """
        # Make sure we don't already have a volume with that name:
        if volume_name in self.catalog:
            raise TraitError(
                ("The volume name '%s' is already in the image " "library.")
                % volume_name
            )

        # If no path specified, derive one from the caller's source code
        # location:
        if path is None:
            path = join(get_resource_path(2), "images")

        # Make sure that the specified path is a directory:
        if not isdir(path):
            raise TraitError(
                "The image volume path '%s' does not exist." % path
            )

        # Create the ImageVolume to describe the path's contents:
        image_volume_path = join(path, "image_volume.py")
        if exists(image_volume_path):
            volume = get_python_value(read_file(image_volume_path), "volume")
        else:
            volume = ImageVolume()

        # Set up the rest of the volume information:
        volume.trait_set(name=volume_name, path=path, is_zip_file=False)

        # Try to bring the volume information up to date if necessary:
        if volume.time_stamp < time_stamp_for(stat(path)[ST_MTIME]):
            # Note that the save could fail if the volume is read-only, but
            # that's OK, because we're only trying to do the save in case
            # a developer had added or deleted some image files, which would
            # require write access to the volume:
            volume.save()

        # Add the new volume to the library:
        self.catalog[volume_name] = volume
        self.volumes.append(volume)
示例#17
0
    def validate(self, obj, name, value):
        validated_value = super(AbsFile, self).validate(obj, name, value)
        if validated_value and op.isabs(validated_value) and op.isfile(value):
            return validated_value
        elif not op.isfile(value):
            raise TraitError("The filepath does not exist.")

        self.error(obj, name, value)
示例#18
0
 def reset_polar_fn(self):
     if self.switched_on:
         if self.mats_eval.mfn_class == None:
             raise TraitError(
                 'No class for function representation specified')
         self.polar_fn = self.mats_eval.mfn_class()
     else:
         self.polar_fn = None
示例#19
0
 def post_setattr(self, object, name, value):
     val = self.mapped_value(value)
     try:
         setattr(object, name + '_', val)
     except:
         # We don't need a fancy error message, because this exception
         # should always be caught by a TraitCompound handler:
         raise TraitError('Unmappable')
示例#20
0
 def set_value(object, name, value):
     _name = DEnumHelper._init_listeners(object, name)
     trait = object.trait(name)
     values = super_getattr(object, trait.values_name)
     if value not in values:
         raise TraitError(object, name, "one of %s" % values, value)
     old = super_getattr(object, _name)
     super_setattr(object, _name, value)
     object.trait_property_changed(name, old, value)
示例#21
0
 def validate(self, object, name, value):
     ''' Set the trait value '''
     # first check if the value is a class
     if isinstance(value, type):
         klass = value
         if not klass in self._klasses:
             raise TraitError('type %s not in the type scope' % klass)
         # check if the last instance of the klass has been
         # registered earlier in the trait history
         new_value = klass()
     else:
         # the value must be one of those in _klasses
         if isinstance(value, tuple(self._klasses)):
             new_value = value
         else:
             raise TraitError('value of type %s out of the scope: %s' %
                              (value.__class__, self._klasses))
     return new_value
示例#22
0
def toolkit(*toolkits):
    """ Selects and returns a low-level GUI toolkit.

    Use this function to get a reference to the current toolkit.

    Parameters
    ----------
    *toolkits : strings
        Toolkit names to try if toolkit not already selected.  If not supplied,
        defaults to order in TraitUIToolkits variable.

    Returns
    -------
    toolkit
        Appropriate concrete Toolkit subclass for selected toolkit.
    """
    global _toolkit

    # If _toolkit has already been set, simply return it.
    if _toolkit is not None:
        return _toolkit

    if ETSConfig.toolkit:
        # If a toolkit has already been set for ETSConfig, then use it:
        _toolkit = _import_toolkit(ETSConfig.toolkit)
        return _toolkit
    else:
        if not toolkits:
            toolkits = TraitUIToolkits

        for toolkit_name in toolkits:
            try:
                with provisional_toolkit(toolkit_name):
                    _toolkit = _import_toolkit(toolkit_name)
                    return _toolkit
            except (AttributeError, ImportError) as exc:
                # import failed, reset toolkit to none, log error and try again
                msg = "Could not import traits UI backend '{0}'"
                logger.info(msg.format(toolkit_name))
                if logger.getEffectiveLevel() <= logging.INFO:
                    logger.exception(exc)
        else:
            # Try using the null toolkit and printing a warning
            try:
                with provisional_toolkit('null'):
                    _toolkit = _import_toolkit('null')
                    import warnings
                    msg = (
                        "Unable to import the '{0}' backend for traits UI; " +
                        "using the 'null' backend instead.")
                    warnings.warn(msg.format(toolkit_name), RuntimeWarning)
                    return _toolkit

            except ImportError as exc:
                logger.exception(exc)
                raise TraitError("Could not import any UI toolkit. Tried:" +
                                 ', '.join(toolkits))
示例#23
0
文件: image.py 项目: enthought/pyface
    def add_volume(self, file_name=None):
        """ If **file_name** is a file, it adds an image volume specified by
            **file_name** to the image library. If **file_name** is a
            directory, it adds all image libraries contained in the directory
            to the image library. If **file_name** is omitted, all image
            libraries located in the *images* directory contained in the same
            directory as the caller are added.
        """
        # If no file name was specified, derive a path from the caller's
        # source code location:
        if file_name is None:
            file_name = join(get_resource_path(2), "images")

        if isfile(file_name):
            # Load an image volume from the specified file:
            volume = self._add_volume(file_name)
            if volume is None:
                raise TraitError(
                    "'%s' is not a valid image volume." % file_name
                )

            if volume.name in self.catalog:
                self._duplicate_volume(volume.name)

            self.catalog[volume.name] = volume
            self.volumes.append(volume)

        elif isdir(file_name):
            # Load all image volumes from the specified path:
            catalog = self.catalog
            volumes = self._add_path(file_name)
            for volume in volumes:
                if volume.name in catalog:
                    self._duplicate_volume(volume.name)

                catalog[volume.name] = volume

            self.volumes.extend(volumes)
        else:
            # Handle an unrecognized argument:
            raise TraitError(
                "The add method argument must be None or a file "
                "or directory path, but '%s' was specified." % file_name
            )
示例#24
0
 def _get_filepath(self):
     if not self.is_pickled:
         fpath = self.specification.get('path', "")
     else:
         if not (self.is_mysql or self.is_postgresql):
             fpath = self.pickled_args['filepath_or_buffer']
         else:
             return ""
     if isinstance(fpath, list):
         for path in fpath:
             if not (op.exists(path) and op.isabs(path)):
                 raise TraitError("filepaths must be absolute.")
     elif isinstance(fpath, str):
         if not op.isabs(fpath):
             fpath = op.join(op.dirname(self.specfile), fpath)
         if not (self.is_mysql or self.is_postgresql):
             if not (op.exists(fpath) and op.isabs(fpath)):
                 raise TraitError("filepaths must be absolute.")
     return fpath
示例#25
0
 def _validate_impurity_concentrations(self, x):
     """ checks number of items in x equal to product_component_names
         in product
     """
     if len(x) != len(self.product.impurity_names):
         msg = ('impurity_concentrations should have same length as '
                'product.impurity_names')
         logger.exception(msg)
         raise TraitError(msg)
     return x
示例#26
0
文件: image.py 项目: enthought/pyface
 def _duplicate_volume(self, volume_name):
     """ Raises a duplicate volume name error.
     """
     raise TraitError(
         (
             "Attempted to add an image volume called '%s' when "
             "a volume with that name is already defined."
         )
         % volume_name
     )
示例#27
0
def find_toolkit(entry_point, toolkits=None, priorities=default_priorities):
    """ Find a toolkit that works.

    If ETSConfig is set, then attempt to find a matching toolkit.  Otherwise
    try every plugin for the entry_point until one works.  The ordering of the
    plugins is supplied via the priorities function which should be suitable
    for use as a sorting key function.  If all else fails, explicitly try to
    load the "null" toolkit backend.  If that fails, give up.

    Parameters
    ----------
    entry_point : str
        The name of the entry point that holds our toolkits.
    toolkits : collection of strings
        Only consider toolkits which match the given strings, ignore other
        ones.
    priorities : callable
        A callable function that returns an priority for each plugin.

    Returns
    -------
    toolkit : Toolkit instance
        A callable object that implements the Toolkit interface.

    Raises
    ------
    TraitError
        If no working toolkit is found.
    RuntimeError
        If no ETSConfig.toolkit is set but the toolkit cannot be loaded for
        some reason.
    """
    if ETSConfig.toolkit:
        return import_toolkit(ETSConfig.toolkit, entry_point)

    entry_points = [
        plugin for plugin in importlib_metadata.entry_points()[entry_point]
        if toolkits is None or plugin.name in toolkits
    ]
    for plugin in sorted(entry_points, key=priorities):
        try:
            with ETSConfig.provisional_toolkit(plugin.name):
                toolkit = plugin.load()
                return toolkit
        except (ImportError, AttributeError, RuntimeError) as exc:
            msg = "Could not load %s plugin %r from %r"
            module_name = plugin.value.split(":")[0]
            logger.info(msg, entry_point, plugin.name, module_name)
            logger.debug(exc, exc_info=True)

    # if all else fails, try to import the null toolkit.
    with ETSConfig.provisional_toolkit("null"):
        return import_toolkit("null", entry_point)

    raise TraitError("Could not import any {} toolkit.".format(entry_point))
示例#28
0
    def rset(self, valstr):
        """
        Set remote value from `valstr`.

        valstr: string
            Value to be set, in string form.
        """
        if self.iotype == 'out':
            raise TraitError("Can't set an output")
        self._client.set(self._rpath, valstr)
        self._valstr = valstr
示例#29
0
    def _set_max_date(self, date):
        """ Set the max_date. Addtional checks are applied to make sure
        that :attr:`min_date` < :attr:`max_date`

        """
        if date < self.min_date:
            msg = ("The maximum date should be larger than the current "
                   "minimum date({0}), but a value of {1} was given.")
            msg = msg.format(self.min_date, date)
            raise TraitError(msg)
        self._max_date = date
示例#30
0
文件: grid.py 项目: zijuzhang/chaco
def float_or_auto(val):
    """
    Validator function that returns *val* if *val* is either a number or
    the word 'auto'.  This is used as a validator for the text editor
    in the traits UI for the tick_interval trait.
    """
    try:
        return float(val)
    except:
        if isinstance(val, str) and val == "auto":
            return val
    raise TraitError("Tick interval must be a number or 'auto'.")