trianglechain package

Submodules

trianglechain.BaseChain module

class trianglechain.BaseChain.BaseChain(fig=None, size=4, **kwargs)[source]

Bases: object

Base class to produce plots. Parameters defined for this class are used for all plots that are added to the figure. If you want to change the parameters for a specific plot, you can do so by passing the parameters to the plotting function.

Parameters:
  • fig – matplotlib figure, default: None

  • size – size of the panels, default: 4

  • params – list of parameters to plot, default: “all”

  • params_from – sample or list of samples from which the parameters should be taken, default: None

  • ranges – dictionary with the ranges for the parameters

  • names – list of names of the parameters, only used when input data is unstructured array

  • labels – list of labels (e.g. latex style) for the parameters for the plot

  • fill – if the contours should be filled, default: False

  • grid – if the grid should be plotted, default: False

  • tri – if upper or lower triangle should be plotted, default: “lower”

  • orientation – orientation for LineChain, default: “horizontal”

  • line_space – space between lines in LineChain, default: 0.5

  • plot_histograms_1D – if the 1D histograms should be plotted, default: True

  • n_ticks – number of ticks on the axes, default: 3

  • ticks – dict specifying the ticks for a parameter

  • tick_length – length of the ticks, default: 3

  • show_values – if best-fit and uncertainty should be given, default: False

  • bestfit_method – method for the best_fit, options: “mode”, “mean”, “median”, “best_sample” (requires lnprobs), default: “mode”

  • levels_method – method to compute the uncertainty bands, options: “hdi”, “percentile”, “PJ-HPD” (requires lnprobs), default: “hdi”

  • credible_interval – credible interval for the uncertainty, default: 0.68

  • n_sigma_for_one_sided_tail – number of sigma for the one-sided tail, default: 3

  • n_bins – number of bins for the 1D histograms, default: 100

  • density_estimation_method

    method for density estimation. Available options:

    • smoothing (default):

      First create a histogram of samples and then smooth it with a Gaussian kernel corresponding to the variance of the 20% of the smallest eigenvalue of the 2D distribution (smoothing scale can be adapted using the smoothing parameter in de_kwargs).

    • gaussian_mixture:

      Use Gaussian mixture to fit the 2D samples.

    • median_filter:

      Use median filter on the 2D histogram.

    • kde:

      Use TreeKDE, may be slow.

    • hist:

      Simple 2D histogram.

  • cmap – colormap, default: “viridis”

  • colorbar – if a colorbar should be plotted, default: False

  • colorbar_label – label for the colorbar, default: None

  • colorbar_ax – axis for the colorbar, default: [0.735, 0.5, 0.03, 0.25]

  • cmap_vmin – minimum value for the colormap, default: 0

  • cmap_vmax – maximum value for the colormap, default: None

  • show_legend – if a legend should be shown, default: False

  • progress_bar – if a progress bar should be shown, default: True

  • alpha1D – alpha for the 1D histograms, default: 1

  • alpha2D – alpha for the 2D histograms, default: 1

  • alpha – alpha for the 2D histograms in LineChain, if passed to TriangleChain, overwrites the alpha1D and alpha2D value, default: 1

  • normalize_prob1D – if the 1D histograms should be normalized for scatter_prob, default: True

  • normalize_prob2D – if the 2D histograms should be normalized for scatter_prob, default: True

  • scatter_vline_1D – if a vertical line should be plotted in the 1D histograms for each point when using scatter, default: False

  • alpha_for_low_density – if low density areas should fade to transparent

  • alpha_threshold – threshold from where the fading to transparent should start, default: 0

  • n_points_scatter – number of points to use for scatter plots, default: -1 (all)

  • label_fontsize – fontsize of the labels, default: 24

  • de_kwargs

    density estimation kwargs, dictionary with keys:

    • n_points:

      number of bins for 2d histograms used to create contours etc., default: n_bins

    • levels:

      density levels for contours, the contours will enclose this level of probability, default: [0.68, 0.95]

    • n_levels_check:

      number of levels to check when looking for density levels More levels is more accurate, but slower, default: 2000

    • smoothing_parameter1D:

      smoothing scale for the 1D histograms, default: 0.1

    • smoothing_parameter2D:

      smoothing scale for the 2D histograms, default: 0.2

  • grid_kwargs

    kwargs for the plot grid, with keys:

    • fontsize_ticklabels:

      font size for tick labels, default: 14

    • font_family:

      font family for tick labels, default: sans-serif

  • hist_kwargs – kwargs for the 1D histograms, passed to plt.hist function

  • labels_kwargs – kwargs for the x and y labels

  • line_kwargs – kwargs for the lines, passed to plt.contour and plt.contourf

  • scatter_kwargs – kwargs for the scatter plot, passed to plt.scatter

  • axvline_kwargs – kwargs for the vertical lines in the 1D histograms, passed to plt.axvline

  • subplots_kwargs – kwargs for the subplots, passed to plt.subplots

  • grouping_kwargs

    kwargs for grouping parameters in the plot with options:

    • n_per_group:

      how many parameters are grouped together (e.g. (3, 4, 5) for grouping the parameters accordingly), default: None

    • empty_ratio:

      fraction of a whole plot that is left empty for separation, default: 0.2

Basic usage:

tri = TriangleChain()
# plot contours at given confidence levels
tri.contour_cl(samples)
# plot PDF density image
tri.density_image(samples)
# simple scatter plot
tri.scatter(samples)
# scatter plot, with probability for each sample provided
tri.scatter_prob(samples, prob=prob)
# scatter plot, color corresponds to probability
tri.scatter_density(samples)
add_plotting_functions(func_add_plot)[source]

Add plotting functions to the class.

Parameters:

func_add_plot – function that adds a plot to the class

setup_color(color)[source]

Setup color for plotting. If color is None, find next color in cycle.

Parameters:

color – color for plotting

Returns:

color

trianglechain.LineChain module

class trianglechain.LineChain.LineChain(fig=None, size=4, **kwargs)[source]

Bases: BaseChain

Class to produce line plots. Parameters defined for this class are used for all plots that are added to the figure. If you want to change the parameters for a specific plot, you can do so by passing the parameters to the plotting function.

Parameters:
  • fig – matplotlib figure, default: None

  • size – size of the panels, if one number is given, the panels are rectangular with the y axis being 70% of the x axis, if two numbers are given, the first number is the width of the panels and the second number is the height of the panels, default: 4

  • params – list of parameters to plot, default: “all”

  • params_from – sample or list of samples from which the parameters should be taken, default: None

  • ranges – dictionary with the ranges for the parameters

  • names – list of names of the parameters, only used when input data is unstructured array

  • labels – list of labels (e.g. latex style) for the parameters for the plot

  • fill – if the contours should be filled, default: False

  • grid – if the grid should be plotted, default: False

  • n_ticks – number of ticks on the axes, default: 3

  • ticks – dict specifying the ticks for a parameter

  • tick_length – length of the ticks, default: 3

  • n_bins – number of bins for the 1D histograms, default: 100

  • density_estimation_method

    method for density estimation. Available options:

    • smoothing (default):

      First create a histogram of samples and then smooth it with a Gaussian kernel corresponding to the variance of the 20% of the smallest eigenvalue of the 2D distribution (smoothing scale can be adapted using the smoothing parameter in de_kwargs).

    • gaussian_mixture:

      Use Gaussian mixture to fit the 2D samples.

    • median_filter:

      Use median filter on the 2D histogram.

    • kde:

      Use TreeKDE, may be slow.

    • hist:

      Simple 2D histogram.

  • cmap – colormap, default: “viridis”

  • colorbar – if a colorbar should be plotted, default: False

  • colorbar_label – label for the colorbar, default: None

  • colorbar_ax – axis for the colorbar, default: [0.735, 0.5, 0.03, 0.25]

  • cmap_vmin – minimum value for the colormap, default: 0

  • cmap_vmax – maximum value for the colormap, default: None

  • show_legend – if a legend should be shown, default: False

  • alpha – alpha for the 2D histograms, default: 1

  • alpha_for_low_density – if low density areas should fade to transparent

  • alpha_threshold – threshold from where the fading to transparent should start, default: 0

  • n_points_scatter – number of points to use for scatter plots, default: -1 (all)

  • label_fontsize – fontsize of the labels, default: 24

  • de_kwargs

    density estimation kwargs, dictionary with keys:

    • n_points:

      number of bins for 2d histograms used to create contours etc., default: n_bins

    • levels:

      density levels for contours, the contours will enclose this level of probability, default: [0.68, 0.95]

    • n_levels_check:

      number of levels to check when looking for density levels More levels is more accurate, but slower, default: 2000

    • smoothing_parameter1D:

      smoothing scale for the 1D histograms, default: 0.1

    • smoothing_parameter2D:

      smoothing scale for the 2D histograms, default: 0.2

  • grid_kwargs

    kwargs for the plot grid, with keys:

    • fontsize_ticklabels:

      font size for tick labels, default: 14

    • font_family:

      font family for tick labels, default: sans-serif

  • labels_kwargs – kwargs for the x and y labels

  • line_kwargs – kwargs for the lines, passed to plt.contour and plt.contourf

  • scatter_kwargs – kwargs for the scatter plot, passed to plt.scatter

  • subplots_kwargs – kwargs for the subplots, passed to plt.subplots

Basic usage:

line = LineChain()
# plot contours at given confidence levels
line.contour_cl(samples)
# plot PDF density image
line.density_image(samples)
# simple scatter plot
line.scatter(samples)
# scatter plot, with probability for each sample provided
line.scatter_prob(samples, prob=prob)
# scatter plot, color corresponds to probability
line.scatter_density(samples)
add_plot(data, plottype, prob=None, color=None, label=None, **kwargs)[source]

Plotting function for the line chain class. Parameters that are passed to this function are overwriting the default parameters of the class.

Parameters:
  • data – data to plot, can be recarray, array, pandas dataframe or dict

  • prob – probability for each sample, default: None

  • color – color for the plot, default: None

  • label – label for the plot, default: None

  • names – list of names of the parameters, only used when input is unstructured array

  • fill – if the contours should be filled, default: False

  • grid – if the grid should be plotted, default: False

  • n_bins – number of bins for the 1D histograms, default: 100

  • density_estimation_method

    method for density estimation. Available options:

    • smoothing (default):

      First create a histogram of samples and then smooth it with a Gaussian kernel corresponding to the variance of the 20% of the smallest eigenvalue of the 2D distribution (smoothing scale can be adapted using the smoothing parameter in de_kwargs).

    • gaussian_mixture:

      Use Gaussian mixture to fit the 2D samples.

    • median_filter:

      Use median filter on the 2D histogram.

    • kde:

      Use TreeKDE, may be slow.

    • hist:

      Simple 2D histogram.

  • cmap – colormap, default: “viridis”

  • colorbar – if a colorbar should be plotted, default: False

  • colorbar_label – label for the colorbar, default: None

  • colorbar_ax – axis for the colorbar, default: [0.735, 0.5, 0.03, 0.25]

  • cmap_vmin – minimum value for the colormap, default: 0

  • cmap_vmax – maximum value for the colormap, default: None

  • show_legend – if a legend should be shown, default: False

  • alpha – alpha for the 2D histograms, default: 1

  • normalize_prob2D – if the 2D histograms should be normalized for scatter_prob, default: True

  • alpha_for_low_density – if low density areas should fade to transparent

  • alpha_threshold – threshold from where the fading to transparent should start, default: 0

  • n_points_scatter – number of points to use for scatter plots, default: -1 (all)

  • de_kwargs

    density estimation kwargs, dictionary with keys:

    • n_points:

      number of bins for 2d histograms used to create contours etc., default: n_bins

    • levels:

      density levels for contours, the contours will enclose this level of probability, default: [0.68, 0.95]

    • n_levels_check:

      number of levels to check when looking for density levels More levels is more accurate, but slower, default: 2000

    • smoothing_parameter1D:

      smoothing scale for the 1D histograms, default: 0.1

    • smoothing_parameter2D:

      smoothing scale for the 2D histograms, default: 0.2

  • grid_kwargs

    kwargs for the plot grid, with keys:

    • fontsize_ticklabels:

      font size for tick labels, default: 14

    • font_family:

      font family for tick labels, default: sans-serif

  • labels_kwargs – kwargs for the x and y labels

  • line_kwargs – kwargs for the lines, passed to plt.contour and plt.contourf

  • scatter_kwargs – kwargs for the scatter plot, passed to plt.scatter

  • subplots_kwargs – kwargs for the subplots, passed to plt.subplots

trianglechain.LineChain.get_param_pairs(n_output)[source]

Get all pairs of parameters.

Parameters:

n_output – number of parameters

trianglechain.LineChain.plot_line_marginals(data, prob=None, func='contour_cl', orientation='horizontal', color='#0063B9', label=None, fig=None, size=4, line_space=0.5, params='all', params_from=None, ranges={}, labels=None, names=None, fill=False, grid=False, n_ticks=3, ticks={}, tick_length=3, n_bins=100, density_estimation_method='smoothing', cmap=<matplotlib.colors.ListedColormap object>, cmap_vmin=0, cmap_vmax=None, colorbar=False, colorbar_label=None, colorbar_ax=[0.735, 0.5, 0.03, 0.25], show_legend=False, alpha=1, normalize_prob2D=True, alpha_for_low_density=False, alpha_threshold=0, n_points_scatter=-1, label_fontsize=24, de_kwargs={}, grid_kwargs={}, labels_kwargs={}, line_kwargs={}, scatter_kwargs={}, subplots_kwargs={}, **kwargs)[source]

Plot line plots of chains.

Parameters:
  • data – rec array, array, dict or pd dataframe data to plot

  • prob – probability for each sample

  • params – parameters to plot, default: “all”

  • params_from – chain to get parameters from, default: None

  • names – names of parameters (when data is np array), default: None

  • func – function to use for plotting options: contour_cl, density_image, scatter_density, scatter_prob, scatter default: contour_cl

  • orientation – orientation of the plots, options: horizontal, vertical default: horizontal

  • color – color of the plot, default: “#0063B9”

  • cmap – colormap for 2D plots, default: plt.cm.viridis

  • cmap_vmin – minimum value for colormap, default: 0

  • cmap_vmax – maximum value for colormap, default: None

  • colorbar – show colorbar, default: False

  • colorbar_label – label for colorbar, default: None

  • colorbar_ax – position of colorbar, default: [0.735, 0.5, 0.03, 0.25]

  • ranges – dictionary with ranges for each parameter, default: {}

  • ticks – dictionary with ticks for each parameter, default: {}

  • n_ticks – number of ticks for each parameter, default: 3

  • tick_length – length of ticks, default: 3

  • n_bins – number of bins for histograms, default: 20

  • fig – figure to plot on, default: None

  • size – size of the figure, default: 4

  • fill – fill the area of the contours, default: True

  • grid – show grid, default: False

  • labels – labels for each parameter, default: None if None, labels are taken from the parameter names

  • label – label for the plot, default: None

  • label_fontsize – fontsize of the label, default: 12

  • show_legend – show legend, default: False

  • line_space – space between plots, default: 0.5

  • density_estimation_method – method to use for density estimation options: smoothing, histo, kde, gaussian_mixture, median_filter default: smoothing

  • alpha – alpha value for the plot, default: 1

  • alpha_for_low_density – use alpha for low density regions, default: False

  • alpha_threshold – threshold for alpha, default: 0

  • subplots_kwargs – kwargs for plt.subplots, default: {}

  • de_kwargs – kwargs for density estimation, default: {}

  • labels_kwargs – kwargs for labels, default: {}

  • grid_kwargs – kwargs for grid, default: {}

  • line_kwargs – kwargs for line plots, default: {}

  • scatter_kwargs – kwargs for scatter plots, default: {}

  • normalize_prob2D – normalize probability for 2D plots, default: True

  • n_points_scatter – number of points for scatter plots, default: -1 (all)

  • kwargs – additional kwargs for the plot function

Returns:

fig, axes

trianglechain.TriangleChain module

class trianglechain.TriangleChain.TriangleChain(fig=None, size=4, **kwargs)[source]

Bases: BaseChain

Class to produce triangle plots. Parameters defined for this class are used for all plots that are added to the figure. If you want to change the parameters for a specific plot, you can do so by passing the parameters to the plotting function.

Parameters:
  • fig – matplotlib figure, default: None

  • size – size of the panels, if one number is given, the panels are square, if two numbers are given, the figure is rectangular, default: 4

  • params – list of parameters to plot, default: “all”

  • params_from – sample or list of samples from which the parameters should be taken, default: None

  • ranges – dictionary with the ranges for the parameters

  • names – list of names of the parameters, only used when input data is unstructured array

  • labels – list of labels (e.g. latex style) for the parameters for the plot

  • fill – if the contours should be filled, default: False

  • grid – if the grid should be plotted, default: False

  • tri – if upper or lower triangle should be plotted, default: “lower”

  • plot_histograms_1D – if the 1D histograms should be plotted, default: True

  • n_ticks – number of ticks on the axes, default: 3

  • ticks – dict specifying the ticks for a parameter

  • tick_length – length of the ticks, default: 3

  • show_values – if best-fit and uncertainty should be given, default: False

  • bestfit_method – method for the best_fit, options: “mode”, “mean”, “median”, “best_sample” (requires lnprobs), default: “mode”

  • levels_method – method to compute the uncertainty bands, options: “hdi”, “percentile”, “PJ-HPD” (requires lnprobs), default: “hdi”

  • credible_interval – credible interval for the uncertainty, default: 0.68

  • n_sigma_for_one_sided_tail – number of sigma for the one-sided tail, default: 3

  • n_bins – number of bins for the 1D histograms, default: 100

  • density_estimation_method

    method for density estimation. Available options:

    • smoothing (default):

      First create a histogram of samples and then smooth it with a Gaussian kernel corresponding to the variance of the 20% of the smallest eigenvalue of the 2D distribution (smoothing scale can be adapted using the smoothing parameter in de_kwargs).

    • gaussian_mixture:

      Use Gaussian mixture to fit the 2D samples.

    • median_filter:

      Use median filter on the 2D histogram.

    • kde:

      Use TreeKDE, may be slow.

    • hist:

      Simple 2D histogram.

  • cmap – colormap, default: “viridis”

  • colorbar – if a colorbar should be plotted, default: False

  • colorbar_label – label for the colorbar, default: None

  • colorbar_ax – axis for the colorbar, default: [0.735, 0.5, 0.03, 0.25]

  • cmap_vmin – minimum value for the colormap, default: 0

  • cmap_vmax – maximum value for the colormap, default: None

  • show_legend – if a legend should be shown, default: False

  • progress_bar – if a progress bar should be shown, default: True

  • alpha – alpha for the plots, overwrite alpha1D and alpha2D, default: None

  • alpha1D – alpha for the 1D histograms, default: 1

  • alpha2D – alpha for the 2D histograms, default: 1

  • normalize_prob1D – if the 1D histograms should be normalized for scatter_prob, default: True

  • normalize_prob2D – if the 2D histograms should be normalized for scatter_prob, default: True

  • scatter_vline_1D – if a vertical line should be plotted in the 1D histograms for each point when using scatter, default: False

  • alpha_for_low_density – if low density areas should fade to transparent

  • alpha_threshold – threshold from where the fading to transparent should start, default: 0

  • n_points_scatter – number of points to use for scatter plots, default: -1 (all)

  • label_fontsize – fontsize of the labels, default: 24

  • de_kwargs

    density estimation kwargs, dictionary with keys:

    • n_points:

      number of bins for 2d histograms used to create contours etc., default: n_bins

    • levels:

      density levels for contours, the contours will enclose this level of probability, default: [0.68, 0.95]

    • n_levels_check:

      number of levels to check when looking for density levels More levels is more accurate, but slower, default: 2000

    • smoothing_parameter1D:

      smoothing scale for the 1D histograms, default: 0.1

    • smoothing_parameter2D:

      smoothing scale for the 2D histograms, default: 0.2

  • grid_kwargs

    kwargs for the plot grid, with keys:

    • fontsize_ticklabels:

      font size for tick labels, default: 14

    • font_family:

      font family for tick labels, default: sans-serif

  • hist_kwargs – kwargs for the 1D histograms, passed to plt.hist function

  • labels_kwargs – kwargs for the x and y labels

  • line_kwargs – kwargs for the lines, passed to plt.contour and plt.contourf

  • scatter_kwargs – kwargs for the scatter plot, passed to plt.scatter

  • axvline_kwargs – kwargs for the vertical lines in the 1D histograms, passed to plt.axvline

  • subplots_kwargs – kwargs for the subplots, passed to plt.subplots

  • grouping_kwargs

    kwargs for grouping parameters in the plot with options:

    • n_per_group:

      how many parameters are grouped together (e.g. (3, 4, 5) for grouping the parameters accordingly), default: None

    • empty_ratio:

      fraction of a whole plot that is left empty for separation, default: 0.2

Basic usage:

tri = TriangleChain()
# plot contours at given confidence levels
tri.contour_cl(samples)
# plot PDF density image
tri.density_image(samples)
# simple scatter plot
tri.scatter(samples)
# scatter plot, with probability for each sample provided
tri.scatter_prob(samples, prob=prob)
# scatter plot, color corresponds to probability
tri.scatter_density(samples)
add_plot(data, plottype, prob=None, color=None, label=None, lnprobs=None, **kwargs)[source]

Plotting function for the triangle chain class. Parameters that are passed to this function are overwriting the default parameters of the class.

Parameters:
  • data – data to plot, can be recarray, array, pandas dataframe or dict

  • prob – probability for each sample, default: None

  • color – color for the plot, default: None

  • label – label for the plot, default: None

  • lnprobs – lnprob for each sample (used for some best-fit methods), default: None

  • names – list of names of the parameters, only used when input is unstructured array

  • fill – if the contours should be filled, default: False

  • grid – if the grid should be plotted, default: False

  • tri – if upper or lower triangle should be plotted, default: “lower”

  • plot_histograms_1D – if 1D histograms should be plotted, default: True

  • show_values – if best-fit and uncertainty should be given, default: False

  • bestfit_method – method for the best_fit, options: “mode”, “mean”, “median”, “best_sample” (requires lnprobs), default: “mode”

  • levels_method – method to compute the uncertainty bands, default: options: “hdi”, “percentile”, “PJ-HPD” (requires lnprobs), default: “hdi”

  • credible_interval – credible interval for the uncertainty, default: 0.68

  • n_sigma_for_one_sided_tail – number of sigma for the one-sided tail, default: 3

  • n_bins – number of bins for the 1D histograms, default: 100

  • density_estimation_method

    method for density estimation. Available options:

    • smoothing (default):

      First create a histogram of samples and then smooth it with a Gaussian kernel corresponding to the variance of the 20% of the smallest eigenvalue of the 2D distribution (smoothing scale can be adapted using the smoothing parameter in de_kwargs).

    • gaussian_mixture:

      Use Gaussian mixture to fit the 2D samples.

    • median_filter:

      Use median filter on the 2D histogram.

    • kde:

      Use TreeKDE, may be slow.

    • hist:

      Simple 2D histogram.

  • cmap – colormap, default: “viridis”

  • colorbar – if a colorbar should be plotted, default: False

  • colorbar_label – label for the colorbar, default: None

  • colorbar_ax – axis for the colorbar, default: [0.735, 0.5, 0.03, 0.25]

  • cmap_vmin – minimum value for the colormap, default: 0

  • cmap_vmax – maximum value for the colormap, default: None

  • show_legend – if a legend should be shown, default: False

  • progress_bar – if a progress bar should be shown, default: True

  • alpha – alpha for the plots, overwrite alpha1D and alpha2D, default: None

  • alpha1D – alpha for the 1D histograms, default: 1

  • alpha2D – alpha for the 2D histograms, default: 1

  • normalize_prob1D – if the 1D histograms should be normalized for scatter_prob, default: True

  • normalize_prob2D – if the 2D histograms should be normalized for scatter_prob, default: True

  • scatter_vline_1D – if a vertical line should be plotted in the 1D histograms for each point when using scatter, default: False

  • alpha_for_low_density – if low density areas should fade to transparent

  • alpha_threshold – threshold from where the fading to transparent should start, default: 0

  • n_points_scatter – number of points to use for scatter plots, default: -1 (all)

  • de_kwargs

    density estimation kwargs, dictionary with keys:

    • n_points:

      number of bins for 2d histograms used to create contours etc., default: n_bins

    • levels:

      density levels for contours, the contours will enclose this level of probability, default: [0.68, 0.95]

    • n_levels_check:

      number of levels to check when looking for density levels More levels is more accurate, but slower, default: 2000

    • smoothing_parameter1D:

      smoothing scale for the 1D histograms, default: 0.1

    • smoothing_parameter2D:

      smoothing scale for the 2D histograms, default: 0.2

  • grid_kwargs

    kwargs for the plot grid, with keys:

    • fontsize_ticklabels:

      font size for tick labels, default: 14

    • font_family:

      font family for tick labels, default: sans-serif

  • hist_kwargs – kwargs for the 1D histograms, passed to plt.hist function

  • labels_kwargs – kwargs for the x and y labels

  • line_kwargs – kwargs for the lines, passed to plt.contour and plt.contourf

  • scatter_kwargs – kwargs for the scatter plot, passed to plt.scatter

  • axvline_kwargs – kwargs for the vertical lines in the 1D histograms, passed to plt.axvline

  • subplots_kwargs – kwargs for the subplots, passed to plt.subplots

  • grouping_kwargs

    kwargs for grouping parameters in the plot with options:

    • n_per_group:

      how many parameters are grouped together (e.g. (3, 4, 5) for grouping the parameters accordingly), default: None

    • empty_ratio:

      fraction of a whole plot that is left empty for separation, default: 0.2

trianglechain.TriangleChain.plot_triangle_marginals(data, prob=None, func='contour_cl', color='#0063B9', label=None, lnprobs=None, fig=None, size=4, params='all', params_from=None, ranges={}, labels=None, names=None, fill=False, grid=False, tri='lower', plot_histograms_1D=True, n_ticks=3, ticks={}, tick_length=3, show_values=False, bestfit_method='mode', levels_method='hdi', credible_interval=0.68, n_sigma_for_one_sided_tail=3, n_bins=100, density_estimation_method='smoothing', cmap=<matplotlib.colors.ListedColormap object>, cmap_vmin=0, cmap_vmax=None, colorbar=False, colorbar_label=None, colorbar_ax=[0.735, 0.5, 0.03, 0.25], show_legend=False, progress_bar=True, alpha=None, alpha1D=1, alpha2D=1, normalize_prob1D=True, normalize_prob2D=True, scatter_vline_1D=False, alpha_for_low_density=False, alpha_threshold=0, n_points_scatter=-1, label_fontsize=24, de_kwargs={}, grid_kwargs={}, hist_kwargs={}, labels_kwargs={}, line_kwargs={}, scatter_kwargs={}, axvline_kwargs={}, subplots_kwargs={}, grouping_kwargs={}, add_empty_plots_like=None, **kwargs)[source]

Plot triangle plot with 1D and 2D histograms, contours, scatter plots, etc.

Parameters:
  • data – data to plot, can be a dictionary, a recarray or a pandas DataFrame

  • prob – probability of each point, default: None

  • func

    function to use for plotting, default: ‘contour_cl’, options:

    • contour_cl (default)

    • density_image

    • scatter_density

    • scatter_prob

    • scatter default

  • color – color for the plot, default: ‘#0063B9’

  • label – label for the plot, default: None

  • lnprobs – lnprob for each sample (used for some best-fit methods), default: None

  • fig – matplotlib figure, default: None

  • size – size of the panels, if one number is given, the panels are square, if two numbers are given, the figure is rectangular, default: 4

  • params – list of parameters to plot, default: ‘all’

  • params_from – sample or list of samples from which the parameters should be taken, default: None

  • ranges – dictionary with ranges for the parameters, default: {}

  • labels – list of labels (e.g. latex style) for the parameters for the plot

  • names – list of names of the parameters, only used when input data is unstructured array

  • fill – if the contours should be filled, default: False

  • grid – if the grid should be plotted, default: False

  • tri – if upper or lower triangle should be plotted, default: “lower”

  • plot_histograms_1D – if the 1D histograms should be plotted, default: True

  • n_ticks – number of ticks on the axes, default: 3

  • ticks – dict specifying the ticks for each parameter

  • tick_length – length of the ticks, default: 3

  • show_values – if best-fit and uncertainty should be given, default: False

  • bestfit_method – method to use for best-fit, options: “mode”, “mean”, “median”, “best_sample” (requires lnprobs), default: “mode”

  • levels_method – method to compute the uncertainty bands, options: “hdi”, “percentile”, “PJ-HPD” (requires lnprobs), default: “hdi”

  • credible_interval – credible interval for the uncertainty bands, default: 0.68

  • n_sigma_for_one_sided_tail – number of sigma for the one-sided tail, default: 3

  • n_bins – number of bins for the 1D histograms, default: 100

  • density_estimation_method – method to use for density estimation, default=”smoothing”

  • cmap – colormap, default: plt.cm.viridis

  • cmap_vmin – minimum value for the colormap, default: 0

  • cmap_vmax – maximum value for the colormap, default: None

  • colorbar – if a colorbar should be plotted, default: False

  • colorbar_label – label for the colorbar, default: None

  • colorbar_ax – position of the colorbar, default: [0.735, 0.5, 0.03, 0.25]

  • show_legend – if a legend should be plotted, default: False

  • progress_bar – if a progress bar should be shown, default: True

  • alpha – alpha for the plots, overwrite alpha1D and alpha2D, default: None

  • alpha1D – alpha for the 1D histograms, default: 1

  • alpha2D – alpha for the 2D histograms, default: 1

  • normalize_prob1D – if the 1D histograms should be normalized for scatter_prob, default: True

  • normalize_prob2D – if the 2D histograms should be normalized for scatter_prob, default: True

  • scatter_vline_1D – if a vertical line should be plotted in the 1D histograms for each point when using scatter, default: False

  • alpha_for_low_density – if low density areas should fade to transparent

  • alpha_threshold – threshold for the alpha for low density areas

  • alpha_threshold – threshold from where the fading to transparent should start, default: 0

  • n_points_scatter – number of points to plot when using scatter, default: -1 (all)

  • label_fontsize – fontsize for the labels, default: 24

  • de_kwargs – dict with kwargs for the density estimation, default: {}

  • grid_kwargs – dict with kwargs for the grid, default: {}

  • hist_kwargs – dict with kwargs for the 1D histograms, default: {}

  • labels_kwargs – dict with kwargs for the labels, default: {}

  • line_kwargs – dict with kwargs for the lines, default: {}

  • scatter_kwargs – dict with kwargs for the scatter plot, default: {}

  • axvline_kwargs – dict with kwargs for the vertical lines, default: {}

  • subplots_kwargs – dict with kwargs for the subplots, default: {}

  • grouping_kwargs – dict with kwargs for the grouping, default: {}

  • add_empty_plots_like – DEPRECATED, default: None

trianglechain.bestfit module

trianglechain.bestfit.best_sample(samples, lnprobs)[source]

Get the sample with the highest log probability.

Parameters:
  • samples – rec array with samples

  • lnprobs – array with log probabilities of the samples

Returns:

sample with the highest log probability

trianglechain.bestfit.get_all_bl_estimates(params_chain, lnprobs, emu, cl_fid, inv_C, ells, lims, prior_ind=[], gauss_mean=[], gauss_sigma=[], just_names=False, use_best_n=1, both_minimization=False, flat_chi2minimization=False)[source]

Get all the best likelihood estimates.

Parameters:
  • params_chain – rec array with samples

  • lnprobs – array with log probabilities of the samples

  • emu – emulator (or any function that returns the observable)

  • cl_fid – fiducial power spectrum

  • inv_C – inverse covariance matrix

  • ells – array with multipoles

  • lims – limits of the parameters

  • prior_ind – indices of the parameters with priors

  • gauss_mean – mean of the Gaussian priors

  • gauss_sigma – standard deviation of the Gaussian priors

  • just_names – if True, only return the names of the best likelihood estimates

  • use_best_n – number of best likelihood samples to use

  • both_minimization – if True, use both minimizations

  • flat_chi2minimization – if True, use chi2 minimization without Gaussian priors

Returns:

array with best likelihood estimates

trianglechain.bestfit.get_all_bl_estimates_except_mode(params_chain, lnprobs, emu, cl_fid, inv_C, ells, lims, prior_ind=[], gauss_mean=[], gauss_sigma=[], just_names=False, use_best_n=1, both_minimization=False, flat_chi2minimization=False)[source]

Get all the best likelihood estimates except the mode.

Parameters:
  • params_chain – rec array with samples

  • lnprobs – array with log probabilities of the samples

  • emu – emulator

  • cl_fid – fiducial power spectrum

  • inv_C – inverse covariance matrix

  • ells – array with multipoles

  • lims – limits of the parameters

  • prior_ind – indices of the parameters with priors

  • gauss_mean – mean of the Gaussian priors

  • gauss_sigma – standard deviation of the Gaussian priors

  • just_names – if True, only return the names of the best likelihood estimates

  • use_best_n – number of best likelihood samples to use

  • both_minimization – if True, use both minimizations

  • flat_chi2minimization – if True, use chi2 minimization without Gaussian priors

Returns:

array with best likelihood estimates

trianglechain.bestfit.get_best_likelihood(params_chain, lnprobs, emu, cl_fid, inv_C, ells, lims, prior_ind=[], gauss_mean=[], gauss_sigma=[], use_best_n=1)[source]

Get the best likelihood value of the chain by minimizing the chi2.

Parameters:
  • params_chain – rec array with samples

  • lnprobs – array with log probabilities of the samples

  • emu – emulator of the power spectrum

  • cl_fid – fiducial power spectrum

  • inv_C – inverse covariance matrix

  • ells – ell values

  • lims – limits of the parameters

  • prior_ind – indices of the parameters with a gaussian prior

  • gauss_mean – mean of the gaussian prior

  • gauss_sigma – sigma of the gaussian prior

  • use_best_n – number of best samples to use for the minimization

Returns:

bool if successful minimization, best likelihood value and best lnprob

trianglechain.bestfit.get_best_likelihood_from_MCMC(params_chain, lnprobs)[source]

Get the best likelihood value of the chain by maximizing the log probability.

Parameters:
  • params_chain – rec array with samples

  • lnprobs – array with log probabilities of the samples

Returns:

best likelihood value

trianglechain.bestfit.get_bestfit(samples, lnprobs=None, bestfit_method='mode')[source]

Get the best fit value each parameter of the sample.

Parameters:
  • samples – rec array with samples

  • lnprobs – array with log probabilities of the samples (optional, default: None)

  • bestfit_method – method to use for best fit, options: mode: mode of the distribution (default) mean: mean of the distribution median: median of the distribution best_sample: sample with the highest log probability

Returns:

best fit value for each parameter

trianglechain.bestfit.get_mean_median_best_likelihood_from_MCMC(params_chain, lnprobs)[source]

Get the mean and median best likelihood of the samples of the chain.

Parameters:
  • params_chain – rec array with samples

  • lnprobs – array with log probabilities of the samples

Returns:

mean and median value of the 10 best likelihood samples

trianglechain.bestfit.get_means_and_medians(samples)[source]

Get the mean and median of each parameter of the sample.

Parameters:

samples – rec array with samples

Returns:

mean and median of each parameter

trianglechain.bestfit.get_mode(samples, lims)[source]

Get the mode of the sample for each parameter.

Parameters:
  • samples – rec array with samples

  • lims – limits of the parameters

Returns:

mode of the sample

trianglechain.bestfit.mode(sample, lim)[source]

Get the mode of a sample.

Parameters:
  • sample – 1D array with samples

  • lim – limits of the parameter

Returns:

mode of the sample

trianglechain.density_estimation module

trianglechain.density_estimation.get_confidence_levels(de, levels, n_levels_check)[source]

Get the confidence levels for a given density estimation

Parameters:
  • de – density estimation

  • levels – confidence levels

  • n_levels_check – number of levels to check

Returns:

confidence levels

trianglechain.density_estimation.get_density_grid_1D(data, binedges, bincenters, lims, prob=None, method='smoothing', de_kwargs={})[source]

Get density estimation for 1D data

Parameters:
  • data – data to estimate density from

  • binedges – bin edges for the histogram

  • bincenters – bin centers for the histogram

  • lims – limits for the histogram

  • prob – weights for the data

  • method – Method for density estimation. Valid options are: - ‘smoothing’: First create a histogram of samples, and then smooth it with a Gaussian kernel corresponding to the variance of the 20% of the smallest eigenvalue of the 2D distribution (smoothing scale can be adapted using the smoothing_scale parameter). - ‘gaussian_mixture’: Fit a Gaussian mixture model to the data. - ‘median_filter’: Use a median filter to smooth the histogram. - ‘kde’: Use a kernel density estimation to estimate the density. - ‘hist’: Use a histogram to estimate the density.

  • de_kwargs – keyword arguments for the density estimation method

Returns:

density estimation

trianglechain.density_estimation.get_density_grid_2D(data, ranges, columns, i, j, prob=None, method='smoothing', de_kwargs={})[source]

Get density estimation for 2D data

Parameters:
  • data – data to estimate density from

  • ranges – ranges for the data

  • columns – columns to use for the data

  • i – index of the first column

  • j – index of the second column

  • prob – weights for the data

  • method – Method for density estimation. Valid options are: - ‘smoothing’: First create a histogram of samples, and then smooth it with a Gaussian kernel corresponding to the variance of the 20% of the smallest eigenvalue of the 2D distribution (smoothing scale can be adapted using the smoothing_scale parameter). - ‘gaussian_mixture’: Fit a Gaussian mixture model to the data. - ‘median_filter’: Use a median filter to smooth the histogram. - ‘kde’: Use a kernel density estimation to estimate the density. - ‘hist’: Use a histogram to estimate the density.

  • de_kwargs – keyword arguments for the density estimation method

Returns:

density estimation

trianglechain.density_estimation.histogram_1D(data, prob, binedges)[source]

Create a histogram of the data

Parameters:
  • data – data to create histogram from

  • prob – weights for the data

  • binedges – bin edges for the histogram

Returns:

histogram

trianglechain.density_estimation.histogram_2D(data_panel, prob, bins_x, bins_y)[source]

Create a 2D histogram

Parameters:
  • data_panel – data to create histogram from

  • prob – weights for the data

  • bins_x – bins for the first dimension

  • bins_y – bins for the second dimension

Returns:

2D histogram

trianglechain.limits module

trianglechain.limits.PJ_HPD(samples, lnprobs, credible_interval=0.68, interpolator=<function interpolate>, **interp_kwargs)[source]

Returns the upper and lower limit using projected joint highest posterior density. see arXiv:2007.01844

Parameters:
  • samples – np.ndarray with the given samples

  • lnprobs – logprobability of the samples

  • credible_interval – which credible interval should be used, defaults to 0.68

  • interpolator – interpolation function, defaults to utils_pj_hpd.interpolate

  • interp_kwargs – kwargs for the interpolation function

Returns:

upper and lower limit

trianglechain.limits.cdf(samples, value)[source]

Get the cumulative distribution function.

Parameters:
  • samples – np.ndarray with the given samples

  • value – value to compute the cdf

Returns:

cdf

trianglechain.limits.check_if_two_tailed(samples, credible_interval, sigma_one_tail)[source]

Check if the credible interval is two tailed or one tailed.

Parameters:
  • samples – np.ndarray with the given samples

  • credible_interval – which credible interval should be used, defaults to 0.68

  • sigma_one_tail – how many sigma should be used to decide if one tailed credible interval should be used defaults to 3

Returns:

True if two tailed, False if one tailed; if one tailed, if upper or lower

trianglechain.limits.get_levels(samples, lnprob=None, levels_method='hdi', credible_interval=0.68, sigma_one_tail=3)[source]

Get the upper and lower level of the credible interval. If the credible interval is two tailed, the upper and lower level are returned. If the credible interval is one tailed, only the lower/upper level is returned.

Parameters:
  • samples – np.ndarray with the given samples

  • lnprob – logprobability of the samples, used for some methods, defaults to None

  • levels_method – method how to compute the levels, options: “hdi”, “percentile”, “PJ_HPD”, defaults to “hdi”

  • credible_interval – which credible interval should be used, defaults to 0.68

  • sigma_one_tail – how many sigma should be used to decide if one tailed credible interval should be used defaults to 3

Returns:

upper and lower limit (or only lower/upper limit if one tailed)

trianglechain.limits.get_one_tailed_levels(samples, credible_interval=0.68, side='upper')[source]

Get the upper or lower level of the credible interval.

Parameters:
  • samples – np.ndarray with the given samples

  • credible_interval – which credible interval should be used, defaults to 0.68

  • side – “upper” or “lower” side of the credible interval

Returns:

upper or lower limit

trianglechain.limits.get_two_tailed_levels(samples, lnprob=None, levels_method='hdi', credible_interval=0.68)[source]

Get the upper and lower level of the credible interval.

Parameters:
  • samples – np.ndarray with the given samples

  • lnprob – logprobability of the samples, used for some methods, defaults to None

  • levels_method – method how to compute the levels, options: “hdi”, “percentile”, “PJ_HPD”, defaults to “hdi”

  • credible_interval – which credible interval should be used, defaults to 0.68

Returns:

upper and lower limit

trianglechain.limits.get_uncertainty_band(lower, upper)[source]

Get the uncertainty band.

Parameters:
  • lower – lower limit

  • upper – upper limit

Returns:

uncertainty band

trianglechain.limits.hdi(samples, credible_interval=0.68)[source]

Returns the upper and lower limit using highest density interval

Parameters:
  • samples – np.ndarray with the given samples

  • credible_interval – which credible interval should be used, defaults to 0.68

Returns:

upper and lower limit

trianglechain.limits.percentile(samples, credible_interval=0.68)[source]

Returns the upper and lower percentile.

Parameters:
  • samples – np.ndarray with the given samples

  • credible_interval – which credible interval should be used, defaults to 0.68

Returns:

upper and lower limit

trianglechain.limits.sigma_to_cdf(sigma, side='left')[source]

Convert sigma to CDF for a standard normal distribution.

Parameters:
  • sigma – sigma value

  • side – “left” for left-tailed CDF, “right” for right-tailed CDF

Returns:

CDF value

trianglechain.limits.uncertainty(samples, model, **model_kwargs)[source]

Get the uncertainty of the samples.

Parameters:
  • samples – np.ndarray with the given samples

  • model – model function to compute uncertainty

Returns:

uncertainty

trianglechain.make_subplots module

trianglechain.make_subplots.add_values(axc, column, data, lnprobs, label, levels_method='hdi', bestfit_method='mean', credible_interval=0.68, sigma_one_tail=3, label_fontsize=12)[source]

Add values of bestfit and uncertainty to the plot.

Parameters:
  • axc – matplotlib axis axis of the plot

  • column – str name of the parameter in data that is plotted

  • data – numpy struct array the data that should be plotted with column data

  • lnprobs – array logprobabilites used for the bestfit and uncertainty finding

  • label – str label of the plot

  • levels_method – {“hdi”, “percentile”, “PJ_HPD”} method how to compute the uncertainty, default is hdi

  • bestfit_method – {“mode”, “mean”, “median”, “best_sample”} method how to compute the bestfit, default is mean

  • credible_interval – float in [0, 1] credible interval of the uncertainty bar, default is 0.68

  • sigma_one_tail – how many sigma should be used to decide if one tailed credible interval should be used defaults to 3

  • label_fontsize – int or float fontsize of the label of the parameters, default is 12

trianglechain.make_subplots.contour_cl(axc, data, ranges, columns, i, j, fill, color, de_kwargs={}, line_kwargs={}, prob=None, density_estimation_method='smoothing', label=None, alpha=1)[source]

Plot the density of the data in the given axis as a contour plot.

Parameters:
  • axc – matplotlib axis axis of the plot

  • data – numpy struct array the data that should be plotted with column data

  • ranges – dict dictionary with the ranges of of the plot for each parameter

  • columns – list list of all parameters

  • i – int index of the first column to plot

  • j – int index of the second column to plot

  • fill – bool if the contour should be filled

  • color – str color of the contour

  • de_kwargs – dict dict with kde settings, has to have n_points, n_levels_check, levels

  • line_kwargs – dict dict with line settings, has to have linewidth, linestyle

  • prob – None or array if not None, then probability attached to the samples, in that case samples are treated as grid not a chain

  • density_estimation_method – {“gaussian_mixture”, “smoothing”, “median_filter”, “kde”, “hist”} method how to estimate the density

  • label – str label of the plot

  • alpha – float alpha value of the contour

trianglechain.make_subplots.density_image(axc, data, ranges, columns, i, j, cmap, de_kwargs={}, vmin=0, vmax=None, prob=None, density_estimation_method='smoothing', label=None, alpha_for_low_density=False, alpha_threshold=0)[source]

Plot the density of the data in the given axis as a density image.

Parameters:
  • axc – matplotlib axis axis of the plot

  • data – numpy struct array the data that should be plotted with column data

  • ranges – dict dictionary with the ranges of of the plot for each parameter

  • columns – list list of all parameters

  • i – int index of the first column to plot

  • j – int index of the second column to plot

  • cmap – matplotlib colormap colormap that is used

  • de_kwargs – dict dict with kde settings, has to have n_points, n_levels_check, levels

  • vmin – None or float minimum value for the density (default=0) if None, the minimum in each subplot will be chosen as vmin

  • vmax – float maximum value for the density (default=None), if None, the maximum in each subplot will be chosen as vmax

  • prob – None or array if not None, then probability attached to the samples, in that case samples are treated as grid not a chain

  • density_estimation_method – {“gaussian_mixture”, “smoothing”, “median_filter”, “kde”, “hist”} method how to estimate the density

  • label – str label of the plot

  • alpha_for_low_density – bool if low density should fade out using alpha values

  • alpha_treshold – float in [0, 1] fraction of sample where alpha value should reach 1 0 means alpha is 1 everywhere 1 means linear decrease of alpha from 0 to 1 over the whole range

trianglechain.make_subplots.plot_1d(axc, column, param_label, data, prob, ranges, current_ranges, hist_binedges, hist_bincenters, de_kwargs, hist_kwargs, empty_columns, show_values=False, label=None, density_estimation_method='smoothing', color_hist='k', alpha1D=1, fill=False, lnprobs=None, levels_method='hdi', bestfit_method='mean', credible_interval=0.68, sigma_one_tail=3, label_fontsize=12)[source]

Plot 1D histogram and density estimation.

Parameters:
  • axc – matplotlib axis axis of the plot

  • column – str name of the parameter in data that is plotted

  • param_label – str name of the parameter that should be plotted in case bestfit and uncertainty are shown

  • data – numpy struct array the data that should be plotted with column data

  • prob – None or array if not None, then probability attached to the samples, in that case samples are treated as grid not a chain

  • ranges – dict dictionary with the ranges of of the plot for each parameter

  • current_ranges – dict dictionary with the current ranges of of the plot for each parameter

  • hist_binedges – array edges of the histogram for the plot

  • hist_bincenters – array centers of the histogram for the plot

  • de_kwargs – dict additional kwargs for density estimation, passed to get_density_grid

  • hist_kwargs – dict additional kwargs for the histogram plot, passed to plt.plot()

  • empty_columns – list list with the indices of empty columns

  • show_values – bool if values of bestfit and uncertainty should be plotted

  • label – str label of the plot

  • density_estimation_method – {“gaussian_mixture”, “smoothing”, “median_filter”, “kde”, “hist”} method how to estimate the density

  • color_hist – color color of the histogram

  • alpha1D – float in [0, 1] alpha value of the histogram

  • fill – bool use filled histograms

  • lnprobs – array logprobabilites used for the bestfit and uncertainty finding

  • levels_method – {“hdi”, “percentile”, “PJ_HPD”} method how to compute the uncertainty

  • bestfit_method – {“mode”, “mean”, “median”, “best_sample”} method how to compute the bestfit

  • credible_interval – float in [0, 1] credible interval of the uncertainty bar

  • sigma_one_tail – how many sigma should be used to decide if one tailed credible interval should be used defaults to 3

  • label_fontsize – int or float fontsize of the label of the parameters

trianglechain.make_subplots.scatter_density(axc, points1, points2, n_bins=50, lim1=None, lim2=None, n_points_scatter=-1, label=None, **kwargs)[source]

Plot the density of the data in the given axis as a scatter plot. The color of the scatter points is determined by the density of the points.

Parameters:
  • axc – matplotlib axis axis of the plot

  • points1 – numpy array array of the first parameter

  • points2 – numpy array array of the second parameter

  • n_bins – int number of bins

  • lim1 – tuple limits of the first parameter

  • lim2 – tuple limits of the second parameter

  • n_points_scatter – int number of points to plot

  • label – str label of the plot

  • kwargs – dict dict with kwargs for the scatter plot

trianglechain.params module

trianglechain.params.add_derived(data, new_param, derived, names=None)[source]

Adds a new derived parameter to the input data.

Parameters:
  • data (numpy.ndarray or dict or pandas.DataFrame) – The input data to add the derived parameter to. If a 2D numpy array, a pandas dataframe, or a dictionary of arrays, it will be converted to a recarray with automatically generated field names.

  • new_param (str) – The name of the new derived parameter to add.

  • derived (np.ndarray or list or float) – The derived value of the new parameter.

  • names (list of str, optional) – A list of field names to use if the input data is a 2D numpy array. The length of this list should match the number of columns in the array. If not provided, field names will be automatically generated.

Returns:

The input data with the new derived parameter added.

Return type:

numpy.recarray

Example usage:

>>> data = add_derived(data, "S8", data["sigma8"] * np.sqrt(data["omega_m"]/0.3))
trianglechain.params.check_if_names_is_used_correctly(names, data)[source]

Check if the names argument is used correctly.

Parameters:
  • names – A list of field names to use if the input data is a 2D numpy array.

  • data – The input data to check.

Returns:

corrected names

trianglechain.params.ensure_rec(data, names=None, column_prefix='')[source]

Ensure that the input data is a numpy record array (recarray). If the input is already a recarray, it is returned as-is. If it is a 2D numpy array, a pandas dataframe, or a dictionary of arrays, it is converted to a recarray with automatically generated field names.

Parameters:
  • data (numpy.ndarray or dict or pandas.DataFrame) – The input data to ensure is a recarray. If a 2D numpy array, a pandas dataframe, or a dictionary of arrays, it will be converted to a recarray with automatically generated field names.

  • names (list of str, optional) – A list of field names to use if the input data is a 2D numpy array. The length of this list should match the number of columns in the array. If not provided, field names will be automatically generated.

  • column_prefix (str, optional) – A prefix to add to the automatically generated field names for the input data. This can be useful for distinguishing between multiple rec arrays with similar fields.

Returns:

The input data as a recarray.

Return type:

numpy.recarray

Example usage:
>>> data = np.array([[1, 2], [3, 4]])
>>> rec = ensure_rec(data)
>>> print(rec)
[(1, 2) (3, 4)]
>>> data_dict = {'a': [1, 2], 'b': [3, 4]}
>>> rec_dict = ensure_rec(data_dict)
>>> print(rec_dict)
[(1, 3) (2, 4)]
>>> data_names = np.array([[1, 2], [3, 4]])
>>> rec_names = ensure_rec(data_names, names=['x', 'y'])
>>> print(rec_names)
[(1, 2) (3, 4)]
>>> data_prefix = np.array([[1, 2], [3, 4]])
>>> rec_prefix = ensure_rec(data_prefix, column_prefix='data_')
>>> print(rec_prefix)
[(1, 2) (3, 4)]
>>> df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
>>> rec_df = ensure_rec(df)
>>> print(rec_df)
[(1, 3) (2, 4)]
trianglechain.params.get_samples(n_samples=100000, n_dims=None, names=None, column_prefix='col', covmat=None, mean=None)[source]

Get a random set of samples from a multivariate Gaussian distribution.

Parameters:
  • n_samples – The number of samples to generate.

  • n_dims – The number of dimensions of the samples.

  • names – A list of field names to use if the input data is a 2D numpy array. The length of this list should match the number of columns in the array. If not provided, field names will be automatically generated.

  • column_prefix – A prefix to add to the automatically generated field names for the input data.

  • covmat – The covariance matrix of the distribution.

  • mean – The mean of of each parameter in the distribution.

Returns:

The samples.

trianglechain.utils_pj_hpd module

trianglechain.utils_pj_hpd.check_threshold(func, p_min, p_max, threshold)[source]

Check if the integral of the function over the interval is above the threshold.

Parameters:
  • func – The function to integrate.

  • p_min – The minimum of the interval.

  • p_max – The maximum of the interval.

  • threshold – The threshold.

Returns:

True if the integral is above the threshold, False otherwise.

trianglechain.utils_pj_hpd.find_threshold_param(func, p_min, p_max, which_changed, credible_interval=0.68)[source]

Find the parameter value at which the integral of the function over the interval is above the threshold.

Parameters:
  • func – The function to integrate.

  • p_min – The minimum of the interval.

  • p_max – The maximum of the interval.

  • which_changed – A flag indicating if the minimum or maximum changed.

  • credible_interval – The credible interval.

Returns:

The parameter value at which the integral is above the threshold.

trianglechain.utils_pj_hpd.interpolate(sample, bins=1000)[source]

Interpolate a histogram of the sample.

Parameters:
  • sample – The sample to interpolate.

  • bins – The number of bins to use for the histogram.

Returns:

A function that can be used to evaluate the interpolated histogram.

trianglechain.utils_pj_hpd.sort_according_to_lnprobs(samples, lnprobs)[source]

Sort the samples according to the log-probabilities.

Parameters:
  • samples – The samples.

  • lnprobs – The log-probabilities of the samples.

Returns:

The sorted samples.

trianglechain.utils_pj_hpd.update_interval(p, p_min, p_max)[source]

Update the interval.

Parameters:
  • p – The new value.

  • p_min – The current minimum.

  • p_max – The current maximum.

Returns:

The new minimum, maximum, and a flag indicating if the minimum or maximum changed.

trianglechain.utils_plots module

trianglechain.utils_plots.add_vline(axc, column, data, color, axvline_kwargs)[source]

Add a vertical line to the axes.

Parameters:
  • axc – The axes to add the line to.

  • column – The column of the data to add the line to.

  • data – The data which is used to add a line

  • color – The color of the line.

  • axvline_kwargs – The kwargs for the axvline.

trianglechain.utils_plots.check_orientation(ax)[source]

Check the orientation of the axes of an previously created figure.

Parameters:

ax – The axes.

Returns:

The orientation of the axes, either “upper”, “lower” or “both”.

trianglechain.utils_plots.compute_plot_limits(x, margin=0.05)[source]

Compute the plot limits.

Parameters:
  • x – The data to compute the limits for.

  • margin – The margin to add to the limits.

Returns:

The limits.

trianglechain.utils_plots.delete_all_ticks(ax)[source]

Delete all ticks from the axes.

Parameters:

ax – The axes.

trianglechain.utils_plots.find_alpha(column, empty_columns, alpha=1)[source]

Find the alpha value for the column.

Parameters:
  • column – The column to find the alpha for.

  • empty_columns – The empty columns.

  • alpha – The alpha value.

Returns:

The alpha value.

trianglechain.utils_plots.find_optimal_ticks(range_of_param, n_ticks=3)[source]

Find the optimal ticks for the given range.

Parameters:
  • range_of_param – The range of the parameter.

  • n_ticks – The number of ticks.

Returns:

The ticks.

trianglechain.utils_plots.get_best_lims(new_xlims, new_ylims, old_xlims, old_ylims)[source]

Get the best limits for the axes.

Parameters:
  • new_xlims – The new x limits.

  • new_ylims – The new y limits.

  • old_xlims – The old x limits.

  • old_ylims – The old y limits.

Returns:

The best limits.

trianglechain.utils_plots.get_best_old_lims(xlim1, xlim2, ylim1, ylim2)[source]

Get the best old limits of the axes. This is used to ensure that the limits of the axes are not changed when a new plot is added.

Parameters:
  • xlim1 – The old x-limits.

  • xlim2 – The new x-limits.

  • ylim1 – The old y-limits.

  • ylim2 – The new y-limits.

Returns:

The best old limits.

trianglechain.utils_plots.get_hw_ratios(columns, grouping_kwargs)[source]

Get the height/width ratios for the plots.

Parameters:
  • columns – The list of columns to be plotted.

  • grouping_kwargs – The grouping keyword arguments.

Returns:

The new list of height/width ratios.

trianglechain.utils_plots.get_labels(labels, columns, grouping_indices=[])[source]

Get the labels for the plots. If no labels are given, the columns are used as labels.

Parameters:
  • labels – The labels to be used.

  • columns – The list of columns to be plotted.

  • grouping_indices – The grouping indices.

Returns:

The new list of labels.

trianglechain.utils_plots.get_lines_and_labels(ax)[source]

Get the lines and labels of the axes for the legend.

Parameters:

ax – The axes to get the lines and labels from.

Returns:

The lines and labels.

trianglechain.utils_plots.get_n_points_for_scatter(x, y, n_points_scatter=-1, prob=None)[source]

Get the number of points to use for the scatter plot.

Parameters:
  • x – The x data.

  • y – The y data.

  • n_points_scatter – The number of points to use for the scatter plot. If -1, all points are used.

  • prob – The probability to use for the scatter plot.

Returns:

The x, y and prob data.

trianglechain.utils_plots.get_old_lims(axc)[source]

Get the old limits of the axes.

Parameters:

axc – The axes.

Returns:

The old limits.

trianglechain.utils_plots.get_rounding_digit(uncertainty)[source]

Get the rounding digit and the format from PDG conventions.

Parameters:

uncertainty – The uncertainty.

Returns:

The rounding digit and the format.

trianglechain.utils_plots.get_smoothing_sigma(x, max_points=5000)[source]

Get the smoothing sigma for the KDE.

Parameters:
  • x – The data to smooth.

  • max_points – The maximum number of points to use.

Returns:

The smoothing sigma.

trianglechain.utils_plots.get_values(column, data, lnprobs, levels_method='hdi', bestfit_method='mean', credible_interval=0.68, sigma_one_tail=3)[source]

Get the values for the best fit and the uncertainty.

Parameters:
  • column – The column.

  • data – The data.

  • lnprobs – The log probabilities.

  • levels_method – The method to compute the uncertainty.

  • bestfit_method – The method to compute the best fit.

  • credible_interval – The credible interval.

  • sigma_one_tail – how many sigma should be used to decide if one tailed credible interval should be used defaults to 3

Returns:

The best fit and the uncertainty.

trianglechain.utils_plots.merge_lists(lists)[source]

Merge a list of lists into a new list, removing duplicates and maintaining the order of the elements.

Parameters:

lists – A list of input lists.

Returns:

A new list with unique elements, maintaining the order of the elements.

Example: >>> lists = [[“a”, “b”, “c”], [“c”, “d”], [“e”, “f”, “g”], [“a”, “g”]] >>> merge_lists(lists) [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’]

trianglechain.utils_plots.normalise(y, x)[source]

Normalise the array with x values.

Parameters:
  • y – The array.

  • x – The x values.

Returns:

The normalised array.

trianglechain.utils_plots.pixel_coords(x, ranges, n_pix_img)[source]

Convert the coordinates to pixel coordinates.

Parameters:
  • x – The coordinates.

  • ranges – The ranges.

  • n_pix_img – The number of pixels.

Returns:

The pixel coordinates.

trianglechain.utils_plots.prepare_columns(data, params='all', params_from=None, add_empty_plots_like=None)[source]

Prepare the columns of the data to be plotted.

Parameters:
  • data – The data to plot.

  • params – The parameters to plot. If “all”, all parameters in the data will be plotted. If a list of strings, only the parameters with the given names will be plotted.

  • params_from – data to get the parameters from.

  • add_empty_plots_like – DEPRECATED: data to get the parameters from.

Returns:

The data with only the columns to be plotted, the list of column names and the list of empty columns.

trianglechain.utils_plots.round_to_significant_digits(number, significant_digits)[source]

Round the number to the given number of significant digits.

Parameters:
  • number – The number.

  • significant_digits – The number of significant digits.

Returns:

The rounded number.

trianglechain.utils_plots.safe_normalise(p)[source]

Normalise the array without x values.

Parameters:

p – The array.

Returns:

The normalised array.

trianglechain.utils_plots.set_limits(axc, ranges, current_ranges, col1, col2, old_xlims, old_ylims)[source]

Set the limits of the axes. If ranges are not specified, the range is determined automatically using current and previous plots.

Parameters:
  • axc – The axis to set the limits for.

  • ranges – The ranges to set. If not specified, the current ranges are used.

  • current_ranges – The current ranges.

  • col1 – The first column of the data.

  • col2 – The second column of the data.

  • old_xlims – previous limits of the x axis

  • old_ylims – previous limits of the y axis

trianglechain.utils_plots.setup_figure(fig, n_box, hw_ratios, size, subplots_kwargs)[source]

Setup the figure.

Parameters:
  • fig – The figure to be used.

  • n_box – The number of boxes.

  • hw_ratios – The height/width ratios.

  • size – The size of the figure.

  • subplots_kwargs – The keyword arguments for the subplots.

Returns:

The figure and the axes.

trianglechain.utils_plots.setup_grouping(columns, grouping_kwargs)[source]

Setup the grouping of the plots.

Parameters:
  • columns – The list of columns to be plotted.

  • grouping_kwargs – The grouping keyword arguments.

Returns:

The new list of columns, the grouping indices and the number of columns per group.

trianglechain.utils_plots.update_current_ranges(current_ranges, ranges, columns, data)[source]

Update the current ranges of the data.

Parameters:
  • current_ranges – The current ranges.

  • ranges – The ranges.

  • columns – The list of columns to be plotted.

  • data – The data.

Returns:

The new current ranges.

trianglechain.utils_plots.update_current_ticks(current_ticks, columns, ranges, current_ranges, n_ticks)[source]

Update the current ticks of the data.

Parameters:
  • current_ticks – The current ticks.

  • columns – The list of columns to be plotted.

  • ranges – The ranges.

  • current_ranges – The current ranges.

  • n_ticks – The number of ticks.

Returns:

The new current ticks.

Module contents

This is the trianglechain package.