Python sympy.And() Examples

The following are 12 code examples of sympy.And(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sympy , or try the search function .
Example #1
Source File: test_expr.py    From chempy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_PiecewisePoly__sympy():
    import sympy as sp
    Poly = mk_Poly('T')
    p1 = Poly([0, 1, 0.1])
    p2 = Poly([0, 3, -.1])

    TPiecewisePoly = mk_PiecewisePoly('temperature')
    tpwp = TPiecewisePoly([2, 2, 0, 10, 2, 10, 20, 0, 1, 0.1, 0, 3, -.1])
    x = sp.Symbol('x')
    res = tpwp.eval_poly({'temperature': x}, backend=sp)
    assert isinstance(res, sp.Piecewise)
    assert res.args[0][0] == 1 + 0.1*x
    assert res.args[0][1] == sp.And(0 <= x, x <= 10)
    assert res.args[1][0] == 3 - 0.1*x
    assert res.args[1][1] == sp.And(10 <= x, x <= 20)

    with pytest.raises(ValueError):
        tpwp.from_polynomials([(0, 10), (10, 20)], [p1, p2]) 
Example #2
Source File: algorithms.py    From devito with MIT License 6 votes vote down vote up
def guard(clusters):
    """
    Split Clusters containing conditional expressions into separate Clusters.
    """
    processed = []
    for c in clusters:
        # Group together consecutive expressions with same ConditionalDimensions
        for cds, g in groupby(c.exprs, key=lambda e: e.conditionals):
            if not cds:
                processed.append(c.rebuild(exprs=list(g)))
                continue

            # Create a guarded Cluster
            guards = {}
            for cd in cds:
                condition = guards.setdefault(cd.parent, [])
                if cd.condition is None:
                    condition.append(CondEq(cd.parent % cd.factor, 0))
                else:
                    condition.append(lower_exprs(cd.condition))
            guards = {k: sympy.And(*v, evaluate=False) for k, v in guards.items()}
            processed.append(c.rebuild(exprs=list(g), guards=guards))

    return ClusterGroup(processed) 
Example #3
Source File: test_sympy_conv.py    From symengine.py with MIT License 5 votes vote down vote up
def test_logic():
    x = true
    y = false
    x1 = sympy.true
    y1 = sympy.false

    assert And(x, y) == And(x1, y1)
    assert And(x1, y) == And(x1, y1)
    assert And(x, y)._sympy_() == sympy.And(x1, y1)
    assert sympify(sympy.And(x1, y1)) == And(x, y)

    assert Or(x, y) == Or(x1, y1)
    assert Or(x1, y) == Or(x1, y1)
    assert Or(x, y)._sympy_() == sympy.Or(x1, y1)
    assert sympify(sympy.Or(x1, y1)) == Or(x, y)

    assert Not(x) == Not(x1)
    assert Not(x1) == Not(x1)
    assert Not(x)._sympy_() == sympy.Not(x1)
    assert sympify(sympy.Not(x1)) == Not(x)

    assert Xor(x, y) == Xor(x1, y1)
    assert Xor(x1, y) == Xor(x1, y1)
    assert Xor(x, y)._sympy_() == sympy.Xor(x1, y1)
    assert sympify(sympy.Xor(x1, y1)) == Xor(x, y)

    x = Symbol("x")
    x1 = sympy.Symbol("x")

    assert Piecewise((x, x < 1), (0, True)) == Piecewise((x1, x1 < 1), (0, True))
    assert Piecewise((x, x1 < 1), (0, True)) == Piecewise((x1, x1 < 1), (0, True))
    assert Piecewise((x, x < 1), (0, True))._sympy_() == sympy.Piecewise((x1, x1 < 1), (0, True))
    assert sympify(sympy.Piecewise((x1, x1 < 1), (0, True))) == Piecewise((x, x < 1), (0, True))

    assert Contains(x, Interval(1, 1)) == Contains(x1, Interval(1, 1))
    assert Contains(x, Interval(1, 1))._sympy_() == sympy.Contains(x1, Interval(1, 1))
    assert sympify(sympy.Contains(x1, Interval(1, 1))) == Contains(x, Interval(1, 1)) 
Example #4
Source File: query_grammar.py    From estnltk with GNU General Public License v2.0 5 votes vote down vote up
def __and__(self, other):
        assert isinstance(other, Node), "Both arguments must be Node instances"
        return And(self, other) 
Example #5
Source File: query_grammar.py    From estnltk with GNU General Public License v2.0 5 votes vote down vote up
def node_to_symbol(words_to_symbols, node):
    if _is_word(node):
        return words_to_symbols[node]
    elif _is_operation(node):
        if isinstance(node, Or):
            return sympy.Or(*[node_to_symbol(words_to_symbols, i) for i in node.nodes])
        elif isinstance(node, And):
            return sympy.And(*[node_to_symbol(words_to_symbols, i) for i in node.nodes]) 
Example #6
Source File: test__rates.py    From chempy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_PiecewiseTPolyMassAction__sympy():
    import sympy as sp
    tp1 = TPoly([10, 0.1])
    tp2 = ShiftedTPoly([273.15, 37.315, -0.1])
    pwp = MassAction(TPiecewise([0, tp1, 273.15, tp2, 373.15]))
    T = sp.Symbol('T')
    r = Reaction({'A': 2, 'B': 1}, {'C': 1}, inact_reac={'B': 1})
    res1 = pwp({'A': 11, 'B': 13, 'temperature': T}, backend=sp, reaction=r)
    ref1 = 11**2 * 13 * sp.Piecewise(
        (10+0.1*T, sp.And(0 <= T, T <= 273.15)),
        (37.315 - 0.1*(T-273.15), sp.And(273.15 <= T, T <= 373.15)),
        (sp.Symbol('NAN'), True)
    )
    assert res1 == ref1 
Example #7
Source File: test_expr.py    From chempy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_create_Piecewise_Poly__sympy():
    import sympy as sp
    Poly = create_Poly('Tmpr')
    p1 = Poly([1, 0.1])
    p2 = Poly([3, -.1])

    TPw = create_Piecewise('Tmpr')
    pw = TPw([0, p1, 10, p2, 20])
    x = sp.Symbol('x')
    res = pw({'Tmpr': x}, backend=sp)
    assert isinstance(res, sp.Piecewise)
    assert res.args[0][0] == 1 + 0.1*x
    assert res.args[0][1] == sp.And(0 <= x, x <= 10)
    assert res.args[1][0] == 3 - 0.1*x
    assert res.args[1][1] == sp.And(10 <= x, x <= 20) 
Example #8
Source File: test_expr.py    From chempy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_create_Piecewise__nan_fallback__sympy():
    import sympy as sp

    TPw = create_Piecewise('Tmpr', nan_fallback=True)
    pw = TPw([0, 42, 10, 43, 20])
    x = sp.Symbol('x')
    res = pw({'Tmpr': x}, backend=sp)
    assert isinstance(res, sp.Piecewise)
    assert res.args[0][0] == 42
    assert res.args[0][1] == sp.And(0 <= x, x <= 10)
    assert res.args[1][0] == 43
    assert res.args[1][1] == sp.And(10 <= x, x <= 20)
    assert res.args[2][0].name.lower() == 'nan'
    assert res.args[2][1] == True  # noqa 
Example #9
Source File: interpolators.py    From devito with MIT License 5 votes vote down vote up
def _interpolation_indices(self, variables, offset=0, field_offset=0):
        """
        Generate interpolation indices for the DiscreteFunctions in ``variables``.
        """
        index_matrix, points = self.sfunction._index_matrix(offset)

        idx_subs = []
        for i, idx in enumerate(index_matrix):
            # Introduce ConditionalDimension so that we don't go OOB
            mapper = {}
            for j, d in zip(idx, self.grid.dimensions):
                p = points[j]
                lb = sympy.And(p >= d.symbolic_min - self.sfunction._radius,
                               evaluate=False)
                ub = sympy.And(p <= d.symbolic_max + self.sfunction._radius,
                               evaluate=False)
                condition = sympy.And(lb, ub, evaluate=False)
                mapper[d] = ConditionalDimension(p.name, self.sfunction._sparse_dim,
                                                 condition=condition, indirect=True)

            # Track Indexed substitutions
            idx_subs.append(mapper)

        # Temporaries for the indirection dimensions
        temps = [Eq(v, k, implicit_dims=self.sfunction.dimensions)
                 for k, v in points.items()]
        # Temporaries for the coefficients
        temps.extend([Eq(p, c, implicit_dims=self.sfunction.dimensions)
                      for p, c in zip(self.sfunction._point_symbols,
                                      self.sfunction._coordinate_bases(field_offset))])

        return idx_subs, temps 
Example #10
Source File: sparse.py    From devito with MIT License 5 votes vote down vote up
def guard(self, expr=None, offset=0):
        """
        Generate guarded expressions, that is expressions that are evaluated
        by an Operator only if certain conditions are met.  The introduced
        condition, here, is that all grid points in the support of a sparse
        value must fall within the grid domain (i.e., *not* on the halo).

        Parameters
        ----------
        expr : expr-like, optional
            Input expression, from which the guarded expression is derived.
            If not specified, defaults to ``self``.
        offset : int, optional
            Relax the guard condition by introducing a tolerance offset.
        """
        _, points = self._index_matrix(offset)

        # Guard through ConditionalDimension
        conditions = {}
        for d, idx in zip(self.grid.dimensions, self._coordinate_indices):
            p = points[idx]
            lb = sympy.And(p >= d.symbolic_min - offset, evaluate=False)
            ub = sympy.And(p <= d.symbolic_max + offset, evaluate=False)
            conditions[p] = sympy.And(lb, ub, evaluate=False)
        condition = sympy.And(*conditions.values(), evaluate=False)
        cd = ConditionalDimension("%s_g" % self._sparse_dim, self._sparse_dim,
                                  condition=condition)

        if expr is None:
            out = self.indexify().xreplace({self._sparse_dim: cd})
        else:
            functions = {f for f in retrieve_function_carriers(expr)
                         if f.is_SparseFunction}
            out = indexify(expr).xreplace({f._sparse_dim: cd for f in functions})

        # Temporaries for the indirection dimensions
        temps = [Eq(v, k, implicit_dims=self.dimensions)
                 for k, v in points.items() if v in conditions]

        return out, temps 
Example #11
Source File: simplification.py    From geppy with GNU Lesser General Public License v3.0 4 votes vote down vote up
def simplify(genome, symbolic_function_map=None):
    """
    Compile the primitive tree into a (possibly simplified) symbolic expression.

    :param genome: :class:`~geppy.core.entity.KExpression`, :class:`~geppy.core.entity.Gene`, or
        :class:`~geppy.core.entity.Chromosome`, the genotype of an individual
    :param symbolic_function_map: dict, maps each function name in the primitive set to a symbolic version
    :return: a (simplified) symbol expression

    For example, *add(sub(3, 3), x)* may be simplified to *x*. This :func:`simplify` function can be used to
    postprocess the best individual obtained in GEP for a simplified representation. Some Python functions like
    :func:`operator.add` can be used directly in *sympy*. However, there are also functions that have their own
    symbolic versions to be used in *sympy*, like the :func:`operator.and_`, which should be replaced by
    :func:`sympy.And`. In such a case, we may provide a map
    ``symbolic_function_map={operator.and_.__name__, sympy.And}`` supposing the function primitive encapsulating
    :func:`operator.and_` uses its default name.

    Such simplification doesn't affect GEP at all. It should be used as a postprocessing step to simplify the final
    solution evolved by GEP.

    .. note::
        If the *symbolic_function_map* argument remains as the default value ``None``, then a default map
        :data:`DEFAULT_SYMBOLIC_FUNCTION_MAP` is used, which contains common
        *name-to-symbolic function* mappings, including the arithmetic operators and Boolean logic operators..

    .. note::
        This function depends on the :mod:`sympy` module. You can find it `here <http://www.sympy.org/en/index.html>`_.
    """
    if symbolic_function_map is None:
        symbolic_function_map = DEFAULT_SYMBOLIC_FUNCTION_MAP
    if isinstance(genome, KExpression):
        return _simplify_kexpression(genome, symbolic_function_map)
    elif isinstance(genome, Gene):
        return _simplify_kexpression(genome.kexpression, symbolic_function_map)
    elif isinstance(genome, Chromosome):
        if len(genome) == 1:
            return _simplify_kexpression(genome[0].kexpression, symbolic_function_map)
        else:   # multigenic chromosome
            simplified_exprs = [_simplify_kexpression(
                g.kexpression, symbolic_function_map) for g in genome]
            # combine these sub-expressions into a single one with the linking function
            try:
                linker = symbolic_function_map[genome.linker.__name__]
            except:
                linker = genome.linker
            return sp.simplify(linker(*simplified_exprs))
    else:
        raise TypeError('Only an argument of type KExpression, Gene, and Chromosome is acceptable. The provided '
                        'genome type is {}.'.format(type(genome))) 
Example #12
Source File: test_dimension.py    From devito with MIT License 4 votes vote down vote up
def test_no_index_sparse(self):
        """Test behaviour when the ConditionalDimension is used as a symbol in
        an expression over sparse data objects."""
        grid = Grid(shape=(4, 4), extent=(3.0, 3.0))
        time = grid.time_dim

        f = TimeFunction(name='f', grid=grid, save=1)
        f.data[:] = 0.

        coordinates = [(0.5, 0.5), (0.5, 2.5), (2.5, 0.5), (2.5, 2.5)]
        sf = SparseFunction(name='sf', grid=grid, npoint=4, coordinates=coordinates)
        sf.data[:] = 1.
        sd = sf.dimensions[sf._sparse_position]

        # We want to write to `f` through `sf` so that we obtain the
        # following 4x4 grid (the '*' show the position of the sparse points)
        # We do that by emulating an injection
        #
        # 0 --- 0 --- 0 --- 0
        # |  *  |     |  *  |
        # 0 --- 1 --- 1 --- 0
        # |     |     |     |
        # 0 --- 1 --- 1 --- 0
        # |  *  |     |  *  |
        # 0 --- 0 --- 0 --- 0

        radius = 1
        indices = [(i, i+radius) for i in sf._coordinate_indices]
        bounds = [i.symbolic_size - radius for i in grid.dimensions]

        eqs = []
        for e, i in enumerate(product(*indices)):
            args = [j > 0 for j in i]
            args.extend([j < k for j, k in zip(i, bounds)])
            condition = And(*args, evaluate=False)
            cd = ConditionalDimension('sfc%d' % e, parent=sd, condition=condition)
            index = [time] + list(i)
            eqs.append(Eq(f[index], f[index] + sf[cd]))

        op = Operator(eqs)
        op.apply(time=0)

        assert np.all(f.data[0, 1:-1, 1:-1] == 1.)
        assert np.all(f.data[0, 0] == 0.)
        assert np.all(f.data[0, -1] == 0.)
        assert np.all(f.data[0, :, 0] == 0.)
        assert np.all(f.data[0, :, -1] == 0.)