2.8 KiB
2.8 KiB
Units and Formulas Definition Format
Units Specification
Units are defined in .d4rt.units files using JSON arrays. Each unit can have:
{
"name": "unit name", // Full name (required)
"symbol": "abbr", // Symbol (required)
"isBase": true, // Mark as base unit (exclusive with baseUnit)
"baseUnit": "parent", // Reference unit for conversions
"factor": 1.0, // Conversion factor to base unit
"toBase": "x * 1000", // Conversion code to base (expression)
"fromBase": "x / 1000" // Conversion code from base (expression)
}
Key Rules:
- Use either
isBaseORbaseUnit+conversion (factor or code) - Factor-based units use simple multiplicative conversions
- Code-based units require both
toBaseandfromBaseDart expressions - Code expressions:
- Use
xas input variable - Must return a numeric value
- Can use math functions via
dart:math
- Use
Examples:
Simple Factor-based:
{
"name": "kilometer",
"symbol": "km",
"baseUnit": "meter",
"factor": 1000
}
Code-based Conversion:
{
"name": "Fahrenheit",
"symbol": "°F",
"baseUnit": "Kelvin",
"toBase": "(x - 32) * 5/9 + 273.15",
"fromBase": "(x - 273.15) * 9/5 + 32"
}
Formulas Specification
Formulas are defined in .d4rt files using JSON arrays. Each formula has:
{
"name": "Formula Name", // Required
"description": "Markdown", // Optional
"input": [ // List of input variables
{
"name": "varName", // Variable identifier
"unit": "unitName" // Base unit for calculations
}
],
"output": { // Single output variable
"name": "resultVar",
"unit": "outputUnit"
},
"d4rtCode": "Dart code", // Calculation logic
"tags": ["physics", "energy"] // Categories
}
Formula Code Rules:
- Input variables are declared as
final - Output variable must be assigned
- Can use:
- Basic math operators
dart:mathfunctions- Custom functions from FormulaEvaluator
- Example:
// Inputs: m (kg), v (m/s)
d4rtCode: "KE = 0.5 * m * pow(v, 2);"
Conversion Code Examples
Expression-style:
// Simple factor conversion
final x = 5; // Value in source unit
main() => x * 1000; // Convert to base unit
Statement-style:
// Complex conversion with multiple steps
final x = 212; // Fahrenheit
main() {
var celsius = (x - 32) * 5/9;
return celsius + 273.15; // Convert to Kelvin
}
Validation Rules
- Units must form a DAG (no circular dependencies)
- Formulas must declare all input variables
- Output variable must be assigned in d4rtCode
- Unit conversion code must handle numeric inputs
- Base units must exist before derived units