MGCS-pytools 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mcmc/__init__.py +0 -0
- mcmc/bivariate_normal.py +145 -0
- mcmc/legacy/multivariate_2d_posterior.py +102 -0
- mcmc/mcmc.py +211 -0
- mcmc/set_posterior.py +66 -0
- mcmc/utils.py +136 -0
- mgcs_pytools-0.1.0.dist-info/METADATA +25 -0
- mgcs_pytools-0.1.0.dist-info/RECORD +18 -0
- mgcs_pytools-0.1.0.dist-info/WHEEL +5 -0
- mgcs_pytools-0.1.0.dist-info/licenses/LICENSE +21 -0
- mgcs_pytools-0.1.0.dist-info/top_level.txt +3 -0
- statistical_membership/__init__.py +0 -0
- statistical_membership/cvt_grid.py +372 -0
- statistical_membership/dr_correction.py +347 -0
- statistical_membership/membership.py +473 -0
- statistical_membership/region_tools.py +53 -0
- utils/__init__.py +0 -0
- utils/plotting.py +916 -0
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import matplotlib.pyplot as plt
|
|
4
|
+
|
|
5
|
+
from shapely import (
|
|
6
|
+
Polygon,
|
|
7
|
+
Point,
|
|
8
|
+
plotting,
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
from scipy.interpolate import CubicSpline
|
|
12
|
+
from scipy.spatial import KDTree
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class createROI:
|
|
16
|
+
|
|
17
|
+
def __init__(self, points):
|
|
18
|
+
self.points = points
|
|
19
|
+
|
|
20
|
+
self.ax = None
|
|
21
|
+
self.fig = None
|
|
22
|
+
self.cid_MOUSE = None
|
|
23
|
+
self.cid_KEYBOARD = None
|
|
24
|
+
self.coords = []
|
|
25
|
+
self.polygon = None
|
|
26
|
+
self.points_in = None
|
|
27
|
+
self.patch = None
|
|
28
|
+
|
|
29
|
+
# generate fig
|
|
30
|
+
self.generate_fig()
|
|
31
|
+
|
|
32
|
+
# make plot
|
|
33
|
+
self.ax.scatter(self.points[:, 0], self.points[:, 1], marker=".", s=0.5, lw=0.1)
|
|
34
|
+
self.fig.canvas.draw()
|
|
35
|
+
plt.show()
|
|
36
|
+
|
|
37
|
+
def __call__(self, event):
|
|
38
|
+
|
|
39
|
+
# left click add vertices
|
|
40
|
+
if event.name == "button_press_event" and event.button == 1:
|
|
41
|
+
self.coords.append((event.xdata, event.ydata))
|
|
42
|
+
self.ax.scatter(
|
|
43
|
+
self.coords[-1][0], self.coords[-1][1], marker="o", c="blue", zorder=3
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
self.fig.canvas.draw()
|
|
47
|
+
self.fig.canvas.flush_events()
|
|
48
|
+
|
|
49
|
+
# spacebar create polygon
|
|
50
|
+
elif event.name == "key_press_event" and event.key == " ":
|
|
51
|
+
self.coords.append(self.coords[0]) # close polygon
|
|
52
|
+
self.polygon = Polygon(self.coords) # close polygon
|
|
53
|
+
self.points_in = self.polygon.contains(
|
|
54
|
+
[Point(x, y) for x, y in self.points]
|
|
55
|
+
)
|
|
56
|
+
self.ax.scatter(
|
|
57
|
+
self.points[self.points_in, 0],
|
|
58
|
+
self.points[self.points_in, 1],
|
|
59
|
+
marker=".",
|
|
60
|
+
s=0.5,
|
|
61
|
+
lw=0.5,
|
|
62
|
+
c="red",
|
|
63
|
+
zorder=3,
|
|
64
|
+
)
|
|
65
|
+
self.patch = plotting.patch_from_polygon(
|
|
66
|
+
self.polygon, color="gray", alpha=0.5
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
self.ax.add_patch(self.patch)
|
|
70
|
+
self.fig.canvas.draw()
|
|
71
|
+
self.fig.canvas.flush_events()
|
|
72
|
+
|
|
73
|
+
# c cancel the polygon
|
|
74
|
+
elif event.name == "key_press_event" and event.key == "c":
|
|
75
|
+
self.coords = []
|
|
76
|
+
self.polygon = None
|
|
77
|
+
self.patch = None
|
|
78
|
+
self.ax.clear()
|
|
79
|
+
self.ax.scatter(
|
|
80
|
+
self.points[:, 0],
|
|
81
|
+
self.points[:, 1],
|
|
82
|
+
marker=".",
|
|
83
|
+
s=0.5,
|
|
84
|
+
lw=0.5,
|
|
85
|
+
zorder=3,
|
|
86
|
+
)
|
|
87
|
+
self.fig.canvas.draw()
|
|
88
|
+
self.fig.canvas.flush_events()
|
|
89
|
+
|
|
90
|
+
# q close the intercative session
|
|
91
|
+
elif event.name == "key_press_event" and event.key == "q":
|
|
92
|
+
for c in [self.cid_KEYBOARD, self.cid_MOUSE]:
|
|
93
|
+
self.fig.canvas.mpl_disconnect(c)
|
|
94
|
+
plt.close(self.fig)
|
|
95
|
+
return
|
|
96
|
+
|
|
97
|
+
def generate_fig(self):
|
|
98
|
+
self.fig, self.ax = plt.subplots(layout="constrained")
|
|
99
|
+
self.cid_MOUSE = self.ax.figure.canvas.mpl_connect("button_press_event", self)
|
|
100
|
+
self.cid_KEYBOARD = self.ax.figure.canvas.mpl_connect("key_press_event", self)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
# params needed:
|
|
104
|
+
# rband1[float], exctiction law in band1
|
|
105
|
+
# rband2[float], exctiction law in band2
|
|
106
|
+
# RA[str], RA colname
|
|
107
|
+
# DEC[str], DEC colname
|
|
108
|
+
# TO_mag[float], Turn off mag
|
|
109
|
+
# TO_color[float], Turn off color
|
|
110
|
+
# nref[int], number of neighbors stars used as reference
|
|
111
|
+
# columns[dict[str]] columns name of the dataframe [X, Y, V, I, membership]
|
|
112
|
+
def compute_differential_reddening(
|
|
113
|
+
df: pd.DataFrame,
|
|
114
|
+
params: dict,
|
|
115
|
+
member_threshold=0.9,
|
|
116
|
+
calc_corr_threhsold=True,
|
|
117
|
+
roi=None,
|
|
118
|
+
plot=False,
|
|
119
|
+
) -> pd.DataFrame:
|
|
120
|
+
|
|
121
|
+
# setup E(B-V)
|
|
122
|
+
# exctintion laws
|
|
123
|
+
rband1 = 3.1 * params["rband1"]
|
|
124
|
+
rband2 = 3.1 * params["rband2"]
|
|
125
|
+
A_band1 = rband1
|
|
126
|
+
A_band2 = rband2
|
|
127
|
+
delta_A = A_band1 - A_band2
|
|
128
|
+
theta = np.arctan2(A_band1, delta_A)
|
|
129
|
+
|
|
130
|
+
# cluster related params
|
|
131
|
+
turn_off_mag = params["TO_mag"]
|
|
132
|
+
turn_off_color = params["TO_color"]
|
|
133
|
+
|
|
134
|
+
# closte neibourghs reference stars number used for correction
|
|
135
|
+
n_ref = params["nref"]
|
|
136
|
+
|
|
137
|
+
# dataframe columns name
|
|
138
|
+
# columns = params["columns"] # columns name
|
|
139
|
+
|
|
140
|
+
x = df[params["xcol"]].values # x
|
|
141
|
+
x_ref = df.loc[df["membership"] > member_threshold, params["xcol"]].values # x
|
|
142
|
+
y = df[params["ycol"]].values # y
|
|
143
|
+
y_ref = df.loc[df["membership"] > member_threshold, params["ycol"]].values # y
|
|
144
|
+
band1 = df[params["band1"]].values # calibrated magnitude in band 1 [mag]
|
|
145
|
+
band1_ref = df.loc[df["membership"] > member_threshold, params["band1"]].values
|
|
146
|
+
band2 = df[params["band2"]].values # calibrated magnitude in band 2 [mag]
|
|
147
|
+
band2_ref = df.loc[df["membership"] > member_threshold, params["band2"]].values
|
|
148
|
+
nstar = df.shape[0]
|
|
149
|
+
|
|
150
|
+
delta_E_B_V_init = df["delta_ebv"].values
|
|
151
|
+
|
|
152
|
+
band1_ini = band1.copy()
|
|
153
|
+
band2_ini = band2.copy()
|
|
154
|
+
|
|
155
|
+
color_obs = band1 - band2
|
|
156
|
+
color_obs_ref = band1_ref - band2_ref
|
|
157
|
+
median_delta_abs = np.zeros(nstar)
|
|
158
|
+
|
|
159
|
+
# start process
|
|
160
|
+
# translation (now the orband2gin of the reference frame is the MS TO)
|
|
161
|
+
band1_t = band1 - params["TO_mag"]
|
|
162
|
+
color_obs_t = color_obs - params["TO_color"]
|
|
163
|
+
|
|
164
|
+
band1_t_ref = band1_ref - params["TO_mag"]
|
|
165
|
+
color_obs_t_ref = color_obs_ref - params["TO_color"]
|
|
166
|
+
|
|
167
|
+
# rotation of the CMD (tilt the CMD along the direction of the reddening vector)
|
|
168
|
+
# in this new reference frame the reddening vector is parallel to the x axis
|
|
169
|
+
# A(lambda)/A(V) extinction coefficients for the two bands
|
|
170
|
+
abscissa = color_obs_t * np.cos(theta) + band1_t * np.sin(theta) # new X
|
|
171
|
+
ordinate = -color_obs_t * np.sin(theta) + band1_t * np.cos(theta) # new Y
|
|
172
|
+
abscissa_ref = color_obs_t_ref * np.cos(theta) + band1_t_ref * np.sin(
|
|
173
|
+
theta
|
|
174
|
+
) # new X
|
|
175
|
+
ordinate_ref = -color_obs_t_ref * np.sin(theta) + band1_t_ref * np.cos(
|
|
176
|
+
theta
|
|
177
|
+
) # new Y
|
|
178
|
+
|
|
179
|
+
if roi is None:
|
|
180
|
+
# spawn cmd widget to choose box
|
|
181
|
+
myROI = createROI(
|
|
182
|
+
np.vstack((abscissa_ref, ordinate_ref)).T
|
|
183
|
+
) # need to be blocking until selection
|
|
184
|
+
while True:
|
|
185
|
+
if myROI.points_in is not None:
|
|
186
|
+
break
|
|
187
|
+
poli = myROI.polygon
|
|
188
|
+
filter = myROI.points_in
|
|
189
|
+
else:
|
|
190
|
+
poli = Polygon(roi) if not isinstance(roi, Polygon) else roi
|
|
191
|
+
filter = poli.contains(
|
|
192
|
+
[Point(x, y) for x, y in zip(abscissa_ref, ordinate_ref)]
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
# _, ax = plt.subplots(layout="constrained")
|
|
196
|
+
# ax.scatter(abscissa, ordinate, marker=".", s=0.5, lw=0.1, zorder=2)
|
|
197
|
+
# plotting.plot_polygon(poli, ax=ax, color="gray", alpha=0.5, zorder=3)
|
|
198
|
+
# plt.show()
|
|
199
|
+
# Define MS stars
|
|
200
|
+
ms_ord = ordinate_ref[filter]
|
|
201
|
+
ms_abs = abscissa_ref[filter]
|
|
202
|
+
ms_x = x_ref[filter]
|
|
203
|
+
ms_y = y_ref[filter]
|
|
204
|
+
ms_band1 = band1_ref[filter]
|
|
205
|
+
nMS = len(ms_band1)
|
|
206
|
+
|
|
207
|
+
# here setup the iteration
|
|
208
|
+
ord_step = params["ord_step"] if "ord_step" in params else 0.1
|
|
209
|
+
ord_max = ms_ord.max()
|
|
210
|
+
ord_min = ms_ord.min()
|
|
211
|
+
n_step = (ord_max - ord_min) / ord_step
|
|
212
|
+
n_step = int(round(n_step))
|
|
213
|
+
|
|
214
|
+
# Define fiducial line
|
|
215
|
+
# calcolo running median nella box e faccio fit sulle mediane
|
|
216
|
+
median_ord = np.zeros(n_step)
|
|
217
|
+
median_abs = np.zeros(n_step)
|
|
218
|
+
|
|
219
|
+
for k in range(n_step):
|
|
220
|
+
ord_bin = ms_ord[
|
|
221
|
+
(ms_ord > ord_min + ord_step * k) & (ms_ord < ord_min + ord_step * (k + 1))
|
|
222
|
+
]
|
|
223
|
+
abs_bin = ms_abs[
|
|
224
|
+
(ms_ord > ord_min + ord_step * k) & (ms_ord < ord_min + ord_step * (k + 1))
|
|
225
|
+
]
|
|
226
|
+
median_ord[k] = np.percentile(ord_bin, 50)
|
|
227
|
+
median_abs[k] = np.percentile(abs_bin, 50)
|
|
228
|
+
|
|
229
|
+
# faccio il fit
|
|
230
|
+
interp_ord = CubicSpline(median_ord, median_abs)
|
|
231
|
+
fiducial_line_ord_all = interp_ord(ms_ord)
|
|
232
|
+
# interp_abs = CubicSpline(median_abs, median_ord)
|
|
233
|
+
# fiducial_line_abs_all = interp_abs(ms_abs)
|
|
234
|
+
|
|
235
|
+
if plot:
|
|
236
|
+
_, ax = plt.subplots(layout="constrained")
|
|
237
|
+
ax.scatter(
|
|
238
|
+
ms_abs,
|
|
239
|
+
ms_ord,
|
|
240
|
+
marker="x",
|
|
241
|
+
s=2,
|
|
242
|
+
lw=0.5,
|
|
243
|
+
color="orange",
|
|
244
|
+
label="reference stars",
|
|
245
|
+
zorder=3,
|
|
246
|
+
)
|
|
247
|
+
xlim = ax.get_xlim()
|
|
248
|
+
ylim = ax.get_ylim()
|
|
249
|
+
ax.scatter(
|
|
250
|
+
abscissa_ref[filter],
|
|
251
|
+
ordinate_ref[filter],
|
|
252
|
+
marker=".",
|
|
253
|
+
s=2,
|
|
254
|
+
lw=1,
|
|
255
|
+
color="black",
|
|
256
|
+
label="all stars",
|
|
257
|
+
zorder=2,
|
|
258
|
+
)
|
|
259
|
+
ax.plot(
|
|
260
|
+
fiducial_line_ord_all[np.argsort(ms_ord)],
|
|
261
|
+
np.sort(ms_ord),
|
|
262
|
+
color="red",
|
|
263
|
+
lw=1,
|
|
264
|
+
label="Fiducial line",
|
|
265
|
+
zorder=3,
|
|
266
|
+
)
|
|
267
|
+
ax.set(xlim=xlim, ylim=ylim, xlabel="abscissa", ylabel="ordinate")
|
|
268
|
+
# ax.set(ylim=(-3, 1))
|
|
269
|
+
ax.invert_xaxis()
|
|
270
|
+
ax.legend()
|
|
271
|
+
# plt.show(block=False)
|
|
272
|
+
plt.draw()
|
|
273
|
+
plt.pause(1.0)
|
|
274
|
+
|
|
275
|
+
########## STEP 5: search for nearest neighbours ##############
|
|
276
|
+
# define the set of reference coordinates (to build the tree) and the set of points (to look for k neighbours)
|
|
277
|
+
ref_coord = [[ms_x[k], ms_y[k]] for k in range(nMS)]
|
|
278
|
+
points = [[x[k], y[k]] for k in range(nstar)]
|
|
279
|
+
|
|
280
|
+
# KDTree
|
|
281
|
+
tree = KDTree(ref_coord)
|
|
282
|
+
|
|
283
|
+
# number of reference stars
|
|
284
|
+
_, indices = tree.query(points, k=n_ref + 1)
|
|
285
|
+
|
|
286
|
+
########## STEP 6: obtain median delta abscissa in the reference stars ##############
|
|
287
|
+
ref_fiducial_line_ord_all = fiducial_line_ord_all[
|
|
288
|
+
(ms_ord <= ord_max) & (ms_ord >= ord_min)
|
|
289
|
+
]
|
|
290
|
+
|
|
291
|
+
# compute delta abscissa
|
|
292
|
+
delta_abscissa = ms_abs - ref_fiducial_line_ord_all
|
|
293
|
+
for k in range(nstar):
|
|
294
|
+
delta_abs_ref = delta_abscissa[indices[k, 1:]]
|
|
295
|
+
|
|
296
|
+
# sigma clip in the eference stars delta abscissa distrband2bution
|
|
297
|
+
delta_abs_ref_sigma_clip = delta_abs_ref[
|
|
298
|
+
(delta_abs_ref < np.median(delta_abs_ref) + 2 * np.std(delta_abs_ref))
|
|
299
|
+
& (delta_abs_ref > np.median(delta_abs_ref) - 2 * np.std(delta_abs_ref))
|
|
300
|
+
]
|
|
301
|
+
|
|
302
|
+
# get median value
|
|
303
|
+
median_delta_abs[k] = np.percentile(delta_abs_ref_sigma_clip, 50)
|
|
304
|
+
|
|
305
|
+
########## STEP 8: compute new magnitudes ##############
|
|
306
|
+
# abscissa = abscissa - median_delta_abs
|
|
307
|
+
abscissa_eval = abscissa - median_delta_abs
|
|
308
|
+
|
|
309
|
+
color_obs_t = abscissa_eval * np.cos(theta) - ordinate * np.sin(theta)
|
|
310
|
+
band1_t = abscissa_eval * np.sin(theta) + ordinate * np.cos(theta)
|
|
311
|
+
|
|
312
|
+
color_obs = color_obs_t + turn_off_color
|
|
313
|
+
band1_eval = band1_t + turn_off_mag
|
|
314
|
+
band2_eval = band1_eval - color_obs
|
|
315
|
+
|
|
316
|
+
########## STEP 9: evaluation of the differential reddening ##############
|
|
317
|
+
if calc_corr_threhsold:
|
|
318
|
+
A_band1_star = band1_ini - band1_eval
|
|
319
|
+
A_band2_star = band2_ini - band2_eval
|
|
320
|
+
delta_e_v_band = A_band1_star - A_band2_star
|
|
321
|
+
delta_E_B_V = delta_e_v_band / ((rband1 - rband2))
|
|
322
|
+
corr_threshold = 2 * np.std(delta_E_B_V)
|
|
323
|
+
print(f"correction threshold at: {corr_threshold:.3f}")
|
|
324
|
+
band1 = np.where(
|
|
325
|
+
np.logical_and(np.abs(delta_E_B_V) > corr_threshold, delta_E_B_V_init != 0),
|
|
326
|
+
band1_eval,
|
|
327
|
+
band1,
|
|
328
|
+
)
|
|
329
|
+
band2 = np.where(
|
|
330
|
+
np.logical_and(np.abs(delta_E_B_V) > corr_threshold, delta_E_B_V_init != 0),
|
|
331
|
+
band2_eval,
|
|
332
|
+
band2,
|
|
333
|
+
)
|
|
334
|
+
# delta_E_B_V = np.where(np.abs(delta_E_B_V) > corr_threshold, delta_E_B_V, 0.0)
|
|
335
|
+
# I = V - color_obs
|
|
336
|
+
|
|
337
|
+
else:
|
|
338
|
+
band1 = band1_eval
|
|
339
|
+
band2 = band2_eval
|
|
340
|
+
|
|
341
|
+
########## STEP 10: compute differential reddening ##############
|
|
342
|
+
A_band1_star = band1_ini - band1
|
|
343
|
+
A_band2_star = band2_ini - band2
|
|
344
|
+
delta_e_v_band = A_band1_star - A_band2_star
|
|
345
|
+
delta_E_B_V = delta_e_v_band / ((rband1 - rband2))
|
|
346
|
+
|
|
347
|
+
return band1, band2, delta_E_B_V, poli
|