code stringlengths 1 18.2k |
|---|
def wrap_fmin_slsqp(fun, guess, opt_kwargs={}): """Wrapper for :py:func:`fmin_slsqp` to allow it to be called with :py:func:`minimize`-like syntax. This is included to enable the code to run with :py:mod:`scipy` versions older than 0.11.0. Accepts `opt_kwargs` in the same format as used by :py:func:`scipy.optimize.mini... |
to minimize. guess : sequence The initial guess for the parameters. opt_kwargs : dict, optional Dictionary of extra keywords to pass to :py:func:`scipy.optimize.minimize`. Refer to that function's docstring for valid options. The keywords 'jac', 'hess' and 'hessp' are ignored. Note that if you were planning to use `jac... |
to compute and return the Jacobian this may cause unexpected behavior. Default is: {}. Returns ------- Result : namedtuple :py:class:`namedtuple` that mimics the fields of the :py:class:`Result` object returned by :py:func:`scipy.optimize.minimize`. Has the following fields: ======= ======= ============================... |
found. fun float Value of the optimized function (-1*LL). x ndarray Optimal values of the hyperparameters. message str String describing the exit state (`smode` from :py:func:`fmin_slsqp`) nit int Number of iterations. ======= ======= =================================================================================== R... |
dict): opt_kwargs['constraints'] = [opt_kwargs['constraints'],] for con in opt_kwargs.pop('constraints'): if con['type'] == 'eq': eqcons += [con['fun'],] elif con['type'] == 'ineq': ieqcons += [con['fun'],] else: raise ValueError("Invalid constraint type %s!" % (con['type'],)) if 'jac' in opt_kwargs: warnings.warn("Jac... |
keywords with less likelihood for causing failures are silently ignored: opt_kwargs.pop('hess', None) opt_kwargs.pop('hessp', None) opt_kwargs.pop('callback', None) out, fx, its, imode, smode = scipy.optimize.fmin_slsqp( fun, guess, full_output=True, eqcons=eqcons, ieqcons=ieqcons, **opt_kwargs ) Result = collections.n... |
def fixed_poch(a, n): """Implementation of the Pochhammer symbol :math:`(a)_n` which handles negative integer arguments properly. Need conditional statement because scipy's impelementation of the Pochhammer symbol is wrong for negative integer arguments. This function uses the definition from http://functions.wolfram.c... |
a % 1 == 0 and n <= -a: # p = (-1.0)**n * scipy.misc.factorial(-a) / scipy.misc.factorial(-a - n) # else: # p = scipy.special.poch(a, n) # return p if (int(n) != n) or (n < 0): raise ValueError("Parameter n must be a nonnegative int!") n = int(n) # Direct form based on product: terms = [a + k for k in range(0, n)] |
return scipy.prod(terms) |
def Kn2Der(nu, y, n=0): r"""Find the derivatives of :math:`K_\nu(y^{1/2})`. Parameters ---------- nu : float The order of the modified Bessel function of the second kind. y : array of float The values to evaluate at. n : nonnegative int, optional The order of derivative to take. """ n = int(n) y = scipy.asarray(y, dtyp... |
sqrty) else: K = scipy.zeros_like(y) x = scipy.asarray( [ fixed_poch(1.5 - j, j) * y**(0.5 - j) for j in scipy.arange(1.0, n + 1.0, dtype=float) ] ).T for k in scipy.arange(1.0, n + 1.0, dtype=float): K += ( scipy.special.kvp(nu, sqrty, n=int(k)) * incomplete_bell_poly(n, int(k), x) ) return K |
def yn2Kn2Der(nu, y, n=0, tol=5e-4, nterms=1, nu_step=0.001): r"""Computes the function :math:`y^{\nu/2} K_{\nu}(y^{1/2})` and its derivatives. Care has been taken to handle the conditions at :math:`y=0`. For `n=0`, uses a direct evaluation of the expression, replacing points where `y=0` with the appropriate value. For... |
Where it becomes infinite, the infinities will have the appropriate sign for a limit approaching zero from the right. Uses a power series expansion around :math:`y=0` to avoid numerical issues. Handles integer `nu` by performing a linear interpolation between values of `nu` slightly above and below the requested value.... |
of `y`. y : array of float The points to evaluate the function at. These are assumed to be nonegative. n : nonnegative int, optional The order of derivative to take. Set to zero (the default) to get the value. tol : float, optional The distance from zero for which the power series is used. Default is 5e-4. nterms : int... |
of terms to include in the power series. Default is 1. nu_step : float, optional The amount to vary `nu` by when handling integer values of `nu`. Default is 0.001. """ n = int(n) y = scipy.asarray(y, dtype=float) if n == 0: K = y**(nu / 2.0) * scipy.special.kv(nu, scipy.sqrt(y)) K[y == 0.0] = scipy.special.gamma(nu) / ... |
k in scipy.arange(0.0, n + 1.0, dtype=float): K += ( scipy.special.binom(n, k) * fixed_poch(1.0 + nu / 2.0 - k, k) * y**(nu / 2.0 - k) * Kn2Der(nu, y, n=n-k) ) # Do the extra work to handle y == 0 only if we need to: mask = (y == 0.0) if (mask).any(): if int(nu) == nu: K[mask] = 0.5 * ( yn2Kn2Der(nu |
- nu_step, y[mask], n=n, tol=tol, nterms=nterms, nu_step=nu_step) + yn2Kn2Der(nu + nu_step, y[mask], n=n, tol=tol, nterms=nterms, nu_step=nu_step) ) else: if n > nu: K[mask] = scipy.special.gamma(-nu) * fixed_poch(1 + nu - n, n) * scipy.inf else: K[mask] = scipy.special.gamma(nu) * scipy.special.gamma(n + 1.0) / ( 2.0*... |
Replace points within tol (absolute distance) of zero with the power # series approximation: mask = (y <= tol) & (y > 0.0) K[mask] = 0.0 if int(nu) == nu: K[mask] = 0.5 * ( yn2Kn2Der(nu - nu_step, y[mask], n=n, tol=tol, nterms=nterms, nu_step=nu_step) + yn2Kn2Der(nu + nu_step, y[mask], n=n, tol=tol, nterms=nterms, nu_s... |
( scipy.special.gamma(nu) * fixed_poch(1.0 + k - n, n) * y[mask]**(k - n) / ( 2.0**(1.0 - nu + 2 * k) * fixed_poch(1.0 - nu, k) * scipy.special.factorial(k)) ) for k in scipy.arange(0, nterms, dtype=float): K[mask] += ( scipy.special.gamma(-nu) * fixed_poch(1.0 + nu + k - n, n) * y[mask]**(nu + k - n) / ( 2.0**(1.0 + n... |
* fixed_poch(1.0 + nu, k) * scipy.special.factorial(k) ) ) return K |
def incomplete_bell_poly(n, k, x): r"""Recursive evaluation of the incomplete Bell polynomial :math:`B_{n, k}(x)`. Evaluates the incomplete Bell polynomial :math:`B_{n, k}(x_1, x_2, \dots, x_{n-k+1})`, also known as the partial Bell polynomial or the Bell polynomial of the second kind. This polynomial is useful in the ... |
is based on the implementation in: :py:func:`sympy.functions.combinatorial.numbers.bell._bell_incomplete_poly` Following that function's documentation, the polynomial is computed according to the recurrence formula: .. math:: B_{n, k}(x_1, x_2, \dots, x_{n-k+1}) = \sum_{m=1}^{n-k+1}x_m\binom{n-1}{m-1}B_{n-m, k-1}(x_1, ... |
: scalar int The first subscript of the polynomial. k : scalar int The second subscript of the polynomial. x : :py:class:`Array` of floats, (`p`, `n` - `k` + 1) `p` sets of `n` - `k` + 1 points to use as the arguments to :math:`B_{n,k}`. The second dimension can be longer than required, in which case the extra entries ... |
facilitates recursion without needing to subset the array `x`). Returns ------- result : :py:class:`Array`, (`p`,) Incomplete Bell polynomial evaluated at the desired values. """ if n == 0 and k == 0: return scipy.ones(x.shape[0], dtype=float) elif k == 0 and n >= 1: return scipy.zeros(x.shape[0], dtype=float) elif n =... |
in xrange(0, n - k + 1): result += x[:, m] * scipy.special.binom(n - 1, m) * incomplete_bell_poly(n - (m + 1), k - 1, x) return result |
def generate_set_partition_strings(n): """Generate the restricted growth strings for all of the partitions of an `n`-member set. Uses Algorithm H from page 416 of volume 4A of Knuth's `The Art of Computer Programming`. Returns the partitions in lexicographical order. Parameters ---------- n : scalar int, non-negative N... |
a number of elements equal to the `n`-th Bell number (i.e., the number of partitions for a set of size `n`). Each element has length `n`, the elements of which are the restricted growth strings describing the partitions of the set. The strings are returned in lexicographic order. """ # Handle edge cases: if n == 0: ret... |
[scipy.array([0])] partitions = [] # Step 1: Initialize a = scipy.zeros(n, dtype=int) b = scipy.ones(n, dtype=int) while True: # Step 2: Visit partitions.append(a.copy()) if a[-1] == b[-1]: # Step 4: Find j. j is the index of the first element from the end # for which a != b, with the exception of the last element. j =... |
Increase a_j (or terminate): if j == 0: break else: a[j] += 1 # Step 6: Zero out a_{j+1} to a_n: b[-1] = b[j] + (a[j] == b[j]) a[j + 1:] = 0 b[j + 1 :-1] = b[-1] else: # Step 3: Increase a_n: a[-1] += 1 return partitions |
def generate_set_partitions(set_): """Generate all of the partitions of a set. This is a helper function that utilizes the restricted growth strings from :py:func:`generate_set_partition_strings`. The partitions are returned in lexicographic order. Parameters ---------- set_ : :py:class:`Array` or other Array-like, (`m... |
equal to the number of partitions, which is the len(`m`)^th Bell number. Each of the inner lists corresponds to a single possible partition. The length of an inner list is therefore equal to the number of blocks. Each of the arrays in an inner list is hence a block. """ set_ = scipy.asarray(set_) strings = generate_set... |
= [] for block_num in scipy.unique(string): blocks.append(set_[string == block_num]) partitions.append(blocks) return partitions |
def unique_rows(arr, return_index=False, return_inverse=False): """Returns a copy of arr with duplicate rows removed. From Stackoverflow "Find unique rows in numpy.array." Parameters ---------- arr : :py:class:`Array`, (`m`, `n`) The array to find the unique rows of. return_index : bool, optional If True, the indices o... |
return_inverse: bool, optional If True, the indices in the unique array to reconstruct the original array will also be returned. I.e., arr = unique[inv]. Default is False (don't return inverse). Returns ------- unique : :py:class:`Array`, (`p`, `n`) where `p` <= `m` The array `arr` with duplicate rows removed. """ b = ... |
= out[0] idx = out[1] if return_inverse: inv = out[2] except TypeError: if return_inverse: raise RuntimeError( "Error in scipy.unique on older versions of numpy prevents " "return_inverse from working!" ) # Handle bug in numpy 1.6.2: rows = [_Row(row) for row in b] srt_idx = sorted(range(len(rows)), key=rows.__getitem_... |
scipy.where(row_cmp != 0)[0] idx = scipy.asarray(srt_idx)[transition_idxs] out = arr[idx] if return_index: out = (out, idx) elif return_inverse: out = (out, inv) elif return_index and return_inverse: out = (out, idx, inv) return out |
def compute_stats(vals, check_nan=False, robust=False, axis=1, plot_QQ=False, bins=15, name=''): """Compute the average statistics (mean, std dev) for the given values. Parameters ---------- vals : array-like, (`M`, `D`) Values to compute the average statistics along the specified axis of. check_nan : bool, optional Wh... |
or not to use robust estimators (median for mean, IQR for standard deviation). Default is False (use non-robust estimators). axis : int, optional Axis to compute the statistics along. Presently only supported if `robust` is False. Default is 1. plot_QQ : bool, optional Whether or not a QQ plot and histogram should be d... |
plots). bins : int, optional Number of bins to use when plotting histogram (for plot_QQ=True). Default is 15 name : str, optional Name to put in the title of the QQ/histogram plot. Returns ------- mean : ndarray, (`M`,) Estimator for the mean of `vals`. std : ndarray, (`M`,) Estimator for the standard deviation of `val... |
is True. NotImplementedError If `plot_QQ` is True. """ if axis != 1 and robust: raise NotImplementedError("Values of axis other than 1 are not supported " "with the robust keyword at this time!") if robust: # TODO: This stuff should really be vectorized if there is something that allows it! if check_nan: mean = scipy.s... |
for k in xrange(0, len(vals)): ch = vals[k] ok_idxs = ~scipy.isnan(ch) if ok_idxs.any(): std[k] = (scipy.stats.scoreatpercentile(ch[ok_idxs], 75) - scipy.stats.scoreatpercentile(ch[ok_idxs], 25)) else: # Leave a nan where there are no non-nan values: std[k] = scipy.nan std /= IQR_TO_STD else: mean = scipy.median(vals, ... |
= scipy.stats.nanmean(vals, axis=axis) std = scipy.stats.nanstd(vals, axis=axis) else: mean = scipy.mean(vals, axis=axis) std = scipy.std(vals, axis=axis) if plot_QQ: f = plt.figure() gs = mplgs.GridSpec(2, 2, height_ratios=[8, 1]) a_QQ = f.add_subplot(gs[0, 0]) a_hist = f.add_subplot(gs[0, 1]) a_slider = f.add_subplot... |
nan_idxs = scipy.isnan(vals[idx, :]) if not nan_idxs.all(): osm, osr = scipy.stats.probplot(vals[idx, ~nan_idxs], dist='norm', plot=None, fit=False) a_QQ.plot(osm, osr, 'bo', markersize=10) a_QQ.set_title('QQ plot') a_QQ.set_xlabel('quantiles of $\mathcal{N}(0,1)$') a_QQ.set_ylabel('quantiles of data') a_hist.hist(vals... |
object to update as a masked argument using a lambda function:: lambda evt: arrow_respond(my_slider, evt) Parameters ---------- slider : Slider instance associated with this handler. event : Event to be handled. """ if event.key == 'right': slider.set_val(min(slider.val + 1, slider.valmax)) elif event.key == 'left': sl... |
evt)) return (mean, std) |
def univariate_envelope_plot(x, mean, std, ax=None, base_alpha=0.375, envelopes=[1, 3], lb=None, ub=None, expansion=10, **kwargs): """Make a plot of a mean curve with uncertainty envelopes. """ if ax is None: f = plt.figure() ax = f.add_subplot(1, 1, 1) elif ax == 'gca': ax = plt.gca() mean = scipy.asarray(mean, dtype=... |
ub is not None and expansion != 1.0: expansion *= ub - lb ub = ub + expansion lb = lb - expansion if ub is not None: mean[mean > ub] = ub if lb is not None: mean[mean < lb] = lb l = ax.plot(x, mean, **kwargs) color = plt.getp(l[0], 'color') e = [] for i in envelopes: lower = mean - i |
* std upper = mean + i * std if ub is not None: lower[lower > ub] = ub upper[upper > ub] = ub if lb is not None: lower[lower < lb] = lb upper[upper < lb] = lb e.append(ax.fill_between(x, lower, upper, facecolor=color, alpha=base_alpha / i)) return (l, e) |
def summarize_sampler(sampler, weights=None, burn=0, ci=0.95, chain_mask=None): r"""Create summary statistics of the flattened chain of the sampler. The confidence regions are computed from the quantiles of the data. Parameters ---------- sampler : :py:class:`emcee.Sampler` instance or array, (`n_temps`, `n_chains`, `n... |
weight for each sample. This is useful for post-processing the output from MultiNest sampling, for instance. burn : int, optional The number of samples to burn from the beginning of the chain. Default is 0 (no burn). ci : float, optional A number between 0 and 1 indicating the confidence region to compute. Default is 0... |
confidence interval). chain_mask : (index) array, optional Mask identifying the chains to keep before plotting, in case there are bad chains. Default is to use all chains. Returns ------- mean : array, (num_params,) Mean values of each of the parameters sampled. ci_l : array, (num_params,) Lower bounds of the `ci*100%`... |
try: k = sampler.flatchain.shape[-1] except AttributeError: # Assumes array input is only case where there is no "flatchain" attribute. k = sampler.shape[-1] if isinstance(sampler, emcee.EnsembleSampler): if chain_mask is None: chain_mask = scipy.ones(sampler.chain.shape[0], dtype=bool) flat_trace = sampler.chain[chain... |
isinstance(sampler, scipy.ndarray): if sampler.ndim == 4: if chain_mask is None: chain_mask = scipy.ones(sampler.shape[1], dtype=bool) flat_trace = sampler[temp_idx, chain_mask, burn:, :] flat_trace = flat_trace.reshape((-1, k)) if weights is not None: weights = weights[temp_idx, chain_mask, burn:] weights = weights.ra... |
= weights[chain_mask, burn:] weights = weights.ravel() elif sampler.ndim == 2: flat_trace = sampler[burn:, :] flat_trace = flat_trace.reshape((-1, k)) if weights is not None: weights = weights[burn:] weights = weights.ravel() else: raise ValueError("Unknown sampler class: %s" % (type(sampler),)) cibdry = 100.0 * (1.0 -... |
mean = weights.dot(flat_trace) / weights.sum() ci_l = scipy.zeros(k) ci_u = scipy.zeros(k) p = scipy.asarray([cibdry, 100.0 - cibdry]) for i in range(0, k): srt = flat_trace[:, i].argsort() x = flat_trace[srt, i] w = weights[srt] Sn = w.cumsum() pn = 100.0 / Sn[-1] * (Sn - w / 2.0) j = scipy.digitize(p, pn) - 1 ci_l[i]... |
1] - pn[j]) * (x[j + 1] - x[j]) return (mean, ci_l, ci_u) |
def plot_sampler( sampler, suptitle=None, labels=None, bins=50, plot_samples=False, plot_hist=True, plot_chains=True, burn=0, chain_mask=None, temp_idx=0, weights=None, cutoff_weight=None, cmap='gray_r', hist_color='k', chain_alpha=0.1, points=None, covs=None, colors=None, ci=[0.95], max_hist_ticks=None, max_chain_tick... |
---------- sampler : :py:class:`emcee.Sampler` instance or array, (`n_temps`, `n_chains`, `n_samp`, `n_dim`), (`n_chains`, `n_samp`, `n_dim`) or (`n_samp`, `n_dim`) The sampler to plot the chains/marginals of. Can also be an array of samples which matches the shape of the `chain` attribute that would be present in a :p... |
: list of str, optional The labels to use for each of the free parameters. Default is to leave the axes unlabeled. bins : int, optional Number of bins to use for the histograms. Default is 50. plot_samples : bool, optional If True, the samples are plotted as individual points. Default is False. plot_hist : bool, option... |
True. plot_chains : bool, optional If True, plot the sampler chains at the bottom. Default is True. burn : int, optional The number of samples to burn before making the marginal histograms. Default is zero (use all samples). chain_mask : (index) array, optional Mask identifying the chains to keep before plotting, in ca... |
: int, optional Index of the temperature to plot when plotting a :py:class:`emcee.PTSampler`. Default is 0 (samples from the posterior). weights : array, (`n_temps`, `n_chains`, `n_samp`), (`n_chains`, `n_samp`) or (`n_samp`,), optional The weight for each sample. This is useful for post-processing the output from Mult... |
present, points with `weights < cutoff_weight * weights.max()` will be excluded. Default is to plot all points. cmap : str, optional The colormap to use for the histograms. Default is 'gray_r'. hist_color : str, optional The color to use for the univariate histograms. Default is 'k'. chain_alpha : float, optional The t... |
something low lets you better visualize what is going on. Default is 0.1. points : array, (`D`,) or (`N`, `D`), optional Array of point(s) to plot onto each marginal and chain. Default is None. covs : array, (`D`, `D`) or (`N`, `D`, `D`), optional Covariance matrix or array of covariance matrices to plot onto each marg... |
covariance matrix for a specific point, set its corresponding entry to `None`. Default is to not plot confidence ellipses for any points. colors : array of str, (`N`,), optional The colors to use for the points in `points`. Default is to use the standard matplotlib RGBCMYK cycle. ci : array, (`num_ci`,), optional List ... |
Default is 0.95 (just plot the 95 percent confidence interval). max_hist_ticks : int, optional The maximum number of ticks for the histogram plots. Default is None (no limit). max_chain_ticks : int, optional The maximum number of y-axis ticks for the chain plots. Default is 6. label_chain_y : bool, optional If True, th... |
bool, optional If True, hide the y axis tick labels for the chain plots. Default is False (show y tick labels). chain_ytick_pad : float, optional The padding (in points) between the y-axis tick labels and the axis for the chain plots. Default is 2.0. label_fontsize : float, optional The font size (in points) to use for... |
float, optional The font size (in points) to use for the axis tick labels. Default is `xtick.labelsize`. chain_label_fontsize : float, optional The font size (in points) to use for the labels of the chain axes. Default is `axes.labelsize`. chain_ticklabel_fontsize : float, optional The font size (in points) to use for ... |
to rotate the x tick labels, in degrees. Default is 90. bottom_sep : float, optional The separation (in relative figure units) between the chains and the marginals. Default is 0.075. suptitle_space : float, optional The amount of space (in relative figure units) to leave for a figure title. Default is 0.1. fixed_height... |
automatically adjust based on `fixed_width` to make the subplots square. fixed_width : float, optional The desired figure width (in inches). Default is `figure.figsize[0]`. l : float, optional The location (in relative figure units) of the left margin. Default is 0.1. r : float, optional The location (in relative figur... |
relative figure units) of the top of the grid of histograms. Overrides `suptitle_space` if present. b1 : float, optional The location (in relative figure units) of the bottom of the grid of histograms. Overrides `bottom_sep` if present. Defaults to 0.1 if `plot_chains` is False. t2 : float, optional The location (in re... |
is 0.2. b2 : float, optional The location (in relative figure units) of the bottom of the grid of chain plots. Default is 0.1. ax_space : float, optional The `w_space` and `h_space` to use (in relative figure units). Default is 0.1. """ masked_weights = None if points is not None: points = scipy.atleast_2d(points) if c... |
"If covariance matrices are provided, len(covs) must equal len(points)!" ) elif covs is None: covs = [None,] * len(points) if colors is None: c_cycle = itertools.cycle(['b', 'g', 'r', 'c', 'm', 'y', 'k']) colors = [c_cycle.next() for p in points] # Create axes: try: k = sampler.flatchain.shape[-1] except AttributeError... |
if labels is None: labels = [''] * k # Set up geometry: # plot_chains = # True: False: # +-----------+ +-----------+ # | +-------+ | | +-------+ | # | | | | | | | | # | | | | | | | | # | | | | | | | | # | +-------+ | | +-------+ | # |
| +-------+ | +-----------+ # | | | | # | +-------+ | # +-----------+ # We retain support for the original suptitle_space keyword, but can # override with t1 as needed: if t1 is None: t1 = 1 - suptitle_space # We retain support for the original bottom_sep keyword, but can override # with b1 as needed: if b1 is None: if... |
b1 = t2 + bottom_sep else: b1 = 0.1 if fixed_height is None and fixed_width is None: # Default: use matplotlib's default width, handle remaining parameters # with the fixed width case below: fixed_width = matplotlib.rcParams['figure.figsize'][0] if fixed_height is None and fixed_width is not None: # Only width specifie... |
- b1) elif fixed_height is not None and fixed_width is None: # Only height specified, compute width to yield square histograms fixed_width = fixed_height * (t1 - b1) / (r - l) # Otherwise width and height are fixed, and we may not have square # histograms, at the user's discretion. wspace = ax_space hspace = ax_space #... |
the chains: f = plt.figure(figsize=(fixed_width, fixed_height)) gs1 = mplgs.GridSpec(k, k) gs1.update(bottom=b1, top=t1, left=l, right=r, wspace=wspace, hspace=hspace) if plot_chains: gs2 = mplgs.GridSpec(1, k) gs2.update(bottom=b2, top=t2, left=l, right=r, wspace=wspace, hspace=hspace) axes = [] # j is the row, i is t... |
if i > 0 and i < j and j < k else None sharex = axes[-1][i] if j > i and j < k else \ (row[-1] if i > 0 and j == k else None) gs = gs1[j, i] if j < k else gs2[:, i] row.append(f.add_subplot(gs, sharey=sharey, sharex=sharex)) if j < k and ticklabel_fontsize is not None: row[-1].tick_params(labelsize=ticklabel_fontsize) ... |
>= k and chain_ticklabel_fontsize is not None: row[-1].tick_params(labelsize=chain_ticklabel_fontsize) axes.append(row) axes = scipy.asarray(axes) # Update axes with the data: if isinstance(sampler, emcee.EnsembleSampler): if chain_mask is None: chain_mask = scipy.ones(sampler.chain.shape[0], dtype=bool) flat_trace = s... |
== 4: if chain_mask is None: chain_mask = scipy.ones(sampler.shape[1], dtype=bool) flat_trace = sampler[temp_idx, chain_mask, burn:, :] flat_trace = flat_trace.reshape((-1, k)) if weights is not None: weights = weights[temp_idx, chain_mask, burn:] weights = weights.ravel() elif sampler.ndim == 3: if chain_mask is None:... |
= weights.ravel() elif sampler.ndim == 2: flat_trace = sampler[burn:, :] flat_trace = flat_trace.reshape((-1, k)) if weights is not None: weights = weights[burn:] weights = weights.ravel() if cutoff_weight is not None and weights is not None: mask = weights >= cutoff_weight * weights.max() flat_trace = flat_trace[mask,... |
the row, i is the column. for i in xrange(0, k): axes[i, i].clear() if plot_hist: axes[i, i].hist(flat_trace[:, i], bins=bins, color=hist_color, weights=masked_weights, normed=True, histtype='stepfilled') if plot_samples: axes[i, i].plot(flat_trace[:, i], scipy.zeros_like(flat_trace[:, i]), ',', alpha=0.1) if points is... |
is not None: xlim = axes[i, i].get_xlim() i_grid = scipy.linspace(xlim[0], xlim[1], 100) axes[i, i].plot( i_grid, scipy.stats.norm.pdf( i_grid, loc=p[i], scale=scipy.sqrt(cov[i, i]) ), c, linewidth=3.0 ) axes[i, i].set_xlim(xlim) if i == k - 1: axes[i, i].set_xlabel(labels[i], fontsize=label_fontsize) plt.setp(axes[i, ... |
im = axes[j, i].hist2d( flat_trace[:, i], flat_trace[:, j], bins=bins, cmap=cmap, weights=masked_weights ) if plot_samples: axes[j, i].plot(flat_trace[:, i], flat_trace[:, j], ',', alpha=0.1) if points is not None: for p, c, cov in zip(points, colors, covs): axes[j, i].plot(p[i], p[j], 'o', color=c) if cov is not None:... |
* 2.0 for cival in ci] a = [2.0 * scipy.sqrt(chi2val * lam[-1]) for chi2val in chi2] b = [2.0 * scipy.sqrt(chi2val * lam[-2]) for chi2val in chi2] ang = scipy.arctan2(v[1, -1], v[0, -1]) for aval, bval in zip(a, b): ell = mplp.Ellipse( [p[i], p[j]], aval, bval, angle=scipy.degrees(ang), facecolor='none', edgecolor=c, l... |
(x[1:] + x[:-1]) # ymid = 0.5 * (y[1:] + y[:-1]) # axes[j, i].contour(xmid, ymid, ct.T, colors='k') if j < k - 1: plt.setp(axes[j, i].get_xticklabels(), visible=False) if i != 0: plt.setp(axes[j, i].get_yticklabels(), visible=False) if i == 0: axes[j, i].set_ylabel(labels[j], fontsize=label_fontsize) if j == k - 1: axe... |
elif isinstance(sampler, emcee.PTSampler): axes[-1, i].plot(sampler.chain[temp_idx, :, :, i].T, alpha=chain_alpha) else: if sampler.ndim == 4: axes[-1, i].plot(sampler[temp_idx, :, :, i].T, alpha=chain_alpha) elif sampler.ndim == 3: axes[-1, i].plot(sampler[:, :, i].T, alpha=chain_alpha) elif sampler.ndim == 2: axes[-1... |
the cutoff weight as a horizontal line and the first sample # which is included as a vertical bar. Note that this won't be quite # the right behavior if the weights are not roughly monotonic. if cutoff_weight is not None: a_wt.axhline(cutoff_weight * weights.max(), linestyle='-', color='r') wi, = scipy.where(weights >=... |
if points is not None: for p, c in zip(points, colors): axes[-1, i].axhline(y=p[i], linewidth=3, color=c) # Reset the xlim since it seems to get messed up: axes[-1, i].set_xlim(left=0) # try: # [axes[-1, i].axhline(y=pt, linewidth=3) for pt in points[i]] # except TypeError: # axes[-1, i].axhline(y=points[i], linewidth=... |
tick._get_text1() for i in xrange(0, k): if max_hist_ticks is not None: axes[k - 1, i].xaxis.set_major_locator(plt.MaxNLocator(nbins=max_hist_ticks - 1)) axes[i, 0].yaxis.set_major_locator(plt.MaxNLocator(nbins=max_hist_ticks - 1)) if plot_chains and max_chain_ticks is not None: axes[k, i].yaxis.set_major_locator(plt.M... |
def plot_sampler_fingerprint( sampler, hyperprior, weights=None, cutoff_weight=None, nbins=None, labels=None, burn=0, chain_mask=None, temp_idx=0, points=None, plot_samples=False, sample_color='k', point_color=None, point_lw=3, title='', rot_x_labels=False, figsize=None ): """Make a plot of the sampler's "fingerprint":... |
: :py:class:`emcee.Sampler` instance or array, (`n_temps`, `n_chains`, `n_samp`, `n_dim`), (`n_chains`, `n_samp`, `n_dim`) or (`n_samp`, `n_dim`) The sampler to plot the chains/marginals of. Can also be an array of samples which matches the shape of the `chain` attribute that would be present in a :py:class:`emcee.Samp... |
so that the hyperparameters can all be shown on the same axis. weights : array, (`n_temps`, `n_chains`, `n_samp`), (`n_chains`, `n_samp`) or (`n_samp`,), optional The weight for each sample. This is useful for post-processing the output from MultiNest sampling, for instance. cutoff_weight : float, optional If `weights`... |
all points. nbins : int or array of int, (`D`,), optional The number of bins dividing [0, 1] to use for each histogram. If a single int is given, this is used for all of the hyperparameters. If an array of ints is given, these are the numbers of bins for each of the hyperparameters. The default is to determine the numb... |
using the Freedman-Diaconis rule. labels : array of str, (`D`,), optional The labels for each hyperparameter. Default is to use empty strings. burn : int, optional The number of samples to burn before making the marginal histograms. Default is zero (use all samples). chain_mask : (index) array, optional Mask identifyin... |
to use all chains. temp_idx : int, optional Index of the temperature to plot when plotting a :py:class:`emcee.PTSampler`. Default is 0 (samples from the posterior). points : array, (`D`,) or (`N`, `D`), optional Array of point(s) to plot as horizontal lines. Default is None. plot_samples : bool, optional If True, the s... |
The color to plot the samples in. Default is 'k', meaning black. point_color : str or list of str, optional The color to plot the individual points in. Default is to loop through matplotlib's default color sequence. If a list is provided, it will be cycled through. point_lw : float, optional Line width to use when plot... |
Title to use for the plot. rot_x_labels : bool, optional If True, the labels for the x-axis are rotated 90 degrees. Default is False (do not rotate labels). figsize : 2-tuple, optional The figure size to use. Default is to use the matplotlib default. """ try: k = sampler.flatchain.shape[-1] except AttributeError: # Ass... |
k = sampler.shape[-1] # Process the samples: if isinstance(sampler, emcee.EnsembleSampler): if chain_mask is None: chain_mask = scipy.ones(sampler.chain.shape[0], dtype=bool) flat_trace = sampler.chain[chain_mask, burn:, :] flat_trace = flat_trace.reshape((-1, k)) elif isinstance(sampler, emcee.PTSampler): if chain_mas... |
= sampler[temp_idx, chain_mask, burn:, :] flat_trace = flat_trace.reshape((-1, k)) if weights is not None: weights = weights[temp_idx, chain_mask, burn:] weights = weights.ravel() elif sampler.ndim == 3: if chain_mask is None: chain_mask = scipy.ones(sampler.shape[0], dtype=bool) flat_trace = sampler[chain_mask, burn:,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.