\documentclass{report}[fleqn,12pt]
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{enumitem}
\usepackage{bm}
\usepackage{blindtext}
\usepackage{scrextend}
\usepackage{geometry}
\usepackage{fancyhdr}
\usepackage{graphicx}
\geometry{letterpaper}

\graphicspath{{../docs/images}}

\makeatletter
\def\@makechapterhead#1{%
  \vspace*{50\p@}%
  {\parindent \z@ \raggedright \normalfont
    \interlinepenalty\@M
    \huge \bfseries \thechapter.\ #1\par\nobreak
    \vskip 40\p@
  }}
\def\@makeschapterhead#1{%
  \vspace*{50\p@}%
  {\parindent \z@ \raggedright
    \normalfont
    \interlinepenalty\@M
    \huge \bfseries \thechapter.\ #1\par\nobreak
    \vskip 40\p@
  }}
\makeatother

\begin{document}
\title{Formulation of the optimization model in Owl}
\author{Martin-D. Lacasse}
\date{\today}
\maketitle
\thispagestyle{fancy}
\fancyfoot[R]{\copyright\ 2024 - Martin-D. Lacasse}
\fancyhead{}

\chapter{Introduction}
This document describes the mathematical model underlying
the optimization algorithms implemented in
Owl, which is a Python application optimizing retirement
planning using linear programming. The goal of
these calculations is to optimize the financial aspects
of retirement planning, considering the types of savings accounts,
federal income tax, contributions, return rates, Medicare premiums, Roth conversions,
and desired income amongst many other things.

The approach is described here mathematically and the Python implementation
follows the structure and notation presented in this document.
The intent of this document is to provide a guide to the source code
for any individual desiring to extend the model to other cases.
The mathematical description is not tied to any specific mathematical
programming language so that it remains as generic as possible and
can be solved using different linear solvers.

\chapter{Indices, variables, and parameters}
In the next sections, the indices, variables, and parameters are
described in detail. Then the model constraints are introduced.
For implementation in a linear programming solver, index mapping
functions are introduced to map all variables into a single
one-dimensional array that
is optimized subject to inequality and equality constraints
expressed in matrix form. Finally, the constraint matrices are built
and so are some useful objective functions.

\section{Indices}
For all indices, we will follow the C array style (starting at 0),
rather than the traditional mathematical standard starting at 1.
This will facilitate the final
sequential mapping of all the variables into a single one-dimensional array,
and serve as a direct reference for better understanding the code implementation.

The indices used and their range are defined here, while we also
introduce the characteristics and dimensions of the problem.
Upper bounds on indices are indicated by the letter $N,$ with the
index name as a subscript, e.g., $N_i$ for index $i$. In other instances,
the subscript will indicate that the array depends on subscripts, for example,
$b_{ikn}$ is a multidimensional array depending on subscripts $i, k,$ and $n$.
\begin{description}[leftmargin=4em,style=multiline]
\item [$i$]
	Individual. $i$ runs from 0 to $N_i - 1$ where $N_i = 2$ for couples,
	or $N_i= 1$ for single individuals. The first individual to pass
	is denoted by $i_d$ while the survivor is $i_s$.
\item [$j$]
	Type of savings account. $j$ goes from 0 to $N_j - 1$, for taxable, tax-deferred,
	and tax-free accounts respectively. Therefore $N_j = 3$.
\item[$k$]
	Type of asset class. $k$ goes from 0 to $N_k -1 $, for S\&P 500,
	Baa corporate bonds, Treasury notes, and cash, respectively,
        and therefore $N_k = 4$.
	More asset classes could be considered at the cost of increasing
	the complexity of the problem while not generating much more insights.
\item [$n$]
	Index of the year being modeled. Period being modeled runs from the beginning of year 0 to 
	the end of year $N_n-1$, and therefore $N_n + 1$ years are actually considered.
	Year $N_n$ is the first year following the passing of all
	individuals in the plan. The time period for all decision variables is annual.
	For spouses, the end of year $n_d-1$ is when the first individual is assumed to pass while
	the survivor will decease at the end of year $N_n-1$ of the plan.
\item [$q$]
	Index for income brackets related to Medicare premium adjustments.
	$q$ goes from 0 to $N_q - 1$, from low to high.
	At the time of writing, there are 5 Medicare premium steps adjustments
        in the federal tax code separating $N_q = 6$ income brackets.
\item [$t$]
	Federal income tax bracket. $t$ goes from 0 to $N_t - 1$, from low to high.
	At the time of writing, there are $N_t = 7$ federal income tax brackets in the current federal tax code.
\end{description}

\section{Variables}
We will use lowercase roman letters to represent variables. This is done to separate
variables from parameters, which will be represented using
Greek letters or caligraphic fonts. All variables are assumed
to take only non-negative values ($\ge 0$ inequality). Variables are resolved by the optimizer
while parameters are prescribed by the user, historical data, or tax laws.
\begin{description}[leftmargin=4em,style=multiline]
\item [$b_{ijn}$]
	Balance for individual $i$ in savings account $j$ at the beginning of year $n$.
	When we consider each asset class $k$, the variable $b_{ijkn}$ is used instead.
\item [$d_{in}$]
	Deposit of year-$n$ net spending surplus in taxable account of individual $i$.
	These deposits are coming from the surplus $s_n$, distributed to
	spousal taxable accounts depending on parameter $\eta$.
\item [$e_{n}$]
	Adjusted standard exemption for year $n$. This is a variable as the taxable income can
        sometimes be less that the standard exemption $\bar{\sigma}_n$, leading to a
	negative taxable income if the inflation-adjusted standard exemption is simply subtracted
	from the gross taxable income $G_n$ in years of low income.
\item [$f_{t n}$]
	Fraction of tax bracket $t$ filled, so that taxable ordinary income $G_n$ can be expressed as
	\begin{eqnarray}
		G_n = \sum_t f'_{t n}\bar{\Delta}_{t n},\\
		0 \leq f'_{t n} \leq 1.
	\end{eqnarray}
	When considering taxes,
	the product $\bar{\Delta}_{tn}\theta_{tn}$ does not guarantee to
	be ordered monotonically. It is therefore more appropriate to use the combined variable
	$\bar{f}_{tn} = f'_{tn}\bar{\Delta}_{tn}$ in the optimization. Given that the rates on
	tax brackets $\theta_{tn}$ are increasing monotonically with income, the lower brackets
	will be filled in first when optimizing. The ordinary taxable income can then be expressed as
	\begin{equation}
		\label{Eq:Tx1}
		G_n = \sum_t \bar{f}_{tn},
	\end{equation}
	with $\bar{f}_{tn}$ bound between 0 and the bracket width $\bar{\Gamma}_{tn} - \bar{\Gamma}_{(t-1)n}$. 
	Definitions of $\Gamma_{tn}$ and $\Delta_{tn}$ are in the section describing the parameters below. 

\item [$g_n$]
	Net spending in year $n$.
\item [$m_n$]
	Medicare costs in year $n$, including part B premiums and IRMAA income-related adjustments.
\item [$s_{n}$]
	Surplus of funds during year $n$, most likely caused by required minimum distributions (RMDs)
	or influx of money from big-ticket items (inheritance, gifts, sale of a house, etc.).
\item [$w_{ijn}$]
	Withdrawal from account $j$ belonging to individual $i$ at the beginning of year $n$.
	For the $(j=1)$ tax-deferred savings account, $w_{i1n}$ is referred to as a distribution for
	tax purposes as it is a taxable withdrawal, and will always satisfy required minimum distributions.
\item [$x_{in}$]
	Roth conversion performed by individual $i$ during year $n$.
	These events are taxable as ordinary income.
\item [$z_{*}^*$]
	Binary variables are all designated by the letter $z$, but a superscript is
	used to distinguish the different families. For example, $z_{qn}^m$ represents
	binary variables associated with Medicare calculations.
\end{description}

\section{Parameters}
For more easily distinguishing parameters from variables, all parameters are expressed
either in Greek letters or using caligraphic fonts.
Parameter values are either set by the user, historical data, or by the tax code.
\begin{description}[leftmargin=4em,style=multiline]
\item [$\beta_{ij}$]
	Initial balances in savings accounts. These amounts are used to initialize $b_{ij0}$.
\item [$\tau_{kn}$]
	Annual rate of return for asset class $k$ in year $n$.
	A time series of annual return rates for each class of asset.
	Here, inflation and the rate of return of cash $(k=3)$ are assumed to be the same.
	In other words, investing in cash yields constant dollars as the return perfectly
	matches inflation.
\item [$\gamma_n$]
	Cumulative inflation at the beginning of year $n$ computed as the product
	\begin{equation}
		\gamma_n = \prod_{n' = 0}^{n-1} (1 + \tau_{3n'}),
	\end{equation}
	with $\gamma_0 := 1$, and where $n'$ is a dummy index.
	As the time span of interest goes from the beginning of the first year to the beginning
        of the year following the last year, variable $\gamma_n$ will have $N_n + 1$ elements.
	Parameters indexed for inflation will be indicated by a bar on top as in $\bar{\sigma}_n$.
	See the next entry for a specific example.
\item [$\sigma_n$]
	Standard deduction. It can be adjusted for inflation as follows
	\begin{equation}
		\bar\sigma_n = \sigma_n \gamma_n,
	\end{equation}
	and can be modified for additional exemptions after 65 of age, for example.
	It is a simple time series
	which can include any foreseeable changes in the tax code, or change in filing status due to the
	passing of one spouse for $n\ge n_d$.  The value of $\bar{\sigma}_n$ is an upper bound for variable $e_n$.
\item [$\xi_{n}$]
	Spending profile. This is a time series that multiplies a basis for the desired net spending amount.
	It is $\xi_n =1, \forall n$ for
	a flat profile, or can be a {\em smile} profile allowing for more money at the start
	of retirement and modulating it over retirement. Parameter
	$\xi_n$ can also contain spending adjustments typically made at the passing of one spouse.
	The {\em smile} can be implemented using a cosine superimposed over a gentle linear increase
	such as in
	\begin{equation}
		\xi_n = 1 + a_1*\cos(2n\pi/(N_n-1)) + a_2n/(N_n-1),
	\end{equation}
	and then normalized by factor $N_n/(\sum_n \xi_n )$ to be sum-neutral with respect to a flat profile.
	Values of $a_1 = 15\%$ and $a_2=12\%$ provide curves that are similar to realistic
	spending profiles reported in the literature. See Fig.~\ref{Fig:profile} for an example.
	At the passing of one spouse, both profiles are reduced by a factor $\chi$ for $n \ge n_d$,
	and the normalizing factor is adjusted accordingly.
	\begin{figure}[t]
	    \includegraphics{profile.png}
	    \caption{\small Example of a spending profile with 15\% cosine factor and a 12\% linear
	    profile. \label{Fig:profile}}
	\end{figure}
\item [$\chi$]
	Factor to reduce spending profile after the passing of one spouse. It is typically
	assumed to be 0.6. That is, we are assuming that the surviving spouse can live with
	60\% of the net spending amount that was available to the couple.
\item [$\rho_{in}$]
	Required minimum distribution for individual $i$ in year $n$. Expressed in fractions
	which are determined from IRS tables. These tables are simple if spouses are less than 10 years apart,
	but a little more complex otherwise, as the age of both spouses need to be taken into account.
	Current implementation only supports spouses being less that 10 years apart.
	An error message is generated if spouses are more than 10 years apart
        and the calculation is aborted.
\item [$\Gamma_{tn}$]
	Bounds for federal income tax brackets. We define $\Gamma_{(-1)n} := 0$, so that
	$\Gamma_{0n}$ is the upper bound for the 10\% tax bracket in year $n$. As the filing status
	can change for couples, and so can the tax code, $\Gamma_{tn}$ will be changing over $n$.
\item [$\Delta_{tn}$]
	Difference between upper bound $\Gamma_t$ and lower bound $\Gamma_{t-1}$
	of a federal income tax bracket,
	\begin{equation}
		\Delta_{tn} = \Gamma_{tn} - \Gamma_{(t-1)n}.
	\end{equation}
	Once adjusted for inflation,
	the taxable income can be expressed as in Eq.~(\ref{Eq:Tx1}). These data are 7 time series.
	The filing status changes after the passing of one spouse ($n \ge n_d$) and income tax
	brackets and differences are adjusted accordingly.
\item [$\theta_{tn}$]
	Tax rate for tax bracket $t$ in year $n$. Using $N_t$ time series allows to adjust income
	tax rates in the foreseeable future.
	For example, in 2024 the rates (in decimal) are .10, .12, .22, .24, .32, .35, and .37.
        While these rates were extended indefinitely by Congress in 2025, they could still
	revert back to 2017 or similar higher rates in the future to
	.10, .15, .25, .28, .33, .35, and .396. See Eq.~(\ref{Eq:IncTax1}) for its use.
\item [$\alpha_{ijkn}$]
	Desired asset allocation for savings account $j$ of individual $i$ in
	assets class $k$ during year $n$.
	Allocation ratios come in many flavors as they could be specified globally between
	individuals and accounts as $\alpha_{kn}$, for example.
	When specified by the user, allocation ratios are given two values, one at the
	beginning of the plan $\alpha_{ijk0}$ and the other at the end
	$\alpha_{ijkN_{n-1}}$, or $\alpha_{ijkn_d}$ for a spouse passing before the other.
        Then, intermediate values are interpolated either using
	a linear relation,
\begin{equation}
	\alpha_{ijkn} = a + \frac{n}{N - 1} (b - a),
\end{equation}
where $N$ is either $n_d$ or $N_n$,or using an s-curve as in
\begin{equation}
	\alpha_{ijkn} = a + \frac{(b - a)}{2}
	(\tanh((n-n_1)/n_2) + 1),
\end{equation}
	where $n_1$ is the number of years ahead when inflection point will occur, and $n_2$ is the
	width (in years) of the transition. Constants $n_1$ and $n_2$ can be adjusted by the user.
	Default values are $n_1 = 15$, and $n_2 = 5$, meaning that the transition center will occur
	in 15 years, taking place from $15-5$ years to $15+5$ years from now.
	Using $a = \alpha_{ijk0}$ and $b = \alpha_{ijk(N-1)}$ is an approximation as values of $\pm 1$
	are only reached at $\pm \infty$ for a hyperbolic tangent.
	More precise bounds $a'$ and $b'$ for matching the desired start and end values
	can be determined by solving a $2\times 2$ system of equations leading to
	\begin{eqnarray}
		a' &=& (a - k_{12}b')/k_{11} \nonumber \\
		b' &=& (b - (k_{21}/k_{11})a)/(k_{22} - (k_{21}/k_{11})k_{12}),
	\end{eqnarray}
	where
	\begin{eqnarray}
		k_{11} &=& \frac{1}{2}(1 + \tanh(n_1/n_2)) \nonumber \\
		k_{12} &=& \frac{1}{2}(1 - \tanh(n_1/n_2)) \nonumber \\
		k_{21} &=& \frac{1}{2}(1 - \tanh((N-1-n_1)/n_2)) \nonumber \\
		k_{22} &=& \frac{1}{2}(1 + \tanh((N-1-n_1)/n_2)).
	\end{eqnarray}
	These interpolation functions allow the allocation ratios to gradually change
	or {\em glide} during retirement. Fig.~\ref{Fig:allocations} provides an example
	of an {\em s-curve} gliding allocation ratios.

	\begin{figure}[t]
	\includegraphics{allocations.png}
		\caption{\small Example of an allocation portfolio with 60/40\% stocks/bonds 
		transitioning to 70/30\% using an s-curve. \label{Fig:allocations}}
	\end{figure}
	It is also possible to have a coarser granularity on the portfolio by
	having an asset allocation scheme
	defined on a sum of accounts. For example, allocation can be coordinated between accounts
	leading to $\alpha_{ikn}$, or even between spouses as $\alpha_{kn}$.
	For any of these cases, it is assumed that weights are always properly scaled so that
	\begin{eqnarray}
		\sum_k \alpha_{ijkn} &=& 1, \nonumber\\
		\text{or} \qquad \sum_k \alpha_{ikn} &=& 1, \nonumber\\
		\text{or} \qquad \sum_k \alpha_{kn} &=& 1,
	\end{eqnarray}
	depending on the scheme selected.

\item[$\mathcal{T}_{ijn}$]
	When the allocation ratios $\alpha_{ijkn}$ are prescribed,
	it is sometimes more convenient to express the return rates as
	\begin{equation}
		\mathcal{T}_{ijn} = \sum_k \alpha_{ijkn} \tau_{kn}.
	\end{equation}

\item [$\Lambda^\pm_{in}$]
	Big-ticket item requested by individual $i$ in year $n$.
	These are large expenses or influx of money
	that can be planned. Therefore, $\Lambda^\pm$ can be positive
	(e.g., sell a house, inheritance) or negative (e.g., buy a house, large gifts).
\item [$\lambda$]
        Allowed deviation from the desired net spending profile during one year. Parameter
        $\lambda$ can be better understood as a percentage. If $\lambda = 0.10$, then net spending
	amount is allowed to vary by up to 10\% from the prescribed profile.
	This parameter is mainly provided for educative purposes.

\item [$\pi_{in}$]
	Sum of pension benefits for individual $i$ in year $n$. These amounts are typically
	specified along with the ages at which these benefits begin.
	Pensions can optionally be indexed for inflation and then represented as $\bar{\pi}_{in}$.
\item [$\zeta_{in}$]
	Social security benefits for individual $i$ in year $n$. Starting age and the passing
	of one individual for spouses will determine the time series. $\bar{\zeta}_{in}$ is
	the same series adjusted for inflation.
\item [$\epsilon_{N_n}$]
	Desired amount to leave as a bequest at the end of the final year of the plan, $N_n-1$,
	which is the beginning of year $N_n$. This amount is the after-tax value of the estate
	for the heirs expressed in today's dollars. See parameter $\nu$ for the heirs tax rate.
\item [$\kappa_{ijn}$]
	Sum of contributions to savings account $j$ made by individual $i$ during year $n$.
	We assume that contributions are made at half-year to better represent periodic
        contributions made throughout the year.
	In practice, a contribution
	amount $\kappa_{ijn}$ is specified in which case the contribution to each asset
	class is
	\begin{equation}
		\kappa_{ijkn} = \alpha_{ijkn}\kappa_{ijn}.
	\end{equation}
\item [$\omega_{in}$]
	Sum of wages obtained by individual $i$ during year $n$.
	Do not confuse wages $\omega$ with withdrawals $w$.
\item [$\mathcal{C}_{q}$]
	Cost of Medicare for bracket $q$ of modified adjusted gross income (MAGI). This includes
	Medicare part B premiums and any additional
	Income-Related Monthly Adjusted Amount (IRMAA). When adjusted
	for inflation, this becomes $\bar{\mathcal{C}}_{qn} = \gamma_n\mathcal{C}_q$.
        There are $N_q = 6$ brackets for IRMAA and therefore 5 step adjustments forming
        a piecewise constant function.
\item [$\mathcal{L}_{q}$]
	Income brackets used to determine Medicare adjustments based on the modified adjusted gross income.
	When adjusted for inflation, this becomes $\bar{\mathcal{L}}_{qn} = \gamma_n\mathcal{L}_q$.
        While there are 6 brackets for IRMAA adjustments forming a piecewise constant function,
	$\mathcal{L}_q$ has $N_q - 1$ distinct thresholds as the last element is an arbitrary large
        number bounding the last bracket. See Fig.~\ref{Fig:piecewise} for a visual representation.
        Note that $\bar{\mathcal{L}}_{qn}$ needs to be adjusted for inflation and marital status,
        including adjustments due to the passing of one spouse.
\item [$\mu$]
	Dividend return rate for equities in taxable accounts. Average is near 2\% for S\&P 500.
\item [$\nu$]
	Heirs income tax rate to be applied on the tax-deferred portion of the estate. This is not an estate tax
	but rather the federal income marginal tax rate that heirs would have to pay on inherited tax-deferred accounts.
\item [$\phi_j$]
	Fraction of savings account $j$ that is left to surviving spouse $i_s$ as a beneficiary
	at the death of individual $i_d$, the first spouse to pass.
\item [$\psi$]
	Income tax rate on long-term capital gain and qualified dividends. Rate $\psi$ is 0, 15, or 20\%
	depending on gross income. If adjusted self-consistently for income, then $\psi$ becomes
 	time series $\psi_n$.
\item [$\Psi$]
	Fraction of social security that is taxed, which depends on gross income and maxes out at 85\%.
        If adjusted self-consistently for income, then $\Psi$ becomes time series $\Psi_n$. However,
	given how low the threshold (around \$44k the married couples) is for reaching the
	maximum taxation level of 85\%, it is fixed at this value in Owl.
\item [$\eta$]
	Spousal ratio for surplus deposits, which goes from 0 to 1, as the fraction
	that goes to the $i = 1$ spouse's account. Therefore, a surplus $s_n$ in year $n$
	will result in a deposit $d$ in the taxable account of individual $i$ as
	\begin{eqnarray}
		\label{Eq:eta}
		d_{0n} & = & (1 - \eta) s_n \nonumber\\
		d_{1n} & = & \eta s_n.
	\end{eqnarray}
	This choice is such that we can set a value depending on the surviving
	individual $\eta = i_s$ for $n \ge n_d$, after the passing of $i_d$.
	Default value is $(N_i - 1)/2$, i.e., $0.5$ for couples and $0$ for single individuals.
	When the beneficiary of the savings accounts is not the other spouse, i.e., 
	when $\phi_j \neq 1, \forall j$, it is recommended that $\eta$ be set to $i_d$ so that
	all surplus get deposited to $i_d$'s accounts,
	thus avoid loopholes when optimizing for the final bequest.
\item[$\mathcal{M}$]
	This large constant is used in the so-called big-$\mathcal{M}$ method to implement
	binary constraints. As this is mainly used around MAGI, a value of about $10^7$ should
	be adequate for most cases.
\end{description}

\section{Intermediate variables}
We use intermediate variables for conciseness or clarity,
but they are ultimately replaced in the final formulation.
Intermediate variables are represented in roman uppercase letters, or in double stroke uppercase letters.
\begin{description}[leftmargin=4em,style=multiline]
\item [$G_n$]
	Taxable ordinary income in year $n$. Sum of wages, pension, social security benefits, all withdrawals
	from tax-deferred accounts, including Roth conversions, and gains from securities
	(i.e., all gains except those from the $k=0$ equities, which are taxed as capital gains)
	in the ($j=0$) taxable account, including contributions $\kappa$, minus the standard deduction,
	\begin{eqnarray}
		\label{Eq:Tx2}
		G_n &=& 
		\sum_i [\omega_{in} + \Psi_n\bar\zeta_{in} + \bar{\pi}_{in}]
		- e_n
		\nonumber \\
		&& + \sum_i [w_{i1n} + x_{in}]
		\nonumber \\
		&& + \sum_{i,k} 
		[(1-\delta(k, 0))(b_{i0n} - w_{i0n} + d_{in} + 0.5\kappa_{i0n})\alpha_{i0kn}\tau_{kn}]
	\end{eqnarray}
	Social security is indexed for inflation and is assumed to be taxed at $\Psi_n$\%.
	Pensions can optionally be indexed for inflation.
	We use a discrete Kronecker $\delta$ function for selecting gains from non-equity assets in
	taxable accounts, but we could have equivalently excluded $k \neq 0$ in the sum.
	These gains are all taxed as ordinary income. Here, we assumed that
	withdrawals and deposits in the taxable account are taking place at the beginning of the year, while
	contributions, if any, are taking place in mid-year.

\item [$Q_n$]
	Qualified dividends and long-term capital gains obtained in year $n$.
	They only involve dividends occurring in the taxable savings accounts $(j=0)$ that
	were obtained from equities $(k=0)$, or sales of stocks due to withdrawals
	from taxable savings accounts.
	For simplicity, we assume that all equity sales only generate long-term capital gains and
	that all dividends are qualified, resulting in
	\begin{equation}
		\label{Eq:Qx2}
		Q_n = \sum_i \alpha_{i00n}\left[(b_{i0n} - w_{i0n} + d_{in} + 0.5\kappa_{i0n})\mu +
		w_{i0n}{\max(0, \tau_{0(n-1)})}\right].
	\end{equation}
	A formulation where only a fraction of dividends are qualified can easily be
	implemented with the addition of another parameter.
	Notice that we are using return rates from the previous year.
	The first terms on the right-hand side represent dividends generated by
        equities $(k=0)$ in the $(j=0)$ taxable savings account plus
	half the yearly contributions. The second term accounts for withdrawals $w$
        of equities assumed to have been purchased a year ago. 
	It does not account for losses, but a market drop
	would most likely result in stock purchase rather than sale.
	For withdrawals, we make the assumption of
	selling the most recent stocks which would not be accurate in situations where
	the taxable savings account is being depleted slowly. An implementation keeping track
	of stock purchases and sales is beyond the scope of providing a guide for retirement decisions.

\item [$\mathbb{G}_n$]
	Modified Gross Adjusted Income or MAGI for year $n$. We approximate it as
	\begin{equation}
		\mathbb{G}_n = G_n + Q_n + e_n.
	\end{equation}
	This approach ignores additional IRS
	rules around tax-free interests which are insignificant in most cases.

\item [$\mathbb{I}_n$]
	Interests earned from taxable account.
	\begin{equation}
		\mathbb{I}_n = \sum_{i,k\neq 0} [(b_{i0n} - w_{i0n} + d_{in}
		     + 0.5\kappa_{i0n})\alpha_{i0kn}\tau_{kn}].
	\end{equation}

\item [$P_n$]
	Amount of 10\% early withdrawal penalty in year $n$,
	\begin{equation}
		\label{Eq:PenTax0}
		P_n = 0.10 \sum_{i, j\neq0} (1 - \mathcal{H}(n - n_{i,59})) w_{ijn}.
	\end{equation}
        Here, $H(n - n_{i, 59})$ is a Heavyside step function which is 0 or 1, depending on the sign of
        its argument:
	\begin{equation}
	\mathcal{H}(x) :=
	\begin{cases}
         0 & x < 0 \\
         1 & x \geq 0.
	\end{cases}
	\end{equation}
        The parameter $n_{i, 59}$ is the year index when individual $i$ turns 59,
	or 0 if the individual is already 59 years old or older at the beginning of the plan.

\item [$T_n$]
	Amount of income tax paid on taxable ordinary income $G_n$ in year $n$.
	This is the taxes paid on ordinary income expressed as the sum of the amounts
	paid in each tax bracket as
	\begin{equation}
		\label{Eq:IncTax1}
		T_n = \sum_t \bar{f}_{tn}\theta_{tn}.
	\end{equation}
	Notice how $\bar{f}_{tn}$ also defines $G_n$ in Eq.~(\ref{Eq:Tx1}), and that optimal
	values of $\bar{f}_{tn}$ have to minimize $T_n$ regardless of whether the bequest or the desired
	net spending is being maximized.

\item [$U_n$]
	Amount of income tax paid on long-term capital gains and qualified dividends in year $n$,
	\begin{equation}
		U_n = \psi_n Q_n.
	\end{equation}
	We assume that qualified dividends and long-term
	capital gains are taxed at the same preferential rate $\psi_n$, which is the case for most situations.

\end{description}

\chapter{Formulation with imposed asset allocation ratios}
We first present the case where the sums of assets in each savings accounts $b_{ijn}$ are known
and for which we assume a prescribed asset allocation ratios.
The amount in each asset class $k$ for $b_{ijkn}$ is simply obtained
from $\alpha_{ijkn} b_{ijn}$ in this case.
This formulation assumes that the accounts are always balanced. This is
a reasonable assumption given the auto-balancing feature offered by many financial service
providers and robot advisers.

The benefit of this approach is that it has less variables and that only the sums of
all asset classes in each savings account need to be considered. The rate of return
of the account is then simply the product of the account balance with the sum of
the rates of return weighted according to the desired allocation ratio.
This approach allows us to eliminate $k$ by summing over it and rewrite
equations such as
\begin{eqnarray}
	\sum_k b_{ijk(n+1)} &=& \sum_k b_{ijkn} (1 + \tau_{kn}) + \ldots,
\end{eqnarray}
for the annual evolution of account balances from year $n$ to year $n+1$
as the simpler expression 
\begin{eqnarray}
	b_{ij(n+1)} &=& b_{ijn} \sum_k \alpha_{ijkn} (1 + \tau_{kn}) + \ldots ,\nonumber \\
		  &=& b_{ijn} (1 + \mathcal{T}_{ijn}) + \ldots ,
\end{eqnarray}
where
\begin{eqnarray}
	\label{Eq:Tau1}
	\mathcal{T}_{ijn} &:=& \sum_k \alpha_{ijkn} \tau_{kn}.
\end{eqnarray}
This is a consequence that the allocation ratios are normalized to unity, i.e.,
\begin{equation}
	\sum_k \alpha_{ijkn} = 1.
\end{equation}
In this formulation where the $\alpha_{ijkn}$ are prescribed,
we will use $\mathcal{T}_{ijn}$ to
add the market returns to the savings balances.

\section{Constraints}
\paragraph*{Required minimum distributions (RMDs)}
	Withdrawals from the ($j=1$) tax-deferred savings accounts must be larger
	or equal than the required minimum distributions, and therefore,
	\begin{equation}
		\label{Eq:C1}
		w_{i1n} -  \rho_{in}b_{i1n} \geq 0.
	\end{equation}
	As $b_{ijn}$ are the balances at the beginning of year $n$, they are also the balances
	at December 31 of the previous year, which is the amount from which the IRS bases the RMDs.
	Eq.~(\ref{Eq:C1}) has to hold for each year $n$ and each individual $i$, and therefore, there
	are $i\times N_n$ such equations (although trivial when $\rho_{in} = 0$).
	These constraints avoid paying the 50\% penalty
	on amounts not withdrawn when RMDs are required.
	Note that aggregate rules need to be considered separately as this approach only considers
	the sum of assets in a class with similar tax treatment (e.g., IRA and 401k).

\paragraph*{Income tax brackets}
	Taxable ordinary income is divided in tax brackets as defined in Eq.~(\ref{Eq:Tx1}),
	and therefore
	\begin{equation}
		\label{Eq:C2}
		0 \le \bar{f}_{tn} \le \bar{\Delta}_{tn},
	\end{equation}
	where each income tax bracket width $\Delta_{tn}$ has been adjusted for inflation.

\paragraph*{Standard exemption}
	The standard exemption is constrained by
	\begin{equation}
		0 \le e_n \le \bar{\sigma}_n.
	\end{equation}
	Variable $e_n$ is required for accounting for years when the taxable ordinary
	income is smaller that the standard exemption.

\paragraph*{Withdrawal limits}
	We introduce another set of constraints that might look unnecessary, but help
	convergence, and prevent overdrafts during the year of passing of the first spouse.
	As withdrawals and conversions are at the beginning of the year 
	we impose that
	\begin{equation}
		w_{ijn} + \delta(j, 1)x_{in} \le b_{ijn},
	\end{equation}
	which just states that account balances need to be larger than withdrawals and possible Roth conversions.

\paragraph*{Posthumous account activities}
	For cases with spouses, no withdrawal, Roth conversion, or deposit should
	occur in the accounts of the passed individual:
	\begin{eqnarray}
		w_{i_djn} &=& 0,\nonumber\\
		d_{i_dn} &=& 0, \nonumber \\
		x_{i_dn} &=& 0, \nonumber \\
		&& \quad \forall j \in {0, \ldots, N_j-1} \nonumber \\
		&& \quad \forall n \in {n_d, \ldots, N_n-1}.
	\end{eqnarray}

\paragraph*{Roth conversions}
	Roth conversions cannot be larger than the balance at the beginning of the year in the account:
	\begin{equation}
		x_{ijn} \le b_{i1n}.
	\end{equation}
	This constraint, however, is naturally satisfied when $b_{ijn} \ge 0$ non-negativity bounds are enforced.
	Additional maximum Roth conversion constraints $x_{max}$ can be imposed by the user and
	then the previous equation becomes
	\begin{equation}
		x_{in} \le \min(b_{i1n}, x_{max}).
	\end{equation}
	As this last equation involves a variable and a parameter in the $\min$ function,
	it needs to be coded as two separate constraints.

\paragraph*{Initial balances}
	The initial balances $\beta_{ij}$ are one of the main inputs of the model.
	The initial savings account balances are imposed through the constraints
	\begin{eqnarray}
		\label{Eq:InitialBalance}
		b_{ij0} = \beta_{ij}.
	\end{eqnarray}
	At this point, we assume that all accounts are balanced according to the desired
	allocation ratios $\alpha_{ijk0}$.

\paragraph*{Cash flow surplus}
	When both spouses are alive, surplus $s_n$ gets deposited in the taxable accounts
	according to variable $\eta$ as described in Eq.~(\ref{Eq:eta}),
	\begin{equation}
		\label{Eq:eta2}
		d_{in} = [\delta(i, 0)(1 - \eta) + \delta(i, 1)\eta] s_n .
	\end{equation}
	Otherwise, for $n \ge n_d$, variable $\eta$ gets redefined as $\eta = \delta(1, i_s)$.
	Surplus can be caused by large influx of money coming from big-ticket items or compulsory RMDs.

\paragraph*{Account balances}
	Contributions are assumed to be made at half-year to better represent periodic contributions
	made throughout the year. As we already mentioned,
	the account balance at the end of a year is the same as the balance
	at the beginning of the following year.
	Changes include contributions $\kappa$, distributions and withdrawals $w$,
	conversions $x$, surplus deposits $d$, and growth $\tau$ on the account through the year.
	For each spouse $i$, we track each savings account $j$ separately, and tax-deferred accounts
	are coupled with the corresponding tax-free account through Roth conversions.

	The timing of Roth conversions, withdrawals, and deposits brings
	additional coupling between these variables, and is worth a detailed discussion.
	First, the financial aspects, and then the algorithmic ones.
	For the former, some financial advisors would recommend making Roth
	conversions at the beginning of the year, while making withdrawals
	at the end. Obviously, financial simulators would always yield higher numbers
	when using this scenario, as the moneys needed to pay the regular bills 
	stayed in the bank until the end of the year. More realistically,
	however, it would be more accurate to assume withdrawals at mid-year,
	to better represent evenly distributed withdrawals. So, financially,
	conversions at the beginning of the year, and withdrawals at mid-year
	make good sense. Conversions are also typically best when
	timed with market downturns, which are obviously not always at the
	beginning of the year.

	Now, let's look at the optimization side of these transactions.
	During years of positive returns,
	a direct withdrawal from the tax-deferred account at mid-year will always
	be unfavorable when compared to a Roth conversion
	at the beginning of the year, followed
	by a tax-free withdrawal later in the same year.
	This is because the second
	scenario involves gains which are tax-free over the half-year, while
	the first one does not. Moving account withdrawals at the beginning
	of the year, and the conversions in mid-year can only solve part of this artificial bias
	under specific conditions.

	To solve these spurious scenarios, it would be desirable to make the following exclusions
	between surplus $s_n$, withdrawals $w_{ijn}$, and conversions $x_{in}$:
	\begin{eqnarray*}
		s_n &\texttt{XOR} & w_{i0n}, \\
		s_n &\texttt{XOR} & w_{i2n}, \\
		x_{in} &\texttt{XOR} & w_{i2n},
	\end{eqnarray*}
	for $j \neq 1$, i.e., for all withdrawals except those from tax-deferred accounts.
	For example, to favor tax-deferred withdrawals in most reasonable situations,
	it is desirable to make Roth conversions and tax-free distributions exclusive events
	by introducing binary variables $z_{in}^x \in \{0, 1\}$ with the following big-$\mathcal{M}$
	constraints:
	\begin{alignat}{2}
		\label{Eq:Binary}
		0 & \le \; z_{in}^x \mathcal{M} - x_{in} &\le \mathcal{M}, \nonumber \\
		0 & \le \; z_{in}^x \mathcal{M} + w_{i2n} &\le \mathcal{M}.
	\end{alignat}
	Here, $\mathcal{M}$ is a large number such as $10^7$, just slightly
	larger than what $x$ and $w$ can possibly be.

	Another approach could be to perform Roth conversions at mid-year, while withdrawals
	could be made at the beginning of the year, and surplus deposits,
	if needed due to RMDs or receiving large sums of money,
	could be made at the end of the year. Let's formulate this approach
	in more detail and investigate for potential problems.
	Timing controls which terms get multiplied by the rate of return $(1 + \mathcal{T}_{ijn})$.
	Therefore, our current choice would yield
	\begin{eqnarray}
		\label{Eq:C3a}
		b_{ij(n+1)} &=& [b_{ijn} - w_{ijn} + 0.5\kappa_{ijn}](1 + \mathcal{T}_{ijn})
		+ [\delta(j, 2) - \delta(j, 1)]x_{in} (1 + \mathcal{T}_{ijn}/2)
		\nonumber \\
		&& 
		+\ \delta(j, 0) d_{in} + 0.5 \kappa_{ijn},
	\end{eqnarray}
	where we use discrete Kronecker $\delta$ functions for selecting the specific accounts involved
	in Roth conversions. These conversions are made such that asset allocation
	ratios in the sending and receiving accounts are unchanged.

	Bringing all variables
	to the left-hand side, this gets rewritten as
	\begin{eqnarray}
		\label{Eq:C3}
		b_{ij(n+1)} - (b_{ijn} - w_{ijn}) (1 + \mathcal{T}_{ijn})
		&& \nonumber \\
		-\ [\delta(j, 2) - \delta(j, 1)]x_{in}(1 + \mathcal{T}_{ijn}/2)
		-\ \delta(j, 0) d_{in}
		&=& \kappa_{ijn} (1 + \mathcal{T}_{ijn}/2).
	\end{eqnarray}

	When $j=0$, this equation introduces
	a path to shelter negative returns by performing an over-withdrawal from the taxable
	account at the beginning of the year followed by a deposit in the
	same account at the end of the year. This can 
	be removed by using another binary variable, thus making these events exclusive by using
	the same strategy as Eq.~(\ref{Eq:Binary}).

	A much simpler approach, while not so natural,
	is to move all transactions to be synchronous at the beginning or at the end of the year
	thus avoiding undesirable movements of funds.
	If we select the beginning of the year, except for contributions, this leads to
	\begin{eqnarray}
		\label{Eq:C3b}
		b_{ij(n+1)}
		% && \nonumber \\
		- \ [b_{ijn} + \delta(j, 0)d_{in} - w_{ijn} + (\delta(j, 2) - \delta(j, 1))x_{in}]
		(1 + \mathcal{T}_{ijn})
		&=& \kappa_{ijn} (1 + \mathcal{T}_{ijn}/2).
		\nonumber
	\end{eqnarray}
This is the current approach used in Owl, coupled with
binary variables excluding simultaneous overwithdrawals and deposits, and
simultaneous Roth conversions and withdrawals from tax-free accounts.

\paragraph*{Net spending}
	For calculating the net spending $g_n$, we consider the cash flow of all withdrawals,
	wages, social security and pension benefits, and big-ticket items. 
	Then we subtract potential surplus $s_{n}$ and all taxes, penalties, and Medicare premiums paid:
	\begin{eqnarray}
		g_n = \sum_i [\omega_{in} + \bar{\zeta}_{in} + \bar{\pi}_{in} ] 
		+ \sum_{i,j} w_{ijn} + \sum_i \Lambda^\pm_{in} - s_{n}
		- P_n - T_n - U_n - m_n.
	\end{eqnarray}
	Notice how big-ticket items $\Lambda^\pm$ contribute directly to the cash flow.
	Replacing intermediate variables and bringing all variables to the left-hand side, we get
	\begin{eqnarray}
		\label{Eq:C4}
		g_n - \sum_{i,j} w_{ijn} + 0.1 \sum_{i,j\neq0} (1-\mathcal{H}(n - n_{i, 59})) w_{ijn}\nonumber\\
                + m_n + s_n + \sum_t \bar{f}_{tn} \theta_{tn} &&\nonumber \\
		+ \psi_n\sum_i \alpha_{i00n} \left[\mu(b_{i0n} - w_{i0n} + d_{in})
		+ w_{i0n}\max(0, \tau_{0(n-1)})\right] 
		&=& \sum_i [\Lambda^\pm_{in} - 0.5\psi_n\mu\alpha_{i00n}\kappa_{i0n}] \nonumber\\
                && + \sum_i [\omega_{in} + \bar{\zeta}_{in} + \bar{\pi}_{in} ].
	\end{eqnarray}
	Notice that we do not consider market losses as we use $\max(0, \tau)$, and that
	rates from only the previous year are used. Tax-loss
	harvesting is beyond the scope of this model, as is the tracking of stocks
	purchased over the years.

	We want the net spending to be predictable and smooth. For that purpose, we use
\begin{equation}
	\label{Eq:C5a}
	g_{n}/\bar{\xi}_{n} = g_0/\bar{\xi}_0,
\end{equation}
where the net spending is adjusted for inflation and where we use the time series of parameter $\xi_n$,
allowing for additional adjustments to the overall desired spending.
Note that $\bar{\xi}_0 = \xi_0$ as $\gamma_0=1$.
This profile is used to lower the desired net spending amount by a reduction factor $\chi$
after the passing of one spouse and/or to allow for more realistic spending profiles, such as
the {\em smile} profile described above.
Eq.~(\ref{Eq:C5a}) can be rewritten as
\begin{equation}
	\label{Eq:C5}
	g_n \xi_0 - g_0 \bar{\xi}_n = 0,
\end{equation}
for the constraints to be enforced. Once $g_0$ is determined, the whole time series of net spending
is determined.
When using slack variable $\lambda$, the spending profile is then implemented as inequality constraints
\begin{eqnarray}
	\label{Eq:lambdha}
	g_n \bar{\xi}_0 - g_0 (1 - \lambda) \bar{\xi}_n &\geq&  0, \nonumber\\
	-g_n \bar{\xi}_0 + g_0 (1 + \lambda) \bar{\xi}_n &\geq&  0.
\end{eqnarray}
In this case, the objective function will need to consider all years when optimizing net spending.

\paragraph*{Taxable ordinary income}
	We connect the two definitions for $G_n$ stated above in Eqs.~(\ref{Eq:Tx1}) and (\ref{Eq:Tx2}),
	\begin{eqnarray}
		\sum_t \bar{f}_{tn} &=&
		\sum_i [\omega_{in} + \Psi_n\bar\zeta_{in} + \bar{\pi}_{in}]  \nonumber \\
		&& + \sum_i [w_{i1n} + x_{in} ]
		\nonumber\\
		&& + \sum_{i,k\neq 0} [(b_{i0n} - w_{i0n} + d_{in}
		     + 0.5\kappa_{i0n})\alpha_{i0kn}\tau_{kn}] - e_n,
	\end{eqnarray}
	and re-arrange to move variables to the LHS as follows
	\begin{eqnarray}
		\label{Eq:C6}
		e_n + \sum_t \bar{f}_{tn}
		- \sum_i [ w_{i1n} + x_{in}] &&
		\nonumber \\
		- \sum_{i,k\neq 0} [(b_{i0n} - w_{i0n} + d_{in})\alpha_{i0kn}\tau_{kn}] &=&
		\sum_i [\omega_{in} + \Psi_n\bar\zeta_{in} + \bar{\pi}_{in} ]
		\nonumber \\
		&& + 0.5\sum_{i,k\neq 0} \alpha_{i0kn}\tau_{kn}\kappa_{i0n}.
	\end{eqnarray}

\paragraph*{Medicare brackets and costs}
	Annual Medicare costs $m_n$ include the Income-Related Monthly Adjusted Amount
	commonly known as IRMAA.
	As this additional adjustment
	is a piecewise constant function,
        it can be computed using binary variables and mixed-integer linear
	programming. In the current tax code, this adjustment
	depends on the modified adjusted gross income (MAGI) $\mathbb{G}$ from 2 years earlier. For the
	MAGI, we use $\mathbb{G}_{(n-2)} = G_{(n-2)} + Q_{(n-2)} + e_{(n-2)}$,
	i.e., gross taxable ordinary income plus dividends
	plus standard exemption from 2 years ago.
	If the plan
        has its oldest individual currently either 64 or 65 years old, MAGI values for previous years
	must be provided by the user to complete the calculations.
	\begin{figure}[t]
	    \center\includegraphics[width=10cm]{piecewiseConstant.png}
	    \caption{\small Modeling a piecewise constant monotonically increasing function.
	    The $x$-axis represents the MAGI from two years ago, while $m_n$ is the Medicare adjusted premiums.
	    A binary variable $z_q^m$ is associated with each segment $q$.
	    \label{Fig:piecewise}}
	\end{figure}

	Including regular premiums, there are $N_q=6$ brackets
	of MAGI indexed for inflation defined with annual Medicare costs of
	$\bar{\mathcal{C}}_{qn} = \gamma_n\mathcal{C}_q$ also adjusted for inflation.
        These segments are separated by $N_q -1$ thresholds
	$\bar{\mathcal{L}}_{qn} = \gamma_n\mathcal{L}_q$.
        Points $(\bar{\mathcal{L}}_{qn}, \bar{\mathcal{C}}_{qn})$ form a piecewise
	constant function that could be modeled using a special ordered set of type 1 (SOS1).
        A simpler approach, however, consists in only performing inequality tests with
        each bracket bound $\bar{\mathcal{L}}_{qn}$.
	Points $(\mathcal{L}_q, \mathcal{C}_q)$ are shown in Fig.~\ref{Fig:piecewise}.
        When $\mathbb{G}_{(n-2)} \leq \bar{\mathcal{L}}_{0n}$,
	the value $\bar{\mathcal{C}}_{0n}$
	represents the (inflation-adjusted) base premium for Medicare part B in year $n$, while
	higher $q$ values include the IRMAA additional costs.

        For testing if the MAGI from 2 years ago is larger than certain brackets,
	we use binary variables $z_{qn}^m \in \{0, 1\}$ with the big-$\mathcal{M}$ constraints
	\begin{eqnarray}
		\label{Eq:MedBracket}
                \mathbb{G}_{(n-2)} - \bar{\mathcal{L}}_{qn} & \geq & -(1 - z_{qn}^m) \mathcal{M}, \nonumber\\
                \mathbb{G}_{(n-2)} - \bar{\mathcal{L}}_{qn} & \leq & z_{qn}^m \mathcal{M},
	\end{eqnarray}
	for all $n \in \{n_m, \ldots, N_n-1\}$, where $n_{m}$ is the index year when
	Medicare starts for any individual $i$ in the plan, and $q \in \{0, \ldots, N_q -2\}$.
        As this applies to each individual eligible for Medicare, values
	$\bar{\mathcal{L}}_{qn}$ and  $\bar{\mathcal{C}}_{qn}$
	can include the accounting details for when both spouses are eligible and/or alive.
        These inequalities make $z_{nq}^m$ be 1 if
        the MAGI is larger than the bracket value $\bar{\mathcal{L}}_{qn}$, and 0 otherwise.
        For each year $n \geq n_m$, we can then express the Medicare costs $m_n$ as
	\begin{equation}
		\label{Eq:MediCosts}
		m_n = \bar{\mathcal{C}}_{0n}
                + \sum_{q=0}^{N_q -2} z_{qn}^m (\bar{\mathcal{C}}_{(q+1)n} - \bar{\mathcal{C}}_{qn}),
	\end{equation}
	as each $z_{qn}^m$ will be unity if the MAGI from 2 years ago, $\mathbb{G}_{n-2}$,
        is larger that the bracket $\bar{\mathcal{L}}_{qn}$.
	The end points $\mathcal{L}_{-1} = 0$ and $\mathcal{L}_{N_q-1} = \mathcal{M}$ are not included
        as they generate trivial constraints.
	For plans where the year index when Medicare first starts $n_m<2$, we will request
	and use user-provided values for the first-years MAGIs.
	Eq.~(\ref{Eq:MedBracket}) constraints are implemented
	with $(N_q -1)(N_n - n_m)$ constraints as
	\begin{eqnarray}
		\label{Eq:MedBracket2}
		G_{(n-2)} + Q_{(n-2)} + e_{(n-2)} - z_{qn}^m \mathcal{M}
                & \geq & \bar{\mathcal{L}}_{qn} - \mathcal{M}, \nonumber\\
		G_{(n-2)} + Q_{(n-2)} + e_{(n-2)} - z_{qn}^m \mathcal{M}
                & \leq & \bar{\mathcal{L}}_{qn}, \nonumber\\
		&&\forall q \in {0, \ldots, N_q-2},\nonumber \\
		&&\forall n \in {n_m, \ldots, N_n-1}.
	\end{eqnarray}

	As $G$ and $Q$ are intermediate variables, we can expand the first inequality of Eq.~(\ref{Eq:MedBracket})
	using Eqs.~(\ref{Eq:Tx2}) and (\ref{Eq:Qx2}) as follows
	\begin{eqnarray}
		\label{Eq:Med1}
		- \sum_i [w_{i1(n-2)} + x_{i(n-2)}] && \nonumber \\
		- \sum_i \left[(b_{i0(n-2)} - w_{i0(n-2)} + d_{i(n-2)})
                \left(\sum_{k\neq 0}[\alpha_{i0k(n-2)}\tau_{k(n-2)}] + \mu\alpha_{i00(n-2)}\right)\right] &&
		\nonumber \\
		- \sum_i [w_{i0(n-2)}\alpha_{i00(n-2)}\max(0, \tau_{0(n-3)})] + z_{qn}^m \mathcal{M}
		& \leq& \nonumber \\
                \mathcal{M} - \bar{\mathcal{L}}_{qn}
		+ \sum_i [\omega_{i(n-2)} + \Psi_n\bar\zeta_{i(n-2)} + \bar{\pi}_{i(n-2)}] && \nonumber\\
		+ 0.5\sum_{i} \left[\kappa_{i0(n-2)} \left(\sum_{k\neq 0}[\alpha_{i0k(n-2)}\tau_{k(n-2)}] + \mu\alpha_{i00(n-2)}\right)\right]. && 
	\end{eqnarray}
	The first term on the left-hand side represents withdrawals and conversions from tax-deferred accounts,
        the second captures interests and dividends earned from the taxable account,
        and the third accounts for long-term capital gains incurred from taxable-account stock withdrawals.
	For indices at the beginning of the time sequence, we use $\tau_{0, \max(0, n-x)}$, when $x>n$.
	Sign was flipped to make the equation an upper bound and variables were left on the left-hand side
        while parameters were moved to the RHS. The second inequality of Eq.(\ref{Eq:MedBracket})
        is obtained similarly
	\begin{eqnarray}
		\label{Eq:Med2}
		+ \sum_i [w_{i1(n-2)} + x_{i(n-2)}] && \nonumber \\
		+ \sum_i \left[(b_{i0(n-2)} - w_{i0(n-2)} + d_{i(n-2)})
                \left(\sum_{k\neq 0}[\alpha_{i0k(n-2)}\tau_{k(n-2)}] + \mu\alpha_{i00(n-2)}\right)\right] &&
		\nonumber \\
		+ \sum_i [w_{i0(n-2)}\alpha_{i00(n-2)}\max(0, \tau_{0(n-3)})] - z_{qn}^m \mathcal{M}
		& \leq& \nonumber \\
                 \bar{\mathcal{L}}_{qn}
		- \sum_i [\omega_{i(n-2)} + \Psi_n\bar\zeta_{i(n-2)} + \bar{\pi}_{i(n-2)}] && \nonumber\\
		- 0.5\sum_{i} \left[\kappa_{i0(n-2)} \left(\sum_{k\neq 0}[\alpha_{i0k(n-2)}\tau_{k(n-2)}] + \mu\alpha_{i00(n-2)}\right)\right], && 
	\end{eqnarray}
	for all $n \in \{n_m, \ldots, N_n-1\}$, and $n_m \ge 2$,
	otherwise using numbers provided by user if $n_m < 2$, and $q \in \{0,\ldots,N_q - 2\}$.

\chapter{Mapping of decision variables}
At this point, one can use one of the many algebraic modeling languages
such as AMPL, GAMS, MOSEK, AIMMS, and Gurobi, and code the equations above
using that language, but most of these applications are
proprietary and require a license and additional software installation.
These languages allow the problem to be stated at a high level and
steps to cast the problem in a form suitable for solution are performed automatically.
There are also object-oriented language extensions, such as Python's Pyomo
and PuLP that can ease the process of solving these problems.
For completeness, however, we present here a simple
index mapping approach that allows solving this problem using a generic
linear programming solver.

Using a simple interface for mapping sparse objects to dense ones, the approach described here
has been successfully tested with both the HiGHS open-source solver
and the MOSEK proprietary solver.
To cast the problem in a form suitable for a linear programming solver, we will use
a single block vector represented by the array $y[q()]$ with index-mapping functions $q()$.
While this process can be achieved using slicing and reshaping in some programming
languages, we will present a generic approach suitable for most programming languages.
The detailed approach presented here also allows us to determine the size of the problem to solve.
We proceed alphabetically for all variables, and continue to use the convention of having
index 0 for representing the first element.

To bring all variables in a single block vector,
we will simply use two generic index mapping functions defined as
\begin{equation}
	q_*(C, \ell_1, \ell_2, \ell_3 ; N_1, N_2, N_3) :=
	C + \ell_1N_2N_3 + \ell_2N_3 + \ell_3 ,
\end{equation}
and
\begin{equation}
	q_C(C, N_1, N_2, N_3) :=
	C + N_1N_2N_3,
\end{equation}
with the constraint that $0 \le \ell_i < N_i$.

\paragraph*{Account balances (\boldmath$b$)}
For storing the savings account balances appropriately, variable $b_{ijn}$ needs to have one
more entry $(N_n + 1)$ to
store the end-of-life estate value. Therefore, we use
\begin{equation}
	y[q_b(i, j, n)] = b_{ijn},
\end{equation}
where
\begin{equation}
	\label{Eq:Extra}
	q_b(i, j, n) = q_*(C_b, i, j, n; N_i, N_j, N_n+1)
\end{equation}
and where $n$ exceptionally runs from 0 to $N_n$ inclusively, and therefore
$q_b$ runs from $C_b = 0$ to $C_{d} - 1$,
where
\[
	C_{d} = q_C(C_b, N_i, N_j, N_n+1) = N_i N_j (N_n+1).
\]

\paragraph*{Surplus deposits (\boldmath$d$)}
For surplus deposits in the taxable savings accounts $d_{in}$ we will use
\begin{equation}
	y[q_d(i, n)] = d_{in},
\end{equation}
where
\begin{equation}
	q_d(i, n) = q_*(C_d, i, n, 0; N_i, N_n, 1)
\end{equation}
with $q_d$ running from $C_d$ to $C_f - 1$, where
\[
	C_f = q_C(C_d, N_i, N_n, 1) = N_i(N_j(N_n+1) + N_n).
\]

\paragraph*{Tax bracket fractions (\boldmath$f$)}
For tax bracket fractions $\bar{f}_{tn}$ we will use
\begin{equation}
	y[q_f(t, n)] = \bar{f}_{tn},
\end{equation}
where
\begin{equation}
	q_f(t, n) = q_*(C_f, t, n, 0; N_t, N_n, 1)
\end{equation}
with $q_f$ running from $C_f$ to $C_g - 1$, where
\[
	C_g = q_C(C_f, N_t, N_n, 1) = N_i(N_j(N_n+1) + N_n) + N_tN_n.
\]

\paragraph*{Net spending (\boldmath$g$)}
For net spending $g_{n}$ we will use
\begin{equation}
	y[q_g(n)] = g_{n},
\end{equation}
where
\begin{equation}
	q_g(n) = q_*(C_g, n, 0, 0; N_n, 1, 1) = C_g + n,
\end{equation}
with $q_g$ running from $C_g$ to $C_m - 1$, where
\[
	C_m = q_C(C_g, N_n, 1, 1) = N_i(N_j(N_n+1) + N_n) + (N_t + 1) N_n.
\]

\paragraph*{Medicare costs (\boldmath$m$)}
For Medicare costs $m_{n}$ we will use
\begin{equation}
	y[q_m(n)] = m_{n},
\end{equation}
where
\begin{equation}
	q_m(n) = q_*(C_m, n, 0, 0; N_n, 1, 1) = C_m + n,
\end{equation}
with $q_m$ running from $C_m$ to $C_s - 1$, where
\[
	C_s = q_C(C_m, N_n, 1, 1) = N_i(N_j(N_n+1) + N_n) + (N_t + 2) N_n.
\]

\paragraph*{Surplus (\boldmath$s$)}
Surplus can be generated if big-ticket items are received (inheritance, sale of a house, etc.)
or due to RMDs. Surplus $s$ is then deposited to taxable savings accounts according
to variable $\eta$. We will use
\begin{equation}
	y[q_s(n)] = s_{n},
\end{equation}
where
\begin{equation}
	q_s(n) = q_*(C_s, n, 0, 0; N_n, 1, 1) = C_s + n,
\end{equation}
with $q_s$ running from $C_s$ to $C_w - 1$, where
\[
	C_w = q_C(C_s, N_n, 1, 1) = N_i(N_j(N_n+1) + N_n) + (N_t + 3) N_n.
\]

\paragraph*{Withdrawals (\boldmath$w$)}
For withdrawals $w_{ijn}$ we will use
\begin{equation}
	y[q_w(i, j, k, n)] = w_{i j n},
\end{equation}
where
\begin{equation}
	q_w(i, j, n) = q_*(C_w, i, j, n; N_i, N_j, N_n)
\end{equation}
with $q_w$ running from $C_w$ to $C_x - 1$, where
\[
	C_x = q_C(C_w, N_i, N_j, N_n) = N_i(N_j(2N_n + 1) + (N_t + 3) N_n.
\]

\paragraph*{Roth conversions (\boldmath$x$)}
Finally, for Roth conversions $x_{in}$ we will use
\begin{equation}
	y[q_x(i, n)] = x_{i n},
\end{equation}
where
\begin{equation}
	q_x(i, n) = q_*(C_x, i, n, 0; N_i, N_n, 1)
\end{equation}
with $q_x$ running from $C_x$ to $C_* - 1$, where
\begin{equation}
	\label{Eq:Cstar}
	C_* = q_C(C_x, N_i, N_n, 1) = N_i(N_j(2N_n + 1) + (N_t + N_i + 3) N_n.
\end{equation}

With $N_i = 2, N_j = 3, N_k = 4, N_t = 7$ we have $24 N_n + 6$ variables. For
a 30-year plan, this results in 726 non-integer decision variables.
If the time resolution is increased to
months, that would result in 8,646 variables which is still solvable by today's standards.
Adding binary variables $z^x_{inz}$ can adds $N_zN_iN_n$ more decision variables,
while adding $z^m_{qn}$ adds $6N_n$ more, resulting in $34 N_n + 6$, or 1,026 for 30 years.

\section{Reverse mapping of indices}
The inverse functions for the index-mapping functions will be derived for the
most complex case encountered in this paper.
If we have
\begin{equation}
	z = q_*(C, i, j, k, n; N_i, N_j, N_k, N_n) := C + iN_jN_kN_n + jN_kN_n + kN_n + n,
\end{equation}
then $(i, j, k, n) = q_*^{-1}(z; N_i, N_j, N_k, N_n, C)$ is obtained from
\begin{eqnarray}
	n &=& \texttt{mod}(\texttt{mod}(\texttt{mod}(z - C, N_jN_kN_n), N_kN_n), N_n), \nonumber \\
	k &=& \texttt{mod}(\texttt{mod}(z - C - n, N_jN_kN_n), N_kN_n)/N_n, \nonumber \\
	j &=& \texttt{mod}(z - C - n - kN_n, N_jN_kN_n)/(N_kN_n), \nonumber \\
	i &=& (z - C - n - kN_n - jN_kN_n)/(N_jN_kN_n).
\end{eqnarray}
While this holds for all cases presented in the previous section, this can be easily simplified
for cases having fewer active indices. However, some modern languages can accomplish this
mapping rather easily by providing \texttt{reshape()} functions.

\chapter{Building constraint matrices}
Let's first define generic index-mapping functions $I$ and $J$ as
\begin{eqnarray}
	\label{Eq:Offsets}
	I_l(n) &=& C_l + n, \nonumber \\
	I_l(i, n; N_n) &=& C_l + iN_n + n, \nonumber \\
	I_l(i, j, n; N_j, N_n) &=& C_l + iN_j N_n + jN_n +n, \\
	\ldots &=& \ldots \nonumber
\end{eqnarray}
and so on, which would cumulatively increase row count $C_l$ at each new instance $l$,
similar to how we proceeded in the previous section.
This allows us to build rectangular matrices by iteratively adding rows.
These constraint matrices have $C_*$ (defined in Eq.~(\ref{Eq:Cstar}))
columns but can have less rows,
forming an underdetermined system to be optimized using linear programming.
Function $J$ is defined similarly for equality constraints, while $I$ is used
for building the rows of the matrix containing the inequality constraints.
Additional indices found in columns and not in rows implies the existence of multiple elements on that row. 

\section{Inequality constraints}
Inequality constraints can be upper or lower bounds expressed in matrix form as
$\ell \le A_{u}y \le u$. When $\ell$ is not specified it is assumed 0, and
an unspecified $u$ implies $\infty$. Most if not all inequalities will be expressed as upper bounds.

\paragraph*{Required minimum distributions (RMDs)}
We rewrite the inequality constraint on required minimum distributions
Eq.~(\ref{Eq:C1}) using matrix $A_{u}y \le u$ starting with the following $N_iN_n$ rows, 
\begin{eqnarray}
	A_u[I_0(i, n), q_w(i, 1, n)] &=& -1 \nonumber \\
	A_u[I_0(i, n), q_b(i, 1, n)] &=& \rho_{in}, \nonumber \\
	u[I_0(i, n)] &=& 0, \\
	&&\qquad\forall i \in \{0,\ldots, N_i - 1\}, \nonumber\\
	&&\qquad\forall n \in \{0,\ldots, N_n - 1\},\nonumber
\end{eqnarray}
and all other elements in the same rows of $A_u$ being $0$.
Notice that while $b$ has $N_n+1$ elements, the constraints
for $b$ go from $0$ to $N_n-1$ as there is no RMD required in the last year of the plan $N_n$.
See Eq.~(\ref{Eq:Extra}).

\paragraph*{Income tax brackets}
Similarly, we add $N_t N_n$ more rows to matrix $A_uy \le u$ to express
the inequality constraint in Eq.~(\ref{Eq:C2})
setting an upper limit on fractions $\bar{f}_{tn}$,
\begin{eqnarray}
	A_u[I_1(t, n), q_{f}(t, n)] &=& 1, \nonumber \\
	u[I_1(t, n)] &=& \bar{\Delta}_{tn},\\
	&&\qquad\forall t \in \{0,\ldots, N_t - 1\}, \nonumber\\
	&&\qquad\forall n \in \{0,\ldots, N_n - 1\},\nonumber
\end{eqnarray}
and all other elements in the same rows of $A_u$ being $0$.

\paragraph*{Medicare brackets}
Medicare's MAGI brackets determine the values of binary variables $z^m_{qn}$.
We first code Eq.~(\ref{Eq:Med1}) and then Eq.~(\ref{Eq:Med2}) will be very similar.
For each bracket we set
\begin{eqnarray}
	A_u[I_2(q, n), q_{w}(i, 1, n-2)] &=& -1, \nonumber \\
	A_u[I_2(q, n), q_{x}(i, n-2)] &=& -1, \nonumber \\
	A_u[I_2(q, n), q_{b}(i, 0, n-2)] &=&
	    - \mu \alpha_{i00(n-2)} -\sum_{k\neq 0} \alpha_{i0k(n-2)}\tau_{k(n-2)},
	    \nonumber \\
	A_u[I_2(q, n), q_{d}(i, n-2)] &=&
	    - \mu \alpha_{i00(n-2)} -\sum_{k\neq 0} \alpha_{i0k(n-2)}\tau_{k(n-2)},
	    \nonumber \\
	A_u[I_2(q, n), q_{w}(i, 0, n-2)] &=&
	    \mu \alpha_{i00(n-2)} + \sum_{k\neq 0} \alpha_{i0k(n-2)}\tau_{k(n-2)}
	    \nonumber \\
	    && - \alpha_{i00(n-2)}\max(0, \tau_{0\max(0, n-3)}), \nonumber \\
	A_u[I_2(q, n), q_{z^m}(q, n)] &=& \mathcal{M}, \nonumber \\
	u[I_2(q, n)] &=& -\bar{\mathcal{L}}_{qn} + \mathcal{M}
         + \sum_i \left[\omega_{i(n-2)} + \Psi_n\bar{\zeta}_{i(n-2)} + \bar{\pi}_{i(n-2)} \right]\nonumber \\
	&& + 0.5 \sum_i \left[\kappa_{i0(n-2)}  \left(
	  \mu\alpha_{i00(n-2)} + \sum_{k\neq 0} \alpha_{i0k(n-2)}\tau_{k(n-2)}
	  \right)\right],\nonumber\\
	&&\qquad\forall i \in \{0,\ldots, N_i - 1\}, \nonumber\\
	&&\qquad\forall k \in \{0,\ldots, N_k - 1\}, \nonumber\\
	&&\qquad\forall q \in \{1,\ldots, N_q - 2\}, \nonumber\\
	&&\qquad\forall n \in \{\max(n_m, 2),\ldots, N_n - 1\}.
\end{eqnarray}
When $n_m < 2$, we use these additional rows
\begin{eqnarray}
	A_u[I_2(q, n), q_{z^m}(q, n)] &=& \mathcal{M}, \nonumber \\
	u[I_2(q, n)] &=& \mathcal{M} + \mathcal{A}_{n} -\bar{\mathcal{L}}_{qn}, \nonumber \\
	&&\qquad\forall q \in \{1,\ldots, N_q - 2\}, \nonumber\\
	&&\qquad\forall n \in \{n_m,\ldots, 2\},
\end{eqnarray}
where $\mathcal{A}_n$ is a user-provided array of MAGI values for (up to) the last two years in chronological order.

For Eq.~(\ref{Eq:Med2}) we obtain
\begin{eqnarray}
	A_u[I_2(q, n), q_{w}(i, 1, n-2)] &=& 1, \nonumber \\
	A_u[I_2(q, n), q_{x}(i, n-2)] &=& 1, \nonumber \\
	A_u[I_2(q, n), q_{b}(i, 0, n-2)] &=&
	    \mu \alpha_{i00(n-2)} + \sum_{k\neq 0} \alpha_{i0k(n-2)}\tau_{k(n-2)},
	    \nonumber \\
	A_u[I_2(q, n), q_{d}(i, n-2)] &=&
	    \mu \alpha_{i00(n-2)} + \sum_{k\neq 0} \alpha_{i0k(n-2)}\tau_{k(n-2)},
	    \nonumber \\
	A_u[I_2(q, n), q_{w}(i, 0, n-2)] &=&
	    - \mu \alpha_{i00(n-2)} -\sum_{k\neq 0} \alpha_{i0k(n-2)}\tau_{k(n-2)}
	    \nonumber \\
	    && + \alpha_{i00(n-2)}\max(0, \tau_{0\max(0, n-3)}), \nonumber \\
	A_u[I_2(q, n), q_{z^m}(q, n)] &=& -\mathcal{M}, \nonumber \\
	u[I_2(q, n)] &=& \bar{\mathcal{L}}_{qn}
         - \sum_i \left[\omega_{i(n-2)} + \Psi_n\bar{\zeta}_{i(n-2)} + \bar{\pi}_{i(n-2)} \right]\nonumber \\
	&& - 0.5 \sum_i \left[\kappa_{i0(n-2)}  \left(
	  \mu\alpha_{i00(n-2)} + \sum_{k\neq 0} \alpha_{i0k(n-2)}\tau_{k(n-2)}
	  \right)\right],\nonumber\\
	&&\qquad\forall i \in \{0,\ldots, N_i - 1\}, \nonumber\\
	&&\qquad\forall k \in \{0,\ldots, N_k - 1\}, \nonumber\\
	&&\qquad\forall q \in \{1,\ldots, N_q - 2\}, \nonumber\\
	&&\qquad\forall n \in \{\max(n_m, 2),\ldots, N_n - 1\}.
\end{eqnarray}
When $n_m < 2$, we enforce these additional rows
\begin{eqnarray}
	A_u[I_2(q, n), q_{z^m}(q, n)] &=& -\mathcal{M}, \nonumber \\
	u[I_2(q, n)] &=& \bar{\mathcal{L}}_{qn} - \mathcal{A}_{n} , \nonumber \\
	&&\qquad\forall q \in \{1,\ldots, N_q - 2\}, \nonumber\\
	&&\qquad\forall n \in \{n_m,\ldots, 2\},
\end{eqnarray}
where $\mathcal{A}_n$ is a user-provided array of MAGI values for (up to) the last two years in chronological order.

\section{Equality constraints}

\paragraph*{Account balances}
For the equality constraints on account balances expressed in Eq.~(\ref{Eq:C3b}),
we define an equality constraint matrix $A_ey = v$ starting
with $N_iN_jN_n$ rows as
\begin{eqnarray}
	\label{Eq:B1}
	A_e[J_0(i, j, n), q_b(i, j, n+1)] &=& 1, \nonumber \\
	A_e[J_0(i, j, n), q_b(i, j, n)] &=& -(1 + \mathcal{T}_{ijn}), \nonumber \\
	A_e[J_0(i, j, n), q_x(i, n)] &=& -(\delta(j, 2) - \delta(j, 1))(1 + \mathcal{T}_{ijn}), \nonumber \\
	A_e[J_0(i, j, n), q_w(i, j, n)] &=& (1 + \mathcal{T}_{ijn}), \nonumber \\
	A_e[J_0(i, j, n), q_d(i, n)] &=& -\delta(j, 0)(1 + \mathcal{T}_{ijn}), \\
	&&\qquad\forall i \in \{0,\ldots, N_i-1\},\nonumber\\
	&&\qquad\forall j \in \{0,\ldots, N_j-1\},\nonumber\\
	&&\qquad\forall n \in \{0,\ldots, N_n-1\}, \nonumber
\end{eqnarray}
where $v$ is
\begin{equation}
	v[J_0(i, j, n)] = \kappa_{ijn}(1 + \mathcal{T}_{ijn}/2).
\end{equation}
The initial account balances expressed in Eq.~(\ref{Eq:InitialBalance}) are imposed through
\begin{eqnarray}
	A_e[J_1(i, j), q_b(i, j, 0)] &=& 1, \nonumber \\
	v[J_1(i, j)] &=& \beta_{ij},  \\
	&&\qquad\forall i \in \{0,\ldots, N_i-1\},\nonumber\\
	&&\qquad\forall j \in \{0,\ldots, N_j-1\},\nonumber\\
\end{eqnarray}
leading to $N_i N_j$ additional rows to $A_e$.

\paragraph*{Medicare costs}
Binary variables $z_{qn}^m$ express all active IRMAA brackets.
The costs for Medicare are easily obtained once the binary variables
$z^m_{qn}$ are determined using Eq.~(\ref{Eq:MediCosts}).
\begin{eqnarray}
	A_u[J_3(n), q_{m}(n)] &=& 1, \nonumber \\
	A_u[J_3(n), q_{z^m}(q, n)] &=& -(\bar{\mathcal{C}}_{(q+1)n} - \bar{\mathcal{C}}_{qn}), \nonumber \\
	u[J_3(n)] &=& \bar{\mathcal{C}}_{0n},\\
	&&\qquad\forall q \in \{0,\ldots, N_q - 2\}, \nonumber\\
	&&\qquad\forall n \in \{n_m,\ldots, N_n - 1\}.\nonumber
\end{eqnarray}

\paragraph*{Net spending}
For the equality constraint on net spending expressed in Eq.~(\ref{Eq:C4}),
we add $N_n$ more rows to $A_ey = v$ as
\begin{eqnarray}
	A_e[J_4(n), q_g(n)] &=& 1, \nonumber \\
	A_e[J_4(n), q_m(n)] &=& 1, \nonumber \\
	A_e[J_4(n), q_b(i, 0, n)] &=& \psi_n\mu\alpha_{i00n}, \nonumber \\
	A_e[J_4(n), q_d(i, n)] &=& 1 + \psi_n\mu\alpha_{i00n}, \nonumber \\
	A_e[J_4(n), q_{\bar{f}}(t, n)] &=& \theta_{tn}, \nonumber \\
	A_e[J_4(n), q_w(i, j ,n)] &=& -1 + 0.1(1-\delta(j, 0))(1-\mathcal{H}(n-n_{i, 59})) + \delta(j, 0)\psi_n\alpha_{i00n}(\max(0, \tau_{0n-1}) - \mu), \nonumber \\
	&&\qquad\forall t \in \{0,\ldots, N_t-1\},\nonumber\\
	&&\qquad\forall i \in \{0,\ldots, N_i-1\},\nonumber\\
	&&\qquad\forall j \in \{0,\ldots, N_j-1\},\nonumber\\
	&&\qquad\forall n \in \{0,\ldots, N_n-1\}, \nonumber
\end{eqnarray}
where $v$ is
\begin{equation}
	v[J_4(n)] = \sum_i [\omega_{in} + \bar\zeta_{in} + \bar{\pi}_{in}
	+ \Lambda^\pm_{in} - 0.5\psi_n\mu\alpha_{i00n}\kappa_{i0n}].
\end{equation}
Here we used Eq.~(\ref{Eq:eta2}) reflecting the fact that the sum of all deposits $d_{in}$ must equal the surplus $s_n$,
\[
	s_n = \sum_i d_{in}.
\]

The condition of having a predictable net spending expressed as an
equality in Eq.~(\ref{Eq:C5}) adds $N_n-1$ more rows to $A_ey = v$ as
\begin{eqnarray}
	A_e[J_5(n), q_g(0)] &=& -\bar{\xi}_n, \nonumber \\
	A_e[J_5(n), q_g(n)] &=& \xi_0, \nonumber \\
	v[J_5(n)] &=& 0, \\
	&&\qquad\forall n \in \{1,\ldots, N_n\}. \nonumber
\end{eqnarray}

\paragraph*{Taxable ordinary income}
Finally, for the equality constraint in Eq.~(\ref{Eq:C6}) establishing taxable
ordinary income, we add $N_n$ rows to $A_ey = v$ as follows
\begin{eqnarray}
	A_e[J_6(n), q_e(n)] &=& 1, \nonumber \\
	A_e[J_6(n), q_{\bar{f}}(t, n)] &=& 1, \nonumber \\
	A_e[J_6(n), q_w(i, 1, n)] &=& -1, \nonumber \\
	A_e[J_6(n), q_x(i, n)] &=& -1, \nonumber \\
	A_e[J_6(n), q_b(i, 0, n)] &=& -\sum_{k\neq 0} \alpha_{i0kn}\tau_{kn}, \\
	A_e[J_6(n), q_w(i, 0, n)] &=&  \sum_{k\neq 0} \alpha_{i0kn}\tau_{kn}, \nonumber \\
	A_e[J_6(n), q_d(i, n)] &=&    -\sum_{k\neq 0} \alpha_{i0kn}\tau_{kn}, \nonumber \\
	&&\qquad\forall t \in \{0,\ldots, N_t-1\},\nonumber\\
	&&\qquad\forall i \in \{0,\ldots, N_i-1\},\nonumber\\
	&&\qquad\forall k \in \{0,\ldots, N_k-1\},\nonumber\\
	&&\qquad\forall n \in \{0,\ldots, N_n-1\}, \nonumber
\end{eqnarray}
with
\begin{eqnarray}
	v[J_6(n)] &=& 
	\sum_i [\omega_{in} + \Psi_n\bar\zeta_{in}  + \bar{\pi}_{in}]
	+ 0.5\sum_{i} \kappa_{i0n} \sum_{k\neq 0} \alpha_{i0kn}\tau_{kn}.
\end{eqnarray}

\section{Other considerations}
\paragraph*{Beneficiaries}
Tax-free and tax-deferred accounts have special tax rules that allow giving part
or the entire value of
tax-free accounts to a spouse who can then consider it as his/her own.
These accounts typically use percentages to designate beneficiaries.
Let $\phi_j$ be the fraction of the account $j$ that a spouse $i_d$ wishes
to leave to his/her surviving spouse $i_s$
in the year $n_d  - 1 < N_n - 1$ following the year of passing. 
To account for that event in year $n_d$, Eq.~(\ref{Eq:C3b}) needs to be rewritten as
\begin{eqnarray}
	b_{ij(n+1)} &=& [1 - \delta(n, n_d-1)\delta(i, i_d)] \nonumber \\
	&&\times \Bigl\{\left[b_{ijn} + \delta(j, 0)d_{ij} - w_{ijn}
	+ (\delta(j, 2) - \delta(j, 1))x_{in}
	\right](1 + \mathcal{T}_{ijn})
	+ \kappa_{ijn}(1 + \mathcal{T}_{ijn}/2) 
	\Bigr\}\nonumber \\
	&& + [\phi_j\delta(n, n_d-1)\delta(i, i_s)] \nonumber  \\
	&& \times \Bigl\{\left[b_{i_djn}
	+ \delta(j, 0)d_{i_dn}
	- w_{i_djn}
	+ (\delta(j, 2) - \delta(j, 1))x_{i_dn}
	\right] (1 + \mathcal{T}_{i_djn})
	\nonumber\\
	&& + \kappa_{i_djn}(1 + \mathcal{T}_{i_djn}/2) 
	\Bigr\}.
\end{eqnarray}
The first multiplier $[\ldots]$ on the right-hand side will always be one except for $i_d$ in
year $n_d-1$ when it will be zero. This will result in emptying all accounts for $i_d$ for years
$n_d$ and beyond.
The second special multiplier $[\ldots]$ before the second set of curly braces
$\{\}$ will always be zero except for the surviving
spouse $i_s$ in year $n_d-1$, who will then inherit a fraction $\phi_j$ of account $j$ that
was scheduled to go into $i_d$'s $j$ account at the beginning of year $n_d$.

Rewriting the last equation as a constraint results in
\begin{eqnarray}
	&&b_{ij(n+1)} 
	  \nonumber  \\
	&& - [1 - \delta(n, n_d-1)\delta(i, i_d)] \nonumber\\
	&& \times \Bigl\{ \left[b_{ijn} + \delta(j, 0)d_{in} - w_{ijn}
	+ (\delta(j, 2) - \delta(j, 1))x_{ikn} \right](1 + \mathcal{T}_{ijn}) \Bigr\}
	\nonumber \\
	&&- [\phi_j\delta(n, n_d-1)\delta(i, i_s)] \nonumber \\
	&& \times \Bigl\{ \left[b_{i_djn} + \delta(j, 0)d_{in} - w_{ijn}
	+ (\delta(j, 2) - \delta(j, 1))x_{i_dkn}
	\right](1 + \mathcal{T}_{i_djn})
	\Bigr\}
	\nonumber \\
	&=& [1 - \delta(n, n_d-1)\delta(i, i_d)] \kappa_{ijn} (1 + \mathcal{T}_{ijn}/2)
	\nonumber\\ &&
	+ [\phi_j\delta(n, n_d-1)\delta(i, i_s)]
	\kappa_{i_djn}(1 + \mathcal{T}_{i_djn}/2).
\end{eqnarray}
We are now ready to replace Eq.~(\ref{Eq:B1}) for $A_ey = v$ by
\begin{eqnarray}
        \label{Eq:B2}
        A_e[J_0(i, j, n), q_b(i, j, n+1)] &=& 1, \nonumber \\
        A_e[J_0(i, j, n), q_b(i, j, n)] &=& - [1 - \delta(n, n_d-1)\delta(i, i_d)]
		(1 + \mathcal{T}_{ijn}), \nonumber \\
        A_e[J_0(i, j, n), q_d(i, j, n)] &=& - [1 - \delta(n, n_d-1)\delta(i, i_d)]
		\delta(j, 0) (1 + \mathcal{T}_{ijn}), \nonumber \\
        A_e[J_0(i, j, n), q_w(i, j, n)] &=& [1 - \delta(n, n_d-1)\delta(i, i_d)]
	(1 + \mathcal{T}_{ijn}),\nonumber \\
        A_e[J_0(i, j, n), q_x(i, n)] &=& - [1 - \delta(n, n_d-1)\delta(i, i_d)]
                (\delta(j, 2) - \delta(j, 1))
		(1 + \mathcal{T}_{ijn}), \nonumber \\
		\text{when $N_i =2$ and $i = i_s$,} && \nonumber\\
        A_e[J_0(i, j, n), q_b(i_d, j, n)] &=& - [\phi_j\delta(n, n_d-1)\delta(i, i_s)]
		(1 + \mathcal{T}_{i_djn}), \nonumber \\
        A_e[J_0(i, j, n), q_d(i_d, n)] &=&  -[\phi_j\delta(n, n_d-1)\delta(i, i_s)]
		\delta(j, 0)(1 + \mathcal{T}_{i_djn}), \nonumber \\
        A_e[J_0(i, j, n), q_w(i_d, j, n)] &=& [\phi_j\delta(n, n_d-1)\delta(i, i_s)]
	(1 + \mathcal{T}_{i_djn}), \nonumber\\
        A_e[J_0(i, j, n), q_x(i_d, n)] &=& - [\phi_j\delta(n, n_d-1)\delta(i, i_s)]
                (\delta(j, 2) - \delta(j, 1))
		(1 + \mathcal{T}_{i_djn}), \nonumber \\
                \nonumber \\
        &&\qquad\forall i \in \{0,\ldots, N_i-1\},\nonumber\\
        &&\qquad\forall j \in \{0,\ldots, N_j-1\},\nonumber\\
        &&\qquad\forall n \in \{0,\ldots, N_n-1\}, \nonumber
\end{eqnarray}
where $v$ is
\begin{eqnarray}
	v[J_0(i, j, n)] 
	&=& [1 - \delta(n, n_d-1)\delta(i, i_d)] \kappa_{ijn}(1 + \mathcal{T}_{ijn}/2)
	\nonumber \\
	&& + [\phi_j\delta(n, n_d-1)\delta(i, i_s)]\kappa_{i_djn}(1 + \mathcal{T}_{i_djn}/2). 
\end{eqnarray}
While the last two equations may look cumbersome, their net effect is only to include
a few more terms when $n=n_d-1$. 

\paragraph*{Assets allocation ratios}
When asset allocation ratios $\alpha$ are imposed,
they should also be applied to how
contributions amounts $\kappa_{ijn}$ are invested, such that 
\begin{equation}
	\kappa_{ijkn} = \alpha_{ijkn} \kappa_{ijn}.
\end{equation}
For other allocation schemes, just substitute $\alpha_{ijkn} = \alpha_{ikn}$ or $\alpha_{kn}$
depending on the scheme selected.

Assets allocation have been handled easily by assuming that
the accounts are always rebalanced
and only using a single multiplier $\mathcal{T}$, defined as
\begin{equation}
	\mathcal{T}_{ijn} = \sum_k \alpha_{ijkn}\tau_{kn},
\end{equation}
to compute to return
on the total balance of each savings account.

\paragraph*{Spousal deposits and withdrawals}
While keeping the problem linear, a simple constraint can be imposed on
surplus deposits in taxable savings accounts. One can specify a spousal ratio $\eta$
such as
\begin{equation}
	d_{0n} = \eta d_{1n}.
\end{equation}
A similar spousal ratio can be imposed on withdrawals from tax-deferred accounts
\begin{equation}
	w_{01n} = \eta w_{11n},
\end{equation}
but this can cause drawing from an empty account while the other spousal account is not.
Only the deposit scheme has currently been implemented in Owl.

\chapter{Objective functions}
The objective function is a simple scalar defined as $c\cdot y$ that will be minimized.

\paragraph*{Maximum net spending}
There are a few ways by which a retirement plan can be optimized. For maximizing the net spending under
the constraint of a desired bequest, we introduce the following relation
\begin{equation}
	\label{Eq:Bequest}
	E_n = \sum_{i,j} (1 - \nu\delta(j, 1)) b_{ijn},
\end{equation}
which is the value of the estate in nominal dollars at year $n$,
taking into consideration the heir's marginal income tax rate $\nu$ on the ($j=1$) tax-deferred account. 

For a desired bequest $\epsilon_{N_n}$, expressed in today's
dollars, the final amount in year $N_n$ will need to be
\begin{equation}
	E_{N_n} = \bar\epsilon_{N_n} = \epsilon_{N_n} \gamma_{N_n}.
\end{equation}
Fixing a bequest value amounts to adding the following constraint
\begin{equation}
	\sum_{i,j} b_{ijN_n} (1 - \nu\delta(j, 1)) = \epsilon_{N_n} \gamma_{N_n},
\end{equation}
which would add one more row to $A_ey = v$ as
\begin{eqnarray}
	A_e[I(0), q_b(i, j, N_n)] &=& (1 - \nu\delta(j, 1)) \nonumber \\
	v[I(0)] &=& \epsilon_{N_n}\gamma_{N_n} \\
	&&\qquad\forall i \in \{0,\ldots, N_i-1\},\nonumber\\
	&&\qquad\forall j \in \{0,\ldots, N_j-1\},\nonumber\\
\end{eqnarray}
where $I(0)$ is used only to provide the proper row offset $C_l$. See Eq.~(\ref{Eq:Offsets}).

For maximizing the net spending under the constraint of a fixed bequest, one has simply to
minimize the inner product $c\cdot y$, where $c$ is
\begin{eqnarray}
	c[q_g(0)] &=& -1,
\end{eqnarray}
and 0 otherwise. See Eq.~(\ref{Eq:C5}).

\paragraph*{Maximum variable net spending}
Instead of maximizing a basis for net spending that is multiplied by a profile $\bar{\xi}_n$,
one could maximize the sum of net spending over the full duration
of the plan, in today's dollars. The quantity to optimize is then
\begin{eqnarray}
	c[q_g(n)] &=& -1/\gamma_n,
\end{eqnarray}
$\forall n \in \{0, \ldots, N_n-1\}$ and 0 otherwise.
In that case, constraint equality Eq.~(\ref{Eq:C5}) will need to be changed to an inequality. 
Instead of obeying 
\begin{equation}
	g_n \xi_0 - g_0 \bar{\xi}_n = 0,
\end{equation}
we now impose the following inequality constraint:
\begin{equation}
        \label{Eq:C15}
	(1 - \lambda) g_0 \bar{\xi}_n/\xi_0 <= g_n <= (1 + \lambda) g_0 \bar{\xi}_n/\xi_0 ,
\end{equation}
where $\lambda$ is the percentage expressed in decimal that the annual net spending is allowed to deviate
from the desired profile. It should be noticed that when $\lambda = 0$ the two
last equations are equivalent.

\paragraph*{Maximum bequest}
If, on the other hand, one would like to maximize the bequest under the constraint of a desired
net spending $g_o$, specified for the first year,
one would add the following row to $A_ey = v$
\begin{eqnarray}
	\label{Eq:FixedIncome}
	A_e[I(0), q_g(0)] &=& 1, \nonumber \\
	v[I(0)] &=& g_o,
\end{eqnarray}
subject to the net spending $g_n$ obeying Eq.~(\ref{Eq:C5}) over time.

The objective function would then be derived from Eq.~(\ref{Eq:Bequest}) as
minimizing the inner product $c\cdot y$, where $c$ is
\begin{eqnarray}
	\label{Eq:MaxBequest}
	c[q_b(i, j, N_n)] &=& -(1 - \nu\delta(j, 1)),\\
	&&\qquad\forall i \in \{0,\ldots, N_i-1\},\nonumber\\
	&&\qquad\forall j \in \{0,\ldots, N_j-1\},\nonumber\\
\end{eqnarray}
and 0 otherwise.

\end{document}
