mc3 3.3.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.
mc3/plots/colors.py ADDED
@@ -0,0 +1,209 @@
1
+ # Copyright (c) 2015-2026 Patricio Cubillos and contributors.
2
+ # mc3 is open-source software under the MIT license (see LICENSE).
3
+
4
+ __all__ = [
5
+ 'alphatize',
6
+ 'rainbow_text',
7
+ 'Theme',
8
+ 'THEMES',
9
+ ]
10
+
11
+ import numpy as np
12
+ from matplotlib.colors import (
13
+ is_color_like,
14
+ same_color,
15
+ to_rgb,
16
+ to_rgba,
17
+ ListedColormap,
18
+ )
19
+ from matplotlib.transforms import Affine2D, offset_copy
20
+
21
+
22
+ def alphatize(colors, alpha, background='w'):
23
+ """
24
+ Get RGB representation of a color as if it had the specified alpha.
25
+
26
+ Parameters
27
+ ----------
28
+ colors: color or iterable of colors
29
+ The color to alphatize.
30
+ alpha: Float
31
+ Alpha value to apply.
32
+ background: color
33
+ Background color.
34
+
35
+ Returns
36
+ -------
37
+ rgb: RGB or list of RGB color arrays
38
+ The RGB representation of the alphatized color (or list of colors).
39
+
40
+ Examples
41
+ --------
42
+ >>> import mc3.plots as mp
43
+
44
+ >>> # As string:
45
+ >>> color = 'red'
46
+ >>> alpha = 0.5
47
+ >>> mp.alphatize(color, alpha)
48
+ array([1. , 0.5, 0.5])
49
+
50
+ >>> # As RGB tuple:
51
+ >>> color = (1.0, 0.0, 0.0)
52
+ >>> mp.alphatize(color, alpha)
53
+ array([1. , 0.5, 0.5])
54
+
55
+ >>> # Specify 'background':
56
+ >>> color1 = 'red'
57
+ >>> color2 = 'blue'
58
+ >>> mp.alphatize(color1, alpha, color2)
59
+ array([0.5, 0. , 0.5])
60
+
61
+ >>> # Input a list of colors:
62
+ >>> mp.alphatize(['r', 'b'], alpha=0.8)
63
+ [array([1. , 0.2, 0.2]), array([0.2, 0.2, 1. ])]
64
+ """
65
+ flatten = False
66
+ if is_color_like(colors):
67
+ colors = [colors]
68
+ flatten = True
69
+ colors = [np.array(to_rgb(color)) for color in colors]
70
+ background = np.array(to_rgb(background))
71
+
72
+ # https://matplotlib.org/tutorials/colors/colors.html
73
+ rgb = [(1.0-alpha) * background + alpha*c for c in colors]
74
+
75
+ if flatten:
76
+ return rgb[0]
77
+ return rgb
78
+
79
+
80
+ def rainbow_text(ax, texts, fontsize, colors=None, loc='above'):
81
+ """
82
+ Plot lines of text on top of each other (above an axis),
83
+ each line with a specified color.
84
+
85
+ Parameters
86
+ ----------
87
+ texts: 1D iterable of strings
88
+ Text to plot.
89
+ colors: 1D interable of colors
90
+ Color for each text.
91
+ ax: A matplotlib axis instance
92
+ Axis where to plot the text.
93
+ fontsize: Float
94
+ Text font size.
95
+ loc: String
96
+ Location of the first text. Select: 'above' or 'inside'.
97
+
98
+ Returns
99
+ -------
100
+ printed_texts: 1D list of strings
101
+ The text objects.
102
+ """
103
+ if colors is None:
104
+ colors = ['black' for _ in texts]
105
+ fig = ax.get_figure()
106
+ t = ax.transAxes
107
+ x = 0.02
108
+ horizontalalignment = 'left'
109
+ if loc == 'above':
110
+ y = 1.02
111
+ verticalalignment = 'bottom'
112
+ bbox = None
113
+ elif loc == 'inside':
114
+ y = 0.97
115
+ verticalalignment = 'top'
116
+ bbox = {'facecolor':'white', 'alpha':0.5, 'pad':0.0, 'edgecolor':'none'}
117
+ elif loc == 'under':
118
+ y = -0.04
119
+ x = 0.97
120
+ verticalalignment = 'top'
121
+ horizontalalignment = 'right'
122
+ bbox = None
123
+
124
+ printed_texts = []
125
+ for string, col in zip(texts, colors):
126
+ text = ax.text(
127
+ x, y, string, color=col, transform=t,
128
+ ha=horizontalalignment, va=verticalalignment,
129
+ size=fontsize,
130
+ bbox=bbox,
131
+ )
132
+ printed_texts.append(text)
133
+ text.draw(fig.canvas.get_renderer())
134
+ ex = text.get_window_extent()
135
+ # Convert window extent from pixels to inches
136
+ # to avoid issues displaying at different dpi
137
+ ex = fig.dpi_scale_trans.inverted().transform_bbox(ex)
138
+ t = text.get_transform() + offset_copy(Affine2D(), fig=fig, y=ex.height)
139
+ return printed_texts
140
+
141
+
142
+ class Theme():
143
+ """A monochromatic color theme from given color"""
144
+ def __init__(self, color, alpha_light=0.15, alpha_dark=0.7):
145
+ """
146
+ Parameters
147
+ ----------
148
+ color: color or iterable of colors
149
+ The color to alphatize.
150
+ alpha_light: Float
151
+ Alpha color value to merge with white to make self.light_color.
152
+ alpha_dark: Float
153
+ Alpha color value to merge with black.
154
+
155
+ Examples
156
+ --------
157
+ >>> import mc3.plots.colors as colors
158
+ >>> theme = colors.Theme('xkcd:blue')
159
+ >>> theme = colors.Theme([0.0, 0.2, 0.8])
160
+ """
161
+ whites = [
162
+ alphatize(color, alpha, 'white')
163
+ for alpha in np.linspace(alpha_light, 1.0, 162)
164
+ ]
165
+ darks = [
166
+ alphatize(color, alpha, 'black')
167
+ for alpha in np.linspace(1.0, alpha_dark, 95)
168
+ ]
169
+ colormap = ListedColormap(whites + darks[1:])
170
+ colormap.set_under(color='white')
171
+ colormap.set_bad(color='white')
172
+
173
+ self.light_color = alphatize(color, 0.75, 'white')
174
+ self.color = color
175
+ self.dark_color = alphatize(color, alpha_dark, 'black')
176
+ self.colormap = colormap
177
+
178
+ def __repr__(self):
179
+ return f"Theme({repr(self.color)})"
180
+
181
+ def __eq__(self, other):
182
+ return (
183
+ same_color(self.color, other.color) and
184
+ same_color(self.light_color, other.light_color) and
185
+ same_color(self.dark_color, other.dark_color) and
186
+ self.colormap == other.colormap
187
+ )
188
+
189
+
190
+ # Setup for THEMES:
191
+ yellow = alphatize('gold', 0.7, 'orange')
192
+ yellow_theme = Theme(yellow, alpha_light=0.2, alpha_dark=0.6)
193
+ yellow_theme.color = 'orange'
194
+ yellow_theme.light_color = 'gold'
195
+ yellow_theme.dark_color = 'darkgoldenrod'
196
+
197
+
198
+ THEMES = {
199
+ 'red': Theme('xkcd:tomato'),
200
+ 'orange': Theme('darkorange'),
201
+ 'yellow': yellow_theme,
202
+ 'green': Theme('xkcd:green'),
203
+ 'lightblue': Theme('dodgerblue'),
204
+ 'blue': Theme('xkcd:blue'),
205
+ 'purple': Theme('xkcd:violet'),
206
+ 'indigo': Theme('xkcd:indigo'),
207
+ 'black': Theme('0.3'),
208
+ }
209
+
@@ -0,0 +1,351 @@
1
+ # Copyright (c) 2015-2026 Patricio Cubillos and contributors.
2
+ # mc3 is open-source software under the MIT license (see LICENSE).
3
+
4
+ __all__ = [
5
+ # Functions:
6
+ 'rms',
7
+ 'trace',
8
+ # To be deprecated:
9
+ 'modelfit',
10
+ 'histogram',
11
+ 'pairwise',
12
+ 'subplotter',
13
+ ]
14
+
15
+ import os
16
+
17
+ import numpy as np
18
+ import matplotlib.pyplot as plt
19
+
20
+ from .. import utils as u
21
+ from .. import stats as ms
22
+
23
+
24
+ def rms(
25
+ binsz, rms, stderr, rmslo, rmshi, cadence=None, binstep=1,
26
+ timepoints=[], ratio=False, fignum=1300,
27
+ yran=None, xran=None, savefile=None,
28
+ ):
29
+ """
30
+ Plot the RMS vs binsize curve.
31
+
32
+ Parameters
33
+ ----------
34
+ binsz: 1D ndarray
35
+ Array of bin sizes.
36
+ rms: 1D ndarray
37
+ RMS of dataset at given binsz.
38
+ stderr: 1D ndarray
39
+ Gaussian-noise rms Extrapolation
40
+ rmslo: 1D ndarray
41
+ RMS lower uncertainty
42
+ rmshi: 1D ndarray
43
+ RMS upper uncertainty
44
+ cadence: Float
45
+ Time between datapoints in seconds.
46
+ binstep: Integer
47
+ Plot every-binstep point.
48
+ timepoints: List
49
+ Plot a vertical line at each time-points.
50
+ ratio: Boolean
51
+ If True, plot rms/stderr, else, plot both curves.
52
+ fignum: Integer
53
+ Figure number
54
+ yran: 2-elements tuple
55
+ Minimum and Maximum y-axis ranges.
56
+ xran: 2-elements tuple
57
+ Minimum and Maximum x-axis ranges.
58
+ savefile: String
59
+ If not None, name of file to save the plot.
60
+
61
+ Returns
62
+ -------
63
+ ax: matplotlib.axes.Axes
64
+ Axes instance containing the marginal posterior distributions.
65
+ """
66
+ if cadence is None:
67
+ cadence = 1.0
68
+ xlabel = 'Bin size'
69
+ else:
70
+ xlabel = 'Bin size (seconds)'
71
+
72
+ if yran is None:
73
+ yran = [np.amin(rms-rmslo), np.amax(rms+rmshi)]
74
+ yran[0] = np.amin([yran[0],stderr[-1]])
75
+ if ratio:
76
+ yran = [0, np.amax(rms/stderr) + 1.0]
77
+ if xran is None:
78
+ xran = [cadence, np.amax(binsz*cadence)]
79
+
80
+ fs = 14 # Font size
81
+ ylabel = r'$\beta$ = RMS / Gaussian noise' if ratio else 'RMS'
82
+
83
+ plt.figure(fignum, (8,6))
84
+ plt.clf()
85
+ ax = plt.subplot(111)
86
+ if ratio:
87
+ ax.errorbar(
88
+ binsz[::binstep]*cadence, (rms/stderr)[::binstep],
89
+ yerr=[(rmslo/stderr)[::binstep], (rmshi/stderr)[::binstep]],
90
+ fmt='k-', ecolor='0.5', capsize=0, label="__nolabel__",
91
+ )
92
+ ax.semilogx(xran, [1,1], "r-", lw=2)
93
+ else:
94
+ # Residuals RMS:
95
+ ax.errorbar(
96
+ binsz[::binstep]*cadence, rms[::binstep],
97
+ yerr=[rmslo[::binstep], rmshi[::binstep]],
98
+ fmt='k-', ecolor='0.5', capsize=0, label='RMS')
99
+ # Gaussian noise projection:
100
+ ax.loglog(
101
+ binsz*cadence, stderr, color='red', ls='-', lw=2.0,
102
+ label='Gaussian noise',
103
+ )
104
+ ax.legend(loc='best')
105
+
106
+ for time in timepoints:
107
+ ax.vlines(time, yran[0], yran[1], 'b', 'dashed', lw=2)
108
+
109
+ ax.tick_params(
110
+ labelsize=fs-1, direction='in', top=True, right=True, which='both',
111
+ )
112
+ ax.set_ylim(yran)
113
+ ax.set_xlim(xran)
114
+ ax.set_ylabel(ylabel, fontsize=fs)
115
+ ax.set_xlabel(xlabel, fontsize=fs)
116
+
117
+ if savefile is not None:
118
+ plt.savefig(savefile)
119
+ return ax
120
+
121
+
122
+ def trace(
123
+ posterior, zchain=None, pnames=None,
124
+ burnin=0, fignum=1000, savefile=None, fmt=".", ms=2.5, fs=10,
125
+ color='xkcd:blue',
126
+ ):
127
+ """
128
+ Plot parameter trace MCMC sampling.
129
+
130
+ Parameters
131
+ ----------
132
+ posterior: 2D float ndarray
133
+ An MCMC posterior sampling with dimension: [nsamples, npars].
134
+ zchain: 1D integer ndarray
135
+ the chain index for each posterior sample.
136
+ pnames: Iterable (strings)
137
+ Label names for parameters.
138
+ burnin: Integer
139
+ Thinned burn-in number of iteration (only used when zchain is not None).
140
+ fignum: Integer
141
+ The figure number.
142
+ savefile: Boolean
143
+ If not None, name of file to save the plot.
144
+ fmt: String
145
+ The format string for the line and marker.
146
+ ms: Float
147
+ Marker size.
148
+ fs: Float
149
+ Fontsize of texts.
150
+ color: string
151
+ A color.
152
+
153
+ Returns
154
+ -------
155
+ axes: 1D list of matplotlib.axes.Axes
156
+ List of axes containing the marginal posterior distributions.
157
+ """
158
+ # Get indices for samples considered in final analysis:
159
+ if zchain is not None:
160
+ nchains = np.amax(zchain) + 1
161
+ good = np.zeros(len(zchain), bool)
162
+ for c in range(nchains):
163
+ good[np.where(zchain == c)[0][burnin:]] = True
164
+ # Values accepted for posterior stats:
165
+ posterior = posterior[good]
166
+ zchain = zchain[good]
167
+ # Sort the posterior by chain:
168
+ zsort = np.lexsort([zchain])
169
+ posterior = posterior[zsort]
170
+ zchain = zchain[zsort]
171
+ # Get location for chains separations:
172
+ xsep = np.where(np.ediff1d(zchain))[0]
173
+
174
+ nsamples, npars = np.shape(posterior)
175
+ npanels = 12 # Max number of panels per page
176
+ npages = int(1 + (npars-1)/npanels)
177
+
178
+ if pnames is None:
179
+ pnames = u.default_parnames(npars)
180
+
181
+ # Make the trace plot:
182
+ axes = []
183
+ ipar = 0
184
+ axis_height = 0.62
185
+ hspace = 0.15
186
+ for page in range(npages):
187
+ fig = plt.figure(fignum+page)
188
+ plt.clf()
189
+ nx = np.clip(npars-ipar, 0, npanels)
190
+ height = axis_height *(nx + (nx-1)*hspace) + 0.65
191
+ fig.set_size_inches(8.0, height)
192
+ bottom = 0.45 / height
193
+ top = 1.0 - 0.20 / height
194
+ plt.subplots_adjust(
195
+ left=0.15, right=0.98, bottom=bottom, top=top, hspace=hspace)
196
+ while ipar < npars:
197
+ ax = plt.subplot(nx, 1, ipar%npanels+1)
198
+ axes.append(ax)
199
+ ax.plot(posterior[:,ipar], fmt, ms=ms, color=color)
200
+ yran = ax.get_ylim()
201
+ if zchain is not None:
202
+ ax.vlines(xsep, yran[0], yran[1], '0.2', lw=0.75, zorder=-10)
203
+
204
+ ax.set_ylim(yran)
205
+ ax.locator_params(axis='y', nbins=5, tight=True)
206
+ ax.tick_params(labelsize=fs-1, direction='in', top=True, right=True)
207
+ ax.set_ylabel(pnames[ipar], size=fs, multialignment='center')
208
+ ax.set_xlim(0, nsamples)
209
+ ax.get_xaxis().set_visible(False)
210
+ ipar += 1
211
+ if ipar%npanels == 0:
212
+ break
213
+ ax.set_xlabel('MCMC sample', size=fs)
214
+ ax.get_xaxis().set_visible(True)
215
+
216
+ if savefile is not None:
217
+ if npages > 1:
218
+ name, extension = os.path.splitext(savefile)
219
+ fig.savefig(f"{name}_page{page+1:02d}{extension}", dpi=300)
220
+ else:
221
+ fig.savefig(savefile, dpi=300)
222
+
223
+ return axes
224
+
225
+
226
+ # ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
227
+ # ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
228
+ # Deprecated functions:
229
+
230
+ def histogram(
231
+ posterior, pnames=None, thinning=1, fignum=1100,
232
+ savefile=None, bestp=None, quantile=None, pdf=None,
233
+ xpdf=None, ranges=None, axes=None, lw=2.0, fs=11,
234
+ nbins=25, theme='blue', yscale=False, orientation='vertical',
235
+ statistics='med_central',
236
+ ):
237
+ """
238
+ Deprecated function. Use the plot_histogram() function of
239
+ mc3.plots.Posterior() instead.
240
+ """
241
+ from .posterior import Posterior
242
+ post = Posterior(
243
+ posterior, pnames=pnames, bestp=bestp, theme=theme,
244
+ quantile=quantile, ranges=ranges,
245
+ statistics=statistics,
246
+ )
247
+ fig = post.plot_histogram(
248
+ savefile=savefile, fignum=fignum, #linewidth=lw, fontsize=fs,
249
+ axes=axes,
250
+ )
251
+ return fig
252
+
253
+
254
+ def pairwise(
255
+ posterior, pnames=None, thinning=1, fignum=1200,
256
+ savefile=None, bestp=None, nbins=25, nlevels=20,
257
+ absolute_dens=False, ranges=None, fs=11, rect=None, margin=0.01,
258
+ quantile=0.683, theme='blue', statistics='med_central',
259
+ linewidth=2.0, plot_marginal=True,
260
+ ):
261
+ """
262
+ Deprecated function. Use the plot() function of
263
+ mc3.plots.Posterior() instead.
264
+ """
265
+ from .posterior import Posterior
266
+ post = Posterior(
267
+ posterior, pnames=pnames, bestp=bestp, theme=theme,
268
+ quantile=quantile, ranges=ranges,
269
+ statistics=statistics,
270
+ )
271
+ fig = post.plot(
272
+ savefile=savefile, fignum=fignum, linewidth=linewidth, fontsize=fs,
273
+ rect=rect, margin=margin,
274
+ )
275
+ return fig
276
+
277
+
278
+
279
+ def modelfit(
280
+ data, uncert, indparams, model, nbins=75,
281
+ fignum=1400, savefile=None, fmt="."
282
+ ):
283
+ """
284
+ Plot the binned dataset with given uncertainties and model curves
285
+ as a function of indparams.
286
+ In a lower panel, plot the residuals bewteen the data and model.
287
+
288
+ Parameters
289
+ ----------
290
+ data: 1D float ndarray
291
+ Input data set.
292
+ uncert: 1D float ndarray
293
+ One-sigma uncertainties of the data points.
294
+ indparams: 1D float ndarray
295
+ Independent variable (X axis) of the data points.
296
+ model: 1D float ndarray
297
+ Model of data.
298
+ nbins: Integer
299
+ Number of bins in the output plot.
300
+ fignum: Integer
301
+ The figure number.
302
+ savefile: Boolean
303
+ If not None, name of file to save the plot.
304
+ fmt: String
305
+ Format of the plotted markers.
306
+
307
+ Returns
308
+ -------
309
+ ax: matplotlib.axes.Axes
310
+ Axes instance containing the marginal posterior distributions.
311
+ """
312
+ # Bin down array:
313
+ binsize = int((np.size(data)-1)/nbins + 1)
314
+ binindp = ms.bin_array(indparams, binsize)
315
+ binmodel = ms.bin_array(model, binsize)
316
+ bindata, binuncert = ms.bin_array(data, binsize, uncert)
317
+ fs = 12
318
+
319
+ plt.figure(fignum, figsize=(8,6))
320
+ plt.clf()
321
+ # Residuals:
322
+ rax = plt.axes([0.15, 0.1, 0.8, 0.2])
323
+ rax.errorbar(binindp, bindata-binmodel, binuncert, fmt='ko', ms=4)
324
+ rax.plot([indparams[0], indparams[-1]], [0,0],'k:',lw=1.5)
325
+ rax.tick_params(labelsize=fs-1, direction='in', top=True, right=True)
326
+ rax.set_xlabel("x", fontsize=fs)
327
+ rax.set_ylabel('Residuals', fontsize=fs)
328
+ # Data and Model:
329
+ ax = plt.axes([0.15, 0.35, 0.8, 0.55])
330
+ ax.errorbar(
331
+ binindp, bindata, binuncert, fmt='ko', ms=4, label='Binned data')
332
+ ax.plot(indparams, model, "b", lw=2, label='Best Fit')
333
+ ax.set_xticklabels([])
334
+ ax.tick_params(labelsize=fs-1, direction='in', top=True, right=True)
335
+ ax.set_ylabel('y', fontsize=fs)
336
+ ax.legend(loc='best')
337
+
338
+ if savefile is not None:
339
+ plt.savefig(savefile)
340
+ return ax, rax
341
+
342
+
343
+ def subplotter(
344
+ rect, margin, ipan, nx, ny=None, ymargin=None,
345
+ ):
346
+ """
347
+ Deprecated function. Use mc3.plots.subplot() instead.
348
+ """
349
+ from .posterior import subplot
350
+ return subplot(rect, margin, ipan, nx, ny, ymargin)
351
+