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 ADDED
File without changes
@@ -0,0 +1,145 @@
1
+ import numpy as np
2
+ from numpy.typing import NDArray
3
+
4
+
5
+ def bivar_norm(
6
+ x1: NDArray,
7
+ x2: NDArray,
8
+ mu1: NDArray,
9
+ mu2: NDArray,
10
+ sigma1: NDArray,
11
+ sigma2: NDArray,
12
+ rho: NDArray,
13
+ ) -> NDArray:
14
+ """Bivariate normal distribution
15
+
16
+ Args:
17
+ x1: NDArray
18
+ First variable.
19
+ x2: NDArray
20
+ Second variable.
21
+ mu1: NDArray
22
+ Mean of the first variable.
23
+ mu2: NDArray
24
+ Mean of the second variable.
25
+ sigma1: NDArray
26
+ Standard deviation of the first variable.
27
+ sigma2: NDArray
28
+ Standard deviation of the second variable.
29
+ rho: NDArray
30
+ Correlation coefficient.
31
+
32
+ Returns:
33
+ PDF: NDArray
34
+ Probability density function values.
35
+ """
36
+ dx1 = x1 - mu1
37
+ dx2 = x2 - mu2
38
+
39
+ det = sigma1 * sigma2 * np.sqrt(1 - rho**2)
40
+ norm = 1.0 / (2.0 * np.pi * det)
41
+
42
+ z = (
43
+ (dx1 / sigma1) ** 2
44
+ + (dx2 / sigma2) ** 2
45
+ - 2 * rho * dx1 * dx2 / (sigma1 * sigma2)
46
+ ) / (2 * (1 - rho**2))
47
+
48
+ return norm * np.exp(-z)
49
+
50
+
51
+ def _logl(data: NDArray, prm: NDArray, component: int, stride: int = 5):
52
+ """Log-likelihood function for a mixture of bivariate normal distributions.
53
+
54
+ Args:
55
+ data: NDArray
56
+ Data array with shape (N, 4), where each row is (pm_ra, pm_dec, epm_ra, epm_dec).
57
+ prm: NDArray
58
+ Parameter array containing the parameters for each component and weights.
59
+ For each component, the parameters are (mu1, mu2, sigma1, sigma2, rho).
60
+ If there are multiple components, the last (component - 1) elements are weights.
61
+ component: int
62
+ Number of bivariate normal components in the mixture.
63
+ stride: int, optional
64
+ Number of parameters per component. Default is 5.
65
+
66
+ Returns:
67
+ log_likelihood: float
68
+ The log-likelihood value.
69
+ """
70
+
71
+ # unpack data
72
+ pm_ra = data[:, 0]
73
+ pm_dec = data[:, 1]
74
+ epm_ra = data[:, 2]
75
+ epm_dec = data[:, 3]
76
+
77
+ if component > 1:
78
+ w = prm[-(component - 1) :]
79
+ else:
80
+ w = prm[-1]
81
+
82
+ # create a model for each component
83
+ c_dist = np.zeros(pm_ra.shape)
84
+ for i in range(component):
85
+ mu1, mu2 = prm[0 + i * stride], prm[1 + i * stride]
86
+ s1, s2 = prm[2 + i * stride], prm[3 + i * stride]
87
+ rho = prm[4 + i * stride]
88
+
89
+ sigma1_obs = np.sqrt(s1**2 + epm_ra**2)
90
+ sigma2_obs = np.sqrt(s2**2 + epm_dec**2)
91
+ # rho_eff
92
+ rho_eff = rho * (s1 * s2) / (sigma1_obs * sigma2_obs)
93
+
94
+ if component > 1 and i < component - 1:
95
+ c_dist += w[i] * bivar_norm(
96
+ pm_ra, pm_dec, mu1, mu2, sigma1_obs, sigma2_obs, rho_eff
97
+ )
98
+ elif component == 1:
99
+ c_dist += w * bivar_norm(
100
+ pm_ra, pm_dec, mu1, mu2, sigma1_obs, sigma2_obs, rho_eff
101
+ )
102
+ else:
103
+ c_dist += (1 - w.sum()) * bivar_norm(
104
+ pm_ra, pm_dec, mu1, mu2, sigma1_obs, sigma2_obs, rho_eff
105
+ )
106
+
107
+ if np.any(np.isnan(np.log(c_dist))):
108
+ print(c_dist)
109
+ print("crashing Args:", prm)
110
+ return np.nan
111
+
112
+ return np.log(c_dist).sum()
113
+
114
+
115
+ def _lnprior(prm: NDArray, qmin: NDArray, qmax: NDArray, ncomp: int) -> float:
116
+ """Log-prior function for the parameters.
117
+
118
+ Args:
119
+ prm: NDArray
120
+ Parameter array containing the parameters for each component and weights.
121
+ For each component, the parameters are (mu1, mu2, sigma1, sigma2, rho).
122
+ If there are multiple components, the last (component - 1) elements are weights.
123
+ qmin: NDArray
124
+ Minimum values for each parameter.
125
+ qmax: NDArray
126
+ Maximum values for each parameter.
127
+ ncomp: int
128
+ Number of bivariate normal components in the mixture.
129
+
130
+ Returns:
131
+ log_prior: float
132
+ The log-prior value.
133
+ """
134
+
135
+ if ncomp > 1:
136
+ ws = prm[-(ncomp - 1) :]
137
+ if (prm < qmin).any() or (prm > qmax).any() or 1 - ws.sum() < 0.0:
138
+ return -np.inf
139
+ else:
140
+ return 0.0
141
+ else:
142
+ if (prm < qmin).any() or (prm > qmax).any():
143
+ return -np.inf
144
+ else:
145
+ return 0.0
@@ -0,0 +1,102 @@
1
+ import numpy as np
2
+ from numpy.typing import NDArray
3
+
4
+
5
+ def mvar_norm(
6
+ x1: NDArray, x2: NDArray, mu1: NDArray, mu2: NDArray, cov: NDArray
7
+ ) -> NDArray:
8
+ """Multivariate normal distribution function.
9
+
10
+ Parameters
11
+ ----------
12
+ x1 : `NDArray`
13
+ Input along first dimension.
14
+ x2 : `NDArray`
15
+ Input along second dimension.
16
+ mu1 : `NDArray`
17
+ Mean value along first dimension.
18
+ mu2 : `NDArray`
19
+ Mean value along first dimension.
20
+ cov : `NDArray`
21
+ Covariance matrix.
22
+
23
+ Returns
24
+ -------
25
+ `NDArray`
26
+ Probability density function.
27
+ """
28
+
29
+ diff = np.array([x1 - mu1, x2 - mu2]).T
30
+ minv = np.linalg.inv(cov)
31
+ norm = 1.0 / (2.0 * np.pi * np.sqrt(np.linalg.det(cov)))
32
+ prod1 = np.matmul(minv, diff[:, :, np.newaxis])
33
+ prod2 = np.matmul(diff[:, np.newaxis, :], prod1)
34
+
35
+ return norm * np.exp(-0.5 * prod2.T)
36
+
37
+
38
+ def _logl(data, prm, component, stride=5):
39
+
40
+ # unpack data
41
+ pm_ra = data[:, 0]
42
+ pm_dec = data[:, 1]
43
+ epm_ra = data[:, 2]
44
+ epm_dec = data[:, 3]
45
+
46
+ if component > 1:
47
+ w = prm[-(component - 1) :]
48
+ else:
49
+ w = prm[-1]
50
+
51
+ # create a model for each component
52
+ c_dist = np.zeros(pm_ra.shape)
53
+ for i in range(component):
54
+
55
+ cprm = prm[(i * stride) : (i + 1) * stride]
56
+ sigma_ra = np.sqrt(cprm[2] * cprm[2] + epm_ra * epm_ra)
57
+ sigma_dec = np.sqrt(cprm[3] * cprm[3] + epm_dec * epm_dec)
58
+ rho_eff = [
59
+ (cprm[-1] * cprm[2] * cprm[3]) / (c_si_ra * c_si_dec)
60
+ for c_si_ra, c_si_dec in zip(sigma_ra, sigma_dec)
61
+ ]
62
+ cov = np.array(
63
+ [
64
+ np.array(
65
+ [
66
+ [c_si_ra * c_si_ra, reff * c_si_ra * c_si_dec],
67
+ [reff * c_si_ra * c_si_dec, c_si_dec * c_si_dec],
68
+ ]
69
+ )
70
+ for c_si_ra, c_si_dec, reff in zip(sigma_ra, sigma_dec, rho_eff)
71
+ ]
72
+ )
73
+
74
+ if component > 1 and i < component - 1:
75
+ c_dist += w[i] * mvar_norm(pm_ra, pm_dec, cprm[0], cprm[1], cov)[0, 0, :]
76
+ elif component == 1:
77
+ c_dist += w * mvar_norm(pm_ra, pm_dec, cprm[0], cprm[1], cov)[0, 0, :]
78
+ else:
79
+ c_dist += (1 - w.sum()) * mvar_norm(pm_ra, pm_dec, cprm[0], cprm[1], cov)[
80
+ 0, 0, :
81
+ ]
82
+
83
+ if np.any(np.isnan(np.log(c_dist))):
84
+ print(c_dist)
85
+ print("crashing parameters:", prm)
86
+ return np.nan
87
+
88
+ return np.log(c_dist).sum()
89
+
90
+
91
+ def _lnprior(prm, qmin, qmax, ncomp) -> float:
92
+ if ncomp > 1:
93
+ ws = prm[-(ncomp - 1) :]
94
+ if (prm < qmin).any() or (prm > qmax).any() or 1 - ws.sum() < 0.0:
95
+ return -np.inf
96
+ else:
97
+ return 0.0
98
+ else:
99
+ if (prm < qmin).any() or (prm > qmax).any():
100
+ return -np.inf
101
+ else:
102
+ return 0.0
mcmc/mcmc.py ADDED
@@ -0,0 +1,211 @@
1
+ import numpy as np
2
+ from numpy.typing import NDArray
3
+
4
+ import emcee
5
+ from emcee.backends import HDFBackend
6
+ from multiprocessing import Pool
7
+
8
+ from .set_posterior import posterior
9
+
10
+
11
+ class MyEmceeES:
12
+ """Class to run MCMC with emcee.
13
+
14
+ This class is particularly design to use multivariate fuctions as posterior,
15
+ but it can be genewralized to work with any function.
16
+ It can managed one or more gaussian components
17
+ and their parameters can be either linked of freezed.
18
+
19
+ Args:
20
+ data: `NDArray`
21
+ Data to fit.
22
+ posterior: `callable`
23
+ Posterior function to use in the mcmc to compute the loglike.
24
+ nwalkers: `int`
25
+ Number of walkers initialized in the MCMC.
26
+ nsteps: `int`
27
+ Number of steps to run.
28
+ ncomp: `int`
29
+ Number of model components to use.
30
+ par_per_comp: `int`
31
+ Number of parameters per component.
32
+ qmin: `NDArray`
33
+ Lower limits for priors.
34
+ qmax: `NDArray`
35
+ Upper limits for priors.
36
+ p0: `NDArray` or `None`, optional
37
+ Initial guess for the parameters.
38
+ If `None`, uniform distribution between qmin and qmax will be used. Defult is `None`.
39
+ fix_params: `NDArray` or `None`, optional
40
+ Array containing the fixed parameters. If None, no parameters will be fixed. Defaul is `None`
41
+ lnk_params: `NDArray` or `None`, optional
42
+ Array containing the linked parameters. If None, no parameters will be linked together.
43
+ Defaul is `None`
44
+ save_chains: `bool`, optional
45
+ If True, the chains will be saved in an HDF5 file. Default is False.
46
+ hdf_filename: `str`, optional
47
+ Name of the HDF5 file to save the chains. Default is "mcmc_chains.h5".
48
+ parallel: `bool`, optional
49
+ If True, use multiprocessing to run the MCMC on multiple processor.
50
+ If False, run the MCMC in a single process. Default is False.
51
+ from_previous_run: `bool`, optional
52
+ If True, load a previous MCMC run from an HDF5 file. Default is False.
53
+ hdf_backend_kwargs: `dict` or `None`, optional
54
+ Dictionary containing the parameters to use for the HDFBackend.
55
+ """
56
+
57
+ def __init__(
58
+ self,
59
+ data: NDArray | None = None,
60
+ nwalkers: int | None = None,
61
+ nsteps: int | None = None,
62
+ ncomp: int | None = None,
63
+ par_per_comp: int | None = None,
64
+ qmin: NDArray | None = None,
65
+ qmax: NDArray | None = None,
66
+ pmodel: str | None = None,
67
+ p0: NDArray | None = None,
68
+ fix_params: NDArray | None = None,
69
+ lnk_params: NDArray | None = None,
70
+ save_chains: bool = False,
71
+ hdf_filename: str = "mcmc_chains.h5",
72
+ parallel: bool = False, # TODO: now with parallel is slower!
73
+ from_previous_run: bool = False,
74
+ hdf_backend_kwargs: dict | None = None,
75
+ ):
76
+ self.from_previous_run = from_previous_run
77
+ if not self.from_previous_run:
78
+ self.data = data
79
+ self.pmodel = pmodel
80
+ self.nwalkers = nwalkers
81
+ self.nsteps = nsteps
82
+ self.ncomp = ncomp
83
+ self.par_per_comp = par_per_comp
84
+ self.ndim = (
85
+ (ncomp * par_per_comp) + ncomp - 1
86
+ if self.ncomp > 1
87
+ else (ncomp * par_per_comp) + ncomp
88
+ )
89
+ self.qmin = qmin
90
+ self.qmax = qmax
91
+ self.fix_params = fix_params
92
+ self.lnk_params = lnk_params
93
+ self.chain = None
94
+
95
+ self.p0 = (
96
+ np.array(
97
+ [
98
+ np.random.uniform(self.qmin, self.qmax)
99
+ for _ in range(self.nwalkers)
100
+ ]
101
+ )
102
+ if p0 is None
103
+ else p0
104
+ )
105
+
106
+ self.p0[:, -2] = np.random.uniform(0.3, 0.6, size=self.nwalkers)
107
+ self.p0[:, -1] = np.random.uniform(0.0, 0.3, size=self.nwalkers)
108
+
109
+ self.bpars = None
110
+
111
+ self.pool = None
112
+ if parallel:
113
+ self.pool = Pool()
114
+
115
+ backend = None
116
+ if save_chains:
117
+ backend = emcee.backends.HDFBackend(hdf_filename)
118
+ backend.reset(nwalkers=self.nwalkers, ndim=self.ndim)
119
+
120
+ # set the sampler
121
+ self.sampler = emcee.EnsembleSampler(
122
+ nwalkers=self.nwalkers,
123
+ ndim=self.ndim,
124
+ log_prob_fn=posterior,
125
+ kwargs={
126
+ "data": self.data,
127
+ "qmin": self.qmin,
128
+ "qmax": self.qmax,
129
+ "component": self.ncomp,
130
+ "stride": self.par_per_comp,
131
+ "fix_params": self.fix_params,
132
+ "lnk_params": self.lnk_params,
133
+ "pmodel": self.pmodel,
134
+ },
135
+ moves=[
136
+ (emcee.moves.DEMove(), 0.8),
137
+ (emcee.moves.DESnookerMove(), 0.2),
138
+ ],
139
+ backend=backend,
140
+ pool=self.pool,
141
+ )
142
+ else:
143
+ self.sampler = self.load_mcmc_run(**hdf_backend_kwargs)
144
+
145
+ def run_emcee(self):
146
+ """Run the MCMC using emcee.
147
+
148
+ Args:
149
+ parallel: `bool`, optional
150
+ If True, use multiprocessing to run the MCMC on multiple processor.
151
+ If False, run the MCMC in a single process. Default is False.
152
+ """
153
+ self.sampler.run_mcmc(self.p0, self.nsteps, progress=True)
154
+
155
+ def get_chain(self, **kwargs) -> NDArray:
156
+ """Get the chain of samples.
157
+
158
+ Args:
159
+ kwargs:
160
+ Parameters of get_chain emcee's method (*thin*, *flat*, *discard*).
161
+
162
+ Returns:
163
+ chain: `NDArray`
164
+ Chain of samples.
165
+ """
166
+ return self.sampler.get_chain(**kwargs)
167
+
168
+ @staticmethod
169
+ def get_model_parameters(
170
+ sampler: emcee.EnsembleSampler | emcee.backends.HDFBackend,
171
+ which: str,
172
+ percentile: list[float] = [16.0, 50.0, 84.0],
173
+ **kwargs
174
+ ) -> NDArray:
175
+ """Obtain the model parameters from the chain.
176
+
177
+ Args:
178
+ sampler: `EnsembleSampler` or `HDFBackend`
179
+ Emcee sampler object containing the MCMC run.
180
+ which: `str`
181
+ How to retrieve the model parameter.
182
+ - *percentiles*: the parameters will be returned at the specified percentiles.
183
+ - *maxln*: the parameters that represent the maximum loglikelihood.
184
+ percentile: `list` of `float`, optional
185
+ Percentiles to use, default are [16., 50., 84.].
186
+ kwargs:
187
+ Parameters of get_chain and get_log_prob emcee methods (*thin*, *flat*, *discard*).
188
+
189
+ Returns:
190
+ pars: `NDArray`
191
+ Parameters set from the chain.
192
+ """
193
+ if which == "maxln":
194
+ maxln = sampler.get_log_prob(**kwargs).argmax()
195
+ return sampler.get_chain(**kwargs)[maxln]
196
+ else:
197
+ return np.percentile(sampler.get_chain(**kwargs), percentile, axis=0)
198
+
199
+ @staticmethod
200
+ def load_mcmc_run(**kwargs) -> HDFBackend:
201
+ """Load a previous MCMC run saved in an HDF5 file.
202
+
203
+ Args:
204
+ kwargs:
205
+ Parameters of the HDFBackend emcee's method.
206
+
207
+ Returns:
208
+ backend: `HDFBackend`
209
+ HDFBackend object containing the MCMC run.
210
+ """
211
+ return emcee.backends.HDFBackend(**kwargs)
mcmc/set_posterior.py ADDED
@@ -0,0 +1,66 @@
1
+ import numpy as np
2
+ from numpy.typing import NDArray
3
+
4
+
5
+ def posterior(
6
+ prm: NDArray,
7
+ data: NDArray,
8
+ qmin: NDArray,
9
+ qmax: NDArray,
10
+ component: NDArray,
11
+ pmodel: str = "bivariate_normal",
12
+ fix_params: NDArray | None = None,
13
+ lnk_params: NDArray | None = None,
14
+ stride: int = 5,
15
+ ) -> float:
16
+ """Posterior function for the MCMC.
17
+
18
+ Args:
19
+ prm : `NDArray`
20
+ Parameters to fit.
21
+ data : `NDArray`
22
+ Data to fit.
23
+ qmin : `NDArray`
24
+ Lower limits for priors.
25
+ qmax : `NDArray`
26
+ Upper limits for priors.
27
+ component : `NDArray`
28
+ Number of components to fit.
29
+ pmodel : `str`, optional
30
+ Model to use for the posterior. Default is "bivariate_normal".
31
+ Currently, only "bivariate_normal" is supported.
32
+ fix_params : `NDArray` or `None`, optional
33
+ Array containing the fixed parameters.
34
+ If `None`, no parameters will be fixed. Defaul is `None`
35
+ lnk_params : `NDArray` or `None`, optional
36
+ Array containing the linked parameters.
37
+ If `None`, no parameters will be linked together.
38
+ Defaul is `None`
39
+ stride : `int`, optional
40
+ Number of parameters per component. Default is 5.
41
+
42
+ Returns:
43
+ output : `float`
44
+ Logarithm of the posterior probability.
45
+ """
46
+
47
+ if pmodel == "bivariate_normal":
48
+ from .bivariate_normal import _logl, _lnprior
49
+ else:
50
+ raise ValueError(f"Model {pmodel} is not supported.")
51
+
52
+ lp = _lnprior(prm, qmin, qmax, component)
53
+
54
+ if fix_params is not None:
55
+ prm_new = np.where(np.isnan(fix_params), prm, fix_params)
56
+ else:
57
+ prm_new = prm
58
+
59
+ if lnk_params is not None:
60
+ for to_link, which in lnk_params:
61
+ prm_new[which] = prm_new[to_link]
62
+
63
+ output = (
64
+ -np.inf if not np.isfinite(lp) else lp + _logl(data, prm_new, component, stride)
65
+ )
66
+ return output
mcmc/utils.py ADDED
@@ -0,0 +1,136 @@
1
+ import numpy as np
2
+ from numpy.typing import NDArray
3
+
4
+
5
+ def _bivar_norm_broadcasting_for_chain(
6
+ x1: NDArray,
7
+ x2: NDArray,
8
+ mu1: NDArray,
9
+ mu2: NDArray,
10
+ sigma1: NDArray,
11
+ sigma2: NDArray,
12
+ rho: NDArray,
13
+ ) -> NDArray:
14
+ """Multivariate normal PDF (2D) with broadcasting for mcmc chain.
15
+
16
+ Args:
17
+ x1: `NDArray`
18
+ First variable.
19
+ x2: `NDArray`
20
+ Second variable.
21
+ mu1: `NDArray`
22
+ Mean of the first variable.
23
+ mu2: `NDArray`
24
+ Mean of the second variable.
25
+ sigma1: `NDArray`
26
+ Standard deviation of the first variable.
27
+ sigma2: `NDArray`
28
+ Standard deviation of the second variable.
29
+ rho: `NDArray`
30
+ Correlation coefficient.
31
+
32
+ Returns:
33
+ PDF: `NDArray`
34
+ Probability density function values.
35
+
36
+ """
37
+ dx1 = x1[:, None] - mu1[None, :] # (Ndata, Nchain)
38
+ dx2 = x2[:, None] - mu2[None, :] # (Ndata, Nchain)
39
+
40
+ det = sigma1 * sigma2 * np.sqrt(1 - rho**2)
41
+ norm = 1.0 / (2.0 * np.pi * det)
42
+
43
+ z = (
44
+ (dx1 / sigma1) ** 2
45
+ + (dx2 / sigma2) ** 2
46
+ - 2 * rho * dx1 * dx2 / (sigma1 * sigma2)
47
+ ) / (2 * (1 - rho**2))
48
+
49
+ return norm * np.exp(-z)
50
+
51
+
52
+ def _generate_weighted_mvar_pdf(
53
+ ch: NDArray, x1: NDArray, x2: NDArray, x1e: NDArray, x2e: NDArray
54
+ ) -> NDArray:
55
+ """Weighted bivariate normal PDF.
56
+
57
+ Args:
58
+ ch: `NDArray`
59
+ Chain parameters (Nchain, 5).
60
+ x1: `NDArray`
61
+ First observable (Ndata,).
62
+ x2: `NDArray`
63
+ Second observable (Ndata,).
64
+ x1e: `NDArray`
65
+ First observable error (Ndata,).
66
+ x2e: `NDArray`
67
+ Second observable error (Ndata,).
68
+
69
+ Returns:
70
+ `NDArray`
71
+ Weighted bivariate normal PDF (Ndata, Nchain).
72
+ """
73
+
74
+ mu1, mu2 = ch[:, 0], ch[:, 1] # (Nchain,)
75
+ s1, s2 = ch[:, 2], ch[:, 3] # (Nchain,)
76
+ rho = ch[:, 4] # (Nchain,)
77
+ w = ch[:, -1] # (Nchain,)
78
+
79
+ sigma1_obs = np.sqrt(s1[None, :] ** 2 + x1e[:, None] ** 2) # (Ndata,Nchain)
80
+ sigma2_obs = np.sqrt(s2[None, :] ** 2 + x2e[:, None] ** 2)
81
+
82
+ # rho_eff
83
+ rho_eff = rho[None, :] * (s1[None, :] * s2[None, :]) / (sigma1_obs * sigma2_obs)
84
+
85
+ pdf = _bivar_norm_broadcasting_for_chain(
86
+ x1, x2, mu1, mu2, sigma1_obs, sigma2_obs, rho_eff
87
+ )
88
+
89
+ return w[None, :] * pdf # shape (Ndata, Nchain)
90
+
91
+
92
+ def get_component_membership_from_mcmc_chain(
93
+ ch: NDArray, data: NDArray, ncomp: int, par_per_comp: int
94
+ ) -> NDArray:
95
+ """Get component membership from MCMC chain.
96
+
97
+ Parameters
98
+ ch: `NDArray`
99
+ Chain parameters.
100
+ data: `NDArray`
101
+ Observational data.
102
+ ncomp: `int`
103
+ Number of components.
104
+ par_per_comp: `int`
105
+ Number of parameters per component.
106
+
107
+ Returns:
108
+ `NDArray`
109
+ Component membership.
110
+ """
111
+ x1, x2, x1e, x2e = data.T # (Ndata,)
112
+
113
+ if ncomp > 1:
114
+ w = ch[:, -(ncomp - 1) :]
115
+ else:
116
+ w = 1.0
117
+
118
+ pdf = np.empty((ncomp, x1.shape[0], ch.shape[0]))
119
+ for i in range(ncomp):
120
+ c_ch = np.empty((ch.shape[0], par_per_comp + 1))
121
+ c_ch[:, :par_per_comp] = ch[:, (i * par_per_comp) : (1 + i) * par_per_comp]
122
+
123
+ if ncomp > 1 and i < ncomp - 1:
124
+ c_ch[:, -1] = w[i]
125
+ elif ncomp > 1 and i == ncomp - 1:
126
+ c_ch[:, -1] = 1 - np.sum(w, axis=1)
127
+ elif ncomp == 1:
128
+ c_ch[:, -1] = w
129
+
130
+ pdf[i] = _generate_weighted_mvar_pdf(c_ch, x1, x2, x1e, x2e) # (Ndata, Nchain)
131
+
132
+ # Membership
133
+ denom = pdf.sum(axis=0)
134
+ membership = pdf / denom[None, :]
135
+
136
+ return membership
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.4
2
+ Name: MGCS_pytools
3
+ Version: 0.1.0
4
+ Summary: A collection of Python tools for data analysis and visualization made for the MGCS HST Treasury program.
5
+ Author-email: Luca Rosignoli <luca.rosignoli@inaf.it>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://https://github.com/LR-inaf/MGCS_pytools
8
+ Project-URL: Bug Tracker, https://github.com/LR-inaf/MGCS_pytools/issues
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: numpy
12
+ Requires-Dist: pandas
13
+ Requires-Dist: shapely
14
+ Requires-Dist: scipy
15
+ Requires-Dist: matplotlib
16
+ Requires-Dist: astropy
17
+ Requires-Dist: emcee
18
+ Requires-Dist: corner
19
+ Requires-Dist: tqdm
20
+ Requires-Dist: seaborn
21
+ Requires-Dist: h5py
22
+ Requires-Dist: scikit-learn
23
+ Dynamic: license-file
24
+
25
+ # Python tools used for the Missing Globular Cluster Survey