1 | initial version |
The command md.show()
prints various lines of output.
The way printing is done might explain the out-of-orderness.
In Python, when using print
, the string to be printed
is put in a queue of things to be printed. Once in a while,
that queue is "flushed" and the printing actually occurs.
When other commands send things to the output zone, depending on flushing, they might appear out of order.
Sometimes one can remedy the problem by forcing flushing,
which can be done using print('bla', flush=True)
; but here
the print comes from some function, not user code.
The other way to remedy the problem, once we are aware
that some operations are a bit slow and might lead to such
out-of-order output, is to add some pauses, using sleep
.
The command sleep
takes as an argument a number of
seconds, which can be an integer or a float. If a float,
it must be a Python float, not a Sage "real number".
Below we add a short sleep, using the raw float 0.5r
as the
argument to sleep
, where r
is for "raw", which tells the
Sage preparser to leave this as the Python float 0.5
, instead of
transforming it to the Sage "real number" RealNumber('0.5')
.
# Nombre de contraintes et de variables.
nmd, mmd = 10, 6
# Coefficients pour chaque contrainte.
coeffs = [(250, 770, 360, 190, 230, -1),
(0, 0, 0, 0, 0, 1),
(31, 44, 14, 27, 3, 0),
(480, 1770, 800, 580, 160, 0),
(1, 0, 0, 0, 0, 0),
(0, 1, 0, 0, 0, 0),
(0, 0, 1, 0, 0, 0),
(0, 0, 0, 1, 0, 0),
(0, 0, 0, 0, 1, 0),
(0, 0, 0, 0, 0, 1)]
# Matrice des contraintes.
Amd = matrix(nmd, mmd, coeffs)
# Bornes inférieures pour les contraintes.
bmdmin = [0, 600, 30, 0, 0, 0, 0, 0, 0]
# Bornes supérieures pour les contraintes (oo = infini).
bmdmax = [0, 900, 1000, oo, oo, oo, oo, oo, oo, oo]
# Visualisons.
show(LatexExpr("A="), Amd)
show(LatexExpr("bmin="), bmdmin)
show(LatexExpr("bmax="), bmdmax)
# On crée le programme de maximisation.
md = MixedIntegerLinearProgram(maximization=False, solver="GLPK")
# Nouvelles variables: x_0 ... x_2; 'integer' dit si variables à valeurs entières
x = md.new_variable(integer=False, nonnegative=True, indices=[0 .. mmd - 1])
# Fonction linéaire pour les contraintes.
Bmd = Amd * x
# On fixe l'objectif.
md.set_objective(1.2*x[0] + 4.5*x[1] + 3.7*x[2] + 6.3*x[3] + 3.2*x[4])
# On construit les contraintes avec leurs bornes.
for i in range(0,4):
md.add_constraint(Bmd[i], min=bmdmin[i], max=bmdmax[i])
md.show()
sleep(0.5r) # short sleep to prevent out-of-order display <--- !!
md.solve()
xmd = md.get_values(x)
# Le résultat.
show(xmd)
Before adding the sleep(0.5r)
line, the out-of-order display
reported in the question can be observed.
Adding the short sleep seems to alleviate the problem: