forked from tmbb/dantzig
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblending_problem.exs
More file actions
251 lines (205 loc) · 8.39 KB
/
Copy pathblending_problem.exs
File metadata and controls
251 lines (205 loc) · 8.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
#!/usr/bin/env elixir
# Blending Problem Example
#
# BUSINESS CONTEXT:
# A food manufacturer needs to create a blended product (e.g., animal feed, fertilizer, or food mix)
# by combining multiple raw materials. Each material has different costs and quality properties.
# The goal is to minimize total cost while ensuring the final blend meets quality specifications
# and usage limits for each material.
#
# This is a classic blending optimization problem commonly found in agriculture, chemical processing,
# and manufacturing industries.
#
# MATHEMATICAL FORMULATION:
# Variables: fraction_m = fraction of material m in the final blend (0.1 ≤ fraction_m ≤ 0.8)
# Constraints:
# Σ fraction_m = 1 (blend composition)
# Σ (fraction_m × quality1_m) ≥ 0.75 (minimum quality1 requirement)
# Σ (fraction_m × quality2_m) ≤ 0.25 (maximum quality2 requirement)
# Objective: Minimize Σ (fraction_m × cost_m)
#
# DSL SYNTAX HIGHLIGHTS:
# - Variable creation with bounds: variables(name, generators, type, min_bound: val, max_bound: val)
# - Sum expressions in constraints: sum(for m <- materials, do: expr)
# - Weighted sum constraints for quality requirements
# - Case expressions for conditional data access (until model parameters are implemented)
#
# GOTCHAS:
# - Variable names are auto-generated as "fraction_Material1", "fraction_Material2", etc.
# - Complex expressions require case statements when model parameters aren't available
# - Sum expressions require explicit comprehension: sum(for m <- materials, do: ...)
# - Bounds are enforced per variable, not globally
# - Model parameters feature is planned but not yet implemented
require Dantzig.Problem, as: Problem
require Dantzig.Problem.DSL, as: DSL
# Define the problem data
materials = ["Material1", "Material2", "Material3"]
# Cost per unit of each material
cost_per_unit = %{
"Material1" => 5.0,
"Material2" => 8.0,
"Material3" => 6.0
}
# Quality properties of each material
# Quality1: Some property (e.g., protein content)
# Quality2: Another property (e.g., fat content)
quality_properties = %{
"Material1" => %{quality1: 0.8, quality2: 0.2},
"Material2" => %{quality1: 0.6, quality2: 0.4},
"Material3" => %{quality1: 0.9, quality2: 0.1}
}
# Quality requirements for the final blend
# We need quality1 >= 0.75 and quality2 <= 0.25
min_quality1 = 0.75
max_quality2 = 0.25
# Minimum and maximum usage for each material (as percentages)
# 10% minimum
# 80% maximum
IO.puts("Blending Problem")
IO.puts("================")
IO.puts("Materials: #{Enum.join(materials, ", ")}")
IO.puts("")
IO.puts("Cost per unit:")
Enum.each(materials, fn material ->
IO.puts(" #{material}: $#{cost_per_unit[material]}")
end)
IO.puts("")
IO.puts("Quality properties:")
Enum.each(materials, fn material ->
props = quality_properties[material]
IO.puts(" #{material}: Quality1=#{props.quality1}, Quality2=#{props.quality2}")
end)
IO.puts("")
IO.puts("Quality requirements:")
IO.puts(" Quality1 >= #{min_quality1}")
IO.puts(" Quality2 <= #{max_quality2}")
IO.puts(" Usage limits: 10.0% - 80.0% per material")
IO.puts("")
# Create the optimization problem
problem =
Problem.define do
new(
name: "Blending Problem",
description: "Minimize cost while meeting quality specifications and usage limits"
)
# Decision variables: fraction_m = fraction of material m in the blend
variables("fraction_Material1", :continuous, "Fraction of Material1 in blend",
min_bound: 0.1,
max_bound: 0.8
)
variables("fraction_Material2", :continuous, "Fraction of Material2 in blend",
min_bound: 0.1,
max_bound: 0.8
)
variables("fraction_Material3", :continuous, "Fraction of Material3 in blend",
min_bound: 0.1,
max_bound: 0.8
)
# Constraint: fractions must sum to 1 (100% of blend)
constraints(
fraction_Material1 + fraction_Material2 + fraction_Material3 == 1,
"Blend composition constraint"
)
# Quality constraints (hardcoded for now - model parameters not yet implemented)
constraints(
fraction_Material1 * 0.8 + fraction_Material2 * 0.6 + fraction_Material3 * 0.9 >=
min_quality1,
"Minimum quality1 requirement"
)
constraints(
fraction_Material1 * 0.2 + fraction_Material2 * 0.4 + fraction_Material3 * 0.1 <=
max_quality2,
"Maximum quality2 requirement"
)
# Objective: minimize total cost
objective(
fraction_Material1 * 5.0 + fraction_Material2 * 8.0 + fraction_Material3 * 6.0,
direction: :minimize
)
end
IO.puts("Solving the blending problem...")
{solution, objective_value} = Problem.solve(problem, solver: :highs, print_optimizer_input: true)
IO.puts("Solution:")
IO.puts("=========")
IO.puts("Objective value (total cost): $#{Float.round(objective_value * 1.0, 2)}")
IO.puts("")
IO.puts("Optimal Blend Composition:")
# Display the blend composition
Enum.each(materials, fn material ->
var_name = "fraction_#{material}"
fraction = solution.variables[var_name]
material_cost = fraction * cost_per_unit[material]
IO.puts(
" #{material}: #{Float.round(fraction * 100.0, 2)}% (cost contribution: $#{Float.round(material_cost, 2)})"
)
end)
IO.puts("")
IO.puts("Summary:")
IO.puts(" Total cost: $#{Float.round(objective_value * 1.0, 2)}")
IO.puts(" Blend composition: 100% (all fractions sum to 1.0)")
IO.puts(" All quality and usage constraints satisfied")
# Validate that all constraints are satisfied
IO.puts("")
IO.puts("Constraint Validation:")
# Check blend composition (sum = 1)
total_fraction =
solution.variables["fraction_Material1"] + solution.variables["fraction_Material2"] +
solution.variables["fraction_Material3"]
blend_ok = abs(total_fraction - 1.0) < 0.001
total_fraction_float = if is_integer(total_fraction), do: :erlang.float(total_fraction), else: total_fraction
IO.puts(
" Blend composition (sum = 1.0): #{Float.round(total_fraction_float, 4)} #{if blend_ok, do: "✅", else: "❌"}"
)
# Check quality constraints
quality1_achieved =
solution.variables["fraction_Material1"] * 0.8 + solution.variables["fraction_Material2"] * 0.6 +
solution.variables["fraction_Material3"] * 0.9
quality2_achieved =
solution.variables["fraction_Material1"] * 0.2 + solution.variables["fraction_Material2"] * 0.4 +
solution.variables["fraction_Material3"] * 0.1
quality1_ok = quality1_achieved >= min_quality1 - 0.001
quality2_ok = quality2_achieved <= max_quality2 + 0.001
IO.puts(
" Quality1 (≥ #{min_quality1}): #{Float.round(quality1_achieved, 4)} #{if quality1_ok, do: "✅", else: "❌"}"
)
IO.puts(
" Quality2 (≤ #{max_quality2}): #{Float.round(quality2_achieved, 4)} #{if quality2_ok, do: "✅", else: "❌"}"
)
# Check fraction bounds (10% - 80%)
bounds_ok =
solution.variables["fraction_Material1"] >= 0.1 - 0.001 and
solution.variables["fraction_Material1"] <= 0.8 + 0.001 and
solution.variables["fraction_Material2"] >= 0.1 - 0.001 and
solution.variables["fraction_Material2"] <= 0.8 + 0.001 and
solution.variables["fraction_Material3"] >= 0.1 - 0.001 and
solution.variables["fraction_Material3"] <= 0.8 + 0.001
IO.puts(" Fraction bounds (10%-80%): #{if bounds_ok, do: "✅ All OK", else: "❌ VIOLATED"}")
all_ok = blend_ok and quality1_ok and quality2_ok and bounds_ok
if not all_ok do
IO.puts("ERROR: Some constraints violated!")
System.halt(1)
end
# Display detailed quality breakdown
IO.puts("")
IO.puts("Quality Contribution by Material:")
Enum.each(materials, fn material ->
var_name = "fraction_#{material}"
fraction = solution.variables[var_name]
props = quality_properties[material]
quality1_contrib = fraction * props.quality1
quality2_contrib = fraction * props.quality2
IO.puts(
" #{material}: Q1=#{Float.round(quality1_contrib * 1.0, 4)}, Q2=#{Float.round(quality2_contrib * 1.0, 4)}"
)
end)
IO.puts("")
IO.puts("LEARNING INSIGHTS:")
IO.puts("==================")
IO.puts("• Blending problems optimize resource allocation with quality constraints")
IO.puts("• Linear programming handles weighted sums efficiently for quality calculations")
IO.puts("• Model parameters enable clean separation of data from optimization logic")
IO.puts("• Variable bounds prevent unrealistic solutions (e.g., 0% or 100% usage)")
IO.puts("• Sum comprehensions create complex constraints from simple expressions")
IO.puts("• Real-world applications: feed mixing, chemical blending, portfolio optimization")
IO.puts("")
IO.puts("✅ Blending problem solved successfully!")