-
Notifications
You must be signed in to change notification settings - Fork 4
/
astronomy.py
1630 lines (1310 loc) · 55.7 KB
/
astronomy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
from __future__ import print_function
from astropy import coordinates
from astropy import units as u
from astropy.wcs import WCS
from astropy.io import fits
from astropy.time import Time
from astropy.coordinates import get_body_barycentric
from astropy.table import Table, Column
from ccdproc import ImageFileCollection
import ccdproc
# from pyraf import iraf
from datetime import datetime
from datetime import timedelta
import math
from os import path, system, getcwd
import numpy as np
import pandas as pd
import sep
import sewpy
import os
import time
import glob
from astropy.utils.exceptions import AstropyWarning
import warnings
class FitsOps:
def __init__(self, file_name, checksum=False, ignore_missing_end=True):
warnings.simplefilter('ignore', category=AstropyWarning)
self.file_name = file_name
self.timeops = TimeOps()
if checksum is True:
with fits.open(self.file_name, mode='update', ignore_missing_end=ignore_missing_end) as self.hdu:
self.hdu[0].add_checksum()
self.hdu = fits.open(self.file_name, ignore_missing_end=ignore_missing_end)
else:
self.hdu = fits.open(self.file_name, ignore_missing_end=ignore_missing_end)
def return_out_file_header(self, observer="YK", tel="TUG 100", code="A84",
contact="[email protected]",
catalog="GAIA"):
"""
Creates MPC report file's head.
@param observer: Observer.
@type observer: str
@param tel: Telescope information.
@type tel: str
@param code: Observatory code.
@type code: str
@param contact: E-mail of the contact person.
@type contact: str
@param catalog: Used catalogue.
@type catalog: str
@return: str
"""
head = """COD {0}
OBS {1}
MEA {2}
TEL {3} + CCD
ACK MPCReport file updated {4}
AC2 {5}
NET {6}""".format(code, observer, observer, tel,
self.timeops.time_stamp(),
contact, catalog)
return(head)
def get_header(self, key):
"""
Extracts requested keyword from FITS header.
@param key: Requested keyword.
@type key: str
@return: str
"""
try:
header_key = self.hdu[0].header[key]
ret = header_key
except Exception as e:
ret = False
return ret
def update_header(self, key, value):
"""
Updates requested keyword from FITS header.
@param key: Requested keyword.
@type key: str
@param value: Value that will be updated.
@type key: str
@return: str
"""
try:
hdu = fits.open(self.file_name, mode='update')
hdu[0].header[key] = value
hdu.close()
except Exception as e:
print(e)
return False
return True
def remove_header_keyword(self, keyword):
"""
Remove keyword from FITS header.
@param keyword: Requested keyword to be removed.
@type keyword: str
@return: str
"""
try:
hdu = fits.open(self.file_name, mode='update')
hdu[0].header.remove(keyword)
print("{0} keyword has beed deleted!".format(keyword))
hdu.close()
except Exception as e:
return False
return True
def detect_sources(self, plot=False, max_sources=None, catalog_output=None):
"""
It detects sources on FITS image with sep module.
@param plot
@type plot: boolean
@param max_sources: Maximum detection limit.
@type max_sources: int
@return: astropy.table
"""
objects = self.source_extract()
if max_sources is not None:
objects = objects[:max_sources]
if catalog_output is True:
cat_file = os.path.splitext(self.file_name)[0]
ascii.write(objects, "{}.csv".format(cat_file), format='csv', fast_writer=False)
if plot is True:
from .visuals import StarPlot
data = self.hdu[0].data.astype(float)
splt = StarPlot()
splt.star_plot(data, objects)
return objects
def source_extract(self, radius=10):
"""
It detects sources on FITS image with sep module.
@return: astropy.table
"""
data = self.hdu[0].data.astype(float)
bkg = sep.Background(data)
data_sub = data - bkg
sew = sewpy.SEW(params=['FLAGS', 'X_IMAGE', 'Y_IMAGE', 'ALPHA_J2000', 'DELTA_J2000', 'FLUX_AUTO', 'FLUXERR_AUTO',
'FLUX_APER', 'FLUXERR_APER', 'FLUX_PETRO', 'FLUXERR_PETRO', 'FLUX_MAX', 'XPEAK_IMAGE', 'YPEAK_IMAGE', 'MAG_APER', 'MAGERR_APER',
'BACKGROUND', 'MAG_AUTO', 'MAGERR_AUTO', 'FWHM_IMAGE', 'ELONGATION', 'A_IMAGE', 'B_IMAGE', 'THETA_IMAGE'],
config={'DETECT_THRESH': 3,
'ANALYSIS_THRESH': 3,
'PHOT_APERTURES': 5,
'PHOT_PETROPARAMS': '"5, 5"',
'DETECT_MINAREA': 1,
'DEBLEND_NTHRESH': 16,
'DEBLEND_MINCONT': 0.00001,
'PHOT_AUTOPARAMS': '"2.5, 3.5"',
'BACK_SIZE': 64,
'BACK_FILTERSIZE': 3,
'FILTER': 'Y',
'VERBOSE_TYPE': 'QUIET'})
out = sew(self.file_name)
try:
out["table"]["MAG_AUTO"][np.where(out["table"]["MAG_AUTO"] == 99)] = None
out["table"]["MAGERR_AUTO"][np.where(out["table"]["MAGERR_AUTO"] == 99)] = None
return out["table"]
except Exception as e:
# Log the error if needed (optional)
print(f"Error processing data: {str(e)}")
return out["table"]
def fits_stat(self):
"""
Caclculates basic fits statistics
"""
try:
hdu = fits.open(self.file_name)
image_data = hdu[0].data
return({'Min': np.min(image_data),
'Max': np.max(image_data),
'Mean': np.mean(image_data),
'Stdev': np.std(image_data)})
except Exception as e:
print(e)
return False
class AstCalc:
def __init__(self):
from .io import FileOps
self.fileops = FileOps()
self.timeops = TimeOps()
def is_object(self, coor1, coor2, max_dist=10, min_dist=0):
"""
It checks whether the object being queried is the same in the
database within the specified limit.
@param coor1: Detected object's coordinate.
@type coor1: coordinate
@param coor2: Calculated object's coordinate.
@type coor2: coordinate
@param max_dist: Max distance limit in arcsec.
@type max_dist: integer
@param min_dist: Max distance limit in arcsec.
@type min_dist: int
@return: boolean
"""
ret = coor1.separation(coor2)
return(min_dist <= ret.arcsecond <= max_dist)
def mag2flux(self, mag, merr=None, exptime=None):
"""
Converts magnitude to flux.
@param mag: Mag.
@type mag: float
@param merr: Mag.
@type merr: float
@param exptime: Exposure time.
@type exptime: float
@return: float
"""
# This calculation for normalize flux to exposure time
if exptime is None:
flux = math.pow(10, (-0.4 * float(mag)))
else:
flux = math.pow(10, -0.4 * float(mag)) / float(exptime)
if merr is not None:
uncer = float(merr) * 100
try:
fluxerr = flux / uncer
except ZeroDivisionError:
fluxerr = 0
else:
fluxerr = 0
if math.isinf(fluxerr):
fluxerr = 0
return flux, fluxerr
def flux2mag(self, flux, fluxerr, exptime=None):
"""
Converts flux to magnitude.
@param flux: Flux.
@type flux: float
@param exptime: Exposure time.
@type exptime: float
@return: float
"""
try:
# This calculation for normalize flux to exposure time
if exptime is None:
mag = -2.5 * math.log10(flux)
else:
mag = -2.5 * math.log10(flux) + 2.5 * math.log10(exptime)
mag_err = math.sqrt(flux / fluxerr)
if math.isinf(mag_err):
mag_err = 0
return mag, mag_err
except Exception as e:
print(e)
def radec2wcs(self, ra, dec):
"""
Converts string RA, DEC coordinates to astropy format.
@param ra: RA of field center for search, format: degrees or hh:mm:ss
@type ra: str
@param dec: DEC of field center for search, format: degrees or hh:mm:ss
@type dec: str
@return: list
"""
try:
c = coordinates.SkyCoord('{0} {1}'.format(ra, dec),
unit=(u.hourangle, u.deg), frame='icrs')
return(c)
except Exception as e:
pass
def deg2hmsdms(self, ra, dec):
"""
Converts string RA, DEC coordinates to astropy format.
@param ra: RA of field center for search, format: degrees or hh:mm:ss
@type ra: str
@param dec: DEC of field center for search, format: degrees or hh:mm:ss
@type dec: str
@return: list
"""
try:
c = coordinates.SkyCoord(ra, dec, frame='icrs', unit='deg')
hmsdms = c.to_string(style='hmsdms', sep=":", precision=2)
except Exception as e:
print(e)
return False
return hmsdms
def xy2sky(self, file_name, x, y, sep=":"):
"""
Converts physical coordinates to WCS coordinates for STDOUT.
@param file_name: FITS image file name with path.
@type file_name: str
@param x: x coordinate of object.
@type x: float
@param y: y coordinate of object.
@type y: float
@param sep: delimiter for HMSDMS format.
@type sep: float
@return: str
"""
try:
header = fits.getheader(file_name)
w = WCS(header)
astcoords_deg = w.wcs_pix2world([[x, y]], 0)
c = coordinates.SkyCoord(astcoords_deg * u.deg,
frame='fk5')
alpha = c.to_string(style='hmsdms', sep=sep, precision=2)[0]
delta = c.to_string(style='hmsdms', sep=sep, precision=1)[0]
return("{0} {1}".format(alpha.split(" ")[0],
delta.split(" ")[1]))
except Exception as e:
pass
def xy2sky2(self, file_name, x, y):
"""
Converts physical coordinates to WCS coordinates for calculations.
@param file_name: FITS image file name with path.
@type file_name: str
@param x: x coordinate of object.
@type x: float
@param y: y coordinate of object.
@type y: float
@return: list
"""
try:
header = fits.getheader(file_name)
w = WCS(header)
astcoords_deg = w.wcs_pix2world([[x, y]], 1)
astcoords = coordinates.SkyCoord(
astcoords_deg * u.deg, frame='fk5')
return(astcoords[0])
except Exception as e:
print(e)
pass
def xy2skywcs(self, file_name, x, y):
"""
Converts physical coordinates to WCS coordinates
for STDOUT with wcstools' xy2sky.
@param file_name: FITS image file name with path.
@type file_name: str
@param A_x: A_x coordinate of object.
@type A_x: float
@param y: y coordinate of object.
@type y: float
@return: str
"""
try:
file_path, file_and_ext = path.split(file_name)
system("xy2sky {0} {1} {2} > {3}/coors".format(
file_name,
x,
y,
file_path))
coors = np.genfromtxt('{0}/coors'.format(file_path),
comments='#',
invalid_raise=False,
delimiter=None,
usecols=(0, 1),
dtype="U")
system("rm -rf {0}/coors".format(file_path))
c = coordinates.SkyCoord('{0} {1}'.format(coors[0], coors[1]),
unit=(u.hourangle, u.deg), frame='fk5')
alpha = c.to_string(style='hmsdms', sep=sep, precision=2)[0]
delta = c.to_string(style='hmsdms', sep=sep, precision=1)[0]
return("{0} {1}".format(alpha.split(" ")[0],
delta.split(" ")[1]))
# return('{0} {1}'.format(alpha, delta))
except Exception as e:
pass
def xy2sky2wcs(self, file_name, x, y):
"""
Converts physical coordinates to WCS coordinates for
calculations with wcstools' xy2sky.
@param file_name: FITS image file name with path.
@type file_name: str
@param A_x: A_x coordinate of object.
@type A_x: float
@param y: y coordinate of object.
@type y: float
@return: str
"""
try:
file_path, file_and_ext = path.split(file_name)
system("xy2sky {0} {1} {2} > {3}/coors".format(
file_name,
x,
y,
file_path))
coors = np.genfromtxt('{0}/coors'.format(file_path),
comments='#',
invalid_raise=False,
delimiter=None,
usecols=(0, 1),
dtype="U")
system("rm -rf {0}/coors".format(file_path))
c = coordinates.SkyCoord('{0} {1}'.format(coors[0], coors[1]),
unit=(u.hourangle, u.deg), frame='fk5')
return(c)
except Exception as e:
pass
def sky2xy(self, image_path, ra, dec):
"""
Converts physical coordinates to WCS coordinates for
calculations with wcstools' xy2sky.
@param image_path: FITS image file name with path.
@type image_path: str
@param ra: RA coordinate of object.
@type ra: string
@param dec: DEC coordinate of object.
@type dec: string
@return: tuple
"""
if image_path:
hdu = fits.open(image_path)[0]
else:
print("FITS image has not been provided by the user!")
raise SystemExit
fo = FitsOps(image_path)
header = hdu.header
w = WCS(header)
naxis1 = fo.get_header('naxis1')
naxis2 = fo.get_header('naxis2')
if ":" in (str(ra) or str(dec)):
c = coordinates.SkyCoord('{0} {1}'.format(
ra, dec), unit=(u.hourangle, u.deg),
frame='icrs')
else:
c = coordinates.SkyCoord('{0} {1}'.format(
ra, dec), unit=(u.deg, u.deg),
frame='icrs')
# target's X and Y coor
t_x, t_y = w.wcs_world2pix(c.ra.degree, c.dec.degree, 1)
if naxis1 < t_x or naxis2 < t_y or t_x < 0 or t_y < 0:
print("Provided coordinates are out of frame!")
return(False)
else:
return(float(t_x), float(t_y))
def center_finder(self, file_name, wcs_ref=False):
"""
It finds image center as WCS coordinates
@param file_name: FITS image file name with path.
@type file_name: str
@return: list
"""
try:
fitsops = FitsOps(file_name)
naxis1 = fitsops.get_header("naxis1")
naxis2 = fitsops.get_header("naxis2")
x, y = [float(naxis1) / 2, float(naxis2) / 2]
if not wcs_ref:
coor = self.xy2sky(file_name, x, y)
ra = ' '.join(coor.split(" ")[:3])
dec = ' '.join(coor.split(" ")[3:])
return([ra, dec])
else:
coor = self.xy2sky2(file_name, x, y)
center_ra = coor.ra
center_dec = coor.dec
return([center_ra,
center_dec])
except Exception as e:
print(e)
def solve_field(self,
image_path,
tweak_order=2,
downsample=4,
radius=0.2,
ra=None,
dec=None,
ra_keyword="objctra",
dec_keyword="objctdec",
overwrite=False):
"""
The astrometry engine will take any image and return
the astrometry world coordinate system (WCS).
@param image_path: FITS image file name with path
@type image_path: str
@param tweak_order: Polynomial order of SIP WCS corrections
@type tweak_order: integer
@param downsample: Downsample the image by factor int before
running source extraction
@type downsample: integer
@param radius: Only search in indexes within 'radius' of the
field center given by --ra and --dec
@type radius: str
@param ra: RA of field center for search, format: degrees or hh:mm:ss
@type ra: str
@param dec: DEC of field center for search, format: degrees or hh:mm:ss
@type dec: str
@param ra_keyword: RA keyword in the FITS image header
@type ra_keyword: str
@param dec_keyword: DEC keyword in the FITS image header
@type dec_keyword: str
@return: boolean
"""
try:
if ra is None and dec is None:
fo = FitsOps(image_path)
ra = fo.get_header(ra_keyword)
dec = fo.get_header(dec_keyword)
ra = ra.strip()
dec = dec.strip()
ra = ra.replace(" ", ":")
dec = dec.replace(" ", ":")
else:
ra = ra.strip()
dec = dec.strip()
ra = ra.replace(" ", ":")
dec = dec.replace(" ", ":")
system(("solve-field --no-plots "
"--no-verify --tweak-order {0} "
"--downsample {1} --overwrite --radius {2} --no-tweak "
"--ra {3} --dec {4} {5}").format(tweak_order,
downsample,
radius,
ra,
dec,
image_path))
# Cleaning
if ".gz" in image_path:
root = '.'.join(image_path.split('.')[:-2])
else:
root, extension = path.splitext(image_path)
system(("rm -rf {0}-indx.png {0}-indx.xyls "
"{0}-ngc.png {0}-objs.png "
"{0}.axy {0}.corr "
"{0}.match {0}.rdls "
"{0}.solved {0}.wcs").format(root))
if not path.exists(root + '.new'):
print(image_path + ' cannot be solved!')
return(False)
else:
if overwrite is False:
system("mv {0}.new {0}_new.fits".format(root))
print("{0}.fits --> {0}_new.fits: solved!".format(root))
elif overwrite is True:
print("Overwrite is True!")
system("mv {0}.new {0}.fits".format(root))
print("{0}.new --> {0}.fits: solved!".format(root))
return(True)
except Exception as e:
print(e)
def std2equ(self, ra0, dec0, xx, yy):
"""
Calculation of equatorial coordinates from
standard coordinates used in astrographic plate measurement
@param ra0: Right ascension of optical axis [rad]
@type ra0: float
@param dec0: Declination of optical axis [rad]
@type dec0: float
@param xx: Standard coordinate of X
@type xx: float
@param yy: Standard coordinate of Y
@type yy: float
@return: Tuple, ra, dec in [rad]
"""
ra = ra0 + math.atan(-xx /
(math.cos(dec0) -
(yy * math.sin(dec0))))
dec = math.asin((math.sin(dec0) + (yy * math.cos(dec0))) /
math.sqrt(1 + math.pow(xx, 2) +
math.pow(yy, 2)))
return(ra, dec)
def equ2std(self, ra0, dec0, ra, dec):
"""
Calculation of standard coordinates from equatorial coordinates
@param ra0: Right ascension of optical axis [rad]
@type ra0: float
@param dec0: Declination of optical axis [rad]
@type dec0: float
@param ra: Right ascension [rad]
@type ra: float
@param dec: Declination
@type dec: float
@return: Tuple, xx, yy
"""
xx = (-(math.cos(dec) * math.sin(ra - ra0)) /
(math.cos(dec0) * math.cos(dec) * math.cos(ra - ra0) +
math.sin(dec0) * math.sin(dec)))
yy = (-(math.sin(dec0) * math.cos(dec) * math.cos(ra - ra0) -
math.cos(dec0) * math.sin(dec)) /
(math.cos(dec0) * math.cos(dec) * math.cos(ra - ra0) +
math.sin(dec0) * math.sin(dec)))
return(xx, yy)
def plate_constants(self, ra_center, dec_center,
objects_matrix, target_xy):
"""
Astrometric analysis of photographic plates.
Add a data equation of form Ax=b to a least squares problem
@param ra_center: RA coordinate of center of optical axis [rad]
@type ra_center: float
@param dec_center: DEC coordinate of center of optical axis [rad]
@type dec_center: float
@param objects_matrix: Return of the detect_sources
function with skycoords.
@type objects_matrix: astropy.table
@param target_xy: Physical coordinates to be converted to Skycoord.
@type target_xy: list
@return: astropy.table
"""
x_xy = []
b_xx = []
b_yy = []
ra0 = ra_center
dec0 = dec_center
for m_object in objects_matrix:
ra = math.radians(m_object[3])
dec = math.radians(m_object[4])
x_xy.append([m_object[1], m_object[2], 1])
b_xx.append(self.equ2std(ra0, dec0, ra, dec)[0])
b_yy.append(self.equ2std(ra0, dec0, ra, dec)[1])
A_x = np.linalg.lstsq(np.array(x_xy), np.asarray(b_xx))[0]
A_y = np.linalg.lstsq(np.array(x_xy), np.asarray(b_yy))[0]
a, b, c = A_x
d, e, f = A_y
coor_list = []
for s_object in objects_matrix:
xx = a * s_object[1] + b * s_object[2] + c
yy = f * s_object[1] + e * s_object[2] + f
ra, dec = self.std2equ(ra0, dec0, xx, yy)
d_ra = ((ra - math.radians(s_object[3])) *
math.cos(math.radians(s_object[4])))
d_dec = (dec - math.radians(s_object[4]))
delta = 3600.0 * math.sqrt(math.pow(d_ra, 2) +
math.pow(d_dec, 2))
coor_list.append([s_object[0],
s_object[1],
s_object[2],
s_object[3],
s_object[4],
math.degrees(ra),
math.degrees(dec),
math.degrees(d_ra) * 3600.0,
math.degrees(d_dec) * 3600.0,
delta,
(s_object[3] - math.degrees(ra)),
(s_object[4] - math.degrees(dec))])
for i, xy in enumerate(target_xy):
xx = a * xy[0] + b * xy[1] + c
yy = f * xy[0] + e * xy[1] + f
ra, dec = self.std2equ(ra0, dec0, xx, yy)
coor_list.append([i,
xy[0],
xy[1],
None,
None,
math.degrees(ra),
math.degrees(dec),
None,
None,
None,
None,
None])
results = np.array(coor_list, dtype=np.float)
# results = results[np.isnan(results)] = 0
rms_ra = np.sqrt(np.mean(np.power(results[:, 7], 2)))
rms_dec = np.sqrt(np.mean(np.power(results[:, 8], 2)))
rms_delta = np.sqrt(np.mean(np.power(results[:, 9], 2)))
tb_results = Table(results, names=('id',
'x',
'y',
'ra',
'dec',
'c_ra',
'c_dec',
'e_c_ra',
'e_c_dec',
'error',
'diff_ra',
'diff_dec'))
return(tb_results,
rms_ra,
rms_dec,
rms_delta)
"""
def ccmap(self, objects_matrix, image_path,
ppm_parallax_cor=True,
stdout=False):
Compute plate solutions using
matched pixel and celestial coordinate lists.
@param objects_matrix: Return of the match_catalog function
in catalog module.
@type objects_matrix: astropy.table
@param image_path: FITS image without WCS keywords.
@type image_path: path
@param ppm_parallax_cor: Apply proper motion
and stellar parallax correction?
@type ppm_parallax_cor: boolean
@param stdout: Print result as a STDOUT?
@type stdout: boolean
@return: boolean, FITS image with WCS solutions
remove_nan = objects_matrix['x',
'y',
'ra',
'dec',
'plx',
'pmra',
'pmdec']
remove_nan = Table(remove_nan, masked=True)
for col in remove_nan.columns.values():
col.mask = np.isnan(col)
col.fill_value = 0.0
trimmed_om = remove_nan.filled()
del objects_matrix
del remove_nan
if ppm_parallax_cor:
corrected_coords = []
fo = FitsOps(image_path)
odate = fo.get_header("date-obs")
for i in range(len(trimmed_om)):
ra_plx, dec_plx = self.stellar_parallax_cor(
(trimmed_om['plx'][i] / 1000),
trimmed_om['ra'][i],
trimmed_om['dec'][i],
odate)
cra_ppm, cdec_ppm = self.ppm_cor(trimmed_om['ra'][i],
trimmed_om['dec'][i],
trimmed_om['pmra'][i],
trimmed_om['pmdec'][i],
odate)
cra = cra_ppm + (ra_plx / 3600)
cdec = cdec_ppm + (dec_plx / 3600)
corrected_coords.append([cra, cdec])
cra_cdec = Table(np.array(corrected_coords),
names=("cra",
"cdec"))
c = coordinates.SkyCoord(cra_cdec['cra'] * u.deg,
cra_cdec['cdec'] * u.deg, frame='icrs')
else:
c = coordinates.SkyCoord(trimmed_om['ra'] * u.deg,
trimmed_om['dec'] * u.deg, frame='icrs')
rd = c.to_string('hmsdms', sep=":", precision=5)
radec = np.reshape(rd, (-1, 1))
iraf.digiphot(_doprint=0)
iraf.daophot(_doprint=0)
ra_dec = Column(name='ra_dec', data=radec[:, 0])
x_y = Table(trimmed_om['x', 'y'])
x_y.add_column(ra_dec, 0)
np.savetxt("{0}/coords".format(getcwd()), x_y, fmt='%s')
# InputCooList should have the following columns
SolutionsList = "{0}/solutions.txt".format(getcwd())
iraf.ccmap.setParam('images', image_path)
iraf.ccmap.setParam('input', "{0}/coords".format(getcwd()))
iraf.ccmap.setParam('database', SolutionsList)
iraf.ccmap.setParam('lngcolumn', 1)
iraf.ccmap.setParam('latcolumn', 2)
iraf.ccmap.setParam('xcolumn', 3)
iraf.ccmap.setParam('ycolumn', 4)
iraf.ccmap.setParam('results', "{0}/results".format(getcwd()))
iraf.ccmap.setParam('refsystem', 2015.0)
iraf.ccmap.setParam('insystem', 'icrs')
iraf.ccmap.setParam('update', 'yes')
iraf.ccmap(interactive='no')
system("rm -rf {0}/coords".format(getcwd()))
return_list = []
with open("{0}/results".format(getcwd())) as f:
for line in f:
if "Ra/Dec or Long/Lat fit rms:" in line:
rms_ra_dec = line.split()
rms_ra = rms_ra_dec[6]
rms_dec = rms_ra_dec[7]
return_list.append([rms_ra,
rms_dec,
"(arcsec arcsec)"])
if "(hours degrees)" in line:
ref_point = line.split()
ref_point_ra = ref_point[3]
ref_point_dec = ref_point[4]
return_list.append([ref_point_ra,
ref_point_dec,
"(hours degrees)"])
if "(pixels pixels)" in line:
ref_point = line.split()
ref_point_x = ref_point[3]
ref_point_y = ref_point[4]
return_list.append([ref_point_x,
ref_point_y,
"(pixels pixels)"])
if "X and Y scale:" in line:
pix_scale = line.split()
pix_scale_x = pix_scale[5]
pix_scale_y = pix_scale[6]
return_list.append([pix_scale_x,
pix_scale_y,
"(arcsec/pixel arcsec/pixel)"])
if "X and Y axis rotation:" in line:
axis_rotation = line.split()
axis_rotation_x = axis_rotation[6]
axis_rotation_y = axis_rotation[7]
return_list.append([axis_rotation_x,
axis_rotation_y,
"(degrees degrees)"])
if "Ra/Dec or Long/Lat wcs rms:" in line:
rms_ra_dec_wcs = line.split()
rms_ra_wcs = rms_ra_dec_wcs[6]
rms_dec_wcs = rms_ra_dec_wcs[7]
return_list.append([rms_ra_wcs,
rms_dec_wcs,
"(arcsec arcsec)"])
f.close()
ccmap_result = Table(return_list,
names=("Ra/Dec or Long/Lat fit rms",
"Reference point (RA, DEC)",
"Reference point (X, Y)",
"X and Y scale",
"X and Y axis rotation",
"Ra/Dec or Long/Lat wcs rms"))
if stdout:
with open("{0}/results".format(getcwd())) as f:
results = f.read()
print(results)
f.close()
return(ccmap_result["Ra/Dec or Long/Lat fit rms",
"Ra/Dec or Long/Lat wcs rms",
"Reference point (RA, DEC)",
"Reference point (X, Y)",
"X and Y scale",
"X and Y axis rotation"])
"""
def ppm_cor(self, ra, dec, pmRA, pmDE, odate):
"""
Compute stellar parallax corrections with given parameters.
@param ra: RA coordinate of object (in degrees).
@type ra: float
@param dec: DEC coordinate of object (in degrees).
@type dec: float
@param pmRA: Proper motion in right ascension µ_α* of
the source in ICRS at the reference epoch Epoch.
This is the projection of the proper motion vector
in the direction of increasing right ascension (in milliarcsec)