Examples
This page provides practical examples demonstrating the various capabilities of OpenSEFA.jl.
Basic Example: Seven Flows Problem
The seven flows problem from [C16] is a canonical example in data reconciliation for material flow analysis.
using OpenSEFA
# Load the problem definition
include(joinpath(MODELS_PATH, "seven_flows.jl"))
rec = seven_flows_cencic_2012()
# Solve with default settings
sol = solve(rec)
# Inspect the solution
println("Objective value: ", sol.objective_value)
println("Max constraint violation: ", sol.score.residual)Using Presolve
The presolve functionality applies symbolic and numeric simplifications to reduce problem size:
using OpenSEFA
include(joinpath(MODELS_PATH, "seven_flows.jl"))
rec = seven_flows_cencic_2012()
# Apply presolve to simplify the problem
pre = unwrap(presolve(rec))
# The presolved problem may have fewer variables/equations
println("Original problem: ", rec)
println("Presolved problem: ", pre.pre)
# Solve the presolved problem
sol = solve(pre.pre)The default solver (DefaultSolver) automatically applies presolve internally. Use explicit presolve when you want to inspect the simplified problem structure.
Custom Solver Backends
OpenSEFA.jl supports multiple solver backends through the JuMP interface.
Using the Default Solver
The default solver applies three steps:
- Presolve: Simplify the problem through structural reductions. If fully solved, return immediately.
- Starting values: Compute initial values for unmeasured variables using
NonlinearSolve. If the problem is fully determined, use these as the final solution. - Optimize: Solve the full weighted least-squares problem using the JuMP framework (with
Ipoptas default solver). Starting values from step 2 are used as a warm start when available.
using OpenSEFA
include(joinpath(MODELS_PATH, "seven_flows.jl"))
rec = seven_flows_cencic_2012()
# Explicit use of DefaultSolver (equivalent to solve(rec))
sol = solve(rec, DefaultSolver())Using Alternative NLP Solvers
You can use any JuMP-compatible solver:
using OpenSEFA
using MadNLP
include(joinpath(MODELS_PATH, "seven_flows.jl"))
rec = seven_flows_cencic_2012()
# Solve using MadNLP instead of Ipopt
sol = solve(rec, JuMPSolver(optimizer=MadNLP.Optimizer))Other compatible solvers include:
Ipopt.Optimizer(default)MadNLP.Optimizer- Any other JuMP-compatible NLP solver
Loading from STAN Software
OpenSEFA.jl can import models created in STAN software.
Example: Loading STAN Trace File
using OpenSEFA
# Path to model directory containing trace.txt
path = joinpath(MODELS_PATH, "Cencic_2016_STAN")
# Parse the STAN trace file
strace = parse(STANTrace, path)
# Convert to ReconciliationProblem
rec = convert(ReconciliationProblem, strace)
# Solve the problem
sol = solve(rec)
println("Solution for Seven Flows model:")
println(" Objective value: ", sol.objective_value)
println(" Variables: ", length(sol.variables_value))To generate a trace.txt file from STAN:
- Open your model in STAN
- Run the solver with "verbose equations output" enabled
- Save the entire trace console output to
trace.txtin your model directory
Example: Loading STAN Data (CSV)
using OpenSEFA
# Path to model directory containing CSV data files
path = joinpath(MODELS_PATH, "Cencic_2016_STAN")
# Load data from STAN CSV exports
sdata = load_stan_data(path)
# Inspect the loaded data
println("Flows data: ", sdata.flows)
println("Variables data: ", sdata.flowvalues)Working with JSON Models
Models can be defined in JSON format for easy integration with web applications:
using OpenSEFA
# Load a JSON model
json_path = joinpath(MODELS_PATH, "seven_flows.json")
model = load_model(json_path)Programmatic Problem Construction
You can build problems programmatically using Julia data structures:
using OpenSEFA
# Define variables
variables = [
MeasuredVariable(name = "F1", value = 1.0, uncertainty = 0.1),
UnmeasuredVariable(name = "F2"),
MeasuredVariable(name = "F3", value = 2.0, uncertainty = 0.3)
]
# Define equations (mass balance: F1 + F3 - F2 = 0)
equations = [
Equation(
ConstantTerm(0.0),
[LinearTerm("F1", 1.0), LinearTerm("F3", 1.0), LinearTerm("F2", -1.0)],
BilinearTerm[]
)
]
# Create the problem and add variables/equations
rec = ReconciliationProblem(name = "Simple Example")
add_variable!(rec, variables)
add_equation!(rec, equations)
# Solve
sol = solve(rec)Equations can alternatively be parsed from a string:
using OpenSEFA
# Define equation F1 + F3 - F2 = 0
eq = parse_equation("F1 + F3 - F2 = 0")Inspecting Solutions
The solution object provides various methods to inspect results:
using OpenSEFA
include(joinpath(MODELS_PATH, "seven_flows.jl"))
rec = seven_flows_cencic_2012()
sol = solve(rec)
# Access solution values
println("Reconciled variable values:")
display(sol.variables_value)
# Check solution quality
println("\nSolution quality:")
println(" Objective: ", sol.objective_value)
display(sol.score)
# Check if solution is acceptable
if sol.score.residual < 1e-6
println(" ✓ Solution satisfies constraints")
else
println(" ✗ Warning: Large constraint violations")
endError Handling and Validation
Handle solver failures gracefully:
using OpenSEFA
rec = # ... your problem definition ...
try
sol = solve(rec)
# Validate solution
if sol.objective_value > 1000.0
@warn "Large objective value, solution may be poor"
end
if sol.score.residual > 1e-4
@warn "Constraint violations detected"
end
catch e
@error "Solver failed" exception=e
# Fall back to alternative solver or settings
sol = solve(rec, JuMPSolver(optimizer=AlternativeSolver.Optimizer))
endPerformance Tips
For large-scale problems:
- Use presolve to reduce problem size
- Choose appropriate solvers - Ipopt is generally robust, MadNLP may be faster for some problems
- Provide good initial guesses when constructing variables
- Monitor solver output to diagnose convergence issues
using OpenSEFA
using Ipopt
# For large problems, explicit presolve can help
rec = # ... large problem ...
presolve_result = presolve(rec)
pre = unwrap(presolve_result).pre
# Solve with custom tolerances (if using JuMP interface)
sol = solve(pre, JuMPSolver(
optimizer = Ipopt.Optimizer,
tol = 1e-6,
max_iter = 1000
))Next Steps
- Explore the HTTP API for web-based integration
- Check the API Reference for detailed function documentation
- Review the References for theoretical background