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,18 @@
1
+ mcmc/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ mcmc/bivariate_normal.py,sha256=p5lyDwbeuhsaSCQQRR9KkRrC9MKXBTwP4dbdRxEKNG8,4250
3
+ mcmc/mcmc.py,sha256=3C88J4dhv0JtcrS6doa1452iJNYZ_TweH1bwa-F64BI,7619
4
+ mcmc/set_posterior.py,sha256=8wPw9L29PNuWDbELt9Cn2oD7fFSY-yIe_RfP9wXRF_g,1986
5
+ mcmc/utils.py,sha256=ZFDLboE0hapzhBcts6NC80CzqfAmRo27C_6Gi9eFvFk,3652
6
+ mcmc/legacy/multivariate_2d_posterior.py,sha256=kbKweKKXCsADW_dRqKiJDxy0WOm4Bp8K0E8rU7l0aVU,2878
7
+ mgcs_pytools-0.1.0.dist-info/licenses/LICENSE,sha256=Nz6flaZwjVLv7cp4kAorLq2yDWh1wPbCKBRqwkOqMVk,1071
8
+ statistical_membership/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ statistical_membership/cvt_grid.py,sha256=5bzeS_6_SgvuMzZyBq7TSK8K0394SJEpvpE9750_Gt0,11532
10
+ statistical_membership/dr_correction.py,sha256=YFNtnCkM4FC9Q8iDIKFQIeQh_osyms9RUlLopWjg37M,11577
11
+ statistical_membership/membership.py,sha256=ZhYG3IySyZX6Z6YgiBmxmFwa4rDCb3Nmh82ZKSqF6MQ,16050
12
+ statistical_membership/region_tools.py,sha256=eHataT4NK_kcJ0owUAMfVuTDG6-e5TDTsSpNpDfn_Ww,1598
13
+ utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ utils/plotting.py,sha256=LBcktOQfQwR_JrasA9vWKay0pr3l9ZZDqsPZwf0F2sY,25242
15
+ mgcs_pytools-0.1.0.dist-info/METADATA,sha256=N7i50CjNC6QMH04sfJc4jctgiX6zne8USyZp0Ec9co8,807
16
+ mgcs_pytools-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
17
+ mgcs_pytools-0.1.0.dist-info/top_level.txt,sha256=jmk3gtiMJeIXhlJjwmRMATgdFzsvzZyptPdCbXZIV8Y,34
18
+ mgcs_pytools-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Luca Rosignoli
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ mcmc
2
+ statistical_membership
3
+ utils
File without changes
@@ -0,0 +1,372 @@
1
+ from typing import Tuple
2
+ import numpy as np
3
+ from numpy.typing import NDArray
4
+ import sys
5
+ from scipy.spatial import Voronoi
6
+ from scipy.interpolate import RegularGridInterpolator
7
+ from sklearn.cluster import KMeans
8
+
9
+ from shapely import (
10
+ Polygon,
11
+ STRtree,
12
+ union,
13
+ )
14
+
15
+ from .region_tools import get_regions_count, get_pts_in_regions
16
+
17
+ """
18
+ This code is adapted from
19
+ https://stackoverflow.com/questions/28665491/getting-a-bounded-polygon-coordinates-from-voronoi-cells
20
+ """
21
+
22
+
23
+ def _bounded_vor(points: NDArray, bounding_box: NDArray) -> Voronoi:
24
+ """Compute bounded Voronoi tessellation.
25
+
26
+ Args:
27
+ points: `NDArray`
28
+ Points to compute the Voronoi tessellation (Npoints, 2).
29
+ bounding_box: `NDArray`
30
+ Bounding box to limit the Voronoi tessellation (xmin, xmax, ymin, ymax).
31
+
32
+ Returns:
33
+ vor: `Voronoi`
34
+ Bounded Voronoi tessellation.
35
+ """
36
+ eps = sys.float_info.epsilon
37
+
38
+ # Mirror points
39
+ points_center = points
40
+ points_left = np.copy(points_center)
41
+ points_left[:, 0] = bounding_box[0] - (points_left[:, 0] - bounding_box[0])
42
+ points_right = np.copy(points_center)
43
+ points_right[:, 0] = bounding_box[1] + (bounding_box[1] - points_right[:, 0])
44
+ points_down = np.copy(points_center)
45
+ points_down[:, 1] = bounding_box[2] - (points_down[:, 1] - bounding_box[2])
46
+ points_up = np.copy(points_center)
47
+ points_up[:, 1] = bounding_box[3] + (bounding_box[3] - points_up[:, 1])
48
+ points = np.append(
49
+ points_center,
50
+ np.append(
51
+ np.append(points_left, points_right, axis=0),
52
+ np.append(points_down, points_up, axis=0),
53
+ axis=0,
54
+ ),
55
+ axis=0,
56
+ )
57
+ # Compute Voronoi
58
+ vor = Voronoi(points)
59
+
60
+ # Filter regions
61
+ regions = []
62
+ for region in vor.regions:
63
+ flag = True
64
+ for index in region:
65
+ if index == -1:
66
+ flag = False
67
+ break
68
+ else:
69
+ x = vor.vertices[index, 0]
70
+ y = vor.vertices[index, 1]
71
+ if not (
72
+ bounding_box[0] - eps <= x
73
+ and x <= bounding_box[1] + eps
74
+ and bounding_box[2] - eps <= y
75
+ and y <= bounding_box[3] + eps
76
+ ):
77
+ flag = False
78
+ break
79
+ if region != [] and flag:
80
+ regions.append(region)
81
+ vor.filtered_points = points_center
82
+ vor.filtered_regions = regions
83
+ return vor
84
+
85
+
86
+ def _centroid_region(vertices: NDArray) -> NDArray:
87
+ """Compute centroid of a polygon.
88
+
89
+ Args:
90
+ vertices: `NDArray`
91
+ Vertices of the polygon (Nvertices, 2).
92
+
93
+ Returns:
94
+ centroid: `NDArray`
95
+ Centroid of the polygon (1, 2).
96
+ """
97
+ # Polygon's signed area
98
+ A = 0
99
+
100
+ # Centroid's x
101
+ C_x = 0
102
+
103
+ # Centroid's y
104
+ C_y = 0
105
+ for i in range(0, len(vertices) - 1):
106
+ s = vertices[i, 0] * vertices[i + 1, 1] - vertices[i + 1, 0] * vertices[i, 1]
107
+ A = A + s
108
+ C_x = C_x + (vertices[i, 0] + vertices[i + 1, 0]) * s
109
+ C_y = C_y + (vertices[i, 1] + vertices[i + 1, 1]) * s
110
+ A = 0.5 * A
111
+ C_x = (1.0 / (6.0 * A)) * C_x
112
+ C_y = (1.0 / (6.0 * A)) * C_y
113
+
114
+ return np.array([[C_x, C_y]])
115
+
116
+
117
+ def _cvt_vor(
118
+ init_points: NDArray, iters: int, padx: float = 0.01, pady: float = 0.01
119
+ ) -> Tuple[Voronoi, NDArray]:
120
+ """Compute Centroidal Voronoi Tessellation (CVT).
121
+
122
+ Args:
123
+ init_points: `NDArray`
124
+ Initial points to compute the CVT (Npoints, 2).
125
+ iters: `int`
126
+ Number of iterations to compute the CVT.
127
+ padx: `float`, optional
128
+ Padding in x direction to limit the Voronoi tessellation. Default is 0.01.
129
+ pady: `float`, optional
130
+ Padding in y direction to limit the Voronoi tessellation. Default is 0.01.
131
+
132
+ Returns:
133
+ vor: `Voronoi`
134
+ Centroidal Voronoi tessellation.
135
+ centroids: `NDArray`
136
+ Centroids of the Voronoi cells (Ncells, 2).
137
+ """
138
+ points = init_points
139
+
140
+ for i in range(iters):
141
+
142
+ vor = _bounded_vor(
143
+ points,
144
+ [
145
+ points[:, 0].min() - padx,
146
+ points[:, 0].max() + padx,
147
+ points[:, 1].min() - pady,
148
+ points[:, 1].max() + pady,
149
+ ],
150
+ )
151
+
152
+ if i == iters - 1 and iters > 1:
153
+ break
154
+ centroids = []
155
+ for region in vor.filtered_regions:
156
+ vertices = vor.vertices[region + [region[0]], :]
157
+ centroid = _centroid_region(vertices)
158
+ centroids.append(list(centroid[0, :]))
159
+
160
+ points = np.array(centroids)
161
+ return vor, np.array(centroids)
162
+
163
+
164
+ def _aggregate_regions(regions: NDArray) -> NDArray:
165
+ """Aggregate regions into joint regions.
166
+
167
+ Args:
168
+ regions: `NDArray`
169
+ Array of regions (Nregions, 2).
170
+
171
+ Returns:
172
+ joint_regions: `NDArray`
173
+ Array of joint regions (Njoint_regions, 2).
174
+ """
175
+
176
+ joint_regions = []
177
+
178
+ old_touched_regions = []
179
+ new_touched_regions = []
180
+
181
+ # sort regions for their area
182
+ regions = sorted(regions, key=lambda x: Polygon(x).area, reverse=False)
183
+ regions = np.array(regions)
184
+ for i, reg in enumerate(regions):
185
+
186
+ if i in old_touched_regions:
187
+ continue
188
+
189
+ ktree_regions = STRtree(regions)
190
+
191
+ new_touched_regions = ktree_regions.query(reg, predicate="touches")
192
+
193
+ new_touched_regions = np.delete(
194
+ new_touched_regions,
195
+ np.where(np.isin(new_touched_regions, old_touched_regions)),
196
+ )
197
+
198
+ old_touched_regions = np.append(old_touched_regions, new_touched_regions)
199
+ old_touched_regions = np.append(old_touched_regions, i)
200
+
201
+ joint_reg = reg
202
+ for touched_reg in regions[new_touched_regions]:
203
+ joint_reg = union(joint_reg, touched_reg)
204
+
205
+ joint_regions.append(joint_reg)
206
+
207
+ return np.array(joint_regions)
208
+
209
+
210
+ def _dilate_grid(regions: NDArray, points: NDArray, target_median: float) -> NDArray:
211
+ """Grid dilation.
212
+
213
+ Dilate the grid by aggregating regions
214
+ until a target median number of points per region is reached.
215
+
216
+ Args:
217
+ regions: `NDArray`
218
+ Array of regions (Nregions, 2).
219
+ points: `NDArray`
220
+ Array of points (Npoints, 2).
221
+ target_median: `float`
222
+ Target median number of points per region.
223
+
224
+ Returns:
225
+ joint_regions: `NDArray`
226
+ Array of joint regions (Njoint_regions, 2).
227
+ """
228
+
229
+ joint_regions = np.array(regions)
230
+
231
+ c = 0
232
+ while True:
233
+ joint_regions = _aggregate_regions(joint_regions)
234
+ pts_in_regions = np.array(get_regions_count(joint_regions, points))
235
+ if np.median(pts_in_regions[:, 1]) >= target_median:
236
+ break
237
+ c += 1
238
+ # print(c)
239
+
240
+ return joint_regions
241
+
242
+
243
+ def generate_weights(XY: NDArray) -> NDArray:
244
+ """Generate weights for points based on their density.
245
+ Args:
246
+ XY: `NDArray`
247
+ Array of points (Npoints, 2).
248
+ Returns:
249
+ weights: `NDArray`
250
+ Weights for each point (Npoints,).
251
+ """
252
+ # compute 2d map to evaluate weights
253
+ hist, xedges, yedges = np.histogram2d(
254
+ x=XY[:, 0], y=XY[:, 1], bins=200, density=True
255
+ )
256
+ xedges = 0.5 * (xedges[1:] + xedges[:-1])
257
+ yedges = 0.5 * (yedges[1:] + yedges[:-1])
258
+
259
+ # interpolate the grid
260
+ interp = RegularGridInterpolator(
261
+ (xedges, yedges), hist, bounds_error=False, fill_value=np.nan
262
+ ) # from scipy
263
+ weights = interp((XY[:, 0], XY[:, 1]))
264
+ return weights
265
+
266
+
267
+ def generate_centroids(
268
+ pos: NDArray,
269
+ points_per_bin: int | None = None,
270
+ nbins: int | None = None,
271
+ weights: NDArray | None = None,
272
+ ):
273
+ """Generate centroids using weighted k-means clustering.
274
+
275
+ Args:
276
+ pos: `NDArray`
277
+ Array of points (Npoints, 2).
278
+ points_per_bin: `int` or `None`, optional
279
+ Target number of points per bin. If `None`, `nbins` must be specified.
280
+ Default is `None`.
281
+ nbins: `int` or `None`, optional
282
+ Number of bins to generate. If `None`, `points_per_bin` must be specified.
283
+ Default is `None`.
284
+ weights: `NDArray` or `None`, optional
285
+ Weights for each point (Npoints,). If `None`, no weights are used.
286
+ Default is `None`.
287
+
288
+ Returns:
289
+ centroids: `NDArray`
290
+ Array of centroids (Ncentroids, 2).
291
+ """
292
+ if points_per_bin is None and nbins is None:
293
+ raise ValueError("points_per_bin or nbins must be specificied")
294
+
295
+ if points_per_bin is not None:
296
+ nbins = pos.shape[0] // points_per_bin
297
+
298
+ # Perform KMeans clustering to divide the points into nbins clusters
299
+ kmeans = KMeans(n_clusters=nbins, random_state=0)
300
+ kmeans.fit(pos) if weights is None else kmeans.fit(pos, sample_weight=weights)
301
+ # labels = kmeans.labels_
302
+ centroids = kmeans.cluster_centers_
303
+
304
+ return centroids
305
+
306
+
307
+ # class cvtGrid:
308
+ # def __init__(
309
+ # self, points, iter=3, padx=0.01, pady=0.01, dilate=False, target_median=3
310
+ # ):
311
+ # self.cvor, self.cpoints = _cvt_vor(points, iter, padx, pady)
312
+ #
313
+ # self.grid = np.array(
314
+ # [Polygon(self.cvor.vertices[reg]) for reg in self.cvor.filtered_regions]
315
+ # )
316
+ #
317
+ # self.dilated_grid = (
318
+ # None if not dilate else _dilate_grid(self.grid, points, target_median)
319
+ # )
320
+ class cvtGrid:
321
+ def __init__(
322
+ self,
323
+ points: NDArray,
324
+ which: str = "dilation",
325
+ iter: int = 3,
326
+ padx: float = 0.01,
327
+ pady: float = 0.01,
328
+ dilate: bool = False,
329
+ target_median: int = 3,
330
+ ):
331
+ """Compute Centroidal Voronoi Tessellation (CVT) grid.
332
+
333
+ Args:
334
+ points: `NDArray`
335
+ Points to compute the CVT (Npoints, 2).
336
+ which: `str`, optional
337
+ Method to compute the CVT. Options are "dilation" or "wkmeans".
338
+ Default is "dilation".
339
+ iter: `int`, optional
340
+ Number of iterations to compute the CVT. Default is 3.
341
+ padx: `float`, optional
342
+ Padding in x direction to limit the Voronoi tessellation. Default is 0.01.
343
+ pady: `float`, optional
344
+ Padding in y direction to limit the Voronoi tessellation. Default is 0.01.
345
+ dilate: `bool`, optional
346
+ Whether to dilate the grid by aggregating regions until a target median
347
+ number of points per region is reached. Default is False.
348
+ target_median: `int`, optional
349
+ Target median number of points per region when dilating the grid.
350
+ Default is 3.
351
+ """
352
+ if which == "dilation":
353
+ self.cvor, self.cpoints = _cvt_vor(points, iter, padx, pady)
354
+
355
+ self.grid = np.array(
356
+ [Polygon(self.cvor.vertices[reg]) for reg in self.cvor.filtered_regions]
357
+ )
358
+
359
+ self.dilated_grid = (
360
+ None if not dilate else _dilate_grid(self.grid, points, target_median)
361
+ )
362
+ elif which == "wkmeans":
363
+ weights = generate_weights(points)
364
+ weights = np.where(np.isnan(weights), 0.0, weights)
365
+ centroids = generate_centroids(
366
+ points, points_per_bin=target_median, weights=weights
367
+ )
368
+
369
+ self.cvor, self.cpoints = _cvt_vor(centroids, iter, padx, pady)
370
+ self.grid = np.array(
371
+ [Polygon(self.cvor.vertices[reg]) for reg in self.cvor.filtered_regions]
372
+ )