API reference

Import the names below from fxtensor_bayesnet. fxtensor_bayesnet.__version__ is the installed version string. Docstrings on this page are English. The Japanese build shows the Japanese text from the source. The behaviour is the same.

  • fxtensor_bayesnet.ConfigError

  • fxtensor_bayesnet.load_config()

  • fxtensor_bayesnet.validate()

  • fxtensor_bayesnet.topo_order()

  • fxtensor_bayesnet.config_hash()

  • fxtensor_bayesnet.dump_config()

  • fxtensor_bayesnet.run()

  • fxtensor_bayesnet.Engine

  • fxtensor_bayesnet.Net

  • fxtensor_bayesnet.do_config()

  • fxtensor_bayesnet.to_english_keys()

fxtensor_bayesnet.plot needs matplotlib. Importing the module does not import matplotlib; the first figure does.

Config-driven inference for discrete Bayesian networks, built on fxtensor-salmon.

Loading, validation, formatting, and hashing of configuration files.

exception fxtensor_bayesnet.config.ConfigError[source]

Bases: ValueError

Raised when a configuration file is invalid.

fxtensor_bayesnet.config.load_config(path)[source]

Load a JSON config, validate it, and return it.

fxtensor_bayesnet.config.topo_order(cfg)[source]

Topological order of the variables (parents first). Raises ConfigError on a cycle.

fxtensor_bayesnet.config.validate(cfg)[source]

Check a config. Every problem is reported together in one ConfigError.

fxtensor_bayesnet.config.config_hash(cfg)[source]

Short hash of the config contents. Key order does not matter.

fxtensor_bayesnet.config.dump_config(cfg)[source]

Readable JSON with each kernel row and each label list on one line, so a diff is readable line by line.

The network: states and Markov kernels built with FXTensor, and direct einsum computation.

class fxtensor_bayesnet.network.Net(cfg)[source]

Bases: object

A Bayesian network built from a config. Each child variable’s conditional probability table is a Markov kernel.

A Bayesian network built from a config. Each child variable’s conditional probability table is a Markov kernel.

ancestors(names, cut=())[source]

Ancestor set of names, including the names themselves. Variables in cut are treated as if their edges from parents were removed (graph surgery for do).

joint_size()[source]

Number of elements in the full joint (the product of the label counts).

contract(priors, targets, evidence=None, do=None, cpt=None, free_roots=False)[source]

Variable elimination: einsum only the factors in the ancestor set, and return the unnormalized joint of targets.

evidence maps a variable to a likelihood vector (hard evidence is one-hot). The result is P(targets, evidence). do maps a variable to a distribution that replaces that variable’s kernel (graph surgery, truncated factorization). cpt maps a variable to an ndarray that replaces its kernel, or a root prior (used by sensitivity analysis). free_roots=True returns the kernel from the roots to targets (root priors are not multiplied in). The full joint is not built; np.einsum(..., optimize=True) keeps intermediate tensors small.

einsum_query(priors, targets, free_roots=False)[source]

Direct einsum for the joint of targets, using only the ancestor set. With free_roots=True, the kernel from the roots to targets.

brute_force_joint(priors)[source]

Full joint of every variable in one einsum, for cross-checks. Axis order is self.order.

prior_state(priors)[source]

Root priors as an FXTensor state (tensor product). priors maps each root to a list of probabilities.

build_joint(priors)[source]

Build the joint state: tensor-product the roots, then add each child in topological order with graph_extend.

Axis order is roots (self.roots order) then children (topological order). That can differ from self.order.

fxtensor_bayesnet.network.wiring_size(in_labels, out_idx)[source]

Number of elements in the dense tensor that wiring(in_labels, out_idx) would build.

fxtensor_bayesnet.network.wiring(in_labels, out_idx)[source]

Deterministic wiring kernel X1⊗…⊗Xn → X at out_idx (the labelled form of copy / swap / discard).

fxtensor_bayesnet.network.graph_extend(st, k, parent_axes)[source]

Extend a state I→X by a kernel k:(parents)→Y, producing I→X⊗Y. Does not build a dense identity.

fxtensor_bayesnet.network.self_test_graph_extend()[source]

Check that graph_extend matches the same extension written only with the library.

Inference: marginals per scenario, Bayesian updates, root-cause inversion, interventions, causal effects, sensitivity, and einsum cross-checks.

fxtensor_bayesnet.inference.as_dict(labels, arr, nd=4)[source]

Map labels to probabilities rounded to nd decimal places (-0.0 becomes 0.0).

fxtensor_bayesnet.inference.movement(prior, post, labels)[source]

Movement from prior to posterior: difference, total variation, and KL divergence.

fxtensor_bayesnet.inference.evidence_vectors(net, evidence)[source]

Turn evidence {variable: label | {"likelihood": [...]} | [...]} into {variable: likelihood vector}.

fxtensor_bayesnet.inference.normalize_observation(ob)[source]

Turn one observations item into (result key, evidence dict, legacy form?).

class fxtensor_bayesnet.inference.Engine(net, priors, max_joint=2000000)[source]

Bases: object

Marginals, conditioning, and root-cause inversion for one set of priors.

mode is joint when the joint has at most max_joint elements, and ancestral above that.

Marginals, conditioning, and root-cause inversion for one set of priors.

mode is joint when the joint has at most max_joint elements, and ancestral above that.

marginal(v)[source]

Marginal distribution. In joint mode, discard axes with the library wiring kernel (or sum the joint directly when that kernel would exceed the size limit). In ancestral mode, einsum over the ancestor set (variable elimination).

pair(a, b)[source]

Joint state I → a ⊗ b as an FXTensor. When the wiring kernel would exceed the size limit, sum the joint directly (joint mode) or use einsum (ancestral mode).

condition_raw(obs, label)[source]

Unrounded posterior of each variable given obs=label. Uses conditionalization(2) on the pair (obs, v). Raises ValueError when that observation has probability 0.

condition(obs, label)[source]

condition_raw rounded to four decimal places, as dicts.

posterior_raw(evidence, targets=None)[source]

Condition on several pieces of evidence at once (hard evidence and soft / likelihood evidence), by variable elimination (einsum over the ancestor set).

evidence maps a variable to a label or to {"likelihood": [...]}. Returns (probability of the evidence, or expected likelihood, {variable: posterior}). When targets is omitted, every variable that is not hard evidence is returned. Raises ValueError when the evidence has probability 0.

inversion_roots(obs, label)[source]

inversion_roots_raw rounded to four decimal places, as dicts.

inversion_size(obs)[source]

Number of elements in the dense tensor built for root-cause inversion (all roots × obs).

inversion_roots_raw(obs, label)[source]

Unrounded root posteriors. Builds the kernel (all roots) → obs with einsum and inverts it with FXTensor.bayesian_inversion.

fxtensor_bayesnet.inference.run(cfg, max_joint=2000000)[source]

Run a config and return the result dict. Raises AssertionError when a cross-check that was actually performed does not match.

Interventions (the do-operator, by graph surgery), the average causal effect (ACE), and sensitivity of conditional probability tables.

fxtensor_bayesnet.causal.do_vector(labels, spec)[source]

Turn an intervention spec into a distribution vector. A label string is a hard do(); a list of probabilities is a stochastic intervention.

fxtensor_bayesnet.causal.do_config(cfg, do)[source]

Graph surgery. For each variable in do (label or distribution), drop the incoming kernel and place that distribution in the priors. The original config is not modified.

The derived config has empty scenarios, observations, interventions, effects, and sensitivity.

fxtensor_bayesnet.causal.given_levels(labels, spec)[source]

Normalize one given_do / given value to a list of labels. None means every label; a string is one label; a list is used as given.

fxtensor_bayesnet.causal.strata(given)[source]

Build strata from {variable: [labels, ...]}.

Returns a list of (stratum name, {variable: label}). The name is Z=z, or Z=z, W=w when several variables are set.

fxtensor_bayesnet.causal.effect_spec(cfg, e)[source]

Fill defaults for one effects item: outcome_label is the last label of the outcome, treated the last label of the treatment, control the first.

given_do and given are normalized to {variable: [labels, ...]}. Missing specifications become empty dicts.

fxtensor_bayesnet.causal.effect_key(variables, e)[source]

Result key for one effects item. name is used when it is set. Otherwise the key is X → Y=y, plus the stratification when there is one: X → Y=y | do(Z), X → Y=y | W, or X → Y=y | do(Z), W.

fxtensor_bayesnet.causal.effect_key_errors(variables, effects)[source]

Error messages for effects items whose result keys collide. Empty when they do not.

fxtensor_bayesnet.causal.sensitivity_specs(cfg)[source]

Normalize sensitivity (one object or a list) to a list and fill defaults.

fxtensor_bayesnet.causal.perturb_row(p, j, new_pj)[source]

Set entry j of row p to new_pj and rescale the other entries proportionally so the row still sums to 1.

fxtensor_bayesnet.causal.sensitivity(net, priors, target, label, delta=0.05, top=10)[source]

One-at-a-time sensitivity of P(target=label) to each parameter (each root-prior entry, and each entry of each CPT row in the target’s ancestor set).

Each parameter is moved by ±delta and clipped to [0, 1]; the rest of the same row moves proportionally. A two-label row moves only its last label.

Returns (baseline probability, number of parameters, top rows sorted by swing).

English keys for results.json (--json-keys en / to_english_keys()).

The internal result dict and history snapshots stay in Japanese, which is the canonical form. English keys are an output-only translation. Names chosen by the user (variables, labels, scenarios, and so on) are not translated. The mapping is positional, so a label that happens to be a Japanese key is safe.

fxtensor_bayesnet.keys.KEY_MAP = {'ACE': 'ace', 'KL(事後||事前)[nat]': 'kl_posterior_prior_nat', 'P(上げたとき)': 'p_high', 'P(下げたとき)': 'p_low', 'P(層|do(処置))': 'p_stratum_do', 'P(結果|do(処置))': 'p_outcome_do', 'P(結果|do(処置),do(層))': 'p_outcome_do_given_do', 'P(結果|do(処置),層)': 'p_outcome_do_given', 'P(結果|処置)(観測)': 'p_outcome_observed', 'bayesian_inversionとconditionalizationの最大差': 'max_err_inversion_vs_conditionalization', 'bayesian_inversionの検算を省略した観測': 'inversion_check_skipped', 'einsum(全同時)との最大差': 'max_err_joint_vs_einsum', 'einsum(条件付け)との最大差': 'max_err_conditioning_vs_einsum', 'einsum(祖先集合・周辺)との最大差': 'max_err_marginal_vs_einsum', 'シナリオ': 'scenarios', 'パラメータ': 'parameter', 'パラメータ数': 'n_parameters', 'ベイズ更新(基本)': 'updates_base', 'ホライズン': 'horizon', 'ラベル': 'label', '上げた値': 'high_value', '上位': 'top', '上書き': 'overrides', '下げた値': 'low_value', '不可能な観測': 'impossible', '事前分布(基本)': 'priors_base', '事後': 'posterior', '交絡による差(観測上の差−ACE)': 'confounding_gap', '介入': 'interventions', '介入:切断因子分解との最大差': 'max_err_intervention_vs_truncated_factorization', '介入内容': 'do', '備考': 'remark', '全変動距離TV': 'tv_distance', '処置': 'treatment', '処置群': 'treated', '動きの大きさ順(TV)': 'ranking_by_tv', '同時分布の要素数': 'joint_size', '名前': 'name', '周辺': 'marginals', '因果効果': 'effects', '基本': 'base', '基準のP': 'baseline', '基準値': 'base_value', '基準日': 'as_of', '変化量delta': 'delta', '対照群': 'control', '尤度': 'likelihood', '尤度の期待値': 'expected_likelihood', '層': 'strata', '層別ACE(given_do)': 'stratified_ace_given_do', '層間のACEの差(最後−最初)': 'ace_difference_last_minus_first', '差(pt)': 'delta_pt', '幅(pt)': 'swing_pt', '感度分析': 'sensitivity', '条件': 'given', '条件の値': 'given_values', '条件付きACE(given)': 'conditional_ace_given', '条件付けの検算を省略した観測': 'conditioning_check_skipped', '検算': 'checks', '注意': 'note', '注目変数の事前': 'focus_prior', '注目変数の動き': 'focus_movement', '目的': 'target', '結果': 'outcome', '結果のラベル': 'outcome_label', '観測上の差': 'observed_difference', '観測前の確率': 'evidence_probability', '観測確率0の水準': 'zero_probability_levels', '計算モード': 'mode', '設定ハッシュ': 'config_hash', '証拠': 'evidence'}

Japanese key to English key, for the fixed keys only. The same pairs are listed in the output-format reference.

fxtensor_bayesnet.keys.to_english_keys(res)[source]

Return a new dict with English keys for a run() result. User-chosen names and values are unchanged. An observation key var=label を観測 becomes var=label.

Markdown result tables and a mermaid structure diagram.

fxtensor_bayesnet.report.render_markdown(res, cfg, lang='ja')[source]

Return the results as Markdown. lang is ja or en (heading language; the result dict is still read with Japanese keys).

fxtensor_bayesnet.report.render_mermaid(cfg)[source]

Mermaid graph TD of the network. Roots, intermediate variables, and outputs are coloured.

fxtensor_bayesnet.report.safe(v)[source]

Mermaid node id. Characters other than letters, digits, and _ are replaced with a short hash.

Daily snapshots and diffs.

fxtensor_bayesnet.history.zero(x, nd=1)[source]

Round and normalize -0.0 to 0.0.

fxtensor_bayesnet.history.snapshot_dir(cfg, history_dir)[source]

Snapshot directory, history_dir/as_of.

fxtensor_bayesnet.history.check_snapshot_free(cfg, history_dir, force=False)[source]

Check that the snapshot directory is free. Call this before writing anything.

fxtensor_bayesnet.history.resolve_diff_path(path)[source]

Resolve a --diff argument to (config.json path, results.json path or None).

A directory uses the config.json and results.json inside it. Raises FileNotFoundError when the config cannot be found.

fxtensor_bayesnet.history.snapshot(cfg, res, history_dir, force=False)[source]

Write the config and the results (Japanese keys) to history_dir/<as_of>/.

Raises FileExistsError when the directory exists and force is false. Returns the directory written.

fxtensor_bayesnet.history.previous_snapshot(history_dir, as_of)[source]

Path to config.json of the latest dated snapshot in history_dir strictly before as_of, or None.

fxtensor_bayesnet.history.diff_configs(old, new)[source]

Lines describing changes between two configs. A single ‘no config changes’ line when there are none.

fxtensor_bayesnet.history.diff_results(old, new, threshold_pt=0.1)[source]

Lines for result changes of at least threshold_pt points. A single ‘no result changes’ line when there are none.

Figures. matplotlib is optional: pip install 'fxtensor-bayesnet[plot]'.

  • plot_network — network structure (layered layout; roots, intermediate, and outputs)

  • plot_marginals — marginals of each output, scenarios side by side

  • plot_updates — prior vs posterior of the focus variables, per observation

  • plot_diff — change in marginals (points) since a previous snapshot

  • plot_effects — conditioning vs intervention, when effects is set

  • plot_sensitivity — tornado chart, when sensitivity is set

exception fxtensor_bayesnet.plot.PlotError[source]

Bases: RuntimeError

Raised when a figure cannot be drawn (for example, matplotlib is not installed).

fxtensor_bayesnet.plot.setup_font()[source]

Pick a font that can display Japanese and set it. Warns and keeps the default font when none is found.

fxtensor_bayesnet.plot.node_kinds(cfg)[source]

Map each variable to root, middle, or output. A non-root that is not in outputs is middle.

fxtensor_bayesnet.plot.layered_layout(cfg)[source]

Layered layout (a small Sugiyama-style pass).

A layer is the longest-path distance from the roots. An edge that skips two or more layers gets a dummy node on each layer in between. Order within a layer is improved with a few barycenter sweeps.

Returns layers (elements per layer; a dummy is ("__d", parent, child, layer)), level, parents, and chains ((parent, child) → dummies along that edge).

fxtensor_bayesnet.plot.plot_network(cfg, path, dpi=150, title=None, lang='ja')[source]

Write the network diagram to path and return that path.

fxtensor_bayesnet.plot.plot_marginals(res, cfg, path, dpi=150, ncols=2, lang='ja')[source]

Write marginals of the output variables (scenarios side by side) to path and return that path.

fxtensor_bayesnet.plot.plot_updates(res, cfg, path, dpi=150, lang='ja')[source]

Write prior vs posterior of the focus variables for each observation to path. Returns None when there is nothing to draw.

fxtensor_bayesnet.plot.diff_deltas(old_res, new_res)[source]

{scenario: [(variable, label, change in points)]}, only for scenarios and variables present in both results.

fxtensor_bayesnet.plot.plot_diff(old_res, new_res, cfg, path, dpi=150, old_label=None, new_label=None, lang='ja')[source]

Write the change in marginals, in points, from the previous result to the new one. Returns None when there is no scenario to compare.

fxtensor_bayesnet.plot.plot_effects(res, cfg, path, dpi=150, ncols=3, lang='ja')[source]

Write causal-effect panels (observation vs intervention, and stratum ACEs) to path. Returns None when there are no effects.

fxtensor_bayesnet.plot.plot_sensitivity(res, cfg, path, dpi=150, lang='ja')[source]

Write the sensitivity tornado chart to path. Returns None when there is no sensitivity block.

fxtensor_bayesnet.plot.plot_all(res, cfg, out_dir, formats=('png',), dpi=150, prefix='', lang='ja')[source]

Write network, marginals, and updates (and effects / sensitivity when present) under out_dir. Returns the paths that were written.

Display strings for Markdown and figures. Keys in results.json do not follow --lang (English keys are --json-keys en).

fxtensor_bayesnet.i18n.t(lang, key, **kw)[source]

Return TEXT[lang][key]. Formats it when keyword arguments are given. Raises ValueError for an unsupported language.

fxtensor_bayesnet.i18n.scenario_name(lang, name)[source]

Map the internal scenario name for the base scenario to the display language.

fxtensor_bayesnet.i18n.obs_text(lang, kind, key, r)[source]

Observation heading (kind is obs_header or obs_annot). Hard evidence uses the prior probability of the evidence (percent). An entry that contains soft evidence uses the expected likelihood.

fxtensor_bayesnet.i18n.obs_name(key)[source]

Strip the `` を観測`` suffix from an observation result key, leaving var=label.

Command-line interface for fxtensor-bayesnet.

Usage:

fxtensor-bayesnet [--config PATH] [options]
--config PATH

Config file (default: config.json in the current directory).

--out-dir DIR

Where results.json, results.md, and model.mmd are written (default: the config file’s directory).

--history-dir DIR

Where snapshots are written (default: history/ next to the config).

--no-write

Do not write those files; print to stdout only.

--md

Print Markdown instead of JSON.

--check

Validate the config only (exit code 2 on error).

--snapshot

Save the config and results under <history-dir>/<as_of>/. An existing folder needs --force.

--force

Allow --snapshot to overwrite.

--diff [PATH]

Diff the config (and results) against a previous snapshot. Without PATH, the latest snapshot dated strictly before as_of.

--format-config

Rewrite the config so each kernel row is one line.

--plot

Write figures to the output directory (network, marginals, updates, effects, sensitivity; with --diff, also diff). Requires matplotlib: pip install 'fxtensor-bayesnet[plot]'.

--plot-format

One or more of png and svg (default png).

--plot-dpi N

PNG resolution (default 150).

--lang ja|en

Language of Markdown and figure text (default ja). Does not change keys in results.json.

--json-keys ja|en

Language of keys in results.json and stdout JSON (default ja). Snapshots always keep Japanese keys.

The text above is the English form of the module docstring. --help prints the Japanese text stored on the module.

fxtensor_bayesnet.cli.build_parser()[source]

Return the command-line ArgumentParser.

fxtensor_bayesnet.cli.main(argv=None)[source]

Run the CLI and return a status code: 0 success, 1 snapshot already exists, 2 config or input error, 3 plotting dependency missing.