B
    ú‹d¶v ã               @   s  d 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	m
Z
 ddlmZmZmZmZmZ ddlmZ ddlmZmZmZmZmZmZmZmZmZmZmZmZm Z  d	d
dgZ!eeeeedœZ"G dd„ deƒZ#dd„ Z$ddd
„Z%dd„ Z&ddd„Z'ddd„Z(ddd„Z)G dd	„ d	ƒZ*dS )a°  
Contains the dynamic nested sampler class :class:`DynamicSampler` used to
dynamically allocate nested samples. Note that :class:`DynamicSampler`
implicitly wraps a sampler from :mod:`~dynesty.nestedsamplers`. Also contains
the weight function :meth:`weight_function` and stopping function
:meth:`stopping_function`. These are used by default within
:class:`DynamicSampler` if corresponding functions are not provided
by the user.

é    N)ÚEnum)Ú	logsumexpé   )ÚUnitCubeSamplerÚSingleEllipsoidSamplerÚMultiEllipsoidSamplerÚRadFriendsSamplerÚSupFriendsSampler)ÚResults)Úget_seed_sequenceÚget_print_funcÚ
_kld_errorÚcompute_integralsÚIteratorResultÚIteratorResultShortÚget_enlarge_bootstrapÚ	RunRecordÚget_neff_from_logwtÚ
DelayTimerÚsave_samplerÚrestore_samplerÚ	_LOWL_VALÚDynamicSamplerÚweight_functionÚstopping_function)ÚnoneZsingleÚmultiZballsZcubesc               @   s4   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdS )ÚDynamicSamplerStatesEnumú r   é   é   é   é   é   é   é   é	   N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚINITÚLIVEPOINTSINITÚINBASEÚ	BASE_DONEÚINBATCHÚ
BATCH_DONEÚINBASEADDLIVEÚINBATCHADDLIVEÚRUN_DONE© r4   r4   úc/work/yifan.wang/ringdown/master-ringdown-env/lib/python3.7/site-packages/dynesty/dynamicsampler.pyr   -   s   r   c             C   sÞ   | j }| j}| j}| j}| j}| ¡ dkrLt d¡ t 	t
|ƒ¡t
|ƒ }nj|d |d  }t |d |¡}t |¡}	t|	| |gd|	|	 gd}
|
t |¡ }|t|ƒ8 }t |¡}t ||d  ¡}|t |¡ }||fS )zj Derive evidence and posterior weights.
    return two arrays, evidence weights and posterior weights
    r   zŒThe calculation of weights is seeing same
logz values associated with all the samples. It may mean somethings is
wrong with your likelihood.éÿÿÿÿ)ZaxisÚb)ÚloglÚlogzÚlogvolÚlogwtÚ	samples_nÚptpÚwarningsÚwarnÚnpÚonesÚlenZ	logaddexpZ	ones_liker   ÚlogÚexpÚsum)Úresultsr8   r9   r:   r;   r<   ÚzweightZlogz_remainZlogz_totZlzonesZlogzinZ
logzweightÚpweightr4   r4   r5   Úcompute_weights;   s*    

rI   Fc             C   s°  |dkri }|  dd¡}d|  kr,dks>n td|› dƒ‚|  dd¡}d|  kr^dkspn td	|› dƒ‚|  d
d¡}|dk r”td|› dƒ‚t| ƒ\}}d| | ||  }t|ƒ}	t ||t |¡ k¡d }
|
d | |
d | f}
| j}|
d |	d kr(|
d |
d |	d   |	d g}
|
d dkr^tj }|t	|
d |
d  |	d ƒ }n||
d  ||
d   }}|
d |	d krtj}|r¨||f|||ffS ||fS )a  
    The default weight function utilized by :class:`DynamicSampler`.
    Zipped parameters are passed to the function via :data:`args`.
    Assigns each point a weight based on a weighted average of the
    posterior and evidence information content::

        weight = pfrac * pweight + (1. - pfrac) * zweight

    where `pfrac` is the fractional importance placed on the posterior,
    the evidence weight `zweight` is based on the estimated remaining
    posterior mass, and the posterior weight `pweight` is the sample's
    importance weight.

    Returns a set of log-likelihood bounds set by the earliest/latest
    samples where `weight > maxfrac * max(weight)`, with additional
    left/right padding based on `pad`.

    Parameters
    ----------
    results : :class:`Results` instance
        :class:`Results` instance.

    args : dictionary of keyword arguments, optional
        Arguments used to set the log-likelihood bounds used for sampling,
        as described above. Default values are `pfrac = 0.8`, `maxfrac = 0.8`,
        and `pad = 1`.

    return_weights : bool, optional
        Whether to return the individual weights (and their components) used
        to compute the log-likelihood bounds. Default is `False`.

    Returns
    -------
    logl_bounds : tuple with shape (2,)
        Log-likelihood bounds `(logl_min, logl_max)` determined by the weights.

    weights : tuple with shape (3,), optional
        The individual weights `(pweight, zweight, weight)` used to determine
        `logl_bounds`.

    NÚpfracgš™™™™™é?g        g      ð?zThe provided `pfrac` z is not between 0. and 1.ÚmaxfraczThe provided `maxfrac` Úpadr   r   z`lpad` z is less than zero.r6   )
ÚgetÚ
ValueErrorrI   rB   r@   ÚnonzeroÚmaxr8   ÚinfÚmin)rF   ÚargsZreturn_weightsrJ   rK   ZlpadrG   rH   ÚweightZnsampsZboundsr8   Úlogl_minÚlogl_maxr4   r4   r5   r   _   s<    ,  c             C   sÄ   | dkr||dkrd}q²|dkr(d| }q²|dkr>d| | }q²|dkrPd	| }q²|d
krbd| }q²t j}t d|› d¡ n6t| tƒrŒ| }n&t| tƒr¤| d | }ntd| › ƒ‚|dkrÀt j}|S )zF
    Get the update_interval divided by the number of live points
    NZunifg      ø?Zrwalkg333333Ã?ÚslicegÍÌÌÌÌÌì?Úrsliceg       @Zhsliceg      9@z6No update_interval set with unknown sampling method: 'z'. Defaulting to no updates.g      ð?zStrange update_interval value r   )r@   rQ   r>   r?   Ú
isinstanceÚfloatÚintÚRuntimeError)Úupdate_intervalÚsampleÚboundÚndimÚnliveÚslicesÚwalksZupdate_interval_fracr4   r4   r5   Ú_get_update_interval_ratio¸   s,    




rd   c                s  |dkri }|dkrt }| dd¡}d|  kr8dksJn td|› dƒ‚| dd¡}|dk r||dk r|td	|› d
|› dƒ‚| dd¡}|dkr²|dk r²td|› dd|›  ƒ‚| dd¡}|dk rÖtd|› dƒ‚|dkrð|dk rðt d¡ | dd¡‰ˆdkrtdˆ› dƒ‚| dd¡‰ |dkr´‡fdd „t|ƒD ƒ}	‡fd!d „t|ƒD ƒ}
‡ fd"d „t|ƒD ƒ}t||ƒ}t|	|
||ƒ}t|t	|ƒƒ}t
 d#d „ |D ƒ¡}t
 |¡}n
ˆjd$ }|| }tˆjƒ}|| }|| d| |  }|r|dk|||ffS |dkS dS )%a©  
    The default stopping function utilized by :class:`DynamicSampler`.
    Zipped parameters are passed to the function via :data:`args`.
    Assigns the run a stopping value based on a weighted average of the
    stopping values for the posterior and evidence::

        stop = pfrac * stop_post + (1.- pfrac) * stop_evid

    The evidence stopping value is based on the estimated evidence error
    (i.e. standard deviation) relative to a given threshold::

        stop_evid = evid_std / evid_thresh

    The posterior stopping value is based on the estimated effective number
    of samples.

        stop_post = target_n_effective / n_effective

    Estimates of the mean and standard deviation are computed using `n_mc`
    realizations of the input using a provided `'error'` keyword (either
    `'jitter'` or `'resample'`, which call related functions :meth:`jitter_run`
    and :meth:`resample_run` in :mod:`dynesty.utils`, respectively.

    Returns the boolean `stop <= 1`. If `True`, the :class:`DynamicSampler`
    will stop adding new samples to our results.

    Parameters
    ----------
    results : :class:`Results` instance
        :class:`Results` instance.

    args : dictionary of keyword arguments, optional
        Arguments used to set the stopping values. Default values are
        `pfrac = 1.0`, `evid_thresh = 0.1`, `target_n_effective = 10000`,
        `n_mc = 0`, `error = 'jitter'`, and `approx = True`.

    rstate : `~numpy.random.Generator`, optional
        `~numpy.random.Generator` instance.

    M : `map` function, optional
        An alias to a `map`-like function. This allows users to pass
        functions from pools (e.g., `pool.map`) to compute realizations in
        parallel. By default the standard `map` function is used.

    return_vals : bool, optional
        Whether to return the stopping value (and its components). Default
        is `False`.

    Returns
    -------
    stop_flag : bool
        Boolean flag indicating whether we have passed the desired stopping
        criteria.

    stop_vals : tuple of shape (3,), optional
        The individual stopping values `(stop_post, stop_evid, stop)` used
        to determine the stopping criteria.

    NrJ   g      ð?g        zThe provided `pfrac` z is not between 0. and 1.Úevid_threshgš™™™™™¹?zThe provided `evid_thresh` z, is not non-negative even though `pfrac` is Ú.Útarget_n_effectivei'  z"The provided `target_n_effective` r   z+is not non-negative even though `pfrac` is Ún_mcr   zThe number of realizations z" must be greater or equal to zero.é   z`Using a small number of realizations might result in excessively noisy stopping value estimates.ÚerrorÚjitter>   rk   ÚresamplezThe chosen `'error'` option z is not valid.ÚapproxTr   c                s   g | ]}ˆ ‘qS r4   r4   )Ú.0Úi)rF   r4   r5   ú
<listcomp>=  s    z%stopping_function.<locals>.<listcomp>c                s   g | ]}ˆ ‘qS r4   r4   )rn   ro   )rj   r4   r5   rp   >  s    c                s   g | ]}ˆ ‘qS r4   r4   )rn   ro   )rm   r4   r5   rp   ?  s    c             S   s   g | ]}|d  j d ‘qS )r   r6   )r9   )rn   Úresr4   r4   r5   rp   C  s    r6   )ÚmaprM   rN   r>   r?   Úranger   ÚzipÚlistr   r@   ÚarrayZstdÚlogzerrr   r;   )rF   rS   ÚrstateÚMÚreturn_valsrJ   re   rg   rh   ZrlistZ
error_listZapprox_listZseedsÚoutputsZlnz_arrZlnz_stdZ	stop_evidÚn_effectiveZ	stop_postÚstopr4   )rm   rj   rF   r5   r   Ø   sV    B






c	          	   C   s€  d}	d}
| dkr¬d}t |t|d dƒƒ}t ||f¡}t ||f¡}t |¡}d}g }d}xè|d7 }|j||fd}|rŽ||t |¡ƒ}nt|t |¡ƒ}t t|ƒ¡}| t |¡¡}|rÔt dd„ |D ƒ¡}t d	d„ |D ƒ¡}|
|7 }
t 	|¡}| }t 
|¡}t || @ ¡r$td
ƒ‚t||< | ¡ }|dkrÈt || |ƒ}|dksZt‚t |¡d d|… }|| |||| …< || |||| …< || |||| …< |rÀ| || ¡ ||7 }||krj|| }|dkr\t |¡d d|… }t|ƒ|kst‚|| |||| …< || |||| …< || |||| …< |r\| || ¡ t |¡ }	P ||kr`|dkrŽtd|› dƒ‚q`t d|› d|› d¡ q`W nœ| dd… \}}}|rÌ| d }t |¡}xXt|ƒD ]L\}}t 	|¡sàt |¡dk rt||< ntd |||| || ¡ƒ‚qàW t |tk¡rHtdƒ‚t |¡dkrdt dt¡ |snd}||||f|	|
fS )a«  
    Initialize the first set of live points before starting the sampling

    Parameters
    ----------
    live_points: tuple of arrays or None
        This can be either none or
        tuple of 3 arrays (u, v, logl) or
        tuple of 4 arrays (u, v, logl, blobs), i.e.
        points location in cube coordinates,
        point slocation in original coordinates,
        logl values and optionally blobs associated

    prior_transform: function

    log_likelihood: function

    M: function
        The function supporting parallel calls like M(func, list)

    nlive: int
        Number of live-points

    npdim: int
        Number of dimensions

    rstate: :class: numpy.random.RandomGenerator

    blob: bool
        If true we also keep track of blobs returned by likelihood

    use_pool_ptform: bool or None
        The flag to perform prior transform using multiprocessing pool or not

    Returns
    -------
    (live_u, live_v, live_logl, blobs), logvol_init, ncalls : tuple
        The first tuple consist of:
        live_u Unit cube coordinates of points
        live_v Original coordinates.
        live_logl log-likelihood values of points
        blobs - Array of blobs associated with logl calls (or None)
        The other arguments are
        logvol_init Log(volume) associated with returned points.
               It will be zero, if all the log(l) values were finite
        ncalls Integer number of function calls
    r   Niè  r   é
   )Úsizec             S   s   g | ]
}|j ‘qS r4   )Úblob)rn   Ú_r4   r4   r5   rp   ²  s    z+_initialize_live_points.<locals>.<listcomp>c             S   s   g | ]
}|j ‘qS r4   )Úval)rn   r   r4   r4   r5   rp   ³  s    z,The log-likelihood of live point is invalid.zAfter z† attempts, we cound not find a single point that have a valid log-likelihood! Please check your prior transform and/or log-likelihood.z& attempts, we cound not find at least zS points that have a valid log-likelihood! The initial sampling is very inefficient!r    zNThe log-likelihood ({0}) of live point {1} located at u={2} v={3}  is invalid.z<Not a single provided live point has a valid log-likelihood!z–All the initial likelihood values are the same. You likely have a plateau in the likelihood. Nested sampling may not be the best sampler in this case.)rR   rP   r@   ÚzerosÚrandomÚasarrayrr   rv   ru   ÚisfiniteÚisneginfÚanyrN   r   rE   ÚAssertionErrorrO   ÚextendrB   rC   r\   r>   r?   Ú	enumerateÚsignÚformatÚallr=   ÚRuntimeWarning)Úlive_pointsÚprior_transformÚloglikelihoodry   ra   Únpdimrx   r€   Úuse_pool_ptformÚlogvol_initZncallsZ
n_attemptsZmin_npointsÚlive_uÚlive_vÚ	live_loglZngoodsÚ
live_blobsZiattemptZ
cur_live_uZ
cur_live_vZcur_live_loglZcur_live_blobsZfiniteZ
not_finiteZneg_infiniteZ	cur_ngoodZnextraZcur_indro   r8   r4   r4   r5   Ú_initialize_live_pointsW  s˜    8











rš   c       (      C   sž  d}d}t  | jd ¡}t  | jd ¡}t  | jd ¡}	t  | jd ¡}
t  | jd ¡}t  | jd ¡}g }t| j | j| j| j| j| j	|| j
| j| j| j| j| j| j| jd}||_| jj|_|d	kr"t  |
|
d
 t  |¡ k ¡d }t|ƒdkr|d
 }nt|	ƒd }t j |	|  }}n|\}}t  |	|k¡}|rtd	| j| j| j|| j| j| j| jd	\\}}}}}}t j|td}t j|td}t j|td}||7 }xPt |ƒD ]D}| !t"| d || || || d|| | j# dd| j$d	¡ q°W | %|¡ nØt  |	|k¡d }t|ƒdkrDt&d|› d|› d|	 '¡ › ƒ‚t|ƒ|k r¸t|	ƒ|k rpt  (t|	ƒ¡}n t  (|d
 | d |d
 d ¡}|d dkr°|	|d d  }nt j }||d  }|
| }t  )|| '¡  ¡} | |  *¡  } | dk *¡ }!| jj+|t,||!ƒ| dd}"t|"ƒ}#|#dkrTt&dd|› d d|#›  d|!›  d| ›  ƒ‚||"d	d	…f  -¡ }||"d	d	…f  -¡ }|	|"  -¡ }||"  -¡ }|#|_.||_/||_0||_1||_2||_3| %|¡ t  4|| jf¡}t  4||j5d f¡}t  4|¡}t j|td}t j|td}t j4|td}| jr(g }nd	}x°t |ƒD ]¤}| 6|¡}$|$\||< ||< ||< ||< | jr~|$d j}%| !|%¡ nd	}%||| 7 }| !t"| d || || || || || | j# || || | j$d	¡ q6W ||7 }||_.||_/||_0||_1||_7||_3||_8|r||_9|t j kr0d}&nt  :t  ;|	| ¡¡d }&x,|j <¡ D ]}'| j|' d	|&… |j|'< qTW t= |d | ¡|_>||_?|||||fS )a  
    This is a utility method that construct a new internal
    sampler that will sample one batch.
    Since the setting up requires us coming up with a set of
    of starting live points we also prepare the first list points
    that will be yielded by the "master" sampler (but those are
    yielded just for printing).

    This method should not modify the parent sampler at all other
    than using the parent's random number generator

    Parameters
    ----------
    main_sampler: DynamicNestedSampler
        The parent sampler that we'll use to initialize a new sampler

    nlive_new: integer
        The number of live-points in the new sampler

    update_interval : int
        Only update the bounding distribution
        every `update_interval`-th likelihood call. Note that
        here it must be integer

    logl_bounds: tuple
        Tuple of bounds in loglikelihood for the batch

    save_bounds: bool
        If true bounds will be preserved

    Returns
    -------
    batch_sampler: Sampler
        The sampler that will actually execute the batch.
        It will also have a first_points attribute with the list
        of IteratorResultShorts
    ncall: integer
        Number of likelihood calls throughout
    niter: integer
        Number of iterations
    logl_min: float
        actually used logl_min as we may modify logl_bound
    logl_max: float
        actually used logl_max
    r   ÚuÚvr8   r:   Úscaler€   )ÚncdimÚkwargsr€   Nr6   r   )ra   r“   rx   r€   r”   )Údtype)	ÚworstÚustarÚvstarÚloglstarÚncÚworst_itÚboundidxÚ	bounditerÚeffz`Could not find live points in the required logl interval. Please report!
Diagnostics. logl_min: z logl_bounds: z saved_loglmax: F)r   ÚpÚreplacezBOnly one live point is selected
Please report the error on github!zDiagnostics nlive_new: r   zcur_nlive: zn_pos_weight: zcur_wt: r   g      ð?)@r@   rv   Ú	saved_runÚ	_SAMPLERSÚboundingr’   r‘   r“   Ú	live_initÚmethodÚfirst_updaterx   Ú
queue_sizeÚpoolÚuse_poolrž   rŸ   r€   Úsave_boundsÚsamplerZlogl_first_updaterO   rC   rB   rQ   rŽ   rš   ry   r”   rƒ   r[   rA   rs   Úappendr   Úitr©   Zupdate_bound_if_neededr\   rP   ZarangerD   rE   ÚchoicerR   Úcopyra   r–   r—   r˜   r   r™   ÚemptyÚshapeZ
_new_pointÚ
live_boundÚlive_itr•   ZargminÚabsÚkeysÚmathZdlvÚfirst_points)(Zmain_samplerÚ	nlive_newr]   Úlogl_boundsrµ   ÚncallÚniterZsaved_uZsaved_vZ
saved_loglZsaved_logvolZsaved_scaleZsaved_blobsrÂ   Úbatch_samplerZlogl_max_posrU   rV   Zpselr–   r—   r˜   r™   Zlogvol0Úinit_ncallsr½   r¾   Zlive_ncro   Zsubset0Z
live_scaleZcur_log_uniwtZ	cur_uniwtZn_pos_weightZsubsetZ	cur_nliveZnewptr€   Zvol_idxÚkr4   r4   r5   Ú_configure_batch_sampler  s    9





"



rÊ   c               @   sò   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zed'dd„ƒZ	dd„ Z
dd„ Zedd„ ƒZedd„ ƒZedd„ ƒZd
d
d
d
d
ejdejd
ddfdd„Zd(dd„Zdd„ Zd
d
d
dejejd
d
d
d
d
d
d
d
d
d
d
dddd
d
dd
d fd!d"„Zd)d%d&„Zd
S )*r   a/  
    A dynamic nested sampler that allocates live points adaptively during
    a single run according to a specified weight function until a specified
    stopping criteria is reached.

    Parameters
    ----------
    loglikelihood : function
        Function returning ln(likelihood) given parameters as a 1-d `~numpy`
        array of length `ndim`.

    prior_transform : function
        Function transforming a sample from the a unit cube to the parameter
        space of interest according to the prior.

    npdim : int, optional
        Number of parameters accepted by `prior_transform`.

    bound : {`'none'`, `'single'`, `'multi'`, `'balls'`, `'cubes'`}, optional
        Method used to approximately bound the prior using the current
        set of live points. Conditions the sampling methods used to
        propose new live points.

    method : {`'unif'`, `'rwalk'`,
        `'slice'`, `'rslice'`, `'hslice'`}, optional
        Method used to sample uniformly within the likelihood constraint,
        conditioned on the provided bounds.

    update_interval : int
        Only update the bounding distribution every `update_interval`-th
        likelihood call.

    first_update : dict
        A dictionary containing parameters governing when the sampler should
        first update the bounding distribution from the unit cube to the one
        specified by the user.

    rstate : `~numpy.random.Generator`
        `~numpy.random.Generator` instance.

    queue_size: int
        Carry out likelihood evaluations in parallel by queueing up new live
        point proposals using (at most) this many threads/members.

    pool: pool
        Use this pool of workers to execute operations in parallel.

    use_pool : dict
        A dictionary containing flags indicating where the provided `pool`
        should be used to execute operations in parallel.

    ncdim: int
        Number of clustered dimensions

    nlive0: int
        Default number of live points to use

    kwargs : dict, optional
        A dictionary of additional parameters (described below).
    c             C   sÄ  || _ || _|| _|| _| d¡p$d| _|| _|| _|| _|| _	d | _
|| _t|| d¡| d¡ƒ\| _| _| j dd¡| _| j dd¡| _| j d	¡| _| j d
¡| _|| _|	| _|
| _| jd krÌt| _n|
j| _|| _| dd¡| _| dd¡| _| dd¡| _| dd¡| _| dd¡| _d| _d| _d| _ g | _!d| _"d| _#|| _$t%j&| _'t(dd| _)t(dd| _*d | _+t,j- t,j- | _.| _/d | _0d | _1d | _2d | _3d | _4d | _5d | _6d | _7d | _8d | _9d S )Nr€   FÚenlargeÚ	bootstraprc   é   rb   r    ÚciteZupdate_funcr‘   Tr’   Zpropose_pointZupdate_boundÚstop_functionr   r   g      ð?)Údynamic):r’   r‘   r“   rž   rM   r€   r®   r°   Úupdate_interval_ratior±   r¶   rŸ   r   rË   rÌ   rc   rb   rÎ   Zcustom_updaterx   r²   r³   rr   ry   r´   r”   Zuse_pool_loglZuse_pool_evolveZuse_pool_updateÚuse_pool_stopfnr¸   ÚbatchrÅ   r_   r©   ÚbaseÚnlive0r   r+   Úinternal_stater   r¬   Úbase_runÚnew_runr@   rQ   Únew_logl_minÚnew_logl_maxr–   r—   r¾   r½   r˜   r¯   Ú
nlive_initrÇ   Úcheckpoint_timerr™   )Úselfr’   r‘   r“   r_   r°   rÑ   r±   rx   r²   r³   r´   rž   rÕ   rŸ   r4   r4   r5   Ú__init__Ž  sf    
zDynamicSampler.__init__c             C   s   || _ d | _t| _d S )N)Ú__dict__r³   rr   ry   )rÝ   Ústater4   r4   r5   Ú__setstate__Ý  s    zDynamicSampler.__setstate__c             C   s   | j  ¡ }|d= |d= |S )z#Get state information for pickling.r³   ry   )rß   rº   )rÝ   rà   r4   r4   r5   Ú__getstate__â  s    
zDynamicSampler.__getstate__c             C   s   t | |ƒ dS )z¦
        Save the state of the dynamic sampler in a file

        Parameters
        ----------
        fname: string
            Filename of the save file.

        N)r   )rÝ   Úfnamer4   r4   r5   Úsaveí  s    
zDynamicSampler.saveNc             C   s   t | |dS )aà  
        Restore the dynamic sampler from a file.
        It is assumed that the file was created using .save() method
        of DynamicNestedSampler or as a result of checkpointing during
        run_nested()

        Parameters
        ----------
        fname: string
            Filename of the save file.
        pool: object(optional)
            The multiprocessing pool-like object that supports map()
            calls that will be used in the restored object.

        )r³   )r   )rã   r³   r4   r4   r5   Úrestoreù  s    zDynamicSampler.restorec             C   s^   t |tƒsZt |tƒr|}n |d kr*| j}ntt d|¡ƒ‚tttt	 
|| ¡tjƒdƒƒ}|S )NzWeird update_interval value {}r   )rY   r[   rZ   rÑ   r\   Ústrr   rP   rR   r@   ÚroundÚsysÚmaxsize)rÝ   r]   ra   Zcur_update_interval_ratior4   r4   r5   Z__get_update_interval  s    

z$DynamicSampler.__get_update_intervalc             C   sZ   d| _ d| _d| _g | _d| _d| _tdd| _tdd| _d| _	t
j t
j | _| _dS )zRe-initialize the sampler.r   r   g      ð?FT)rÐ   N)r¸   rÓ   rÅ   r_   r©   rÔ   r   r¬   r×   rØ   r@   rQ   rÙ   rÚ   )rÝ   r4   r4   r5   Úreset  s    zDynamicSampler.resetc          	   C   sT  i }x dD ]}t  | j| ¡||< q
W t ¡ ª t d¡ d| jd fd|d fd| jfd|d	 fg}x"d
D ]}| d| || f¡ qlW xdD ]}| ||| f¡ qW | dt  	|d ¡f¡ | d|d f¡ W dQ R X | j
jrL| dt | j¡f¡ | dt  | jd ¡f¡ | dt  | jd ¡f¡ | dt  | jd ¡f¡ t|ƒS )z_Saved results from the dynamic nested sampling run. All saved
        bounds are also returned.)r¥   rœ   ÚidrÓ   r¸   r›   Únr;   r8   r:   r9   ÚlogzvarÚhÚbatch_nliveÚbatch_boundsr€   ÚignorerÆ   r   rÅ   r¥   r©   Zsamplesrœ   )rë   rÓ   r¸   r›   rì   Zsamples_)r;   r8   r:   r9   rï   rð   r€   rw   rí   Úinformationrî   Nr_   Z
bound_iterr¨   Zsamples_boundr§   r   )r@   rv   r¬   r>   Úcatch_warningsÚsimplefilterr¸   r©   r·   Úsqrtr¶   rµ   rº   Údeepcopyr_   r
   )rÝ   ÚdrÉ   rF   r4   r4   r5   rF   ,  s*    





zDynamicSampler.resultsc             C   s<   | j d }t|ƒdks&t t |¡¡r*dS tt |¡ƒS dS )a  
        Estimate the effective number of posterior samples using the Kish
        Effective Sample Size (ESS) where `ESS = sum(wts)^2 / sum(wts^2)`.
        Note that this is `len(wts)` when `wts` are uniform and
        `1` if there is only one non-zero element in `wts`.

        r;   r   N)r¬   rB   r@   r‡   rP   r   r…   )rÝ   r;   r4   r4   r5   r|   R  s    	
zDynamicSampler.n_effectivec             C   s   | j S )zw
        Return list of papers that should be cited given the specified
        configuration of the sampler.

        )rÎ   )rÝ   r4   r4   r5   Ú	citationsb  s    zDynamicSampler.citationsç{®Gáz„?Fc             c   sv  |t jk	r4t ¡  t d¡ t dt¡ W dQ R X |dkrBtj}|dkrPtj}|pX| j	}|  
||¡}|d| j kr~t d¡ |sª|  ¡  t|	| j| j| j|| j| j| j| jd	\\| _| _| _}}}| jrÖ|| _nd| _t| jƒ| _| j| j| j| jg}	dd„ |	D ƒ| _|  j|7  _t j| jtd	| _t j| jtd	| _ | j!}|dkrT| j"}t#| | j| j| j| j| j$||| j| j%| j&| j'| j| j(| j|d
| _)| j)j*| _*t+j,| _-xt.| j)j/||
||||dƒD ]î\}}t0|j1|j2|j3|j4|j5|j6|j7|j8|j9|j:|j;| j|j|j<|j=| j)j>d}| j? @|¡ | jA @|¡ |  j|j:7  _d| jB | j | _C|  jBd7  _Bt+jD| _-tE|j1|j2|j3|j4|j5|j6|j7|j8|j9|j:|j|j;|j<|j=| jC|jFdV  qÊW t+jG| _-xìt.| j) H¡ ƒD ]Ú\}}t0|j1|j2|j3|j4|j5|j6|j7|j8|j9|j|j:|j;| j| |j<|j=| j)j>d}| j? @|¡ | jA @|¡ d| jB | j | _C|  jBd7  _BtE|j1|j2|j3|j4|j5|j6|j7|j8|j9|j|j:|j;|j<|j=| jC|jFdV  qÔW i }tI| jAd | jAd d\|d< |d< |d< |d< x2dD ]*}||  J¡ | jA|< ||  J¡ | j?|< qìW t jt| jAd ƒtd	| jAd< | jAd  @| j¡ | jAd  @t j t jf¡ d| _Kt+jL| _-dS )a  
        Generate a series of initial samples from a nested sampling
        run using a fixed number of live points using an internal
        sampler from :mod:`~dynesty.nestedsamplers`. Instantiates a
        generator that will be called by the user.

        Parameters
        ----------
        nlive : int, optional
            The number of live points to use for the baseline nested
            sampling run. Default is either nlive0 parameter of 500

        update_interval : int or float, optional
            If an integer is passed, only update the bounding distribution
            every `update_interval`-th likelihood call. If a float is passed,
            update the bound after every `round(update_interval * nlive)`-th
            likelihood call. Larger update intervals can be more efficient
            when the likelihood function is quick to evaluate. If no value is
            provided, defaults to the value passed during initialization.

        first_update : dict, optional
            A dictionary containing parameters governing when the sampler will
            first update the bounding distribution from the unit cube
            (`'none'`) to the one specified by `sample`.

        maxiter : int, optional
            Maximum number of iterations. Iteration may stop earlier if the
            termination condition is reached. Default is `sys.maxsize`
            (no limit).

        maxcall : int, optional
            Maximum number of likelihood evaluations. Iteration may stop
            earlier if termination condition is reached. Default is
            `sys.maxsize` (no limit).

        dlogz : float, optional
            Iteration will stop when the estimated contribution of the
            remaining prior volume to the total evidence falls below
            this threshold. Explicitly, the stopping criterion is
            `ln(z + z_est) - ln(z) < dlogz`, where `z` is the current
            evidence from all saved samples and `z_est` is the estimated
            contribution from the remaining volume. The default is
            `0.01`.

        logl_max : float, optional
            Iteration will stop when the sampled ln(likelihood) exceeds the
            threshold set by `logl_max`. Default is no bound (`np.inf`).

        n_effective: int, optional
            This option is deprecated and will be removed in a future release.

        live_points: list of 3 `~numpy.ndarray` each with shape (nlive, ndim)
            and optionally list of blobs associated with these likelihood calls
            (if blob=True in the sampler)
            A set of live points used to initialize the nested sampling run.
            Contains `live_u`, the coordinates on the unit cube, `live_v`, the
            transformed variables, and `live_logl`, the associated
            loglikelihoods. By default, if these are not provided the initial
            set of live points will be drawn from the unit `npdim`-cube.
            **WARNING: It is crucial that the initial set of live points have
            been sampled from the prior. Failure to provide a set of valid
            live points will lead to incorrect results.**

        Returns
        -------
        worst : int
            Index of the live point with the worst likelihood. This is our
            new dead point sample.

        ustar : `~numpy.ndarray` with shape (npdim,)
            Position of the sample.

        vstar : `~numpy.ndarray` with shape (ndim,)
            Transformed position of the sample.

        loglstar : float
            Ln(likelihood) of the sample.

        logvol : float
            Ln(prior volume) within the sample.

        logwt : float
            Ln(weight) of the sample.

        logz : float
            Cumulative ln(evidence) up to the sample (inclusive).

        logzvar : float
            Estimated cumulative variance on `logz` (inclusive).

        h : float
            Cumulative information up to the sample (inclusive).

        nc : int
            Number of likelihood calls performed before the new
            live point was accepted.

        worst_it : int
            Iteration when the live (now dead) point was originally proposed.

        boundidx : int
            Index of the bound the dead point was originally drawn from.

        bounditer : int
            Index of the bound being used at the current iteration.

        eff : float
            The cumulative sampling efficiency (in percent).

        delta_logz : float
            The estimated remaining evidence expressed as the ln(ratio) of the
            current evidence.

        ÚoncezlThe n_effective option to DynamicSampler.sample_initial is deprecated and will be removed in future releasesNr   z!Beware: `nlive_init <= 2 * ndim`!)ra   r“   rx   r€   r”   c             S   s   g | ]}t  |¡‘qS r4   )r@   rv   )rn   r   r4   r4   r5   rp     s    z1DynamicSampler.sample_initial.<locals>.<listcomp>)r    )rž   rŸ   r€   r•   )ÚmaxiterÚsave_samplesÚmaxcallrV   ÚdlogzÚresume)rë   r›   rœ   r8   r:   r;   r9   rí   rî   r¥   r¸   rì   r€   r§   r¨   r   g      Y@r   )r¡   r¢   r£   r¤   r:   r;   r9   rí   rî   r¥   r€   r¦   r§   r¨   r©   Ú
delta_logz)rë   r›   rœ   r8   r:   r;   r9   rí   rî   r€   r¥   r¸   rì   r§   r¨   r   )r¡   r¢   r£   r¤   r:   r;   r9   rí   rî   r€   r¥   r¦   r§   r¨   r©   r   r8   r:   )r8   r:   r;   r9   rí   rî   )r;   r9   rí   rî   rë   rÓ   rï   rð   T)Mr@   rQ   r>   ró   Úfilterwarningsr?   ÚDeprecationWarningrè   ré   rÕ   Ú$_DynamicSampler__get_update_intervalrž   rê   rš   r‘   r’   ry   r“   rx   r€   r”   r–   r—   r˜   r™   rB   rÛ   r¯   rÅ   rƒ   r[   r½   r¾   r®   r±   r­   r°   r²   r³   r´   rŸ   r¶   r_   r   r,   rÖ   r‹   r^   Údictr¡   r¢   r£   r¤   r:   r;   r9   rí   rî   r¥   r¦   r§   r¨   r   r×   r·   r¬   r¸   r©   r-   r   r   r1   Úadd_live_pointsr   ÚtolistrÔ   r.   )rÝ   ra   r]   r±   rû   rý   rV   rþ   r|   r   rü   rÿ   Zblobsr•   rÈ   r®   r¸   rF   Úadd_infoÚnew_valsZcurkr4   r4   r5   Úsample_initiall  s0    









&

zDynamicSampler.sample_initialTc	             c   sT  |pt j}|pt j}|p| j}|d| j kr6t d¡ |sº|  ||¡}t| ||||d\}	}
}}}|	| _| jj	| _	|| | _
| _tdd| _|  j|
7  _| j|	_| j}||
 }|| }n"| j}	|	j}| j
| j }}|}|}x$tt|	jƒƒD ]}|	j d¡V  qìW d}xìt|	j||||d||dƒD ]Ì\}}t|j|j|j|j|j|j| |j||j|j |	j!d	}| j "|¡ |  j|j7  _d
| j | j | _#|  jd7  _|d8 }||j8 }d}t$j%| _&t'|j|j|j|j|j|j| |j|j | j#d	V  q$W |r0|j|k r0t( )|¡r0|dkr0|dkr0t d¡ t$j*| _&|s’t|	j+d ƒdkr’t(j, g|	j+d< |g|	j+d< dg|	j+d< dg|	j+d< dg|	j+d< x²t|	 -¡ ƒD ]¢\}}t|j|j|j|j|j|j| || |j|j|j |	j!d}| j "|¡ d
| j | j | _#|  jd7  _t'|j|j|j|j|j|j| |j|j | j#d	V  q W | `d| _dS )a  
        Generate an additional series of nested samples that will be combined
        with the previous set of dead points. Works by hacking the internal
        `sampler` object.
        Instantiates a generator that will be called by the user.

        Parameters
        ----------
        nlive_new : int
            Number of new live points to be added. Default is `500`.

        update_interval : int or float, optional
            If an integer is passed, only update the bounding distribution
            every `update_interval`-th likelihood call. If a float is passed,
            update the bound after every `round(update_interval * nlive)`-th
            likelihood call. Larger update intervals can be more efficient
            when the likelihood function is quick to evaluate. If no value is
            provided, defaults to the value passed during initialization.

        logl_bounds : tuple of size (2,), optional
            The ln(likelihood) bounds used to bracket the run. If `None`,
            the default bounds span the entire range covered by the
            original run.

        maxiter : int, optional
            Maximum number of iterations. Iteration may stop earlier if the
            termination condition is reached. Default is `sys.maxsize`
            (no limit).

        maxcall : int, optional
            Maximum number of likelihood evaluations. Iteration may stop
            earlier if termination condition is reached. Default is
            `sys.maxsize` (no limit).

        save_bounds : bool, optional
            Whether or not to save past distributions used to bound
            the live points internally. Default is `True`.

        dlogz : float, optional
            The stopping point in terms of remaining delta(logz)

        Returns
        -------
        worst : int
            Index of the live point with the worst likelihood. This is our
            new dead point sample. **Negative values indicate the index
            of a new live point generated when initializing a new batch.**

        ustar : `~numpy.ndarray` with shape (npdim,)
            Position of the sample.

        vstar : `~numpy.ndarray` with shape (ndim,)
            Transformed position of the sample.

        loglstar : float
            Ln(likelihood) of the sample.

        nc : int
            Number of likelihood calls performed before the new
            live point was accepted.

        worst_it : int
            Iteration when the live (now dead) point was originally proposed.

        boundidx : int
            Index of the bound the dead point was originally drawn from.

        bounditer : int
            Index of the bound being used at the current iteration.

        eff : float
            The cumulative sampling efficiency (in percent).

        r   z"Beware: `nlive_batch <= 2 * ndim`!)r]   rÄ   rµ   T)rÐ   r   F)rþ   rV   rû   rý   rü   rµ   rÿ   )rë   r›   rœ   r8   r¥   r¸   r€   rì   r§   r¨   r   g      Y@r   )	r¡   r¢   r£   r¤   r¥   r¦   r§   r¨   r©   zˆWarning. The maximum likelihood not reached in the batch. You may not have enough livepoints and/or have highly multi-modal distributionr8   r:   g}Ã”%­I²Ôr9   rí   rî   )rë   r›   rœ   r8   r¥   r¸   rì   r€   r§   r¨   r   N).rè   ré   rÕ   rž   r>   r?   r  rÊ   rÇ   r_   rÙ   rÚ   r   rØ   rÅ   r¸   Úit0rs   rB   rÂ   Úpopr‹   r^   r  r¡   r¢   r£   r¤   r¥   r¦   r€   r§   r¨   r   r·   r©   r   r/   rÖ   r   r@   r†   r2   r¬   rQ   r  )rÝ   rþ   rÃ   r]   rÄ   rû   rý   rµ   rÿ   rÇ   rÅ   rÆ   rU   rV   r
  Zmaxcall_leftZmaxiter_leftr   Ziterated_batchr¸   rF   ÚDr4   r4   r5   Úsample_batch¢  sÎ    U









zDynamicSampler.sample_batchc       $   	   C   s¢  t | jd ƒdkrtdƒ‚i }i }x4dD ],}t | j| ¡||< t | j| ¡||< q(W t | jd ¡|d< t |d ƒ}|d t|d ƒ d |d< t |d ƒ}| j| j }}| jd }| jd	 }	| `t	d
d| _d\}
}|d |
 |d |  }}|d |
 |d |  }}|| }x<t
|ƒD ].}|| jkr>|| }n|}i }||krv|d |
 |d< |}t|
ƒ}|
d7 }
n"| jd |d< |}t|ƒ}|d7 }xdD ]}|| | ||< qžW | j |¡ | jd  |¡ y|d |
 }|d |
 }W n  tk
r   tj}d}Y nX y|d | }|d | }W n  tk
rN   tj}d}Y nX q"W d}d}d}| jj}t | jd ¡}t | jd ¡}xòtt||ƒƒD ]à\}\}}|s|t |ƒd kr|| ||d  kr||d… |k}| ¡ }|dkr|}|t d|d  ¡ }d
}|s2|t |d | ¡8 }n|t t || ¡ ¡ }| jd  |¡ |rš|d8 }|dkršd}qšW | jd d t|d d |d d ƒks¬t‚| jd d t|d d |d d ƒksÚt‚t| jd | jd d\} }!}"}#| jd  |  ¡ ¡ | jd  |! ¡ ¡ | jd  |" ¡ ¡ | jd  |# ¡ ¡ d| _tj tj | _| _|  jd7  _|	t|d ƒg | jd	< |||fg | jd< dS )zs Merge the most recent run into the previous (combined) run by
        "stepping through" both runs simultaneously.rë   r   z#No new samples are currently saved.)rë   r›   rœ   r8   r¥   r§   r¸   r¨   rì   r   r€   r:   rÓ   rì   r   rð   rï   T)rÐ   )r   r   r8   )
rë   r›   rœ   r8   r¥   r§   r¸   r¨   r   r€   FNg      ð?r:   r6   )r8   r:   r;   r9   rí   rî   )rB   rØ   rN   r@   rv   r¬   rP   rÙ   rÚ   r   rs   r[   rÓ   r·   Ú
IndexErrorrQ   r¶   r•   r‹   rt   rE   rC   rÁ   Úlog1prD   rR   r‰   r   rŠ   r  )$rÝ   Zsaved_dZnew_drÉ   ZnsavedZnnewZllminZllmaxZold_batch_boundsZold_batch_nliveZ	idx_savedZidx_newZlogl_sZlogl_nZnlive_sZnlive_nZntotr   ra   r  Z
add_sourceZadd_idxZplateau_modeZplateau_counterZplateau_logdvolr:   Z
logl_arrayZnlive_arrayro   Zcur_loglZplateau_maskZnplateauZ	new_logwtZnew_logzZnew_logzvarZnew_hr4   r4   r5   Úcombine_runs†  s°    










zDynamicSampler.combine_runsé<   c       )      C   sx  |t jk	r4t ¡  t d¡ t dt¡ W dQ R X |dkrBtj}|dkrPtj}|
dkr^tj}
|dkrltj}|dkrztj}|dkrˆtj}|dkr–tj}|dkr¢t	}|	dkr®i }	|dkrÀd}t
}nd}|dkrÐi }|rö|dkrît| j| j dƒ}||d< |pþ| j}|p
| j}| j}| jd }t j t jf}t||ƒ}t||ƒ}|rb| jtjkrbt d	t¡ dS t||ƒ\}}t|ƒ| _zØ| jsxŠ| j||||||||dd
	D ]j}|r²d}||j7 }|d7 }|dk	rò| jtjkrò| j ¡ rò|  |¡ |r¤||||d||d q¤W x t| j|ƒD ]} | j }!t|| |ƒ}"t|| |
ƒ}#|"dkrš|#dkrš|rš| j!rt| j"}$nt#}$||!|| j$|$dd\}%}&|&d }'n
d}%t j%}'|"dkrö|#dkrö|%sö| j&|||	|#|"||||'||d}(|rèd}|(\}}}}n:|d t jkr.|r*||||| |'|d |d d P nP q"W tj| _|dk	rR|  |¡ W d|dk	rh| '¡  | j( )¡  X dS )a`  
        **The main dynamic nested sampling loop.** After an initial "baseline"
        run using a constant number of live points, dynamically allocates
        additional (nested) samples to optimize a specified weight function
        until a specified stopping criterion is reached.

        Parameters
        ----------
        nlive_init : int, optional
            The number of live points used during the initial ("baseline")
            nested sampling run. Default is the number provided at
            initialization

        maxiter_init : int, optional
            Maximum number of iterations for the initial baseline nested
            sampling run. Iteration may stop earlier if the
            termination condition is reached. Default is `sys.maxsize`
            (no limit).

        maxcall_init : int, optional
            Maximum number of likelihood evaluations for the initial
            baseline nested sampling run. Iteration may stop earlier
            if the termination condition is reached. Default is `sys.maxsize`
            (no limit).

        dlogz_init : float, optional
            The baseline run will stop when the estimated contribution of the
            remaining prior volume to the total evidence falls below
            this threshold. Explicitly, the stopping criterion is
            `ln(z + z_est) - ln(z) < dlogz`, where `z` is the current
            evidence from all saved samples and `z_est` is the estimated
            contribution from the remaining volume. The default is
            `0.01`.

        logl_max_init : float, optional
            The baseline run will stop when the sampled ln(likelihood) exceeds
            this threshold. Default is no bound (`np.inf`).

        n_effective_init: int, optional
            Minimum number of effective posterior samples needed during the
            baseline run. If the estimated "effective sample size" (ESS)
            exceeds this number, sampling will terminate.
            Default is no ESS (`np.inf`).
            This option is deprecated and will be removed in a future release.

        nlive_batch : int, optional
            The number of live points used when adding additional samples
            from a nested sampling run within each batch. Default is the
            number provided at init

        wt_function : func, optional
            A cost function that takes a :class:`Results` instance
            and returns a log-likelihood range over which a new batch of
            samples should be generated. The default function simply
            computes a weighted average of the posterior and evidence
            information content as::

                weight = pfrac * pweight + (1. - pfrac) * zweight

        wt_kwargs : dict, optional
            Extra arguments to be passed to the weight function.

        maxiter_batch : int, optional
            Maximum number of iterations for the nested
            sampling run within each batch. Iteration may stop earlier
            if the termination condition is reached. Default is `sys.maxsize`
            (no limit).

        maxcall_batch : int, optional
            Maximum number of likelihood evaluations for the nested
            sampling run within each batch. Iteration may stop earlier
            if the termination condition is reached. Default is `sys.maxsize`
            (no limit).

        maxiter : int, optional
            Maximum number of iterations allowed. Default is `sys.maxsize`
            (no limit).

        maxcall : int, optional
            Maximum number of likelihood evaluations allowed.
            Default is `sys.maxsize` (no limit).

        maxbatch : int, optional
            Maximum number of batches allowed. Default is `sys.maxsize`
            (no limit).

        n_effective: int, optional
            Minimum number of effective posterior samples needed during the
            entire run. If the estimated "effective sample size" (ESS)
            exceeds this number, sampling will terminate.
            Default is max(10000, ndim^2)

        stop_function : func, optional
            A function that takes a :class:`Results` instance and
            returns a boolean indicating that we should terminate the run
            because we've collected enough samples.

        stop_kwargs : float, optional
            Extra arguments to be passed to the stopping function.

        use_stop : bool, optional
            Whether to evaluate our stopping function after each batch.
            Disabling this can improve performance if other stopping criteria
            such as :data:`maxcall` are already specified. Default is `True`.

        save_bounds : bool, optional
            Whether or not to save distributions used to bound
            the live points internally during dynamic live point allocation.
            Default is `True`.

        print_progress : bool, optional
            Whether to output a simple summary of the current run that
            updates each iteration. Default is `True`.

        print_func : function, optional
            A function that prints out the current state of the sampler.
            If not provided, the default :meth:`results.print_fn` is used.

        live_points: list of 3 `~numpy.ndarray` each with shape (nlive, ndim)
            and optionally list of blobs associated with these likelihood calls
            (if blob=True in the sampler)
            A set of live points used to initialize the nested sampling run.
            Contains `live_u`, the coordinates on the unit cube, `live_v`, the
            transformed variables, and `live_logl`, the associated
            loglikelihoods. By default, if these are not provided the initial
            set of live points will be drawn from the unit `npdim`-cube.
            **WARNING: It is crucial that the initial set of live points have
            been sampled from the prior. Failure to provide a set of valid
            live points will lead to incorrect results.**

        resume: bool, optional
            If resume is set to true, we will try to resume a previously
            interrupted run
        checkpoint_file: string, optional
            if not None The state of the sampler will be saved into this
            file every checkpoint_every seconds
        checkpoint_every: float, optional
            The number of seconds between checkpoints that will save
            the internal state of the sampler
        rú   zmThe n_effective_init option to DynamicSampler.run_nested is deprecated and will be removed in future releasesNTFi'  rg   r   ziYou tried to resume the run that has ended successfully.
This is not supported. No sampling was performed)	ra   rþ   rý   rû   rV   r   r|   rÿ   rü   r   )Únbatchrþ   rV   )rx   ry   rz   r   )ra   Úwt_functionÚ	wt_kwargsrû   rý   rµ   Úprint_progressÚ
print_funcÚstop_valrÿ   Úcheckpoint_file)r  r  rU   rV   )*r@   rQ   r>   ró   r  r?   r  rè   ré   r   r   rP   r“   rÕ   rÅ   r¸   rR   rÖ   r   r3   r   r   r   rÜ   rÔ   r	  r¥   r1   Úis_timerä   rs   rÓ   rF   rÒ   ry   rr   rx   ÚnanÚ	add_batchÚcloser’   Úhistory_save))rÝ   rÛ   Zmaxiter_initZmaxcall_initZ
dlogz_initZlogl_max_initZn_effective_initZnlive_batchr  r  Zmaxiter_batchZmaxcall_batchrû   rý   Zmaxbatchr|   rÏ   Zstop_kwargsZuse_stoprµ   r  r  r   rÿ   r  Úcheckpoint_everyZdefault_stop_functionrÅ   rÆ   rÄ   ÚpbarrF   rì   rq   ZmcallZmiterry   r}   Z	stop_valsr  Zpassbackr4   r4   r5   Ú
run_nested  sö     )













zDynamicSampler.run_nestedéô  rT   c             C   sR  |pt j}|pt j}|pt}|p"i }|p,tj}| j}|dkrL|dk	rLtdƒ‚|dkrd|dkrdtdƒ‚|dkst|dkr~|||ƒ}|dkr˜tj tj }}n|\}}|d d |d	 d d
  }}| j| j	d | j
  }}}|dk	rø|dk	ròt|ƒ}n| j}|dkrF|dkrFt||
ƒ\}}zðd}xæ| j||||||	|dD ]Ê}|rHd}|jdkrf||j7 }|d7 }t|j|j|j|jdtjtj||tj|j|j|j|j|jtjd}|
rÈ|||||d |||d |dk	r:| jtjkr:| jtjkr:| ¡ r:|  |¡ q:W W d|dk	r| ¡  | j  !¡  X |  "¡  tj| _||||fS tdƒ‚dS )ae  
        Allocate an additional batch of (nested) samples based on
        the combined set of previous samples using the specified
        weight function.

        Parameters
        ----------
        nlive : int, optional
            The number of live points used when adding additional samples
            in the batch. Default is `500`.

        mode: string, optional
            How to allocate a new batch.
            The possible values are 'auto', 'weight', 'full', 'manual'
            'weight' means to use the weight_function to decide the optimal
            logl range.
            'full' means sample the whole posterior again
            'auto' means choose automatically, which currently means using
            'weight'
            'manual' means that logl_bounds need to be explicitely specified

        wt_function : func, optional
            A cost function that takes a `Results` instance
            and returns a log-likelihood range over which a new batch of
            samples should be generated. The default function simply
            computes a weighted average of the posterior and evidence
            information content as::

                weight = pfrac * pweight + (1. - pfrac) * zweight

        wt_kwargs : dict, optional
            Extra arguments to be passed to the weight function.

        maxiter : int, optional
            Maximum number of iterations allowed. Default is `sys.maxsize`
            (no limit).

        maxcall : int, optional
            Maximum number of likelihood evaluations allowed.
            Default is `sys.maxsize` (no limit).

        logl_bounds : tuple of size (2,), optional
            The ln(likelihood) bounds used to bracket the run. If `None`,
            the provided `wt_function` will be used to determine the bounds
            (this is the default behavior).

        save_bounds : bool, optional
            Whether or not to save distributions used to bound
            the live points internally during dynamic live point allocations.
            Default is `True`.

        print_progress : bool, optional
            Whether to output a simple summary of the current run that
            updates each iteration. Default is `True`.

        print_func : function, optional
            A function that prints out the current state of the sampler.
            If not provided, the default :meth:`results.print_fn` is used.

        stop_val : float, optional
            The value of the stopping criteria to be passed to
            :meth:`print_func`. Used internally within :meth:`run_nested` to
            keep track of progress.
        resume: bool, optional
            If resume is set to true, we will try to resume a previously
            interrupted run
        checkpoint_file: string, optional
            if not None The state of the sampler will be saved into this
            file every checkpoint_every seconds
        checkpoint_every: float, optional
            The number of seconds between checkpoints that will save
            the internal state of the sampler. If this is None, we
            we will use the timer created in run_nested()
        ZmanualNz6specified logl_bounds are only allowed for manual modez0logl_bounds need to be specified for manual modeÚautorT   r9   r6   rw   r   r   r   )rÃ   rþ   rÄ   rû   rý   rµ   rÿ   F)r¡   r¢   r£   r¤   r€   r:   r;   r9   rí   rî   r¥   r¦   r§   r¨   r©   r   )r  r  rU   rV   z=add_batch called with no leftover function callsor iterations)#rè   ré   r   r@   r  rF   r\   rQ   rÅ   r¸   rÓ   r   rÜ   r   r  r¡   r¥   r   r¢   r£   r¤   r¦   r§   r¨   r©   rÖ   r   r2   r0   r  rä   r  r’   r  r  )rÝ   ra   rþ   Úmoder  r  rû   rý   rÄ   rµ   r  r  r  rÿ   r  r  rq   rU   rV   r9   rí   rÅ   rÆ   rì   Útimerr  rF   Zcur_resultsr4   r4   r5   r  V  sš    \










zDynamicSampler.add_batch)N)rù   NNNNNTF)r!  rù   rT   NNNNNTTNNFNN)r'   r(   r)   r*   rÞ   rá   râ   rä   Ústaticmethodrå   r  rê   ÚpropertyrF   r|   rø   r@   rQ   r	  r  r  r   r  r4   r4   r4   r5   r   P  sœ   <O&  .       
 ]   ,              )NF)NNNF)NNNFN)NN)+r*   rè   r>   rÁ   rº   Úenumr   Únumpyr@   Zscipy.specialr   Znestedsamplersr   r   r   r   r	   rF   r
   Úutilsr   r   r   r   r   r   r   r   r   r   r   r   r   Ú__all__r­   r   rI   r   rd   r   rš   rÊ   r   r4   r4   r4   r5   Ú<module>   sJ   <$
Y!   
    
 ; 
  8