-
Notifications
You must be signed in to change notification settings - Fork 2
/
SC_exoplanet.py
217 lines (190 loc) · 7.72 KB
/
SC_exoplanet.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
#!/usr/bin/env python
# -*- coding: utf8 -*-
#
# Example:
# python SC_exoplanet_v2.py teq0 sma -z metal -lx -ly -o star teq0 sma metal -t aaa.rdb
#
# My imports
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
try:
import seaborn as sns
sns.set_style('dark')
sns.set_context('talk', font_scale=1.2)
color = sns.color_palette()
except ImportError:
print('Install seaborn for better plots (optional): pip install seaborn')
color = 'b,g,r,m,y,k'.split(',')
try:
import pandas as pd
except ImportError:
raise ImportError('Install pandas: pip install pandas')
from PyAstronomy import pyasl
import argparse
def radTorres(teff, erteff, logg, erlogg, feh, erfeh):
ntrials = 100
randomteff = teff + erteff*np.random.randn(ntrials)
randomlogg = logg + erlogg*np.random.randn(ntrials)
randomfeh = feh + erfeh*np.random.randn(ntrials)
# Parameters for the Torres calibration:
b1, b2, b3 = 2.4427, 0.6679, 0.1771
b4, b5, b6 = 0.705, -0.21415, 0.02306
b7 = 0.04173
logR = np.zeros(ntrials)
for i in range(ntrials):
X = np.log10(randomteff[i]) - 4.1
logR[i] = b1 + b2*X + b3*X**2 + b4*X**3 + b5*randomlogg[i]**2 + b6*randomlogg[i]**3 + b7*randomfeh[i]
meanRadlog = np.mean(logR)
sigRadlog = np.sqrt(np.sum((logR-meanRadlog)**2))/(ntrials-1)
sigRadlogTot = np.sqrt(0.014**2 + sigRadlog**2)
meanRad = 10**meanRadlog
sigRad = 10**(meanRadlog + sigRadlogTot) - meanRad
return meanRad, sigRad
def _parser():
parser = argparse.ArgumentParser(description='Preprocess the results')
sc = pyasl.SWEETCat()
sc = sc.data
eu = pyasl.ExoplanetEU()
eu = eu.getAllData()
eu = pd.DataFrame(eu)
p = list(sc.columns) + list(eu.columns) + ['teq0', 'mass', 'masserr', 'radius', 'radiuserr', 'lum']
parser.add_argument('x', choices=p)
parser.add_argument('y', choices=p)
parser.add_argument('-z', help='Color scale', choices=p, default=None)
parser.add_argument('-i', '--input', help='File name of result file', default='results.csv')
parser.add_argument('-c', '--convergence', help='Only plot converged results', default=True, action='store_false')
parser.add_argument('-ix', help='Inverse x axis', default=False, action='store_true')
parser.add_argument('-iy', help='Inverse y axis', default=False, action='store_true')
parser.add_argument('-lx', help='Logarithmic x axis', default=False, action='store_true')
parser.add_argument('-ly', help='Logarithmic y axis', default=False, action='store_true')
parser.add_argument('-o', '--output', help='Save a list of arguments to exoplanets.csv', nargs='+')
parser.add_argument('-t', '--table', help='Table to intercept. Column name must be "star"')
args = parser.parse_args()
return args
if __name__ == '__main__':
args = _parser()
# Prepare the SWEET-Cat data
print('Downloading the data from SWEET-Cat...')
sc = pyasl.SWEETCat()
sc.downloadData()
sc = sc.data
newname = [x.lower().replace(' ', '') for x in sc.star] # Put name lower and remove all spaces
newname = list(map(str.strip, newname)) # Remove all newline or tab characters
sc['nameNew'] = newname
# Prepare the exoplanetEU data
print('Downloading the data from exoplanetEU...')
eu = pyasl.ExoplanetEU()
eu = eu.getAllData()
eu = pd.DataFrame(eu) # Convert the structure to a DataFrame
newstname = [x.lower().replace(' ', '') for x in eu.stName] # Put name lower and remove all spaces
newstname = list(map(str.strip, newstname)) # Remove all newline or tab characters
eu['stNameNew'] = newstname
# Merge the two based on the stellar name
print(1)
df = pd.merge(left=sc, right=eu, left_on='nameNew', right_on='stNameNew')
print(2)
df.rename(columns={'ra_x': 'ra', 'dec_x': 'dec'}, inplace=True)
# Calculate radius and luminosity
rr = ['radius', 'radiuserr', 'teq0']
if (args.x in rr) or (args.y in rr) or (args.z in rr):
params = list(zip(df.teff, df.erteff, df.logg, df.erlogg, df.metal, df.ermetal))
print(3)
r = [radTorres(t, et, l, el, f, ef) for t, et, l, el, f, ef in params]
# Insert the radius, and luminosity in the table
print(4)
df['radius'] = pd.Series(np.asarray(r)[:, 0])
df['radiuserr'] = pd.Series(np.asarray(r)[:, 1])
# Compute Teq0:
df['teq0'] = df.teff*((df.radius*700000.)/(2.*df.sma*150000000.))**(0.5)
df['lum'] = (df.teff/5777.)**4 * df.mass
# Intersect the table df with the list of stars in file aaa.rdb
if args.table:
tt = pd.read_csv(args.table)
df2 = pd.merge(left=tt, right=df, left_on='planet', right_on='plName', how='inner')
df = df2
plt.figure()
if args.z:
z = df[args.z].values
color = df[args.z].values
z[np.isnan(z)] = min(z[~np.isnan(z)])
size = (z-z.min())/(z.max()-z.min())*100
size[np.argmin(size)] = 10 # Be sure to see the "smallest" point
plt.scatter(df[args.x], df[args.y], c=color, s=size, cmap=cm.seismic)
else:
plt.scatter(df[args.x], df[args.y], c=color[0], s=40)
labels = {'teff': r'$T_\mathrm{eff}$ [K]',
'tefferr': r'$\sigma T_\mathrm{eff}$ [K]',
'stTeff': r'$T_\mathrm{eff}$ [K]',
'logg': r'$\log(g)$ [cgs]',
'logglc': r'$\log(g)$ [cgs]',
'loggerr': r'\sigma $\log(g)$ [cgs]',
'erlogglc': r'\sigma $\log(g)$ [cgs]',
'metal': '[Fe/H]',
'ermetal': r'$\sigma$ [Fe/H]',
'vt': r'$\xi_\mathrm{micro}$ [km/s]',
'vterr': r'$\sigma\xi_\mathrm{micro}$ [km/s]',
'lum': r'$L_\odot$',
'mass': r'$M_\odot$',
'ermass': r'$\sigma M_\odot$',
'stMass': r'$M_\odot$',
'stRadius': r'$R_\odot$',
'sma': 'Semi major axis [AU]',
'vmag': 'V magnitude',
'ervmag': 'Error on V magnitude',
'par': 'Parallax ["]',
'erpar': 'Error on parallax ["]',
'plMass': r'Planet mass [$M_\mathrm{Jup}$]',
'plRadius': r'Planet radius [$R_\mathrm{Jup}$]',
'period': 'Period [day]',
'eccentricity': 'Eccentricity',
'inclination': 'Inclination [degree]',
'angDistance': 'Angular distance [arcsec]',
'discovered': 'Discovered [year]',
'omega': r'$\Omega$ [degree]',
'tperi': 'Time of periastron [JD]',
'mag_v': 'V mag',
'mag_i': 'I mag',
'mag_j': 'J mag',
'mag_h': 'H mag',
'mag_k': 'K mag',
'dist': 'Distance [pc]',
'mh': 'Metallicity',
'stAge': 'Stellar age [Gyr]'}
try:
plt.xlabel(labels[args.x])
except KeyError:
plt.xlabel(args.x)
try:
plt.ylabel(labels[args.y])
except KeyError:
plt.ylabel(args.y)
if args.z:
cbar = plt.colorbar()
try:
cbar.set_label(labels[args.z])
except KeyError:
cbar.set_label(args.z)
if args.lx:
plt.xscale('log')
if args.ly:
plt.yscale('log')
if args.ix:
plt.xlim(plt.xlim()[::-1])
if args.iy:
plt.ylim(plt.ylim()[::-1])
plt.tight_layout()
plt.grid(True)
plt.show()
if args.output:
try:
dfout = df[args.output]
except KeyError:
for key in args.output:
try:
_ = df[key]
except KeyError:
print('Invalid name: %s' % key)
raise SystemExit()
dfout.to_csv('exoplanets.csv', sep='\t', index=False, na_rep='...')
print('Saved result in exoplanet.csv')