How to use kiwisolver - 10 common examples

To help you get started, we’ve selected a few kiwisolver examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nucleic / enaml / enaml / workbench / ui / menu_helper.py View on Github external
Parameters
    ----------
    nodes : list
        The list of PathNode objects which should be ordered. It
        is assumed that all nodes reside in the same group.

    Returns
    -------
    result : list
        The PathNode objects ordered according to the constraints
        specified by the 'before' and 'after' items attributes.

    """
    variables = {}
    for node in nodes:
        variables[node.id] = kiwi.Variable(str(node.id))

    prev_var = None
    constraints = []
    for node in nodes:
        this_var = variables[node.id]
        constraints.append(this_var >= 0)
        if prev_var is not None:  # weakly preserve relative order
            constraints.append((prev_var + 0.1 <= this_var) | 'weak')
        before = node.item.before
        if before:
            if before not in variables:
                msg = "item '%s' has invalid `before` reference '%s'"
                raise ValueError(msg % (node.path, before))
            target_var = variables[before]
            constraints.append((this_var + 0.1 <= target_var) | 'strong')
        after = node.item.after
github enthought / enable / enable / layout / constraints_namespace.py View on Github external
----------
        name : str
            The name of the constraint variable to return.

        """
        try:
            return super(ConstraintsNamespace, self).__getattr__(name)
        except AttributeError:
            pass

        constraints = self._constraints
        if name in constraints:
            res = constraints[name]
        else:
            label = '{0}|{1}|{2}'.format(self._name, self._owner, name)
            res = constraints[name] = Variable(label)
        return res
github enthought / enable / enable / layout / layout_helpers.py View on Github external
other_attrs = attrs[:]
            constraints = [
                getattr(self, attr) == getattr(component, other)
                for (attr, other) in zip(attrs, other_attrs)
            ]
        else:
            constraints = []

        # Create the row and column constraint variables along with
        # some default limits
        row_vars = []
        col_vars = []
        cn_id = self.constraints_id
        for idx in sm.range(num_rows + 1):
            name = 'row' + str(idx)
            var = Variable('{0}|{1}'.format(cn_id, name))
            row_vars.append(var)
            constraints.append(var >= 0)
        for idx in sm.range(num_cols + 1):
            name = 'col' + str(idx)
            var = Variable('{0}|{1}'.format(cn_id, name))
            col_vars.append(var)
            constraints.append(var >= 0)

        # Add some neighbor relations to the row and column vars.
        for r1, r2 in zip(row_vars[:-1], row_vars[1:]):
            constraints.append(r1 >= r2)
        for c1, c2 in zip(col_vars[:-1], col_vars[1:]):
            constraints.append(c1 <= c2)

        # Setup the initial interior bounding box for the grid.
        margins = self.margins
github nucleic / enaml / enaml / layout / linear_symbolic.py View on Github external
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
#------------------------------------------------------------------------------
from abc import ABCMeta

import kiwisolver as kiwi


class LinearSymbolic(object, metaclass=ABCMeta):
    """ An abstract base class for testing linear symbolic interfaces.

    """


LinearSymbolic.register(kiwi.Variable)
LinearSymbolic.register(kiwi.Term)
LinearSymbolic.register(kiwi.Expression)
github nucleic / enaml / enaml / layout / grid_helper.py View on Github external
num_cols = max(num_cols, len(row))
            for col_idx, item in enumerate(row):
                if item is None:
                    continue
                elif item in cell_map:
                    cell_map[item].expand_to(row_idx, col_idx)
                else:
                    cell = self._Cell(item, row_idx, col_idx)
                    cell_map[item] = cell
                    cells.append(cell)

        # Create the row and column variables and their default limits.
        row_vars = []
        col_vars = []
        for idx in range(num_rows + 1):
            var = kiwi.Variable('row%d' % idx)
            row_vars.append(var)
            cns.append(var >= 0)
        for idx in range(num_cols + 1):
            var = kiwi.Variable('col%d' % idx)
            col_vars.append(var)
            cns.append(var >= 0)

        # Add the neighbor constraints for the row and column vars.
        for r1, r2 in zip(row_vars[:-1], row_vars[1:]):
            cns.append(r1 <= r2)
        for c1, c2 in zip(col_vars[:-1], col_vars[1:]):
            cns.append(c1 <= c2)

        # Setup the initial interior bounding box for the grid.
        firsts = (self.top, col_vars[-1], row_vars[-1], self.left)
        seconds = (row_vars[0], self.right, self.bottom, col_vars[0])
github nucleic / enaml / enaml / layout / constrainable.py View on Github external
def default(self, owner):
        return kiwi.Variable(self.name)
github nucleic / enaml / enaml / workbench / ui / menu_helper.py View on Github external
if before:
            if before not in variables:
                msg = "item '%s' has invalid `before` reference '%s'"
                raise ValueError(msg % (node.path, before))
            target_var = variables[before]
            constraints.append((this_var + 0.1 <= target_var) | 'strong')
        after = node.item.after
        if after:
            if after not in variables:
                msg = "item '%s' has invalid `after` reference '%s'"
                raise ValueError(msg % (node.path, after))
            target_var = variables[after]
            constraints.append((target_var + 0.1 <= this_var) | 'strong')
        prev_var = this_var

    solver = kiwi.Solver()
    for cn in constraints:
        solver.addConstraint(cn)
    solver.updateVariables()

    return sorted(nodes, key=lambda node: (variables[node.id].value(), id(node)))
github enthought / enable / enable / layout / layout_manager.py View on Github external
def __init__(self):
        self._solver = kiwi.Solver()
        self._edit_stack = []
        self._initialized = False
        self._running = False
github nucleic / enaml / enaml / layout / layout_manager.py View on Github external
"""
        raise NotImplementedError


class LayoutManager(Atom):
    """ A class which manages the layout for a system of items.

    This class is used by the various in-process backends to simplify
    the task of implementing constraint layout management.

    """
    #: The primary layout item which owns the layout.
    _root_item = Typed(LayoutItem)

    #: The solver used by the layout manager.
    _solver = Typed(kiwi.Solver, ())

    #: The stack of edit variables added to the solver.
    _edit_stack = List()

    #: The list of layout items handled by the manager.
    _layout_items = List()

    def __init__(self, item):
        """ Initialize a LayoutManager.

        Parameters
        ----------
        item : LayoutItem
            The layout item which contains the widget which is the
            root of the layout system. This item is the conceptual
            owner of the system. It is not resized by the manager,
github nucleic / enaml / enaml / layout / layout_manager.py View on Github external
----------
        items : list
            A list of LayoutItem instances for the system. The root
            item should *not* be included in this list.

        """
        # Reset the state of the solver.
        del self._edit_stack
        del self._layout_items
        solver = self._solver
        solver.reset()

        # Setup the standard edit variables.
        root = self._root_item
        d = root.constrainable()
        strength = kiwi.strength.medium
        pairs = ((d.width, strength), (d.height, strength))
        self._push_edit_vars(pairs)

        # Generate the constraints for the layout system. The size hint
        # and bounds of the root item are ignored since the input to the
        # solver is the suggested size of the root item and the output
        # of the solver is used to compute the bounds of the item.
        cns = []
        hc = root.hard_constraints()
        mc = root.margin_constraints()
        lc = root.layout_constraints()
        root._margin_cache = mc
        cns.extend(hc)
        cns.extend(mc)
        cns.extend(lc)
        for child in items:

kiwisolver

A fast implementation of the Cassowary constraint solver

BSD-3-Clause
Latest version published 4 months ago

Package Health Score

91 / 100
Full package analysis

Similar packages