Example #1
0
    def _contains(self, other):
        from sympy.solvers.solveset import solveset, linsolve

        L = self.lamda
        if self._is_multivariate():
            solns = list(linsolve([expr - val for val, expr in zip(other, L.expr)], L.variables).args[0])
        else:
            solnsSet = solveset(L.expr - other, L.variables[0])
            if solnsSet.is_FiniteSet:
                solns = list(solveset(L.expr - other, L.variables[0]))
            else:
                raise NotImplementedError(
                    filldedent(
                        """
                Determining whether an ImageSet contains %s has not
                been implemented."""
                        % func_name(other)
                    )
                )
        for soln in solns:
            try:
                if soln in self.base_set:
                    return S.true
            except TypeError:
                return self.base_set.contains(soln.evalf())
        return S.false
Example #2
0
File: point.py Project: latot/sympy
    def __new__(cls, *args, **kwargs):
        evaluate = kwargs.get("evaluate", global_evaluate[0])
        on_morph = kwargs.get("on_morph", "ignore")

        # unpack into coords
        if len(args) == 1 and is_sequence(args[0]):
            coords = args[0]
        else:
            coords = args

        # A point where only `dim` is specified is initialized
        # to zeros.
        if len(coords) == 0 and kwargs.get("dim", None):
            coords = (S.Zero,) * kwargs.get("dim")

        # check args and handle quickly handle Point instances
        if isinstance(coords, Point):
            # even if we're mutating the dimension of a point, we
            # don't reevaluate its coordinates
            evaluate = False
            if len(coords) == kwargs.get("dim", len(coords)):
                return coords

        if not is_sequence(coords):
            raise TypeError(
                filldedent(
                    """
                Expecting sequence of coordinates, not `{}`""".format(
                        func_name(coords)
                    )
                )
            )

        coords = Tuple(*coords)
        dim = kwargs.get("dim", len(coords))

        if len(coords) != dim:
            message = ("Dimension of {} needs to be changed" "from {} to {}.").format(coords, len(coords), dim)
            if on_morph == "ignore":
                pass
            elif on_morph == "error":
                raise ValueError(message)
            elif on_morph == "warn":
                warnings.warn(message)
            else:
                raise ValueError(
                    filldedent(
                        """
                        on_morph value should be 'error',
                        'warn' or 'ignore'."""
                    )
                )
        if any(i for i in coords[dim:]):
            raise ValueError("Nonzero coordinates cannot be removed.")
        if any(a.is_number and im(a) for a in coords):
            raise ValueError("Imaginary coordinates are not permitted.")
        if not all(isinstance(a, Expr) for a in coords):
            raise TypeError("Coordinates must be valid SymPy expressions.")

        # pad with zeros appropriately
        coords = coords[:dim] + (S.Zero,) * (dim - len(coords))

        # Turn any Floats into rationals and simplify
        # any expressions before we instantiate
        if evaluate:
            coords = coords.xreplace(dict([(f, simplify(nsimplify(f, rational=True))) for f in coords.atoms(Float)]))

        # return 2D or 3D instances
        if len(coords) == 2:
            kwargs["_nocheck"] = True
            return Point2D(*coords, **kwargs)
        elif len(coords) == 3:
            kwargs["_nocheck"] = True
            return Point3D(*coords, **kwargs)

        # the general Point
        return GeometryEntity.__new__(cls, *coords)
Example #3
0
    def _contains(self, other):
        from sympy.matrices import Matrix
        from sympy.solvers.solveset import solveset, linsolve
        from sympy.utilities.iterables import iterable, cartes

        L = self.lamda
        if self._is_multivariate():
            if not iterable(L.expr):
                if iterable(other):
                    return S.false
                return other.as_numer_denom() in self.func(Lambda(L.variables, L.expr.as_numer_denom()), self.base_set)
            if len(L.expr) != len(self.lamda.variables):
                raise NotImplementedError(
                    filldedent(
                        """
    Dimensions of input and output of Lambda are different."""
                    )
                )
            eqs = [expr - val for val, expr in zip(other, L.expr)]
            variables = L.variables
            free = set(variables)
            if all(i.is_number for i in list(Matrix(eqs).jacobian(variables))):
                solns = list(linsolve([e - val for e, val in zip(L.expr, other)], variables))
            else:
                syms = [e.free_symbols & free for e in eqs]
                solns = {}
                for i, (e, s, v) in enumerate(zip(eqs, syms, other)):
                    if not s:
                        if e != v:
                            return S.false
                        solns[vars[i]] = [v]
                        continue
                    elif len(s) == 1:
                        sy = s.pop()
                        sol = solveset(e, sy)
                        if sol is S.EmptySet:
                            return S.false
                        elif isinstance(sol, FiniteSet):
                            solns[sy] = list(sol)
                        else:
                            raise NotImplementedError
                    else:
                        raise NotImplementedError
                solns = cartes(*[solns[s] for s in variables])
        else:
            # assume scalar -> scalar mapping
            solnsSet = solveset(L.expr - other, L.variables[0])
            if solnsSet.is_FiniteSet:
                solns = list(solnsSet)
            else:
                raise NotImplementedError(
                    filldedent(
                        """
                Determining whether an ImageSet contains %s has not
                been implemented."""
                        % func_name(other)
                    )
                )
        for soln in solns:
            try:
                if soln in self.base_set:
                    return S.true
            except TypeError:
                return self.base_set.contains(soln.evalf())
        return S.false