This section is a hand-curated reference for the retained public Abacus API.
It focuses on stable entry points that users are expected to import directly.
It does not try to document every internal module under abacus.mmm.models,
abacus.mmm.summarization, or abacus.pipeline.stages.
For task-oriented workflows, use the main documentation sections first. Use
this reference when you need the exact import path, object name, or the scope
of a public surface.
Main module groups
Module
Primary public surface
abacus.mmm.panel
PanelMMM
abacus.mmm
Adstock, saturation, Fourier, HSGP, and trend classes
abacus.mmm.optimization
PanelBudgetOptimizerWrapper and advanced optimisation helpers
Optional named estimator declaration; time_series, fe, and cre are released
dims
Optional panel dimensions such as ("geo",)
control_columns
Optional non-media regressors
control_impacts
Optional directional expectations for controls
control_sign_policy
"soft" or "strict"
yearly_seasonality
Number of yearly Fourier modes
time_varying_intercept
bool or an HSGPBase instance
time_varying_media
bool or an HSGPBase instance
use_mundlak_cre
Add the legacy low-level Mundlak terms; this is not the named CRE preset
scaling
Scaling, a dict, or None
model_config
Prior and likelihood configuration
sampler_config
Default sampler settings
adstock_first
Whether adstock runs before saturation
Core lifecycle methods
The most commonly used methods are:
Method
Purpose
build_model(X, y)
Build the PyMC graph for the current configuration
fit(X, y, **kwargs)
Sample the posterior and store idata
approximate_fit(X, y, ...)
Fit with variational inference instead of NUTS
sample_prior_predictive(X, y, ...)
Sample prior and prior predictive draws
sample_posterior_predictive(X, ...)
Sample posterior predictive draws
predict(X, ...)
Return posterior mean predictions
predict_posterior(X, ...)
Return posterior predictive samples for output_var
save(path, **kwargs)
Save idata to NetCDF
load(path, check=True)
Load a saved model from NetCDF
load_from_idata(idata, check=True)
Rebuild from an in-memory InferenceData
fit(...), sample_prior_predictive(...), predict(...), save(...), and
the load helpers come from the shared model-builder base classes but are part
of the user-facing PanelMMM surface.
Named estimator release gates apply to this public surface. Internal graph
helpers are reserved for maintainer tests and statistical implementation
evidence; they require an explicit internal override for a gated preset and
are not a supported fitting interface.
Post-fit model methods
PanelMMM also exposes model-specific post-fit methods:
Output variable name used in predictive sampling ("y")
channel_columns
Configured channel names
control_columns
Configured control names
dims
Configured panel dimensions
mu_effects
Additive effects attached before build
Named estimator presets
Use estimator={"type": "time_series"} for one aggregate time series. This
named preset builds the same single-series graph as the established
no-dimension PanelMMM path for the same constructor arguments. Under the
default constructor settings, that graph has one global intercept, shared media
and control parameters, shared adstock and saturation parameters, and the
existing Gaussian levels likelihood. Its information comes from temporal
variation in the aggregate series, combined with the declared priors.
The preset does not override orthogonal PanelMMM options. For example,
explicit time-varying intercept, time-varying media, or likelihood settings
retain the same behaviour as the equivalent unlabelled single-series model.
Those options are not estimator-level categorical time effects.
The named time_series, fe, and cre presets are released. The named re
preset remains unavailable until its separate statistical implementation and
verification checkpoint passes. It raises EstimatorReleaseGateError before
graph construction; Abacus does not substitute the low-level dims surface.
The released CRE implementation uses an exact marginal Gaussian random-intercept
likelihood and a separate correlated-effects adjustment. Its media summaries
are derived from the declared transformed exposure basis, rather than raw spend
means. Eligible time-varying controls use centred unit means. Pipeline evidence
keeps that adjustment on the baseline/non-incremental side of decomposition and
records pre-fit and post-fit estimability diagnostics.
This adjustment is not a general remedy for confounding. It does not establish
causal identification, prove that the random-effects assumptions are adequate,
or address omitted time-varying confounding, measurement error, or
response-function misspecification. The released preset also rejects unseen units,
fitted-unit subsets, budget optimisation, and calibration. Historical and manual
scenarios are supported for the complete fitted-unit panel. They retain the fitted
training-period CRE summaries instead of recomputing them from planned spend.
The CRE release verifies the declared graph, configuration boundary,
estimability evidence, fitted-unit prediction contract and persistence path. It
does not promise 15% point-estimate accuracy, causal validity, or general
robustness across arbitrary panel designs. Analysts must inspect posterior
diagnostics, prior sensitivity, and the within- and between-unit design evidence
for each fitted model.
estimator and dims are mutually exclusive. Existing models that omit
estimator keep their current behaviour and identity.
Convert a posterior variable or array to original scale
to_scaled(...)
Convert an original-scale array back to model scale
mmm.summary
mmm.summary returns MMMSummaryFactory.
Direct import path:
fromabacus.mmm.summaryimportMMMSummaryFactory
If you instantiate it manually, pass model=mmm when you need transform-backed
curve summaries:
summary=MMMSummaryFactory(mmm.data,model=mmm)
Main methods:
Method
Purpose
posterior_predictive(...)
Predictive summary table with observed target
contributions(...)
Tidy contribution summaries
mean_contributions_over_time(...)
Wide decomposition table
roas(...)
ROAS summary
cost_per_target(...)
Cost-per-target summary
efficiency(...)
Target-type-aware efficiency summary
channel_spend(...)
Raw spend table
saturation_curves(...)
Saturation curve summary table
adstock_curves(...)
Adstock curve summary table
total_contribution(...)
Totals by component type
change_over_time(...)
Percentage change in channel contributions
Methods accepting hdi_probs return single-interval empirical HDIs with the
same calculation for chain/draw and sample layouts. The abs_error_*
columns are interval endpoints. See
Summary interval semantics
for pointwise interpretation and the correction to earlier sample-axis bounds.
PanelBudgetOptimizerWrapper adapts a fitted PanelMMM to the generic budget
optimiser. It rejects the named FE, CRE and release-gated RE presets with
EstimatorOperationError; a fitted posterior alone is insufficient. See the
estimator support matrix.
PanelBudgetOptimizerWrapper exposes two user-facing methods:
Method
Purpose
optimize_budget(...)
Optimise allocation over the future window
sample_response_distribution(...)
Simulate spend and contribution outcomes for an allocation
optimize_budget(...)
Key arguments:
Argument
Meaning
budget
Total spend across all optimised cells for one model period
budget_bounds
Optional per-cell lower and upper bounds
response_variable
Objective variable to optimise
utility_function
Utility function applied to the response distribution
constraints
Extra custom constraints
default_constraints
Whether to add the default sum constraint
budgets_to_optimize
Optional boolean mask over budget cells
budget_distribution_over_period
Optional date flighting weights
callback
Whether to return iteration diagnostics
Return values:
allocation, result
allocation, result, callback_info when callback=True
allocation is an xarray.DataArray over the non-date budget dimensions.
result is SciPy OptimizeResult.
Masks require boolean dtype. Masks and time profiles require unique, explicit
budget-coordinate labels with exactly the model’s membership; Abacus aligns
label and dimension order. Profile fractions must be finite and non-negative,
and sum to one along date for every budget cell, including disabled cells.
See Time distribution
for the date-order contract and sum tolerance.
sample_response_distribution(...)
Key arguments:
Argument
Meaning
allocation_strategy
Optimised or manually supplied allocation
noise_level
Relative noise added to the synthetic future spend
additional_var_names
Extra posterior predictive variables to include
include_last_observations
Pass lag context into posterior predictive sampling
The preferred statistical scenario API lives under abacus.scenarios.
Use it when you want to compare current, manual, and fixed-budget optimised
plans in total horizon spend units. FE and CRE support current and manual
plans only; their fixed-budget optimisation path remains blocked.
abacus.scenario_planner remains available as a compatibility namespace for
existing statistical imports. New statistical scenario code should import from
abacus.scenarios.
The experimental abacus-dashboard application is deprecated. Legacy
dashboard imports under abacus.scenario_planner remain as advisory
compatibility facades; their warnings refer to that deprecated package.
Scenario spec classes
Main concrete spec types:
Type
Purpose
CurrentScenarioSpec
Historical reference scenario
ManualAllocationScenarioSpec
User-defined future allocation
FixedBudgetOptimizedScenarioSpec
Fixed-budget optimised future allocation
DataArraySpec
JSON-friendly or YAML-friendly xarray representation
Shared fields across the concrete specs include:
name
start_date
end_date
scenario_id
Planner service objects
Main service types:
Type
Purpose
ScenarioPlanner
Evaluate and compare scenarios for a fitted PanelMMM
ScenarioResult
Output object from evaluate(...)
ScenarioComparison
Combined output object from compare(...)
ScenarioRecipe
Versioned collection of historical and manual specifications
ScenarioArtifactBundle
Retained recipe output paths plus the in-memory comparison
ScenarioPlanner
planner=ScenarioPlanner(mmm)
Main methods:
Method
Purpose
evaluate(spec)
Evaluate one scenario and return ScenarioResult
compare(specs)
Evaluate several scenarios and return ScenarioComparison
Useful property:
Property
Meaning
channels
Modelled channel names
ScenarioResult
ScenarioResult exposes:
spec
totals
channels
contributions_over_time
allocation
metadata
ScenarioComparison
ScenarioComparison exposes:
totals
channels
contributions_over_time
allocations
metadata
It also provides:
payload=comparison.to_store_payload()
to_store_payload() returns a JSON-friendly payload for client-side UIs. The
payload contains a scalar contract_version plus record lists for the
comparison tables. The current contract value is exported as
SCENARIO_CONTRACT_VERSION from abacus.scenarios.
Recipe functions
Function
Purpose
load_scenario_recipe(path)
Parse and validate a versioned YAML recipe
evaluate_scenario_recipe(...)
Evaluate an in-memory recipe against a fitted model and retain its evidence
run_scenario_recipe(...)
Load a fitted pipeline run, evaluate a YAML recipe, and retain its evidence
write_scenario_artifacts(...)
Persist an evaluated comparison as an immutable, checksummed bundle
The command-line equivalent of run_scenario_recipe(...) is:
Historical reference only: the experimental abacus-dashboard application is
deprecated. The entry points and former removal criteria below record its
prototype interface, not a current recommendation or release commitment.
The Dash app visualises a precomputed ScenarioComparison. It does not fit
models.
Legacy app-layer imports such as
abacus.scenario_planner.dash_app.create_scenario_planner_dash_app still work
as compatibility facades, but they are advisory only. No removal will happen
before Abacus 4.0, and removal requires all of the following:
a documented abacus-dashboard release and install path
passing dashboard smoke checks against the supported Abacus scenario contract
zero known internal imports using legacy dashboard paths under
abacus.scenario_planner
PipelineRunConfig is the user-facing run configuration dataclass. Supply
pathlib.Path objects for path fields; this dataclass does not convert strings
to paths.
Key fields:
Field
Meaning
config_path
YAML config file
output_dir
Output root for run directories
run_name
Optional logical run name
dataset_path
Optional combined dataset CSV
x_path / y_path
Optional separate feature and target CSVs
holidays_path
Optional holiday CSV override
target_column
Optional target-column override
prior_samples
Prior predictive sample count
draws, tune, chains, cores
Sampler overrides
random_seed
Global random seed override
curve_samples
Curve summary sample count
curve_points
Curve summary x-axis resolution
It also exposes:
effective_run_name()
run_pipeline(...)
Use run_pipeline(...) to execute the structured runner. This fragment assumes
an existing runner config at config.yml and a matching dataset at data.csv;
it writes a new run under results/. For a complete setup, see
Quickstart: Pipeline Runner.
The current assessment and curve stages require original-scale outcome and
media-contribution variables. Include this block in the runner configuration,
as the bundled demos do:
original_scale_vars:[y,channel_contribution]
Here y is the model’s internal output variable, not the CSV target-column
name. A minimal builder-only configuration without these variables can build
and fit but fails when these runner stages need them.
Event effect specification combining a basis and effect size prior
GaussianBasis
Symmetric Gaussian event basis
HalfGaussianBasis
One-sided Gaussian event basis
AsymmetricGaussianBasis
Gaussian basis with different pre and post widths
You can use EventEffect either:
directly with PanelMMM.add_events(...), or
indirectly through EventAdditiveEffect
Example: direct event attachment
This fragment assumes an unbuiltPanelMMM named mmm, configured for a
single time series with its required adstock and saturation objects, and valid
training data X and y. See Quickstart: Python API
for model and data setup. Attach the event before any call that builds the graph.
The event table needs name, start_date and end_date columns.
Fit with mmm.fit(X, y) using the same training data and your configured
sampler settings. For panel models, the event effect dimensions must also
include the model’s panel dimensions. Event components do not constitute
experimental calibration; use Calibration
for that separate task.
Serialisation note
FourierEffect and LinearTrendEffect participate in the PanelMMM
round-trip path.
EventAdditiveEffect does not currently round-trip through
PanelMMM.load(...), because the original event DataFrame is not serialised.