B
    zd.                 @   sX   d Z ddlmZmZ ddlZddlmZmZmZ ddl	m
Z
 G dd deZdd	 ZdS )
z&Base class and functions for samplers.    )ABCabstractmethodN)create_seed
dump_state
load_state)Normalc               @   s  e Zd ZdZdZdZdZdZdZdZ	dZ
edd Zejdd Zedd Zd>dd	Zed
d Zejdd Zedd Zejdd Zedd Zejdd Zedd Zejdd Zedd Zedd Zedd Zed?ddZedd Zejd d Zd!d" Zd#d$ Zed%d& Zed'd( Zed)d* Zed+d, Zed-d. Z ed/d0 Z!ed1d2 Z"ed3d4 Z#ed5d6 Z$d7d8 Z%d@d:d;Z&dAd<d=Z'dS )BBaseSamplerzBase class for samplers.
    Nc             C   s   | j S )z"The sampled parameters as a tuple.)_parameters)self r   `/work/yifan.wang/ringdown/master-ringdown-env/lib/python3.7/site-packages/epsie/samplers/base.py
parameters$   s    zBaseSampler.parametersc             C   s    t |tjr|g}t|| _d S )N)
isinstancesixstring_typestupler	   )r
   r   r   r   r   r   )   s    c             C   s   | j S )z6List of the proposals used for the sampled parameters.)
_proposals)r
   r   r   r   	proposals/   s    zBaseSampler.proposalsc             C   s|   |dkrg }n|  }|dkr"t}|dkr.i }|rHtjdd |D  }nt }t| j| }|rr|||f| || _dS )a  Sets the proposals for all parameters.

        If no proposals are given for one or more parameters, the default
        proposal will be used for them.

        Parameters
        ----------
        proposals : list, optional
            A list of :py:class:`proposals.BaseProposal` instances. If none
            provided, will use the ``default_proposal`` for all parameters.
        default_proposal : proposals.BaseProposal type class, optional
            The default proposal class to use for parameters that are not
            specified in ``proposals``. Default (None) is to use
            :py:class:`proposals.Normal`.
        default_proposal_args : dict, optional
            Dictionary of keyword arguments to pass to the default proposal
            when initializing.
        Nc             S   s   g | ]}t |jqS r   )setr   ).0pr   r   r   
<listcomp>R   s    z-BaseSampler.set_proposals.<locals>.<listcomp>)copyr   r   unionr   appendr   )r
   r   Zdefault_proposalZdefault_proposal_argsZgiven_paramsZmissing_paramsr   r   r   set_proposals4   s    
zBaseSampler.set_proposalsc             C   s   | j S )zThe model used.)_model)r
   r   r   r   model[   s    zBaseSampler.modelc             C   s
   || _ d S )N)r   )r
   r   r   r   r   r   `   s    c             C   s   | j S )zList of the chains used.)_chains)r
   r   r   r   chainsd   s    zBaseSampler.chainsc             C   s
   || _ d S )N)r   )r
   r   r   r   r   r   i   s    c             C   s   | j S )z+The seed used for the random bit generator.)_seed)r
   r   r   r   seedm   s    zBaseSampler.seedc             C   s   |dkrt |}|| _dS )z:Sets the seed. If the given seed is None, will create one.N)r   r    )r
   r!   r   r   r   r!   r   s    c             C   s   | j S )z(The pool being used for parallelization.)_pool)r
   r   r   r   pooly   s    zBaseSampler.poolc             C   s$   || _ |d krt}n|j}|| _d S )N)r"   map_map)r
   r#   Zmap_funcr   r   r   r#   ~   s
    c             C   s
   t | jS )z The number of chains being used.)lenr   )r
   r   r   r   nchains   s    zBaseSampler.nchainsc             C   s   | j d jS )z?The number of iterations the chains have been run for.
        r   )r   	iteration)r
   r   r   r   niterations   s    zBaseSampler.niterationsc             C   s   dS )a  Concatenates dictionary attributes over all of the chains.

        This is a convenience function used by properties such as
        ``current_positions`` to gather all of the dictionary attributes from
        the chains.

        Parameters
        ----------
        attr : str
            The name of the attribute to get from the chains. The attribute
            is assumed to return a dictionary.

        Returns
        -------
        dict :
            Dictionary mapping parameters to arrays.
        Nr   )r
   attrr   r   r   _concatenate_dicts   s    zBaseSampler._concatenate_dictsc             C   s   dS )a  Concatenates the given attribute over all of the chains.

        This is a convenience function used by properties such as ``positions``
        to gather all of the array attributes from the chains.

        Parameters
        ----------
        attr : str
            The name of the attribute to get from the chains. The attribute
            is assumed to return a (structred) array.
        item : str or array index, optional
            Get a particular item from the (structred) array from each chain
            before concatenating.

        Returns
        -------
        array :
            The returned array sould have ``nchains x niterations`` as the last
            two dimensions.
        Nr   )r
   r*   itemr   r   r   _concatenate_arrays   s    zBaseSampler._concatenate_arraysc             C   s
   |  dS )a$  The start position of the chains.

        Will raise a ``ValueError`` is ``set_start`` hasn't been run.

        Returns
        -------
        dict :
            Dictionary mapping parameters to arrays with shape ``nchains``
            giving the starting position of each chain.
        start_position)r+   )r
   r   r   r   r.      s    zBaseSampler.start_positionc                s2   x,t | jD ]\ } fddD |_qW dS )zSets the starting position of all of the chains.

        Parameters
        ----------
        positions : dict
            Dictionary mapping parameter names to arrays of values. The arrays
            must have shape ``[ntemps x] nchains``.
        c                s   i | ]}| d  f |qS ).r   )r   r   )ii	positionsr   r   
<dictcomp>   s   z.BaseSampler.start_position.<locals>.<dictcomp>N)	enumerater   r.   )r
   r0   chainr   )r/   r0   r   r.      s    
c             C   s`   x0| j D ]&}| jt||jt|  d7  _qW t|gt| j  | j }t| t|| _ dS )zEvolves all of the chains by niterations.

        Parameters
        ----------
        niterations : int
            The number of iterations to evolve the chains for.
        r   N)r   Z
scratchlenmaxr&   ziplistr%   _evolve_chain)r
   r)   cargsr   r   r   run   s    	&zBaseSampler.runc             C   s   x| j D ]}|  qW dS )zClears all of the chains.N)r   clear)r
   r3   r   r   r   r;      s    zBaseSampler.clearc             C   s   | j d jS )z.The iteration that the last clear occurred at.r   )r   	lastclear)r
   r   r   r   r<      s    zBaseSampler.lastclearc             C   s
   |  dS )z0The history of positions from all of the chains.r0   )r-   )r
   r   r   r   r0      s    zBaseSampler.positionsc             C   s
   |  dS )zThe current position of the chains.

        This will default to the start position if the chains haven't been
        run yet.
        current_position)r+   )r
   r   r   r   current_positions   s    zBaseSampler.current_positionsc             C   s
   |  dS )z,The history of stats from all of the chains.stats)r-   )r
   r   r   r   r?     s    zBaseSampler.statsc             C   s
   |  dS )zThe current stats of the chains.

        This will default to the stats of the start positions if the chains
        haven't been run yet.
        current_stats)r+   )r
   r   r   r   r@     s    zBaseSampler.current_statsc             C   s    | j d jr| d}nd}|S )z7The history of all of the blobs from all of the chains.r   blobsN)r   hasblobsr-   )r
   rA   r   r   r   rA     s    zBaseSampler.blobsc             C   s    | j d jr| d}nd}|S )zThe current blob data.

        This will default to the blob data of the start positions if the
        chains haven't been run yet.
        r   Zcurrent_blobN)r   rB   r+   )r
   rA   r   r   r   current_blobs  s    zBaseSampler.current_blobsc             C   s
   |  dS )z;The history of all acceptance stats from all of the chains.
acceptance)r-   )r
   r   r   r   rD   ,  s    zBaseSampler.acceptancec             C   s   dd | j D S )ziThe state of all of the chains.

        Returns a dictionary mapping chain ids to their states.
        c             S   s   i | ]}|j |jqS r   )stateZchain_id)r   r3   r   r   r   r1   7  s    z%BaseSampler.state.<locals>.<dictcomp>)r   )r
   r   r   r   rE   1  s    zBaseSampler.statec             C   s*   x$t | jD ]\}}|||  qW dS )zSets the state of the all of the chains.

        Parameters
        ----------
        state : dict
            Dictionary mapping chain id to the state to set the chain to. See
            :py:func:`chain.Chain.set_state` for details.
        N)r2   r   	set_state)r
   rE   r/   r3   r   r   r   rF   9  s    	zBaseSampler.set_statesampler_statec             C   s   t | j|||d dS )a  Save the sampler's state to an HDF file.

        Parameters
        ----------
        fp : :py:class:h5py.File
            Open file handler to an hdf5 file. The file handler must have
            write permission.
        path : str, optional
            What group to write the state to in the hdf file. Default is the
            top-level.
        dsetname : str, optional
            The name of dataset to store the state to. Default is
            "sampler_state".
        )pathdsetnameN)r   rE   )r
   fprH   rI   r   r   r   
checkpointE  s    zBaseSampler.checkpointc             C   s   |  t||d dS )a%  Loads a state from an HDF file.

        Parameters
        ----------
        fp : :py:class:h5py.File
            Open file handler to an hdf5 file.
        path : str, optional
            What group to store the file to in the hdf file. Default is the
            top-level ('/').
        )rH   N)rF   r   )r
   rJ   rH   r   r   r   set_state_from_checkpointV  s    z%BaseSampler.set_state_from_checkpoint)NNN)N)NrG   )N)(__name__
__module____qualname____doc__r	   r   r   r   r    r"   r%   propertyr   setterr   r   r   r   r!   r#   r'   r)   r   r+   r-   r.   r:   r;   r<   r0   r>   r?   r@   rA   rC   rD   rE   rF   rK   rL   r   r   r   r   r      sT    
&
			
r   c             C   s&   | \}}xt |D ]}|  qW |S )a  Evolves a chain for some number of iterations.

    This is used by ``Sampler.run`` to evolve a collection of chains in a
    parallel environment. This is not a staticmethod of ``Sampler`` because
    such functions need to be picklable when using python's multiprocessing
    pool.

    Parameters
    ----------
    niterations_chain : tuple of int, chain
        The number of iterations to run on the given chain.
    )rangestep)Zniterations_chainr)   r3   _r   r   r   r7   d  s    r7   )rP   abcr   r   r   Zepsier   r   r   Zepsie.proposalsr   r   r7   r   r   r   r   <module>   s     M