Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

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

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

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

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

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

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

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

506

507

508

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

538

539

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

802

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

828

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

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

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

941

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

992

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

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

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

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

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

1249

1250

1251

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

1398

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

1516

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

1559

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

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

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

1716

1717

1718

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

1825

1826

1827

1828

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

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

#!/usr/local/bin/python 

# encoding: utf-8 

""" 

*Plot the maps showing the timeline of observations of the gravitation wave sky-locations* 

 

:Author: 

David Young 

 

:Date Created: 

November 5, 2015 

""" 

################# GLOBAL IMPORTS #################### 

# SUPPRESS MATPLOTLIB WARNINGS 

from __future__ import unicode_literals 

import warnings 

warnings.filterwarnings("ignore") 

import sys 

import os 

os.environ['TERM'] = 'vt100' 

import healpy as hp 

import numpy as np 

import math 

from datetime import datetime 

import matplotlib 

import matplotlib.cm as cm 

import matplotlib.pyplot as plt 

from matplotlib.collections import PatchCollection 

# from shapely.geometry import Point 

# from shapely.ops import cascaded_union 

from matplotlib.path import Path 

from matplotlib.pyplot import savefig 

import matplotlib.patches as patches 

import matplotlib.path as mpath 

from matplotlib.projections.geo import GeoAxes 

from astropy import wcs as awcs 

from astropy.io import fits 

from fundamentals import tools, times 

from fundamentals.mysql import readquery 

from crowdedText import adjust_text 

from astrocalc.times import now 

 

 

class ThetaFormatterShiftPi(GeoAxes.ThetaFormatter): 

"""Shifts labelling by pi 

Shifts labelling from -180,180 to 0-360""" 

 

def __call__(self, x, pos=None): 

if x != 0: 

x *= -1 

if x < 0: 

x += 2 * np.pi 

return GeoAxes.ThetaFormatter.__call__(self, x, pos) 

 

 

class plot_wave_observational_timelines(): 

""" 

*TPlot the maps showing the timeline of observations of the gravitation wave sky-locations* 

 

You can plot either the history (looking back from now) or timeline (looking forward from date of GW detection) of the survey. 

 

**Key Arguments:** 

- ``log`` -- logger 

- ``settings`` -- the settings dictionary 

- ``plotType`` -- history (looking back from now) or timeline (looking forward from date of GW detection) 

- ``gwid`` -- a given graviational wave ID. If given only maps for this wave shall be plotted. Default *False* (i.e. plot all waves) 

- ``projection`` -- projection for the plot. Default *mercator* [mercator|gnomonic|mollweide] 

- ``probabilityCut`` -- remove footprints where probability assigned to the healpix pixel found at the center of the exposure is ~0.0. Default *False* 

- ``databaseConnRequired`` -- are the database connections going to be required? Default *True* 

- ``allPlots`` -- plot all timeline plot (including the CPU intensive -21-0 days and all transients/footprints plots). Default *False* 

- ``telescope`` -- select an individual telescope. Default *False*. [ps1|atlas] 

- ``timestamp`` -- add a timestamp to the plot to show when it was created. Default *True* 

- ``filters`` -- only plot certain filters. Default *False* 

 

**Usage:** 

 

To plot a the history of a specific wave: 

 

.. code-block:: python 

 

from breaker.plots import plot_wave_observational_timelines 

plotter = plot_wave_observational_timelines( 

log=log, 

settings=settings, 

plotType="history", 

gwid="G184098", 

projection="mercator" 

) 

plotter.get() 

 

or to plot all waves in the settings file with a mollweide projection: 

 

.. code-block:: python 

 

from breaker.plots import plot_wave_observational_timelines 

plotter = plot_wave_observational_timelines( 

log=log, 

settings=settings, 

plotType="history", 

projection="mollweide" 

) 

plotter.get() 

 

To plot the timeline of the survey, change ``plotType="timeline"``: 

 

.. code-block:: python 

 

from breaker.plots import plot_wave_observational_timelines 

plotter = plot_wave_observational_timelines( 

log=log, 

settings=settings, 

plotType="timeline" 

) 

plotter.get() 

""" 

# Initialisation 

 

def __init__( 

self, 

log, 

settings=False, 

plotType=False, 

gwid=False, 

projection="mercator", 

probabilityCut=False, 

databaseConnRequired=True, 

allPlots=False, 

telescope=False, 

timestamp=True, 

filters=False 

): 

self.log = log 

log.debug("instantiating a new 'plot_wave_observational_timelines' object") 

self.settings = settings 

self.plotType = plotType 

self.gwid = gwid 

self.projection = projection 

self.probabilityCut = probabilityCut 

self.allPlots = allPlots 

self.telescope = telescope 

self.timestamp = timestamp 

self.filters = filters 

 

# xt-self-arg-tmpx 

 

# Initial Actions 

 

if self.settings and databaseConnRequired: 

# CONNECT TO THE VARIOUS DATABASES REQUIRED 

from breaker import database 

db = database( 

log=self.log, 

settings=self.settings 

) 

self.ligo_virgo_wavesDbConn, self.ps1gwDbConn, self.cataloguesDbConn, self.atlasDbConn, self.ps13piDbConn = db.get() 

else: 

self.ligo_virgo_wavesDbConn, self.ps1gwDbConn, self.cataloguesDbConn = False, False, False 

 

self.log.debug( 

'connected to databases') 

 

return None 

 

def get(self): 

""" 

*Generate the plots* 

""" 

self.log.info('starting the ``get`` method') 

 

if self.plotType == "history": 

self.get_history_plots() 

elif self.plotType == "timeline": 

self.get_timeline_plots() 

 

self.log.info('completed the ``get`` method') 

return None 

 

def get_gw_parameters_from_settings( 

self, 

gwid, 

inPastDays=False, 

inFirstDays=False, 

maxProbCoordinate=[0, 0]): 

""" 

*Query the settings file and database for PS1 Pointings, PS1 discovered transients and plot parameters relatiing to the given gravitational wave (``gwid``)* 

 

**Key Arguments:** 

- ``gwid`` -- the unique ID of the gravitational wave to plot 

- ``inPastDays`` -- used for the `history` plots (looking back from today) 

- ``inFirstDays`` -- used in the `timeline` plots (looking forward from wave detection). A tuple (start day, end day). 

- ``maxProbCoordinate`` -- the sky-coordiante of the pixel containing the highest likelihood (calculated from map). 

 

**Return:** 

- ``plotParameters`` -- the parameters used for the plots 

- ``ps1Transients`` -- the transients to add to the plot 

- ``ps1Pointings`` -- the pointings to place on the plot 

 

**Usage:** 

 

.. code-block:: python 

 

from breaker.plots import plot_wave_observational_timelines 

plotter = plot_wave_observational_timelines( 

log=log, 

settings=settings 

) 

plotParameters, ps1Transients, ps1Pointings, atlasPointings, atlasTransients = plotter.get_gw_parameters_from_settings( 

gwid="G211117" 

) 

print plotParameters 

 

# OUT: {'raRange': 90.0, 'centralCoordinate': [55.0, 27.5], 

# 'decRange': 85.0} 

 

print ps1Transients 

 

# OUT: ({'local_designation': u'5L3Gbaj', 'ra_psf': 

# 39.29767123836419, 'ps1_designation': u'PS15don', 'dec_psf': 

# 19.055638423458053}, {'local_designation': u'5L3Gcbu', 

# 'ra_psf': 40.06271352712189, 'ps1_designation': u'PS15dox', 

# 'dec_psf': 22.536709765810823}, {'local_designation': 

# u'5L3Gcca', 'ra_psf': 41.97569854977185, 'ps1_designation': 

# u'PS15doy', 'dec_psf': 21.773344501616435}, 

# {'local_designation': u'5L3Gbla', 'ra_psf': 

# 50.732664347994714, 'ps1_designation': u'PS15dcq', 'dec_psf': 

# 34.98988923347591}, {'local_designation': u'6A3Gcvu', 

# 'ra_psf': 34.77565307934415, 'ps1_designation': u'PS16ku', 

# 'dec_psf': 10.629310832257824}, {'local_designation': 

# u'5L3Gcel', 'ra_psf': 38.24898916543392, 'ps1_designation': 

# u'PS15dpn', 'dec_psf': 18.63530332013424}, 

# {'local_designation': u'5L3Gcvk', 'ra_psf': 

# 40.13754684778398, 'ps1_designation': u'PS15dpz', 'dec_psf': 

# 23.003023065333267}, .... 

 

print ps1Pointings 

 

# OUT: ({'raDeg': 37.1814041667, 'mjd': 57388.2124067, 

# 'decDeg': 18.9258969444}, {'raDeg': 37.1813666667, 'mjd': 

# 57388.2140101, 'decDeg': 18.9259066667}, ... 

 

It can also be useful to give time-limits for the request to get the observations and discoveries from the past few days (``inPastDays``), or for the first few days after wave detection (``inFirstDays``). So for the past week: 

 

from breaker.plots import plot_wave_observational_timelines 

plotter = plot_wave_observational_timelines( 

log=log, 

settings=settings 

) 

plotParameters, ps1Transients, ps1Pointings, atlasPointings, atlasTransients = plotter.get_gw_parameters_from_settings( 

gwid="G211117", 

inPastDays=7 

) 

 

Or the first 3 days since wave detection: 

 

from breaker.plots import plot_wave_observational_timelines 

plotter = plot_wave_observational_timelines( 

log=log, 

settings=settings 

) 

plotParameters, ps1Transients, ps1Pointings, atlasPointings, atlasTransients = plotter.get_gw_parameters_from_settings( 

gwid="G211117", 

inFirstDays=(0,3) 

) 

""" 

self.log.info( 

'starting the ``get_gw_parameters_from_settings`` method') 

 

plotParameters = self.settings["gravitational waves"][gwid]["plot"] 

 

if "centralCoordinate" not in plotParameters: 

plotParameters["centralCoordinate"] = maxProbCoordinate 

 

# GRAB PS1 TRANSIENTS FROM THE DATABASE 

ps1Transients, atlasTransients = self._get_ps1_transient_candidates( 

gwid=gwid, 

mjdStart=self.settings["gravitational waves"][ 

gwid]["mjd"], 

mjdEnd=self.settings["gravitational waves"][ 

gwid]["mjd"] + 31., 

plotParameters=plotParameters, 

inPastDays=inPastDays, 

inFirstDays=inFirstDays, 

maxProbCoordinate=maxProbCoordinate 

) 

 

self.log.debug( 

'finished getting the PS1 transients') 

 

# GRAB PS1 & ATLAS POINTINGS FROM THE DATABASE 

ps1Pointings = self._get_ps1_pointings(gwid, inPastDays, inFirstDays) 

atlasPointings = self._get_atlas_pointings( 

gwid, inPastDays, inFirstDays) 

 

self.log.info( 

'completed the ``get_gw_parameters_from_settings`` method') 

 

if self.telescope == "ps1": 

atlasPointings = [] 

atlasTransients = [] 

elif self.telescope == "atlas": 

ps1Transients = [] 

ps1Pointings = [] 

 

return plotParameters, ps1Transients, ps1Pointings, atlasPointings, atlasTransients 

 

def _get_ps1_transient_candidates( 

self, 

gwid, 

mjdStart, 

mjdEnd, 

plotParameters, 

inPastDays, 

inFirstDays, 

maxProbCoordinate): 

""" 

*get ps1 transient candidates* 

 

**Key Arguments:** 

- ``gwid`` -- the gravitational wave id 

- ``mjdStart`` -- earliest mjd of discovery 

- ``mjdEnd`` -- latest mjd of discovery 

- ``plotParameters`` -- the parameters of the plot (for spatial & temporal parameters etc) 

- ``inPastDays`` -- used for the `history` plots (looking back from today) 

- ``inFirstDays`` -- used in the `timeline` plots (looking forward from wave detection). A tuple (start day, end day). 

 

**Return:** 

- ``ps1Transients`` -- the transients to add to the plot 

""" 

self.log.info('starting the ``_get_ps1_transient_candidates`` method') 

 

# UNPACK THE PLOT PARAMETERS 

if "centralCoordinate" in plotParameters: 

centralCoordinate = plotParameters["centralCoordinate"] 

else: 

centralCoordinate = maxProbCoordinate 

 

raRange = plotParameters["raRange"] 

decRange = plotParameters["decRange"] 

 

raMax = centralCoordinate[0] + raRange / 2. 

raMin = centralCoordinate[0] - raRange / 2. 

decMax = centralCoordinate[1] + decRange / 2. 

decMin = centralCoordinate[1] - decRange / 2. 

 

if inPastDays: 

nowMjd = now( 

log=self.log 

).get_mjd() 

mjdStart = nowMjd - inPastDays 

mjdEnd = 1000000000000000 

 

if inFirstDays: 

mjdStart = self.settings["gravitational waves"][ 

gwid]["mjd"] + inFirstDays[0] 

mjdEnd = self.settings["gravitational waves"][ 

gwid]["mjd"] + inFirstDays[1] 

if inFirstDays[1] == 0 and inFirstDays[0] == 0: 

mjdEnd = 10000000000 

 

if raMin >= 0 and raMax < 360.: 

sqlQuery = u""" 

SELECT ps1_designation, local_designation, ra_psf, dec_psf FROM tcs_transient_objects o, tcs_latest_object_stats s where o.detection_list_id in (1,2) and o.id=s.id and (s.earliest_mjd between %(mjdStart)s and %(mjdEnd)s) and (ra_psf between %(raMin)s and %(raMax)s) and (`dec_psf` between %(decMin)s and %(decMax)s) ; 

""" % locals() 

elif raMin < 0.: 

praMin = 360. + raMin 

sqlQuery = u""" 

SELECT ps1_designation, local_designation, ra_psf, dec_psf FROM tcs_transient_objects o, tcs_latest_object_stats s where o.detection_list_id in (1,2) and o.id=s.id and (s.earliest_mjd between %(mjdStart)s and %(mjdEnd)s) and ((ra_psf between %(praMin)s and 360.) or (ra_psf between 0. and %(raMax)s)) and (`dec_psf` between %(decMin)s and %(decMax)s) ; 

""" % locals() 

elif raMax > 360.: 

praMax = raMax - 360. 

sqlQuery = u""" 

SELECT ps1_designation, local_designation, ra_psf, dec_psf FROM tcs_transient_objects o, tcs_latest_object_stats s where o.detection_list_id in (1,2) and o.id=s.id and (s.earliest_mjd between %(mjdStart)s and %(mjdEnd)s) and ((ra_psf between %(raMin)s and 360.) or (ra_psf between 0. and %(praMax)s)) and (`dec_psf` between %(decMin)s and %(decMax)s) ; 

""" % locals() 

 

ps1Transients = readquery( 

log=self.log, 

sqlQuery=sqlQuery, 

dbConn=self.ps1gwDbConn 

) 

 

if raMin > 0 and raMax < 360.: 

sqlQuery = u""" 

SELECT atlas_designation, ra, `dec` FROM atlas_diff_objects o, tcs_latest_object_stats s where o.detection_list_id in (1,2) and o.id=s.id and (s.earliest_mjd between %(mjdStart)s and %(mjdEnd)s) and (ra between %(raMin)s and %(raMax)s) and (`dec` between %(decMin)s and %(decMax)s) ; 

""" % locals() 

elif raMin < 0.: 

araMin = 360. + raMin 

sqlQuery = u""" 

SELECT atlas_designation, ra, `dec` FROM atlas_diff_objects o, tcs_latest_object_stats s where o.detection_list_id in (1,2) and o.id=s.id and (s.earliest_mjd between %(mjdStart)s and %(mjdEnd)s) and ((ra between %(araMin)s and 360.) or (ra between 0. and %(raMax)s)) and (`dec` between %(decMin)s and %(decMax)s) ; 

""" % locals() 

elif raMax > 360.: 

araMax = raMax - 360. 

sqlQuery = u""" 

SELECT atlas_designation, ra, `dec` FROM atlas_diff_objects o, tcs_latest_object_stats s where o.detection_list_id in (1,2) and o.id=s.id and (s.earliest_mjd between %(mjdStart)s and %(mjdEnd)s) and ((ra between %(raMin)s and 360.) or (ra between 0. and %(araMax)s)) and (`dec` between %(decMin)s and %(decMax)s) ; 

""" % locals() 

 

atlasTransients = readquery( 

log=self.log, 

sqlQuery=sqlQuery, 

dbConn=self.atlasDbConn 

) 

 

self.log.info('completed the ``_get_ps1_transient_candidates`` method') 

return ps1Transients, atlasTransients 

 

def _get_ps1_pointings( 

self, 

gwid, 

inPastDays, 

inFirstDays): 

""" 

*get ps1 pointings to add to the plot* 

 

**Key Arguments:** 

- ``gwid`` -- the unique ID of the gravitational wave to plot 

- ``inPastDays`` -- used for the `history` plots (looking back from today) 

- ``inFirstDays`` -- used in the `timeline` plots (looking forward from wave detection). A tuple (start day, end day). 

 

**Return:** 

- ``ps1Pointings`` -- the pointings to place on the plot 

""" 

self.log.info('starting the ``_get_ps1_pointings`` method') 

 

# DETERMINE THE TEMPORAL CONSTRAINTS FOR MYSQL QUERY 

if inPastDays != False or inPastDays == 0: 

nowMjd = now( 

log=self.log 

).get_mjd() 

mjdStart = nowMjd - inPastDays 

mjdEnd = 10000000000 

if inPastDays == 0: 

mjdStart = 0.0 

 

if inFirstDays: 

mjdStart = self.settings["gravitational waves"][ 

gwid]["mjd"] + inFirstDays[0] 

mjdEnd = self.settings["gravitational waves"][ 

gwid]["mjd"] + inFirstDays[1] 

if inFirstDays[1] == 0 and inFirstDays[0] == 0: 

mjdEnd = 10000000000 

 

if inPastDays == False and inFirstDays == False: 

mjdStart = self.settings["gravitational waves"][gwid]["mjd"] 

mjdEnd = self.settings["gravitational waves"][ 

gwid]["mjd"] + 31. 

 

sqlQuery = u""" 

SELECT raDeg, decDeg, mjd, exp_time, filter, limiting_mag FROM ps1_pointings where gw_id like "%%%(gwid)s%%" and mjd between %(mjdStart)s and %(mjdEnd)s 

""" % locals() 

 

sqlQuery = u""" 

SELECT raDeg, decDeg, mjd_registered as mjd, etime as exp_time, f as filter FROM ps1_nightlogs where gw_id like "%%%(gwid)s%%" and mjd_registered between %(mjdStart)s and %(mjdEnd)s 

""" % locals() 

 

if self.filters: 

filters = ' and filter in ("' + ('", "').join(self.filters) + '")' 

else: 

filters = "" 

 

sqlQuery = u""" 

SELECT distinct * from ( 

SELECT distinct raDeg, decDeg, mjd, filter, p.skycell_id as exp_id FROM ps1_stack_stack_diff_skycells p, ps1_skycell_gravity_event_annotations s, ps1_skycell_map m where mjd between %(mjdStart)s and %(mjdEnd)s and p.skycell_id=s.skycell_id and p.skycell_id=m.skycell_id and gracedb_id = "%(gwid)s" %(filters)s 

UNION 

SELECT distinct raDeg, decDeg, mjd, filter, p.skycell_id as exp_id FROM ps1_warp_stack_diff_skycells p, ps1_skycell_gravity_event_annotations s, ps1_skycell_map m where mjd between %(mjdStart)s and %(mjdEnd)s and p.skycell_id=s.skycell_id and p.skycell_id=m.skycell_id and gracedb_id = "%(gwid)s" %(filters)s) p order by mjd; 

""" % locals() 

 

# # STACK-STACK ONLY 

# sqlQuery = u""" 

# SELECT raDeg, decDeg, mjd, exp_time, filter, p.skycell_id, limiting_mag as limiting_magnitude, "stack" as diff_type, filename as exp_id FROM ps1_stack_stack_diff_skycells p, panstarrs_rings_v3_skycell_map s where mjd between %(mjdStart)s and %(mjdEnd)s and p.skycell_id=s.skycell_id order by mjd; 

# """ % locals() 

 

ps1Pointings = readquery( 

log=self.log, 

sqlQuery=sqlQuery, 

dbConn=self.ligo_virgo_wavesDbConn 

) 

 

self.log.info('completed the ``_get_ps1_pointings`` method') 

return ps1Pointings 

 

def _get_atlas_pointings( 

self, 

gwid, 

inPastDays, 

inFirstDays): 

""" 

*get atlas pointings to add to the plot* 

 

**Key Arguments:** 

- ``gwid`` -- the unique ID of the gravitational wave to plot 

- ``inPastDays`` -- used for the `history` plots (looking back from today) 

- ``inFirstDays`` -- used in the `timeline` plots (looking forward from wave detection). A tuple (start day, end day). 

 

**Return:** 

- ``atlasPointings`` -- the pointings to place on the plot 

""" 

self.log.info('starting the ``_get_atlas_pointings`` method') 

 

# DETERMINE THE TEMPORAL CONSTRAINTS FOR MYSQL QUERY 

if inPastDays != False or inPastDays == 0: 

nowMjd = now( 

log=self.log 

).get_mjd() 

mjdStart = nowMjd - inPastDays 

mjdEnd = 10000000000 

if inPastDays == 0: 

mjdStart = 0.0 

 

if inFirstDays: 

mjdStart = self.settings["gravitational waves"][ 

gwid]["mjd"] + inFirstDays[0] 

mjdEnd = self.settings["gravitational waves"][ 

gwid]["mjd"] + inFirstDays[1] 

if inFirstDays[1] == 0 and inFirstDays[0] == 0: 

mjdEnd = 10000000000 

 

if inPastDays == False and inFirstDays == False: 

mjdStart = self.settings["gravitational waves"][gwid]["mjd"] 

mjdEnd = self.settings["gravitational waves"][ 

gwid]["mjd"] + 31. 

 

sqlQuery = u""" 

SELECT atlas_object_id as exp_id, raDeg, decDeg, mjd, exp_time, filter, limiting_magnitude FROM atlas_pointings where gw_id like "%%%(gwid)s%%" and mjd between %(mjdStart)s and %(mjdEnd)s group by atlas_object_id; 

""" % locals() 

 

atlasPointings = readquery( 

log=self.log, 

sqlQuery=sqlQuery, 

dbConn=self.ligo_virgo_wavesDbConn 

) 

 

self.log.info('completed the ``_get_atlas_pointings`` method') 

return atlasPointings 

 

def generate_probability_plot( 

self, 

pathToProbMap, 

gwid, 

mjdStart=False, 

timeLimitLabel=False, 

timeLimitDay=False, 

fileFormats=["pdf"], 

folderName="", 

plotType="timeline", 

plotParameters=False, 

ps1Transients=[], 

atlasTransients=[], 

ps1Pointings=[], 

atlasPointings=[], 

projection="mercator", 

raLimit=False, 

probabilityCut=False, 

outputDirectory=False, 

fitsImage=False, 

allSky=False, 

center=False): 

""" 

*Generate a single probability map plot for a given gravitational wave and save it to file* 

 

**Key Arguments:** 

- ``gwid`` -- the unique ID of the gravitational wave to plot 

- ``plotParameters`` -- the parameters of the plot (for spatial & temporal parameters etc). 

- ``ps1Transients`` -- the PS1 transients to add to the plot. Default **[]** 

- ``atlasTransients`` -- the ATLAS transients to add to the plot. Default **[]** 

- ``ps1Pointings`` -- the PS1 pointings to place on the plot. Default **[]** 

- ``atlasPointings`` -- the atlas pointings to add to the plot. Default **[]** 

- ``pathToProbMap`` -- path to the FITS file containing the probability map of the wave 

- ``mjdStart`` -- earliest mjd of discovery 

- ``timeLimitLabel`` -- the labels of the time contraints (for titles) 

- ``timeLimitDay`` -- the time limits (in ints) 

- ``raLimit`` -- ra limit at twilight 

- ``fileFormats`` -- the format(s) to output the plots in (list of strings) Default **["pdf"]** 

- ``folderName`` -- the name of the folder to add the plots to 

- ``plotType`` -- history (looking back from now) or timeline (looking forward from date of GW detection). Default **timeline** 

- ``projection`` -- projection for the plot. Default *mercator*. [mercator|mollweide|gnomonic] 

- ``probabilityCut`` -- remove footprints where probability assigned to the healpix pixel found at the center of the exposure is ~0.0. Default *False* 

- ``outputDirectory`` -- can be used to override the output destination in the settings file 

- ``fitsImage`` -- generate a FITS image file of map 

- ``allSky`` -- generate an all-sky map (do not use the ra, dec window in the breaker settings file). Default *False* 

- ``center`` -- central longitude in degrees. Default *0*. 

 

 

**Return:** 

- None 

 

**Usage:** 

 

First you neeed to collect your data and a few plot parameters: 

 

.. code-block:: python 

 

from breaker.plots import plot_wave_observational_timelines 

plotter = plot_wave_observational_timelines( 

log=log, 

settings=settings 

) 

plotParameters, ps1Transients, ps1Pointings, atlasPointings, atlasTransients = plotter.get_gw_parameters_from_settings( 

gwid="G211117", 

inFirstDays=(0,7) 

) 

 

Then you can pass in these parameter to generate a plot: 

 

.. code-block:: python 

 

plotter.generate_probability_plot( 

gwid="G211117", 

plotParameters=plotParameters, 

ps1Transients=ps1Transients, 

atlasTransient=atlasTransient, 

ps1Pointings=ps1Pointings, 

atlasPointings=altasPointings, 

pathToProbMap="/Users/Dave/config/breaker/maps/G211117/LALInference_skymap.fits", 

mjdStart=57382., 

timeLimitLabel="", 

timeLimitDay=(0, 5), 

raLimit=False, 

fileFormats=["pdf"], 

folderName="survey_timeline_plots", 

projection="mercator", 

plotType="timeline", 

probabilityCut=True, 

outputDirectory=False 

) 

 

""" 

self.log.info('starting the ``generate_probability_plot`` method') 

 

import matplotlib.pyplot as plt 

import healpy as hp 

from matplotlib.font_manager import FontProperties 

font = FontProperties() 

 

# HEALPY REQUIRES RA, DEC IN RADIANS AND AS TWO SEPERATE ARRAYS 

import math 

pi = (4 * math.atan(1.0)) 

DEG_TO_RAD_FACTOR = pi / 180.0 

RAD_TO_DEG_FACTOR = 180.0 / pi 

 

# VARIABLES 

font.set_family("Arial") 

pixelSizeDeg = 0.066667 

unit = "likelihood" 

cmap = "YlOrRd" 

colorBar = False 

 

# DETERMINE PATH TO MAP AND IF IT IS THE PREFERRED MAP AT THIS TIME 

bestMap = False 

if pathToProbMap is None or not pathToProbMap: 

pathToProbMap = self.settings[ 

"gravitational waves"][gwid]["mapPath"] 

 

pathToProbMap = os.path.abspath(pathToProbMap) 

 

if gwid in self.settings["gravitational waves"]: 

bestMapPath = self.settings[ 

"gravitational waves"][gwid]["mapPath"] 

bestMapPath = os.path.abspath(bestMapPath) 

if pathToProbMap == bestMapPath: 

bestMap = True 

 

mapBasename = os.path.basename(pathToProbMap) 

mapBasename = os.path.splitext(mapBasename)[0] 

mapBasename = os.path.splitext(mapBasename)[0] 

mapBasename = os.path.splitext(mapBasename)[0] 

 

# INITIALISE FIGURE 

fig = plt.figure() 

 

# READ HEALPIX MAPS FROM FITS FILE 

# THIS FILE IS A ONE COLUMN FITS BINARY, WITH EACH CELL CONTAINING AN 

# ARRAY OF PROBABILITIES (3,072 ROWS) 

# READ IN THE HEALPIX FITS FILE 

aMap, mapHeader = hp.read_map(pathToProbMap, 0, h=True, verbose=False) 

# DETERMINE THE SIZE OF THE HEALPIXELS 

nside = hp.npix2nside(len(aMap)) 

 

# MIN-MAX PROB VALUES TO ADJUST MAP CONTRAST 

vmin = min(aMap) 

vmax = max(aMap) * 0.9 

 

totalProb = sum(aMap) 

# print "Total Probability for the entire sky is %(totalProb)s" % 

# locals() 

 

# UNPACK THE PLOT PARAMETERS 

# FIND THE COORDINATES OF THE CORE LIKEIHOOD 

maxProbHealpix = aMap.argmax() 

maxCoordinate = hp.pix2ang(nside, maxProbHealpix, lonlat=True) 

print "The %(gwid)s %(mapBasename)s map's maximum likelihood is centered at %(maxCoordinate)s" % locals() 

 

if center == False: 

center = maxCoordinate[0] 

 

if plotParameters: 

centralCoordinate = plotParameters["centralCoordinate"] 

else: 

centralCoordinate = [center, 0] 

 

# CREATE A NEW WCS OBJECT 

w = awcs.WCS(naxis=2) 

# SET THE REQUIRED PIXEL SIZE 

w.wcs.cdelt = np.array([pixelSizeDeg, pixelSizeDeg]) 

# WORLD COORDINATES AT REFERENCE PIXEL 

w.wcs.crval = centralCoordinate 

 

projectionDict = { 

"mollweide": "MOL", 

"gnomonic": "MER", 

"mercator": "MER", 

"cartesian": "CAR" 

} 

 

if projection in ["mollweide"]: 

# MAP VISULISATION RATIO IS ALWAYS 1/2 

xRange = 2000 

yRange = xRange / 2. 

 

# SET THE REFERENCE PIXEL TO THE CENTRE PIXEL 

w.wcs.crpix = [xRange / 2., yRange / 2.] 

 

# FULL-SKY MAP SO PLOT FULL RA AND DEC RANGES 

# DEC FROM 180 to 0 

theta = np.linspace(np.pi, 0, yRange) 

 

latitude = np.radians(np.linspace(-90, 90, yRange)) 

# RA FROM -180 to +180 

phi = np.linspace(-np.pi, np.pi, xRange) 

longitude = np.radians( 

np.linspace(-180, 180, xRange)) 

X, Y = np.meshgrid(longitude, latitude) 

 

# PROJECT THE MAP TO A RECTANGULAR MATRIX xRange X yRange 

PHI, THETA = np.meshgrid(phi, theta) 

healpixIds = hp.ang2pix(nside, THETA, PHI) 

probs = aMap[healpixIds] 

 

# healpixIds = np.reshape(healpixIds, (1, -1))[0] 

 

# CTYPE FOR THE FITS HEADER 

thisctype = projectionDict[projection] 

w.wcs.ctype = ["RA---%(thisctype)s" % 

locals(), "DEC--%(thisctype)s" % locals()] 

 

# ALL PROJECTIONS IN FITS SEEM TO BE MER 

w.wcs.ctype = ["RA---MER" % 

locals(), "DEC--MER" % locals()] 

 

stampProb = np.sum(aMap) 

print "Probability for the plot stamp is %(stampProb)s" % locals() 

 

# MATPLOTLIB IS DOING THE PROJECTION 

ax = fig.add_subplot(111, projection=projection) 

 

# RASTERIZED MAKES THE MAP BITMAP WHILE THE LABELS REMAIN VECTORIAL 

# FLIP LONGITUDE TO THE ASTRO CONVENTION 

image = ax.pcolormesh(longitude[ 

::-1], latitude, probs, rasterized=True, cmap=cmap) 

 

# GRATICULE 

ax.set_longitude_grid(30) 

ax.set_latitude_grid(15) 

ax.xaxis.set_major_formatter(ThetaFormatterShiftPi(30)) 

ax.set_longitude_grid_ends(90) 

 

# CONTOURS - NEED TO ADD THE CUMMULATIVE PROBABILITY 

i = np.flipud(np.argsort(aMap)) 

cumsum = np.cumsum(aMap[i]) 

cls = np.empty_like(aMap) 

cls[i] = cumsum * 99.99999999 * stampProb 

 

# EXTRACT CONTOUR VALUES AT HEALPIX INDICES 

contours = [] 

contours[:] = [cls[i] for i in healpixIds] 

# contours = np.reshape(np.array(contours), (yRange, xRange)) 

 

CS = ax.contour(longitude[::-1], latitude, 

contours, linewidths=.5, alpha=0.7, zorder=2) 

 

CS.set_alpha(0.5) 

CS.clabel(fontsize=10, inline=True, 

fmt='%2.1f', fontproperties=font, alpha=0.0) 

 

# COLORBAR 

if colorBar: 

cb = fig.colorbar(image, orientation='horizontal', 

shrink=.6, pad=0.05, ticks=[0, 1]) 

cb.ax.xaxis.set_label_text("likelihood") 

cb.ax.xaxis.labelpad = -8 

# WORKAROUND FOR ISSUE WITH VIEWERS, SEE COLORBAR DOCSTRING 

cb.solids.set_edgecolor("face") 

 

ax.tick_params(axis='x', labelsize=12) 

ax.tick_params(axis='y', labelsize=12) 

# lon.set_ticks_position('bt') 

# lon.set_ticklabel_position('b') 

# lon.set_ticklabel(size=20) 

# lat.set_ticklabel(size=20) 

# lon.set_axislabel_position('b') 

# lat.set_ticks_position('lr') 

# lat.set_ticklabel_position('l') 

# lat.set_axislabel_position('l') 

 

# # REMOVE TICK LABELS 

# ax.xaxis.set_ticklabels([]) 

# ax.yaxis.set_ticklabels([]) 

# # REMOVE GRID 

# ax.xaxis.set_ticks([]) 

# ax.yaxis.set_ticks([]) 

 

# REMOVE WHITE SPACE AROUND FIGURE 

spacing = 0.01 

plt.subplots_adjust(bottom=spacing, top=1 - spacing, 

left=spacing, right=1 - spacing) 

 

plt.grid(True) 

 

elif projection in ["mercator", "cartesian"]: 

 

if allSky: 

raRange = 360. 

decRange = 180. 

else: 

# UNPACK THE PLOT PARAMETERS 

raRange = plotParameters["raRange"] 

decRange = plotParameters["decRange"] 

 

raMax = centralCoordinate[0] + raRange / 2. 

raMin = centralCoordinate[0] - raRange / 2. 

decMax = centralCoordinate[1] + decRange / 2. 

decMin = centralCoordinate[1] - decRange / 2. 

 

# DETERMINE THE PIXEL GRID X,Y RANGES 

xRange = int(raRange / pixelSizeDeg) 

yRange = int(decRange / pixelSizeDeg) 

if projection == "mercator" and allSky: 

# yRange = yRange 

yRange = yRange * 2 

largest = max(xRange, yRange) 

# xRange = largest 

# yRange = largest 

 

# SET THE REFERENCE PIXEL TO THE CENTRE PIXEL 

w.wcs.crpix = [xRange / 2., yRange / 2.] 

 

# FOR AN ORTHOGONAL GRID THE CRPIX2 VALUE MUST BE ZERO AND CRPIX2 

# MUST REFLECT THIS 

w.wcs.crpix[1] -= w.wcs.crval[1] / w.wcs.cdelt[1] 

w.wcs.crval[1] = 0 

 

# USE THE "GNOMONIC" PROJECTION ("COORDINATESYS---PROJECTION") 

ctype = projectionDict[projection] 

w.wcs.ctype = ["RA---" + ctype, "DEC--" + ctype] 

 

# CREATE A PIXEL GRID - 2 ARRAYS OF X, Y 

columns = [] 

px = np.tile(np.arange(0, xRange), yRange) 

py = np.repeat(np.arange(0, yRange), xRange) 

 

# CONVERT THE PIXELS TO WORLD COORDINATES 

wr, wd = w.wcs_pix2world(px, py, 1) 

 

# MAKE SURE RA IS +VE 

nr = [] 

nr[:] = [r if r > 0 else r + 360. for r in wr] 

wr = np.array(nr) 

 

# THETA: IS THE POLAR ANGLE, RANGING FROM 0 AT THE NORTH POLE TO PI AT THE SOUTH POLE. 

# PHI: THE AZIMUTHAL ANGLE ON THE SPHERE FROM 0 TO 2PI 

# CONVERT DEC TO THE REQUIRED HEALPIX FORMAT 

nd = -wd + 90. 

 

# CONVERT WORLD TO HEALPIX INDICES 

healpixIds = hp.ang2pix(nside, theta=nd * DEG_TO_RAD_FACTOR, 

phi=wr * DEG_TO_RAD_FACTOR) 

 

# NOW READ THE VALUES OF THE MAP AT THESE HEALPIX INDICES 

uniqueHealpixIds = np.unique(healpixIds) 

probs = [] 

probs[:] = [aMap[i] for i in healpixIds] 

 

uniProb = [] 

uniProb[:] = [aMap[i] for i in uniqueHealpixIds] 

 

stampProb = np.sum(uniProb) 

print "Probability for the plot stamp is %(stampProb)s" % locals() 

 

# RESHAPE THE ARRAY AS BITMAP 

probs = np.reshape(np.array(probs), (yRange, xRange)) 

 

# CREATE THE FITS HEADER WITH WCS 

header = w.to_header() 

# CREATE THE FITS FILE 

hdu = fits.PrimaryHDU(header=header, data=probs) 

 

# GRAB THE WCS FROM HEADER GENERATED EARLIER 

from astropy.wcs import WCS 

from astropy.visualization.wcsaxes import WCSAxes 

 

wcs = WCS(hdu.header) 

# USE WCS AS THE PROJECTION 

ax = WCSAxes(fig, [0.15, 0.1, 0.8, 0.8], wcs=wcs) 

# note that the axes have to be explicitly added to the figure 

ax = fig.add_axes(ax) 

 

# PLOT MAP WITH PROJECTION IN HEADER 

im = ax.imshow(probs, 

cmap=cmap, origin='lower', alpha=0.7, zorder=1, vmin=vmin, vmax=vmax, aspect='auto') 

 

# CONTOURS - NEED TO ADD THE CUMMULATIVE PROBABILITY 

i = np.flipud(np.argsort(aMap)) 

cumsum = np.cumsum(aMap[i]) 

cls = np.empty_like(aMap) 

cls[i] = cumsum * 100 * stampProb 

cls[i] = cumsum * 100 

 

# EXTRACT CONTOUR VALUES AT HEALPIX INDICES 

contours = [] 

contours[:] = [cls[i] for i in healpixIds] 

contours = np.reshape(np.array(contours), (yRange, xRange)) 

 

# PLOT THE CONTOURS ON THE SAME PLOT 

CS = plt.contour(contours, linewidths=1, 

alpha=0.3, zorder=3) 

plt.clabel(CS, fontsize=12, inline=1, 

fmt='%2.1f', fontproperties=font) 

 

# RESET THE AXES TO THE FRAME OF THE FITS FILE 

ax.set_xlim(-0.5, hdu.data.shape[1] - 0.5) 

ax.set_ylim(-0.5, hdu.data.shape[0] - 0.5) 

 

# THE COORDINATES USED IN THE PLOT CAN BE ACCESSED USING THE COORDS 

# ATTRIBUTE (NOT X AND Y) 

lon = ax.coords[0] 

lat = ax.coords[1] 

 

lon.set_axislabel('RA (deg)', minpad=0.87, 

size=20) 

lat.set_axislabel('DEC (deg)', minpad=0.87, 

size=20) 

lon.set_major_formatter('d') 

lat.set_major_formatter('d') 

 

# THE SEPARATORS FOR ANGULAR COORDINATE TICK LABELS CAN ALSO BE SET BY 

# SPECIFYING A STRING 

# lat.set_separator(':-s') 

# SET THE APPROXIMATE NUMBER OF TICKS, WITH COLOR & PREVENT OVERLAPPING 

# TICK LABELS FROM BEING DISPLAYED. 

lon.set_ticks(number=6, color='#657b83', 

exclude_overlapping=True, size=10) 

lat.set_ticks(number=10, color='#657b83', 

exclude_overlapping=True, size=10) 

 

# MINOR TICKS NOT SHOWN BY DEFAULT 

lon.display_minor_ticks(True) 

lat.display_minor_ticks(True) 

# lat.set_minor_frequency(2) 

 

# CUSTOMISE TICK POSITIONS (l, b, r, t == left, bottom, right, or 

# top) 

lon.set_ticks_position('bt') 

lon.set_ticklabel_position('b') 

lon.set_ticklabel(size=20) 

lat.set_ticklabel(size=20) 

lon.set_axislabel_position('b') 

 

# HIDE AXES 

# lon.set_ticklabel_position('') 

# lat.set_ticklabel_position('') 

# lon.set_axislabel('', minpad=0.5, fontsize=12) 

# lat.set_axislabel('', minpad=0.5, fontsize=12) 

 

# ADD A GRID 

ax.coords.grid(color='#657b83', alpha=0.5, linestyle='dashed') 

 

lat.set_ticks_position('l') 

lat.set_ticklabel_position('l') 

lat.set_axislabel_position('l') 

 

lat.set_ticks_position('r') 

lat.set_ticklabel_position('r') 

lat.set_axislabel_position('r') 

 

plt.gca().invert_xaxis() 

 

# lon.set_ticks(number=20) 

# lat.set_ticks(number=3) 

 

elif projection == "gnomonic": 

# UNPACK THE PLOT PARAMETERS 

 

if allSky: 

raRange = 360. 

decRange = 180. 

else: 

raRange = plotParameters["raRange"] 

decRange = plotParameters["decRange"] 

 

raMax = centralCoordinate[0] + raRange / 2. 

raMin = centralCoordinate[0] - raRange / 2. 

decMax = centralCoordinate[1] + decRange / 2. 

decMin = centralCoordinate[1] - decRange / 2. 

 

# DETERMINE THE PIXEL GRID X,Y RANGES 

xRange = int(raRange / pixelSizeDeg) 

yRange = int(decRange / pixelSizeDeg) 

largest = max(xRange, yRange) 

# xRange = largest 

# yRange = largest 

 

# SET THE REFERENCE PIXEL TO THE CENTRE PIXEL 

w.wcs.crpix = [xRange / 2., yRange / 2.] 

 

# USE THE "GNOMONIC" PROJECTION ("COORDINATESYS---PROJECTION") 

w.wcs.ctype = ["RA---TAN", "DEC--TAN"] 

 

# CREATE A PIXEL GRID - 2 ARRAYS OF X, Y 

columns = [] 

px = np.tile(np.arange(0, xRange), yRange) 

py = np.repeat(np.arange(0, yRange), xRange) 

 

# CONVERT THE PIXELS TO WORLD COORDINATES 

wr, wd = w.wcs_pix2world(px, py, 1) 

 

# MAKE SURE RA IS +VE 

nr = [] 

nr[:] = [r if r > 0 else r + 360. for r in wr] 

wr = np.array(nr) 

 

# THETA: IS THE POLAR ANGLE, RANGING FROM 0 AT THE NORTH POLE TO PI AT THE SOUTH POLE. 

# PHI: THE AZIMUTHAL ANGLE ON THE SPHERE FROM 0 TO 2PI 

# CONVERT DEC TO THE REQUIRED HEALPIX FORMAT 

nd = -wd + 90. 

 

# CONVERT WORLD TO HEALPIX INDICES 

healpixIds = hp.ang2pix(nside, theta=nd * DEG_TO_RAD_FACTOR, 

phi=wr * DEG_TO_RAD_FACTOR) 

 

# NOW READ THE VALUES OF THE MAP AT THESE HEALPIX INDICES 

uniqueHealpixIds = np.unique(healpixIds) 

probs = [] 

probs[:] = [aMap[i] for i in healpixIds] 

 

uniProb = [] 

uniProb[:] = [aMap[i] for i in uniqueHealpixIds] 

 

stampProb = np.sum(uniProb) 

print "Probability for the plot stamp is %(stampProb)s" % locals() 

 

# RESHAPE THE ARRAY AS BITMAP 

probs = np.reshape(np.array(probs), (yRange, xRange)) 

 

# CREATE THE FITS HEADER WITH WCS 

header = w.to_header() 

# CREATE THE FITS FILE 

hdu = fits.PrimaryHDU(header=header, data=probs) 

 

# GRAB THE WCS FROM HEADER GENERATED EARLIER 

from astropy.wcs import WCS 

from astropy.visualization.wcsaxes import WCSAxes 

 

wcs = WCS(hdu.header) 

# USE WCS AS THE PROJECTION 

ax = WCSAxes(fig, [0.15, 0.1, 0.8, 0.8], wcs=wcs) 

# note that the axes have to be explicitly added to the figure 

ax = fig.add_axes(ax) 

 

# PLOT MAP WITH PROJECTION IN HEADER 

im = ax.imshow(probs, 

cmap=cmap, origin='lower', alpha=0.7, zorder=1, vmin=vmin, vmax=vmax, aspect='auto') 

 

# CONTOURS - NEED TO ADD THE CUMMULATIVE PROBABILITY 

i = np.flipud(np.argsort(aMap)) 

cumsum = np.cumsum(aMap[i]) 

cls = np.empty_like(aMap) 

cls[i] = cumsum * 100 * stampProb 

 

# EXTRACT CONTOUR VALUES AT HEALPIX INDICES 

contours = [] 

contours[:] = [cls[i] for i in healpixIds] 

contours = np.reshape(np.array(contours), (yRange, xRange)) 

 

# PLOT THE CONTOURS ON THE SAME PLOT 

CS = plt.contour(contours, linewidths=1, 

alpha=0.3, zorder=3) 

plt.clabel(CS, fontsize=12, inline=1, 

fmt='%2.1f', fontproperties=font) 

 

# RESET THE AXES TO THE FRAME OF THE FITS FILE 

ax.set_xlim(-0.5, hdu.data.shape[1] - 0.5) 

ax.set_ylim(-0.5, hdu.data.shape[0] - 0.5) 

 

# THE COORDINATES USED IN THE PLOT CAN BE ACCESSED USING THE COORDS 

# ATTRIBUTE (NOT X AND Y) 

lon = ax.coords[0] 

lat = ax.coords[1] 

 

lon.set_axislabel('RA (deg)', minpad=0.87, 

size=20) 

lat.set_axislabel('DEC (deg)', minpad=0.87, 

size=20) 

lon.set_major_formatter('d') 

lat.set_major_formatter('d') 

 

# THE SEPARATORS FOR ANGULAR COORDINATE TICK LABELS CAN ALSO BE SET BY 

# SPECIFYING A STRING 

lat.set_separator(':-s') 

# SET THE APPROXIMATE NUMBER OF TICKS, WITH COLOR & PREVENT OVERLAPPING 

# TICK LABELS FROM BEING DISPLAYED. 

lon.set_ticks(number=4, color='#657b83', 

exclude_overlapping=True, size=10) 

lat.set_ticks(number=10, color='#657b83', 

exclude_overlapping=True, size=10) 

 

# MINOR TICKS NOT SHOWN BY DEFAULT 

lon.display_minor_ticks(True) 

lat.display_minor_ticks(True) 

lat.set_minor_frequency(2) 

 

# CUSTOMISE TICK POSITIONS (l, b, r, t == left, bottom, right, or 

# top) 

lon.set_ticks_position('bt') 

lon.set_ticklabel_position('b') 

lon.set_ticklabel(size=20) 

lat.set_ticklabel(size=20) 

lon.set_axislabel_position('b') 

lat.set_ticks_position('lr') 

lat.set_ticklabel_position('l') 

lat.set_axislabel_position('l') 

 

# HIDE AXES 

# lon.set_ticklabel_position('') 

# lat.set_ticklabel_position('') 

# lon.set_axislabel('', minpad=0.5, fontsize=12) 

# lat.set_axislabel('', minpad=0.5, fontsize=12) 

 

# ADD A GRID 

ax.coords.grid(color='#657b83', alpha=0.5, linestyle='dashed') 

plt.gca().invert_xaxis() 

lon.set_ticks(number=20) 

 

else: 

self.log.error( 

'please give a valid projection. The projection given was `%(projection)s`.' % locals()) 

 

header = w.to_header() 

# CREATE THE FITS FILE 

hdu = fits.PrimaryHDU(header=header, data=probs) 

 

# ADD RA LIMIT 

if raLimit: 

x = np.ones(100) * raLimit 

y = np.linspace(decMin, decMax, 100) 

ax.plot(x, y, 'b--', transform=ax.get_transform('fk5')) 

 

# SETUP TITLE OF PLOT 

from datetime import datetime, date, time 

now = datetime.now() 

now = now.strftime("%Y-%m-%d") 

timeRangeLabel = "NULL" 

if plotType == "timeline" and timeLimitDay: 

start = timeLimitDay[0] 

end = timeLimitDay[1] 

if self.filters: 

f = ("").join(self.filters) 

else: 

f = "" 

if self.telescope: 

t = self.telescope 

else: 

t = "" 

plotTitle = "%(gwid)s %(timeLimitLabel)s %(projection)s %(t)s %(f)s" % locals( 

) 

timeRangeLabel = timeLimitLabel.lower().replace( 

"in", "").replace("between", "").strip() 

if timeLimitLabel == "no limit": 

plotTitle = "%(gwid)s" % locals( 

) 

timeRangeLabel = "all transients" 

elif plotType == "timeline": 

 

plotTitle = "%(gwid)s %(mapBasename)s skymap %(projection)s" % locals( 

) 

timeRangeLabel = "" 

 

else: 

timeRangeLabel = "" 

 

subTitle = "(updated %(now)s)" % locals() 

if timeLimitDay == 0 or plotType == "timeline": 

subTitle = "" 

 

# ax.set_title(plotTitle + "\n", fontsize=10) 

# GRAB PS1 POINTINGS 

pointingArray = [] 

 

from matplotlib.patches import Ellipse 

from matplotlib.patches import Circle 

from matplotlib.patches import Rectangle 

 

# ps1Pointings = [] 

# PS1 POINTINGS (NOT SKYCELLS) 

if len(ps1Pointings) and "skycell" not in ps1Pointings[0]["exp_id"]: 

 

for psp in ps1Pointings: 

raDeg = psp["raDeg"] 

decDeg = psp["decDeg"] 

 

# REMOVE LOWER PROBABILITY FOOTPRINTS 

phi = raDeg 

if phi > 180.: 

phi = phi - 360. 

theta = -decDeg + 90. 

healpixId = hp.ang2pix( 

nside, theta * DEG_TO_RAD_FACTOR, phi * DEG_TO_RAD_FACTOR) 

probs = aMap[healpixId] 

probs = float("%0.*f" % (7, probs)) 

if probabilityCut and probs == 0.: 

continue 

 

# height = 2.8 

height = 0.2 

width = height / math.cos(decDeg * DEG_TO_RAD_FACTOR) 

 

# MULTIPLE CIRCLES 

if projection in ["mercator", "gnomonic", "cartesian"]: 

circ = Ellipse( 

(raDeg, decDeg), width=width, height=height, alpha=0.2, color='#859900', fill=True, transform=ax.get_transform('fk5'), zorder=3) 

else: 

if raDeg > 180.: 

raDeg = raDeg - 360. 

circ = Ellipse( 

(-raDeg * DEG_TO_RAD_FACTOR, decDeg * DEG_TO_RAD_FACTOR), width=width * DEG_TO_RAD_FACTOR, height=height * DEG_TO_RAD_FACTOR, alpha=0.2, color='#859900', fill=True, zorder=3) 

 

ax.add_patch(circ) 

else: 

plotted = [] 

patches = [] 

for psp in ps1Pointings: 

 

if psp["exp_id"] in plotted: 

continue 

else: 

plotted.append(psp["exp_id"]) 

 

patch = add_square_fov( 

log=self.log, 

raDeg=psp["raDeg"], 

decDeg=psp["decDeg"], 

nside=nside, 

aMap=aMap, 

fovSide=0.4, 

axes=ax, 

probabilityCut=self.probabilityCut, 

projection=projection, 

color='#859900') 

 

if patch: 

patches.append(patch) 

 

ax.add_collection(PatchCollection(patches, alpha=0.6, 

color='#859900', zorder=3, transform=ax.get_transform('fk5'))) 

 

patches = [] 

for atp in atlasPointings: 

 

if atp["exp_id"] in plotted: 

continue 

else: 

plotted.append(atp["exp_id"]) 

 

patch = add_square_fov( 

log=self.log, 

raDeg=atp["raDeg"], 

decDeg=atp["decDeg"], 

nside=nside, 

aMap=aMap, 

fovSide=5.46, 

axes=ax, 

probabilityCut=self.probabilityCut, 

projection=projection, 

color="#6c71c4") 

 

if patch: 

patches.append(patch) 

 

ax.add_collection(PatchCollection(patches)) 

 

# ADD DATA POINTS FOR TRANSIENTS 

names = [] 

ra = [] 

dec = [] 

raRad = [] 

decRad = [] 

texts = [] 

 

# ps1Transients = [] 

for trans in ps1Transients: 

# if trans["ps1_designation"] in ["PS15dpg", "PS15dpp", "PS15dpq", "PS15don", "PS15dpa", "PS15dom"]: 

# continue 

 

name = trans["ps1_designation"] 

if name is None: 

name = trans["local_designation"] 

names.append(name) 

raDeg = trans["ra_psf"] 

decDeg = trans["dec_psf"] 

ra.append(raDeg) 

dec.append(decDeg) 

raRad.append(-raDeg * DEG_TO_RAD_FACTOR) 

decRad.append(decDeg * DEG_TO_RAD_FACTOR) 

 

if len(ra) > 0: 

# MULTIPLE CIRCLES 

if projection in ["mercator", "gnomonic", "cartesian"]: 

ax.scatter( 

x=np.array(ra), 

y=np.array(dec), 

transform=ax.get_transform('fk5'), 

s=6, 

c='#036d09', 

edgecolor='#036d09', 

alpha=1, 

zorder=4 

) 

xx, yy = w.wcs_world2pix(np.array(ra), np.array(dec), 0) 

# ADD TRANSIENT LABELS 

for r, d, n in zip(xx, yy, names): 

texts.append(ax.text( 

r, 

d, 

n, 

color='#036d09', 

fontsize=10, 

zorder=4, 

family='monospace' 

)) 

 

if len(texts): 

adjust_text( 

xx, 

yy, 

texts, 

expand_text=(1.2, 1.6), 

expand_points=(1.2, 3.2), 

va='center', 

ha='center', 

force_text=2.0, 

force_points=0.5, 

lim=1000, 

precision=0, 

only_move={}, 

text_from_text=True, 

text_from_points=True, 

save_steps=False, 

save_prefix='', 

save_format='png', 

add_step_numbers=True, 

min_arrow_sep=50.0, 

draggable=True, 

arrowprops=dict(arrowstyle="-", color='#036d09', lw=1.2, 

patchB=None, shrinkB=0, connectionstyle="arc3,rad=0.1", zorder=3, alpha=0.5), 

fontsize=10, 

family='monospace' 

) 

else: 

ax.scatter( 

x=np.array(raRad), 

y=np.array(decRad), 

s=6, 

c='#dc322f', 

edgecolor='#dc322f', 

alpha=1, 

zorder=4 

) 

 

# ADD DATA POINTS FOR TRANSIENTS 

names = [] 

ra = [] 

dec = [] 

raRad = [] 

decRad = [] 

texts = [] 

# atlasTransients = [] 

for trans in atlasTransients: 

# if trans["ps1_designation"] in ["PS15dpg", "PS15dpp", "PS15dpq", "PS15don", "PS15dpa", "PS15dom"]: 

# continue 

 

name = trans["atlas_designation"] 

names.append(name) 

raDeg = trans["ra"] 

decDeg = trans["dec"] 

ra.append(raDeg) 

dec.append(decDeg) 

raRad.append(-raDeg * DEG_TO_RAD_FACTOR) 

decRad.append(decDeg * DEG_TO_RAD_FACTOR) 

 

if len(ra) > 0: 

# MULTIPLE CIRCLES 

if projection in ["mercator", "gnomonic", "cartesian"]: 

ax.scatter( 

x=np.array(ra), 

y=np.array(dec), 

transform=ax.get_transform('fk5'), 

s=6, 

c='#5c0bb0', 

edgecolor='#5c0bb0', 

alpha=1, 

zorder=4 

) 

xx, yy = w.wcs_world2pix(np.array(ra), np.array(dec), 0) 

# ADD TRANSIENT LABELS 

for r, d, n in zip(xx, yy, names): 

texts.append(ax.text( 

r, 

d, 

n, 

fontsize=10, 

color='#5c0bb0', 

zorder=4, 

family='monospace' 

)) 

 

if len(texts): 

adjust_text( 

xx, 

yy, 

texts, 

expand_text=(1.2, 1.6), 

expand_points=(1.2, 3.2), 

va='center', 

ha='center', 

force_text=2.0, 

force_points=0.5, 

lim=1000, 

precision=0, 

only_move={}, 

text_from_text=True, 

text_from_points=True, 

save_steps=False, 

save_prefix='', 

save_format='png', 

add_step_numbers=True, 

min_arrow_sep=50.0, 

draggable=True, 

arrowprops=dict(arrowstyle="-", color='#5c0bb0', lw=1.2, 

patchB=None, shrinkB=0, connectionstyle="arc3,rad=0.1", zorder=3, alpha=0.5), 

fontsize=10, 

family='monospace' 

) 

else: 

ax.scatter( 

x=np.array(raRad), 

y=np.array(decRad), 

s=6, 

c='#dc322f', 

edgecolor='#dc322f', 

alpha=1, 

zorder=4 

) 

 

# TIME-RANGE LABEL 

fig = plt.gcf() 

fWidth, fHeight = fig.get_size_inches() 

 

if projection in ["mercator", "gnomonic", "cartesian"]: 

fig.set_size_inches(8.0, 8.0) 

ax.text(0.95, 0.95, timeRangeLabel, 

horizontalalignment='right', 

verticalalignment='top', 

transform=ax.transAxes, 

color="#dc322f", 

fontproperties=font, 

fontsize=16, 

zorder=4) 

 

else: 

ax.text(0.95, 0.95, timeRangeLabel, 

horizontalalignment='right', 

verticalalignment='top', 

transform=ax.transAxes, 

color="#dc322f", 

fontproperties=font, 

fontsize=16, 

zorder=4) 

 

if self.timestamp: 

utcnow = datetime.utcnow() 

utcnow = utcnow.strftime("%Y-%m-%d %H:%M.%S UTC") 

ax.text(0, 1.02, utcnow, 

horizontalalignment='left', 

verticalalignment='top', 

transform=ax.transAxes, 

color="#657b83", 

fontproperties=font, 

fontsize=6) 

 

# RECURSIVELY CREATE MISSING DIRECTORIES 

if self.settings and not outputDirectory: 

plotDir = self.settings["output directory"] + "/" + gwid 

elif outputDirectory: 

plotDir = outputDirectory 

 

if not os.path.exists(plotDir): 

os.makedirs(plotDir) 

 

plotTitle = plotTitle.replace(" ", " ").replace(" ", " ").replace(" ", " ").replace(" ", "_").replace("-", "_").replace( 

"<", "lt").replace(">", "gt").replace(",", "").replace("\n", "_").replace("&", "and") 

figureName = """%(plotTitle)s""" % locals( 

) 

if timeLimitDay == 0: 

figureName = """%(plotTitle)s""" % locals( 

) 

if allSky and plotDir == ".": 

figureName = figureName + "_" + projection.title() 

if plotDir != ".": 

for f in fileFormats: 

if not os.path.exists("%(plotDir)s/%(folderName)s/%(f)s" % locals()): 

os.makedirs("%(plotDir)s/%(folderName)s/%(f)s" % locals()) 

figurePath = "%(plotDir)s/%(folderName)s/%(f)s/%(figureName)s.%(f)s" % locals() 

savefig(figurePath, bbox_inches='tight', dpi=300) 

# savefig(figurePath, dpi=300) 

 

if bestMap and allSky: 

linkName = "%(plotDir)s/%(folderName)s/%(f)s/%(gwid)s_preferred_skymap_%(projection)s.%(f)s" % locals() 

try: 

os.remove(linkName) 

except: 

pass 

os.symlink(figurePath, linkName) 

 

# if not os.path.exists("%(plotDir)s/%(folderName)s/fits" % locals()): 

# os.makedirs("%(plotDir)s/%(folderName)s/fits" % locals()) 

# pathToExportFits = "%(plotDir)s/%(folderName)s/fits/%(gwid)s_map_%(projection)s.fits" % locals() 

# try: 

# os.remove(pathToExportFits) 

# except: 

# pass 

# hdu.writeto(pathToExportFits) 

else: 

for f in fileFormats: 

figurePath = "%(plotDir)s/%(figureName)s.%(f)s" % locals() 

savefig(figurePath, bbox_inches='tight', dpi=300) 

# savefig(figurePath, dpi=300) 

 

# pathToExportFits = "%(plotDir)s/%(gwid)s_skymap.fits" % locals() 

# try: 

# os.remove(pathToExportFits) 

# except: 

# pass 

# hdu.writeto(pathToExportFits) 

 

if fitsImage: 

self.generate_fits_image_map( 

gwid=gwid, 

pathToProbMap=pathToProbMap, 

folderName=folderName, 

outputDirectory=outputDirectory, 

center=center, 

bestMap=bestMap 

) 

 

self.log.info('completed the ``generate_probability_plot`` method') 

return None 

 

def get_history_plots( 

self): 

""" 

*plot the history plots* 

 

**Return:** 

- None 

 

**Usage:** 

 

.. code-block:: python 

 

from breaker.plots import plot_wave_observational_timelines 

plotter = plot_wave_observational_timelines( 

log=log, 

settings=settings, 

plotType="history", 

gwid="G184098", 

projection="mercator" 

) 

plotter.get() 

""" 

self.log.info('starting the ``get_history_plots`` method') 

 

timeLimitLabels = ["day", "2 days", "3 days", "4 days", "5 days", "6 days", 

"7 days", "2 weeks", "3 weeks", "1 month", "2 months", "3 months", "no limit"] 

timeLimitDays = [1, 2, 3, 4, 5, 6, 7, 14, 21, 30, 60, 90, 0] 

 

if self.gwid: 

theseIds = [self.gwid] 

else: 

theseIds = self.settings["gravitational waves"] 

 

for gwid in theseIds: 

for tday, tlabel in zip(timeLimitDays, timeLimitLabels): 

 

plotParameters, ps1Transients, ps1Pointings, atlasPointings, atlasTransients = self.get_gw_parameters_from_settings( 

gwid=gwid, 

inPastDays=tday, 

inFirstDays=False) 

 

pathToProbMap = self.settings[ 

"gravitational waves"][gwid]["mapPath"] 

if not os.path.exists(pathToProbMap): 

message = "the path to the map %s does not exist on this machine" % ( 

pathToProbMap,) 

self.log.critical(message) 

raise IOError(message) 

 

mjdStart = self.settings["gravitational waves"][ 

gwid]["mjd"] 

 

self.generate_probability_plot( 

gwid=gwid, 

plotParameters=plotParameters, 

ps1Transients=ps1Transients, 

atlasTransients=atlasTransients, 

ps1Pointings=ps1Pointings, 

atlasPointings=atlasPointings, 

pathToProbMap=pathToProbMap, 

mjdStart=mjdStart, 

timeLimitLabel=tlabel, 

timeLimitDay=tday, 

raLimit=False, 

fileFormats=["png", "pdf"], 

folderName="survey_history_plots", 

plotType=self.plotType, 

projection=self.projection, 

probabilityCut=self.probabilityCut) 

 

self.log.info('completed the ``get_history_plots`` method') 

return None 

 

def get_timeline_plots( 

self): 

""" 

*plot the history plots* 

 

**Return:** 

- None 

 

**Usage:** 

 

.. code-block:: python 

 

from breaker.plots import plot_wave_observational_timelines 

plotter = plot_wave_observational_timelines( 

log=log, 

settings=settings, 

plotType="timeline", 

gwid="G184098", 

projection="mercator" 

) 

plotter.get() 

""" 

self.log.info('starting the ``get_timeline_plots`` method') 

 

matplotlib.use('PDF') 

 

if self.allPlots: 

timeLimitLabels = ["21 days pre-detection", "<1d", "1-2d", 

"2-3d", "3-4d", "4-5d", "5-10d", "10-17d", "17-24d", "24-31d"] 

timeLimitDays = [(-21, 0), (0, 1), (1, 2), (2, 3), (3, 4), 

(4, 5), (5, 10), (10, 17), (17, 24), (24, 31)] 

else: 

timeLimitLabels = ["0-1d", "1-2d", "2-3d", "3-4d", 

"4-5d", "5-10d", "10-17d", "17-24d", "24-31d"] 

timeLimitLabels = ["0-1d"] 

timeLimitDays = [(0, 1), (1, 2), (2, 3), (3, 4), 

(4, 5), (5, 10), (10, 17), (17, 24), (24, 31)] 

 

raLimits = [134.25, 144.75, 152.25, 159.50, 167.0, 174.5] 

raLimits = [False, False, False, False, 

False, False, False, False, False, False, False, False] 

 

if self.gwid: 

theseIds = [self.gwid] 

else: 

theseIds = self.settings["gravitational waves"] 

 

for gwid in theseIds: 

for tday, tlabel, raLimit in zip(timeLimitDays, timeLimitLabels, raLimits): 

 

pathToProbMap = self.settings[ 

"gravitational waves"][gwid]["mapPath"] 

aMap, mapHeader = hp.read_map( 

pathToProbMap, 0, h=True, verbose=False) 

 

mapBasename = os.path.basename(pathToProbMap) 

mapBasename = os.path.splitext(mapBasename)[0] 

mapBasename = os.path.splitext(mapBasename)[0] 

mapBasename = os.path.splitext(mapBasename)[0] 

 

# DETERMINE THE SIZE OF THE HEALPIXELS 

nside = hp.npix2nside(len(aMap)) 

maxProbHealpix = aMap.argmax() 

maxProbCoordinate = hp.pix2ang( 

nside, maxProbHealpix, lonlat=True) 

 

plotParameters, ps1Transients, ps1Pointings, atlasPointings, atlasTransients = self.get_gw_parameters_from_settings( 

gwid=gwid, 

inPastDays=False, 

inFirstDays=tday, 

maxProbCoordinate=maxProbCoordinate) 

 

if not os.path.exists(pathToProbMap): 

message = "the path to the map %s does not exist on this machine" % ( 

pathToProbMap,) 

self.log.critical(message) 

raise IOError(message) 

 

mjdStart = self.settings["gravitational waves"][ 

gwid]["mjd"] 

 

self.generate_probability_plot( 

gwid=gwid, 

plotParameters=plotParameters, 

ps1Transients=ps1Transients, 

ps1Pointings=ps1Pointings, 

atlasTransients=atlasTransients, 

atlasPointings=atlasPointings, 

pathToProbMap=pathToProbMap, 

mjdStart=mjdStart, 

timeLimitLabel=tlabel, 

timeLimitDay=tday, 

raLimit=raLimit, 

fileFormats=["png"], 

folderName="survey_timeline_plots", 

plotType=self.plotType, 

projection=self.projection, 

probabilityCut=self.probabilityCut, 

center=maxProbCoordinate) 

 

self.log.info('completed the ``get_timeline_plots`` method') 

return None 

 

def generate_fits_image_map( 

self, 

gwid, 

pathToProbMap, 

folderName="", 

outputDirectory=False, 

rebin=True, 

center=False, 

bestMap=False): 

"""*generate fits image map from the LV-skymap (FITS binary table)* 

 

**Key Arguments:** 

- ``pathToProbMap`` -- path to the FITS file containing the probability map of the wave 

- ``outputDirectory`` -- can be used to override the output destination in the settings file 

- ``gwid`` -- the unique ID of the gravitational wave to plot 

- ``folderName`` -- the name of the folder to add the plots to 

- ``rebin`` -- rebin the final image to reduce size 

- ``center`` -- central longitude in degrees. Default *0*. 

- ``bestMap`` -- is this the prefered skymap. If so, add symlink to placeholder name for prefered map. 

 

**Return:** 

- None 

 

**Usage:** 

 

To generate an all-sky image from the LV FITS binary table healpix map run the following code: 

 

from breaker.plots import plot_wave_observational_timelines 

plotter = plot_wave_observational_timelines( 

log=log, 

settings=settings, 

databaseConnRequired=False 

) 

plotter.generate_fits_image_map( 

gwid="G211117", 

pathToProbMap="/path/to/LV/healpix_map.fits", 

outputDirectory="/path/to/output", 

rebin=True 

) 

 

The size of the final FITS image map is ~1.1GB so it's probably best to rebin the image (~80MB) unless you really need the resolution. 

""" 

self.log.info('starting the ``generate_fits_image_map`` method') 

 

import healpy as hp 

# HEALPY REQUIRES RA, DEC IN RADIANS AND AS TWO SEPERATE ARRAYS 

import math 

pi = (4 * math.atan(1.0)) 

DEG_TO_RAD_FACTOR = pi / 180.0 

RAD_TO_DEG_FACTOR = 180.0 / pi 

 

mapBasename = os.path.basename(pathToProbMap) 

mapBasename = os.path.splitext(mapBasename)[0] 

mapBasename = os.path.splitext(mapBasename)[0] 

mapBasename = os.path.splitext(mapBasename)[0] 

 

# X, Y PIXEL COORDINATE GRID 

xRange = 10000 

yRange = xRange / 2 

 

# PIXELSIZE AS MAPPED TO THE FULL SKY 

pixelSizeDeg = 360. / xRange 

 

# READ HEALPIX MAPS FROM FITS FILE 

# THIS FILE IS A ONE COLUMN FITS BINARY, WITH EACH CELL CONTAINING AN 

# ARRAY OF PROBABILITIES (3,072 ROWS) 

# READ IN THE HEALPIX FITS FILE 

aMap, mapHeader = hp.read_map(pathToProbMap, 0, h=True, verbose=False) 

# DETERMINE THE SIZE OF THE HEALPIXELS 

nside = hp.npix2nside(len(aMap)) 

 

# FROM THE PIXEL GRID (xRange, yRange), GENERATE A MAP TO LAT (pi to 0) AND LONG (-pi to pi) THAT CAN THEN MAPS TO HEALPIX SKYMAP 

# RA FROM -pi to pi 

 

# FITS convention for fractional pixels is that the center of the lower left pixel is at (1,1), the lower left corner of the 

# lower left pixel is at (0.5,0.5). [1-index pix] refers to this 

# convention. arange index starts at 0 so we need to fix for this 

 

# FULL-SKY MAP SO PLOT FULL RA AND DEC RANGES 

# DEC FROM 180 to 0 

theta = np.linspace(np.pi - pixelSizeDeg / 2, + 

pixelSizeDeg / 2, yRange) 

 

latitude = np.radians(np.linspace(-90 + pixelSizeDeg, 90, yRange)) 

 

# FIND THE COORDINATES OF THE CORE LIKEIHOOD 

maxProbHealpix = aMap.argmax() 

maxCoordinate = hp.pix2ang(nside, maxProbHealpix, lonlat=True) 

print "The %(gwid)s %(mapBasename)s map's maximum likelihood is centered at %(maxCoordinate)s" % locals() 

 

if center == False: 

center = maxCoordinate[0] 

 

# RA FROM -180 to +180 

centralRa = center 

centralRaRad = centralRa * DEG_TO_RAD_FACTOR 

phi = np.linspace(-np.pi + centralRaRad + pixelSizeDeg / 2, 

np.pi + centralRaRad - pixelSizeDeg / 2, xRange) 

 

longitude = np.radians(np.linspace(-180 + pixelSizeDeg, 180, xRange)) 

X, Y = np.meshgrid(longitude, latitude) 

 

# PROJECT THE MAP TO A RECTANGULAR MATRIX xRange X yRange 

PHI, THETA = np.meshgrid(phi, theta) 

healpixIds = hp.ang2pix(nside, THETA, PHI) 

# GIVEN A HIGH ENOUGH RESOLUTION IN THE PIXEL GRID WE WILL HAVE 

# DUPLICATES - LET COUNT THEM ADD DIVIDE PROBABILITY EQUALLY 

unique, counts = np.unique(healpixIds, return_counts=True) 

 

# countDict has healpixid as keys and count rates as values (e.g. the 

# ID XXXX occurs in 78 pixels) 

countDict = dict(zip(unique, counts)) 

 

# PROB SHAPE IS (5000, 10000) .. indexing measured from top left in 

# matrix. 

probs = aMap[healpixIds] 

 

# NOTE i = -y-direction, shape[0] is the y-axis range 

# j = x-direction, shape[1] is the x-axis range 

weightedProb = np.array([ 

[probs[i, j] / countDict[healpixIds[i, j]] 

for j in xrange(probs.shape[1])] 

for i in xrange(probs.shape[0]) 

]) 

 

if rebin == True: 

rebinSize = 4 

# resize by getting rid of extra columns/rows 

# xedge and yedge find the pixels we need to trim is rebinSize does 

# divide evenly into image 

yedge = np.shape(weightedProb)[0] % rebinSize 

xedge = np.shape(weightedProb)[1] % rebinSize 

weightedProb = weightedProb[yedge:, xedge:] 

 

# put image array into arrays of rebinSize x rebinSize - so (1250, 

# 4, 2500, 4) 

weightedProb = np.reshape(weightedProb, (np.shape(weightedProb)[ 

0] / rebinSize, rebinSize, np.shape(weightedProb)[1] / rebinSize, rebinSize)) 

 

# average each rebinSize x rebinSize array 

weightedProb = np.mean(weightedProb, axis=3) * rebinSize 

weightedProb = np.mean(weightedProb, axis=1) * rebinSize 

 

pixelSizeDeg = pixelSizeDeg * rebinSize 

xRange = int(xRange / rebinSize) 

yRange = int(yRange / rebinSize) 

 

# CREATE A NEW WCS OBJECT 

w = awcs.WCS(naxis=2) 

# SET THE REQUIRED PIXEL SIZE 

w.wcs.cdelt = np.array([pixelSizeDeg, pixelSizeDeg]) 

# WORLD COORDINATES AT REFERENCE PIXEL 

centralCoordinate = [centralRa, 0] 

w.wcs.crval = centralCoordinate 

cx = xRange / 2. + 0.5 

cy = yRange / 2. + 0.5 

# SET THE REFERENCE PIXEL TO THE CENTRE PIXEL 

w.wcs.crpix = [cx, cy] 

 

unweightedImageProb = np.sum(probs) 

self.log.info( 

"The total unweighted probability flux in the FITS images added to %(unweightedImageProb)s" % locals()) 

 

totalImageProb = np.sum(weightedProb) 

self.log.info( 

"The total probability flux in the FITS images added to %(totalImageProb)s" % locals()) 

 

# CTYPE FOR THE FITS HEADER 

w.wcs.ctype = ["RA---CAR" % 

locals(), "DEC--CAR" % locals()] 

 

header = w.to_header() 

# CREATE THE FITS FILE 

hdu = fits.PrimaryHDU(header=header, data=weightedProb) 

 

# Recursively create missing directories 

if self.settings and not outputDirectory: 

plotDir = self.settings["output directory"] + "/" + gwid 

elif outputDirectory: 

plotDir = outputDirectory 

 

if not os.path.exists(plotDir): 

os.makedirs(plotDir) 

 

if plotDir != ".": 

if not os.path.exists("%(plotDir)s/%(folderName)s/fits" % locals()): 

os.makedirs("%(plotDir)s/%(folderName)s/fits" % locals()) 

pathToExportFits = "%(plotDir)s/%(folderName)s/fits/%(gwid)s_%(mapBasename)s_breaker_skymap.fits" % locals() 

try: 

os.remove(pathToExportFits) 

except: 

pass 

hdu.writeto(pathToExportFits) 

 

if bestMap: 

linkName = "%(plotDir)s/%(folderName)s/fits/%(gwid)s_preferred_breaker_skymap.fits" % locals() 

print "The %(gwid)s prefered likeihood map is symlinked at `%(linkName)s`" % locals() 

try: 

os.remove(linkName) 

except: 

pass 

os.symlink(pathToExportFits, linkName) 

else: 

pathToExportFits = "%(plotDir)s/%(gwid)s_%(mapBasename)s_breaker_skymap.fits" % locals() 

try: 

os.remove(pathToExportFits) 

except: 

pass 

hdu.writeto(pathToExportFits) 

 

print "The %(gwid)s %(mapBasename)s likeihood map can be found here `%(pathToExportFits)s`" % locals() 

 

self.log.info('completed the ``generate_fits_image_map`` method') 

return None 

 

 

def y2lat( 

y, 

xRange, 

yRange 

): 

# R is the radius of the sphere at the scale of the map as drawn 

y = y - yRange / 2 

R = xRange / (2. * np.pi) 

return -((np.pi / 2.0) - 2.0 * np.arctan(np.e ** (-y / R))) + np.pi / 2 

 

 

def x2long( 

x, 

xRange 

): 

# R is the radius of the sphere at the scale of the map as drawn 

R = xRange / (2. * np.pi) 

return x / R - np.pi 

 

 

def add_square_fov( 

log, 

raDeg, 

decDeg, 

nside, 

aMap, 

fovSide, 

axes, 

probabilityCut, 

projection, 

color): 

"""*summary of function* 

 

**Key Arguments:** 

- ``dbConn`` -- mysql database connection 

- ``log`` -- logger 

 

**Return:** 

- None 

 

**Usage:** 

.. todo:: 

 

add usage info 

create a sublime snippet for usage 

 

.. code-block:: python  

 

usage code  

""" 

log.info('starting the ``add_square_fov`` function') 

 

import math 

pi = (4 * math.atan(1.0)) 

DEG_TO_RAD_FACTOR = pi / 180.0 

RAD_TO_DEG_FACTOR = 180.0 / pi 

 

# REMOVE LOWER PROBABILITY FOOTPRINTS 

phi = raDeg 

if phi > 180.: 

phi = phi - 360. 

theta = -decDeg + 90. 

healpixId = hp.ang2pix( 

nside, theta * DEG_TO_RAD_FACTOR, phi * DEG_TO_RAD_FACTOR) 

probs = aMap[healpixId] 

probs = float("%0.*f" % (7, probs)) 

if probabilityCut and probs == 0.: 

return None 

elif probabilityCut: 

# print atp["mjd"], atlasExpId, raDeg, decDeg 

pass 

 

deltaDeg = fovSide / 2 

if decDeg < 0: 

deltaDeg = -deltaDeg 

 

if projection in ["mercator", "gnomonic", "cartesian"]: 

widthDegTop = fovSide / \ 

math.cos((decDeg + deltaDeg) * DEG_TO_RAD_FACTOR) 

widthDegBottom = fovSide / \ 

math.cos((decDeg - deltaDeg) * DEG_TO_RAD_FACTOR) 

heightDeg = fovSide 

llx = (raDeg - widthDegBottom / 2) 

lly = decDeg - (heightDeg / 2) 

ulx = (raDeg - widthDegTop / 2) 

uly = decDeg + (heightDeg / 2) 

urx = (raDeg + widthDegTop / 2) 

ury = uly 

lrx = (raDeg + widthDegBottom / 2) 

lry = lly 

 

Path = mpath.Path 

path_data = [ 

(Path.MOVETO, [llx, lly]), 

(Path.LINETO, [ulx, uly]), 

(Path.LINETO, [urx, ury]), 

(Path.LINETO, [lrx, lry]), 

(Path.CLOSEPOLY, [llx, lly]) 

] 

codes, verts = zip(*path_data) 

path = mpath.Path(verts, codes) 

 

# EXCLUDE FOOTPRINTS THAT CROSS 360. 

if lrx > 180. and llx < 180: 

return None 

 

patch = patches.PathPatch(path) 

else: 

if raDeg > 180.: 

raDeg = raDeg - 360. 

 

widthRadTop = fovSide * DEG_TO_RAD_FACTOR / \ 

math.cos((decDeg + deltaDeg) * DEG_TO_RAD_FACTOR) 

widthRadBottom = fovSide * DEG_TO_RAD_FACTOR / \ 

math.cos((decDeg - deltaDeg) * DEG_TO_RAD_FACTOR) 

heightRad = fovSide * DEG_TO_RAD_FACTOR 

llx = -(raDeg * DEG_TO_RAD_FACTOR - widthRadBottom / 2) 

lly = decDeg * DEG_TO_RAD_FACTOR - (heightRad / 2) 

ulx = -(raDeg * DEG_TO_RAD_FACTOR - widthRadTop / 2) 

uly = decDeg * DEG_TO_RAD_FACTOR + (heightRad / 2) 

urx = -(raDeg * DEG_TO_RAD_FACTOR + widthRadTop / 2) 

ury = uly 

lrx = -(raDeg * DEG_TO_RAD_FACTOR + widthRadBottom / 2) 

lry = lly 

Path = mpath.Path 

path_data = [ 

(Path.MOVETO, [llx, lly]), 

(Path.LINETO, [ulx, uly]), 

(Path.LINETO, [urx, ury]), 

(Path.LINETO, [lrx, lry]), 

(Path.CLOSEPOLY, [llx, lly]) 

] 

codes, verts = zip(*path_data) 

path = mpath.Path(verts, codes) 

patch = patches.PathPatch(path, alpha=0.6, 

color=color, fill=True, zorder=3,) 

 

log.info('completed the ``add_square_fov`` function') 

return patch 

 

# use the tab-trigger below for new function 

# xt-def-function