B
    1agi              B   @   s  d dl Z d dlZd dlmZ d dlmZ d dlmZ d dl	Z
d dlZd dlT d dlmZ d dlZe  ed d dlmZ W dQ R X dZed	 Zd
Zedd d Zee Zee ZeefZeefZee d ZeefZdeiZ ed Z!de! Z"e!e d< e!e d< e"e d< e"e d< de d< ddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@(Z#dAdB Z$dCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~ddddddAZ%e&e%' Z(dd e(D Z)e*e+e)e(Z,dd Z-dd Z.dd e%' D Z/d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?gZ0ddddddddd'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d&ddddd!dddddddddg0Z1e j23e j24e5Z6e7e j28e6ddZ9e
:e9Z;W dQ R X e7e j28e6ddZ9e
:e9Z<W dQ R X e7e j28e6ddjZ9e
:e9Z=x.e<> D ]"\Z?Z@e?e=kr|e@Ae=e?  q|W x(e=> D ]\Z?Z@e?e<kre@e<e?< qW W dQ R X e7e j28e6ddjZ9e
:e9ZBx.e<> D ]"\Z?Z@e?eBkr e@AeBe?  q W x(eB> D ]\Z?Z@e?e<kr0e@e<e?< q0W W dQ R X dd e<d > D ZCdddddddddddddddZDx>eDE > D ].\Z?Z@de@krde@kre@d eDe?d < qW dddddddddddddddddddddМZFG dd҄ deGZHG ddԄ deGZIddք ZJddefddلZKddd݄ZLddd߄ZMdddZNdddZOdddZPdddZQdddZRdddZSd dlmZT G dd deTZUdddZVdS )    N)gaussian_kde)interp1d)cumtrapz)*ignore)bounded_1d_kde   g     n@gRhV?   g      ?g       @gR@zfigure.figsize	   g?zaxes.labelsizezlegend.fontsizezxtick.labelsizezytick.labelsizetrueztext.usetexZ	GW200316IZ	GW200311LZ	GW200225BZ	GW200224HZ	GW200219DZ	GW200208FZ	GW200202FZ	GW200129DZ	GW200115A	GW191222AZ	GW191216GZ	GW191215GZ	GW191204GZ	GW191129F	GW191109A	GW190408A	GW190412A	GW190421A	GW190425A	GW190503A	GW190512A	GW190513A	GW190517A	GW190519A	GW190521A	GW190521B	GW190602A	GW190630A	GW190706A	GW190707A	GW190708A	GW190720A	GW190727A	GW190728A	GW190814A	GW190828A	GW190828B	GW190910A	GW190915A	GW190924A)(	GW200316A	GW200311B	GW200225A	GW200224B	GW200219A	GW200208A	GW200202A	GW200129AGW200115r   	GW191216A	GW191215A	GW191204B	GW191129Ar   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   c             C   s   t |  S )N)o3_name_dict)Zcat_name r5   C/work/yifan.wang/ringdown/LVKringdownfile/gwtc3/rin/pyring/utils.pycat_to_snamep   s    r7   Z	S200316bjZ	S200311bgZS200225qZ	S200224caZ	S200219acZS200208qZ	S200202acZS200129mZS200115jZS191222nZ	S191216apZS191215wZS191204rZS191129uZS191109dZ	S190408anZS190412mZS190413iZ	S190413acZ	S190421arZ	S190424aoZS190425zZS190426cZ	S190503bfZ	S190512atZ	S190513bmZS190514nZS190517hZ	S190519bjZS190521gZS190521rZS190527wZ	S190602aqZS190620eZ	S190630agZ	S190701ahZ	S190706aiZS190707qZ	S190708apZ	S190719anZS190720aZS190727hZS190728qZ	S190731aaZS190803eZ	S190814bvZS190828jZS190828lZS190909wZS190910sZ	S190915akZS190924hZS190929dZS190930sZS150914ZS151012ZS151226ZS170104ZS170608ZS170729ZS170809ZS170814ZS170817ZS170818ZS170823)Ar'   r(   r)   r*   r+   r,   r-   r.   r/   r   r0   r1   r2   r3   r   r   r   Z	GW190413AZ	GW190413Br   Z	GW190424Ar   Z	GW190426Ar   r   r   Z	GW190514Ar   r   r   r   Z	GW190527Ar   Z	GW190620Ar   Z	GW190701Ar   r   r   Z	GW190719Ar   r   r    Z	GW190731AZ	GW190803Ar!   r"   r#   Z	GW190909Ar$   r%   r&   Z	GW190929AZ	GW190930A	GW150914AZ	GW151012A	GW151226A	GW170104A	GW170608AZ	GW170729A	GW170809A	GW170814AZ	GW170817A	GW170818A	GW170823Ac             C   s   g | ]}t | qS r5   ) catalog_id_to_superevent_id_dict).0vr5   r5   r6   
<listcomp>   s    rC   c             C   s   t |  S )z0 Get GraceDB superevent ID from catalog ID.
    )r@   )Z
catalog_idr5   r5   r6   
cid_to_sid   s    rD   c             C   s   t |  S )z0 Get catalog ID from GraceDB superevent ID.
    ) superevent_id_to_catalog_id_dict)Zsuperevent_idr5   r5   r6   
sid_to_cid   s    rF   c             C   s    g | ]}d |ksd|kr|qS )ZGW15ZGW17r5   )rA   kr5   r5   r6   rC      s    r8   r9   r:   r;   r<   r=   r>   r?   r3   r2   r1   r0   r/   r.   r-   r,   r+   r*   r)   r(   r'   z
colors.pklrbzparameters_o3a.pklzparameters_o1o2.pklzparameters_o3b.pklc             C   s   i | ]\}}||qS r5   r5   )rA   rG   rB   r5   r5   r6   
<dictcomp>  s    rI   NAME
chirp_mass
total_mass
mass_ratiomass_1mass_2
final_mass
final_spinspin_1spin_2chi_effchi_predshiftluminosity_distancenetworkmatchedfiltersnr)MCMQM1M2ZMFZCHIFZCHI1ZCHI2ZCHIEFFZCHIPZDZSNRmassratio_sourceZ_SRCz	M/M_\odotz\mathcal{{M}}/M_\odotz(1+z)M/M_\odotz(1+z)\mathcal{{M}}/M_\odotzm_1/M_\odotzm_2/M_\odotz(1+z)m_1/M_\odotz(1+z)m_2/M_\odotz\chi_1z\chi_2z\chi_{{\rm eff}}z\chi_pzD_L/{\rm Gpc}zqzM_{\rm f}/M_\odotz(1+z)M_{\rm f}/M_\odotzM_{\rm f}^{\rm det}/M_\odotz\chi_{\rm f}z	{\rm SNR})Ztotal_mass_sourceZchirp_mass_sourcerL   rK   Zmass_1_sourceZmass_2_sourcerN   rO   rR   rS   rT   rU   rW   rV   rM   final_mass_sourcerP   re   rQ   rX   c               @   s   e Zd Zdd ZdS )	Parameterc             C   sb   |  | _t| j | _| jdd| _d| jkrRd| jkrRd| jkrR|  jd7  _t| j | _d S )N_ r`   ra   sourcedet)uppername_pesummary_namesZpe_namereplace	macro_keycolumn_name2tex_namelatex)selfrl   r5   r5   r6   __init__3  s    

zParameter.__init__N)__name__
__module____qualname__rs   r5   r5   r5   r6   rf   2  s   rf   c               @   s4   e Zd Zdd Zdd Zedd Zedd Zd	S )
Eventc                s   fddt D }d_t|rNdd tt |D d _tj_d_n tkrj _tj_nx 	 t
kr 	 _tj_nT dd}|tkr|_tj_n, tkrt  _tj_ntd	  jtk_jd d
 jd
   }jdkrBtd | _td | _td | _nd_d_d_jdkrtj_fddt D _nfddt D _jd _jd _d S )Nc                s    g | ]}| d  d kqS )GWA)strip)rA   rG   )keyr5   r6   rC   >  s    z"Event.__init__.<locals>.<listcomp>ZO3c             S   s   g | ]\}}|r|qS r5   r5   )rA   rG   mr5   r5   r6   rC   B  s    r   ZO1O2rx   Szunrecognized event %rZO3acolors
linestyles
linewidthsrh   -   c                s   i | ]\}}|  j|qS r5   )getrl   )rA   rG   rB   )rr   r5   r6   rI   g  s    z"Event.__init__.<locals>.<dictcomp>c                s   i | ]\}}|  j|qS r5   )r   cid)rA   rG   rB   )rr   r5   r6   rI   i  s    ZOBSERVINGINSTRUMENTSrJ   )o1o2_eventsrunanyzipr   rD   Zsidsuperevent_idsrF   rk   catalog_idsrn   
_NAME_DICT
ValueError
all_eventsZin_paperlower_STYLE_DICTcolorlslwr7   rl   _PE_DICTitemspeZifos)rr   r{   Z
match_o1o2new_keyZalt_cidr5   )r{   rr   r6   rs   =  sF    

zEvent.__init__c             C   s   | j t|j S )N)r   rf   ro   )rr   r{   r5   r5   r6   	get_paramm  s    zEvent.get_paramc             C   s8   g }x.t  D ]"}t|j| jkr||  qW |S )N)rm   keysrf   ro   r   appendr   )rr   r   rG   r5   r5   r6   
parametersp  s
    zEvent.parametersc             C   s   d| j krd| j  S | jS d S )NZGW19z	\NAME{%s})r   rl   )rr   r5   r5   r6   
name_macrox  s    

zEvent.name_macroN)rt   ru   rv   rs   r   propertyr   r   r5   r5   r5   r6   rw   <  s   0rw   c             C   sJ   |d |d  }t |}x*| D ]"}|||9 }|t ||  }q W |S )a:   Multiply a set of KDEs, evaluated over array.

    Arguments
    ---------
    all_kdes: list
        list of KDE functions to be combined.
    x: array
        array of parameter values over which to evaluate KDEs.

    Returns
    -------
    joint_like: array
        combined KDE evaluated over `x` grid.
    r   r   )np	ones_likesum)all_kdesxdx
joint_likekder5   r5   r6   multiply_likelihood_kdes  s    

r     c             K   s   |dkr.t dd | D }tdd | D }n|\}}t|||}g }x,| D ]$}	||	f|}
|t||
| qNW t||}||fS )a   Multiply PDFs starting from samples.

    Arguments
    ---------
    all_samples: list
        list of arrays of samples drawn from the PDFs to be combined.
    range: tuple, None
        range of x over which to combine PDF(x), defaults to the min and max
        over all sets of samples provided.
    nbins: int
        number of bins used to produce grid overwhich to multiply PDFs
        (def. 1000).
    kde: function
        function to prodce KDE from samples (def. scipy.stats.gaussian_kde).

    kwargs:
        additional arguments passed to KDE function.

    Returns
    -------
    joint_like: array
        combined PDF evaluated over `x` grid.
    x: array
        parameter grid over which PDF was evaluated.
    Nc             S   s   g | ]}t |qS r5   )min)rA   sr5   r5   r6   rC     s    z(multiply_likelihoods.<locals>.<listcomp>c             S   s   g | ]}t |qS r5   )max)rA   r   r5   r5   r6   rC     s    )r   r   r   linspacer   r   r   )Zall_samplesrangenbinsr   kwargsxminxmaxr   r   samplespdfr   r5   r5   r6   multiply_likelihoods  s    

r   ?Tc       
      C   s   dd|  }d| }t | |dd}|r2||  }|t|k rTtd t|}d}nt||}||}|t|krtd t|}	n|pt||}||}	||	fS )a   Compute symmetric credible interval from PDF evaluated over grid.

    Arguments
    ---------
    y: array
        array of PDF values
    x: array
        array of parameter values corresponding to `y`.
    p: float
        credible level (def. 0.9).
    normalize: bool
        normalize PDF before computing CI (def. True).

    Returns
    -------
    left: float
        parameter value corresponding to lower interval edge.
    right: float
        parameter value corresponding to upper interval edge.
    g      ?r   g        )initialzWARNING: value below range.NzWARNING: value above range.)r   r   r   printr   )
yr   p	normalizeZcdf_leftZ	cdf_rightcdfleft
cdf_interprightr5   r5   r6   get_sym_interval_from_pdf  s"    

r   c             C   sR   t | |dd}|r||  }|t|kr<td t|}nt||}||}|S )a   Compute symmetric upper limit from PDF evaluated over grid.

    Arguments
    ---------
    y: array
        array of PDF values
    x: array
        array of parameter values corresponding to `y`.
    p: float
        credible level (def. 0.9).
    normalize: bool
        normalize PDF before computing UL (def. True).

    Returns
    -------
    ul: float
        parameter value corresponding to UL.
    g        )r   zWARNING: value above range.)r   r   r   r   )r   r   r   r   r   ulr   r5   r5   r6   get_ul_from_pdf  s    

r   c             C   sN   t | |dk ||dk d|d}t | |dk  ||dk  dd| d }||fS )a   Get p-credible upper limit for of absolute value of negative/positive
    samples treated separately.
    
    Arguments
    ---------
    y: array
        PDF(x) evaluated on x grid.
    x: array
        x values.
    p: float
        credibility (def. 0.9).
    
    Returns
    -------
    ul_m : float
        limit for negative values.
    ul_p : float
        limit for positive values.
    r   T)r   r   r   )r   )r   r   r   ul_pul_mr5   r5   r6   get_negpos_uls_from_pdf  s     &r   c             C   sD   | | dk }t ||d }| | dk  }t |d| d }||fS )a   Get p-credible upper limit for of absolute value of negative/positive
    samples treated separately.
    
    Arguments
    ---------
    y: array
        PDF(x) evaluated on x grid.
    x: array
        x values.
    p: float
        credibility (def. 0.9).
    
    Returns
    -------
    ul_m : float
        limit for negative values.
    ul_p : float
        limit for positive values.
    r   d   r   )r   
percentile)r   r   Z	samples_pr   Z	samples_mr   r5   r5   r6   get_negpos_uls_from_samples%  s
    r   c             C   s0   t | |dd}|r||  }t||}||S )a   Get one-sided quantile of target value from PDF data.
    
    Arguments
    ---------
    y: array
        PDF(x) evaluated on x grid.
    x: array
        x values.
    target: float
        x value for which to compute quantile (def. 0).
    normalize: bool
        whether to normalize PDF before computing quantile (def. True).
    
    Returns
    -------
    q: float
       quantile at target. 
    g        )r   )r   r   r   )r   r   targetr   r   r   r5   r5   r6   get_quantile_from_pdf?  s
    
r   Fc             C   sb   |rFt | t |  }t |t |  }t|||k t|  }nt| | |k t|  }|S )aj   Get quantile (one or two-sided) of target value from samples.
    
    Arguments
    ---------
    x: array
        array of samples.
    target: float
        x value for which to compute quantile (def. 0).
    twosided: bool
        whether to compute two-sided quantile (def. False).
    
    Returns
    -------
    q: float
       quantile at target. 
    )r   absmedianlen)r   r   twosidedZabs_distZtarget_distrd   r5   r5   r6   get_quantile_from_samplesZ  s    r   r   r   c       
      C   sd   t | |f}|r.t |t | | ff}n|}t|}||}||}t ||k t| }	|	S )aC   Get 2D quantile of target value from samples (x, y).
    
    The 2D quantile is defined as the isoprobability contour that passes
    through the target point.
    
    WARNING: this function is written with the hyperparameters (x=mu, y=sigma)
    in mind, for which the usual target (0, 0) lies at the edge of the sigma 
    prior. To deal with this, the 2D distribution is reflected around the 
    x-axis by default (behavior controlled by `reflect_around_x` argument).
    
    Arguments
    ---------
    x: array
        x samples (1D).
    y: array
        y samples (1D).
    target: array
        coordinates at which to evaluate quantile (def. [0, 0]).
    reflect_around_x: bool
        whether to reflect points around the x-axis (def. True).
        
    Returns
    -------
    q: float
        quantile at target.
    )r   	row_stackcolumn_stackr   count_nonzeror   )
r   r   r   Zreflect_around_xptsZpts_reflectedr   Zpts_densitiesZtarget_densityrd   r5   r5   r6   get_2d_quantile_from_sampless  s    r   c             K   s   | dd}|dkr.t||d}t| |}g }xRt|D ]F}tj||}	x(| |	tjd|k rvtj||}	qPW ||	 q<W t|}
|
S )a   Make `nsamp` draws from PDF using rejection sampling.

    Arguments
    ---------
    pdf: function
        probability density function for quantity x.
    x_min: float
        minimum value of x.
    x_max: float
        maximum value of x.
    nsamp: int
        number of samples to draw through rejection sampling..

    Returns
    -------
    samples: array
        array of samples drawn from PDF.
    p_maxNi  r   )	popr   r   r   r   randomuniformr   array)r   x_minx_maxZnsampr   r   r   Zsample_listisampler   r5   r5   r6   draw_samples  s    
r   c                   sf   e Zd ZdZd fdd	Zedd Zedd Zed	d
 Zedd Z	 fddZ
dd Z  ZS )Bounded_2d_kdezRepresents a two-dimensional Gaussian kernel density estimator
    for a probability distribution function that exists on a bounded
    domain.Nc                sR   t |}|jdkstdtt| j|jf|| || _|| _	|| _
|| _dS )a  Initialize with the given bounds.  Either ``low`` or
        ``high`` may be ``None`` if the bounds are one-sided.  Extra
        parameters are passed to :class:`gaussian_kde`.

        :param xlow: The lower x domain boundary.

        :param xhigh: The upper x domain boundary.

        :param ylow: The lower y domain boundary.

        :param yhigh: The upper y domain boundary.
        r   z'Bounded_kde can only be two-dimensionalN)r   
atleast_2dndimAssertionErrorsuperr   rs   T_xlow_xhigh_ylow_yhigh)rr   r   xlowxhighylowyhighargsr   )	__class__r5   r6   rs     s    
zBounded_2d_kde.__init__c             C   s   | j S )z The lower bound of the x domain.)r   )rr   r5   r5   r6   r     s    zBounded_2d_kde.xlowc             C   s   | j S )z The upper bound of the x domain.)r   )rr   r5   r5   r6   r     s    zBounded_2d_kde.xhighc             C   s   | j S )z The lower bound of the y domain.)r   )rr   r5   r5   r6   r     s    zBounded_2d_kde.ylowc             C   s   | j S )z The upper bound of the y domain.)r   )rr   r5   r5   r6   r     s    zBounded_2d_kde.yhighc                s  t |}|jdkstd|j\}}tt| |j}| jdk	rd|tt| d| j | |g7 }| j	dk	r|tt| d| j	 | |g7 }| j
dk	r|tt| |d| j
 | g7 }| jdk	r|tt| |d| j | g7 }| jdk	rd| j
dk	r,|tt| d| j | d| j
 | g7 }| jdk	rd|tt| d| j | d| j | g7 }| j	dk	r| j
dk	r|tt| d| j	 | d| j
 | g7 }| jdk	r|tt| d| j	 | d| j | g7 }|S )zHReturn an estimate of the density evaluated at the given
        points.r   zpoints must be two-dimensionalN)r   r   r   r   r   r   r   evaluater   r   r   r   )rr   r   r   r   r   )r   r5   r6   r     s.    


"
"
"
",,,,zBounded_2d_kde.evaluatec             C   s   t |}t j|jd dd}| jd k	rBd||d d df | jk < | jd k	rfd||d d df | jk< | jd k	rd||d d df | jk < | jd k	rd||d d df | jk< | |}d||< |S )Nr   bool)dtypeTr   g        )	r   r   zerosshaper   r   r   r   r   )rr   r   out_of_boundsresultsr5   r5   r6   __call__  s    





zBounded_2d_kde.__call__)NNNN)rt   ru   rv   __doc__rs   r   r   r   r   r   r   r   __classcell__r5   r5   )r   r6   r     s   #r      c                s  yt | dt| }W n, tk
rF   tdd|d dd }Y nX fdddD }tt| |ff|}tdt |d  d	}tjj	t | |d
}|t| | || ft
 t fdd|D }	t| dt| d }
t|dt|d }tt| dd|
  t| dd|
  d}tt|dd|  t|dd|  d}t||dd\}}|t| | f|j}dt }|j|||fd|	i dS )ak   Plot contours at specified credible levels.

    Arguments
    ---------
    xs: array
        samples of the first variable.
    ys: array
        samples of the second variable, drawn jointly with `xs`.
    levels: float, array
        if float, interpreted as number of credible levels to be equally 
        spaced between (0, 1); if array, interpreted as list of credible
        levels.
    xlow: float
        lower bound for abscissa passed to Bounded_2d_kde (optional).
    xigh: float
        upper bound for abscissa passed to Bounded_2d_kde (optional).
    ylow: float
        lower bound for ordinate passed to Bounded_2d_kde (optional).
    yhigh: float
        upper bound for ordinate passed to Bounded_2d_kde (optional).
    ax: Axes
        matplotlib axes on which to plot (optional).
    kwargs:
        additional arguments passed to plt.contour().
    r   r   r   r~   c                s   i | ]}  |d |qS )N)r   )rA   rG   )r   r5   r6   rI   M  s    z&kdeplot_2d_clevels.<locals>.<dictcomp>)r   r   r   r   
   i  )sizec          	      s(   g | ] } t t|t    qS r5   )introundr   )rA   ff)r   r   r5   r6   rC   S  s    z&kdeplot_2d_clevels.<locals>.<listcomp>c   g?   ij)indexingaxlevelsN)r   r   r   	TypeErrorr   r   r   r   r   choiceargsortr   meshgridflattenreshaper   r   gcacontour)xsysr  r   fkde_kwsrG   r   clZDxZDyr   r   ZXSYSZZSr  r5   )r   r   r   r6   kdeplot_2d_clevels.  s(    ,,"r  )r   T)r   T)r   )r   )r   T)r   F)r   T)r   )r   )Wosnumpyr   scipy.statsr   scipy.interpolater   scipy.integrater   picklepkljsonpylabstatssswarningscatch_warningssimplefilterZ#pesummary.core.plots.bounded_1d_kder   ZBounded_1d_kdescale_factorfig_width_ptinches_per_ptsqrt	fig_ratio	fig_width
fig_heightfigsize_columnfigsize_squarefig_width_pagefigsize_pagercParamsfsfs_labelr4   r7   r@   sortedr   r   r   dictr   rE   rD   rF   r   Z
o3a_eventsr   pathdirnamerealpath__file__	base_pathopenjoinr  loadr   r   Z_PE_DICT_O1O2r   rG   rB   updateZ_PE_DICT_O3Br   rm   copyrp   objectrf   rw   r   r   r   r   r   r   r   r   r   r   r   r   r  r5   r5   r5   r6   <module>   s  























G'
,
 




&
*i