Subsections of API Reference
PanelMMM
PanelMMM is the single retained public MMM model API in Abacus.
Import it from:
from abacus.mmm.panel import PanelMMM
For conceptual guidance, see
Model Overview . For data contracts,
see Data Preparation .
Constructor
PanelMMM(...) is keyword-only.
The main constructor arguments are:
Argument
Meaning
date_column
Name of the date column in X
channel_columns
Required media columns
target_column
Semantic target column name
target_type
"revenue" or "conversion"
adstock
An AdstockTransformation instance
saturation
A SaturationTransformation instance
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 Mundlak / correlated random effects terms
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.
Post-fit model methods
PanelMMM also exposes model-specific post-fit methods:
Method
Purpose
add_original_scale_contribution_variable(var=[...])
Add original-scale deterministics before fitting
sample_saturation_curve(...)
Sample posterior saturation curves
sample_adstock_curve(...)
Sample posterior adstock curves
sample_channel_contribution_forward_pass(...)
Sample channel contributions in scaled target space
channel_contribution_forward_pass(...)
Evaluate channel contributions in original target units
get_channel_contribution_forward_pass_grid(...)
Build a contribution grid over shared spend multipliers
new_spend_contributions(...)
Simulate forward contribution paths for a spend scenario
add_lift_test_measurements(...)
Add lift-test calibration measurements
add_cost_per_target_calibration(...)
Add cost-per-target calibration penalties
add_events(df_events, prefix, effect)
Add dated event effects before build
Bound properties
Once the model exists, these bound properties expose the retained post-fit
surface:
Property
Returns
plot
MMMPlotSuite
data
MMMIDataWrapper
summary
MMMSummaryFactory
diagnostics
MMMDiagnosticsFactory
efficiency_metric
Default efficiency metric key for target_type
efficiency_metric_label
Display label such as ROAS or CPA
See Post-Fit Facades .
Other useful attributes
Common model attributes include:
Attribute
Meaning
idata
The fitted arviz.InferenceData
output_var
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
Minimal example
from abacus.mmm import GeometricAdstock , LogisticSaturation
from abacus.mmm.panel import PanelMMM
mmm = PanelMMM (
date_column = "date" ,
target_column = "revenue" ,
channel_columns = [ "tv" , "search" , "social" ],
dims = ( "geo" ,),
adstock = GeometricAdstock ( l_max = 8 ),
saturation = LogisticSaturation (),
)
mmm . fit ( X , y , draws = 500 , tune = 500 , chains = 2 , progressbar = False )
mmm . sample_posterior_predictive ( X = X , progressbar = False )
Abacus keeps most reusable modelling primitives under abacus.mmm.
This page lists the main import groups for transformations, seasonality and
trend components, HSGP helpers, and scaling types.
Top-level abacus.mmm re-exports
Import these directly from abacus.mmm:
from abacus.mmm import GeometricAdstock , LogisticSaturation , YearlyFourier
Top-level import path:
from abacus.mmm import (
AdstockTransformation ,
BinomialAdstock ,
DelayedAdstock ,
GeometricAdstock ,
NoAdstock ,
WeibullCDFAdstock ,
WeibullPDFAdstock ,
adstock_from_dict ,
)
Main public types:
Type
Purpose
AdstockTransformation
Base adstock interface
NoAdstock
No carryover
GeometricAdstock
Geometric decay
DelayedAdstock
Delayed peak with decay
BinomialAdstock
Binomial-style lag weights
WeibullCDFAdstock
Weibull CDF carryover
WeibullPDFAdstock
Weibull PDF carryover
adstock_from_dict(...)
Rebuild an adstock from serialised config
Top-level import path:
from abacus.mmm import (
HillSaturation ,
HillSaturationSigmoid ,
InverseScaledLogisticSaturation ,
LogisticSaturation ,
MichaelisMentenSaturation ,
NoSaturation ,
RootSaturation ,
SaturationTransformation ,
TanhSaturation ,
TanhSaturationBaselined ,
saturation_from_dict ,
)
Main public types:
Type
Purpose
SaturationTransformation
Base saturation interface
NoSaturation
No diminishing returns
LogisticSaturation
Logistic response curve
InverseScaledLogisticSaturation
Inverse-scaled logistic curve
HillSaturation
Hill response curve
HillSaturationSigmoid
Hill-style sigmoid curve
MichaelisMentenSaturation
Michaelis-Menten curve
RootSaturation
Root response curve
TanhSaturation
Hyperbolic tangent curve
TanhSaturationBaselined
Tanh curve with baseline handling
saturation_from_dict(...)
Rebuild a saturation from serialised config
Fourier and trend components
Top-level import path:
from abacus.mmm import MonthlyFourier , WeeklyFourier , YearlyFourier , LinearTrend
These classes are building blocks for built-in or custom additive effects.
Type
Purpose
YearlyFourier
Yearly Fourier basis
MonthlyFourier
Monthly Fourier basis
WeeklyFourier
Weekly Fourier basis
LinearTrend
Piecewise linear trend component
HSGP and time-varying parameter helpers
Top-level import path:
from abacus.mmm import (
HSGP ,
CovFunc ,
HSGPPeriodic ,
PeriodicCovFunc ,
SoftPlusHSGP ,
approx_hsgp_hyperparams ,
create_complexity_penalizing_prior ,
create_constrained_inverse_gamma_prior ,
create_eta_prior ,
create_m_and_L_recommendations ,
)
Main public types and helpers:
Name
Purpose
HSGP
General HSGP configuration
SoftPlusHSGP
HSGP variant used by time-varying parameter surfaces
HSGPPeriodic
Periodic HSGP configuration
CovFunc
Covariance-function enum for HSGP
PeriodicCovFunc
Periodic covariance-function enum
approx_hsgp_hyperparams(...)
Approximate HSGP hyperparameter helper
create_eta_prior(...)
Eta prior helper
create_m_and_L_recommendations(...)
Basis-size and domain recommendations
create_complexity_penalizing_prior(...)
Complexity-penalising prior helper
create_constrained_inverse_gamma_prior(...)
Inverse-gamma prior helper
Scaling types
Scaling is not re-exported from abacus.mmm. Import it from
abacus.mmm.scaling:
from abacus.mmm.scaling import Scaling , VariableScaling
The scaling types are:
Type
Purpose
VariableScaling
Method and non-date dims for one variable group
Scaling
Combined target and channel scaling configuration
Supported VariableScaling.method values are:
VariableScaling.dims must not include date, because Abacus already assumes
the date dimension for scaling.
Notes on import paths
PanelMMM is not re-exported from abacus.mmm. Import it from
abacus.mmm.panel.
Scaling is not re-exported from abacus.mmm. Import it from
abacus.mmm.scaling.
Post-Fit Facades
After fitting, PanelMMM exposes most read and reporting operations through
bound properties:
mmm.data
mmm.summary
mmm.diagnostics
mmm.plot
These are the preferred entry points when you already have a fitted model.
mmm.data
mmm.data returns MMMIDataWrapper.
Direct import path:
from abacus.data.idata import MMMIDataWrapper
You can also create it explicitly with:
wrapper = MMMIDataWrapper . from_mmm ( mmm )
Main methods:
Method
Purpose
get_target(original_scale=True)
Return observed target data
get_channel_spend()
Return observed channel spend
get_posterior_predictive(original_scale=True)
Return posterior predictive samples
get_errors(original_scale=True)
Return residual samples
get_channel_contributions(original_scale=True)
Return media contribution samples
get_contributions(...)
Return channels, baseline, controls, seasonality, and events
get_elementwise_roas(original_scale=True)
Contribution-over-spend ratios
get_elementwise_cost_per_target(original_scale=True)
Spend-over-contribution ratios
get_channel_scale()
Return stored channel scaling factors
get_target_scale()
Return stored target scaling factors
to_original_scale(...)
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:
from abacus.mmm.summary import MMMSummaryFactory
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
MMMSummaryFactory also exposes:
hdi_probs
output_format
efficiency_metric
efficiency_metric_label
mmm.diagnostics
mmm.diagnostics returns MMMDiagnosticsFactory.
Direct import path:
from abacus.mmm.diagnostics.factory import MMMDiagnosticsFactory
Main methods:
Method
Purpose
design_summary(X, ...)
Per-variable design checks
design_report(X, ...)
Machine-readable design report
mcmc_summary(...)
Parameter-level MCMC diagnostics
mcmc_report(...)
Machine-readable MCMC report
predictive_summary(...)
Aggregate predictive metrics
predictive_report(...)
Machine-readable predictive report
The report methods return typed dataclass objects with to_dict().
mmm.plot
mmm.plot returns MMMPlotSuite.
Direct import path:
from abacus.mmm.plot import MMMPlotSuite
PanelMMM binds this automatically to the model’s idata, but the class also
supports compatible custom InferenceData objects.
Main methods:
Method
Purpose
posterior_predictive(...)
Plot fitted or sampled predictive series
prior_predictive(...)
Plot prior predictive series
residuals_over_time(...)
Plot residual trajectories
residuals_posterior_distribution(...)
Plot residual posterior distributions
contributions_over_time(...)
Plot time-series contributions
posterior_distribution(...)
Plot posterior violin distributions
channel_parameter(...)
Plot channel-level parameter posteriors
prior_vs_posterior(...)
Compare prior and posterior distributions
saturation_scatterplot(...)
Plot spend-versus-contribution scatter views
saturation_curves(...)
Plot sampled saturation curves
waterfall_components_decomposition(...)
Plot waterfall decompositions
media_contribution_over_time(...)
Plot stacked media contributions
channel_contribution_share_hdi(...)
Plot contribution share intervals
budget_allocation(...)
Plot optimisation allocation outputs
allocated_contribution_by_channel_over_time(...)
Plot simulated allocation contributions
Direct idata utilities
The abacus.data.idata package also exports schema and utility helpers:
Import
Purpose
MMMIdataSchema
Expected structure for retained MMM InferenceData
VariableSchema
Variable-level schema helper
InferenceDataGroupSchema
Group-level schema helper
filter_idata_by_dates(...)
Filter idata on a date window
filter_idata_by_dims(...)
Filter idata on non-date dimensions
aggregate_idata_time(...)
Aggregate idata over time
aggregate_idata_dims(...)
Aggregate idata over non-time dims
subsample_draws(...)
Subsample posterior draws
Optimisation API
Abacus exposes the retained optimisation surface through
abacus.mmm.optimization.
For workflow guidance and interpretation, see
Optimisation .
Primary wrapper
Recommended import path:
from abacus.mmm.optimization import PanelBudgetOptimizerWrapper
PanelBudgetOptimizerWrapper adapts a fitted PanelMMM to the generic budget
optimiser.
Constructor:
wrapper = PanelBudgetOptimizerWrapper (
model = mmm ,
start_date = "2025-03-03" ,
end_date = "2025-03-31" ,
)
Main constructor arguments:
Argument
Meaning
model
Fitted PanelMMM
start_date
Optimisation window start date
end_date
Optimisation window end date
compile_kwargs
Optional compilation settings
Useful attributes:
Attribute
Meaning
start_date
Requested window start
end_date
Requested window end
num_periods
Number of periods in the optimisation window
zero_data
Synthetic zero-spend future dataset
channel_columns
Modelled channels
dims
Budget dims beyond date
Main methods
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.
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
include_carryover
Extend and zero the tail to capture carryover
budget_distribution_over_period
Optional date flighting weights
It returns an xarray.Dataset containing:
allocation
one variable per channel for realised spend
the model output variable
channel_contribution
total_media_contribution_original_scale
any extra requested variables
Advanced exported helpers
The same module also exports:
from abacus.mmm.optimization import (
CustomModelWrapper ,
MinimizeException ,
OptimizerCompatibleModelWrapper ,
optimizer_xarray_builder ,
)
These are advanced surfaces for custom optimiser integrations.
Name
Purpose
CustomModelWrapper
Wrap a custom PyMC model for optimisation
OptimizerCompatibleModelWrapper
Protocol for compatible wrappers
optimizer_xarray_builder(...)
Build shaped xarray inputs for optimisation
MinimizeException
Exception raised when optimisation fails
Import-path note
abacus.mmm.panel also re-exports PanelBudgetOptimizerWrapper, but the
recommended reference import path is abacus.mmm.optimization.
Scenario Planner API
The scenario planner API lives under abacus.scenario_planner.
Use it when you want to compare current, manual, and fixed-budget optimised
plans in total horizon spend units.
For workflow guidance, see Scenario Planning .
Main import path
from abacus.scenario_planner import (
CurrentScenarioSpec ,
DataArraySpec ,
FixedBudgetOptimizedScenarioSpec ,
ManualAllocationScenarioSpec ,
ScenarioComparison ,
ScenarioPlanner ,
ScenarioResult ,
)
The package also exports shared base types:
BaseScenarioSpec
HistoricalReferenceScenarioSpec
SimulatedScenarioSpec
ScenarioSpec
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(...)
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.
Dash app entry point
The optional UI lives in a separate module:
from abacus.scenario_planner.dash_app import create_scenario_planner_dash_app
Use it like this:
app = create_scenario_planner_dash_app ( comparison )
app . run ( debug = True )
The Dash app visualises a precomputed ScenarioComparison. It does not run
the planner itself.
Builders and Pipeline
Abacus exposes one public YAML builder and one structured pipeline runner.
Use these surfaces when you want configuration-driven model construction or a
staged run directory with machine-readable artefacts.
YAML builder
Import path:
from abacus.mmm.builders.yaml import build_mmm_from_yaml
Signature:
model = build_mmm_from_yaml (
config_path ,
X = X ,
y = y ,
model_kwargs = None ,
holidays_path = None ,
)
Main inputs:
Argument
Meaning
config_path
YAML file path
X
Optional pre-loaded feature data
y
Optional pre-loaded target data
model_kwargs
Model init overrides
holidays_path
Optional holiday CSV override
It returns a built PanelMMM.
The builder orchestrates:
model construction
optional additive effects
holiday augmentation
build_model(X, y)
optional original_scale_vars
optional calibration steps
optional inference-data attachment
Structured pipeline runner
Top-level import path:
from abacus.pipeline import PipelineRunConfig , PipelineRunResult , run_pipeline
PipelineRunConfig
PipelineRunConfig is the user-facing run configuration dataclass.
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:
run_pipeline(...)
Use run_pipeline(...) to execute the structured runner:
from abacus.pipeline import PipelineRunConfig , run_pipeline
result = run_pipeline (
PipelineRunConfig (
config_path = "config.yml" ,
dataset_path = "data.csv" ,
)
)
run_pipeline(...):
loads the YAML config
loads data from the configured or overridden paths
resolves sampler overrides
creates the run directory and manifest
runs the retained stage sequence
The stage sequence is:
metadata
preflight
fit
assessment
decomposition
diagnostics
curves
optimisation
PipelineRunResult
PipelineRunResult is a small dataclass with:
Field
Meaning
run_dir
Concrete run directory path
manifest_path
Manifest JSON path
CLI entry point
The CLI entry point lives in abacus.pipeline.runner:
python -m abacus.pipeline.runner --config config.yml --dataset-path data.csv
For full CLI usage, see CLI Reference .
Additive Effects and Events
Abacus supports advanced additive components through mu_effects and dated
event surfaces.
These are extension points rather than the default modelling path, but they are
part of the retained public API.
MuEffect protocol surface
Import path:
from abacus.mmm.additive_effect import MuEffect
MuEffect is the abstract base class for additive components appended to
mmm.mu_effects.
Required methods:
Method
Purpose
create_data(mmm)
Register any required pm.Data inputs
create_effect(mmm)
Return the additive contribution tensor
set_data(mmm, model, X)
Update the effect for new prediction data
Custom effects should inherit from MuEffect so they can participate in model
serialization logic.
Built-in additive effect classes
Import path:
from abacus.mmm.additive_effect import (
EventAdditiveEffect ,
FourierEffect ,
LinearTrendEffect ,
)
Built-in types:
Type
Purpose
FourierEffect
Wrap a FourierBase component as a MuEffect
LinearTrendEffect
Wrap a LinearTrend component as a MuEffect
EventAdditiveEffect
Turn dated events into additive model effects
Typical usage:
from abacus.mmm import WeeklyFourier
from abacus.mmm.additive_effect import FourierEffect
mmm . mu_effects . append (
FourierEffect ( fourier = WeeklyFourier ( n_order = 2 , prefix = "weekly" ))
)
Event surfaces
Import path:
from abacus.mmm.events import (
AsymmetricGaussianBasis ,
EventEffect ,
GaussianBasis ,
HalfGaussianBasis ,
)
Main public event types:
Type
Purpose
EventEffect
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
from pymc_extras.prior import Prior
from abacus.mmm.events import EventEffect , GaussianBasis
effect = EventEffect (
basis = GaussianBasis (),
effect_size = Prior ( "Normal" , mu = 0 , sigma = 1 , dims = "promo" ),
dims = ( "promo" ,),
)
mmm . add_events ( df_events = df_events , prefix = "promo" , effect = effect )
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.