Octave With Spice
Octave With Spice
Tommi Sottinen
[email protected]
www.uwasa.fi/∼tsottine/spicy or/octave with spice.pdf
These notes are an introduction on how to use GNU Octave for the six week 5 ECTS course
ORMS1020 Operations Research in the University of Vaasa. I expect that it will take two
weeks to go through the material presented here in the course. The remaining four weeks will
then be from the companion notes “Linear Programming with Spice”.
The first three chapters of these notes are the gentle introduction to Octave and the fourth
chapter is the spice. Indeed, the first three chapters should give a student with minimal
experience of programming the necessary background to understand chapter 4, where we show
how Linear Programming problems (LP’s) can be solved by using GNU Linear Programming
Kit (GLPK) in GNU Octave.
T.S.
Vaasa October 31, 2022
Contents
These instructions refer to GNU Octave version 6.2.0 released in 2021-02-20. Instructions for
newer versions (e.g. 6.3.0 released in 2021-07-11) should be pretty much the same. If you have
already an older GNU Octave installed, it will probably work just fine. There is most likely no
reason to update your GNU Octave for the purpose of these notes and the ORMS1020 course.
On the other hand, there is absolutely no reason not to update your GNU Octave to the latest
stable version.
Note that depending on your system setup, you Octave GUI window may look slightly
different.
The following is our first exercise. The exercises are littered all around the notes and not
collected to separate sections. They also follow the general running numbering of subsections.
This makes finding the exercises slightly inconvenient and the numbering may look a bit con-
fusing. The reason for this inconvenience is that in this way you are encouraged to read the
material and you will also know how the exercises are related to the material. The first Exercise
1.1 is simple. Its almost only point is to check that your installation of GNU Octave works.
can use the command line (a.k.a. console) immediately, but using script files (a.k.a. m-files)
requires signing in to the system. You can simply sign in by using your e-mail.
Octave Online seems convenient, but I strongly discourage using it. Besides the obvious
problems with online systems, it seems that Octave Online is very slow compared to installing
GNU Octave on your own computer. Also, it seems that Octave Online is not comfortable
with big data. Finally, I have limited experience in using Octave Online, so I may not be able
to help with the problems you will experience in using it.
Getting Help
The most obvious way of getting help on GNU Octave is to switch to the Documenta-
tion tab next to the Command Window tab at the bottom of your GNU Octave GUI
window. This will open the GNU Octave Manual. You can also find this manual in
https://octave.org/doc/v6.2.0/. (This is the manual for version 6.2.0. I leave it to you to
guess where you can find the manual for version 6.3.0.)
GNU Octave also has Wiki pages https://wiki.octave.org/GNU Octave Wiki with FAQ
https://wiki.octave.org/FAQ. This is a good place to start if you have problems.
There is also a GNU Octave community https://octave.discourse.group/, where you can ask
for help. This is a good place to ask if you have specific advanced problems or you think you
have found a bug.
Finally, if you already know what you want to do, but do not know or remember the details,
you can type help <topic> on the Command Window. The next Example 1.3 explains how
to use help.
Formally, a solution is
x = tan−1 0.5,
where tan−1 denotes an inverse of the function tan. Unfortunately, the inverses of trigono-
metric functions have funny names. Also, some might interpret tan−1 y as 1/ tan y . So, how
do we solve (1.4) with GNU Octave? The best way to start is to see what GNU Octave has
to say about the tan function. So, we type help tan in the Command Window:
1 >> help tan
2 ’ tan ’ i s a b u i l t −i n function from t h e f i l e l i b i n t e r p / c o r e f c n / mappers . c c
3
4 −− tan ( Z )
5 Compute t h e t a n g e n t f o r each e l e m e n t o f X i n r a d i a n s .
6
7 See a l s o : atan , tand , tanh .
Chapter 1 Getting Help 6
8
9 A d d i t i o n a l help f o r b u i l t −i n f u n c t i o n s and o p e r a t o r s i s
10 a v a i l a b l e i n t h e o n l i n e version o f t h e manual . Use t h e command
11 ’ doc <t o p i c > ’ t o s e a r c h t h e manual i n d e x .
12
13 Help and i n f o r m a t i o n about Octave i s a l s o a v a i l a b l e on t h e WWW
14 a t h t t p s : / /www. o c t a v e . o r g and v i a t h e help@octave . o r g
15 mailing l i s t .
In the answer we spot (look at line 7) something vaguely familiar from our days in high school:
atan. This looks like arcus tan or arctan, which is one name for the inverse of tan. So, let us
ask help for that
1 >> help atan
2 ’ atan ’ i s a b u i l t −i n function from t h e f i l e l i b i n t e r p / c o r e f c n / mappers . c c
3
4 −− atan (X)
5 Compute t h e i n v e r s e t a n g e n t i n r a d i a n s f o r each e l e m e n t o f X.
6
7 See a l s o : tan , atand .
8
9 A d d i t i o n a l help f o r b u i l t −i n f u n c t i o n s and o p e r a t o r s i s
10 a v a i l a b l e i n t h e o n l i n e version o f t h e manual . Use t h e command
11 ’ doc <t o p i c > ’ t o s e a r c h t h e manual i n d e x .
12
13 Help and i n f o r m a t i o n about Octave i s a l s o a v a i l a b l e on t h e WWW
14 a t h t t p s : / /www. o c t a v e . o r g and v i a t h e help@octave . o r g
15 mailing l i s t .
Looks correct. So, the solution for (1.4) is given by the following Command Window conver-
sation.
1 >> atan ( 0 . 5 )
2 ans = 0 . 4 6 3 6
GNU Octave is a very convenient calculator. It can be used as a simple calculator (with
variables), but its true power is in how it handles matrices and vectors.
This answer is wrong, because 2/7+3 ̸= 2/(7+3). The human reader might read the command
line 1 above differently because of all the extra spaces, but GNU Octave does not care about
extra spaces. Also, while 10ˆ−2 is technically correct, I strongly encourage to use parentheses
there to avoid mistakes. Here is the correct way to calculate (2.2):
1 >> 1.4∗10ˆ( −2) + 2/(7+3)
2 ans = 0 . 2 1 4 0
Chapter 2 Simple Calculations and Variables 8
8 ÷ 2(2 + 2)
Let us then consider calculation with variables. Like most programming languages, GNU
Octave can handle many different types of variables. GNU Octave uses weak typing meaning
that we do not have to declare variables or their type like in Java, or C. If you don’t know what
this means, you are lucky. So, don’t worry about it. In this section we only consider (real)
numbers. In the next section we consider (real) vectors and (real) matrices. Later in the course
we will also consider strings and a little bit struct (structure) type variables. Other variable
types are not used in this course.
Now we should see in the Workspace panel a line that says something like x under Name and
double under Class. We can also ask what variables we have in our workspace by asking who
1 >> who
2 V a r i a b l e s v i s i b l e from t h e c u r r e n t s c o p e :
3
4 x
Since x is defined we can use it in calculations. For example, we can calculate 2x = 21/3 as
1 >> 2ˆ x
2 ans = 1 . 2 5 9 9
GNU Octave calculated the answer and assinged its value to the variable named ans. Indeed,
if we now ask who, we obtain
1 >> who
2 V a r i a b l e s v i s i b l e from t h e c u r r e n t s c o p e :
3
4 ans x
Chapter 2 Simple Calculations and Variables 9
To see the values of the variables that are defined we can simply type them on the Command
Window
1 >> ans
2 ans = 1 . 2 5 9 9
3 >> x
4 x = 0.3333
So, after line 1 the Command Window becomes empty, but the variables are not cleared as is
shown by the who command in line 2. Lines 7 and 8 show that after the clear command the
workspace is empty of variables. Indeed, asking for x in line 9 gives a more or less obvious
error message. Now, in line 11 we define x and GNU Octave annoyingly echoes back what
happened. In line 13 we define y to be the calculation we did earlier in Example 2.5, when we
did not assing a variable to the solution. Since we now asked the answer to be stored in the
variable y, GNU Octave does not use the auxiliary variable ans as in Example 2.5. This can
be seen by asking who in line 15. We obtain the result that there are two variables, x and y,
defined. The variable ans is not defined.
Chapter 2 Matrices and Vectors 10
In Example 2.7 we noticed the annoying thing that GNU Octave echoes back (almost)
everything we do. Quite often this is not what we want. Indeed, we usually want GNU Octave
to perform the calculations quietly and only give the answer when we ask for it. We can tell
GNU Octave to be quiet by ending our commands with semicolon. So, the semicolon works
very differently in GNU Octave than in Java or C!
Now, for A = [Aij ] we have A13 = A1,3 = 13 and A31 = A3,1 does not exist. The following
conversation is how GNU Octave sees this:
1 >> A( 1 , 3 )
2 ans = 13
3 >> A( 3 , 1 )
4 error : A( 3 , ) : out o f bound 2 ( d i m e n s i o n s a r e 2 x4 )
A vector is simply a matrix that has either one row or one column. If it has only one column,
it is a column vector. If it has only one row, it is a row vector. If not otherwise stated, we will
assume that all vectors are column vectors. Also note that vectors that have only one row and
one column are called numbers.
Matrix algebra works with GNU Octave with the obvious and convenient way: if A and
B are matrices (with suitable dimensions), then the transpose A′ = A⊤ of A is in GNU
Octave A’. Sums like A + B and A − B are obvious, the product (when defined) AB is A∗B.
Matrix power An is obviously Aˆn, the inverse matrix A−1 can be written as Aˆ(−1) or inv(A).
Finally, the matrix equation (a.k.a. a system of linear equations) Ax = b can be solved by the
left-division \ as x=A\b. It is left for the reader to figure out what the right-division / does.
The n-by-n identity matrix I = In can be constructed with GNU Octave by using the
(terrible) pun eye(n) as the following console command shows:
1 >> eye ( 4 )
2 ans =
3
4 D i a g o n a l Matrix
5
6 1 0 0 0
7 0 1 0 0
8 0 0 1 0
9 0 0 0 1
In this course we do not use matrix algebra much as such. We will however use block
matrices a lot. This means that we will cut matrices apart and paste them together. This
can become very complicated very quickly. So, instead of giving the full exposure, we will just
consider some cases now. More complicated constructions will be given later.
Let A be some matrix. If we want to refer to its row i, a typical mathematical notation is
Ai• . One way to understand this is that the row i is fixed, but the columns “run free”. With
GNU Octave colon takes the place of the bullet: Ai• becomes A(i ,:) In the same way, A•j and
A(:, j ) refer to the fixed column j of the matrix A.
Chapter 2 Matrices and Vectors 12
We can also take out a block of matrix. In GNU Octave this means that we use A(v1,v2),
where v1 and v2 are vectors that indicate which rows and columns we take.
11 1 3
12
13 >> v2 = [ 3 4 ]
14 v2 =
15
16 3 4
17
18 >> A( v1 , v2 )
19 ans =
20
21 13 14
22 33 34
23
24 >> A( v1 , v2 ) = [ 0 0 ; 0 0 ]
25 A =
26
27 11 12 0 0
28 21 22 23 24
29 31 32 0 0
So here we first, in line 1, defined the matrix A. In line 8 we defined the (row or column,
it does not matter) vector v1 to correspond rows 1 and 3. In line 13 we defined the (row or
column, it does not matter) vector v2 to correspond columns 3 and 4. In line 19 we asked
what is the submatrix of the matrix A, where only rows 1 and 3 and columns 3 and 4 are
considered. Finally, in line 25 we asked GNU Octave to replace the 2-by-2 submatrix A(v1,v2)
with a 2-by-2 zero matrix.
Submatrices, that is cutting matrices, as considered above can be tricky. Block matrices,
that is pasting matrices, is arguably much simpler. Again the following console discussion of
Example 2.13 should explain how to paste matrices.
3
4 11 12 13
5 21 22 23
6
7 >> b = [ 7 6 0 −98] ’
8 b =
9
10 760
11 −98
12
13 >> I = eye ( 2 )
14 I =
15
16 D i a g o n a l Matrix
17
18 1 0
19 0 1
20
21 >> c = [ 2 4 0 4 0 ] ’
22 c =
23
24 2
25 4
26 0
27 4
28 0
29
30 >> T = [ c ’ 1 ; A I b ]
31 T =
32
33 2 4 0 4 0 1
34 11 12 13 1 0 760
35 21 22 23 0 1 −98
Let
11 12 13 14 15 16
21 22 23 24 25 26
A =
31
.
32 33 34 35 36
41 42 43 44 45 46
So far we have used the Command Window when discussing with GNU Octave. This becomes
very quickly very clumsy. In this chapter we introduce the so-called m-files that makes this
discussion much more fluent.
There are two types of m-files: script files and function files.
Script m-Files
A script type m-file is simply a list of console commands. The advantage of using script m-files
instead of the console are twofold:
(i) You can edit and debug the file and run all its command at once without the need executes
many commands in a row.
(ii) You can format the file so that, for example, matrices can be adjusted by rows and
columns.
Suppose we want to calculate the net present value of a cash-flow under a given interest
rate. As all students with loans should know, the formula for this is
T
X ct
(3.1) npv = ,
t=1
(1 + r)t
where ct is the cash received at the end of period t, T is the number of periods, and r is the
(fixed) rate of interest during the periods.
extension .m in their names) that is in the Current Directory of our GNU session. You can
set the Current Directory in the field near the top of your Octave GUI window. The script
file is executed by typing its name (without the .m extension) in the Command Window.
As you can see, this is very quick and very dirty. To get the solution, make sure that the
file npv qd.m is in your Current Directory. You should be able to see it listed in the File
Browser panel (top left panel typically). To execute the file simply state its name without the
.m extension. Here is the related Console Window discussion
1 >> npv qd
2 npv = 8 4 0 8 . 3
I strongly discourage using quick and dirty m files like in Example 3.3. One of the dirtiest
and stupidest thing we did was that we plugged in the numbers in the formula. You should
absolutely never ever do this! What we should have done is to give the numbers as variables
and then implement the formula for GNU Octave in a general form. Of course, if you are in a
hurry and do not intend to use the m file later, you can be quick and dirty. However, if you
intend to use the m file later, I encourage you to do something like the more elegant solution
in Solution 3.4 below.
15 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
16 %% C a l c u l a t i o n s
17 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
18
19 T = length ( c f ) ; %% Number o f p e r i o d s .
20
21 %% C a l c u l a t e t h e npv sum i t e r a t i v e l y
22 npv = 0 ;
23 fo r t =1:T
24 npv = npv + c f ( t ) / ( (1+ r ) ˆ t ) ;
25 end
26
27 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
28 %% Output Net P r e s e n t Value ( npv )
29 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
30 npv
Compared to the quick and dirty solution of Example 3.3 this one is certainly tedious. But it
is also elegant.
Let us analyze the code above on a block level:
The code is divided into 4 blocks: The 1st block, lines 1–7 just describes what this code
is supposed to do. The 2nd block, lines 8–14, set the data. The key point here is that this
code will also work with different data, i.e., if you want to change the cash-flow or the interest
rate, you can do it here and the rest will work just fine. The 3rd block, lines 15–26 will do
the actual calculations, so that’s where the beef is. The final 4th block, lines 27–30, is for the
output.
A line-by-line analysis of the code is:
The lines 1–11 do absolutety nothing. They are there for the readers’ convenience. Indeed,
the percentage symbol % at the begining of the lines 1–6 and 8–10 means that these lines
are comments. GNU Octave will simply ignore these lines. GNU Octave will also ignore the
empty lines 7 and 11. Also, the use of double comment signs %% is not necessary; one %
would be enough. This is a matter of style. Indeed, a double comment sign %% should mean
a permanent comment, while a single comment sign % should mean something that is used
for debugging or testing purposes.
Line 12 defines the (column) vector cf to contain the cash-flow. There is a comment sign
%% at the end of the line, which GNU Octave will ignore. This comment is here for the
readers’ convenience. Line 13 defines the interest rate in the same way.
Lines 14–18 do absolutely nothing.
Line 19 gets the number of periods from the vector cf . The idea here is that we infer the
number of periods T from the length of the vector cf , and do not set it by hand. Indeed, this
way the m-file will work just fine if we change the parameters in line 12–13.
Lines 20–21 do absolutely nothing.
Lines 22–25 are the beef of the code. They calculate the sum in the formula (3.1) in a
for-loop. Type help for in GNU Octave to unerstand what is going on!
Again, lines 26–29, do absolutely nothing.
Finally, in line 30 we call the variable npv without semicolon. Thus GNU Octave will echo
the value of the variable npv to the console, showing us the result.
Chapter 3 Function m-Files 19
Now, calling the script m-file npv elegant.m in the console (make su you have the m-file in
your Current Directory) solves the Net Present Value problem 3.2:
1 >> n p v e l e g a n t
2 npv = 8 4 0 8 . 3
3.5 Exercise
Calculate the Net Present Value (npv) of having 100 000 EUR after 10 years when the annual
interest rate is 50%.
Function m-Files
Suppose you want to calculate the net present value (3.1) for many different values of cash-
flows and/or interest rates. Then it makes sense to have the npv as a function, and not to make
separate elegant script m-files for all the different cf and r values. To do this, you should make
a function m-file for npv.
A function m-file is an m-file that starts with the keyword function. So, GNU Octave will
know not to try to parse this file as a script m-file. Instead, GNU Octave will only parse this
file, if it will be called as a function with given parameters.
Below is the code for the function m-file for npv, that can be downloaded from
www.uwasa.fi/∼tsottine/spicy or/npv.m
1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2 %% Function v = npv ( c f , r ) r e t u r n s t h e Net P r e s e n t Value ( npv ) o f t h e c a s h f l o w
3 %% c f . The c a s h f l o w c f i s r e c e i v e d a t t h e end o f each p e r i o d . The r a t e o f
4 %% r e t u r n o v e r t h e p e r i o d i s r . The parameter r i s s c a l a r . The c a s h f l o w c f
5 %% i s a ( column ) v e c t o r .
6 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
7
8 function v = npv ( c f , r )
9 T = length ( c f ) ; %% The number o f p e r i o d s .
10 pv = zeros (T, 1 ) ; %% I n i t i a l i z e p r e s e n t v a l u e s ( pv ) t o z e r o .
11 f o r t =1:T
12 pv ( t ) = c f ( t ) / (1+ r ) ˆ t ; %% S e t t h e pv ’ s .
13 end
14 v = sum( pv ) ; %% npv i s t h e sum o f pv ’ s .
15 end
Trying to call the function as it were a script m-file will lead to the following unsatisfying
discussion with GNU Octave console:
1 >> npv
2 error : ’ c f ’ u n d e f i n e d n e a r l i n e 9 , column 9
3 error : c a l l e d from
4 npv a t l i n e 9 column 7
A more fruitful conversation with GNU Octave console and npv-function could be
Chapter 3 Function m-Files 20
1 >> r = 0 . 0 5
2 r = 0.050000
3 >> c f = [ 0 0 0 1 ]
4 cf =
5
6 0 0 0 1
7
8 >> npv ( c f , r )
9 ans = 0 . 8 2 2 7
A Linear Program (LP) is a linear optimization problem, where all the “things” are linear.
This means that that the objective function you want to optimize (maximize or minimize) is a
linear function of your decision variables, and so are also your constraints.
In this chapter we consider an LP called the Product-Mix Problem or Product-
Selection Problem. We first introduce the problem. Then we model it mathematically, and
finally we solve it by using the GNU Octave function glpk (GNU Linear Programming Kit).
Product-Mix Problem
Atreides Cake Fat 70 g, sugar 500 g, protein 280 g, water 600 ml, spice Melange 8 mg.
Price: 120 solaris.
Corrino Cake Fat 50 g, sugar 300 g, protein 180 g, water 800 ml, spice Melange 35 mg.
Price: 170 solaris.
Harkonnen Cake Fat 150 g, sugar 500 g, protein 50 g, water 500 ml, spice Melange 10 mg.
Price: 100 solaris.
Muad’Dib Bakery has the following amount of nutrient powders at its disposal daily:
Fat 100 kg
Sugar 400 kg
Protein 150 kg
Water 300 l
Spice Melange 10 g
Muad’Dib Bakery wants to maximize daily revenues. What should Muad’Dib Bakery do?
Chapter 4 Product-Mix Problem 22
To model mathematically optimization problems like 4.1 one may follow the following three-step
procedure:
Let us then start the mathematical modeling phase following Algorithm 4.2 above.
Muad’Dib Bakery produces three different types of cakes. So, the decision variables are:
Once the decision variables x = [x1 x2 x3 ]′ are known, the objective function z = z(x)
of this problem is simply the revenue
Note that the profit z depends linearly on the number of produced cakes x1 , x2 , x3 . So, this
is a linear problem so far (the constraints must turn out to be linear, too).
It may seem at first glance that the profit can be maximized by simply increasing x1 , x2
and x2 . Well, if life were that easy, let’s all start manufacturing Fremen cakes and become
infinitely rich! Unfortunately, there are constraints that limit the decisions (or else the model
is very likely to be wrong). Indeed, we need nutrient powders, and these are scarce resources.
Let us consider the constraint induced by the limited supply of fat powder. If we decide
to produce x1 Atreides cakes, x2 Corrino cakes, and x3 Harkonnen cakes, then the amount (in
grams) of fat powder we have used is 70x1 + 50x2 + 150x3 grams. Since we only have 100 kg
of fat powder, we have the constraint (note the unit change 1 kg = 1 000 g)
So, this is the constraint induced by the scarcity of fat powder. Note that this is a linear
constraint. This is good. Indeed, if it were not a linear constraint we wouldn’t be able to solve
it with GNU Octave’s function glpk.
Similarly, for sugar powder we have the linear constraint
since there is only 400 kg = 400 000 g of sugar powder available daily, and the requirement per
cake for Atreides, Corrino, and Harkonnen type cakes are 500 g, 300 g and 500 g, respectively.
Chapter 4 Product-Mix Problem 23
The daily supply for protein powder is 150 kg = 150 000 g. Consequently, we obtain the
linear constraint
since Atreides cake needs 280 g of protein, Corrino cake need 180 g of protein, and Harkonnen
cake needs 50 g of protein.
For water powder we obtain the linear constraint
since 300 l = 300 000 ml, and the requirements per cake types are 600 ml, 800 ml, and 500 ml.
Finally, for spice Melange the linear constraint is
z = c′ x.
Let then
70 50 150
500 300 500
A =
280 180 50 .
600 800 500
8 35 10
This means that A is the technology matrix that corresponds to how the different products
(cakes) are produced from the resources (nutrient powders). The final piece of data is the
Chapter 4 Solving Product-Mix Problem with GLPK 24
column vector b = [10000 400000 150000 300000 10000]′ that tells the number of available
resources. With c, A, and b the Muad’Dib Bakery LP (4.3) can be written very compactly
as
max z = c′ x
(4.5) s.t. Ax ≤ b .
x ≥ 0
Now that the mathematical modeling phase is finished, there is the implementation
phase, i.e. we have to tell the problem to a computer so that it can solve it. In the next
section we show how to do this with GNU Octave and its GLPK solver.
14 A∗x = b
15 x >= 0
16
17 but may a l s o s o l v e problems o f t h e form
18
19 [ min | max ] C’ ∗ x
20
21 s u b j e c t to
22
23 A∗x [ ”=” | ”<=” | ”>=” ] b
24 x >= LB
25 x <= UB
26
27 Input arguments :
28
29 C
30 A column a r r a y c o n t a i n i n g t h e o b j e c t i v e function c o e f f i c i e n t s .
31
32 A
33 A matrix c o n t a i n i n g t h e c o n s t r a i n t s c o e f f i c i e n t s .
34
35 B
36 A column a r r a y c o n t a i n i n g t h e r i g h t −hand s i d e v a l u e f o r each
37 c o n s t r a i n t i n t h e c o n s t r a i n t matrix .
38
39 LB
40 An a r r a y c o n t a i n i n g t h e lower bound on each o f t h e v a r i a b l e s .
41 I f LB i s not s u p p l i e d , t h e d e f a u l t lower bound f o r t h e
42 variables i s zero .
43
44 UB
45 An a r r a y c o n t a i n i n g t h e upper bound on each o f t h e v a r i a b l e s .
46 I f UB i s not s u p p l i e d , t h e d e f a u l t upper bound i s assumed t o
47 be i n f i n i t e .
48
49 CTYPE
50 An a r r a y o f c h a r a c t e r s c o n t a i n i n g t h e s e n s e o f each c o n s t r a i n t
51 i n t h e c o n s t r a i n t matrix . Each e l e m e n t o f t h e a r r a y may be
52 one o f t h e f o l l o w i n g v a l u e s
53
54 ”F”
55 A f r e e ( unbounded ) c o n s t r a i n t ( t h e c o n s t r a i n t i s
56 ignored ) .
57
58 ”U”
59 An i n e q u a l i t y c o n s t r a i n t with an upper bound ( ’A( i , : ) ∗x
60 <= b ( i ) ’ ) .
61
62 ”S”
63 An e q u a l i t y c o n s t r a i n t ( ’A( i , : ) ∗x = b ( i ) ’ ) .
64
65 ”L”
66 An i n e q u a l i t y with a lower bound ( ’A( i , : ) ∗x >= b ( i ) ’ ) .
67
68 ”D”
69 An i n e q u a l i t y c o n s t r a i n t with both upper and lower bounds
70 ( ’A( i , : ) ∗x >= −b ( i ) ’ ) a n d ( ’A( i , : ) ∗x <= b ( i ) ’ ) .
Chapter 4 Solving Product-Mix Problem with GLPK 26
71
72 VARTYPE
73 A column a r r a y c o n t a i n i n g t h e t y p e s o f t h e v a r i a b l e s .
74
75 ”C”
76 A continuous variable .
77
78 ”I”
79 An i n t e g e r v a r i a b l e .
80
81 SENSE
82 I f SENSE i s 1 , t h e problem i s a m i n i m i z a t i o n . I f SENSE i s −1,
83 t h e problem i s a maximization . The d e f a u l t v a l u e i s 1 .
84
85 PARAM
86 A s t r u c t u r e c o n t a i n i n g t h e f o l l o w i n g p a r a m e t e r s used t o d e f i n e
87 the behavior of s o l v e r . Missing elements in the s t r u c t u r e
88 t a k e on d e f a u l t v a l u e s , s o you o n l y need t o set t h e e l e m e n t s
89 t h a t you wish t o change from t h e d e f a u l t .
90
91 I n t e g e r parameters :
92
93 ’ msglev ( d e f a u l t : 1 ) ’
94 L e v e l o f m es sa ges output by s o l v e r r o u t i n e s :
95
96 0 ( ’GLP MSG OFF ’ )
97 No output .
98
99 1 ( ’GLP MSG ERR ’ )
100 E r r o r and warning me ssa ge s o n l y .
101
102 2 ( ’GLP MSG ON ’ )
103 Normal output .
104
105 3 ( ’GLP MSG ALL ’ )
106 F u l l output ( i n c l u d e s i n f o r m a t i o n a l m es sa ges ) .
107
108 ’ s c a l e ( d e f a u l t : 16) ’
109 S c a l i n g o p t i o n . The v a l u e s can be combined with t h e
110 b i t w i s e OR o p e r a t o r and may be t h e f o l l o w i n g :
111
112 1 ( ’GLP SF GM ’ )
113 Geometric mean s c a l i n g .
114
115 16 ( ’ GLP SF EQ ’ )
116 Equilibration scaling .
117
118 32 ( ’ GLP SF 2N ’ )
119 Round s c a l e f a c t o r s t o power o f two .
120
121 64 ( ’ GLP SF SKIP ’ )
122 Skip i f problem i s w e l l s c a l e d .
123
124 A l t e r n a t i v e l y , a v a l u e o f 128 ( ’GLP SF AUTO ’ ) may be a l s o
125 s p e c i f i e d , i n which case t h e r o u t i n e c h o o s e s t h e s c a l i n g
126 options automatically .
127
Chapter 4 Solving Product-Mix Problem with GLPK 27
128 ’ dual ( d e f a u l t : 1) ’
129 Simplex method o p t i o n :
130
131 1 ( ’GLP PRIMAL ’ )
132 Use two−phase p r i m a l s i m p l e x .
133
134 2 ( ’GLP DUALP ’ )
135 Use two−phase d u a l simplex , and i f i t f a i l s , switch
136 to the primal simplex .
137
138 3 ( ’GLP DUAL ’ )
139 Use two−phase d u a l s i m p l e x .
140
141 ’ p r i c e ( d e f a u l t : 34) ’
142 P r i c i n g o p t i o n ( f o r both p r i m a l and d u a l s i m p l e x ) :
143
144 17 ( ’GLP PT STD ’ )
145 Textbook p r i c i n g .
146
147 34 ( ’GLP PT PSE ’ )
148 S t e e p e s t edge p r i c i n g .
149
150 ’ i t l i m ( d e f a u l t : intmax ) ’
151 Simplex i t e r a t i o n s l i m i t . I t i s d e c r e a s e d by one each
152 time when one s i m p l e x i t e r a t i o n has been performed , and
153 reaching zero value s i g n a l s the s o l v e r to stop the
154 search .
155
156 ’ o u t f r q ( d e f a u l t : 200) ’
157 Output f r e q u e n c y , i n i t e r a t i o n s . This parameter
158 s p e c i f i e s how f r e q u e n t l y t h e s o l v e r s e n d s i n f o r m a t i o n
159 about t h e s o l u t i o n t o t h e s t a n d a r d output .
160
161 ’ branch ( d e f a u l t : 4 ) ’
162 Branching t e c h n i q u e o p t i o n ( f o r MIP o n l y ) :
163
164 1 ( ’GLP BR FFV ’ )
165 First fractional variable .
166
167 2 ( ’GLP BR LFV ’ )
168 Last f r a c t i o n a l v a r i a b l e .
169
170 3 ( ’GLP BR MFV ’ )
171 Most f r a c t i o n a l v a r i a b l e .
172
173 4 ( ’GLP BR DTH ’ )
174 H e u r i s t i c by D r i e b e c k and Tomlin .
175
176 5 ( ’GLP BR PCH ’ )
177 Hybrid p s e u d o c o s t h e u r i s t i c .
178
179 ’ btrack ( d e f a u l t : 4) ’
180 B a c k t r a c k i n g t e c h n i q u e o p t i o n ( f o r MIP o n l y ) :
181
182 1 ( ’GLP BT DFS ’ )
183 Depth f i r s t s e a r c h .
184
Chapter 4 Solving Product-Mix Problem with GLPK 28
356 ’ time ’
357 Time ( i n s e c o n d s ) used f o r s o l v i n g LP/MIP problem .
358
359 ’ status ’
360 Status of the optimization .
361
362 1 ( ’GLP UNDEF ’ )
363 Solution status i s undefined .
364
365 2 ( ’GLP FEAS ’ )
366 Solution i s f e a s i b l e .
367
368 3 ( ’GLP INFEAS ’ )
369 Solution i s i n f e a s i b l e .
370
371 4 ( ’GLP NOFEAS ’ )
372 Problem has no f e a s i b l e s o l u t i o n .
373
374 5 ( ’GLP OPT ’ )
375 Solution i s optimal .
376
377 6 ( ’GLP UNBND ’ )
378 Problem has no unbounded s o l u t i o n .
379
380 Example :
381
382 c = [10 , 6 , 4] ’;
383 A = [ 1 , 1 , 1;
384 10 , 4 , 5 ;
385 2, 2, 6];
386 b = [ 1 0 0 , 600 , 3 0 0 ] ’ ;
387 lb = [0 , 0 , 0 ] ’ ;
388 ub = [ ] ;
389 c t y p e = ”UUU” ;
390 v a r t y p e = ”CCC” ;
391 s = −1;
392
393 param . msglev = 1 ;
394 param . i t l i m = 1 0 0 ;
395
396 [ xmin , fmin , s t a t u s , e x t r a ] = . . .
397 g l p k ( c , A, b , lb , ub , ctype , vartype , s , param ) ;
398
399 A d d i t i o n a l help f o r b u i l t −i n f u n c t i o n s and o p e r a t o r s i s
400 a v a i l a b l e i n t h e o n l i n e version o f t h e manual . Use t h e command
401 ’ doc <t o p i c > ’ t o s e a r c h t h e manual i n d e x .
402
403 Help and i n f o r m a t i o n about Octave i s a l s o a v a i l a b l e on t h e WWW
404 a t h t t p s : / /www. o c t a v e . o r g and v i a t h e help@octave . o r g
405 mailing l i s t .
Additionally, we must tell the function glpk what are the lower bounds lb, the upper bounds
ub, the types of the constraints ctype, and the sense (max or min) of the problem sense. Finally
there is the input parameter param, but this is optional. For now, we do not care about it. The
parameters c, A and b are given in Remark 4.4. As for lb, the only lower bounds we have are the
sign constraints. From lines 39–42 we see that the default lower bound are the sign constraints.
So, we use the default. This means that we give the nothing for the lower bounds. In GNU
Octave the nothing is the empty matrix [] . As for the upper bounds ub, we do not have any.
Indeed, the upper bounds b are not for the decision variables, but for the technology matrix.
So, we give the nothing [] for the upper bounds also. Then we have the ctype, that is the type
of bounds associated with the technology matrix A. They are all upper bounds, i.e. of type
≤. There are 5 of them. Thus, we will have ctype=”UUUUU”. Then we have to tell the types of
our 3 decision variables x1 , x2 and x3 . We will assume that they are continuous. Indeed, we
will almost always assume this. So, vartype=”CCC”. Finally, we must tell glpk whether we are
maximizing or minimizing. We are maximizing. So according to lines 81–83 of the help listing
we set sense=−1.
Having set the parameters c, A and b, we can solve Problem 4.1 by calling the function glpk
as
1 [ x max , z max ] = g l p k ( c , A, b , [ ] , [ ] , ”UUUUU” , ”CCC” , −1) .
Then the optimal decision will be in the vector x max and the optimal revenue will be in the
scalar z max.
23
24 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
25 %% S o l u t i o n with GLPK
26 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
27
28 [ x max , z max ] = g l p k ( c , A, b , [ ] , [ ] , ”UUUUU” , ”CCC” , −1) ;
29
30 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
31 %% Output : x max f o r t h e o p t i m a l d e c i s i o n and z max f o r t h e o p t i m a l v a l u e .
32 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
33 x max
34 z max
35
36 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
37 %% Test r e s u l t :
38 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
39 %%>> muaddib
40 %%x max =
41 %%
42 %% 171.2329
43 %% 246.5753
44 %% 0
45 %%
46 %%z max = 6 . 2 4 6 6 e+04
Lines 30-32 tells the human reader that next we will ask GNU Octave to print the solutions.
Indeed, so far we have told GNU OCtave to keep quiet. If we just type a variable name, its
value will be printed in the console.
Finally, the commented section 36–46 is there just for test purposes. Indeed, you sould
run the m-file muaddib.m and check that you get the same result as given there.
Let us then run the m-file muaddib.m in the GNU Octave console (make sure that the m-file
is in you current directory). We get the solution:
1 >> muaddib
2 x max =
3
4 171.2329
5 246.5753
6 0
7
8 z max = 6 . 2 4 6 6 e+04
So, Muad’Dib Bakery should produce 171.239 Atreides cakes, 246.5753 Corrino cakes, and
no Harkonnen cakes at all. With this choise the daily revenue is maximized and it is 62 466
solaris.
We have omitted the optional input parameter param, and we shall usually continue to do so.
Here, we use it a little bit, just to a have a small flavor of it. The parameter param (just p
later) is actually a tuning paramer. It is of struct type which means it has different fields
that can be set to different values. To go through all the possible tuning possibilities would
take too long, and would probably be almost pointless. We will consider only to fields here:
• msglev controls how much glpk will tell us what it is doing. Value 0 means blissful
quietness. Value 3 means annoying babbling.
• presol set whether glpk uses a so-called presolver (by default it does) or not. The idea of
the presolver is to try some easy tricks before going to a “full” solver.
In the example below we will set p.msglev=3 so that glpk will tell us “everything” it is doing.
We will also set p. presol=0, i.e., we will tell glpk not to use a presolver.
Let us consider the optional output parameters e and xtra. That is, let us consider calling
glpk as
1 [ x , z , e , x t r a ] = g l p k ( c , A, b , lb , ub , ctype , vartype , s e n s e , p )
The third output parameter e is of no interest to us, except in the case if something went
wrong. The fourth output parameter xtra, on the other hand, is very interesting. The output
parameter xtra is of struct type. This means that it is a structural variable that contains
different fields. Its fields are:
Chapter 4 Solving Product-Mix Problem with GLPK 36
• lambda for the dual variables a.k.a. shadow prices a.k.a. marginal prices.
• redcosts for the reduced costs a.k.a. opportunity costs.
• time for the time it took to calculate the solution.
• status for the status of the solution. (This is a funny field, since it seems to be redundant
given the return value e. The author is truly confused why this even exitsts.)
Here is a solution to the Muad’Dib Bakery Problem 4.1 where we have tuned
glpk so that it babbles a lot and does not use a presolver. Also, we asked
for full output x, z, e, xtra. You can donwload the solution m-file muaddib kh here:
www.uwasa.fi/∼tsottine/spicy or/muaddib kh.m
1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2 %%
3 %% Muad ’ Dib Kwisatz Haderach . ( Remark 4 . 1 4 from Octave with S p i c e )
4 %%
5 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6
7 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
8 %% Data
9 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
10
11 %% P r i c e s f o r A t r e i d e s , Corrino , Harkonnen ( S o l a r i )
12 c = [ 1 2 0 170 1 0 0 ] ’ ;
13
14 %% N u t r i e n t powder c o m p o s i t i o n of t h e c a k e s A t r e i d e s , Corrino , Harkonnen
15 A = [ 70 50 1 5 0 ; %% Fat ( g )
16 500 300 5 0 0 ; %% Sugar ( g )
17 280 180 5 0 ; %% Protein (g)
18 600 800 5 0 0 ; %% Water ( ml )
19 8 35 10 ] ; %% S p i c e Melange (mg)
20
21 %% A v a i l a b l e n u t r i e n t s ( n o t e u n i t s c a l e )
22 b = 1 0 0 0 ∗ [ 1 0 0 400 150 300 1 0 ] ’ ;
23
24 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
25 %% S o l u t i o n with GLPK with o u t p u t s
26 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
27
28 p . msglev = 3 ;
29 p . presol = 0;
30 [ x , z , e , x t r a ] = g l p k ( c , A, b , [ ] , [ ] , ”UUUUU” , ”CCC” , −1, p )
Running the m-file muaddib kh.m will give hte following output:
1 >> muaddib kh
2 Scaling . . .
3 A: min | a i j | = 8 . 0 0 0 e+00 max| a i j | = 8 . 0 0 0 e+02 r a t i o = 1 . 0 0 0 e+02
4 EQ: min | a i j | = 1 . 7 8 6 e −01 max| a i j | = 1 . 0 0 0 e+00 r a t i o = 5 . 6 0 0 e+00
5 Constructing i n i t i a l basis . . .
6 Size of t r i a n g u l a r part i s 5
7 GLPK Simplex Optimizer , v4 . 6 5
8 5 rows , 3 columns , 15 non−zeros
9 ∗ 0 : o b j = −0.000000000 e+00 i n f = 0 . 0 0 0 e+00 ( 3 )
10 ∗ 2: obj = 6 . 2 4 6 5 7 5 3 4 2 e+04 i n f = 0 . 0 0 0 e+00 ( 0 )
11 OPTIMAL LP SOLUTION FOUND
12 x =
Chapter 4 Solving Product-Mix Problem with GLPK 37
13
14 171.2329
15 246.5753
16 0
17
18 z = 6 . 2 4 6 6 e+04
19 e = 0
20 xtra =
21
22 s c a l a r s t r u c t u r e containing the f i e l d s :
23
24 lambda =
25
26 0
27 0
28 0
29 0.1945
30 0.4110
31
32 redcosts =
33
34 0
35 0
36 −1.3699
37
38 time = 0
39 status = 5
Here the output lines 2–11 are there because we asked glpk to babble. If we would have let glpk
to use the presolver these lines would have been slightly different. In thelines 12–18 we have
the usual result. The interesting new information is in lines 20–36. There we see two vectors:
• xtra.lambda
• xtra. redcosts
The shadow prices λ=xtra.lambda are related to the constraints or to the resources b. The
shadow price associated with a resource tells you how much more profit you would get by
increasing the amount of that resource by one unit. So, since the shadow prices for fat, sugar
and protein are all zero, it means that Muad’Dib Bakery does not gain anything for additional
fat, sugar or proteig powder. Shadow prices for water and spice Melange are positive. For
sexampe spice Melange’s shadow price λ5 = 0.4110. This means that if someone is willing to
sell spice Melange to Muad’Dib Bakery with price less than 0.4110 sol/mg, Muad’Dib Bakery
should buy the powder. If the price is more than 0.4110 sol/mg, it does not make sense for
Muad’Dib bakery to buy more spice Melange.
The reduced costs u=xtra. redcosts are related to the decision variables, or to the objective
coefficients c. The reduced costs and the decision variables are complementary in the sense
that if xk > 0 then the associated reduced cost uk = 0, and vice versa. One way of interpreting
the reduced cost is to say that it is the amount of how much profit gained from decision variable
must increase so that it will become optimal to produce it. So, for Muad’Dib the reduced costs
for Atreides and Corrino are both 0, since it is optimal to make them. It is not optimal to
make Harkonnen cakes. The reduced cost u3 = −1.3699 tells us that the price of Harkonnen
cake must be increase to 100+1.37 = 101.37 before it is optimal to make them.