bayespputils.py 298 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
# -*- coding: utf-8 -*-
#
#       bayespputils.py
#
#       Copyright 2010
#       Benjamin Aylott <benjamin.aylott@ligo.org>,
#       Benjamin Farr <bfarr@u.northwestern.edu>,
#       Will M. Farr <will.farr@ligo.org>,
#       John Veitch <john.veitch@ligo.org>,
#       Salvatore Vitale <salvatore.vitale@ligo.org>,
#       Vivien Raymond <vivien.raymond@ligo.org>
#
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

#===============================================================================
# Preamble
#===============================================================================

"""
This module contains classes and functions for post-processing the output
of the Bayesian parameter estimation codes.
"""

#standard library imports
import os
import sys
from math import cos,ceil,floor,sqrt,pi as pi_constant
import xml
from xml.dom import minidom
from operator import itemgetter

#related third party imports
46
from .io import read_samples
47
from . import plot as lp
48 49 50 51 52
import healpy as hp
import astropy.table
import numpy as np
from numpy import fmod
import matplotlib
53
matplotlib.use('agg')
54 55 56 57 58 59 60 61 62 63
from matplotlib import pyplot as plt,cm as mpl_cm,lines as mpl_lines
from scipy import stats
from scipy import special
from scipy import signal
from scipy.optimize import newton
from scipy import interpolate
from numpy import linspace
import random
import socket
from itertools import combinations
64
from .lalinference import LALInferenceHDF5PosteriorSamplesDatasetName as posterior_grp_name
65
import re
66
import six
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81

try:
    import lalsimulation as lalsim
except ImportError:
    print('Cannot import lalsimulation SWIG bindings')
    raise

try:
    from .imrtgr.nrutils import bbh_final_mass_non_spinning_Panetal, bbh_final_spin_non_spinning_Panetal, bbh_final_spin_non_precessing_Healyetal, bbh_final_mass_non_precessing_Healyetal, bbh_final_spin_projected_spin_Healyetal, bbh_final_mass_projected_spin_Healyetal, bbh_aligned_Lpeak_6mode_SHXJDK
except ImportError:
    print('Cannot import lalinference.imrtgr.nrutils. Will suppress final parameter calculations.')

from matplotlib.ticker import FormatStrFormatter,ScalarFormatter,AutoMinorLocator

try:
82
    hostname_short=socket.gethostbyaddr(socket.gethostname())[0].split('.',1)[1]
83
except:
84
    hostname_short='Unknown'
85
if hostname_short=='ligo.caltech.edu' or hostname_short=='cluster.ldas.cit': #The CIT cluster has troubles with the default 'cm' font. 'custom' has the least troubles, but does not include \odot
86 87 88 89
    matplotlib.rcParams.update(
                               {'mathtext.fontset' : "custom",
                               'mathtext.fallback_to_cm' : True
                               })
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126

from xml.etree.cElementTree import Element, SubElement, ElementTree, Comment, tostring, XMLParser

#local application/library specific imports
import lal
from . import git_version

__author__="Ben Aylott <benjamin.aylott@ligo.org>, Ben Farr <bfarr@u.northwestern.edu>, Will M. Farr <will.farr@ligo.org>, John Veitch <john.veitch@ligo.org>, Vivien Raymond <vivien.raymond@ligo.org>"
__version__= "git id %s"%git_version.id
__date__= git_version.date

def replace_column(table, old, new):
    """Workaround for missing astropy.table.Table.replace_column method,
    which was added in Astropy 1.1.

    FIXME: remove this function when LALSuite depends on Astropy >= 1.1."""
    index = table.colnames.index(old)
    table.remove_column(old)
    table.add_column(astropy.table.Column(new, name=old), index=index)

def as_array(table):
    """Workaround for missing astropy.table.Table.as_array method,
    which was added in Astropy 1.0.

    FIXME: remove this function when LALSuite depends on Astropy >= 1.0."""
    try:
        return table.as_array()
    except:
        return table._data

#===============================================================================
# Constants
#===============================================================================
#Parameters which are not to be exponentiated when found
logParams=['logl','loglh1','loglh2','logll1','loglv1','deltalogl','deltaloglh1','deltalogll1','deltaloglv1','logw','logprior','logpost','nulllogl','chain_log_evidence','chain_delta_log_evidence','chain_log_noise_evidence','chain_log_bayes_factor']
#Parameters known to cbcBPP
relativePhaseParams=[ a+b+'_relative_phase' for a,b in combinations(['h1','l1','v1'],2)]
127
snrParams=['snr','optimal_snr','matched_filter_snr','coherence'] + ['%s_optimal_snr'%(i) for i in ['h1','l1','v1']] + ['%s_cplx_snr_amp'%(i) for i in ['h1','l1','v1']] + ['%s_cplx_snr_arg'%(i) for i in ['h1', 'l1', 'v1']] + relativePhaseParams
128 129 130 131 132 133 134 135 136 137 138
calAmpParams=['calamp_%s'%(ifo) for ifo in ['h1','l1','v1']]
calPhaseParams=['calpha_%s'%(ifo) for ifo in ['h1','l1','v1']]
calParams = calAmpParams + calPhaseParams
# Masses
massParams=['m1','m2','chirpmass','mchirp','mc','eta','q','massratio','asym_massratio','mtotal','mf']
#Spins
spinParamsPrec=['a1','a2','phi1','theta1','phi2','theta2','costilt1','costilt2','costheta_jn','cosbeta','tilt1','tilt2','phi_jl','theta_jn','phi12','af']
spinParamsAli=['spin1','spin2','a1z','a2z']
spinParamsEff=['chi','effectivespin','chi_eff','chi_tot','chi_p']
spinParams=spinParamsPrec+spinParamsEff+spinParamsAli
# Source frame params
139
cosmoParam=['m1_source','m2_source','mtotal_source','mc_source','redshift','mf_source','m1_source_maxldist','m2_source_maxldist','mtotal_source_maxldist','mc_source_maxldist','redshift_maxldist','mf_source_maxldist']
140 141 142 143 144
#Strong Field
ppEParams=['ppEalpha','ppElowera','ppEupperA','ppEbeta','ppElowerb','ppEupperB','alphaPPE','aPPE','betaPPE','bPPE']
tigerParams=['dchi%i'%(i) for i in range(8)] + ['dchi%il'%(i) for i in [5,6] ] + ['dxi%d'%(i+1) for i in range(6)] + ['dalpha%i'%(i+1) for i in range(5)] + ['dbeta%i'%(i+1) for i in range(3)] + ['dsigma%i'%(i+1) for i in range(4)]
bransDickeParams=['omegaBD','ScalarCharge1','ScalarCharge2']
massiveGravitonParams=['lambdaG']
Carl-Johan Haster's avatar
Carl-Johan Haster committed
145
tidalParams=['lambda1','lambda2','lam_tilde','dlam_tilde','lambdat','dlambdat','lambdas','bluni']
146
eosParams=['logp1','gamma1','gamma2','gamma3']
147
energyParams=['e_rad', 'l_peak','e_rad_maxldist']
148
strongFieldParams=ppEParams+tigerParams+bransDickeParams+massiveGravitonParams+tidalParams+eosParams+energyParams
149 150

#Extrinsic
151
distParams=['distance','distMPC','dist','distance_maxl']
152 153 154 155 156 157 158 159 160 161 162 163 164 165
incParams=['iota','inclination','cosiota']
polParams=['psi','polarisation','polarization']
skyParams=['ra','rightascension','declination','dec']
phaseParams=['phase', 'phi0','phase_maxl']
#Times
timeParams=['time','time_mean']
endTimeParams=['l1_end_time','h1_end_time','v1_end_time']
#others
statsParams=['logprior','logl','deltalogl','deltaloglh1','deltalogll1','deltaloglv1','deltaloglh2','deltaloglg1']
calibParams=['calpha_l1','calpha_h1','calpha_v1','calamp_l1','calamp_h1','calamp_v1']

## Greedy bin sizes for cbcBPP and confidence leves used for the greedy bin intervals
confidenceLevels=[0.67,0.9,0.95,0.99]

166
greedyBinSizes={'mc':0.025,'m1':0.1,'m2':0.1,'mass1':0.1,'mass2':0.1,'mtotal':0.1,'mc_source':0.025,'m1_source':0.1,'m2_source':0.1,'mtotal_source':0.1,'mc_source_maxldist':0.025,'m1_source_maxldist':0.1,'m2_source_maxldist':0.1,'mtotal_source_maxldist':0.1,'eta':0.001,'q':0.01,'asym_massratio':0.01,'iota':0.01,'cosiota':0.02,'time':1e-4,'time_mean':1e-4,'distance':1.0,'dist':1.0,'distance_maxl':1.0,'redshift':0.01,'redshift_maxldist':0.01,'mchirp':0.025,'chirpmass':0.025,'spin1':0.04,'spin2':0.04,'a1z':0.04,'a2z':0.04,'a1':0.02,'a2':0.02,'phi1':0.05,'phi2':0.05,'theta1':0.05,'theta2':0.05,'ra':0.05,'dec':0.05,'chi':0.05,'chi_eff':0.05,'chi_tot':0.05,'chi_p':0.05,'costilt1':0.02,'costilt2':0.02,'thatas':0.05,'costheta_jn':0.02,'beta':0.05,'omega':0.05,'cosbeta':0.02,'ppealpha':1.0,'ppebeta':1.0,'ppelowera':0.01,'ppelowerb':0.01,'ppeuppera':0.01,'ppeupperb':0.01,'polarisation':0.04,'rightascension':0.05,'declination':0.05,'massratio':0.001,'inclination':0.01,'phase':0.05,'tilt1':0.05,'tilt2':0.05,'phi_jl':0.05,'theta_jn':0.05,'phi12':0.05,'flow':1.0,'phase_maxl':0.05,'calamp_l1':0.01,'calamp_h1':0.01,'calamp_v1':0.01,'calpha_h1':0.01,'calpha_l1':0.01,'calpha_v1':0.01,'logdistance':0.1,'psi':0.1,'costheta_jn':0.1,'mf':0.1,'mf_source':0.1,'mf_source_maxldist':0.1,'af':0.02,'e_rad':0.1,'e_rad_maxldist':0.1,'l_peak':0.1}
167
for s in snrParams:
168
    greedyBinSizes[s]=0.05
169
for derived_time in ['h1_end_time','l1_end_time','v1_end_time','h1l1_delay','l1v1_delay','h1v1_delay']:
170
    greedyBinSizes[derived_time]=greedyBinSizes['time']
171
for derived_phase in relativePhaseParams:
172
    greedyBinSizes[derived_phase]=0.05
173
for param in tigerParams + bransDickeParams + massiveGravitonParams:
174
    greedyBinSizes[param]=0.01
175
for param in tidalParams:
176
    greedyBinSizes[param]=2.5
177
for param in eosParams:
178 179
    greedyBinSizes[param]=2.5
    #Confidence levels
180
for loglname in statsParams:
181
    greedyBinSizes[loglname]=0.1
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295

#Pre-defined ordered list of line styles for use in matplotlib contour plots.
__default_line_styles=['solid', 'dashed', 'dashdot', 'dotted']
#Pre-defined ordered list of matplotlib colours for use in plots.
__default_color_lst=['r','b','y','g','c','m']
#A default css string for use in html results pages.
__default_css_string="""
p,h1,h2,h3,h4,h5
{
font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
}

p
{
font-size:14px;
}

h1
{
font-size:20px;
}

h2
{
font-size:18px;
}

h3
{
font-size:16px;
}



table
{
font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
width:100%;
border-collapse:collapse;
}
td,th
{
font-size:12px;
border:1px solid #B5C1CF;
padding:3px 7px 2px 7px;
}
th
{
font-size:14px;
text-align:left;
padding-top:5px;
padding-bottom:4px;
background-color:#B3CEEF;
color:#ffffff;
}
#postable tr:hover
{
background: #DFF4FF;
}
#covtable tr:hover
{
background: #DFF4FF;
}
#statstable tr:hover
{
background: #DFF4FF;
}

img {
    max-width: 510px;
    max-height: 510px;
    width:100%;
    eight:100%;
}

.ppsection
{
border-bottom-style:double;
}

"""
__default_javascript_string='''
//<![CDATA[
function toggle_visibility(tbid,lnkid)
{

  if(document.all){document.getElementById(tbid).style.display = document.getElementById(tbid).style.display == 'block' ? 'none' : 'block';}

  else{document.getElementById(tbid).style.display = document.getElementById(tbid).style.display == 'table' ? 'none' : 'table';}

  document.getElementById(lnkid).value = document.getElementById(lnkid).value == '[-] Collapse' ? '[+] Expand' : '[-] Collapse';

 }
 //]]>

'''


#===============================================================================
# Function to return the correct prior distribution for selected parameters
#===============================================================================
def get_prior(name):
    distributions={
      'm1':'uniform',
      'm2':'uniform',
      'mc':None,
      'eta':None,
      'q':None,
      'mtotal':'uniform',
      'm1_source':None,
      'm2_source':None,
      'mtotal_source':None,
      'mc_source':None,
      'redshift':None,
296 297 298 299 300
      'm1_source_maxldist':None,
      'm2_source_maxldist':None,
      'mtotal_source_maxldist':None,
      'mc_source_maxldist':None,
      'redshift_maxldist':None,
301 302
      'mf':None,
      'mf_source':None,
303
      'mf_source_maxldist':None,
304 305
      'af':None,
      'e_rad':None,
306
      'e_rad_maxldist':None,
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
      'l_peak':None,
      'spin1':'uniform',
      'spin2':'uniform',
      'a1':'uniform',
      'a2':'uniform',
      'a1z':'uniform',
      'a2z':'uniform',
      'theta1':'uniform',
      'theta2':'uniform',
      'phi1':'uniform',
      'phi2':'uniform',
      'chi_eff':None,
      'chi_tot':None,
      'chi_p':None,
      'tilt1':None,
      'tilt2':None,
      'costilt1':'uniform',
      'costilt2':'uniform',
      'iota':'np.cos',
      'cosiota':'uniform',
      'time':'uniform',
      'time_mean':'uniform',
      'dist':'x**2',
330
      'distance_maxl':'x**2',
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
      'ra':'uniform',
      'dec':'np.cos',
      'phase':'uniform',
      'psi':'uniform',
      'theta_jn':'np.sin',
      'costheta_jn':'uniform',
      'beta':None,
      'cosbeta':None,
      'phi_jl':None,
      'phi12':None,
      'logl':None,
      'h1_end_time':None,
      'l1_end_time':None,
      'v1_end_time':None,
      'h1l1_delay':None,
      'h1v1_delay':None,
      'l1v1_delay':None,
      'lambdat' :None,
      'dlambdat':None,
      'lambda1' : 'uniform',
      'lambda2': 'uniform',
      'lam_tilde' : None,
      'dlam_tilde': None,
Carl-Johan Haster's avatar
Carl-Johan Haster committed
354 355
      'lambdas':'uniform',
      'bluni':'uniform',
356
      'logp1':None,
357 358 359
      'gamma1':None,
      'gamma2':None,
      'gamma3':None,
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
      'calamp_h1' : 'uniform',
      'calamp_l1' : 'uniform',
      'calpha_h1' : 'uniform',
      'calpha_l1' : 'uniform',
      'polar_eccentricity':'uniform',
      'polar_angle':'uniform',
      'alpha':'uniform'
    }
    try:
        return distributions(name)
    except:
        return None

#===============================================================================
# Function used to generate plot labels.
#===============================================================================
def plot_label(param):
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
    """
    A lookup table for plot labels.
    """
    m1_names = ['mass1', 'm1']
    m2_names = ['mass2', 'm2']
    mc_names = ['mc','mchirp','chirpmass']
    eta_names = ['eta','massratio','sym_massratio']
    q_names = ['q','asym_massratio']
    iota_names = ['iota','incl','inclination']
    dist_names = ['dist','distance']
    ra_names = ['rightascension','ra']
    dec_names = ['declination','dec']
    phase_names = ['phi_orb', 'phi', 'phase', 'phi0']
    gr_test_names = ['dchi%d'%i for i in range(8)]+['dchil%d'%i for i in [5,6]]+['dxi%d'%(i+1) for i in range(6)]+['dalpha%d'%(i+1) for i in range(5)]+['dbeta%d'%(i+1) for i in range(3)]+['dsigma%d'%(i+1) for i in range(4)]

    labels={
        'm1':r'$m_1\,(\mathrm{M}_\odot)$',
        'm2':r'$m_2\,(\mathrm{M}_\odot)$',
        'mc':r'$\mathcal{M}\,(\mathrm{M}_\odot)$',
        'eta':r'$\eta$',
        'q':r'$q$',
        'mtotal':r'$M_\mathrm{total}\,(\mathrm{M}_\odot)$',
        'm1_source':r'$m_{1}^\mathrm{source}\,(\mathrm{M}_\odot)$',
        'm2_source':r'$m_{2}^\mathrm{source}\,(\mathrm{M}_\odot)$',
        'mtotal_source':r'$M_\mathrm{total}^\mathrm{source}\,(\mathrm{M}_\odot)$',
        'mc_source':r'$\mathcal{M}^\mathrm{source}\,(\mathrm{M}_\odot)$',
        'redshift':r'$z$',
404 405 406 407 408
        'm1_source_maxldist':r'$m_{1}^\mathrm{source - maxLdist}\,(\mathrm{M}_\odot)$',
        'm2_source_maxldist':r'$m_{2}^\mathrm{source - maxLdist}\,(\mathrm{M}_\odot)$',
        'mtotal_source_maxldist':r'$M_\mathrm{total}^\mathrm{source - maxLdist}\,(\mathrm{M}_\odot)$',
        'mc_source_maxldist':r'$\mathcal{M}^\mathrm{source - maxLdist}\,(\mathrm{M}_\odot)$',
        'redshift_maxldist':r'$z^\mathrm{maxLdist}$',
409 410
        'mf':r'$M_\mathrm{final}\,(\mathrm{M}_\odot)$',
        'mf_source':r'$M_\mathrm{final}^\mathrm{source}\,(\mathrm{M}_\odot)$',
411
        'mf_source_maxldist':r'$M_\mathrm{final}^\mathrm{source - maxLdist}\,(\mathrm{M}_\odot)$',
412 413
        'af':r'$a_\mathrm{final}$',
        'e_rad':r'$E_\mathrm{rad}\,(\mathrm{M}_\odot)$',
414
        'e_rad_maxldist':r'$E_\mathrm{rad}^\mathrm{maxLdist}\,(\mathrm{M}_\odot)$',
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
        'l_peak':r'$L_\mathrm{peak}\,(10^{56}\,\mathrm{ergs}\,\mathrm{s}^{-1})$',
        'spin1':r'$S_1$',
        'spin2':r'$S_2$',
        'a1':r'$a_1$',
        'a2':r'$a_2$',
        'a1z':r'$a_{1z}$',
        'a2z':r'$a_{2z}$',
        'theta1':r'$\theta_1\,(\mathrm{rad})$',
        'theta2':r'$\theta_2\,(\mathrm{rad})$',
        'phi1':r'$\phi_1\,(\mathrm{rad})$',
        'phi2':r'$\phi_2\,(\mathrm{rad})$',
        'chi_eff':r'$\chi_\mathrm{eff}$',
        'chi_tot':r'$\chi_\mathrm{total}$',
        'chi_p':r'$\chi_\mathrm{P}$',
        'tilt1':r'$t_1\,(\mathrm{rad})$',
        'tilt2':r'$t_2\,(\mathrm{rad})$',
        'costilt1':r'$\mathrm{cos}(t_1)$',
        'costilt2':r'$\mathrm{cos}(t_2)$',
        'iota':r'$\iota\,(\mathrm{rad})$',
        'cosiota':r'$\mathrm{cos}(\iota)$',
        'time':r'$t_\mathrm{c}\,(\mathrm{s})$',
        'time_mean':r'$<t>\,(\mathrm{s})$',
        'dist':r'$d_\mathrm{L}\,(\mathrm{Mpc})$',
438
        'distance_maxl':r'$d_\mathrm{L}^\mathrm{maxL}\,(\mathrm{Mpc})$',
439 440 441
        'ra':r'$\alpha$',
        'dec':r'$\delta$',
        'phase':r'$\phi\,(\mathrm{rad})$',
442
        'phase_maxl':r'$\phi^\mathrm{maxL}\,(\mathrm{rad})$',
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
        'psi':r'$\psi\,(\mathrm{rad})$',
        'theta_jn':r'$\theta_\mathrm{JN}\,(\mathrm{rad})$',
        'costheta_jn':r'$\mathrm{cos}(\theta_\mathrm{JN})$',
        'beta':r'$\beta\,(\mathrm{rad})$',
        'cosbeta':r'$\mathrm{cos}(\beta)$',
        'phi_jl':r'$\phi_\mathrm{JL}\,(\mathrm{rad})$',
        'phi12':r'$\phi_\mathrm{12}\,(\mathrm{rad})$',
        'logl':r'$\mathrm{log}(\mathcal{L})$',
        'h1_end_time':r'$t_\mathrm{H}$',
        'l1_end_time':r'$t_\mathrm{L}$',
        'v1_end_time':r'$t_\mathrm{V}$',
        'h1l1_delay':r'$\Delta t_\mathrm{HL}$',
        'h1v1_delay':r'$\Delta t_\mathrm{HV}$',
        'l1v1_delay':r'$\Delta t_\mathrm{LV}$',
        'lambdat' : r'$\tilde{\Lambda}$',
        'dlambdat': r'$\delta \tilde{\Lambda}$',
        'lambda1' : r'$\lambda_1$',
        'lambda2': r'$\lambda_2$',
        'lam_tilde' : r'$\tilde{\Lambda}$',
        'dlam_tilde': r'$\delta \tilde{\Lambda}$',
        'logp1':r'$\log(p_1)$',
        'gamma1':r'$\Gamma_1$',
        'gamma2':r'$\Gamma_2$',
        'gamma3':r'$\Gamma_3$',
        'calamp_h1' : r'$\delta A_{H1}$',
        'calamp_l1' : r'$\delta A_{L1}$',
        'calpha_h1' : r'$\delta \phi_{H1}$',
        'calpha_l1' : r'$\delta \phi_{L1}$',
        'polar_eccentricity':r'$\epsilon_{polar}$',
        'polar_angle':r'$\alpha_{polar}$',
        'alpha':r'$\alpha_{polar}$',
        'dchi0':r'$d\chi_0$',
        'dchi1':r'$d\chi_1$',
        'dchi2':r'$d\chi_2$',
        'dchi3':r'$d\chi_3$',
        'dchi4':r'$d\chi_4$',
        'dchi5':r'$d\chi_5$',
        'dchi5l':r'$d\chi_{5}^{(l)}$',
        'dchi6':r'$d\chi_6$',
        'dchi6l':r'$d\chi_{6}^{(l)}$',
        'dchi7':r'$d\chi_7$',
        'dxi1':r'$d\xi_1$',
        'dxi2':r'$d\xi_2$',
        'dxi3':r'$d\xi_3$',
        'dxi4':r'$d\xi_4$',
        'dxi5':r'$d\xi_5$',
        'dxi6':r'$d\xi_6$',
        'dalpha1':r'$d\alpha_1$',
        'dalpha2':r'$d\alpha_2$',
        'dalpha3':r'$d\alpha_3$',
        'dalpha4':r'$d\alpha_4$',
        'dalpha5':r'$d\alpha_5$',
        'dbeta1':r'$d\beta_1$',
        'dbeta2':r'$d\beta_2$',
        'dbeta3':r'$d\beta_3$',
        'dsigma1':r'$d\sigma_1$',
        'dsigma2':r'$d\sigma_2$',
        'dsigma3':r'$d\sigma_3$',
        'dsigma4':r'$d\sigma_4$',
        'optimal_snr':r'$\rho^{opt}$',
        'h1_optimal_snr':r'$\rho^{opt}_{H1}$',
        'l1_optimal_snr':r'$\rho^{opt}_{L1}$',
        'v1_optimal_snr':r'$\rho^{opt}_{V1}$',
Carl-Johan Haster's avatar
Carl-Johan Haster committed
506 507 508
        'matched_filter_snr':r'$\rho^{MF}$',
        'lambdas':r'$\Lambda_S$',
        'bluni' : r'$BL_{uniform}$'
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
      }

    # Handle cases where multiple names have been used
    if param in m1_names:
        param = 'm1'
    elif param in m2_names:
        param = 'm2'
    elif param in mc_names:
        param = 'mc'
    elif param in eta_names:
        param = 'eta'
    elif param in q_names:
        param = 'q'
    elif param in iota_names:
        param = 'iota'
    elif param in dist_names:
        param = 'dist'
    elif param in ra_names:
        param = 'ra'
    elif param in dec_names:
        param = 'dec'
    elif param in phase_names:
        param = 'phase'

    try:
        label = labels[param]
    except KeyError:
        # Use simple string if no formated label is available for param
        label = param
538

539
    return label
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801

#===============================================================================
# Class definitions
#===============================================================================

class PosteriorOneDPDF(object):
    """
    A data structure representing one parameter in a chain of posterior samples.
    The Posterior class generates instances of this class for pivoting onto a given
    parameter (the Posterior class is per-Sampler oriented whereas this class represents
    the same one parameter in successive samples in the chain).
    """
    def __init__(self,name,posterior_samples,injected_value=None,injFref=None,trigger_values=None,prior=None):
        """
        Create an instance of PosteriorOneDPDF based on a table of posterior_samples.

        @param name: A literal string name for the parameter.
        @param posterior_samples: A 1D array of the samples.
        @param injected_value: The injected or real value of the parameter.
        @param injFref: reference frequency for injection
        @param trigger_values: The trigger values of the parameter (dictionary w/ IFOs as keys).
        @param prior: The prior value corresponding to each sample.
        """
        self.__name=name
        self.__posterior_samples=np.array(posterior_samples)

        self.__injFref=injFref
        self.__injval=injected_value
        self.__trigvals=trigger_values
        self.__prior=prior

        return

    def __len__(self):
        """
        Container method. Defined as number of samples.
        """
        return len(self.__posterior_samples)

    def __getitem__(self,idx):
        """
        Container method . Returns posterior containing sample idx (allows slicing).
        """
        return PosteriorOneDPDF(self.__name, self.__posterior_samples[idx], injected_value=self.__injval, f_ref=self.__f_ref, trigger_values=self.__trigvals)

    @property
    def name(self):
        """
        Return the string literal name of the parameter.

        """
        return self.__name

    @property
    def mean(self):
        """
        Return the arithmetic mean for the marginal PDF on the parameter.

        """
        return np.mean(self.__posterior_samples)

    @property
    def median(self):
        """
        Return the median value for the marginal PDF on the parameter.

        """
        return np.median(self.__posterior_samples)

    @property
    def stdev(self):
        """
        Return the standard deviation of the marginal PDF on the parameter.

        """
        try:
            stdev = sqrt(np.var(self.__posterior_samples))
            if not np.isfinite(stdev):
                raise OverflowError
        except OverflowError:
            mean = np.mean(self.__posterior_samples)
            stdev = mean * sqrt(np.var(self.__posterior_samples/mean))
        return stdev

    @property
    def stacc(self):
        """
        Return the 'standard accuracy statistic' (stacc) of the marginal
        posterior of the parameter.

        stacc is a standard deviant incorporating information about the
        accuracy of the waveform recovery. Defined as the mean of the sum
        of the squared differences between the points in the PDF
        (x_i - sampled according to the posterior) and the true value
        (\f$x_{true}\f$).  So for a marginalized one-dimensional PDF:
        \f$stacc = \sqrt{\frac{1}{N}\sum_{i=1}^N (x_i-x_{\rm true})2}\f$

        """
        if self.__injval is None:
            return None
        else:
            return np.sqrt(np.mean((self.__posterior_samples - self.__injval)**2.0))

    @property
    def injval(self):
        """
        Return the injected value set at construction . If no value was set
        will return None .

        """
        return self.__injval

    @property
    def trigvals(self):
        """
        Return the trigger values set at construction. If no value was set
        will return None .

        """
        return self.__trigvals

    #@injval.setter #Python 2.6+
    def set_injval(self,new_injval):
        """
        Set the injected/real value of the parameter.

        @param new_injval: The injected/real value to set.
        """

        self.__injval=new_injval

    def set_trigvals(self,new_trigvals):
        """
        Set the trigger values of the parameter.

        @param new_trigvals: Dictionary containing trigger values with IFO keys.
        """

        self.__trigvals=new_trigvals

    @property
    def samples(self):
        """
        Return a 1D numpy.array of the samples.

        """
        return self.__posterior_samples

    def delete_samples_by_idx(self,samples):
        """
        Remove samples from posterior, analagous to numpy.delete but opperates in place.

        @param samples: A list containing the indexes of the samples to be removed.
        """
        self.__posterior_samples=np.delete(self.__posterior_samples,samples).reshape(-1,1)

    @property
    def gaussian_kde(self):
        """
        Return a SciPy gaussian_kde (representing a Gaussian KDE) of the samples.

        """
        from numpy import seterr as np_seterr
        from scipy import seterr as sp_seterr

        np_seterr(under='ignore')
        sp_seterr(under='ignore')
        try:
            return_value=stats.kde.gaussian_kde(np.transpose(self.__posterior_samples))
        except:
            exfile=open('exception.out','w')
            np.savetxt(exfile,self.__posterior_samples)
            exfile.close()
            raise

        return return_value

    @property
    def KL(self):
        """Returns the KL divergence between the prior and the posterior.
        It measures the relative information content in nats. The prior is evaluated
        at run time. It defaults to None. If None is passed, it just returns the information content
        of the posterior."
        """

        def uniform(x):
            return np.array([1./(np.max(x)-np.min(x)) for _ in x])

        posterior, dx = np.histogram(self.samples,bins=36,normed=True)
        from scipy.stats import entropy
        # check the kind of prior and process the string accordingly
        prior = get_prior(self.name)
        if prior is None:
            raise ValueError
        elif prior=='uniform':
            prior+='(self.samples)'
        elif 'x' in prior:
            prior.replace('x','self.samples')
        elif not(prior.startswith('np.')):
            prior = 'np.'+prior
            prior+='(self.samples)'
        else:
            raise ValueError

        try:
            prior_dist = eval(prior)
        except:
            raise ValueError

        return entropy(posterior, qk=prior_dist)

    def prob_interval(self,intervals):
        """
        Evaluate probability intervals.

        @param intervals: A list of the probability intervals [0-1]
        """
        list_of_ci=[]
        samples_temp=np.sort(np.squeeze(self.samples))

        for interval in intervals:
            if interval<1.0:
                samples_temp
                N=np.size(samples_temp)
                #Find index of lower bound
                lower_idx=int(floor((N/2.0)*(1-interval)))
                if lower_idx<0:
                    lower_idx=0
                #Find index of upper bound
                upper_idx=N-int(floor((N/2.0)*(1-interval)))
                if upper_idx>N:
                    upper_idx=N-1

                list_of_ci.append((float(samples_temp[lower_idx]),float(samples_temp[upper_idx])))
            else:
                list_of_ci.append((None,None))

        return list_of_ci

class Posterior(object):
    """
    Data structure for a table of posterior samples .
    """
    def __init__(self,commonResultsFormatData,SimInspiralTableEntry=None,inj_spin_frame='OrbitalL', injFref=100,SnglInspiralList=None,name=None,description=None):
        """
        Constructor.

        @param commonResultsFormatData: A 2D array containing the posterior
            samples and related data. The samples chains form the columns.
        @param SimInspiralTableEntry: A SimInspiralTable row containing the injected values.
        @param SnglInspiralList: A list of SnglInspiral objects containing the triggers.
        @param inj_spin_frame: spin frame
        @param injFref: reference frequency
        @param name: optional name
        @param description: optional description

        """
        common_output_table_header,common_output_table_raw =commonResultsFormatData
        self._posterior={}
        self._injFref=injFref
        self._injection=SimInspiralTableEntry

802
        self._triggers=SnglInspiralList
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
        self._loglaliases=['deltalogl', 'posterior', 'logl','logL','likelihood']
        self._logpaliases=['logp', 'logP','prior','logprior','Prior','logPrior']

        common_output_table_header=[i.lower() for i in common_output_table_header]

        # Define XML mapping
        self._injXMLFuncMap={
                            'mchirp':lambda inj:inj.mchirp,
                            'chirpmass':lambda inj:inj.mchirp,
                            'mc':lambda inj:inj.mchirp,
                            'mass1':lambda inj:inj.mass1,
                            'm1':lambda inj:inj.mass1,
                            'mass2':lambda inj:inj.mass2,
                            'm2':lambda inj:inj.mass2,
                            'mtotal':lambda inj:float(inj.mass1)+float(inj.mass2),
                            'eta':lambda inj:inj.eta,
                            'q':self._inj_q,
                            'asym_massratio':self._inj_q,
                            'massratio':lambda inj:inj.eta,
                            'sym_massratio':lambda inj:inj.eta,
                            'time': lambda inj:float(inj.get_end()),
                            'time_mean': lambda inj:float(inj.get_end()),
                            'end_time': lambda inj:float(inj.get_end()),
                            'phi0':lambda inj:inj.phi0,
                            'phi_orb': lambda inj: inj.coa_phase,
Salvatore Vitale's avatar
Salvatore Vitale committed
828
                            'phase': lambda inj: inj.coa_phase,
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
                            'dist':lambda inj:inj.distance,
                            'distance':lambda inj:inj.distance,
                            'ra':self._inj_longitude,
                            'rightascension':self._inj_longitude,
                            'long':self._inj_longitude,
                            'longitude':self._inj_longitude,
                            'dec':lambda inj:inj.latitude,
                            'declination':lambda inj:inj.latitude,
                            'lat':lambda inj:inj.latitude,
                            'latitude':lambda inj:inj.latitude,
                            'psi': lambda inj: np.mod(inj.polarization, np.pi),
                            'f_ref': lambda inj: self._injFref,
                            'polarisation':lambda inj:inj.polarization,
                            'polarization':lambda inj:inj.polarization,
                            'h1_end_time':lambda inj:float(inj.get_end('H')),
                            'l1_end_time':lambda inj:float(inj.get_end('L')),
                            'v1_end_time':lambda inj:float(inj.get_end('V')),
                            'lal_amporder':lambda inj:inj.amp_order}

        # Add on all spin parameterizations
        for key, val in self._inj_spins(self._injection, frame=inj_spin_frame).items():
            self._injXMLFuncMap[key] = val

        for one_d_posterior_samples,param_name in zip(np.hsplit(common_output_table_raw,common_output_table_raw.shape[1]),common_output_table_header):

            self._posterior[param_name]=PosteriorOneDPDF(param_name.lower(),one_d_posterior_samples,injected_value=self._getinjpar(param_name),injFref=self._injFref,trigger_values=self._gettrigpar(param_name))

        if 'mchirp' in common_output_table_header and 'eta' in common_output_table_header \
        and (not 'm1' in common_output_table_header) and (not 'm2' in common_output_table_header):
            try:
859
                print('Inferring m1 and m2 from mchirp and eta')
860 861 862 863
                (m1,m2)=mc2ms(self._posterior['mchirp'].samples, self._posterior['eta'].samples)
                self._posterior['m1']=PosteriorOneDPDF('m1',m1,injected_value=self._getinjpar('m1'),trigger_values=self._gettrigpar('m1'))
                self._posterior['m2']=PosteriorOneDPDF('m2',m2,injected_value=self._getinjpar('m2'),trigger_values=self._gettrigpar('m2'))
            except KeyError:
864
                print('Unable to deduce m1 and m2 from input columns')
865 866 867 868 869 870 871 872 873 874


        logLFound=False

        for loglalias in self._loglaliases:

            if loglalias in common_output_table_header:
                try:
                    self._logL=self._posterior[loglalias].samples
                except KeyError:
875
                    print("No '%s' column in input table!"%loglalias)
876 877 878 879 880 881 882 883 884 885 886 887
                    continue
                logLFound=True

        if not logLFound:
            raise RuntimeError("No likelihood/posterior values found!")
        self._logP=None

        for logpalias in self._logpaliases:
            if logpalias in common_output_table_header:
                try:
                    self._logP=self._posterior[logpalias].samples
                except KeyError:
888
                    print("No '%s' column in input table!"%logpalias)
889 890
                    continue
                if not 'log' in logpalias:
891
                    self._logP=[np.log(i) for i in self._logP]
892 893 894 895 896 897 898 899 900 901

        if name is not None:
            self.__name=name

        if description is not None:
            self.__description=description

        return

    def extend_posterior(self):
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
        """
        Add some usefule derived parameters (such as tilt angles, time delays, etc) in the Posterior object
        """
        injection=self._injection
        pos=self
        # Generate component mass posterior samples (if they didnt exist already)
        if 'mc' in pos.names:
            mchirp_name = 'mc'
        elif 'chirpmass' in pos.names:
            mchirp_name = 'chirpmass'
        else:
            mchirp_name = 'mchirp'

        if 'asym_massratio' in pos.names:
            q_name = 'asym_massratio'
        else:
            q_name = 'q'

        if 'sym_massratio' in pos.names:
            eta_name= 'sym_massratio'
        elif 'massratio' in pos.names:
            eta_name= 'massratio'
        else:
            eta_name='eta'

        if 'mass1' in pos.names and 'mass2' in pos.names:
            pos.append_mapping(('m1','m2'), lambda x,y:(x,y), ('mass1','mass2'))

        if (mchirp_name in pos.names and eta_name in pos.names) and \
        ('mass1' not in pos.names or 'm1' not in pos.names) and \
        ('mass2' not in pos.names or 'm2' not in pos.names):

            pos.append_mapping(('m1','m2'),mc2ms,(mchirp_name,eta_name))

        if (mchirp_name in pos.names and q_name in pos.names) and \
        ('mass1' not in pos.names or 'm1' not in pos.names) and \
        ('mass2' not in pos.names or 'm2' not in pos.names):

            pos.append_mapping(('m1','m2'),q2ms,(mchirp_name,q_name))
941
            pos.append_mapping('eta',q2eta,q_name)
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991

        if ('m1' in pos.names and 'm2' in pos.names and not 'mtotal' in pos.names ):
            pos.append_mapping('mtotal', lambda m1,m2: m1+m2, ('m1','m2') )

        if('a_spin1' in pos.names): pos.append_mapping('a1',lambda a:a,'a_spin1')
        if('a_spin2' in pos.names): pos.append_mapping('a2',lambda a:a,'a_spin2')
        if('phi_spin1' in pos.names): pos.append_mapping('phi1',lambda a:a,'phi_spin1')
        if('phi_spin2' in pos.names): pos.append_mapping('phi2',lambda a:a,'phi_spin2')
        if('theta_spin1' in pos.names): pos.append_mapping('theta1',lambda a:a,'theta_spin1')
        if('theta_spin2' in pos.names): pos.append_mapping('theta2',lambda a:a,'theta_spin2')

        my_ifos=['h1','l1','v1']
        for ifo1,ifo2 in combinations(my_ifos,2):
            p1=ifo1+'_cplx_snr_arg'
            p2=ifo2+'_cplx_snr_arg'
            if p1 in pos.names and p2 in pos.names:
                delta=np.mod(pos[p1].samples - pos[p2].samples + np.pi ,2.0*np.pi)-np.pi
                pos.append(PosteriorOneDPDF(ifo1+ifo2+'_relative_phase',delta))

        # Ensure that both theta_jn and inclination are output for runs
        # with zero tilt (for runs with tilt, this will be taken care of
        # below when the old spin angles are computed as functions of the
        # new ones
        # Disabled this since the parameters are degenerate and causing problems
        #if ('theta_jn' in pos.names) and (not 'tilt1' in pos.names) and (not 'tilt2' in pos.names):
        #    pos.append_mapping('iota', lambda t:t, 'theta_jn')

        # Compute time delays from sky position
        try:
            if ('ra' in pos.names or 'rightascension' in pos.names) \
            and ('declination' in pos.names or 'dec' in pos.names) \
            and 'time' in pos.names:
                from lal import ComputeDetAMResponse, GreenwichMeanSiderealTime, LIGOTimeGPS, TimeDelayFromEarthCenter
                import itertools
                from numpy import array
                detMap = {'H1': 'LHO_4k', 'H2': 'LHO_2k', 'L1': 'LLO_4k',
                        'G1': 'GEO_600', 'V1': 'VIRGO', 'T1': 'TAMA_300'}
                if 'ra' in pos.names:
                    ra_name='ra'
                else: ra_name='rightascension'
                if 'dec' in pos.names:
                    dec_name='dec'
                else: dec_name='declination'
                ifo_times={}
                my_ifos=['H1','L1','V1']
                for ifo in my_ifos:
                    inj_time=None
                    if injection:
                        inj_time=float(injection.get_end(ifo[0]))
                    location = lal.cached_detector_by_prefix[ifo].location
992
                    ifo_times[ifo]=array(list(map(lambda ra,dec,time: array([time[0]+TimeDelayFromEarthCenter(location,ra[0],dec[0],LIGOTimeGPS(float(time[0])))]), pos[ra_name].samples,pos[dec_name].samples,pos['time'].samples)))
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
                    loc_end_time=PosteriorOneDPDF(ifo.lower()+'_end_time',ifo_times[ifo],injected_value=inj_time)
                    pos.append(loc_end_time)
                for ifo1 in my_ifos:
                    for ifo2 in my_ifos:
                        if ifo1==ifo2: continue
                        delay_time=ifo_times[ifo2]-ifo_times[ifo1]
                        if injection:
                            inj_delay=float(injection.get_end(ifo2[0])-injection.get_end(ifo1[0]))
                        else:
                            inj_delay=None
                        time_delay=PosteriorOneDPDF(ifo1.lower()+ifo2.lower()+'_delay',delay_time,inj_delay)
                        pos.append(time_delay)
        except ImportError:
            print('Warning: Could not import lal python bindings, check you ./configured with --enable-swig-python')
            print('This means I cannot calculate time delays')

        #Calculate new spin angles
        new_spin_params = ['tilt1','tilt2','theta_jn','beta']
        if not set(new_spin_params).issubset(set(pos.names)):
            old_params = ['f_ref',mchirp_name,'eta','iota','a1','theta1','phi1']
            if 'a2' in pos.names: old_params += ['a2','theta2','phi2']
            try:
                pos.append_mapping(new_spin_params, spin_angles, old_params)
            except KeyError:
                print("Warning: Cannot find spin parameters.  Skipping spin angle calculations.")

        #Store signed spin magnitudes in separate parameters and make a1,a2 magnitudes
        if 'a1' in pos.names:
            if 'tilt1' in pos.names:
                pos.append_mapping('a1z', lambda a, tilt: a*np.cos(tilt), ('a1','tilt1'))
            else:
                pos.append_mapping('a1z', lambda x: x, 'a1')
                inj_az = None
                if injection is not None:
                    inj_az = injection.spin1z
                pos['a1z'].set_injval(inj_az)
                pos.pop('a1')
                pos.append_mapping('a1', lambda x: np.abs(x), 'a1z')

        if 'a2' in pos.names:
            if 'tilt2' in pos.names:
                pos.append_mapping('a2z', lambda a, tilt: a*np.cos(tilt), ('a2','tilt2'))
            else:
                pos.append_mapping('a2z', lambda x: x, 'a2')
                inj_az = None
                if injection is not None:
                    inj_az = injection.spin2z
                pos['a2z'].set_injval(inj_az)
                pos.pop('a2')
                pos.append_mapping('a2', lambda x: np.abs(x), 'a2z')

        #Calculate effective spin parallel to L
        if ('m1' in pos.names and 'a1z' in pos.names) and ('m2' in pos.names and 'a2z' in pos.names):
            pos.append_mapping('chi_eff', lambda m1,a1z,m2,a2z: (m1*a1z + m2*a2z) / (m1 + m2), ('m1','a1z','m2','a2z'))

        #If precessing spins calculate total effective spin
        if ('m1' in pos.names and 'a1' in pos.names and 'tilt1' in pos.names) and ('m2' in pos.names and 'a2' in pos.names and 'tilt2' in pos.names):
            pos.append_mapping('chi_tot', lambda m1,a1,m2,a2: (m1*a1 + m2*a2) / (m1 + m2), ('m1','a1','m2','a2'))

        #Calculate effective precessing spin magnitude
        if ('m1' in pos.names and 'a1' in pos.names and 'tilt1' in pos.names) and ('m2' in pos.names and 'a2' in pos.names and 'tilt2' in pos.names):
            pos.append_mapping('chi_p', chi_precessing, ['m1', 'a1', 'tilt1', 'm2', 'a2', 'tilt2'])

        # Calculate redshift from luminosity distance measurements
        if('distance' in pos.names):
            pos.append_mapping('redshift', calculate_redshift, 'distance')
1059 1060
        elif('dist' in pos.names):
            pos.append_mapping('redshift', calculate_redshift, 'dist')
1061 1062 1063
        # If using the DistanceMarginalisation, compute the maxL redshift distribution from the maxL d_L
        elif('distance_maxl' in pos.names):
            pos.append_mapping('redshift_maxldist', calculate_redshift, 'distance_maxl')
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077

        # Calculate source mass parameters
        if ('m1' in pos.names) and ('redshift' in pos.names):
            pos.append_mapping('m1_source', source_mass, ['m1', 'redshift'])

        if ('m2' in pos.names) and ('redshift' in pos.names):
            pos.append_mapping('m2_source', source_mass, ['m2', 'redshift'])

        if ('mtotal' in pos.names) and ('redshift' in pos.names):
            pos.append_mapping('mtotal_source', source_mass, ['mtotal', 'redshift'])

        if ('mc' in pos.names) and ('redshift' in pos.names):
            pos.append_mapping('mc_source', source_mass, ['mc', 'redshift'])

1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
        # Calculate source mass parameters if DistanceMarginalisation was used, using the maxL distance and redshift
        if ('m1' in pos.names) and ('redshift_maxldist' in pos.names):
            pos.append_mapping('m1_source_maxldist', source_mass, ['m1', 'redshift_maxldist'])

        if ('m2' in pos.names) and ('redshift_maxldist' in pos.names):
            pos.append_mapping('m2_source_maxldist', source_mass, ['m2', 'redshift_maxldist'])

        if ('mtotal' in pos.names) and ('redshift_maxldist' in pos.names):
            pos.append_mapping('mtotal_source_maxldist', source_mass, ['mtotal', 'redshift_maxldist'])

        if ('mc' in pos.names) and ('redshift_maxldist' in pos.names):
            pos.append_mapping('mc_source_maxldist', source_mass, ['mc', 'redshift_maxldist'])

1091 1092
        #Calculate new tidal parameters
        new_tidal_params = ['lam_tilde','dlam_tilde']
1093
        old_tidal_params = ['lambda1','lambda2','q']
1094 1095 1096 1097 1098 1099 1100 1101
        if 'lambda1' in pos.names or 'lambda2' in pos.names:
            try:
                pos.append_mapping(new_tidal_params, symm_tidal_params, old_tidal_params)
            except KeyError:
                print("Warning: Cannot find tidal parameters.  Skipping tidal calculations.")

        #If new spin params present, calculate old ones
        old_spin_params = ['iota', 'theta1', 'phi1', 'theta2', 'phi2', 'beta']
Salvatore Vitale's avatar
Salvatore Vitale committed
1102
        new_spin_params = ['theta_jn', 'phi_jl', 'tilt1', 'tilt2', 'phi12', 'a1', 'a2', 'm1', 'm2', 'f_ref','phase']
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
        try:
            if pos['f_ref'].samples[0][0]==0.0:
                for name in ['flow','f_lower']:
                    if name in pos.names:
                        new_spin_params = ['theta_jn', 'phi_jl', 'tilt1', 'tilt2', 'phi12', 'a1', 'a2', 'm1', 'm2', name]
        except:
            print("No f_ref for SimInspiralTransformPrecessingNewInitialConditions().")
        if set(new_spin_params).issubset(set(pos.names)) and not set(old_spin_params).issubset(set(pos.names)):
            pos.append_mapping(old_spin_params, physical2radiationFrame, new_spin_params)

        #Calculate spin magnitudes for aligned runs
        if 'spin1' in pos.names:
            inj_a1 = inj_a2 = None
            if injection:
                inj_a1 = sqrt(injection.spin1x*injection.spin1x + injection.spin1y*injection.spin1y + injection.spin1z*injection.spin1z)
                inj_a2 = sqrt(injection.spin2x*injection.spin2x + injection.spin2y*injection.spin2y + injection.spin2z*injection.spin2z)

            try:
                a1_samps = abs(pos['spin1'].samples)
                a1_pos = PosteriorOneDPDF('a1',a1_samps,injected_value=inj_a1)
                pos.append(a1_pos)
            except KeyError:
                print("Warning: problem accessing spin1 values.")

            try:
                a2_samps = abs(pos['spin2'].samples)
                a2_pos = PosteriorOneDPDF('a2',a2_samps,injected_value=inj_a2)
                pos.append(a2_pos)
            except KeyError:
                print("Warning: no spin2 values found.")

        # Calculate mass and spin of final merged system
        if ('m1' in pos.names) and ('m2' in pos.names):
            if ('tilt1' in pos.names) or ('tilt2' in pos.names):
                print("A precessing fit formula is not available yet. Using a non-precessing fit formula on the aligned-spin components.")
            if ('a1z' in pos.names) and ('a2z' in pos.names):
                print("Using non-precessing fit formula [Healy at al (2014)] for final mass and spin (on masses and projected spin components).")
                try:
                    pos.append_mapping('af', bbh_final_spin_non_precessing_Healyetal, ['m1', 'm2', 'a1z', 'a2z'])
                    pos.append_mapping('mf', lambda m1, m2, chi1z, chi2z, chif: bbh_final_mass_non_precessing_Healyetal(m1, m2, chi1z, chi2z, chif=chif), ['m1', 'm2', 'a1z', 'a2z', 'af'])
                except Exception as e:
                    print("Could not calculate final parameters. The error was: %s"%(str(e)))
            elif ('a1' in pos.names) and ('a2' in pos.names):
                if ('tilt1' in pos.names) and ('tilt2' in pos.names):
                    print("Projecting spin and using non-precessing fit formula [Healy at al (2014)] for final mass and spin.")
                    try:
                        pos.append_mapping('af', bbh_final_spin_projected_spin_Healyetal, ['m1', 'm2', 'a1', 'a2', 'tilt1', 'tilt2'])
                        pos.append_mapping('mf', bbh_final_mass_projected_spin_Healyetal, ['m1', 'm2', 'a1', 'a2', 'tilt1', 'tilt2', 'af'])
                    except Exception as e:
                        print("Could not calculate final parameters. The error was: %s"%(str(e)))
                else:
                    print("Using non-precessing fit formula [Healy at al (2014)] for final mass and spin (on masses and spin magnitudes).")
                    try:
                        pos.append_mapping('af', bbh_final_spin_non_precessing_Healyetal, ['m1', 'm2', 'a1', 'a2'])
                        pos.append_mapping('mf', lambda m1, m2, chi1, chi2, chif: bbh_final_mass_non_precessing_Healyetal(m1, m2, chi1, chi2, chif=chif), ['m1', 'm2', 'a1', 'a2', 'af'])
                    except Exception as e:
                        print("Could not calculate final parameters. The error was: %s"%(str(e)))
            else:
                print("Using non-spinning fit formula [Pan at al (2010)] for final mass and spin.")
                try:
                    pos.append_mapping('af', bbh_final_spin_non_spinning_Panetal, ['m1', 'm2'])
                    pos.append_mapping('mf', bbh_final_mass_non_spinning_Panetal, ['m1', 'm2'])
                except Exception as e:
                    print("Could not calculate final parameters. The error was: %s"%(str(e)))
        if ('mf' in pos.names) and ('redshift' in pos.names):
            try:
                pos.append_mapping('mf_source', source_mass, ['mf', 'redshift'])
            except Exception as e:
                print("Could not calculate final source frame mass. The error was: %s"%(str(e)))

1173 1174 1175 1176 1177 1178
        if ('mf' in pos.names) and ('redshift_maxldist' in pos.names):
            try:
                pos.append_mapping('mf_source_maxldist', source_mass, ['mf', 'redshift_maxldist'])
            except Exception as e:
                print("Could not calculate final source frame mass. The error was: %s"%(str(e)))

1179 1180 1181 1182 1183 1184 1185
        # Calculate radiated energy and peak luminosity
        if ('mtotal_source' in pos.names) and ('mf_source' in pos.names):
            try:
                pos.append_mapping('e_rad', lambda mtot_s, mf_s: mtot_s-mf_s, ['mtotal_source', 'mf_source'])
            except Exception as e:
                print("Could not calculate radiated energy. The error was: %s"%(str(e)))

1186 1187 1188 1189 1190 1191
        if ('mtotal_source_maxldist' in pos.names) and ('mf_source_maxldist' in pos.names):
            try:
                pos.append_mapping('e_rad_maxldist', lambda mtot_s, mf_s: mtot_s-mf_s, ['mtotal_source_maxldist', 'mf_source_maxldist'])
            except Exception as e:
                print("Could not calculate radiated energy. The error was: %s"%(str(e)))

1192 1193 1194 1195 1196
        if ('q' in pos.names) and ('a1z' in pos.names) and ('a2z' in pos.names):
            try:
                pos.append_mapping('l_peak', bbh_aligned_Lpeak_6mode_SHXJDK, ['q', 'a1z', 'a2z'])
            except Exception as e:
                print("Could not calculate peak luminosity. The error was: %s"%(str(e)))
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248

    def bootstrap(self):
        """
        Returns a new Posterior object that contains a bootstrap
        sample of self.

        """
        names=[]
        samples=[]
        for name,oneDpos in self._posterior.items():
            names.append(name)
            samples.append(oneDpos.samples)

        samplesBlock=np.hstack(samples)

        bootstrapSamples=samplesBlock[:,:]
        Nsamp=bootstrapSamples.shape[0]

        rows=np.vsplit(samplesBlock,Nsamp)

        for i in range(Nsamp):
            bootstrapSamples[i,:]=random.choice(rows)

        return Posterior((names,bootstrapSamples),self._injection,self._triggers)

    def delete_samples_by_idx(self,samples):
        """
        Remove samples from all OneDPosteriors.

        @param samples: The indexes of the samples to be removed.
        """
        for name,pos in self:
            pos.delete_samples_by_idx(samples)
        return

    def delete_NaN_entries(self,param_list):
        """
        Remove samples containing NaN in request params.

        @param param_list: The parameters to be checked for NaNs.
        """
        nan_idxs = np.array(())
        nan_dict = {}
        for param in param_list:
            nan_bool_array = np.isnan(self[param].samples).any(1)
            idxs = np.where(nan_bool_array == True)[0]
            if len(idxs) > 0:
                nan_dict[param]=len(idxs)
                nan_idxs = np.append(nan_idxs, idxs)
        total_samps = len(self)
        nan_samps   = len(nan_idxs)
        if nan_samps is not 0:
1249
            print("WARNING: removing %i of %i total samples due to NaNs:"% (nan_samps,total_samps))
1250
            for param in nan_dict.keys():
1251
                print("\t%i NaNs in %s."%(nan_dict[param],param))
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
            self.delete_samples_by_idx(nan_idxs)
        return

    @property
    def DIC(self):
        """Returns the Deviance Information Criterion estimated from the
        posterior samples.  The DIC is defined as -2*(<log(L)> -
        Var(log(L))); smaller values are "better."

        """

        return -2.0*(np.mean(self._logL) - np.var(self._logL))

    @property
    def injection(self):
        """
        Return the injected values.

        """

        return self._injection

    @property
    def triggers(self):
        """
        Return the trigger values .

        """

        return self._triggers

    def _total_incl_restarts(self, samples):
        total=0
        last=samples[0]
        for x in samples[1:]:
            if x < last:
                total += last
            last = x
        total += samples[-1]
        return total

    def longest_chain_cycles(self):
        """
        Returns the number of cycles in the longest chain

        """
        samps,header=self.samples()
        header=header.split()
        if not ('cycle' in header):
            raise RuntimeError("Cannot compute number of cycles in longest chain")

        cycle_col=header.index('cycle')
        if 'chain' in header:
            chain_col=header.index('chain')
            chain_indexes=np.unique(samps[:,chain_col])
            max_cycle=0
            for ind in chain_indexes:
                chain_cycle_samps=samps[ samps[:,chain_col] == ind, cycle_col ]
                max_cycle=max(max_cycle, self._total_incl_restarts(chain_cycle_samps))
            return int(max_cycle)
        else:
            return int(self._total_incl_restarts(samps[:,cycle_col]))

    #@injection.setter #Python 2.6+
    def set_injection(self,injection):
        """
        Set the injected values of the parameters.

        @param injection: A SimInspiralTable row object containing the injected parameters.
        """
        if injection is not None:
            self._injection=injection
            for name,onepos in self:
                new_injval=self._getinjpar(name)
                if new_injval is not None:
                    self[name].set_injval(new_injval)

    def set_triggers(self,triggers):
        """
        Set the trigger values of the parameters.

        @param triggers: A list of SnglInspiral objects.
        """
        if triggers is not None:
            self._triggers=triggers
            for name,onepos in self:
                new_trigvals=self._gettrigpar(name)
                if new_trigvals is not None:
                    self[name].set_trigvals(new_trigvals)


    def _getinjpar(self,paramname):
        """
        Map parameter names to parameters in a SimInspiralTable .
        """
        if self._injection is not None:
            for key,value in self._injXMLFuncMap.items():
                if paramname.lower().strip() == key.lower().strip():
                    try:
                        return self._injXMLFuncMap[key](self._injection)
                    except TypeError:
                        return self._injXMLFuncMap[key]
        return None

    def _gettrigpar(self,paramname):
        """
        Map parameter names to parameters in a SnglInspiral.
        """
        vals = None
        if self._triggers is not None:
            for key,value in self._injXMLFuncMap.items():
                if paramname.lower().strip() == key.lower().strip():
                    try:
                        vals = dict([(trig.ifo,self._injXMLFuncMap[key](trig)) for trig in self._triggers])
                    except TypeError:
                        return self._injXMLFuncMap[key]
                    except AttributeError:
                        return None
        return vals

    def __getitem__(self,key):
        """
        Container method . Returns posterior chain,one_d_pos, with name one_d_pos.name.
        """
        return self._posterior[key.lower()]

    def __len__(self):
        """
        Container method. Defined as number of samples.
        """
        return len(self._logL)

    def __iter__(self):
        """
        Container method. Returns iterator from self.forward for use in
        for (...) in (...) etc.
        """
        return self.forward()

    def forward(self):
        """
        Generate a forward iterator (in sense of list of names) over Posterior
        with name,one_d_pos.
        """
        current_item = 0
        while current_item < self.dim:
1398
            name=list(self._posterior.keys())[current_item]
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
            pos=self._posterior[name]
            current_item += 1
            yield name,pos

    def bySample(self):
        """
        Generate a forward iterator over the list of samples corresponding to
        the data stored within the Posterior instance. These are returned as
        ParameterSamples instances.
        """
        current_item=0
        pos_array,header=self.samples
        while current_item < len(self):
            sample_array=(np.squeeze(pos_array[current_item,:]))
            yield PosteriorSample(sample_array, header, header)
            current_item += 1


    @property
    def dim(self):
        """
        Return number of parameters.
        """
        return len(self._posterior.keys())

    @property
    def names(self):
        """
        Return list of parameter names.
        """
        nameslist=[]
        for key,value in self:
            nameslist.append(key)
        return nameslist

    @property
    def means(self):
        """
        Return dict {paramName:paramMean} .
        """
        meansdict={}
        for name,pos in self:
            meansdict[name]=pos.mean
        return meansdict

    @property
    def medians(self):
        """
        Return dict {paramName:paramMedian} .
        """
        mediansdict={}
        for name,pos in self:
            mediansdict[name]=pos.median
        return mediansdict

    @property
    def stdevs(self):
        """
        Return dict {paramName:paramStandardDeviation} .
        """
        stdsdict={}
        for name,pos in self:
            stdsdict[name]=pos.stdev
        return stdsdict

    @property
    def name(self):
        """
        Return qualified string containing the 'name' of the Posterior instance.
        """
        return self.__name

    @property
    def description(self):
        """
        Return qualified string containing a 'description' of the Posterior instance.
        """
        return self.__description

    def append(self,one_d_posterior):
        """
        Container method. Add a new OneDParameter to the Posterior instance.
        """
        self._posterior[one_d_posterior.name]=one_d_posterior
        return

    def pop(self,param_name):
        """
        Container method.  Remove PosteriorOneDPDF from the Posterior instance.
        """
        return self._posterior.pop(param_name)

    def append_mapping(self, new_param_names, func, post_names):
        """
        Append posteriors pos1,pos2,...=func(post_names)
        """
        # deepcopy 1D posteriors to ensure mapping function doesn't modify the originals
        import copy
        #1D input
        if isinstance(post_names, str):
            old_post = copy.deepcopy(self[post_names])
            old_inj  = old_post.injval
            old_trigs  = old_post.trigvals
            if old_inj:
                new_inj = func(old_inj)
            else:
                new_inj = None
            if old_trigs:
                new_trigs = {}
                for IFO in old_trigs.keys():
                    new_trigs[IFO] = func(old_trigs[IFO])
            else:
                new_trigs = None

            samps = func(old_post.samples)
            new_post = PosteriorOneDPDF(new_param_names, samps, injected_value=new_inj, trigger_values=new_trigs)
            if new_post.samples.ndim is 0:
1516
                print("WARNING: No posterior calculated for %s ..." % post.name)
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
            else:
                self.append(new_post)
        #MultiD input
        else:
            old_posts = [copy.deepcopy(self[post_name]) for post_name in post_names]
            old_injs = [post.injval for post in old_posts]
            old_trigs = [post.trigvals for post in old_posts]
            samps = func(*[post.samples for post in old_posts])
            #1D output
            if isinstance(new_param_names, str):
                if None not in old_injs:
                    inj = func(*old_injs)
                else:
                    inj = None
                if None not in old_trigs:
                    new_trigs = {}
                    for IFO in old_trigs[0].keys():
                        oldvals = [param[IFO] for param in old_trigs]
                        new_trigs[IFO] = func(*oldvals)
                else:
                    new_trigs = None
                new_post = PosteriorOneDPDF(new_param_names, samps, injected_value=inj, trigger_values=new_trigs)
                self.append(new_post)
            #MultiD output
            else:
                if None not in old_injs:
                    injs = func(*old_injs)
                else:
                    injs = [None for name in new_param_names]
                if None not in old_trigs:
                    new_trigs = [{} for param in range(len(new_param_names))]
                    for IFO in old_trigs[0].keys():
                        oldvals = [param[IFO] for param in old_trigs]
                        newvals = func(*oldvals)
                        for param,newval in enumerate(newvals):
                            new_trigs[param][IFO] = newval
                else:
                    new_trigs = [None for param in range(len(new_param_names))]
                if not samps: return() # Something went wrong
                new_posts = [PosteriorOneDPDF(new_param_name,samp,injected_value=inj,trigger_values=new_trigs) for (new_param_name,samp,inj,new_trigs) in zip(new_param_names,samps,injs,new_trigs)]
                for post in new_posts:
                    if post.samples.ndim is 0:
1559
                        print("WARNING: No posterior calculated for %s ..." % post.name)
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
                    else:
                        self.append(post)
        return

    def _average_posterior(self, samples, post_name):
        """
        Returns the average value of the 'post_name' column of the
        given samples.
        """
        ap = 0.0
        for samp in samples:
            ap = ap + samp[post_name]
        return ap / len(samples)

    def _average_posterior_like_prior(self, samples, logl_name, prior_name, log_bias = 0):
        """
        Returns the average value of the posterior assuming that the
        'logl_name' column contains log(L) and the 'prior_name' column
        contains the prior (un-logged).
        """
        ap = 0.0
        for samp in samples:
            ap += np.exp(samp[logl_name]-log_bias)*samp[prior_name]
        return ap / len(samples)

    def _bias_factor(self):
        """
        Returns a sensible bias factor for the evidence so that
        integrals are representable as doubles.
        """
        return np.mean(self._logL)

    def di_evidence(self, boxing=64):
        """
        Returns the log of the direct-integration evidence for the
        posterior samples.
        """
        allowed_coord_names=["spin1", "spin2", "a1", "phi1", "theta1", "a2", "phi2", "theta2",
                             "iota", "psi", "ra", "dec",
                             "phi_orb", "phi0", "dist", "time", "mc", "mchirp", "chirpmass", "q"]
        samples,header=self.samples()
        header=header.split()
        coord_names=[name for name in allowed_coord_names if name in header]
        coordinatized_samples=[PosteriorSample(row, header, coord_names) for row in samples]
        tree=KDTree(coordinatized_samples)

        if "prior" in header and "logl" in header:
            bf = self._bias_factor()
            return bf + np.log(tree.integrate(lambda samps: self._average_posterior_like_prior(samps, "logl", "prior", bf), boxing))
        elif "prior" in header and "likelihood" in header:
            bf = self._bias_factor()
            return bf + np.log(tree.integrate(lambda samps: self._average_posterior_like_prior(samps, "likelihood", "prior", bf), boxing))
        elif "post" in header:
            return np.log(tree.integrate(lambda samps: self._average_posterior(samps, "post"), boxing))
        elif "posterior" in header:
            return np.log(tree.integrate(lambda samps: self._average_posterior(samps, "posterior"), boxing))
        else:
            raise RuntimeError("could not find 'post', 'posterior', 'logl' and 'prior', or 'likelihood' and 'prior' columns in output to compute direct integration evidence")

    def elliptical_subregion_evidence(self):
        """Returns an approximation to the log(evidence) obtained by
        fitting an ellipse around the highest-posterior samples and
        performing the harmonic mean approximation within the ellipse.
        Because the ellipse should be well-sampled, this provides a
        better approximation to the evidence than the full-domain HM."""
        allowed_coord_names=["spin1", "spin2", "a1", "phi1", "theta1", "a2", "phi2", "theta2",
                             "iota", "psi", "ra", "dec",
                             "phi_orb", "phi0", "dist", "time", "mc", "mchirp", "chirpmass", "q"]
        samples,header=self.samples()
        header=header.split()

        n=int(0.05*samples.shape[0])
        if not n > 1:
            raise IndexError

        coord_names=[name for name in allowed_coord_names if name in header]
        indexes=np.argsort(self._logL[:,0])

        my_samples=samples[indexes[-n:], :] # The highest posterior samples.
        my_samples=np.array([PosteriorSample(sample,header,coord_names).coord() for sample in my_samples])

        mu=np.mean(my_samples, axis=0)
        cov=np.cov(my_samples, rowvar=0)

        d0=None
        for mysample in my_samples:
            d=np.dot(mysample-mu, np.linalg.solve(cov, mysample-mu))
            if d0 is None:
                d0 = d
            else:
                d0=max(d0,d)

        ellipse_logl=[]
        ellipse_samples=[]
        for sample,logl in zip(samples, self._logL):
            coord=PosteriorSample(sample, header, coord_names).coord()
            d=np.dot(coord-mu, np.linalg.solve(cov, coord-mu))

            if d <= d0:
                ellipse_logl.append(logl)
                ellipse_samples.append(sample)

        if len(ellipse_samples) > 5*n:
1663
            print('WARNING: ellpise evidence region encloses significantly more samples than %d'%n)
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675

        ellipse_samples=np.array(ellipse_samples)
        ellipse_logl=np.array(ellipse_logl)

        ndim = len(coord_names)
        ellipse_volume=np.pi**(ndim/2.0)*d0**(ndim/2.0)/special.gamma(ndim/2.0+1)*np.sqrt(np.linalg.det(cov))

        try:
            prior_index=header.index('prior')
            pmu=np.mean(ellipse_samples[:,prior_index])
            pstd=np.std(ellipse_samples[:,prior_index])
            if pstd/pmu > 1.0:
1676
                print('WARNING: prior variation greater than 100\% over elliptical volume.')
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
            approx_prior_integral=ellipse_volume*pmu
        except KeyError:
            # Maybe prior = 1?
            approx_prior_integral=ellipse_volume

        ll_bias=np.mean(ellipse_logl)
        ellipse_logl = ellipse_logl - ll_bias

        return np.log(approx_prior_integral) - np.log(np.mean(1.0/np.exp(ellipse_logl))) + ll_bias

    def harmonic_mean_evidence(self):
        """
        Returns the log of the harmonic mean evidence for the set of
        posterior samples.
        """
        bf = self._bias_factor()
        return bf + np.log(1/np.mean(1/np.exp(self._logL-bf)))

    def _posMaxL(self):
        """
        Find the sample with maximum likelihood probability. Returns value
        of likelihood and index of sample .
        """
        logl_vals=self._logL
        max_i=0
        max_logl=logl_vals[0]
        for i in range(len(logl_vals)):
            if logl_vals[i] > max_logl:
                max_logl=logl_vals[i]
                max_i=i
        return max_logl,max_i

    def _posMap(self):
        """
        Find the sample with maximum a posteriori probability. Returns value
        of posterior and index of sample .
        """
        logl_vals=self._logL
        if self._logP is not None:
1716
            logp_vals=self._logP
1717
        else:
1718
            return None
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824

        max_i=0
        max_pos=logl_vals[0]+logp_vals[0]
        for i in range(len(logl_vals)):
            if logl_vals[i]+logp_vals[i] > max_pos:
                max_pos=logl_vals[i]+logp_vals[i]
                max_i=i
        return max_pos,max_i

    def _print_table_row(self,name,entries):
        """
        Print a html table row representation of

        name:item1,item2,item3,...
        """

        row_str='<tr><td>%s</td>'%name
        for entry in entries:
            row_str+='<td>%s</td>'%entry
        row_str+='</tr>'
        return row_str

    @property
    def maxL(self):
        """
        Return the maximum likelihood probability and the corresponding
        set of parameters.
        """
        maxLvals={}
        max_logl,max_i=self._posMaxL()
        for param_name in self.names:
            maxLvals[param_name]=self._posterior[param_name].samples[max_i][0]

        return (max_logl,maxLvals)

    @property
    def maxP(self):
        """
        Return the maximum a posteriori probability and the corresponding
        set of parameters.
        """
        maxPvals={}
        max_pos,max_i=self._posMap()
        for param_name in self.names:
            maxPvals[param_name]=self._posterior[param_name].samples[max_i][0]

        return (max_pos,maxPvals)


    def samples(self):
        """
        Return an (M,N) numpy.array of posterior samples; M = len(self);
        N = dim(self) .
        """
        header_string=''
        posterior_table=[]
        for param_name,one_pos in self:
            column=np.array(one_pos.samples)
            header_string+=param_name+'\t'
            posterior_table.append(column)
        posterior_table=tuple(posterior_table)
        return np.column_stack(posterior_table),header_string

    def write_to_file(self,fname):
        """
        Dump the posterior table to a file in the 'common format'.
        """
        column_list=()

        posterior_table,header_string=self.samples()

        fobj=open(fname,'w')

        fobj.write(header_string+'\n')
        np.savetxt(fobj,posterior_table,delimiter='\t')
        fobj.close()

        return

    def gelman_rubin(self, pname):
        """
        Returns an approximation to the Gelman-Rubin statistic (see
        Gelman, A. and Rubin, D. B., Statistical Science, Vol 7,
        No. 4, pp. 457--511 (1992)) for the parameter given, accurate
        as the number of samples in each chain goes to infinity.  The
        posterior samples must have a column named 'chain' so that the
        different chains can be separated.
        """
        from numpy import seterr as np_seterr
        np_seterr(all='raise')

        if "chain" in self.names:
            chains=np.unique(self["chain"].samples)
            chain_index=self.names.index("chain")
            param_index=self.names.index(pname)
            data,header=self.samples()
            chainData=[data[ data[:,chain_index] == chain, param_index] for chain in chains]
            allData=np.concatenate(chainData)
            chainMeans=[np.mean(data) for data in chainData]
            chainVars=[np.var(data) for data in chainData]
            BoverN=np.var(chainMeans)
            W=np.mean(chainVars)
            sigmaHat2=W + BoverN
            m=len(chainData)
            VHat=sigmaHat2 + BoverN/m
            try:
1825
                R = VHat/W
1826
            except:
1827 1828
                print("Error when computer Gelman-Rubin R statistic for %s.  This may be a fixed parameter"%pname)
                R = np.nan
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
            return R
        else:
            raise RuntimeError('could not find necessary column header "chain" in posterior samples')

    def healpix_map(self, resol, nest=True):
        """Returns a healpix map in the pixel ordering that represents the
        posterior density (per square degree) on the sky.  The pixels
        will be chosen to have at least the given resolution (in
        degrees).

        """

        # Ensure that the resolution is twice the desired
        nside = 2
        while hp.nside2resol(nside, arcmin=True) > resol*60.0/2.0:
            nside *= 2

        ras = self['ra'].samples.squeeze()
        decs = self['dec'].samples.squeeze()

        phis = ras
        thetas = np.pi/2.0 - decs

        # Create the map in ring ordering
        inds = hp.ang2pix(nside, thetas, phis, nest=False)
        counts = np.bincount(inds)
        if counts.shape[0] < hp.nside2npix(nside):
            counts = np.concatenate((counts, np.zeros(hp.nside2npix(nside) - counts.shape[0])))

        # Smooth the map a bit (Gaussian sigma = resol)
        hpmap = hp.sphtfunc.smoothing(counts, sigma=resol*np.pi/180.0)

        hpmap = hpmap / (np.sum(hpmap)*hp.nside2pixarea(nside, degrees=True))

        if nest:
            hpmap = hp.reorder(hpmap, r2n=True)

        return hpmap

    def __str__(self):
        """
        Define a string representation of the Posterior class ; returns
        a html formatted table of various properties of posteriors.
        """
        return_val='<table border="1" id="statstable"><tr><th/>'
        column_names=['maP','maxL','stdev','mean','median','stacc','injection value']
        IFOs = []
        if self._triggers is not None:
            IFOs = [trig.ifo for trig in self._triggers]
            for IFO in IFOs:
                column_names.append(IFO+' trigger values')

        for column_name in column_names:
            return_val+='<th>%s</th>'%column_name

        return_val+='</tr>'

        for name,oned_pos in self:

            max_logl,max_i=self._posMaxL()
            maxL=oned_pos.samples[max_i][0]
            max_post,max_j=self._posMap()
            maP=oned_pos.samples[max_j][0]
            mean=str(oned_pos.mean)
            stdev=str(oned_pos.stdev)
            median=str(np.squeeze(oned_pos.median))
            stacc=str(oned_pos.stacc)
            injval=str(oned_pos.injval)
            trigvals=oned_pos.trigvals

            row = [maP,maxL,stdev,mean,median,stacc,injval]
            if self._triggers is not None:
                for IFO in IFOs:
                    try:
                        row.append(str(trigvals[IFO]))
                    except TypeError:
                        row.append(None)
            return_val+=self._print_table_row(name,row)

        return_val+='</table>'

        parser=XMLParser()
        parser.feed(return_val)
        Estr=parser.close()

        elem=Estr
        rough_string = tostring(elem, 'utf-8')
        reparsed = minidom.parseString(rough_string)
        return_val=reparsed.toprettyxml(indent="  ")
        return return_val[len('<?xml version="1.0" ?>')+1:]


    #===============================================================================
    # Functions used to parse injection structure.
    #===============================================================================
    def _inj_m1(self,inj):
        """
        Return the mapping of (mchirp,eta)->m1; m1>m2 i.e. return the greater of the mass
        components (m1) calculated from the chirp mass and the symmetric mass ratio.

        @param inj: a custom type with the attributes 'mchirp' and 'eta'.
        """
        (mass1,mass2)=mc2ms(inj.mchirp,inj.eta)
        return mass1

    def _inj_m2(self,inj):
        """
        Return the mapping of (mchirp,eta)->m2; m1>m2 i.e. return the lesser of the mass
        components (m2) calculated from the chirp mass and the symmetric mass ratio.

        @param inj: a custom type with the attributes 'mchirp' and 'eta'.
        """
        (mass1,mass2)=mc2ms(inj.mchirp,inj.eta)
        return mass2

    def _inj_q(self,inj):
        """
        Return the mapping of (mchirp,eta)->q; m1>m2 i.e. return the mass ratio q=m2/m1.

        @param inj: a custom type with the attributes 'mchirp' and 'eta'.
        """
        (mass1,mass2)=mc2ms(inj.mchirp,inj.eta)
        return mass2/mass1

    def _inj_longitude(self,inj):
        """
        Return the mapping of longitude found in inj to the interval [0,2*pi).

        @param inj: a custom type with the attribute 'longitude'.
        """
        if inj.longitude>2*pi_constant or inj.longitude<0.0:
            maplong=2*pi_constant*(((float(inj.longitude))/(2*pi_constant)) - floor(((float(inj.longitude))/(2*pi_constant))))
1961
            print("Warning: Injected longitude/ra (%s) is not within [0,2\pi)! Angles are assumed to be in radians so this will be mapped to [0,2\pi). Mapped value is: %s."%(str(inj.longitude),str(maplong)))
1962 1963 1964
            return maplong
        else:
            return inj.longitude
Salvatore Vitale's avatar
Salvatore Vitale committed
1965
        
1966
    def _inj_spins(self, inj, frame='OrbitalL'):
Salvatore Vitale's avatar
Salvatore Vitale committed
1967 1968 1969

        from lalsimulation import SimInspiralTransformPrecessingWvf2PE

1970 1971 1972 1973 1974 1975 1976 1977
        spins = {}
        f_ref = self._injFref

        if not inj:
            spins = {}

        else:
            axis = lalsim.SimInspiralGetFrameAxisFromString(frame)
Salvatore Vitale's avatar
Salvatore Vitale committed
1978 1979 1980 1981 1982 1983 1984 1985 1986
            s1x=inj.spin1x
            s1y=inj.spin1y
            s1z=inj.spin1z
            s2x=inj.spin2x
            s2y=inj.spin2y
            s2z=inj.spin2z
            iota=inj.inclination
            m1, m2 = inj.mass1, inj.mass2
            mc, eta = inj.mchirp, inj.eta
1987

Salvatore Vitale's avatar
Salvatore Vitale committed
1988 1989
            a1, theta1, phi1 = cart2sph(s1x, s1y, s1z)
            a2, theta2, phi2 = cart2sph(s2x, s2y, s2z)
1990

Salvatore Vitale's avatar
Salvatore Vitale committed
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
            spins = {'a1':a1, 'theta1':theta1, 'phi1':phi1,
                     'a2':a2, 'theta2':theta2, 'phi2':phi2,
                     'iota':iota}
            # If spins are aligned, save the sign of the z-component
            if inj.spin1x == inj.spin1y == inj.spin2x == inj.spin2y == 0.:
                spins['a1z'] = inj.spin1z
                spins['a2z'] = inj.spin2z

            L  = orbital_momentum(f_ref, m1,m2, iota)
            S1 = np.hstack((s1x, s1y, s1z))
            S2 = np.hstack((s2x, s2y, s2z))

            zhat = np.array([0., 0., 1.])
            aligned_comp_spin1 = array_dot(S1, zhat)
            aligned_comp_spin2 = array_dot(S2, zhat)
            chi = aligned_comp_spin1 + aligned_comp_spin2 + \
                  np.sqrt(1. - 4.*eta) * (aligned_comp_spin1 - aligned_comp_spin2)
            S1 *= m1**2
            S2 *= m2**2
            J = L + S1 + S2

            beta  = array_ang_sep(J, L)
            spins['beta'] = beta
            spins['spinchi'] = chi
Salvatore Vitale's avatar
Salvatore Vitale committed
2015 2016 2017 2018 2019 2020 2021
            # Huge caveat: SimInspiralTransformPrecessingWvf2PE assumes that the cartesian spins in the XML table  are given in the L frame, ie. in  a frame where L||z. While this is the default in inspinj these days, other possibilities exist.
            # Unfortunately, we don't have a function (AFIK), that transforms spins from an arbitrary  frame to an arbitrary frame, otherwise I'd have called it here to be sure we convert in the L frame. 
            # FIXME: add that function here if it ever gets written. For the moment just check
            if not frame=='OrbitalL':
                print("I cannot calculate the injected values of the spin angles unless frame is OrbitalL. Skipping...")
                return spins
            # m1 and m2 here are NOT in SI, but in Msun, this is not a typo.
Salvatore Vitale's avatar
Salvatore Vitale committed
2022 2023 2024 2025 2026 2027 2028
            theta_jn,phi_jl,tilt1,tilt2,phi12,chi1,chi2=SimInspiralTransformPrecessingWvf2PE(inj.inclination,inj.spin1x, inj.spin1y, inj.spin1z,inj.spin2x, inj.spin2y, inj.spin2z, m1, m2, f_ref, inj.coa_phase)
            spins['theta_jn']=theta_jn
            spins['phi12']=phi12
            spins['tilt1']=tilt1
            spins['tilt2']=tilt2
            spins['phi_jl']=phi_jl

Salvatore Vitale's avatar
Salvatore Vitale committed
2029 2030 2031
            """ 
            #If everything is all right, this function should give back the cartesian spins. Uncomment to check
            print("Inverting ")
Salvatore Vitale's avatar
Salvatore Vitale committed
2032 2033
            iota_back,a1x_back,a1y_back,a1z_back,a2x_back,a2y_back,a2z_back = \
    lalsim.SimInspiralTransformPrecessingNewInitialConditions(theta_jn,phi_jl,tilt1,tilt2,phi12,chi1,chi2,m1*lal.MSUN_SI,m2*lal.MSUN_SI,f_ref,inj.coa_phase)
Salvatore Vitale's avatar
Salvatore Vitale committed
2034 2035 2036 2037
            print(a1x_back,a1y_back,a1z_back)
            print(a2x_back,a2y_back,a2z_back)
            print(iota_back)
            """