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.
@@ -0,0 +1,473 @@
1
+ import numpy as np
2
+ from math import modf
3
+
4
+ from pandas import DataFrame
5
+
6
+ import matplotlib.pyplot as plt
7
+
8
+ from astropy.coordinates import SkyCoord
9
+ import astropy.units as u
10
+
11
+ from shapely import (
12
+ Polygon,
13
+ Point,
14
+ union,
15
+ difference,
16
+ intersection,
17
+ )
18
+
19
+ from scipy.spatial import ConvexHull
20
+
21
+ from .dr_correction import compute_differential_reddening
22
+ from .cvt_grid import cvtGrid
23
+ from .region_tools import get_regions_count, get_pts_in_regions
24
+
25
+ import sys
26
+
27
+ # sys.path.append("..") # add parent directory to path
28
+ from ..mcmc.utils import plotting as utplot
29
+
30
+ #
31
+ #
32
+ # !!!!!!!! THIS CODE IS STILL UNDER DEVELOPMENT !!!!!!!!
33
+ #
34
+ #
35
+
36
+
37
+ def spatial_groupby(
38
+ df_cluster: DataFrame, df_field: DataFrame, racol: str, deccol: str, minstars=200
39
+ ):
40
+ """Group stars in the cluster dataframe by their spatial location.
41
+ The grouping is done by creating concentric annuli around the center of the
42
+ cluster and dividing each annulus in regions with at least minstars stars.
43
+
44
+ Args:
45
+ df_cluster: DataFrame
46
+ DataFrame containing the cluster stars.
47
+ df_field: DataFrame
48
+ DataFrame containing the field stars.
49
+ racol: str
50
+ Name of the column containing the RA of the stars.
51
+ deccol: str
52
+ Name of the column containing the DEC of the stars.
53
+ minstars: int, optional
54
+ Minimum number of stars in each region. Default is 200.
55
+
56
+ Returns:
57
+ groups: list of DataFrame
58
+ List of DataFrames, each containing the stars in a region.
59
+ subfovs: list of Polygon
60
+ List of Polygons, each containing the area of a region.
61
+ fov: Polygon
62
+ Polygon containing the area of the instrument FoV.
63
+ """
64
+
65
+ # Calculate the field star density and the min area for at least min stars
66
+ ra_center = (
67
+ df_field[racol].min() + (df_field[racol].max() - df_field[racol].min()) / 2
68
+ )
69
+ dec_center = (
70
+ df_field[deccol].min() + (df_field[deccol].max() - df_field[deccol].min()) / 2
71
+ )
72
+
73
+ field_center = SkyCoord(ra_center, dec_center, unit=u.deg)
74
+
75
+ df_field.loc[:, "center_sep"] = field_center.separation(
76
+ SkyCoord(
77
+ df_field[racol],
78
+ df_field[deccol],
79
+ unit="deg",
80
+ )
81
+ ).arcsec
82
+
83
+ area_conversion = 3600**2
84
+ star_density = df_field.shape[0] / (np.pi * df_field["center_sep"].max() ** 2)
85
+ min_stars = minstars
86
+ min_area = min_stars / star_density
87
+
88
+ print(
89
+ f"Star density: {star_density:.2f} stars / arcsec^2",
90
+ f"Min area for at least {min_stars} stars: {min_area:.2f} arcsec^2",
91
+ )
92
+
93
+ # groupby the cluster datafram in bin with at least minstars
94
+ ra_center = (
95
+ df_cluster[racol].min()
96
+ + (df_cluster[racol].max() - df_cluster[racol].min()) / 2
97
+ )
98
+ dec_center = (
99
+ df_cluster[deccol].min()
100
+ + (df_cluster[deccol].max() - df_cluster[deccol].min()) / 2
101
+ )
102
+
103
+ # make the FoV polygon from coordinates
104
+ hull = ConvexHull(df_cluster.loc[:, [racol, deccol]].values)
105
+ fov = Polygon(hull.points[hull.vertices])
106
+
107
+ dr = 1 / 3600
108
+ r = dr
109
+ subfovs = [Point(ra_center, dec_center)]
110
+
111
+ # iterating by increasing the annulus radius
112
+ while True:
113
+
114
+ # make annulus by subtraction wrt the last subfov
115
+ subfov = Point(ra_center, dec_center).buffer(r)
116
+
117
+ if subfov.contains(fov):
118
+ break # max fov exceeded
119
+ elif (
120
+ intersection(difference(subfov, subfovs[-1]), fov).area
121
+ > min_area / area_conversion
122
+ ):
123
+ pol = intersection(difference(subfov, subfovs[-1]), fov)
124
+ subfovs.append(subfov)
125
+ r += dr
126
+
127
+ subfovs[-1] = union(intersection(fov, subfovs[-1]), difference(fov, subfovs[-1]))
128
+ subfovs = [difference(subfovs[i], subfovs[i - 1]) for i in range(1, len(subfovs))]
129
+
130
+ # TODO: This part need to be change using pandas groupby
131
+ groups = []
132
+ for subf in subfovs:
133
+ group = df_cluster[
134
+ df_cluster.apply(lambda x: Point(x[racol], x[deccol]).within(subf), axis=1)
135
+ ].copy()
136
+ groups.append(group)
137
+
138
+ return groups, subfovs, fov
139
+
140
+
141
+ def get_membership(
142
+ cell_counts: list[tuple[int, int]],
143
+ cell_points: list[tuple[int, list[Point]]],
144
+ common_regions: list[int],
145
+ iter=1000,
146
+ fov_ratio=1.0,
147
+ ) -> np.ndarray:
148
+ """Get the membership of each stars thorugh iterative random extractions.
149
+
150
+ Args:
151
+ cell_counts: list of tuple(int, int)
152
+ List of tuples containing the region id and the number of field stars
153
+ in that region.
154
+ cell_points: list of tuple(int, list of Point)
155
+ List of tuples containing the region id and the list of Points
156
+ corresponding to the cluster stars in that region.
157
+ common_regions: list of int
158
+ List of region ids that are common between the field and cluster
159
+ stars.
160
+ iter: int, optional
161
+ Number of iterations to perform. Default is 1000.
162
+ fov_ratio: float, optional
163
+ Ratio between the instrument FoV and the sub-FoV area.
164
+ Default is 1.0.
165
+
166
+ Returns:
167
+ membership: np.ndarray
168
+ Array of shape (N, 2) containing the star index and its membership
169
+ probability.
170
+ """
171
+
172
+ cell_counts_points = [
173
+ (
174
+ [count for rrid, count in cell_counts if rrid == rid][0],
175
+ [pts for rrid, pts in cell_points if rrid == rid][0],
176
+ )
177
+ for rid in common_regions
178
+ ]
179
+
180
+ # initialize extractions vector
181
+ extractions = np.full(
182
+ iter * np.sum([count for count, _ in cell_counts_points]),
183
+ fill_value=-1,
184
+ dtype=int,
185
+ )
186
+
187
+ c = 0
188
+ for _ in range(iter):
189
+ for count, pts in cell_counts_points:
190
+ # rescaling the counts
191
+ new_count = count * fov_ratio
192
+ if new_count < 1.0:
193
+ new_count = np.random.choice(
194
+ np.array([0, 1]), p=[1 - new_count, new_count]
195
+ )
196
+ else:
197
+ p, bias = modf(new_count)
198
+ new_count = int(bias) + np.random.choice(np.array([0, 1]), p=[1 - p, p])
199
+
200
+ if len(pts) > new_count:
201
+ extractions[c : c + new_count] = np.random.choice(
202
+ pts, new_count, replace=False
203
+ )
204
+ c += new_count
205
+ else:
206
+ extractions[c : c + (len(pts))] = list(pts)
207
+ c += len(pts)
208
+
209
+ extractions = extractions[extractions != -1]
210
+ extractions = sorted(extractions)
211
+ unique_id = np.unique(extractions)
212
+ bincount = np.bincount(extractions)
213
+ bincount = bincount[bincount > 0]
214
+
215
+ membership = np.vstack((unique_id, bincount)).T
216
+ res = [1 - count / iter for _, count in membership]
217
+
218
+ membership = np.array(membership).astype(float)
219
+ membership[:, 1] = res
220
+
221
+ return membership
222
+
223
+
224
+ def do_statistical_membership(
225
+ df_cluster_input: DataFrame,
226
+ df_field_input: DataFrame,
227
+ field_mag_col: list[str],
228
+ dr_params: dict[str, str],
229
+ member_threshold: float = 0.8,
230
+ minstars: int = 200,
231
+ racol: str = "RA",
232
+ deccol: str = "DEC",
233
+ process_iter: int = 3,
234
+ min_star_per_cell: int = 3,
235
+ membership_iter: int = 1000,
236
+ fov_ratio: float = 1.0,
237
+ roi: list[float] | None = None,
238
+ plot_dred: bool = False,
239
+ plot_voronoi: bool = False,
240
+ which_voronoi: str = "dilation",
241
+ do_dilation: bool = True,
242
+ ) -> DataFrame:
243
+ """Compute the statistical membership of stars in a cluster field.
244
+
245
+ Args:
246
+ df_cluster_input: DataFrame
247
+ DataFrame containing the cluster stars.
248
+ df_field_input: DataFrame
249
+ DataFrame containing the field stars.
250
+ field_mag_col: list of str
251
+ List containing the names of the columns with the magnitudes
252
+ to use for the CMD (color, mag).
253
+ dr_params: dict of str
254
+ Dictionary containing the names of the columns with the magnitudes
255
+ to use for the differential reddening correction.
256
+ Example: {"band1": "F606W", "band2": "F814W"}
257
+ member_threshold: float, optional
258
+ Membership threshold to consider a star as a member of the cluster.
259
+ Default is 0.8.
260
+ minstars: int, optional
261
+ Minimum number of stars in each region. Default is 200.
262
+ racol: str, optional
263
+ Name of the column containing the RA of the stars. Default is "RA".
264
+ deccol: str, optional
265
+ Name of the column containing the DEC of the stars. Default is "DEC".
266
+ process_iter: int, optional
267
+ Number of iterations to perform. Default is 3.
268
+ min_star_per_cell: int, optional
269
+ Minimum number of stars per Voronoi cell. Default is 3.
270
+ membership_iter: int, optional
271
+ Number of iterations to perform for the membership calculation.
272
+ Default is 1000.
273
+ fov_ratio: float, optional
274
+ Ratio between the instrument FoV and the sub-FoV area.
275
+ Default is 1.0.
276
+ roi: list of float or None, optional
277
+ List containing the vertices of a polygon to use as region of interest
278
+ for the differential reddening correction.
279
+ Example: [x1, y1, x2, y2, ..., xn, yn]
280
+ If None, no region of interest will be used. Default is None.
281
+ plot_dred: bool, optional
282
+ If True, plot the differential reddening correction results.
283
+ Default is False.
284
+ plot_voronoi: bool, optional
285
+ If True, plot the Voronoi grid used for the membership calculation.
286
+ Default is False.
287
+ which_voronoi: str, optional
288
+ Type of Voronoi grid to use. Options are "standard" and "dilation".
289
+ Default is "dilation".
290
+ do_dilation: bool, optional
291
+ If True, dilate the Voronoi regions to have at least min_star_per_cell
292
+ stars in each cell. Default is True.
293
+
294
+ Returns:
295
+ df_cluster: DataFrame
296
+ DataFrame containing the cluster stars with the membership and
297
+ differential reddening corrected magnitudes added.
298
+ """
299
+ # make a copy to preserve the original dataframe
300
+ df_cluster = df_cluster_input.copy()
301
+ df_field = df_field_input.copy()
302
+
303
+ groups, subfovs, instrument_fov = spatial_groupby(
304
+ df_cluster,
305
+ df_field,
306
+ racol=racol,
307
+ deccol=deccol,
308
+ minstars=minstars,
309
+ )
310
+
311
+ ra_center = (
312
+ df_cluster[racol].min()
313
+ + (df_cluster[racol].max() - df_cluster[racol].min()) / 2
314
+ )
315
+ dec_center = (
316
+ df_cluster[deccol].min()
317
+ + (df_cluster[deccol].max() - df_cluster[deccol].min()) / 2
318
+ )
319
+
320
+ fov_ratio = [subfov.area / instrument_fov.area for subfov in subfovs]
321
+
322
+ field_pts = [
323
+ Point(row[field_mag_col[0]] - row[field_mag_col[1]], row[field_mag_col[0]])
324
+ for _, row in df_field.iterrows()
325
+ ]
326
+
327
+ # initialize the cluster columns for membership and differential reddening
328
+ dr_band1_corr = dr_params["band1"] + "_drcorr"
329
+ dr_band2_corr = dr_params["band2"] + "_drcorr"
330
+ df_cluster[dr_band1_corr] = df_cluster[dr_params["band1"]]
331
+ df_cluster[dr_band2_corr] = df_cluster[dr_params["band2"]]
332
+
333
+ dr_params["band1"] = dr_band1_corr
334
+ dr_params["band2"] = dr_band2_corr
335
+
336
+ df_cluster["delta_ebv"] = 0.0
337
+ df_cluster["membership"] = 1.0
338
+
339
+ for it in range(process_iter):
340
+ print(f"ITERATION {it+1}")
341
+
342
+ # reddening differential correction
343
+ print("compute differential reddening..")
344
+ print(df_cluster["membership"].describe())
345
+ if it == 0:
346
+ print("First iteration, correction threshold skipped")
347
+ calc_corr_threhsold = False
348
+ else:
349
+ print(f"do calcuation of the Correction threshold")
350
+ calc_corr_threhsold = True
351
+
352
+ b1_corr, b2_corr, EBV, poli = compute_differential_reddening(
353
+ df_cluster,
354
+ params=dr_params,
355
+ member_threshold=member_threshold,
356
+ calc_corr_threhsold=calc_corr_threhsold,
357
+ roi=roi,
358
+ plot=plot_dred,
359
+ )
360
+ roi = poli
361
+ df_cluster[dr_band1_corr] = b1_corr
362
+ df_cluster[dr_band2_corr] = b2_corr
363
+ df_cluster["delta_ebv"] += EBV
364
+
365
+ if plot_dred:
366
+ # plot new cmd
367
+ _, ax = plt.subplots(layout="constrained")
368
+ utplot.plot_cmd(
369
+ ax,
370
+ df_cluster,
371
+ [dr_band1_corr, dr_band2_corr],
372
+ color="black",
373
+ inverty=True,
374
+ )
375
+ ax.set(xlim=(0.5, 3.5), ylim=(26.5, 14))
376
+
377
+ # plot reddening map
378
+ _ = utplot.plot_reddening_map(
379
+ df_cluster["ra(1)"],
380
+ df_cluster[deccol],
381
+ ra_center,
382
+ dec_center,
383
+ EBV,
384
+ )
385
+ # plt.show(block=False)
386
+ plt.draw()
387
+ plt.pause(1.0)
388
+
389
+ print("...differential reddening completed")
390
+ print(f"EBV stat: {EBV.mean():.4f}, {EBV.min():.4f}, {EBV.max():.4f}")
391
+
392
+ print("Start decontamionation process..")
393
+ for i, (group, fovr) in enumerate(zip(groups, fov_ratio)):
394
+
395
+ # updating the membership of the groups
396
+ # !!! this can be avoided if pandas groupby is used !!!
397
+ group.loc[:, "membership"] = df_cluster.loc[group.index, "membership"]
398
+ group.loc[:, dr_band1_corr] = df_cluster.loc[group.index, dr_band1_corr]
399
+ group.loc[:, dr_band2_corr] = df_cluster.loc[group.index, dr_band2_corr]
400
+
401
+ print(f"\t#### GROUP N.{i + 1} ####")
402
+
403
+ # Voronoi grid creation
404
+ xg = group[dr_band1_corr] - group[dr_band2_corr]
405
+ yg = group[dr_band1_corr]
406
+ cluster_pts = [Point(x, y) for x, y in zip(xg, yg)]
407
+
408
+ # dilate regions to have at least n stars in each cell
409
+ if do_dilation:
410
+ if min_star_per_cell > group.shape[0]:
411
+ print(
412
+ f"\tNot enough stars in this region "
413
+ f"({group.shape[0]}, requested {min_star_per_cell})"
414
+ )
415
+ dilate = False
416
+ else:
417
+ dilate = True
418
+ else:
419
+ dilate = False
420
+
421
+ # cvt_grid = cvtGrid(points, iter=1, dilate=dilate)
422
+
423
+ cvt_grid = cvtGrid(
424
+ np.array([xg.values, yg.values]).T,
425
+ iter=1,
426
+ dilate=dilate,
427
+ which=which_voronoi,
428
+ target_median=min_star_per_cell,
429
+ )
430
+
431
+ regions = cvt_grid.grid if not dilate else cvt_grid.dilated_grid
432
+ cluster_ids = group.index.values
433
+
434
+ # count field stars in cells
435
+ cell_field_counts = get_regions_count(regions, field_pts)
436
+ points_in_reigons = get_pts_in_regions(regions, cluster_pts)
437
+
438
+ if plot_voronoi:
439
+ _ = utplot.plot_cmd_and_vorgrid(
440
+ group,
441
+ [dr_band1_corr, dr_band2_corr],
442
+ regions,
443
+ points_in_reigons,
444
+ )
445
+ # plt.show(block=False)
446
+ plt.draw()
447
+ plt.pause(1.0)
448
+
449
+ common_regions = set([el[0] for el in cell_field_counts]).intersection(
450
+ set([el[0] for el in points_in_reigons])
451
+ )
452
+
453
+ # add membership
454
+ membership = get_membership(
455
+ cell_field_counts,
456
+ points_in_reigons,
457
+ common_regions,
458
+ membership_iter,
459
+ fovr,
460
+ )
461
+
462
+ print(
463
+ f"\tMembership (mean, min, max): "
464
+ f"({membership[:, 1].mean():.4f},"
465
+ f" {membership[:, 1].min():.4f},"
466
+ f" {membership[:, 1].max():.4f})\n\n"
467
+ )
468
+
469
+ df_cluster.loc[cluster_ids[membership[:, 0].astype(int)], "membership"] = (
470
+ membership[:, 1]
471
+ )
472
+
473
+ return df_cluster
@@ -0,0 +1,53 @@
1
+ import numpy as np
2
+ from shapely import Polygon, STRtree, Point
3
+
4
+
5
+ def get_regions_count(
6
+ regions: list[Polygon], points: list[Point]
7
+ ) -> list[tuple[int, int]]:
8
+ """Get the count of points in each region.
9
+
10
+ Args:
11
+ regions: list of shapely Polygons
12
+ List of regions to check.
13
+ points: list of shapely Points
14
+ List of points to check.
15
+
16
+ Returns:
17
+ list of tuples
18
+ List of tuples with region index and count of points in that region.
19
+ """
20
+
21
+ k3_regs = STRtree(regions)
22
+ # check if points are shapely Points object and convert if necessary
23
+ if not all(isinstance(pt, Point) for pt in points):
24
+ points = [Point(*pt) for pt in points if not isinstance(pt, Point)]
25
+
26
+ _, region_ids = k3_regs.query(points, predicate="intersects")
27
+
28
+ regions_count = [(reg, list(region_ids).count(reg)) for reg in set(region_ids)]
29
+ return regions_count
30
+
31
+
32
+ def get_pts_in_regions(
33
+ regions: list[Polygon], points: list[Point]
34
+ ) -> list[tuple[int, list[Point]]]:
35
+ """Get the points in each region.
36
+
37
+ Args:
38
+ regions: list of shapely Polygons
39
+ List of regions to check.
40
+ points: list of shapely Points
41
+ List of points to check.
42
+
43
+ Returns:
44
+ list of tuples
45
+ List of tuples with region index and list of points in that region.
46
+ """
47
+
48
+ k3_pts = STRtree(regions)
49
+ id_pts, id_region = k3_pts.query(points, predicate="intersects")
50
+ pts_in_regions = [
51
+ (reg, id_pts[np.where(id_region == reg)[0]]) for reg in np.unique(id_region)
52
+ ]
53
+ return pts_in_regions
utils/__init__.py ADDED
File without changes