Macro
Welcome to the Macro documentation!
This documentation is a work-in-progress, so please forgive our appearance as we add material.
All feedback is welcome and please report and errors or omissions through the MacroEnergy.jl issues page.
What is Macro?
Macro is a bottom-up, multi-sectoral infrastructure optimization model for macro-energy systems. It co-optimizes the design and operation of user-defined models of multi-sector energy systems and networks. Macro allows users to explore the impact of energy policies, technology costs and performance, demand patterns, and other factors on an energy system as a whole and as separate sectors.
The main features of Macro include:
- Graph-based representation of the energy system, facilitating clear representation and analysis of energy and mass flows between sectors.
- "Plug and play" flexibility for integrating new technologies and sectors, including electricity, hydrogen, heat, and transport.
- High spatial and temporal resolution to accurately capture sector dynamics.
- Designed for distributed computing to enable large-scale optimizations.
- Tailored Benders decomposition framework for optimization.
- Open-source built using Julia and JuMP.
Structure of the documentation
The documentation contains five main sections:
Getting Started: How to install Macro and run your first cases
Tutorials: Long-form guides with worked examples, intended to help you learn how to use Macro
Guides: Short guides which walk you through how to achieve specific tasks, intended to be a day-to-day reference when working with Macro
Manual: A detailed description of Macro's components and features
Reference: A function reference for Macro's API
Recent changes
<!– BEGIN GENERATED RECENT CHANGES –>
0.3.0 - 2026-11-10
Added
- Added
@add_to_balancefor appending raw terms to an existing named balance. - Added
@add_to_storage_balanceas the preferred helper for extending storage law-of-motion balances. - Added
@inspect_stoichiometric_balanceto inspect the pairwise equations generated by@add_stoichiometric_balance. - Added focused single-asset solve tests under
test/asset_teststo validate migrated asset balances against manual algebraic rewrites where appropriate. - Added scaling functionality for input data. New
ParameterScaling(defaultfalse) andParameterScalingFactor(default1e3) parameters have been added to case settings. - Added capacity_summary.csv for multi-period cases, combining per-period capacity outputs into a single long- or wide-format file.
- Added optional StartYear input in case_settings.json to label periods by calendar year.
- Added
capex.csvoutput file to report per-component asset capital costs. - Added repository-local benchmarking tools to compare case loading, case generation, and model generation between
upstream/mainand the current worktree using reproducible example inputs. - Added system-wide and per-location capacity constraints for selected groups of assets:
MaxCapacityConstraintandMinCapacityConstraintbound total capacity, andMaxNewCapacityConstraintbounds newly built capacity. Limits are configured via aconstraintsblock insystem_data.json(whole system) or per location inlocations.json, using asset-type and tag selectors. The limit values are scaled withParameterScalinglike other capacity inputs. - For
VRE, the optionaltechnologyinput is normalized into an asset tag (for example,technology: "Solar"adds:solar) without changing the asset's Julia type. - Added
ConstrainedFossilLiquidFuels, a refinery asset with fixed jet-fuel and diesel output ratios and configurable fuel-specific emissions. - Added optional auxiliary-fuel inputs to
BECCSHydrogenand captured-CO₂ return flows toSyntheticLiquidFuels. - Added unit-commitment support for
Electrolyzerhydrogen output, including startup electricity consumption, minimum up/down times, and ramping limits. - Added time-domain reduction (TDR) to replace full input time series with weighted representative periods. The new
preprocess_inputsandtime_domain_reductionworkflows generate a separate reduced case that loads and runs through the ordinary MacroEnergy APIs. - Added JSON-configured TDR with independent per-System settings, k-means, k-medoids and autoencoder clustering, feature selection and weights, scaling, and forced extreme-period selection.
- Added TDR input discovery for JSON and model-input CSV references across arbitrary directories, including inline time-series vectors. Per-System copies retain only required files and time-series columns, preserve model-input CSV format, and consolidate identical shared inputs.
- Added optional model-output clustering features from isolated candidate-period solves, with distributed execution, selective policy-constraint exclusion, retained inputs/results, and fingerprint-validated feature caches under the source case’s
TDR/directory. - Added support for reclustering into shorter representative periods while preserving source-period boundaries and occurrence weights. TDR reports trimmed timesteps, rejects longer requested periods, updates time settings, and validates source/destination separation before overwriting.
- Added TDR period maps, provenance and feature-use logs, including records of inputs reduced without being used for clustering. Preprocessing logs are saved under
preprocessing_logs/in the reduced case. - Added
OutputFormatsetting inmacro_settings.jsonto write output tables as"csv"(default),"csv.gz"or"parquet", globally or per output (e.g.,{"Flow": "parquet"}). Compressed formats make results folders much smaller; on an 8-period test case, Parquet output was 26× smaller than CSV. - Added
WriteOutputssetting inmacro_settings.jsonto skip individual output files (e.g.,{"Curtailment": false, "Duals": false}). Outputs that are not listed are still written. - Added
OutputSignificantDigitssetting inmacro_settings.jsonto round time-series outputs (flows, storage levels, curtailment, non-served demand, balance duals) to a number of significant digits before writing. Capacity, cost and CAPEX outputs keep full precision. - Added a
commoditiesobject to location inputs for defining commodity nodes directly inlocations.json, including demand, supply segments, time series, and node constraints. Empty objects use existing node defaults and generate<location>_<commodity>node IDs; explicit IDs override the default. Existing location-name strings and independentnodes.jsondefinitions remain supported. - Added
write_json(io::IO, data::AbstractDict)for writing JSON to a caller-owned stream without closing it.
Changed
- Parquet outputs are now zstd-compressed (about 3× smaller than the previous snappy default), and Symbol columns with missing values are written correctly.
- Myopic restarts now read
capacity.csv,capacity.csv.gzorcapacity.parquetfrom the restart folder, whichever was written. If none exists, the error says which file is missing and suggests the likely cause (WriteOutputs.Capacity = false). If more than one exists (left over from an earlier run withOverwriteResults = true), the restart stops with an error instead of picking one. - A Myopic run that stops early (
StopAfterPeriod) now fails before the first solve ifWriteOutputs.Capacityisfalsefor any period it writes, since a later restart needs those files. A run to the last period only logs a warning. - Cached repeated reads of shared CSV inputs within each case or system load, avoiding repeated full-file parsing when assets select different columns from the same file.
@add_balanceis now the recommended API for ordinary algebraic balance equations and inequalities, and follows standard algebraic sign conventions forflow(...)terms.@add_balancenow validates balance expressions more strictly and rejects unsupported non-flow(...)variable terms.@add_stoichiometric_balancenow expands recipe-style balances using a consistent proportional rule around the selectedbase_term.- Asset balance definitions have been migrated away from legacy raw
balance_data = Dict(...)patterns toward@add_balance,@add_to_storage_balance, and@add_stoichiometric_balance. - Updated MacroEnergyScaling.jl compatibility to 0.4. Constraint scaling now updates constraints in place, so existing JuMP
ConstraintRefs remain valid instead of being invalidated by constraint replacement. This version also allows for objective scaling in the future. - Hoisted repeated time-data lookups during model construction and simplified ramping and minimum up/down-time constraints to avoid temporary expression and index containers.
- Weight policy slack to ensure CO2 slack penalty has economic interpretation.
- A constraint entry in a
constraintsblock may now be an inline configuration object (carrying its settings) instead of only the booleantrue/falsetoggle, enabling data-driven constraint parameterization. - Location entries in
locations.jsonmay now be objects carrying aconstraintsblock (bare id strings still work), allowing location-specific constraints to be loaded from input data. - Reduced model-generation allocations in edge balance updates by inserting flow variables directly into vertex balance expressions instead of constructing temporary effective-flow expressions.
run_casenow scopes logging to the run, restores the caller’s logger, and closes its own file log stream on success or failure.- Storage Charge/Discharge limit constraints now can be applied to
LongDurationStorage. - Variable O&M cost on a
BidirectionalEdgeis now charged on |flow| via itsflow_pos/flow_negpair, instead of on the net flow; theVariableOMcost outputs follow the same rule. - A negative
variable_om_coston a unidirectional edge (including edges with unit commitment) is now a credit per unit of flow in the objective and theVariableOMcost outputs, instead of being ignored. A negativevariable_om_coston aBidirectionalEdgeis an error, since it is charged on |flow|. - Extended DuckDB.jl compatibility to include 2.x (
DuckDB = "1, 2"). Environments that resolve DuckDB.jl 2.x read CSV inputs with the bundled DuckDB 2.0 engine. - Automatically created commodity nodes now use
<location>_<commodity>IDs instead of reusing the location ID. - Location entries are normalized into a validated
LocationInputwith a required nonempty string ID and optional constraint and commodity dictionaries. Programmatic location dictionaries must use symbol keys, matching parsed JSON inputs; location-name strings remain supported. - Location loading now creates each location and its declared nodes before loading independent nodes and assets. Node and location IDs share one namespace, with collisions rejected by both registration methods. Input validation also rejects duplicate commodity nodes within a location and conflicting location assignments as objects are loaded or registered.
- Multi-System TDR copies configured asset directories to
inputs/system_<n>/assets, avoiding repeated source directory names such asassets/assets_1when the destination is free of other dependencies.
Deprecated
DualExportsEnabledinmacro_settings.jsonis deprecated in favor ofWriteOutputs.Duals. It still works: it is translated toWriteOutputs.Dualswith a deprecation warning. Setting both to different values is an error. Code that readssystem.settings.DualExportsEnabledkeeps working: it is stilltrueorfalse, mirroringWriteOutputs.Duals.
Removed
- Removed
ReviseandTestfrom the package dependencies.MacroEnergy.jlno longer loadsReviseat package load time, so developers who relied on that must now load it themselves;Testremains available to the test suite through[extras]/[targets].
Fixed
- Myopic runs with
MyopicSettings.ReturnModels = falsenow actually free each period's model. Each period's references are now released once its results have been written, and the model is emptied. Results are unchanged; scalar capacities remain readable on the returnedCaseasFloat64. - Fixed asset component traversal and Benders planning updates for assets whose optional edges are absent.
StorageChargeLimitConstraintis now attached to aBattery's charge edge. Before, it was declared as a top-level key in the charge edge's default data instead of inside itsconstraintsdictionary, so it was silently dropped.- Dual exports now handle unavailable solver duals safely, recording
NaNinstead of failing while preservingFloat64output arrays. - CSV input reading now releases file handles deterministically to allow immediate rewriting and deletion on Windows. JSON reads/writes and CSV header reads also close streams after exceptions.
- Added
edge_losses.csvoutput file to report the commodity lost on every edge with a nonzeroloss_fraction, for all solution algorithms and in the full time series (keyLossesinOutputLayout,OutputFormatandWriteOutputs). LossyBidirectionalEdges now hold theirflow_pos/flow_negpair as fields. - Lossy bidirectional edges now split their flow into a single
vFLOWPOS/vFLOWNEGpair shared by both vertex balances. - Iterating over
SubproblemsData, the container for per-subproblem Benders results, no longer yields the first subproblem twice. Written outputs were not affected, since the output writers read its fields directly rather than iterating it. - Fixed TDR weights for shared CSV columns so excluded references and references with no matching feature do not increase clustering influence. Total usage counts are retained for provenance; clustering occurrence summaries count included references only.
- Corrected exported duals after MacroEnergyScaling constraint-row and objective scaling. All model builders now retain cumulative scaling metadata per model, and dual reporting restores the original model units before applying input scaling, time weights and discount conversions. Requires MacroEnergyScaling v0.4.1 or later.
- Multi-period cases no longer fail with a
MethodErrorwhen carrying over capacities for an asset whose optional edge is absent, such as aBECCSHydrogenasset without afuel_edge. Myopic runs withReturnModels: falsefailed the same way when releasing such an asset. - Myopic runs with
ReturnModels: falsenow also release the JuMP references held by system-wide and per-location grouped capacity constraints. These kept an emptied model alive for each period, which increased memory use with the number of periods. - Fixed location membership for automatically created nodes so location-based outputs and capacity constraints can identify their location correctly. Automatic nodes are registered before attachment, so rejected duplicate IDs leave membership unchanged and repeated lookups still fail.
- Fixed unresolved endpoint handling:
AutoCreateNodesnow reports an error when an endpoint matches neither an existing node nor a location, rather than attempting to create an anonymous node. - Fixed time-domain reduction commodity context for nodes defined within locations, so commodity-scoped feature weights and exclusions apply to inline series and CSV references. Reference exclusions now match actual input context, including file, field, asset, and commodity, even when a generic feature is selected.
- Fixed
template_locationto support location dictionaries and mixed batches, preserve existing commodity and constraint definitions, and check duplicates by location ID. Conflicting definitions are rejected before writing; new JSON files and directories can be created directly. - Fixed time-domain reduction of inputs defined inline within
caseentries insystem_data.json. Bare and case-wrapped Systems now share scoped discovery and rewriting, so reduced and isolated subperiod cases use the selected periods' values without mixing Systems' profiles. Older output-feature caches are invalidated and regenerated. - Fixed
mermaid_diagramto create explicit placeholder endpoints in its temporary system, preserving asset diagrams with stricterAutoCreateNodesendpoint validation. Commodity names also resolve consistently when called from another Julia module.
Documentation
- Expanded the balance documentation with guidance on choosing between balance macros, stoichiometric coefficient bases, pairwise expansion limits, multi-term algebraic balances, common mistakes, and numerical sensitivity.
- Updated modeler documentation to include balance APIs in the asset-construction workflow and to recommend a small single-asset regression test for each new asset.
- Updated debugging guidance around
balance_data,get_balance, and@inspect_stoichiometric_balance. - Updated asset-specific documentation examples to use the balance macros instead of legacy raw balance dictionaries.
- Added preprocessing and TDR manuals covering configuration, input discovery, candidate construction, clustering, output-feature caching, generated files, and function workflow trees.
- Added output manual sections on output formats and file sizes, selecting outputs, and reading all periods' outputs as one table with DuckDB, polars or pandas.
- Synced the tutorials with MacroEnergyExamples.jl: added Tutorial 3 (a three-zone multisector showcase) and a Benders decomposition section in Tutorial 1, and updated the code in Tutorials 0-2 to the current API (
scalingargument of the result functions,resource_typeoutput column, sign of storage charge flows). - Fixed the Tutorial 2 asset diagrams, which did not load on the deployed site, and a table-of-contents entry pointing to a tutorial page that does not exist.
Migration guide
- When updating an asset, prefer
@add_balancefor ordinary algebraic equalities and inequalities, prefer@add_to_storage_balancefor storage law-of-motion terms, and use@add_stoichiometric_balanceonly when the relationship is naturally a recipe-style proportional conversion. - Legacy raw balance dictionaries should usually be replaced with explicit balance macros. For example:
transform.balance_data = Dict(
:energy => Dict(
output_edge.id => coeff,
input_edge.id => 1.0,
),
)can become:
@add_balance(transform, :energy, flow(output_edge) == coeff * flow(input_edge))or, when the relationship is best represented as a recipe:
@add_stoichiometric_balance(
transform,
:production,
coeff * flow(input_edge) --> flow(output_edge),
flow(output_edge),
)- Use
@add_balancewhen the relationship is easiest to write as an explicit equation, includes three or more independently varying terms, or is not just a set of pairwise proportional relations. - Use
@add_stoichiometric_balancewhen onebase_termshould anchor several proportional relationships and all coefficients can be written on a common recipe basis. - In one
@add_stoichiometric_balanceexpression, all coefficients must share a common basis. For example, if the base term is product output, coefficients should usually be expressed per unit output; if the base term is fuel input, coefficients should usually be expressed per unit fuel. - When extending the
:storagebalance of a storage component, use@add_to_storage_balance(storage, coeff * flow(edge)). In normal usage, write positive magnitudes for both inflows and outflows and let MacroEnergy apply the effective sign through edge direction. - During migration, inspect generated pairwise equations with
@inspect_stoichiometric_balance(...), inspect stored coefficients withbalance_data(component, balance_id), inspect compiled expressions withget_balance(component, balance_id), and validate the asset with a small single-asset solve test. - Small differences in large-system results do not automatically indicate a balance bug. Algebraically equivalent formulations can change row scaling and solver tie-breaking in large, near-degenerate systems, so localized single-asset regression tests are the primary evidence that migrated balances remain correct.
- Results change: no public API changed, but any case using a
Batteryasset could now produce different results. The charge limit (charge_flow[t] <= capacity - storage_level[t-1], scaled by the charge efficiency) was previously not included by default and is now enforced. To keep the old behavior, disable it explicitly on the charge edge:"charge_edge": {"constraints": {"StorageChargeLimitConstraint": false}}. - If you set
StorageChargeLimitConstraintas a top-level key on a charge edge, rather than inside that edge'sconstraintsdictionary, it was and still is ignored. Move it insideconstraintsfor it to take effect. - Replace
"DualExportsEnabled": falseinmacro_settings.jsonwith"WriteOutputs": {"Duals": false}."DualExportsEnabled": truecan simply be removed, since duals are written by default. StorageChargeLimitConstraintonly applies to an edge whose end vertex is the storage, i.e. the charge edge. Setting it on the discharge edge (or viadischarge_constraintsin the simple input format) has no effect.
For the full release history, see the changelog. <!– END GENERATED RECENT CHANGES –>
Macro development strategy
Macro is a very flexible tool for modelling energy systems. However, that flexibility also means the core architecture and functions are complex and difficult to use correctly.
To make Macro as useful and accessible to the widest audience possible we designed and developed it with three layers of abstractions in mind, each serving a different user profile:

Due to these abstractions, users and modelers will be able to achieve their goals without needing to understand every aspect of Macro. The guides section of the documentation has guides for users, modelers, and developers.