8. Manipulating LaTeX Outputs of JuMP#
Suppose you printed an objective function in JuMP, but it is very long and doesn’t fit into the page (either in HTML or LaTeX).
using JuMP
model = Model()
@variable(model, x[1:30] >= 0)
@objective(model, Min, sum(x))
or
print(model)
In these cases, it may be worth considering just using a summary like show(model).
However, if printing is necessary, we can still do so, by modifying the underlying LaTeX string.
For the objective function, we can access the string with
s = objective_function_string(MIME("text/latex"), model)
"x_{1} + x_{2} + x_{3} + x_{4} + x_{5} + x_{6} + x_{7} + x_{8} + x_{9} + x_{10} + x_{11} + x_{12} + x_{13} + x_{14} + x_{15} + x_{16} + x_{17} + x_{18} + x_{19} + x_{20} + x_{21} + x_{22} + x_{23} + x_{24} + x_{25} + x_{26} + x_{27} + x_{28} + x_{29} + x_{30}"
This gives a string that we can modify, for example by adding a line break with \\\\ (special characters need escaping).
s = s[begin:123] * "\\\\" * s[124:end]
"x_{1} + x_{2} + x_{3} + x_{4} + x_{5} + x_{6} + x_{7} + x_{8} + x_{9} + x_{10} + x_{11} + x_{12} + x_{13} + x_{14} + x_{15}\\\\ + x_{16} + x_{17} + x_{18} + x_{19} + x_{20} + x_{21} + x_{22} + x_{23} + x_{24} + x_{25} + x_{26} + x_{27} + x_{28} + x_{29} + x_{30}"
Once we have what we’d like printed, we can render it using the display function. One thing to take note is that the string still requires being put in an appropriate environment.
display("text/latex","\\begin{align*}"*s*"\\end{align*}")
For printing the entire model, the same logic applies, but accessing the string is slightly different. One way of doing so is by using buffers
io = IOBuffer()
JuMP._print_latex(io, model)
s = String(take!(io))
"\$\$ \\begin{aligned}\n\\min\\quad & x_{1} + x_{2} + x_{3} + x_{4} + x_{5} + x_{6} + x_{7} + x_{8} + x_{9} + x_{10} + x_{11} + x_{12} + x_{13} + x_{14} + x_{15} + x_{16} + x_{17} + x_{18} + x_{19} + x_{20} + x_{21} + x_{22} + x_{23} + x_{24} + x_{25} + x_{26} + x_{27} + x_{28}" ⋯ 351 bytes ⋯ "eq 0\\\\\n & x_{18} \\geq 0\\\\\n & x_{19} \\geq 0\\\\\n & x_{20} \\geq 0\\\\\n & x_{21} \\geq 0\\\\\n & x_{22} \\geq 0\\\\\n & x_{23} \\geq 0\\\\\n & x_{24} \\geq 0\\\\\n & x_{25} \\geq 0\\\\\n & x_{26} \\geq 0\\\\\n & x_{27} \\geq 0\\\\\n & x_{28} \\geq 0\\\\\n & x_{29} \\geq 0\\\\\n & x_{30} \\geq 0\\\\\n\\end{aligned} \$\$"
This one is likely much longer and it comes pre-wrapped in a math environment, so one only needs to apply the desired modifications.
When including such a content, you can make use of cell tags to hide the modification code. For example with
```{code-cell}
:tags: [remove-output]
objective_function(model)
```
```{code-cell}
:tags: [remove-input]
s = objective_function_string(MIME("text/latex"), model)
s = s[begin:123] * "\\\\" * s[124:end]
display("text/latex","\\begin{align*}"*s*"\\end{align*}")
```
the resulting HTML/LaTeX will look as if the output was uninterrupted.
objective_function(model)