a
    ضa_[                     @   s
  d Z ddlZddl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gZd&d
dZG d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dd Zeddd ZG dd deZdd Zd d! Z d"d# Z!d$d% Z"dS )'z,
Streamline plotting for 2D vector fields.

    N)_apicm
streamplot   -|>皙?      @bothc           4   	   C   sd  t ||}t|}t||}|du r,tjj}|du r:| j}|du rL| j }|du r^t	j
d }i }t|d|
 d}tjg d|d |dkr|d }t|tj}|r|j|jkrtd	g }tj|}n||d
< ||d
< t|tjr|j|jkrtdg |d< n||d< ||d< ||d< ||d< |j|jksB|j|jkrJtdtj|}tj|}t||||||}g }|du rt|jD ]J\}}|||f dkr|||\}}|||}|dur|| qntj|td } | D ]d\}!}"|j|!  kr|j|j krDn n$|j|"  krB|j|j ksn td |!|"q| dddf  |j8  < | dddf  |j8  < | D ]`\}!}"|!|!|"\}}t"|d|j#d }t"|d|j$d }|||}|dur|| q|r |	du rt%&|' |( }	t)*|}g }#g }$|D ]t}|j+\}%}&|,|%|&\}'}(|'|j7 }'|(|j7 }(t-|'|(g.ddd})|#/t0|)dd |)dd g t1t2t3|'t3|(}*t4|*|*d d }+|'|+ |(|+ f},t5|'|+|+d  t5|(|+|+d  f}-t|tjrFt6||%|&dd }.|d /|. |.|+ |d< |r~t6||%|&dd }/||/ ||	|/|+ |d
< t7j8|,|-fd|i|}0|$|0 q,t9j:|#fd|i|}1|j|j|j g|1j;j<dd< |j|j|j g|1j;j=dd< |r"|1>tj0| |1?| |1@|	 | A|1 t	jBC|$}2|$D ]}0| D|0 q<| E  tF|1|2}3|3S )a^  
    Draw streamlines of a vector flow.

    Parameters
    ----------
    x, y : 1D/2D arrays
        Evenly spaced strictly increasing arrays to make a grid.  If 2D, all
        rows of *x* must be equal and all columns of *y* must be equal; i.e.,
        they must be as if generated by ``np.meshgrid(x_1d, y_1d)``.
    u, v : 2D arrays
        *x* and *y*-velocities. The number of rows and columns must match
        the length of *y* and *x*, respectively.
    density : float or (float, float)
        Controls the closeness of streamlines. When ``density = 1``, the domain
        is divided into a 30x30 grid. *density* linearly scales this grid.
        Each cell in the grid can have, at most, one traversing streamline.
        For different densities in each direction, use a tuple
        (density_x, density_y).
    linewidth : float or 2D array
        The width of the stream lines. With a 2D array the line width can be
        varied across the grid. The array must have the same shape as *u*
        and *v*.
    color : color or 2D array
        The streamline color. If given an array, its values are converted to
        colors using *cmap* and *norm*.  The array must have the same shape
        as *u* and *v*.
    cmap : `~matplotlib.colors.Colormap`
        Colormap used to plot streamlines and arrows. This is only used if
        *color* is an array.
    norm : `~matplotlib.colors.Normalize`
        Normalize object used to scale luminance data to 0, 1. If ``None``,
        stretch (min, max) to (0, 1). This is only used if *color* is an array.
    arrowsize : float
        Scaling factor for the arrow size.
    arrowstyle : str
        Arrow style specification.
        See `~matplotlib.patches.FancyArrowPatch`.
    minlength : float
        Minimum length of streamline in axes coordinates.
    start_points : Nx2 array
        Coordinates of starting points for the streamlines in data coordinates
        (the same coordinates as the *x* and *y* arrays).
    zorder : int
        The zorder of the stream lines and arrows.
        Artists with lower zorder values are drawn first.
    maxlength : float
        Maximum length of streamline in axes coordinates.
    integration_direction : {'forward', 'backward', 'both'}, default: 'both'
        Integrate the streamline in forward, backward or both directions.
    data : indexable object, optional
        DATA_PARAMETER_PLACEHOLDER

    Returns
    -------
    StreamplotSet
        Container object with attributes

        - ``lines``: `.LineCollection` of streamlines

        - ``arrows``: `.PatchCollection` containing `.FancyArrowPatch`
          objects representing the arrows half-way along stream lines.

        This container will probably change in the future to allow changes
        to the colormap, alpha, etc. for both lines and arrows, but these
        changes should be backward compatible.
    Nzlines.linewidth
   )
arrowstyleZmutation_scale)r	   forwardbackward)integration_directionr	   g       @z<If 'color' is given, it must match the shape of 'Grid(x, y)'colorz@If 'linewidth' is given, it must match the shape of 'Grid(x, y)'	linewidthzorderz0'u' and 'v' must match the shape of 'Grid(x, y)'r   )Zdtypez2Starting point ({}, {}) outside of data boundariesr      	transform)GGrid
StreamMask	DomainMapmlinesZLine2Dr   Z	transDataZ
_get_linesZget_next_color
matplotlibZrcParamsdictr   Zcheck_in_list
isinstancenpndarrayshape
ValueErrormaZmasked_invalid_get_integrator_gen_starting_points	mask2gridappendZ
asanyarrayfloatcopyx_originwidthy_originheightformat	data2gridclipnxnymcolorsZ	Normalizeminmaxr   Zget_cmapT	grid2dataZ	transposeZreshapeextendZhstackZcumsumhypotdiffZsearchsortedmean
interpgridpatchesZFancyArrowPatchmcollectionsZLineCollectionZsticky_edgesxyZ	set_arrayZset_cmapZset_normZadd_collectioncollectionsZPatchCollectionZ	add_patchZautoscale_viewStreamplotSet)4Zaxesr<   r=   uvdensityr   r   ZcmapZnormZ	arrowsizer   	minlengthr   r   Zstart_points	maxlengthr   gridmaskdmapZline_kwZarrow_kwZuse_multicolor_linesZline_colors	integrateZtrajectoriesxmymxgygtZsp2xsZysZstreamlinesarrowsZtgxZtgyZtxtyZpointssnZ
arrow_tailZ
arrow_headZline_widthsZcolor_valuesplcacZstream_container rV   e/Users/vegardjervell/Documents/master/model/venv/lib/python3.9/site-packages/matplotlib/streamplot.pyr      s    F








&











$,




c                   @   s   e Zd Zdd ZdS )r?   c                 C   s   || _ || _d S N)linesrO   )selfrY   rO   rV   rV   rW   __init__   s    zStreamplotSet.__init__N)__name__
__module____qualname__r[   rV   rV   rV   rW   r?      s   r?   c                   @   sX   e Zd Z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dd ZdS )r   a  
    Map representing different coordinate systems.

    Coordinate definitions:

    * axes-coordinates goes from 0 to 1 in the domain.
    * data-coordinates are specified by the input x-y coordinates.
    * grid-coordinates goes from 0 to N and 0 to M for an N x M grid,
      where N and M match the shape of the input data.
    * mask-coordinates goes from 0 to N and 0 to M for an N x M mask,
      where N and M are user-specified to control the density of streamlines.

    This class also has methods for adding trajectories to the StreamMask.
    Before adding a trajectory, run `start_trajectory` to keep track of regions
    crossed by a given trajectory. Later, if you decide the trajectory is bad
    (e.g., if the trajectory is very short) just call `undo_trajectory`.
    c                 C   sl   || _ || _|jd |jd  | _|jd |jd  | _d| j | _d| j | _d|j | _	d|j
 | _d S )Nr         ?)rE   rF   r.   x_grid2maskr/   y_grid2maskx_mask2gridy_mask2griddxx_data2griddyy_data2grid)rZ   rE   rF   rV   rV   rW   r[     s    zDomainMap.__init__c                 C   s$   t || j d t || j d fS )z;Return nearest space in mask-coords from given grid-coords.      ?)intr`   ra   rZ   xiyirV   rV   rW   	grid2mask  s    zDomainMap.grid2maskc                 C   s   || j  || j fS rX   )rb   rc   rZ   rI   rJ   rV   rV   rW   r#   !  s    zDomainMap.mask2gridc                 C   s   || j  || j fS rX   re   rg   )rZ   ZxdZydrV   rV   rW   r,   $  s    zDomainMap.data2gridc                 C   s   || j  || j fS rX   ro   )rZ   rK   rL   rV   rV   rW   r4   '  s    zDomainMap.grid2datac                 C   s"   |  ||\}}| j|| d S rX   )rm   rF   _start_trajectoryrZ   rK   rL   rI   rJ   rV   rV   rW   start_trajectory*  s    zDomainMap.start_trajectoryc                 C   s    |  ||\}}||f| j_d S rX   )rm   rF   _current_xyrq   rV   rV   rW   reset_start_point.  s    zDomainMap.reset_start_pointc                 C   s4   | j ||st| ||\}}| j|| d S rX   )rE   within_gridInvalidIndexErrorrm   rF   _update_trajectoryrq   rV   rV   rW   update_trajectory2  s    zDomainMap.update_trajectoryc                 C   s   | j   d S rX   )rF   _undo_trajectoryrZ   rV   rV   rW   undo_trajectory8  s    zDomainMap.undo_trajectoryN)r\   r]   r^   __doc__r[   rm   r#   r,   r4   rr   rt   rx   r{   rV   rV   rV   rW   r      s   r   c                   @   s,   e Zd ZdZdd Zedd Zdd ZdS )	r   zGrid of data.c                 C   s  |j dkrn<|j dkr@|dd d f }t||s:td|}ntd|j dkrTn>|j dkr|d d df }t||jstd|}ntdt|dk stdt|dk std	t|| _t|| _	|d |d  | _
|d |d  | _|d | _|d | _|d
 |d  | _|d
 |d  | _tt|| j| jd  s^tdtt|| j| j	d  stdd S )Nr   r   r   zThe rows of 'x' must be equalz$'x' can have at maximum 2 dimensionsz The columns of 'y' must be equalz$'y' can have at maximum 2 dimensionsz'x' must be strictly increasingz'y' must be strictly increasingr   z!'x' values must be equally spacedz!'y' values must be equally spaced)ndimr   Zallcloser   r3   r7   alllenr.   r/   rd   rf   r'   r)   r(   r*   )rZ   r<   r=   Zx_rowZy_colrV   rV   rW   r[   >  s@    







  zGrid.__init__c                 C   s   | j | jfS rX   )r/   r.   rz   rV   rV   rW   r   j  s    z
Grid.shapec                 C   s<   d|  ko| j d kn  o:d|  ko6| jd kS   S )z9Return whether (*xi*, *yi*) is a valid index of the grid.r   r   )r.   r/   rj   rV   rV   rW   ru   n  s    zGrid.within_gridN)r\   r]   r^   r|   r[   propertyr   ru   rV   rV   rV   rW   r   <  s
   ,
r   c                   @   s8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )r   aN  
    Mask to keep track of discrete regions crossed by streamlines.

    The resolution of this grid determines the approximate spacing between
    trajectories. Streamlines are only allowed to pass through zeroed cells:
    When a streamline enters a cell, that cell is set to 1, and no new
    streamlines are allowed to enter.
    c              
   C   s   z"dt |d t\| _| _W n. tyP } ztd|W Y d }~n
d }~0 0 | jdk sf| jdk rntdt | j| jf| _| jj	| _	d | _
d S )N   r   z,'density' must be a scalar or be of length 2r   z'density' must be positive)r   Zbroadcast_toastyperi   r.   r/   r   Zzeros_maskr   rs   )rZ   rB   errrV   rV   rW   r[     s    "
zStreamMask.__init__c                 C   s
   | j | S rX   )r   )rZ   argsrV   rV   rW   __getitem__  s    zStreamMask.__getitem__c                 C   s   g | _ | || dS )z%Start recording streamline trajectoryN)_trajrw   rn   rV   rV   rW   rp     s    zStreamMask._start_trajectoryc                 C   s   | j D ]}d| j|< qdS )z#Remove current trajectory from maskr   N)r   r   )rZ   rM   rV   rV   rW   ry     s    
zStreamMask._undo_trajectoryc                 C   sP   | j ||fkrL| ||f dkrH| j||f d| j||f< ||f| _ ntdS )z
        Update current trajectory position in mask.

        If the new position has already been filled, raise `InvalidIndexError`.
        r   r   N)rs   r   r$   r   rv   rn   rV   rV   rW   rw     s    zStreamMask._update_trajectoryN)	r\   r]   r^   r|   r[   r   rp   ry   rw   rV   rV   rV   rW   r   u  s   	r   c                   @   s   e Zd ZdS )rv   Nr\   r]   r^   rV   rV   rV   rW   rv     s   rv   c                   @   s   e Zd ZdS )TerminateTrajectoryNr   rV   rV   rV   rW   r     s   r   c           	         s    \jjd  }jjd  }tj|d |d  fddfdd  fdd}|S )	Nr   r   c                    s\    j | |stt| |}|dkr,t d| }t| |}t| |}|| || fS )Nr   r_   )rE   ru   OutOfBoundsr9   r   )rk   rl   Zds_dtZdt_dsZuivi)rG   speedr@   rA   rV   rW   forward_time  s    z%_get_integrator.<locals>.forward_timec                    s    | |\}}| | fS rX   rV   )rk   rl   ZdxiZdyi)r   rV   rW   backward_time  s    z&_get_integrator.<locals>.backward_timec                    s   dg  }}z | | W n ty.   Y dS 0 dv rft| | \}}||7 }||ddd 7 }dv r| | t| |\}}||7 }||dd 7 }|krt|tdd S   dS dS )	a  
        Return (N, 2) grid-coordinates of trajectory based on starting point.

        Integrate both forward and backward in time from starting point in
        grid coordinates.

        Integration is terminated when a trajectory reaches a domain boundary
        or when it crosses into an already occupied cell in the StreamMask. The
        resulting trajectory is None if it is shorter than `minlength`.
        g        N)r	   r   r   )r	   r   r   )r   r   r   )rr   rv   _integrate_rk12rt   r   Zbroadcast_arraysemptyr{   )x0y0stotalxy_trajrQ   Zxyt)r   rG   r   r   rD   rC   rV   rW   rH     s$    
z"_get_integrator.<locals>.integrate)r,   rE   r.   r/   r   r    sqrt)	r@   rA   rG   rC   rD   r   Zu_axZv_axrH   rV   )	r   rG   r   r   rD   rC   r   r@   rA   rW   r!     s    #r!   z3.5c                 C   s:   t | |||||}|d u rd S t|s.g g fS g t| S rX   )r!   r   zip)r@   rA   rG   rC   rD   r   r   rV   rV   rW   get_integrator  s    
r   c                   @   s   e Zd ZdS )r   Nr   rV   rV   rV   rW   r     s   r   c                 C   s  d}t d|jj d|jj d}|}d}| }	|}
g }zR|j|	|
rT||	|
f nt||	|
\}}||	||  |
||  \}}W nJ ty   |rt|||\}}||7 }Y qY n t	y   Y qY n0 || }|| }|d ||  }|d ||  }|jj
\}}t|| |d  || |d  }||k r|	|7 }	|
|7 }
z||	|
 W n tyv   Y qY n0 || |krq||7 }|dkr|}q4t |d| || d  }q4||fS )a  
    2nd-order Runge-Kutta algorithm with adaptive step size.

    This method is also referred to as the improved Euler's method, or Heun's
    method. This method is favored over higher-order methods because:

    1. To get decent looking trajectories and to sample every mask cell
       on the trajectory we need a small timestep, so a lower order
       solver doesn't hurt us unless the data is *very* high resolution.
       In fact, for cases where the user inputs
       data smaller or of similar grid size to the mask grid, the higher
       order corrections are negligible because of the very fast linear
       interpolation used in `interpgrid`.

    2. For high resolution input data (i.e. beyond the mask
       resolution), we must reduce the timestep. Therefore, an adaptive
       timestep is more suited to the problem as this would be very hard
       to judge automatically otherwise.

    This integrator is about 1.5 - 2x as fast as RK4 and RK45 solvers (using
    similar Python implementations) in most setups.
    g~jth?r_   r   r   rh   r   g333333?)r1   rF   r.   r/   rE   ru   r$   r   _euler_stepr   r   r   r6   rx   rv   )r   r   rG   frD   ZmaxerrorZmaxdsdsr   rk   rl   xyf_trajZk1xZk1yZk2xZk2yZdx1Zdy1Zdx2Zdy2r/   r.   errorrV   rV   rW   r     sP    "
$

r   c                 C   s   |j j\}}| d \}}|||\}}|dkr6tj}	n$|dk rJ||  }	n|d | | }	|dkrjtj}
n$|dk r~||  }
n|d | | }
t|	|
}| |||  |||  f || fS )zBSimple Euler integration step that extends streamline to boundary.r   r   r   )rE   r   r   infr1   r$   )r   rG   r   r/   r.   rk   rl   ZcxcyZdsxZdsyr   rV   rV   rW   r   _  s     
r   c                 C   s@  t | \}}t|t jr\|t}|t}t |d d|d }t |d d|d }nDt|}t|}||d kr~|}n|d }||d kr|}n|d }| ||f }	| ||f }
| ||f }| ||f }|| }|| }|	d|  |
|  }|d|  ||  }|d|  ||  }t|t js<t j|r<t	|S )z0Fast 2D, linear interpolation on an integer gridr   r   )
r   r   r   r   r   ri   r-   r    Z	is_maskedr   )ark   rl   ZNyZNxr<   r=   ZxnZynZa00Za01Za10Za11ZxtZytZa0Za1ZairV   rV   rW   r9   x  s6    

r9   c                 c   s   | \}}d}d}|d }|d }d\}}d}	t || D ]}
||fV  |	dkrl|d7 }||kr|d8 }d}	q8|	dkr|d7 }||kr|d8 }d}	q8|	dkr|d8 }||kr|d7 }d}	q8|	dkr8|d8 }||kr8|d7 }d}	q8dS )	a  
    Yield starting points for streamlines.

    Trying points on the boundary first gives higher quality streamlines.
    This algorithm starts with a point on the mask corner and spirals inward.
    This algorithm is inefficient, but fast compared to rest of streamplot.
    r   r   )r   r   rightZupleftZdownN)range)r   r/   r.   ZxfirstZyfirstZxlastZylastr<   r=   	directionirV   rV   rW   r"     s:    
r"   )r   NNNNr   r   r   NNNr   r	   )#r|   Znumpyr   r   r   r   Zmatplotlib.colorscolorsr0   Zmatplotlib.collectionsr>   r;   Zmatplotlib.linesrY   r   Zmatplotlib.patchesr:   __all__r   r?   r   r   r   	Exceptionrv   r   r!   
deprecatedr   
IndexErrorr   r   r   r9   r"   rV   rV   rV   rW   <module>   s8       
 `
@93?
`(