/
demand-of-your-art.jl
2348 lines (1952 loc) · 76.5 KB
/
demand-of-your-art.jl
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
### A Pluto.jl notebook ###
# v0.19.25
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
quote
local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)
el
end
end
# ╔═╡ d9e64c42-cef6-444d-a5e4-d266488bbd08
using PrettyTables, JuMP, Cbc, PlutoUI, Plots, LinearAlgebra, StatsPlots, Ipopt, SCIP
# ╔═╡ 1a8ed181-8119-4f49-812a-5bcfc3151722
using LaTeXStrings
# ╔═╡ 12385e30-d544-4fd8-aab9-7f6fadfb5ccd
md"""
# Demand of your art
As we saw on [last episode](https://www.youtube.com/watch?v=IOUi1juD5HQ), Javier is creating and selling his art on the beach.
However, we assumed that everything that Javier builds will be sold, which is unrealistic.
Now, we have to deal with a more realistic scenario, in which the demand for Javier's product is not infinite.
We will still need assumptions, but the model is a bit more realistic.
"""
# ╔═╡ c775b393-844e-42a4-9a18-add5dc3ce911
md"""
## Strategy 1: Sell excess inventory at a discount
The first strategy is simple.
If there is no more demand for the products, Javier sells them at a discounted price.
For that, we need to assume that
- Javier knows the demand for each of their products under the price that he decided to sell them;
- Javier discounted price is low enough to sell all of the remaining products.
Below you can see the data.
Notice the new columns **discounted price** and **demand**.
"""
# ╔═╡ 4b1f59f4-1ad3-4bb8-8fc5-ba0578fd4de6
begin
materials = ["beads", "string", "wire"]
products = ["bracelet", "necklace", "earring"]
material_per_product = [
15 0.6 0.15;
80 2.5 0.2;
4 0.1 0.15;
]
selling_price = [25.0; 45.0; 10]
discounted_selling_price = [8.0; 30.0; 3.5]
hours_to_assemble = [2.5; 4; 1.5]
demand = [4, 2, 3]
units = " (" .* ["u", "m", "m", "€", "€", "h", "u"] .* ")"
pretty_table(
HTML,
[material_per_product selling_price discounted_selling_price hours_to_assemble demand],
header=[materials; "price"; "discounted price"; "hours"; "demand"] .* units,
row_labels=products,
)
end
# ╔═╡ d00174ed-45d7-4a1b-8b5a-4c4c22e2045a
begin
material_cost = [0.25; 0.70; 1.5]
pretty_table(
HTML,
material_cost',
header=materials .* units[1:3],
row_labels=["cost (€)"],
)
end
# ╔═╡ c44623d4-b378-4250-bd6a-20d5525ad315
md"""
## Modeling
Our new model is pretty much the same as before, but I will bring the new parts to your attention.
### How to model discounted price
(see also piece-wise concave linear objective)
Let's consider only the bracelet: selling price €25 up to 4 units and €8 after that.
One way of describing our objective is by defining the nonlinear function $\text{revenue}(q)$:
"""
# ╔═╡ e1c97f9e-4504-4265-97df-c340ff955666
md"""
$\text{revenue}(q) = \left\{\begin{array}{cc}
25q, & 0 \leq q \leq 4, \\
25\times 4 + (q - 4)\times 8, & q > 4.
\end{array}\right.$
"""
# ╔═╡ f4bfb073-e33d-4cb1-957b-f90df7d9d8ad
let
c1 = selling_price[1]
c2 = discounted_selling_price[1]
x1 = demand[1]
x2 = 10
plot(
[0, x1, x2],
[0, c1 * x1, c1 * x1 + (x2 - x1) * c2],
lab = "",
m = (2,:lightblue),
)
xlabel!("Quantity")
ylabel!("Revenue")
png("revenue-function")
plot!()
end
# ╔═╡ cdec7db4-75db-4009-86e8-695c9dc1a6c3
md"""
This is not linear, though, so to maximize this function we need to some modeling magic, and in this case there is a very simple approach.
First, we split the quantity decision variable $q$ into two parts:
- Quantity under demand: $\underline{q}$
- Quantity over demand: $\overline{q}$
Then, the revenue function can be expressed as
$25\underline{q} + 8\overline{q} \quad \text{subject to} \quad \underline{q} \leq 4, \ \overline{q} \geq 0$
And whenever cost is not important, use $\underline{q} + \overline{q}$ instead of $q$.
We can, to improve readability, create that as an expression $q = \underline{q} + \overline{q}$.
It might not be clear at first why this works, since $q = \underline{q} + \overline{q}$ does not imply that we are selling **first** the normal priced items.
The reason that it works is that we are maximizing the revenue.
This means that if you have to write $7 = \underline{q} + \overline{q}$ to maximize revenue, one would prefer $\underline{q} = 4$ and $\overline{q} = 3$.
Notice that the new constraints $\underline{q} \leq 4$ and $\overline{q} \geq 0$ are necessary.
"""
# ╔═╡ e8d3422f-4720-4c9c-ad2b-9fc1a96fc63f
md"""
production = $(@bind ui_prod3d Slider(0:8, show_value=true)) $br
θ, ϕ = $(@bind ui_θ Slider(0:5:90, default=20)), $(@bind ui_ϕ Slider(0:5:90, default=20))
"""
# ╔═╡ 6eaab6b8-7541-44db-bab6-632009145a0a
let
prod = ui_prod3d
c1 = selling_price[1]
c2 = discounted_selling_price[1]
x1 = demand[1]
x2 = 10
plt = plot(layout=grid(1, 2), size=(800, 500))
f(x, y) = c1 * x + c2 * y
contourf!(
plt[1],
range(0, x1, length=5),
range(0, x2 - x1, length=5),
f,
lab = "",
lw=0.2,
m = (2,:lightblue),
axis_ratio = :equal,
)
surface!(
plt[2],
range(0, x1, length=5),
range(0, x2 - x1, length=5),
f,
lab = "",
m = (2,:lightblue),
camera = (ui_θ, ui_ϕ),
colorbar = false,
)
X = min.(x1, prod:-1:0)
Y = 0:prod
Z = f.(X, Y)
plot!(plt[1], X, Y, c=:lightblue, lab="", m=(3,:lightblue,stroke(1,:blue)))
plot!(plt[2], X, Y, Z, c=:lightblue, lab="", m=(3,:lightblue,stroke(1,:blue)))
# end
xlims!(-0.2, x1 + 0.2)
ylims!(-0.2, x2 - x1 + 0.2)
zlims!(plt[2], -0.2, f(x1, x2 - x1) + 0.2)
xlabel!(plt[1], "Normal production")
ylabel!(plt[1], "Extra production")
end
# ╔═╡ 690b0069-f041-462c-b564-638506ff2346
md"""
### Model
**Sets**:
- Products: $p \in \mathcal{P}$
- Materials: $m \in \mathcal{M}$
"""
# ╔═╡ 3e0cfd88-0848-4555-943d-0a8e716b1928
md"""
**Parameters**:
| Name | Unit | Identifier | Set |
|:--|:--|:--|:--|
| Time availability | h | $\text{time\_available}$ | |
| Selling price of $p$ | € / unit | $\text{selling\_price}_p$ | $p \in \mathcal{P}$ |
| **(New) Discounted price of $p$** | € / unit | $\text{discounted\_selling\_price}_p$ | $p \in \mathcal{P}$ |
| **(New) Demand for product $p$** | unit | $\text{demand}_p$ | $p \in \mathcal{P}$ |
| Hours to assemble product $p$ | $h$ / unit | $\text{assemble\_time}_{p}$ | $p \in \mathcal{P}$ |
| Material $m$ cost | € / [$m$] | $\text{material\_cost}_m$ | $m \in \mathcal{M}$ |
| Amount of $m$ per unit of $p$ | [$m$] / unit | $\text{mat\_per\_prod}_{p,m}$ | $p \in \mathcal{P}, m \in \mathcal{M}$ |
"""
# ╔═╡ 5fca3abb-6ace-4ee3-b8a3-ae3d40355493
md"""
**Variables**:
As mentioned, the production variable is split into two parts, one to possibly satisfy the demand, and one for extra products sold.
- Amount of product $p$ assembled and sold at full price (unit): $\text{prod\_normal}_p, \quad p \in \mathcal{P}$
- Amount of product $p$ assembled and sold at discount (unit): $\text{prod\_extra}_{p}, \quad p \in \mathcal{P}$
"""
# ╔═╡ 5112c1c4-4ade-47eb-b17d-ddfee5ceb923
md"""
**Expressions**:
As mentioned before, let's create a helper expression for the total amount of products produced.
This essentially allows us to reuse all other expressions and constraints.
- Amount produced and sold of product $p$:
$\displaystyle \text{prod}_p = \text{prod\_normal}_{p} + \text{prod\_extra}_{p}, \quad p \in \mathcal{P}$
- Revenue:
$\begin{align}
\text{revenue} = & \sum_{p \in \mathcal{P}} \bigg( \text{selling\_price}_p \times \text{prod\_normal}_{p} + \\
& \text{discounted\_selling\_price}_p \times \text{prod\_extra}_{p}
\bigg)
\end{align}$
- Total Used Material:
$\displaystyle \text{total\_used\_material}_m = \sum_{p \in \mathcal{P}} \text{mat\_per\_prod}_{p,m} \times \text{prod}_p, \quad m \in \mathcal{M}$
- Total Material Cost:
$\displaystyle \text{total\_material\_cost} = \sum_{m \in \mathcal{M}} \text{total\_used\_mat}_m \times \text{material\_cost}_m, \quad m \in \mathcal{M}$
- Time expenditure:
$\text{time\_spent} = \displaystyle \sum_{p \in \mathcal{P}} \text{assemble\_time}_{p} \times \text{prod}_p$
"""
# ╔═╡ 74b99316-b892-4682-affd-b6f060e976dd
md"""
**Objective**:
- Maximize profit:
$\text{maximize} \quad \text{revenue} - \text{total\_material\_cost}$
"""
# ╔═╡ 22e49663-e352-4b18-b4eb-04f04d8eb99b
md"""
**Constraints**:
Now, to finalize, we have the extra constraints mentioned before.
- Production under demand:
$\text{prod\_normal}_{p} \leq \text{demand}_p, \quad p \in \mathcal{P}$
- Nonnegativity:
$\text{prod\_normal}_{p}, \ \text{prod\_extra}_{p} \geq 0$
- Integer production:
$\text{prod\_normal}_{p}, \ \text{prod\_extra}_{p} \in \mathbb{Z}$
- Time Availability:
$\text{spent\_time} \leq \text{time\_available}$
"""
# ╔═╡ 9c6136a1-e603-47c1-9df6-2445fcba3933
begin
# using JuMP, Cbc
function optimize_production(time_availability)
model = Model(Cbc.Optimizer)
set_attribute(model, "logLevel", 0)
num_products = length(products)
num_materials = length(materials)
@variable(model,
0 ≤ prod_normal[p=1:num_products] ≤ demand[p],
Int
)
@variable(model,
prod_extra[p=1:num_products] ≥ 0,
Int
)
prod = prod_normal + prod_extra
@expression(model,
total_used_material[m=1:num_materials],
sum(
material_per_product[p, m] * prod[p]
for p in 1:num_products
)
)
total_mat_cost = sum(total_used_material .* material_cost)
revenue = sum(prod_normal .* selling_price + prod_extra .* discounted_selling_price)
profit = revenue - total_mat_cost
time_expenditure = sum(hours_to_assemble .* prod)
@objective(model, Max, profit)
@constraint(model, time_expenditure ≤ time_availability)
optimize!(model)
return Dict(
:prod_normal => value.(prod_normal),
:prod_extra => value.(prod_extra),
:objective => objective_value(model),
:model => model,
:revenue => value(revenue),
:profit => value(profit),
)
end
end
# ╔═╡ ea2a69b8-c883-444e-b09b-9890c551c64d
md"""
Time Availability = $(@bind slider_time_availability Slider(0:40, show_value=true))
"""
# ╔═╡ bad1999d-c085-433c-a42e-d309ae2ae624
let
output = optimize_production(slider_time_availability)
prod_normal = output[:prod_normal]
prod_extra = output[:prod_extra]
pretty_table(
HTML,
[prod_normal prod_extra],
row_labels=products,
header=["normal production"; "extra production"],
)
end
# ╔═╡ f99652cb-bc7e-4400-98bd-3373de0e978b
let
output = optimize_production(slider_time_availability)
prod_normal = output[:prod_normal]
prod_extra = output[:prod_extra]
groupedbar(
hcat(sum.([prod_extra, prod_normal], dims=2)...),
bar_position = :stack,
bar_width = 0.5,
xticks = (1:length(products), string.(products)),
label = ["extra" "normal"],
)
ylims!(0, 7)
end
# ╔═╡ 6991aec5-0d20-4ef3-a85a-668fb2a24334
let
profits = Float64[]
slacks = Float64[]
for time_availability = 0:40
output = optimize_production(time_availability)
push!(profits, output[:profit])
end
plt = plot(size=(600, 600))
plot!(
plt,
profits,
lab="profits",
m=(3, :lightblue, stroke(1, :blue)),
c=:blue,
)
xlabel!("Time availability")
ylabel!("€")
png("revenue-strategy1")
plot!()
end
# ╔═╡ af603777-9d1b-4382-b62f-5d997211c500
md"""
## Strategy 2: Demand is a function of price
Our second approach is to consider that the demand for the products depends on their price and to add this relation into the model.
In other words, we are not only deciding how many products we will build, we will decide at which price we will sell them.
To do that we have to assume that we know how the demand depends on the price, which is not something trivial to figure out.
For today, let's assume that this dependency will be linear:
$\text{demand} = \text{intercept} + \text{slope} \times \text{price},$
and that we now the intercept and slope values for each product.
"""
# ╔═╡ 1ef83b37-910c-474f-bc20-0298673ae813
md"""
product = $(@bind selected_product Select([j => p for (j, p) in enumerate(products)]))
"""
# ╔═╡ c9164c4a-d962-463a-a3d1-77958a72968e
md"""
Below are the values that we assume represent the demand.
"""
# ╔═╡ fa7064dd-c06d-469e-b8a5-d71d498f872a
begin
demand_slope = -[0.5; 0.4; 2.0]
# L = I + m x = d₀ + m (x - p₀)
# ⇒ I = d₀ - m p₀
demand_intercept = demand - demand_slope .* selling_price
pretty_table(
HTML,
[demand_intercept demand_slope],
row_labels=products,
header=["demand intercept (unit)", "demand slope (unit / €)"]
)
end
# ╔═╡ f8c7d28c-ae76-4f29-8f6a-a0492d8c080c
md"""
price = $(@bind price_slider Slider(0:ceil(Int, selling_price[selected_product] - demand[selected_product] / demand_slope[selected_product]), default=selling_price[selected_product], show_value=true))
"""
# ╔═╡ a755c453-cd1e-4b33-bfa2-28e44c1fba0c
let
d₀ = demand[selected_product]
p₀ = selling_price[selected_product]
α = demand_slope[selected_product]
demand_f(p) = d₀ + (p - p₀) * α
p_max = (α * p₀ - d₀) / α
plt = plot(layout=grid(1,2), size=(800,500))
plot!(plt[1], demand_f, 0, p_max, ylabel="quantity", title="demand", lab="", axis_ratio=:equal)
p = price_slider
d = demand_f(p)
plot!(plt[1], [p, p, 0], [0, d, d], c=:lightblue, l=:dash, fill=true, lab="revenue")
scatter!(plt[1], [p₀], [d₀], lab="original")
title!(plt[1], "price of $(products[selected_product])")
xticks!(plt, 0:5:5 * ceil(Int, p_max / 5))
xlims!(plt, 0, p_max + 1)
ylims!(plt[1], 0, d₀ - α * p₀ + 1)
xlabel!(plt, "price")
prices = range(0, p_max, length=100)
demands = prices .* demand_f.(prices)
plot!(plt[2], prices, demands, lab="revenue")
plot!(plt[2], [p, p], [0, d * p], c=:lightblue, l=:dash, lab="")
scatter!(plt[2], [p], [d * p], c=:red, lab="")
png("demand-given-price$selected_product")
plot!()
end
# ╔═╡ 9287c22d-6261-4160-97c8-8b00a01ff48c
md"""
### Modeling
There are a few more nuanced differences in this model.
**Sets**:
- Products: $p \in \mathcal{P}$
- Materials: $m \in \mathcal{M}$
**Parameters**:
| Name | Unit | Identifier | Set |
|:--|:--|:--|:--|
| Time availability | h | $\text{time\_available}$ | |
| **(new) Demand of product $p$ (intercept)** | unit | $\text{demand\_intercept}_p$ | $p \in \mathcal{P}$ |
| **(new) Demand of product $p$ (slope)** | unit / [€] | $\text{demand\_slope}_p$ | $p \in \mathcal{P}$ |
| Hours to assemble product $p$ | h / unit | $\text{assemble\_time}_p$ | $p \in \mathcal{P}$ |
| Material $m$ cost | € / [$m$] | $\text{material\_cost}_m$ | $m \in \mathcal{M}$ |
| Amount of $m$ per unit of $p$ | [$m$] / unit | $\text{mat\_per\_prod}_{p,m}$ | $p \in \mathcal{P}, m \in \mathcal{M}$ |
"""
# ╔═╡ 36084aee-33b3-4889-bc73-b98ec1348e13
md"""
**Variables**:
- Amount of product $p$ assembled and sold (unit): $\quad \text{prod}_p, \quad p \in \mathcal{P}$
- **(New) Price of product $p$ (€)**: $\quad \text{decided\_price}_p, \quad p \in \mathcal{P}$
"""
# ╔═╡ a8174177-0764-4936-abb9-fc78d369a792
md"""
**Expressions**:
A few things changed here.
First, the demand is an expression now, which we will use in the constraints.
Second, and maybe most important, the revenue is quadratic now.
This by itself is not an issue, but when coupled with the integrality of the variable $\text{prod}_p$, we have a much harder problem on our hands.
- **(New) Demand**:
$\displaystyle \text{demand\_given\_price}_p = \text{demand\_intercept}_p + \text{demand\_slope}_p \times \text{decided\_price}_p, \quad p \in \mathcal{P}$
- Revenue:
$\displaystyle \text{revenue} = \sum_{p \in \mathcal{P}} \text{decided\_price}_p \times \text{prod}_p$
- Total Used Material:
$\displaystyle \text{total\_used\_material}_m = \sum_{p \in \mathcal{P}} \text{mat\_per\_prod}_{p,m} \times \text{prod}_p, \quad m \in \mathcal{M}$
- Total Material Cost:
$\displaystyle \text{total\_material\_cost} = \sum_{m \in \mathcal{M}} \text{total\_used\_material}_m \times \text{material\_cost}_m$
- Time expenditure:
$\text{time\_spent} = \displaystyle \sum_{p \in \mathcal{P}} \text{assemble\_time}_p \times \text{prod}_p$
"""
# ╔═╡ 6f290571-9518-4300-8b0a-f44b71c267c8
md"""
**Objective**:
- Maximize profit:
$\text{maximize} \quad \text{revenue} - \text{total\_material\_cost}$
"""
# ╔═╡ 22b7f8f1-ffb7-44dd-bb58-e35d32baf9df
md"""
**Constraints**:
The new constraint of the model is relating the production to the price via the demand.
Notice that the actual constraint could be written using equality.
However, since the production is an integer, and the price is a floating-point number, it might be that the actual demand value (which should be an integer), is just a little bit off.
Depending on the solver, it might help a lot.
- **(New) Produce what you can sell**:
$\text{prod}_p \leq \text{demand\_given\_price}_p, \quad p \in \mathcal{P}$
- Time Availability:
$\text{spent\_time} \leq \text{time\_available}$
- Non-negativity:
$\text{prod}_p, \ \text{decided\_price}_p \geq 0, \quad p \in \mathcal{P}$
- Integer production:
$\text{prod}_p \in \mathbb{Z}$
"""
# ╔═╡ b3182f7f-2949-4720-b2b9-c0232e0c133f
md"""
## Implementation
Last time we used the Cbc solver to solve our problem.
It had integer variables, but it was otherwise linear.
This time, the objective is quadratic.
Therefore, we need to use a different solver.
SCIP is a good open-source choice.
"""
# ╔═╡ 4c2d14a6-b074-4c9c-885a-106863336e0f
begin
# using JuMP, SCIP
function optimize_production_nonlinear(time_availability)
model = Model(SCIP.Optimizer)
set_attribute(model, "display/verblevel", 0)
set_attribute(model, "limits/gap", 0.01)
num_products = length(products)
num_materials = length(materials)
@variable(model,
prod[p=1:num_products] ≥ 0, Int
)
@variable(model,
decided_price[p=1:num_products] ≥ 0,
)
demand_given_price = demand_intercept + demand_slope .* decided_price
@expression(model,
total_used_material[m=1:num_materials],
sum(
material_per_product[p, m] * prod[p]
for p in 1:num_products
)
)
total_mat_cost = sum(total_used_material .* material_cost)
revenue = sum(
prod[p] * decided_price[p]
for p in 1:num_products
)
profit = revenue - total_mat_cost
time_expenditure = sum(hours_to_assemble .* prod)
@objective(model, Max, profit)
@constraint(model, time_expenditure .≤ time_availability)
@constraint(model,
production_limited_by_demand[p=1:num_products],
prod[p] ≤ demand_given_price[p],
)
optimize!(model)
return Dict(
:prod => value.(prod),
:demand => value.(demand_given_price),
:price => value.(decided_price),
:objective => objective_value(model),
:model => model,
:revenue => value(revenue),
:profit => value(profit),
)
end
end
# ╔═╡ 65604aec-a34d-45e2-a8f2-92a25d91276d
md"""
## Results
"""
# ╔═╡ 7b68ff21-3ba1-4041-a5a9-ad521624a546
md"""
time availability = $(@bind slider_time_availability2 Slider(0:40, show_value=true))
"""
# ╔═╡ 3f0ed7cd-39b6-41a6-8702-95a0fb237065
let
output = optimize_production_nonlinear(slider_time_availability2)
prod = output[:prod]
demand = output[:demand]
price = output[:price]
product_labels = [
products[i] * " $(round(price[i], digits=2))"
for i = 1:3
]
bar(
(1:3) .- 0.2,
prod,
bar_position = :stack,
bar_width = 0.4,
xticks = (1:length(products), product_labels),
label="production",
)
bar!(
(1:3) .+ 0.2,
demand,
bar_position = :stack,
bar_width = 0.4,
xticks = (1:length(products), product_labels),
opacity=0.5,
label="demand",
)
ylims!(0, 7)
end
# ╔═╡ ecf2f51b-4199-48f8-8575-89ce8ce9a4ab
let
for max_t = [40, 80]
profits = Float64[]
slacks = Float64[]
for time_availability = 0:max_t
output = optimize_production_nonlinear(time_availability)
push!(profits, output[:profit])
end
plt = plot(size=(600, 600))
plot!(
plt,
0:max_t,
profits,
lab="profits",
m=(3, :lightblue, stroke(1, :blue)),
c=:blue,
)
xlabel!("Time availability")
ylabel!("€")
png("revenue-strategy2-$max_t")
end
plot!()
end
# ╔═╡ a4e70d13-a1ca-4582-b7b7-3b96d4f9de58
md"""
---
Extras for the blog post
"""
# ╔═╡ e3111d88-3462-47d9-8a7f-8690fe1df371
let
c1 = selling_price[1]
c2 = discounted_selling_price[1]
x1 = demand[1]
x2 = 10
anim = @animate for prod = range(0, 10, length=80)
plt = plot(layout=grid(1, 2), size=(800, 400))
f(x, y) = c1 * x + c2 * y
contourf!(
plt[1],
range(0, x1, length=5),
range(0, x2 - x1, length=5),
f,
lab = "",
lw=0.2,
m = (2,:lightblue),
axis_ratio = :equal,
)
X = min.(x1, prod:-1:0)
X = [min(prod, x1), min(prod, x1), 0]
Y = [0, prod - min(prod, x1), prod]
plot!(plt[1], X, Y, c=:white, lw=2, lab="")
scatter!(plt[1], [X[2]], [Y[2]], m=(3,:pink,stroke(1,:red)), lab="")
plot!(plt[1], [0, X[1], X[1]], [0, 0, Y[2]], c=:blue, lw=2, lab="")
xlims!(plt[1], -0.2, x1 + 0.2)
ylims!(plt[1], -0.2, x2 - x1 + 0.2)
xlabel!(plt[1], "Normal production")
ylabel!(plt[1], "Extra production")
plot!(plt[2],
[0, x1, x2],
[0, c1 * x1, c1 * x1 + (x2 - x1) * c2],
lab = "",
c=:blue,
m = (2,:lightblue,stroke(1,:blue)),
)
plot!(plt[2],
[prod, prod],
[0, f(X[2],Y[2])],
c=:lightblue,
lab="",
)
scatter!(plt[2], [prod], [f(X[2], Y[2])], m=(3,:pink,stroke(1,:red)), lab="")
xlabel!("Quantity")
ylabel!("Revenue")
end
gif(anim, "revenue.gif", fps=20)
end
# ╔═╡ 52d44b98-1da3-4f1a-84a0-db1b8241a40e
let
anim = @animate for t = min.(0:60, 40)
output = optimize_production(t)
prod_normal = output[:prod_normal]
prod_extra = output[:prod_extra]
groupedbar(
hcat(sum.([prod_extra, prod_normal], dims=2)...),
bar_position = :stack,
bar_width = 0.5,
xticks = (1:length(products), string.(products)),
label = ["extra" "normal"],
)
title!("Available time: $t h")
ylims!(0, 7)
end
gif(anim, "solution-strategy-1.gif", fps=5)
end
# ╔═╡ 81cc6f5e-c8b7-4e8a-a7d9-36ad501f4b44
let
anim = @animate for t = min.(0:60, 40)
output = optimize_production_nonlinear(t)
prod = output[:prod]
demand = output[:demand]
price = output[:price]
product_labels = [
products[i] * " $(round(price[i], digits=2))"
for i = 1:3
]
bar(
(1:3) .- 0.2,
prod,
bar_position = :stack,
bar_width = 0.4,
xticks = (1:length(products), product_labels),
label="production",
)
bar!(
(1:3) .+ 0.2,
demand,
bar_position = :stack,
bar_width = 0.4,
xticks = (1:length(products), product_labels),
opacity=0.5,
label="demand",
)
title!("Available time: $t h")
ylims!(0, 7)
end
gif(anim, "solution-strategy-2.gif", fps=5)
end
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
Cbc = "9961bab8-2fa3-5c5a-9d89-47fab24efd76"
Ipopt = "b6b21f68-93f8-5de0-b562-5493be1d77c9"
JuMP = "4076af6c-e467-56ae-b986-b466b2749572"
LaTeXStrings = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
PrettyTables = "08abe8d2-0d0c-5749-adfa-8a2ac140af0d"
SCIP = "82193955-e24f-5292-bf16-6f2c5261a85f"
StatsPlots = "f3b207a7-027a-5e70-b257-86293d7955fd"
[compat]
Cbc = "~1.1.1"
Ipopt = "~1.3.0"
JuMP = "~1.11.1"
LaTeXStrings = "~1.3.0"
Plots = "~1.38.12"
PlutoUI = "~0.7.51"
PrettyTables = "~2.2.4"
SCIP = "~0.11.6"
StatsPlots = "~0.15.5"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
julia_version = "1.9.0"
manifest_format = "2.0"
project_hash = "577b82dd4350c9935de5ff59e72d2e3f79a41b06"
[[deps.ASL_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "6252039f98492252f9e47c312c8ffda0e3b9e78d"
uuid = "ae81ac8f-d209-56e5-92de-9978fef736f9"
version = "0.1.3+0"
[[deps.AbstractFFTs]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "16b6dbc4cf7caee4e1e75c49485ec67b667098a0"
uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c"
version = "1.3.1"
weakdeps = ["ChainRulesCore"]
[deps.AbstractFFTs.extensions]
AbstractFFTsChainRulesCoreExt = "ChainRulesCore"
[[deps.AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "8eaf9f1b4921132a4cff3f36a1d9ba923b14a481"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.1.4"
[[deps.Adapt]]
deps = ["LinearAlgebra", "Requires"]
git-tree-sha1 = "76289dc51920fdc6e0013c872ba9551d54961c24"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "3.6.2"
weakdeps = ["StaticArrays"]
[deps.Adapt.extensions]
AdaptStaticArraysExt = "StaticArrays"
[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
version = "1.1.1"
[[deps.Arpack]]
deps = ["Arpack_jll", "Libdl", "LinearAlgebra", "Logging"]
git-tree-sha1 = "9b9b347613394885fd1c8c7729bfc60528faa436"
uuid = "7d9fca2a-8960-54d3-9f78-7d1dccf2cb97"
version = "0.5.4"
[[deps.Arpack_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "OpenBLAS_jll", "Pkg"]
git-tree-sha1 = "5ba6c757e8feccf03a1554dfaf3e26b3cfc7fd5e"
uuid = "68821587-b530-5797-8361-c406ea357684"
version = "3.5.1+1"
[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[deps.AxisAlgorithms]]
deps = ["LinearAlgebra", "Random", "SparseArrays", "WoodburyMatrices"]
git-tree-sha1 = "66771c8d21c8ff5e3a93379480a2307ac36863f7"
uuid = "13072b0f-2c55-5437-9ae7-d433b7a33950"
version = "1.0.1"
[[deps.Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[deps.BenchmarkTools]]
deps = ["JSON", "Logging", "Printf", "Profile", "Statistics", "UUIDs"]
git-tree-sha1 = "d9a9701b899b30332bbcb3e1679c41cce81fb0e8"
uuid = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
version = "1.3.2"
[[deps.BitFlags]]
git-tree-sha1 = "43b1a4a8f797c1cddadf60499a8a077d4af2cd2d"
uuid = "d1d4a3ce-64b1-5f1a-9ba4-7e7e69966f35"
version = "0.1.7"
[[deps.Bzip2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "19a35467a82e236ff51bc17a3a44b69ef35185a2"
uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0"
version = "1.0.8+0"
[[deps.Cairo_jll]]
deps = ["Artifacts", "Bzip2_jll", "CompilerSupportLibraries_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "LZO_jll", "Libdl", "Pixman_jll", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "4b859a208b2397a7a623a03449e4636bdb17bcf2"
uuid = "83423d85-b0ee-5818-9007-b63ccbeb887a"
version = "1.16.1+1"
[[deps.Calculus]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "f641eb0a4f00c343bbc32346e1217b86f3ce9dad"
uuid = "49dc2e85-a5d0-5ad3-a950-438e2897f1b9"
version = "0.5.1"
[[deps.Cbc]]
deps = ["Cbc_jll", "MathOptInterface", "SparseArrays"]
git-tree-sha1 = "55e2e9684102dd2f68c406a6a282b16883a7bc00"
uuid = "9961bab8-2fa3-5c5a-9d89-47fab24efd76"
version = "1.1.1"
[[deps.Cbc_jll]]
deps = ["ASL_jll", "Artifacts", "Cgl_jll", "Clp_jll", "CoinUtils_jll", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "OpenBLAS32_jll", "Osi_jll", "Pkg"]
git-tree-sha1 = "1d12b6aa435f30bd5619e0144f4c815c854a91b6"
uuid = "38041ee0-ae04-5750-a4d2-bb4d0d83d27d"
version = "200.1000.800+0"
[[deps.Cgl_jll]]
deps = ["Artifacts", "Clp_jll", "CoinUtils_jll", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Osi_jll", "Pkg"]
git-tree-sha1 = "3e53a23c0bf96e8c0115777e351a04d5b0f52529"
uuid = "3830e938-1dd0-5f3e-8b8e-b3ee43226782"
version = "0.6000.600+0"
[[deps.ChainRulesCore]]
deps = ["Compat", "LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "e30f2f4e20f7f186dc36529910beaedc60cfa644"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "1.16.0"
[[deps.Clp_jll]]
deps = ["Artifacts", "CoinUtils_jll", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "METIS_jll", "MUMPS_seq_jll", "OpenBLAS32_jll", "Osi_jll", "Pkg"]
git-tree-sha1 = "51861cd16c6c4e0018ad401b2afb36e51c7d4bcd"
uuid = "06985876-5285-5a41-9fcb-8948a742cc53"
version = "100.1700.700+1"
[[deps.Clustering]]
deps = ["Distances", "LinearAlgebra", "NearestNeighbors", "Printf", "Random", "SparseArrays", "Statistics", "StatsBase"]
git-tree-sha1 = "a6e6ce44a1e0a781772fc795fb7343b1925e9898"
uuid = "aaaa29a8-35af-508c-8bc3-b662a17a0fe5"
version = "0.15.2"
[[deps.CodecBzip2]]
deps = ["Bzip2_jll", "Libdl", "TranscodingStreams"]
git-tree-sha1 = "2e62a725210ce3c3c2e1a3080190e7ca491f18d7"
uuid = "523fee87-0ab8-5b00-afb7-3ecf72e48cfd"
version = "0.7.2"
[[deps.CodecZlib]]
deps = ["TranscodingStreams", "Zlib_jll"]
git-tree-sha1 = "9c209fb7536406834aa938fb149964b985de6c83"
uuid = "944b1d66-785c-5afd-91f1-9de20f533193"
version = "0.7.1"
[[deps.CoinUtils_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "OpenBLAS32_jll", "Pkg"]
git-tree-sha1 = "5e9852361e31af66143665e780535df262fa3407"
uuid = "be027038-0da8-5614-b30d-e42594cb92df"
version = "200.1100.600+0"
[[deps.ColorSchemes]]
deps = ["ColorTypes", "ColorVectorSpace", "Colors", "FixedPointNumbers", "PrecompileTools", "Random"]
git-tree-sha1 = "be6ab11021cd29f0344d5c4357b163af05a48cba"
uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
version = "3.21.0"
[[deps.ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "eb7f0f8307f71fac7c606984ea5fb2817275d6e4"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.4"
[[deps.ColorVectorSpace]]
deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "SpecialFunctions", "Statistics", "TensorCore"]
git-tree-sha1 = "600cc5508d66b78aae350f7accdb58763ac18589"
uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4"
version = "0.9.10"
[[deps.Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "fc08e5930ee9a4e03f84bfb5211cb54e7769758a"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.10"
[[deps.CommonSubexpressions]]
deps = ["MacroTools", "Test"]
git-tree-sha1 = "7b8a93dba8af7e3b42fecabf646260105ac373f7"
uuid = "bbf7d656-a473-5ed7-a52c-81e309532950"
version = "0.3.0"
[[deps.Compat]]
deps = ["UUIDs"]
git-tree-sha1 = "7a60c856b9fa189eb34f5f8a6f6b5529b7942957"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"