B
    bd                 @   s  d dl mZmZmZmZ dZd dlZd dlmZmZ d dl	m
Z d dlZd dlZd dlZd dlZd dlmZ d dl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$ d dl%Z%yej&Z'ej(Z)ej*Z+W n   e,Z'e-Z)e.Z+Y nX e/e-e0ej1j2Z3dOddZ4dPddZ5dQddZ6ddddgdddddddddddddddddd ddddddfd!d"Z7dRd$d%Z8ddddgd&ddddddd dddddddddfd'd(Z9dSd*d+Z:e;ej<d,krej=>d-ej<d  ef  e?d# ej<d# Z@eAd.e@  ejBCe@d/ sdej=>d0ej<d# ef  e?d, eDeEe@d/ ZFe;eFZGejHeGe@d1ZIeIJ ZKejLeKeEe@d2 d3d4d5 eAd6 eAd7eKd8 eKd9 f  eAd: xeMeFeKd; D ]\ZNZOeOd< \ZPZQeOd= ZReQeP d, ZSeSd krdZTn eUd e.eVeWeS d# ZTd>eT ZXd?Yd@eX dA eX gZZeAeZeNeReSf  qW eAdB eI[ Z\e\ddd#f ] dddC ZTe\eTd,df Z^e\eTd f Z_e\eTd#f Z`eKd8 Zaee_de`  ea ZbebebU  Zbece^e_ebdDZde7edeFddE ejee@dF dGdH ejee@dI dGdH ef  e9edeFddE ejee@dJ dGdH ejee@dK dGdH ef  e8edeFdL ejee@dM dGdH ejee@dN dGdH ef  dS )T    )absolute_importunicode_literalsprint_functiondivisionz
Script that does default visualizations (marginal plots, 1-d and 2-d).

Author: Johannes Buchner (C) 2013-2019
Author: Josh Speagle (MIT licensed)
N)explog)range)MaxNLocatorNullLocator)LinearSegmentedColormapcolorConverter)ScalarFormatter)spatial)gaussian_filter)gaussian_kdec             C   s   t | } t |}t |dk s0t |dkr8td|dkrTt | td| S t |}t| t|krvtdt | }|| }t |dd }||d  }t 	d|}t 
||| |  }|S dS )	a	  
    Compute (weighted) quantiles from an input set of samples.
    Parameters
    ----------
    x : `~numpy.ndarray` with shape (nsamps,)
        Input samples.
    q : `~numpy.ndarray` with shape (nquantiles,)
       The list of quantiles to compute from `[0., 1.]`.
    weights : `~numpy.ndarray` with shape (nsamps,), optional
        The associated weight from each sample.
    Returns
    -------
    quantiles : `~numpy.ndarray` with shape (nquantiles,)
        The weighted sample quantiles computed at `q`.
    g        g      ?z#Quantiles must be between 0. and 1.Ng      Y@z+Dimension mismatch: len(weights) != len(x).r   )np
atleast_1dany
ValueErrorZ
percentilelistlenargsortcumsumappendinterptolist)xqweightsidxswZcdf	quantiles r#   s/work/yifan.wang/ringdown/master-ringdown-env/lib/python3.7/site-packages/../../../bin/multinest_marginals_fancy.py	_quantile,   s     



r%   c       	      C   s   |dkrt j}tt |d tkr,tdt|}| t | | }t j|t j	d}t 
|}d\}}x6||k r|| || k r|||< |d7 }qn|d7 }qnW | | S )a  
    Resample a new set of points from the weighted set of inputs
    such that they all have equal weight.
    Each input sample appears in the output array either
    `floor(weights[i] * nsamples)` or `ceil(weights[i] * nsamples)` times,
    with `floor` or `ceil` randomly selected (weighted by proximity).
    Parameters
    ----------
    samples : `~numpy.ndarray` with shape (nsamples,)
        Set of unequally weighted samples.
    weights : `~numpy.ndarray` with shape (nsamples,)
        Corresponding weight of each sample.
    rstate : `~numpy.random.RandomState`, optional
        `~numpy.random.RandomState` instance.
    Returns
    -------
    equal_weight_samples : `~numpy.ndarray` with shape (nsamples,)
        New set of samples with equal weights.
    Examples
    --------
    >>> x = np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]])
    >>> w = np.array([0.6, 0.2, 0.15, 0.05])
    >>> utils.resample_equal(x, w)
    array([[ 1.,  1.],
           [ 1.,  1.],
           [ 1.,  1.],
           [ 3.,  3.]])
    Notes
    -----
    Implements the systematic resampling method described in `Hol, Schon, and
    Gustafsson (2006) <doi:10.1109/NSSPW.2006.4378824>`_.
    Ng      ?zWeights do not sum to 1.)Zdtype)r   r      )r   randomabssumSQRTEPSr   r   arangezerosintr   )	samplesr   ZrstateZnsamplesZ	positionsr    Zcumulative_sumijr#   r#   r$   resample_equalV   s    "


r1   FT  bluered      c       $         s  |dkrt  }|dkrt  }|dkr*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 nZ   t|| d  }|| | d kr0td| d d ddd }t||}Y nX |rb|| | d krT|}nt	
d d}|t|t|tg}|rtt |d }td d |}|| |d< dkrdd |D d}nd}ttdkr tdxXtD ]L\}}y| \}}W n0   t|| |  t|| f|< Y nX q
W |r|r|rtd dd   td dd   f} n"ddtd dd    f} | d< |dkrtjddd d!\}fd"dD nf|\}ydd W n   td#Y nX d$d D d%d D d&d D d'd D fd(dtdD  fd)dtdD  d*d+d,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 d6|  j!|!| f| |r|dkr j" |"fd1i| d2d D nF|r|dkr j#| |"fd1i| n j# |"fd1i| |dkr.|r. fd3dtddD  |rx j$|  fd4dd5| |dkrx j%|fd4dd5| |dkr|	dk	rʈ j%t|	fd1|
i| qW |fS )7a  
    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solidr6   niterlogvollogllogwtlogzr   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.   r   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!g433333@g?g      @)   rI   )figsizec                s   g | ]}d t   fqS )g        )min)rE   ax)r=   r#   r$   rG   9  s    zCProvided axes do not match the required shape for plotting samples.c             S   s   g | ]}|  qS r#   )Zget_xlim)rE   rL   r#   r#   r$   rG   C  s    c             S   s   g | ]}|  qS r#   )get_ylim)rE   rL   r#   r#   r$   rG   D  s    c             S   s   g | ]}|d kr|ndqS ))g        g      ?)NNr#   )rE   tr#   r#   r$   rG   G  s    c             S   s   g | ]}|d kr|ndqS ))g        g      ?)NNr#   )rE   rN   r#   r#   r$   rG   H  s    c          	      s@   g | ]8} |  td | d tt | d gqS )g        r   r&   )set_xlimrK   rD   )rE   r/   )axesr=   xspanr#   r$   rG   K  s   c          	      sJ   g | ]B} |  t| d  | d  t| d | d gqS )r   r&   )set_ylimrK   rD   )rE   r/   )rP   spanyspanr#   r$   rG   N  s   zLive PointszLikelihood
(normalized)zImportance
WeightZEvidencez PDF)useMathText$-\ln X$colorc             S   s   g | ]}|  qS r#   )rM   )rE   rL   r#   r#   r$   rG   r  s    c          
      s>   g | ]6} j  t|  t|  d dqS )g?)rW   r9   )fill_betweenr   r   )rE   s)rL   cr=   r@   rA   r#   r$   rG   x  s   dashed)rW   lslw)rV   )&dictgetrD   r   isfiniter   Zonesr+   r   warningswarnr   r   r1   linspacepdfr   r   	enumerateplsubplotsreshaper   
isinstancestr_typexaxisset_major_locatorr
   r	   yaxisr   set_major_formatter
set_xlabel
set_ylabelZsemilogyplotaxvlineaxhline)$resultsrS   ZlogplotkdenkderW   plot_kwargslabel_kwargsZ	lnz_errorZ	lnz_truthtruth_colortruth_kwargsZmax_x_ticksZmax_y_ticksuse_math_textZmark_final_livefigr<   r>   r?   nsampsrB   Znlive_finalZlive_idxdatawt_kdeZ
logvol_newZno_spanr/   _ZyminZymaxZzspanlabelsrF   sfr#   )	rL   rP   rZ   r=   r@   rA   rS   rQ   rT   r$   runplot   s    _

0"




"r   g?g      ?g333333?{Gz?plasma
   r8   z.2fc       A   
      s  |dkrt  }|dkrt  }|
dkr*t  }
|dkr8t  }|dkrFt  }dkrTt  |dd|d< |dd|d< |
dd|
d< ddd< d	d
d	< | d }| d }yt| d | d d  }W n   | d }Y nX |r4tt| |}t|d |d |}|| } t| | | }!n|}!t	|}t
|jdkr^t|}nt
|jd
ksvtd|j}|jd |jd kstd|j\}"}#|jdkrtd|#|jd krtd|jdkrtd|#|jd krtd|r^y| d }$t|$}%W n   tdY nX y|d }&|}&W n   tjj|%|dd}&Y nX |dkrzdd t|"D }t|}t
||"krtdxjt|D ]^\}'}(y||' \})}*W nB   d d ||'   d d ||'   g}+t||' |+|d!||'< Y nX qW |dkr d"d t|"D }tts8ttrNfd#dt|"D |dkrvtj|"d
d$d|" fd%\}},n.|\}},y|,|"d
 W n   td&Y nX x
t|D ]\}'}-t|d dkr|,d  n|,|'df  |	dk	r
t|	tr |	}.n|	|' }.n|!}.t|tr |}/n||' }/ d't | g  !t |-t"|-g |dkrz j#$t%   j&$t%  n  j#$t'|  j&$t'| t(|d(}0 j&)|0  j*d;|  j+||' f|  j,| |-f|.|/d*|
 |r*x8|&D ]0}1|$|1k}2 j-||2  |-|2 fd+|i| qW |dk	r||' dk	ry fd,d||' D  W n&    j.||' fd+i Y nX t|d dkr|,d  n|,|'df  t|tr|}.n||' }. ||'  |dkr j#$t%   j&$t%  n j#$t'|  j&$t%  t(|d(}0 j#)|0  j*||' f| |' }3t|3trʈ j/|-f|3||.t0||' d-|\}4}5}(t1tt2|5dd |5dd 3 }6t1tt2|4|43 }7nrt4t5d.|3 }8tj6|-|8|t0||' d/\}4}5t7|4d.}4d |5dd |5dd   }6|4}7 j8|6|7fd+|.i|  !d't"|7d0 g |dk	rt
|dkrt|-||d!}9x |9D ]}+ j9|+dd1|.d2 q~W |rt:d3 t:||' d4d t2||9D  |dk	r$||' dk	r$y fd5d||' D  W n&    j9||' fd+i Y nX |rd}:|dk	rt|-d6d d7g|d!\};}<}=|<|; |=|<  }>}?d8;|j;}@d9}:|:;|@|<|@|>|@|?}:d:;||' |:}: j<|:f| qW ||,fS )<a  
    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`.

    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 `True`.

    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.

    Nr9   gffffff?g333333?rY   r6   r:   r;   r7   rC   r.   r=   r?   r@   r   r   r   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#   )rE   r/   r#   r#   r$   rG   p  s    ztraceplot.<locals>.<listcomp>z,Dimension mismatch between samples and span.g      ?)r   c             S   s    g | ]}d t |d  d qS )z$x_{r&   z}$)str)rE   r/   r#   r#   r$   rG   }  s    c                s   g | ]} qS r#   r#   )rE   r/   )smoothr#   r$   rG     s       )rJ   zCProvided axes do not match the required shape for plotting samples.g        )rU   $-\ln X$)rZ   cmaprW   c                s"   g | ]} j |fd iqS )rW   )rs   )rE   rN   )rL   ry   rz   r#   r$   rG     s   )binsr   rW   r   g      $@)r   r   r   g?r[   )r]   r\   rW   z
Quantiles:c             S   s   g | ]}|qS r#   r#   )rE   blobr#   r#   r$   rG     s    c                s"   g | ]} j |fd iqS )rW   )rr   )rE   rN   )rL   ry   rz   r#   r$   rG     s   g?g333333?z	{{0:{0}}}z${{{0}}}_{{-{1}}}^{{+{2}}}$z	{0} = {1})r   )=r^   r_   r   r   r   r1   rc   rd   r   r   r   shape
atleast_2dAssertionErrorTndimr   uniquer'   choicer   r   re   r%   ri   int_type
float_typerf   rg   rh   rj   rO   rK   rR   rD   rk   rl   r
   rm   r	   r   rn   ro   rp   scatterrq   rs   histsortarrayzipflattenr-   round	histogramnorm_kderX   rr   printformat	set_title)Art   rS   r"   r   Z
post_colorZpost_kwargsru   rv   Z
trace_cmapZtrace_colorZtrace_kwargsconnectZconnect_highlightZconnect_colorZconnect_kwargsmax_n_ticksr{   r   rx   show_titles	title_fmttitle_kwargstruthsry   rz   verboser|   r.   r=   r   r   logvol_gridwt_gridZwtsr   r}   r   uidZidsr/   r   xminxmaxr   rP   r   rW   r   r   r0   selrY   nbZx0Zy0r   qstitleqlqmqhq_minusq_plusfmtr#   )rL   r   ry   rz   r$   	traceplot  sL    


 "







 


(


 
r   r&   c       +   	      sL  dkrt  |	dkrt  }	|dkr*t  }|dd|d< ddd< ddd< dd	d< | d
 }| d }yt| d | d d  }W n   | d }Y nX |rtt| |}t|d |d |}|| }t| | |}t	|}t
|jdkrt|}nt
|jdks4td|j}|jd |jd ksXtd|j\}}|jdkrvtd||jd krtd|dk	rt
||krtdxjt|D ]^\}}y|| \}}W nB   dd||   dd||   g}t|| ||d||< Y nX qW |dkr6dd t|D }|dkrD|}d}d| }d| }d} ||d  ||d  |   }!||! | }"|dkrtj|d |d |"|"fd\}}#n>y(|\}}#t|#|d |d f}#W n   tdY nX ||" }$||! |" }%|j|$|$|%|%| | d  x(t|dd D ]\}}&xt|dd D ]\}'}(|#||'f  |dk	r ||'   ||  |'|kr d!  g   g  qJ|dkrڈ jt    j!t   n( jt"|d"d#  j!t"|d"d# t#|d$}) j$|)  j!$|) ||d k r> %g  n2d%d  & D   j'||' f|	  j(dd& |'dkr )g  n6d'd  * D   j+||d  f|	  j!(d&d t,|(-d(}*|dk	r|| dk	r|*|&|| d k|&|| d k@ 9 }*|dk	rD||' dk	rD|*|(||' d k|(||' d k@ 9 }* j.|(|* dd| |&|* dd| f||d)| |
dk	rJ|
|' dk	ry fd*d|
|' D  W n&    j/|
|' fd+i Y nX |
|d  dk	rJy" fd,d|
|d  D  W n*    j0|
|d  fd+i Y nX qJW q,W ||#fS )-a  
    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/>`_.

    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.

    NrY   r&   r:   r;   r7   rC   r9   gffffff?r.   r=   r?   r@   r   r   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,Dimension mismatch between samples and span.g      ?)r   c             S   s    g | ]}d t |d  d qS )z$x_{r&   z}$)r   )rE   r/   r#   r#   r$   rG     s    z cornerpoints.<locals>.<listcomp>g       @g?g?g      ?)rJ   z$Mismatch between axes and dimension.)leftbottomrighttopwspacehspaceFlower)prune)rU   c             S   s   g | ]}| d qS )-   )set_rotation)rE   lr#   r#   r$   rG     s    g333333ӿc             S   s   g | ]}| d qS )r   )r   )rE   r   r#   r#   r$   rG     s    bool)rZ   r   c                s"   g | ]} j |fd iqS )rW   )rr   )rE   rN   )rL   ry   rz   r#   r$   rG     s   rW   c                s"   g | ]} j |fd iqS )rW   )rs   )rE   rN   )rL   ry   rz   r#   r$   rG     s   )1r^   r_   r   r   r   r1   rc   rd   r   r   r   r   r   r   r   r   r   re   r%   r   rf   rg   r   rh   subplots_adjustrO   rR   set_frame_on
set_xticks
set_yticksrk   rl   r
   rm   r	   r   rn   set_xticklabelsget_xticklabelsro   set_label_coordsset_yticklabelsget_yticklabelsrp   Z	ones_likeZastyper   rr   rs   )+rt   ZthinrS   r   rW   ru   rv   rw   r   rx   r   ry   rz   r   r{   r|   r.   r=   r   r   r   r   r   r}   r/   r   r   r   r   factorlbdimtrdimwhspaceplotdimdimrP   lbtrr   r0   yr   Z	in_boundsr#   )rL   ry   rz   r$   cornerpoints  s    ^


 "


" 












$$&
r   blackc       <   
      sB	  |dkrg }dkrt  |dkr(t  }|dkr6t  }|dkrDt  }|dkrRt  }|dd|d< |dd|d< ddd< ddd< ddd< | d	 }yt| d
 | d d  }W n   | d }Y nX t|}t|jdkrt|}nt|jdkstd|j	}|jd |jd ks@td|j\}}|j
dkr^td||jd krvtd|dkrdd t|D }t|}t||krtdxjt|D ]^\}}y|| \}}W nB   dd||   dd||   g}t|| ||d||< Y nX qW |dkr8dd t|D }ttsPttrffddt|D d}d| }d| }d} || ||d  |   }!||! | }"|dkrtj|||"|"fd\}}#n6y |\}}#t|#||f}#W n   td Y nX ||" }$||! |" }%|j|$|$|%|%| | d! xt|D ]\}}&t|d dkrV|# n|#||f   ||  |dkr jt   jt  n" jt|d"d#  jt  t|d$}' j|' ||d k r|r j d% d&d  ! D  n
 "g  n2d'd  ! 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/|d0 qHW |rt.d1 t.|| d2d t/||-D  |dk	r|| dk	ry fd3d|| D  W n&    j-|| fd4i Y nX |	rvd}.|
dk	rvt|&d5dd6g|d\}/}0}1|0|/ |1|0  }2}3d70|
j0}4d8}.|.0|4|0|4|2|4|3}.d90|| |.}. j1|.f| xt|D ]\}5}6t|d dkr|# n|#||5f  |5|kr 2d:  3g   4g  qn|5|krq|dkr jt   jt  n( jt|d"d#  jt|d"d# t|d$}' j|'  j|' ||d k rz "g  n2d;d  ! D   j#||5 f|  j$dd( |5dkr 5g  n2d<d  6 D   j7|| f|  j$d(d |5 }7t|(t}8t|7t}9|8r&|9r&d:}:d:};nd=}:d=};|d>|:|d>< |d?|;|d?< t8|6|&f ||5 || g|||7|(gd@| |dk	r||5 dk	ry fdAd||5 D  W n&    j-||5 fd4i Y nX || dk	ry fdBd|| D  W n&    j9|| fd4i Y nX qW q2W ||#fS )Cau  
    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/>`_.

    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`.

    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 `True`.

    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.

    Nr9   g333333?r:   r;   r7   rC   gffffff?r.   r?   r@   r   r   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#   )rE   r/   r#   r#   r$   rG     s    zcornerplot.<locals>.<listcomp>z,Dimension mismatch between samples and span.g      ?)r   c             S   s    g | ]}d t |d  d qS )z$x_{r&   z}$)r   )rE   r/   r#   r#   r$   rG     s    c                s   g | ]} qS r#   r#   )rE   r/   )r   r#   r$   rG     s    g       @g?g?g      ?)rJ   z$Mismatch between axes and dimension.)r   r   r   r   r   r   r   )r   )rU   r   c             S   s   g | ]}| d qS )r   )r   )rE   r   r#   r#   r$   rG     s    c             S   s   g | ]}| d qS )r   )r   )rE   r   r#   r#   r$   rG     s    g333333ӿ)r   r   rW   r   g      $@)r   r   r   )r   r   r   rW   g        g?r[   )r]   r\   rW   z
Quantiles:c             S   s   g | ]}|qS r#   r#   )rE   r   r#   r#   r$   rG     s    c                s"   g | ]} j |fd iqS )rW   )rr   )rE   rN   )rL   ry   rz   r#   r$   rG     s   rW   g?g333333?z	{{0:{0}}}z${{{0}}}_{{-{1}}}^{{+{2}}}$z	{0} = {1}Fc             S   s   g | ]}| d qS )r   )r   )rE   r   r#   r#   r$   rG   B  s    c             S   s   g | ]}| d qS )r   )r   )rE   r   r#   r#   r$   rG   H  s    Tfill_contoursplot_contours)rL   rS   r   rW   r   c                s"   g | ]} j |fd iqS )rW   )rr   )rE   rN   )rL   ry   rz   r#   r$   rG   `  s   c                s"   g | ]} j |fd iqS )rW   )rs   )rE   rN   )rL   ry   rz   r#   r$   rG   g  s   ):r^   r_   r   r   r   r   r   r   r   r   r   r   r   r   re   r%   ri   r   r   rf   rg   r   rh   r   rO   rk   rl   r
   rm   r	   r   rn   Zset_ticks_positionr   r   ro   r   r   r   r-   r   r   r   rR   rD   rr   r   r   r   r   r   r   r   r   r   rp   _hist2drs   )<rt   rS   r"   rW   r   Zhist_kwargsZhist2d_kwargsr   rx   r   r   r   r   ry   rz   r   Z	top_ticksr{   r   r|   r.   r   r   r}   r/   r   r   r   r   r   r   r   r   r   r   rP   r   r   r   r   sxr   r   r   Zb0r   r   r   r   r   r   r   r   r0   r   ZsyZcheck_ixZcheck_iyr   r   r#   )rL   r   ry   rz   r$   
cornerplot  sp   t


 "






 


 

















r   grayc       ,         s  |dkrt  }| |g}|dkr2dd tdD }t|}t|dkrNtdxht|D ]\\}}y|| \}}W qX   dd||   dd||   g}t|| ||d||< Y qXX qXW |dkrdt	d	t
dd
dd   }td|dg}tjdddgdd}t|  fdd|D  g }x:t|D ].\}}|| d  t|t|d  9  < q0W t|tszt|tr||g}g }g }xP|D ]H}t|tr|| |d n |ttd|  |d qW y2tj|  | |tttj||d\}}} W n tk
r,   tdY nX t|dksHt||}| }!t|!ddd }"|!|" }!t|!}#|#|#d  }#tt|}$xHt|D ]<\}}%y|!|#|%k d |$|< W n   |!d |$|< Y nX qW |$  t|$dk}&t |&r|
rt!"d x>t |&rJ|$t#|&d d   d9  < t|$dk}&qW |$  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r"t) }|*d$||d$< |*d%d|d%< |*d&d'|d&< |*d(d)|d(< |j+| |d*fdd+d,| |
s|	r|s|j,|*|+|)j-|$$ |. g|d-d. |
r |r |dkrt) }|*d/||d/< |*d0d-|d0< |j,|*|+|)j-t'dg|$|. d1 ggf| n"|	rB|j/|| |. |j- |d2 |
r~|dkrXt) }|*d/||d/< |j0|*|+|)j-|$f| |1|d  |2|d  dS )3a  
    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#   )rE   r/   r#   r#   r$   rG     s    z_hist2d.<locals>.<listcomp>rC   z,Dimension mismatch between samples and span.g      ?)r   g      ?g      g @density_cmap)r&   r&   r&   r   
white_cmap)r&   r&   r&   )Nc                s   g | ]}t  qS r#   )r   )rE   r   )
rgba_colorr#   r$   rG     s    r   r&   g        g       @)r   r   r   zHIt looks like at least one of your sample columns have no dynamic range.r   z(Too few points to create valid contours.gH.?rH   )r   r   )r&   r&   )r   r   )r&   r   )r   r   )r   r&   )r   r   )r   r   rW   msZmecnoner9   g?oT)ZzorderZ
rasterizedF)r   antialiasedcolorsr   gqh ?)r   )3rf   Zgcar   r   r   r   re   r%   r   r   r+   r   	from_listr   Zto_rgbafloatri   r   r   r   r-   r   Zhistogram2dr   mapr   allr   r   r   emptydiffr   loggingwarningwhererK   r,   r   Zconcatenater   r^   r_   rq   Zcontourfr   rD   ZpcolorZcontourrO   rR   ),r   r   r   rS   r   ZlevelsrL   rW   Zplot_datapointsZplot_densityr   Zno_fill_contoursr   Zcontour_kwargsZcontourf_kwargsZdata_kwargskwargsr~   r/   r   r   r   r   r   r   Zcontour_cmapr   r   ZsvaluesrY   HXYZHflatZindssmVZv0mZX1ZY1ZH2ZX2ZY2r#   )r   r$   r   q  s    F   
*




:*,,,,



(
r   rC   zSYNOPSIS: %s <output-root> 

	output-root: 	Where the output of a MultiNest run has been written to. 
	            	Example: chains/1-
%sz
model "%s"zparams.jsonzExpected the file %sparams.json with the parameter names.
For example, for a three-dimensional problem:

["Redshift $z$", "my parameter 2", "A"]
%s)n_paramsZoutputfiles_basenamez
stats.jsonwrH   )indentz  marginal likelihood:z    ln Z = %.1f +- %.1fzglobal evidencezglobal evidence errorz  parameters:Z	marginalsZ1sigmaZmedianz%%.%df	z	    %-15sz +- zcreating marginal plot ...r   )r.   r   r=   )r   r   z	trace.pdfZtight)Zbbox_inchesz	trace.pngz
corner.pdfz
corner.png)r   zcornerp.pdfzcornerp.png)N)N)NFTr2   r3   NNTNr4   Nr5   r6   TTN)r&   Nr   NTr2   NNNNr4   Nr8   FN)r   NNNNr   FTTFTNNN)g
__future__r   r   r   r   __doc__numpyr   r   Zmatplotlib.pyplotZpyplotZpltsysosjsonZpymultinestZ	six.movesr   r   typesmathr   rf   Zmatplotlib.tickerr	   r
   Zmatplotlib.colorsr   r   r   Zscipyr   Zscipy.ndimager   r   Zscipy.statsr   ra   ZStringTypesrj   Z	FloatTyper   ZIntTyper   r   r   r-   sqrtZfinfoZfloat64Zepsr*   r%   r1   r   r   r   r   r   r   argvstderrwriteexitprefixr   pathexistsloadopen
parametersr   ZAnalyzeraZ	get_statsrY   dumpr   pr   lohiZmedsigmar/   rD   floorlog10r   joinZfmtsget_datar~   r   r.   r   ZloglikeZr=   r^   rt   Zsavefigcloser#   r#   r#   r$   <module>   s   


*
:    
 v  ~    
 u
  h   
 Z



 