29from __future__
import print_function, division
41 from scipy.integrate
import trapezoid, cumulative_trapezoid
44 from scipy.integrate
import trapz
as trapezoid, cumtrapz
as cumulative_trapezoid
46from scipy.interpolate
import interp1d
49 from scipy.special
import logsumexp
51 from scipy.misc
import logsumexp
54ARCSECTORAD =
float(
"4.8481368110953599358991410235794797595635330237270e-6")
55RADTOARCSEC =
float(
"206264.80624709635515647335733077861319665970087963")
56SECTORAD =
float(
"7.2722052166430399038487115353692196393452995355905e-5")
57RADTOSEC =
float(
"13750.987083139757010431557155385240879777313391975")
58RADTODEG =
float(
"57.295779513082320876798154814105170332405472466564")
59DEGTORAD =
float(
"1.7453292519943295769236907684886127134428718885417e-2")
60RADTOHRS =
float(
"3.8197186342054880584532103209403446888270314977710")
61HRSTORAD =
float(
"2.6179938779914943653855361527329190701643078328126e-1")
62PI =
float(
"3.1415926535897932384626433832795028841971693993751")
63TWOPI =
float(
"6.2831853071795864769252867665590057683943387987502")
64PIBYTWO =
float(
"1.5707963267948966192313216916397514420985846996876")
66SECPERJULYR =
float(
"31557600.0")
86 Convert radians to degrees, minutes, and seconds of arc.
92 arc = RADTODEG * np.fmod(np.fabs(rad), math.pi)
94 arc = (arc - d) * 60.0
97 if sign == -1
and d == 0:
98 return (sign * d, sign * m, sign * s)
100 return (sign * d, m, s)
106 Convert degrees, minutes, and seconds of arc to radians.
110 elif deg == 0.0
and (mins < 0.0
or sec < 0.0):
117 * (60.0 * (60.0 * np.fabs(deg) + np.fabs(mins)) + np.fabs(sec))
124 Convert degrees, minutes, and seconds of arc to degrees.
132 Convert radians to hours, minutes, and seconds of arc.
134 rad = np.fmod(rad, 2.0 * math.pi)
136 rad = rad + 2.0 * math.pi
139 arc = (arc - h) * 60.0
148 Convert hours, minutes, and seconds of arc to radians
155 sign * SECTORAD * (60.0 * (60.0 * np.fabs(hour) + np.fabs(mins)) + np.fabs(sec))
162 Return a formatted string of RA or DEC values
as
163 'hh:mm:ss.ssss' if RA,
or 'dd:mm:ss.ssss' if DEC.
168 elif abs(h_or_d) == 0:
169 if (m < 0.0)
or (s < 0.0):
172 h_or_d, m, s = abs(h_or_d), abs(m), abs(s)
174 return retstr +
"%.2d:%.2d:%.4f" % (h_or_d, m, s)
176 return retstr +
"%.2d:%.2d:0%.4f" % (h_or_d, m, s)
182 Convert an angle in radians to hours/degrees, minutes seconds
and output
183 it
as a string
in the format
'hh:mm:ss.ssss' if RA,
or 'dd:mm:ss.ssss' if DEC.
184 Whether to use hours
or degrees
is set by whether ra_or_dec
is 'RA' or 'DEC'
186 if ra_or_dec.upper() ==
"RA":
188 elif ra_or_dec.upper() ==
"DEC":
192 "Unrecognised option: Expected 'ra_or_dec' to be 'RA' or 'DEC'"
201 Given a string containing RA information as
202 'hh:mm:ss.ssss',
return the equivalent decimal
203 radians. Also deal
with cases where input
204 string
is just hh:mm,
or hh.
206 hms = ra_string.split(":")
214 print(
"Problem parsing RA string %s" % ra_string, file=sys.stderr)
221 Given a string containing DEC information as
222 'dd:mm:ss.ssss',
return the equivalent decimal
223 radians. Also deal
with cases where input string
226 dms = dec_string.split(":")
227 if "-" in dms[0]
and float(dms[0]) == 0.0:
239 print(
"Problem parsing DEC string %s" % dec_string, file=sys.stderr)
243def p_to_f(p, pd, pdd=None):
246 Convert period, period derivative
and period second
247 derivative to the equivalent frequency counterparts.
248 Will also convert
from f to p.
258 fdd = 2.0 * pd * pd / (p**3.0) - pdd / (p * p)
263def pferrs(porf, porferr, pdorfd=None, pdorfderr=None):
265 pferrs(porf, porferr, pdorfd=None, pdorfderr=
None):
266 Calculate the period
or frequency errors
and
267 the pdot
or fdot errors
from the opposite one.
270 return [1.0 / porf, porferr / porf**2.0]
272 forperr = porferr / porf**2.0
274 (4.0 * pdorfd**2.0 * porferr**2.0) / porf**6.0
275 + pdorfderr**2.0 / porf**4.0
277 [forp, fdorpd] =
p_to_f(porf, pdorfd)
279 return [forp, forperr, fdorpd, fdorpderr]
395 This class parses
a TEMPO(2)-style pulsar parameter file. If possible all parameters
396 are converted into SI units
and angles are
in radians. Epochs will be converted
from
397 MJD values into GPS times.
401 for line
in pf.readlines():
407 line = line.replace(
"D-",
"E-")
408 line = line.replace(
"D+",
"E+")
410 line = line.replace(
"d-",
"e-")
411 line = line.replace(
"d+",
"e+")
412 splitline = line.split()
415 key = splitline[0].upper()
418 setattr(self, key, splitline[1])
419 elif key
in float_keys:
421 setattr(self, key,
float(splitline[1]))
428 if splitline[2]
not in [
"0",
"1"]:
429 setattr(self, key +
"_ERR",
float(splitline[2]))
430 setattr(self, key +
"_FIT", 0)
432 if len(splitline) == 4:
433 if splitline[2] ==
"1":
434 setattr(self, key +
"_FIT", 1)
436 setattr(self, key +
"_FIT", 0)
437 setattr(self, key +
"_ERR",
float(splitline[3]))
440 if hasattr(self,
"RAJ"):
441 setattr(self,
"RA_RAD",
ra_to_rad(self.RAJ))
444 if hasattr(self,
"RAJ_ERR"):
445 setattr(self,
"RA_RAD_ERR",
hms_to_rad(0, 0, self.RAJ_ERR))
447 if hasattr(self,
"RAJ_FIT"):
448 setattr(self,
"RA_RAD_FIT", self[
"RAJ_FIT"])
449 if hasattr(self,
"DECJ"):
450 setattr(self,
"DEC_RAD",
dec_to_rad(self.DECJ))
453 if hasattr(self,
"DECJ_ERR"):
454 setattr(self,
"DEC_RAD_ERR",
dms_to_rad(0, 0, self.DECJ_ERR))
456 if hasattr(self,
"DECJ_FIT"):
457 setattr(self,
"DEC_RAD_FIT", self[
"DECJ_FIT"])
460 for pv
in [
"RA",
"DEC"]:
461 if hasattr(self,
"PM" + pv):
462 pmv = self[
"PM" + pv]
463 setattr(self,
"PM" + pv +
"_ORIGINAL", pmv)
465 self,
"PM" + pv, pmv * np.pi / (180.0 * 3600.0e3 * 365.25 * 86400.0)
468 if hasattr(self,
"PM" + pv +
"_ERR"):
469 pmve = self[
"PM" + pv +
"_ERR"]
471 self,
"PM" + pv +
"_ERR_ORIGINAL", pmv
476 pmve * np.pi / (180.0 * 3600.0e3 * 365.25 * 86400.0),
480 if hasattr(self,
"P"):
481 setattr(self,
"P0", self.P)
482 if hasattr(self,
"P0"):
483 setattr(self,
"F0", 1.0 / self.P0)
484 if hasattr(self,
"F0"):
485 setattr(self,
"P0", 1.0 / self.F0)
486 if hasattr(self,
"FB0"):
487 setattr(self,
"PB", (1.0 / self.FB0) / 86400.0)
488 if hasattr(self,
"P0_ERR"):
489 if hasattr(self,
"P1_ERR"):
490 f, ferr, fd, fderr =
pferrs(self.P0, self.P0_ERR, self.P1, self.P1_ERR)
491 setattr(self,
"F0_ERR", ferr)
492 setattr(self,
"F1", fd)
493 setattr(self,
"F1_ERR", fderr)
495 if hasattr(self,
"P1"):
499 ) =
p_to_f(self.P0, self.P1)
500 setattr(self,
"F0_ERR", self.P0_ERR / (self.P0 * self.P0))
501 setattr(self,
"F1", fd)
502 if hasattr(self,
"F0_ERR"):
503 if hasattr(self,
"F1_ERR"):
504 p, perr, pd, pderr =
pferrs(self.F0, self.F0_ERR, self.F1, self.F1_ERR)
505 setattr(self,
"P0_ERR", perr)
506 setattr(self,
"P1", pd)
507 setattr(self,
"P1_ERR", pderr)
509 if hasattr(self,
"F1"):
513 ) =
p_to_f(self.F0, self.F1)
514 setattr(self,
"P0_ERR", self.F0_ERR / (self.F0 * self.F0))
515 setattr(self,
"P1", pd)
519 from lalpulsar
import TTMJDtoGPS
530 if hasattr(self, epoch):
532 self, epoch +
"_ORIGINAL", self[epoch]
534 setattr(self, epoch, TTMJDtoGPS(self[epoch]))
540 self, epoch +
"_ERR_ORIGINAL", self[epoch +
"_ERR"]
542 setattr(self, epoch +
"_ERR", self[epoch +
"_ERR"] * SECPERDAY)
545 "Could not convert epochs to GPS times. They are all still MJD values.",
550 convfacs = {
"DIST": KPC,
"PX": 1e-3 * ARCSECTORAD}
551 for item
in convfacs:
552 if hasattr(self, item):
553 setattr(self, item +
"_ORIGINAL", self[item])
554 setattr(self, item, self[item] * convfacs[item])
556 if hasattr(self, item +
"_ERR"):
558 self, item +
"_ERR_ORIGINAL", self[item +
"_ERR"]
560 setattr(self, item +
"_ERR", self[item +
"_ERR"] * convfacs[item])
564 for om
in [
"OM",
"OM_2",
"OM_3",
"KIN",
"KOM"]:
565 if hasattr(self, om):
566 setattr(self, om, self[om] / RADTODEG)
568 if hasattr(self, om +
"_ERR"):
569 setattr(self, om +
"_ERR", self[om +
"_ERR"] / RADTODEG)
572 for pb
in [
"PB",
"PB_2",
"PB_3"]:
573 if hasattr(self, pb):
574 setattr(self, pb +
"_ORIGINAL", self[pb])
575 setattr(self, pb, self[pb] * SECPERDAY)
577 if hasattr(self, pb +
"_ERR"):
579 self, pb +
"_ERR_ORIGINAL", self[pb +
"_ERR"]
581 setattr(self, pb +
"_ERR", self[pb +
"_ERR"] * SECPERDAY)
584 if hasattr(self,
"OMDOT"):
585 setattr(self,
"OMDOT_ORIGINAL", self[
"OMDOT"])
586 setattr(self,
"OMDOT", self[
"OMDOT"] / (RADTODEG * 365.25 * SECPERDAY))
588 if hasattr(self,
"OMDOT_ERR"):
590 self,
"OMDOT_ERR_ORIGINAL", self[
"OMDOT_ERR"]
595 self[
"OMDOT_ERR"] / (RADTODEG * 365.25 * SECPERDAY),
598 if hasattr(self,
"EPS1")
and hasattr(self,
"EPS2"):
599 ecc = math.sqrt(self.EPS1 * self.EPS1 + self.EPS2 * self.EPS2)
600 omega = math.atan2(self.EPS1, self.EPS2)
601 setattr(self,
"E", ecc)
602 setattr(self,
"OM", omega)
603 setattr(self,
"T0", self.TASC + self.PB * omega / TWOPI)
606 and hasattr(self,
"A1")
607 and not (hasattr(self,
"E")
or hasattr(self,
"ECC"))
609 setattr(self,
"E", 0.0)
612 and not hasattr(self,
"TASC")
613 and hasattr(self,
"OM")
614 and hasattr(self,
"PB")
616 setattr(self,
"TASC", self.T0 - self.PB * self.OM / TWOPI)
619 for binu
in [
"XDOT",
"PBDOT",
"EDOT",
"EPS1DOT",
"EPS2DOT",
"XPBDOT"]:
620 if hasattr(self, binu):
621 setattr(self, binu +
"_ORIGINAL", self[binu])
622 if np.abs(self[binu]) > 1e-7:
623 setattr(self, binu, self[binu] * 1.0e-12)
626 if self[binu] > 10000.0:
627 setattr(self, binu, 0.0)
630 for mass
in [
"M2",
"MTOT"]:
631 if hasattr(self, mass):
632 setattr(self, mass +
"_ORIGINAL", self[mass])
633 setattr(self, mass, self[mass] * MSUN)
635 if hasattr(self, mass +
"_ERR"):
637 self, mass +
"_ERR_ORIGINAL", self[mass +
"_ERR"]
639 setattr(self, mass +
"_ERR", self[mass +
"_ERR"] * MSUN)
642 if hasattr(self,
"D_AOP"):
643 setattr(self,
"D_AOP_ORIGINAL", self[
"D_AOP"])
644 setattr(self,
"D_AOP", self[
"D_AOP"] * RADTODEG * 3600.0)
650 par = getattr(self, key)
658 for k, v
in self.__dict__.items():
660 if isinstance(self.__dict__[k], string_type):
661 out +=
"%10s = '%s'\n" % (k, v)
663 out +=
"%10s = %-20.15g\n" % (k, v)
672 pf = open(priorfilenm)
673 for line
in pf.readlines():
674 splitline = line.split()
677 key = splitline[0].upper()
681 setattr(self, key, [
float(splitline[2]),
float(splitline[3])])
682 elif key
in float_keys:
683 setattr(self, key, [
float(splitline[2]),
float(splitline[3])])
686 if hasattr(self,
"RA"):
691 setattr(self,
"RA_STR", [rastrl, rastru])
693 if hasattr(self,
"DEC"):
698 setattr(self,
"DEC_STR", [decstrl, decstru])
704 atr = getattr(self, key)
712 for k, v
in self.__dict__.items():
714 out +=
"%10s = %-20.15g, %-20.15g\n" % (k,
float(v[0]),
float(v[1]))
723 hsd = np.sqrt((5.0 / 2.0) * (G / C**3) * I38 * np.fabs(fdot) / freq) / (
733 ell = h0 * C**4.0 * dist * KPC / (16.0 * np.pi**2 * G * I38 * freq**2)
741 np.sqrt(15.0 / (8.0 * np.pi))
746 / (16.0 * np.pi**2 * G * freq**2)
756 * np.sqrt((8.0 * np.pi) / 15.0)
761 / (C**4.0 * dist * KPC)
770 chainlen = len(phipchain)
775 theta = math.atan2(1, 2)
779 for i
in range(0, chainlen):
780 phi0 = (1 / (2 * st)) * phipchain[i] - (1 / (2 * st)) * psipchain[i]
781 psi = (1 / (2 * ct)) * phipchain[i] + (1 / (2 * ct)) * psipchain[i]
784 if math.fabs(psi) > math.pi / 4.0:
786 phi0 = phi0 + math.pi
789 if psi > math.pi / 4.0:
790 psi = -(math.pi / 4.0) + math.fmod(psi + (math.pi / 4.0), math.pi / 2.0)
792 psi = (math.pi / 4.0) - math.fmod((math.pi / 4.0) - psi, math.pi / 2.0)
795 if phi0 > 2.0 * math.pi:
796 phi0 = math.fmod(phi0, 2.0 * math.pi)
798 phi0 = 2.0 * math.pi - math.fmod(2.0 * math.pi - phi0, 2.0 * math.pi)
800 phichain.append(phi0)
803 return phichain, psichain
813 parambounds=[float(
"-inf"),
float(
"inf")],
821 from matplotlib
import pyplot
as plt
835 "axes.linewidth": 0.5,
837 "grid.linewidth": 0.5,
838 "font.family":
"serif",
842 matplotlib.rcParams.update(mplparams)
845 coldict = {
"H1":
"r",
"H2":
"c",
"L1":
"g",
"V1":
"b",
"G1":
"m",
"Joint":
"k"}
849 paraxis = paramlatexdict[param.upper()]
859 parval = parfile[param.upper()]
866 for idx, ifo
in enumerate(ifos):
868 if overplot
and idx == 0:
869 myfig = plt.figure(figsize=(4, 4), dpi=200)
872 myfig = plt.figure(figsize=(4, 4), dpi=200)
876 pos_samps = pos[param].samples
880 pos_samps,
int(nbins), parambounds[0], parambounds[1]
884 plt.step(bins, n, color=coldict[ifo])
886 if "h0" not in param:
887 plt.xlim(parambounds[0], parambounds[1])
889 plt.xlabel(
r"" + paraxis, fontsize=14, fontweight=100)
890 plt.ylabel(
r"Probability Density", fontsize=14, fontweight=100)
891 myfig.subplots_adjust(left=0.18, bottom=0.15)
894 plt.ylim(0, n.max() + 0.1 * n.max())
898 ax.set_axis_bgcolor(
"#F2F1F0")
901 ymax.append(n.max() + 0.1 * n.max())
905 ct = cumulative_trapezoid(n, bins)
908 ct = np.insert(ct, 0, 0)
911 ctu, ui = np.unique(ct, return_index=
True)
912 intf = interp1d(ctu, bins[ui], kind=
"linear")
913 ulvals.append(intf(
float(upperlimit)))
919 plt.axvline(parval, color=
"k", ls=
"--", linewidth=1.5)
921 plt.axvline(parval, color=
"k", ls=
"--", linewidth=1.5)
924 plt.ylim(0,
max(ymax))
927 ax.set_axis_bgcolor(
"#F2F1F0")
931 return myfigs, ulvals
937 pos, upperlimit=0.95, parambounds=[float(
"-inf"),
float(
"inf")], nbins=50
946 ct = cumulative_trapezoid(n, bins)
949 ct = np.insert(ct, 0, 0)
952 ctu, ui = np.unique(ct, return_index=
True)
953 intf = interp1d(ctu, bins[ui], kind=
"linear")
954 ulval = intf(
float(upperlimit))
960 n, binedges = np.histogram(pos, bins=nbins)
961 dbins = binedges[1] - binedges[0]
967 frac +=
float(nv) / len(pos)
969 if frac > upperlimit:
973 ul = binedges[j - 1] + (upperlimit - prevfrac) * (dbins / (frac - prevfrac))
986 from matplotlib
import pyplot
as plt
990 from matplotlib
import gridspec
998 "axes.linewidth": 0.5,
1000 "grid.linewidth": 0.5,
1001 "font.family":
"sans-serif",
1002 "font.sans-serif":
"Avant Garde, Helvetica, Computer Modern Sans serif",
1006 matplotlib.rcParams.update(mplparams)
1008 coldict = {
"H1":
"r",
"H2":
"c",
"L1":
"g",
"V1":
"b",
"G1":
"m",
"Joint":
"k"}
1017 paryaxis = paramlatexdict[p.upper()]
1026 minsamp =
float(
"inf")
1027 maxsamp = -
float(
"inf")
1029 for idx, ifo
in enumerate(ifos):
1031 myfig = plt.figure(figsize=(12, 4), dpi=200)
1032 myfig.subplots_adjust(bottom=0.15)
1035 gs = gridspec.GridSpec(1, 4, wspace=0)
1036 ax1 = plt.subplot(gs[:-1])
1037 ax2 = plt.subplot(gs[-1])
1039 pos = list(poslist)[idx]
1043 pos_samps = np.cos(pos[
"iota"].samples)
1045 pos_samps = pos[param].samples
1047 if np.min(pos_samps) < minsamp:
1048 minsamp = np.min(pos_samps)
1049 if np.max(pos_samps) > maxsamp:
1050 maxsamp = np.max(pos_samps)
1053 ax1.plot(pos_samps,
".", color=coldict[ifo], markersize=1)
1055 n, binedges = np.histogram(pos_samps, withhist, density=
True)
1057 ax2.step(n, binedges, color=coldict[ifo])
1059 if np.max(n) > maxn:
1062 plt.plot(pos_samps,
".", color=coldict[ifo], markersize=1)
1066 legendvals.append(
r"$R = %.2f$" % grr[idx][param])
1072 if len(pos_samps) > maxiter:
1073 maxiter = len(pos_samps)
1078 bounds = [minsamp, maxsamp]
1080 ax1.set_ylabel(
r"" + paryaxis, fontsize=16, fontweight=100)
1081 ax1.set_xlabel(
r"Iterations", fontsize=16, fontweight=100)
1083 ax1.set_xlim(0, maxiter)
1084 ax1.set_ylim(bounds[0], bounds[1])
1087 ax2.set_ylim(bounds[0], bounds[1])
1088 ax2.set_xlim(0, maxn + 0.1 * maxn)
1089 ax2.set_yticklabels([])
1090 ax2.set_axis_bgcolor(
"#F2F1F0")
1094 ax1.legend(legendvals, title=
"Gelman-Rubins test")
1114 fp = open(histfile,
"rb")
1116 print(
"Could not open prior file %s" % histfile, file=sys.stderr)
1117 return None,
None,
None
1122 print(
"Could not read in data from prior file %s" % histfile, file=sys.stderr)
1123 return None,
None,
None
1129 header = struct.unpack(
"d" * 6, pd[: 6 * 8])
1136 grid = struct.unpack(
"d" *
int(header[2]) *
int(header[5]), pd[6 * 8 :])
1141 header = list(header)
1145 histarr = np.array([g[:
int(header[5])]], ndmin=2)
1146 for i
in range(
int(header[2]) - 1):
1147 histarr = np.append(
1148 histarr, [g[(i + 1) *
int(header[5]) : (i + 2) *
int(header[5])]], axis=0
1151 xbins = np.linspace(
1152 header[0], header[0] + header[1] * (header[2] - 1),
int(header[2])
1154 ybins = np.linspace(
1155 header[3], header[3] + header[4] * (header[5] - 1),
int(header[5])
1158 return xbins, ybins, histarr
1166 histfile, ndimlabel, mdimlabel, margpars=True, mplparams=False
1169 from matplotlib
import pyplot
as plt
1176 print(
"Could not read binary histogram file", file=sys.stderr)
1185 "text.usetex":
True,
1186 "axes.linewidth": 0.5,
1188 "grid.linewidth": 0.5,
1189 "font.family":
"serif",
1193 matplotlib.rcParams.update(mplparams)
1195 fig = plt.figure(figsize=(4, 4), dpi=200)
1199 parxaxis = paramlatexdict[ndimlabel.upper()]
1201 parxaxis = ndimlabel
1204 paryaxis = paramlatexdict[mdimlabel.upper()]
1206 paryaxis = mdimlabel
1208 plt.xlabel(
r"" + parxaxis, fontsize=14, fontweight=100)
1209 plt.ylabel(
r"" + paryaxis, fontsize=14, fontweight=100, rotation=270)
1211 dx = xbins[1] - xbins[0]
1212 dy = ybins[1] - ybins[0]
1215 xbins[0] - dx / 2.0,
1216 xbins[-1] + dx / 2.0,
1217 ybins[-1] + dy / 2.0,
1218 ybins[0] - dy / 2.0,
1222 np.transpose(histarr),
1225 interpolation=
"bicubic",
1229 fig.subplots_adjust(left=0.18, bottom=0.15)
1230 fax = (fig.get_axes())[0].
axis()
1237 for i
in range(len(xbins)):
1238 xmarg.append(trapezoid(histarr[:][i], x=ybins))
1241 xarea = trapezoid(xmarg, x=xbins)
1242 xmarg = map(
lambda x: x / xarea, xmarg)
1245 for i
in range(len(ybins)):
1246 ymarg.append(trapezoid(np.transpose(histarr)[:][i], x=xbins))
1249 yarea = trapezoid(ymarg, x=ybins)
1250 ymarg = map(
lambda x: x / yarea, ymarg)
1253 figx = plt.figure(figsize=(4, 4), dpi=200)
1254 plt.step(xbins, xmarg, color=
"k")
1255 plt.ylim(0,
max(xmarg) + 0.1 *
max(xmarg))
1256 plt.xlim(fax[0], fax[1])
1257 plt.xlabel(
r"" + parxaxis, fontsize=14, fontweight=100)
1258 plt.ylabel(
r"Probability Density", fontsize=14, fontweight=100)
1259 figx.subplots_adjust(left=0.18, bottom=0.15)
1261 ax.set_axis_bgcolor(
"#F2F1F0")
1264 figy = plt.figure(figsize=(4, 4), dpi=200)
1265 plt.step(ybins, ymarg, color=
"k")
1266 plt.ylim(0,
max(ymarg) + 0.1 *
max(ymarg))
1267 plt.xlim(fax[3], fax[2])
1268 plt.xlabel(
r"" + paryaxis, fontsize=14, fontweight=100)
1269 plt.ylabel(
r"Probability Density", fontsize=14, fontweight=100)
1270 figy.subplots_adjust(left=0.18, bottom=0.15)
1272 ax.set_axis_bgcolor(
"#F2F1F0")
1286 if not h0bins.any():
1287 print(
"Could not read binary histogram file", file=sys.stderr)
1292 for i
in range(len(h0bins)):
1293 h0marg.append(trapezoid(histarr[:][i], x=cibins))
1296 h0bins = h0bins - (h0bins[1] - h0bins[0]) / 2
1297 h0area = trapezoid(h0marg, x=h0bins)
1298 h0margnorm = map(
lambda x: x / h0area, h0marg)
1301 ct = cumulative_trapezoid(h0margnorm, h0bins)
1304 ct = np.insert(ct, 0, 0)
1307 ctu, ui = np.unique(ct, return_index=
True)
1308 intf = interp1d(ctu, h0bins[ui], kind=
"linear")
1309 return intf(
float(ulval))
1324 from matplotlib
import pyplot
as plt
1327 if len(params) != 2:
1328 print(
"Require 2 parameters", file=sys.stderr)
1335 "text.usetex":
True,
1336 "axes.linewidth": 0.5,
1338 "grid.linewidth": 0.5,
1339 "font.family":
"serif",
1343 matplotlib.rcParams.update(mplparams)
1359 parxaxis = paramlatexdict[params[0].upper()]
1361 parxaxis = params[0]
1364 paryaxis = paramlatexdict[params[1].upper()]
1366 paryaxis = params[1]
1372 parval1 = parfile[params[0].upper()]
1373 parval2 = parfile[params[1].upper()]
1378 for idx, ifo
in enumerate(ifos):
1382 myfig = plt.figure(figsize=(4, 4), dpi=200)
1386 cmap = plt.cm.get_cmap(
"Greys")
1389 cmap = plt.cm.get_cmap(coldict[ifo])
1392 myfig = plt.figure(figsize=(4, 4), dpi=200)
1394 cmap = plt.cm.get_cmap(
"Greys")
1396 posterior = poslist[idx]
1398 a = np.squeeze(posterior[params[0]].samples)
1399 b = np.squeeze(posterior[params[1]].samples)
1402 par1pos_min = a.min()
1403 par2pos_min = b.min()
1405 par1pos_max = a.max()
1406 par2pos_max = b.max()
1408 plt.xlabel(
r"" + parxaxis, fontsize=14, fontweight=100)
1409 plt.ylabel(
r"" + paryaxis, fontsize=14, fontweight=100, rotation=270)
1411 H, xedges, yedges = np.histogram2d(a, b, nbins, normed=
True)
1418 Hm = np.transpose(H)
1420 extent = [xedges[0], xedges[-1], yedges[-1], yedges[0]]
1425 interpolation=
"bilinear",
1432 plt.xlim(bounds[0][0], bounds[0][1])
1433 plt.ylim(bounds[1][0], bounds[1][1])
1436 if parval1
and parval2:
1437 if overplot
and idx == len(ifos) - 1:
1440 plt.plot(parval1, parval2,
"rx", markersize=8, mew=2)
1443 plt.plot(parval1, parval2,
"rx", markersize=8, mew=2)
1448 myfig.subplots_adjust(left=0.18, bottom=0.15)
1449 myfigs.append(myfig)
1452 myfig.subplots_adjust(left=0.18, bottom=0.15)
1453 myfigs.append(myfig)
1463 n, binedges = np.histogram(samples, nbins)
1466 binwidth = binedges[1] - binedges[0]
1469 bincentres = np.array([])
1470 for i
in range(0, len(binedges) - 1):
1471 bincentres = np.append(bincentres, binedges[i] + binwidth / 2)
1475 if bincentres[0] - binwidth > low:
1477 n = np.insert(n, 0, 0)
1480 bincentres = np.insert(bincentres, 0, bincentres[0] - binwidth)
1485 dx = bincentres[0] - low
1488 bincentres = np.insert(bincentres, 0, low)
1492 nbound = n[0] - (dn / binwidth) * dx
1497 n = np.insert(n, 0, nbound)
1500 if bincentres[-1] + binwidth < high:
1505 bincentres = np.append(bincentres, bincentres[-1] + binwidth)
1507 dx = high - bincentres[-1]
1510 bincentres = np.append(bincentres, high)
1514 nbound = n[-1] + (dn / binwidth) * dx
1519 n = np.append(n, nbound)
1522 area = trapezoid(n, x=bincentres)
1525 for i
in range(0, len(bincentres)):
1526 ns = np.append(ns,
float(n[i]) / area)
1528 return ns, bincentres
1535 return np.hanning(N)
1538 x = np.linspace(0, 1, N)
1541 win = np.ones(x.shape)
1545 win[lhs] = 0.5 * (1 + np.cos(2 * np.pi / alpha * (x[lhs] - alpha / 2)))
1548 rhs = x >= (1 - alpha / 2)
1549 win[rhs] = 0.5 * (1 + np.cos(2 * np.pi / alpha * (x[rhs] - 1 + alpha / 2)))
1567 from matplotlib.mlab
import specgram
1568 from matplotlib
import colors
1569 from matplotlib
import pyplot
as plt
1582 "text.usetex":
True,
1583 "axes.linewidth": 0.5,
1585 "grid.linewidth": 0.5,
1586 "font.family":
"sans-serif",
1587 "font.sans-serif":
"Avant Garde, Helvetica, Computer Modern Sans serif",
1591 matplotlib.rcParams.update(mplparams)
1592 matplotlib.rcParams[
"text.latex.preamble"] =
r"\usepackage{xfrac}"
1595 coldict = {
"H1":
"r",
"H2":
"c",
"L1":
"g",
"V1":
"b",
"G1":
"m"}
1608 Bk = np.loadtxt(Bkdata[ifo], comments=[
"#",
"%"])
1610 print(
"Could not open file %s" % Bkdata[ifo], file=sys.stderr)
1614 Bk = Bk[Bk[:, 0].argsort()]
1617 uargs = np.unique(Bk[:, 0], return_index=
True)[1]
1626 n, binedges = np.histogram(
1627 np.log(np.fabs(np.concatenate((Bk[:, 1], Bk[:, 2])))), 50
1632 stdest = math.exp((binedges[j] + binedges[j + 1]) / 2)
1636 vals = np.where(np.fabs(Bk[:, 1]) < removeoutlier * stdest)
1637 Bknew = Bk[vals, :][-1]
1639 vals = np.where(np.fabs(Bknew[:, 2]) < removeoutlier * stdest)
1640 Bk = Bknew[vals, :][-1]
1645 mindt =
min(np.diff(gpstime))
1646 sampledt.append(mindt)
1648 Bkabs = np.sqrt(Bk[:, 1] ** 2 + Bk[:, 2] ** 2)
1651 Bkfig = plt.figure(figsize=(11, 3.5), dpi=200)
1652 Bkfig.subplots_adjust(bottom=0.15, left=0.09, right=0.94)
1654 tms = list(map(
lambda x: x - gpstime[0], gpstime))
1656 plt.plot(tms, Bkabs,
".", color=coldict[ifo], markersize=1)
1657 plt.xlabel(
r"GPS - %d" %
int(gpstime[0]), fontsize=14, fontweight=100)
1658 plt.ylabel(
r"$|B_k|$", fontsize=14, fontweight=100)
1660 plt.xlim(tms[0], tms[-1])
1662 Bkfigs.append(Bkfig)
1664 if plotpsds
or plotfscan:
1667 totlen = gpstime[-1] - gpstime[0]
1670 if math.fmod(mindt, 1) != 0.0
or mindt < 1:
1672 "Error... time steps between data points must be integers",
1680 datazeropad = np.zeros(
int(math.ceil(totlen / mindt)) + 1, dtype=complex)
1682 idx = list(map(
lambda x:
int(math.floor((x / mindt) + 0.5)), tms))
1683 for i
in range(0, len(idx)):
1684 datazeropad[idx[i]] = complex(Bk[i, 1], Bk[i, 2])
1686 win =
tukey_window(math.floor(delt / mindt), alpha=0.1)
1690 fscan, freqs, t = specgram(
1692 NFFT=
int(math.floor(delt / mindt)),
1695 noverlap=
int(math.floor(delt / (2.0 * mindt))),
1699 fshape = fscan.shape
1701 totalasd = np.zeros(fshape[0])
1703 for i
in range(0, fshape[0]):
1704 scanasd = np.sqrt(fscan[i, :])
1705 nonzasd = np.nonzero(scanasd)
1706 scanasd = scanasd[nonzasd]
1710 totalasd[i] = np.median(scanasd)
1713 asdlist.append(totalasd)
1716 psdfig = plt.figure(figsize=(4, 3.5), dpi=200)
1717 psdfig.subplots_adjust(left=0.18, bottom=0.15)
1719 plt.plot(freqs, totalasd, color=coldict[ifo])
1720 plt.xlim(freqs[0], freqs[-1])
1721 plt.xlabel(
r"Frequency (Hz)", fontsize=14, fontweight=100)
1722 plt.ylabel(
r"$h/\sqrt{\rm Hz}$", fontsize=14, fontweight=100)
1726 xt = [-Fs / 2.0, -Fs / 4.0, 0.0, Fs / 2.0, Fs / 4.0]
1734 xl.append(
r"$-\sfrac{1}{%d}$" % (-1.0 / item))
1736 xl.append(
r"$\sfrac{1}{%d}$" % (1.0 / item))
1737 ax.set_xticklabels(xl)
1739 plt.tick_params(axis=
"x", which=
"major", labelsize=14)
1741 psdfigs.append(psdfig)
1744 fscanfig = plt.figure(figsize=(11, 3.5), dpi=200)
1745 fscanfig.subplots_adjust(bottom=0.15, left=0.09, right=0.94)
1747 extent = [tms[0], tms[-1], freqs[0], freqs[-1]]
1749 np.sqrt(np.flipud(fscan)),
1753 cmap=colmapdic[ifo],
1754 norm=colors.Normalize(),
1756 plt.ylabel(
r"Frequency (Hz)", fontsize=14, fontweight=100)
1757 plt.xlabel(
r"GPS - %d" %
int(gpstime[0]), fontsize=14, fontweight=100)
1761 yt = [-Fs / 2.0, -Fs / 4.0, 0.0, Fs / 2.0, Fs / 4.0]
1769 yl.append(
r"$-\sfrac{1}{%d}$" % (-1.0 / item))
1771 yl.append(
r"$\sfrac{1}{%d}$" % (1.0 / item))
1772 ax.set_yticklabels(yl)
1773 plt.tick_params(axis=
"y", which=
"major", labelsize=14)
1775 fscanfigs.append(fscanfig)
1777 return Bkfigs, psdfigs, fscanfigs, asdlist, sampledt
1784 lims, param, ifos, prevlims=None, bins=20, overplot=False, mplparams=False
1787 from matplotlib
import pyplot
as plt
1793 "text.usetex":
True,
1794 "axes.linewidth": 0.5,
1796 "grid.linewidth": 0.5,
1797 "font.family":
"serif",
1801 matplotlib.rcParams.update(mplparams)
1806 coldict = {
"H1":
"r",
"H2":
"c",
"L1":
"g",
"V1":
"b",
"G1":
"m",
"Joint":
"k"}
1809 parxaxis = paramlatexdict[param.upper()]
1813 paryaxis =
"Number of Pulsars"
1817 if prevlims
is not None:
1818 logprevlims = np.log10(prevlims)
1831 for j, ifo
in enumerate(ifos):
1832 theselims = lims[ifo]
1835 for i, val
in enumerate(theselims):
1839 loglims = np.log10(theselims)
1841 stackdata.append(loglims)
1843 highbins.append(np.max(loglims))
1844 lowbins.append(np.min(loglims))
1846 if logprevlims
is not None:
1847 highbins.append(
max(logprevlims))
1848 lowbins.append(
min(logprevlims))
1850 hrange = (
min(lowbins),
max(highbins))
1852 for j, ifo
in enumerate(ifos):
1854 theselims = lims[ifo]
1857 for i, val
in enumerate(theselims):
1861 loglims = np.log10(theselims)
1867 myfig = plt.figure(figsize=(4, 4), dpi=200)
1874 for ifoname
in ifos:
1875 edgecolor.append(coldict[ifoname])
1876 facecolor.append(coldict[ifoname])
1878 edgecolor = [coldict[ifo]]
1879 facecolor = [coldict[ifo]]
1882 n, bins, patches = plt.hist(
1892 for i, patch
in enumerate(patches):
1893 plt.setp(patch,
"facecolor", facecolor[i])
1896 maxlims.append(np.max(loglims))
1897 minlims.append(np.min(loglims))
1899 if logprevlims
is not None:
1901 maxlims.append(
max(logprevlims))
1902 minlims.append(
min(logprevlims))
1904 maxlim =
max(maxlims)
1905 minlim =
min(minlims)
1923 maxlim =
max(maxlims)
1924 minlim =
min(minlims)
1933 tickvals =
range(
int(math.ceil(maxlim) - math.floor(minlim)))
1934 tickvals = map(
lambda x: x +
int(math.floor(minlim)), tickvals)
1935 ax.set_xticks(tickvals)
1936 tls = map(
lambda x:
"$10^{%d}$" % x, tickvals)
1937 ax.set_xticklabels(tls)
1939 plt.ylabel(
r"" + paryaxis, fontsize=14, fontweight=100)
1940 plt.xlabel(
r"" + parxaxis, fontsize=14, fontweight=100)
1942 myfig.subplots_adjust(left=0.18, bottom=0.15)
1944 myfigs.append(myfig)
1975 from matplotlib
import pyplot
as plt
1980 "text.usetex":
True,
1981 "axes.linewidth": 0.5,
1983 "grid.linewidth": 0.5,
1984 "font.family":
"serif",
1988 matplotlib.rcParams.update(mplparams)
1993 coldict = {
"H1":
"r",
"H2":
"c",
"L1":
"g",
"V1":
"b",
"G1":
"m",
"Joint":
"k"}
1995 parxaxis =
"Frequency (Hz)"
1998 for j, ifo
in enumerate(ifos):
2006 if len(h0lim) != len(f0s):
2009 if not overplot
or (overplot
and j == 0):
2010 myfig = plt.figure(figsize=(7, 5.5), dpi=200)
2013 if ulesttop
is not None and ulestbot
is not None:
2017 if len(ult) == len(ulb)
and len(ult) == len(f0s):
2018 for i
in range(len(ult)):
2020 [f0s[i], f0s[i]], [ulb[i], ult[i]], ls=
"-", lw=3, c=
"lightgrey"
2025 and prevlimf0gw
is not None
2026 and len(prevlim) == len(prevlimf0gw)
2028 if not overplot
or (overplot
and j == len(ifos) - 1):
2042 f0s, h0lim, marker=
"*", ms=10, mfc=coldict[ifo], mec=coldict[ifo], ls=
"None"
2045 plt.ylabel(
r"" + paryaxis, fontsize=14, fontweight=100)
2046 plt.xlabel(
r"" + parxaxis, fontsize=14, fontweight=100)
2048 plt.xlim(xlims[0], xlims[1])
2050 if not overplot
or (overplot
and j == len(ifos) - 1):
2052 myfig.subplots_adjust(left=0.12, bottom=0.10)
2053 myfigs.append(myfig)
2070 s = np.array([], dtype=complex)
2072 sphi = np.sin(pardict[
"phi0"])
2073 cphi = np.cos(pardict[
"phi0"])
2075 Xplus = 0.25 * (1.0 + pardict[
"cosiota"] * pardict[
"cosiota"]) * pardict[
"h0"]
2076 Xcross = 0.5 * pardict[
"cosiota"] * pardict[
"h0"]
2077 Xpsinphi = Xplus * sphi
2078 Xcsinphi = Xcross * sphi
2079 Xpcosphi = Xplus * cphi
2080 Xccosphi = Xcross * cphi
2083 while tmpts < starttime + duration:
2084 ts.append(starttime + (dt * i))
2088 ts[i], pardict[
"ra"], pardict[
"dec"], pardict[
"psi"], detector
2093 s, (fp * Xpcosphi + fc * Xcsinphi) + 1j * (fp * Xpsinphi - fc * Xccosphi)
2115 pardict, detector, starttime=900000000.0, duration=86400.0, dt=60.0, datatimes=None
2117 if "cosiota" in pardict:
2118 cosiota = pardict[
"cosiota"]
2119 iota = math.acos(cosiota)
2120 siniota = math.sin(iota)
2122 raise KeyError(
"cos(iota) not defined!")
2124 if "psi" in pardict:
2125 psi = pardict[
"psi"]
2127 raise KeyError(
"psi not defined!")
2129 if "C22" in pardict:
2130 C22 = pardict[
"C22"]
2133 C22 = -pardict[
"h0"] / 2.0
2137 if "phi22" in pardict:
2138 phi22 = pardict[
"phi22"]
2140 if "phi0" in pardict:
2141 phi22 = 2.0 * pardict[
"phi0"]
2145 ePhi22 = cmath.exp(phi22 * 1j)
2147 if "C21" in pardict:
2148 C21 = pardict[
"C21"]
2152 if "phi21" in pardict:
2153 phi21 = pardict[
"phi21"]
2157 ePhi21 = cmath.exp(phi21 * 1j)
2162 if "C21" in pardict
and "C22" in pardict
and "h0" not in pardict:
2169 if datatimes
is None:
2170 datatimes = np.arange(starttime, starttime + duration, dt)
2174 datatimes, pardict[
"ra"], pardict[
"dec"], pardict[
"psi"], detector
2179 -(C21 / 4.0) * ePhi21 * siniota * cosiota * fp
2180 + 1j * (C21 / 4.0) * ePhi21 * siniota * fc
2184 -(C22 / 2.0) * ePhi22 * (1.0 + cosiota**2.0) * fp
2185 + 1j * (C22) * ePhi22 * cosiota * fc
2188 ts.append(datatimes)
2197 costheta = pardict[
"costheta"]
2198 theta = np.arccos(costheta)
2199 sintheta = math.sin(theta)
2200 sin2theta = math.sin(2.0 * theta)
2201 sinlambda = math.sin(pardict[
"lambdapin"])
2202 coslambda = math.cos(pardict[
"lambdapin"])
2203 sin2lambda = math.sin(2.0 * pardict[
"lambdapin"])
2205 phi0 = pardict[
"phi0"]
2207 I21 = pardict[
"I21"]
2208 I31 = pardict[
"I31"]
2210 A22 = I21 * (sinlambda**2 - (coslambda * costheta) ** 2) - I31 * sintheta**2
2211 B22 = I21 * sin2lambda * costheta
2213 C22 = 2.0 * math.sqrt(A22**2 + B22**2)
2215 A21 = I21 * sin2lambda * sintheta
2216 B21 = (I21 * coslambda**2 - I31) * sin2theta
2218 C21 = 2.0 * math.sqrt(A21**2 + B21**2)
2220 phi22 = np.fmod(2.0 * phi0 - math.atan2(B22, A22), 2.0 * np.pi)
2221 phi21 = np.fmod(phi0 - math.atan2(B21, A21), 2.0 * np.pi)
2223 outvals = {
"C22": C22,
"C21": C21,
"phi22": phi22,
"phi21": phi21}
2236 iota = np.arccos(pardict[
"cosiota"])
2237 theta = np.arccos(pardict[
"costheta"])
2238 siniota = math.sin(iota)
2239 sintheta = math.sin(theta)
2240 sin2theta = math.sin(2.0 * theta)
2241 sinlambda = math.sin(pardict[
"lambdapin"])
2242 coslambda = math.cos(pardict[
"lambdapin"])
2243 sin2lambda = math.sin(2.0 * pardict[
"lambdapin"])
2245 ePhi = cmath.exp(0.5 * pardict[
"phi0"] * 1j)
2246 e2Phi = cmath.exp(pardict[
"phi0"] * 1j)
2248 f2_r = pardict[
"f0"] ** 2 / pardict[
"dist"]
2251 This model is a complex heterodyned time series
for a pinned superfluid
2252 neutron star emitting at its roation frequency
and twice its rotation
2253 frequency (
as defined
in Eqns 35-38 of Jones 2012 LIGO DCC T1200265-v3)
2256 Xplusf = -(f2_r / 2.0) * siniota * pardict["cosiota"]
2257 Xcrossf = (f2_r / 2.0) * siniota
2259 Xplus2f = -f2_r * (1.0 + pardict[
"cosiota"] ** 2)
2260 Xcross2f = 2.0 * f2_r * pardict[
"cosiota"]
2262 A21 = pardict[
"I21"] * sin2lambda * sintheta
2263 B21 = (pardict[
"I21"] * coslambda**2 - pardict[
"I31"]) * sin2theta
2266 pardict[
"I21"] * (sinlambda**2 - coslambda**2 * pardict[
"costheta"] ** 2)
2267 - pardict[
"I31"] * sintheta**2
2269 B22 = pardict[
"I21"] * sin2lambda * pardict[
"costheta"]
2277 s1 = np.array([], dtype=complex)
2278 s2 = np.array([], dtype=complex)
2281 while tmpts < starttime + duration:
2282 ts1.append(starttime + (dt * i))
2283 ts2.append(starttime + (dt * i))
2287 ts1[i], pardict[
"ra"], pardict[
"dec"], pardict[
"psi"], detector
2293 (fp * Xplusf * ePhi * (A21 - 1j * B21))
2294 + (fc * Xcrossf * ePhi * (B21 + 1j * A21)),
2300 (fp * Xplus2f * e2Phi * (A22 - 1j * B22))
2301 + (fc * Xcross2f * e2Phi * (B22 + 1j * A22)),
2309 ts = np.vstack([ts1, ts2])
2310 s = np.vstack([s1, s2])
2323 "H1": lal.LALDetectorIndexLHODIFF,
2324 "H2": lal.LALDetectorIndexLHODIFF,
2325 "L1": lal.LALDetectorIndexLLODIFF,
2326 "G1": lal.LALDetectorIndexGEO600DIFF,
2327 "V1": lal.LALDetectorIndexVIRGODIFF,
2328 "T1": lal.LALDetectorIndexTAMA300DIFF,
2329 "AL1": lal.LALDetectorIndexLLODIFF,
2330 "AH1": lal.LALDetectorIndexLHODIFF,
2331 "AV1": lal.LALDetectorIndexVIRGODIFF,
2332 "E1": lal.LALDetectorIndexE1DIFF,
2333 "E2": lal.LALDetectorIndexE2DIFF,
2334 "E3": lal.LALDetectorIndexE3DIFF,
2338 detector = detMap[det]
2340 raise KeyError(
"ERROR. Key {} is not a valid detector name.".
format(det))
2343 detval = lal.CachedDetectors[detector]
2344 response = detval.response
2347 if not isinstance(ra, float):
2348 if isinstance(ra, str):
2353 "Right ascension string '{}' not formatted properly".
format(ra)
2357 "Right ascension must be a 'float' in radians or a string of the format 'hh:mm:ss.s'"
2360 if not isinstance(dec, float):
2361 if isinstance(dec, str):
2366 "Declination string '{}' not formatted properly".
format(ra)
2370 "Declination must be a 'float' in radians or a string of the format 'dd:mm:ss.s'"
2374 if isinstance(gpsTime, float)
or isinstance(gpsTime, int):
2375 gpsTime = np.array([gpsTime])
2377 gpsTime = np.copy(gpsTime)
2380 gpsTime = gpsTime.astype(
"float64")
2383 if len(gpsTime) == 1
or np.unique(np.diff(gpsTime)).size == 1:
2384 gpsStart = lal.LIGOTimeGPS(gpsTime[0])
2386 if len(gpsTime) > 1:
2387 dt = gpsTime[1] - gpsTime[0]
2388 fp, fc = lal.ComputeDetAMResponseSeries(
2389 response, ra, dec, psi, gpsStart, dt, len(gpsTime)
2393 return fp.data.data, fc.data.data
2395 fp = np.zeros(len(gpsTime))
2396 fc = np.zeros(len(gpsTime))
2398 for i
in range(len(gpsTime)):
2399 gps = lal.LIGOTimeGPS(gpsTime[i])
2400 gmst_rad = lal.GreenwichMeanSiderealTime(gps)
2403 fp[i], fc[i] = lal.ComputeDetAMResponse(response, ra, dec, psi, gmst_rad)
2423 if isinstance(detectors, str):
2424 detectors = [detectors]
2431 for det
in detectors:
2437 ns = np.sqrt((psd / 2.0) / (2.0 * dt))
2445 for j, det
in enumerate(detectors):
2448 tmpnpsds.append(np.sqrt((npsds[0] / 2.0) / (2.0 * dt)))
2450 tmpnpsds.append(np.sqrt((npsds[count] / 2.0) / (2.0 * dt)))
2456 if len(freqfac) == 1
and len(detectors) != len(npsds):
2458 "Number of detectors {} not the same as number of noises {}".
format(
2459 len(detectors), len(npsds)
2463 if len(freqfac) == 2
and 2 * len(detectors) != len(npsds):
2465 "Number of detectors {} not half the number of noises {}".
format(
2466 len(detectors), len(npsds)
2474 for j, det
in enumerate(detectors):
2476 if len(freqfac) == 1
and freqfac[0] == 2.0:
2480 tss = np.append(tss, ts)
2481 ss = np.append(ss, s)
2483 tss = np.vstack([tss, ts])
2484 ss = np.vstack([ss, s])
2488 elif len(freqfac) == 2:
2492 for k, frf
in enumerate(freqfac):
2493 if j == 0
and k == 0:
2494 tss = np.append(tss, ts[k][:])
2495 ss = np.append(ss, s[k][:])
2497 tss = np.vstack([tss, ts[k][:]])
2498 ss = np.vstack([ss, s[k][:]])
2501 snrtmp = snrtmp + snrtmp2 * snrtmp2
2503 snrtmp = np.sqrt(snrtmp)
2505 snrtot = snrtot + snrtmp * snrtmp
2508 snrtot = np.sqrt(snrtot)
2511 if snrscale
is not None:
2513 snrscale = snrscale / snrtot
2518 signalonly = ss.copy()
2521 for det
in detectors:
2523 if len(freqfac) == 1:
2525 rs = np.random.randn(len(ts[0]), 2)
2527 for j, t
in enumerate(ts[0]):
2528 if len(tss.shape) == 1:
2529 signalonly[j] = (snrscale * ss[j].real) + 1j * (
2530 snrscale * ss[j].imag
2532 ss[j] = (snrscale * ss[j].real + npsds[i] * rs[j][0]) + 1j * (
2533 snrscale * ss[j].imag + npsds[i] * rs[j][1]
2536 signalonly[i][j] = (snrscale * ss[i][j].real) + 1j * (
2537 snrscale * ss[i][j].imag
2539 ss[i][j] = (snrscale * ss[i][j].real + npsds[i] * rs[j][0]) + 1j * (
2540 snrscale * ss[i][j].imag + npsds[i] * rs[j][1]
2544 elif len(freqfac) == 2:
2546 rs = np.random.randn(len(ts[0][:]), 4)
2548 for j, t
in enumerate(ts[0][:]):
2549 signalonly[i][j] = (snrscale * ss[i][j].real) + 1j * (
2550 snrscale * ss[i][j].imag
2552 ss[i][j] = (snrscale * ss[i][j].real + npsds[i] * rs[j][0]) + 1j * (
2553 snrscale * ss[i][j].imag + npsds[i] * rs[j][1]
2555 signalonly[i + 1][j] = (snrscale * ss[i + 1][j].real) + 1j * (
2556 snrscale * ss[i + 1][j].imag
2559 snrscale * ss[i + 1][j].real + npsds[i + 1] * rs[j][2]
2560 ) + 1j * (snrscale * ss[i + 1][j].imag + npsds[i + 1] * rs[j][3])
2564 print(
"Something wrong with injection", file=sys.stderr)
2567 snrtot = snrtot * snrscale
2569 return tss, ss, signalonly, snrtot, snrscale, npsds
2578 import lalsimulation
2581 return lalsimulation.SimNoisePSDAdvVirgo(f)
2582 elif det ==
"H1" or det ==
"L1":
2583 return lalsimulation.SimNoisePSDiLIGOSRD(f)
2585 return lalsimulation.SimNoisePSDiLIGOSRD(f) * 2.0
2587 return lalsimulation.SimNoisePSDGEO(f)
2589 return lalsimulation.SimNoisePSDVirgo(f)
2591 return lalsimulation.SimNoisePSDTAMA(f)
2593 return lalsimulation.SimNoisePSDKAGRA(f)
2594 elif det ==
"AL1" or det ==
"AH1":
2595 return lalsimulation.SimNoisePSDaLIGOZeroDetHighPower(f)
2597 raise ValueError(
"{} is not a recognised detector".
format(det))
2606 ss = ss + val.real**2 + val.imag**2
2608 return np.sqrt(ss / sig**2)
2615 chainMeans = [np.mean(data)
for data
in chains]
2616 chainVars = [np.var(data)
for data
in chains]
2618 BoverN = np.var(chainMeans)
2619 W = np.mean(chainVars)
2621 sigmaHat2 = W + BoverN
2625 VHat = sigmaHat2 + BoverN / m
2639 from lalinference
import bayespputils
as bppu
2647 for cfile
in chainfiles:
2648 if os.path.isfile(cfile):
2653 if mcmcChain
is None:
2654 return None,
None,
None,
None
2658 for j
in range(1, mcmcChain.shape[1]):
2659 neff, acl, acf = bppu.effectiveSampleSize(mcmcChain[:, j])
2660 neffstmp.append(neff)
2665 neffs.append(math.floor(np.mean(neffstmp)))
2668 nskip =
int(math.ceil(mcmcChain.shape[0] / np.mean(neffstmp)))
2671 mcmc.append(mcmcChain[::nskip, :])
2672 cl.append(mcmcChain.shape[0])
2674 print(
"File %s does not exist!" % cfile, file=sys.stderr)
2675 return None,
None,
None,
None
2679 cf = open(chainfiles[0],
"r")
2680 headers = cf.readline()
2681 headers = cf.readline()
2683 headers = re.sub(
"%",
"", headers)
2685 headers = re.sub(
"rads",
"", headers)
2687 headers = re.sub(
"[()]",
"", headers)
2691 for idx, parv
in enumerate(headers.split()):
2694 for j
in range(0, len(mcmc)):
2696 singlechain = achain[:, idx]
2697 lgr.append(singlechain)
2702 headers = headers.replace(
"\n",
"\tpost\n")
2705 comfile = chainfiles[0] +
"_common_tmp.dat"
2707 cf = open(comfile,
"w")
2709 print(
"Can't open common posterior file!", file=sys.stderr)
2714 for j
in range(0, narr.shape[0]):
2717 mline = np.append(mline, np.exp(mline[0]))
2719 strmline =
" ".join(
str(x)
for x
in mline) +
"\n"
2724 peparser = bppu.PEOutputParser(
"common")
2725 cf = open(comfile,
"r")
2726 commonResultsObj = peparser.parse(cf)
2733 pos = bppu.Posterior(commonResultsObj, SimInspiralTableEntry=
None, votfile=
None)
2738 cipos = bppu.PosteriorOneDPDF(
"cosiota", np.cos(pos[
"iota"].samples))
2746 return pos, neffs, grr, cl
2758 cfdata = np.loadtxt(cf, comments=
"%")
2764 headers = fc.readline()
2765 headers = fc.readline()
2768 headers = re.sub(
"%",
"", headers)
2770 headers = re.sub(
"rads",
"", headers)
2772 headers = re.sub(
"[()]",
"", headers)
2774 lh = len(headers.split())
2776 cfdata = np.array([])
2778 lines = cf.readlines()
2780 for i, line
in enumerate(lines):
2784 lvals = line.split()
2787 if len(lvals) != lh:
2792 lvalsf = map(float, lvals)
2798 cfdata = np.array(lvalsf)
2800 cfdata = np.vstack((cfdata, lvalsf))
2802 if cfdata.size == 0:
2812 This function will import a posterior sample file created by `lalapps_nest2pos` (
or a nested
2813 sample file). It will be returned
as a Posterior
class object from `bayespputils`. The
2814 signal evidence
and noise evidence are also returned.
2816 If there are samples
in 'Q22' and not 'H0',
and also a distance,
or distance samples, then
2817 the Q22 samples will be converted into equivalent H0 values.
2821 postfile : str, required
2822 The file name of the posterior
or nested sample file. In general this should be a HDF5 file
with the extension
2823 '.hdf' or '.h5', although older format ascii files are still supported at the moment.
2824 nestedsamples : bool, default:
False
2825 If the file being input contains nested samples, rather than posterior samples, then this flag must be set to
2827 removeuntrig : bool, default:
True
2828 If this
is True then any parameters that are sines
or cosines of a value will have the value removed
if present
2829 e.g.
if cosiota
and iota exist then iota will be removed.
2832 from lalinference
import bayespputils
as bppu
2835 fe = os.path.splitext(postfile)[-1].lower()
2838 if fe ==
".h5" or fe ==
".hdf":
2843 from lalinference
import LALInferenceHDF5NestedSamplesDatasetName
2845 samples = read_samples(
2846 postfile, tablename=LALInferenceHDF5NestedSamplesDatasetName
2848 params = samples.colnames
2851 for param
in params:
2852 replace_column(samples, param, samples[param].astype(float))
2856 samples.as_array().view(float).reshape(-1, len(params)),
2859 raise IOError(
"Could not import nested samples")
2861 peparser = bppu.PEOutputParser(
"hdf5")
2862 nsResultsObject = peparser.parse(postfile)
2866 peparser = bppu.PEOutputParser(
"common")
2867 nsResultsObject = peparser.parse(gzip.open(postfile,
"r"))
2869 peparser = bppu.PEOutputParser(
"common")
2870 nsResultsObject = peparser.parse(open(postfile,
"r"))
2872 pos = bppu.Posterior(nsResultsObject, SimInspiralTableEntry=
None)
2876 nsamps = len(pos[pnames[0]].samples)
2877 permarr = np.arange(nsamps)
2878 np.random.shuffle(permarr)
2881 for pname
in pnames:
2883 if pos[pname].samples.tolist().
count(pos[pname].samples[0]) == len(
2886 if pname ==
"f0_fixed":
2888 posfreqs = pos[pname].samples[0]
2889 elif pname ==
"dist":
2891 posdist = pos[pname].samples[0] / KPC
2897 shufpos = bppu.PosteriorOneDPDF(pname, pos[pname].samples[permarr])
2903 if "iota" in pos.names:
2904 posIota = pos[
"iota"].samples
2906 if posIota
is not None:
2908 cipos = bppu.PosteriorOneDPDF(
"cosiota", np.cos(posIota))
2915 if "i" in pos.names:
2916 posI = pos[
"i"].samples
2918 if posI
is not None:
2920 sinipos = bppu.PosteriorOneDPDF(
"sini", np.sin(posI))
2927 if "c21" in pos.names:
2928 posC21 = pos[
"c21"].samples
2931 if "c22" in pos.names:
2932 posC22 = pos[
"c22"].samples
2935 if "phi22" in pos.names:
2936 posphi22 = pos[
"phi22"].samples
2939 if posC22
is not None and posC21
is None:
2941 h0pos = bppu.PosteriorOneDPDF(
"h0", 2.0 * pos[
"c22"].samples)
2946 if posphi22
is not None:
2948 phi0pos = bppu.PosteriorOneDPDF(
2949 "phi0", np.fmod(pos[
"phi22"].samples + math.pi, 2.0 * math.pi)
2957 if "q22" in pos.names:
2958 posQ22 = pos[
"q22"].samples
2960 if "dist" in pos.names:
2962 pos[
"dist"].samples / KPC
2967 distpos = bppu.PosteriorOneDPDF(
"dist", posdist)
2970 if "f0" in pos.names:
2971 posfreqs = pos[
"f0"].samples
2974 if posQ22
is not None and posdist
is not None and "h0" not in pos.names:
2976 h0pos = bppu.PosteriorOneDPDF(
"h0",
quadrupole_to_h0(posQ22, posfreqs, posdist))
2981 if fe ==
".h5" or fe ==
".hdf":
2983 hdf = h5py.File(postfile,
"r")
2984 a = hdf[
"lalinference"][
"lalinference_nest"]
2985 sigev = a.attrs[
"log_evidence"]
2986 noiseev = a.attrs[
"log_noise_evidence"]
2989 B = np.loadtxt(postfile.replace(
".gz",
"") +
"_B.txt")
2994 return pos, sigev, noiseev
2999 return np.logaddexp(x, y)
3004 Perform trapezium rule integration for the logarithm of a function on a regular grid.
3008 lnf - a numpy array of values that are the natural logarithm of a function
3009 dx - a float giving the step size between values
in the function
3013 The natural logarithm of the area under the function.
3016 return np.log(dx / 2.0) + logsumexp([logsumexp(lnf[:-1]), logsumexp(lnf[1:])])
3026 places = ranges[pname]
3027 axis = pnames.index(pname)
3031 x = np.apply_along_axis(logtrapz, axis, like, places[1] - places[0])
3032 elif len(places) == 1:
3035 q = np.arange(0, len(z)).astype(int) != axis
3036 newshape = tuple((np.array(list(z)))[q])
3037 x = np.reshape(like, newshape)
3041 pnames.remove(pname)
3047def marginal(lnlike, pname, pnames, ranges, multflatprior=False):
3048 from copy
import deepcopy
3051 lnliketmp = deepcopy(lnlike)
3052 pnamestmp = deepcopy(pnames)
3053 rangestmp = deepcopy(ranges)
3060 + np.log(1.0 / (rangestmp[name][-1] - rangestmp[name][0])),
3066 lnliketmp =
marginalise(lnliketmp, name, pnamestmp, rangestmp)
3079 dt = np.min(np.diff(ts))
3088 chunkLengths.append(count)
3097 if t2 - t1 > 2.0 * dt
or count == chunkMax:
3098 chunkLengths.append(count)
3108 A function to estimate the signal-to-noise ratio of a pulsar signal (for a triaxial neutron
3109 star emitting at twice the rotation frequency
from the l=m=2 quadrupole mode)
in a given
3110 detector over a given time range,
for a given one-sided power spectral density.
3114 source - a dictionary containing
'h0',
'cosiota',
'psi',
'ra' (rads
or string),
'dec' (rads
or string)
3115 det - the detector, e.g.
'H1'
3116 tstart - a GPS start time
3117 duration - a signal duration (seconds)
3118 Sn - a one-sided power spectral density
3119 dt - timestep
for antenna response calculation [default: 1800s]
3123 rho - an estimate of the optimal matched filter SNR
3128 Ndays = duration / sidday
3129 Nsamps = np.floor(sidday / dt)
3130 tend = tstart + duration
3137 tts = np.arange(tstart, tstart + sidday, dt)
3140 Fp, Fc =
antenna_response(tts, source[
"ra"], source[
"dec"], source[
"psi"], det)
3142 sFp = np.floor(Ndays) * np.sum(Fp**2)
3143 sFc = np.floor(Ndays) * np.sum(Fc**2)
3146 if np.floor(Ndays) * sidday > dt:
3147 tts = np.arange(tstart + sidday * np.floor(Ndays), tend, dt)
3149 Fp, Fc =
antenna_response(tts, source[
"ra"], source[
"dec"], source[
"psi"], det)
3151 sFp += np.sum(Fp**2)
3152 sFc += np.sum(Fc**2)
3156 (source[
"h0"] ** 2 / Sn)
3159 sFp * (0.5 * (1 + source[
"cosiota"] ** 2)) ** 2
3160 + sFc * source[
"cosiota"] ** 2
3164 return np.sqrt(snr2)
3169 A function to estimate the signal amplitude of a pulsar signal (for a triaxial neutron star emitting at twice
3170 the rotation frequency
from the l=m=2 quadrupole mode)
for a given SNR
in a particular detector over
3171 a given time range,
for a given one-sided power spectral density.
3175 snr - the optimal matched filter signal-to-noise ratio
3176 source - a dictionary containing
'cosiota',
'psi',
'ra' (rads
or string),
'dec' (rads
or string)
3177 det - the detector, e.g.
'H1'
3178 tstart - a GPS start time
for the signal
3179 duration - a signal duration (seconds)
3180 Sn - a one-sided power spectral density
3181 dt - timestep
for antenna response calculation [default: 600s]
3185 h0 - an estimate of signal amplitude required to give the input SNR
3190 Ndays = duration / sidday
3191 Nsamps = np.floor(sidday / dt)
3192 tend = tstart + duration
3199 tts = np.arange(tstart, tstart + sidday, dt)
3202 Fp, Fc =
antenna_response(tts, source[
"ra"], source[
"dec"], source[
"psi"], det)
3204 sFp = np.floor(Ndays) * np.sum(Fp**2)
3205 sFc = np.floor(Ndays) * np.sum(Fc**2)
3208 if np.floor(Ndays) * sidday > dt:
3209 tts = np.arange(tstart + sidday * np.floor(Ndays), tend, dt)
3211 Fp, Fc =
antenna_response(tts, source[
"ra"], source[
"dec"], source[
"psi"], det)
3213 sFp += np.sum(Fp**2)
3214 sFc += np.sum(Fc**2)
3217 h02 = (snr**2 * Sn) / (
3220 sFp * (0.5 * (1 + source[
"cosiota"] ** 2)) ** 2
3221 + sFc * source[
"cosiota"] ** 2
3242 A function to calculate the 4-parameter posterior probability density for a continuous wave signal
3243 given a set of processed data
from a set of detectors.
3247 dets - a list of strings containing the detectors being used
in the likelihood calculation
3248 ts - a dictionary of 1d numpy arrays containing the GPS times of the data
for each detector
3249 data - a dictionary of 1d numpy arrays containing the complex data values
for each detector
3250 ra - the right ascension (
in rads) of the source
3251 dec - the declination (
in rads) of the source
3252 sigmas - a dictionary of 1d numpy arrays containing the times series of standard deviation
3253 values
for each detector. If this
is not given a Student
's t likelihood will be used,
3254 but if it
is given a Gaussian likelihood will be used (default:
None)
3255 paramranges - a dictionary of tuples
for each parameter (
'h0',
'phi0',
'psi' and 'cosiota') giving
3256 the lower
and upper ranges of the parameter grid
and the number of grid points. If
not
3257 given then defaults will be used.
3258 datachunks -
in the calculation split the data into stationary chunks
with a maximum length given
3259 by this value. If set to 0
or inf then the data will
not be split. (default: 30)
3260 chunkmin - this
is the shortest chunk length allowed to be included
in the likelihood calculation
3262 ngrid - the number of grid points to use
for each dimension of the likelihood calculation. This
3263 is used
if the values are
not specified
in the paramranges argument (default: 50)
3264 outputlike - output the log likelihoods rather than posteriors (default:
False)
3268 L - The 4d posterior (
or likelihood) over all parameters
3269 h0pdf - The 1d marginal posterior
for h0
3270 phi0pdf - The 1d marginal posterior
for phi0 (the rotation frequency,
not GW frequency)
3271 psipdf - The 1d marginal posterior
for psi
3272 cosiotapdf - The 1d marginal posterior
for cosiota
3273 lingrids - A dictionary of the grid points
for each parameter
3274 sigev - The log evidence
for the signal model
3275 noiseev - The log evidence
for the noise model
3277 An example would be:
3285 ts[det] = np.arange(900000000., 921000843., 60.)
3286 data[det] = np.random.randn(len(ts[det])) + 1j*np.random.randn(len(ts[det]))
3292 paramranges[
'h0'] = (0., 2., 50)
3293 paramranges[
'psi'] = (0., np.pi/2., 50)
3294 paramranges[
'phi0'] = (0., np.pi, 50)
3295 paramranges[
'cosiota'] = (-1., 1., 50)
3297 L, h0pdf, phi0pdf, psipdf, cosiotapdf, grid, sigev, noiseev =
pulsar_posterior_grid(dets, ts, data, ra, dec,
3298 paramranges=paramranges)
3304 from scipy.special
import gammaln
3308 liketype =
"studentst"
3310 liketype =
"gaussian"
3313 if not isinstance(dets, list):
3314 if isinstance(dets, str):
3317 print(
"Detector not, or incorrectly, set", file=sys.stderr)
3321 alloweddets = [
"H1",
"L1",
"V1",
"G1",
"T1",
"H2"]
3325 if det
not in alloweddets:
3327 "Detector not in list of allowed detectors ("
3328 +
",".join(alloweddets)
3336 print(
"No time stamps given for detector %s" % det, file=sys.stderr)
3341 print(
"No data time series given for detector %s" % det, file=sys.stderr)
3346 if det
not in sigmas:
3348 "No sigma time series given for detector %s" % det, file=sys.stderr
3353 if len(ts[det]) != len(data[det]):
3355 "Length of times stamps array and data array are inconsistent for %s"
3361 if len(ts[det]) != len(sigmas[det]):
3363 "Length of times stamps array and sigma array are inconsistent for %s"
3369 params = [
"h0",
"phi0",
"psi",
"cosiota"]
3371 defaultranges[
"phi0"] = (0.0, np.pi, ngrid)
3372 defaultranges[
"psi"] = (0.0, np.pi / 2.0, ngrid)
3373 defaultranges[
"cosiota"] = (-1.0, 1.0, ngrid)
3375 defaultranges[
"h0"] = (
3378 * np.max([np.std(data[dv])
for dv
in data])
3379 * np.sqrt(1440.0 / np.max([len(ts[dtx])
for dtx
in ts])),
3384 for param
in params:
3385 if param
in paramranges:
3386 if len(paramranges[param]) != 3:
3387 paramranges[param] = defaultranges[param]
3390 paramranges[param][1] < paramranges[param][0]
3391 or paramranges[param][2] < 1
3394 "Parameter ranges wrong for %s, reverting to defaults" % param,
3397 paramranges[param] = defaultranges[param]
3399 paramranges[param] = defaultranges[param]
3401 lingrids[param] = np.linspace(
3402 paramranges[param][0], paramranges[param][1], paramranges[param][2]
3404 shapetuple += (paramranges[param][2],)
3407 [H0S, PHI0S, PSIS, COSIS] = np.meshgrid(
3411 lingrids[
"cosiota"],
3415 APLUS = 0.5 * (1.0 + COSIS**2)
3417 SINPHI = np.sin(2.0 * PHI0S)
3418 COSPHI = np.cos(2.0 * PHI0S)
3419 SIN2PSI = np.sin(2.0 * PSIS)
3420 COS2PSI = np.cos(2.0 * PSIS)
3422 Apsinphi_2 = 0.5 * APLUS * SINPHI
3423 Acsinphi_2 = 0.5 * ACROSS * SINPHI
3424 Apcosphi_2 = 0.5 * APLUS * COSPHI
3425 Accosphi_2 = 0.5 * ACROSS * COSPHI
3426 Acpsphicphi_2 = 0.5 * APLUS * ACROSS * COSPHI * SINPHI
3430 TWOAPACSPCP = 2.0 * APLUS * ACROSS * SINPHI * COSPHI
3434 C2PS2P = COS2PSI * SIN2PSI
3441 like = np.zeros(shapetuple)
3447 logprior -= np.log(paramranges[p][1] - paramranges[p][0])
3451 if liketype ==
"gaussian":
3454 nstd = np.ones(len(ts[det]))
3460 if np.isfinite(datachunks)
and datachunks > 0:
3463 chunklengths = [len(ts[det])]
3466 for cl
in chunklengths:
3467 endidx = startidx + cl
3473 thisdata = data[det][startidx:endidx] / nstd[startidx:endidx]
3474 ast = As[startidx:endidx] / nstd[startidx:endidx]
3475 bst = Bs[startidx:endidx] / nstd[startidx:endidx]
3479 AB = np.dot(ast, bst)
3481 dA1real = np.dot(thisdata.real, ast)
3482 dA1imag = np.dot(thisdata.imag, ast)
3484 dB1real = np.dot(thisdata.real, bst)
3485 dB1imag = np.dot(thisdata.imag, bst)
3487 dd1real = np.sum(thisdata.real**2)
3488 dd1imag = np.sum(thisdata.imag**2)
3490 P1 = A * C2P2 + B * S2P2 + 2.0 * AB * C2PS2P
3491 P2 = B * C2P2 + A * S2P2 - 2.0 * AB * C2PS2P
3492 P3 = AB * (C2P2 - S2P2) - A * C2PS2P + B * C2PS2P
3494 hr2 = (Apcosphi_2**2) * P1 + (Acsinphi_2**2) * P2 + Acpsphicphi_2 * P3
3495 hi2 = (Apsinphi_2**2) * P1 + (Accosphi_2**2) * P2 - Acpsphicphi_2 * P3
3497 d1hr = Apcosphi_2 * (dA1real * COS2PSI + dB1real * SIN2PSI) + Acsinphi_2 * (
3498 dB1real * COS2PSI - dA1real * SIN2PSI
3500 d1hi = Apsinphi_2 * (dA1imag * COS2PSI + dB1imag * SIN2PSI) - Accosphi_2 * (
3501 dB1imag * COS2PSI - dA1imag * SIN2PSI
3504 chiSq = dd1real + dd1imag + H02 * (hr2 + hi2) - 2.0 * H0S * (d1hr + d1hi)
3506 if liketype ==
"gaussian":
3507 like -= 0.5 * (chiSq)
3508 like -= (cl * np.log(2.0 * np.pi)) + 2.0 * np.sum(
3509 np.log(nstd[startidx:endidx])
3511 noiselike -= 0.5 * (dd1real + dd1imag)
3512 noiselike -= (cl * np.log(2.0 * np.pi)) + 2.0 * np.sum(
3513 np.log(nstd[startidx:endidx])
3516 like -=
float(cl) * np.log(chiSq)
3517 like += gammaln(cl) - np.log(2.0) - cl * np.log(np.pi)
3518 noiselike -=
float(cl) * np.log(dd1real + dd1imag)
3519 noiselike += gammaln(cl) - np.log(2.0) - cl * np.log(np.pi)
3527 sigev =
marginal(like,
"all", params, lingrids)
3539 posts[p] = np.exp(
marginal(like, p, params, lingrids))
3542 like, p, params, lingrids, multflatprior=
True
3546 evrat = sigev - noiselike
3561ATNF_VERSION =
"1.58"
3566 Get the pulsar (psr) distance (DIST in kpc), proper motion corrected period derivative (P1_I)
and any association
3567 (ASSOC e.g. GC)
from the ATNF catalogue.
3572 psrname = re.sub(
r"\+",
"%2B", psr)
3575 "http://www.atnf.csiro.au/people/pulsar/psrcat/proc_form.php?version="
3578 atnfurl +=
"&Dist=Dist&Assoc=Assoc&P1_i=P1_i"
3580 "&startUserDefined=true&c1_val=&c2_val=&c3_val=&c4_val=&sort_attr=jname&sort_order=asc&condition=&pulsar_names="
3583 atnfurl +=
"&ephemeris=selected&submit_ephemeris=Get+Ephemeris&coords_unit=raj%2Fdecj&radius=&coords_1=&coords_2="
3584 atnfurl +=
"&style=Long+with+last+digit+error&no_value=*&fsize=3&x_axis=&x_scale=linear&y_axis=&y_scale=linear&state=query"
3587 urldat = requests.get(atnfurl)
3589 r"<pre[^>]*>([^<]+)</pre>",
str(urldat.content)
3592 predat.group(1).strip().split(
r"\n")
3596 "Warning... could not get information from ATNF pulsar catalogue.",
3605 for line
in [p
for p
in pdat
if len(p) != 0]:
3606 if "WARNING" in line
or "not in catalogue" in line:
3609 if "DIST" in vals[0]:
3610 dist =
float(vals[1])
3611 if "P1_I" in vals[0]:
3612 age =
float(vals[1])
3613 if "ASSOC" in vals[0]:
3616 return (dist, p1_I, assoc, atnfurl)
3621 Convert a covariance matrix to a correlation coefficient matrix.
3622 Return the correlation coefficient matrix and the standard deviations
3623 from the covariance matrix.
3627 sigmas = np.sqrt(np.diag(cov))
3630 D = sigmas * np.identity(cov.shape[0])
3633 Dinv = np.linalg.inv(D)
3636 Ccor = np.dot(np.dot(Dinv, cov), Dinv)
def __init__(self, parfilenm)
This class parses a TEMPO(2)-style pulsar parameter file.
def __getitem__(self, key)
def __init__(self, priorfilenm)
def __getitem__(self, key)
def heterodyned_pulsar_signal(pardict, detector, starttime=900000000.0, duration=86400.0, dt=60.0, datatimes=None)
def quadrupole_to_h0(q22, freq, dist)
def rad_to_hms(rad)
rad_to_hms(rad): Convert radians to hours, minutes, and seconds of arc.
def dec_to_rad(dec_string)
dec_to_rad(dec_string): Given a string containing DEC information as 'dd:mm:ss.ssss',...
def hms_to_rad(hour, mins, sec)
hms_to_rad(hour, min, sec): Convert hours, minutes, and seconds of arc to radians
def cov_to_cor(cov)
Convert a covariance matrix to a correlation coefficient matrix.
def pulsar_mcmc_to_posterior(chainfiles)
def heterodyned_pinsf_pulsar(starttime, duration, dt, detector, pardict)
def plot_posterior_hist(poslist, param, ifos, parambounds=[float("-inf"), float("inf")], nbins=50, upperlimit=0, overplot=False, parfile=None, mplparams=False)
def dms_to_rad(deg, mins, sec)
dms_to_rad(deg, min, sec): Convert degrees, minutes, and seconds of arc to radians.
def pulsar_posterior_grid(dets, ts, data, ra, dec, sigmas=None, paramranges={}, datachunks=30, chunkmin=5, ngrid=50, outputlike=False)
A function to calculate the 4-parameter posterior probability density for a continuous wave signal gi...
def rad_to_string(rad, ra_or_dec)
rad_to_string(rad, ra_or_dec): Convert an angle in radians to hours/degrees, minutes seconds and outp...
def ra_to_rad(ra_string)
ra_to_rad(ar_string): Given a string containing RA information as 'hh:mm:ss.ssss',...
def pferrs(porf, porferr, pdorfd=None, pdorfderr=None)
pferrs(porf, porferr, pdorfd=None, pdorfderr=None): Calculate the period or frequency errors and the ...
def plot_limits_hist(lims, param, ifos, prevlims=None, bins=20, overplot=False, mplparams=False)
def marginalise(like, pname, pnames, ranges)
def pulsar_estimate_snr(source, det, tstart, duration, Sn, dt=1800)
A function to estimate the signal-to-noise ratio of a pulsar signal (for a triaxial neutron star emit...
def read_pulsar_mcmc_file(cf)
def heterodyned_triaxial_pulsar(starttime, duration, dt, detector, pardict)
def convert_model_parameters(pardict)
def coord_to_string(h_or_d, m, s)
coord_to_string(h_or_d, m, s): Return a formatted string of RA or DEC values as 'hh:mm:ss....
def logtrapz(lnf, dx)
Perform trapezium rule integration for the logarithm of a function on a regular grid.
def gelman_rubins(chains)
def pulsar_nest_to_posterior(postfile, nestedsamples=False, removeuntrig=True)
This function will import a posterior sample file created by lalapps_nest2pos (or a nested sample fil...
def phipsiconvert(phipchain, psipchain)
def upper_limit_greedy(pos, upperlimit=0.95, nbins=100)
def marginal(lnlike, pname, pnames, ranges, multflatprior=False)
def pulsar_estimate_h0_from_snr(snr, source, det, tstart, duration, Sn, dt=600)
A function to estimate the signal amplitude of a pulsar signal (for a triaxial neutron star emitting ...
def plot_posterior_hist2D(poslist, params, ifos, bounds=None, nbins=[50, 50], parfile=None, overplot=False, mplparams=False)
def get_chunk_lengths(ts, chunkMax)
def tukey_window(N, alpha=0.5)
def read_hist_from_file(histfile)
def h0_to_quadrupole(h0, freq, dist)
def get_optimal_snr(s, sig)
def hist_norm_bounds(samples, nbins, low=float("-inf"), high=float("inf"))
def plot_2Dhist_from_file(histfile, ndimlabel, mdimlabel, margpars=True, mplparams=False)
def spin_down_limit(freq, fdot, dist)
def inject_pulsar_signal(starttime, duration, dt, detectors, pardict, freqfac=[2.0], npsds=None, snrscale=None)
def antenna_response(gpsTime, ra, dec, psi, det)
def upper_limit(pos, upperlimit=0.95, parambounds=[float("-inf"), float("inf")], nbins=50)
def detector_noise(det, f)
def plot_posterior_chain(poslist, param, ifos, grr=None, withhist=0, mplparams=False)
def get_atnf_info(psr)
Get the pulsar (psr) distance (DIST in kpc), proper motion corrected period derivative (P1_I) and any...
def plot_h0_lims(h0lims, f0gw, ifos, xlims=[10, 1500], ulesttop=None, ulestbot=None, prevlim=None, prevlimf0gw=None, overplot=False, mplparams=False)
def dms_to_deg(deg, mins, sec)
dms_to_deg(deg, min, sec): Convert degrees, minutes, and seconds of arc to degrees.
def rad_to_dms(rad)
rad_to_dms(rad): Convert radians to degrees, minutes, and seconds of arc.
def plot_Bks_ASDs(Bkdata, delt=86400, plotpsds=True, plotfscan=False, removeoutlier=None, mplparams=False)
def p_to_f(p, pd, pdd=None)
p_to_f(p, pd, pdd=None): Convert period, period derivative and period second derivative to the equiva...
def h0ul_from_prior_file(priorfile, ulval=0.95)
def h0_to_ellipticity(h0, freq, dist)