text:
# LaTeX customization¶

The latex target does not benefit from pre-prepared themes like the html target does (see HTML theming support).

## Basic customization¶

It is available from conf.py via usage of the Options for LaTeX output as described in The build configuration file (backslashes must be doubled in Python string literals to reach latex.) For example:

# inside conf.py
latex_engine = 'xelatex'
latex_elements = {
'fontenc': '\\usepackage{fontspec}',
'fontpkg': '''\
\\setmainfont{DejaVu Serif}
\\setsansfont{DejaVu Sans}
\\setmonofont{DejaVu Sans Mono}''',
'geometry': '\\usepackage[vmargin=2.5cm, hmargin=3cm]{geometry}',
'preamble': '''\
\\usepackage[titles]{tocloft}
\\cftsetpnumwidth {1.25cm}\\cftsetrmarg{1.5cm}
\\setlength{\\cftchapnumwidth}{0.75cm}
\\setlength{\\cftsecindent}{\\cftchapnumwidth}
\\setlength{\\cftsecnumwidth}{1.25cm}''',
'fncychap': '\\usepackage[Bjornstrup]{fncychap}',
'printindex': '\\footnotesize\\raggedright\\printindex',
}
latex_show_urls = 'footnote'

More advanced customization will be obtained via insertion into the LaTeX preamble of relevant \renewcommand, \renewenvironment, \setlength, or \definecolor commands. The 'preamble' key of latex_elements will serve for inserting these commands. If they are numerous, it may prove more convenient to assemble them into a specialized file mystyle.tex and then use:

'preamble': r'\makeatletter\input{mystyle.tex}\makeatother',

or, better, to set up a style file mystyle.sty which can then be loaded via:

'preamble': r'\usepackage{mystyle}',

The build configuration file file for the project needs to have its variable latex_additional_files appropriately configured, for example:

latex_additional_files = ["mystyle.sty"]

## The Sphinx LaTeX style package options¶

The 'sphinxsetup' key to latex_elements provides a more convenient interface to various style parameters. It is a comma separated string of key=value instructions:

key1=value1,key2=value2, ...

• if a key is repeated, it is its last occurence which counts,
• spaces around the commas and equal signs are ignored.

If non-empty, it will be passed as argument to the \sphinxsetup command:

\usepackage{sphinx}
\sphinxsetup{key1=value1,key2=value2,...}

New in version 1.5.

Note

• Most options described next could also have been positioned as sphinx.sty package options. But for those where the key value contains some LaTeX code the use of \sphinxsetup is mandatory. Hence the whole 'sphinxsetup' string is passed as argument to \sphinxsetup.

• As an alternative to the 'sphinxsetup' key, it is possibly to insert explicitely the \\sphinxsetup{key=value,..} inside the 'preamble' key. It is even possible to use the \sphinxsetup in the body of the document, via the raw directive, to modify dynamically the option values: this is actually what we did for the duration of this chapter for the PDF output, which is styled using:

verbatimwithframe=false,
VerbatimColor={named}{OldLace}, TitleColor={named}{DarkGoldenrod},
hintBorderColor={named}{LightCoral}, attentionBgColor={named}{LightPink},
attentionborder=3pt,  attentionBorderColor={named}{Crimson},
noteBorderColor={named}{Olive}, noteborder=2pt,
cautionBorderColor={named}{Cyan}, cautionBgColor={named}{LightCyan},
cautionborder=3pt

and with the svgnames option having been passed to “xcolor” package:

latex_elements = {
'passoptionstopackages': r'\PassOptionsToPackage{svgnames}{xcolor}',
}

Here are the currently available options together with their default values.

Caution

These options correspond to what has been so far the default LaTeX rendering by Sphinx; if in future Sphinx offers various themes for LaTeX, the interface may change.

verbatimwithframe

default true. Boolean to specify if code-blocks and literal includes are framed. Setting it to false does not deactivate use of package “framed”, because it is still in use for the optional background colour (see below).

Attention

LaTeX requires true or false to be specified in lowercase.

verbatimwrapslines
default true. Tells whether long lines in code-blocks should be wrapped.
inlineliteralwraps

default true. Allows linebreaks inside inline literals: but extra potential break-points (additionally to those allowed by LaTeX at spaces or for hyphenation) are currently inserted only after the characters . , ; ? ! /. Due to TeX internals, white space in the line will be stretched (or shrinked) in order to accomodate the linebreak.

New in version 1.5: set this option to false to recover former behaviour.

verbatimvisiblespace
default \textcolor{red}{\textvisiblespace}. When a long code line is split, space characters located at end of the line before the break are displayed using this code.
verbatimcontinued

The default is:

\makebox[2\fontcharwd\font\x][r]{\textcolor{red}{\tiny$\hookrightarrow$}}

It is printed at start of continuation lines. This rather formidable expression reserves twice the width of a typical character in the current (monospaced) font and puts there a small red hook pointing to the right.

Changed in version 1.5: The breaking of long code lines was introduced at 1.4.2. The space reserved to the continuation symbol was changed at 1.5 to obey the current font characteristics (this was needed as Sphinx 1.5 LaTeX allows code-blocks in footnotes which use a smaller font size).

Hint

This specification gives the same spacing as before 1.5:

\normalfont\normalsize\makebox[3ex][r]{\textcolor{red}{\tiny$\hookrightarrow$}

TitleColor
default {rgb}{0.126,0.263,0.361}. The colour for titles (as configured via use of package “titlesec”.) It must obey the syntax of the \definecolor command. Check the documentation of packages color or xcolor.
InnerLinkColor
default {rgb}{0.208,0.374,0.486}. A colour passed to hyperref as value of linkcolor and citecolor.
OuterLinkColor
default {rgb}{0.216,0.439,0.388}. A colour passed to hyperref as value of filecolor, menucolor, and urlcolor.
VerbatimColor
default {rgb}{1,1,1}. The background colour for code-blocks. The default is white.
VerbatimBorderColor
default {rgb}{0,0,0}. The frame color, defaults to black.
verbatimsep
default \fboxsep. The separation between code lines and the frame.
verbatimborder
default \fboxrule. The width of the frame around code-blocks.
shadowsep
default 5pt. The separation between contents and frame for contents and topic boxes.
shadowsize
default 4pt. The width of the lateral “shadow” to the right.
shadowrule
default \fboxrule. The width of the frame around topic boxes.
noteBorderColor

default {rgb}{0,0,0}. The colour for the two horizontal rules used by Sphinx in LaTeX for styling a note admonition. Defaults to black.

Note

The actual name of the colour as declared to “color” or “xcolor” is sphinxnoteBorderColor. The same “sphinx” prefix applies to all colours for notices and admonitions.

hintBorderColor
default {rgb}{0,0,0}. id.
importantBorderColor
default {rgb}{0,0,0}. id.
tipBorderColor
default {rgb}{0,0,0}. id.
noteborder
default 0.5pt. The width of the two horizontal rules.
hintborder
default 0.5pt. id.
importantborder
default 0.5pt. id.
tipborder
default 0.5pt. id.
warningBorderColor
default {rgb}{0,0,0}. The colour of the frame for warning type admonitions. Defaults to black.
cautionBorderColor
default {rgb}{0,0,0}. id.
attentionBorderColor
default {rgb}{0,0,0}. id.
dangerBorderColor
default {rgb}{0,0,0}. id.
errorBorderColor
default {rgb}{0,0,0}. id.
warningBgColor
default {rgb}{1,1,1}. The background colour for warning type admonition, defaults to white.
cautionBgColor
default {rgb}{1,1,1}. id.
attentionBgColor
default {rgb}{1,1,1}. id.
dangerBgColor
default {rgb}{1,1,1}. id.
errorBgColor
default {rgb}{1,1,1}. id.
warningborder
default 1pt. The width of the frame.
cautionborder
default 1pt. id.
attentionborder
default 1pt. id.
dangerborder
default 1pt. id.
errorborder
default 1pt. id.
AtStartFootnote
default \mbox{ }. LaTeX macros inserted at the start of the footnote text at bottom of page, after the footnote number.
BeforeFootnote

default \leavevmode\unskip. LaTeX macros inserted before the footnote mark. The default removes possible space before it.

It can be set to empty (BeforeFootnote={},) to recover the earlier behaviour of Sphinx, or alternatively contain a \nobreak\space or a \thinspace after the \unskip to insert some chosen (non-breakable) space.

New in version 1.5: formerly, footnotes from explicit mark-up were preceded by a space (hence a linebreak there was possible), but automatically generated footnotes had no such space.

HeaderFamily
default \sffamily\bfseries. Sets the font used by headings.

As seen above, key values may even be used for LaTeX commands. But don’t forget to double the backslashes if not using “raw” Python strings.

## The LaTeX environments defined by Sphinx¶

Let us now list some macros from the package file sphinx.sty and class file sphinxhowto.cls or sphinxmanual.cls, which can be entirely redefined, if desired.

• text styling commands (they have one argument): \sphinx<foo> with <foo> being one of strong, bfcode, email, tablecontinued, titleref, menuselection, accelerator, crossref, termref, optional. By default and for backwards compatibility the \sphinx<foo> expands to \<foo> hence the user can choose to customize rather the latter (the non-prefixed macros will be left undefined if option latex_keep_old_macro_names is set to False in conf.py.)

Changed in version 1.4.5: use of \sphinx prefixed macro names to limit possibilities of conflict with user added packages: if latex_keep_old_macro_names is set to False in conf.py only the prefixed names are defined.

• more text styling commands: \sphinxstyle<bar> with <bar> one of indexentry, indexextra, indexpageref, topictitle, sidebartitle, othertitle, sidebarsubtitle, thead, emphasis, literalemphasis, strong, literalstrong, abbreviation, literalintitle.

New in version 1.5: the new macros are wrappers of the formerly hard-coded \texttt, \emph, ... The default definitions can be found in sphinx.sty.

• paragraph level environments: for each admonition type <foo>, the used environment is named sphinx<foo>. They may be \renewenvironment ‘d individually, and must then be defined with one argument (it is the heading of the notice, for example Warning: for warning directive, if English is the document language). Their default definitions use either the sphinxheavybox (for the first listed directives) or the sphinxlightbox environments, configured to use the parameters (colours, border thickness) specific to each type, which can be set via 'sphinxsetup' string.

Changed in version 1.5: use of public environment names, separate customizability of the parameters.

• the contents directive (with :local: option) and the topic directive are implemented by environment sphinxShadowBox. See above for the three dimensions associated with it.

Changed in version 1.5: use of public names for the three lengths. The environment itself was redefined to allow page breaks at release 1.4.2.

• the literal blocks (code-block directives, etc ...), are implemented using sphinxVerbatim environment which is a wrapper of Verbatim environment from package fancyvrb.sty. It adds the handling of the top caption and the wrapping of long lines, and a frame which allows pagebreaks. Inside tables the used environment is sphinxVerbatimintable (it does not draw a frame, but allows a caption).

Changed in version 1.5: Verbatim keeps exact same meaning as in fancyvrb.sty (meaning which is the one of OriginalVerbatim too), and custom one is called sphinxVerbatim. Also, earlier version of Sphinx used OriginalVerbatim inside tables (captions were lost, long code lines were not wrapped), it now uses there sphinxVerbatimintable.

New in version 1.5: the two customizable lengths, the sphinxVerbatimintable, the boolean toggles described above.

• by default the Sphinx style file sphinx.sty includes the command \fvset{fontsize=\small} as part of its configuration of fancyvrb.sty. The user may override this for example via \fvset{fontsize=auto} which will use for listings the ambient font size. Refer to fancyvrb.sty‘s documentation for further keys.

New in version 1.5: formerly, the use of \small for code listings was not customizable.

• the section, subsection, ... headings are set using titlesec‘s \titleformat command. Check sphinx.sty for the definitions.

• for the 'sphinxmanual' class (corresponding to the fifth element of latex_documents being set to 'manual'), the chapter headings can be customized using fncychap‘s commands \ChNameVar, \ChNumVar, \ChTitleVar. Check sphinx.sty for the default definitions. They are applied only if fncychap is loaded with option Bjarne. It is also possible to use an empty 'fncychap' key, and use the titlesec \titleformat command to style the chapter titles.

Changed in version 1.5: formerly, use of fncychap with other styles than Bjarne was dysfunctional.

• the table of contents is typeset via \sphinxtableofcontents which is a wrapper (whose definition can be found in sphinxhowto.cls or in sphinxmanual.cls) of standard \tableofcontents.

Changed in version 1.5: formerly, the meaning of \tableofcontents was modified by Sphinx.

• the bibliography and Python Module index are typeset respectively within environments sphinxthebibliography and sphinxtheindex, which are simple wrappers of the non-modified thebibliography and theindex environments.

Changed in version 1.5: formerly, the original environments were modified by Sphinx.

• the list is not exhaustive: refer to sphinx.sty for more.

Hint

As an experimental feature, Sphinx can use user-defined template file for LaTeX source if you have a file named _templates/latex.tex_t` on your project. Now all template variables are unstable and undocumented. They will be changed in future version.

New in version 1.5.


text:
## LSU Historical Dissertations and Theses

1988

Dissertation

#### Degree Name

Doctor of Philosophy (PhD)

Edward T. Lee

#### Abstract

This thesis addresses the problem of recognizing partially occluded two dimensional objects. The goal is to develop a system which is able to identify and locate several overlapping objects in the scene. To achieve this goal, the system must perform the following specific tasks: (1) storing useful information about objects in some format, which is often referred to as the process of object representation or model formation (2) matching procedure based on the object representation, and (3) efficient search of the best matching. This thesis presents a new approach to accomplish these tasks. Polygonal approximation is used to represent an object in this research. The accumulated lengths of line segments, s, and the accumulated sizes of turning angles, $\theta$, along the boundary from some starting point are extracted. The boundary of an object is then described as an equation $\theta$ = f(s). As algorithm shows, matching objects under s-$\theta$ space will be simple and effective. To avoid exhaustive matching in the recognition process, index diagrams of the features characterizing the boundary are established. Once the features of some unknown object are detected, the possible objects which might produce the best matching can be efficiently retrieved from this scheme.

132

COinS

format: plain


text:
This exercise helps you to recognize the graph of a function, or the function corresponding to a graph. Functions in this interactive exercise are quadratic functions, that is, polynomials of degree 2.

You can make your choices on the configuration of the exercise

• Style of the exercise: .
• Level of difficulty: .
• A session will be composed of questions ( with a score assigned at the end of each session) .

Other exercises on: Graphing   Polynomials   Real function

In order to access WIMS services, you need a browser supporting forms. In order to test the browser you are using, please type the word wims here: and press Enter''.

Please take note that WIMS pages are interactively generated; they are not ordinary HTML files. They must be used interactively ONLINE. It is useless for you to gather them through a robot program.

• Description: recognize the graph of a quadratic polynomial. interactive exercises, online calculators and plotters, mathematical recreation and games
• Keywords: interactive mathematics, interactive math, server side interactivity, wims, ubfc, bourgogne franche-comté,, geometry, algebra, equations, graphing, parabola,polynomials


text:
MathSciNet bibliographic data MR937803 32H05 (32F15 32M05) Bedford, E.; Pinchuk, S. I. Domains in ${\bf C}^2$${\bf C}^2$ with noncompact groups of holomorphic automorphisms. (Russian) Mat. Sb. (N.S.) 135(177) (1988), no. 2, 147--157, 271; translation in Math. USSR-Sb. 63 (1989), no. 1, 141–151 Links to the journal or article are not yet available

For users without a MathSciNet license , Relay Station allows linking from MR numbers in online mathematical literature directly to electronic journals and original articles. Subscribers receive the added value of full MathSciNet reviews.


text:
# Tag Info

0

Solved! The problem was that the babel package was outdated. I runned MikTeX 2.9 Updater (Administrator) and I updated all the packages. After that and a LyX reconfiguration it works now.

0

I just happened to came with the same problem. As Ulrike Fischer and Javier Bezos pointed out, a simple update (as manager) from your MikTeX's administrative tools should work it out.

6

Turkish makes = active which is a known source of problems with keyval-arguments. You can deactivate it with \shorthandoff: \documentclass[a4paper,12pt]{article} \usepackage[utf8]{inputenc} \usepackage{lmodern} \usepackage[turkish]{babel} \usepackage{enumitem} \begin{document} \shorthandoff{=} \begin{enumerate}[label=\Roman*)] \item One \item Two ...

3

The documentation is far from clear, but I don't think there's much more to do than redefining the shorthand to do specific tasks depending on the current language: \documentclass{article} \usepackage[british,ngerman]{babel} \usepackage[utf8]{inputenc} \addto\extrasbritish{% \languageshorthands{ngerman}% \useshorthands*{"}% } ...

5

There is a bug in the redefinition of \@chapter done by arabicore.sty; the same bug is in the redefinition of \@part. \def\@part[#1]#2{% \addtocontents{toc}{\xstring\select@language{\main@Arabi@language}}% \if@rl{\SAV@@part[\textRL{#1}]{\textRL{#2}}}% \else{\SAV@@part[\textLR{#1}]{\textLR{#2}}}% \fi} \def\@chapter[#1]#2{% ...

2

This seems to solve the problem. \documentclass[12pt]{book} \usepackage[utf8]{inputenc} \usepackage[arabic,english]{babel} \begin{document} \chapter{Introduction \label{ch:intro}} We talked about the second chapter \ref{ch:poly}. \section{start} \section{end} \chapter{Polyglot \label{ch:poly}} We talked about the first chapter \ref{ch:intro}. ...

0

I do not know why, but none of the previous answers has worked for me. They showed me the right path though; adding just \deactivatequoting on the preambled fixed the problem. Calling babel with english as well as spanish does the trick, too \usepackage[spanish,english]{babel}

0

To resolve the problematic you can just put the theorem environment inside english context with the usage of otherlanguage environment , and your code becomes: \documentclass[12pt,a4paper]{book} \usepackage{tikz} \usepackage{fancyhdr} \definecolor{ocre}{RGB}{243,102,25} \graphicspath{{Pictures/}} \usepackage{amsmath} \usepackage[LFE,LAE]{fontenc} ...

2

I'm only answering to get the question from the "unanswered queue". Personally I don't think that it is a good idea to overload ascii chars like this. There are too much potential places (e.g. the bib-file) where the char needs to have the "other" meaning. I myself use \MakeAutoQuote{«}{»} together with a sensible shortcut in my editor to put the quotes ...

6

The babel documention states: The macro \<lang>hyphenmins is used to store the values of the \lefthyphenmin and \righthyphenmin. Redefine this macro to set your own values, with two numbers corresponding to these two parameters. So that would be: \renewcommand\ngermanhyphenmins{66}

1

I found a simple solution: \usepackage[ngerman=nohyphenation]{babel}

0

Mexico is not an option for the babel package just put spanish and thats enough \usepackage[spanish]{babel} \begin{document} TEXT \end{document}

0

To get Hebrew to work with pdftex you need to install culmus-latex in order to have proper fonts. The jerus10 file you see reference to was part of the now obsolete Ivritex package. Typesetting Hebrew directly in latex is a nightmare of directionality and I would recommend you to avoid it. Lyx has good support for Hebrew and can be set up to work with ...

2

\mbox{-} should remove the breakpoint.

Top 50 recent answers are included


text:
# American Institute of Mathematical Sciences

2017, 24: 38-52. doi: 10.3934/era.2017.24.005

## Existence and uniqueness of weak solutions for a class of nonlinear parabolic equations

 Department of Mathematics, Shanghai University, Shanghai 200444, China

Received  December 16, 2016 Revised  April 30, 2017 Published  June 2017

Fund Project: The author would like to thank her supervisor Prof. Zhongrui Shi, who supported her throughout her paper with his knowledge, patience and excellent guidance.

In this paper, we study the Dirichlet boundary value problem of a class of nonlinear parabolic equations. By a priori estimates, difference and variation techniques, we establish the existence and uniqueness of weak solutions of this problem.

Citation: Peiying Chen. Existence and uniqueness of weak solutions for a class of nonlinear parabolic equations. Electronic Research Announcements, 2017, 24: 38-52. doi: 10.3934/era.2017.24.005
##### References:

show all references

##### References:
 [1] Zhilei Liang, Jiangyu Shuai. Existence of strong solution for the Cauchy problem of fully compressible Navier-Stokes equations in two dimensions. Discrete & Continuous Dynamical Systems - B, 2020  doi: 10.3934/dcdsb.2020348 [2] Stefano Bianchini, Paolo Bonicatto. Forward untangling and applications to the uniqueness problem for the continuity equation. Discrete & Continuous Dynamical Systems - A, 2020  doi: 10.3934/dcds.2020384 [3] Christian Beck, Lukas Gonon, Martin Hutzenthaler, Arnulf Jentzen. On existence and uniqueness properties for solutions of stochastic fixed point equations. Discrete & Continuous Dynamical Systems - B, 2020  doi: 10.3934/dcdsb.2020320 [4] Thabet Abdeljawad, Mohammad Esmael Samei. Applying quantum calculus for the existence of solution of $q$-integro-differential equations with three criteria. Discrete & Continuous Dynamical Systems - S, 2020  doi: 10.3934/dcdss.2020440 [5] Yichen Zhang, Meiqiang Feng. A coupled $p$-Laplacian elliptic system: Existence, uniqueness and asymptotic behavior. Electronic Research Archive, 2020, 28 (4) : 1419-1438. doi: 10.3934/era.2020075 [6] Shenglan Xie, Maoan Han, Peng Zhu. A posteriori error estimate of weak Galerkin fem for second order elliptic problem with mixed boundary condition. Discrete & Continuous Dynamical Systems - B, 2020  doi: 10.3934/dcdsb.2020340 [7] Lingfeng Li, Shousheng Luo, Xue-Cheng Tai, Jiang Yang. A new variational approach based on level-set function for convex hull problem with outliers. Inverse Problems & Imaging, , () : -. doi: 10.3934/ipi.2020070 [8] Agnaldo José Ferrari, Tatiana Miguel Rodrigues de Souza. Rotated $A_n$-lattice codes of full diversity. Advances in Mathematics of Communications, 2020  doi: 10.3934/amc.2020118 [9] Yifan Chen, Thomas Y. Hou. Function approximation via the subsampled Poincaré inequality. Discrete & Continuous Dynamical Systems - A, 2021, 41 (1) : 169-199. doi: 10.3934/dcds.2020296 [10] Wenjun Liu, Yukun Xiao, Xiaoqing Yue. Classification of finite irreducible conformal modules over Lie conformal algebra $\mathcal{W}(a, b, r)$. Electronic Research Archive, , () : -. doi: 10.3934/era.2020123 [11] Cheng He, Changzheng Qu. Global weak solutions for the two-component Novikov equation. Electronic Research Archive, 2020, 28 (4) : 1545-1562. doi: 10.3934/era.2020081 [12] Yu Zhou, Xinfeng Dong, Yongzhuang Wei, Fengrong Zhang. A note on the Signal-to-noise ratio of $(n, m)$-functions. Advances in Mathematics of Communications, 2020  doi: 10.3934/amc.2020117 [13] Mathew Gluck. Classification of solutions to a system of $n^{\rm th}$ order equations on $\mathbb R^n$. Communications on Pure & Applied Analysis, 2020, 19 (12) : 5413-5436. doi: 10.3934/cpaa.2020246 [14] Mark F. Demers. Uniqueness and exponential mixing for the measure of maximal entropy for piecewise hyperbolic maps. Discrete & Continuous Dynamical Systems - A, 2021, 41 (1) : 217-256. doi: 10.3934/dcds.2020217 [15] Bahaaeldin Abdalla, Thabet Abdeljawad. Oscillation criteria for kernel function dependent fractional dynamic equations. Discrete & Continuous Dynamical Systems - S, 2020  doi: 10.3934/dcdss.2020443 [16] Min Chen, Olivier Goubet, Shenghao Li. Mathematical analysis of bump to bucket problem. Communications on Pure & Applied Analysis, 2020, 19 (12) : 5567-5580. doi: 10.3934/cpaa.2020251 [17] Qingfang Wang, Hua Yang. Solutions of nonlocal problem with critical exponent. Communications on Pure & Applied Analysis, 2020, 19 (12) : 5591-5608. doi: 10.3934/cpaa.2020253 [18] Antoine Benoit. Weak well-posedness of hyperbolic boundary value problems in a strip: when instabilities do not reflect the geometry. Communications on Pure & Applied Analysis, 2020, 19 (12) : 5475-5486. doi: 10.3934/cpaa.2020248 [19] Bo Chen, Youde Wang. Global weak solutions for Landau-Lifshitz flows and heat flows associated to micromagnetic energy functional. Communications on Pure & Applied Analysis, , () : -. doi: 10.3934/cpaa.2020268 [20] Hai-Feng Huo, Shi-Ke Hu, Hong Xiang. Traveling wave solution for a diffusion SEIR epidemic model with self-protection and treatment. Electronic Research Archive, , () : -. doi: 10.3934/era.2020118

2019 Impact Factor: 0.5


text:
# Real Options Valuation with MATLAB: A Mining Economics Case Study

By David Willingham, MathWorks

Committing to the development of a major business initiative, such as a new mine, involves vast amounts of capital expenditure and long time frames—in some cases, up to 30 years. In order to understand the mine’s future economic potential and all associated risks, an accurate risk/return forecast is essential. Traditional spreadsheet solutions, which may use average values or simplistic distributions, often result in inaccurate forecasts that do not adequately assess all possible economic upside and downside risks. A more reliable approach is to use real options valuation.

In real options valuation, a separate model is created for each aspect of the project. The models are then used to simulate distributions of outcomes for different economic scenarios. Using the resultant scenarios, analysts can more accurately assess the upside and downside economic risks and recommend possible responses, such as deferring, abandoning, expanding, staging, or contracting capital investment in the project.

This article shows how MATLAB® can be used to develop and formalize a process for real options valuation of an iron ore mine. Topics include developing price and interest-rate models based on historical data and producing distributions for a range of possible economic outcomes based on calculations of net present value (NPV).

## Using Net Present Value to Determine Future Profit

NPV is a standard method for appraising long-term projects by determining the time value of money. It measures the present value of money today based on the present value in the future, incorporating cash inflow and outflow and taking inflation into account.

Table 1 shows sample input data for calculating a single NPV for a mine's first year of operation. The NPV is calculated based on average values for the many areas of a mine’s operation that involve uncertainty, such as iron ore prices, production rate, and costs, but it does not take into account upside and downside risks. We will need to develop models for some or all these risks. We will use these models to perform thousands of Monte Carlo simulations and generate a distribution of possible outcomes of the mine’s NPV that we can use to measure risk.

Table 1. Input data for calculating a mine’s NPV. Average values are used for production costs and discounting.

To demonstrate this approach, we will develop models for iron ore prices and interest rates (Figure 2).

Figure 2. Net present value calculation model.

## Developing Iron Ore Price Models

To determine what type of model we need, we review the historical iron ore prices (Figure 3). The data shows that the price of iron ore has risen sharply since 2005 and has been quite volatile for the past five years. Speculators believe that the rise is due to the strong growth in China and India, and that it will remain high until economic growth in those countries starts to slow.

Figure 3. Historical monthly iron ore prices, February 1993–September 2012. Source: www.indexmundi.com.

We will simulate two models: a returns-based model based on the assumption that the price will continue to fluctuate for the next two years, and a mean-reversion model based on the assumption that the price will remain stable over that period.

We will use stochastic differential equations (SDEs) to create both models. (SDEs are a typical approach to modeling and simulating uncertain phenomena, such as fluctuating stock prices.)

For the returns-based model, we create a geometric Brownian motion (GBM) SDE. It can be described as:

$dX_t=\mu*X_t*dt+\sigma*X_t*dW_t$

where

$$\mu =$$ Instantaneous rate of return
$$\sigma =$$ Volatility rate

For the mean reversion model, we use a Hull-White/Vasicek SDE with mean-reverting drift:

$dX_t=\alpha*(\mu- X_t)*dt+\sigma*dW_t$

where

$$\alpha =$$ Mean reversion rate
$$\mu =$$ Mean level
$$\sigma =$$ Volatility

Using the gbm and hwv functions in Econometrics Toolbox™, we can create both models in a few lines of code.

Using gbm, the code is as follows:

     sigma = std(returns);
mu = mean(returns);
model = gbm(mu,sigma,'StartState', startdate);

Using hwv, the code is:

     regressors = [ones(length(returns) - 1, 1) returns(1:end-1)];
[coefficients, intervals, residuals] = regress(diff(returns), regressors);
dt    = 1;
speed = -coefficients(2)/dt;
level = -coefficients(1)/coefficients(2);
sigma =  std(residuals)/sqrt(dt);
model = hwv(speed,level,sigma,  'StartState',startdate);

Once we have created the models, we simulate them using the forecasted time frame, number of simulations, and type of model as inputs:

     NTrials = 1000;
years = 8;
ann = 12;
NSteps = years*ann;

     tic
Xsim = simulate(model, NSteps, 'NTrials', NTrials, 'DeltaTime', dt);
Xsim = squeeze(Xsim); % Remove redundant dimension
toc
Elapsed time is 0.026889 seconds.

Note that it took only a fraction of a second to complete 1000 simulations.

Figures 4 and 5 show the simulation results for each model.

Figure 4. Forecasting iron ore prices based on GBM model.

Figure 5. Forecasting iron ore prices based on HWV model.

Each model predicts a different outcome in response to a downturn in prices: With the GBM model the forecasts trend downwards, while with the HWV model, they return to a mean. With these two models available, we will be able to plan for both scenarios.

## Modeling Interest Rates

Interest rates tend to revert to a mean; in Australia, that has been the case for the past 30 years. For this reason, we will use the HWV model, modifying it to reflect historical interest rates.

Figure 6 shows the historical interest rates, with an average mean level of 5.5%.

Figure 6. Historical Australian interest rates. Source: www.rba.gov.au.

Figure 7 shows a histogram of the spread of 1000 simulations of the interest rate model with a mean of approximately 5.5%. The mean is what we expected; however, there is some upside and downside risk with the tails of the interest rates +/- 2.5% (or 50% away from the mean).

Figure 7. Histogram of final interest rate values based on HWV model.

## Calculating Net Present Value

The final task is to calculate the discounted cash flow and the final NPV of the mine.

NPV can be summarized as follows:

DiscountFactor = exp(-interest*timeperiod)
NPV = (Cashflow – Costs)*DiscountFactor

Now that we have calculated the NPV of the mine based on the GBM and HWV models, we can run scenarios on iron ore prices (either mean reverting or based on returns and interest rates).

First, let’s look at a scenario that uses the HWV iron ore price model. Figure 8 shows the NPV distribution of cash flow when running this model. It also shows the cash flow values around certain outcomes, such as mean, 5% value at risk, and a base rate of \$108 per tonne. Using the Distribution Fitting app in Statistics and Machine Learning Toolbox™, we calculate these values from a normal distribution for HWV and a generalized extreme value distribution for GBM. Note that in this scenario, all possible outcomes are positive, so that if iron ore prices revert to the mean, the mine should continue to be profitable.

Figure 8. Net present value, derived from HWV model.

Now let’s look at a scenario where we use the GBM model. As Figure 9 shows, some of the cash flow results are negative, and 55% of the simulations result in a negative value. If iron ore prices continue to decline, the mine should cease production until they rise again or until costs can be reduced.

Figure 9. Net present value derived from GBM model.

## Assumptions and Future Improvements

The models in our examples were chosen based on the assumption that Brownian motions of the prices and interest rates are independent and uncorrelated, whereas in reality they could be linked. To provide a more realistic forecast for NPV, the models could be jointly calibrated and simulated to introduce a correlation. The SDE framework within Econometrics Toolbox supports this level of modeling.

## Reusable Forecasting

The purpose of performing real options valuation was to help us decide whether the mine should continue to operate or be put on hold. Focusing on iron ore prices and interest rates, we modeled and forecast 1000 potential outcomes of NPV using an approach that was fast, efficient, and reusable. The two scenarios produced very different outcomes, resulting in different “real options.” We would need to compare each model with actual prices and then rerun the models to see whether the outcomes change with time.

Published 2013 - 92117v00


text:
# Why function cannot be defined inside For loop? [closed]

I have a following code (which is simplified version of what I am doing):

For[i = 1, i <= 5, i++,
f[x_] := Sin[x]^2
Print[{i, f[i]}]
]

And the question is simple: why such thing doesn't work at all. It does not write any output, nor it prints anything, nor it displays any error. Just nothing.

-

## closed as too localized by Sjoerd C. de Vries, Leonid Shifrin, belisarius, Ajasja, Oleksandr R.Apr 26 '13 at 13:10

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

Why put the function definition inside the loop, even? Take it out of the loop; you save some effort that way. –  Ｊ. Ｍ. Apr 26 '13 at 11:50
@J.M.: because I have reason for putting it inside. In fact the function is a bit different everytime. And I can do such thing in Scilab, Python or in C++. –  Misery Apr 26 '13 at 11:54
You should have mentioned in your question that your function is changing. But also in this case, you should try to define it outside of your for loop (or Table). E.g. you could work with a Piecewise function. But it is difficult to give more exact hints without knowing the problem better. Btw: You do not get an error message, because your code is not really wrong (the syntax is correct – but not the logic). Run it and check the result of f[1], then you see that your code worked – just in a way you do not want it to work. –  partial81 Apr 26 '13 at 12:07
Why was this closed? Because it was just a programming error? I have seen other examples of this in questions that are not closed. The "too localized" doesn't feel right to me. Also the rage about using a loop seems unnecessary to me. Reminds me of when people use capital letters for symbols/function names. True, but needless comments. –  Gabriel Apr 26 '13 at 17:28
@Gabriel: for i in range(1,10): def ABC(y): print(y) ABC(i) Of course I can. Just get the indent right. –  Misery Apr 26 '13 at 18:10

I think you only forgot a comma. Try:

For[i = 1, i <= 5, i++, {f[x_] := Sin[x]^2, Print[{i, f[i]}]}]

If I were you, I would not define a function in a For Loop (can be time consuming). And, if possible, I would work with a Table because this works faster too. So do something like:

f[x_] := Sin[x]^2;
Table[{i, f[i]}, {i, 1, 5}]

-
Why a list rather than a CompoundExpression (;)? Now you make it look even more like its another language ;). –  Jacob Akkerboom Apr 26 '13 at 11:58

It is of course possible to redefine functions within loops in Mathematica. You are actually just missing a semicolon at the right place for your code to work as intendend:

For[i = 1, i <= 5, i++,
f[x_] := Sin[x]^2;
Print[{i, f[i]}]
]

It's probably worth noting (as Jacob did in his comment) that the semicolon is just a shortcut for a CompoundExpresson, so something like a;b;c looks like this in FullForm: CompoundExpression[a,b,c], which you can check with e.g. FullForm[Hold[a;b;c]]. As the default evaluation order is to evaluate arguments from left to right, you could actually use any other symbol without (matching) definitions and Hold attributes instead of CompoundExpression, which is why e.g. List in the other answer also works, but of course using CompoundExpression is much more standard and clear. The main difference is that CompoundExpression returns the return value of its last argument, which other symbols won't do, the following might make these subtleties more clear:

Print[a];Print[b];c
CompoundExpression[Print[a],Print[b],c]
{Print[a],Print[b],c}
List[Print[a],Print[b],c]
somethingelse[Print[a],Print[b],c]

Without that semicolon (CompoundExpression) what you do is to redefine f[x_] to Sin[x]^2*Print[{i,f[i]}] in every loop pass without ever using that function. This is also the reason why you don't see any output. As it is perfect valid code there is no reason to expect any error or even warning messages - Mathematica can't (yet) guess that this is not what you intended...

You'll often find that people tell you to not use loops in Mathematica, but I think there are many cases where using loops is the right thing to do. You'll find that other constructs will give you better performance, less typing and still clearer code in many cases, though. Learning those other possibilities will be of great advantage if you plan to use Mathematica more often in the future. For reasons mentioned e.g. in answers to this question I'd strongly suggest to avoid For loops, though. Here is the same thing using a Do loop:

Do[
f[x_] := Sin[x]^2;
Print[{i, f[i]}],
{i,5}
]

You should also learn about the difference of Printing a result and returning it. In almost all cases you want to return what you calculate and not just print it, and thus you'd probably rather use something like this:

Table[
f[x_] := Sin[x]^2;
{i, f[i]},
{i,5}
]

-