SDK code usage docs

Follow one capability path in every Darkstar SDK.

Start with installation and core probability models. Then choose specialized, temporal, decision, causal-evidence, policy-evaluation, and operational workflows as the question requires. Every code card switches among all 13 languages.

Model and analysis reference

31 model types and 101 causal-analysis methods.

Open either list to learn what each model represents and what each method does.

Prefer to browse by the job you need to perform? Use the Capability Catalog.

Model types
31
Analysis methods
101
All 31 model types

This inventory includes Bayesian networks, temporal and state-space models, factor and chain graphs, structural causal models, decision and influence models, probabilistic circuits, Gaussian processes, credal inference, and relational and logic-based models. Variants such as hidden Markov models and Kalman filters appear under their corresponding temporal model types.

ModelWhat it models
Bayesian Network (BN) Represents dependencies between discrete variables using an acyclic graph and conditional probability tables.
Linear Gaussian Causal Model Represents linear causal relationships between numerical variables with Gaussian disturbances.
Dynamic Bayesian Network (DBN) Represents discrete variables over time using dependencies within each step and from the preceding step.
Hidden Markov Model (HMM) Represents a hidden discrete state that changes over time and produces observable measurements.
Gaussian Dynamic Bayesian Network (DBN) Represents evolving numerical variables through linear Gaussian dependencies within and across time steps.
Kalman State-Space Model Represents a continuous hidden state with linear Gaussian transitions and noisy observations.
Conditional Linear Gaussian Model (CLG) Represents mixed discrete and continuous variables by letting discrete states select linear Gaussian relationships.
Factor Graph Represents a joint distribution as a product of factors over subsets of discrete variables.
Markov Random Field (MRF) Represents dependencies among discrete variables through an undirected graph and local factors.
Temporal Conditional Linear Gaussian Model (CLG) Represents mixed discrete and continuous processes using conditional linear Gaussian relationships repeated over time.
Latent Gaussian Causal Model Represents linear Gaussian causal systems with correlated disturbances that account for unobserved shared causes.
Partially Observable Markov Decision Process (POMDP) Represents sequential decisions where the true state is hidden and actions depend on beliefs formed from observations.
Markov Decision Process (MDP) Represents sequential decisions where the current state is fully observed and actions affect future states and rewards.
Continuous-Time Bayesian Network (CTBN) Represents discrete variables that change at conditional transition rates in continuous time.
Sum-Product Probabilistic Circuit Represents a probability distribution through weighted sums and products arranged for tractable inference.
Decision Analysis Network (DAN) Represents chance events, decisions, utilities, and the information available when each decision is made.
Gaussian Process Regression (GPR) Represents uncertainty about a continuous function using a covariance kernel and observed input-output pairs.
Lauritzen–Wermuth–Frydenberg Chain Graph (LWF) Represents discrete dependencies using directed and undirected edges under the Lauritzen–Wermuth–Frydenberg interpretation.
Functional Structural Causal Model (SCM) Represents each variable as an explicit function of its causes and exogenous noise.
Credal Network Represents imprecise probabilities through sets of distributions, yielding lower and upper probability bounds.
Influence Diagram with Perfect Recall (ID) Represents sequential decisions where each decision retains all earlier observations and decisions.
Limited-Memory Influence Diagram (LIMID) Represents sequential decisions with explicit restrictions on the information each decision can use.
Markov Influence Diagram (MID) Represents finite-horizon decision problems using state transitions, actions, and utilities in a graphical model.
Probabilistic Relational Model / Object-Oriented Bayesian Network (PRM/OOBN) Represents finite systems of related objects with reusable probabilistic structure for their classes and attributes.
Probabilistic Logic Program (PLP) Represents uncertainty using probabilistic facts and deterministic rules over a finite set of objects.
Probabilistic Soft Logic / Hinge-Loss Markov Random Field (PSL/HL-MRF) Represents soft truth values through weighted logical rules expressed as hinge-loss potentials and hard constraints.
Linear-Chain Conditional Random Field (CRF) Represents the probability of a label sequence given observed features and dependencies between adjacent labels.
Gaussian Markov Random Field (GMRF) Represents a latent Gaussian field through sparse conditional dependencies and an observation model.
Switching Linear Dynamical System (SLDS) Represents a continuous state whose linear Gaussian dynamics change according to a discrete regime.
Nonlinear Non-Gaussian State-Space Model Represents hidden states and observations with nonlinear mechanisms and noise that need not be Gaussian.
Andersson–Madigan–Perlman Chain Graph (AMP) Represents discrete dependencies using directed and undirected edges under the Andersson–Madigan–Perlman interpretation.
All 101 causal-analysis methods

This inventory includes estimators, designs, graph analyses, diagnostics, mediation, conditional effects, policy evaluation, and Bayesian causal profiles.

MethodWhat it does
G-Computation Estimates average outcomes under each treatment by averaging predictions from an outcome model.
Propensity Score Matching (PSM) Estimates a treatment effect by comparing treated and untreated observations with similar treatment probabilities.
Propensity Score Subclassification Estimates an average treatment effect by combining comparisons within groups of similar propensity scores.
Inverse Probability Weighting (IPW) Estimates a treatment effect by weighting observations according to the inverse probability of their received treatment.
Inverse Probability of Censoring Weighting (IPCW) Adjusts treatment-effect estimation for observation or censoring probabilities using inverse weights.
Augmented Inverse Probability Weighting (AIPW) Combines outcome predictions with treatment-probability weights to estimate an average treatment effect.
Targeted Maximum Likelihood Estimation (TMLE) Updates an initial outcome model toward a targeted estimate of the average effect of a binary treatment.
Tabular Front-Door Adjustment Estimates a total causal effect through a measured mediator when the front-door identification conditions hold.
Linear Two-Stage Least Squares (2SLS) Estimates a linear treatment effect using an instrument to isolate treatment variation.
Partially Linear Instrumental Variables (PLIV) Estimates a treatment coefficient with an instrument while allowing flexible adjustment for observed covariates.
Interactive Instrumental Variable Model (IIVM) Estimates a complier treatment effect with a binary instrument and treatment using flexible outcome and assignment models.
Treatment-Effect Generalized Method of Moments (GMM) Estimates a treatment effect by solving declared regression-adjustment or weighting moment conditions.
Sample-Selection Adjustment Estimates an average treatment effect while adjusting for the process that determines which outcomes are observed.
Partially Linear Regression Double Machine Learning (PLR DML) Estimates a treatment coefficient after removing covariate-driven variation from treatment and outcome.
Logistic Partially Linear Regression (Logistic PLR) Estimates a marginal treatment contrast for a binary outcome with flexible adjustment for covariates.
Panel Partially Linear Regression (Panel PLR) Estimates a treatment coefficient in panel data while adjusting for covariates and the declared panel structure.
Interactive Regression Model (IRM) Estimates average treatment effects using separate outcome relationships for treated and untreated observations.
Average Potential Outcome (APO) Estimates the population mean outcome that would occur under a specified treatment.
Multiple-Treatment Average Potential Outcomes (APO) Estimates the mean potential outcome for each treatment in a declared set of treatment options.
External Out-of-Fold Predictions (OOF) Validates externally supplied nuisance predictions and fold assignments for use in cross-fitted causal estimation.
Doubly Robust Conditional Average Treatment Effect (DR-CATE) Estimates how treatment effects vary with observed characteristics using cross-fitted outcome and propensity predictions.
Nonparametric Double Machine Learning (DML) Estimates a flexible treatment-effect function using orthogonalized outcome and treatment information.
Two-Group, Two-Period Difference-in-Differences (DiD) Estimates the effect on a treated group by comparing its before-and-after change with a control group.
Panel Difference-in-Differences (DiD) Estimates treatment effects from repeated observations of the same units before and after treatment.
Repeated Cross-Section Difference-in-Differences (DiD) Estimates treatment effects from before-and-after population samples that need not contain the same individuals.
Two-Way Fixed Effects (TWFE) Estimates a declared panel treatment coefficient after accounting for unit and time fixed effects.
Staggered-Adoption Group-Time Effects Estimates separate treatment effects for groups that begin treatment at different times.
Event Study Estimates a sequence of treatment effects indexed by time before or after treatment begins.
Two-Stage Difference-in-Differences (DiD) Estimates a treatment effect in a second stage after removing untreated outcome patterns in a first stage.
Local-Projection Difference-in-Differences (DiD) Estimates treatment responses at separate time horizons using local-projection comparisons.
Synthetic Control Estimates an intervention effect by comparing a treated unit with a weighted combination of untreated donor units.
Synthetic Difference-in-Differences (SDiD) Estimates a panel treatment effect using unit and time weights to improve treated-control comparability.
Low-Rank Panel Counterfactuals Estimates untreated outcomes by completing a low-rank panel and compares them with observed treated outcomes.
Segmented Interrupted Time Series (ITS) Estimates changes in outcome level and trend at a declared intervention time.
Comparative Interrupted Time Series (ITS) Estimates an intervention effect by comparing changes in a treated time series with a control series.
Bayesian Structural Time-Series Causal Impact (BSTS) Estimates intervention impact by comparing observations with a posterior forecast of the untreated time series.
Geographic Lift Estimates incremental outcomes across treated and comparison regions under a declared geographic study design.
Sharp Regression Discontinuity Design (RDD) Estimates a local treatment effect at a cutoff that deterministically assigns treatment.
Fuzzy Regression Discontinuity Design (RDD) Estimates a local complier effect where crossing a cutoff changes the probability of treatment.
Covariate-Adjusted Regression Discontinuity Design (RDD) Estimates a local cutoff effect while adjusting for observed covariates.
Binary-Treatment Causal Forest Estimates how the effect of a binary treatment varies across observations using an ensemble of causal trees.
Double Machine Learning Orthogonal Forest (DML) Estimates local treatment effects with forest weights and orthogonalized outcome and treatment models.
Doubly Robust Orthogonal Forest (DR) Estimates local treatment effects with forest weights and doubly robust outcome and propensity adjustments.
Causal Forest with Double Machine Learning (DML) Estimates heterogeneous treatment effects with an honest forest fitted to residualized treatment and outcome information.
Doubly Robust Forest (DR) Estimates heterogeneous treatment effects by fitting a forest to doubly robust effect targets.
Single-Model Meta-Learner (S-Learner) Estimates conditional treatment effects by comparing predictions from one outcome model with treatment as an input.
Two-Model Meta-Learner (T-Learner) Estimates conditional treatment effects by comparing separate treated and untreated outcome models.
Imputed-Effect Meta-Learner (X-Learner) Estimates conditional treatment effects by combining effect models fitted to imputed treatment contrasts.
Residual-Loss Meta-Learner (R-Learner) Estimates conditional treatment effects by minimizing a loss based on residualized outcomes and treatments.
Uplift Tree Partitions observations into groups with different incremental responses to treatment.
Uplift Forest Combines multiple uplift trees to score how incremental treatment responses vary across observations.
Causal Tree Estimates treatment effects within subgroups while separating tree construction from effect estimation.
Multiple-Treatment Causal Forest Estimates heterogeneous treatment contrasts across multiple treatment arms using a causal forest.
Instrumental Forest Estimates heterogeneous treatment effects from instrument-induced treatment variation.
Restricted Mean Survival Time Forest (RMST) Estimates heterogeneous treatment effects on expected survival time up to a specified horizon.
Survival Probability Forest Estimates heterogeneous treatment effects on the probability of surviving beyond a specified time.
Continuous-Treatment Partial-Effect Forest Estimates how a continuous treatment locally changes the outcome across different covariate profiles.
Conditional-Effect Result Evaluation Evaluates a previously fitted conditional-effect result for declared observations and treatment contrasts.
Potential-Outcome Quantiles Estimates quantiles of the outcome distribution under each declared treatment.
Quantile Treatment Effects (QTE) Compares treatment-specific outcome quantiles across a declared probability grid.
Conditional Distribution Treatment Effects (CDTE) Compares treatment-specific outcome distribution probabilities at declared thresholds and covariate profiles.
Dose-Response Curve Estimates how the mean outcome changes across a declared grid of treatment doses.
Generalized Propensity Score Dose Response (GPS) Estimates a dose-response curve while adjusting for the conditional distribution of a continuous treatment.
Stochastic Intervention Estimates the mean outcome under a treatment policy that assigns treatments probabilistically.
Transported Treatment Effect Estimates a treatment effect for a target population using information from a different source population.
Selection-Diagram Data Fusion Combines data sources to identify an effect under declared graphical assumptions about population differences.
Linear Proximal Causal Effect Estimates a treatment effect through linear bridge functions using observed proxies for unmeasured confounders.
Intervention Calculus with an Absent Directed Acyclic Graph (IDA) Evaluates possible causal effects across graphs consistent with a partially specified causal structure.
Generalized Covariate Adjustment Checks which covariate sets identify a causal effect under the graph's adjustment criterion.
Placebo Treatment Check Tests whether replacing the treatment with a placebo assignment produces an unexpected estimated effect.
Random Common-Cause Check Checks how an effect estimate changes after adding a randomly generated candidate confounder.
Unobserved-Confounder Sensitivity Traces how an estimated effect changes across declared strengths of unmeasured confounding.
Data-Subset Stability Check Checks how an effect estimate changes when the analysis is repeated on subsets of the data.
Bootstrap Stability Check Assesses variation in an effect estimate by repeatedly resampling the observed data.
Negative-Control Check Tests a relationship expected to have no causal effect to detect possible bias or model problems.
Rosenbaum Sensitivity Bounds Bounds the sensitivity of matched-study conclusions to hidden differences in treatment assignment odds.
E-Value Sensitivity Summarizes the unmeasured-confounding strength needed to explain away a declared risk-ratio effect.
Ordinary Least Squares Partial R-Squared Sensitivity (OLS) Assesses how omitted-variable relationships with treatment and outcome could change a linear effect estimate.
Partially Linear Instrumental Variables Weak-Instrument Check (PLIV) Assesses whether the instrument supplies enough treatment variation for the declared partially linear analysis.
Treatment Overlap Diagnostics Checks whether treated and untreated observations have sufficient overlap in their treatment probabilities.
Pre-Treatment Trend Diagnostics Checks whether differences in outcome trends are evident before treatment begins.
Synthetic Control Diagnostics Assesses synthetic-control credibility with donor placebo comparisons and leave-one-out checks.
Controlled Direct Effect Measures the treatment effect when the mediator is held at a specified value.
Natural Direct Effect Measures the treatment effect while the mediator follows its natural value under the reference treatment.
Natural Indirect Effect Measures the effect transmitted through treatment-induced changes in the mediator.
Total Effect Measures the combined direct and mediated effect of changing the treatment.
Path-Specific Effect Measures the treatment effect transmitted along selected causal paths.
Interventional Mediation Separates direct and indirect effects using interventions on the mediator's distribution.
Contextual Bandit Policy Value Estimates the expected reward of a target action policy using contextual logged decisions.
Inverse Propensity Scoring / Self-Normalized Inverse Propensity Scoring (IPS/SNIPS) Estimates target-policy value by reweighting logged rewards, optionally normalizing the weights.
Doubly Robust Off-Policy Evaluation (DR-OPE) Estimates target-policy value by combining reward predictions with importance-weighted corrections.
Sequential Doubly Robust Policy Evaluation (DR) Estimates finite-horizon policy value using reward predictions and sequential importance-weighted corrections.
Fitted Q Evaluation (FQE) Estimates a target policy's value by repeatedly fitting its expected future reward function.
Structural Policy Replay Evaluates a target policy within a structural model while reusing the same exogenous randomness across policy comparisons.
Dynamic Treatment Regime (DTR) Evaluates a sequence of treatment rules that adapt to an individual's observed history.
Policy Tree or Forest Evaluates treatment decisions learned as a tree or forest of rules based on observed characteristics.
Finite-Horizon Policy Optimization Selects a policy using a conservative estimate of its value over a declared finite horizon.
Bayesian Causal Generalized Linear Model (GLM) Estimates a posterior treatment contrast with a Bayesian linear or generalized linear outcome model.
Hierarchical Bayesian Treatment Effects Estimates population and group treatment effects with partial pooling across groups.
Bayesian Additive Regression Trees for Causal Effects (BART) Estimates nonlinear conditional treatment effects with a posterior ensemble of regression trees.
Gaussian Process Causal Surface (GP) Estimates a smooth treatment-effect surface with posterior uncertainty using a Gaussian process.

Stage 1

Start with installation and a core model.

Load the package, build a finite-discrete BBN, add evidence, and inspect the graph.

Install and import

Start with the package and import path that match your stack.

These public pages describe the current supported SDK line from installation through models, decisions, causal evidence, and delivery. Every downloaded archive includes exact-version offline technical docs and its native API reference.

Inputs

Choose the package source, import path, and modules that match your app, service, or notebook environment.

Outputs

You get the concrete constructors and helper functions used by the later samples, so installation is tied directly to usage.

Package / module

darkstar crate

Rust

Add the crate with `cargo add darkstar`, then pull the helpers you need into scope.

Discrete BBN graph generation

Generate singly connected and multi-connected graphs.

Use the generator helpers when you want deterministic seed-driven graph creation for demos, tests, and benchmarking before you hand-tune a production model.

Inputs

Pass graph-size controls such as node count, edge density, state count, and a seed so the generated shape is reproducible.

Outputs

The generator returns a graph plus starter parameters that can flow directly into model construction and benchmark fixtures.

Package / module

darkstar generator helpers

Rust

Discrete BBN

Build a small discrete model from labeled graph and CPT values.

Use the host SDK builder to name nodes, states, edges, and probabilities directly. Then start with the task prediction method; numeric ordinals and the native __p__ table key stay behind the compatibility layer.

Inputs

Provide a directed graph and one CPT per node, including root distributions and any parent-conditioned rows.

Outputs

The constructor returns a reasoning model that can answer exact associational, interventional, and counterfactual queries.

Package / module

darkstar

Rust

Discrete BBN evidence

Run probability queries with hard, soft-finding, and virtual evidence.

Darkstar uses pquery as the short alias for a probability query: it returns posterior distributions after conditioning on evidence. Start with an observed state, then move to weighted finding and virtual evidence when you want softer beliefs.

Inputs

Choose the queried nodes, then provide either a hard observed value, a weighted finding over the node states, or a virtual evidence vector over the same states.

Outputs

Each pquery call returns the posterior distribution for the requested nodes, making it easy to compare how different evidence styles shift the result.

Package / module

darkstar evidence helpers

Rust

Use the discrete model built above; the query payload can carry observation, finding, or virtual evidence arrays directly through `evidences`.

Discrete BBN

Run associational, interventional, and counterfactual queries.

Use one discrete model for marginals, joints, conditionals, evidence probabilities, interventions, and counterfactual mirrors.

Inputs

Choose the nodes or target you want, then add factual evidence, optional given variables, and hypothetical interventions when you move into counterfactual analysis.

Outputs

Associational calls return potentials or scalar evidence probabilities, iquery returns causal effects, and the counterfactual helpers mirror the same marginal, joint, conditional, and evidence forms.

Package / module

darkstar

Rust

Graph layout

Lay out the graph for explorer, editor, and dashboard UIs.

Layout helpers give you deterministic node coordinates for customer-facing graph views without forcing you into one front-end framework.

Inputs

Pass the graph you already built plus a named layout algorithm supported by the wrapper or runtime.

Outputs

You get stable node coordinates that can be fed into canvases, SVGs, editors, and dashboard components.

Package / module

darkstar layout helpers

Rust

Stage 2

Choose the model family that matches the question.

Move from continuous and hybrid models to portable SCMs and specialized native families.

Linear-causal Gaussian (LCG)

Build an LCG model without changing the continuous serde format.

LCG is the causal interpretation of the existing static continuous Gaussian SCM: define the graph, provide ordered parameters, and construct the same portable model in code.

Inputs

Define the graph, the ordered variable list, and the Gaussian parameters such as means and covariance terms expected by the wrapper.

Outputs

You get one continuous reasoning model ready for all three levels of Pearl’s causal hierarchy, plus a canonical JSON round trip in the existing continuous envelope.

Package / module

darkstar::ScmModel

Rust

LCG Pearl hierarchy

Run Pearl levels 1–3 on one linear-causal Gaussian model.

Use pquery for level-1 conditioning, iquery and equery for level-2 interventions and contrasts, and cquery or cquery_stats for level-3 shared-disturbance counterfactuals.

Inputs

Use observed numeric values for conditioning, then provide interventions or counterfactual scenarios when you want to compare worlds.

Outputs

The calls return posterior moments, interventional summaries, effect contrasts, and counterfactual values or moments without changing the LCG serde envelope.

Package / module

darkstar continuous queries

Rust

Conditional linear Gaussian (CLG)

Keep categorical regimes and selectable inference together.

CLG is distinct from the all-continuous LCG model and an unstructured GMM: categorical regimes and linear-Gaussian mechanisms share one causal DAG. Exact inference is the default; Rao-Blackwellized importance inference is an explicit scalable route.

Model and serde

Categorical nodes have categorical parents only; continuous nodes may also have continuous parents and must define one positive-variance regime per categorical-parent tuple. Canonical version-1 JSON and its semantic digest round-trip byte-for-byte. Engine selection is runtime policy and never enters model serde or identity.

Inference and PCH

Omit inference controls for exact pquery, iquery, equery, cquery, and caller-ordered named worlds. Or attach an immutable approximate policy when constructing the model and override it per invocation when needed. Structural worlds share inverse-CDF categorical noise and Gaussian disturbances after factual abduction in either mode.

Read and govern results

Exact continuous answers retain every Gaussian-mixture component; approximate answers are Gaussian summaries with quality diagnostics. There is no silent fallback: auto is unavailable, and impossible evidence, cancellation, deadlines, accuracy gates, and resource limits remain typed outcomes.

Package / module

darkstar

Rust

clgSpec is the canonical two-regime model from the CLG architecture guide. Exact remains the default; the sample also creates an immutable native Rao-Blackwellized-importance view and overrides it back to exact for one call. It queries both target kinds and runs p/i/e/c plus ordered named-world PCH through the same native C++ engine. Inference policy stays outside canonical model serde and its semantic digest.

Qualified model interchange

Move models through qualified external formats.

Keep canonical Darkstar JSON as model identity. Use native BIF, XMLBIF, XDSL, or UAI BAYES conversion for BBNs and UAI MARKOV for top-level factor graphs.

Round trip

Export one bounded envelope, import an owned model, and inspect native fidelity diagnostics.

Boundary

Lossy export needs explicit consent; limits, deadlines, and cancellation remain native.

Package / module

darkstar crate

Rust

Canonical JSON remains model identity. External formats are bounded native conversions with fidelity diagnostics and explicit loss consent.

Portable functional SCMs

Model nonlinear, non-Gaussian mechanisms and replay shared-noise worlds.

Declare portable mechanisms and exogenous distributions, then use one compiled native model for seeded simulation, supplied-noise evaluation, and exact abduction-action-prediction. The counterfactual worlds keep the factual disturbance profile fixed.

Build

Use SDK expression helpers to create versioned mechanism data. Helpers never execute a host callback; the C++ engine validates and compiles the expression graph.

Evaluate and sample

Evaluate known exogenous values for analytic checks, or draw reproducible seeded batches from Laplace, logistic, Gaussian, Bernoulli, categorical, and other declared laws.

Counterfactual

Provide factual endogenous values for invertible mechanisms, apply named value or mechanism interventions, and compare predictions under one shared exogenous state.

Package / module

darkstar

Rust

The builder creates portable data, not a host callback. Sampling, supplied-noise evaluation, exact invertible abduction, interventions, and shared-world prediction all execute in the same native C++ engine through the C ABI.

Credal and imprecise inference

Bound what the model can say when its mechanisms are uncertain.

Replace selected CPT rows with vertices or lower/upper simplex constraints, then query associational, interventional, and shared-parameter counterfactual lower and upper probabilities. Exact runs return extremizing witnesses; governed anytime runs keep witnessed inner bounds, safe outer bounds, and the remaining gap distinct.

Local uncertainty

Attach a separately specified credal set to any discrete CPT row. Point-valued sets collapse to the ordinary BBN, while interventions remove uncertainty from the mechanisms they replace.

Three causal levels

Use p for conditioning, i for mechanism replacement, and c for factual abduction plus a counterfactual action. Counterfactual extrema retain one precise parameter configuration across both worlds.

Certified or anytime

Enumerate bounded vertex spaces exactly, or set a deterministic evaluation budget. Read lower and upper witnesses, inner and outer bounds, gap, termination, resource use, and warnings from the common result.

Package / module

darkstar

Rust

The example continues from a darkstar.credal-model document whose local CPT rows use vertices or lower/upper simplex bounds. Associational, interventional, and shared-parameter counterfactual bounds, exact witnesses, honest anytime gaps, batches, limits, and cancellation all execute in the native C++ engine through the C ABI.

Native CPU model families

Choose among nine specialized native model families.

One exact-by-default C++ engine owns factor graphs, finite-discrete LWF chain graphs, temporal CLGs, latent causal models, POMDPs, continuous-time Bayesian networks, probabilistic circuits, decision-analysis networks, and Gaussian-process regression.

Families

Choose FactorGraphModel, FiniteDiscreteLwfChainGraphModel, TemporalConditionalLinearGaussianModel, LatentCausalModel, PomdpModel, ContinuousTimeBayesianNetwork, ProbabilisticCircuitModel, DecisionAnalysisNetwork, or GaussianProcessModel.

Serde and queries

Construct from canonical JSON, round-trip the validated model, retain its semantic digest, and run schema-versioned requests. Exact routes are default; approximate and statistical routes are always explicit.

PCH

Temporal CLG and latent causal models expose their governed associational, interventional, and counterfactual levels. Families where the Pearl hierarchy is not meaningful say so instead of borrowing causal semantics.

Runtime boundary

C++ owns validation, math, cancellation, limits, diagnostics, and results. The 12 non-C++ packages are idiomatic C ABI adapters, not independent implementations.

Package / module

darkstar

Rust

Darkstar runs validation, canonical serde, inference, cancellation, and resource limits in the native C++ engine through the governed C ABI. Exact is the default; approximate or statistical operations must be selected explicitly and report method, seed, quality, and resource diagnostics.

Finite-discrete LWF chain graphs

Query a standalone LWF chain-graph model.

Construct the dedicated LWF schema and run exact bounded associational inference without borrowing DAG or generic model-family semantics.

Semantics

The model exposes rung-1 probability inference over chain components.

Boundary

It does not claim intervention, counterfactual, learning, CPDAG/PAG, or AMP support.

Package / module

darkstar crate

Rust

The standalone LWF model provides exact finite-discrete associational rung-1 inference without causal-effect or learning claims.

Stage 3

Add time only when the model is temporal.

Use one temporal contract for state inference, exact path decoding, causal worlds, and streams.

Dynamic Bayesian networks

Filter, forecast, smooth, and score a discrete time series.

Load one canonical weather DBN, condition the current state, predict future slices, revise an earlier state with later evidence, and score an observed sequence. These are Pearl Level 1 associational operations over time.

Inputs

Use zero-based observations and targets over the same immutable finite-discrete temporal model. Filtering uses evidence through the target time, forecasting reaches forward, and smoothing can use later evidence.

Outputs

Each operation returns the canonical temporal result envelope with values, exact provenance, the selected method, model identity, and resource diagnostics.

Sequence score

Log likelihood scores the observation history itself, so it is useful for monitoring model fit and comparing candidate temporal models without requesting a target marginal.

Package / module

darkstar

Rust

All four Level 1 operations reuse the immutable native plan. Results retain exactness, method, model digest, resource diagnostics, and Pearl level in their provenance envelope.

Exact temporal decoding

Decode the most likely hidden-state path.

Use exact Viterbi on a qualified finite-discrete HMM. The result keeps the path, joint log probability, model identity, method, limits, and provenance together.

Input

Provide an ordered observation sequence through the temporal query contract.

Output

Read one exact joint-MAP path; Viterbi is not a sequence of independent marginals.

Package / module

darkstar crate

Rust

Viterbi is exact joint-MAP decoding for qualified finite-discrete HMMs; it reports method, model identity, limits, and provenance.

Temporal causality

Compare observed, intervened, and counterfactual worlds.

Hold the evidence, target, and target time fixed while moving from association to a time-indexed intervention and then to abduction-action-prediction. The comparison makes the three Pearl levels concrete without changing the question halfway through.

Observed

Condition on seeing an umbrella at time 2 and ask for rain at time 2. This is a Level 1 posterior in the factual world.

Intervened

Keep that evidence and target, but replace the rain mechanism at time 1. This Level 2 query predicts under an explicit do-style action.

Counterfactual

Abduce from the same factual evidence, apply the time-1 action in a named world, and predict rain at time 2 there. This is a Level 3 counterfactual.

Package / module

darkstar

Rust

The three requests deliberately keep the umbrella evidence and rain target at time 2 fixed. Only the world semantics change: observe, intervene at time 1, then ask the time-2 counterfactual.

Streaming DBN sessions

Reuse a compiled plan for an observation stream.

Use a session when observations arrive one slice at a time. Advance transactionally, inspect the current marginal or a forecast, retain a sequence score, and capture a replayable event log where the wrapper exposes it.

Ownership

Share the immutable compiled model across work, but give each stream or worker its own mutable session and close it deterministically.

Bounds

Apply step, event, work, memory, and deadline limits for long-lived services. A rejected advance does not publish partial state.

Replay

Event logs are the cross-build recovery format; exact checkpoints are a same-engine-build optimization in SDKs that expose checkpoint operations.

Package / module

darkstar

Rust

Keep one immutable model per worker and one mutable session per stream. Sessions reuse the compiled plan; close them deterministically and bound long-lived streams where the wrapper exposes session resource options.

Linear-Gaussian DBNs

Track continuous state with exact Gaussian inference.

Load a compact linear-Gaussian temporal model and use the same time-indexed contract for Kalman filtering, RTS smoothing, forecasting, interventions, and structural counterfactual replay.

Inputs

Define continuous variables, linear transition mechanisms, and Gaussian innovation laws, then supply numeric observations and moments targets at absolute times.

Outputs

Queries return means and variances with exact provenance and numerical diagnostics rather than discrete state-probability rows.

Package / module

darkstar

Rust

LinearGaussianDBN uses the same canonical model/query/result contract as DiscreteDBN, with exact Kalman filtering, RTS smoothing, Gaussian forecasting, interventions, and structural replay.

Stage 4

Turn beliefs into governed decisions.

Start with utility, then progress through policy structure, time, and multi-objective planning.

Influence diagrams

Evaluate single-decision expected utility and MEU.

Use an influence-diagram JSON payload when one finite decision chooses between actions under chance-model uncertainty. The single-decision surface evaluates a fixed action with expectedUtility and selects the best action with maximumExpectedUtility.

Inputs

Native influence-diagram JSON containing the discrete BBN chance model, decision specs, decisionOrder, informationSets, and complete finite utility tables; optional evidence known before choosing the action.

Outputs

Expected utility for a fixed action, plus maximum expected utility, selected action, action-level feasibility, and diagnostics for MEU.

Package / module

darkstar

Rust

diagram_json is the native influence-diagram JSON: a discrete BBN plus decisions, decisionOrder, informationSets, and complete finite utility tables.

Influence diagrams

Solve multi-decision policies with exact variable elimination.

Use solvePolicy for ordered finite decisions with explicit information sets. The auto solver selects exact variable elimination; bruteforce remains available for small oracle checks.

Inputs

Same influence-diagram payload, contextEvidence known before the first decision, optional solver limits, and optional solver selection auto, variableElimination, or bruteforce.

Outputs

Global maximum expected utility, complete policy tables for each decision, unreachable-row diagnostics, solver name, evaluated row counts, and variable-elimination diagnostics.

Package / module

darkstar

Rust

solvePolicy defaults to exact variable elimination; pass bruteforce only for small oracle checks.

Limited-memory decisions

Optimize exact policies without inventing perfect recall.

Declare exactly what each decision can observe, inspect the resulting information structure, and solve the bounded deterministic policy space exactly. The result preserves declared action-order ties and reports typed resource refusal instead of applying an invalid perfect-recall algorithm.

Explicit memory

Set memoryProfile to limitedMemory and list each decision information set. Later decisions may forget earlier signals or actions; unknown, future, and post-decision information is rejected.

Inspect before solving

Analyze policy rows, complete-strategy count, assignment work, perfect-recall status, limits, and the conservative structural elimination-solvability certificate.

Exact and governed

The LIMID path performs complete deterministic strategy search inside policy-row, strategy, assignment, factor, and cancellation bounds. It returns exact MEU, complete policy rows, global strategy ties, and stable typed outcomes.

Package / module

darkstar

Rust

The example continues from a complete influence-diagram document with memoryProfile=limitedMemory. Information validation, exact bounded strategy search, additive utility, ties, resource limits, and cancellation execute in the native C++ engine through the C ABI; each SDK only adapts the same result.

Temporal decision analysis

Optimize Markov policies and compare cost-effectiveness.

Use one finite-horizon temporal decision model to solve an exact policy, evaluate candidate strategies in a shared native batch, and calculate economically valid cost-effectiveness results.

Inputs

Pass a canonical temporal model, finite horizon, stationary action, explicit time-indexed information, named additive utility/cost/effect dimensions, hard evidence, exact solver limits, and compact named strategies.

Outputs

Results include exact policy rows and objective totals, solver provenance and complexity, fixed-strategy values and increments, strict or extended dominance, efficient frontier, valid ICERs, and willingness-to-pay NMB ranking.

Scale safely

Fully observed current-state policies use backward induction. Future-conditioned or history-aware policies use exact bounded enumeration; auto never falls back to approximation. Preflight the structure before large solves.

Package / module

darkstar

Rust

The example continues from the complete markovSpec and named compact strategies in the correctness fixture. Backward induction, evidence conditioning, batch evaluation, dominance, NMB, and valid ICERs execute in the native C++ engine through the C ABI; each SDK only adapts the same result.

Governed causal decisions

Discover decision capabilities before planning.

Read the native capability document, then use only the comparison, handoff inspection, recovery inspection, or model-bound planning lane it authorizes.

Lifecycle

Runtime loading returns stateless proof; recovery verdicts are inspection-only.

Authority

Native code owns eligibility, objective evaluation, feasibility, dominance, and ranking.

Package / module

darkstar crate

Rust

Read native capability metadata before comparison, handoff inspection, recovery-verdict inspection, or model-bound planning.

Stage 5

Build causal evidence before estimating policy value.

Identify the target, estimate it, challenge it, and preserve refusals before policy evaluation.

Causal identification

Compile a front-door target and inspect the exact formula.

Supply a DAG or ADMG and ask whether the effect is identifiable before choosing or fitting an estimator. Darkstar returns a normalized observational estimand and derivation trace, or a typed hedge certificate when ID proves the target is not identifiable.

Inputs

Use stable node IDs, directed causal edges, bidirected latent-confounding edges, outcomes, interventions, and optional conditioning variables.

Outputs

The exact result contains the selected ID or IDC method, canonical graph and query digests, an executable normalized estimand, and every derivation step.

Boundary

This operation identifies an effect from a supplied graph. It does not learn causal structure, silently choose assumptions, or implement inference in the wrapper.

Package / module

darkstar

Rust

ID/IDC, formula normalization, derivation traces, and hedge certificates run in the native C++ engine through the governed C ABI.

Causal estimation

Estimate and refute causal effects with honest uncertainty.

Normalize typed columns once, fit a reusable native estimator session, evaluate g-computation, IPW, or doubly robust AIPW targets, and run governed refuters without moving statistics into the wrapper.

Inputs

Provide an identified adjustment estimand plus numeric or dictionary-encoded categorical columns with explicit treatment, outcome, covariate, effect-modifier, validity, and optional weight roles.

Outputs

Estimate results include influence-curve uncertainty and model diagnostics. Refutation results add the original and perturbed estimates, reference distribution, p-value, standardized changes, deterministic replicate lineage, warnings, and provenance.

Boundary

Placebo treatment, random common cause, subset, bootstrap, and assumption diagnostics run in native C++. Passing is robustness evidence, not proof of causal correctness. Darkstar refuses nonidentified targets, unsupported shapes, and resource violations.

Package / module

darkstar

Rust

ATE, ATT, subgroup CATE, refutation, nuisance fitting, overlap and balance diagnostics, and influence-curve uncertainty run in native C++. Reuse a fitted session for multiple targets and refuters.

Treatment effects

Choose a structural contrast or a fitted-data estimand explicitly.

Use queryEffect on an applicable causal model to compare two intervention worlds. Use the fitted estimator separately for ATE, ATT, ATC, or GATE. Both routes preserve their assumptions, uncertainty, exactness, selected method, diagnostics, and provenance.

Structural model query

Population average, a proven pre-treatment group average, and a factual unit-effect distribution are available on static discrete, static Gaussian, static CLG, discrete DBN, Gaussian DBN, temporal CLG, and latent-causal models. Exact and approximate availability is model-specific, and exact never silently falls back.

Fitted-data estimator

ATE averages over the analysis population, ATT over treated rows, ATC over controls, and GATE over an explicit subgroup. The legacy cate spelling remains a compatibility route for a supplied subgroup.

Do not overclaim

A GATE is not an individual treatment effect. A structural unit-effect distribution is a Level-3 model result under the declared shared-noise coupling and assumptions, not a model-free identified ITE.

Package / module

Darkstar Rust SDK

Rust

queryEffect compares worlds inside a structural model. The fitted estimator is separate: use ATE, ATT, ATC, or GATE and keep its uncertainty and diagnostics. A group effect is not an identified individual treatment effect.

Causal mediation

Decompose total effects and inspect governed path effects.

Reuse a compiled functional model to measure natural direct and indirect effects, then select a declared treatment-to-outcome path. Darkstar preserves the exact effect definition and refuses nonidentified, recanting, or unsupported targets with typed failures.

Effect family

Hold mediators fixed for a controlled direct effect; compare treatment worlds for natural direct and indirect effects; and measure the total effect. Under this convention, the natural direct and indirect effects decompose the total.

Selected paths

Declare complete ordered paths such as X → M → Y. With treatment-mediator interaction, a selected mediated path is not assumed to equal the natural indirect effect.

Identification and diagnostics

Read identified, estimate, failure, assumptions, method, exactness, seed, model digest, and capabilities from the common native result. The wrapper does not substitute a nearby estimand.

Package / module

darkstar

Rust

The example continues from a portable functional-SCM builder with X → M, X → Y, and M → Y. Controlled, natural, total, and selected-path worlds, identification checks, typed failures, and estimates all execute in the native C++ engine through the C ABI.

Causal model evaluation and attribution

Validate mechanisms and explain anomalies or distribution shifts.

Evaluate structural residuals, score anomalous outcomes against a governed reference, attribute those scores through Shapley hybrid worlds, and localize mechanism changes between compatible functional SCMs. The common result keeps assumptions, uncertainty, provenance, limits, and additivity diagnostics explicit.

Model evaluation

Compare observed endogenous values with mechanism predictions for supplied exogenous rows. Per-mechanism residuals and the overall pass flag use your declared absolute tolerance.

Anomaly attribution

Use the governed mean-deviation score, then attribute the score to ancestor mechanisms with exact Shapley values or deterministic permutation sampling. Score-only mode avoids the hybrid-world cost.

Mechanism change

Compare compatible reference and target SCMs with common random numbers. Signed contributions add to the reported target-mean shift up to the explicit residual.

Package / module

darkstar

Rust

The example continues from compatible portable functional SCMs plus governed reference and anomalous exogenous rows. Residual evaluation, mean-deviation scoring, Shapley hybrid worlds, mechanism-change attribution, limits, and diagnostics all execute in the native C++ engine through the C ABI.

Causal estimation diagnostics

Inspect cross-fitting, IV, and sensitivity contracts.

Discover deterministic cross-fitting, one-instrument PLIV, binary-instrument IIVM LATE, and linear partial-R² sensitivity support before fitting or diagnosing an effect.

Assumptions

Capability documents state supported shapes, nuisance evidence, estimands, and refusal conditions.

Diagnostics

Use fitted-session provenance, uncertainty, refuters, and sensitivity results as evidence, not proof.

Package / module

darkstar crate

Rust

Capability documents make cross-fitting, PLIV, IIVM, and linear partial-R² sensitivity assumptions and limits explicit before estimation.

Counterfactual policy evaluation

Preflight candidate policies before estimating value.

Use typed logged episodes for off-policy value estimation, or explicit finite-discrete temporal bindings for structural replay. Both routes keep identification evidence and native provenance visible.

Logged data

An episode with T actions has T + 1 observations. Candidate probabilities follow flattened logged steps.

Refusals

Preserve status-17 nonidentification evidence, including unresolved hidden confounding.

Package / module

darkstar crate

Rust

An episode with T actions has T + 1 observations. Preflight first, expect native_cpp provenance, and preserve unresolved_hidden_confounding refusals.

Stage 6

Scale, diagnose, and deliver deliberately.

Select approximate methods explicitly, reuse compiled work, inspect diagnostics, and verify packages.

Loopy belief propagation

Run bounded LBP and inspect fixed-point convergence.

Select LBP explicitly for a large discrete marginal when exact factor growth is too expensive, then make convergence, resource use, and the no-fallback contract part of your application logic.

Inputs

Pass query nodes, evidence, method=lbp, an iteration budget, fixed-point tolerance, maximum working values, and a relative deadline. LBP is deterministic; a seed and sampling budget are not its quality controls.

Outputs

Read the selected method, convergenceStatus, iterations, residual, peakWorkingValues, warmStartUsed, and fallbackPolicy. LBP reports fixed-point residual rather than sampling ESS or an evidence-probability estimate.

Choose deliberately

Use explicit LBP when the method is part of your contract. Use auto only when deterministic native planning across the governed portfolio is acceptable. Neither route silently changes method after planning.

Package / module

darkstar

Rust

Explicit LBP stays on the native LBP route with fallbackPolicy none. An exact request never silently downgrades to approximation. Treat selectionReason, convergenceStatus, iterations, fixed-point residual, and peakWorkingValues as part of the result contract; effective sample size and evidence-probability estimates do not apply to LBP. Use method auto only when deterministic native planning across LBP, Gibbs, AIS-BN, EPIS, likelihood weighting, and explicitly permitted exact inference is acceptable.

High-throughput approximate inference

Reuse one compiled model for ordered approximate queries.

Submit related auto-planned and explicit-LBP requests as one native batch instead of rebuilding or reloading the model for every marginal.

Inputs

Pass up to 1,024 ordered query objects. Each entry keeps its own evidence, method, convergence, memory, and deadline controls.

Outputs

Results preserve request order and retain complete per-query planner and convergence diagnostics. The batch fails without publishing a partial result.

Reuse safely

The native engine reuses the compiled model and compatible warm state. An auto request may choose from the governed portfolio; an explicit LBP request remains LBP with fallbackPolicy none.

Package / module

darkstar

Rust

One batch accepts at most 1,024 ordered requests, reuses the compiled native model and compatible warm state, and publishes no partial result on failure. Auto planning is deterministic for the normalized request and reports selectionReason; an exact request never silently downgrades to approximation. The explicit LBP entry remains LBP with fallbackPolicy none. All 12 non-C++ SDK calls cross the governed C ABI into the same C++ engine.

Analysis patterns

Run one-call sensitivity and expected value of perfect information.

Two first-class operations replace the manual baseline, CPT-copy, and observation-state loops: one-way sensitivity sweeps named CPT values without mutating the model, and EVPI evaluates perfect information before the first decision.

One-way sensitivity

Call one_way_probability_sensitivity with a target node/state and a parameters list. Each parameter names one CPT row with node, parentStates, state, and explicit values to sweep; hard evidence is optional.

Expected value of perfect information

Call expected_value_of_perfect_information with chance-node candidates that can be observed before the first decision, plus optional context evidence. It is cost-free perfect information, not noisy-test EVSI.

Read the result

Sensitivity returns an immutable baseline, resolved CPT rows, deltas, and a ranked parameter list. EVPI returns the base MEU, per-state conditional MEUs, completeness diagnostics, and ranked candidates.

Package / module

darkstar

Rust

Sensitivity is an immutable finite sweep with proportional covariation; EVPI is perfect, cost-free information before the first decision, not noisy-test EVSI. Substitute valid model and influence-diagram JSON, then inspect the baseline and ranked audit fields before acting.

Native SDK projections

Use projected diagnostics, intervention, learning, and provenance operations.

The C++ engine owns exact pquery planning, evidence information, point sensitivity derivatives, soft and policy interventions, provenance, multi-world counterfactuals, EM parameter learning, and continuous numerical diagnostics. Each wrapper delegates its projection through the governed C ABI.

Discrete diagnostics

Use exact_pquery_plan_diagnostics, evidence_information_diagnostics, and probability_sensitivity_derivative when you need explainable exact-query routing, evidence entropy/conflict summaries, or a single proportional-covariation derivative.

Causal model variants

Use intervene_soft and intervene_policy to create replacement-model handles, iquery_with_provenance to keep causal-effect metadata with the answer, and cpquery_worlds to evaluate named structural counterfactual worlds in one call.

Learning and continuous checks

Use learn_parameters_em for incomplete discrete rows and numerical_diagnostics on continuous SCMs to report backend and covariance-stability diagnostics.

Wrapper availability

Engine availability does not create a host-language method by itself. Use the selected SDK snippet and capability metadata to confirm the projected operations.

Package / module

darkstar

Rust

C++ calls the engine directly; all 12 non-C++ SDKs delegate production reasoning to that same engine through the governed C ABI. Wrappers provide idiomatic types and lifecycle handling, not alternate algorithms.

Download manifest

Review the exact SDK package contents before you install.

Every SDK archive includes a manifest at the zip root, and the account page provides the same manifest as a separate download for that archive.

Inputs

Choose a language, platform, and SDK version from your account page, then download the archive and its matching manifest.

Outputs

The manifest identifies the release, platform, package descriptor snapshots, included docs, native runtime files, and per-file SHA-256 hashes.

Package / module

Rust download manifest

Rust

The account page also provides the same manifest as a separate download so you can review file names, sizes, and hashes before installing the archive.