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.ConfigErrorfxtensor_bayesnet.load_config()fxtensor_bayesnet.validate()fxtensor_bayesnet.topo_order()fxtensor_bayesnet.config_hash()fxtensor_bayesnet.dump_config()fxtensor_bayesnet.run()fxtensor_bayesnet.Enginefxtensor_bayesnet.Netfxtensor_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:
ValueErrorRaised when a configuration file is invalid.
- 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:
objectA 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 incutare treated as if their edges from parents were removed (graph surgery for do).
- 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.evidencemaps a variable to a likelihood vector (hard evidence is one-hot). The result isP(targets, evidence).domaps a variable to a distribution that replaces that variable’s kernel (graph surgery, truncated factorization).cptmaps a variable to an ndarray that replaces its kernel, or a root prior (used by sensitivity analysis).free_roots=Truereturns the kernel from the roots totargets(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. Withfree_roots=True, the kernel from the roots totargets.
- brute_force_joint(priors)[source]¶
Full joint of every variable in one einsum, for cross-checks. Axis order is
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_extendmatches 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
nddecimal 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
observationsitem into(result key, evidence dict, legacy form?).
- class fxtensor_bayesnet.inference.Engine(net, priors, max_joint=2000000)[source]¶
Bases:
objectMarginals, conditioning, and root-cause inversion for one set of priors.
modeisjointwhen the joint has at mostmax_jointelements, andancestralabove that.Marginals, conditioning, and root-cause inversion for one set of priors.
modeisjointwhen the joint has at mostmax_jointelements, andancestralabove that.- marginal(v)[source]¶
Marginal distribution. In
jointmode, discard axes with the library wiring kernel (or sum the joint directly when that kernel would exceed the size limit). Inancestralmode, 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 (
jointmode) or use einsum (ancestralmode).
- condition_raw(obs, label)[source]¶
Unrounded posterior of each variable given
obs=label. Usesconditionalization(2)on the pair(obs, v). Raises ValueError when that observation has probability 0.
- 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).
evidencemaps a variable to a label or to{"likelihood": [...]}. Returns(probability of the evidence, or expected likelihood, {variable: posterior}). Whentargetsis omitted, every variable that is not hard evidence is returned. Raises ValueError when the evidence has probability 0.
- 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, andsensitivity.
- fxtensor_bayesnet.causal.given_levels(labels, spec)[source]¶
Normalize one
given_do/givenvalue to a list of labels.Nonemeans 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 isZ=z, orZ=z, W=wwhen several variables are set.
- fxtensor_bayesnet.causal.effect_spec(cfg, e)[source]¶
Fill defaults for one
effectsitem:outcome_labelis the last label of the outcome,treatedthe last label of the treatment,controlthe first.given_doandgivenare normalized to{variable: [labels, ...]}. Missing specifications become empty dicts.
- fxtensor_bayesnet.causal.effect_key(variables, e)[source]¶
Result key for one
effectsitem.nameis used when it is set. Otherwise the key isX → Y=y, plus the stratification when there is one:X → Y=y | do(Z),X → Y=y | W, orX → Y=y | do(Z), W.
- fxtensor_bayesnet.causal.effect_key_errors(variables, effects)[source]¶
Error messages for
effectsitems 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
jof rowptonew_pjand 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 keyvar=label を観測becomesvar=label.
Markdown result tables and a mermaid structure diagram.
- fxtensor_bayesnet.report.render_markdown(res, cfg, lang='ja')[source]¶
Return the results as Markdown.
langisjaoren(heading language; the result dict is still read with Japanese keys).
- fxtensor_bayesnet.report.render_mermaid(cfg)[source]¶
Mermaid
graph TDof 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.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
--diffargument to(config.json path, results.json path or None).A directory uses the
config.jsonandresults.jsoninside 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
forceis false. Returns the directory written.
- fxtensor_bayesnet.history.previous_snapshot(history_dir, as_of)[source]¶
Path to
config.jsonof the latest dated snapshot inhistory_dirstrictly beforeas_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_ptpoints. 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 sideplot_updates— prior vs posterior of the focus variables, per observationplot_diff— change in marginals (points) since a previous snapshotplot_effects— conditioning vs intervention, wheneffectsis setplot_sensitivity— tornado chart, whensensitivityis set
- exception fxtensor_bayesnet.plot.PlotError[source]¶
Bases:
RuntimeErrorRaised 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, oroutput. A non-root that is not inoutputsismiddle.
- 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, andchains((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
pathand 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
pathand 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, andupdates(andeffects/sensitivitywhen present) underout_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 (
kindisobs_headerorobs_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 PATHConfig file (default:
config.jsonin the current directory).--out-dir DIRWhere
results.json,results.md, andmodel.mmdare written (default: the config file’s directory).--history-dir DIRWhere snapshots are written (default:
history/next to the config).--no-writeDo not write those files; print to stdout only.
--mdPrint Markdown instead of JSON.
--checkValidate the config only (exit code 2 on error).
--snapshotSave the config and results under
<history-dir>/<as_of>/. An existing folder needs--force.--forceAllow
--snapshotto overwrite.--diff [PATH]Diff the config (and results) against a previous snapshot. Without PATH, the latest snapshot dated strictly before
as_of.--format-configRewrite the config so each kernel row is one line.
--plotWrite figures to the output directory (
network,marginals,updates,effects,sensitivity; with--diff, alsodiff). Requires matplotlib:pip install 'fxtensor-bayesnet[plot]'.--plot-formatOne or more of
pngandsvg(defaultpng).--plot-dpi NPNG resolution (default 150).
--lang ja|enLanguage of Markdown and figure text (default
ja). Does not change keys inresults.json.--json-keys ja|enLanguage of keys in
results.jsonand stdout JSON (defaultja). 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.