forked from gerhajdu/pyfiner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyfiner.py
executable file
·207 lines (157 loc) · 9.74 KB
/
pyfiner.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
"""
PyFiNeR: Fitting Near-infrared RR Lyrae light curves
This routine implements the RR Lyrae near-infrared light curve fitting techniques
described in Hajdu et al. (2018)
The K-band light curve are fit with the Fourier transformed principal components
coefficients; the H-band data is fit with the same light-curve shape; the shape
of the J-band light curve is approximated with the K-band principal component
amplitudes.
This code is a fork of: github.com/gerhajdu/pyfiner .
Forked and rewritten by Istvan Dekany (2022).
What's new:
- Restructured code following PEP, with improved modularity and readibility
- All previous bugs leading to memory overflow by matplotlib were eliminated.
- The code computes uncertainties with bias corrections for small sample sizes.
- All algorithm parameters can be set on the command line or using an external parameter file.
- The list of input time series can be specified by a list file.
- Period fitting can be turned off.
"""
import matplotlib as mpl
import matplotlib.pyplot as plt
from pyfiner_util import *
plt.ioff()
plt.style.use('seaborn-dark-palette')
if __name__ == '__main__':
# ----------------------------------------------------------------------------------------------------------------------
# COMMAND-LINE PARAMETERS:
# Read parameters from a file or from the command line:
parser = argparser()
if len(sys.argv) == 1:
# use default name for the parameter file
pars = parser.parse_args([default_parameter_file])
else:
pars = parser.parse_args()
# ----------------------------------------------------------------------------------------------------------------------
if not pars.fit_period:
pars.per_ival = 10e-8
phase_grid = np.linspace(-0.01, 2.01, 202)
# Read input list file with object ID' and periods:
inputlist = np.genfromtxt(os.path.join(pars.rootdir, pars.input_list), dtype=['S30', 'f8'], unpack=False,
comments='#', filling_values=np.nan, names=True)
identifiers = inputlist['id'].astype(str).reshape(-1, )
n_object = len(identifiers)
periods = inputlist['period'].reshape(-1, )
print(
"# ID period meanK_mag meanK_int nJ meanJ_mag wmean_J_mag std_J_mag wmean_J_int std_J_int median_J_mag "
"median_J_int nH meanH_mag wmean_H_mag std_H_mag wmean_H_int std_H_int median_H_mag median_H_int "
"U1 U2 U3 U4 RMSE COST COSTN N_final N_initial")
fig, axes = plt.subplots(3, sharex=True)
for ilc, (identifier, period) in enumerate(zip(identifiers, periods)):
# Define input / output:
k_lightcurve_path = os.path.join(pars.rootdir, pars.k_lc_dir, str(identifiers[ilc].astype(str)) + pars.k_lc_suffix)
j_lightcurve_path = os.path.join(pars.rootdir, pars.j_lc_dir, str(identifiers[ilc].astype(str)) + pars.j_lc_suffix)
h_lightcurve_path = os.path.join(pars.rootdir, pars.h_lc_dir, str(identifiers[ilc].astype(str)) + pars.h_lc_suffix)
figure_path = os.path.join(pars.rootdir, pars.plotdir, str(identifiers[ilc].astype(str)) + pars.figname_suffix)
# Initialize list for Julian date minima in K,J,H:
jd_min = []
# Initialize dictionary for results:
results = {}
# ------------------------------------------------------------------------------------------------------------------
# Read in the K-band light curve:
if os.path.isfile(k_lightcurve_path):
k_lightcurve = np.loadtxt(k_lightcurve_path, unpack=True)
jd_min.append(np.min(k_lightcurve[0]))
else:
# There is no light-curve file for this object, go to next object.
mywarn(k_lightcurve_path + " not found, object {} was skipped.".format(identifier))
continue
# ------------------------------------------------------------------------------------------------------------------
# Read in the J-band light curve:
j_lightcurve = None
if os.path.isfile(j_lightcurve_path):
j_lightcurve = np.loadtxt(j_lightcurve_path, unpack=True)
if j_lightcurve.size > 0:
if len(j_lightcurve.shape) == 1:
j_lightcurve = j_lightcurve.reshape(-1, 1)
jd_min.append(np.min(j_lightcurve[0]))
else:
j_lightcurve = None
# ------------------------------------------------------------------------------------------------------------------
# Read in the H-band light curve:
h_lightcurve = None
if os.path.isfile(h_lightcurve_path):
h_lightcurve = np.loadtxt(h_lightcurve_path, unpack=True)
if h_lightcurve.size > 0:
if len(h_lightcurve.shape) == 1:
h_lightcurve = h_lightcurve.reshape(-1, 1)
jd_min.append(np.min(h_lightcurve[0]))
else:
h_lightcurve = None
jd0 = int(np.min(jd_min)) - 2
# ------------------------------------------------------------------------------------------------------------------
# Initialize the figure:
fig.set_size_inches(9, 10)
fig.subplots_adjust(hspace=0.11)
for ax in axes:
ax.tick_params(axis='both', direction='in')
ax.invert_yaxis()
ax.set_xlim(-0.01, 2.01)
ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.1))
axes[0].set_ylabel('$K_s$')
axes[1].set_ylabel('$H$')
axes[2].set_ylabel('$J$')
# ------------------------------------------------------------------------------------------------------------------
# Fit the K light curve:
results['K'] = fit_lightcurve(k_lightcurve, jd0, period, phase_grid,
pars.min_mag, pars.max_mag, pars.median_cut, pars.per_ival,
pars.sigma_threshold, pars.n_restarts)
# ------------------------------------------------------------------------------------------------------------------
# Plot the K light curve:
axes[0].plot(results['K']['phases_obs'], results['K']['magnitudes'], 'r.')
axes[0].plot(results['K']['phases_obs'] + 1, results['K']['magnitudes'], 'r.')
axes[0].plot(results['K']['phases_obs'], results['K']['magnitudes'], 'b.')
axes[0].plot(results['K']['phases_obs'] + 1, results['K']['magnitudes'], 'b.')
axes[0].plot(phase_grid, results['K']['fitted_shape'], 'r-', lw=2)
# ------------------------------------------------------------------------------------------------------------------
# Predict the J and H light curves:
results['J'] = predict_lightcurve('J', j_lightcurve, jd0, results['K'], phase_grid)
results['H'] = predict_lightcurve('H', h_lightcurve, jd0, results['K'], phase_grid)
# ------------------------------------------------------------------------------------------------------------------
# Plot the J light curve:
if j_lightcurve is not None:
axes[2].plot(phase_grid, results['J']['predicted_shape'] + results['J']['mag_mean'], 'k-', lw=2)
axes[2].plot(phase_grid, results['J']['predicted_shape'] + results['J']['mag_median'], 'k--', lw=2)
axes[2].plot(results['J']['phases'], j_lightcurve[1], 'b.', ms=15.0)
axes[2].plot(results['J']['phases'] + 1, j_lightcurve[1], 'b.', ms=15.0)
# ------------------------------------------------------------------------------------------------------------------
# Plot the H light curve:
if h_lightcurve is not None:
axes[1].plot(phase_grid, results['H']['predicted_shape'] + results['H']['mag_mean'], 'k-', lw=2)
axes[1].plot(phase_grid, results['H']['predicted_shape'] + results['H']['mag_median'], 'k--', lw=2)
axes[1].plot(results['H']['phases'], h_lightcurve[1], 'b.', ms=15.0)
axes[1].plot(results['H']['phases'] + 1, h_lightcurve[1], 'b.', ms=15.0)
# ------------------------------------------------------------------------------------------------------------------
# Create figure header:
textstr = '{:10s} P: {:9.7f} N: {:d} ({:d})\n'\
.format(identifier, results['K']['regression'].x[2], k_lightcurve.shape[1], results['K']['n_data_initial'])
textstr += 'RMSE: {:6.4f} cost: {:6.4f} cost/N: {:8.6f}\n'\
.format(results['K']['rmse'], results['K']['cost'], results['K']['cost/N'])
textstr += '<K> = {:6.3f} <J> = {:6.3f} +/- {:.3f} <H> = {:6.3f} +/- {:.3f} (mag. mean)\n'\
.format(results['K']['intercept'], results['J']['mag_wmean'], results['J']['mag_std'],
results['H']['mag_wmean'], results['H']['mag_std'])
textstr += '<K> = {:6.3f} <J> = {:6.3f} +/- {:.3f} <H> = {:6.3f} +/- {:.3f} (int. mean)'\
.format(results['K']['int_mean'], results['J']['int_wmean'], results['J']['int_std'],
results['H']['int_wmean'], results['H']['int_std'])
props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
axes[0].text(.02, 1.04, textstr, fontsize=11,
horizontalalignment='left', verticalalignment='bottom',
bbox=props,
transform=axes[0].transAxes)
# ------------------------------------------------------------------------------------------------------------------
# Save and clear figure:
plt.savefig(figure_path + '.' + pars.figformat, bbox_inches='tight', format=pars.figformat)
for axis in axes:
axis.clear()
# ------------------------------------------------------------------------------------------------------------------
# Print the next row of the results table to the stdout:
print_results(identifier, results)