API Reference#

This page documents the public MorphZ API. Private helpers whose names start with _ are intentionally omitted.

Morph Approximations#

class morphZ.KDEBase[source]#

Base class for KDE implementations with JSON bandwidth loading support.

class morphZ.Morph_Indep(data, kde_bw='silverman', param_names=None, bw_json_path=None, verbose=False, bw_method=None)[source]#

Independent KDE approximation for multivariate posterior samples.

Each parameter is modeled with a one-dimensional Gaussian KDE and the joint density is evaluated as the product of those marginal densities. This is the fastest Morph approximation and assumes weak dependence between parameters.

Fit one one-dimensional KDE per parameter.

Parameters:
  • data (array-like) – 2D array of shape (n_samples, n_params) used to fit the KDEs.

  • kde_bw (str, scalar, or dict, optional) – The method used to estimate the bandwidth of the KDE. Can also be used to override specific parameter bandwidths when using JSON files. Defaults to ‘silverman’.

  • bw_method (str, scalar, or dict, optional) – Backward‑compat alias for kde_bw.

  • param_names (list of str, optional) – Names of the parameters. If None, parameters are named by their index.

  • bw_json_path (str, optional) – Path to JSON file containing bandwidth values. If provided, bandwidths will be loaded from this file and kde_bw can be used to override specific parameters.

  • verbose (bool, optional) – Print fitting details per parameter.

Suggestions:
  • kde_bw can be a number (e.g., 0.8) for slightly tighter KDEs or a dict mapping parameter names to custom values.

  • Supported selectors from bw_method.py for SciPy‑compatible factors: 'scott', 'silverman', 'isj' (Botev’s ISJ), 'cv_iso' (isotropic CV), 'cv_diag' (diagonal CV → scalar factor via geometric mean). Choose 'cv_iso'/'cv_diag' for higher fidelity at extra cost.

  • Use bw_json_path with values from compute_and_save_bandwidths to ensure consistent settings between different KDE approximations.

Raises:

ValueError – If data is not two-dimensional, param_names has the wrong length, or both bandwidth aliases are specified with different values.

logpdf_kde(point)[source]#

Evaluate the approximated joint log density at a point.

The total log probability is the sum of the log probabilities from each 1D KDE, assuming independence.

Parameters:

point (array-like) – The point at which to evaluate the log probability density.

Returns:

The log probability density at the given point.

Return type:

float

resample(size=1)[source]#

Draw independent samples from the fitted marginal KDEs.

Parameters:

size (int, optional) – The number of samples to generate. Defaults to 1.

Returns:

An array of resampled points with shape (size, n_params).

Return type:

np.ndarray

class morphZ.Morph_Pairwise(data, param_mi, param_names=None, kde_bw='silverman', min_mi=None, verbose=False, bw_json_path=None, bw_method=None, top_k_greedy=1)[source]#

Greedy pairwise KDE approximation guided by mutual information (MI).

Pairs with highest MI are modeled jointly with 2D KDEs; remaining variables are modeled as independent 1D KDEs. This balances flexibility and speed.

Use dependency_tree.compute_and_plot_mi_tree or Nth_TC.compute_and_save_tc to generate MI pairs if you need persistent files for reuse.

Initialize and fit pairwise/independent KDE components.

Parameters:
  • data (ndarray) – Samples with shape (n_samples, n_params).

  • param_mi (str | list) – Either a path to params_MI.json (as saved by dependency utilities) or a list of [a, b, mi] entries where a and b are names or indices.

  • param_names (list[str] | None) – Optional parameter names; if None, defaults to ["param_i"].

  • kde_bw (str | float | dict) – Bandwidth method or numeric factor. If a dict, values override JSON bandwidths per parameter name.

  • bw_method (str | float | dict | None) – Backward‑compat alias for kde_bw.

  • min_mi (float | None) – Filter out pairs with MI below this value before selection.

  • verbose (bool) – Print helpful fitting logs.

  • bw_json_path (str | None) – Path to bandwidth JSON produced by compute_and_save_bandwidths(..., n_order=2). When provided, speeds up and standardizes bandwidths. You can still override individual parameters via the kde_bw dict.

  • top_k_greedy (int) – Try K seeded greedy runs. Run i in [0..K-1] seeds the selection with the i-th highest MI pair from the sorted candidate list, then completes selection greedily. The run with the largest total MI is kept. Defaults to 1 (current behavior).

Notes

  • When kde_bw is a list per pair, the geometric mean is used to obtain a scalar suitable for 2D gaussian_kde.

  • Supported selectors from bw_method.py for SciPy‑compatible factors: 'scott', 'silverman', 'isj' (Botev’s ISJ), 'cv_iso' (isotropic CV), 'cv_diag' (diagonal CV → scalar factor via geometric mean). Try 'cv_iso' when pairwise components need tighter fits; prefer 'silverman' for speed.

logpdf(x)[source]#

Evaluate the joint log density under the pairwise KDE approximation.

Parameters:

x (ndarray | List[float]) – Either a single point with shape (d,) or a batch with shape (N, d) (both accepted; columns are dimensions).

Returns:

Log density for each point; returns a scalar for a single input point.

Return type:

float or ndarray

pdf(x)[source]#

Return exp(logpdf(x)) as a convenience wrapper.

Parameters:

x (ndarray | List[float])

resample(n_resamples, random_state=None)[source]#

Draw i.i.d. samples from the fitted approximation.

Parameters:
  • n_resamples (int) – Number of samples to generate.

  • random_state (int | None) – Optional integer seed for reproducibility.

Returns:

Samples with shape (n_resamples, d).

Return type:

np.ndarray

class morphZ.Morph_Group(data, param_tc=None, param_names=None, kde_bw='silverman', min_tc=None, verbose=False, bw_json_path=None, bw_method=None, top_k_greedy=1, shuffle_samples=True, random_state=None, n_order=2)[source]#

Group‑based KDE approximation guided by N‑th order Total Correlation (TC).

Disjoint groups with largest TC are modeled by multi‑dimensional KDEs; any leftovers are modeled as independent 1D KDEs. Use Nth_TC.compute_and_save_tc to generate and persist groups.

Initialize and fit group/independent KDE components.

Parameters:
  • data (ndarray) – Samples with shape (n_samples, n_params).

  • param_tc (str | list | None) – Either a path to a TC JSON file with entries like [[group_names], tc] or an in‑memory list of such pairs. When omitted, total correlations are computed automatically from data.

  • param_names (list[str] | None) – Optional names for parameters.

  • kde_bw (str | float | dict) – Bandwidth method/factor or per‑name overrides.

  • bw_method (str | float | dict | None) – Backward‑compat alias for kde_bw.

  • min_tc (float | None) – Discard groups with TC below this threshold.

  • verbose (bool) – Print helpful fitting logs.

  • bw_json_path (str | None) – Path to bandwidth JSON (e.g., produced by compute_and_save_bandwidths(..., n_order=k, group_format="groups")).

  • top_k_greedy (int) – Try K seeded greedy runs. Run i in [0..K-1] seeds the selection with the i-th highest‑TC group from the sorted candidate list, then completes selection greedily. The run with the largest total TC is kept. Defaults to 1 (current behavior).

  • shuffle_samples (bool) – Independently shuffle the samples within each parameter column before fitting. This leaves the parameter (column) order unchanged and prevents jointly ordered columns from producing a singular covariance in gaussian_kde. Defaults to True.

  • random_state (int | None) – Optional seed for the per-dimension sample shuffling.

  • n_order (int) – Group order used when param_tc is omitted. Defaults to 2.

Notes

  • For group KDEs (dim>1), a single scalar bandwidth is required by gaussian_kde; we use the geometric mean when a list is given.

  • Supported selectors from bw_method.py for SciPy‑compatible factors: 'scott', 'silverman', 'isj' (Botev’s ISJ), 'cv_iso' (isotropic CV), 'cv_diag' (diagonal CV → scalar factor via geometric mean). 'cv_iso' often improves multi‑D group fits but is slower.

logpdf(x)[source]#

Evaluate the joint log density under the group KDE approximation.

Parameters:

x (ndarray | List[float]) – Either a single point with shape (d,) or a batch with shape (N, d) (both accepted; columns are dimensions).

Returns:

Log density for each point; returns a scalar for a single input point.

Return type:

float or ndarray

pdf(x)[source]#

Return exp(logpdf(x)) as a convenience wrapper.

Parameters:

x (ndarray | List[float])

resample(n_resamples, random_state=None)[source]#

Draw i.i.d. samples from the fitted approximation.

Parameters:
  • n_resamples (int) – Number of samples to generate.

  • random_state (int | None) – Optional integer seed for reproducibility.

Returns:

Samples with shape (n_resamples, d).

Return type:

np.ndarray

class morphZ.Morph_Tree(data, tree_file, param_names=None, kde_bw='silverman', bw_json_path=None, bw_method=None)[source]#

Chow-Liu tree KDE approximation for multivariate posterior samples.

The joint density is approximated as p(root) times conditional factors p(child | parent) along the dependency tree edges.

Fit root and branch KDEs from a saved dependency tree.

Parameters:
  • data (array-like) – 2D array of shape (n_samples, n_params) used to fit the KDEs.

  • tree_file (str) – Path to the JSON file containing the tree structure.

  • param_names (list of str, optional) – Names of the parameters. If None, parameters are named by their index.

  • kde_bw (str, scalar, or dict, optional) – The method used to estimate the bandwidth of the KDE. Can also be used to override specific parameter bandwidths when using JSON files. Defaults to ‘silverman’.

  • bw_json_path (str, optional) – Path to JSON file containing bandwidth values. If provided, bandwidths will be loaded from this file and kde_bw can be used to override specific parameters.

  • bw_method (str, scalar, or dict, optional) – Backward‑compat alias for kde_bw.

Suggestions:
  • Generate tree_file via dependency_tree.compute_and_plot_mi_tree to ensure consistency with MI weights and labels used elsewhere.

  • When passing a dict for kde_bw, keys must match param_names.

  • Supported selectors from bw_method.py for SciPy‑compatible factors: 'scott', 'silverman', 'isj' (Botev’s ISJ), 'cv_iso' (isotropic CV), 'cv_diag' (diagonal CV → scalar factor via geometric mean). For trees, 'cv_iso' can offer a good accuracy/runtime trade‑off.

Raises:

ValueError – If data is not two-dimensional, param_names has the wrong length, the tree has no unique root, or both bandwidth aliases are specified with different values.

logpdf(point)[source]#

Evaluate the approximated joint log density at a point.

Parameters:

point (array-like) – The point at which to evaluate the log probability density.

Returns:

The log probability density at the given point.

Return type:

float

resample(n_resamples, nwalkers=None, progress=True)[source]#

Draw samples from the fitted tree approximation using emcee.

The number of MCMC steps and thinning are adapted to generate the requested number of output samples.

Parameters:
  • n_resamples (int) – The desired number of resamples.

  • nwalkers (int, optional) – The number of walkers. Defaults to 2 * ndim.

  • progress (bool, optional) – Whether to display an emcee progress bar. Defaults to True.

Returns:

An array of resampled points with shape (n_resamples, n_dims).

Return type:

np.ndarray

Raises:

ValueError – If the chain produces no post-thinning samples.

Tips:
  • If too few independent samples are produced, increase n_steps by raising n_resamples or override the initial autocorrelation guess.

  • For speed, consider using PairwiseKDE/GroupKDE resampling when the tree structure is not essential.

Evidence Estimation#

morphZ.evidence(post_samples, log_posterior_function=None, log_posterior_values=None, n_resamples=1000, thin=1, kde_fraction=0.5, bridge_start_fraction=0.5, max_iter=2000, tol=0.01, morph_type='2_group', param_names=None, output_path=None, n_estimations=1, kde_bw='silverman', verbose=False, top_k_greedy=None, plot=False, prefer_corner=True, pool=None, show_progress=True, shuffle=True, overwrite_path=False)[source]#

Compute log evidence using morphological bridge sampling with KDE proposals.

This orchestrates proposal construction (independent, pairwise, or grouped KDE), draws proposal samples, and performs bridge sampling.

Parameters:
  • post_samples (ndarray) – Posterior samples of shape (N, d).

  • log_posterior_function (callable) – Callable taking a single vector theta with shape (d,) and returning the log target density. Required even when log_posterior_values is provided because proposal samples are evaluated during bridge sampling.

  • log_posterior_values (ndarray | None) – Log posterior values for post_samples; shape (N,). Used to avoid re‑evaluating expensive log posteriors. If None, values are precomputed for the bridge subset before bridge sampling.

  • n_resamples (int) – Number of proposal samples per estimation. Typical range 500–5000 depending on dimensionality.

  • thin (int) – Thinning stride applied to post_samples and, when provided, log_posterior_values to reduce autocorrelation. Use thin>1 if your MCMC is highly autocorrelated.

  • kde_fraction (float) – Fraction of the (thinned) chain used to fit the proposal KDE(s). Remaining samples are reserved for the bridge. Values between 0.3 and 0.7 are common.

  • bridge_start_fraction (float) – Fraction of (thinned) chain index from which the bridge uses the posterior samples. E.g., 0.5 starts at the latter half to reduce dependence with KDE fitting.

  • max_iter (int) – Max bridge iterations.

  • tol (float) – Convergence tolerance for the bridge fixed‑point update.

  • morph_type (MorphType) – Proposal family. Use "indep" for a product of 1D KDEs, "pair" for greedy pairwise KDEs using MI ranking, or "{k}_group" for group KDEs using k-order total correlation groups from Nth_TC. Common grouped values are "2_group", "3_group", "4_group", and "5_group".

  • param_names (list[str] | None) – Optional names for parameters; used for bandwidth JSONs and reporting. Defaults to ["param_i"].

  • output_path (str | None) – Directory for artifacts (bandwidth JSONs, MI/TC files, and results). When omitted, a temporary directory is created for the duration of the run and removed afterward.

  • n_estimations (int) – Number of independent bridge estimates to run. Use >1 to gauge variability; results are saved as a 2‑column text file with logz and err per row.

  • kde_bw (BandwidthMethod | float | dict | silverman) – Bandwidth selector/factor. Supported selectors from bw_method.py: 'scott', 'silverman', 'isj' (Botev’s ISJ), 'cv_iso' (isotropic CV), 'cv_diag' (diagonal CV → scalar factor). You can also pass a number (e.g., 0.9) or a {name: value} dict to override specific parameters when using bw_json_path.

  • verbose (bool) – Print fitting details for KDE components.

  • top_k_greedy (int) – For pair and *_group morph types, run K seeded greedy selections starting from each of the top‑K candidates (by MI or TC), and keep the selection with the highest total score. Default is 1 (single greedy pass as before).

  • plot (bool) – If True, saves a corner plot comparing posterior samples (black) and proposal samples (red) as a PNG in output_path. The plot is not displayed.

  • prefer_corner (bool) – If True, attempts to render the corner plot using the corner package with filled contours and the following style: bins=50, quantiles=(0.05,0.5,0.95), show_titles=True, title_fmt='.2f', plot_datapoints=True, fill_contours=True, levels=(0.5,0.8,0.95), smooth=0.9. If corner is not installed, a warning is emitted and the plot is skipped.

  • pool (int | "max" | None) – Worker processes for evaluating proposal samples during bridge sampling. Use "max" to match os.cpu_count(). When None or <=1 evaluations run serially.

  • show_progress (bool) – If True and tqdm is available, show a progress bar while evaluating proposal samples (expensive likelihood calls).

  • shuffle (bool) – If True (default), randomly permute the thinned posterior samples and their corresponding log-posterior values before KDE fitting and bridge sampling. The same permutation is applied to both arrays so sample–log-prob correspondence is preserved.

  • overwrite_path (bool) – If True, recompute and overwrite all cached files (bandwidth JSONs and MI/TC files) even if they already exist on disk. Default is False (skip recomputation when files exist).

Returns:

A list of [logz, err] for each estimation.

Return type:

list[[float, float]]

Suggestions:
  • Start with morph_type='2_group' for speed. If diagnostics look poor, try ``’3_group’``to capture dependencies.

  • For bandwidths, try 'silverman' for speed, 'cv_iso' for tighter fits, or 'isj' as a robust nonparametric choice.

  • Use n_estimations>=3 to assess stability and report mean/SE.

morphZ.bridge_sampling_ln(f, g, samples_post, log_post, samples_prop, tol=0.01, max_iter=5000, estimation_label=None, verbose=False, show_progress=True)[source]#

Estimate log marginal likelihood log p(y) using bridge sampling in log space.

Parameters:
  • f – Callable that returns the log of the unnormalized target density for a single parameter vector, i.e. log p(y, theta) = log p(y|theta) + log p(theta). Called as f(theta) with theta shaped (d,).

  • g – Callable that returns the log proposal density. Called as g(theta_T) where theta_T has shape (d, n) (samples in columns).

  • samples_post (ndarray) – Posterior samples of shape (N1, d) used on the target side of the bridge.

  • log_post (ndarray) – Precomputed log target values for samples_post of shape (N1,). This saves recomputation of expensive likelihoods.

  • samples_prop (ndarray) – Proposal samples of shape (N2, d) used on the proposal side of the bridge. These are typically drawn from a KDE.

  • tol (float) – Convergence tolerance on successive log‑evidence updates. Smaller values increase accuracy but may require more iterations.

  • max_iter (int) – Maximum number of bridge iterations.

  • show_progress (bool) – If True and tqdm is available, show a progress bar while evaluating proposal samples (expensive likelihood calls).

  • estimation_label (str | None)

  • verbose (bool)

Returns:

[log_evidence, rmse_estimate] where the second element is an approximate RMSE estimate computed via compute_bridge_rmse.

Return type:

list[float, float]

Suggestions:
  • If f occasionally fails (e.g., numerical domain errors), this function automatically skips those proposal samples and continues.

  • Use a moderate tol (1e‑4 to 1e‑3) and cap max_iter to prevent long runs on difficult posteriors.

morphZ.compute_bridge_rmse(log_p_final, f, g, samples_prop, samples_post, log_f_prop, log_g_prop, log_f_post, log_g_post, s1, s2, posterior_acf_func=<function compute_rho_f2_0_via_correlate>)[source]#

Estimate the root mean square error (RMSE) for the bridge sampling result.

Parameters:
  • log_p_final (float) – Final bridge estimate of log evidence.

  • f (callable) – Same target/proposal log‑density callables as used in bridge_sampling_ln.

  • g (callable) – Same target/proposal log‑density callables as used in bridge_sampling_ln.

  • samples_prop (ndarray) – Proposal samples (N2, d).

  • samples_post (ndarray) – Posterior samples (N1, d).

  • log_f_prop (ndarray) – Cached log densities evaluated on corresponding samples.

  • log_g_prop (ndarray) – Cached log densities evaluated on corresponding samples.

  • log_f_post (ndarray) – Cached log densities evaluated on corresponding samples.

  • log_g_post (ndarray) – Cached log densities evaluated on corresponding samples.

  • s1 (float) – Mixing coefficients N1/(N1+N2) and N2/(N1+N2).

  • s2 (float) – Mixing coefficients N1/(N1+N2) and N2/(N1+N2).

  • posterior_acf_func (callable) – Function estimating the integrated autocorrelation time of f2 terms from the posterior side. By default a fast correlate‑based estimator is used; if you have statsmodels available, consider utils.compute_rho_f2_0_via_statsmodels.

Returns:

Approximate RMSE of the log‑evidence estimate.

Return type:

float

Note

This is a heuristic approximation following common practice for bridge sampling diagnostics; it is useful for relative comparisons across runs.

morphZ.bridge_multiprocess.bridge_sampling_ln(f, g, samples_post, log_post, samples_prop, tol=0.01, max_iter=5000, estimation_label=None, verbose=False, pool=None, num_workers=None, show_progress=True)[source]#

Estimate log marginal likelihood log p(y) using bridge sampling in log space.

Parameters:
  • f – Callable that returns the log of the unnormalized target density for a single parameter vector, i.e. log p(y, theta) = log p(y|theta) + log p(theta). Called as f(theta) with theta shaped (d,).

  • g – Callable that returns the log proposal density. Called as g(theta_T) where theta_T has shape (d, n) (samples in columns).

  • samples_post (ndarray) – Posterior samples of shape (N1, d) used on the target side of the bridge.

  • log_post (ndarray) – Precomputed log target values for samples_post of shape (N1,). This saves recomputation of expensive likelihoods.

  • samples_prop (ndarray) – Proposal samples of shape (N2, d) used on the proposal side of the bridge. These are typically drawn from a KDE.

  • tol (float) – Convergence tolerance on successive log‑evidence updates. Smaller values increase accuracy but may require more iterations.

  • max_iter (int) – Maximum number of bridge iterations.

  • pool – Optional parallel pool. Accepts: - None: run serially. - int: create an internal multiprocessing pool with that many workers. - any object with a map method: treated as an external pool.

  • num_workers (Optional[int]) – Deprecated alias for pool kept for backward compatibility.

  • show_progress (bool) – If True and tqdm is available, show a progress bar while evaluating proposal samples (expensive likelihood calls).

  • estimation_label (str | None)

  • verbose (bool)

Returns:

[log_evidence, rmse_estimate] where the second element is an approximate RMSE estimate computed via compute_bridge_rmse.

Return type:

list[float, float]

Suggestions:
  • If f occasionally fails (e.g., numerical domain errors), this function automatically skips those proposal samples and continues.

  • Use a moderate tol (1e‑4 to 1e‑3) and cap max_iter to prevent long runs on difficult posteriors.

morphZ.bridge_multiprocess.compute_bridge_rmse(log_p_final, f, g, samples_prop, samples_post, log_f_prop, log_g_prop, log_f_post, log_g_post, s1, s2, posterior_acf_func=<function compute_rho_f2_0_via_correlate>)[source]#

Estimate the root mean square error (RMSE) for the bridge sampling result.

Parameters:
  • log_p_final (float) – Final bridge estimate of log evidence.

  • f (callable) – Same target/proposal log‑density callables as used in bridge_sampling_ln.

  • g (callable) – Same target/proposal log‑density callables as used in bridge_sampling_ln.

  • samples_prop (ndarray) – Proposal samples (N2, d).

  • samples_post (ndarray) – Posterior samples (N1, d).

  • log_f_prop (ndarray) – Cached log densities evaluated on corresponding samples.

  • log_g_prop (ndarray) – Cached log densities evaluated on corresponding samples.

  • log_f_post (ndarray) – Cached log densities evaluated on corresponding samples.

  • log_g_post (ndarray) – Cached log densities evaluated on corresponding samples.

  • s1 (float) – Mixing coefficients N1/(N1+N2) and N2/(N1+N2).

  • s2 (float) – Mixing coefficients N1/(N1+N2) and N2/(N1+N2).

  • posterior_acf_func (callable) – Function estimating the integrated autocorrelation time of f2 terms from the posterior side. By default a fast correlate‑based estimator is used; if you have statsmodels available, consider utils.compute_rho_f2_0_via_statsmodels.

Returns:

Approximate RMSE of the log‑evidence estimate.

Return type:

float

Note

This is a heuristic approximation following common practice for bridge sampling diagnostics; it is useful for relative comparisons across runs.

Bandwidth Selection#

morphZ.bw_method.scott_factor(data)[source]#

Return the exact factor used by SciPy’s gaussian_kde with bw_method=’scott’.

This delegates to gaussian_kde(…).factor to ensure identical behavior to the installed SciPy version. No fallback is provided; gaussian_kde is required for this project.

Parameters:

data (ndarray | list | tuple)

Return type:

float

morphZ.bw_method.silverman_factor(data)[source]#

Return the exact factor used by SciPy’s gaussian_kde with bw_method=’silverman’.

This delegates to gaussian_kde(…).factor to ensure identical behavior to the installed SciPy version. No fallback is provided; gaussian_kde is required for this project.

Parameters:

data (ndarray | list | tuple)

Return type:

float

morphZ.scott_rule(data)[source]#

Legacy Scott rule: returns per-dimension numeric bandwidth(s) h_j in data units such that h_j = factor * sigma_j where factor = scott_factor and sigma_j = std(X[:, j]) (population std).

Parameters:

data (ndarray | list | tuple)

Return type:

float | ndarray

morphZ.silverman_rule(data)[source]#

Legacy Silverman rule (robust): per-dimension bandwidths in data units.

For 1D uses: h = 0.9 * min(std, IQR/1.34) * n**(-1/5) For ND uses robust per-dim scales with the multivariate constant.

Parameters:

data (ndarray | list | tuple)

Return type:

float | ndarray

morphZ.botev_isj_bandwidth(data, n_bins=4096, limits=None)[source]#

ISJ bandwidth(s) in data units. For ND returns per-dimension h_j. Use botev_isj_factor to convert to a SciPy-compatible scalar factor.

Parameters:
  • data (ndarray | list | tuple)

  • n_bins (int)

  • limits (Tuple[float, float] | None)

Return type:

float | ndarray

morphZ.bw_method.botev_isj_factor(data, n_bins=4096)[source]#

Convert ISJ per-dimension bandwidths to a SciPy factor.

factor = exp(mean(log(h_j / s_j))) where s_j is sample std (ddof=1). For 1D this is simply h / s.

Parameters:
  • data (ndarray | list | tuple)

  • n_bins (int)

Return type:

float

morphZ.cross_validation_bandwidth(data, kind='isotropic', factor_grid=None, cv=10, random_state=None, return_diag_h=False)[source]#

Cross-validation bandwidth selection that returns a SciPy-compatible scalar factor by optimizing the summed log-likelihood using scipy.stats.gaussian_kde.

Parameters:
  • data ((n_samples, n_features))

  • kind ('isotropic' or 'diagonal') –

    • ‘isotropic’: searches scalar factors directly (best match for SciPy).

    • ’diagonal’: performs coordinate-descent search for per-dimension bandwidths h_j (in data units) by scoring with gaussian_kde on scaled data; returns the equivalent SciPy scalar factor via geometric mean.

  • factor_grid (optional grid of candidate factors for isotropic search.)

  • cv (number of folds)

  • random_state (RNG seed)

  • return_diag_h (if True and kind=='diagonal', also return the per-dim h vector)

Return type:

float (best SciPy factor) or (factor, h_vector) when return_diag_h=True.

morphZ.select_bandwidth(data, method='silverman')[source]#

Unified bandwidth selector returning SciPy-compatible scalar factors.

  • ‘scott’: returns scott_factor

  • ‘silverman’: returns silverman_factor

  • ‘isj’: returns botev_isj_factor

  • ‘cv_iso’: cross-validated isotropic factor (optimizes SciPy log-lik)

  • ‘cv_diag’: diagonal CV -> returns SciPy factor (geometric mean); use select_bandwidth(…); with method=’cv_diag’ to get scalar factor, or call cross_validation_bandwidth(…, kind=’diagonal’, return_diag_h=True) to also get per-dimension h_j.

Parameters:
  • data (ndarray | list | tuple)

  • method (Literal['scott', 'silverman', 'isj', 'cv_iso', 'cv_diag'])

Return type:

float | ndarray

morphZ.compute_and_save_bandwidths(data, method, param_names, output_path, n_order, in_path=None, group_format='pairs', top_k_greedy=1)[source]#

Compute SciPy-compatible scalar factors for each parameter or group and save a simplified JSON file. Each entry is [param1, …, factor].

Note: for group-level joint estimation we produce a single scalar factor that can be passed to gaussian_kde.set_bandwidth(factor) for subsequent evaluations. For diagonal/group-per-dimension exact control consider returning per-dim h_j and applying them with a custom KDE wrapper.

Parameters:
  • data ((n_samples, n_features))

  • method ({'scott','silverman','isj','cv_iso','cv_diag'})

  • param_names (list[str])

  • output_path (str)

  • n_order (int) – Group order (2 for pairs, k for k-groups) used only for output filename.

  • in_path (str | None) – Optional path to MI/TC JSON (pairs or groups). When provided, groups are selected greedily from this candidate list.

  • group_format ({'pairs','groups'}) – Format of in_path entries.

  • top_k_greedy (int) – Run K seeded greedy selections starting from each of the top-K candidates (by MI or TC), then keep the selection with the largest total score. Default 1 (single greedy pass).

Return type:

list[list[str | float]]

Dependency Analysis#

Total Correlation#

morphZ.Nth_TC.stable_seed_for_indices(base_seed, indices)[source]#

Derive a deterministic 32‑bit seed from a base seed and an index tuple.

Parameters:
  • base_seed (int)

  • indices (tuple[int, ...])

Return type:

int

morphZ.Nth_TC.compute_marginal_log_p(samples, bw_method, loo, seed, eps)[source]#

Compute 1‑D marginal log‑densities at the provided sample points.

Returns the log densities (shape (n_dims, n_samples)) and the RNG used.

Parameters:
  • samples (ndarray)

  • bw_method (str | float | None)

  • loo (bool)

  • seed (int)

  • eps (float)

Return type:

tuple[ndarray, Generator]

morphZ.Nth_TC.compute_tc_for_indices(indices, samples_T, log_p, bw_method, loo, eps, rng)[source]#

Compute TC/MI for a single index group.

Parameters:
  • indices (tuple[int, ...])

  • samples_T (ndarray)

  • log_p (ndarray)

  • bw_method (str | float)

  • loo (bool)

  • eps (float)

  • rng (Generator)

Return type:

float

morphZ.Nth_TC.compute_total_correlation(samples, n_order=2, bw_method='silverman', loo=True, seed=0, eps=1e-300, n_workers=0, show_progress=True, auto_thin=True)[source]#

Compute a symmetric matrix of pairwise mutual informations (n_order=2) or a list of n-order total correlations using KDE.

Parameters:
  • samples (np.ndarray) – 2D array of shape (n_samples, n_dims).

  • n_order (int, optional) – Order of total correlation. Defaults to 2 (pairwise MI).

  • bw_method (str or float, optional) – Bandwidth method for KDE. Defaults to “silverman”.

  • loo (bool, optional) – If True, use leave-one-out correction. Defaults to True.

  • seed (int, optional) – Random seed. Defaults to 0.

  • eps (float, optional) – Small value to clip PDF values to avoid log(0). Defaults to 1e-300.

  • n_workers (int, optional) – >1 enables threaded parallelism; 0/1 uses serial path.

  • show_progress (bool, optional) – If True and tqdm is available, show progress over groups. Defaults to True.

  • auto_thin (bool, optional) – If True, downsample large, high-order problems for speed. Defaults to True.

Returns:

For n_order=2, a symmetric matrix of pairwise MIs.

For n_order>2, a list of (indices, tc_value) tuples.

Return type:

np.ndarray | list

morphZ.Nth_TC.plot_tc_heatmap(mi, labels, outfile='mi_heatmap.png', cmap='magma')[source]#

Save a heat-map of the MI matrix (only for n_order=2).

Parameters:
  • mi (np.ndarray) – The mutual information matrix.

  • labels (Sequence[str]) – The labels for the axes.

  • outfile (str, optional) – The output file path. Defaults to “mi_heatmap.png”.

  • cmap (str, optional) – The colormap to use. Defaults to “magma”.

Return type:

None

morphZ.Nth_TC.compute_and_save_tc(samples, names=None, n_order=2, bw_method='silverman', loo=True, seed=0, out_path=None, n_workers=0, show_progress=True, auto_thin=True)[source]#

Compute TC, visualise (for n=2), and save all TC values.

Parameters:
  • samples (np.ndarray) – 2D array of shape (n_samples, n_dims).

  • names (Optional[Iterable[str]], optional) – Names of the parameters. Defaults to None.

  • n_order (int, optional) – Order of total correlation. Defaults to 2.

  • bw_method (str | float, optional) – Bandwidth method for KDE. Defaults to “silverman”.

  • loo (bool, optional) – If True, use leave-one-out correction. Defaults to True.

  • seed (int, optional) – Random seed. Defaults to 0.

  • out_path (Optional[str], optional) – The output directory path. Defaults to None.

  • n_workers (int, optional) – >1 enables threaded parallelism; 0/1 uses serial path.

  • show_progress (bool, optional) – If True and tqdm is available, show progress over groups. Defaults to True.

  • auto_thin (bool, optional) – If True, downsample large, high-order problems for speed. Defaults to True.

Returns:

The total correlation results.

Return type:

np.ndarray | list

Utilities#

morphZ.setup_logging(level=20, stream=None, fmt=None)[source]#

Configure root logging for morphZ consumers.

Parameters:
  • level (int) – Logging level passed to logging.basicConfig().

  • stream – Optional stream override (sys.stdout by default).

  • fmt (str | None) – Optional logging format string. Defaults to a concise pattern.

Return type:

None

morphZ.utils.compute_rho_f2_0_via_statsmodels(f2_values, nlags=None)[source]#

Estimate integrated autocorrelation time using statsmodels.acf.

The integrated autocorrelation time is defined as:

tau = 1 + 2 * sum_{lag>=1} acf(lag)

where the sum stops at the first negative value.

Parameters:
  • f2_values – One-dimensional values computed from posterior samples.

  • nlags – Maximum number of lags to compute. If None, uses len(f2_values) - 1.

Returns:

Estimated integrated autocorrelation time.

Return type:

float

morphZ.utils.compute_rho_f2_0_via_correlate(f2_values)[source]#

Estimate integrated autocorrelation time using scipy.signal.correlate.

The integrated autocorrelation time is defined as:

tau = 1 + 2 * sum_{lag>=1} acf(lag)

where the sum stops at the first negative value.

Parameters:

f2_values – One-dimensional values computed from posterior samples.

Returns:

Estimated integrated autocorrelation time.

Return type:

float

morphZ.utils.log_plus(x, y)[source]#

Compute log(exp(x) + exp(y)) in a numerically stable way.

Parameters:
  • x – First log-space scalar.

  • y – Second log-space scalar.

Returns:

Log-space sum of the two inputs.

Return type:

float

morphZ.utils.log_sum(vec)[source]#

Compute log(sum(exp(vec))) for a vector of log-space values.

Parameters:

vec – Sequence of log-space scalar values.

Returns:

Stable log-space sum.

Return type:

float

morphZ.utils.error_bound_from_oscillation(x)[source]#

Estimate a fixed-point error bound from oscillatory iterates.

The first 20 percent of values are discarded as transient behavior, then the bound is the remaining range max(x) - min(x).

Parameters:

x – Sequence of fixed-point iterates.

Returns:

Oscillation range after discarding the initial transient.

Return type:

float

Raises:

ValueError – If fewer than two post-transient iterates remain.