Skip to content

source.py

Class to describe a VAST astrophysical source.

Source

This is a class representation of a catalogued source position

Attributes:

Name Type Description
pipeline bool

Set to True if the source is generated from a VAST Pipeline run.

coord SkyCoord

The coordinate of the source as a SkyCoord object. Planets can sometimes have a SkyCoord containing more than one coordinate.

name str

The name of the source.

epochs List[str]

The epochs the source contains.

fields List[str]

The fields the source contains.

stokes str

The Stokes parameter of the source.

crossmatch_radius Angle

Angle of the crossmatch. This will not be valid for pipeline sources.

measurements DataFrame

The individual measurements of the source.

islands bool

Set to True if islands have been used for the source creation.

outdir str

Path that will be appended to any files that are saved.

base_folder str

The directory where the data (fits files) is held.

image_type str

'TILES' or 'COMBINED'.

tiles bool

True if image_type == TILES.

corrected_data bool

Access the corrected data. Only relevant if tiles is True. Defaults to False.

post_processed_data

Access the post-processed data. Only relevant if tiles is True. Defaults to True.

detections int

The number of selavy detections the source contains.

limits int

The number of upper limits the source contains. Will be set to None for pipeline sources.

forced_fits int

The number of forced fits the source contains.

planet bool

Set to True if the source has been defined as a planet.

Source code in vasttools/source.py
  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
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
class Source:
    """
    This is a class representation of a catalogued source position

    Attributes:
        pipeline (bool): Set to `True` if the source is generated from a VAST
            Pipeline run.
        coord (astropy.coordinates.SkyCoord):
            The coordinate of the source as a SkyCoord object.
            Planets can sometimes have a SkyCoord containing more than
            one coordinate.
        name (str): The name of the source.
        epochs (List[str]): The epochs the source contains.
        fields (List[str]): The fields the source contains.
        stokes (str): The Stokes parameter of the source.
        crossmatch_radius (astropy.coordinates.Angle):
            Angle of the crossmatch. This will not be valid for
            pipeline sources.
        measurements (pandas.core.frame.DataFrame):
            The individual measurements of the source.
        islands (bool): Set to `True` if islands have been used for the
            source creation.
        outdir (str): Path that will be appended to any files that are saved.
        base_folder (str): The directory where the data (fits files) is held.
        image_type (str): 'TILES' or 'COMBINED'.
        tiles (bool): `True` if `image_type` == `TILES`.
        corrected_data (bool): Access the corrected data. Only relevant if
            `tiles` is `True`. Defaults to `False`.
        post_processed_data: Access the post-processed data. Only relevant
                if `tiles` is `True`. Defaults to `True`.
        detections (int): The number of selavy detections the source contains.
        limits (int):
            The number of upper limits the source contains. Will be set to
            `None` for pipeline sources.
        forced_fits (int): The number of forced fits the source contains.
        planet (bool): Set to `True` if the source has been defined
            as a planet.
    """

    def __init__(
        self,
        coord: SkyCoord,
        name: Union[str, int],
        epochs: List[str],
        fields: List[str],
        stokes: str,
        primary_field: str,
        crossmatch_radius: Angle,
        measurements: pd.DataFrame,
        base_folder: str,
        image_type: str = "COMBINED",
        islands: bool = False,
        outdir: str = ".",
        planet: bool = False,
        pipeline: bool = False,
        tiles: bool = False,
        corrected_data: bool = False,
        post_processed_data: bool = True,
        forced_fits: bool = False,
    ) -> None:
        """
        Constructor method

        Args:
            coord: Source coordinates.
            name: The name of the source. Will be converted to a string.
            epochs: The epochs that the source contains.
            fields: The fields that the source contains.
            stokes: The stokes parameter of the source.
            primary_field: The primary VAST Pilot field of the source.
            crossmatch_radius: The crossmatch radius used to find the
                measurements.
            measurements: DataFrame containing the measurements.
            base_folder: Path to base folder in default directory structure
            image_type: The string representation of the image type,
                either 'COMBINED' or 'TILES', defaults to "COMBINED".
            islands: Is `True` if islands has been used instead of
                components, defaults to `False`.
            outdir: The directory where any media outputs will be written
                to, defaults to ".".
            planet: Set to `True` if the source is a planet, defaults
                to `False`.
            pipeline: Set to `True` if the source has been loaded from a
                VAST Pipeline run, defaults to `False`.
            tiles: Set to 'True` if the source is from a tile images,
                defaults to `False`.
            corrected_data: Access the corrected data. Only relevant if
                `tiles` is `True`. Defaults to `True`.
            forced_fits: Set to `True` if forced fits are included in the
                source measurements, defaults to `False`.

        Returns:
            None
        """
        self.logger = logging.getLogger(f'vasttools.source.Source[{name}]')
        self.logger.debug('Created Source instance')
        self.pipeline = pipeline
        self.coord = coord
        self.name = str(name)
        self.epochs = epochs
        self.fields = fields
        self.stokes = stokes
        self.primary_field = primary_field
        self.crossmatch_radius = crossmatch_radius
        self.measurements = measurements.infer_objects()
        self.measurements.dateobs = pd.to_datetime(
            self.measurements.dateobs
        )
        self.islands = islands
        if self.islands:
            self.cat_type = 'islands'
        else:
            self.cat_type = 'components'

        self.outdir = outdir

        self.base_folder = base_folder
        self.image_type = image_type
        if image_type == 'TILES':
            self.tiles = True
        else:
            self.tiles = False

        self.corrected_data = corrected_data
        self.post_processed_data = post_processed_data
        if self.pipeline:
            self.detections = self.measurements[
                self.measurements.forced == False
            ].shape[0]

            self.forced = self.measurements[
                self.measurements.forced == False
            ].shape[0]

            self.limits = None
            self.forced_fits = False
        else:
            self.detections = self.measurements[
                self.measurements.detection
            ].shape[0]

            self.limits = self.measurements[
                self.measurements.detection == False
            ].shape[0]

            self.forced = None
            self.forced_fits = forced_fits

        self._cutouts_got = False

        self.planet = planet

    def write_measurements(
        self, simple: bool = False, outfile: Optional[str] = None
    ) -> None:
        """Write the measurements to a CSV file.

        Args:
            simple: Only include flux density and uncertainty in returned
                table, defaults to `False`.
            outfile: File to write measurements to, defaults to None.

        Returns:
            None
        """
        if simple:
            if self.pipeline:
                cols = [
                    'source',
                    'ra',
                    'dec',
                    'component_id',
                    'flux_peak',
                    'flux_peak_err',
                    'flux_int',
                    'flux_int_err',
                    'rms',
                ]
            else:
                cols = [
                    'name',
                    'ra_deg_cont',
                    'dec_deg_cont',
                    'component_id',
                    'flux_peak',
                    'flux_peak_err',
                    'flux_int',
                    'flux_int_err',
                    'rms_image',
                ]

            measurements_to_write = self.measurements[cols]

        else:
            cols = [
                'fields',
                'skycoord',
                'selavy',
                'image',
                'rms',
            ]

            if self.pipeline:
                cols[0] = 'field'

            measurements_to_write = self.measurements.drop(
                labels=cols, axis=1
            )

        # drop any empty values
        if not self.pipeline and not self.forced_fits:
            measurements_to_write = measurements_to_write[
                measurements_to_write['rms_image'] != -99
            ]

        if measurements_to_write.empty:
            self.logger.warning(
                "%s has no measurements! No file will be written.",
                self.name
            )
            return

        if outfile is None:
            outfile = "{}_measurements.csv".format(self.name.replace(
                " ", "_"
            ).replace(
                "/", "_"
            ))

        elif not outfile.endswith(".csv"):
            outfile += ".csv"

        if self.outdir != ".":
            outfile = os.path.join(
                self.outdir,
                outfile
            )

        measurements_to_write.to_csv(outfile, index=False)

        self.logger.debug("Wrote {}.".format(outfile))

    def plot_lightcurve(
        self,
        sigma_thresh: int = 5,
        figsize: Tuple[int, int] = (8, 4),
        min_points: int = 2,
        min_detections: int = 0,
        mjd: bool = False,
        # TODO: Is this a pd.Timestamp or a datetime?
        start_date: Optional[pd.Timestamp] = None,
        grid: bool = False,
        yaxis_start: str = "0",
        peak_flux: bool = True,
        save: bool = False,
        outfile: Optional[str] = None,
        use_forced_for_limits: bool = False,
        use_forced_for_all: bool = False,
        hide_legend: bool = False,
        plot_dpi: int = 150
    ) -> Union[None, matplotlib.figure.Figure]:
        """
        Plot source lightcurves and save to file

        Args:
            sigma_thresh: Threshold to use for upper limits, defaults to 5.
            figsize: Figure size, defaults to (8, 4).
            min_points: Minimum number of points for plotting, defaults
                to 2.
            min_detections:  Minimum number of detections for plotting,
                defaults to 0.
            mjd: Plot x-axis in MJD rather than datetime, defaults to False.
            start_date: Plot in days from start date, defaults to None.
            grid: Turn on matplotlib grid, defaults to False.
            yaxis_start: Define where the y-axis begins from, either 'auto'
                or '0', defaults to "0".
            peak_flux: Uses peak flux instead of integrated flux,
                defaults to `True`.
            save: When `True` the plot is saved rather than displayed,
                defaults to `False`.
            outfile: The filename to save when using, defaults to None which
                will use '<souce_name>_lc.png'.
            use_forced_for_limits: Use the forced extractions instead of
                upper limits for non-detections., defaults to `False`.
            use_forced_for_all: Use the forced fits for all the datapoints,
                defaults to `False`.
            hide_legend: Hide the legend, defaults to `False`.
            plot_dpi: Specify the DPI of saved figures, defaults to 150.

        Returns:
            None if save is `True` or the matplotlib figure if save is
                `False`.

        Raises:
            SourcePlottingError: Source does not have any forced fits when the
                'use_forced_for_all' or 'use_forced_for_limits' options have
                been selected.
            SourcePlottingError: Number of detections lower than the
                minimum required.
            SourcePlottingError: Number of datapoints lower than the
                minimum required.
            SourcePlottingError: If measurements dataframe is empty.
        """
        if use_forced_for_all or use_forced_for_limits:
            if not self.forced_fits:
                raise SourcePlottingError(
                    "Source does not have any forced fits points to plot."
                )

        if self.detections < min_detections:
            msg = (
                f"Number of detections ({self.detections}) lower "
                f"than minimum required ({min_detections})"
            )
            self.logger.error(msg)
            raise SourcePlottingError(msg)

        if self.measurements.shape[0] < min_points:
            msg = (
                f"Number of datapoints ({self.measurements.shape[0]}) lower "
                f"than minimum required ({min_points})"
            )
            self.logger.error(msg)
            raise SourcePlottingError(msg)

        if mjd and start_date is not None:
            msg = (
                "The 'mjd' and 'start date' options "
                "cannot be used at the same time!"
            )
            self.logger.error(msg)
            raise SourcePlottingError(msg)

        # remove empty values
        measurements_df = self.measurements
        if not self.pipeline and not (
            use_forced_for_limits or use_forced_for_all
        ):
            measurements_df = self.measurements[
                self.measurements['rms_image'] != -99
            ]

        if measurements_df.empty:
            msg = f"{self.name} has no measurements!"
            self.logger.error(msg)
            raise SourcePlottingError(msg)

        # Build figure and labels
        fig = plt.figure(figsize=figsize)
        ax = fig.add_subplot(111)
        plot_title = self.name
        if self.islands:
            plot_title += " (island)"
        ax.set_title(plot_title)

        if peak_flux:
            label = 'Peak Flux Density (mJy/beam)'
            flux_col = "flux_peak"
        else:
            label = 'Integrated Flux Density (mJy)'
            flux_col = "flux_int"

        if use_forced_for_all:
            label = "Forced " + label
            flux_col = "f_" + flux_col

        if self.stokes != "I":
            label = "Absolute " + label
            measurements_df[flux_col] = measurements_df[flux_col].abs()

        ax.set_ylabel(label)

        freq_col = 'frequency'

        grouped_df = measurements_df.groupby(freq_col)
        freqs = list(grouped_df.groups.keys())

        # Colours for each frequency
        freq_cmap = matplotlib.colormaps.get_cmap('viridis')
        cNorm = matplotlib.colors.Normalize(
            vmin=min(freqs), vmax=max(freqs) * 1.1)
        scalarMap = matplotlib.cm.ScalarMappable(norm=cNorm, cmap=freq_cmap)
        sm = scalarMap
        sm._A = []

        # Markers for each frequency
        markers = ['o', 'D', '*', 'X', 's', 'd', 'p']

        self.logger.debug("Frequencies: {}".format(freqs))
        for i, (freq, measurements) in enumerate(grouped_df):
            self.logger.debug("Plotting {} MHz data".format(freq))
            marker = markers[i % len(markers)]
            marker_colour = sm.to_rgba(freq)
            plot_dates = measurements['dateobs']
            self.logger.debug(plot_dates)
            if mjd:
                plot_dates = Time(plot_dates.to_numpy()).mjd
            elif start_date:
                plot_dates -= start_date
                plot_dates /= pd.Timedelta(1, unit='d')

            self.logger.debug("Plotting upper limit")
            if self.pipeline:
                upper_lim_mask = measurements.forced
            else:
                upper_lim_mask = measurements.detection == False
                if use_forced_for_all:
                    upper_lim_mask = np.array([False for i in upper_lim_mask])
            upper_lims = measurements[
                upper_lim_mask
            ]
            if self.pipeline:
                if peak_flux:
                    value_col = 'flux_peak'
                    err_value_col = 'flux_peak_err'
                else:
                    value_col = 'flux_int'
                    err_value_col = 'flux_int_err'
                uplims = False
                sigma_thresh = 1.0
                label = 'Forced'
                markerfacecolor = 'w'
            else:
                if use_forced_for_limits:
                    value_col = 'f_flux_peak'
                    err_value_col = 'f_flux_peak_err'
                    uplims = False
                    sigma_thresh = 1.0
                    markerfacecolor = 'w'
                    label = "Forced"
                else:
                    value_col = err_value_col = 'rms_image'
                    uplims = True
                    markerfacecolor = marker_colour
                    label = 'Upper limit'
            if upper_lim_mask.any():
                upperlim_points = ax.errorbar(
                    plot_dates[upper_lim_mask],
                    sigma_thresh *
                    upper_lims[value_col],
                    yerr=upper_lims[err_value_col],
                    uplims=uplims,
                    lolims=False,
                    marker=marker,
                    c=marker_colour,
                    linestyle="none",
                    markerfacecolor=markerfacecolor
                )

            self.logger.debug("Plotting detection")

            if use_forced_for_all:
                detections = measurements
            else:
                detections = measurements[
                    ~upper_lim_mask
                ]

            if self.pipeline:
                if peak_flux:
                    err_value_col = 'flux_peak_err'
                else:
                    err_value_col = 'flux_int_err'
            else:
                if use_forced_for_all:
                    err_value_col = flux_col + '_err'
                else:
                    err_value_col = 'rms_image'

            if use_forced_for_all:
                markerfacecolor = 'w'
                label = 'Forced'
            else:
                markerfacecolor = marker_colour
                label = 'Selavy'
            if (~upper_lim_mask).any():
                detection_points = ax.errorbar(
                    plot_dates[~upper_lim_mask],
                    detections[flux_col],
                    yerr=detections[err_value_col],
                    marker=marker,
                    c=marker_colour,
                    linestyle="none",
                    markerfacecolor=markerfacecolor
                )

        self.logger.debug("Plotting finished.")
        if self.pipeline:
            upper_lim_mask = measurements_df.forced
        else:
            upper_lim_mask = measurements_df.detection == False

        if use_forced_for_all:
            detections = measurements_df
        else:
            detections = measurements_df[
                ~upper_lim_mask
            ]

        if self.pipeline:
            upper_lim_mask = measurements_df.forced
        else:
            upper_lim_mask = measurements_df.detection == False
            if use_forced_for_all:
                upper_lim_mask = np.array([False for i in upper_lim_mask])
        upper_lims = measurements_df[
            upper_lim_mask
        ]

        if yaxis_start == "0":
            max_det = detections.loc[:, [flux_col, err_value_col]].sum(axis=1)
            if use_forced_for_limits or self.pipeline:
                max_y = np.nanmax(
                    max_det.tolist() +
                    upper_lims[value_col].tolist()
                )
            elif use_forced_for_all:
                max_y = np.nanmax(max_det.tolist())
            else:
                max_y = np.nanmax(
                    max_det.tolist() +
                    (sigma_thresh * upper_lims[err_value_col]).tolist()
                )
            ax.set_ylim(
                bottom=0,
                top=max_y * 1.1
            )

        if mjd:
            ax.set_xlabel('Date (MJD)')
        elif start_date:
            ax.set_xlabel('Days since {}'.format(start_date))
        else:
            fig.autofmt_xdate()
            ax.set_xlabel('Date')

            date_form = mdates.DateFormatter("%Y-%m-%d")
            ax.xaxis.set_major_formatter(date_form)
            ax.xaxis.set_major_locator(mdates.AutoDateLocator(maxticks=15))

        ax.grid(grid)

        if not hide_legend:
            # Manually create legend artists for consistency.
            # Using dummy points throws a matplotlib warning.
            handles = []
            labels = []
            for i, freq in enumerate(freqs):
                line = Line2D([],
                              [],
                              ls="",
                              marker=markers[i],
                              color=sm.to_rgba(freq)
                              )
                barline = LineCollection(np.empty((2, 2, 2)))

                err = ErrorbarContainer((line, None, [barline]),
                                        has_yerr=True
                                        )
                handles.append(err)
                labels.append('{} MHz'.format(freq))

            ax.legend(handles=handles, labels=labels)

        if save:
            if outfile is None:
                outfile = "{}_lc.png".format(self.name.replace(
                    " ", "_"
                ).replace(
                    "/", "_"
                ))

            elif not outfile.endswith(".png"):
                outfile += ".png"

            if self.outdir != ".":
                outfile = os.path.join(
                    self.outdir,
                    outfile
                )

            plt.savefig(outfile, bbox_inches='tight', dpi=plot_dpi)
            plt.close()

            return

        else:

            return fig

    def get_cutout_data(self, size: Optional[Angle] = None) -> None:
        """
        Function to fetch the cutout data for that source
        required for producing all the media output.

        If size is not provided then the default size of 5 arcmin will be
        used.

        Args:
            size: The angular size of the cutouts, defaults to None.

        Returns:
            None
        """
        if size is None:
            args = None
        else:
            args = (size,)

        self.cutout_df = self.measurements.apply(
            self._get_cutout,
            args=args,
            axis=1,
            result_type='expand'
        ).rename(columns={
            0: "data",
            1: "wcs",
            2: "header",
            3: "selavy_overlay",
            4: "beam"
        })
        self._cutouts_got = True

    def _analyse_norm_level(
        self,
        percentile: float = 99.9,
        zscale: bool = False,
        z_contrast: float = 0.2,
        cutout_data: Optional[pd.DataFrame] = None
    ) -> Union[None, ImageNormalize]:
        """
        Selects the appropriate image to use as the normalization
        value for each image.

        Either the first `detection` image is used, or the first image
        in time if there are no detections.

        Args:
            percentile: The value passed to the percentile
                normalization function, defaults to 99.9.
            zscale: Uses ZScale normalization instead of PercentileInterval,
                defaults to `False`
            z_contrast: Contast value passed to the ZScaleInterval
                function when zscale is selected, defaults to 0.2.
            cutout_data: Pass external cutout_data to be used
                instead of fetching the data, defaults to None.

        Returns:
            The normalisation.

        Raises:
            ValueError: If the cutout data is yet to be obtained.
        """
        if cutout_data is None:
            if not self._cutouts_got:
                self.logger.warning(
                    "Fetch cutout data before running this function!"
                )

                raise ValueError(
                    "Fetch cutout data before running this function!"
                )
            else:
                cutout_data = self.cutout_df

        if self.detections > 0:
            scale_index = self.measurements[
                self.measurements.detection
            ].index.values[0]
        else:
            scale_index = 0

        scale_data = cutout_data.loc[scale_index].data * 1.e3

        if zscale:
            norms = ImageNormalize(
                scale_data, interval=ZScaleInterval(
                    contrast=z_contrast))
        else:
            norms = ImageNormalize(
                scale_data,
                interval=PercentileInterval(percentile),
                stretch=LinearStretch())

        return norms

    def _get_cutout(
        self, row: pd.Series, size: Angle = Angle(5. * u.arcmin)
    ) -> Tuple[np.ndarray, WCS, fits.Header, pd.DataFrame, Beam]:
        """Does the actual fetching of the cutout data.

        Args:
            row: The row in the measurements df for which
                media will be fetched.
            size: The size of the cutout, defaults to Angle(5.*u.arcmin)

        Returns:
            Tuple containing the cutout data.
        """

        self._size = size

        if self.pipeline:
            image = Image(
                row.field, row.epoch, self.stokes, self.base_folder,
                path=row.image, rmspath=row.rms,
                corrected_data=self.corrected_data,
                post_processed_data=self.post_processed_data
            )
            image.get_img_data()
        else:
            e = row.epoch
            if "-" in e:
                e = e.split("-")[0]
            image = Image(
                row.field, e, self.stokes,
                self.base_folder, tiles=self.tiles, sbid=row.sbid,
                corrected_data=self.corrected_data,
                post_processed_data=self.post_processed_data
            )
            image.get_img_data()

        cutout = Cutout2D(
            image.data,
            position=row.skycoord,
            size=size,
            wcs=image.wcs
        )

        cutout_data = copy.deepcopy(cutout.data)
        cutout_wcs = copy.deepcopy(cutout.wcs)

        header = copy.deepcopy(image.header)
        header.update(cutout.wcs.to_header())

        beam = image.beam

        del cutout
        del image

        if self.pipeline:
            selavy_components = pd.read_parquet(
                row.selavy,
                columns=[
                    'island_id',
                    'ra',
                    'dec',
                    'bmaj',
                    'bmin',
                    'pa'
                ]
            ).rename(
                columns={
                    'ra': 'ra_deg_cont',
                    'dec': 'dec_deg_cont',
                    'bmaj': 'maj_axis',
                    'bmin': 'min_axis',
                    'pa': 'pos_ang'
                }
            )
        else:
            selavy_components = read_selavy(row.selavy, cols=[
                'island_id',
                'ra_deg_cont',
                'dec_deg_cont',
                'maj_axis',
                'min_axis',
                'pos_ang'
            ])

        selavy_coords = SkyCoord(
            selavy_components.ra_deg_cont.values,
            selavy_components.dec_deg_cont.values,
            unit=(u.deg, u.deg)
        )

        selavy_components = filter_selavy_components(
            selavy_components,
            selavy_coords,
            size,
            row.skycoord
        )

        del selavy_coords

        return (
            cutout_data, cutout_wcs, header, selavy_components, beam
        )

    def show_png_cutout(
        self,
        index: int,
        selavy: bool = True,
        percentile: float = 99.9,
        zscale: bool = False,
        contrast: float = 0.2,
        no_islands: bool = True,
        label: str = "Source",
        no_colorbar: bool = False,
        title: Optional[str] = None,
        crossmatch_overlay: bool = False,
        hide_beam: bool = False,
        size: Optional[Angle] = None,
        force_cutout_fetch: bool = False,
        offset_axes: bool = True,
    ) -> plt.Figure:
        """
        Wrapper for make_png to make nicer interactive function.
        No access to save.

        Args:
            index: Index of the observation to show.
            selavy: If `True` then selavy overlay are shown,
                 defaults to `True`.
            percentile: The value passed to the percentile
                normalization function, defaults to 99.9.
            zscale: Uses ZScale normalization instead of
                PercentileInterval, defaults to `False`.
            contrast: Contrast value passed to the ZScaleInterval
                function when zscale is selected, defaults to 0.2.
            no_islands: Hide island name labels, defaults to `True`.
            label: legend label for source, defaults to "Source".
            no_colorbar: Hides the colorbar, defaults to `False`.
            title: Sets the plot title, defaults to None.
            crossmatch_overlay: Plots a circle that represents the
                crossmatch radius, defaults to `False`.
            hide_beam: Hide the beam on the plot, defaults to `False`.
            size: Size of the cutout, defaults to None.
            force_cutout_fetch: Whether to force the re-fetching of the cutout
                data, defaults to `False`.
            offset_axes: Use offset, rather than absolute, axis labels.

        Returns:
            The cutout Figure.
        """

        fig = self.make_png(
            index,
            selavy=selavy,
            percentile=percentile,
            zscale=zscale,
            contrast=contrast,
            no_islands=no_islands,
            label=label,
            no_colorbar=no_colorbar,
            title=title,
            crossmatch_overlay=crossmatch_overlay,
            hide_beam=hide_beam,
            size=size,
            force_cutout_fetch=force_cutout_fetch,
            offset_axes=offset_axes,
            disable_autoscaling=True
        )

        return fig

    def save_png_cutout(
        self,
        index: int,
        selavy: bool = True,
        percentile: float = 99.9,
        zscale: bool = False,
        contrast: float = 0.2,
        no_islands: bool = True,
        label: str = "Source",
        no_colorbar: bool = False,
        title: Optional[str] = None,
        crossmatch_overlay: bool = False,
        hide_beam: bool = False,
        size: Optional[Angle] = None,
        force_cutout_fetch: bool = False,
        outfile: Optional[str] = None,
        plot_dpi: int = 150,
        offset_axes: bool = True
    ) -> None:
        """
        Wrapper for make_png to make nicer interactive function.
        Always save.

        Args:
            index: Index of the observation to show.
            selavy: If `True` then selavy overlay are shown,
                 defaults to `True`.
            percentile: The value passed to the percentile
                normalization function, defaults to 99.9.
            zscale: Uses ZScale normalization instead of
                PercentileInterval, defaults to `False`.
            contrast: Contrast value passed to the ZScaleInterval
                function when zscale is selected, defaults to 0.2.
            no_islands: Hide island name labels, defaults to `True`.
            label: legend label for source, defaults to "Source".
            no_colorbar: Hides the colorbar, defaults to `False`.
            title: Sets the plot title, defaults to None.
            crossmatch_overlay: Plots a circle that represents the
                crossmatch radius, defaults to `False`.
            hide_beam: Hide the beam on the plot, defaults to `False`.
            size: Size of the cutout, defaults to None.
            force_cutout_fetch: Whether to force the re-fetching
                of the cutout data, defaults to `False`.
            outfile: Name to give the file, if None then the name is
                automatically generated, defaults to None.
            plot_dpi: Specify the DPI of saved figures, defaults to 150.
            offset_axes: Use offset, rather than absolute, axis labels.

        Returns:
            None
        """
        fig = self.make_png(
            index,
            selavy=selavy,
            percentile=percentile,
            zscale=zscale,
            contrast=contrast,
            no_islands=no_islands,
            label=label,
            no_colorbar=no_colorbar,
            title=title,
            crossmatch_overlay=crossmatch_overlay,
            hide_beam=hide_beam,
            size=size,
            force_cutout_fetch=force_cutout_fetch,
            outfile=outfile,
            save=True,
            plot_dpi=plot_dpi,
            offset_axes=offset_axes,
            disable_autoscaling=True
        )

        return

    def _get_save_name(self,
                       index: int,
                       ext: str
                       ) -> str:
        """
        Generate name of file to save to.

        Args:
            index: Index of the requested data
            ext: File extension

        Returns:
            Name of file to save.
        """

        row = self.measurements.iloc[index]

        if not ext.startswith("."):
            ext = f".{ext}"

        source_name = self.name.replace(" ", "_").replace("/", "_")

        if self.pipeline:
            outfile = f"{source_name}_{index}{ext}"
        else:
            field_name = row.field
            sbid = row.sbid

            outfile = f"{source_name}_{field_name}_SB{sbid}{ext}"

        return outfile

    def save_fits_cutout(
        self,
        index: int,
        outfile: Optional[str] = None,
        size: Optional[Angle] = None,
        force_cutout_fetch: bool = False,
        cutout_data: Optional[pd.DataFrame] = None
    ) -> None:
        """
        Saves the FITS file cutout of the requested observation.

        Args:
            index: The index of the requested observation.
            outfile: File to save to, defaults to None.
            size: Size of the cutout, defaults to None.
            force_cutout_fetch: Whether to force the re-fetching
                of the cutout data, defaults to `False`.
            cutout_data: Pass external cutout_data to be used
                instead of fetching the data, defaults to None.

        Returns:
            None

        Raises:
            ValueError: If the source does not contain the requested index.
        """

        if (self._cutouts_got is False) or force_cutout_fetch:
            if cutout_data is None:
                self.get_cutout_data(size)

        if outfile is None:
            outfile = self._get_save_name(index, ".fits")

        if self.outdir != ".":
            outfile = os.path.join(
                self.outdir,
                outfile
            )
        if cutout_data is None:
            cutout_row = self.cutout_df.iloc[index]
        else:
            cutout_row = cutout_data.iloc[index]

        hdu_stamp = fits.PrimaryHDU(
            data=cutout_row.data,
            header=cutout_row.header
        )

        # Write the cutout to a new FITS file
        hdu_stamp.writeto(outfile, overwrite=True)
        self.logger.debug(f"Wrote to {outfile}")

        del hdu_stamp

    def _save_noisemap_cutout(
        self,
        index: int,
        cutout_data: pd.DataFrame,
        noisemap_type: str,
        outfile: Optional[str] = None,
    ) -> None:
        """
        Saves the FITS file cutout of the requested observation.

        Args:
            index: The index of the requested observation.
            cutout_data: The external cutout data to be used.
            noisemap_type: The type of noisemap to use. Must be 'rms' or 'bkg'.
            outfile: File to save to, defaults to None.

        Returns:
            None

        Raises:
            ValueError: If the noisemap_type is not 'rms' or 'bkg'
        """

        if noisemap_type not in ['rms', 'bkg']:
            raise ValueError("noisemap_type must be 'rms' or 'bkg'")
        if outfile is None:
            outfile = self._get_save_name(index, f"{noisemap_type}.fits")

        if self.outdir != ".":
            outfile = os.path.join(
                self.outdir,
                outfile
            )
        cutout_row = cutout_data.iloc[index]

        hdu_stamp = fits.PrimaryHDU(
            data=cutout_row[f'{noisemap_type}_data'],
            header=cutout_row[f'{noisemap_type}_header']
        )

        # Write the cutout to a new FITS file
        hdu_stamp.writeto(outfile, overwrite=True)
        self.logger.debug(f"Wrote to {outfile}")

        del hdu_stamp

    def save_all_ann(
        self,
        crossmatch_overlay: bool = False,
        cutout_data: Optional[pd.DataFrame] = None
    ) -> None:
        """
        Save kvis annotation file corresponding to the source

        Args:
            crossmatch_overlay: Include the crossmatch radius,
                defaults to `False`
            cutout_data: Pass external cutout_data to be used
                instead of fetching the data, defaults to None.

        Returns:
            None
        """
        indices = self.measurements.index.to_series()
        indices.apply(
            self.write_ann,
            args=(
                None,
                crossmatch_overlay,
                None,
                False,
                cutout_data
            )
        )

    def save_all_reg(
        self,
        crossmatch_overlay: bool = False,
        cutout_data: Optional[pd.DataFrame] = None
    ) -> None:
        """
        Save DS9 region file corresponding to the source

        Args:
            crossmatch_overlay: Include the crossmatch radius,
                defaults to `False`
            cutout_data: Pass external cutout_data to be used
                instead of fetching the data, defaults to None.

        Returns:
            None
        """

        indices = self.measurements.index.to_series()
        indices.apply(
            self.write_reg,
            args=(
                None,
                crossmatch_overlay,
                None,
                False,
                cutout_data
            )
        )

    def save_all_fits_cutouts(
        self,
        size: Optional[Angle] = None,
        force_cutout_fetch: bool = False,
        cutout_data: Optional[pd.DataFrame] = None
    ) -> None:
        """
        Save all cutouts of the source to fits file

        Args:
            size: Size of the cutouts, defaults to None.
            force_cutout_fetch: Whether to force the re-fetching
                of the cutout data, defaults to `False`.
            cutout_data: Pass external cutout_data to be used
                instead of fetching the data, defaults to None.

        Returns:
            None
        """
        if (self._cutouts_got is False) or force_cutout_fetch:
            if cutout_data is None:
                self.get_cutout_data(size)

        self.logger.debug("Saving fits cutouts...")

        if cutout_data is None:
            indices = self.measurements.index
        else:
            indices = cutout_data.index

        for i in indices:
            self.save_fits_cutout(i, cutout_data=cutout_data)

    def _save_all_noisemap_cutouts(
        self,
        cutout_data: pd.DataFrame,
        rms: bool = True,
        bkg: bool = True,
    ) -> None:
        """
        Save all cutouts of the source to fits file

        Args:
            cutout_data: The external data to be used.
            rms: Create rms map cutouts.
            bkg: Create bkg map cutouts.

        Returns:
            None
        """

        self.logger.debug("Saving noisemap cutouts...")

        for i in cutout_data.index:
            if rms:
                self._save_noisemap_cutout(i, cutout_data, 'rms')
            if bkg:
                self._save_noisemap_cutout(i, cutout_data, 'bkg')

    def save_all_png_cutouts(
        self,
        selavy: bool = True,
        percentile: float = 99.9,
        zscale: bool = False,
        contrast: float = 0.2,
        no_islands: bool = True,
        no_colorbar: bool = False,
        crossmatch_overlay: bool = False,
        hide_beam: bool = False,
        size: Optional[Angle] = None,
        disable_autoscaling: bool = False,
        cutout_data: Optional[pd.DataFrame] = None,
        calc_script_norms: bool = False,
        plot_dpi: int = 150,
        offset_axes: bool = True
    ) -> None:
        """
        Wrapper function to save all the png cutouts
        for all epochs.

        Args:
            selavy: If `True` then selavy overlay are shown,
                 defaults to `True`.
            percentile: The value passed to the percentile
                normalization function, defaults to 99.9.
            zscale: Uses ZScale normalization instead of
                PercentileInterval, defaults to `False`.
            contrast: Contrast value passed to the ZScaleInterval
                function when zscale is selected, defaults to 0.2.
            no_islands: Hide island name labels, defaults to `True`.
            no_colorbar: Hides the colorbar, defaults to `False`.
            crossmatch_overlay: Plots a circle that represents the
                crossmatch radius, defaults to `False`.
            hide_beam: Hide the beam on the plot, defaults to `False`.
            size: Size of the cutout, defaults to None.
            disable_autoscaling: Do not use the consistent normalization
                values but calculate norms separately for each epoch,
                defaults to `False`.
            cutout_data: Pass external cutout_data to be used
                instead of fetching the data, defaults to None.
            calc_script_norms: When passing cutout data this parameter
                can be set to True to pass this cutout data to the analyse
                norms function, defaults to False.
            plot_dpi: Specify the DPI of saved figures, defaults to 150.
            offset_axes: Use offset, rather than absolute, axis labels.

        Returns:
            None
        """
        if self._cutouts_got is False:
            if cutout_data is None:
                self.get_cutout_data(size)

        if disable_autoscaling:
            norms = None
        else:
            if not calc_script_norms:
                norms = self._analyse_norm_level(
                    percentile=percentile,
                    zscale=zscale,
                    z_contrast=contrast
                )
            else:
                norms = self._analyse_norm_level(
                    percentile=percentile,
                    zscale=zscale,
                    z_contrast=contrast,
                    cutout_data=cutout_data
                )

        indices = self.measurements.index.to_series()
        indices.apply(
            self.make_png,
            args=(
                selavy,
                percentile,
                zscale,
                contrast,
                None,
                no_islands,
                "Source",
                no_colorbar,
                None,
                crossmatch_overlay,
                hide_beam,
                True,
                None,
                False,
                disable_autoscaling,
                cutout_data,
                norms,
                plot_dpi,
                offset_axes
            )
        )

    def show_all_png_cutouts(
        self,
        columns: int = 4,
        percentile: float = 99.9,
        zscale: bool = False,
        contrast: float = 0.1,
        outfile: Optional[str] = None,
        save: bool = False,
        size: Optional[Angle] = None,
        stampsize: Optional[Tuple[float, float]] = (4, 4),
        figsize: Optional[Tuple[float, float]] = None,
        force_cutout_fetch: bool = False,
        no_selavy: bool = False,
        disable_autoscaling: bool = False,
        hide_epoch_labels: bool = False,
        plot_dpi: int = 150,
        offset_axes: bool = True
    ) -> Union[None, matplotlib.figure.Figure]:
        """
        Creates a grid plot showing the source in each epoch.

        Args:
            columns: Number of columns to use for the grid plot,
                defaults to 4.
            percentile: The value passed to the percentile
                normalization function, defaults to 99.9.
            zscale: Uses ZScale normalization instead of
                PercentileInterval, defaults to `False`.
            contrast: Contast value passed to the ZScaleInterval
                function when zscale is selected, defaults to 0.2.
            outfile: Name of the output file, if None then the name
                 is automatically generated, defaults to None.
            save: Save the plot instead of displaying,
                defaults to `False`.
            size: Size of the cutout, defaults to None.
            stampsize: Size of each postagestamp, to be used to calculate
                the figsize. Default to (4,4).
            figsize: Size of the matplotlib.pyplot figure, which will overwrite
                the stampsize argument if provided. Defaults to None.
            force_cutout_fetch: Whether to force the re-fetching
                of the cutout data, defaults to `False`.
            no_selavy: When `True` the selavy overlay
                is hidden, defaults to `False`.
            disable_autoscaling: Turn off the consistent normalization and
                 calculate the normalizations separately for each epoch,
                defaults to `False`.
            hide_epoch_labels: Turn off the epoch number label (found in
                top left corner of image).
            plot_dpi: Specify the DPI of saved figures, defaults to 150.
            offset_axes: Use offset, rather than absolute, axis labels.

        Returns:
            None is save is `True` or the Figure if `False`.

        Raises:
            ValueError: Stampsize and Figsize cannot both be None
        """

        if (self._cutouts_got is False) or force_cutout_fetch:
            self.get_cutout_data(size)

        num_plots = self.measurements.shape[0]
        nrows = int(np.ceil(num_plots / columns))

        if figsize is None:
            if stampsize is None:
                raise ValueError("Stampsize and Figsize cannot both be None")
            figsize = (stampsize[0] * columns, stampsize[1] * nrows)

        fig = plt.figure(figsize=figsize)
        fig.tight_layout()
        plots = {}

        img_norms = self._analyse_norm_level(
            percentile=percentile,
            zscale=zscale,
            z_contrast=contrast
        )

        for i in range(num_plots):
            cutout_row = self.cutout_df.iloc[i]
            measurement_row = self.measurements.iloc[i]
            target_coords = np.array(
                ([[
                    measurement_row.ra,
                    measurement_row.dec
                ]])
            )
            i += 1
            plots[i] = fig.add_subplot(
                nrows,
                columns,
                i,
                projection=cutout_row.wcs
            )

            if disable_autoscaling:
                if zscale:
                    img_norms = ImageNormalize(
                        cutout_row.data * 1.e3,
                        interval=ZScaleInterval(
                            contrast=contrast
                        )
                    )
                else:
                    img_norms = ImageNormalize(
                        cutout_row.data * 1.e3,
                        interval=PercentileInterval(percentile),
                        stretch=LinearStretch())

            im = plots[i].imshow(
                cutout_row.data * 1.e3, norm=img_norms, cmap="gray_r"
            )

            epoch_time = measurement_row.dateobs
            epoch = measurement_row.epoch

            plots[i].set_title('{}'.format(
                epoch_time.strftime("%Y-%m-%d %H:%M:%S")
            ))

            if not hide_epoch_labels:
                plots[i].text(
                    0.05, 0.9, f"{epoch}", transform=plots[i].transAxes
                )

            cross_target_coords = cutout_row.wcs.wcs_world2pix(
                target_coords, 0
            )
            crosshair_lines = self._create_crosshair_lines(
                cross_target_coords,
                0.15,
                0.15,
                cutout_row.data.shape
            )

            if (not cutout_row['selavy_overlay'].empty) and (not no_selavy):
                plots[i].set_autoscale_on(False)
                (
                    collection,
                    patches,
                    island_names
                ) = self._gen_overlay_collection(
                    cutout_row
                )
                plots[i].add_collection(collection, autolim=False)

            if self.forced_fits:
                (
                    collection,
                    patches,
                    island_names
                ) = self._gen_overlay_collection(
                    cutout_row, f_source=measurement_row
                )
                plots[i].add_collection(collection, autolim=False)
                del collection

            [plots[i].plot(
                l[0], l[1], color="C3", zorder=10, lw=1.5, alpha=0.6
            ) for l in crosshair_lines]

            lon = plots[i].coords[0]
            lat = plots[i].coords[1]

            lon.set_ticks_visible(False)
            lon.set_ticklabel_visible(False)
            lat.set_ticks_visible(False)
            lat.set_ticklabel_visible(False)

        if save:
            if outfile is None:
                outfile = "{}_cutouts.png".format(self.name.replace(
                    " ", "_"
                ).replace(
                    "/", "_"
                ))

            elif not outfile.endswith(".png"):
                outfile += ".png"

            if self.outdir != ".":
                outfile = os.path.join(
                    self.outdir,
                    outfile
                )

            plt.savefig(outfile, bbox_inches='tight', dpi=plot_dpi)

            plt.close()

            return

        else:

            return fig

    def _gen_overlay_collection(
        self,
        cutout_row: pd.Series,
        f_source: Optional[pd.DataFrame] = None
    ) -> Tuple[PatchCollection, Patch, List[str]]:
        """
        Generates the ellipse collection for selavy sources to add
        to the matplotlib axis.

        Args:
            cutout_row: The row containing the selavy data
                to make the ellipses from.
            f_source: Forced fit extraction to create the
                 forced fit ellipse, defaults to None.

        Returns:
            Tuple of the ellipse collection, patches, and the island names.
        """

        wcs = cutout_row.wcs
        selavy_sources = cutout_row.selavy_overlay
        pix_scale = proj_plane_pixel_scales(wcs)
        sx = pix_scale[0]
        sy = pix_scale[1]
        degrees_per_pixel = np.sqrt(sx * sy)

        # define ellipse properties for clarity, selavy cut will have
        # already been created.
        if f_source is None:
            ww = selavy_sources["maj_axis"]
            hh = selavy_sources["min_axis"]
            aa = selavy_sources["pos_ang"]
            x = selavy_sources["ra_deg_cont"]
            y = selavy_sources["dec_deg_cont"]
        else:
            ww = np.array([f_source["f_maj_axis"]])
            hh = np.array([f_source["f_min_axis"]])
            aa = np.array([f_source["f_pos_ang"]])
            x = np.array([f_source["ra"]])
            y = np.array([f_source["dec"]])

        ww = ww.astype(float) / 3600.
        hh = hh.astype(float) / 3600.
        ww /= degrees_per_pixel
        hh /= degrees_per_pixel
        aa = aa.astype(float)
        x = x.astype(float)
        y = y.astype(float)

        coordinates = np.column_stack((x, y))

        coordinates = wcs.wcs_world2pix(coordinates, 0)

        # Create ellipses, collect them, add to axis.
        # Also where correction is applied to PA to account for how selavy
        # defines it vs matplotlib
        if f_source is None:
            island_names = selavy_sources["island_id"].apply(
                self._remove_sbid
            )
            colors = ["C2" if c.startswith(
                "n") else "C1" for c in island_names]
        else:
            island_names = [f_source["f_island_id"], ]
            colors = ["C3" for c in island_names]

        patches = [Ellipse(
            coordinates[i], hh[i], ww[i],
            angle=aa[i]) for i in range(len(coordinates))]
        collection = PatchCollection(
            patches,
            facecolors="None",
            edgecolors=colors,
            lw=1.5)

        return collection, patches, island_names

    def skyview_contour_plot(
        self,
        index: int,
        survey: str,
        contour_levels: List[float] = [3., 5., 10., 15.],
        percentile: float = 99.9,
        zscale: bool = False,
        contrast: float = 0.2,
        outfile: Optional[str] = None,
        no_colorbar: bool = False,
        title: Optional[str] = None,
        save: bool = False,
        size: Optional[Angle] = None,
        force_cutout_fetch: bool = False,
        plot_dpi: int = 150,
    ) -> Union[None, matplotlib.figure.Figure]:
        """
        Fetches a FITS file from SkyView of the requested survey at
        the source location and overlays ASKAP contours.

        Args:
            index: Index of the requested ASKAP observation.
            survey: Survey requested to be fetched using SkyView.
            contour_levels: Contour levels to plot which are multiples
                 of the local rms, defaults to [3., 5., 10., 15.].
            percentile: The value passed to the percentile
                normalization function, defaults to 99.9.
            zscale: Uses ZScale normalization instead of
                PercentileInterval, defaults to `False`.
            contrast: Contrast value passed to the ZScaleInterval
                function when zscale is selected, defaults to 0.2.
            outfile: Name to give the file, if None then the name is
                automatically generated, defaults to None.
            no_colorbar: Hides the colorbar, defaults to `False`.
            title: Plot title, defaults to None.
            save: Saves the file instead of returing the figure,
                defaults to `False`.
            size: Size of the cutout, defaults to None.
            force_cutout_fetch: Whether to force the re-fetching
                of the cutout data, defaults to `False`.
            plot_dpi: Specify the DPI of saved figures, defaults to 150.

        Returns:
            None if save is `True` or the figure object if `False`

        Raises:
            ValueError: If the index is out of range.
            ValueError: If the requested survey is not valid.
        """

        if (self._cutouts_got is False) or force_cutout_fetch:
            self.get_cutout_data(size)

        size = self._size

        surveys = list(SkyView.survey_dict.values())
        survey_list = [item for sublist in surveys for item in sublist]

        if survey not in survey_list:
            raise ValueError(f"{survey} is not a valid SkyView survey name")

        if index > len(self.measurements):
            raise ValueError(f"Cannot access {index}th measurement.")
            return

        if outfile is None:
            outfile = self._get_save_name(index, ".png")

        if self.outdir != ".":
            outfile = os.path.join(
                self.outdir,
                outfile
            )

        try:
            paths = SkyView.get_images(
                position=self.measurements.iloc[index]['skycoord'],
                survey=[survey], radius=size
            )
            path_fits = paths[0][0]

            path_wcs = WCS(path_fits.header)

        except Exception as e:
            warnings.warn("SkyView fetch failed!")
            warnings.warn(e)
            return

        fig = plt.figure(figsize=(8, 8))
        ax = fig.add_subplot(111, projection=path_wcs)

        mean_vast, median_vast, rms_vast = sigma_clipped_stats(
            self.cutout_df.iloc[index].data
        )

        levels = [
            i * rms_vast for i in contour_levels
        ]

        if zscale:
            norm = ImageNormalize(
                path_fits.data,
                interval=ZScaleInterval(
                    contrast=contrast
                )
            )
        else:
            norm = ImageNormalize(
                path_fits.data,
                interval=PercentileInterval(percentile),
                stretch=LinearStretch()
            )

        im = ax.imshow(path_fits.data, norm=norm, cmap='gray_r')

        ax.contour(
            self.cutout_df.iloc[index].data,
            levels=levels,
            transform=ax.get_transform(self.cutout_df.iloc[index].wcs),
            colors='C0',
            zorder=10,
        )

        if title is None:
            obs_time = self.measurements.iloc[index].dateobs
            title = "{} {}".format(
                self.name,
                obs_time.strftime(
                    "%Y-%m-%d %H:%M:%S"
                )
            )

        ax.set_title(title)

        lon = ax.coords[0]
        lat = ax.coords[1]
        lon.set_axislabel("Right Ascension (J2000)")
        lat.set_axislabel("Declination (J2000)")

        if not no_colorbar:
            divider = make_axes_locatable(ax)
            cax = divider.append_axes(
                "right", size="3%", pad=0.1, axes_class=maxes.Axes)
            cb = fig.colorbar(im, cax=cax)

        if save:
            plt.savefig(outfile, bbox_inches="tight", dpi=plot_dpi)
            self.logger.debug("Saved {}".format(outfile))

            plt.close(fig)

            return
        else:
            return fig

    def make_png(
        self,
        index: int,
        selavy: bool = True,
        percentile: float = 99.9,
        zscale: bool = False,
        contrast: float = 0.2,
        outfile: Optional[str] = None,
        no_islands: bool = True,
        label: str = "Source",
        no_colorbar: bool = False,
        title: Optional[str] = None,
        crossmatch_overlay: bool = False,
        hide_beam: bool = False,
        save: bool = False,
        size: Optional[Angle] = None,
        force_cutout_fetch: bool = False,
        disable_autoscaling: bool = False,
        cutout_data: Optional[pd.DataFrame] = None,
        norms: Optional[ImageNormalize] = None,
        plot_dpi: int = 150,
        offset_axes: bool = True
    ) -> Union[None, matplotlib.figure.Figure]:
        """
        Save a PNG of the image postagestamp.

        Args:
            index: The index correpsonding to the requested observation.
            selavy: `True` to overlay selavy components, `False` otherwise.
            percentile: The value passed to the percentile
                normalization function, defaults to 99.9.
            zscale: Uses ZScale normalization instead of
                PercentileInterval, defaults to `False`.
            contrast: Contrast value passed to the ZScaleInterval
                function when zscale is selected, defaults to 0.2.
            outfile: Name to give the file, if None then the name is
                automatically generated, defaults to None.
            no_islands: Disable island lables on the png, defaults to
                `False`.
            label: Figure title (usually the name of the source of
                interest), defaults to "Source".
            no_colorbar: If `True`, do not show the colorbar on the png,
                defaults to `False`.
            title: String to set as title,
                defaults to None where a default title will be used.
            crossmatch_overlay: If 'True' then a circle is added to the png
                plot representing the crossmatch radius, defaults to `False`.
            hide_beam: If 'True' then the beam is not plotted onto the png
                plot, defaults to `False`.
            save: If `True` the plot is saved rather than the figure being
                returned, defaults to `False`.
            size: Size of the cutout, defaults to None.
            force_cutout_fetch: Whether to force the re-fetching of the cutout
                data, defaults to `False`.
            disable_autoscaling: Turn off the consistent normalization and
                calculate the normalizations separately for each observation,
                defaults to `False`.
            cutout_data: Pass external cutout_data to be used
                instead of fetching the data, defaults to None.
            norms: Pass external normalization to be used
                instead of internal calculations.
            plot_dpi: Specify the DPI of saved figures, defaults to 150.
            offset_axes: Use offset, rather than absolute, axis labels.

        Returns:
            None if save is `True` or the figure object if `False`

        Raises:
            ValueError: If the index is out of range.
        """

        if (self._cutouts_got is False) or force_cutout_fetch:
            if cutout_data is None:
                self.get_cutout_data(size)

        if index > len(self.measurements):
            raise ValueError(f"Cannot access {index}th measurement.")

        if outfile is None:
            outfile = self._get_save_name(index, ".png")

        if self.outdir != ".":
            outfile = os.path.join(
                self.outdir,
                outfile
            )

        if cutout_data is None:
            cutout_row = self.cutout_df.iloc[index]
        else:
            cutout_row = cutout_data.iloc[index]

        fig = plt.figure(figsize=(8, 8))
        ax = fig.add_subplot(111, projection=cutout_row.wcs)
        # Get the Image Normalisation from zscale, user contrast.
        if not disable_autoscaling:
            if norms is not None:
                img_norms = norms
            else:
                img_norms = self._analyse_norm_level(
                    percentile=percentile,
                    zscale=zscale,
                    z_contrast=contrast
                )
        else:
            if zscale:
                img_norms = ImageNormalize(
                    cutout_row.data * 1.e3,
                    interval=ZScaleInterval(
                        contrast=contrast
                    ))
            else:
                img_norms = ImageNormalize(
                    cutout_row.data * 1.e3,
                    interval=PercentileInterval(percentile),
                    stretch=LinearStretch())

        im = ax.imshow(
            cutout_row.data * 1.e3,
            norm=img_norms,
            cmap="gray_r"
        )

        # insert crosshair of target
        target_coords = np.array(
            ([[
                self.measurements.iloc[index].ra,
                self.measurements.iloc[index].dec
            ]])
        )

        target_coords = cutout_row.wcs.wcs_world2pix(
            target_coords, 0
        )

        crosshair_lines = self._create_crosshair_lines(
            target_coords,
            0.03,
            0.03,
            cutout_row.data.shape
        )

        [ax.plot(
            l[0], l[1], color="C3", zorder=10, lw=1.5, alpha=0.6
        ) for l in crosshair_lines]
        # the commented lines below are to use the crosshair
        # marker directly.
        # ax.scatter(
        #     [self.src_coord.ra.deg], [self.src_coord.dec.deg],
        #     transform=ax.get_transform('world'), marker="c",
        #     color="C3", zorder=10, label=label, s=1000, lw=1.5,
        #     alpha=0.5
        # )
        if crossmatch_overlay:
            try:
                crossmatch_patch = SphericalCircle(
                    (
                        self.measurements.iloc[index].skycoord.ra,
                        self.measurements.iloc[index].skycoord.dec
                    ),
                    self.crossmatch_radius,
                    transform=ax.get_transform('world'),
                    label="Crossmatch radius ({:.1f} arcsec)".format(
                        self.crossmatch_radius.arcsec
                    ), edgecolor='C4', facecolor='none', alpha=0.8)
                ax.add_patch(crossmatch_patch)
            except Exception as e:
                self.logger.warning(
                    "Crossmatch circle png overlay failed!"
                    " Has the source been crossmatched?")
                crossmatch_overlay = False

        if (not cutout_row['selavy_overlay'].empty) and selavy:
            ax.set_autoscale_on(False)
            collection, patches, island_names = self._gen_overlay_collection(
                cutout_row
            )
            ax.add_collection(collection, autolim=False)
            del collection

            # Add island labels, haven't found a better way other than looping
            # at the moment.
            if not no_islands and not self.islands:
                for i, val in enumerate(patches):
                    ax.annotate(
                        island_names[i],
                        val.center,
                        annotation_clip=True,
                        color="C0",
                        weight="bold")
        else:
            self.logger.debug(
                "PNG: No selavy selected or selavy catalogue failed. (%s)",
                self.name
            )

        if self.forced_fits:
            collection, patches, island_names = self._gen_overlay_collection(
                cutout_row,
                f_source=self.measurements.iloc[index]
            )
            ax.add_collection(collection, autolim=False)
            del collection

        legend_elements = [
            Line2D(
                [0], [0], marker='c', color='C3', label=label,
                markerfacecolor='g', ls="none", markersize=8
            )
        ]

        if selavy:
            legend_elements.append(
                Line2D(
                    [0], [0], marker='o', color='C1',
                    label="Selavy {}".format(self.cat_type),
                    markerfacecolor='none', ls="none", markersize=10
                )
            )

        if crossmatch_overlay:
            legend_elements.append(
                Line2D(
                    [0], [0], marker='o', color='C4',
                    label="Crossmatch radius ({:.1f} arcsec)".format(
                        self.crossmatch_radius.arcsec
                    ),
                    markerfacecolor='none', ls="none",
                    markersize=10
                )
            )

        if self.forced_fits:
            legend_elements.append(
                Line2D(
                    [0], [0], marker='o', color='C3',
                    label="Forced Fit",
                    markerfacecolor='none', ls="none",
                    markersize=10
                )
            )

        ax.legend(handles=legend_elements)
        lon = ax.coords[0]
        lat = ax.coords[1]
        lon.set_axislabel("Right Ascension (J2000)")
        lat.set_axislabel("Declination (J2000)")

        if not no_colorbar:
            divider = make_axes_locatable(ax)
            cax = divider.append_axes(
                "right", size="3%", pad=0.1, axes_class=maxes.Axes)
            cb = fig.colorbar(im, cax=cax)
            cb.set_label("mJy/beam")

        if title is None:
            obs_time = self.measurements.iloc[index].dateobs
            title = "{} {}".format(
                self.name,
                obs_time.strftime(
                    "%Y-%m-%d %H:%M:%S"
                )
            )

        ax.set_title(title)

        if cutout_row.beam is not None and hide_beam is False:
            img_beam = cutout_row.beam
            if cutout_row.wcs.is_celestial:
                major = img_beam.major.value
                minor = img_beam.minor.value
                pa = img_beam.pa.value
                pix_scale = proj_plane_pixel_scales(
                    cutout_row.wcs
                )
                sx = pix_scale[0]
                sy = pix_scale[1]
                degrees_per_pixel = np.sqrt(sx * sy)
                minor /= degrees_per_pixel
                major /= degrees_per_pixel

                png_beam = AnchoredEllipse(
                    ax.transData, width=minor,
                    height=major, angle=pa, loc="lower right",
                    pad=0.5, borderpad=0.4,
                    frameon=False)
                png_beam.ellipse.set_edgecolor("k")
                png_beam.ellipse.set_facecolor("w")
                png_beam.ellipse.set_linewidth(1.5)

                ax.add_artist(png_beam)
        else:
            self.logger.debug("Hiding beam.")

        if offset_axes:
            axis_units = u.arcmin

            if size is None and cutout_row.wcs.is_celestial:
                pix_scale = proj_plane_pixel_scales(
                    cutout_row.wcs
                )
                sx = pix_scale[0]
                sy = pix_scale[1]
                xlims = ax.get_xlim()
                ylims = ax.get_ylim()

                xsize = sx * (xlims[1] - xlims[0])
                ysize = sy * (ylims[1] - ylims[0])
                size = max([xsize, ysize]) * u.deg

            if size is not None:
                if size < 2 * u.arcmin:
                    axis_units = u.arcsec
                elif size > 2 * u.deg:
                    axis_units = u.deg

            offset_postagestamp_axes(ax,
                                     self.coord,
                                     ra_units=axis_units,
                                     dec_units=axis_units
                                     )

        if save:
            plt.savefig(outfile, bbox_inches="tight", dpi=plot_dpi)
            self.logger.debug("Saved {}".format(outfile))

            plt.close(fig)
            return

        else:
            return fig

    def write_ann(
        self,
        index: int,
        outfile: str = None,
        crossmatch_overlay: bool = False,
        size: Optional[Angle] = None,
        force_cutout_fetch: bool = False,
        cutout_data: Optional[pd.DataFrame] = None
    ) -> None:
        """
        Write a kvis annotation file containing all selavy sources
        within the image.

        Args:
            index: The index correpsonding to the requested observation.
            outfile: Name of the file to write, defaults to None.
            crossmatch_overlay: If True, a circle is added to the
                annotation file output denoting the crossmatch radius,
                defaults to False.
            size: Size of the cutout, defaults to None.
            force_cutout_fetch: Whether to force the re-fetching
                of the cutout data, defaults to `False`
            cutout_data: Pass external cutout_data to be used
                instead of fetching the data, defaults to None.

        Returns:
            None
        """
        if (self._cutouts_got is False) or force_cutout_fetch:
            if cutout_data is None:
                self.get_cutout_data(size)

        if outfile is None:
            outfile = self._get_save_name(index, ".ann")
        if self.outdir != ".":
            outfile = os.path.join(
                self.outdir,
                outfile
            )

        neg = False
        with open(outfile, 'w') as f:
            f.write("COORD W\n")
            f.write("PA SKY\n")
            f.write("FONT hershey14\n")
            f.write("COLOR BLUE\n")
            f.write("CROSS {0} {1} {2} {2}\n".format(
                self.measurements.iloc[index].ra,
                self.measurements.iloc[index].dec,
                3. / 3600.
            ))
            if crossmatch_overlay:
                try:
                    f.write("CIRCLE {} {} {}\n".format(
                        self.measurements.iloc[index].ra,
                        self.measurements.iloc[index].dec,
                        self.crossmatch_radius.deg
                    ))
                except Exception as e:
                    self.logger.warning(
                        "Crossmatch circle overlay failed!"
                        " Has the source been crossmatched?")
            f.write("COLOR GREEN\n")

            if cutout_data is None:
                selavy_cat_cut = self.cutout_df.iloc[index].selavy_overlay
            else:
                selavy_cat_cut = cutout_data.iloc[index].selavy_overlay

            for i, row in selavy_cat_cut.iterrows():
                if row["island_id"].startswith("n"):
                    neg = True
                    f.write("COLOR RED\n")
                ra = row["ra_deg_cont"]
                dec = row["dec_deg_cont"]
                f.write(
                    "ELLIPSE {} {} {} {} {}\n".format(
                        ra,
                        dec,
                        float(
                            row["maj_axis"]) /
                        3600. /
                        2.,
                        float(
                            row["min_axis"]) /
                        3600. /
                        2.,
                        float(
                            row["pos_ang"])))
                f.write(
                    "TEXT {} {} {}\n".format(
                        ra, dec, self._remove_sbid(
                            row["island_id"])))
                if neg:
                    f.write("COLOR GREEN\n")
                    neg = False

        self.logger.debug("Wrote annotation file {}.".format(outfile))

    def write_reg(
        self,
        index: int,
        outfile: Optional[str] = None,
        crossmatch_overlay: bool = False,
        size: Optional[Angle] = None,
        force_cutout_fetch: bool = False,
        cutout_data: Optional[pd.DataFrame] = None
    ) -> None:
        """
        Write a DS9 region file containing all selavy sources within the image

        Args:
            index: The index correpsonding to the requested observation.
            outfile: Name of the file to write, defaults to None.
            crossmatch_overlay: If True, a circle is added to the
                annotation file output denoting the crossmatch radius,
                defaults to False.
            size: Size of the cutout, defaults to None.
            force_cutout_fetch: Whether to force the re-fetching
                of the cutout data, defaults to `False`.
            cutout_data: Pass external cutout_data to be used
                instead of fetching the data, defaults to None.

        Returns:
            None
        """
        if (self._cutouts_got is False) or force_cutout_fetch:
            if cutout_data is None:
                self.get_cutout_data(size)

        if outfile is None:
            outfile = self._get_save_name(index, ".reg")
        if self.outdir != ".":
            outfile = os.path.join(
                self.outdir,
                outfile
            )

        with open(outfile, 'w') as f:
            f.write("# Region file format: DS9 version 4.0\n")
            f.write("global color=green font=\"helvetica 10 normal\" "
                    "select=1 highlite=1 edit=1 "
                    "move=1 delete=1 include=1 "
                    "fixed=0 source=1\n")
            f.write("fk5\n")
            f.write(
                "point({} {}) # point=x color=blue\n".format(
                    self.measurements.iloc[index].ra,
                    self.measurements.iloc[index].dec,
                ))
            if crossmatch_overlay:
                try:
                    f.write("circle({} {} {}) # color=blue\n".format(
                        self.measurements.iloc[index].ra,
                        self.measurements.iloc[index].dec,
                        self.crossmatch_radius.deg
                    ))
                except Exception as e:
                    self.logger.warning(
                        "Crossmatch circle overlay failed!"
                        " Has the source been crossmatched?")

            if cutout_data is None:
                selavy_cat_cut = self.cutout_df.iloc[index].selavy_overlay
            else:
                selavy_cat_cut = cutout_data.iloc[index].selavy_overlay

            for i, row in selavy_cat_cut.iterrows():
                if row["island_id"].startswith("n"):
                    color = "red"
                else:
                    color = "green"
                ra = row["ra_deg_cont"]
                dec = row["dec_deg_cont"]
                f.write(
                    "ellipse({} {} {} {} {}) # color={}\n".format(
                        ra,
                        dec,
                        float(
                            row["maj_axis"]) /
                        3600. /
                        2.,
                        float(
                            row["min_axis"]) /
                        3600. /
                        2.,
                        float(
                            row["pos_ang"]) +
                        90.,
                        color))
                f.write(
                    "text({} {} \"{}\") # color={}\n".format(
                        ra - (10. / 3600.), dec, self._remove_sbid(
                            row["island_id"]), color))

        self.logger.debug("Wrote region file {}.".format(outfile))

    def _remove_sbid(self, island: str) -> str:
        """Removes the SBID component of the island name.

        Takes into account negative 'n' label for negative sources.

        Args:
            island: island name.

        Returns:
            Truncated island name.
        """

        temp = island.split("_")
        new_val = "_".join(temp[-2:])
        if temp[0].startswith("n"):
            new_val = "n" + new_val
        return new_val

    def _create_crosshair_lines(
        self,
        target: np.ndarray,
        pixel_buff: float,
        length: float,
        img_size: Tuple[int, int]
    ) -> List[List[float]]:
        """
        Takes the target pixel coordinates and creates the plots
        that are required to plot a 'crosshair' marker.

        To keep the crosshair consistent between scales, the values are
        provided as percentages of the image size.

        Args:
            target: The target in pixel coordinates.
            pixel_buff: Percentage of image size that is the buffer
                of the crosshair, i.e. the distance between the target and
                beginning of the line.
            length: Size of the line of the crosshair, again as a
                percentage of the image size.
            img_size: Tuple size of the image array.

        Returns:
            List of pairs of pixel coordinates to plot using scatter.
        """
        x = target[0][0]
        y = target[0][1]

        min_size = np.min(img_size)

        pixel_buff = int(min_size * pixel_buff)
        length = int(min_size * length)

        plots = []

        plots.append([[x, x], [y + pixel_buff, y + pixel_buff + length]])
        plots.append([[x, x], [y - pixel_buff, y - pixel_buff - length]])
        plots.append([[x + pixel_buff, x + pixel_buff + length], [y, y]])
        plots.append([[x - pixel_buff, x - pixel_buff - length], [y, y]])

        return plots

    def simbad_search(
        self, radius: Angle = Angle(20. * u.arcsec)
    ) -> Union[None, Table]:
        """
        Searches SIMBAD for object coordinates and returns matches.

        Args:
            radius: Radius to search, defaults to Angle(20. * u.arcsec)

        Returns:
            Table of matches or None if no matches

        Raises:
            ValueError: Error in performing the SIMBAD region search.
        """
        Simbad.add_votable_fields('ra(d)', 'dec(d)')

        try:
            result_table = Simbad.query_region(self.coord, radius=radius)
            if result_table is None:
                return None

            return result_table

        except Exception as e:
            raise ValueError(
                "Error in performing the SIMBAD region search! Error: %s", e
            )
            return None

    def ned_search(
        self, radius: Angle = Angle(20. * u.arcsec)
    ) -> Union[None, Table]:
        """
        Searches NED for object coordinates and returns matches.

        Args:
            radius: Radius to search, defaults to Angle(20. * u.arcsec).

        Returns:
            Table of matches or None if no matches

        Raises:
            ValueError: Error in performing the NED region search.
        """
        try:
            result_table = Ned.query_region(self.coord, radius=radius)

            return result_table

        except Exception as e:
            raise ValueError(
                "Error in performing the NED region search! Error: %s", e
            )
            return None

    def casda_search(
        self,
        radius: Angle = Angle(20. * u.arcsec),
        filter_out_unreleased: bool = False,
        show_all: bool = False
    ) -> Union[None, Table]:
        """
        Searches CASDA for object coordinates and returns matches.

        Args:
            radius: Radius to search, defaults to Angle(20. * u.arcsec).
            filter_out_unreleased: Remove unreleased data,
                defaults to `False`.
            show_all: Show all available data, defaults to `False`.

        Returns:
            Table of matches or None if no matches

        Raises:
            ValueError: Error in performing the CASDA region search.
        """
        try:
            result_table = Casda.query_region(self.coord, radius=radius)

            if filter_out_unreleased:
                result_table = Casda.filter_out_unreleased(result_table)
            if not show_all:
                mask = result_table[
                    'dataproduct_subtype'
                ] == 'cont.restored.t0'
                result_table = result_table[mask]
                mask = [(
                    ("image.i" in i) & ("taylor.0.res" in i)
                ) for i in result_table[
                    'filename'
                ]]
                result_table = result_table[mask]

            return result_table

        except Exception as e:
            raise ValueError(
                "Error in performing the CASDA region search! Error: %s", e
            )
            return None

    def _get_fluxes_and_errors(
        self,
        suffix: str,
        forced_fits: bool
    ) -> Tuple[pd.Series, pd.Series]:
        """
        Selects the correct fluxes, upper limits or forced fits
        to calculate the metrics

        Args:
            suffix: 'peak' or 'int'.
            forced_fits: Set to `True` if forced fits should be used.

        Returns:
            The fluxes and errors to use.
        """
        if self.pipeline:
            non_detect_label = 'flux_{}'.format(suffix)
            non_detect_label_err = 'flux_{}_err'.format(suffix)
            scale = 1.
            detection_label = 'forced'
            detection_value = False
        else:
            detection_label = 'detection'
            detection_value = True
            if forced_fits:
                non_detect_label = 'f_flux_{}'.format(suffix)
                non_detect_label_err = 'f_flux_{}_err'.format(suffix)
                scale = 1.
            else:
                scale = 5.
                non_detect_label = 'rms_image'
                non_detect_label_err = 'rms_image'

        detect_mask = self.measurements[detection_label] == detection_value

        detect_fluxes = (
            self.measurements[detect_mask]['flux_{}'.format(suffix)]
        )
        detect_errors = (
            self.measurements[detect_mask]['flux_{}_err'.format(
                suffix
            )]
        )

        non_detect_fluxes = (
            self.measurements[~detect_mask][non_detect_label] * scale
        )
        non_detect_errors = (
            self.measurements[~detect_mask][non_detect_label_err]
        )

        fluxes = pd.concat([detect_fluxes, non_detect_fluxes])
        errors = pd.concat([detect_errors, non_detect_errors])

        return fluxes, errors

    def calc_eta_metric(
        self,
        use_int: bool = False,
        forced_fits: bool = False
    ) -> float:
        """
        Calculate the eta variability metric

        Args:
            use_int: Calculate using integrated (rather than peak) flux,
                defaults to `False`
            forced_fits: Use forced fits, defaults to `False`

        Returns:
            Eta variability metric.

        Raises:
            Exception: No forced fits are present when forced fits have been
                selected.
        """
        if self.measurements.shape[0] == 1:
            return 0.

        suffix = 'int' if use_int else 'peak'

        if forced_fits and not self.forced_fits:
            raise Exception(
                "Forced fits selected but no forced fits are present!"
            )

        fluxes, errors = self._get_fluxes_and_errors(suffix, forced_fits)
        n_src = fluxes.shape[0]

        weights = 1. / errors**2
        eta = (n_src / (n_src - 1)) * (
            (weights * fluxes**2).mean() - (
                (weights * fluxes).mean()**2 / weights.mean()
            )
        )

        return eta

    def calc_v_metric(
        self,
        use_int: bool = False,
        forced_fits: bool = False
    ) -> float:
        """
        Calculate the V variability metric.

        Args:
            use_int: Calculate using integrated (rather than peak) flux,
                defaults to `False`.
            forced_fits: Use forced fits, defaults to `False`.

        Returns:
            V variability metric.

        Raises:
            Exception: No forced fits are present when forced fits have been
                selected.
        """
        if self.measurements.shape[0] == 1:
            return 0.

        suffix = 'int' if use_int else 'peak'

        if forced_fits and not self.forced_fits:
            raise Exception(
                "Forced fits selected but no forced fits are present!"
            )

        fluxes, _ = self._get_fluxes_and_errors(suffix, forced_fits)
        v = fluxes.std() / fluxes.mean()

        return v

    def calc_eta_and_v_metrics(
        self,
        use_int: bool = False,
        forced_fits: bool = False
    ) -> Tuple[float, float]:
        """
        Calculate both variability metrics

        Args:
            use_int: Calculate using integrated (rather than peak) flux,
                defaults to `False`.
            forced_fits: Use forced fits, defaults to `False`.

        Returns:
            Variability metrics eta and v.
        """

        eta = self.calc_eta_metric(use_int=use_int, forced_fits=forced_fits)
        v = self.calc_v_metric(use_int=use_int, forced_fits=forced_fits)

        return eta, v

__init__(coord, name, epochs, fields, stokes, primary_field, crossmatch_radius, measurements, base_folder, image_type='COMBINED', islands=False, outdir='.', planet=False, pipeline=False, tiles=False, corrected_data=False, post_processed_data=True, forced_fits=False)

Constructor method

Parameters:

Name Type Description Default
coord SkyCoord

Source coordinates.

required
name Union[str, int]

The name of the source. Will be converted to a string.

required
epochs List[str]

The epochs that the source contains.

required
fields List[str]

The fields that the source contains.

required
stokes str

The stokes parameter of the source.

required
primary_field str

The primary VAST Pilot field of the source.

required
crossmatch_radius Angle

The crossmatch radius used to find the measurements.

required
measurements DataFrame

DataFrame containing the measurements.

required
base_folder str

Path to base folder in default directory structure

required
image_type str

The string representation of the image type, either 'COMBINED' or 'TILES', defaults to "COMBINED".

'COMBINED'
islands bool

Is True if islands has been used instead of components, defaults to False.

False
outdir str

The directory where any media outputs will be written to, defaults to ".".

'.'
planet bool

Set to True if the source is a planet, defaults to False.

False
pipeline bool

Set to True if the source has been loaded from a VAST Pipeline run, defaults to False.

False
tiles bool

Set to 'Trueif the source is from a tile images, defaults toFalse`.

False
corrected_data bool

Access the corrected data. Only relevant if tiles is True. Defaults to True.

False
forced_fits bool

Set to True if forced fits are included in the source measurements, defaults to False.

False

Returns:

Type Description
None

None

Source code in vasttools/source.py
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
def __init__(
    self,
    coord: SkyCoord,
    name: Union[str, int],
    epochs: List[str],
    fields: List[str],
    stokes: str,
    primary_field: str,
    crossmatch_radius: Angle,
    measurements: pd.DataFrame,
    base_folder: str,
    image_type: str = "COMBINED",
    islands: bool = False,
    outdir: str = ".",
    planet: bool = False,
    pipeline: bool = False,
    tiles: bool = False,
    corrected_data: bool = False,
    post_processed_data: bool = True,
    forced_fits: bool = False,
) -> None:
    """
    Constructor method

    Args:
        coord: Source coordinates.
        name: The name of the source. Will be converted to a string.
        epochs: The epochs that the source contains.
        fields: The fields that the source contains.
        stokes: The stokes parameter of the source.
        primary_field: The primary VAST Pilot field of the source.
        crossmatch_radius: The crossmatch radius used to find the
            measurements.
        measurements: DataFrame containing the measurements.
        base_folder: Path to base folder in default directory structure
        image_type: The string representation of the image type,
            either 'COMBINED' or 'TILES', defaults to "COMBINED".
        islands: Is `True` if islands has been used instead of
            components, defaults to `False`.
        outdir: The directory where any media outputs will be written
            to, defaults to ".".
        planet: Set to `True` if the source is a planet, defaults
            to `False`.
        pipeline: Set to `True` if the source has been loaded from a
            VAST Pipeline run, defaults to `False`.
        tiles: Set to 'True` if the source is from a tile images,
            defaults to `False`.
        corrected_data: Access the corrected data. Only relevant if
            `tiles` is `True`. Defaults to `True`.
        forced_fits: Set to `True` if forced fits are included in the
            source measurements, defaults to `False`.

    Returns:
        None
    """
    self.logger = logging.getLogger(f'vasttools.source.Source[{name}]')
    self.logger.debug('Created Source instance')
    self.pipeline = pipeline
    self.coord = coord
    self.name = str(name)
    self.epochs = epochs
    self.fields = fields
    self.stokes = stokes
    self.primary_field = primary_field
    self.crossmatch_radius = crossmatch_radius
    self.measurements = measurements.infer_objects()
    self.measurements.dateobs = pd.to_datetime(
        self.measurements.dateobs
    )
    self.islands = islands
    if self.islands:
        self.cat_type = 'islands'
    else:
        self.cat_type = 'components'

    self.outdir = outdir

    self.base_folder = base_folder
    self.image_type = image_type
    if image_type == 'TILES':
        self.tiles = True
    else:
        self.tiles = False

    self.corrected_data = corrected_data
    self.post_processed_data = post_processed_data
    if self.pipeline:
        self.detections = self.measurements[
            self.measurements.forced == False
        ].shape[0]

        self.forced = self.measurements[
            self.measurements.forced == False
        ].shape[0]

        self.limits = None
        self.forced_fits = False
    else:
        self.detections = self.measurements[
            self.measurements.detection
        ].shape[0]

        self.limits = self.measurements[
            self.measurements.detection == False
        ].shape[0]

        self.forced = None
        self.forced_fits = forced_fits

    self._cutouts_got = False

    self.planet = planet

calc_eta_and_v_metrics(use_int=False, forced_fits=False)

Calculate both variability metrics

Parameters:

Name Type Description Default
use_int bool

Calculate using integrated (rather than peak) flux, defaults to False.

False
forced_fits bool

Use forced fits, defaults to False.

False

Returns:

Type Description
Tuple[float, float]

Variability metrics eta and v.

Source code in vasttools/source.py
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
def calc_eta_and_v_metrics(
    self,
    use_int: bool = False,
    forced_fits: bool = False
) -> Tuple[float, float]:
    """
    Calculate both variability metrics

    Args:
        use_int: Calculate using integrated (rather than peak) flux,
            defaults to `False`.
        forced_fits: Use forced fits, defaults to `False`.

    Returns:
        Variability metrics eta and v.
    """

    eta = self.calc_eta_metric(use_int=use_int, forced_fits=forced_fits)
    v = self.calc_v_metric(use_int=use_int, forced_fits=forced_fits)

    return eta, v

calc_eta_metric(use_int=False, forced_fits=False)

Calculate the eta variability metric

Parameters:

Name Type Description Default
use_int bool

Calculate using integrated (rather than peak) flux, defaults to False

False
forced_fits bool

Use forced fits, defaults to False

False

Returns:

Type Description
float

Eta variability metric.

Raises:

Type Description
Exception

No forced fits are present when forced fits have been selected.

Source code in vasttools/source.py
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
def calc_eta_metric(
    self,
    use_int: bool = False,
    forced_fits: bool = False
) -> float:
    """
    Calculate the eta variability metric

    Args:
        use_int: Calculate using integrated (rather than peak) flux,
            defaults to `False`
        forced_fits: Use forced fits, defaults to `False`

    Returns:
        Eta variability metric.

    Raises:
        Exception: No forced fits are present when forced fits have been
            selected.
    """
    if self.measurements.shape[0] == 1:
        return 0.

    suffix = 'int' if use_int else 'peak'

    if forced_fits and not self.forced_fits:
        raise Exception(
            "Forced fits selected but no forced fits are present!"
        )

    fluxes, errors = self._get_fluxes_and_errors(suffix, forced_fits)
    n_src = fluxes.shape[0]

    weights = 1. / errors**2
    eta = (n_src / (n_src - 1)) * (
        (weights * fluxes**2).mean() - (
            (weights * fluxes).mean()**2 / weights.mean()
        )
    )

    return eta

calc_v_metric(use_int=False, forced_fits=False)

Calculate the V variability metric.

Parameters:

Name Type Description Default
use_int bool

Calculate using integrated (rather than peak) flux, defaults to False.

False
forced_fits bool

Use forced fits, defaults to False.

False

Returns:

Type Description
float

V variability metric.

Raises:

Type Description
Exception

No forced fits are present when forced fits have been selected.

Source code in vasttools/source.py
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
def calc_v_metric(
    self,
    use_int: bool = False,
    forced_fits: bool = False
) -> float:
    """
    Calculate the V variability metric.

    Args:
        use_int: Calculate using integrated (rather than peak) flux,
            defaults to `False`.
        forced_fits: Use forced fits, defaults to `False`.

    Returns:
        V variability metric.

    Raises:
        Exception: No forced fits are present when forced fits have been
            selected.
    """
    if self.measurements.shape[0] == 1:
        return 0.

    suffix = 'int' if use_int else 'peak'

    if forced_fits and not self.forced_fits:
        raise Exception(
            "Forced fits selected but no forced fits are present!"
        )

    fluxes, _ = self._get_fluxes_and_errors(suffix, forced_fits)
    v = fluxes.std() / fluxes.mean()

    return v

Searches CASDA for object coordinates and returns matches.

Parameters:

Name Type Description Default
radius Angle

Radius to search, defaults to Angle(20. * u.arcsec).

Angle(20.0 * arcsec)
filter_out_unreleased bool

Remove unreleased data, defaults to False.

False
show_all bool

Show all available data, defaults to False.

False

Returns:

Type Description
Union[None, Table]

Table of matches or None if no matches

Raises:

Type Description
ValueError

Error in performing the CASDA region search.

Source code in vasttools/source.py
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
def casda_search(
    self,
    radius: Angle = Angle(20. * u.arcsec),
    filter_out_unreleased: bool = False,
    show_all: bool = False
) -> Union[None, Table]:
    """
    Searches CASDA for object coordinates and returns matches.

    Args:
        radius: Radius to search, defaults to Angle(20. * u.arcsec).
        filter_out_unreleased: Remove unreleased data,
            defaults to `False`.
        show_all: Show all available data, defaults to `False`.

    Returns:
        Table of matches or None if no matches

    Raises:
        ValueError: Error in performing the CASDA region search.
    """
    try:
        result_table = Casda.query_region(self.coord, radius=radius)

        if filter_out_unreleased:
            result_table = Casda.filter_out_unreleased(result_table)
        if not show_all:
            mask = result_table[
                'dataproduct_subtype'
            ] == 'cont.restored.t0'
            result_table = result_table[mask]
            mask = [(
                ("image.i" in i) & ("taylor.0.res" in i)
            ) for i in result_table[
                'filename'
            ]]
            result_table = result_table[mask]

        return result_table

    except Exception as e:
        raise ValueError(
            "Error in performing the CASDA region search! Error: %s", e
        )
        return None

get_cutout_data(size=None)

Function to fetch the cutout data for that source required for producing all the media output.

If size is not provided then the default size of 5 arcmin will be used.

Parameters:

Name Type Description Default
size Optional[Angle]

The angular size of the cutouts, defaults to None.

None

Returns:

Type Description
None

None

Source code in vasttools/source.py
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
def get_cutout_data(self, size: Optional[Angle] = None) -> None:
    """
    Function to fetch the cutout data for that source
    required for producing all the media output.

    If size is not provided then the default size of 5 arcmin will be
    used.

    Args:
        size: The angular size of the cutouts, defaults to None.

    Returns:
        None
    """
    if size is None:
        args = None
    else:
        args = (size,)

    self.cutout_df = self.measurements.apply(
        self._get_cutout,
        args=args,
        axis=1,
        result_type='expand'
    ).rename(columns={
        0: "data",
        1: "wcs",
        2: "header",
        3: "selavy_overlay",
        4: "beam"
    })
    self._cutouts_got = True

make_png(index, selavy=True, percentile=99.9, zscale=False, contrast=0.2, outfile=None, no_islands=True, label='Source', no_colorbar=False, title=None, crossmatch_overlay=False, hide_beam=False, save=False, size=None, force_cutout_fetch=False, disable_autoscaling=False, cutout_data=None, norms=None, plot_dpi=150, offset_axes=True)

Save a PNG of the image postagestamp.

Parameters:

Name Type Description Default
index int

The index correpsonding to the requested observation.

required
selavy bool

True to overlay selavy components, False otherwise.

True
percentile float

The value passed to the percentile normalization function, defaults to 99.9.

99.9
zscale bool

Uses ZScale normalization instead of PercentileInterval, defaults to False.

False
contrast float

Contrast value passed to the ZScaleInterval function when zscale is selected, defaults to 0.2.

0.2
outfile Optional[str]

Name to give the file, if None then the name is automatically generated, defaults to None.

None
no_islands bool

Disable island lables on the png, defaults to False.

True
label str

Figure title (usually the name of the source of interest), defaults to "Source".

'Source'
no_colorbar bool

If True, do not show the colorbar on the png, defaults to False.

False
title Optional[str]

String to set as title, defaults to None where a default title will be used.

None
crossmatch_overlay bool

If 'True' then a circle is added to the png plot representing the crossmatch radius, defaults to False.

False
hide_beam bool

If 'True' then the beam is not plotted onto the png plot, defaults to False.

False
save bool

If True the plot is saved rather than the figure being returned, defaults to False.

False
size Optional[Angle]

Size of the cutout, defaults to None.

None
force_cutout_fetch bool

Whether to force the re-fetching of the cutout data, defaults to False.

False
disable_autoscaling bool

Turn off the consistent normalization and calculate the normalizations separately for each observation, defaults to False.

False
cutout_data Optional[DataFrame]

Pass external cutout_data to be used instead of fetching the data, defaults to None.

None
norms Optional[ImageNormalize]

Pass external normalization to be used instead of internal calculations.

None
plot_dpi int

Specify the DPI of saved figures, defaults to 150.

150
offset_axes bool

Use offset, rather than absolute, axis labels.

True

Returns:

Type Description
Union[None, Figure]

None if save is True or the figure object if False

Raises:

Type Description
ValueError

If the index is out of range.

Source code in vasttools/source.py
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
2098
2099
2100
2101
2102
2103
2104
2105
def make_png(
    self,
    index: int,
    selavy: bool = True,
    percentile: float = 99.9,
    zscale: bool = False,
    contrast: float = 0.2,
    outfile: Optional[str] = None,
    no_islands: bool = True,
    label: str = "Source",
    no_colorbar: bool = False,
    title: Optional[str] = None,
    crossmatch_overlay: bool = False,
    hide_beam: bool = False,
    save: bool = False,
    size: Optional[Angle] = None,
    force_cutout_fetch: bool = False,
    disable_autoscaling: bool = False,
    cutout_data: Optional[pd.DataFrame] = None,
    norms: Optional[ImageNormalize] = None,
    plot_dpi: int = 150,
    offset_axes: bool = True
) -> Union[None, matplotlib.figure.Figure]:
    """
    Save a PNG of the image postagestamp.

    Args:
        index: The index correpsonding to the requested observation.
        selavy: `True` to overlay selavy components, `False` otherwise.
        percentile: The value passed to the percentile
            normalization function, defaults to 99.9.
        zscale: Uses ZScale normalization instead of
            PercentileInterval, defaults to `False`.
        contrast: Contrast value passed to the ZScaleInterval
            function when zscale is selected, defaults to 0.2.
        outfile: Name to give the file, if None then the name is
            automatically generated, defaults to None.
        no_islands: Disable island lables on the png, defaults to
            `False`.
        label: Figure title (usually the name of the source of
            interest), defaults to "Source".
        no_colorbar: If `True`, do not show the colorbar on the png,
            defaults to `False`.
        title: String to set as title,
            defaults to None where a default title will be used.
        crossmatch_overlay: If 'True' then a circle is added to the png
            plot representing the crossmatch radius, defaults to `False`.
        hide_beam: If 'True' then the beam is not plotted onto the png
            plot, defaults to `False`.
        save: If `True` the plot is saved rather than the figure being
            returned, defaults to `False`.
        size: Size of the cutout, defaults to None.
        force_cutout_fetch: Whether to force the re-fetching of the cutout
            data, defaults to `False`.
        disable_autoscaling: Turn off the consistent normalization and
            calculate the normalizations separately for each observation,
            defaults to `False`.
        cutout_data: Pass external cutout_data to be used
            instead of fetching the data, defaults to None.
        norms: Pass external normalization to be used
            instead of internal calculations.
        plot_dpi: Specify the DPI of saved figures, defaults to 150.
        offset_axes: Use offset, rather than absolute, axis labels.

    Returns:
        None if save is `True` or the figure object if `False`

    Raises:
        ValueError: If the index is out of range.
    """

    if (self._cutouts_got is False) or force_cutout_fetch:
        if cutout_data is None:
            self.get_cutout_data(size)

    if index > len(self.measurements):
        raise ValueError(f"Cannot access {index}th measurement.")

    if outfile is None:
        outfile = self._get_save_name(index, ".png")

    if self.outdir != ".":
        outfile = os.path.join(
            self.outdir,
            outfile
        )

    if cutout_data is None:
        cutout_row = self.cutout_df.iloc[index]
    else:
        cutout_row = cutout_data.iloc[index]

    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_subplot(111, projection=cutout_row.wcs)
    # Get the Image Normalisation from zscale, user contrast.
    if not disable_autoscaling:
        if norms is not None:
            img_norms = norms
        else:
            img_norms = self._analyse_norm_level(
                percentile=percentile,
                zscale=zscale,
                z_contrast=contrast
            )
    else:
        if zscale:
            img_norms = ImageNormalize(
                cutout_row.data * 1.e3,
                interval=ZScaleInterval(
                    contrast=contrast
                ))
        else:
            img_norms = ImageNormalize(
                cutout_row.data * 1.e3,
                interval=PercentileInterval(percentile),
                stretch=LinearStretch())

    im = ax.imshow(
        cutout_row.data * 1.e3,
        norm=img_norms,
        cmap="gray_r"
    )

    # insert crosshair of target
    target_coords = np.array(
        ([[
            self.measurements.iloc[index].ra,
            self.measurements.iloc[index].dec
        ]])
    )

    target_coords = cutout_row.wcs.wcs_world2pix(
        target_coords, 0
    )

    crosshair_lines = self._create_crosshair_lines(
        target_coords,
        0.03,
        0.03,
        cutout_row.data.shape
    )

    [ax.plot(
        l[0], l[1], color="C3", zorder=10, lw=1.5, alpha=0.6
    ) for l in crosshair_lines]
    # the commented lines below are to use the crosshair
    # marker directly.
    # ax.scatter(
    #     [self.src_coord.ra.deg], [self.src_coord.dec.deg],
    #     transform=ax.get_transform('world'), marker="c",
    #     color="C3", zorder=10, label=label, s=1000, lw=1.5,
    #     alpha=0.5
    # )
    if crossmatch_overlay:
        try:
            crossmatch_patch = SphericalCircle(
                (
                    self.measurements.iloc[index].skycoord.ra,
                    self.measurements.iloc[index].skycoord.dec
                ),
                self.crossmatch_radius,
                transform=ax.get_transform('world'),
                label="Crossmatch radius ({:.1f} arcsec)".format(
                    self.crossmatch_radius.arcsec
                ), edgecolor='C4', facecolor='none', alpha=0.8)
            ax.add_patch(crossmatch_patch)
        except Exception as e:
            self.logger.warning(
                "Crossmatch circle png overlay failed!"
                " Has the source been crossmatched?")
            crossmatch_overlay = False

    if (not cutout_row['selavy_overlay'].empty) and selavy:
        ax.set_autoscale_on(False)
        collection, patches, island_names = self._gen_overlay_collection(
            cutout_row
        )
        ax.add_collection(collection, autolim=False)
        del collection

        # Add island labels, haven't found a better way other than looping
        # at the moment.
        if not no_islands and not self.islands:
            for i, val in enumerate(patches):
                ax.annotate(
                    island_names[i],
                    val.center,
                    annotation_clip=True,
                    color="C0",
                    weight="bold")
    else:
        self.logger.debug(
            "PNG: No selavy selected or selavy catalogue failed. (%s)",
            self.name
        )

    if self.forced_fits:
        collection, patches, island_names = self._gen_overlay_collection(
            cutout_row,
            f_source=self.measurements.iloc[index]
        )
        ax.add_collection(collection, autolim=False)
        del collection

    legend_elements = [
        Line2D(
            [0], [0], marker='c', color='C3', label=label,
            markerfacecolor='g', ls="none", markersize=8
        )
    ]

    if selavy:
        legend_elements.append(
            Line2D(
                [0], [0], marker='o', color='C1',
                label="Selavy {}".format(self.cat_type),
                markerfacecolor='none', ls="none", markersize=10
            )
        )

    if crossmatch_overlay:
        legend_elements.append(
            Line2D(
                [0], [0], marker='o', color='C4',
                label="Crossmatch radius ({:.1f} arcsec)".format(
                    self.crossmatch_radius.arcsec
                ),
                markerfacecolor='none', ls="none",
                markersize=10
            )
        )

    if self.forced_fits:
        legend_elements.append(
            Line2D(
                [0], [0], marker='o', color='C3',
                label="Forced Fit",
                markerfacecolor='none', ls="none",
                markersize=10
            )
        )

    ax.legend(handles=legend_elements)
    lon = ax.coords[0]
    lat = ax.coords[1]
    lon.set_axislabel("Right Ascension (J2000)")
    lat.set_axislabel("Declination (J2000)")

    if not no_colorbar:
        divider = make_axes_locatable(ax)
        cax = divider.append_axes(
            "right", size="3%", pad=0.1, axes_class=maxes.Axes)
        cb = fig.colorbar(im, cax=cax)
        cb.set_label("mJy/beam")

    if title is None:
        obs_time = self.measurements.iloc[index].dateobs
        title = "{} {}".format(
            self.name,
            obs_time.strftime(
                "%Y-%m-%d %H:%M:%S"
            )
        )

    ax.set_title(title)

    if cutout_row.beam is not None and hide_beam is False:
        img_beam = cutout_row.beam
        if cutout_row.wcs.is_celestial:
            major = img_beam.major.value
            minor = img_beam.minor.value
            pa = img_beam.pa.value
            pix_scale = proj_plane_pixel_scales(
                cutout_row.wcs
            )
            sx = pix_scale[0]
            sy = pix_scale[1]
            degrees_per_pixel = np.sqrt(sx * sy)
            minor /= degrees_per_pixel
            major /= degrees_per_pixel

            png_beam = AnchoredEllipse(
                ax.transData, width=minor,
                height=major, angle=pa, loc="lower right",
                pad=0.5, borderpad=0.4,
                frameon=False)
            png_beam.ellipse.set_edgecolor("k")
            png_beam.ellipse.set_facecolor("w")
            png_beam.ellipse.set_linewidth(1.5)

            ax.add_artist(png_beam)
    else:
        self.logger.debug("Hiding beam.")

    if offset_axes:
        axis_units = u.arcmin

        if size is None and cutout_row.wcs.is_celestial:
            pix_scale = proj_plane_pixel_scales(
                cutout_row.wcs
            )
            sx = pix_scale[0]
            sy = pix_scale[1]
            xlims = ax.get_xlim()
            ylims = ax.get_ylim()

            xsize = sx * (xlims[1] - xlims[0])
            ysize = sy * (ylims[1] - ylims[0])
            size = max([xsize, ysize]) * u.deg

        if size is not None:
            if size < 2 * u.arcmin:
                axis_units = u.arcsec
            elif size > 2 * u.deg:
                axis_units = u.deg

        offset_postagestamp_axes(ax,
                                 self.coord,
                                 ra_units=axis_units,
                                 dec_units=axis_units
                                 )

    if save:
        plt.savefig(outfile, bbox_inches="tight", dpi=plot_dpi)
        self.logger.debug("Saved {}".format(outfile))

        plt.close(fig)
        return

    else:
        return fig

Searches NED for object coordinates and returns matches.

Parameters:

Name Type Description Default
radius Angle

Radius to search, defaults to Angle(20. * u.arcsec).

Angle(20.0 * arcsec)

Returns:

Type Description
Union[None, Table]

Table of matches or None if no matches

Raises:

Type Description
ValueError

Error in performing the NED region search.

Source code in vasttools/source.py
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
def ned_search(
    self, radius: Angle = Angle(20. * u.arcsec)
) -> Union[None, Table]:
    """
    Searches NED for object coordinates and returns matches.

    Args:
        radius: Radius to search, defaults to Angle(20. * u.arcsec).

    Returns:
        Table of matches or None if no matches

    Raises:
        ValueError: Error in performing the NED region search.
    """
    try:
        result_table = Ned.query_region(self.coord, radius=radius)

        return result_table

    except Exception as e:
        raise ValueError(
            "Error in performing the NED region search! Error: %s", e
        )
        return None

plot_lightcurve(sigma_thresh=5, figsize=(8, 4), min_points=2, min_detections=0, mjd=False, start_date=None, grid=False, yaxis_start='0', peak_flux=True, save=False, outfile=None, use_forced_for_limits=False, use_forced_for_all=False, hide_legend=False, plot_dpi=150)

Plot source lightcurves and save to file

Parameters:

Name Type Description Default
sigma_thresh int

Threshold to use for upper limits, defaults to 5.

5
figsize Tuple[int, int]

Figure size, defaults to (8, 4).

(8, 4)
min_points int

Minimum number of points for plotting, defaults to 2.

2
min_detections int

Minimum number of detections for plotting, defaults to 0.

0
mjd bool

Plot x-axis in MJD rather than datetime, defaults to False.

False
start_date Optional[Timestamp]

Plot in days from start date, defaults to None.

None
grid bool

Turn on matplotlib grid, defaults to False.

False
yaxis_start str

Define where the y-axis begins from, either 'auto' or '0', defaults to "0".

'0'
peak_flux bool

Uses peak flux instead of integrated flux, defaults to True.

True
save bool

When True the plot is saved rather than displayed, defaults to False.

False
outfile Optional[str]

The filename to save when using, defaults to None which will use '_lc.png'.

None
use_forced_for_limits bool

Use the forced extractions instead of upper limits for non-detections., defaults to False.

False
use_forced_for_all bool

Use the forced fits for all the datapoints, defaults to False.

False
hide_legend bool

Hide the legend, defaults to False.

False
plot_dpi int

Specify the DPI of saved figures, defaults to 150.

150

Returns:

Type Description
Union[None, Figure]

None if save is True or the matplotlib figure if save is False.

Raises:

Type Description
SourcePlottingError

Source does not have any forced fits when the 'use_forced_for_all' or 'use_forced_for_limits' options have been selected.

SourcePlottingError

Number of detections lower than the minimum required.

SourcePlottingError

Number of datapoints lower than the minimum required.

SourcePlottingError

If measurements dataframe is empty.

Source code in vasttools/source.py
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
def plot_lightcurve(
    self,
    sigma_thresh: int = 5,
    figsize: Tuple[int, int] = (8, 4),
    min_points: int = 2,
    min_detections: int = 0,
    mjd: bool = False,
    # TODO: Is this a pd.Timestamp or a datetime?
    start_date: Optional[pd.Timestamp] = None,
    grid: bool = False,
    yaxis_start: str = "0",
    peak_flux: bool = True,
    save: bool = False,
    outfile: Optional[str] = None,
    use_forced_for_limits: bool = False,
    use_forced_for_all: bool = False,
    hide_legend: bool = False,
    plot_dpi: int = 150
) -> Union[None, matplotlib.figure.Figure]:
    """
    Plot source lightcurves and save to file

    Args:
        sigma_thresh: Threshold to use for upper limits, defaults to 5.
        figsize: Figure size, defaults to (8, 4).
        min_points: Minimum number of points for plotting, defaults
            to 2.
        min_detections:  Minimum number of detections for plotting,
            defaults to 0.
        mjd: Plot x-axis in MJD rather than datetime, defaults to False.
        start_date: Plot in days from start date, defaults to None.
        grid: Turn on matplotlib grid, defaults to False.
        yaxis_start: Define where the y-axis begins from, either 'auto'
            or '0', defaults to "0".
        peak_flux: Uses peak flux instead of integrated flux,
            defaults to `True`.
        save: When `True` the plot is saved rather than displayed,
            defaults to `False`.
        outfile: The filename to save when using, defaults to None which
            will use '<souce_name>_lc.png'.
        use_forced_for_limits: Use the forced extractions instead of
            upper limits for non-detections., defaults to `False`.
        use_forced_for_all: Use the forced fits for all the datapoints,
            defaults to `False`.
        hide_legend: Hide the legend, defaults to `False`.
        plot_dpi: Specify the DPI of saved figures, defaults to 150.

    Returns:
        None if save is `True` or the matplotlib figure if save is
            `False`.

    Raises:
        SourcePlottingError: Source does not have any forced fits when the
            'use_forced_for_all' or 'use_forced_for_limits' options have
            been selected.
        SourcePlottingError: Number of detections lower than the
            minimum required.
        SourcePlottingError: Number of datapoints lower than the
            minimum required.
        SourcePlottingError: If measurements dataframe is empty.
    """
    if use_forced_for_all or use_forced_for_limits:
        if not self.forced_fits:
            raise SourcePlottingError(
                "Source does not have any forced fits points to plot."
            )

    if self.detections < min_detections:
        msg = (
            f"Number of detections ({self.detections}) lower "
            f"than minimum required ({min_detections})"
        )
        self.logger.error(msg)
        raise SourcePlottingError(msg)

    if self.measurements.shape[0] < min_points:
        msg = (
            f"Number of datapoints ({self.measurements.shape[0]}) lower "
            f"than minimum required ({min_points})"
        )
        self.logger.error(msg)
        raise SourcePlottingError(msg)

    if mjd and start_date is not None:
        msg = (
            "The 'mjd' and 'start date' options "
            "cannot be used at the same time!"
        )
        self.logger.error(msg)
        raise SourcePlottingError(msg)

    # remove empty values
    measurements_df = self.measurements
    if not self.pipeline and not (
        use_forced_for_limits or use_forced_for_all
    ):
        measurements_df = self.measurements[
            self.measurements['rms_image'] != -99
        ]

    if measurements_df.empty:
        msg = f"{self.name} has no measurements!"
        self.logger.error(msg)
        raise SourcePlottingError(msg)

    # Build figure and labels
    fig = plt.figure(figsize=figsize)
    ax = fig.add_subplot(111)
    plot_title = self.name
    if self.islands:
        plot_title += " (island)"
    ax.set_title(plot_title)

    if peak_flux:
        label = 'Peak Flux Density (mJy/beam)'
        flux_col = "flux_peak"
    else:
        label = 'Integrated Flux Density (mJy)'
        flux_col = "flux_int"

    if use_forced_for_all:
        label = "Forced " + label
        flux_col = "f_" + flux_col

    if self.stokes != "I":
        label = "Absolute " + label
        measurements_df[flux_col] = measurements_df[flux_col].abs()

    ax.set_ylabel(label)

    freq_col = 'frequency'

    grouped_df = measurements_df.groupby(freq_col)
    freqs = list(grouped_df.groups.keys())

    # Colours for each frequency
    freq_cmap = matplotlib.colormaps.get_cmap('viridis')
    cNorm = matplotlib.colors.Normalize(
        vmin=min(freqs), vmax=max(freqs) * 1.1)
    scalarMap = matplotlib.cm.ScalarMappable(norm=cNorm, cmap=freq_cmap)
    sm = scalarMap
    sm._A = []

    # Markers for each frequency
    markers = ['o', 'D', '*', 'X', 's', 'd', 'p']

    self.logger.debug("Frequencies: {}".format(freqs))
    for i, (freq, measurements) in enumerate(grouped_df):
        self.logger.debug("Plotting {} MHz data".format(freq))
        marker = markers[i % len(markers)]
        marker_colour = sm.to_rgba(freq)
        plot_dates = measurements['dateobs']
        self.logger.debug(plot_dates)
        if mjd:
            plot_dates = Time(plot_dates.to_numpy()).mjd
        elif start_date:
            plot_dates -= start_date
            plot_dates /= pd.Timedelta(1, unit='d')

        self.logger.debug("Plotting upper limit")
        if self.pipeline:
            upper_lim_mask = measurements.forced
        else:
            upper_lim_mask = measurements.detection == False
            if use_forced_for_all:
                upper_lim_mask = np.array([False for i in upper_lim_mask])
        upper_lims = measurements[
            upper_lim_mask
        ]
        if self.pipeline:
            if peak_flux:
                value_col = 'flux_peak'
                err_value_col = 'flux_peak_err'
            else:
                value_col = 'flux_int'
                err_value_col = 'flux_int_err'
            uplims = False
            sigma_thresh = 1.0
            label = 'Forced'
            markerfacecolor = 'w'
        else:
            if use_forced_for_limits:
                value_col = 'f_flux_peak'
                err_value_col = 'f_flux_peak_err'
                uplims = False
                sigma_thresh = 1.0
                markerfacecolor = 'w'
                label = "Forced"
            else:
                value_col = err_value_col = 'rms_image'
                uplims = True
                markerfacecolor = marker_colour
                label = 'Upper limit'
        if upper_lim_mask.any():
            upperlim_points = ax.errorbar(
                plot_dates[upper_lim_mask],
                sigma_thresh *
                upper_lims[value_col],
                yerr=upper_lims[err_value_col],
                uplims=uplims,
                lolims=False,
                marker=marker,
                c=marker_colour,
                linestyle="none",
                markerfacecolor=markerfacecolor
            )

        self.logger.debug("Plotting detection")

        if use_forced_for_all:
            detections = measurements
        else:
            detections = measurements[
                ~upper_lim_mask
            ]

        if self.pipeline:
            if peak_flux:
                err_value_col = 'flux_peak_err'
            else:
                err_value_col = 'flux_int_err'
        else:
            if use_forced_for_all:
                err_value_col = flux_col + '_err'
            else:
                err_value_col = 'rms_image'

        if use_forced_for_all:
            markerfacecolor = 'w'
            label = 'Forced'
        else:
            markerfacecolor = marker_colour
            label = 'Selavy'
        if (~upper_lim_mask).any():
            detection_points = ax.errorbar(
                plot_dates[~upper_lim_mask],
                detections[flux_col],
                yerr=detections[err_value_col],
                marker=marker,
                c=marker_colour,
                linestyle="none",
                markerfacecolor=markerfacecolor
            )

    self.logger.debug("Plotting finished.")
    if self.pipeline:
        upper_lim_mask = measurements_df.forced
    else:
        upper_lim_mask = measurements_df.detection == False

    if use_forced_for_all:
        detections = measurements_df
    else:
        detections = measurements_df[
            ~upper_lim_mask
        ]

    if self.pipeline:
        upper_lim_mask = measurements_df.forced
    else:
        upper_lim_mask = measurements_df.detection == False
        if use_forced_for_all:
            upper_lim_mask = np.array([False for i in upper_lim_mask])
    upper_lims = measurements_df[
        upper_lim_mask
    ]

    if yaxis_start == "0":
        max_det = detections.loc[:, [flux_col, err_value_col]].sum(axis=1)
        if use_forced_for_limits or self.pipeline:
            max_y = np.nanmax(
                max_det.tolist() +
                upper_lims[value_col].tolist()
            )
        elif use_forced_for_all:
            max_y = np.nanmax(max_det.tolist())
        else:
            max_y = np.nanmax(
                max_det.tolist() +
                (sigma_thresh * upper_lims[err_value_col]).tolist()
            )
        ax.set_ylim(
            bottom=0,
            top=max_y * 1.1
        )

    if mjd:
        ax.set_xlabel('Date (MJD)')
    elif start_date:
        ax.set_xlabel('Days since {}'.format(start_date))
    else:
        fig.autofmt_xdate()
        ax.set_xlabel('Date')

        date_form = mdates.DateFormatter("%Y-%m-%d")
        ax.xaxis.set_major_formatter(date_form)
        ax.xaxis.set_major_locator(mdates.AutoDateLocator(maxticks=15))

    ax.grid(grid)

    if not hide_legend:
        # Manually create legend artists for consistency.
        # Using dummy points throws a matplotlib warning.
        handles = []
        labels = []
        for i, freq in enumerate(freqs):
            line = Line2D([],
                          [],
                          ls="",
                          marker=markers[i],
                          color=sm.to_rgba(freq)
                          )
            barline = LineCollection(np.empty((2, 2, 2)))

            err = ErrorbarContainer((line, None, [barline]),
                                    has_yerr=True
                                    )
            handles.append(err)
            labels.append('{} MHz'.format(freq))

        ax.legend(handles=handles, labels=labels)

    if save:
        if outfile is None:
            outfile = "{}_lc.png".format(self.name.replace(
                " ", "_"
            ).replace(
                "/", "_"
            ))

        elif not outfile.endswith(".png"):
            outfile += ".png"

        if self.outdir != ".":
            outfile = os.path.join(
                self.outdir,
                outfile
            )

        plt.savefig(outfile, bbox_inches='tight', dpi=plot_dpi)
        plt.close()

        return

    else:

        return fig

save_all_ann(crossmatch_overlay=False, cutout_data=None)

Save kvis annotation file corresponding to the source

Parameters:

Name Type Description Default
crossmatch_overlay bool

Include the crossmatch radius, defaults to False

False
cutout_data Optional[DataFrame]

Pass external cutout_data to be used instead of fetching the data, defaults to None.

None

Returns:

Type Description
None

None

Source code in vasttools/source.py
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
def save_all_ann(
    self,
    crossmatch_overlay: bool = False,
    cutout_data: Optional[pd.DataFrame] = None
) -> None:
    """
    Save kvis annotation file corresponding to the source

    Args:
        crossmatch_overlay: Include the crossmatch radius,
            defaults to `False`
        cutout_data: Pass external cutout_data to be used
            instead of fetching the data, defaults to None.

    Returns:
        None
    """
    indices = self.measurements.index.to_series()
    indices.apply(
        self.write_ann,
        args=(
            None,
            crossmatch_overlay,
            None,
            False,
            cutout_data
        )
    )

save_all_fits_cutouts(size=None, force_cutout_fetch=False, cutout_data=None)

Save all cutouts of the source to fits file

Parameters:

Name Type Description Default
size Optional[Angle]

Size of the cutouts, defaults to None.

None
force_cutout_fetch bool

Whether to force the re-fetching of the cutout data, defaults to False.

False
cutout_data Optional[DataFrame]

Pass external cutout_data to be used instead of fetching the data, defaults to None.

None

Returns:

Type Description
None

None

Source code in vasttools/source.py
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
def save_all_fits_cutouts(
    self,
    size: Optional[Angle] = None,
    force_cutout_fetch: bool = False,
    cutout_data: Optional[pd.DataFrame] = None
) -> None:
    """
    Save all cutouts of the source to fits file

    Args:
        size: Size of the cutouts, defaults to None.
        force_cutout_fetch: Whether to force the re-fetching
            of the cutout data, defaults to `False`.
        cutout_data: Pass external cutout_data to be used
            instead of fetching the data, defaults to None.

    Returns:
        None
    """
    if (self._cutouts_got is False) or force_cutout_fetch:
        if cutout_data is None:
            self.get_cutout_data(size)

    self.logger.debug("Saving fits cutouts...")

    if cutout_data is None:
        indices = self.measurements.index
    else:
        indices = cutout_data.index

    for i in indices:
        self.save_fits_cutout(i, cutout_data=cutout_data)

save_all_png_cutouts(selavy=True, percentile=99.9, zscale=False, contrast=0.2, no_islands=True, no_colorbar=False, crossmatch_overlay=False, hide_beam=False, size=None, disable_autoscaling=False, cutout_data=None, calc_script_norms=False, plot_dpi=150, offset_axes=True)

Wrapper function to save all the png cutouts for all epochs.

Parameters:

Name Type Description Default
selavy bool

If True then selavy overlay are shown, defaults to True.

True
percentile float

The value passed to the percentile normalization function, defaults to 99.9.

99.9
zscale bool

Uses ZScale normalization instead of PercentileInterval, defaults to False.

False
contrast float

Contrast value passed to the ZScaleInterval function when zscale is selected, defaults to 0.2.

0.2
no_islands bool

Hide island name labels, defaults to True.

True
no_colorbar bool

Hides the colorbar, defaults to False.

False
crossmatch_overlay bool

Plots a circle that represents the crossmatch radius, defaults to False.

False
hide_beam bool

Hide the beam on the plot, defaults to False.

False
size Optional[Angle]

Size of the cutout, defaults to None.

None
disable_autoscaling bool

Do not use the consistent normalization values but calculate norms separately for each epoch, defaults to False.

False
cutout_data Optional[DataFrame]

Pass external cutout_data to be used instead of fetching the data, defaults to None.

None
calc_script_norms bool

When passing cutout data this parameter can be set to True to pass this cutout data to the analyse norms function, defaults to False.

False
plot_dpi int

Specify the DPI of saved figures, defaults to 150.

150
offset_axes bool

Use offset, rather than absolute, axis labels.

True

Returns:

Type Description
None

None

Source code in vasttools/source.py
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
def save_all_png_cutouts(
    self,
    selavy: bool = True,
    percentile: float = 99.9,
    zscale: bool = False,
    contrast: float = 0.2,
    no_islands: bool = True,
    no_colorbar: bool = False,
    crossmatch_overlay: bool = False,
    hide_beam: bool = False,
    size: Optional[Angle] = None,
    disable_autoscaling: bool = False,
    cutout_data: Optional[pd.DataFrame] = None,
    calc_script_norms: bool = False,
    plot_dpi: int = 150,
    offset_axes: bool = True
) -> None:
    """
    Wrapper function to save all the png cutouts
    for all epochs.

    Args:
        selavy: If `True` then selavy overlay are shown,
             defaults to `True`.
        percentile: The value passed to the percentile
            normalization function, defaults to 99.9.
        zscale: Uses ZScale normalization instead of
            PercentileInterval, defaults to `False`.
        contrast: Contrast value passed to the ZScaleInterval
            function when zscale is selected, defaults to 0.2.
        no_islands: Hide island name labels, defaults to `True`.
        no_colorbar: Hides the colorbar, defaults to `False`.
        crossmatch_overlay: Plots a circle that represents the
            crossmatch radius, defaults to `False`.
        hide_beam: Hide the beam on the plot, defaults to `False`.
        size: Size of the cutout, defaults to None.
        disable_autoscaling: Do not use the consistent normalization
            values but calculate norms separately for each epoch,
            defaults to `False`.
        cutout_data: Pass external cutout_data to be used
            instead of fetching the data, defaults to None.
        calc_script_norms: When passing cutout data this parameter
            can be set to True to pass this cutout data to the analyse
            norms function, defaults to False.
        plot_dpi: Specify the DPI of saved figures, defaults to 150.
        offset_axes: Use offset, rather than absolute, axis labels.

    Returns:
        None
    """
    if self._cutouts_got is False:
        if cutout_data is None:
            self.get_cutout_data(size)

    if disable_autoscaling:
        norms = None
    else:
        if not calc_script_norms:
            norms = self._analyse_norm_level(
                percentile=percentile,
                zscale=zscale,
                z_contrast=contrast
            )
        else:
            norms = self._analyse_norm_level(
                percentile=percentile,
                zscale=zscale,
                z_contrast=contrast,
                cutout_data=cutout_data
            )

    indices = self.measurements.index.to_series()
    indices.apply(
        self.make_png,
        args=(
            selavy,
            percentile,
            zscale,
            contrast,
            None,
            no_islands,
            "Source",
            no_colorbar,
            None,
            crossmatch_overlay,
            hide_beam,
            True,
            None,
            False,
            disable_autoscaling,
            cutout_data,
            norms,
            plot_dpi,
            offset_axes
        )
    )

save_all_reg(crossmatch_overlay=False, cutout_data=None)

Save DS9 region file corresponding to the source

Parameters:

Name Type Description Default
crossmatch_overlay bool

Include the crossmatch radius, defaults to False

False
cutout_data Optional[DataFrame]

Pass external cutout_data to be used instead of fetching the data, defaults to None.

None

Returns:

Type Description
None

None

Source code in vasttools/source.py
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
def save_all_reg(
    self,
    crossmatch_overlay: bool = False,
    cutout_data: Optional[pd.DataFrame] = None
) -> None:
    """
    Save DS9 region file corresponding to the source

    Args:
        crossmatch_overlay: Include the crossmatch radius,
            defaults to `False`
        cutout_data: Pass external cutout_data to be used
            instead of fetching the data, defaults to None.

    Returns:
        None
    """

    indices = self.measurements.index.to_series()
    indices.apply(
        self.write_reg,
        args=(
            None,
            crossmatch_overlay,
            None,
            False,
            cutout_data
        )
    )

save_fits_cutout(index, outfile=None, size=None, force_cutout_fetch=False, cutout_data=None)

Saves the FITS file cutout of the requested observation.

Parameters:

Name Type Description Default
index int

The index of the requested observation.

required
outfile Optional[str]

File to save to, defaults to None.

None
size Optional[Angle]

Size of the cutout, defaults to None.

None
force_cutout_fetch bool

Whether to force the re-fetching of the cutout data, defaults to False.

False
cutout_data Optional[DataFrame]

Pass external cutout_data to be used instead of fetching the data, defaults to None.

None

Returns:

Type Description
None

None

Raises:

Type Description
ValueError

If the source does not contain the requested index.

Source code in vasttools/source.py
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
def save_fits_cutout(
    self,
    index: int,
    outfile: Optional[str] = None,
    size: Optional[Angle] = None,
    force_cutout_fetch: bool = False,
    cutout_data: Optional[pd.DataFrame] = None
) -> None:
    """
    Saves the FITS file cutout of the requested observation.

    Args:
        index: The index of the requested observation.
        outfile: File to save to, defaults to None.
        size: Size of the cutout, defaults to None.
        force_cutout_fetch: Whether to force the re-fetching
            of the cutout data, defaults to `False`.
        cutout_data: Pass external cutout_data to be used
            instead of fetching the data, defaults to None.

    Returns:
        None

    Raises:
        ValueError: If the source does not contain the requested index.
    """

    if (self._cutouts_got is False) or force_cutout_fetch:
        if cutout_data is None:
            self.get_cutout_data(size)

    if outfile is None:
        outfile = self._get_save_name(index, ".fits")

    if self.outdir != ".":
        outfile = os.path.join(
            self.outdir,
            outfile
        )
    if cutout_data is None:
        cutout_row = self.cutout_df.iloc[index]
    else:
        cutout_row = cutout_data.iloc[index]

    hdu_stamp = fits.PrimaryHDU(
        data=cutout_row.data,
        header=cutout_row.header
    )

    # Write the cutout to a new FITS file
    hdu_stamp.writeto(outfile, overwrite=True)
    self.logger.debug(f"Wrote to {outfile}")

    del hdu_stamp

save_png_cutout(index, selavy=True, percentile=99.9, zscale=False, contrast=0.2, no_islands=True, label='Source', no_colorbar=False, title=None, crossmatch_overlay=False, hide_beam=False, size=None, force_cutout_fetch=False, outfile=None, plot_dpi=150, offset_axes=True)

Wrapper for make_png to make nicer interactive function. Always save.

Parameters:

Name Type Description Default
index int

Index of the observation to show.

required
selavy bool

If True then selavy overlay are shown, defaults to True.

True
percentile float

The value passed to the percentile normalization function, defaults to 99.9.

99.9
zscale bool

Uses ZScale normalization instead of PercentileInterval, defaults to False.

False
contrast float

Contrast value passed to the ZScaleInterval function when zscale is selected, defaults to 0.2.

0.2
no_islands bool

Hide island name labels, defaults to True.

True
label str

legend label for source, defaults to "Source".

'Source'
no_colorbar bool

Hides the colorbar, defaults to False.

False
title Optional[str]

Sets the plot title, defaults to None.

None
crossmatch_overlay bool

Plots a circle that represents the crossmatch radius, defaults to False.

False
hide_beam bool

Hide the beam on the plot, defaults to False.

False
size Optional[Angle]

Size of the cutout, defaults to None.

None
force_cutout_fetch bool

Whether to force the re-fetching of the cutout data, defaults to False.

False
outfile Optional[str]

Name to give the file, if None then the name is automatically generated, defaults to None.

None
plot_dpi int

Specify the DPI of saved figures, defaults to 150.

150
offset_axes bool

Use offset, rather than absolute, axis labels.

True

Returns:

Type Description
None

None

Source code in vasttools/source.py
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
def save_png_cutout(
    self,
    index: int,
    selavy: bool = True,
    percentile: float = 99.9,
    zscale: bool = False,
    contrast: float = 0.2,
    no_islands: bool = True,
    label: str = "Source",
    no_colorbar: bool = False,
    title: Optional[str] = None,
    crossmatch_overlay: bool = False,
    hide_beam: bool = False,
    size: Optional[Angle] = None,
    force_cutout_fetch: bool = False,
    outfile: Optional[str] = None,
    plot_dpi: int = 150,
    offset_axes: bool = True
) -> None:
    """
    Wrapper for make_png to make nicer interactive function.
    Always save.

    Args:
        index: Index of the observation to show.
        selavy: If `True` then selavy overlay are shown,
             defaults to `True`.
        percentile: The value passed to the percentile
            normalization function, defaults to 99.9.
        zscale: Uses ZScale normalization instead of
            PercentileInterval, defaults to `False`.
        contrast: Contrast value passed to the ZScaleInterval
            function when zscale is selected, defaults to 0.2.
        no_islands: Hide island name labels, defaults to `True`.
        label: legend label for source, defaults to "Source".
        no_colorbar: Hides the colorbar, defaults to `False`.
        title: Sets the plot title, defaults to None.
        crossmatch_overlay: Plots a circle that represents the
            crossmatch radius, defaults to `False`.
        hide_beam: Hide the beam on the plot, defaults to `False`.
        size: Size of the cutout, defaults to None.
        force_cutout_fetch: Whether to force the re-fetching
            of the cutout data, defaults to `False`.
        outfile: Name to give the file, if None then the name is
            automatically generated, defaults to None.
        plot_dpi: Specify the DPI of saved figures, defaults to 150.
        offset_axes: Use offset, rather than absolute, axis labels.

    Returns:
        None
    """
    fig = self.make_png(
        index,
        selavy=selavy,
        percentile=percentile,
        zscale=zscale,
        contrast=contrast,
        no_islands=no_islands,
        label=label,
        no_colorbar=no_colorbar,
        title=title,
        crossmatch_overlay=crossmatch_overlay,
        hide_beam=hide_beam,
        size=size,
        force_cutout_fetch=force_cutout_fetch,
        outfile=outfile,
        save=True,
        plot_dpi=plot_dpi,
        offset_axes=offset_axes,
        disable_autoscaling=True
    )

    return

show_all_png_cutouts(columns=4, percentile=99.9, zscale=False, contrast=0.1, outfile=None, save=False, size=None, stampsize=(4, 4), figsize=None, force_cutout_fetch=False, no_selavy=False, disable_autoscaling=False, hide_epoch_labels=False, plot_dpi=150, offset_axes=True)

Creates a grid plot showing the source in each epoch.

Parameters:

Name Type Description Default
columns int

Number of columns to use for the grid plot, defaults to 4.

4
percentile float

The value passed to the percentile normalization function, defaults to 99.9.

99.9
zscale bool

Uses ZScale normalization instead of PercentileInterval, defaults to False.

False
contrast float

Contast value passed to the ZScaleInterval function when zscale is selected, defaults to 0.2.

0.1
outfile Optional[str]

Name of the output file, if None then the name is automatically generated, defaults to None.

None
save bool

Save the plot instead of displaying, defaults to False.

False
size Optional[Angle]

Size of the cutout, defaults to None.

None
stampsize Optional[Tuple[float, float]]

Size of each postagestamp, to be used to calculate the figsize. Default to (4,4).

(4, 4)
figsize Optional[Tuple[float, float]]

Size of the matplotlib.pyplot figure, which will overwrite the stampsize argument if provided. Defaults to None.

None
force_cutout_fetch bool

Whether to force the re-fetching of the cutout data, defaults to False.

False
no_selavy bool

When True the selavy overlay is hidden, defaults to False.

False
disable_autoscaling bool

Turn off the consistent normalization and calculate the normalizations separately for each epoch, defaults to False.

False
hide_epoch_labels bool

Turn off the epoch number label (found in top left corner of image).

False
plot_dpi int

Specify the DPI of saved figures, defaults to 150.

150
offset_axes bool

Use offset, rather than absolute, axis labels.

True

Returns:

Type Description
Union[None, Figure]

None is save is True or the Figure if False.

Raises:

Type Description
ValueError

Stampsize and Figsize cannot both be None

Source code in vasttools/source.py
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
def show_all_png_cutouts(
    self,
    columns: int = 4,
    percentile: float = 99.9,
    zscale: bool = False,
    contrast: float = 0.1,
    outfile: Optional[str] = None,
    save: bool = False,
    size: Optional[Angle] = None,
    stampsize: Optional[Tuple[float, float]] = (4, 4),
    figsize: Optional[Tuple[float, float]] = None,
    force_cutout_fetch: bool = False,
    no_selavy: bool = False,
    disable_autoscaling: bool = False,
    hide_epoch_labels: bool = False,
    plot_dpi: int = 150,
    offset_axes: bool = True
) -> Union[None, matplotlib.figure.Figure]:
    """
    Creates a grid plot showing the source in each epoch.

    Args:
        columns: Number of columns to use for the grid plot,
            defaults to 4.
        percentile: The value passed to the percentile
            normalization function, defaults to 99.9.
        zscale: Uses ZScale normalization instead of
            PercentileInterval, defaults to `False`.
        contrast: Contast value passed to the ZScaleInterval
            function when zscale is selected, defaults to 0.2.
        outfile: Name of the output file, if None then the name
             is automatically generated, defaults to None.
        save: Save the plot instead of displaying,
            defaults to `False`.
        size: Size of the cutout, defaults to None.
        stampsize: Size of each postagestamp, to be used to calculate
            the figsize. Default to (4,4).
        figsize: Size of the matplotlib.pyplot figure, which will overwrite
            the stampsize argument if provided. Defaults to None.
        force_cutout_fetch: Whether to force the re-fetching
            of the cutout data, defaults to `False`.
        no_selavy: When `True` the selavy overlay
            is hidden, defaults to `False`.
        disable_autoscaling: Turn off the consistent normalization and
             calculate the normalizations separately for each epoch,
            defaults to `False`.
        hide_epoch_labels: Turn off the epoch number label (found in
            top left corner of image).
        plot_dpi: Specify the DPI of saved figures, defaults to 150.
        offset_axes: Use offset, rather than absolute, axis labels.

    Returns:
        None is save is `True` or the Figure if `False`.

    Raises:
        ValueError: Stampsize and Figsize cannot both be None
    """

    if (self._cutouts_got is False) or force_cutout_fetch:
        self.get_cutout_data(size)

    num_plots = self.measurements.shape[0]
    nrows = int(np.ceil(num_plots / columns))

    if figsize is None:
        if stampsize is None:
            raise ValueError("Stampsize and Figsize cannot both be None")
        figsize = (stampsize[0] * columns, stampsize[1] * nrows)

    fig = plt.figure(figsize=figsize)
    fig.tight_layout()
    plots = {}

    img_norms = self._analyse_norm_level(
        percentile=percentile,
        zscale=zscale,
        z_contrast=contrast
    )

    for i in range(num_plots):
        cutout_row = self.cutout_df.iloc[i]
        measurement_row = self.measurements.iloc[i]
        target_coords = np.array(
            ([[
                measurement_row.ra,
                measurement_row.dec
            ]])
        )
        i += 1
        plots[i] = fig.add_subplot(
            nrows,
            columns,
            i,
            projection=cutout_row.wcs
        )

        if disable_autoscaling:
            if zscale:
                img_norms = ImageNormalize(
                    cutout_row.data * 1.e3,
                    interval=ZScaleInterval(
                        contrast=contrast
                    )
                )
            else:
                img_norms = ImageNormalize(
                    cutout_row.data * 1.e3,
                    interval=PercentileInterval(percentile),
                    stretch=LinearStretch())

        im = plots[i].imshow(
            cutout_row.data * 1.e3, norm=img_norms, cmap="gray_r"
        )

        epoch_time = measurement_row.dateobs
        epoch = measurement_row.epoch

        plots[i].set_title('{}'.format(
            epoch_time.strftime("%Y-%m-%d %H:%M:%S")
        ))

        if not hide_epoch_labels:
            plots[i].text(
                0.05, 0.9, f"{epoch}", transform=plots[i].transAxes
            )

        cross_target_coords = cutout_row.wcs.wcs_world2pix(
            target_coords, 0
        )
        crosshair_lines = self._create_crosshair_lines(
            cross_target_coords,
            0.15,
            0.15,
            cutout_row.data.shape
        )

        if (not cutout_row['selavy_overlay'].empty) and (not no_selavy):
            plots[i].set_autoscale_on(False)
            (
                collection,
                patches,
                island_names
            ) = self._gen_overlay_collection(
                cutout_row
            )
            plots[i].add_collection(collection, autolim=False)

        if self.forced_fits:
            (
                collection,
                patches,
                island_names
            ) = self._gen_overlay_collection(
                cutout_row, f_source=measurement_row
            )
            plots[i].add_collection(collection, autolim=False)
            del collection

        [plots[i].plot(
            l[0], l[1], color="C3", zorder=10, lw=1.5, alpha=0.6
        ) for l in crosshair_lines]

        lon = plots[i].coords[0]
        lat = plots[i].coords[1]

        lon.set_ticks_visible(False)
        lon.set_ticklabel_visible(False)
        lat.set_ticks_visible(False)
        lat.set_ticklabel_visible(False)

    if save:
        if outfile is None:
            outfile = "{}_cutouts.png".format(self.name.replace(
                " ", "_"
            ).replace(
                "/", "_"
            ))

        elif not outfile.endswith(".png"):
            outfile += ".png"

        if self.outdir != ".":
            outfile = os.path.join(
                self.outdir,
                outfile
            )

        plt.savefig(outfile, bbox_inches='tight', dpi=plot_dpi)

        plt.close()

        return

    else:

        return fig

show_png_cutout(index, selavy=True, percentile=99.9, zscale=False, contrast=0.2, no_islands=True, label='Source', no_colorbar=False, title=None, crossmatch_overlay=False, hide_beam=False, size=None, force_cutout_fetch=False, offset_axes=True)

Wrapper for make_png to make nicer interactive function. No access to save.

Parameters:

Name Type Description Default
index int

Index of the observation to show.

required
selavy bool

If True then selavy overlay are shown, defaults to True.

True
percentile float

The value passed to the percentile normalization function, defaults to 99.9.

99.9
zscale bool

Uses ZScale normalization instead of PercentileInterval, defaults to False.

False
contrast float

Contrast value passed to the ZScaleInterval function when zscale is selected, defaults to 0.2.

0.2
no_islands bool

Hide island name labels, defaults to True.

True
label str

legend label for source, defaults to "Source".

'Source'
no_colorbar bool

Hides the colorbar, defaults to False.

False
title Optional[str]

Sets the plot title, defaults to None.

None
crossmatch_overlay bool

Plots a circle that represents the crossmatch radius, defaults to False.

False
hide_beam bool

Hide the beam on the plot, defaults to False.

False
size Optional[Angle]

Size of the cutout, defaults to None.

None
force_cutout_fetch bool

Whether to force the re-fetching of the cutout data, defaults to False.

False
offset_axes bool

Use offset, rather than absolute, axis labels.

True

Returns:

Type Description
Figure

The cutout Figure.

Source code in vasttools/source.py
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
def show_png_cutout(
    self,
    index: int,
    selavy: bool = True,
    percentile: float = 99.9,
    zscale: bool = False,
    contrast: float = 0.2,
    no_islands: bool = True,
    label: str = "Source",
    no_colorbar: bool = False,
    title: Optional[str] = None,
    crossmatch_overlay: bool = False,
    hide_beam: bool = False,
    size: Optional[Angle] = None,
    force_cutout_fetch: bool = False,
    offset_axes: bool = True,
) -> plt.Figure:
    """
    Wrapper for make_png to make nicer interactive function.
    No access to save.

    Args:
        index: Index of the observation to show.
        selavy: If `True` then selavy overlay are shown,
             defaults to `True`.
        percentile: The value passed to the percentile
            normalization function, defaults to 99.9.
        zscale: Uses ZScale normalization instead of
            PercentileInterval, defaults to `False`.
        contrast: Contrast value passed to the ZScaleInterval
            function when zscale is selected, defaults to 0.2.
        no_islands: Hide island name labels, defaults to `True`.
        label: legend label for source, defaults to "Source".
        no_colorbar: Hides the colorbar, defaults to `False`.
        title: Sets the plot title, defaults to None.
        crossmatch_overlay: Plots a circle that represents the
            crossmatch radius, defaults to `False`.
        hide_beam: Hide the beam on the plot, defaults to `False`.
        size: Size of the cutout, defaults to None.
        force_cutout_fetch: Whether to force the re-fetching of the cutout
            data, defaults to `False`.
        offset_axes: Use offset, rather than absolute, axis labels.

    Returns:
        The cutout Figure.
    """

    fig = self.make_png(
        index,
        selavy=selavy,
        percentile=percentile,
        zscale=zscale,
        contrast=contrast,
        no_islands=no_islands,
        label=label,
        no_colorbar=no_colorbar,
        title=title,
        crossmatch_overlay=crossmatch_overlay,
        hide_beam=hide_beam,
        size=size,
        force_cutout_fetch=force_cutout_fetch,
        offset_axes=offset_axes,
        disable_autoscaling=True
    )

    return fig

Searches SIMBAD for object coordinates and returns matches.

Parameters:

Name Type Description Default
radius Angle

Radius to search, defaults to Angle(20. * u.arcsec)

Angle(20.0 * arcsec)

Returns:

Type Description
Union[None, Table]

Table of matches or None if no matches

Raises:

Type Description
ValueError

Error in performing the SIMBAD region search.

Source code in vasttools/source.py
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
def simbad_search(
    self, radius: Angle = Angle(20. * u.arcsec)
) -> Union[None, Table]:
    """
    Searches SIMBAD for object coordinates and returns matches.

    Args:
        radius: Radius to search, defaults to Angle(20. * u.arcsec)

    Returns:
        Table of matches or None if no matches

    Raises:
        ValueError: Error in performing the SIMBAD region search.
    """
    Simbad.add_votable_fields('ra(d)', 'dec(d)')

    try:
        result_table = Simbad.query_region(self.coord, radius=radius)
        if result_table is None:
            return None

        return result_table

    except Exception as e:
        raise ValueError(
            "Error in performing the SIMBAD region search! Error: %s", e
        )
        return None

skyview_contour_plot(index, survey, contour_levels=[3.0, 5.0, 10.0, 15.0], percentile=99.9, zscale=False, contrast=0.2, outfile=None, no_colorbar=False, title=None, save=False, size=None, force_cutout_fetch=False, plot_dpi=150)

Fetches a FITS file from SkyView of the requested survey at the source location and overlays ASKAP contours.

Parameters:

Name Type Description Default
index int

Index of the requested ASKAP observation.

required
survey str

Survey requested to be fetched using SkyView.

required
contour_levels List[float]

Contour levels to plot which are multiples of the local rms, defaults to [3., 5., 10., 15.].

[3.0, 5.0, 10.0, 15.0]
percentile float

The value passed to the percentile normalization function, defaults to 99.9.

99.9
zscale bool

Uses ZScale normalization instead of PercentileInterval, defaults to False.

False
contrast float

Contrast value passed to the ZScaleInterval function when zscale is selected, defaults to 0.2.

0.2
outfile Optional[str]

Name to give the file, if None then the name is automatically generated, defaults to None.

None
no_colorbar bool

Hides the colorbar, defaults to False.

False
title Optional[str]

Plot title, defaults to None.

None
save bool

Saves the file instead of returing the figure, defaults to False.

False
size Optional[Angle]

Size of the cutout, defaults to None.

None
force_cutout_fetch bool

Whether to force the re-fetching of the cutout data, defaults to False.

False
plot_dpi int

Specify the DPI of saved figures, defaults to 150.

150

Returns:

Type Description
Union[None, Figure]

None if save is True or the figure object if False

Raises:

Type Description
ValueError

If the index is out of range.

ValueError

If the requested survey is not valid.

Source code in vasttools/source.py
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
def skyview_contour_plot(
    self,
    index: int,
    survey: str,
    contour_levels: List[float] = [3., 5., 10., 15.],
    percentile: float = 99.9,
    zscale: bool = False,
    contrast: float = 0.2,
    outfile: Optional[str] = None,
    no_colorbar: bool = False,
    title: Optional[str] = None,
    save: bool = False,
    size: Optional[Angle] = None,
    force_cutout_fetch: bool = False,
    plot_dpi: int = 150,
) -> Union[None, matplotlib.figure.Figure]:
    """
    Fetches a FITS file from SkyView of the requested survey at
    the source location and overlays ASKAP contours.

    Args:
        index: Index of the requested ASKAP observation.
        survey: Survey requested to be fetched using SkyView.
        contour_levels: Contour levels to plot which are multiples
             of the local rms, defaults to [3., 5., 10., 15.].
        percentile: The value passed to the percentile
            normalization function, defaults to 99.9.
        zscale: Uses ZScale normalization instead of
            PercentileInterval, defaults to `False`.
        contrast: Contrast value passed to the ZScaleInterval
            function when zscale is selected, defaults to 0.2.
        outfile: Name to give the file, if None then the name is
            automatically generated, defaults to None.
        no_colorbar: Hides the colorbar, defaults to `False`.
        title: Plot title, defaults to None.
        save: Saves the file instead of returing the figure,
            defaults to `False`.
        size: Size of the cutout, defaults to None.
        force_cutout_fetch: Whether to force the re-fetching
            of the cutout data, defaults to `False`.
        plot_dpi: Specify the DPI of saved figures, defaults to 150.

    Returns:
        None if save is `True` or the figure object if `False`

    Raises:
        ValueError: If the index is out of range.
        ValueError: If the requested survey is not valid.
    """

    if (self._cutouts_got is False) or force_cutout_fetch:
        self.get_cutout_data(size)

    size = self._size

    surveys = list(SkyView.survey_dict.values())
    survey_list = [item for sublist in surveys for item in sublist]

    if survey not in survey_list:
        raise ValueError(f"{survey} is not a valid SkyView survey name")

    if index > len(self.measurements):
        raise ValueError(f"Cannot access {index}th measurement.")
        return

    if outfile is None:
        outfile = self._get_save_name(index, ".png")

    if self.outdir != ".":
        outfile = os.path.join(
            self.outdir,
            outfile
        )

    try:
        paths = SkyView.get_images(
            position=self.measurements.iloc[index]['skycoord'],
            survey=[survey], radius=size
        )
        path_fits = paths[0][0]

        path_wcs = WCS(path_fits.header)

    except Exception as e:
        warnings.warn("SkyView fetch failed!")
        warnings.warn(e)
        return

    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_subplot(111, projection=path_wcs)

    mean_vast, median_vast, rms_vast = sigma_clipped_stats(
        self.cutout_df.iloc[index].data
    )

    levels = [
        i * rms_vast for i in contour_levels
    ]

    if zscale:
        norm = ImageNormalize(
            path_fits.data,
            interval=ZScaleInterval(
                contrast=contrast
            )
        )
    else:
        norm = ImageNormalize(
            path_fits.data,
            interval=PercentileInterval(percentile),
            stretch=LinearStretch()
        )

    im = ax.imshow(path_fits.data, norm=norm, cmap='gray_r')

    ax.contour(
        self.cutout_df.iloc[index].data,
        levels=levels,
        transform=ax.get_transform(self.cutout_df.iloc[index].wcs),
        colors='C0',
        zorder=10,
    )

    if title is None:
        obs_time = self.measurements.iloc[index].dateobs
        title = "{} {}".format(
            self.name,
            obs_time.strftime(
                "%Y-%m-%d %H:%M:%S"
            )
        )

    ax.set_title(title)

    lon = ax.coords[0]
    lat = ax.coords[1]
    lon.set_axislabel("Right Ascension (J2000)")
    lat.set_axislabel("Declination (J2000)")

    if not no_colorbar:
        divider = make_axes_locatable(ax)
        cax = divider.append_axes(
            "right", size="3%", pad=0.1, axes_class=maxes.Axes)
        cb = fig.colorbar(im, cax=cax)

    if save:
        plt.savefig(outfile, bbox_inches="tight", dpi=plot_dpi)
        self.logger.debug("Saved {}".format(outfile))

        plt.close(fig)

        return
    else:
        return fig

write_ann(index, outfile=None, crossmatch_overlay=False, size=None, force_cutout_fetch=False, cutout_data=None)

Write a kvis annotation file containing all selavy sources within the image.

Parameters:

Name Type Description Default
index int

The index correpsonding to the requested observation.

required
outfile str

Name of the file to write, defaults to None.

None
crossmatch_overlay bool

If True, a circle is added to the annotation file output denoting the crossmatch radius, defaults to False.

False
size Optional[Angle]

Size of the cutout, defaults to None.

None
force_cutout_fetch bool

Whether to force the re-fetching of the cutout data, defaults to False

False
cutout_data Optional[DataFrame]

Pass external cutout_data to be used instead of fetching the data, defaults to None.

None

Returns:

Type Description
None

None

Source code in vasttools/source.py
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
def write_ann(
    self,
    index: int,
    outfile: str = None,
    crossmatch_overlay: bool = False,
    size: Optional[Angle] = None,
    force_cutout_fetch: bool = False,
    cutout_data: Optional[pd.DataFrame] = None
) -> None:
    """
    Write a kvis annotation file containing all selavy sources
    within the image.

    Args:
        index: The index correpsonding to the requested observation.
        outfile: Name of the file to write, defaults to None.
        crossmatch_overlay: If True, a circle is added to the
            annotation file output denoting the crossmatch radius,
            defaults to False.
        size: Size of the cutout, defaults to None.
        force_cutout_fetch: Whether to force the re-fetching
            of the cutout data, defaults to `False`
        cutout_data: Pass external cutout_data to be used
            instead of fetching the data, defaults to None.

    Returns:
        None
    """
    if (self._cutouts_got is False) or force_cutout_fetch:
        if cutout_data is None:
            self.get_cutout_data(size)

    if outfile is None:
        outfile = self._get_save_name(index, ".ann")
    if self.outdir != ".":
        outfile = os.path.join(
            self.outdir,
            outfile
        )

    neg = False
    with open(outfile, 'w') as f:
        f.write("COORD W\n")
        f.write("PA SKY\n")
        f.write("FONT hershey14\n")
        f.write("COLOR BLUE\n")
        f.write("CROSS {0} {1} {2} {2}\n".format(
            self.measurements.iloc[index].ra,
            self.measurements.iloc[index].dec,
            3. / 3600.
        ))
        if crossmatch_overlay:
            try:
                f.write("CIRCLE {} {} {}\n".format(
                    self.measurements.iloc[index].ra,
                    self.measurements.iloc[index].dec,
                    self.crossmatch_radius.deg
                ))
            except Exception as e:
                self.logger.warning(
                    "Crossmatch circle overlay failed!"
                    " Has the source been crossmatched?")
        f.write("COLOR GREEN\n")

        if cutout_data is None:
            selavy_cat_cut = self.cutout_df.iloc[index].selavy_overlay
        else:
            selavy_cat_cut = cutout_data.iloc[index].selavy_overlay

        for i, row in selavy_cat_cut.iterrows():
            if row["island_id"].startswith("n"):
                neg = True
                f.write("COLOR RED\n")
            ra = row["ra_deg_cont"]
            dec = row["dec_deg_cont"]
            f.write(
                "ELLIPSE {} {} {} {} {}\n".format(
                    ra,
                    dec,
                    float(
                        row["maj_axis"]) /
                    3600. /
                    2.,
                    float(
                        row["min_axis"]) /
                    3600. /
                    2.,
                    float(
                        row["pos_ang"])))
            f.write(
                "TEXT {} {} {}\n".format(
                    ra, dec, self._remove_sbid(
                        row["island_id"])))
            if neg:
                f.write("COLOR GREEN\n")
                neg = False

    self.logger.debug("Wrote annotation file {}.".format(outfile))

write_measurements(simple=False, outfile=None)

Write the measurements to a CSV file.

Parameters:

Name Type Description Default
simple bool

Only include flux density and uncertainty in returned table, defaults to False.

False
outfile Optional[str]

File to write measurements to, defaults to None.

None

Returns:

Type Description
None

None

Source code in vasttools/source.py
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
def write_measurements(
    self, simple: bool = False, outfile: Optional[str] = None
) -> None:
    """Write the measurements to a CSV file.

    Args:
        simple: Only include flux density and uncertainty in returned
            table, defaults to `False`.
        outfile: File to write measurements to, defaults to None.

    Returns:
        None
    """
    if simple:
        if self.pipeline:
            cols = [
                'source',
                'ra',
                'dec',
                'component_id',
                'flux_peak',
                'flux_peak_err',
                'flux_int',
                'flux_int_err',
                'rms',
            ]
        else:
            cols = [
                'name',
                'ra_deg_cont',
                'dec_deg_cont',
                'component_id',
                'flux_peak',
                'flux_peak_err',
                'flux_int',
                'flux_int_err',
                'rms_image',
            ]

        measurements_to_write = self.measurements[cols]

    else:
        cols = [
            'fields',
            'skycoord',
            'selavy',
            'image',
            'rms',
        ]

        if self.pipeline:
            cols[0] = 'field'

        measurements_to_write = self.measurements.drop(
            labels=cols, axis=1
        )

    # drop any empty values
    if not self.pipeline and not self.forced_fits:
        measurements_to_write = measurements_to_write[
            measurements_to_write['rms_image'] != -99
        ]

    if measurements_to_write.empty:
        self.logger.warning(
            "%s has no measurements! No file will be written.",
            self.name
        )
        return

    if outfile is None:
        outfile = "{}_measurements.csv".format(self.name.replace(
            " ", "_"
        ).replace(
            "/", "_"
        ))

    elif not outfile.endswith(".csv"):
        outfile += ".csv"

    if self.outdir != ".":
        outfile = os.path.join(
            self.outdir,
            outfile
        )

    measurements_to_write.to_csv(outfile, index=False)

    self.logger.debug("Wrote {}.".format(outfile))

write_reg(index, outfile=None, crossmatch_overlay=False, size=None, force_cutout_fetch=False, cutout_data=None)

Write a DS9 region file containing all selavy sources within the image

Parameters:

Name Type Description Default
index int

The index correpsonding to the requested observation.

required
outfile Optional[str]

Name of the file to write, defaults to None.

None
crossmatch_overlay bool

If True, a circle is added to the annotation file output denoting the crossmatch radius, defaults to False.

False
size Optional[Angle]

Size of the cutout, defaults to None.

None
force_cutout_fetch bool

Whether to force the re-fetching of the cutout data, defaults to False.

False
cutout_data Optional[DataFrame]

Pass external cutout_data to be used instead of fetching the data, defaults to None.

None

Returns:

Type Description
None

None

Source code in vasttools/source.py
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
def write_reg(
    self,
    index: int,
    outfile: Optional[str] = None,
    crossmatch_overlay: bool = False,
    size: Optional[Angle] = None,
    force_cutout_fetch: bool = False,
    cutout_data: Optional[pd.DataFrame] = None
) -> None:
    """
    Write a DS9 region file containing all selavy sources within the image

    Args:
        index: The index correpsonding to the requested observation.
        outfile: Name of the file to write, defaults to None.
        crossmatch_overlay: If True, a circle is added to the
            annotation file output denoting the crossmatch radius,
            defaults to False.
        size: Size of the cutout, defaults to None.
        force_cutout_fetch: Whether to force the re-fetching
            of the cutout data, defaults to `False`.
        cutout_data: Pass external cutout_data to be used
            instead of fetching the data, defaults to None.

    Returns:
        None
    """
    if (self._cutouts_got is False) or force_cutout_fetch:
        if cutout_data is None:
            self.get_cutout_data(size)

    if outfile is None:
        outfile = self._get_save_name(index, ".reg")
    if self.outdir != ".":
        outfile = os.path.join(
            self.outdir,
            outfile
        )

    with open(outfile, 'w') as f:
        f.write("# Region file format: DS9 version 4.0\n")
        f.write("global color=green font=\"helvetica 10 normal\" "
                "select=1 highlite=1 edit=1 "
                "move=1 delete=1 include=1 "
                "fixed=0 source=1\n")
        f.write("fk5\n")
        f.write(
            "point({} {}) # point=x color=blue\n".format(
                self.measurements.iloc[index].ra,
                self.measurements.iloc[index].dec,
            ))
        if crossmatch_overlay:
            try:
                f.write("circle({} {} {}) # color=blue\n".format(
                    self.measurements.iloc[index].ra,
                    self.measurements.iloc[index].dec,
                    self.crossmatch_radius.deg
                ))
            except Exception as e:
                self.logger.warning(
                    "Crossmatch circle overlay failed!"
                    " Has the source been crossmatched?")

        if cutout_data is None:
            selavy_cat_cut = self.cutout_df.iloc[index].selavy_overlay
        else:
            selavy_cat_cut = cutout_data.iloc[index].selavy_overlay

        for i, row in selavy_cat_cut.iterrows():
            if row["island_id"].startswith("n"):
                color = "red"
            else:
                color = "green"
            ra = row["ra_deg_cont"]
            dec = row["dec_deg_cont"]
            f.write(
                "ellipse({} {} {} {} {}) # color={}\n".format(
                    ra,
                    dec,
                    float(
                        row["maj_axis"]) /
                    3600. /
                    2.,
                    float(
                        row["min_axis"]) /
                    3600. /
                    2.,
                    float(
                        row["pos_ang"]) +
                    90.,
                    color))
            f.write(
                "text({} {} \"{}\") # color={}\n".format(
                    ra - (10. / 3600.), dec, self._remove_sbid(
                        row["island_id"]), color))

    self.logger.debug("Wrote region file {}.".format(outfile))

SourcePlottingError

Bases: Exception

A custom exception for plotting errors.

Source code in vasttools/source.py
61
62
63
64
65
class SourcePlottingError(Exception):
    """
    A custom exception for plotting errors.
    """
    pass