A MoonBit-native report layer for chemical engineering calculations.
moon update
moon check --target all --deny-warn
moon test --target all --deny-warn
moon run cmd/mainmoon run cmd/main| Area | Files | Responsibility |
|---|---|---|
| Domain model | moonbit-chemreport.mbt | Report records, enums, and constructors |
| Exporters | markdown_export.mbt, html_export.mbt, json_export.mbt, table.mbt | Deterministic human and machine output |
| Engineering math | units.mbt, balance.mbt, process_calculations.mbt | Units, balances, equipment and safety calculations |
| Scenario analysis | analytics.mbt, scenario_engine.mbt | Statistics, control limits, sweeps, and sensitivity |
| Process models | streams.mbt, equipment_design.mbt, reactor_kinetics.mbt, mass_transfer.mbt, heat_transfer.mbt | Inventory, sizing, kinetics, contacting and thermal screening |
| Operations | batch_operations.mbt, process_schedule.mbt, workflow.mbt, control_system.mbt | Recipes, calendars, review state, alarms and control loops |
| Quality and risk | validate.mbt, quality.mbt, diagnostics.mbt, validation_rules.mbt, data_quality.mbt, risk_analysis.mbt | Evidence checks, risk ranking, import quality and acceptance gates |
| Economics and sustainability | cost_model.mbt, uncertainty.mbt, environmental.mbt | Cost, uncertainty, emissions and reduction scenarios |
| Integration | report_pipeline.mbt, benchmark.mbt, data_import.mbt | Builders, batches, reproducible measurements and delimited data |
| Integration | report_pipeline.mbt, benchmark.mbt | Builders, batches, and reproducible export measurements |
let result = benchmark_exports([example_chemreport()], 100)
println(result.to_markdown())moon test --target all --deny-warn
moon test --target native --enable-coverage
moon coverage report -f summary
moon coverage analyzepub struct AbsorberDesign {
gas_flow_mol_h : Float
liquid_flow_mol_h : Float
inlet_gas_fraction : Float
outlet_gas_fraction : Float
equilibrium : EquilibriumLine
overall_kya_h : Float
}pub struct Alarm {
code : String
tag : String
value : Float
low : Float
high : Float
state : AlarmState
message : String
} derive(Eq, Debug)pub struct AntoineCorrelation {
a : Float
b : Float
c : Float
minimum_c : Float
maximum_c : Float
}pub struct ArrheniusModel {
pre_exponential : Float
activation_energy_kj : Float
reference_temperature_k : Float
}pub struct BatchCharge {
material : String
mass_kg : Float
purity : Float
}pub struct BatchPlan {
recipe : BatchRecipe
steps : Array[BatchStep]
cleaning_hours : Float
setup_hours : Float
}pub struct BatchRecipe {
name : String
target_kg : Float
charges : Array[BatchCharge]
hold_hours : Float
yield_fraction : Float
}pub struct BatchRecord {
id : String
plan_name : String
started_at : String
finished_at : String
output_kg : Float
scrap_kg : Float
accepted : Bool
}pub struct BatchStep {
name : String
duration_hours : Float
temperature_c : Float
pressure_bar : Float
agitation_rpm : Float
}pub struct ChemReport {
metadata : ReportMetadata
summary : String
assumptions : Array[Assumption]
inputs : Array[InputValue]
formulas : Array[FormulaNote]
results : Array[ResultValue]
warnings : Array[WarningNote]
sources : Array[SourceRef]
sections : Array[ReportSection]
tags : Array[String]
} derive(Eq, Debug)pub struct ChemicalPropertySet {
name : String
molecular_weight : Float
density : LinearProperty
viscosity : LinearProperty
heat_capacity : LinearProperty
vapor_pressure : AntoineCorrelation
}fn ChemicalPropertySet::heat_capacity_at(self : ChemicalPropertySet, temperature_c : Float) -> Floatfn ChemicalPropertySet::phase_at(self : ChemicalPropertySet, temperature_c : Float, pressure_kpa : Float) -> PhaseStatefn ChemicalPropertySet::vapor_pressure_at(self : ChemicalPropertySet, temperature_c : Float) -> Floatfn ControlLoop::update(self : ControlLoop, values : Array[Float], step : Float, minimum : Float, maximum : Float) -> ControlLooppub struct Controller {
tag : String
setpoint : Float
process_value : Float
output : Float
gain : Float
integral : Float
mode : ControllerMode
} derive(Eq, Debug)fn Controller::next_output(self : Controller, step : Float, minimum : Float, maximum : Float) -> Floatfn Controller::update(self : Controller, process_value : Float, step : Float, minimum : Float, maximum : Float) -> Controllerpub struct CstrDesign {
volume_m3 : Float
flow_m3_h : Float
rate_mol_m3_h : Float
feed_mol_m3 : Float
}pub struct DataField {
name : String
value : String?
expected_unit : String?
policy : MissingPolicy
} derive(Eq, Debug)pub struct Diagnostic {
code : String
severity : DiagnosticSeverity
path : String
message : String
remediation : String
} derive(Eq, Debug)pub struct EnergyBalance {
inlet : Float
outlet : Float
residual : Float
streams : Array[EnergyStream]
} derive(Eq, Debug)fn EnergyBalance::specific_duty(self : EnergyBalance, mass : Quantity) -> Result[Quantity, QuantityError]pub struct EnergyStream {
name : String
duty : Quantity
direction : StreamDirection
} derive(Eq, Debug)pub struct EquilibriumLine {
slope : Float
intercept : Float
}pub struct Hazard {
id : String
node : String
deviation : String
cause : String
consequence : String
likelihood : RiskLikelihood
severity : RiskSeverity
safeguards : Array[String]
}pub struct HeatExchangerCheck {
area_m2 : Float
required_m2 : Float
duty_kw : Float
pressure_drop_bar : Float
max_pressure_drop_bar : Float
}pub struct ImportIssue {
line_number : Int
field : String
message : String
severity : String
}pub struct InsulationDesign {
thickness_m : Float
conductivity_w_mk : Float
area_m2 : Float
ambient_c : Float
process_c : Float
}pub struct LinearProperty {
reference : Float
slope : Float
reference_temperature : Float
}pub struct MaintenanceWindow {
asset : String
due_hour : Float
duration_hours : Float
critical : Bool
completed : Bool
}pub struct MaterialBalance {
components : Array[ComponentBalance]
total_inlet : Float
total_outlet : Float
} derive(Eq, Debug)pub struct MixtureProperty {
component : String
mole_fraction : Float
property : ChemicalPropertySet
}pub struct PackedColumn {
diameter_m : Float
packing_height_m : Float
packing_factor : Float
gas_velocity_m_s : Float
flooding_velocity_m_s : Float
}pub struct PfrDesign {
volume_m3 : Float
flow_m3_h : Float
inlet_mol_m3 : Float
rate_mol_m3_h : Float
}pub enum PhaseState {
Solid
Liquid
Vapor
Supercritical
}pub struct ProcessStream {
name : String
direction : StreamDirection
components : Array[ComponentFlow]
} derive(Eq, Debug)pub enum QuantityError {
IncompatibleDimensions(UnitDimension, UnitDimension)
BelowAbsoluteZero
InvalidValue
} derive(Eq, Debug)pub struct ReactionOrder {
order_a : Float
order_b : Float
stoich_a : Float
stoich_b : Float
}fn ReactionOrder::rate(self : ReactionOrder, constant : Float, concentration_a : Float, concentration_b : Float) -> Floatpub struct ReactionPath {
name : String
conversion : Float
selectivity : Float
yield_fraction : Float
}fn ReactorCase::is_safe(self : ReactorCase, temperature_limit : Float, pressure_limit : Float) -> Boolfn ReportBuilder::add_assumption(self : ReportBuilder, statement : String, impact : String) -> ReportBuilderfn ReportBuilder::add_formula(self : ReportBuilder, name : String, expression : String, explanation : String) -> ReportBuilderfn ReportBuilder::add_input(self : ReportBuilder, name : String, value : String, unit : String?, note : String?) -> ReportBuilderfn ReportBuilder::add_result(self : ReportBuilder, name : String, value : String, unit : String?, status : ResultStatus, note : String?) -> ReportBuilderfn ReportBuilder::add_section(self : ReportBuilder, title : String, kind : SectionKind, body : String) -> ReportBuilderfn ReportBuilder::add_source(self : ReportBuilder, label : String, kind : SourceKind, url : String?, license : String?, note : String?) -> ReportBuilderfn ReportBuilder::add_warning(self : ReportBuilder, code : String, severity : WarningSeverity, summary : String, action : String) -> ReportBuilderfn ReportTemplate::missing_fields(self : ReportTemplate, values : Array[TemplateValue]) -> Array[String]fn ReportTemplate::to_report(self : ReportTemplate, values : Array[TemplateValue], metadata : ReportMetadata) -> ChemReportpub struct ReportWorkflow {
id : String
steps : Array[WorkflowStep]
current : Int
} derive(Eq, Debug)pub struct ResultValue {
name : String
value : String
unit : String?
status : ResultStatus
note : String?
} derive(Eq, Debug)pub enum RiskLikelihood {
Rare
Unlikely
Possible
Likely
Frequent
}pub struct Rule {
code : String
operator : RuleOperator
field : String
limit : Float
severity : RuleSeverity
} derive(Eq, Debug)pub struct RuleEvaluation {
passed : Bool
violations : Array[RuleViolation]
checked : Int
} derive(Eq, Debug)pub struct RuleViolation {
code : String
field : String
actual : Float
limit : Float
severity : RuleSeverity
message : String
} derive(Eq, Debug)pub struct Safeguard {
name : String
kind : String
independent : Bool
test_interval_hours : Float
enabled : Bool
}pub struct ScenarioPoint {
name : String
input : Float
output : Float
score : Float
status : ResultStatus
note : String
} derive(Eq, Debug)pub struct ScenarioSeries {
name : String
points : Array[ScenarioPoint]
input_unit : String
output_unit : String
} derive(Eq, Debug)fn ScenarioSeries::quality_gate(self : ScenarioSeries, minimum_score : Float, maximum_flagged : Int) -> Boolpub struct ScheduleBlock {
id : String
asset : String
kind : ScheduleKind
start_hour : Float
duration_hours : Float
priority : Int
operator : String
}pub enum ScheduleKind {
Production
Cleaning
Maintenance
Inspection
Changeover
}pub struct SensitivityAnalysis {
baseline : Float
points : Array[SensitivityPoint]
} derive(Eq, Debug)pub struct Shift {
name : String
start_hour : Float
end_hour : Float
crew : Int
}pub struct SourceRef {
label : String
kind : SourceKind
url : String?
license : String?
note : String?
} derive(Eq, Debug)fn StreamInventory::normalize(self : StreamInventory, target : MeasureUnit) -> Result[StreamInventory, QuantityError]fn StreamInventory::without_component(self : StreamInventory, component : String) -> StreamInventoryfn TimeSeries::quality_gate(self : TimeSeries, minimum_count : Int, maximum_outliers : Int, threshold : Float) -> Boolpub struct TrayStage {
number : Int
efficiency : Float
liquid_flow : Float
vapor_flow : Float
}pub struct WallLayer {
name : String
thickness_m : Float
conductivity_w_mk : Float
}pub struct WarningNote {
code : String
severity : WarningSeverity
summary : String
action : String
} derive(Eq, Debug)fn WeightedObjective::rank(self : WeightedObjective, candidates : Array[Candidate]) -> Array[Candidate]pub struct WorkflowStep {
name : String
owner : String
status : WorkflowStatus
note : String
} derive(Eq, Debug)fn absorber_design(gas_flow_mol_h : Float, liquid_flow_mol_h : Float, inlet_gas_fraction : Float, outlet_gas_fraction : Float, equilibrium : EquilibriumLine, overall_kya_h : Float) -> AbsorberDesignfn alarm(code : String, tag : String, value : Float, low : Float, high : Float, message : String) -> Alarmfn antoine(a : Float, b : Float, c : Float, minimum_c : Float, maximum_c : Float) -> AntoineCorrelationfn arrhenius(pre_exponential : Float, activation_energy_kj : Float, reference_temperature_k : Float) -> ArrheniusModelfn batch_plan(recipe : BatchRecipe, steps : Array[BatchStep], cleaning_hours : Float, setup_hours : Float) -> BatchPlanfn batch_recipe(name : String, target_kg : Float, charges : Array[BatchCharge], hold_hours : Float, yield_fraction : Float) -> BatchRecipefn batch_record(id : String, plan_name : String, started_at : String, finished_at : String, output_kg : Float, scrap_kg : Float, accepted : Bool) -> BatchRecordfn batch_step(name : String, duration_hours : Float, temperature_c : Float, pressure_bar : Float, agitation_rpm : Float) -> BatchStepfn break_even_quantity(fixed_cost : Float, price : Float, variable_cost : Float) -> Floatfn catalyst_productivity(product_kg : Float, catalyst_kg : Float, hours : Float) -> Floatfn chemical_properties(name : String, molecular_weight : Float, density : LinearProperty, viscosity : LinearProperty, heat_capacity : LinearProperty, vapor_pressure : AntoineCorrelation) -> ChemicalPropertySetfn component_recovery(feed : StreamInventory, product : StreamInventory, component : String) -> Floatfn compressor_design(suction_pressure : Float, discharge_pressure : Float, inlet_temperature : Float, flow_rate : Float, efficiency : Float, gas_constant : Float, heat_capacity_ratio : Float) -> CompressorDesignfn conduction_resistance(thickness_m : Float, conductivity_w_mk : Float, area_m2 : Float) -> Floatfn controller(tag : String, setpoint : Float, process_value : Float, output : Float, gain : Float, integral : Float, mode : ControllerMode) -> Controllerfn convection_resistance(coefficient_w_m2k : Float, area_m2 : Float) -> Floatfn cstr_design(volume_m3 : Float, flow_m3_h : Float, rate_mol_m3_h : Float, feed_mol_m3 : Float) -> CstrDesignfn data_field(name : String, value : String?, expected_unit : String?, policy : MissingPolicy) -> DataFieldfn data_quality(name : String, completeness : Float, validity : Float, timeliness : Float, consistency : Float) -> DataQualityfn delimited_table(headers : Array[String], rows : Array[DelimitedRow], delimiter : String) -> DelimitedTablefn diagnostic(code : String, severity : DiagnosticSeverity, path : String, message : String, remediation : String) -> Diagnosticfn distillation_case(feed_rate : Float, feed_fraction : Float, distillate_rate : Float, distillate_fraction : Float, bottoms_rate : Float, bottoms_fraction : Float, reflux_ratio : Float, stages : Int) -> DistillationCasefn earliest_available(calendar : ResourceCalendar, duration_hours : Float, from_hour : Float) -> Floatfn elasticity(input_before : Float, input_after : Float, output_before : Float, output_after : Float) -> Floatfn emission_factor(pollutant : String, factor : Float, unit : String, source : String) -> EmissionFactorfn energy_cost(energy : Float, rate : Float, demand_charge : Float, fixed_charge : Float) -> EnergyCostfn environmental_inventory(emissions : Array[Emission], period : String, facility : String) -> EnvironmentalInventoryfn exchanger_area(duty_kw : Float, coefficient_kw_m2k : Float, driving_force_k : Float, correction : Float) -> Floatfn exchanger_design(area : Float, overall_u : Float, hot_inlet : Float, hot_outlet : Float, cold_inlet : Float, cold_outlet : Float, hot_capacity : Float, cold_capacity : Float) -> ExchangerDesignfn first_order_conversion(rate_constant : Float, residence_hours : Float) -> Floatfn hazard(id : String, node : String, deviation : String, cause : String, consequence : String, likelihood : RiskLikelihood, severity : RiskSeverity, safeguards : Array[String]) -> Hazardfn heat_balance(inlet_kw : Float, reaction_kw : Float, utility_kw : Float, outlet_kw : Float) -> Floatfn heat_duty(mass_flow_kg_h : Float, heat_capacity_kj_kgk : Float, delta_temperature_k : Float) -> Floatfn heat_duty_with_phase(mass_flow_kg_h : Float, heat_capacity_kj_kgk : Float, delta_temperature_k : Float, latent_kj_kg : Float) -> Floatfn heat_exchanger_case(hot_inlet : Float, hot_outlet : Float, cold_inlet : Float, cold_outlet : Float, hot_capacity_rate : Float, cold_capacity_rate : Float, area : Float, overall_u : Float) -> HeatExchangerCasefn heat_exchanger_check(area_m2 : Float, required_m2 : Float, duty_kw : Float, pressure_drop_bar : Float, max_pressure_drop_bar : Float) -> HeatExchangerCheckfn import_issue(line_number : Int, field : String, message : String, severity : String) -> ImportIssuefn insulation_design(thickness_m : Float, conductivity_w_mk : Float, area_m2 : Float, ambient_c : Float, process_c : Float) -> InsulationDesignfn interpolate_linear(x : Float, x_one : Float, y_one : Float, x_two : Float, y_two : Float) -> Floatfn latent_duty(mass_flow : Float, latent_heat : Float, vapor_fraction : Float) -> Floatfn linear_property(reference : Float, slope : Float, reference_temperature : Float) -> LinearPropertyfn log_mean_temperature_difference(delta_one : Float, delta_two : Float) -> Floatfn maintenance_task(asset : String, task : String, interval_hours : Float, operating_hours : Float, critical : Bool) -> MaintenanceTaskfn maintenance_window(asset : String, due_hour : Float, duration_hours : Float, critical : Bool, completed : Bool) -> MaintenanceWindowfn mass_transfer_coefficient(diffusivity_m2_s : Float, film_thickness_m : Float) -> Floatfn material_property(name : String, molecular_weight : Float, density : Float, heat_capacity : Float, boiling_point : Float, safety_limit : Float) -> MaterialPropertyfn mixture_property(component : String, mole_fraction : Float, property : ChemicalPropertySet) -> MixturePropertyfn optimization_report(candidates : Array[Candidate], constraints : Array[Constraint]) -> ReportSectionfn packed_column(diameter_m : Float, packing_height_m : Float, packing_factor : Float, gas_velocity_m_s : Float, flooding_velocity_m_s : Float) -> PackedColumnfn penalized_best(candidates : Array[Candidate], constraints : Array[Constraint], penalty : Float) -> Candidate?fn pfr_design(volume_m3 : Float, flow_m3_h : Float, inlet_mol_m3 : Float, rate_mol_m3_h : Float) -> PfrDesignfn pipe_design(length : Float, diameter : Float, roughness : Float, flow_rate : Float, density : Float, viscosity : Float, allowable_drop : Float) -> PipeDesignfn prandtl_number(heat_capacity : Float, viscosity : Float, conductivity : Float) -> Floatfn pressure_drop_case(length : Float, diameter : Float, velocity : Float, density : Float, viscosity : Float, roughness : Float, fittings_k : Float) -> PressureDropCasefn production_economics(revenue : Float, operating_cost : Float, capital_cost : Float, production : Float, lifetime : Int) -> ProductionEconomicsfn property_reynolds_number(density : Float, velocity : Float, diameter : Float, viscosity : Float) -> Floatfn pump_case(flow_rate : Float, differential_pressure : Float, efficiency : Float, fluid_density : Float, installed_power : Float) -> PumpCasefn radiation_coefficient(emissivity : Float, hot_k : Float, cold_k : Float) -> Floatfn reaction_order(order_a : Float, order_b : Float, stoich_a : Float, stoich_b : Float) -> ReactionOrderfn reaction_path(name : String, conversion : Float, selectivity : Float, yield_fraction : Float) -> ReactionPathfn reactor_case(name : String, feed : Float, product : Float, byproduct : Float, residence_time : Float, temperature : Float, pressure : Float) -> ReactorCasefn reactor_gate(conversion : Float, minimum : Float, temperature_c : Float, maximum_c : Float) -> Boolfn report(metadata : ReportMetadata, summary : String, assumptions : Array[Assumption], inputs : Array[InputValue], formulas : Array[FormulaNote], results : Array[ResultValue], warnings : Array[WarningNote], sources : Array[SourceRef], sections : Array[ReportSection], tags : Array[String]) -> ChemReportfn resource_calendar(name : String, capacity_hours : Float, blocks : Array[ScheduleBlock]) -> ResourceCalendarfn reynolds_number(density : Float, velocity : Float, diameter : Float, viscosity : Float) -> Floatfn rule(code : String, operator : RuleOperator, field : String, limit : Float, severity : RuleSeverity) -> Rulefn safeguard(name : String, kind : String, independent : Bool, test_interval_hours : Float, enabled : Bool) -> Safeguardfn safety_review(name : String, measured : Float, design_limit : Float, warning_fraction : Float, unit : String) -> SafetyReviewfn scenario_point(name : String, input : Float, output : Float, score : Float, status : ResultStatus, note : String) -> ScenarioPointfn scenario_series(name : String, points : Array[ScenarioPoint], input_unit : String, output_unit : String) -> ScenarioSeriesfn schedule_block(id : String, asset : String, kind : ScheduleKind, start_hour : Float, duration_hours : Float, priority : Int, operator : String) -> ScheduleBlockfn sensitivity(base : Float, delta : Float, response_base : Float, response_delta : Float) -> Floatfn sherwood_number(coefficient_m_s : Float, length_m : Float, diffusivity_m2_s : Float) -> Floatfn stream(name : String, direction : StreamDirection, components : Array[ComponentFlow]) -> ProcessStreamfn tank_design(diameter : Float, height : Float, working_level : Float, dead_volume : Float, overflow_level : Float) -> TankDesignfn thermal_duty(mass_flow : Float, heat_capacity : Float, inlet : Float, outlet : Float) -> Floatfn total_heat_duty(sensible : Float, latent : Float, reaction : Float) -> Floatfn transfer_duty(flow_mol_h : Float, inlet_fraction : Float, outlet_fraction : Float) -> Floatfn tray_stage(number : Int, efficiency : Float, liquid_flow : Float, vapor_flow : Float) -> TrayStagefn valve_design(flow_coefficient : Float, pressure_drop : Float, density : Float, opening : Float, maximum_flow : Float) -> ValveDesignfn vessel_design(volume : Float, liquid_volume : Float, design_pressure : Float, allowable_pressure : Float, design_temperature : Float, allowable_temperature : Float) -> VesselDesignfn workflow_step(name : String, owner : String, status : WorkflowStatus, note : String) -> WorkflowStepA MoonBit-native report layer for chemical engineering calculations.