B
    db                @   s.  d Z ddlZddlZddl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mZ dd
lmZ ddlmZmZ ddlmZ eZeZ e!Z"dddddddgZ#dd Z$dd Z%d4ddZ&dd Z'd5d#dZ(d6d*dZ)d7d+dZ*d8d-dZ+d9d1dZ,d:d2dZ-d;d3dZ.dS )<zx
A set of built-in plotting functions to help visualize ``dynesty`` nested
sampling :class:`~dynesty.results.Results`.

    N)MaxNLocatorNullLocator)LinearSegmentedColormapcolorConverter)ScalarFormatter)gaussian_filter)gaussian_kde   )resample_equal	unitcheck)quantile)get_random_generatorget_nonbounded)boundingrunplot	traceplotcornerpoints
cornerplot	boundplotcornerbound_hist2dc             C   sx   | d kr4t j||||fd\} }t|||}n<| \} }yt|||}W n tk
rn   tdY nX | |fS )N)Zfigsizez-Provided axes do not match the required shape)plZsubplotsnpZasarrayZreshape
ValueError)fignxnyZxsizeZysizeaxes r   ]/work/yifan.wang/ringdown/master-ringdown-env/lib/python3.7/site-packages/dynesty/plotting.py_make_subplots!   s    r    c             C   s6   |dkr|   }n|  }x|D ]}|d q W d S )Nx-   )Zget_xticklabelsZget_yticklabelsZset_rotation)axZxyZlabsZlabr   r   r   rotate_ticks/   s
    

r$   c       	      C   sv   |r| j }n|r| j}ntd|dk	rryt|}W n tk
rN   |g}Y nX x |D ]}||fd|i| qVW dS )zZ
Plot the thruth line (horizontal or vertical).
truths can be None or one value or a list
z/vertical or horizontal option must be specifiedNcolor)axvlineaxhliner   iter	TypeError)	r#   truthstruth_colortruth_kwargsvertical
horizontalfuncZcurttr   r   r   plot_thruth8   s    

r1   c          	   C   s   xt | D ]|\}}y(t| |  t| | dkr8tdW q
 tk
r   dd| |   dd| |   g}t|| ||d| |< Y q
X q
W dS )zv
If span is a list of scalars, replace it by the list of bounds.
If the input is list of pairs, it is kept intact
       zIncorrect span valueg      ?)weightsN)	enumerater(   lenr   r)   	_quantile)spansamplesr3   i_qr   r   r   
check_spanQ   s     r<   FT  bluered      c       0   
      sB  |dkri }|dkri }|dkr$i }t  }|dd|d< |dd|d< |dd|d< |dd|d< | d	 }| d
 | d t| d  }| d | d d  }| d }| d }d|t| < t|}y| d }d}W nd tk
r>   t|| d  }|| | d kr:td| d d ddd }t	||}Y nX |rl|| | d kr^|}nt
d d}|t|t||r|nt|g}|rtt |d |d}td d |}|| |d< |dkrdd |D }d}nd}t|}t|dkrtdx|t|D ]p\}} y*t||  t|| dkrRtdW n: tk
r   t|| ||  t|| f||< Y nX q"W |r|r|r|d d|d   |d d |d   f}!n"dd!t|d d"|d    f}!|!|d< |pd}"t|ddd#d#\}}#|# }#d$d |#D }$|"rFd%d |#D }%n|}%fd&d|$D }$d'd |%D }%xtdD ]}|$| d dkrd}&ntd|$| d }&|$| d dkrt }'ntt |$| d }'|%| d dkrd}(nt|| d |%| d }(|%| d dkr,|| d })nt|| d |%| d })|#| |&|'g |#| |(|)g qvW d(d)d*|rd+nd,g}*|r|*d  d-7  < xt|D ]\}}+|#|  t|tr|},n|| },|dkr jt   n jt!| |dkr j"t   n j"t!| t#|d.}- j"$|-  j%d7|  j&|*| f| |r|dkr j' |+fd0|,i|  fd1d|#D }%nF|r|dkrƈ j'| |+fd0|,i| n j' |+fd0|,i| |dkr|r|rT| ( d d2 k}.xtddD ]8}/ j)|.  ||/|  |. ||/|  |. |,d3d4 qW nHxFtddD ]8}/ j) t||/|  t||/|  |,d3d4 q`W |r j*|  f|,d5dd6| |dkr j+|f|,d5dd6| |dkr|	dk	r|r j+|	fd0|
i| n j+t|	fd0|
i| qW ||#fS )8a  
    Plot live points, ln(likelihood), ln(weight), and ln(evidence)
    as a function of ln(prior volume).

    Parameters
    ----------
    results : :class:`~dynesty.results.Results` instance
        A :class:`~dynesty.results.Results` instance from a nested
        sampling run.

    span : iterable with shape (4,), optional
        A list where each element is either a length-2 tuple containing
        lower and upper bounds *or* a float from `(0., 1.]` giving the
        fraction below the maximum. If a fraction is provided,
        the bounds are chosen to be equal-tailed. An example would be::

            span = [(0., 10.), 0.001, 0.2, (5., 6.)]

        Default is `(0., 1.05 * max(data))` for each element.

    logplot : bool, optional
        Whether to plot the evidence on a log scale. Default is `False`.

    kde : bool, optional
        Whether to use kernel density estimation to estimate and plot
        the PDF of the importance weights as a function of log-volume
        (as opposed to the importance weights themselves). Default is
        `True`.

    nkde : int, optional
        The number of grid points used when plotting the kernel density
        estimate. Default is `1000`.

    color : str or iterable with shape (4,), optional
        A `~matplotlib`-style color (either a single color or a different
        value for each subplot) used when plotting the lines in each subplot.
        Default is `'blue'`.

    plot_kwargs : dict, optional
        Extra keyword arguments that will be passed to `plot`.

    label_kwargs : dict, optional
        Extra keyword arguments that will be sent to the
        `~matplotlib.axes.Axes.set_xlabel` and
        `~matplotlib.axes.Axes.set_ylabel` methods.

    lnz_error : bool, optional
        Whether to plot the 1, 2, and 3-sigma approximate error bars
        derived from the ln(evidence) error approximation over the course
        of the run. Default is `True`.

    lnz_truth : float, optional
        A reference value for the evidence that will be overplotted on the
        evidence subplot if provided.

    truth_color : str or iterable with shape (ndim,), optional
        A `~matplotlib`-style color used when plotting :data:`lnz_truth`.
        Default is `'red'`.

    truth_kwargs : dict, optional
        Extra keyword arguments that will be used for plotting
        :data:`lnz_truth`.

    max_x_ticks : int, optional
        Maximum number of ticks allowed for the x axis. Default is `8`.

    max_y_ticks : int, optional
        Maximum number of ticks allowed for the y axis. Default is `4`.

    use_math_text : bool, optional
        Whether the axis tick labels for very large/small exponents should be
        displayed as powers of 10 rather than using `e`. Default is `False`.

    mark_final_live : bool, optional
        Whether to indicate the final addition of recycled live points
        (if they were added to the resulting samples) using
        a dashed vertical line. Default is `True`.

    fig : (`~matplotlib.figure.Figure`, `~matplotlib.axes.Axes`), optional
        If provided, overplot the run onto the provided figure.
        Otherwise, by default an internal figure is generated.

    Returns
    -------
    runplot : (`~matplotlib.figure.Figure`, `~matplotlib.axes.Axes`)
        Output summary plot.

    N	linewidth   alphagffffff?	linestylesolidrA   niterlogvollogllogwtlogzlogzerrg        Z	samples_nFnliver	   zThe number of iterations and samples differ by an amount that isn't the number of final live points. `mark_final_live` has been disabled.r2   )rstater   c             S   s   g | ]}d dt | fqS )g        g?)max).0dr   r   r   
<listcomp>  s    zrunplot.<locals>.<listcomp>T   z-More bounds provided in `span` than subplots!zIncorrect span valueggffff>@g433333@g?g      @   c             S   s   g | ]}|  qS r   )Zget_xlim)rQ   r#   r   r   r   rS   !  s    c             S   s   g | ]}|  qS r   )get_ylim)rQ   r#   r   r   r   rS   #  s    c                s&   g | ]}|d kr|ndt   fqS ))g        g      ?g        )min)rQ   r0   )rH   r   r   rS   (  s    c             S   s   g | ]}|d kr|ndqS ))g        g      ?)NNr   )rQ   r0   r   r   r   rS   )  s    zLive PointszLikelihood
(normalized)zImportance
Weightzlog(Evidence)ZEvidencez PDF)useMathText$-\ln X$r%   c                s   g | ]}   qS r   )rV   )rQ   Z_ax)r#   r   r   rS   b  s    
   g?)r%   rD   dashed)r%   lslw)rY   ),r   getrP   r   isfiniter5   KeyErrorZonesarangeappendwarningswarnexpr   r
   linspacepdflistr   r4   r(   r)   r    flattenrangerW   set_xlimset_ylim
isinstancestr_typexaxisset_major_locatorr   r   yaxisr   set_major_formatter
set_xlabel
set_ylabelplotrV   fill_betweenr&   r'   )0resultsr7   Zlogplotkdenkder%   plot_kwargslabel_kwargsZ	lnz_errorZ	lnz_truthr+   r,   Zmax_x_ticksZmax_y_ticksuse_math_textZmark_final_liver   rO   rG   rI   rJ   rK   rM   nsampsrN   Znlive_finalZlive_idxdatawt_kdeZ
logvol_newZno_spanr9   r:   ZzspanZhad_figr   ZxspanZyspanZxminZxmaxZyminZymaxlabelsrR   csfmasksr   )r#   rH   r   r   `   s   k


0"




g?g      ?g333333?{Gz?plasmarZ   rC   .2fc       D   
      s  |dkri }|dkri }|dkr$i }|dkr0i }|dkr<i }|dkrHi }t  }|dd|d< |dd|d< |dd|d< |dd|d< |dd|d< |d	d
|d	< |dd|d< t  }| d }| d } |  }!|r,tt|  |!|d}"t| d | d |	}#|"|# }$t|  |# |$}%n|!}%t	|}t
|jdkrVt|}nt
|jdksntd|j}|jd |jd kstd|dk	r|| }|j\}&}'|!jdkrtd|'|!jd krtd| jdkrtd|'| jd krtd|rdd|  kr.| d }(t|(})ntdy|d }*|}*W n   |j|)|dd}*Y nX |dkrdd t|&D }t|}t
||&krtdt|||! |dkrd d t|&D }t ttfr fd!dt|&D  t||&dd"d|& \}}+xt|D ]t\},}-|+|,df }.|dk	rLt|trB|}/n||, }/n|%dd| }/t|
trl|
}0n|
|, }0|.d#t|  g |.t|-t |-g |dkr|.j!"t#  |.j$"t#  n |.j!"t%| |.j$"t%| t&|d$}1|.j$'|1 |.j(d7| |.j)||, f| |.j*| dd|  |-dd| f|/|0d&| |rxV|*D ]N}2|(dd| |2k}3|.j+| dd| |3  |-dd| |3 fd'|i| qVW |dk	rt,|.||, ||d(d) |+|,df }.t|tr|}/n||, }/|.||,  |dkr$|.j!"t#  |.j$"t#  n|.j!"t%| |.j$"t#  t&|d$}1|.j!'|1 |.j(||, f|  |, }4t|4tr|.j-|-f|4|!|/t.||, d*|\}5}6}7t/tt0|6dd |6dd 1 }8t/tt0|5|51 }9nrt2t3d+|4 }:tj4|-|:|!t.||, d,\}5}6t5|5d+}5d-|6dd |6dd   }8|5}9|.j6|8|9fd'|/i| |.d#t |9d. g |dk	rt
|dkrt7|-||!d/};x |;D ]}<|.j8|<dd0|/d1 qW |rt9d2 t9||, tt0||; |dk	rt,|.||, ||d(d3 |rd}=|dk	rt7|-||!d/\}>}?}@|?|> |@|?  }A}Bd4:|j:}Cd5}=|=:|C|?|C|A|C|B}=d6:||, |=}=|.j;|=f| qW ||+fS )8a  
    Plot traces and marginalized posteriors for each parameter.

    Parameters
    ----------
    results : :class:`~dynesty.results.Results` instance
        A :class:`~dynesty.results.Results` instance from a nested
        sampling run. **Compatible with results derived from**
        `nestle <http://kylebarbary.com/nestle/>`_.

    span : iterable with shape (ndim,), optional
        A list where each element is either a length-2 tuple containing
        lower and upper bounds or a float from `(0., 1.]` giving the
        fraction of (weighted) samples to include. If a fraction is provided,
        the bounds are chosen to be equal-tailed. An example would be::

            span = [(0., 10.), 0.95, (5., 6.)]

        Default is `0.999999426697` (5-sigma credible interval) for each
        parameter.

    quantiles : iterable, optional
        A list of fractional quantiles to overplot on the 1-D marginalized
        posteriors as vertical dashed lines. Default is `[0.025, 0.5, 0.975]`
        (the 95%/2-sigma credible interval).

    smooth : float or iterable with shape (ndim,), optional
        The standard deviation (either a single value or a different value for
        each subplot) for the Gaussian kernel used to smooth the 1-D
        marginalized posteriors, expressed as a fraction of the span.
        Default is `0.02` (2% smoothing). If an integer is provided instead,
        this will instead default to a simple (weighted) histogram with
        `bins=smooth`.

    thin : int, optional
        Thin the samples so that only each `thin`-th sample is plotted.
        Default is `1` (no thinning).

    dims : iterable of shape (ndim,), optional
        The subset of dimensions that should be plotted. If not provided,
        all dimensions will be shown.

    post_color : str or iterable with shape (ndim,), optional
        A `~matplotlib`-style color (either a single color or a different
        value for each subplot) used when plotting the histograms.
        Default is `'blue'`.

    post_kwargs : dict, optional
        Extra keyword arguments that will be used for plotting the
        marginalized 1-D posteriors.

    kde : bool, optional
        Whether to use kernel density estimation to estimate and plot
        the PDF of the importance weights as a function of log-volume
        (as opposed to the importance weights themselves). Default is
        `True`.

    nkde : int, optional
        The number of grid points used when plotting the kernel density
        estimate. Default is `1000`.

    trace_cmap : str or iterable with shape (ndim,), optional
        A `~matplotlib`-style colormap (either a single colormap or a
        different colormap for each subplot) used when plotting the traces,
        where each point is colored according to its weight. Default is
        `'plasma'`.

    trace_color : str or iterable with shape (ndim,), optional
        A `~matplotlib`-style color (either a single color or a
        different color for each subplot) used when plotting the traces.
        This overrides the `trace_cmap` option by giving all points
        the same color. Default is `None` (not used).

    trace_kwargs : dict, optional
        Extra keyword arguments that will be used for plotting the traces.

    connect : bool, optional
        Whether to draw lines connecting the paths of unique particles.
        Default is `False`.

    connect_highlight : int or iterable, optional
        If `connect=True`, highlights the paths of a specific set of
        particles. If an integer is passed, :data:`connect_highlight`
        random particle paths will be highlighted. If an iterable is passed,
        then the particle paths corresponding to the provided indices
        will be highlighted.

    connect_color : str, optional
        The color of the highlighted particle paths. Default is `'red'`.

    connect_kwargs : dict, optional
        Extra keyword arguments used for plotting particle paths.

    max_n_ticks : int, optional
        Maximum number of ticks allowed. Default is `5`.

    use_math_text : bool, optional
        Whether the axis tick labels for very large/small exponents should be
        displayed as powers of 10 rather than using `e`. Default is `False`.

    labels : iterable with shape (ndim,), optional
        A list of names for each parameter. If not provided, the default name
        used when plotting will follow :math:`x_i` style.

    label_kwargs : dict, optional
        Extra keyword arguments that will be sent to the
        `~matplotlib.axes.Axes.set_xlabel` and
        `~matplotlib.axes.Axes.set_ylabel` methods.

    show_titles : bool, optional
        Whether to display a title above each 1-D marginalized posterior
        showing the 0.5 quantile along with the upper/lower bounds associated
        with the 0.025 and 0.975 (95%/2-sigma credible interval) quantiles.
        Default is `False`.

    title_quantiles : iterable, optional
        A list of fractional quantiles to use in the title. Default is
        `[0.025, 0.5, 0.975]` (median plus 95%/2-sigma credible interval).

    title_fmt : str, optional
        The format string for the quantiles provided in the title. Default is
        `'.2f'`.

    title_kwargs : dict, optional
        Extra keyword arguments that will be sent to the
        `~matplotlib.axes.Axes.set_title` command.

    truths : iterable with shape (ndim,), optional
        A list of reference values that will be overplotted on the traces and
        marginalized 1-D posteriors as solid horizontal/vertical lines.
        Individual values can be exempt using `None`. Default is `None`.

    truth_color : str or iterable with shape (ndim,), optional
        A `~matplotlib`-style color (either a single color or a different
        value for each subplot) used when plotting `truths`.
        Default is `'red'`.

    truth_kwargs : dict, optional
        Extra keyword arguments that will be used for plotting the vertical
        and horizontal lines with `truths`.

    verbose : bool, optional
        Whether to print the values of the computed quantiles associated with
        each parameter. Default is `False`.

    fig : (`~matplotlib.figure.Figure`, `~matplotlib.axes.Axes`), optional
        If provided, overplot the traces and marginalized 1-D posteriors
        onto the provided figure. Otherwise, by default an
        internal figure is generated.

    Returns
    -------
    traceplot : (`~matplotlib.figure.Figure`, `~matplotlib.axes.Axes`)
        Output trace plot.

    NrD   gffffff?g333333?r   rA   	edgecolor
edgecolorsrE   rF   rB   r2   r8   rH   )rO   r   rL   r	   zSamples must be 1- or 2-D.z'There are more dimensions than samples!zWeights must be 1-D.z+The number of weights and samples disagree!zLn(volume)'s must be 1-D.z0The number of ln(volume)'s and samples disagree!
samples_idzSample IDs are not defined!F)sizereplacec             S   s   g | ]}d qS )g5?r   )rQ   r9   r   r   r   rS     s    ztraceplot.<locals>.<listcomp>z,Dimension mismatch between samples and span.c             S   s    g | ]}d t |d  d qS )z$x_{r	   z}$)str)rQ   r9   r   r   r   rS     s    c                s   g | ]} qS r   r   )rQ   r9   )smoothr   r   rS     s       g        )rX   $-\ln X$)r   cmapr%   T)r.   )binsr3   r%   rj   g      $@)r   r3   rj   g      ?g?)r3   r[   )r]   r\   r%   z
Quantiles:)r-   z	{{0:{0}}}z${{{0}}}_{{-{1}}}^{{+{2}}}$z	{0} = {1})r   )<r   r^   importance_weightsr   r
   r   rf   rg   interp
atleast_1dr5   shape
atleast_2dAssertionErrorTndimr   keysuniquechoicerj   rh   r<   rm   int_type
float_typer    r4   rn   rk   rW   rl   rP   ro   rp   r   rq   r   r   rr   rs   rt   scatterru   r1   histsortarrayzipri   intround	histogramnorm_kderv   r6   r&   printformat	set_title)Drw   r7   	quantilesr   thindimsZ
post_colorZpost_kwargsrx   ry   Z
trace_cmapZtrace_colorZtrace_kwargsconnectZconnect_highlightZconnect_colorZconnect_kwargsmax_n_ticksr|   r   r{   show_titlestitle_quantiles	title_fmttitle_kwargsr*   r+   r,   verboser   rO   r8   rH   r3   r   logvol_gridwt_gridZwtsr   r}   r   uidZidsr   r9   r!   r#   r%   r   r   jselr   nbr:   Zx0Zy0r   qsr;   titleqlqmqhq_minusq_plusfmtr   )r   r   r     sL    =














(



c       *   	   C   sV  |dkri }|
dkri }
|dkr$i }| dd|d< | dd|d< | dd|d< | dd|d< | dd	|d< | d
d|d
< | d }| d }|  }|rtt| |}t|d |d |}|| }t| | |}t|}t	|j
dkr
t|}nt	|j
d	ks"td|j}|j
d |j
d ksFtd|dk	rX|| }|j
\}}|jdkrvtd||j
d krtd|dkrtd|dk	rt	||krtdt||| |	dkrdd t|D }	|dkr|}d}d| }d| }d}||d  ||d  |  }|| | }t||d |d ||\}}|| } || | }!|j| | |!|!||d xt|dd D ]\}"}#xt|dd D ]\}$}%y||"|$f }&W n   |}&Y nX |dk	r |&||$  |&||"  |$|"kr,|&d |&g  |&g  q|dkrT|&jt  |&jt  n(|&jt|dd  |&jt|dd  t|d!}'|&j |' |&j |' |"|d	 k r|&!g  n*t"|&d" |&j#|	|$ f|
 |&j$dd# |$dkr|&%g  n.t"|&d$ |&j&|	|"d  f|
 |&j$d#d t'|%(d%}(|dk	rr||" dk	rr|(|#||" d k|#||" d k@ 9 }(|dk	r||$ dk	r|(|%||$ d k|%||$ d k@ 9 }(t)|t*r|})n||( dd| })|&j+|%|( dd| |#|( dd| f|)|d&| |dk	rt,|&||$ ||d'd( t,|&||"d  ||d'd) qW qW ||fS )*aD  
    Generate a (sub-)corner plot of (weighted) samples.

    Parameters
    ----------
    results : :class:`~dynesty.results.Results` instance
        A :class:`~dynesty.results.Results` instance from a nested
        sampling run. **Compatible with results derived from**
        `nestle <http://kylebarbary.com/nestle/>`_.

    dims : iterable of shape (ndim,), optional
        The subset of dimensions that should be plotted. If not provided,
        all dimensions will be shown.

    thin : int, optional
        Thin the samples so that only each `thin`-th sample is plotted.
        Default is `1` (no thinning).

    span : iterable with shape (ndim,), optional
        A list where each element is either a length-2 tuple containing
        lower and upper bounds or a float from `(0., 1.]` giving the
        fraction of (weighted) samples to include. If a fraction is provided,
        the bounds are chosen to be equal-tailed. An example would be::

            span = [(0., 10.), 0.95, (5., 6.)]

        Default is `1.` for all parameters (no bound).

    cmap : str, optional
        A `~matplotlib`-style colormap used when plotting the points,
        where each point is colored according to its weight. Default is
        `'plasma'`.

    color : str, optional
        A `~matplotlib`-style color used when plotting the points.
        This overrides the `cmap` option by giving all points
        the same color. Default is `None` (not used).

    kde : bool, optional
        Whether to use kernel density estimation to estimate and plot
        the PDF of the importance weights as a function of log-volume
        (as opposed to the importance weights themselves). Default is
        `True`.

    nkde : int, optional
        The number of grid points used when plotting the kernel density
        estimate. Default is `1000`.

    plot_kwargs : dict, optional
        Extra keyword arguments that will be used for plotting the points.

    labels : iterable with shape (ndim,), optional
        A list of names for each parameter. If not provided, the default name
        used when plotting will follow :math:`x_i` style.

    label_kwargs : dict, optional
        Extra keyword arguments that will be sent to the
        `~matplotlib.axes.Axes.set_xlabel` and
        `~matplotlib.axes.Axes.set_ylabel` methods.

    truths : iterable with shape (ndim,), optional
        A list of reference values that will be overplotted on the traces and
        marginalized 1-D posteriors as solid horizontal/vertical lines.
        Individual values can be exempt using `None`. Default is `None`.

    truth_color : str or iterable with shape (ndim,), optional
        A `~matplotlib`-style color (either a single color or a different
        value for each subplot) used when plotting `truths`.
        Default is `'red'`.

    truth_kwargs : dict, optional
        Extra keyword arguments that will be used for plotting the vertical
        and horizontal lines with `truths`.

    max_n_ticks : int, optional
        Maximum number of ticks allowed. Default is `5`.

    use_math_text : bool, optional
        Whether the axis tick labels for very large/small exponents should be
        displayed as powers of 10 rather than using `e`. Default is `False`.

    fig : (`~matplotlib.figure.Figure`, `~matplotlib.axes.Axes`), optional
        If provided, overplot the points onto the provided figure object.
        Otherwise, by default an internal figure is generated.

    Returns
    -------
    cornerpoints : (`~matplotlib.figure.Figure`, `~matplotlib.axes.Axes`)
        Output (sub-)corner plot of (weighted) samples.

    Nr   r	   r   r   rE   rF   rB   r2   rD   gffffff?r8   rH   r   rL   zSamples must be 1- or 2-D.z'There are more dimensions than samples!zWeights must be 1-D.z+The number of weights and samples disagree!z2cornerpoints does not make sense for 1-D posteriorz,Dimension mismatch between samples and span.c             S   s    g | ]}d t |d  d qS )z$x_{r	   z}$)r   )rQ   r9   r   r   r   rS     s    z cornerpoints.<locals>.<listcomp>g       @g      ?g?g?g      ?)leftbottomrighttopwspacehspaceFlower)prune)rX   r!   g333333ӿybool)r   r   T)r-   )r.   )-r^   r   r   r
   r   rf   rg   r   r   r5   r   r   r   r   r   r   r<   rj   r    subplots_adjustr4   rk   rl   set_frame_on
set_xticks
set_yticksro   rp   r   rq   r   r   rr   set_xticklabelsr$   rs   set_label_coordsset_yticklabelsrt   Z	ones_likeZastyperm   r   r   r1   )*rw   r   r   r7   r   r%   rx   ry   rz   r   r{   r*   r+   r,   r   r|   r   r8   rH   r3   r   r   r   r   r}   factorlbdimtrdimwhspaceplotdimdimr   lbtrr9   r!   r   r   r#   r   Z	in_boundsZ	cur_colorr   r   r   r   1  s    n

















$$

blackc       >   
      sl  |dkrg }|dkri }|
dkr$i }
|dkr0i }|dkr<i }|dkrHi }| dd|d< | d||d< | dd|d< | dd|d< | dd	|d< | d
 }|  }t|}t|jdkrt|}nt|jdkstd|j}|jd |jd kstd|dk	r|| }|j\}}|j	dkr6t
d||jd krNt
d|dkrjdd t|D }t|}t||krt
dt||| |	dkrdd t|D }	t ttfrև fddt|D  d}d| }d| }d}|| ||d  |  }|| | } t|||| | \}}!||  }"|| |  }#|j|"|"|#|#||d xt|D ]\}$}%|!|$|$f }&|&||$  |dkr|&jt  |&jt  n"|&jt|dd |&jt  t|d}'|&j|' |$|d k r|r|&jd t|&d  n
|&g  n*t|&d  |&j|	|$ f|
 |&j dd!  |$ }(t|(tr|&j!|%f|(||t"||$ d"|\})}*}+nt#t$d#|( },tj%|%|,|t"||$ d$\})}*t&|)d#})d|*dd |*dd%   }-|&j!|-f|*|)t"||$ |d&|\})}*}+|&'d't(|)d( g |dk	rt|dkrt)|%||d)}.x |.D ]}/|&j*|/dd*|d+ qHW |rt+d, t+|	|$ tt,||. |dk	rt-|&||$ ||d-d. |r,d}0|dk	r,t)|%||d)\}1}2}3|2|1 |3|2  }4}5d/.|j.}6d0}0|0.|6|2|6|4|6|5}0d1.|	|$ |0}0|&j/|0f| x.t|D ] \}7}8t|d dkr\|!}&n|!|$|7f }&|7|$kr|&0d2 |&1g  |&2g  q8n|7|$krq8|dkr|&jt  |&jt  n(|&jt|dd |&jt|dd t|d}'|&j|' |&j|' |$|d k r0|&g  n*t|&d  |&j|	|7 f|
 |&j dd! |7dkrp|&3g  n*t|&d3 |&j4|	|$ f|
 |&j d!d  |7 }9t|(t}:t|9t};|:r|;rd2}<d2}=nd-}<d-}=| d4|<|d4< | d5|=|d5< t5|8|%f|&||7 ||$ g|||9|(gd6| |dk	r8t-|&||7 ||d-d. t-|&||$ ||d-d7 q8W q\W ||!fS )8a  
    Generate a corner plot of the 1-D and 2-D marginalized posteriors.

    Parameters
    ----------
    results : :class:`~dynesty.results.Results` instance
        A :class:`~dynesty.results.Results` instance from a nested
        sampling run. **Compatible with results derived from**
        `nestle <http://kylebarbary.com/nestle/>`_.

    dims : iterable of shape (ndim,), optional
        The subset of dimensions that should be plotted. If not provided,
        all dimensions will be shown.

    span : iterable with shape (ndim,), optional
        A list where each element is either a length-2 tuple containing
        lower and upper bounds or a float from `(0., 1.]` giving the
        fraction of (weighted) samples to include. If a fraction is provided,
        the bounds are chosen to be equal-tailed. An example would be::

            span = [(0., 10.), 0.95, (5., 6.)]

        Default is `0.999999426697` (5-sigma credible interval).

    quantiles : iterable, optional
        A list of fractional quantiles to overplot on the 1-D marginalized
        posteriors as vertical dashed lines. Default is `[0.025, 0.5, 0.975]`
        (spanning the 95%/2-sigma credible interval).

    color : str or iterable with shape (ndim,), optional
        A `~matplotlib`-style color (either a single color or a different
        value for each subplot) used when plotting the histograms.
        Default is `'black'`.

    smooth : float or iterable with shape (ndim,), optional
        The standard deviation (either a single value or a different value for
        each subplot) for the Gaussian kernel used to smooth the 1-D and 2-D
        marginalized posteriors, expressed as a fraction of the span.
        Default is `0.02` (2% smoothing). If an integer is provided instead,
        this will instead default to a simple (weighted) histogram with
        `bins=smooth`.

    quantiles_2d : iterable with shape (nquant,), optional
        The quantiles used for plotting the smoothed 2-D distributions.
        If not provided, these default to 0.5, 1, 1.5, and 2-sigma contours
        roughly corresponding to quantiles of `[0.1, 0.4, 0.65, 0.85]`.

    hist_kwargs : dict, optional
        Extra keyword arguments to send to the 1-D (smoothed) histograms.

    hist2d_kwargs : dict, optional
        Extra keyword arguments to send to the 2-D (smoothed) histograms.

    labels : iterable with shape (ndim,), optional
        A list of names for each parameter. If not provided, the default name
        used when plotting will follow :math:`x_i` style.

    label_kwargs : dict, optional
        Extra keyword arguments that will be sent to the
        `~matplotlib.axes.Axes.set_xlabel` and
        `~matplotlib.axes.Axes.set_ylabel` methods.

    show_titles : bool, optional
        Whether to display a title above each 1-D marginalized posterior
        showing the 0.5 quantile along with the upper/lower bounds associated
        with the 0.025 and 0.975 (95%/2-sigma credible interval) quantiles.
        Default is `False`.

    title_quantiles : iterable, optional
        A list of fractional quantiles to use in the title. Default is
        `[0.025, 0.5, 0.975]` (median plus 95%/2-sigma credible interval).

    title_fmt : str, optional
        The format string for the quantiles provided in the title. Default is
        `'.2f'`.

    title_kwargs : dict, optional
        Extra keyword arguments that will be sent to the
        `~matplotlib.axes.Axes.set_title` command.

    truths : iterable with shape (ndim,), optional
        A list of reference values that will be overplotted on the traces and
        marginalized 1-D posteriors as solid horizontal/vertical lines.
        Individual values can be exempt using `None`. Default is `None`.

    truth_color : str or iterable with shape (ndim,), optional
        A `~matplotlib`-style color (either a single color or a different
        value for each subplot) used when plotting `truths`.
        Default is `'red'`.

    truth_kwargs : dict, optional
        Extra keyword arguments that will be used for plotting the vertical
        and horizontal lines with `truths`.

    max_n_ticks : int, optional
        Maximum number of ticks allowed. Default is `5`.

    top_ticks : bool, optional
        Whether to label the top (rather than bottom) ticks. Default is
        `False`.

    use_math_text : bool, optional
        Whether the axis tick labels for very large/small exponents should be
        displayed as powers of 10 rather than using `e`. Default is `False`.

    verbose : bool, optional
        Whether to print the values of the computed quantiles associated with
        each parameter. Default is `False`.

    fig : (`~matplotlib.figure.Figure`, `~matplotlib.axes.Axes`), optional
        If provided, overplot the traces and marginalized 1-D posteriors
        onto the provided figure. Otherwise, by default an
        internal figure is generated.

    Returns
    -------
    cornerplot : (`~matplotlib.figure.Figure`, `~matplotlib.axes.Axes`)
        Output corner plot.

    NrD   g333333?levelsrE   rF   rB   r2   gffffff?r8   r	   zSamples must be 1- or 2-D.r   z'There are more dimensions than samples!zWeights must be 1-D.z+The number of weights and samples disagree!c             S   s   g | ]}d qS )g5?r   )rQ   r9   r   r   r   rS     s    zcornerplot.<locals>.<listcomp>z,Dimension mismatch between samples and span.c             S   s    g | ]}d t |d  d qS )z$x_{r	   z}$)r   )rQ   r9   r   r   r   rS     s    c                s   g | ]} qS r   r   )rQ   r9   )r   r   r   rS   
  s    g       @g      ?g?g?g      ?)r   r   r   r   r   r   r   )r   )rX   r   r!   g333333ӿ)r   r3   r%   rj   g      $@)r   r3   rj   rL   )r   r3   rj   r%   g        g?)r3   r[   )r]   r\   r%   z
Quantiles:T)r-   z	{{0:{0}}}z${{{0}}}_{{-{1}}}^{{+{2}}}$z	{0} = {1}Fr   fill_contoursplot_contours)r#   r7   r3   r%   r   )r.   )6r^   r   r   r   r5   r   r   r   r   r   r   rj   rh   r<   rm   r   r   r    r   r4   rk   ro   rp   r   rq   r   r   rr   Zset_ticks_positionr$   r   rs   r   r   r   r   r   r   r   rl   rP   r6   r&   r   r   r1   r   r   r   r   r   r   rt   r   )>rw   r   r7   r   r%   r   Zquantiles_2dZhist_kwargsZhist2d_kwargsr   r{   r   r   r   r   r*   r+   r,   r   Z	top_ticksr|   r   r   r8   r3   r   r}   r   r   r   r   r   r   r   r   r   r9   r!   r#   r   sxr   r   r:   r   Zb0r   r;   r   r   r   r   r   r   r   r   r   ZsyZcheck_ixZcheck_iyr   r   r   )r   r   r   <  sp    

























  gray
darkvioletc       2         s  |	dkri }	|dkri }|dkr$i }|dkr4|dksD|dk	rL|dk	rLt d|	dd|	d< |	dd|	d< |	dd|	d< |	d	d
|	d	< |dd|d< |dd|d< |dd|d< y| d }W n tk
r   t dY nX t| d }t|d j|| |dk	rl||kr t dyt| d }W n tk
rP   t dY nX |dkrbd}n|| }nF||kr~t dy| d }W n tk
r   t dY nX || }|| }|r|y| d }| d }|| |krt d| d }| d }|jd }t	||f}|| d ||| d < |dkrB| d | }x:t
d|| d D ]$}||  } ||  }!||  ||!< qVW W n   | d | }"| d |" }#| d |"k}$t|$|# }%| d |$ }| d |$ }|t|8 }|jd }t	|#|f}||# d |||# d < |dkr&| d | }t|$d|d  }&x:t
d|%|& d D ]$}|#|  } ||  }!||  ||!< qNW Y nX t }'t|tjtjfs|j||'d}(n|sy| d }| d }|| |krt d| d }| d }|jd }t	||f}|| d ||| d < |dkr.| d | }x:t
d|| d D ]$}||  } ||  }!||  ||!< qBW W n   t dY nX |j|||'d}(|dkr|(dd|f j\})}*|r@|dd|f j\}+},np fdd |(D }-ttt||(|- }.|.dd|f j\})}*|r@ttt||}/|/dd|f j\}+},t|ddd!d!\}}0|0d" }0|0j|)|*f|dd#|	 |r|0j|+|,f|d$d#| |dk	r|0|d  |0|d  |dkr|0jt  |0jt  n |0jt| |0jt| t|d%}1|0j |1 |0j |1 |
dk	rV|0j!|
d f| |0j"|
d f| nD|0j!d&t#|d d  d' f| |0j"d&t#|d d  d' f| ||0fS )(a  
    Return the bounding distribution used to propose either (1) live points
    at a given iteration or (2) a specific dead point during
    the course of a run, projected onto the two dimensions specified
    by `dims`.

    Parameters
    ----------
    results : :class:`~dynesty.results.Results` instance
        A :class:`~dynesty.results.Results` instance from a nested
        sampling run.

    dims : length-2 tuple
        The dimensions used to plot the bounding.

    it : int, optional
        If provided, returns the bounding distribution at the specified
        iteration of the nested sampling run. **Note that this option and
        `idx` are mutually exclusive.**

    idx : int, optional
        If provided, returns the bounding distribution used to propose the
        dead point at the specified iteration of the nested sampling run.
        **Note that this option and `it` are mutually exclusive.**

    prior_transform : func, optional
        The function transforming samples within the unit cube back to samples
        in the native model space. If provided, the transformed bounding
        distribution will be plotted in the native model space.

    periodic : iterable, optional
        A list of indices for parameters with periodic boundary conditions.
        These parameters *will not* have their positions constrained to be
        within the unit cube, enabling smooth behavior for parameters
        that may wrap around the edge. Default is `None` (i.e. no periodic
        boundary conditions).

    reflective : iterable, optional
        A list of indices for parameters with reflective boundary conditions.
        These parameters *will not* have their positions constrained to be
        within the unit cube, enabling smooth behavior for parameters
        that may reflect at the edge. Default is `None` (i.e. no reflective
        boundary conditions).

    ndraws : int, optional
        The number of random samples to draw from the bounding distribution
        when plotting. Default is `5000`.

    color : str, optional
        The color of the points randomly sampled from the bounding
        distribution. Default is `'gray'`.

    plot_kwargs : dict, optional
        Extra keyword arguments used when plotting the bounding draws.

    labels : iterable with shape (ndim,), optional
        A list of names for each parameter. If not provided, the default name
        used when plotting will follow :math:`x_i` style.

    label_kwargs : dict, optional
        Extra keyword arguments that will be sent to the
        `~matplotlib.axes.Axes.set_xlabel` and
        `~matplotlib.axes.Axes.set_ylabel` methods.

    max_n_ticks : int, optional
        Maximum number of ticks allowed. Default is `5`.

    use_math_text : bool, optional
        Whether the axis tick labels for very large/small exponents should be
        displayed as powers of 10 rather than using `e`. Default is `False`.

    show_live : bool, optional
        Whether the live points at a given iteration (for `it`) or
        associated with the bounding (for `idx`) should be highlighted.
        Default is `False`. In the dynamic case, only the live points
        associated with the batch used to construct the relevant bound
        are plotted.

    live_color : str, optional
        The color of the live points. Default is `'darkviolet'`.

    live_kwargs : dict, optional
        Extra keyword arguments used when plotting the live points.

    span : iterable with shape (2,), optional
        A list where each element is a length-2 tuple containing
        lower and upper bounds. Default is `None` (no bound).

    fig : (`~matplotlib.figure.Figure`, `~matplotlib.axes.Axes`), optional
        If provided, overplot the draws onto the provided figure.
        Otherwise, by default an internal figure is generated.

    Returns
    -------
    bounding_plot : (`~matplotlib.figure.Figure`, `~matplotlib.axes.Axes`)
        Output plot of the bounding distribution.

    Nz1You must specify either an iteration or an index!markerorE   None
markersizer	   rD   g?boundz$No bounds were saved in the results!r8   r   zHThe iteration requested goes beyond the number of iterations in the run.
bound_iterzrCannot reconstruct the bound used at the specified iteration since bound iterations were not saved in the results.zAThe index requested goes beyond the number of samples in the run.samples_boundzCannot reconstruct the bound used to compute the specified dead point since sample bound indices were not saved in the results.rN   rG   z^Cannot reconstruct bound because the final set of live points are not included in the results.	samples_ur   
samples_itsamples_batchbatch_nlive)rO   zKLive point tracking currently not implemented for dynamic sampling results.c                s   g | ]}t | qS r   )r   )rQ   point)
nonboundedr   r   rS     s    zboundplot.<locals>.<listcomp>   )r   r   )r%   zorderr2   )rX   z$x_{z}$)$r   r^   r`   r5   r   r   r   r   r   emptyrj   sumrW   r   rm   r   
RadFriends
SupFriendsr8   r   rh   mapr    ru   rk   rl   ro   rp   r   rq   r   r   rr   rs   rt   r   )2rw   r   itidxprior_transformperiodic
reflectivendrawsr%   rz   r   r{   r   r|   	show_live
live_colorlive_kwargsr7   r   boundsr}   r   pidxr   r   rN   rG   r8   r   r   live_ur9   ruidxbatchnbatchbsel	niter_effit_effrO   psampsx1Zx2l1l2r   Zvsampslsampsr   r   r   )r   r   r     s   w 


















""c       9         s  |dkri }|	dkri }	|dkr$i }|dkr4|dksD|dk	rL|dk	rLt d|	dd|	d< |	dd|	d< |	dd|	d< |	d	d
|	d	< |dd|d< |dd|d< |dd|d< y| d }W n tk
r   t dY nX | d j\}}|dkrt dt|d j|| |dk	r||kr4t dyt| d }W n tk
rd   t dY nX |dkrvd}n|| }nF||krt dy| d }W n tk
r   t dY nX || }|| }|ry| d }| d }|| |krt d| d }| d }|jd }t||f}|| d ||| d < |dkrV| d | }x:t	d|| d D ]$}||  } ||  }!||  ||!< qjW W n   |dk	r| d | }"n| d | }"| d |" }#| d |"k}$t
|$|# }%| d |$ }| d |$ }|t|8 }|jd }t|#|f}||# d |||# d < |dkrT| d | }t
|$d|d  }&x:t	d|%|& d D ]$}|#|  } ||  }!||  ||!< q|W Y nX t }'t|tjtjfs|j||'d}(n|s| d }| d }|| |kr t d| d }| d }|jd }t||f}|| d ||| d < |dkrZ| d | }x:t	d|| d D ]$}||  } ||  }!||  ||!< qnW |j|||'d}(|dkr|(j}(|r|j})nP fdd |(D }*ttt||(|* }(|(j}(|rttt||})|)j})|dk	r4|(| }(|r4|)| })|(jd }|
dkrZd!d  t	|D }
d"}+d#|+ },d$|+ }-d%}.|+|d&  |+|d"  |.  }/|,|/ |- }0t||d |d |0|0\}}1|,|0 }2|,|/ |0 }3|j|2|2|3|3|.|.d' xt|(dd D ]\}}4xt|(dd( D ]\}5}6|1||5f }7|dk	rN|7||5  |7||  |5|krz|7d) |7g  |7g  q|dkr|7jt  |7j t  n(|7jt!|d*d+ |7j t!|d*d+ t"|d,}8|7j#|8 |7j #|8 ||d- k r|7$g  n*t%|7d. |7j&|
|5 f| |7j'd#d/ |5dkrF|7(g  n.t%|7d0 |7j)|
|d  f| |7j 'd/d# |7j*|6|4fd1|i|	 |r|7j*|)|5 |)|d  fd1|i| qW qW ||1fS )2a  
    Return the bounding distribution used to propose either (1) live points
    at a given iteration or (2) a specific dead point during
    the course of a run, projected onto all pairs of dimensions.

    Parameters
    ----------
    results : :class:`~dynesty.results.Results` instance
        A :class:`~dynesty.results.Results` instance from a nested
        sampling run.

    it : int, optional
        If provided, returns the bounding distribution at the specified
        iteration of the nested sampling run. **Note that this option and
        `idx` are mutually exclusive.**

    idx : int, optional
        If provided, returns the bounding distribution used to propose the
        dead point at the specified iteration of the nested sampling run.
        **Note that this option and `it` are mutually exclusive.**

    dims : iterable of shape (ndim,), optional
        The subset of dimensions that should be plotted. If not provided,
        all dimensions will be shown.

    prior_transform : func, optional
        The function transforming samples within the unit cube back to samples
        in the native model space. If provided, the transformed bounding
        distribution will be plotted in the native model space.

    periodic : iterable, optional
        A list of indices for parameters with periodic boundary conditions.
        These parameters *will not* have their positions constrained to be
        within the unit cube, enabling smooth behavior for parameters
        that may wrap around the edge. Default is `None` (i.e. no periodic
        boundary conditions).

    reflective : iterable, optional
        A list of indices for parameters with reflective boundary conditions.
        These parameters *will not* have their positions constrained to be
        within the unit cube, enabling smooth behavior for parameters
        that may reflect at the edge. Default is `None` (i.e. no reflective
        boundary conditions).

    ndraws : int, optional
        The number of random samples to draw from the bounding distribution
        when plotting. Default is `5000`.

    color : str, optional
        The color of the points randomly sampled from the bounding
        distribution. Default is `'gray'`.

    plot_kwargs : dict, optional
        Extra keyword arguments used when plotting the bounding draws.

    labels : iterable with shape (ndim,), optional
        A list of names for each parameter. If not provided, the default name
        used when plotting will be in :math:`x_i` style.

    label_kwargs : dict, optional
        Extra keyword arguments that will be sent to the
        `~matplotlib.axes.Axes.set_xlabel` and
        `~matplotlib.axes.Axes.set_ylabel` methods.

    max_n_ticks : int, optional
        Maximum number of ticks allowed. Default is `5`.

    use_math_text : bool, optional
        Whether the axis tick labels for very large/small exponents should be
        displayed as powers of 10 rather than using `e`. Default is `False`.

    show_live : bool, optional
        Whether the live points at a given iteration (for `it`) or
        associated with the bounding (for `idx`) should be highlighted.
        Default is `False`. In the dynamic case, only the live points
        associated with the batch used to construct the relevant bound
        are plotted.

    live_color : str, optional
        The color of the live points. Default is `'darkviolet'`.

    live_kwargs : dict, optional
        Extra keyword arguments used when plotting the live points.

    span : iterable with shape (2,), optional
        A list where each element is a length-2 tuple containing
        lower and upper bounds. Default is `None` (no bound).

    fig : (`~matplotlib.figure.Figure`, `~matplotlib.axes.Axes`), optional
        If provided, overplot the draws onto the provided figure.
        Otherwise, by default an internal figure is generated.


    Returns
    -------
    cornerbound : (`~matplotlib.figure.Figure`, `~matplotlib.axes.Axes`)
        Output corner plot of the bounding distribution.

    Nz1You must specify either an iteration or an index!r   r   rE   r   r   r	   rD   g?r   z$No bounds were saved in the results!r8   z,cornerbound does not work for 1-D posteriorsr   zHThe iteration requested goes beyond the number of iterations in the run.r   zrCannot reconstruct the bound used at the specified iteration since bound iterations were not saved in the results.zAThe index requested goes beyond the number of samples in the run.r   zCannot reconstruct the bound used to compute the specified dead point since sample bound indices were not saved in the results.rN   rG   z^Cannot reconstruct bound because the final set of live points are not included in the results.r   r   r   r   r   )rO   c                s   g | ]}t | qS r   )r   )rQ   r   )r   r   r   rS     s    zcornerbound.<locals>.<listcomp>c             S   s    g | ]}d t |d  d qS )z$x_{r	   z}$)r   )rQ   r9   r   r   r   rS   (  s    g       @g      ?g?g?g      ?)r   r   r   r   r   r   rL   Fr   )r   )rX   r2   r!   g333333ӿr   r   )+r   r^   r`   r   r   r   r   r   r   rj   r   rW   r   rm   r   r   r   r8   r   rh   r   r    r   r4   rk   rl   r   r   r   ro   rp   r   rq   r   r   rr   r   r$   rs   r   r   rt   ru   )9rw   r   r   r   r   r   r   r   r%   rz   r   r{   r   r|   r  r  r  r7   r   r  r}   r   r   r  r   r   rN   rG   r8   r   r  r9   r  r  r	  r
  r  r  r  rO   r  r  r   r   r   r   r   r   r   r   r   r   r!   r   r   r#   r   r   )r   r   r      sJ   x 





























0c       (      C   sD  |dkrt  }| |g}|dkr2dd tdD }t|}t|dkrNtdt||| |dkrdtdt	dd	dd   }t
d
|dg}t
jdddgdd}t|}t|}t|g| |g }x0t|D ]$}|| d  t||d  9  < qW t|ttfr||g}g }g }xP|D ]H}t|trJ|| |d n |ttd|  |d q$W y2tj|  | |tttj||d\}}}W n tk
r   tdY nX t|dkst||}| }t|ddd }|| }t|}||d  }tt|} xHt|D ]<\}}!y|||!k d | |< W n   |d | |< Y nX q.W |   t| dk}"t |"r|
rt!"d t|"rt!"d nHx>t |"r| t#|"d d   d9  < t| dk}"qW |   d|dd |dd   d|dd |dd    }#}$|$ t%|j&d d |j&d d f }%||%ddddf< |dddf |%dddf< |dddf |%dddf< |d |%dddf< |d |%dddf< |d |%d< |d |%d< |d |%d < |d! |%d"< t'|#d t(ddgt|#dd   |#|#d t(ddgt|#dd   g}&t'|$d t(ddgt|$dd   |$|$d t(ddgt|$dd   g}'|r(|dkri }|)d#||d#< |)d$d|d$< |)d%d&|d%< |)d'd(|d'< |j*| |d)fdd*d+| |
s4|	r^|s^|j+|&|'|%j,| $ |- g|d,d- |
r|r|dkrxi }|)d.||d.< |)d/d,|d/< |j+|&|'|%j,t'dg| |- d0 ggf| n"|	r|j.|||- |j, |d1 |
r$|dkri }|)d.||d.< |j/|&|'|%j,| f| |0|d  |1|d  dS )2a  
    Internal function called by :meth:`cornerplot` used to generate a
    a 2-D histogram/contour of samples.

    Parameters
    ----------
    x : interable with shape (nsamps,)
       Sample positions in the first dimension.

    y : iterable with shape (nsamps,)
       Sample positions in the second dimension.

    span : iterable with shape (ndim,), optional
        A list where each element is either a length-2 tuple containing
        lower and upper bounds or a float from `(0., 1.]` giving the
        fraction of (weighted) samples to include. If a fraction is provided,
        the bounds are chosen to be equal-tailed. An example would be::

            span = [(0., 10.), 0.95, (5., 6.)]

        Default is `0.999999426697` (5-sigma credible interval).

    weights : iterable with shape (nsamps,)
        Weights associated with the samples. Default is `None` (no weights).

    levels : iterable, optional
        The contour levels to draw. Default are `[0.5, 1, 1.5, 2]`-sigma.

    ax : `~matplotlib.axes.Axes`, optional
        An `~matplotlib.axes.axes` instance on which to add the 2-D histogram.
        If not provided, a figure will be generated.

    color : str, optional
        The `~matplotlib`-style color used to draw lines and color cells
        and contours. Default is `'gray'`.

    plot_datapoints : bool, optional
        Whether to plot the individual data points. Default is `False`.

    plot_density : bool, optional
        Whether to draw the density colormap. Default is `True`.

    plot_contours : bool, optional
        Whether to draw the contours. Default is `True`.

    no_fill_contours : bool, optional
        Whether to add absolutely no filling to the contours. This differs
        from `fill_contours=False`, which still adds a white fill at the
        densest points. Default is `False`.

    fill_contours : bool, optional
        Whether to fill the contours. Default is `True`.

    contour_kwargs : dict
        Any additional keyword arguments to pass to the `contour` method.

    contourf_kwargs : dict
        Any additional keyword arguments to pass to the `contourf` method.

    data_kwargs : dict
        Any additional keyword arguments to pass to the `plot` method when
        adding the individual data points.

    Nc             S   s   g | ]}d qS )g5?r   )rQ   r9   r   r   r   rS     s    z_hist2d.<locals>.<listcomp>r2   z,Dimension mismatch between samples and span.g      ?g      g      ?g @density_cmap)r	   r	   r	   r   
white_cmap)r	   r	   r	   )NrL   r	   g        g       @)r   rj   r3   zHIt looks like at least one of your sample columns have no dynamic range.r   z(Too few points to create valid contours.z&No points at all in the plotted regiongH.?rT   )r   r   )r	   r	   )r   rL   )r	   r  )rL   r   )r  r	   )rL   rL   )r  r  r%   msZmecnonerD   g?r   T)r   Z
rasterizedF)r   antialiasedcolorsr  gqh ?)r   )2r   Zgcarj   rh   r5   r   r<   r   re   ra   r   	from_listr   Zto_rgbafloatrm   r   r   rb   r   r   Zhistogram2dri   r   r   allr   ZargsortZcumsumr   r4   diffanyloggingwarningwhererW   Zzerosr   Zconcatenater   r^   ru   Zcontourfr   rP   ZpcolorZcontourrk   rl   )(r!   r   r   r7   r3   r   r#   r%   Zplot_datapointsZplot_densityr   Zno_fill_contoursr   Zcontour_kwargsZcontourf_kwargsZdata_kwargsr~   r  r  Z
rgba_colorZn_levelsZcontour_cmapr9   r   Zsvaluesr   HXYZHflatZindssmVZv0mZX1ZY1ZH2ZX2ZY2r   r   r   r   m  s    Q 

$





:*(,(,


)NN)NFTr=   r>   NNTNr?   Nr@   rA   TTN)Nr   r   r	   Nr>   NTr=   r   NNFrZ   r?   NrC   FNNFr   r   NNr?   NFN)Nr	   Nr   NTr=   NNNNr?   NrC   FN)NNr   r   r   NNNNNFr   r   NNr?   NrC   FFFN)NNNNNr   r   NNNrC   FFr   NNN)NNNNNNr   r   NNNrC   FFr   NNN)r   NNNNr   FTTFTNNN)/__doc__r   rc   numpyr   Zmatplotlib.pyplotZpyplotr   Zmatplotlib.tickerr   r   Zmatplotlib.colorsr   r   r   Zscipy.ndimager   r   Zscipy.statsr   utilsr
   r   r   r6   r   r    r   r   rn   r  r   r   r   __all__r    r$   r1   r<   r   r   r   r   r   r   r   r   r   r   r   <module>   sN  
 
               
  !                            
   
               
 }                     
  u                
  .                 
  _             