Chapter 18: Custom Logic Block Development
Converting methodology equations into executable code using Guardian's customLogicBlock
This chapter teaches you how to implement methodology calculations as working code that produces accurate emission reductions or removals. You'll learn to translate VM0033's mathematical formulas into executable functions, using the ABC Mangrove's real world data artifact as your validation benchmark. By the end, you'll write code that transforms methodology equations into verified carbon credit calculations.
Learning Objectives
After completing this chapter, you will be able to:
Translate methodology equations into executable JavaScript or Python code
Implement formulas for baseline emissions, project emissions, and net emission reductions
Process monitoring data through mathematical models defined in VM0033 methodology
Validate equation implementations against Allcot test artifact input/output data
Handle data precision and validation requirements for accurate calculations
Structure mathematical calculations for production-ready environmental credit systems
Prerequisites
Completed Part IV: Policy Workflow Design and Implementation
Understanding of VM0033 methodology and equations from Part I
Basic programming knowledge for implementing mathematical formulas (JavaScript or Python)
Access to validation artifacts: equation implementations, test input data, and Allcot validation spreadsheet
Guardian customLogicBlock: Your Calculation Engine
The Mathematical Execution Environment
Guardian's customLogicBlock is your calculation engine for environmental methodologies - it's where mathematical equations become executable code. Think of it as a computational engine that processes monitoring data through formulas to produce emission reductions that match methodology equations precisely.
You can write your calculations in JavaScript or Python - Guardian supports both languages. Most of our examples use JavaScript, but the concepts apply equally to Python.

Understanding Your Input Data
Every customLogicBlock receives Guardian documents through arguments[0]. These contain the measured variables and parameters needed for your methodology equations - real data from environmental monitoring. Here's the data structure you'll process through mathematical formulas:
This is actual data from the ABC Blue Carbon Mangrove Project in Senegal - the same project used in our test case spreadsheet.
Accessing Data Like a Pro
Field Access Patterns from Production Code
Let's look at how VM0033's production code accesses data. These utility functions from er-calculations.js make your code clean and readable:
The ?? operator provides safe defaults when data might be missing.
Building Your Calculation Engine
The Main Calculation Function
Every customLogicBlock starts with a main function that processes the documents. Here's the pattern from VM0033's production code:
Processing Project Instances
Each project instance represents a restoration site. The processInstance function is where you implement the methodology calculations:
Implementing Baseline Emission Equations
From Methodology Equations to Code
Baseline emissions implement the scientific equations from VM0033 Section 8.1 - representing the "business as usual" scenario without restoration. Each equation in the methodology PDF more or less becomes a function in your code.
Example: VM0033 Equation 8.1.1 - Soil CO2 Emissions
Implementing Project Emission Equations
Translating VM0033 Section 8.2 Equations
Project emissions implement equations from VM0033 Section 8.2 - the restoration scenario calculations. These equations typically show reduced emissions and increased sequestration compared to baseline.
Example: VM0033 Equation 8.2.3 - Project Biomass Change
Implementing Net Emission Reduction Equations
VM0033 Section 8.5 - The Final Scientific Calculation
This implements VM0033's core equation that transforms baseline and project emissions into verified carbon units (VCUs). Each line of code corresponds to specific equations in Section 8.5 of the methodology.
Example: VM0033 Equation 8.5.1 - Net Emission Reductions
Handling Real-World Data Challenges
Defensive Programming Patterns
Real project data is messy. Projects miss monitoring periods, equipment fails, and data gets corrupted. They might send a different data type than you might expect. Your code needs to handle this gracefully:
Error Handling
Validation: Allcot Test Artifact as Your Benchmark
Ensuring Mathematical Accuracy
The Allcot test artifact is your validation benchmark - it contains input parameters and expected output results calculated manually according to VM0033 methodology equations. Your code must reproduce these results exactly to ensure mathematical accuracy.
Your equation implementations must produce the same results as the manual calculations to be valid.
Python Alternative
Writing CustomLogicBlocks in Python
Guardian also supports Python for customLogicBlock development. The concepts are the same, just different syntax:
Choose the language you're more comfortable with - both produce identical results.
Testing Your Code
Quick Testing Tips
While Chapter 21 covers comprehensive testing, here are quick validation techniques while you're developing:
1. Console Logging for Debug
2. Guardian's Built-in Testing Use Guardian's customLogicBlock testing interface (covered in Chapter 21) to test with real final-PDD-vc.json data.
3. Unit Testing Individual Functions
Real Results: ABC Mangrove Project
Production Calculation Results
Using VM0033's calculation engine with the ABC Blue Carbon Mangrove Project data, here are the actual VCU projections over the 40-year crediting period(data added till 2055 only):
2022
0.01
2032
104,012.50
2042
122,680.75
2052
75,559.80
2023
0.29
2033
110,576.46
2043
120,929.68
2053
72,200.65
2024
4.31
2034
115,770.40
2044
118,625.12
2054
69,072.40
2025
1,307.66
2035
119,502.79
2045
115,610.59
2055
66,174.64
Total Project Impact: 2,861,923 VCU credits over 40 years
This demonstrates what your code should produce - substantial carbon credits from mangrove restoration that follow the methodology calculations exactly.
Deep Dive: VM0033 Production Implementation Analysis
Note for Readers: This section provides an detailed analysis of VM0033 calculation implementation in Guardian's customLogicBlock. It's intended for developers who need to understand, write, or maintain VM0033. You can skip this section if you only need to understand the basic customLogicBlock concepts.
This deep dive examines the complete production implementation of VM0033 tidal wetland restoration calculations in Guardian, using the VM0033 Allcot Test Case Artifact and er-calculations.js as our reference implementations.
Complete VM0033 Production Code Architecture
The 1261-line er-calculations.js contains 25+ interconnected functions implementing the full VM0033 methodology. Here's the complete function catalog mapped to test artifact worksheets:
Core Architecture Overview
Test Artifact Mapping
Each function maps directly to specific data models defined within VM0033_Allcot_Test_Case_Artifact.xlsx:
ProjectBoundary (27x13) β getProjectBoundaryValue(), processInstance() boundary logic
QuantificationApproach (8x22) β getQuantificationValue(), SOC approach selection
StratumLevelInput + UI Req (49x29) β All stratum processing functions
MonitoringPeriodInputs (158x8) β processMonitoringSubmergence(), monitoring functions
5.1_TemporalBoundary (36x24) β calculatePDTSDT(), temporal boundary functions
8.1BaselineEmissions (158x84) β processBaselineEmissions() complete logic
8.2ProjectEmissions (158x83) β processProjectEmissions() complete logic
8.5NetERR (53x23) β processNETERR() and all VCU calculation functions
Section 3: Temporal Boundary System (Lines 181-350)
Peat and Soil Depletion Time Calculations
VM0033 calculates when carbon pools will be depleted to determine crediting periods. This maps directly to the 5.1_TemporalBoundary worksheet (36x24) in our test artifact.
calculatePDTSDT() - Temporal Boundary Implementation (Lines 181-286)
This function implements VM0033 Section 5.1 equations for calculating Peat Depletion Time (PDT) and Soil organic carbon Depletion Time (SDT):
Temporal Boundary Helper Functions (Lines 288-350)
These functions provide stratum-specific temporal boundary access:
100-Year Carbon Projection Functions (Lines 312-350)
These functions calculate carbon coverage over 100-year projections:
Test Artifact Cross-Reference:
The temporal boundary calculations map to 5.1_TemporalBoundary worksheet rows 5-36
PDT calculations use peat depth and loss rates from StratumLevelInput columns M-P
SDT calculations use soil characteristics from StratumLevelInput columns Q-T
100-year projections cross-reference 5.2.4_Ineligible wetland areas worksheet
This temporal boundary system determines:
When carbon pools will be depleted in the baseline scenario
How long emission reductions can be credited for each stratum
Which calculation approach to use (total stock vs stock loss)
The temporal scope for SOC_MAX calculations
Section 4: SOC Calculation Approaches (Lines 352-516)
Two Ways to Calculate Soil Organic Carbon Benefits
VM0033 offers two approaches for calculating soil organic carbon benefits. Both map to the 5.2.4_Ineligible wetland areas worksheet (47x30) in our test artifact.
totalStockApproach() - Compare 100-Year Carbon Stocks (Lines 352-458)
This approach compares total carbon stocks at 100 years between baseline and project scenarios:
stockLossApproach() - Compare Carbon Loss Rates (Lines 461-506)
This approach compares carbon loss rates over 100 years:
SOC_MAX_calculation() - Approach Selector (Lines 508-514)
This function selects which approach to use and calculates the final SOC_MAX value:
Test Artifact Cross-Reference:
SOC calculations map to 5.2.4_Ineligible wetland areas worksheet columns A-AD
Total stock approach uses 100-year projections from columns B-H
Stock loss approach uses carbon loss rates from columns I-O
Both approaches feed into SOC_MAX value in column AD
Section 1: Monitoring and Submergence Processing (Lines 39-94)
Processing Time-Series Monitoring Data
VM0033 tracks wetland submergence over time to calculate biomass changes. This maps to the MonitoringPeriodInputs worksheet (158x8) in our test artifact.
processMonitoringSubmergence() - Submergence Monitoring Engine (Lines 39-69)
This function processes submergence measurements across monitoring years and calculates biomass deltas:
getDeltaCBSLAGBiomassForStratumAndYear() - Biomass Delta Lookup (Lines 71-91)
This function retrieves biomass delta values for specific stratum and year combinations:
Test Artifact Cross-Reference:
Submergence data maps to MonitoringPeriodInputs worksheet columns A-H
is_submergedvalues from column Bsubmergence_Tperiods from column Carea_submerged_percentagefrom column DCalculated
delta_C_BSL_agbiomass_i_tvalues stored in column H
Section 2: Specialized Calculator Functions (Lines 95-180)
Allocation Deductions and VCU Change Calculations
These functions handle allocation deductions and VCU change calculations between monitoring periods.
Allocation Deduction Functions (Lines 95-137)
VM0033 requires allocation deductions for certain soil types and approaches:
GHG Emission Getter Functions (Lines 140-169)
These functions safely retrieve emission values by year:
VCU Change Calculation Functions (Lines 170-179)
These functions calculate VCU changes between monitoring periods:
Test Artifact Cross-Reference:
Allocation deductions map to 8.1BaselineEmissions and 8.2ProjectEmissions allocation columns
VCU change calculations feed into 8.5NetERR worksheet VCU change columns M-P
Fire reduction premiums cross-reference FireReductionPremium + UI Req worksheet
Section 8: Complete processInstance Orchestration (Lines 1126-1241)
The Master Controller: How All 25+ Functions Work Together
The processInstance() function is where the entire VM0033 methodology comes together. It orchestrates all the functions we've covered and maps to multiple test artifact worksheets. This is the production-level implementation that processes a complete project instance.
Parameter Extraction Phase (Lines 1126-1184)
The function starts by extracting parameters from every section of the Guardian document:
Monitoring Data Processing Phase (Lines 1185-1221)
Next, the function processes monitoring period inputs:
Calculation Orchestration Phase (Lines 1221-1241)
Finally, the function orchestrates all the calculations in the correct order:
Test Artifact Cross-Reference:
ProjectBoundary worksheet β Project boundary parameter extraction (lines 1132-1159)
QuantificationApproach worksheet β Quantification approach parameters (lines 1162-1170)
IndividualParameters worksheet β Individual parameter extraction (lines 1173-1184)
MonitoringPeriodInputs worksheet β Monitoring data processing (lines 1186-1200)
IF Wood Product Is Included worksheet β Wood product data (lines 1211-1218)
All calculation worksheets β Orchestrated function calls (lines 1221-1240)
This orchestration demonstrates production-level implementation where:
Parameter extraction is conditional - only extract what you need
Calculation order matters - temporal boundaries before emissions, emissions before VCUs
Every major worksheet in the test artifact maps to specific code sections
Defensive programming - safe defaults and conditional logic throughout
Section 9: Entry Point and Final Integration (Lines 1243-1261)
The calc() Function - Guardian's Entry Point
The calc() function is Guardian's entry point for customLogicBlock execution. It processes multiple project instances and calculates total VCUs:
Section 5: Complete processBaselineEmissions Implementation (Lines 517-713)
The 200-Line Baseline Calculation Engine
This is the production implementation that processes VM0033 baseline emissions, mapping directly to the 8.1BaselineEmissions worksheet (158x84) in our test artifact.
Key Production Features:
AR Tool Integration - integration with AR Tool 14 (afforestation) and AR Tool 05 (fuel)
Temporal Boundary Application - PDT/SDT constraints applied to actual emission calculations
Submergence Integration - Monitoring data affects biomass calculations
Multiple Calculation Methods - Field data, proxies, IPCC factors handled
Defensive Programming - Safe defaults and null checks throughout
Year-level Aggregation - Proper summing across strata and time
Each function processes multi-dimensional calculations across temporal and spatial boundaries
Baseline Emissions Processing
Let's examine the baseline emissions calculation in detail, cross-referencing with test artifact data:
1. Temporal Boundary Calculations - PDT/SDT Implementation
From er-calculations.js:1145-1220, the calculatePDTSDT function establishes critical temporal boundaries required by VM0033 methodology:
This corresponds directly to the 5.1_TemporalBoundary worksheet in our test artifact (36x24 dimensions), which contains:
Peat thickness measurements (cm) - Column C in test data
Subsidence rates (cm/year) - Column D in test data
Calculated PDT values for each stratum - Column E in test data
SOC depletion time calculations - Column F in test data
2. Fire Emissions Processing with Multi-Pool Carbon Dynamics
The fire emissions processing demonstrates temporal modeling across multiple carbon pools:
This implementation maps precisely to the 8.1BaselineEmissions worksheet rows handling fire emission calculations, which include:
Fire area data (hectares) - Columns K-M in test data
Above-ground biomass (tC/ha) - Columns N-P in test data
Below-ground biomass (tC/ha) - Columns Q-S in test data
Combustion factors - Columns T-V in test data
Root combustion factors - Columns W-Y in test data
3. Soil Carbon Stock Approaches Implementation
The implementation handles two distinct soil carbon quantification approaches as specified in VM0033 Section 5.2:
Project Emissions Processing
Project emissions represent the "with project" scenario and involve restoration activity modeling:
1. Project Emissions Calculation
From er-calculations.js:712-785, project emissions account for various restoration phases:
This corresponds to the 8.2ProjectEmissions worksheet (158x83 dimensions) containing:
Machinery fuel consumption data - Columns F-H in test data
Transportation emission factors - Columns I-K in test data
Restoration activity schedules - Columns L-N in test data
Equipment operation parameters - Columns O-Q in test data
2. Soil GHG Emissions Under Restored Conditions
The project scenario accounts for altered soil GHG emissions under restored wetland conditions:
Net Emission Reductions (NER) with Uncertainty Handling
The final stage calculates creditable emission reductions with uncertainty and buffer deductions:
1. Multi-Component NER Calculation Engine
From er-calculations.js:786-849, the net emission reduction calculation:
2. Uncertainty and Buffer Deduction Framework
The implementation applies uncertainty and buffer deductions as required by VM0033:
This maps directly to the 8.5NetERR worksheet (53x23 dimensions) which contains:
Annual emission reduction calculations - Columns C-E in test data
Uncertainty percentage applications - Columns F-H in test data
Buffer percentage deductions - Columns I-K in test data
NERRWE cap applications - Columns L-N in test data
Final creditable volumes - Columns O-Q in test data
Section 6: Complete processProjectEmissions Implementation (Lines 715-926)
The processProjectEmissions function calculates the project scenario emissions. It follows a parallel structure to baseline processing but applies project-specific parameters.
AR Tool Results Integration
The function begins by extracting AR Tool results for each stratum:
This corresponds to the 6.2ARTool14ProjectData worksheet (2x4 dimensions) where AR Tool 14 calculates carbon stock changes in:
Tree biomass - Column C in test data
Shrub biomass - Column D in test data
And 6.4ARTool5ProjectData worksheet (43x4 dimensions) where AR Tool 05 calculates fossil fuel consumption for project machinery and operations.
Biomass Application Logic
The function includes conditional logic for biomass components:
This checks stratum configuration flags to determine which biomass pools should be included in calculations. The corresponding test data in 7.2ProjectScenarioData worksheet (43x28 dimensions) shows these boolean flags in columns H-J.
Project Scenario Soil Emissions
The soil emissions calculation follows the same three-method approach as baseline but applies project scenario parameters:
This maps to 7.2ProjectScenarioData columns K-M which contain project scenario soil carbon change data calculated using the same methods as baseline but with project-specific parameters.
Non-CO2 Gas Calculations
The function handles CH4 and N2O emissions from soil using project-specific approaches:
This corresponds to columns N-P in 7.2ProjectScenarioData where CH4 emissions are calculated using project-specific approaches and emission factors.
Prescribed Burning Calculations
The function includes specialized calculations for prescribed burning activities:
This calculates emissions from biomass burning using emission factors for N2O and CH4, converted to CO2 equivalent using Global Warming Potentials. The calculations use the Math.pow(10, -6) conversion factor for unit consistency. Test data in columns S-U of 7.2ProjectScenarioData validate these burning emission calculations.
Annual Aggregation
The function aggregates all emission components for each monitoring year:
This produces the annual project scenario emissions that feed into net emission reduction calculations. The final aggregation creates cumulative totals across all monitoring years using the reduce operations.
The function outputs correspond to 7.3ProjectScenarioGHGEmissions worksheet (43x7 dimensions) which contains:
Annual biomass emission changes - Column C
Annual soil emissions - Column D
Annual fuel consumption emissions - Column E
Annual burning emissions - Column F
Total annual project emissions - Column G
Section 7: Complete processNETERR Implementation (Lines 927-1118)
The processNETERR function calculates the net emission reductions for each monitoring year. This function brings together baseline and project scenario results to determine final creditable volumes.
Baseline and Project Aggregation
The function begins by aggregating baseline and project scenario results across all strata for each monitoring year:
This aggregation corresponds to 8.1NetERRCoreData worksheet (43x8 dimensions) where baseline and project scenario emissions are aggregated across all strata to produce project-level totals for each monitoring year.
Cumulative Calculations
The function maintains cumulative sums across monitoring years using running totals:
This produces cumulative emission totals that are essential for stock loss approach calculations and buffer pool management. Test data in columns C-F of 8.1NetERRCoreData shows these cumulative progressions.
Stock Loss Deduction Logic
The function implements stock loss approach deductions when enabled:
This logic deducts any emissions above the maximum soil organic carbon limit (SOC_MAX) to ensure conservative crediting. The calculation corresponds to column G in 8.1NetERRCoreData which shows stock loss deductions applied when cumulative differences exceed the methodology limits.
Fire Reduction Premium Integration
The function includes optional fire reduction premium credits:
This applies fire reduction credits based on documented fire management activities. Test data in column H of 8.1NetERRCoreData shows annual fire reduction premium applications.
NERRWE Calculation
The core net emission reduction calculation combines all components:
This formula represents the fundamental VM0033 equation: Net Emission Reductions = Baseline Emissions + Project Emissions + Fire Reduction Premium - Leakage - Stock Loss Deductions.
Capping Logic
The function applies optional annual emission reduction caps:
This ensures annual emission reductions don't exceed methodology-defined limits. Test data in 8.2NetERRAdjustments worksheet (43x6 dimensions) shows the application of caps in column C.
Uncertainty Adjustments
The function applies measurement and model uncertainties:
This incorporates both positive (allowable) and negative (model error) uncertainty adjustments. The calculation corresponds to column D in 8.2NetERRAdjustments where uncertainty percentages are applied to final emission reductions.
Buffer Pool Calculations
The function calculates buffer pool deductions using an incremental approach:
This calculates buffer deductions based on incremental changes between monitoring years rather than applying the buffer percentage to total accumulations. Test data in 8.3NetERRBufferDeduction worksheet (43x6 dimensions) validates these buffer calculations.
Final VCU Calculations
The function produces final Verified Carbon Units:
This produces the final creditable carbon units for each monitoring year. The outputs correspond to 8.4NetERRFinalCalculations worksheet (43x6 dimensions) which contains:
Gross emission reductions - Column C
Uncertainty-adjusted reductions - Column D
Buffer deductions - Column E
Final VCU issuance - Column F
The function establishes total VCU quantities that determine final carbon credit issuance amounts for the project.
Chapter Summary
You've learned how to translate scientific equations from environmental methodologies into executable code that produces verified carbon credits. The key principles:
Equation-to-Code Translation - Every methodology equation becomes a function in your customLogicBlock
Scientific Precision Required - Use defensive programming to handle edge cases while maintaining mathematical accuracy
Allcot Test Artifact is Your Benchmark - Your code must reproduce manual calculations exactly for scientific validity
Field Access Utilities enable clean implementation of complex mathematical formulas
Both JavaScript and Python supported - choose the language that best implements your equations
Your equation implementations are the foundation of environmental credit integrity. When coded properly, they transform scientific methodology equations into verified carbon units that represent real, measured emission reductions from restoration projects.
The next chapter explores Formula Linked Definitions (FLDs) for managing parameter relationships, and Chapter 21 covers comprehensive testing to ensure your calculations are production-ready.
Last updated