a
    RG5dh                    @   sV  d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
mZ ddlmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZmZ ddlmZ dadd Zdd Z G dd dZ!G dd dZ"G dd dZ#G dd de#Z$G dd de$Z%G dd  d e$Z&G d!d" d"e$Z'G d#d$ d$e$Z(G d%d& d&e(Z)G d'd( d(e#Z*G d)d* d*e*Z+G d+d, d,e*Z,G d-d. d.e#Z-G d/d0 d0Z.G d1d2 d2e.Z/G d3d4 d4e.Z0G d5d6 d6e.Z1e/e0e1d7Z2d8d9 Z3d:d; Z4dQd=d>Z5d?d@ Z6ddAdBdCZ7ddAdDdEZ8ddAdFdGZ9ddAdHdIZ:ddAdJdKZ;ddAdLdMZ<dNdO Z=dPS )Ra   Plotting module for SymPy.

A plot is represented by the ``Plot`` class that contains a reference to the
backend and a list of the data series to be plotted. The data series are
instances of classes meant to simplify getting points and meshes from SymPy
expressions. ``plot_backends`` is a dictionary with all the backends.

This module gives only the essential. For all the fancy stuff use directly
the backend. You can get the backend wrapper for every plot from the
``_backend`` attribute. Moreover the data series classes have various useful
methods like ``get_points``, ``get_meshes``, etc, that may
be useful if you wish to use another plotting library.

Especially if you need publication ready graphs and this module is not enough
for you - just get the ``_backend`` attribute and add whatever you want
directly to it. In the case of matplotlib (the common way to graph data in
python) just copy ``_backend.fig`` which is the figure and ``_backend.ax``
which is the axis and work on them as you would on any other matplotlib object.

Simplicity of code takes much greater importance than performance. Do not use it
if you care at all about performance. A new backend instance is initialized
every time you call ``show()`` and the old one is left to the garbage collector.
    )Callable)Basic)Tuple)Expr)arityFunction)DummySymbol)sympify)import_module)latex)sympy_deprecation_warning)is_sequence   )vectorized_lambdifylambdify)textplotTc                   C   s   da dS )z/
    Disable show(). For use in the tests.
    FN)_show r   r   O/var/www/html/django/DPS/env/lib/python3.9/site-packages/sympy/plotting/plot.py
unset_show5   s    r   c                 C   s   t | trt| ddS t| S )Ninline)mode)
isinstancer   r   str)labelr   r   r   _str_or_latex<   s    
r   c                       s   e Zd ZdZddddddddddddddddddddd	 fd
d
Zdd Zdd Zdd Zdd Zdd Z	dd Z
dd Zdd Z  ZS )Plota)  The central class of the plotting module.

    Explanation
    ===========

    For interactive work the function :func:`plot()` is better suited.

    This class permits the plotting of SymPy expressions using numerous
    backends (:external:mod:`matplotlib`, textplot, the old pyglet module for SymPy, Google
    charts api, etc).

    The figure can contain an arbitrary number of plots of SymPy expressions,
    lists of coordinates of points, etc. Plot has a private attribute _series that
    contains all data series to be plotted (expressions for lines or surfaces,
    lists of points, etc (all subclasses of BaseSeries)). Those data series are
    instances of classes not imported by ``from sympy import *``.

    The customization of the figure is on two levels. Global options that
    concern the figure as a whole (e.g. title, xlabel, scale, etc) and
    per-data series options (e.g. name) and aesthetics (e.g. color, point shape,
    line type, etc.).

    The difference between options and aesthetics is that an aesthetic can be
    a function of the coordinates (or parameters in a parametric plot). The
    supported values for an aesthetic are:

    - None (the backend uses default values)
    - a constant
    - a function of one variable (the first coordinate or parameter)
    - a function of two variables (the first and second coordinate or parameters)
    - a function of three variables (only in nonparametric 3D plots)

    Their implementation depends on the backend so they may not work in some
    backends.

    If the plot is parametric and the arity of the aesthetic function permits
    it the aesthetic is calculated over parameters and not over coordinates.
    If the arity does not permit calculation over parameters the calculation is
    done over coordinates.

    Only cartesian coordinates are supported for the moment, but you can use
    the parametric plots to plot in polar, spherical and cylindrical
    coordinates.

    The arguments for the constructor Plot must be subclasses of BaseSeries.

    Any global option can be specified as a keyword argument.

    The global options for a figure are:

    - title : str
    - xlabel : str or Symbol
    - ylabel : str or Symbol
    - zlabel : str or Symbol
    - legend : bool
    - xscale : {'linear', 'log'}
    - yscale : {'linear', 'log'}
    - axis : bool
    - axis_center : tuple of two floats or {'center', 'auto'}
    - xlim : tuple of two floats
    - ylim : tuple of two floats
    - aspect_ratio : tuple of two floats or {'auto'}
    - autoscale : bool
    - margin : float in [0, 1]
    - backend : {'default', 'matplotlib', 'text'} or a subclass of BaseBackend
    - size : optional tuple of two floats, (width, height); default: None

    The per data series options and aesthetics are:
    There are none in the base series. See below for options for subclasses.

    Some data series support additional aesthetics or options:

    :class:`~.LineOver1DRangeSeries`, :class:`~.Parametric2DLineSeries`, and
    :class:`~.Parametric3DLineSeries` support the following:

    Aesthetics:

    - line_color : string, or float, or function, optional
        Specifies the color for the plot, which depends on the backend being
        used.

        For example, if ``MatplotlibBackend`` is being used, then
        Matplotlib string colors are acceptable (``"red"``, ``"r"``,
        ``"cyan"``, ``"c"``, ...).
        Alternatively, we can use a float number, 0 < color < 1, wrapped in a
        string (for example, ``line_color="0.5"``) to specify grayscale colors.
        Alternatively, We can specify a function returning a single
        float value: this will be used to apply a color-loop (for example,
        ``line_color=lambda x: math.cos(x)``).

        Note that by setting line_color, it would be applied simultaneously
        to all the series.

    Options:

    - label : str
    - steps : bool
    - integers_only : bool

    :class:`~.SurfaceOver2DRangeSeries` and :class:`~.ParametricSurfaceSeries`
    support the following:

    Aesthetics:

    - surface_color : function which returns a float.
    NautoTlinearFr   default)titlexlabelylabelzlabelaspect_ratioxlimylimaxis_centeraxisxscaleyscalelegend	autoscalemarginannotationsmarkers
rectanglesfillbackendsizec                   s  t    |_|_|_|_|_|_|	_|
_	|_
|_|_|_|_|_|_|_g _j| t|trt| _n&t|tkrt|tr|_ntddd dd   fdd}d _|d| d _|d| d _|d	| d S )
Nz<backend must be either a string or a subclass of BaseBackendc                 S   s   t dd | D S )Nc                 s   s   | ]}t |d dV  qdS )is_realTNgetattr.0ir   r   r   	<genexpr>       2Plot.__init__.<locals>.<lambda>.<locals>.<genexpr>alllimr   r   r   <lambda>   r<   zPlot.__init__.<locals>.<lambda>c                 S   s   t dd | D S )Nc                 s   s   | ]}t |d dV  qdS )	is_finiteTNr6   r8   r   r   r   r;      r<   r=   r>   r@   r   r   r   rB      r<   c                    sX   |rT|st d| | |s4t d| |t| t|d t|d f d S )Nz#All numbers from {}={} must be realz%All numbers from {}={} must be finiter   r   )
ValueErrorformatsetattrfloat)Zt_nametrC   r5   selfr   r   check_and_set   s    

z$Plot.__init__.<locals>.check_and_setr&   r'   r4   )super__init__r!   r"   r#   r$   r%   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   _seriesextendr   r   plot_backendsr3   type
issubclassBaseBackend	TypeErrorr&   r'   r4   )rJ   r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   argskwargsrK   	__class__rI   r   rM      sJ    




zPlot.__init__c                 C   s.   t | dr| j  | | | _| j  d S N_backendhasattrrZ   closer3   showrJ   r   r   r   r^      s    

z	Plot.showc                 C   s0   t | dr| j  | | | _| j| d S rY   r\   rZ   r]   r3   saverJ   pathr   r   r   ra      s    

z	Plot.savec                 C   s"   dd t | jD }dd| S )Nc                 S   s    g | ]\}}d | t | qS )z[%d]: r   )r9   r:   sr   r   r   
<listcomp>  s   z Plot.__str__.<locals>.<listcomp>zPlot object containing:

)	enumeraterN   join)rJ   Zseries_strsr   r   r   __str__  s    zPlot.__str__c                 C   s
   | j | S NrN   rJ   indexr   r   r   __getitem__  s    zPlot.__getitem__c                 G   s(   t |dkr$t|d tr$|| j|< d S )Nr   r   )lenr   
BaseSeriesrN   )rJ   rn   rU   r   r   r   __setitem__  s    zPlot.__setitem__c                 C   s   | j |= d S rk   rl   rm   r   r   r   __delitem__  s    zPlot.__delitem__c                 C   s$   t |tr| j| ntddS )aE  Adds an element from a plot's series to an existing plot.

        Examples
        ========

        Consider two ``Plot`` objects, ``p1`` and ``p2``. To add the
        second plot's first series object to the first, use the
        ``append`` method, like so:

        .. plot::
           :format: doctest
           :include-source: True

           >>> from sympy import symbols
           >>> from sympy.plotting import plot
           >>> x = symbols('x')
           >>> p1 = plot(x*x, show=False)
           >>> p2 = plot(x, show=False)
           >>> p1.append(p2[0])
           >>> p1
           Plot object containing:
           [0]: cartesian line: x**2 for x over (-10.0, 10.0)
           [1]: cartesian line: x for x over (-10.0, 10.0)
           >>> p1.show()

        See Also
        ========

        extend

        z'Must specify element of plot to append.N)r   rq   rN   appendrT   rJ   argr   r   r   rt     s     
zPlot.appendc                 C   s<   t |tr| j|j nt|r0| j| ntddS )a  Adds all series from another plot.

        Examples
        ========

        Consider two ``Plot`` objects, ``p1`` and ``p2``. To add the
        second plot to the first, use the ``extend`` method, like so:

        .. plot::
           :format: doctest
           :include-source: True

           >>> from sympy import symbols
           >>> from sympy.plotting import plot
           >>> x = symbols('x')
           >>> p1 = plot(x**2, show=False)
           >>> p2 = plot(x, -x, show=False)
           >>> p1.extend(p2)
           >>> p1
           Plot object containing:
           [0]: cartesian line: x**2 for x over (-10.0, 10.0)
           [1]: cartesian line: x for x over (-10.0, 10.0)
           [2]: cartesian line: -x for x over (-10.0, 10.0)
           >>> p1.show()

        z(Expecting Plot or sequence of BaseSeriesN)r   r   rN   rO   r   rT   ru   r   r   r   rO   7  s
    
zPlot.extend)__name__
__module____qualname____doc__rM   r^   ra   rj   ro   rr   rs   rt   rO   __classcell__r   r   rW   r   r   F   s   l
D%r   c                   @   s8   e Zd ZdZdddddZdd Zd	d
 Zdd ZdS )PlotGrida	  This class helps to plot subplots from already created SymPy plots
    in a single figure.

    Examples
    ========

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

        >>> from sympy import symbols
        >>> from sympy.plotting import plot, plot3d, PlotGrid
        >>> x, y = symbols('x, y')
        >>> p1 = plot(x, x**2, x**3, (x, -5, 5))
        >>> p2 = plot((x**2, (x, -6, 6)), (x, (x, -5, 5)))
        >>> p3 = plot(x**3, (x, -5, 5))
        >>> p4 = plot3d(x*y, (x, -5, 5), (y, -5, 5))

    Plotting vertically in a single line:

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

        >>> PlotGrid(2, 1, p1, p2)
        PlotGrid object containing:
        Plot[0]:Plot object containing:
        [0]: cartesian line: x for x over (-5.0, 5.0)
        [1]: cartesian line: x**2 for x over (-5.0, 5.0)
        [2]: cartesian line: x**3 for x over (-5.0, 5.0)
        Plot[1]:Plot object containing:
        [0]: cartesian line: x**2 for x over (-6.0, 6.0)
        [1]: cartesian line: x for x over (-5.0, 5.0)

    Plotting horizontally in a single line:

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

        >>> PlotGrid(1, 3, p2, p3, p4)
        PlotGrid object containing:
        Plot[0]:Plot object containing:
        [0]: cartesian line: x**2 for x over (-6.0, 6.0)
        [1]: cartesian line: x for x over (-5.0, 5.0)
        Plot[1]:Plot object containing:
        [0]: cartesian line: x**3 for x over (-5.0, 5.0)
        Plot[2]:Plot object containing:
        [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)

    Plotting in a grid form:

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

        >>> PlotGrid(2, 2, p1, p2, p3, p4)
        PlotGrid object containing:
        Plot[0]:Plot object containing:
        [0]: cartesian line: x for x over (-5.0, 5.0)
        [1]: cartesian line: x**2 for x over (-5.0, 5.0)
        [2]: cartesian line: x**3 for x over (-5.0, 5.0)
        Plot[1]:Plot object containing:
        [0]: cartesian line: x**2 for x over (-6.0, 6.0)
        [1]: cartesian line: x for x over (-5.0, 5.0)
        Plot[2]:Plot object containing:
        [0]: cartesian line: x**3 for x over (-5.0, 5.0)
        Plot[3]:Plot object containing:
        [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)

    TN)r^   r4   c                O   sL   || _ || _g | _|| _|D ]}| j|j qt| _|| _|rH|   dS )a  
        Parameters
        ==========

        nrows :
            The number of rows that should be in the grid of the
            required subplot.
        ncolumns :
            The number of columns that should be in the grid
            of the required subplot.

        nrows and ncolumns together define the required grid.

        Arguments
        =========

        A list of predefined plot objects entered in a row-wise sequence
        i.e. plot objects which are to be in the top row of the required
        grid are written first, then the second row objects and so on

        Keyword arguments
        =================

        show : Boolean
            The default value is set to ``True``. Set show to ``False`` and
            the function will not display the subplot. The returned instance
            of the ``PlotGrid`` class can then be used to save or display the
            plot by calling the ``save()`` and ``show()`` methods
            respectively.
        size : (float, float), optional
            A tuple in the form (width, height) in inches to specify the size of
            the overall figure. The default value is set to ``None``, meaning
            the size will be set by the default backend.
        N)	nrowsncolumnsrN   rU   rt   DefaultBackendr3   r4   r^   )rJ   r}   r~   r^   r4   rU   rV   rv   r   r   r   rM     s    #zPlotGrid.__init__c                 C   s.   t | dr| j  | | | _| j  d S rY   r[   r_   r   r   r   r^     s    

zPlotGrid.showc                 C   s0   t | dr| j  | | | _| j| d S rY   r`   rb   r   r   r   ra     s    

zPlotGrid.savec                 C   s"   dd t | jD }dd| S )Nc                 S   s    g | ]\}}d | t | qS )z	Plot[%d]:rd   )r9   r:   plotr   r   r   rf     s   z$PlotGrid.__str__.<locals>.<listcomp>zPlotGrid object containing:
rg   )rh   rU   ri   )rJ   Z	plot_strsr   r   r   rj     s    zPlotGrid.__str__)rw   rx   ry   rz   rM   r^   ra   rj   r   r   r   r   r|   Z  s
   K.r|   c                       sP   e Zd ZdZdZdZdZdZdZdZ	 fddZ
edd Zedd Z  ZS )	rq   a  Base class for the data objects containing stuff to be plotted.

    Explanation
    ===========

    The backend should check if it supports the data series that is given.
    (e.g. TextBackend supports only LineOver1DRangeSeries).
    It is the backend responsibility to know how to use the class of
    data series that is given.

    Some data series classes are grouped (using a class attribute like is_2Dline)
    according to the api they present (based only on convention). The backend is
    not obliged to use that api (e.g. LineOver1DRangeSeries belongs to the
    is_2Dline group and presents the get_points method, but the
    TextBackend does not use the get_points method).
    Fc                    s   t    d S rk   rL   rM   r_   rW   r   r   rM   &  s    zBaseSeries.__init__c                 C   s   | j | jg}t|S rk   )	is_3Dlineis_3Dsurfaceany)rJ   Zflags3Dr   r   r   is_3D)  s    zBaseSeries.is_3Dc                 C   s   | j | jg}t|S rk   )	is_2Dliner   r   )rJ   Z
flagslinesr   r   r   is_line1  s    zBaseSeries.is_line)rw   rx   ry   rz   r   r   r   
is_contouris_implicitis_parametricrM   propertyr   r   r{   r   r   rW   r   rq     s   
rq   c                       s@   e Zd ZdZdZdZ fddZdd Zdd	 Zd
d Z	  Z
S )Line2DBaseSerieszA base class for 2D lines.

    - adding the label, steps and only_integers options
    - making is_2Dline true
    - defining get_segments and get_color_array
    T   c                    s&   t    d | _d| _d| _d | _d S )NF)rL   rM   r   stepsonly_integers
line_colorr_   rW   r   r   rM   G  s
    
zLine2DBaseSeries.__init__c                 C   s   t d}|  }| jdu rt|dkrx||d |d fj dd }||d |d fj dd }||f}nR||d ddd }||d ddd	 }||d ddd }|||f}|S )
a2   Return lists of coordinates for plotting the line.

        Returns
        =======
            x : list
                List of x-coordinates

            y : list
                List of y-coordinates

            z : list
                List of z-coordinates in case of Parametric3DLineSeries
        numpyTr   r   r   N   )r   
get_pointsr   rp   arrayTflattenrepeat)rJ   nppointsxyzr   r   r   get_dataN  s    
$$

zLine2DBaseSeries.get_datac                 C   sb   t dddd td}t| | }|j|jdd| j}|jj	|d d |dd  gddS )	Nz
            The Line2DBaseSeries.get_segments() method is deprecated.

            Instead, use the MatplotlibBackend.get_segments() method, or use
            The get_points() or get_data() methods.
            z1.9zdeprecated-get-segments)deprecated_since_versionactive_deprecations_targetr   r   r   r)   )
r   r   rQ   r   mar   r   reshape_dimconcatenate)rJ   r   r   r   r   r   get_segmentsj  s    
zLine2DBaseSeries.get_segmentsc                 C   s   t d}| j}t|dr||}t|}|dkrL| jrL|  }|t|S tt	t| 
 }|dkrr||d S |dkr||d d  S || S n||| j S d S )Nr   __call__r   r   r   )r   r   r\   	vectorizer   r   get_parameter_pointscenters_of_segmentslistmapr   onesnb_of_points)rJ   r   cfnargsr   	variablesr   r   r   get_color_arrayz  s    


z Line2DBaseSeries.get_color_array)rw   rx   ry   rz   r   r   rM   r   r   r   r{   r   r   rW   r   r   ;  s   r   c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )List2DSeriesz7Representation for a line consisting of list of points.c                    s4   t d}t   ||| _||| _d| _d S )Nr   r   )r   rL   rM   r   list_xlist_yr   )rJ   r   r   r   rW   r   r   rM     s
    
zList2DSeries.__init__c                 C   s   dS )Nz	list plotr   r_   r   r   r   rj     s    zList2DSeries.__str__c                 C   s   | j | jfS rk   )r   r   r_   r   r   r   r     s    zList2DSeries.get_points)rw   rx   ry   rz   rM   rj   r   r{   r   r   rW   r   r     s   r   c                       s8   e Zd ZdZ fddZdd Zdd Zdd	 Z  ZS )
LineOver1DRangeSerieszHRepresentation for a line consisting of a SymPy expression over a range.c                    s   t    t|| _|dd p$| j| _t|d | _t|d | _t|d | _	|dd| _
|dd| _|d	d
| _|dd | _|dd| _d S )Nr   r   r   r   r   ,  adaptiveTdepth   r   r*   r   )rL   rM   r
   exprgetr   varrG   startendr   r   r   r   r*   )rJ   r   var_start_endrV   rW   r   r   rM     s    

zLineOver1DRangeSeries.__init__c                 C   s&   dt | jt | jt | j| jff S )Nz!cartesian line: %s for %s over %s)r   r   r   r   r   r_   r   r   r   rj     s    zLineOver1DRangeSeries.__str__c                    s   j sjs S tjgj g g td fdd j} j}	j 	| 
j|g
j|gd fS )a   Return lists of coordinates for plotting. Depending on the
        ``adaptive`` option, this function will either use an adaptive algorithm
        or it will uniformly sample the expression over the provided range.

        Returns
        =======
            x : list
                List of x-coordinates

            y : list
                List of y-coordinates


        Explanation
        ===========

        The adaptive sampling is done by recursively checking if three
        points are almost collinear. If they are not collinear, then more
        points are added between those points.

        References
        ==========

        .. [1] Adaptive polygonal approximation of parametric curves,
               Luiz Henrique de Figueiredo.

        r   c           
         s4  dj  d  }jdkrPd| d ||d | d     }n| d ||d | d    } |}||g}|jkr|d  |d  n|dk r؈| ||d  |||d  nX| d du r|d du rjdkr| d |d d}n| d |d d}t	t
 |}td	d
 |D s0tt|d D ]V}	||	 du r||	d  du s`||	 ||	 g||	d  ||	d  g|d  q`nv| d du s|d du s|d du st| ||s| ||d  |||d  n|d  |d  dS )a   Samples recursively if three points are almost collinear.
                For depth < 6, points are added irrespective of whether they
                satisfy the collinearity condition or not. The maximum depth
                allowed is 12.
                ?皙?log
   r   r      Nc                 s   s   | ]}|d u V  qd S rk   r   )r9   r   r   r   r   r;     r<   zCLineOver1DRangeSeries.get_points.<locals>.sample.<locals>.<genexpr>)randomrandr*   log10r   r   rt   logspacelinspacer   r   r?   rangerp   flat)
pqr   r   xnewynew	new_pointxarrayyarrayr:   r   r   samplerJ   x_coordsy_coordsr   r   r     s@    

 
*
z0LineOver1DRangeSeries.get_points.<locals>.sampler   )r   r   _uniform_samplingr   r   r   r   r   r   rt   r   )rJ   Zf_startZf_endr   r   r   r     s    4


z LineOver1DRangeSeries.get_pointsc                 C   s   t d}| jdu r| jdkrN|jt| jt| jt| jt| j d d}q|jt| jt| jt| jt| j d d}n8| jdkr|j| j| j| jd}n|j| j| j| jd}t	| j
g| j}||}||fS )Nr   Tr   r   num)r   r   r*   r   intr   r   r   r   r   r   r   )rJ   r   r   r   r   r   r   r   r     s    


z'LineOver1DRangeSeries._uniform_sampling)	rw   rx   ry   rz   rM   rj   r   r   r{   r   r   rW   r   r     s
   `r   c                       sD   e Zd ZdZdZ fddZdd Zdd Zd	d
 Zdd Z	  Z
S )Parametric2DLineSerieszZRepresentation for a line consisting of two parametric SymPy expressions
    over a range.Tc                    s   t    t|| _t|| _|dd p6t| j| j| _t|d | _t	|d | _
t	|d | _|dd| _|dd| _|d	d
| _|dd | _d S )Nr   r   r   r   r   r   r   Tr   r   r   )rL   rM   r
   expr_xexpr_yr   r   r   r   rG   r   r   r   r   r   r   )rJ   r   r   r   rV   rW   r   r   rM   -  s    


zParametric2DLineSeries.__init__c                 C   s.   dt | jt | jt | jt | j| jff S )Nz2parametric cartesian line: (%s, %s) for %s over %s)r   r   r   r   r   r   r_   r   r   r   rj   ;  s    zParametric2DLineSeries.__str__c                 C   s   t d}|j| j| j| jdS Nr   r   r   r   r   r   r   rJ   r   r   r   r   r   @  s    z+Parametric2DLineSeries.get_parameter_pointsc                 C   s@   |   }t| jg| j}t| jg| j}||}||}||fS rk   )r   r   r   r   r   )rJ   paramfxfyr   r   r   r   r   r   D  s    z(Parametric2DLineSeries._uniform_samplingc                    s   j s S tjgj tjgjg g  fdd j}j}||g} j}j}||g}| | jj||d fS )a   Return lists of coordinates for plotting. Depending on the
        ``adaptive`` option, this function will either use an adaptive algorithm
        or it will uniformly sample the expression over the provided range.

        Returns
        =======
            x : list
                List of x-coordinates

            y : list
                List of y-coordinates


        Explanation
        ===========

        The adaptive sampling is done by recursively checking if three
        points are almost collinear. If they are not collinear, then more
        points are added between those points.

        References
        ==========

        .. [1] Adaptive polygonal approximation of parametric curves,
            Luiz Henrique de Figueiredo.

        c                    sL  t d}d|j d  }| |||    } |}|}	|||	g}
|jkrr|d  |d  n|dk r| |||
|d  |||
||d  n|d du r|d du s|d du r|d du r|| |d}tt |}tt|}t	d	d
 t
||D sHtt|d D ]}|| durN|| dusr||d  dur.||d  dur.|| || g}||d  ||d  g}|| || |||d  q.n|d du s|d du s|d du s|d du st||
|s,| |||
|d  |||
||d  n|d  |d  dS )z Samples recursively if three points are almost collinear.
            For depth < 6, points are added irrespective of whether they
            satisfy the collinearity condition or not. The maximum depth
            allowed is 12.
            r   r   r   r   r   r   Nr   c                 s   s"   | ]\}}|d u o|d u V  qd S rk   r   )r9   r   r   r   r   r   r;     s   zDParametric2DLineSeries.get_points.<locals>.sample.<locals>.<genexpr>)r   r   r   r   r   rt   r   r   r   r?   zipr   rp   r   )Zparam_pZparam_qr   r   r   r   r   Z	param_newr   r   r   Zparam_arrayx_arrayy_arrayr:   Zpoint_aZpoint_bf_xZf_yr   rJ   r   r   r   r   r   p  sZ    







z1Parametric2DLineSeries.get_points.<locals>.sampler   )	r   r   r   r   r   r   r   r   rt   )rJ   Z	f_start_xZ	f_start_yr   Zf_end_xZf_end_yr   r   r   r   r   L  s"    6





z!Parametric2DLineSeries.get_points)rw   rx   ry   rz   r   rM   rj   r   r   r   r{   r   r   rW   r   r   '  s   r   c                       s,   e Zd ZdZdZdZdZ fddZ  ZS )Line3DBaseSerieszSA base class for 3D lines.

    Most of the stuff is derived from Line2DBaseSeries.FTr   c                    s   t    d S rk   r   r_   rW   r   r   rM     s    zLine3DBaseSeries.__init__)	rw   rx   ry   rz   r   r   r   rM   r{   r   r   rW   r   r     s
   r   c                       s<   e Zd ZdZdZ fddZdd Zdd Zd	d
 Z  Z	S )Parametric3DLineSeriesz^Representation for a 3D line consisting of three parametric SymPy
    expressions and a range.Tc                    s   t    t|| _t|| _t|| _|dd p@t| j| j| _t|d | _	t
|d | _t
|d | _|dd| _|dd | _d | _d | _d | _d S )Nr   r   r   r   r   r   r   )rL   rM   r
   r   r   expr_zr   r   r   r   rG   r   r   r   r   _xlim_ylim_zlim)rJ   r   r   r   r   rV   rW   r   r   rM     s    



zParametric3DLineSeries.__init__c                 C   s6   dt | jt | jt | jt | jt | j| jff S )Nz93D parametric cartesian line: (%s, %s, %s) for %s over %s)r   r   r   r   r   r   r   r_   r   r   r   rj     s    zParametric3DLineSeries.__str__c                 C   s   t d}|j| j| j| jdS r   r   r   r   r   r   r     s    z+Parametric3DLineSeries.get_parameter_pointsc           	      C   s   t d}|  }t| jg| j}t| jg| j}t| jg| j}||}||}||}|j||jd}|j||jd}|j||jd}|j	
|}|j	
|}|j	
|}||||f| _||||f| _||||f| _|||fS Nr   dtype)r   r   r   r   r   r   r   r   float64r   masked_invalidaminamaxr   r   r   )	rJ   r   r   r   r   fzr   r   Zlist_zr   r   r   r     s$    z!Parametric3DLineSeries.get_points)
rw   rx   ry   rz   r   rM   rj   r   r   r{   r   r   rW   r   r     s   r   c                       s,   e Zd ZdZdZ fddZdd Z  ZS )SurfaceBaseSerieszA base class for 3D surfaces.Tc                    s   t    d | _d S rk   )rL   rM   surface_colorr_   rW   r   r   rM     s    
zSurfaceBaseSeries.__init__c                 C   s   t d}| j}t|tr||}t|}| jrfttt	| 
 }|dkrV||d S |dkrf|| S ttt	|  }|dkr||d S |dkr||d d  S || S n:t| tr||t| j| j S ||t| j| j S d S )Nr   r   r   r   )r   r   r   r   r   r   r   r   r   centers_of_facesget_parameter_meshes
get_meshesSurfaceOver2DRangeSeriesr   minnb_of_points_xnb_of_points_ynb_of_points_unb_of_points_v)rJ   r   r   r   r   r   r   r   r   r     s(    



z!SurfaceBaseSeries.get_color_array)rw   rx   ry   rz   r   rM   r   r{   r   r   rW   r   r     s   r   c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )r   zRRepresentation for a 3D surface consisting of a SymPy expression and 2D
    range.c                    s   t    t|| _t|d | _t|d | _t|d | _t|d | _t|d | _	t|d | _
|dd| _|dd| _|dd | _| j| jf| _| j	| j
f| _d S )Nr   r   r   r  2   r  r   )rL   rM   r
   r   var_xrG   start_xend_xvar_ystart_yend_yr   r  r  r   r   r   )rJ   r   var_start_end_xvar_start_end_yrV   rW   r   r   rM      s    

z!SurfaceOver2DRangeSeries.__init__c                 C   s<   dt | jt | jt | j| jft | jt | j| jff S )Nz3cartesian surface: %s for %s over %s and %s over %sr   r   r  r  r  r	  r
  r  r_   r   r   r   rj   0  s    z SurfaceOver2DRangeSeries.__str__c                 C   s   t d}||j| j| j| jd|j| j| j| jd\}}t	| j
| jf| j}|||}|j||jd}|j|}||||f| _|||fS )Nr   r   r   )r   meshgridr   r  r  r  r
  r  r  r   r  r	  r   r   r   r   r   r   r   r   )rJ   r   mesh_xmesh_yr   mesh_zr   r   r   r   9  s    
z#SurfaceOver2DRangeSeries.get_meshes)rw   rx   ry   rz   rM   rj   r   r{   r   r   rW   r   r     s   	r   c                       s<   e Zd ZdZdZ fddZdd Zdd Zd	d
 Z  Z	S )ParametricSurfaceSerieszaRepresentation for a 3D surface consisting of three parametric SymPy
    expressions and a range.Tc                    s   t    t|| _t|| _t|| _t|d | _t|d | _t|d | _	t|d | _
t|d | _t|d | _|dd| _|dd| _|dd | _d S )Nr   r   r   r  r  r  r   )rL   rM   r
   r   r   r   var_urG   start_uend_uvar_vstart_vend_vr   r  r  r   )rJ   r   r   r   Zvar_start_end_uZvar_start_end_vrV   rW   r   r   rM   M  s    



z ParametricSurfaceSeries.__init__c              
   C   sL   dt | jt | jt | jt | jt | j| jft | jt | j| j	ff S )NzHparametric cartesian surface: (%s, %s, %s) for %s over %s and %s over %s)
r   r   r   r   r  r  r  r  r  r  r_   r   r   r   rj   ^  s    zParametricSurfaceSeries.__str__c                 C   s8   t d}||j| j| j| jd|j| j| j| jdS r   )	r   r  r   r  r  r  r  r  r  r   r   r   r   r   i  s    z,ParametricSurfaceSeries.get_parameter_meshesc           
      C   s  t d}|  \}}t| j| jf| j}t| j| jf| j}t| j| jf| j}|||}|||}|||}	|j||j	d}|j||j	d}|j|	|j	d}	|j
|}|j
|}|j
|	}	||||f| _||||f| _||	||	f| _|||	fS r   )r   r   r   r  r  r   r   r   r   r   r   r   r   r   r   r   r   )
rJ   r   Zmesh_uZmesh_vr   r   r   r  r  r  r   r   r   r   p  s$    


z"ParametricSurfaceSeries.get_meshes)
rw   rx   ry   rz   r   rM   rj   r   r   r{   r   r   rW   r   r  G  s   r  c                       s4   e Zd ZdZdZ fddZdd Zdd Z  ZS )	ContourSeriesz"Representation for a contour plot.Tc                    s   t    d| _d| _t|| _t|d | _t|d | _t|d | _	t|d | _
t|d | _t|d | _| j| _| j| j	f| _| j| jf| _d S )Nr  r   r   r   )rL   rM   r  r  r
   r   r  rG   r  r  r	  r
  r  r   r   r   r   )rJ   r   r  r  rW   r   r   rM     s    

zContourSeries.__init__c                 C   s<   dt | jt | jt | j| jft | jt | j| jff S )Nz)contour: %s for %s over %s and %s over %sr  r_   r   r   r   rj     s    zContourSeries.__str__c                 C   s`   t d}||j| j| j| jd|j| j| j| jd\}}t	| j
| jf| j}|||||fS r   )r   r  r   r  r  r  r
  r  r  r   r  r	  r   )rJ   r   r  r  r   r   r   r   r     s    zContourSeries.get_meshes)	rw   rx   ry   rz   r   rM   rj   r   r{   r   r   rW   r   r    s
   	r  c                       s8   e Zd ZdZ fddZdd Zdd Zdd	 Z  ZS )
rS   a(
  Base class for all backends. A backend represents the plotting library,
    which implements the necessary functionalities in order to use SymPy
    plotting functions.

    How the plotting module works:

    1. Whenever a plotting function is called, the provided expressions are
        processed and a list of instances of the :class:`BaseSeries` class is
        created, containing the necessary information to plot the expressions
        (e.g. the expression, ranges, series name, ...). Eventually, these
        objects will generate the numerical data to be plotted.
    2. A :class:`~.Plot` object is instantiated, which stores the list of
        series and the main attributes of the plot (e.g. axis labels, title, ...).
    3. When the ``show`` command is executed, a new backend is instantiated,
        which loops through each series object to generate and plot the
        numerical data. The backend is also going to set the axis labels, title,
        ..., according to the values stored in the Plot instance.

    The backend should check if it supports the data series that it is given
    (e.g. :class:`TextBackend` supports only :class:`LineOver1DRangeSeries`).

    It is the backend responsibility to know how to use the class of data series
    that it's given. Note that the current implementation of the ``*Series``
    classes is "matplotlib-centric": the numerical data returned by the
    ``get_points`` and ``get_meshes`` methods is meant to be used directly by
    Matplotlib. Therefore, the new backend will have to pre-process the
    numerical data to make it compatible with the chosen plotting library.
    Keep in mind that future SymPy versions may improve the ``*Series`` classes
    in order to return numerical data "non-matplotlib-centric", hence if you code
    a new backend you have the responsibility to check if its working on each
    SymPy release.

    Please explore the :class:`MatplotlibBackend` source code to understand how a
    backend should be coded.

    Methods
    =======

    In order to be used by SymPy plotting functions, a backend must implement
    the following methods:

    * show(self): used to loop over the data series, generate the numerical
        data, plot it and set the axis labels, title, ...
    * save(self, path): used to save the current plot to the specified file
        path.
    * close(self): used to close the current plot backend (note: some plotting
        library does not support this functionality. In that case, just raise a
        warning).

    See also
    ========

    MatplotlibBackend
    c                    s   t    || _d S rk   )rL   rM   parentrJ   r  rW   r   r   rM     s    
zBaseBackend.__init__c                 C   s   t d S rk   NotImplementedErrorr_   r   r   r   r^     s    zBaseBackend.showc                 C   s   t d S rk   r  rb   r   r   r   ra     s    zBaseBackend.savec                 C   s   t d S rk   r  r_   r   r   r   r]     s    zBaseBackend.close)	rw   rx   ry   rz   rM   r^   ra   r]   r{   r   r   rW   r   rS     s
   6rS   c                       sV   e Zd ZdZ fddZedddZdd Zd	d
 Zdd Z	dd Z
dd Z  ZS )MatplotlibBackendzd This class implements the functionalities to use Matplotlib with SymPy
    plotting functions.
    c           
   
      s  t  | tddg didtfd| _| jj| _| jj| _| jjj	| _	t
| jdd}|dkrrt|d |d	  }t| jtrd
\}}| jjg}n&t| jtr| jj| jj }}| jj}g | _| jj|jd| _t|D ]\}}dd |D }t|rt|stdqt|rNtdddgid}	| j| jj|||d d|d qt|s| j| jj|||d |d | j| jd d | j| jd d | j| jd d | j| jd d | j| j !d | j| j"!d qd S )N
matplotlibfromlist)pyplotcmcollections1.1.0)import_kwargsmin_module_versioncatchr%   r   r   r   )r   r   )figsizec                 S   s   g | ]
}|j qS r   )r   )r9   re   r   r   r   rf     r<   z.MatplotlibBackend.__init__.<locals>.<listcomp>z,The matplotlib backend cannot mix 2D and 3D.mpl_toolkitsmplot3dr&  Z3d)
projectionaspect)r.  leftzerorightnonebottomtop)#rL   rM   r   RuntimeErrorr   r"  pltr#  r$  LineCollectionr7   r  rG   r   r   rN   r|   r}   r~   axfigurer4   figrh   r   r?   rD   rt   add_subplotspinesset_position	set_colorZxaxisZset_ticks_positionZyaxis)
rJ   r  r.  r}   r~   series_listr:   seriesZare_3Dr*  rW   r   r   rM     sH    




$ zMatplotlibBackend.__init__Nc                 C   sh   t d}|dur d}| ||f}nd}| |f}|j|jdd|}|jj|dd |dd gddS )a   Convert two list of coordinates to a list of segments to be used
        with Matplotlib's :external:class:`~matplotlib.collections.LineCollection`.

        Parameters
        ==========
            x : list
                List of x-coordinates

            y : list
                List of y-coordinates

            z : list
                List of z-coordinates for a 3D line.
        r   Nr   r   r   r   r   )r   r   r   r   r   r   )r   r   r   r   dimr   r   r   r   r   1  s    zMatplotlibBackend.get_segmentsc           .   
   C   s  t d}t dddgid}g g g   }}}|D ]}	|	jr|	 \}
}t|	jttfs`t|	jr| |
|}| 	|}|
|	  || n t|	j}|j|
|||	jd\}q.|	jr|j|	   q.|	jrz|	 \}
}}t|	jttfst|	jr4|jj}| |
||}||}|
|	  || n t|	j}|j|
||||	jd ||	j ||	j ||	j q.|	jr|	 \}
}}|j|
||t| jd| jjddd	d
}t|	j ttt!fr|	 }|"|j#}|
| n|$|	j  ||	j ||	j ||	j q.|	j%r|	& }t'|dkr`t(|d \}
}|j)|
||	jdd nT| j*j+j,}|d|	jg}|\}}}}|dkr|j||||d n|j-||||d q.t.d/|q.|jj0}t||s|j1|2 |3 d n|r<|4|}|5|d d df |6|d d df f}|7| n|7ddg |r|4|}|5|d d df |6|d d df f}|8| n|8ddg |r|4|}|5|d d df |6|d d df f}|9| n|9ddg |j:rt||s|;|j: |j<r6t||s6|=|j< t||rP| j*j>dkr\|?|j@ |jArD|jA}t||rxn|dkr|jBd Cd |jBd Cd n|dkr|D \}} |E \}!}"||  dkrdnd}#|!|" dkrdnd}$|jBd C|# |jBd C|$ n0|jBd Cd|d f |jBd Cd|d f |jFsT|G  |jHrt|H rt|jIJ|jH |jKr|L|jK |M|jK |jNr|O|jN |jPrt|jP}%|jQ|%dd |jRrt|jR}&|jS|&dd t||r|jTrt|jT}'|jU|'dd |jVr:|jVD ]}(|jWf i |( q"|jXrr|jXD ](})|)Y }*|*Zd}+|j|+i |* qH|j[r|j[D ]$},| j*j\j]f i |,}-|^|- q|j)r|j_f i |j) |j`r|7|j` |jar|8|ja d S )Nr   r*  r!  r+  r,  )r   colorZviridisr   r   )cmaprstridecstride	linewidthr   r   None)Z	facecolorZ	edgecolorwhitecontour)rC  zc{} is not supported in the SymPy plotting module with matplotlib backend. Please report this issue.)scalexZscaleyz1.2.0centerr/  r3  r   )datar   rL  )r   r   )position)r   r   rU   )br   r   r   r   r   r   rG   callabler   r7  Z	set_arrayr   Zadd_collectionr   r   r   r   rI  r   r   r+  art3dZLine3DCollectionrt   r   r   r   r   plot_surfacer7   r#  Zjetr   r   r   r4   r>  r   Z
get_rasterrp   _matplotlib_listr2   r   colorsListedColormapZcontourfr  rE   Axes3DZautoscale_viewZget_autoscalex_onZget_autoscaley_onr   r   r   set_xlimset_ylimZset_zlimr*   Z
set_xscaler+   Z
set_yscale__version__Zset_autoscale_onr-   r(   r<  r=  Zget_xlimZget_ylimr)   Zset_axis_offr,   Zlegend_Zset_visibler.   Zset_xmarginZset_ymarginr!   Z	set_titler"   
set_xlabelr#   
set_ylabelr$   
set_zlabelr/   annotater0   copypopr1   ZpatchesZ	RectangleZ	add_patchZfill_betweenr&   r'   ).rJ   r@  r8  r  r   r*  ZxlimsZylimsZzlimsre   r   r   segmentsZ
collectionlblliner   rO  Zcolor_arrayr   rS  colormapr   r   ZzarrayZ	plot_typerT  r&   r'   ZzlimvalxlxhZylZyhpos_leftZ
pos_bottomZxlblZylblZzlblamarkermrU   rrectr   r   r   _process_seriesK  s    










,
,
,









z!MatplotlibBackend._process_seriesc                 C   sh   | j }t|tr|jg}n|j}tt|| jD ]2\}\}}t| j trT| j j| }| 	||| q0dS )za
        Iterates over every ``Plot`` object and further calls
        _process_series()
        N)
r  r   r   rN   rh   r   r8  r|   rU   rk  )rJ   r  r?  r:   r@  r8  r   r   r   process_series  s    

z MatplotlibBackend.process_seriesc                 C   s.   |    tr"| j  | j  n|   d S rk   )rl  r   r:  Ztight_layoutr6  r^   r]   r_   r   r   r   r^     s
    
zMatplotlibBackend.showc                 C   s   |    | j| d S rk   )rl  r:  savefigrb   r   r   r   ra     s    zMatplotlibBackend.savec                 C   s   | j | j d S rk   )r6  r]   r:  r_   r   r   r   r]     s    zMatplotlibBackend.close)N)rw   rx   ry   rz   rM   staticmethodr   rk  rl  r^   ra   r]   r{   r   r   rW   r   r    s   + 2r  c                       s,   e Zd Z fddZdd Zdd Z  ZS )TextBackendc                    s   t  | d S rk   r   r  rW   r   r   rM      s    zTextBackend.__init__c                 C   s`   t sd S t| jjdkr"tdn:t| jjd ts>tdn| jjd }t|j|j	|j
 d S )Nr   z1The TextBackend supports only one graph per Plot.r   z9The TextBackend supports only expressions over a 1D range)r   rp   r  rN   rD   r   r   r   r   r   r   )rJ   serr   r   r   r^   #  s    zTextBackend.showc                 C   s   d S rk   r   r_   r   r   r   r]   0  s    zTextBackend.close)rw   rx   ry   rM   r^   r]   r{   r   r   rW   r   ro    s   ro  c                   @   s   e Zd Zdd ZdS )r   c                 C   s(   t ddtfd}|rt|S t|S d S )Nr   r%  )r'  r(  )r   r5  r  ro  )clsr  r   r   r   r   __new__5  s    zDefaultBackend.__new__N)rw   rx   ry   rr  r   r   r   r   r   4  s   r   )r   textr    c                 C   s.   t d}||| d d | dd  fdS )Nr   r   r   r   )r   meanvstackr   r   r   r   r   r   H  s    r   c                 C   sb   t d}||| d dd df | dd d df | d ddd f | d dd df fdS )Nr   r   r   r   )r   rt  dstackrv  r   r   r   r   M  s    r   MbP?c                 C   sh   t d}| | |j}|| |j}|||}|j|}|j|}	|||	  }
t|
d |k S )z0Checks whether three points are almost collinearr   r   )r   astyper   dotlinalgnormabs)r   r   r   epsr   Zvector_aZvector_bZdot_productZvector_a_normZvector_b_normZ	cos_thetar   r   r   r   V  s    r   c                 C   s   g }g }t | rd| D ]L}|d }|d }||j|j|j|jdg ||j|j|j|jdg qn|d |d ||fS )zi
    Returns lists for matplotlib ``fill`` command from a list of bounding
    rectangular intervals
    r   r   N)NNNN)rp   rO   r   r   )Zinterval_listZxlistZylist	intervalsZ	intervalxZ	intervalyr   r   r   rQ  f  s    




rQ  )r^   c           	         s   t tt|}t }|D ],}t|tr||jO }t|dkrtdq|rR|	 nt
d} d|  dtd| g }t|dd} fdd|D }t|i  }| r|  |S )	aX  Plots a function of a single variable as a curve.

    Parameters
    ==========

    args :
        The first argument is the expression representing the function
        of single variable to be plotted.

        The last argument is a 3-tuple denoting the range of the free
        variable. e.g. ``(x, 0, 5)``

        Typical usage examples are in the followings:

        - Plotting a single expression with a single range.
            ``plot(expr, range, **kwargs)``
        - Plotting a single expression with the default range (-10, 10).
            ``plot(expr, **kwargs)``
        - Plotting multiple expressions with a single range.
            ``plot(expr1, expr2, ..., range, **kwargs)``
        - Plotting multiple expressions with multiple ranges.
            ``plot((expr1, range1), (expr2, range2), ..., **kwargs)``

        It is best practice to specify range explicitly because default
        range may change in the future if a more advanced default range
        detection algorithm is implemented.

    show : bool, optional
        The default value is set to ``True``. Set show to ``False`` and
        the function will not display the plot. The returned instance of
        the ``Plot`` class can then be used to save or display the plot
        by calling the ``save()`` and ``show()`` methods respectively.

    line_color : string, or float, or function, optional
        Specifies the color for the plot.
        See ``Plot`` to see how to set color for the plots.
        Note that by setting ``line_color``, it would be applied simultaneously
        to all the series.

    title : str, optional
        Title of the plot. It is set to the latex representation of
        the expression, if the plot has only one expression.

    label : str, optional
        The label of the expression in the plot. It will be used when
        called with ``legend``. Default is the name of the expression.
        e.g. ``sin(x)``

    xlabel : str or expression, optional
        Label for the x-axis.

    ylabel : str or expression, optional
        Label for the y-axis.

    xscale : 'linear' or 'log', optional
        Sets the scaling of the x-axis.

    yscale : 'linear' or 'log', optional
        Sets the scaling of the y-axis.

    axis_center : (float, float), optional
        Tuple of two floats denoting the coordinates of the center or
        {'center', 'auto'}

    xlim : (float, float), optional
        Denotes the x-axis limits, ``(min, max)```.

    ylim : (float, float), optional
        Denotes the y-axis limits, ``(min, max)```.

    annotations : list, optional
        A list of dictionaries specifying the type of annotation
        required. The keys in the dictionary should be equivalent
        to the arguments of the :external:mod:`matplotlib`'s
        :external:meth:`~matplotlib.axes.Axes.annotate` method.

    markers : list, optional
        A list of dictionaries specifying the type the markers required.
        The keys in the dictionary should be equivalent to the arguments
        of the :external:mod:`matplotlib`'s :external:func:`~matplotlib.pyplot.plot()` function
        along with the marker related keyworded arguments.

    rectangles : list, optional
        A list of dictionaries specifying the dimensions of the
        rectangles to be plotted. The keys in the dictionary should be
        equivalent to the arguments of the :external:mod:`matplotlib`'s
        :external:class:`~matplotlib.patches.Rectangle` class.

    fill : dict, optional
        A dictionary specifying the type of color filling required in
        the plot. The keys in the dictionary should be equivalent to the
        arguments of the :external:mod:`matplotlib`'s
        :external:meth:`~matplotlib.axes.Axes.fill_between` method.

    adaptive : bool, optional
        The default value is set to ``True``. Set adaptive to ``False``
        and specify ``nb_of_points`` if uniform sampling is required.

        The plotting uses an adaptive algorithm which samples
        recursively to accurately plot. The adaptive algorithm uses a
        random point near the midpoint of two points that has to be
        further sampled. Hence the same plots can appear slightly
        different.

    depth : int, optional
        Recursion depth of the adaptive algorithm. A depth of value
        `n` samples a maximum of `2^{n}` points.

        If the ``adaptive`` flag is set to ``False``, this will be
        ignored.

    nb_of_points : int, optional
        Used when the ``adaptive`` is set to ``False``. The function
        is uniformly sampled at ``nb_of_points`` number of points.

        If the ``adaptive`` flag is set to ``True``, this will be
        ignored.

    size : (float, float), optional
        A tuple in the form (width, height) in inches to specify the size of
        the overall figure. The default value is set to ``None``, meaning
        the size will be set by the default backend.

    Examples
    ========

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

       >>> from sympy import symbols
       >>> from sympy.plotting import plot
       >>> x = symbols('x')

    Single Plot

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

       >>> plot(x**2, (x, -5, 5))
       Plot object containing:
       [0]: cartesian line: x**2 for x over (-5.0, 5.0)

    Multiple plots with single range.

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

       >>> plot(x, x**2, x**3, (x, -5, 5))
       Plot object containing:
       [0]: cartesian line: x for x over (-5.0, 5.0)
       [1]: cartesian line: x**2 for x over (-5.0, 5.0)
       [2]: cartesian line: x**3 for x over (-5.0, 5.0)

    Multiple plots with different ranges.

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

       >>> plot((x**2, (x, -6, 6)), (x, (x, -5, 5)))
       Plot object containing:
       [0]: cartesian line: x**2 for x over (-6.0, 6.0)
       [1]: cartesian line: x for x over (-5.0, 5.0)

    No adaptive sampling.

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

       >>> plot(x**2, adaptive=False, nb_of_points=400)
       Plot object containing:
       [0]: cartesian line: x**2 for x over (-10.0, 10.0)

    See Also
    ========

    Plot, LineOver1DRangeSeries

    r   zMThe same variable should be used in all univariate expressions being plotted.r   r"   r#   r   c                    s   g | ]}t |i  qS r   )r   r9   rv   rV   r   r   rf   M  r<   zplot.<locals>.<listcomp>)r   r   r
   setr   r   free_symbolsrp   rD   r]  r	   
setdefaultr   check_argumentsr   r^   )	r^   rU   rV   freerf  r   r@  	plot_exprplotsr   r  r   r     s(     >

r   c                    sN   t tt|}g }t|dd} fdd|D }t|i  }| rJ|  |S )a  
    Plots a 2D parametric curve.

    Parameters
    ==========

    args
        Common specifications are:

        - Plotting a single parametric curve with a range
            ``plot_parametric((expr_x, expr_y), range)``
        - Plotting multiple parametric curves with the same range
            ``plot_parametric((expr_x, expr_y), ..., range)``
        - Plotting multiple parametric curves with different ranges
            ``plot_parametric((expr_x, expr_y, range), ...)``

        ``expr_x`` is the expression representing $x$ component of the
        parametric function.

        ``expr_y`` is the expression representing $y$ component of the
        parametric function.

        ``range`` is a 3-tuple denoting the parameter symbol, start and
        stop. For example, ``(u, 0, 5)``.

        If the range is not specified, then a default range of (-10, 10)
        is used.

        However, if the arguments are specified as
        ``(expr_x, expr_y, range), ...``, you must specify the ranges
        for each expressions manually.

        Default range may change in the future if a more advanced
        algorithm is implemented.

    adaptive : bool, optional
        Specifies whether to use the adaptive sampling or not.

        The default value is set to ``True``. Set adaptive to ``False``
        and specify ``nb_of_points`` if uniform sampling is required.

    depth :  int, optional
        The recursion depth of the adaptive algorithm. A depth of
        value $n$ samples a maximum of $2^n$ points.

    nb_of_points : int, optional
        Used when the ``adaptive`` flag is set to ``False``.

        Specifies the number of the points used for the uniform
        sampling.

    line_color : string, or float, or function, optional
        Specifies the color for the plot.
        See ``Plot`` to see how to set color for the plots.
        Note that by setting ``line_color``, it would be applied simultaneously
        to all the series.

    label : str, optional
        The label of the expression in the plot. It will be used when
        called with ``legend``. Default is the name of the expression.
        e.g. ``sin(x)``

    xlabel : str, optional
        Label for the x-axis.

    ylabel : str, optional
        Label for the y-axis.

    xscale : 'linear' or 'log', optional
        Sets the scaling of the x-axis.

    yscale : 'linear' or 'log', optional
        Sets the scaling of the y-axis.

    axis_center : (float, float), optional
        Tuple of two floats denoting the coordinates of the center or
        {'center', 'auto'}

    xlim : (float, float), optional
        Denotes the x-axis limits, ``(min, max)```.

    ylim : (float, float), optional
        Denotes the y-axis limits, ``(min, max)```.

    size : (float, float), optional
        A tuple in the form (width, height) in inches to specify the size of
        the overall figure. The default value is set to ``None``, meaning
        the size will be set by the default backend.

    Examples
    ========

    .. plot::
       :context: reset
       :format: doctest
       :include-source: True

       >>> from sympy import plot_parametric, symbols, cos, sin
       >>> u = symbols('u')

    A parametric plot with a single expression:

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

       >>> plot_parametric((cos(u), sin(u)), (u, -5, 5))
       Plot object containing:
       [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0)

    A parametric plot with multiple expressions with the same range:

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

       >>> plot_parametric((cos(u), sin(u)), (u, cos(u)), (u, -10, 10))
       Plot object containing:
       [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-10.0, 10.0)
       [1]: parametric cartesian line: (u, cos(u)) for u over (-10.0, 10.0)

    A parametric plot with multiple expressions with different ranges
    for each curve:

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

       >>> plot_parametric((cos(u), sin(u), (u, -5, 5)),
       ...     (cos(u), u, (u, -5, 5)))
       Plot object containing:
       [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0)
       [1]: parametric cartesian line: (cos(u), u) for u over (-5.0, 5.0)

    Notes
    =====

    The plotting uses an adaptive algorithm which samples recursively to
    accurately plot the curve. The adaptive algorithm uses a random point
    near the midpoint of two points that has to be further sampled.
    Hence, repeating the same plot command can give slightly different
    results because of the random sampling.

    If there are multiple plots, then the same optional arguments are
    applied to all the plots drawn in the same canvas. If you want to
    set these options separately, you can index the returned ``Plot``
    object and set it.

    For example, when you specify ``line_color`` once, it would be
    applied simultaneously to both series.

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

        >>> from sympy import pi
        >>> expr1 = (u, cos(2*pi*u)/2 + 1/2)
        >>> expr2 = (u, sin(2*pi*u)/2 + 1/2)
        >>> p = plot_parametric(expr1, expr2, (u, 0, 1), line_color='blue')

    If you want to specify the line color for the specific series, you
    should index each item and apply the property manually.

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

        >>> p[0].line_color = 'red'
        >>> p.show()

    See Also
    ========

    Plot, Parametric2DLineSeries
    r   r   c                    s   g | ]}t |i  qS r   )r   r  r  r   r   rf     r<   z#plot_parametric.<locals>.<listcomp>)r   r   r
   r  r   r^   r^   rU   rV   r@  r  r  r   r  r   plot_parametricU  s     6r  c                    sr   t tt|}g }t|dd} fdd|D } dd  dd  d	d
 t|i  }| rn|  |S )a  
    Plots a 3D parametric line plot.

    Usage
    =====

    Single plot:

    ``plot3d_parametric_line(expr_x, expr_y, expr_z, range, **kwargs)``

    If the range is not specified, then a default range of (-10, 10) is used.

    Multiple plots.

    ``plot3d_parametric_line((expr_x, expr_y, expr_z, range), ..., **kwargs)``

    Ranges have to be specified for every expression.

    Default range may change in the future if a more advanced default range
    detection algorithm is implemented.

    Arguments
    =========

    expr_x : Expression representing the function along x.

    expr_y : Expression representing the function along y.

    expr_z : Expression representing the function along z.

    range : (:class:`~.Symbol`, float, float)
        A 3-tuple denoting the range of the parameter variable, e.g., (u, 0, 5).

    Keyword Arguments
    =================

    Arguments for ``Parametric3DLineSeries`` class.

    nb_of_points : The range is uniformly sampled at ``nb_of_points``
    number of points.

    Aesthetics:

    line_color : string, or float, or function, optional
        Specifies the color for the plot.
        See ``Plot`` to see how to set color for the plots.
        Note that by setting ``line_color``, it would be applied simultaneously
        to all the series.

    label : str
        The label to the plot. It will be used when called with ``legend=True``
        to denote the function with the given label in the plot.

    If there are multiple plots, then the same series arguments are applied to
    all the plots. If you want to set these options separately, you can index
    the returned ``Plot`` object and set it.

    Arguments for ``Plot`` class.

    title : str
        Title of the plot.

    size : (float, float), optional
        A tuple in the form (width, height) in inches to specify the size of
        the overall figure. The default value is set to ``None``, meaning
        the size will be set by the default backend.

    Examples
    ========

    .. plot::
       :context: reset
       :format: doctest
       :include-source: True

       >>> from sympy import symbols, cos, sin
       >>> from sympy.plotting import plot3d_parametric_line
       >>> u = symbols('u')

    Single plot.

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

       >>> plot3d_parametric_line(cos(u), sin(u), u, (u, -5, 5))
       Plot object containing:
       [0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0)


    Multiple plots.

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

       >>> plot3d_parametric_line((cos(u), sin(u), u, (u, -5, 5)),
       ...     (sin(u), u**2, u, (u, -5, 5)))
       Plot object containing:
       [0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0)
       [1]: 3D parametric cartesian line: (sin(u), u**2, u) for u over (-5.0, 5.0)


    See Also
    ========

    Plot, Parametric3DLineSeries

    r   r   c                    s   g | ]}t |i  qS r   )r   r  r  r   r   rf     r<   z*plot3d_parametric_line.<locals>.<listcomp>r"   r   r#   r   r$   r   r   r   r
   r  r  r   r^   r  r   r  r   plot3d_parametric_line  s    pr  c                    s   t tt|}g }t|dd} fdd|D } d|d j  d|d j  dtd	|d j|d j t|i  }| r|	  |S )
aL  
    Plots a 3D surface plot.

    Usage
    =====

    Single plot

    ``plot3d(expr, range_x, range_y, **kwargs)``

    If the ranges are not specified, then a default range of (-10, 10) is used.

    Multiple plot with the same range.

    ``plot3d(expr1, expr2, range_x, range_y, **kwargs)``

    If the ranges are not specified, then a default range of (-10, 10) is used.

    Multiple plots with different ranges.

    ``plot3d((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)``

    Ranges have to be specified for every expression.

    Default range may change in the future if a more advanced default range
    detection algorithm is implemented.

    Arguments
    =========

    expr : Expression representing the function along x.

    range_x : (:class:`~.Symbol`, float, float)
        A 3-tuple denoting the range of the x variable, e.g. (x, 0, 5).

    range_y : (:class:`~.Symbol`, float, float)
        A 3-tuple denoting the range of the y variable, e.g. (y, 0, 5).

    Keyword Arguments
    =================

    Arguments for ``SurfaceOver2DRangeSeries`` class:

    nb_of_points_x : int
        The x range is sampled uniformly at ``nb_of_points_x`` of points.

    nb_of_points_y : int
        The y range is sampled uniformly at ``nb_of_points_y`` of points.

    Aesthetics:

    surface_color : Function which returns a float
        Specifies the color for the surface of the plot.
        See :class:`~.Plot` for more details.

    If there are multiple plots, then the same series arguments are applied to
    all the plots. If you want to set these options separately, you can index
    the returned ``Plot`` object and set it.

    Arguments for ``Plot`` class:

    title : str
        Title of the plot.

    size : (float, float), optional
        A tuple in the form (width, height) in inches to specify the size of the
        overall figure. The default value is set to ``None``, meaning the size will
        be set by the default backend.

    Examples
    ========

    .. plot::
       :context: reset
       :format: doctest
       :include-source: True

       >>> from sympy import symbols
       >>> from sympy.plotting import plot3d
       >>> x, y = symbols('x y')

    Single plot

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

       >>> plot3d(x*y, (x, -5, 5), (y, -5, 5))
       Plot object containing:
       [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)


    Multiple plots with same range

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

       >>> plot3d(x*y, -x*y, (x, -5, 5), (y, -5, 5))
       Plot object containing:
       [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
       [1]: cartesian surface: -x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)


    Multiple plots with different ranges.

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

       >>> plot3d((x**2 + y**2, (x, -5, 5), (y, -5, 5)),
       ...     (x*y, (x, -3, 3), (y, -3, 3)))
       Plot object containing:
       [0]: cartesian surface: x**2 + y**2 for x over (-5.0, 5.0) and y over (-5.0, 5.0)
       [1]: cartesian surface: x*y for x over (-3.0, 3.0) and y over (-3.0, 3.0)


    See Also
    ========

    Plot, SurfaceOver2DRangeSeries

    r   r   c                    s   g | ]}t |i  qS r   )r   r  r  r   r   rf   	  r<   zplot3d.<locals>.<listcomp>r"   r   r#   r$   r   )
r   r   r
   r  r  r  r	  r   r   r^   r  r   r  r   plot3d  s     "r  c                    sr   t tt|}g }t|dd} fdd|D } dd  dd  d	d
 t|i  }| rn|  |S )a
  
    Plots a 3D parametric surface plot.

    Explanation
    ===========

    Single plot.

    ``plot3d_parametric_surface(expr_x, expr_y, expr_z, range_u, range_v, **kwargs)``

    If the ranges is not specified, then a default range of (-10, 10) is used.

    Multiple plots.

    ``plot3d_parametric_surface((expr_x, expr_y, expr_z, range_u, range_v), ..., **kwargs)``

    Ranges have to be specified for every expression.

    Default range may change in the future if a more advanced default range
    detection algorithm is implemented.

    Arguments
    =========

    expr_x : Expression representing the function along ``x``.

    expr_y : Expression representing the function along ``y``.

    expr_z : Expression representing the function along ``z``.

    range_u : (:class:`~.Symbol`, float, float)
        A 3-tuple denoting the range of the u variable, e.g. (u, 0, 5).

    range_v : (:class:`~.Symbol`, float, float)
        A 3-tuple denoting the range of the v variable, e.g. (v, 0, 5).

    Keyword Arguments
    =================

    Arguments for ``ParametricSurfaceSeries`` class:

    nb_of_points_u : int
        The ``u`` range is sampled uniformly at ``nb_of_points_v`` of points

    nb_of_points_y : int
        The ``v`` range is sampled uniformly at ``nb_of_points_y`` of points

    Aesthetics:

    surface_color : Function which returns a float
        Specifies the color for the surface of the plot. See
        :class:`~Plot` for more details.

    If there are multiple plots, then the same series arguments are applied for
    all the plots. If you want to set these options separately, you can index
    the returned ``Plot`` object and set it.


    Arguments for ``Plot`` class:

    title : str
        Title of the plot.

    size : (float, float), optional
        A tuple in the form (width, height) in inches to specify the size of the
        overall figure. The default value is set to ``None``, meaning the size will
        be set by the default backend.

    Examples
    ========

    .. plot::
       :context: reset
       :format: doctest
       :include-source: True

       >>> from sympy import symbols, cos, sin
       >>> from sympy.plotting import plot3d_parametric_surface
       >>> u, v = symbols('u v')

    Single plot.

    .. plot::
       :context: close-figs
       :format: doctest
       :include-source: True

       >>> plot3d_parametric_surface(cos(u + v), sin(u - v), u - v,
       ...     (u, -5, 5), (v, -5, 5))
       Plot object containing:
       [0]: parametric cartesian surface: (cos(u + v), sin(u - v), u - v) for u over (-5.0, 5.0) and v over (-5.0, 5.0)


    See Also
    ========

    Plot, ParametricSurfaceSeries

    r   r   c                    s   g | ]}t |i  qS r   )r  r  r  r   r   rf   	  r<   z-plot3d_parametric_surface.<locals>.<listcomp>r"   r   r#   r   r$   r   r  r  r   r  r   plot3d_parametric_surface	  s    er  c                 O   s`   t tt|}t|dd}dd |D }t|i |}t|d jdkrPtd| r\|  |S )a#  
    Draws contour plot of a function

    Usage
    =====

    Single plot

    ``plot_contour(expr, range_x, range_y, **kwargs)``

    If the ranges are not specified, then a default range of (-10, 10) is used.

    Multiple plot with the same range.

    ``plot_contour(expr1, expr2, range_x, range_y, **kwargs)``

    If the ranges are not specified, then a default range of (-10, 10) is used.

    Multiple plots with different ranges.

    ``plot_contour((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)``

    Ranges have to be specified for every expression.

    Default range may change in the future if a more advanced default range
    detection algorithm is implemented.

    Arguments
    =========

    expr : Expression representing the function along x.

    range_x : (:class:`Symbol`, float, float)
        A 3-tuple denoting the range of the x variable, e.g. (x, 0, 5).

    range_y : (:class:`Symbol`, float, float)
        A 3-tuple denoting the range of the y variable, e.g. (y, 0, 5).

    Keyword Arguments
    =================

    Arguments for ``ContourSeries`` class:

    nb_of_points_x : int
        The x range is sampled uniformly at ``nb_of_points_x`` of points.

    nb_of_points_y : int
        The y range is sampled uniformly at ``nb_of_points_y`` of points.

    Aesthetics:

    surface_color : Function which returns a float
        Specifies the color for the surface of the plot. See
        :class:`sympy.plotting.Plot` for more details.

    If there are multiple plots, then the same series arguments are applied to
    all the plots. If you want to set these options separately, you can index
    the returned ``Plot`` object and set it.

    Arguments for ``Plot`` class:

    title : str
        Title of the plot.

    size : (float, float), optional
        A tuple in the form (width, height) in inches to specify the size of
        the overall figure. The default value is set to ``None``, meaning
        the size will be set by the default backend.

    See Also
    ========

    Plot, ContourSeries

    r   r   c                 S   s   g | ]}t | qS r   )r  r  r   r   r   rf   	  r<   z plot_contour.<locals>.<listcomp>r   z5Contour Plot cannot Plot for more than two variables.)	r   r   r
   r  r   rp   r  rD   r^   )r^   rU   rV   r  r@  Zplot_contoursr   r   r   plot_contour	  s    Mr  c           
         s  | sg S |dkrt | d trt| |k r6tdtt| D ]}t | | trB qfqBt| d }t| d|  }tt jdd |D  }t| || kr|t| |d   g}nbtdd}g  |D ]} 	t||  qtt|| D ]} 	tt
 |  q|t   g}|S t | d tsZt | d trt| d |kr|d	krtt| D ]N}t | | trt| | |kr qt | | tsft| | | |< qft| d }| d| }td
d |D sJ tt jdd |D  }t||krtd| t| || krpt | | trptdd | |||  D    fdd|D }|S tdd}g  |D ]} 	t||  qt|t| D ]} 	tt
 |  qt    fdd|D }|S nt | d trt| d || kr| D ]x}	t|D ]*}t |	| tstdt|	|  qt|D ]4}t|	||  d	ksRtdt|	||   qRq| S dS )a  
    Checks the arguments and converts into tuples of the
    form (exprs, ranges).

    Examples
    ========

    .. plot::
       :context: reset
       :format: doctest
       :include-source: True

       >>> from sympy import cos, sin, symbols
       >>> from sympy.plotting.plot import check_arguments
       >>> x = symbols('x')
       >>> check_arguments([cos(x), sin(x)], 2, 1)
           [(cos(x), sin(x), (x, -10, 10))]

       >>> check_arguments([x, x**2], 1, 1)
           [(x, (x, -10, 10)), (x**2, (x, -10, 10))]
    r   r   z*len(args) should not be less than expr_lenNc                 S   s   g | ]
}|j qS r   r  )r9   er   r   r   rf   
  r<   z#check_arguments.<locals>.<listcomp>ir   r   c                 s   s"   | ]}|D ]}t |tV  q
qd S rk   )r   r   r9   r   r  r   r   r   r;   )
  r<   z"check_arguments.<locals>.<genexpr>c                 S   s   g | ]}|D ]
}|j qqS r   r  r  r   r   r   rf   *
  s   z?The number of free_symbols in the expression is greater than %dc                 S   s   g | ]}|qS r   r   )r9   Z
range_exprr   r   r   rf   1
  r<   c                    s   g | ]}|  qS r   r   r9   r   rangesr   r   rf   3
  r<   c                    s   g | ]}|  qS r   r   r  r  r   r   rf   ?
  r<   z Expected an expression, given %sz0The ranges should be a tuple of length 3, got %s)r   r   rp   rD   r   r   r   r  unionrt   r   r?   r   )
rU   Zexpr_lenZnb_of_free_symbolsr:   exprsr  r  Zdefault_rangesymbolrv   r   r  r   r  	  s    
 ""



&

r  N)rx  )>rz   collections.abcr   sympy.core.basicr   sympy.core.containersr   sympy.core.exprr   sympy.core.functionr   r   sympy.core.symbolr   r	   sympy.core.sympifyr
   sympy.externalr   sympy.printing.latexr   sympy.utilities.exceptionsr   sympy.utilities.iterablesr   Zexperimental_lambdifyr   r   Zsympy.plotting.textplotr   r   r   r   r   r|   rq   r   r   r   r   r   r   r   r   r  r  rS   r  ro  r   rP   r   r   r   rQ  r   r  r  r  r  r  r  r   r   r   r   <module>   st   
   NT  9#*E/G  
	
 T @} qW