Skip to content

Python API

This page is generated from the docstrings in the code. For a short introduction, see From Python.

Module Contents
layerbn.analysis Analysis: the complete analysis, from files or from a data frame.
layerbn.figures All figures, and save_figure.
layerbn.project load_project: settings and variables table, checked against each other.
layerbn.design load_design: the variables table.
layerbn.settings load_settings: settings.yml.
layerbn.runner run_project: the function called by layerbn run.
layerbn.explorer The interactive explorer.
layerbn.bn_utils Structure learning and bootstrap, independent of the study design.
layerbn.inference Mutual information and relations to a target.
layerbn.discretisation Binning and bin labels.

Analysis

Analysis

A project plus its data, with every analysis step as one call.

Parameters:

Name Type Description Default
project Project

From layerbn.project.load_project.

required
df DataFrame

One row per participant, one column per variable.

required
verbose bool

Print progress and notes. Turn off for scripts.

True

Attributes:

Name Type Description
df DataFrame

The data actually analysed: the declared variables, complete cases if data.missing is drop_rows.

notes list of str

Everything worth knowing that is not an error: columns that were not used, rows that were dropped, values that were placed in a bin, resamples that failed. These are also written to the report.

set_bins

set_bins(bins: Mapping[str, int] | int | None = None, **per_variable: int) -> Analysis

Choose the number of bins per variable, e.g. 4 for quartiles, 5 for quintiles.

study.set_bins({"AGE": 5, "MEASURE_1": 4}), or study.set_bins(5) for every continuous variable. Variables are named by column or label. This replaces bins and cut points from the design table for those variables, and discards networks learned with the old bins, so learn again afterwards. Returns the analysis, so calls can be chained.

from_files classmethod

from_files(settings_path: str | Path, data_path: str | Path | None = None, *, verbose: bool = True) -> Analysis

Load the project, then the data file named in it (or data_path).

template

template(network_name: str) -> Any

The discretisation of one network, computed once from the full data.

bins

bins(network: str | None = None) -> pd.DataFrame

How every variable was binned. Read this before the results.

network

network(name: str | None = None, *, refresh: bool = False) -> Any

Learn (and keep) the network of one entry in networks.

explore

explore(network: str | None = None, *, path: str | Path | None = None, stability: bool = False, evidence: Mapping[str, Any] | None = None) -> Any

Interactive network: distributions inside the nodes, click to set evidence.

Shows itself in a notebook. With path it is also written as one HTML file that opens in any browser. stability=True colours arcs by their bootstrap frequency (runs the bootstrap if not done yet). evidence can start the page with states chosen, e.g. {"AGE": "≥ 72"}.

arcs

arcs(name: str | None = None) -> list[tuple[str, str]]

The arcs of a network as (parent column, child column).

edge_frequencies

edge_frequencies(name: str | None = None, *, refresh: bool = False) -> dict[tuple[str, str], float]

Fraction of bootstrap resamples that contain each arc.

This is the slow step, and the result is kept, so asking again for a table and then a figure costs nothing.

arc_strengths

arc_strengths(name: str | None = None) -> dict[tuple[str, str], float]

Mutual information (bits) between parent and child, for each learned arc.

stable_edges

stable_edges(name: str | None = None, *, min_frequency: float = 0.0) -> pd.DataFrame

Arc stability as a table, most frequent first.

In network says whether the arc is in the network learned from the full data. That is a different question from how often the arc survives resampling, and the two can disagree in both directions.

compare_networks

compare_networks(names: Sequence[str] | None = None) -> pd.DataFrame

Arc frequency in each network, side by side.

Use this to see what changes when a layer or variable is left out. An empty cell means the arc did not occur in any resample of that network, or the arc is not possible there.

importance

importance(name: str | None = None, *, targets: Sequence[str] | None = None) -> pd.DataFrame

Rank the other variables by mutual information with each target.

Mutual information (bits) is what a variable tells you about the target. It includes information that reaches the target through other variables, so a variable can rank high without being connected to the target directly. Relation says how the variable is connected to the target in the learned network: parent, child, co-parent (shares a child with the target) or other. Arcs is the shortest number of arcs between the two, ignoring direction. Neither number is an effect estimate.

resolve_profile

resolve_profile(network_name: str, profile: Mapping[str, Any], *, label: str = 'profile') -> dict[str, int]

Convert the values of a profile to state indices.

AGE: 72 is placed in the bin that contains 72, a category is matched by name, and "≥ 27" as printed in the bins table also works. Values that cannot be placed are reported and left out.

profiles

profiles(name: str | None = None) -> pd.DataFrame

Probability of each state of the targets, given each profile.

One row per profile, target and state, with the mean over the bootstrap resamples and a 95% percentile interval. The interval reflects uncertainty in both the structure and the parameters, because each resample learns both again.

sweep

sweep(name: str | None = None) -> tuple[pd.DataFrame, dict[str, Any]]

Move one variable across its states with a profile held fixed.

Returns (table, meta). meta carries what the figure needs. A note is made if the fixed profile contains a variable downstream of the moved one: holding it fixed blocks part of the effect being measured. These are conditional probabilities, not effects of an intervention.

summary

summary() -> str

Text description of the project and the data.

Figures

network_figure

network_figure(study: Any, network: str | None = None, *, stability: bool = True, highlight: Sequence[str] = (), layout: str = 'auto', title: str | None = None) -> Any

The network figure for one network of an Analysis.

With stability=True the arc colour shows the bootstrap frequency, which runs the bootstrap for this network if that has not been done yet.

design_figure

design_figure(project: Any, *, layout: str = 'auto') -> Any

The layers and variables without arcs, to check the design before running.

plot_network

plot_network(layers: Sequence[FigLayer], arcs: Sequence[FigArc], *, title: str | None = None, subtitle: str | None = None, layout: str = 'auto', highlight: Sequence[str] = (), label_below: float | None = None, max_arc_labels: int = 60, legend: bool = True) -> Any

Draw layers and arcs, from the top down.

Each layer is a row, in causal order from top to bottom, named in the left margin beside a rule in its colour. Each variable is a card: its name in a strip tinted in the layer's colour (solid for a target) and, when the node has states and probs, one bar per state with its probability. Arcs run downwards, darker and wider the more stable and informative, each with its percentage beside it.

Arcs that skip a row are routed through the gaps between the cards of the rows they cross, so they never run behind a variable, and the arcs at one edge of a card are spread along it. Each percentage sits on its own arc, at a place where it covers no card, no other percentage and as few other arcs as possible.

Parameters:

Name Type Description Default
layers Sequence[FigLayer]

What to draw. An arc's strength sets its width and its frequency its colour; either may be None.

required
arcs Sequence[FigLayer]

What to draw. An arc's strength sets its width and its frequency its colour; either may be None.

required
layout ('auto', 'columns', 'grid')

With grid (the default when layers have time points) each time point is headed in the margin; otherwise the time point is part of the layer name.

"auto"
highlight sequence of column names

Draw only the arcs that touch these variables at full strength and fade the others. Useful for reading the neighbourhood of a target.

()
label_below float | None

By default every arc with a known frequency has its percentage written on it. With a value, only arcs below it are labelled. At most max_arc_labels arcs are labelled, the least stable first.

None

plot_stability

plot_stability(table: DataFrame, *, top: int = 30, title: str | None = None, subtitle: str | None = None) -> Any

Horizontal bars: share of bootstrap resamples containing each arc.

table is the output of Analysis.stable_edges.

plot_importance

plot_importance(table: DataFrame, target: str, *, top: int = 15, title: str | None = None) -> Any

Mutual information of each variable with one target, coloured by relation.

table is the output of Analysis.importance.

plot_profiles

plot_profiles(table: DataFrame, *, title: str | None = None) -> Any

Probability of each state of each target for each profile, with 95% intervals.

plot_sweep

plot_sweep(table: DataFrame, meta: Mapping[str, Any], *, title: str | None = None) -> Any

Target probabilities across the states of the moved variable.

plot_comparison

plot_comparison(table: DataFrame, *, top: int = 25, title: str | None = None) -> Any

Arc frequency in each network, as a matrix.

save_figure

save_figure(fig: Any, path: str | Path, formats: Sequence[str] = ('png', 'pdf'), dpi: int = 300) -> list[Path]

Write a figure in several formats. path may omit the extension.

Project files

load_project

load_project(settings_path: str | Path) -> Project

Read the settings and the design table they point to, and check both.

load_design

load_design(path: str | Path, *, column_pattern: str = DEFAULT_COLUMN_PATTERN) -> Design

Read the design tables and return the expanded, validated design.

load_settings

load_settings(path: str | Path) -> Settings

Read and check settings.yml. Raises SettingsError naming the key.

run_project

run_project(settings_path: str | Path, *, data: str | Path | None = None, output: str | Path | None = None, fast: bool = False, fast_resamples: int = 20, networks: list[str] | None = None, formats: tuple[str, ...] = ('png', 'pdf'), verbose: bool = True) -> RunResult

Run every analysis in the project and write the results folder.

Explorer

write_explorer

write_explorer(study: Any, path: str | Path, network: str | None = None, *, stability: bool = False, evidence: Mapping[str, Sequence[str]] | None = None) -> Path

explorer_model

explorer_model(study: Any, network: str | None = None, *, stability: bool = False) -> dict[str, Any]

Everything the page needs, as plain data.

Learning

build_bn

build_bn(df: DataFrame, layer_map: Mapping[str, Sequence[str]], type_processor: Any, *, score: str = 'K2', search: str = 'tabu', max_parents: int = 5, seed: int = 42, fixed_template: Any = None, enforce_structure: bool = True, no_inner_arcs: Iterable[str] = (), forbidden_pairs: Iterable[tuple[str, str]] = (), mandatory_pairs: Iterable[tuple[str, str]] = (), no_parents: Iterable[str] = (), no_children: Iterable[str] = ()) -> Any

Learn a layered Bayesian network with pyAgrum.

Parameters:

Name Type Description Default
df DataFrame

Complete data. Only the columns in layer_map are used.

required
layer_map mapping

{layer name: [column, ...]} in causal order.

required
type_processor DiscreteTypeProcessor

From layerbn.discretisation.make_type_processor.

required
score ('K2', 'BIC', 'BDeu')

The structure score. K2 and BDeu contain their own prior. BIC does not, so a smoothing prior is added for BIC only: a parent configuration that nobody in a resample happens to occupy then gets a small probability instead of zero. Adding a second prior to K2 or BDeu would count the prior twice.

"K2"
search ('tabu', 'greedy')

Tabu search explores more than greedy hill climbing and is slower.

"tabu"
fixed_template optional

A discretisation computed once from the full data. Bootstrap resamples should share it so that every resample uses the same bins.

None
enforce_structure bool

With False every rule, including the layer order, is skipped. That is an unconstrained search, useful as a comparison and not as the analysis.

True

bootstrap_edge_frequencies

bootstrap_edge_frequencies(df: DataFrame, *, layer_map: Mapping[str, Sequence[str]], type_processor: Any, resamples: int = 200, seed: int = 42, progress: Progress | None = None, **build_kwargs: Any) -> tuple[dict[tuple[str, str], float], int]

Learn the network on resamples bootstrap samples; count each arc.

Returns (frequencies, failed). A frequency is the fraction of resamples in which the arc occurs. The denominator is resamples, not the number of fits that succeeded, so a failed fit lowers every frequency instead of being left out of the calculation.

configure_structure

configure_structure(learner: Any, layer_map: Mapping[str, Sequence[str]], *, no_inner_arcs: Iterable[str] = (), forbidden_pairs: Iterable[tuple[str, str]] = (), mandatory_pairs: Iterable[tuple[str, str]] = (), no_parents: Iterable[str] = (), no_children: Iterable[str] = ()) -> None

Restrict a pyAgrum learner to the arcs the layer order allows.

  • An arc may run from a layer to itself or to a later layer, never back.
  • no_inner_arcs names layers in which members may not be connected.
  • forbidden_pairs are further (parent, child) arcs ruled out.
  • mandatory_pairs are arcs the learner must include.
  • no_parents / no_children pin variables as roots or as sinks.

A pair that is both mandatory and forbidden raises ValueError here, because pyAgrum's own message does not say which pair is at fault.

Inference

Mutual information and structural relations, for reading a learned network.

mutual_information_scores ranks variables by how much they tell you about a target, in bits, computed from the joint distribution of the network.

relations_to_target says how each variable is connected to the target in the learned structure: as a parent, as a child, as a co-parent (a variable that shares a child with the target) or not directly.

Mutual information alone does not say whether a variable is directly connected to the target or only related to it through other variables. Together the two give both pieces of information.

Mutual information given the target's parents is deliberately not offered. In a Bayesian network every variable is independent of its non-descendants given its parents, so that quantity is exactly zero for everything except the target's descendants and says nothing about the data.

mutual_information_scores

mutual_information_scores(bn: Any, target: str, *, exclude: Iterable[str] = (), verbose: bool = False) -> pd.Series

Mutual information (bits) of every other variable with target.

Returns a Series indexed by column name, largest first. A variable for which the computation fails gets NaN, so a gap is visible.

relations_to_target

relations_to_target(bn: Any, target: str) -> dict[str, tuple[str, int | None]]

For each variable: its relation to target, and its distance in arcs.

Relations: parent, child, co-parent (shares a child with the target), other. The distance is the number of arcs on the shortest path between the two variables, ignoring arc direction; None if they are not connected at all.