Ejemplo n.º 1
0
    def equation(self, x='x', y='y'):
        """The equation of the ellipse.

        Parameters
        ----------
        x : str, optional
            Label for the x-axis. Default value is 'x'.
        y : str, optional
            Label for the y-axis. Default value is 'y'.

        Returns
        -------
        equation : sympy expression

        Examples
        --------
        >>> from sympy import Point, Ellipse
        >>> e1 = Ellipse(Point(1, 0), 3, 2)
        >>> e1.equation()
        -1 + (1/3 - x/3)**2 + y**2/4

        """
        if isinstance(x, basestring): x = C.Symbol(x, real=True)
        if isinstance(y, basestring): y = C.Symbol(y, real=True)
        t1 = ((x - self.center[0]) / self.hradius)**2
        t2 = ((y - self.center[1]) / self.vradius)**2
        return t1 + t2 - 1
Ejemplo n.º 2
0
    def equation(self, x='x', y='y'):
        """The equation of the circle.

        Parameters
        ----------
        x : str or Symbol, optional
            Default value is 'x'.
        y : str or Symbol, optional
            Default value is 'y'.

        Returns
        -------
        equation : sympy expression

        Examples
        --------
        >>> from sympy import Point, Circle
        >>> c1 = Circle(Point(0, 0), 5)
        >>> c1.equation()
        -25 + x**2 + y**2

        """
        if isinstance(x, basestring):
            x = C.Symbol(x, real=True)
        if isinstance(y, basestring):
            y = C.Symbol(y, real=True)
        t1 = (x - self.center[0])**2
        t2 = (y - self.center[1])**2
        return t1 + t2 - self.hradius**2
Ejemplo n.º 3
0
 def equation(self, xaxis_name='x', yaxis_name='y'):
     """
     Returns the equation for this line. Optional parameters xaxis_name
     and yaxis_name can be used to specify the names of the symbols used
     for the equation.
     """
     x = C.Symbol(xaxis_name, real=True)
     y = C.Symbol(yaxis_name, real=True)
     a, b, c = self.coefficients
     return simplify(a * x + b * y + c)
Ejemplo n.º 4
0
    def equation(self, x='x', y='y'):
        """
        Returns the equation of the circle.

        Optional parameters x and y can be used to specify symbols, or the
        names of the symbols used in the equation.
        """
        if isinstance(x, basestring): x = C.Symbol(x, real=True)
        if isinstance(y, basestring): y = C.Symbol(y, real=True)
        t1 = (x - self.center[0])**2
        t2 = (y - self.center[1])**2
        return t1 + t2 - self.hradius**2
Ejemplo n.º 5
0
 def __contains__(self, o):
     """Return True if o is on this Line, or False otherwise."""
     if isinstance(o, Line):
         return self.__eq__(o)
     elif isinstance(o, Point):
         x = C.Symbol('x', real=True)
         y = C.Symbol('y', real=True)
         r = self.equation().subs({x: o[0], y: o[1]})
         x = simplify(r)
         return simplify(x) == 0
     else:
         return False
Ejemplo n.º 6
0
 def fdiff(self, argindex=1):
     if argindex == 1:
         return 1 / self.args[0]
         s = C.Symbol('x', dummy=True)
         return Lambda(s**(-1), s)
     else:
         raise ArgumentIndexError(self, argindex)
Ejemplo n.º 7
0
    def arbitrary_point(self, parameter_name='t'):
        """A parametric point on the ellipse.

        Parameters
        ----------
        parameter_name : str, optional
            Default value is 't'.

        Returns
        -------
        arbitrary_point : Point

        See Also
        --------
        Point

        Examples
        --------
        >>> from sympy import Point, Ellipse
        >>> e1 = Ellipse(Point(0, 0), 3, 2)
        >>> e1.arbitrary_point()
        Point(3*cos(t), 2*sin(t))

        """
        t = C.Symbol(parameter_name, real=True)
        return Point(self.center[0] + self.hradius * C.cos(t),
                     self.center[1] + self.vradius * C.sin(t))
Ejemplo n.º 8
0
 def random_point(self):
     """Returns a random point on the ellipse."""
     from random import random
     t = C.Symbol('t', real=True)
     p = self.arbitrary_point('t')
     # get a random value in [-pi, pi)
     subs_val = float(S.Pi) * (2 * random() - 1)
     return Point(p[0].subs(t, subs_val), p[1].subs(t, subs_val))
Ejemplo n.º 9
0
 def __init__(self, settings=None):
     CodePrinter.__init__(self, settings)
     self._init_leading_padding()
     assign_to = self._settings['assign_to']
     if isinstance(assign_to, string_types):
         self._settings['assign_to'] = C.Symbol(assign_to)
     elif not isinstance(assign_to, (C.Basic, type(None))):
         raise TypeError("FCodePrinter cannot assign to object of type %s" %
                         type(assign_to))
Ejemplo n.º 10
0
    def doprint(self, expr, assign_to=None):
        """
        Print the expression as code.

        Parameters
        ----------
        expr : Expression
            The expression to be printed.

        assign_to : Symbol, MatrixSymbol, or string (optional)
            If provided, the printed code will set the expression to a
            variable with name ``assign_to``.
        """

        if isinstance(assign_to, string_types):
            assign_to = C.Symbol(assign_to)
        elif not isinstance(assign_to, (C.Basic, type(None))):
            raise TypeError("{0} cannot assign to object of type {1}".format(
                type(self).__name__, type(assign_to)))

        if assign_to:
            expr = Assignment(assign_to, expr)
        else:
            expr = _sympify(expr)

        # keep a set of expressions that are not strictly translatable to Code
        # and number constants that must be declared and initialized
        self._not_supported = set()
        self._number_symbols = set()

        lines = self._print(expr).splitlines()

        # format the output
        if self._settings["human"]:
            frontlines = []
            if len(self._not_supported) > 0:
                frontlines.append(
                    self._get_comment("Not supported in {0}:".format(
                        self.language)))
                for expr in sorted(self._not_supported, key=str):
                    frontlines.append(self._get_comment(type(expr).__name__))
            for name, value in sorted(self._number_symbols, key=str):
                frontlines.append(self._declare_number_const(name, value))
            lines = frontlines + lines
            lines = self._format_code(lines)
            result = "\n".join(lines)
        else:
            lines = self._format_code(lines)
            result = (self._number_symbols, self._not_supported,
                      "\n".join(lines))
        del self._not_supported
        del self._number_symbols
        return result
Ejemplo n.º 11
0
    def doprint(self, expr, assign_to=None):
        """
        Actually format the expression as Javascript code.
        """

        if isinstance(assign_to, basestring):
            assign_to = C.Symbol(assign_to)
        elif not isinstance(assign_to, (C.Basic, type(None))):
            raise TypeError(
                "JavascriptCodePrinter cannot assign to object of type %s" %
                type(assign_to))

        # keep a set of expressions that are not strictly translatable to Javascript
        # and number constants that must be declared and initialized
        not_js = self._not_supported = set()
        self._number_symbols = set()

        # We treat top level Piecewise here to get if tests outside loops
        lines = []
        if isinstance(expr, C.Piecewise):
            for i, (e, c) in enumerate(expr.args):
                if i == 0:
                    lines.append("if (%s) {" % self._print(c))
                elif i == len(expr.args) - 1 and c is True:
                    lines.append("else {")
                else:
                    lines.append("else if (%s) {" % self._print(c))
                code0 = self._doprint_a_piece(e, assign_to)
                lines.extend(code0)
                lines.append("}")
        else:
            code0 = self._doprint_a_piece(expr, assign_to)
            lines.extend(code0)

        # format the output
        if self._settings["human"]:
            frontlines = []
            if len(not_js) > 0:
                frontlines.append("// Not Javascript:")
                for expr in sorted(not_js, key=str):
                    frontlines.append("// %s" % repr(expr))
            for name, value in sorted(self._number_symbols, key=str):
                frontlines.append("var %s = %s;" % (name, value))
            lines = frontlines + lines
            lines = "\n".join(lines)
            result = self.indent_code(lines)
        else:
            lines = self.indent_code("\n".join(lines))
            result = self._number_symbols, not_js, lines
        del self._not_supported
        del self._number_symbols
        return result
Ejemplo n.º 12
0
 def _print_Function(self, e):
     from sympy.physics.vector.functions import dynamicsymbols
     t = dynamicsymbols._t
     # XXX works only for applied functions
     func = e.func
     args = e.args
     func_name = func.__name__
     pform = self._print_Symbol(C.Symbol(func_name))
     # If this function is an Undefined function of t, it is probably a
     # dynamic symbol, so we'll skip the (t). The rest of the code is
     # identical to the normal PrettyPrinter code
     if not (isinstance(func, UndefinedFunction) and (args == (t,))):
         return super(VectorPrettyPrinter, self)._print_Function(e)
     return pform
Ejemplo n.º 13
0
    def _print_Function(self, e):
        # XXX works only for applied functions
        func = e.func
        args = e.args
        n = len(args)

        func_name = func.__name__

        prettyFunc = self._print(C.Symbol(func_name));
        prettyArgs = prettyForm(*self._print_seq(args).parens())

        pform = prettyForm(binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs))

        # store pform parts so it can be reassembled e.g. when powered
        pform.prettyFunc = prettyFunc
        pform.prettyArgs = prettyArgs

        return pform
Ejemplo n.º 14
0
    def _print_Lambda(self, e):
        symbols, expr = e.args

        if len(symbols) == 1:
            symbols = self._print(symbols[0])
        else:
            symbols = self._print(tuple(symbols))

        args = (symbols, self._print(expr))

        prettyFunc = self._print(C.Symbol("Lambda"))
        prettyArgs = prettyForm(*self._print_seq(args).parens())

        pform = prettyForm(binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs))

        # store pform parts so it can be reassembled e.g. when powered
        pform.prettyFunc = prettyFunc
        pform.prettyArgs = prettyArgs

        return pform
Ejemplo n.º 15
0
 def _print_Function(self, e):
     from sympy.physics.vector.functions import dynamicsymbols
     t = dynamicsymbols._t
     # XXX works only for applied functions
     func = e.func
     args = e.args
     func_name = func.__name__
     prettyFunc = self._print(C.Symbol(func_name))
     prettyArgs = prettyForm(*self._print_seq(args).parens())
     # If this function is an Undefined function of t, it is probably a
     # dynamic symbol, so we'll skip the (t). The rest of the code is
     # identical to the normal PrettyPrinter code
     if isinstance(func, UndefinedFunction) and (args == (t, )):
         pform = prettyForm(binding=prettyForm.FUNC,
                            *stringPict.next(prettyFunc))
     else:
         pform = prettyForm(binding=prettyForm.FUNC,
                            *stringPict.next(prettyFunc, prettyArgs))
     # store pform parts so it can be reassembled e.g. when powered
     pform.prettyFunc = prettyFunc
     pform.prettyArgs = prettyArgs
     return pform
Ejemplo n.º 16
0
    def random_point(self):
        """A random point on the ellipse.

        Returns
        -------
        point : Point

        See Also
        --------
        Point

        Note
        ----
        A random point may not appear to be on the ellipse, ie, `p in e` may
        return False. This is because the coordinates of the point will be
        floating point values, and when these values are substituted into the
        equation for the ellipse the result may not be zero because of floating
        point rounding error.

        Examples
        --------
        >>> from sympy import Point, Ellipse
        >>> e1 = Ellipse(Point(0, 0), 3, 2)
        >>> p1 = e1.random_point()
        >>> # a random point may not appear to be on the ellipse because of
        >>> # floating point rounding error
        >>> p1 in e1 # doctest: +SKIP
        True
        >>> p1 # doctest +ELLIPSIS
        Point(...)

        """
        from random import random
        t = C.Symbol('t', real=True)
        p = self.arbitrary_point('t')
        # get a random value in [-pi, pi)
        subs_val = float(S.Pi) * (2 * random() - 1)
        return Point(p[0].subs(t, subs_val), p[1].subs(t, subs_val))
Ejemplo n.º 17
0
    def plot_interval(self, parameter_name='t'):
        """The plot interval for the default geometric plot of the Ellipse.

        Parameters
        ----------
        parameter_name : str, optional
            Default value is 't'.

        Returns
        -------
        plot_interval : list
            [parameter, lower_bound, upper_bound]

        Examples
        --------
        >>> from sympy import Point, Ellipse
        >>> e1 = Ellipse(Point(0, 0), 3, 2)
        >>> e1.plot_interval()
        [t, -pi, pi]

        """
        t = C.Symbol(parameter_name, real=True)
        return [t, -S.Pi, S.Pi]
Ejemplo n.º 18
0
 def plot_interval(self, parameter_name='t'):
     t = C.Symbol(parameter_name, real=True)
     return [t, 0, 1]
Ejemplo n.º 19
0
 def arbitrary_point(self, parameter_name='t'):
     """Returns a symbolic point that is on this line segment."""
     t = C.Symbol(parameter_name, real=True)
     x = simplify(self.p1[0] + t * (self.p2[0] - self.p1[0]))
     y = simplify(self.p1[1] + t * (self.p2[1] - self.p1[1]))
     return Point(x, y)
Ejemplo n.º 20
0
 def plot_interval(self, parameter_name='t'):
     """Returns the plot interval for the default geometric plot of line"""
     t = C.Symbol(parameter_name, real=True)
     return [t, -5, 5]
Ejemplo n.º 21
0
    def __new__(cls, expr, *symbols, **assumptions):
        expr = sympify(expr).expand()
        if expr is S.NaN:
            return S.NaN

        if symbols:
            symbols = map(sympify, symbols)
        else:
            symbols = list(expr.atoms(C.Symbol))

        symbols.sort(Basic.compare)

        if expr.is_Order:

            new_symbols = list(expr.symbols)
            for s in symbols:
                if s not in new_symbols:
                    new_symbols.append(s)
            if len(new_symbols)==len(expr.symbols):
                return expr
            symbols = new_symbols

        elif symbols:

            symbol_map = {}
            new_symbols = []
            for s in symbols:
                if isinstance(s, C.Symbol):
                    new_symbols.append(s)
                    continue
                z = C.Symbol('z',dummy=True)
                x1,s1 = solve4linearsymbol(s, z)
                expr = expr.subs(x1,s1)
                symbol_map[z] = s
                new_symbols.append(z)

            if symbol_map:
                r = Order(expr, *new_symbols, **assumptions)
                expr = r.expr.subs(symbol_map)
                symbols = []
                for s in r.symbols:
                    if symbol_map.has_key(s):
                        symbols.append(symbol_map[s])
                    else:
                        symbols.append(s)
            else:
                if expr.is_Add:
                    lst = expr.extract_leading_order(*symbols)
                    expr = C.Add(*[f.expr for (e,f) in lst])
                else:
                    expr = expr.as_leading_term(*symbols)
                    coeff, terms = expr.as_coeff_terms()
                    if coeff is S.Zero:
                        return coeff
                    expr = C.Mul(*[t for t in terms if t.has(*symbols)])

        elif expr is not S.Zero:
            expr = S.One

        if expr is S.Zero:
            return expr

        # create Order instance:
        obj = Expr.__new__(cls, expr, *symbols, **assumptions)

        return obj
Ejemplo n.º 22
0
 def plot_interval(self, parameter_name='t'):
     """Returns a typical plot interval used by the plotting module."""
     t = C.Symbol(parameter_name, real=True)
     return [t, -S.Pi, S.Pi]
Ejemplo n.º 23
0
 def arbitrary_point(self, parameter_name='t'):
     """Returns a symbolic point that is on the ellipse."""
     t = C.Symbol(parameter_name, real=True)
     return Point(self.center[0] + self.hradius * C.cos(t),
                  self.center[1] + self.vradius * C.sin(t))