class Gromacs_genconf(BaseGromacsCommand):
    """Wrapper around Gromacs genconf command
    http://manual.gromacs.org/archive/4.6.5/online/genconf.html"""

    #: Name of Gromacs genbox command
    name = ReadOnly('genconf')

    #: List of accepted flags for Gromacs genbox command
    flags = ReadOnly(['-f', '-o', '-trj', '-nbox'])
class Gromacs_genion(BaseGromacsCommand):
    """Wrapper around Gromacs genion command
    http://manual.gromacs.org/documentation/2018/onlinehelp/gmx-genion.html"""

    #: Name of Gromacs genion command
    name = ReadOnly('genion')

    #: List of accepted flags for Gromacs genion command
    flags = ReadOnly([
        '-s', '-n', '-p', '-o', '-np', '-pname', '-pq', '-nn', '-nname', '-nq',
        '-rmin', '-seed', '-conc'
    ])
class Gromacs_grompp(BaseGromacsCommand):
    """Wrapper around Gromacs grompp command
    http://manual.gromacs.org/documentation/2018/onlinehelp/gmx-grompp.html"""

    #: Name of Gromacs grompp command
    name = ReadOnly('grompp')

    #: List of accepted flags for Gromacs grompp command
    flags = ReadOnly([
        '-f', '-c', '-r', '-rb', '-n', '-p', '-t', '-e', '-ref', '-po', '-pp',
        '-o', '-idm', '-time', '-maxwarn'
    ])
class Gromacs_solvate(BaseGromacsCommand):
    """Wrapper around Gromacs solvate command
    http://manual.gromacs.org/documentation/2018/onlinehelp/gmx-solvate.html"""

    #: Name of Gromacs genbox command
    name = ReadOnly('solvate')

    #: List of accepted flags for Gromacs solvate command
    flags = ReadOnly([
        '-cp', '-cs', '-p', '-maxsol', '-o', '-box', '-radius', '-scale',
        '-shell', '-vel'
    ])
class Gromacs_insert_molecules(BaseGromacsCommand):
    """Wrapper around Gromacs insert-molecules command
    http://manual.gromacs.org/documentation/2018/onlinehelp/gmx-insert-molecules.html # noqa
    """

    #: Name of Gromacs genbox command
    name = ReadOnly('insert-molecules')

    #: List of accepted flags for Gromacs insert-molecules command
    flags = ReadOnly([
        '-f', '-ci', '-ip', '-n', '-o', '-replace', '-sf', '-selfrpos', '-box',
        '-nmol', '-try', '-seed', '-radius', '-scale', '-dr', '-rot'
    ])
class Gromacs_genbox(BaseGromacsCommand):
    """Wrapper around Gromacs genbox command
    http://manual.gromacs.org/archive/4.6.5/online/genbox.html"""

    #: Name of Gromacs executable
    executable = ReadOnly('')

    #: Name of Gromacs genbox command
    name = ReadOnly('genbox')

    #: List of accepted flags for Gromacs genbox command
    flags = ReadOnly(
        ['-cp', '-cs', '-ci', '-maxsol', '-o', '-box', '-try', '-nmol'])
Пример #7
0
class WorkflowWriter(HasStrictTraits):
    """A Writer for writing the Workflow onto disk.
    """

    version = ReadOnly("1.1")

    def write(self, workflow, path, *, mode="w"):
        """Writes the workflow model object to a file f in JSON format.

        Parameters
        ----------
        workflow: Workflow
            The Workflow instance to write to file

        path: string
            A path string of the file on which to write the workflow

        mode: string
            file open mode, "w" by default to write
        """
        data = {
            "version": self.version,
            "workflow": self.get_workflow_data(workflow),
        }

        with open(path, mode) as f:
            json.dump(data, f, indent=4)

    def get_workflow_data(self, workflow):
        """ Public method to get a serialized form of workflow"""
        return workflow.__getstate__()
class Gromacs_trjconv(BaseGromacsCommand):
    """Wrapper around Gromacs trjconv command
    http://manual.gromacs.org/documentation/2019/onlinehelp/gmx-trjconv.html"""

    #: Name of Gromacs trjconv command
    name = ReadOnly('trjconv')

    #: List of accepted flags for Gromacs genion command
    flags = ReadOnly([
        '-f', '-s', '-n', '-fr', '-sub', '-drop', '-o', '-b', '-e', '-tu',
        '-w', '-now', '-xvg', '-skip', '-dt', 'round', '-noround', '-dump',
        '-timestep', '-pbc', '-ur', '-centre', '-nocentre', '-boxcenter',
        '-box', '-trans', '-shift', '-fit', '-ndec', 'vel', '-novel', '-force',
        '-noforce', '-trunc', '-exec', '-split', '-sep', '-nosep', '-nzero',
        '-dropunder', '-dropover', '-conect', '-noconect'
    ])
Пример #9
0
class ObjectWithReadOnlyText(HasTraits):
    """ A dummy object that set the readonly trait in __init__

    There exists such usage in TraitsUI.
    """

    text = ReadOnly()

    def __init__(self, text, **traits):
        self.text = text
        super(ObjectWithReadOnlyText, self).__init__(**traits)
class Gromacs_mdrun(BaseGromacsCommand):
    """Wrapper around Gromacs mdrun command
    http://manual.gromacs.org/documentation/2018/onlinehelp/gmx-mdrun.html

    Extra boolean attribute `mpi_run` signals whether to perform a
    simulation using MPI parallel processing (default is `False`). The number
    of cores can also be set using the `n_proc` attribute (default is `1`).

    Example
    ------
    Calling simulation run in series:
        md_run = Gromacs_mdrun()
    Calling a MPI run on 2 cores:
        mpi_mdrun = Gromacs_mdrun(mpi_run=True, n_proc=2)
    """

    #: Whether or not to perform an MPI run
    mpi_run = Bool(False)

    #: Number of processors for MPI run
    n_proc = Int(1)

    #: Name of Gromacs mdrun command
    name = Property(Unicode, depends_on='mpi_run')

    #: List of accepted flags for Gromacs mdrun command
    flags = ReadOnly([
        '-s', '-g', '-e', '-o', '-x', '-c', '-cpo', '-cpi', '-rerun', '-ei',
        '-awh', '-mp', '-mn', '-cpnum', '-nocpnum', '-multidir', '-nsteps',
        '-maxh', '-nt'
    ])

    def _get_name(self):
        """Returns correct name syntax, depending on MPI run
        option and installation version"""
        if self.mpi_run and not self.executable:
            return "mdrun_mpi"
        return "mdrun"

    def _build_command(self):
        """Overloads build_command option to include shell mpirun
        command with processor count if running in parallel"""
        command = super()._build_command()
        if self.mpi_run:
            command = f"mpirun -np {self.n_proc} {command}"
        return command
class Gromacs_select(BaseGromacsCommand):
    """Wrapper around Gromacs select (or g_select) command
    http://manual.gromacs.org/documentation/2019/onlinehelp/gmx-select.html"""

    #: Name of Gromacs select command
    name = Property(Unicode, depends_on='executable')

    #: List of accepted flags for Gromacs select command
    flags = ReadOnly([
        '-f', '-s', '-n', '-os', '-oc', '-oi', '-on', '-om', '-of', '-ofpdb',
        '-olt', '-b', '-e', '-dt', 'tu', '-fgroup', '-xvg', '-rmpbc',
        '-normpbc', '-pbc', '-nppbc', '-sf', '-selrpos', '-seltype', '-select',
        '-norm', '-nonorm', '-resnr', '-pdbatoms', '-cumlt', '-nocumlt'
    ])

    def _get_name(self):
        """Returns correct name syntax, depending on installation
        version"""
        if self.executable == 'gmx':
            return 'select'
        else:
            return 'g_select'
Пример #12
0
class BaseFileReader(HasStrictTraits):
    """Class parses input files and returns data
    required for each molecular type listed.
    """

    # --------------------
    # Protected Attributes
    # --------------------

    #: Extension of accepted file types
    _ext = ReadOnly()

    #: Character representing a comment in file line
    _comment = ReadOnly()

    # ------------------
    #     Defaults
    # ------------------

    def __ext_default(self):
        """Default extension for this reader subclass"""
        raise NotImplementedError

    def __comment_default(self):
        """Default file comment character for this reader subclass"""
        raise NotImplementedError

    # ------------------
    #  Private Methods
    # ------------------

    def _check_file_types(self, file_path):
        """Raise exception if specified Gromacs file does not have
        expected format"""

        space_check = file_path.isspace()
        ext_check = not file_path.endswith(f'.{self._ext}')

        if space_check or ext_check:
            raise IOError('{} not a valid Gromacs file type'.format(file_path))

    def _read_file(self, file_path):
        """Simple file loader"""

        self._check_file_types(file_path)

        with open(file_path, 'r') as infile:
            file_lines = infile.readlines()

        return file_lines

    def _remove_comments(self, file_lines):
        """Removes comments and whitespace lines from parsed
        topology file"""

        # If no comments are allowed, return original file
        # lines
        if self._comment is None:
            return file_lines

        file_lines = [
            line.strip() for line in file_lines if not line.isspace()
            and not line.strip().startswith(self._comment)
        ]

        return file_lines

    def _get_data(self, file_lines):
        """Process data from a parsed Gromacs file"""
        raise NotImplementedError

    # ------------------
    #   Public Methods
    # ------------------

    def read(self, file_path):
        """Read file and return processed data"""
        raise NotImplementedError
Пример #13
0
class ShadowGroup(Group):
    """Corresponds to a Group object, but with all embedded Include
    objects resolved, and with all embedded Group objects replaced by
    corresponding ShadowGroup objects.
    """
    def __init__(self, shadow, **traits):
        # Set the 'shadow' trait before all others, to avoid exceptions
        # when setting those other traits.
        self.shadow = shadow
        super().__init__(**traits)

    # -------------------------------------------------------------------------
    # Trait definitions:
    # -------------------------------------------------------------------------

    #: Group object this is a "shadow" for
    shadow = ReadOnly()

    #: Number of ShadowGroups in **content**
    groups = ReadOnly()

    #: Name of the group
    id = ShadowDelegate

    #: User interface label for the group
    label = ShadowDelegate

    #: Default context object for group items
    object = ShadowDelegate

    #: Default style of items in the group
    style = ShadowDelegate

    #: Default docking style of items in the group
    dock = ShadowDelegate

    #: Default image to display on notebook tabs
    image = ShadowDelegate

    #: The theme to use for a DockWindow:
    dock_theme = ShadowDelegate

    #: Category of elements dragged from the view
    export = ShadowDelegate

    #: Spatial orientation of the group
    orientation = ShadowDelegate

    #: Layout style of the group
    layout = ShadowDelegate

    #: Should the group be scrollable along the direction of orientation?
    scrollable = ShadowDelegate

    #: The number of columns in the group
    columns = ShadowDelegate

    #: Should a border be drawn around group?
    show_border = ShadowDelegate

    #: Should labels be added to items in group?
    show_labels = ShadowDelegate

    #: Should labels be shown to the left of items (vs. the right)?
    show_left = ShadowDelegate

    #: Is group the initially selected page?
    selected = ShadowDelegate

    #: Should the group use extra space along its parent group's layout
    #: orientation?
    springy = ShadowDelegate

    #: Optional help text (for top-level group)
    help = ShadowDelegate

    #: Pre-condition for defining the group
    defined_when = ShadowDelegate

    #: Pre-condition for showing the group
    visible_when = ShadowDelegate

    #: Pre-condition for enabling the group
    enabled_when = ShadowDelegate

    #: Amount of padding to add around each item
    padding = ShadowDelegate

    #: Style sheet for the panel
    style_sheet = ShadowDelegate

    def get_content(self, allow_groups=True):
        """Returns the contents of the Group within a specified context for
        building a user interface.

        This method makes sure that all Group types are of the same type (i.e.,
        Group or Item) and that all Include objects have been replaced by their
        substituted values.
        """
        # Make a copy of the content:
        result = self.content[:]

        # If result includes any ShadowGroups and they are not allowed,
        # replace them:
        if self.groups != 0:
            if not allow_groups:
                i = 0
                while i < len(result):
                    value = result[i]
                    if isinstance(value, ShadowGroup):
                        items = value.get_content(False)
                        result[i:i + 1] = items
                        i += len(items)
                    else:
                        i += 1
            elif (self.groups != len(result)) and (self.layout == "normal"):
                items = []
                content = []
                for item in result:
                    if isinstance(item, ShadowGroup):
                        self._flush_items(content, items)
                        content.append(item)
                    else:
                        items.append(item)
                self._flush_items(content, items)
                result = content

        # Return the resulting list of objects:
        return result

    def get_id(self):
        """Returns an ID for the group."""
        if self.id != "":
            return self.id

        return ":".join([item.get_id() for item in self.get_content()])

    def set_container(self):
        """Sets the correct container for the content."""
        pass

    def _flush_items(self, content, items):
        """Creates a sub-group for any items contained in a specified list."""
        if len(items) > 0:
            content.append(
                # Set shadow before hand to prevent delegation errors
                ShadowGroup(shadow=self.shadow).trait_set(
                    groups=0,
                    label="",
                    show_border=False,
                    content=items,
                    show_labels=self.show_labels,
                    show_left=self.show_left,
                    springy=self.springy,
                    orientation=self.orientation,
                ))
            del items[:]

    def __repr__(self):
        """Returns a "pretty print" version of the Group."""
        return repr(self.shadow)
Пример #14
0
class ImageData(AbstractDataSource):
    """
    Represents a grid of data to be plotted using a Numpy 2-D grid.

    The data array has dimensions NxM, but it may have more than just 2
    dimensions.  The appropriate dimensionality of the value array depends
    on the context in which the ImageData instance will be used.
    """
    # The dimensionality of the data.
    dimension = ReadOnly(DimensionTrait('image'))

    # Depth of the values at each i,j. Values that are used include:
    #
    # * 3: color images, without alpha channel
    # * 4: color images, with alpha channel
    value_depth = Int(1)  # TODO: Modify ImageData to explicitly support scalar
    # value arrays, as needed by CMapImagePlot

    # Holds the grid data that forms the image.  The shape of the array is
    # (N, M, D) where:
    #
    # * D is 1, 3, or 4.
    # * N is the length of the y-axis.
    # * M is the length of the x-axis.
    #
    # Thus, data[0,:,:] must be the first row of data.  If D is 1, then
    # the array must be of type float; if D is 3 or 4, then the array
    # must be of type uint8.
    #
    # NOTE: If this ImageData was constructed with a transposed data array,
    # then internally it is still transposed (i.e., the x-axis is the first axis
    # and the y-axis is the second), and the **data** array property might not be
    # contiguous.  If contiguousness is required and calling copy() is too
    # expensive, use the **raw_value** attribute. Also note that setting this
    # trait does not change the value of **transposed**,
    # so be sure to set it to its proper value when using the same ImageData
    # instance interchangeably to store transposed and non-transposed data.
    data = Property(ImageTrait)

    # Is **raw_value**, the actual underlying image data
    # array, transposed from **value**? (I.e., does the first axis correspond to
    # the x-direction and the second axis correspond to the y-direction?)
    #
    # Rather than transposing or swapping axes on the data and destroying
    # continuity, this class exposes the data as both **value** and **raw_value**.
    transposed = Bool(False)

    # A read-only attribute that exposes the underlying array.
    raw_value = Property(ImageTrait)

    #------------------------------------------------------------------------
    # Private traits
    #------------------------------------------------------------------------

    # The actual image data array.  Can be MxN or NxM, depending on the value
    # of **transposed**.
    _data = ImageTrait

    # Is the bounds cache valid? If False, it needs to be computed.
    _bounds_cache_valid = Bool(False)

    # Cached value of min and max as long as **data** doesn't change.
    _bounds_cache = Tuple

    #------------------------------------------------------------------------
    # Public methods
    #------------------------------------------------------------------------

    @classmethod
    def fromfile(cls, filename):
        """ Alternate constructor to create an ImageData from an image file
        on disk. 'filename' may be a file path or a file object.
        """

        from kiva.image import Image
        img = Image(filename)
        imgdata = cls(data=img.bmp_array, transposed=False)
        fmt = img.format()

        if fmt == "rgb24":
            imgdata.value_depth = 3
        elif fmt == "rgba32":
            imgdata.value_depth = 4
        else:
            raise ValueError("Unknown image format in file %s: %s" %
                             (filename, fmt))
        return imgdata

    def get_width(self):
        """ Returns the shape of the x-axis.
        """
        if self.transposed:
            return self._data.shape[0]
        else:
            return self._data.shape[1]

    def get_height(self):
        """ Returns the shape of the y-axis.
        """
        if self.transposed:
            return self._data.shape[1]
        else:
            return self._data.shape[0]

    def get_array_bounds(self):
        """ Always returns ((0, width), (0, height)) for x-bounds and y-bounds.
        """
        if self.transposed:
            b = ((0, self._data.shape[0]), (0, self._data.shape[1]))
        else:
            b = ((0, self._data.shape[1]), (0, self._data.shape[0]))
        return b

    #------------------------------------------------------------------------
    # Datasource interface
    #------------------------------------------------------------------------

    def get_data(self):
        """ Returns the data for this data source.

        Implements AbstractDataSource.
        """
        return self.data

    def is_masked(self):
        """is_masked() -> False

        Implements AbstractDataSource.
        """
        return False

    def get_bounds(self):
        """ Returns the minimum and maximum values of the data source's data.

        Implements AbstractDataSource.
        """
        if not self._bounds_cache_valid:
            if self.raw_value.size == 0:
                self._cached_bounds = (0, 0)
            else:
                self._cached_bounds = (nanmin(self.raw_value),
                                       nanmax(self.raw_value))
            self._bounds_cache_valid = True
        return self._cached_bounds

    def get_size(self):
        """get_size() -> int

        Implements AbstractDataSource.
        """
        if self._data is not None and self._data.shape[0] != 0:
            return self._data.shape[0] * self._data.shape[1]
        else:
            return 0

    def set_data(self, data):
        """ Sets the data for this data source.

        Parameters
        ----------
        data : array
            The data to use.
        """
        self._set_data(data)

    #------------------------------------------------------------------------
    # Private methods
    #------------------------------------------------------------------------

    def _get_data(self):
        if self.transposed:
            return swapaxes(self._data, 0, 1)
        else:
            return self._data

    def _set_data(self, newdata):
        self._data = newdata
        self._bounds_cache_valid = False
        self.data_changed = True

    def _get_raw_value(self):
        return self._data

    #------------------------------------------------------------------------
    # Event handlers
    #------------------------------------------------------------------------

    def _metadata_changed(self, event):
        self.metadata_changed = True

    def _metadata_items_changed(self, event):
        self.metadata_changed = True
Пример #15
0
class PointDataSource(ArrayDataSource):
    """ A data source representing a (possibly unordered) set of (X,Y) points.

    This is internally always represented by an Nx2 array, so that data[i]
    refers to a single point (represented as a length-2 array).

    Most of the traits and methods of ArrayDataSeries work for the
    PointDataSeries as well, since its data is linear.  This class
    overrides only the methods and traits that are different.

    """

    # The dimensionality of the indices into this data source (overrides
    # ArrayDataSource).
    index_dimension = ReadOnly('scalar')

    # The dimensionality of the value at each index point (overrides
    # ArrayDataSource).
    value_dimension = ReadOnly('point')

    # The sort order of the data. Although sort order is less common with point
    # data, it can be useful in case where the value data is sorted along some
    # axis.  Note that **sort_index** is used only if **sort_order** is not
    # 'none'.
    sort_order = SortOrderTrait

    # Which of the value axes the **sort_order** refers to.
    # If **sort_order** is 'none', this attribute is ignored.
    # In the unlikely event that the value data is sorted along both
    # X and Y (i.e., monotonic in both axes), then set **sort_index** to
    # whichever one has the best binary-search performance for hit-testing.
    sort_index = Enum(0, 1)

    #------------------------------------------------------------------------
    # Private traits
    #------------------------------------------------------------------------

    # The actual data (overrides ArrayDataSource).
    _data = PointTrait

    # Cached values of min and max as long as **_data** doesn't change
    # (overrides ArrayDataSource). ((min_x, max_x), (min_y, max_y))
    _cached_bounds = Tuple

    # These return lists of all the x and y positions, respectively

    # List of X positions.
    _xdata = Property
    # List of Y positions.
    _ydata = Property

    #------------------------------------------------------------------------
    # AbstractDataSource interface
    #------------------------------------------------------------------------

    def __init__(self, data=transpose(array([[], []])), **kw):
        shape = data.shape
        if (len(shape) != 2) or (shape[1] != 2):
            raise RuntimeError, "PointDataSource constructor requires Nx2 array, but got array of shape " + str(
                shape) + " instead."
        super(PointDataSource, self).__init__(data, **kw)
        return

    def get_data(self):
        """ Returns the data for this data source, or (0.0, 0.0) if it has no
        data.

        Overrides ArryDataSource.
        """
        if self._data is not None:
            return self._data
        else:
            return (0.0, 0.0)

    def reverse_map(self, pt, index=0, outside_returns_none=True):
        """Returns the index of *pt* in the data source.

        Overrides ArrayDataSource.

        Parameters
        ----------
        pt : (x, y)
            value to find
        index : 0 or 1
            Which of the axes of *pt* the *sort_order* refers to.
        outside_returns_none : Boolean
            Whether the method returns None if *pt* is outside the range of
            the data source; if False, the method returns the value of the
            bound that *pt* is outside of, in the *index* dimension.

        """
        # reverse_map is of limited utility for a PointDataSeries and thus
        # we only perform reverse-mapping if the data is sorted along an axis.

        if self.sort_order == "none":
            # By default, only provide reverse_map if the value data is sorted
            # along one of its axes.
            raise NotImplementedError

        if index != 0 and index != 1:
            raise ValueError, "Index must be 0 or 1."

        # This basically reduces to a scalar data search along self.data[index].
        lowerleft, upperright = self._cached_bounds
        min_val = lowerleft[index]
        max_val = upperright[index]
        val = pt[index]
        if (val < min_val):
            if outside_returns_none:
                return None
            else:
                return self._min_index
        elif (val > max_val):
            if outside_returns_none:
                return None
            else:
                return self._max_index
        else:
            return reverse_map_1d(self._data[:, index], val, self.sort_order)

    #------------------------------------------------------------------------
    # Private methods
    #------------------------------------------------------------------------

    def _compute_bounds(self):
        """ Computes the minimum and maximum values of self._data.

        Overrides ArrayDataSource.
        """
        if len(self._data) == 0:
            self._cached_bounds = ((0.0, 0.0), (0.0, 0.0))
        elif len(self._data) == 1:
            x, y = self._data[0]
            self._cached_bounds = ((x, y), (x, y))
        else:
            # calculate the X and Y values independently
            x = self._data[:, 0]
            min_x = min(x)
            max_x = max(x)
            y = self._data[:, 1]
            min_y = min(y)
            max_y = max(y)
            self._cached_bounds = ((min_x, min_y), (max_x, max_y))
        return

    def _get__xdata(self):
        return ArrayDataSource(self._data[:, 0])

    def _get__ydata(self):
        return ArrayDataSource(self._data[:, 1])
Пример #16
0
class Deferred(HasTraits):
    """ A Deferred operations which will complete in the future.

    Usage:
    ------
    In an asynchronous method which would normally require you to accept a
    callback method, you can use the Deferred object to let callers add
    callbacks even after making the call, in fact even after the operation
    has finished.

    The following example illustrates the simplest use of a Future::

        def background_job():
            deferred = Deferred()
            # Some async job which takes a callback
            async_background_job(callback=lambda result: deferred.done(result))
            return deferred.promise()

        def on_job_finished(self, result):
            print result

        bg_job = background_job()
        # bg_job promise can be used add callbacks
        bg_job.on_done(on_job_finished)

    The advantages of this approach to passing callbacks are:
        - ability to add callbacks after the call has been made
        - ability to add callbacks even after the function has returned
        - pass around promise objects to let others add callacks for the job
          This can be useful for example to add a progress feature to
          an existing function which would have otherwise needed to add
          an extra progress_callback argument.

    The Deferred supports two dispatch mechanisms, "same" and "ui" if the
    ``dispatch`` trait is set to "ui" all attributes are set on the GUI thread
    and all callbacks are also called from the UI thread.

    Notes:
    ------
    Always return the promise() object for an operation to callers when using
    Deferred so that so that they can only add callbacks and not set result.

    """
    # `Deferred` Interface ####################################################
    def done(self, value):
        """ Complete the deferred with success and specified result.
            and set the progress to 1.0
        """
        if self.dispatch == 'ui':
            promise = self.promise
            set_trait_later(promise, '_result', value)
            set_trait_later(promise, '_progress', 1.0)
            set_trait_later(promise, '_status', 'done')
        else:
            with self.promise._lock:
                self.promise._result = value
                self.promise._progress = 1.0
                self.promise._status = 'done'

    def error(self, value):
        """ Complete the deferred with failure and specified result. """
        if self.dispatch == 'ui':
            promise = self.promise
            set_trait_later(promise, '_error', value)
            set_trait_later(promise, '_status', 'error')
        else:
            with self.promise._lock:
                self.promise._error = value
                self.promise._status = 'error'

    def progress(self, value):
        """ Set the progress of the operation (0 <= value <= 1). """
        if self.dispatch == 'ui':
            set_trait_later(self.promise, '_progress', value)
        else:
            with self.promise._lock:
                self.promise._progress = value

    # Traits ##################################################################

    # Dispatch all callbacks either in the same thread or in the UI thread.
    dispatch = Enum('same', 'ui')

    promise = ReadOnly(Instance(Promise))

    def _promise_default(self):
        return Promise(dispatch=self.dispatch)
Пример #17
0
class Editor(HasPrivateTraits):
    """ Represents an editing control for an object trait in a Traits-based
        user interface.
    """

    #: The UI (user interface) this editor is part of:
    ui = Instance("traitsui.ui.UI", clean_up=True)

    #: Full name of the object the editor is editing (e.g.
    #: 'object.link1.link2'):
    object_name = Str("object")

    #: The object this editor is editing (e.g. object.link1.link2):
    object = Instance(HasTraits, clean_up=True)

    #: The name of the trait this editor is editing (e.g. 'value'):
    name = ReadOnly()

    #: The context object the editor is editing (e.g. object):
    context_object = Property()

    #: The extended name of the object trait being edited. That is,
    #: 'object_name.name' minus the context object name at the beginning. For
    #: example: 'link1.link2.value':
    extended_name = Property()

    #: Original value of object.name (e.g. object.link1.link2.value):
    old_value = Any(clean_up=True)

    #: Text description of the object trait being edited:
    description = ReadOnly()

    #: The Item object used to create this editor:
    item = Instance(Item, (), clean_up=True)

    #: The GUI widget defined by this editor:
    control = Any(clean_up=True)

    #: The GUI label (if any) defined by this editor:
    label_control = Any(clean_up=True)

    #: Is the underlying GUI widget enabled?
    enabled = Bool(True)

    #: Is the underlying GUI widget visible?
    visible = Bool(True)

    #: Is the underlying GUI widget scrollable?
    scrollable = Bool(False)

    #: The EditorFactory used to create this editor:
    factory = Instance(EditorFactory, clean_up=True)

    #: Is the editor updating the object.name value?
    updating = Bool(False)

    #: Current value for object.name:
    value = Property()

    #: Current value of object trait as a string:
    str_value = Property()

    #: The trait the editor is editing (not its value, but the trait itself):
    value_trait = Property()

    #: The current editor invalid state status:
    invalid = Bool(False)

    # -- private trait definitions ------------------------------------------

    #: A set to track values being updated to prevent infinite recursion.
    _no_trait_update = Set(Str)

    #: A list of all values synchronized to.
    _user_to = List(Tuple(Any, Str, Callable))

    #: A list of all values synchronized from.
    _user_from = List(Tuple(Str, Callable))

    # ------------------------------------------------------------------------
    # Editor interface
    # ------------------------------------------------------------------------

    # -- Abstract methods ---------------------------------------------------

    def init(self, parent):
        """ Create and initialize the underlying toolkit widget.

        This method must be overriden by subclasses.  Implementations must
        ensure that the :attr:`control` trait is set to an appropriate
        toolkit object.

        Parameters
        ----------
        parent : toolkit control
            The parent toolkit object of the editor's toolkit objects.
        """
        raise NotImplementedError("This method must be overriden.")

    def update_editor(self):
        """ Updates the editor when the value changes externally to the editor.

        This should normally be overridden in a subclass.
        """
        pass

    def error(self, excp):
        """ Handles an error that occurs while setting the object's trait value.

        This should normally be overridden in a subclass.

        Parameters
        ----------
        excp : Exception
            The exception which occurred.
        """
        pass

    def set_focus(self):
        """ Assigns focus to the editor's underlying toolkit widget.

        This method must be overriden by subclasses.
        """
        raise NotImplementedError("This method must be overriden.")

    def string_value(self, value, format_func=None):
        """ Returns the text representation of a specified object trait value.

        This simply delegates to the factory's `string_value` method.
        Sub-classes may choose to override the default implementation.

        Parameters
        ----------
        value : any
            The value being edited.
        format_func : callable or None
            A function that takes a value and returns a string.
        """
        return self.factory.string_value(value, format_func)

    def restore_prefs(self, prefs):
        """ Restores saved user preference information for the editor.

        Editors with state may choose to override this. It will only be used
        if the editor has an `id` value.

        Parameters
        ----------
        prefs : dict
            A dictionary of preference values.
        """
        pass

    def save_prefs(self):
        """ Returns any user preference information for the editor.

        Editors with state may choose to override this. It will only be used
        if the editor has an `id` value.

        Returns
        -------
        prefs : dict or None
            A dictionary of preference values, or None if no preferences to
            be saved.
        """
        return None

    # -- Editor life-cycle methods ------------------------------------------

    def prepare(self, parent):
        """ Finish setting up the editor.

        Parameters
        ----------
        parent : toolkit control
            The parent toolkit object of the editor's toolkit objects.
        """
        name = self.extended_name
        if name != "None":
            self.context_object.on_trait_change(self._update_editor,
                                                name,
                                                dispatch="ui")
        self.init(parent)
        self._sync_values()
        self.update_editor()

    def dispose(self):
        """ Disposes of the contents of an editor.

        This disconnects any synchronised values and resets references
        to other objects.

        Subclasses may chose to override this method to perform additional
        clean-up.
        """
        if self.ui is None:
            return

        name = self.extended_name
        if name != "None":
            self.context_object.on_trait_change(self._update_editor,
                                                name,
                                                remove=True)

        for name, handler in self._user_from:
            self.on_trait_change(handler, name, remove=True)

        for object, name, handler in self._user_to:
            object.on_trait_change(handler, name, remove=True)

        # Break linkages to references we no longer need:
        for name in self.trait_names(clean_up=True):
            setattr(self, name, None)

    # -- Undo/redo methods --------------------------------------------------

    def log_change(self, undo_factory, *undo_args):
        """ Logs a change made in the editor with undo/redo history.

        Parameters
        ----------
        undo_factory : callable
            Callable that creates an undo item.  Often self.get_undo_item.
        *undo_args
            Any arguments to pass to the undo factory.
        """
        ui = self.ui

        # Create an undo history entry if we are maintaining a history:
        undoable = ui._undoable
        if undoable >= 0:
            history = ui.history
            if history is not None:
                item = undo_factory(*undo_args)
                if item is not None:
                    if undoable == history.now:
                        # Create a new undo transaction:
                        history.add(item)
                    else:
                        # Extend the most recent undo transaction:
                        history.extend(item)

    def get_undo_item(self, object, name, old_value, new_value):
        """ Creates an undo history entry.

        Can be overridden in a subclass for special value types.

        Parameters
        ----------
        object : HasTraits instance
            The object being modified.
        name : str
            The name of the trait that is to be changed.
        old_value : any
            The original value of the trait.
        new_value : any
            The new value of the trait.
        """
        return UndoItem(object=object,
                        name=name,
                        old_value=old_value,
                        new_value=new_value)

    # -- Trait synchronization code -----------------------------------------

    def sync_value(
        self,
        user_name,
        editor_name,
        mode="both",
        is_list=False,
        is_event=False,
    ):
        """ Synchronize an editor trait and a user object trait.

        Also sets the initial value of the editor trait from the
        user object trait (for modes 'from' and 'both'), and the initial
        value of the user object trait from the editor trait (for mode
        'to'), as long as the relevant traits are not events.

        Parameters
        ----------
        user_name : str
            The name of the trait to be used on the user object. If empty, no
            synchronization will be set up.
        editor_name : str
            The name of the relevant editor trait.
        mode : str, optional; one of 'to', 'from' or 'both'
            The direction of synchronization. 'from' means that trait changes
            in the user object should be propagated to the editor. 'to' means
            that trait changes in the editor should be propagated to the user
            object. 'both' means changes should be propagated in both
            directions. The default is 'both'.
        is_list : bool, optional
            If true, synchronization for item events will be set up in
            addition to the synchronization for the object itself.
            The default is False.
        is_event : bool, optional
            If true, this method won't attempt to initialize the user
            object or editor trait values. The default is False.
        """
        if user_name == "":
            return

        key = "%s:%s" % (user_name, editor_name)

        parts = user_name.split(".")
        if len(parts) == 1:
            user_object = self.context_object
            xuser_name = user_name
        else:
            user_object = self.ui.context[parts[0]]
            xuser_name = ".".join(parts[1:])
            user_name = parts[-1]

        if mode in {"from", "both"}:
            self._bind_from(key, user_object, xuser_name, editor_name, is_list)

            if not is_event:
                # initialize editor value from user value
                with self.raise_to_debug():
                    user_value = xgetattr(user_object, xuser_name)
                    setattr(self, editor_name, user_value)

        if mode in {"to", "both"}:
            self._bind_to(key, user_object, xuser_name, editor_name, is_list)

            if mode == "to" and not is_event:
                # initialize user value from editor value
                with self.raise_to_debug():
                    editor_value = xgetattr(self, editor_name)
                    xsetattr(user_object, xuser_name, editor_value)

    # -- Utility methods -----------------------------------------------------

    def parse_extended_name(self, name):
        """ Extract the object, name and a getter from an extended name

        Parameters
        ----------
        name : str
            The extended name to parse.

        Returns
        -------
        object, name, getter : any, str, callable
            The object from the context, the (extended) name of the
            attributes holding the value, and a callable which gets the
            current value from the context.
        """
        base_name, __, name = name.partition(".")
        if name:
            object = self.ui.context[base_name]
        else:
            name = base_name
            object = self.context_object

        return (object, name, partial(xgetattr, object, name))

    # -- Utility context managers --------------------------------------------

    @contextmanager
    def no_trait_update(self, name):
        """ Context manager that blocks updates from the named trait. """
        if name in self._no_trait_update:
            yield
            return

        self._no_trait_update.add(name)
        try:
            yield
        finally:
            self._no_trait_update.remove(name)

    @contextmanager
    def raise_to_debug(self):
        """ Context manager that uses raise to debug to raise exceptions. """
        try:
            yield
        except Exception:
            from traitsui.api import raise_to_debug

            raise_to_debug()

    @contextmanager
    def updating_value(self):
        """ Context manager to handle updating value. """
        if self.updating:
            yield
            return

        self.updating = True
        try:
            yield
        finally:
            self.updating = False

    # ------------------------------------------------------------------------
    # object interface
    # ------------------------------------------------------------------------

    def __init__(self, parent, **traits):
        """ Initializes the editor object.
        """
        super(HasPrivateTraits, self).__init__(**traits)
        try:
            self.old_value = getattr(self.object, self.name)
        except AttributeError:
            ctrait = self.object.base_trait(self.name)
            if ctrait.type == "event" or self.name == "spring":
                # Getting the attribute will fail for 'Event' traits:
                self.old_value = Undefined
            else:
                raise

        # Synchronize the application invalid state status with the editor's:
        self.sync_value(self.factory.invalid, "invalid", "from")

    # ------------------------------------------------------------------------
    # private methods
    # ------------------------------------------------------------------------

    def _update_editor(self, object, name, old_value, new_value):
        """ Performs updates when the object trait changes.

        This is designed to be used as a trait listener.
        """
        # If background threads have modified the trait the editor is bound to,
        # their trait notifications are queued to the UI thread. It is possible
        # that by the time the UI thread dispatches these events, the UI the
        # editor is part of has already been closed. So we need to check if we
        # are still bound to a live UI, and if not, exit immediately:
        if self.ui is None:
            return

        # If the notification is for an object different than the one actually
        # being edited, it is due to editing an item of the form:
        # object.link1.link2.name, where one of the 'link' objects may have
        # been modified. In this case, we need to rebind the current object
        # being edited:
        if object is not self.object:
            self.object = self.ui.get_extended_value(self.object_name)

        # If the editor has gone away for some reason, disconnect and exit:
        if self.control is None:
            self.context_object.on_trait_change(self._update_editor,
                                                self.extended_name,
                                                remove=True)
            return

        # Log the change that was made (as long as the Item is not readonly
        # or it is not for an event):
        if (self.item.style != "readonly"
                and object.base_trait(name).type != "event"):
            # Indicate that the contents of the UI have been changed:
            self.ui.modified = True

            if self.updating:
                self.log_change(self.get_undo_item, object, name, old_value,
                                new_value)

        # If the change was not caused by the editor itself:
        if not self.updating:
            # Update the editor control to reflect the current object state:
            self.update_editor()

    def _sync_values(self):
        """ Initialize and synchronize editor and factory traits

        Initializes and synchronizes (as needed) editor traits with the
        value of corresponding factory traits.  The name of the factory
        trait and the editor trait must match and the factory trait needs
        to have ``sync_value`` metadata set.  The strategy followed is:

        - for each factory trait with ``sync_value`` metadata:

          1.  if the value is a :class:`ContextValue` instance then
              call :meth:`sync_value` with the ``name`` from the
              context value.
          2.  if the trait has ``sync_name`` metadata, look at the
              referenced trait value and if it is a non-empty string
              then use this value as the name of the value in the
              context.
          3.  otherwise initialize the current value of the factory
              trait to the corresponding value of the editor.

        - synchronization mode in cases 1 and 2 is taken from the
          ``sync_value`` metadata of the editor trait first and then
          the ``sync_value`` metadata of the factory trait if that is
          empty.

        - if the value is a container type, then the `is_list` metadata
          is set to
        """
        factory = self.factory
        for name, trait in factory.traits(sync_value=not_none).items():
            value = getattr(factory, name)
            self_trait = self.trait(name)
            if self_trait.sync_value:
                mode = self_trait.sync_value
            else:
                mode = trait.sync_value
            if isinstance(value, ContextValue):
                self.sync_value(
                    value.name,
                    name,
                    mode,
                    bool(self_trait.is_list),
                    self_trait.type == "event",
                )
            elif (trait.sync_name is not None
                  and getattr(factory, trait.sync_name, "") != ""):
                # Note: this is implemented as a stepping stone from things
                # like ``low_name`` and ``high_name`` to using context values.
                sync_name = getattr(factory, trait.sync_name)
                self.sync_value(
                    sync_name,
                    name,
                    mode,
                    bool(self_trait.is_list),
                    self_trait.type == "event",
                )
            elif value is not Undefined:
                setattr(self, name, value)

    def _bind_from(self, key, user_object, xuser_name, editor_name, is_list):
        """ Bind trait change handlers from a user object to the editor.

        Parameters
        ----------
        key : str
            The key to use to guard against recursive updates.
        user_object : object
            The object in the TraitsUI context that is being bound.
        xuser_name: : str
            The extended name of the trait to be used on the user object.
        editor_name : str
            The name of the relevant editor trait.
        is_list : bool, optional
            If true, synchronization for item events will be set up in
            addition to the synchronization for the object itself.
            The default is False.
        """
        def user_trait_modified(new):
            if key not in self._no_trait_update:
                with self.no_trait_update(key), self.raise_to_debug():
                    xsetattr(self, editor_name, new)

        user_object.on_trait_change(user_trait_modified, xuser_name)
        self._user_to.append((user_object, xuser_name, user_trait_modified))

        if is_list:

            def user_list_modified(event):
                if (isinstance(event, TraitListEvent)
                        and key not in self._no_trait_update):
                    with self.no_trait_update(key), self.raise_to_debug():
                        n = event.index
                        getattr(self,
                                editor_name)[n:n +
                                             len(event.removed)] = event.added

            items = xuser_name + "_items"
            user_object.on_trait_change(user_list_modified, items)
            self._user_to.append((user_object, items, user_list_modified))

    def _bind_to(self, key, user_object, xuser_name, editor_name, is_list):
        """ Bind trait change handlers from a user object to the editor.

        Parameters
        ----------
        key : str
            The key to use to guard against recursive updates.
        user_object : object
            The object in the TraitsUI context that is being bound.
        xuser_name: : str
            The extended name of the trait to be used on the user object.
        editor_name : str
            The name of the relevant editor trait.
        is_list : bool, optional
            If true, synchronization for item events will be set up in
            addition to the synchronization for the object itself.
            The default is False.
        """
        def editor_trait_modified(new):
            if key not in self._no_trait_update:
                with self.no_trait_update(key), self.raise_to_debug():
                    xsetattr(user_object, xuser_name, new)

        self.on_trait_change(editor_trait_modified, editor_name)

        self._user_from.append((editor_name, editor_trait_modified))

        if is_list:

            def editor_list_modified(event):
                if key not in self._no_trait_update:
                    with self.no_trait_update(key), self.raise_to_debug():
                        n = event.index
                        value = xgetattr(user_object, xuser_name)
                        value[n:n + len(event.removed)] = event.added

            self.on_trait_change(editor_list_modified, editor_name + "_items")
            self._user_from.append(
                (editor_name + "_items", editor_list_modified))

    def __set_value(self, value):
        """ Set the value of the trait the editor is editing.

        This calls the appropriate setattr method on the handler to perform
        the actual change.
        """
        with self.updating_value():
            try:
                handler = self.ui.handler
                obj_name = self.object_name
                name = self.name
                method = (getattr(handler, "%s_%s_setattr" %
                                  (obj_name, name), None)
                          or getattr(handler, "%s_setattr" % name, None)
                          or getattr(handler, "setattr"))
                method(self.ui.info, self.object, name, value)
            except TraitError as excp:
                self.error(excp)
                raise

    # -- Traits property getters and setters --------------------------------

    @cached_property
    def _get_context_object(self):
        """ Returns the context object the editor is using

        In some cases a proxy object is edited rather than an object directly
        in the context, in which case we return ``self.object``.
        """
        object_name = self.object_name
        context_key = object_name.split(".", 1)[0]
        if (object_name != "") and (context_key in self.ui.context):
            return self.ui.context[context_key]

        # This handles the case of a 'ListItemProxy', which is not in the
        # ui.context, but is the editor 'object':
        return self.object

    @cached_property
    def _get_extended_name(self):
        """ Returns the extended trait name being edited.
        """
        return ("%s.%s" % (self.object_name, self.name)).split(".", 1)[1]

    def _get_value_trait(self):
        """ Returns the trait the editor is editing (Property implementation).
        """
        return self.object.trait(self.name)

    def _get_value(self):
        """ Returns the value of the trait the editor is editing.
        """
        return getattr(self.object, self.name, Undefined)

    def _set_value(self, value):
        """ Set the value of the trait the editor is editing.

        Dispatches via the TraitsUI Undo/Redo mechanisms to make change
        reversible, if desired.
        """
        if self.ui and self.name != "None":
            self.ui.do_undoable(self.__set_value, value)

    def _get_str_value(self):
        """ Returns the text representation of the object trait.
        """
        return self.string_value(getattr(self.object, self.name, Undefined))