\chapter{The GNK value: A new solution}
\label{cha:new_solution}

In the previous chapter we introduced several different solution concepts, each stemming from different ethical principles and perspectives.
In this chapter we detail a new approach that combines some of the features of the solution concepts outlaid in the previous chapter.
The primary motivation for this new solution, is to attempt to distil the intuition behind the Nash bargaining solution concepts (per section \ref{sec:solutions_bargaining}) into a description of total allocation that is suitable for arbitrary number of players - rather than just two.
Our solution extends the work of others to the space of generalised non-cooperative games, which are then suitable for application in various electrical network contexts.

Our solution relates to many of the concepts of the previous chapter: where we have a fundamentally coalitional scheme (per Coalitional Game Theory), that rewards based upon disagreement points (Bargaining Theory), which is partially informed by how much individual's participation influences the group's wellbeing (reminiscent of VCG), and attempts to describe normative trading between large numbers of participants (Marginalism).

We call our new solution concept the \textit{Generalized Neyman and Kohlberg Value} or \textit{GNK value} for short, and is computed and directly compared against other solutions concepts of the previous chapter in the context of electricity allocation.
By this comparison it is seen that the different solution concepts give different outcomes, and we discuss these differences in light of our ethical considerations (from Chapter \ref{cha:background}).

The material from this chapter extends from work which was originally submitted to AAMAS, and was accepted as an extended abstract: \\
\-\hspace{5mm}``The Generalized N\&K Value: An Axiomatic Mechanism for Electricity Trading''\\ International Conference on Autonomous Agents and Multiagent Systems\\ (AAMAS) 2018 (accessible: \href{ifaamas.org/Proceedings/aamas2018/pdfs/p1883.pdf}{ifaamas.org/Proceedings/aamas2018/pdfs/p1883.pdf})

This chapter consists of the following parts:

\begin{itemize}
\item	In sections \ref{sec:prelude_gnk} and \ref{the_value_def2}, we introduce and define the GNK value, relating it to historical roots and similar solution concepts.
\item	In section \ref{more_involved}, we consider how the GNK value can be computed to derive financial and electrical outcomes on a DC electricity network, against LMP and VCG.
\item	In section \ref{sec:features}, we point-by-point discuss the features GNK, LMP and VCG as they are expressed in the context of an example electricity network.
%\item	in section \ref{sec:scaling} we address the possible ways of remedying the GNK value for computation in larger network contexts, particularly via the use of sampling to approximate its value, and by the adoption of a proxy for the GNK inner optimisation (which we denote as the M-GNK).
%\item	in section \ref{sec:results_and_evaluation_of_GNK}, we detail computation and the efficiency of computation of the sampled M-GNK value for larger networks, and discuss its shortcommings for an example computed larger network.
%\item	in section \ref{sec:GNK_extensions_discussion} and the concluding section \ref{sec:GNK_value_discussion}, we discuss possible extensions to the GNK concept and compare it point-by-point with ethical qualities.
\end{itemize}

We identify that the GNK value is difficult to compute for large numbers of players, and so in the next chapter \ref{sec:scaling} we address and consider the GNK value at scale against ethical criteria.

%\begin{itemize}
%\item Derive the GNK value (section \ref{the_value_def2})
%\item Apply it to DC networks (section \ref{more_involved})
%\item We discuss some of its qualities (section \ref{sec:features})
%\item Before discussing techniques to scale it (section \ref{sec:scaling})
%\item Then evaluating it at scale (section \ref{sec:results_and_evaluation_of_GNK})
%\item And then conclude with an ethical evaluation (section \ref{sec:GNK_extensions_discussion})
%\end{itemize}

%derive the GNK value (section \ref{the_value_def2}) before applying it to DC networks (section \ref{more_involved}), we discuss its qualities (section \ref{sec:features}), before discussing techniques to scale it (section \ref{sec:scaling}), before evaluating it at scale (section \ref{sec:results_and_evaluation_of_GNK}) and concluding with ethical evaluation (section \ref{sec:GNK_extensions_discussion})

%Particularly:
%\begin{itemize}
%\item	in sections \ref{sec:prelude_gnk},\ref{sec:introduction_gnk_sec},\ref{the_value_def2}, We introduce and define the GNK value at a conceptual and mathematical level, relating it to historical roots and similar solution concepts.
%\item	in sections \ref{more_involved} we consider how the GNK value can be applied to derive financial and electrical transactions on a small example electricity network, and outlay the procedures for its computation alongside LMP and VCG in this context.
%\item	in section \ref{sec:features} we point-by-point discuss the features GNK, LMP and VCG as they are expressed in the context of the small example DC electricity network. particularly we pay attention to the fact that the GNK value is computationally difficult to compute for larger networks.
%\item	in section \ref{sec:scaling} we address the possible ways of remedying the GNK value for computation in larger network contexts, particularly via the use of sampling to approximate its value, and by the adoption of a proxy for the GNK inner optimisation (which we denote as the M-GNK).
%\item	in section \ref{sec:results_and_evaluation_of_GNK}, we detail computation and the efficiency of computation of the sampled M-GNK value for larger networks, and discuss its shortcommings for an example computed larger network.
%\item	in section \ref{sec:GNK_extensions_discussion} and the concluding section \ref{sec:GNK_value_discussion}, we discuss possible extensions to the GNK concept and compare it point-by-point with ethical qualities.
%\end{itemize}

%After this chapter, the next Chapter \ref{chap:stratified_sampling_chapter} details our investigation into novel sampling methods which are which are used to scale the GNK value in section \ref{sec:scaling}.

\section{Introduction to the GNK value}\label{sec:prelude_gnk}\label{sec:introduction_gnk_sec}

How should we model ideal competition? In the two player case, existing bargaining solutions (such as Nash's) seem rather difficult to surpass as they describe a singular and axiomatic outcome that is both cooperatively Pareto optimal and also accounts for anti-cooperative strategising.

In the context of Nash bargaining with endogenous disagreement point (per section \ref{subsec:nash_bargaining_endogenous}), the disagreement point was interpreted as a unique point defined by a minimax equilibrium in the payoff-advantage of strategies.
However there exists a problem extending this scheme directly to three or more players, as there may not exist a unique minimax equilibrium in payoff-advantages for strategies in a game of more than two players.
The question then is how to logically and consistently extend Nash's bargaining solution with endogenous disagreement point to an arbitrary number of players.

While it may be possible to arbitrarily choose one of those possible minimax equilibria in a 3+ person game as the disagreement point,
instead we consider all the possible divisions of players between two groups and then consider all the two-player minimax payoff advantages between them. We then integrate this information via Shapley Value axioms to form a unique outcome, that does not depend on any arbitrary choice.
In this way our new solution allocates outcomes in proportion to the aggregate leverage that all the individuals - and groups of individuals - could hypothetically posses in bargaining for outcomes they desire.
In the following sections of this chapter (sections \ref{the_value_def2} to \ref{more_involved}) we give all the details of this process.% Particularly we note that this process of how to reasonably extend Nash's bargaining solution to multiple players has a history.

The fundamental idea behind our approach was first detailed by \cite{values3}.
So far as we know, Harsanyi's solution concepts have never been applied to electricity networks, as there exists a particular problem in doing so, particularly that Harsanyi's solution concepts apply to non-cooperative games but cannot apply to generalised non-cooperative games.
The details of this problem and our novel remedy are given in following section \ref{the_value_def3}.

But briefly, in electricity network contexts the mutual interactions of participants can be limited by the physical constraint of the network, for instance: network participants cannot simply draw or push power to/from the network without restraint, as doing so would lead to damage to the network.
And these limitations on the space of possible mutual actions is best modelled by a generalised non-cooperative game, and unfortunately in the context of such a generalised game there is no unique minimax point between two players.
Our principle and novel development in this chapter is the provision of a remedy, such that Harsanyi's solution can then be applied.
The remedy is to take the expected outcome on a coin-flip on who chooses actions first in the minimax strategies - and as we shall see - this turns out to be a unique value that satisfies all required properties, and thus leads to a coherent outcome.

The resulting outcome we call the \textit{Generalized Neyman and Kohlberg Value} or the \textit{GNK value} for short,
as Harsanyi's solution was also axiomatically derived by \cite{value2,KOHLBERG2018139}.
This solution concept is shown to apply for all transferable utility (TU) generalised non-cooperative games, and directly equivalent to the Nash bargaining with endogenous disagreement point under transferable utility (TU) between two players (such as per section \ref{sec:nash_bargaining_exogenous}, as in the example in that section).

The GNK value is thus flexible enough to extend to many contexts, but we focus particularly on the specific case of allocating monetary payments over Optimal Power Flow (OPF) instances under the DC approximation - as we will explain.

Let us derive the GNK value (in section \ref{the_value_def2}) before giving details of its application to DC networks (in section \ref{more_involved}), discussing it (section \ref{sec:features}) and scaling it (section \ref{sec:scaling}).

\section{Deriving the GNK value}\label{the_value_def2}

We begin by presenting the axiomatic foundations of the GNK value, in a similar manner as \cite{value2}'s exposition.
We begin by defining the GNK value to be the integration of \emph{threat} values between possible coalitions; defined via Shapley Value axioms.
We then describe the \emph{threat} or \emph{advantage} of a coalition $v(S)$ in the context of a \textit{generalized non-cooperative game} (which is our key point of novelty in the solution concept).
And then we clarify how the GNK value relates to other prominent solution concepts in non-cooperative games.

\subsection{Axiomatic foundations and the \textit{Value}}\label{the_value_def}

%There have been many attempts to answer the question of what cooperative outcome \textit{should} occur in the context of a non-cooperative TU game.
%One well known answer is the \textit{Nash bargaining solution} between two players \cite{nash2}, which Harsanyi extended to arbitrary numbers of players.
%Building on this, Harsanyi's solution \cite{values3} was derived from a simple set of axioms by Neyman and Kohlberg ~\cite{value2};
%our axiomatic derivation of a value for games with generalized action spaces mirrors the steps in theirs.

We begin by considering \cite{KOHLBERG2018139}'s \textit{coalitional game of threats},
which is a coalitional game defined by a pair $\langle N,v \rangle$ in which:
\begin{itemize}
\item	$N=\{1,\dots,n\}$ is a finite set of \textit{players} or \textit{agents}, and
\item	$v:2^N\rightarrow \mathbb{R}$ is a \textit{characteristic function} with
\begin{equation}
v(S)=-v(N\setminus S) \label{myeq2} \quad \forall S\subseteq N.
\end{equation}
\end{itemize}
The intuition for \eqref{myeq2} is that the characteristic function of this game is a measure of the strength of the bargaining position (the `threat' or `advantage') that a coalition, $S$, has over its complement, $N\setminus S$.
This contrasts with classical cooperative game theory games, where the characteristic function $v(\emptyset)=0$ and equation \ref{myeq2} does not generally hold (see section \ref{sec:cooperative_game_theory_part}).

Neyman and Kohlberg's key result was to prove that if $\mathbb{D}$ is the set of all such games, then there exists a unique mapping $\varphi:\mathbb{D}\rightarrow\mathbb{R}^n$ that satisfies the following four axioms:

\begin{itemize}
\item	\textbf{Efficiency}: $\sum_i\varphi(\langle N,v\rangle)_i = v(N)\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad~~\refstepcounter{equation}(\theequation)\label{myeq}$
\item	\textbf{Symmetry}: If two players $i$ and $j$ are substitutes, such that if\\ $v(S\cup i)=v(S\cup j)~~\forall S\subseteq N\setminus\{i,j\}$, then $\varphi(\langle N,v\rangle)_i = \varphi(\langle N,v\rangle)_j$
\item	\textbf{Null Player}: If a player $i$ is a null player (i.e.\ $v(S\cup i)=v(S)~~\forall S\subseteq N$) then $\varphi(\langle N,v\rangle)_i=0$
\item	\textbf{Additivity}: for any $v_1$ and $v_2$, $\varphi(\langle N,v_1+v_2\rangle)=\varphi(\langle N,v_1 \rangle) + \varphi(\langle N,v_2\rangle)$
\end{itemize}

Letting agent $i$'s element of $\varphi$ be denoted by $\varphi_i$, this mapping is:
\begin{equation}\label{da_value_eq}
\varphi_i(\langle N,v\rangle)
= \frac{1}{n}\sum_{k=1}^n v_{i,k}
= \frac{1}{n}\sum_{k=1}^n \frac{1}{\binom{n-1}{k-1}} \sum_{\substack{S:i\in S \\ |S|=k}}v(S)
\end{equation}
Where $v_{i,k}$ is the average value of $v(S)$ for all coalitions of size $k$ that include $i$.
This mapping gives a distribution of the total surplus $v(N)$ among the players, and \cite{KOHLBERG2018139} appropriately call this unique mapping the `Shapley Value' of the game of threats as it mirrors the classic \textit{Shapley Value} of cooperative game theory.

Indeed \cite{KOHLBERG2018139} have shown that for any game of threats $\langle N,v\rangle$ there is a classic cooperative game $\langle N,v'\rangle$ where the two Shapley Values are the same.
It is possible to map a game of threats $v$ to a cooperative game $v'$ via relation:
\begin{equation}\label{convert1}
v'(S)=\frac{1}{2}v(S)+\frac{1}{2}v(N)
\end{equation}
%Where the Shapley value is hence given by the classic expression:
%\begin{equation}\label{eq:shapley_value}
%    \varphi_i(\langle N,v\rangle)= \frac{1}{n}\sum_{S\subseteq N\setminus\{i\}} \binom{n-1}{|S|}^{-1} \left(v'(S\cup\{i\})-v'(S)\right)
%\end{equation}
%Which identifies the Shapley value of a player in a cooperative game as its average over marginal contributions; which we can similarly be expressed by averages over marginal contributions by player and size:
%\begin{equation}\label{eq:shapley_value2}
%\hat{v}_{i,k} = \frac{1}{\binom{n-1}{k}}\sum_{S\subset N\setminus \{ i\} , |S|=k} %\frac{(n-|S|-1)!\,|S|!}{(n-1)!}
%(v'(S\cup\{i\})-v'(S))
%\end{equation}
%\begin{equation}\label{shap2} \varphi_i(\langle N,v\rangle) = \frac{1}{n}\sum_{k=0}^{n-1}\hat{v}_{i,k} \end{equation}
%These multiple formulations of the Shapley value will be useful to us in Section \ref{} where we use these expressions in different methods of sampling the GNK value.

A central question in \cite{KOHLBERG2018139}'s coalitional game of threats, is what the `threat' of a coalition of players $v(S)$ should be (such as on an electricity network), and one way of considering this is in relation to the actions that the coalition could exert and their consequences (positive and negative) over other players; such as may be described in non-cooperative game theory.

\subsection{Defining threats in games with general action spaces}\label{the_value_def3}

In this subsection we define the characteristic function $v(S)$, in the context of a \textit{generalized non-cooperative game}.
A generalised non-cooperative game is a game where the strategies available to one player may be restricted by the strategy choice of others.
Such games were introduced by \cite{Debreu01101952} and the problem of finding equilibria in such games has been a topic of further research \citep{Facchinei2007,fischer2014}.

In more detail, a generalised non-cooperative game consists of a triplet $G = \langle N,A,u \rangle$ in which:
\begin{itemize}
\item	$N=\{1,\dots,n\}$ is a finite set of players,
\item	$A\subseteq \prod_{i\in N}A^i$ is a set of all possible joint strategies, where $A^i$ denotes the set of strategies available to player $i\in N$, and $A$ is a subset of their product space
\item	$\{u_i(a) : A\rightarrow \mathbb{R}\}_{i\in N}$ is a set of functions of each player's payoff/utility when joint strategy $a\in A$ is executed.
\end{itemize}

In this context, we wish to describe the payoff `threat' or `advantage' $v(S)$ of a coalition $S\subseteq N$ (letting $A^S=\prod_{i\in S}A^i$), taking into account the constraints that apply to the joint action space.
A key contribution in our research is the following construction of the coalitional game of threat's characteristic function.
Denoting $(x,y)\in A$ as a partition of a joint action between two coalitions $S$ and $N\setminus S$,
the characteristic function for the game of threats with generalised action spaces is given by:
\begin{align}
\label{knvalue1}
v(S) = &
\frac{1}{2}\min_{\substack{y\in A^{N\setminus S} \\ \text{s.t.}\exists x,(x,y)\in A}}
\max_{\substack{x\in A^S \\ \text{s.t.}(x,y)\in A}}
	\left(\sum_{i\in S} u_i(x,y) - \sum_{i\in N\setminus S}u_i(x,y)\right)\nonumber\\
+&
\frac{1}{2}\max_{\substack{x\in A^S \\ \text{s.t.}\exists y,(x,y)\in A}}
\min_{\substack{y\in A^{N\setminus S} \\ \text{s.t.}(x,y)\in A}}
	\left(\sum_{i\in S} u_i(x,y) - \sum_{i\in N\setminus S} u_i(x,y) \right)
\end{align}

The requisite condition $v(S)=-v(N\setminus S)$, as given in~\eqref{myeq2}, is immediately satisfied irrespective of the structure of strategy space $A$, insofar as the $\max$ and $\min$ terms are defined.
Thus, \eqref{knvalue1} is a feasible representation of the competitive advantage (or threat) that a coalition has over its complement in a generalised strategy space.
With the characteristic function \eqref{knvalue1}, the formulation of $\varphi$ (per \eqref{da_value_eq}) defines the GNK value.
This is a novel extension of existing work to the space of generalised games (see Section~\ref{relating_to_the_old}).

\subsection{Understanding the GNK value}\label{the_value_def4}

In the characteristic function~\eqref{knvalue1}, the inner term:
\[
\sum_{i\in S} u_i(x,y) - \sum_{i\in N\setminus S} u_i(x,y)
\]
is the sum of payoffs that the coalition $S$ receives,
minus the sum of payoffs that the complement $N\setminus S$ receives,
under the joint strategy $(x,y)\in A$, we call this the \textit{payoff advantage} to $S$.

The first line of $v(S)$ in~\eqref{knvalue1} is half the payoff advantage achieved if, the players in $S$ collectively choose their strategies to maximise the payoff advantage knowing that the players in $N\setminus S$ will subsequently choose their strategies to minimise it - and thus this dynamic constitutes a bilevel optimisation problem.
Then the second line of~\eqref{knvalue1} is an additional half of the payoff advantage achieved if the ordering of choice were reversed, with $N\setminus S$ choosing first.
In this way, \eqref{knvalue1} can be interpreted as the expectation of Nash equilibrium payoff advantage of $S$ over its complement under a fair coin-toss of who chooses their strategies first.

In this formulation $v(N) = \max_{a\in A} (\sum_{i\in N} u_i(a))$ is the maximum achievable sum of payoffs that the players can achieve, and the GNK value $\varphi$, splits all of this amount between the players (by the efficiency axiom).
The allocation of utility that the GNK value allocates can be realised by having the players execute the strategies that achieve this maximal sum, and then enacting appropriate utility transfers between the players.
In this way the GNK value can be seen as a method of allocating a Pareto optimal outcome and budget-balanced payments between players, to attain utility proportional to their competitive advantages.

\subsection{Relation to other solution concepts}\label{relating_to_the_old}

The GNK value is closely related to several other solution concepts, and even equivalent to them under certain conditions.

Most immediately, the GNK value is identical to \cite{value2}'s Value when the strategy space $A$ represents a mixed strategy game that is not generalised; that is when the strategy space, $A$, is an unconstrained combination of strategies for all agents (ie. $A = \prod_{i\in N}A^i$).
To see this, we observe that the two halves of \eqref{knvalue1} are equal in the absence of joint action constraints (%proof in Appendix \ref{appendix1}, or
via direct application of von Neumann's minimax theorem\footnote{see Lemma 1 of \cite{value2}}),
and hence the characteristic value reduces to that used in Neyman and Kohlberg's original definition:
\begin{equation}\label{knvalue2}v_o(S) = \max_{x\in A^S}\min_{y\in A^{N\setminus S}} \left(\sum_{i\in S} u_i(x,y) - \sum_{i\in N\setminus S} u_i(x,y) \right).\end{equation}
%
That is, Neyman and Kohlberg's Value is the formulation of $\varphi$ (per \eqref{da_value_eq})
with $v_o(S)$ (per \eqref{knvalue2}).
Unfortunately Neyman and Kohlberg's Value cannot be directly applied to generalised games because the required condition $v_o(S)=-v_o(N\setminus S)$ can fail to hold in that case.

Neyman and Kohlberg's Value (and the GNK value) are also directly conceptually related to \cite{values3}'s solution in this context,
while in the 2-player context, it is identical to \cite{kalai1,Kalai2010}'s \textit{coco-value} in the context of complete information
and also identical to \cite{nash2}'s bargaining solution in the context of transferable utility (see \cite{value2}, or section \ref{subsec:nash_bargaining_endogenous}).
It also shares a conceptual similarity with \cite{aumann1961core}'s $\alpha$ and $\beta$ core solution concepts, and \cite{1944}'s historic formulation :
\begin{equation}\label{knvalue3}v_m(S) = \max_{x\in A^S}\min_{y\in A^{N\setminus S}} \sum_{i\in S} u_i(x,y).\end{equation}
In this way the GNK value can be seen as a conceptual continuation of historic solution concepts, and can be judged according to how well it derives outcomes in application contexts.

As a simple example demonstration, it is possible to see how the GNK value is identical to Nash bargaining in the context of transferable utility games (such as in the example matrix game \ref{eq:example_game1} of section \ref{subsec:nash_bargaining_endogenous}), we calculate all the terms $v(S)$ for coalitions of players $1$ and $2$, particularly:

\begin{align*}
v(\{1,2\})=&\max\max\begin{bmatrix}3 & -3\\ -3 & 3\end{bmatrix}=3\\
v(\{1\})=&\frac{1}{2}\min\max\begin{bmatrix}1 & 1\\ -1 & -1\end{bmatrix}+\frac{1}{2}\max\min\begin{bmatrix}1 & -1\\ 1 & -1\end{bmatrix}=1\\
v(\{2\})=&\frac{1}{2}\min\max\begin{bmatrix}1 & -1\\ 1 & -1\end{bmatrix}+\frac{1}{2}\max\min\begin{bmatrix}1 & 1\\ -1 & -1\end{bmatrix}=-1\\
v(\emptyset)=&-\max\max\begin{bmatrix}3 & -3\\ -3 & 3\end{bmatrix}=-3\\
\end{align*}
From this:
$$ \varphi_1(\langle N,v\rangle)=\frac{1}{2}(v(\{1,2\})+v(\{1\}))=\frac{1}{2}(3+1)=2 $$
$$ \varphi_2(\langle N,v\rangle)=\frac{1}{2}(v(\{1,2\})+v(\{2\}))=\frac{1}{2}(3-1)=1 $$
Which matches exactly the result in section \ref{subsec:nash_bargaining_endogenous}. In section \ref{subsec:nash_bargaining_endogenous} we considered that the minimax in the payoff advantage matrix (ie. $d$ in that section) was the nash equilibrium point of threat in bargaining between the players in choosing a subsequent point on the Pareto frontier (see Figure \ref{fig:graph1_utilities}) that divides the maximum possible sum revenue (ie $s$ in that section).
The GNK value also directly encodes this same logic as $v(\{1\})=-v(\{2\})$ is the minimax in the payoff advantage between the player (in this ungeneralised game), and $v(\{1,2\})$ is the maximum sum revenue which is split. This result is the same as we would get by the \textit{coco-value}, and working with Neyman and Kohlberg's value (equation \ref{knvalue2}).

In the following section we describe the setup for an application and evaluation of the GNK value in the context of DC-approximated electrical networks.

\section{GNK value computation on DC powerflows}\label{more_involved}

Because of its flexibility the GNK value has the potential to be used in a large range of different contexts,
however in this section we focus solely on the development of a simple case --- the pricing of the immediate consumption and generation of power on a meshed network under DC approximation, where all participants have linear utilities over their own power.
Although this construction simplifies away some key technical problems in power networks, it allows us to clarify the analysis of the GNK value and its features.

In this section, we consider the DC network model, discuss how to calculate the GNK value as well as LMP and VCG for it, before in the next section \ref{sec:features} we discuss the features of these mechanisms with an example.

\subsection{Network model}\label{sec:the_setup}

We begin by setting out the elements of an electricity network under DC approximation:
\begin{itemize}
    \item A set of buses $B$ with, for all $i\in B$:
    \begin{itemize}
        \item Power consumption at each bus $p_i$, and
        \item A bus voltage phase-angle $\theta_i$,
    \end{itemize}
    \item Lines $C\subseteq B\times B$, with, for all $(i,j)\in C$:
        \begin{itemize}
        \item Line susceptance $b_{i,j}$, and
        \item Power flow $p_{i,j}$ (power from bus $i$ to $j$), with $p_{i,j}=-p_{j,i}$.
    \end{itemize}
\end{itemize}
In this context, the DC approximated powerflow constraints (per \cite{Wang1}) are expressed as follows:
\begin{equation}
\label{dcopf1}
\begin{aligned}
\text{DC-powerflow} \quad& \\
\text{Variables:} \quad&  p_{i\in B},\ \theta_{i\in B},\ p_{(i,j)\in C} \\
\text{constraints:} \quad& p_i^{l}\le p_i \le p_i^{u} \\
&p_{i,j}^l \le p_{i,j} \le p_{i,j}^u \\
&p_j = \sum_{(i,j)\in C}p_{i,j}\\
&p_{i,j} = -b_{i,j}(\theta_i - \theta_j)
\end{aligned}
\end{equation}
where $p_i^{l}$, $p_i^{u}$, $p_{i,j}^l$, $p_{i,j}^u$ are the upper and lower bounds on power consumption/generation and line limits, respectively.

We can eliminate redundant variables, such as $\theta_i$ and $p_{i,j}$, and to ease presentation, and use the abstract functions $h_j$ and $g_k$ (for indices $j,k$) to represent the remaining linear functions:

\begin{equation}
\label{dcopf2}
\begin{aligned}
\text{DC-powerflow}\\
\text{Variables:}\quad & p_{i\in B} \\
\text{constraints:}\quad & h_j(p_1,p_2,\dots)=0\quad \forall j\\
& g_k(p_1,p_2,\dots)\le 0 \quad \forall k
\end{aligned}
\end{equation}

In this DC powerflow network the participants on each bus are treated as players in a game.
For simplicity, we have one player per bus (i.e.~$N=B$), and the power consumption of that bus is the respective player's strategy space (i.e.\ $A_i=[p_i^l,p_i^u]$).
Then the DC constraints define the space of jointly executable strategies --- forming the generalised strategy space $A$.

We further assume that there is a linear utility (or payoff) associated with the power consumption of each player, denoted $u_i(p_i)$ for player $i$, which makes all the components of a generalised game.\footnote{the Linear utility assumption simplifies the mathematics, as it makes the objective function linear, intuitively consumers should value consuming more power more, and generators cost producing more power more with some gradient.}
We now consider how to calculate the GNK value against LMP and VCG for such a generalised game.

\subsection{Computing the GNK value}\label{subsec:gnk_compute1}

The GNK value is difficult to solve because of the bilevel structure of \eqref{knvalue1} which must be computed for each of the possible coalitions of network participants.
Even though we have modelled our example network with a set of linear utility functions and linear constraints (as given in section \ref{sec:the_setup}), equation \eqref{knvalue1} is still quite difficult to solve as it constitutes a linear bilevel program (LBP) which are a class of problems known by to be NP-hard. \citep{DBLP:journals/tec/SinhaMD18,Ben-Ayed:1990:CDB}

There exist a range of techniques which can be used to solve LBPs, such as summarised by \cite{DBLP:journals/tec/SinhaMD18,S.Dempe.Optimisations}.
Some of the many methods include: vertex enumeration processes \citep{Bialas:1984:TLP:2784019.2784026,Shi:2005:EKA:2641854.2642183,LIU1995644}; penalty method schemes \citep{KleinertSchmidt2019,ONAL1993126,dempe_optimisation111};
cutting plane approaches \citep{cuttingplane1};
branch-and-bound/cut methods \citep{SHI200551,Hansen:1992:NBR:141164.141181,Audet2007};
and approximating algorithms \citep{Pineda2018,rnnlbp1,genetic_algirthm_blp}.

One well known way of addressing LBPs involves converting the inner optimisation constraints into KKT conditions (introduced by \cite{kuhn1951nonlinear}), and then converting the complementarity conditions into disjunctive constraints with binary variables - see \cite{Fortuny-Amat1981,Pineda2018}.
In this way, a bilevel program is converted into a mixed integer linear program, which is then directly amenable to standard optimisation software.
This method was chosen, and the SCIP Optimisation Suite was employed to compute the GNK value for an example network as described in the next section \ref{sec:example_network}.

KKT conditions are a well known set of algebraic tests which imply that the function under consideration is locally optimal (maximal or alternatively minimal) with respect to its variables under a set of constraint functions (with some regularity assumptions on those functions).
KKT are well documented, and extend the method of Lagrange multipliers.

Specifically for maximising an objective function $f(\mathbf{x})$ subject to multiple constraints:
\begin{equation}\label{eq:KKT_condition1} g_k(\mathbf{x})\le 0 \end{equation}
\begin{equation}\label{eq:KKT_condition2} h_j(\mathbf{x})=0 \end{equation}
Then $\mathbf{x}*$ is a local maximum if the following KKT conditions are true:
\begin{equation}\label{eq:KKT_conditions3} \nabla f(\mathbf{x}*) - \sum_k\lambda_k\nabla g_k(\mathbf{x}*) - \sum_j\mu_k\nabla h_k(\mathbf{x}*) =0\end{equation}
and equations \ref{eq:KKT_condition1} and \ref{eq:KKT_condition2} hold for $\mathbf{x}*$, and for all $i$ that $\lambda_i\ge 0$ and $\lambda_ig_i(\mathbf{x}*)=0$.

By KKT conditions, we can convert the DC powerflow constraints given by equations \ref{dcopf2} into a set of equations for maximising an objective function $f(p_{i\in B})$:

\begin{equation}\forall i~~\frac{\partial f}{\partial p_i}(p_{i\in B})=\sum_j\mu_j\frac{\partial h_j}{\partial p_i}(p_{i\in B}) + \sum_k\lambda_k\frac{\partial g_k}{\partial p_i}(p_{i\in B})\end{equation}
\begin{equation}\forall j~~ h_j(p_{i\in B})=0\end{equation}
\begin{equation}\forall k~~ g_k(p_{i\in B})\le 0\end{equation}
\begin{equation}\forall k~~ \lambda_k \ge 0\end{equation}
\begin{equation}\label{eq:complementarity_constraint_KKT}\forall k~~ \lambda_kg_k(p_{i\in B}) = 0\end{equation}

Hence the reformulation of our LBPs in equation \ref{knvalue1} involves transforming the inner maximisation/minimisation constraints into KKT conditions.
The sets of variable values which satisfy the KKT conditions are called KKT points, if we denote the set of values of an maximised objective function $f(p_{i\in B})$ at the KKT points as $\mathcal{KKT}(f(p_{i\in B}))$.
Then reformulation of the inner part of \eqref{knvalue1} to involve KKT conditions is as follows:

\begin{equation}
\label{kkt_optimization1}
\begin{aligned}
v(S) =&
 \frac{1}{2}\max_{\substack{p_i \\ i\in S}}   \min\left[-\mathcal{KKT}\left(-\sum_{i\in S} u_i(x,y) + \sum_{i\in N\setminus S}u_i(x,y)\right)\right] +\\
&\frac{1}{2}\min_{\substack{p_i \\ i\notin S}}\max\left[\mathcal{KKT}\left(\sum_{i\in S} u_i(x,y) - \sum_{i\in N\setminus S}u_i(x,y)\right)\right]
\end{aligned}
\end{equation}

By reformulating the inner maximisations/minimisations of \eqref{knvalue1} in this way we replaced the inner minimisations/maximisations in the space $(x,y)\in A$ with minimisations/maximisations over KKT points in the same space.%\footnote{By doing this we tacitly we assume that $u_i(p_i)$ is continuously differentiable, and satisfy some regularity conditions.}

As the constraints under DC-approximation are linear and hence define a convex polygon,
%if we assume that the functions $u_i(p_i)$ are concave then there is either: only ever a single KKT point for all sets of outer variables, or (if weakly-concave) then any of the KKT points will be equal to the global minima (maxima).
%Hence the inner maximization (minimization) over the KKT points can be ignored.
and as the functions $u_i(p_i)$ are linear (per the assumption of linear utility in section \ref{sec:the_setup}), then there will only be a single maximum/minimum value of these inner minimisations/maximisations - which will be the global maximum/minimum value.\footnote{as linear optimisation problem has a unique solution, although there may be multiple points which attain this maximum/minimum value}
In this way the inner maximisation (minimisation) over the KKT points can be ignored.

It was also realised that a binary reformulation of the complementary slackness conditions (equation \ref{eq:complementarity_constraint_KKT}) would increase computational efficiency, and so we transformed these complementarity constraints into disjunctive binary constraints.

Specifically, for each complementary slackness condition $\lambda_kg_k(p_{i\in B}) = 0$ we introduced a binary variable $Z_k$ to indicate whether $\lambda_k$ or $g_k(p_{i\in B})$ was zero and then introduced large numbers $\bar{\lambda}_k$ and $ \underline{g_k} $ such as to make the complementary slackness condition equivalent to: $(1-Z_k)\bar{\lambda}_k \ge \lambda_k \ge 0$ and $\underline{g_k}Z_k\le g_k(p_{i\in B})\le 0$.
Where $\bar{\lambda}_k$ and $\underline{g_k}$ are the estimated upper and lower bounds on the KKT multipliers and constraint functions respectively.

the resulting KKT conditions for maximising and objective function $f(p_{i\in B})$ under this complementary slackness conditions are as follows:

\begin{equation}\forall i~~\frac{\partial f}{\partial p_i}(p_{i\in B})=\sum_j\mu_j\frac{\partial h_j}{\partial p_i}(p_{i\in B}) + \sum_k\lambda_k\frac{\partial g_k}{\partial p_i}(p_{i\in B})\end{equation}
\begin{equation}\forall j~~ h_j(p_{i\in B})=0\end{equation}
\begin{equation}\forall k~~ g_k(p_{i\in B})\le 0\end{equation}
\begin{equation}\forall k~~ (1-Z_k)\bar{\lambda}_k \ge \lambda_k \ge 0\end{equation}
\begin{equation}\forall k~~ \underline{g_k}Z_k\le g_k(p_{i\in B}) \le 0\end{equation}

if we denote the set of values of an maximised objective function $f(p_{i\in B})$ that satisfy these new KKT conditions $\mathbb{KKT}(f(p_{i\in B}))$.
Then reformulation of the inner part of \eqref{knvalue1} to involve KKT conditions is as follows:

The resulting reformulation is as follows:

\begin{equation}
\label{optimization_eq1}
\begin{aligned}
v(S) =
&\frac{1}{2}\max_{\substack{p_i \\ i\in S}}   \left[-\mathbb{KKT}\left(-\sum_{i\in S} u_i(x,y) + \sum_{i\in N\setminus S}u_i(x,y)\right)\right] +\\
&\frac{1}{2}\min_{\substack{p_i \\ i\notin S}}\left[\mathbb{KKT}\left(\sum_{i\in S} u_i(x,y) - \sum_{i\in N\setminus S}u_i(x,y)\right)\right]
\end{aligned}
\end{equation}

This reformulation renders the LBP into a mixed integer program which is directly amenable for calculation by optimisation solvers, and the SCIP optimisation suite was used in our case.
%Using the SCIP optimisation suite the GNK transfers were calculated for an example DC network in the next section \ref{sec:example_network} particularly as shown in Figures \ref{fig:1d} and \ref{fig:1c} show the utility transfers and the post-transfer utilities under GNK.

\subsection{Computing the LMP transfers}\label{subsec:LMP_compute1}

Computing the Locational Marginal Price (LMP) transfers for DC electricity networks is a process described in various literature - such as by \cite{lmp1,lmp2}.

Particularly we consider optimising the sum of utility: $\sum_{i\in B} u_i(p_i)$ subject to the DC powerflow constraints in equations \ref{dcopf1}.
In this context the power conservation constraints on each bus are the constraints $p_j = \sum_{(i,j)\in C}p_{i,j}$, and the lagrange multipliers associated with these constraints are the marginal prices for power on each of the respective busses.
This process is an application of the more general marginal price calculation procedure discussed previously in section \ref{subsec:marginal_price_sketch}.
We utilised the SCIP optimisation suite\footnote{development reported by \cite{MaherFischerGallyetal.2017}}.

\subsection{Computing the VCG imputations}\label{subsec:VCG_compute1}

From section \ref{sec:solutions_VCG} the VCG payment that a participant makes is the difference between the sum of other's utility at the social optimum point $x^*$, and the utility that others would have if the participant were not present and the optimisation were only over the remaining participants, as seen in equation \ref{eq:VCG_payment_rule}.

In this way the socially optimum value $x^*$ needs to be computed, and then additionally an additional optimisation problem for each player - where we assume that the excluded participant has power zero $p_i=0$. Thus in our context, equation \ref{eq:VCG_payment_rule} becomes:
\begin{equation}\label{eq:VCG_calculation_DC} d_i=\argmax_{\sum_{j} u_j(p_j)}\sum_{j\ne i}u_j(p_j) - \argmax_{\sum_{j\ne i} u_j(p_j), p_i=0}\sum_{j\ne i}u_j(p_j)\end{equation}

The first term in this equation is the sum of utilities at the point which maximises the sum of utilities minus the player $i$.
The second term in this equation is the sum of other's utilities (ie. excluding player $i$) at the point which maximises the sum of other's utilities in the context that the players power is zero.
The first part of the equation is common to all player's contributions $d_i$, but the second negative part is unique for each.
In this way, if there are $n$ participants, there are $n+1$ comparable OPF optimisation problems which need to be solved to calculate VCG payments.
The SCIP optimisation suite was used solving these optimisation problems.

\subsection{Computing the Shapley Value imputations}\label{subsec:Shap_compute1}

From section \ref{subsec:the_shapley_value} the Shapley Value utility imputations that a participant receives is the average marginal contribution that it adds to a characteristic function under ambiguity of the join ordering.
In this way we need to consider a characteristic function in the context of DC networks:
\begin{equation*}v_{shap}(S) = \max\sum_{j}u_j(p_j)~~~~\text{s.t.}~~\forall i\notin S~~p_i=0\end{equation*}
This characteristic function describes the utility that a coalition could achieve by themselves, absent any consumption/generation from those not in the coalition - it is one possible way of creating a characteristic function for DC networks.

The utilities under the Shapley Value (by efficiency axiom) sum to give the value of the grand coalition $v_{shap}(N)$ which occurs at the optimal operating point $x^*$.
Thus the Shapley Value can be implementing by enacting electrical outcomes described by $x^*$ and conducting budget balanced utility transfers between participants.
To calculate the Shapley Value imputations, the maximal sum of utilities under OPF for all the possible $2^n-1$ coalitions need computed, and the SCIP optimisation suite was used for these calculations.

\section{Some features of GNK, in context of an example}\label{sec:features}\label{sec:example_network}

In the previous section \ref{more_involved} we detailed a procedure to calculate the financial payments and dispatched powers under the GNK value as well as LMP, VCG and Shapley Value, so that now we can compute and compare them with an example.
In this section we are thus able to witness and discuss the characteristics of the GNK value, in the context of an example 5-bus network shown in Figure \ref{fig:example1}, with parameters given in Table~\ref{tab:example1}.
In this example we calculate and subsequently consider the features of the GNK value against LMP, VCG and Shapley Value against parameter $p_1^l$ (the generator capacity in the network).
The results of these calculations of the financial payments are plotted against $p_1^l$ in Figures \ref{fig:1d}, \ref{fig:1f}, \ref{fig:1h} and \ref{fig:1j} for GNK, LMP, VCG and Shapley Value respectively. Which in addition to the utilities derived from power consumption/generation (Figure \ref{fig:1b}) form the post payment utility imputations as Figures \ref{fig:1c}, \ref{fig:1e}, \ref{fig:1g} and \ref{fig:1i}.

%For GNK, LMP and VCG, the power allocations and the utilities associated with these power allocations are plotted against $p_1^l$ (the generator capacity in the network) and are shown in Figures \ref{fig:1a} and \ref{fig:1b}.
%And through subsequent pairs of figures we can see how the different mechanisms allocate payments and utilities in the context of constrained resources - Figures \ref{fig:1c}, \ref{fig:1d} for GNK, Figures \ref{fig:1e}, \ref{fig:1f} for LMP, Figures \ref{fig:1g}, \ref{fig:1h} for VCG.

\input{figs/Electro_table.tex}

\iffigures
% \input{graph0.tex}
\input{figs/GNK_graph1.tex}
\fi

In Figure~\ref{fig:1a}, increasing the generator capacity from $0$ shows that power is initially consumed entirely by the consumer at bus 2,
who uses all $p_1^l$kW of power and values it at a rate of 1.9 units of utility. This continues until the power constraint on line (1,2) binds, at 70kW.
Then the consumer at bus 3 begins to be supplied with power, who values it at a rate of 1.8 units of utility until its consumption is maximised at 100kW.
This dynamic is then repeated for the agent with the next-highest marginal utility for power (given by the utility function coefficients in Table~\ref{tab:example1}), until the respective line constraints are also met.

In the interval of the first 70 units of generator capacity (ie. $p_1^l \in [0,-70]$), the LMP price for this power, for both the generator at bus 1 and the consumer at bus 2, is given by its marginal value 1.9 (as the line constraint is not active). This corresponds to the slope of the black line in Figure~\ref{fig:1f} (or \ref{fig:1b}) over this interval.
More generally, the full set of the LMP transfers plotted in Figure~\ref{fig:1f} are given by the Lagrange multiplier for power conservation in the OPF optimisation multiplied by the power consumed at that bus, and that as the generation capacity increases the marginal price of power changes, and the gradients of the lines change in discrete steps as the utility functions in the example network are linear.

Additionally, the VCG payments are plotted against $p_1^l$ in Figures \ref{fig:1h} and resulting utilities in Figure \ref{fig:1g}.
The VCG payments are similar to the LMP payments, except that instead of payment proportional to the marginal unit of electricity, each player is compensated at his/her marginal cost of their participation.
VCG takes into account the marginal effect that each of the player's participation has upon each other at the social optimum

In contrast VCG and LMP, the GNK value takes into account the full bargaining position of each agent and also every possible coalition of agents when determining transfers, which are based on the utilities (or costs, in the case of the generator) of all agents in the system, and not just the marginal value of participation or electrical supply.
The GNK value is plotted against $p_1^l$ for our example in Figure~\ref{fig:1c}, and the resulting transfers (GNK value less utility) are plotted in Figure~\ref{fig:1d}.

In contrast to VCG, LMP and GNK, the Shapley Value exhibits character traits that are similar to LMP and VCG, particularly as the Shapley value is composed of many more marginal contributions than those ones inherent to VCG, which is in turn proportional to the marginalism inherent in LMP.
Furthermore it has a superficial similarity to the GNK value as they both extend from the same axioms - either exhibited in section \ref{the_value_def}, or by conversion to Shapley value by equation \ref{convert1} thus having exactly the same axioms as in section \ref{subsec:the_shapley_value}.
The Shapley Value results are plotted against $p_1^l$ for our example in Figure~\ref{fig:1i}, and the resulting transfers (GNK value less utility) are plotted in Figure~\ref{fig:1j}.

From these graphs we can witness some of the qualities of the GNK value against LMP and VCG and the Shapley Value:

% \begin{itemize}
% \item GNK is continuous in the parameters of the network
% \end{itemize}

\subsubsection*{The GNK value, VCG and Shapley Value imputations are continuous in the parameters of the network}
The GNK value has some evident continuity properties, as can be seen from equation \ref{knvalue1}, in which the minimax characteristic function, $v(S)$, always changes continuously with the utility functions $u$.
This continuity property is proven in the Appendix \ref{appendix:continuity_of_GNK}, together with some associated monotonicity properties.
%, and are generally continuous with continuous deformations of the strategy space $A$.
This continuity is similarly witnessed in VCG imputations, but notably not in the context of LMP payments.

It is seen that LMP features discontinuous changes in financial transfers and this can clearly be seen from the jagged edges in Figure \ref{fig:1f}, where the payments received by generator 1 drop sharply with increasing generator capacity.
This happens because the change in generator capacity is changing the parameters of the network itself and its feasibility region, which yields discontinuous changes in network operating point, and thus marginal prices.
This dynamic under LMP might be seen to lead to a somewhat perverse incentive to produce less power than what is socially optimal, and in contrast, the utilities under the GNK value (Figure \ref{fig:1c}), VCG (Figure \ref{fig:1g}) and Shapley Value (Figure \ref{fig:1i}) which feature no such drops or discontinuities.
In a power systems context under LMP, these discontinuities are known to occur precisely in the event of network \emph{congestion}
which is one known cause of the volatility experienced in electricity markets - see \cite{RePEc:aen:journl:2006v27-02-a09}.
In contrast, the post-payment utilities under the GNK value and VCG are always continuous with network parameters.

%In the electrical context,
%$v(S)$ will change continuously when the utilities of the participants and/or the network constraint functions change continuously.
%In these cases, because $v(S)$ will change continuously, the GNK value $\varphi$ will also change continuously.

% \begin{itemize}
% \item the GNK value is always budget balanced
% \end{itemize}
\subsubsection*{The GNK and Shapley Value payments are always budget balanced}
The transactions under VCG are not necessarily budget-balanced and can yield a surplus or deficit, and transactions under LMP can yield a budget surplus (they are weakly budget balanced \cite{Wu1996}[Fact 4]), whereas payments under the GNK value and Shapley Value are strongly budget-balanced and result in no surplus or deficit.
This is an outcome of the GNK value's axiomatic derivation, as given by equation \eqref{myeq}, which is reflective of the Shapley Value axioms, per section \ref{subsec:the_shapley_value}.
Under LMP, each participant is credited or debited at the effective rate of supply for their location but there is no guarantees that the total payments should add to zero.
This can be seen by inspecting the region $x>300$ in Figure~\ref{fig:1f}, where generator 1 is credited $\$56$ while the consumers are debited at $\$133.0$, $\$160.0$, $\$119.0$, and $\$64.0$ respectively, leading to a budget surplus of $\$420$.
The surplus of $\$420$ comes particularly from the existence of congestion in the example network which is well known to introduce so-called `congestion-rents'.
Additionally VCG payments are known not to be budget balanced generally and may yield a surplus or deficit depending on various conditions, as considered in section \ref{sec:solutions_VCG}.

%In a power systems context, budget-balancedness of payments is desirable in that any revenue/deficit collected is independent of the network operating conditions.

% \begin{itemize}
% \item the GNK value can offset those that do not receive/generate power
% \end{itemize}
\subsubsection*{The GNK value (but not VCG or LMP) can offset those that do not receive or generate power}
The GNK value can allocate payments between parties such that the consumers that receive power compensate those that are excluded from receiving it.
This can be seen from Figures \ref{fig:1a} and \ref{fig:1c} particularly in the region where $x<50$.
In this region there is only sufficient power to supply consumer 2 (who has the highest utility for that power) whereas consumers 3, 4 and 5 who would otherwise be in a position to receive that power are
compensated such as to be barely worse off (as can be seen from \ref{fig:1c}).

For instance at $x=50$, generator 1 produces $50$kW which is consumed entirely by consumer 2; the utilities of the participants before transfers are: $-10, 95, 0, 0, 0$ respectively (which can be seen from Figure \ref{fig:1b}).
However under the GNK value, consumer 2 must pay both the generator and also the other consumers for its right-of-way to consumption.

The utilities after the transfers of the participants are: $0.5, 23.83, 21.33, 20.08, 19.25$ respectively (which can be seen from Figure \ref{fig:1c}).
In a power systems context, this is likely to be seen as a desirable quality as it may correspond to people's intuitions about the fair allocation of resources.
For example, distribution network feeders that have a high penetration of PV systems have been identified by \cite{feeder1} to experience voltage rise problems at
times of high-supply/low-demand, particularly at the feeder extremities.
In these settings, the inverters of PV owners at the bottom are unable to inject their power into the network and also typically get no compensation for essentially a forced curtailment of their electricity generation.

In this context under LMP, curtailed generators that dont inject their power get no reward, and under VCG curtailed generators will only be allocated utility if their presence or absence would make a difference to the network operating point, which is not assured.
Under Shapley Value, it is witnessed that there is some rather small offset for those that do not receive power, though this is mostly determined by marginal coalitional considerations that exclude most other consumers.

% \begin{itemize}
% \item the GNK value is not incentive compatible
% \end{itemize}
\subsubsection*{The GNK value is not incentive compatible}
Unlike VCG, the GNK value, LMP and Shapley Value are not \emph{incentive compatible} in the sense that is often referred-to in Mechanism Design (see Section \ref{sec:solutions_VCG}).
Specifically, the payments between parties are potentially subject to strategic manipulation if the agents are freely able to report their utility.
In the GNK value this can be seen in \eqref{knvalue1}, or more easily in its reduced form, \eqref{knvalue2}, where the payoff advantage of a coalition $v(S)$ is based on its reported utilities in minimax strategies which may not be actualised; the same consideration holds for the Shapley Value.
Because of this consideration, misreporting the utilities of these unactualised events may change the $v(S)$ and hence the GNK value itself.
Additionally, LMP is known not to be incentive compatible, and there is further work to understand exactly how consequential this would likely be - such as by \cite{8054716}.
In section \ref{sec:GNK_extensions_discussion} we continue discussion about this point.

% \begin{itemize}
% \item the GNK value is computationally difficult
% \end{itemize}
\subsubsection*{The GNK value and Shapley Value are computationally difficult}
The GNK value is more difficult than the Shapley Value, which is more difficult than VCG, which is more difficult than LMP, to compute.
This can be seen via \eqref{da_value_eq} where calculating the GNK value exactly requires calculating $v(S)$ for all the $2^n-1$ possible coalitions $S$, and each calculation of $v(s)$ is an NP-hard bilevel optimisation problem.
The Shapley Value also requires calculating $v_{shape}(S)$ for all the $2^n-1$ possible coalitions $S$, but the calculation of $v_{shape}(S)$ is not necessarily NP-hard problem, as DC OPF problem can be a linear optimisation.
Conversely VCG calculation for $n$ agents requires $n+1$ OPF optimisations (which are potentially linear in the DC case) per equation \ref{eq:VCG_calculation_DC}, where as LMP calculation requires exactly one OPF optimisation (as identified in section \ref{subsec:LMP_compute1}).

The computational difficulty of the GNK value is reflected in a later Figure \ref{fig:performance_graph2} where it is seen that even using sampling to approximate the GNK value to sufficient accuracy is witnessed to be a double-exponentially complex process.

\section{Summary}

In this Chapter we have introduced the GNK value from its axioms and we have considered its conceptual inheritance from other solution concepts.
In order to apply the GNK value to the pricing of immediate power generation and consumption in small DC networks we formally introduced the elements of the DC network and have detailed a computation methodology for the GNK value in that context.
We then compared the GNK against LMP, VCG and Shapley Value on a small example network to examine their features, particularly we identified that the GNK value has some nice budget-balance and continuity properties, however we also realised that the GNK is not incentive compatable and that it is difficult to calculate for larger electricity networks.

In the next chapter we consider the ways in which the computational difficultly of calculating the GNK value on larger networks can be ameliorated.
The two primary techniques to ameliorate this difficulty are principally by sampling, and also by the adoption of a proxy for the inner optimisations.
We discuss these to directions in the next chapter \ref{sec:scaling} before actually applying these techniques for an application of GNK to larger network in section \ref{sec:results_and_evaluation_of_GNK} where we discuss in section \ref{sec:GNK_value_discussion}.


% Features to discuss in depth:
This section gives a basic introduction of SymPy, and lists its features.
A few features---assumptions, simplification, calculus, polynomials, printers,
solvers, and matrices---are core components of SymPy and are discussed in
depth. Many other features are discussed in depth in the supplementary
material.

\subsection{Basic Usage}
\label{sec:basic-usage}
\input{basic_usage.tex}

\subsection{List of Features}

Although SymPy's extensive feature set cannot be covered in depth in this
paper, bedrock areas, that is, those areas that are used throughout the
library, are discussed in their own
subsections below. Additionally, Table~\ref{features-table} gives a compact listing
of all major capabilities present in the SymPy codebase. This grants a
sampling from the breadth of topics and application domains that SymPy
services. Unless stated otherwise, all features noted in
Table~\ref{features-table} are symbolic in nature. Numeric features are
discussed in Section~\ref{sec:numerics}.

\begin{longtable}[htbc]{>{\raggedright}p{0.30\linewidth}p{0.63\linewidth}}
\caption{SymPy Features and Descriptions.\label{features-table}}\\
\toprule
\textbf{Feature (submodules)} & \textbf{Description} \\
\midrule
Calculus (\texttt{sympy.core}, \texttt{sympy.calculus}, \texttt{sympy.integrals}, \texttt{sympy.series}) & Algorithms for computing derivatives, integrals, and limits.\\

Category Theory (\texttt{sympy.categories}) & Representation of objects, morphisms, and diagrams. Tools
for drawing diagrams with Xy-pic~\cite{rose1999xy}.\\

Code Generation (\texttt{sympy.printing}, \texttt{sympy.codegen}) & Generation of compilable and executable code in a
variety of different programming languages from expressions directly. Target
languages include C, Fortran, Julia, JavaScript,
Mathematica, MATLAB and Octave, Python, and Theano.\\

Combinatorics \& Group Theory (\texttt{sympy.combinatorics}) & Permutations, combinations,
partitions, subsets, various permutation groups (such as polyhedral, Rubik,
symmetric, and others), Gray codes~\cite{Nijenhuis1978combinatorial},
and Prufer sequences~\cite{biggs1976graph}.\\

Concrete Math (\texttt{sympy.concrete}) & Summation, products, tools for determining whether summation
and product expressions are convergent, absolutely convergent, hypergeometric,
and for determining other properties; computation of Gosper's normal form~\cite{Petkovsek1997AeqB} for two univariate polynomials.\\

Cryptography (\texttt{sympy.crypto}) & Block and stream ciphers, including shift, Affine,
substitution, Vigen\`{e}re's, Hill's, bifid, RSA, Kid RSA,
linear-feedback shift registers, and Elgamal encryption.\\

Differential Geometry (\texttt{sympy.diffgeom}) & Representations of manifolds, metrics, tensor
products, and coordinate systems in Riemannian and pseudo-Riemannian
geometries~\cite{sussman2013functional}.\\
% TODO: Someone verify that this is a good summary of the diffgeom module

Geometry (\texttt{sympy.geometry}) & Representations of 2D geometrical entities, such as lines and
circles. Enables queries on these entities, such as asking the area of an
ellipse, checking for collinearity of a set of
points, or finding the intersection between objects.\\

Lie Algebras (\texttt{sympy.liealgebras}) & Representations of Lie algebras and root systems.\\

Logic (\texttt{sympy.logic}) & Boolean expressions, equivalence testing, satisfiability, and normal
forms.\\

Matrices (\texttt{sympy.matrices}) & Tools for creating matrices of symbols and expressions.
Both sparse and dense representations, as well as symbolic linear
algebraic operations (e.g., inversion and factorization), are
supported.\\

Matrix Expressions (\texttt{sympy.matrices.expressions}) & Matrices with symbolic dimensions (unspecified entries).
Block matrices.\\

Number Theory (\texttt{sympy.ntheory}) & Prime number generation, primality testing, integer
factorization, continued fractions, Egyptian fractions, modular arithmetic,
quadratic residues, partitions, binomial and multinomial coefficients,
prime number tools, hexidecimal digits of $\pi$, and integer factorization. \\

Plotting (\texttt{sympy.plotting}) & Hooks for visualizing expressions via matplotlib~\cite{Hunter:2007}
or as text drawings when lacking a graphical back-end. 2D function plotting,
3D function
plotting, and 2D implicit function plotting are supported.\\

Polynomials (\texttt{sympy.polys}) & Polynomial algebras over various coefficient domains.
Functionality ranges from simple operations (e.g., polynomial division) to
advanced computations (e.g., Gr\"obner bases~\cite{Adams1994intro} and multivariate
factorization over algebraic number domains).\\

Printing (\texttt{sympy.printing}) & Functions for printing SymPy expressions in the terminal with ASCII
or Unicode characters and converting SymPy expressions to \LaTeX{} and
MathML.\\

Quantum Mechanics (\texttt{sympy.physics.quantum}) & Quantum states, bra--ket notation, operators, basis sets,
representations, tensor products, inner products, outer products, commutators,
anticommutators, and specific quantum system implementations.\\

Series (\texttt{sympy.series}) & Series expansion, sequences, and limits of sequences.
This includes Taylor, Laurent, and Puiseux series as well as special series, such
as Fourier and formal power series.\\

Sets (\texttt{sympy.sets}) & Representations of empty, finite, and infinite sets (including
special sets such as the natural, integer, and complex numbers). Operations
on sets such as union, intersection, Cartesian product, and building sets from
other sets are supported.\\

Simplification (\texttt{sympy.simplify}) & Functions for manipulating and simplifying expressions.
Includes algorithms for simplifying hypergeometric functions, trigonometric
expressions, rational functions, combinatorial functions, square root
denesting, and common subexpression elimination.\\

Solvers (\texttt{sympy.solvers}) & Functions for symbolically solving equations, systems
of equations, both linear and non-linear, inequalities, ordinary differential
equations, partial differential equations, Diophantine equations, and
recurrence relations.\\

Special Functions (\texttt{sympy.functions}) & Implementations of a number of well known special functions,
including Dirac delta, Gamma, Beta, Gauss error functions, Fresnel integrals,
Exponential integrals, Logarithmic integrals, Trigonometric integrals, Bessel,
Hankel, Airy, B-spline, Riemann Zeta, Dirichlet eta, polylogarithm, Lerch
transcendent, hypergeometric, elliptic integrals, Mathieu, Jacobi polynomials,
Gegenbauer polynomial, Chebyshev polynomial, Legendre polynomial, Hermite
polynomial, Laguerre polynomial, and
spherical harmonic functions.\\

Statistics (\texttt{sympy.stats}) & Support for a random variable type as well as the ability to
declare this variable from prebuilt distribution functions such as
Normal, Exponential, Coin, Die, and other custom distributions~\cite{rocklin2012symbolic}.\\

Tensors (\texttt{sympy.tensor}) & Symbolic manipulation of indexed objects.\\

Vectors (\texttt{sympy.vector}) & Basic operations on vectors and differential calculus with respect
to 3D Cartesian coordinate systems.\\
\bottomrule

\end{longtable}

%% Assumptions
\subsection{Assumptions}
\label{sec:assumptions}
\input{assumptions.tex}

\subsection{Simplification}

\input{simplification}

\subsection{Calculus}
\label{sec:calculus}
\input{calculus}

\subsection{Polynomials}
\input{polys}

\subsection{Printers}

\input{printers.tex}

% Solvers (regular equations, maybe also mention other types of solvers like ODEs/recurrence/Diophantine)
\subsection{Solvers}
\input{solvers.tex}

% Matrices (worth emphasizing that they are symbolic)
\subsection{Matrices}

\input{matrices}


% Copyright 2021 Google LLC
%
% Use of this source code is governed by an MIT-style
% license that can be found in the LICENSE file or at
% https://opensource.org/licenses/MIT.

%!BIB program = biber
%!TeX program = lualatex
%!TeX spellcheck = en-US

\documentclass[hctr2.tex]{subfiles}
\begin{document}
\section{Injectivity of H onto polynomials}\label{injective}
To demonstrate injectivity,
the following algorithm recovers \(T\) and \(M\) given
a binary string \(X\) of length \(\abs{X} = n (1 + \deg(H(T, M)))\)
representing the coefficients of
the polynomial \(H(T, M)\) in binary form,
starting with the greatest nonzero power; thus
\(13\hpoly^3\) would encode as \(1011 \Concat 0^{4n -4}\).
\begin{algorithmic}[1]
    \Procedure{GetTM}{$X$}
    \State \textbf{assert} \(\abs{X} \bmod n = 0\)
    \State \textbf{assert} \(\abs{X} \geq 2n\)
    \State \textbf{assert} \(X[\abs{X} - n; n] = 0^n\)
    \State \(t \gets \fromint^{-1}_{n-1}(X[1;n-1])\)
    \State \textbf{assert} \(t > 0\)
    \State \(t \gets t-1\)
    \State \(w \gets n(1 + \ceil{t/n})\)
    \If{\(X[0; 1] = 0\)}
        \State \textbf{assert} \(w + n \leq \abs{X}\)
        \State \(M \gets X[w;\abs{X}-w-n]\)
    \Else
        \State \textbf{assert} \(w + 2n \leq \abs{X}\)
        \State \textbf{assert} \(X[\abs{X}-2n+1; n-1] \neq 0^{n-1}\)
        \State \(i \gets \abs{X} - n - 1\)
        \While{\(X[i; 1] = 0\)}
            \State \(i \gets i - 1\)
        \EndWhile
        \State \(M \gets X[w;i - w]\)
    \EndIf
    \State \(T \gets X[n;t]\)
    \State \textbf{return} \(T, M\)
    \EndProcedure
\end{algorithmic}

\end{document}


\section{A simple multi-skill contact center}
\label{sec:SimpleMSK}

This section presents an example of a contact center with three
contact types, two
agent groups, and three two-hours periods.  Contacts arrive
following a non-homogeneous Poisson process
with randomized arrival rate
$B\lambda_{k, p}$ for contact type~$k$ during period~$p$.
As in the previous section,
$B$ is a gamma busyness factor with parameters
$(\alpha_0, \alpha_0)$.

When a contact arrives, an agent is selected from a group depending on
the contact type.  Contacts of type~0 can only be served by agents in
group~0 while contacts of type~2 can only be served by agents in
group~1.  Contacts of type~1 are served by agents in group~0, or
in group~1 if no agent is free in group~0.
For contacts arriving during period~$p$,
service times are i.i.d.\ exponential random variables with
mean~$1/\mu_p$.
Agents in groups are not differentiated, and the total number of
agents can change from periods to periods.

A contact that cannot be served immediately is added to a waiting
queue corresponding to its type.  After a patience time, if service
has not started, the contact abandons.  For contacts arriving during
period~$p$,
patience times are i.i.d.\ exponential variables with mean~$1/\nu_p$.

We are interested in the overall service level defined
by~(\ref{eq:slab}), and the occupancy ratio
of the first agent group defined by
\begin{equation}
o_i=\frac{E\left[\int_0^{t_P} \Nb[i](t)\
    dt\right]}{E\left[\int_0^{t_P} (N_i(t)+\Ng[i](t))
    dt\right]}\label{eq:occi}
\end{equation}
where $\Nb[i](t)$ corresponds to the number of busy agents in
group~$i$, $N_i(t)$ corresponds to the total number of agents in group~$i$,
and $\Ng[i](t)$ corresponds to the number of ghost agents in
group~$i$, at time~$t$.
We also estimate $\E[\Sg[k, p](s)]$ for $k=0,\ldots,K-1$ and
$p=0,\ldots,P-1$, the number of contacts meeting the service level
target.

\subsection{Implementing the model}

Listing~\ref{lst:SimpleMSK} presents the code implementing this
model.

\lstinputlisting[
caption={A simple multi-skill contact center},%
emph={main,simulateOneDay,MyContactFactory,MyContactMeasures},
label=lst:SimpleMSK
]
{SimpleMSK.java}

As with previous examples, a class representing the simulator is
defined.  The \texttt{main} method constructs the simulator, runs a
simulation, and prints some statistics.

Fields are declared for contact center's components, statistical
counters, etc.
For the number of served and
abandoned contacts, simple integers are sufficient,
but a matrix is needed to get the number of contacts meeting service
level target, for each contact type and main period.

As in previous examples, a constructor is responsible for creating all
arrival processes, agent groups, waiting queues, etc.
The period-change event has a preliminary period of length~0,
two-hours main periods, and a wrap-up period with
random length.
For each contact type, a factory and an arrival process are
constructed.  In contrast with the previous examples, the
factory requires the contact type identifier to be given as an
argument.  In this example,
all the arrival processes use the same period-change event to be
notified when a new period starts.  Some arrival processes could of
course use different period-change events.
Constructing the agent groups only
requires the period-change event for $N_i(t)$ to be automatically updated,
and an array containing the number of agents for each period.

Service and patience times are generated using
random variate generators adapted for multiple periods.  Such
generators use a
period-change event to determine the current period and select a
period-specific generator to get random values.  The generic way to
construct them is to create a random variate generator for each
period and give the resulting array of generators, with a
period-change event, to the
constructor of \texttt{Multi\-Period\-Gen}.  For some distributions,
including exponential,
helper methods such as \texttt{create\-Exponential}
are available to construct the generators more
conveniently.

Because each waiting queue and agent group is
functionally identical, it is the task of the router to decide which contacts to
send to which agents or
queues, and from which queues contacts must be removed.
For the router to be constructed, a type-to-group map and a
group-to-type map are needed.  The selected
\texttt{Single\-FIFO\-Queue\-Router} class affects how these
structures are used.  Here, because we model a multi-skill contact
center, the data structures for the routing policy become important
and can greatly affect the performance of the contact center.
The choice of the subclass of \texttt{Router} affects how
contacts interact with the center.

The \texttt{simulate\-One\-Day} method must initialize several arrays
of elements, including arrival processes, agent groups, and counters.
The same value of $B$ is used for every arrival process, because the
busyness is not specific to a contact type.
As in the previous example, the period-change event and the
arrival processes are started before the simulation starts.

One factory object has been constructed for each arrival
process, the only difference between these objects being the value of
their \texttt{type} field.  This
avoids the necessity of one factory class for each contact type,
which greatly improves scalability.
The factory constructs a contact of the
appropriate type and generates a service and a patience times.

When a contact of type~0 arrives, the router takes the element~0 of
the type-to-group map, which corresponds to an ordered list containing
the
agent group~0 only.  Let $\Nf[i](t)$ be the number of idle agents in
group~$i$ available to serve contacts.
If $\Nf[0](t)>0$, the contact is served
immediately.  Otherwise, it is added to waiting queue~0.  Contacts of
type~2 are treated similarly.  For contacts of type~1, the router
obtains an ordered list containing~0 and~1.  If $\Nf[0](t)>0$, the contact
is served immediately by an agent in group~0.  Otherwise, it overflows
to the next agent
group in the list:  if $\Nf[1](t)>0$, the contact is served by an
agent in group~1.
Otherwise, it is added at the end of the queue~1.

When an agent within group~0 becomes free or is added, the router uses
the group-to-type map to obtain the ordered list $\{1, 0\}$.  The
chosen
router selects the queued contact with the longest waiting time rather
than using the order induced by the list.  If the waiting queues
accessible for agents in group~0 contain no contact, the agent
remains free until new arrivals occur.  Similar routing
happens for agents in group~1.  This is equivalent to managing a
single FIFO queue by merging all
per-type waiting queues, sorting contacts by increasing arrival
times, and removing the first contact the free agent can serve.

If \texttt{Queue\-Priority\-Router} was used as in previous examples,
the algorithm for agent selection would be the same, but waiting
queues would be scanned sequentially rather than considered as a
single FIFO queue.  For example, if an agent in
group~0 became free, the queue priority router would check for
contacts in queue~0 only when queue~1 is empty.

Each contact exiting the system is notified to the registered
exited-contact listener.  The \texttt{blocked} method does nothing
because
the capacity of the contact center is infinite; no contact is
blocked.   When a contact leaves the queue without service, it is
counted as having abandoned.
If its waiting time is greater than or equal
to $s$, a contact having abandoned after the acceptable waiting time
is also counted.  When a
contact is served, a new service is counted.  If its waiting time is
small enough, it is also counted as a contact meeting service level
target.

For a contact to be counted in \texttt{numGoodSLKP}, the main
period of its arrival must be
determined.  Arrivals occur in periods~$1,\ldots,P$,
corresponding to main periods~$0,\ldots,P-1$.
If the main period index, i.e., the period index minus one, is
negative or greater than or equal to~$P$,
the arrival occurred during the preliminary or
wrap-up periods, and the event is ignored.  When the arrival occurs
during a main period, the appropriate element of the matrix is
incremented.

\lstinputlisting[caption={Results of the program \texttt{SimpleMSK}},%
label=res:SimpleMSK,language={},float=htb,breaklines,prebreak={\char92}
 ]{SimpleMSK.res}

After the simulation stops, the \texttt{stop} method of
\texttt{Period\-Change\-Event} is called,
computed observations are added to collectors.
To keep the program simple, we estimate the occupancy ratio from
times~0 to~$T$ rather than~$t_P$.  Getting the correct ratio would
require the creation of a custom period-change listener to get
$\int_0^{t_P}\Nb[0](t)\ dt$ and $\int_0^{t_P} (N_0(t)+\Ng[0](t)) dt$ at
time~$t_P$, i.e., at the beginning of wrap-up period.
This will be done in a further example, in sections~\ref{sec:occcor}
and~\ref{sec:Blend}.
Listing~\ref{res:SimpleMSK} displays the results of the program when
performing 1000 independent runs.

\subsection{Adding a contact-by-contact trace}

For debugging or advanced statistical processing using tools such as
SAS or R, it may be
needed to get a contact-by-contact trace of the simulation. This can be done
easily by using observers, as shown in
Listing~\ref{lst:SimpleMSKWithTrace}.
This example is a simplified version of the trace facility available
in the generic simulator of call centers supporting blend and
multi-skill systems.
It shows how it is possible to extract information from a contact
object, and other parts of the simulator.

\lstinputlisting[
caption={Contact-by-contact trace added to the simple multi-skill contact
  center example},%
emph={main,simulateOneDay,ContactTrace},
label=lst:SimpleMSKWithTrace
]
{SimpleMSKWithTrace.java}

This program behaves the same as the program in the preceding subsection,
but it creates a text file named \texttt{contactTrace.log} with one line
for each processed contact, whether it has abandoned or was served.
One can then open the resulting (large) trace file with any text
editor, or make a program to parse it.
Listing~\ref{res:SimpleMSKWithTrace} displays ten lines of the trace
produced by the program.  We cannot display the full trace, because
its size is 2MB, even though we have simulated only five days.

The trace contains the following fields:
\begin{description}
\item[Step] The index of the replication the contact arrived in.
\item[Type] The type of the contact.
\item[Period] The period the contact arrived in.
\item[ArvTime] The simulation time of the contact's arrival.
\item[QueueTime] The waiting time in queue of the contact.
\item[Outcome] The outcome of the contact, can be \texttt{Served} or \texttt{Abandoned}.
\item[Group] The group index of the agent who has served the contact, or
  $-1$ for abandoned contacts.
\item[SrvTime] The service time of the contact, or \texttt{NaN} for
  unserved contacts.
\end{description}

\lstinputlisting[caption={Sample trace produced by the program \texttt{SimpleMSKWithTrace}},%
label=res:SimpleMSKWithTrace,language={},float=htb
 ]{SimpleMSKTrace.res}

The program defines a class named \texttt{SimpleMSKWithTrace} which
extends \texttt{SimpleMSK} to inherit the simulation logic of the
example in the previous subsection, but it adds a new exited-contact
listener to the router for logging contacts.
This trace manager, which is initialized at the beginning of the
simulation, writes a trace entry to a file for any exiting contact.
It does not have any effect on how the contacts are managed by the
simulator.

The new subclass defines three fields: the trace manager, the output
trace file, and the current
replication number.
The first two fields are initialized by the constructor, which also
attach the trace manager to the router, defined in the superclass
\texttt{Simple\-MSK}.
This way, every contact processed by the router is broadcast to the contact
trace manager.
Moreover, one could disable the contact-by-contact trace simply by unregistering
the trace manager from the router.

The last field is updated after each replication by an overridden
\texttt{simulate\-One\-Day} method, and is used when formatting trace
entries.

The overridden \texttt{simulate} method opens the trace file at
the beginning of the simulation, calls the \texttt{simulate} method
from the superclass to
perform the simulation, and closes the trace at the end.
We put the call to \texttt{close} into a
\texttt{finally} block that will be called even if an unexpected
exception is thrown by the simulator.
This prevents any loss of information caused by an unflushed buffer.

The main part of the program is the
\texttt{Trace\-Manager} inner class which is an exited-contact listener
producing the data written into the trace.
A trace manager has an associated print writer used to format trace
entries into the output file.

Log lines are constructed by the \texttt{dequeued} and \texttt{served}
methods of \texttt{Trace\-Manager}, using the \texttt{format} method
of \texttt{Print\-Writer}.
Note how the arrival time, the service time, the waiting time, the
contact type, etc.\ can all be extracted from the \texttt{Contact}
object.
The \texttt{format} method fills a user-provided pattern
by using the values given by the remaining arguments.  The print stream
takes the system's current locale and the line separator into account.

Arrival times and time durations are formatted with a fixed
number \texttt{timePrecision} of decimal digits of precision, which is
set to 3 in this program.
This allows for a better visual formatting of the data in the plain
text file.
One could easily use another format, e.g., XML, or use JDBC to
write data into a database instead of a file.

\subsection{Rerouting queued contacts}

Agents may sometimes be allowed to serve some types of contacts only
after the contacts have waited for some time in queue.
For example, we can modify the model of this example to allow agents
in group~1 to serve contacts of type~1 only after these contacts have
waited more than 12s.
This can be done by customizing the router as in
Listing~\ref{lst:SimpleMSKWithRerouting} for \emph{contact rerouting},
i.e., the router can, after a delay elapses, reprocess a queued
contact for a new agent selection with different criteria.
Note that the router in ContactCenters also supports \emph{agent
  rerouting} which is not covered in this example but
works in a way similar to contact rerouting:
if an agent stays free after the end of a service for a certain delay,
the router can reprocess the agent to do a new contact selection, with
different criteria.
Of course, agent rerouting requires the agent groups to keep track of
individual agents.

\lstinputlisting[
caption={Contact rerouting added to the simple multi-skill contact
  center example},%
emph={main,MyRouter},
label=lst:SimpleMSKWithRerouting
]
{SimpleMSKWithRerouting.java}

The customized router, named \texttt{My\-Router}, extends the
\texttt{Single\-FIFO\-Queue\-Router} used by the original example.
As a result, the agent and contact selections are performed the same
way as in the original example, but we use a different type-to-group
map which allows incoming contacts of type~1 to be served by agents in
group~0 only.

Contact rerouting works as follows.
When a new contact is notified to the router, an agent is selected by
the \texttt{select\-Agent} methods which is given the new contact as
its argument. This method must construct and return an end-service
event representing the served contact, or \texttt{null} if the contact
cannot be served.
When the contact cannot be served, it is added into a waiting queue by
the \texttt{select\-Waiting\-Queue} method of the router.
If the contact can be queued, the router obtains its initial
\emph{rerouting delay}, i.e., the time after which the queued contact
is reprocessed if still in queue.
If this delay is negative, no rerouting happens, which is the default.
When a positive rerouting delay elapses for a queued contact, the
router passes this queued contact to a second \texttt{select\-Agent}
method which accepts the dequeue event along with the number of
reroutings done. For the first rerouting, this corresponds to 0.
This new method returns an end-service event or \texttt{null}, exactly
as the ordinary \texttt{select\-Agent} method.
Of course, the scheme for agent selection implemented by this method
should differ from the scheme implemented by the ordinary
\texttt{select\-Agent} method.
If the contact still cannot be served, it remains in queue, and a new
rerouting delay is required.
The process continues until a negative delay is obtained, the contact
is served, or abandons.

The initial rerouting delay is obtained
using \texttt{get\-Rerouting\-Delay} with
$-1$ as the number of preceding reroutings. By
default, this method always returns $-1$, which results in no rerouting.
In our case, we return \texttt{DELAY} if the number of reroutings done
is $-1$, or $-1$ otherwise.
The \texttt{select\-Agent} method for rerouting applies the overflow
routing of the
original example, which allows contacts of type~1 to be routed to
agents in group~1 when no agent is available in group~0.

We also need to override contact selection in order to prevent an
agent in group~1 to dequeue a contact of type~1 if its waiting time is
smaller than \texttt{DELAY}.  We therefore override the
\texttt{select\-Contact}
method of \texttt{Router}, which accepts an agent group containing the
free agents, and returns the dequeue event representing the
contact to serve.
Our method scans the waiting queues accessible to the free agent, and
records the waiting queue whose first contact has the smallest enqueue
time. However, if the free agent is in group~1, the method filters out
queue~1 if the first contact has a waiting time smaller than
\texttt{DELAY}.
After the queue is selected, the first contact is removed, and
returned.  The contact is removed with dequeue type
\texttt{DEQUEUETYPE\_BEGINSERVICE} which is used to represent the
beginning of the service for a queued contact.

Listing~ \ref{res:SimpleMSKWithRerouting} shows that the modified
program produces slightly different results: the number of contacts
having abandoned is higher and the service level is smaller than with
the original model.  The simulator behaves as we would expect:
some contacts of type~0 have to wait 12s longer in queue before they
can be served, and some of them abandon while they were served in the
original setting.

\lstinputlisting[caption={Results of \texttt{SimpleMSKWithRerouting}},%
label=res:SimpleMSKWithRerouting,language={},float=htb,breaklines,prebreak={\char92}
 ]{SimpleMSKWithRerouting.res}


\subsection{Bernstein inequalities}\label{subsec:bernstein_inequalities}

\begin{definition}\label{def:real_function_space_operators}
  Consider the \hyperref[def:function]{operator} \( T: C([a, b]) \to C([a, b]) \).

  \begin{thmenum}
    \thmitem{def:real_function_space_operators/positive} If \( f([a, b]) \subseteq [0, \infty) \) implies \( T(f)([a, b]) \subseteq [0, \infty) \), we say that \( T \) is \term{positive}.

    \thmitem{def:real_function_space_operators/monotone} If \( f(x) \leq g(x) \) for all \( x \in [a, b] \) implies \( T(f)(x) \leq T(g)(x) \) for all \( x \in [a, b] \), we say that \( T \) is \term{monotone}.
  \end{thmenum}
\end{definition}

\begin{definition}\label{def:periodic_function_space}\mcite[44]{Николов2020Лекции}
  We denote by \( \tilde{C}([a, b]) \) the subspace of \( C([a, b]) \) consisting of all continuous functions in \( [a, b] \) which are periodic with minimal period \( b - a \).
\end{definition}

\begin{definition}\label{def:approximation_error}\mcite[44]{Николов2020Лекции}
  We introduce two operators.

  \begin{thmenum}
    \thmitem{def:approximation_error/algebraic} The \term{algebraic approximation error}
    \begin{balign*}
      E_n: C([a, b]) \to [0, \infty] \\
      E_n(f) \coloneqq \inf_{p \in \pi_n} \norm{f - p}.
    \end{balign*}

    \thmitem{def:approximation_error/trigonometric} The \term{trigonometric approximation error}
    \begin{balign*}
      \tilde{E}_n: C([a, b]) \to [0, \infty] \\
      \tilde{E}_n(f) \coloneqq \inf_{p \in \tau_n} \norm{f - p}.
    \end{balign*}
  \end{thmenum}
\end{definition}

\begin{theorem}[Jackson's trigonometric theorem]\label{thm:jacksons_trigonometric_theorem}\mcite[47]{Николов2020Лекции}
  For \( f \in \tilde{C}[-\pi, \pi] \) we have
  \begin{equation*}
    \tilde{E}_n(f) \leq \frac {6^{k+1}} {n^k} \omega\left(f^{(k)}, \frac 1 n \right).
  \end{equation*}
\end{theorem}

\begin{theorem}[Szego’s inequality]\label{thm:szegos_trigonometric_inequality}\mcite[55]{Николов2020Лекции}
  For any nonnegative integer \( n \) and any \( s \in S_{\tau_n} \), we have
  \begin{equation}\label{eq:thm:szegos_trigonometric_inequality}
    [s'(\theta)]^2 + n^2 s^2 (\theta) \leq n^2 \quad\forall \theta \in [-\pi, \pi].
  \end{equation}
\end{theorem}
\begin{proof}
  Fix \( n = 1, 2, \ldots \) and \( \alpha \in [-1, 1] \).

  For brevity, denote \( c(\theta) \coloneqq \cos(n \theta) \). Let \( \theta_s \) and \( \theta_c \) be numbers in \( [-\pi, \pi] \) such that
  \begin{equation*}
    s(\theta_s) + c(\theta_c) = \alpha.
  \end{equation*}

  We will show that
  \begin{equation}\label{eq:thm:szegos_trigonometric_inequality/abs}
    \abs{s'(\theta_s)} \leq \abs{c'(\theta_c)}
  \end{equation}

  This will, in turn, imply that
  \begin{equation*}
    [s'(\theta_s)]^2
    \leq
    [c'(\theta_c)]^2
    =
    n^2 [\sin(n \theta_c)]^2
    \reloset {\ref{thm:trigonometric_identities/pythagorean_identity}}
    =
    n^2 [1 - \cos(n \theta_c)^2]
    =
    n^2 [1 - s(\theta_s)]
  \end{equation*}
  which is equivalent to \eqref{eq:thm:szegos_trigonometric_inequality}.

  Now we will prove \eqref{eq:thm:szegos_trigonometric_inequality/abs}. If \( \theta_c \) is a critical point of \( c \), i.e. if \( r'(\theta_c) = 0 \), then \( c'(\theta_c) = s'(\theta_s) \) and \eqref{eq:thm:szegos_trigonometric_inequality/abs} holds. Suppose that \( \theta_c \) is not a critical point. Denote by
  \begin{equation*}
    \theta_n \coloneqq \tfrac k n \pi, k = -n, -n+1, \ldots, n-2, n-1.
  \end{equation*}
  the extrema of \( c(\theta) \) in \( [-\pi, \pi) \).

  Define the auxiliary function
  \begin{equation*}
    r(\theta) \coloneqq c(\theta) - s(\theta - \theta_c + \theta_s).
  \end{equation*}

  We now have \( r(\theta_c) = c(\theta_c) - s(\theta_s) = 0 \).

  Furthermore, since \( \norm{s} = 1 \), then \( \abs{s(\theta)} \leq 1 \) for all \( \theta \in [-\pi, \pi) \). Therefore, \( r(\theta_k) \leq 0 \) for all odd \( k \) and \( r(\theta_k) \geq 0 \) for all even \( k \).

  If \( \theta_c \) coincides with any of the extrema \( \theta_k \), then \( r(\theta_c) \) holds trivially. Suppose that \( \theta_c \) is between \( \theta_{k-1} \) and \( \theta_k \). Without loss of generality, assume that \( k \) is even.

  By the intermediate value theorem, there exists a zero of \( r \) between \( r(\theta_c) \) and \( r(\theta_k) \). If \( r(\theta_c) < 0 \), then \( \theta_c \) is a local minimum and hence there exists a point \( \theta_{c'} \) between \( r(\theta_{k-1}) \) and \( \theta_c \) such that \( r(\theta_{c'}) = r(\theta_c) = 0 \). But this would imply that \( r \) has more than \( 2n \) different roots in the interval \( [-\pi, \pi) \), which is a contradiction.
\end{proof}

\begin{corollary}[Bernstein's trigonometric inequality]\label{thm:bernsteins_trigonometric_inequality}\mcite[53]{Николов2020Лекции}
  For any nonnegative integer \( n \) and any \( s \in \tau_n \) we have
  \begin{equation}\label{eq:thm:bernsteins_trigonometric_inequality}
    \abs{s'(\theta)} \leq n \norm{s} \quad\forall \theta \in [-\pi, \pi].
  \end{equation}
\end{corollary}
\begin{proof}
  The case \( n = 0 \) is trivial. If \( n > 0 \), for any \( s \in \tau_n \), we can apply \eqref{eq:thm:szegos_trigonometric_inequality} to \( \frac s {\norm s} \) to obtain
  \begin{equation}
    [s'(\theta)]^2 + n^2 s^2 (\theta) \leq \norm{s}^2 n^2 \quad\forall \theta \in [-\pi, \pi].
  \end{equation}

  \eqref{eq:thm:bernsteins_trigonometric_inequality} follows directly.
\end{proof}

\begin{theorem}[Bernstein's trigonometric theorem]\label{thm:bernsteins_trigonometric_theorem}\mcite[55]{Николов2020Лекции}
  Let \( f \in \tilde(C)[-\pi, \pi] \) and
  \begin{equation*}
    \tilde{E}_n(f) \leq \frac A {n^{k+\alpha}} \quad n = 0, 1, 2, \ldots,
  \end{equation*}
  where \( A \in \BbbR \) and \( \alpha \in (0, 1) \).

  Then \( f \in C^{(k)}[-\pi, \pi] \) and \( f^{(k)} \) is \( \alpha \)-H\"older.
\end{theorem}
\begin{proof}
  Since \( \tilde{E}_n(f) \) is bounded by \( \frac A {n^{k+\alpha}} \) on a compact interval, there exists a sequence \( \{ s_k \}_{k=0}^\infty \) such that
  \begin{equation*}
    \norm{f - s_n} \leq A {n^{k+\alpha}}.
  \end{equation*}

  Define the sequence of polynomials
  \begin{equation*}
    v_j \coloneqq \begin{cases}
      s_1,                  &j = 0, \\
      s_{2^j} - s_{2^{j-1}} &j > 0.
    \end{cases}
  \end{equation*}

  It is now clear that
  \begin{equation*}
    \norm{f - \sum_{j=0}^n v_j} \xrightarrow[]{j \to \infty} 0
  \end{equation*}
  because
  \begin{equation*}
    \abs{f(\theta) - \sum_{j=0}^n v_j (\theta)}
    =
    \abs{f(\theta) - s_{2^n}(\theta)}
    \leq
    A {n^{k+\alpha}}.
  \end{equation*}

  For each term of the series, we have
  \begin{equation*}
    \abs{v_j(\theta)}
    \leq
    \abs{f(\theta) - s_{2^j}(\theta)} + \abs{f(\theta) - s_{2^{j-1}}(\theta)}
    \leq
    \frac A {2^{j(k + \alpha)}} + \frac A {2^{(j - 1) (k + \alpha)}}.
  \end{equation*}

  By setting \( B \coloneqq A (2^{k + \alpha}) \), we obtain
  \begin{equation*}
    \abs{v_j(\theta)} \leq \frac B {2^{j(k + \alpha)}}.
  \end{equation*}

  By \fullref{thm:bernsteins_trigonometric_inequality},
  \begin{equation*}
    \norm{v_j^{(r)}} \leq 2^{jr} \norm{v_j} \leq \frac B {2^{j(k - r + \alpha)}}.
  \end{equation*}

  Then
  \begin{equation*}
    \sum_{j=0}^\infty v_j^{(r)} (\theta)
  \end{equation*}
  converges uniformly, therefore
  \begin{equation*}
    f^{(r)}(\theta) = \sum_{j=0}^\infty v_j^{(r)} (\theta).
  \end{equation*}
\end{proof}

\begin{theorem}[Bernstein's algebraic inequality]\label{thm:bernsteins_algebraic_inequality}\mcite[59]{Николов2020Лекции}
  For any nonnegative integer \( n \) and any \( p \in \pi_n \) and \( x \in (a, b) \) we have
  \begin{equation*}
    \abs{p'(x)} \leq n \frac 1 {(b - a)(b - x)} \norm{p}.
  \end{equation*}
\end{theorem}

\begin{theorem}[Bernstein's algebraic theorem]\label{thm:bernsteins_algebraic_theorem}\mcite[60]{Николов2020Лекции}
  Let \( f \in C[a, b] \) and
  \begin{equation*}
    E_n(f) \leq \frac A {n^{k+\alpha}} \quad n = 0, 1, 2, \ldots,
  \end{equation*}
  where \( A \in \BbbR \) and \( \alpha \in (0, 1) \).

  Then \( f \in C^{(k)}(a, b) \) and \( f^{(k)} \) is \( \alpha \)-H\"older in every \( [a_1, b_1] \) such that \( a_1 > a \) and \( b_1 < b \).
\end{theorem}


    \filetitle{datdiff}{Number of periods between two dates with check for date frequency}{dates/datdiff}

	\paragraph{Syntax}\label{syntax}

\begin{verbatim}
D = datdiff(D1,D2)
\end{verbatim}

\paragraph{Input arguments}\label{input-arguments}

\begin{itemize}
\itemsep1pt\parskip0pt\parsep0pt
\item
  \texttt{D1}, \texttt{D2} {[} numeric {]} - IRIS dates of vectors of
  IRIS dates.
\end{itemize}

\paragraph{Output arguments}\label{output-arguments}

\begin{itemize}
\itemsep1pt\parskip0pt\parsep0pt
\item
  \texttt{D} {[} numeric {]} - Number of periods between \texttt{D1} and
  \texttt{D2}, positive for \texttt{D1} greater than \texttt{D2},
  negative for \texttt{D1} smaller than \texttt{D2}, or NaN for dates of
  different frequencies.
\end{itemize}

\paragraph{Description}\label{description}

\paragraph{Example}\label{example}

\begin{verbatim}
d1 = mm(2010,12);
d2 = mm(2011,12);

datdiff(d1,d2)
ans =
   -12

datdiff(d2,d1)
ans =
    12

d3 = yy(2011);
datdiff(d1,d3)
ans =
   NaN
\end{verbatim}