\subsection*{#1}}
  {\end{marginfigure}}

\let\quote\quoting
\let\endquote\endquoting
\renewenvironment{quotation}
  {\ClassError{Please use the `quote` environment instead of `quotation`}}

\newcolumntype{L}{>{$}l<{$}}
\newcolumntype{C}{>{$}c<{$}}
\newcolumntype{R}{>{$}r<{$}}
\newcolumntype{T}{>{\ttfamily}l}
\newcolumntype{S}{>{\sffamily}l}

\newenvironment{block}
  {\begin{center}}
  {\end{center}}

\newmacro{newlogo}[2][]
  {\ifthenelse{\isempty{#1}}
     {\newlogoaux{#2}{\smallcaps{\lowercase{#2}}}}
     {\newlogoaux{#1}{#2}}}
\newmacro{newlogoaux}[2]
  {\newmacro{#1}{#2}}

\newmacro{newoperator}[1]
  {\newmathcommand[op]{#1}}
\newmacro{newkeyword}[2][]

  {\ifthenelse{\isempty{#1}}
    {\newoperator{#2}{\text{\normalfont\sffamily\bfseries #2}}}
    {\newoperator{#1}{\text{\normalfont\sffamily\bfseries #2}}}}
\newmacro{newvalue}[2][]
  {\ifthenelse{\isempty{#1}}
    {\newoperator{#2}{\text{\normalfont\sffamily #2}}}
    {\newoperator{#1}{\text{\normalfont\sffamily #2}}}}
\newmacro{newtype}[2][]
  {\ifthenelse{\isempty{#1}}
    {\newoperator{#2}{\text{\normalfont\sffamily\scshape #2}}}
    {\newoperator{#1}{\text{\normalfont\sffamily\scshape #2}}}}

\newmacro{obox}[2]
  {\makebox[0pt][l]{\ensuremath{#2}}\phantom{\ensuremath{#1}}}

\newmacro{highlight}[1]
  {\colorbox{lightgray}{\ensuremath{#1}}}

\newmacro{Quad}
  {\hspace{1.5em}}
\newmacro{Break}
  {\\[\smallskipamount]}

\newmacro{upon}
  {\genfrac{}{}{0pt}{0}}

\let\nothing\varnothing

\let\<\langle
\let\>\rangle

\newmathcommand[open]{llbrace}{\{\!|}
\newmathcommand[close]{rrbrace}{|\!\}}

\newmacro{set}[1]
  {\ensuremath{\{#1\}}}
\newmacro{tuple}[1]
  {\ensuremath{\<#1\>}}

\let\lt<
\let\gt>
\let\To\Rightarrow

\newmathcommand[bin]{pp}
  {+\!\!+}
\newmathcommand{Mid}
  {\;\mid\;}

\newmacro{powerset}[1]

  {\mathcal{P}(#1)}

\newmathcommand{n}{\underline{n}}

\newmathcommand[bb]  {NN}{N}
\newmathcommand[bb]  {ZZ}{Z}
\newmathcommand[bb]  {EE}{E}
\newmathcommand[bb]  {OO}{O}
\newmathcommand[bb]  {QQ}{A}
\newmathcommand[bb]  {RR}{R}
\newmathcommand[bb]  {CC}{C}
\newmathcommand[bb]  {HH}{H}

\newmathcommand[bb]  {LL}{L}
\newmathcommand[bb]  {UU}{U}
\newmathcommand[bb]  {BB}{B}
\renewmathcommand[bb]{SS}{S}

\let\to\rightarrow
\let\implies\supset
\let\infers\vdash

\newmacro{hint}[1]
  {\quad\text{\{ #1 \}}}

\newmathcommand[op]{when}
  {\mathbf{when}}
\newmathcommand[op]{where}
  {\mathbf{where}}
\renewmathcommand[op]{and}
  {\mathbf{and}}
\newmathcommand[op]{otherwise}
  {\mathbf{otherwise}}
\newmathcommand[op]{impossible}
  {\mathrm{impossible}}

\let\group\begingroup

\newenvironment*{marginequation}[1]
  {\begin{marginfigure}[#1]\equation}
  {\endequation\end{marginfigure}}

\newenvironment*{marginequation*}[1]
  {\begin{marginfigure}[#1]\equation\nonumber}
  {\endequation\end{marginfigure}}

\newenvironment*{function}
  {\begin{tabular}{@{}L@{\ \ }C@{\ \ }L@{}}}
  {\end{tabular}}
\newmacro{signature}[1]
  {\multicolumn{3}{@{}L@{}}{#1}}
\newmacro{inset}[1]
  {\multicolumn{3}{L}{\quad #1}}

\newenvironment*{grammar}

  {\begin{block}\begin{tabular}{@{}rRCLl}}
  {\end{tabular}\end{block}}
\newenvironment*{grammar*}

  {\begin{block}\begin{tabular}{@{}RLl}}
  {\end{tabular}\end{block}}

\newmacro{placerule}[4]
  {\ensuremath{
    \upon
      {\text{\smallcaps{#1}}\hfill}
      {\dfrac{#2}{#3}\ #4}
  }}

\newmacro{newrule}[4]
  {\newmacro{#1}{\placerule{#1}{#2}{#3}{#4}}}
\newmacro{userule}
  {\usemacro}
\newmacro{refrule}[1]
  {\ifthenelse{\isundefined{#1}}
    {\GenericError{}{Rule `#1` is not defined}{}{}}
    {\textsc{#1}}}

\section{Examples}
\label{sec:examples}

We present a few examples to demonstrate how our framework handles TopHat programs.
The candy vending machine combines the Select and View editor, the
Step Task, and the Pair Task to construct a candy machine (Section~\ref{sec:example-candymachine}).
The calorie calculator demonstrates a real-world
application of our framework (Section~\ref{sec:example-calorie-calculator}). The chat sessions demonstrates the use of shared data stores (Section~\ref{sec:example-chat}), and finally Section~\ref{sec:tax} describes UI generation for the tax example from Section~\ref{sec:top:formal}

\subsection{Candy vending machine}
\label{sec:example-candymachine}

The candy machine allows a user to choose a chocolate bar and, after the bill is
paid, the candy machine returns the bar. The candy machine combines the Edit,
Pair and Step task. We have defined different Edit tasks with View and Select
editors. The implementation of the initial task is given in Listing
\ref{sec:artefact:lst:candymachine}. The Pair combinator is denoted with the
operator \lstinline{><}.

\begin{enumerate}
    \item After the candy machine is started, the machine displays some
          introductory text and a selection of chocolate bars (see Figure
          \ref{fig:candymachine-step1}). This is done using a Pair Task that consists
          of two Edit tasks: an Edit task with a View editor and an Edit Task with a
          Select editor.

    \item Select a chocolate bar. After choosing a bar, the candy machine
          displays the price of the bar (see Figure \ref{fig:candymachine-step2}).
          This is done using another Pair Task that consists of an Edit task with a
          View editor (\textit{``you need to pay:''}) and a Step Task. The Step task consists of
          two tasks: first a view editor is shown (with the price) and after the step,
          a select editor is rendered (see Figure \ref{fig:candymachine-step3}).

    \item Press the continue button.

    \item Insert coins until you have paid the bill (see Figure \ref{fig:candymachine-step3}). The application alternates a view and a select editor.

    \item The application shows a view editor to indicate to the user that the
          bill is paid (see Figure \ref{fig:candymachine-step4}).
\end{enumerate}

    \begin{lstlisting}[caption={Initial Task of the candy vending machine (Haskell)},label={sec:artefact:lst:candymachine},language=Haskell]
data CandyMachineMood = Fair | Evil

startCandyMachine :: (Task h (Text, (Text, Text)))
startCandyMachine = view "We offer you three chocolate
    bars. Pure Chocolate: It's all in the name. IO
    Chocolate: Chocolate with unpredictable side effects.
    Sem Chocolate: don't try to understand, just eat
    it!" >< select candyOptions

candyOptions :: HashMap Label (Task h (Text, Text))
candyOptions =
  [ entry "Pure Chocolate" 8,
    entry "IO Chocolate" 7,
    entry "Sem Chocolate" 9
  ]
  where
    entry :: Text -> Int -> (Label, Task h (Text, Text))
    entry name price =
      (name, view "You need to pay:" >< (view price >>? payCandy))

payCandy :: Int -> Task h Text
payCandy bill =
    select (payCoin bill) >>? \billLeft ->
        case compare billLeft 0 of
        EQ -> dispenseCandy Fair
        LT -> dispenseCandy Evil
        GT -> payCandy billLeft

payCoin :: Int -> HashMap Label (Task h Int)
payCoin bill =
  [ coinSize 5,
    coinSize 2,
    coinSize 1
  ]
  where
    coinSize :: Int -> (Label, Task h Int)
    coinSize size = (display size, view (bill - size))

dispenseCandy :: CandyMachineMood -> Task h Text
dispenseCandy Fair =
    view "You have paid. Here is your candy. Enjoy it!"
dispenseCandy Evil =
    view "You have paid too much! Sorry, no change, but here is your candy."
\end{lstlisting}

\begin{figure}[t]
    \subfloat[Step 1: Select a chocolate bar]{
        \includegraphics[width=\linewidth]{pics/candymachine_step1-small.png}
        \label{fig:candymachine-step1}
    }

    \subfloat[Step 2: Price of the selected candy is shown to the user]{
        \includegraphics[width=\linewidth]{pics/candymachine_step2-small.png}
        \label{fig:candymachine-step2}
    }

    \subfloat[Step 3: Insert a coin]{
        \includegraphics[width=\linewidth]{pics/candymachine_step3-small.png}
        \label{fig:candymachine-step3}
    }

    \subfloat[Step 4: You have paid the bill]{
        \includegraphics[width=\linewidth]{pics/candymachine_step4-small.png}
        \label{fig:candymachine-step4}
    }
    \caption{Different stages of the candy vending machine}
\end{figure}

\subsection{Calorie calculator}
\label{sec:example-calorie-calculator}

To demonstrate a more real-world application that incorporates most task types,
we created a calorie calculator. This application calculates how many calories a
person should eat per day in order to maintain their weight. The calculation
depends on several factors, such as age, weight, and activity level. The
application can be broken down in several steps to prompt the user for input,
and finally calculating the result. The implementation of the task is
given in Listing \ref{sec:artefact:lst:calories}.

\begin{enumerate}
    \item When started, the application presents the user with some information
          about the calculation using a View editor.
    \item After pressing continue, the user is prompted to enter the required
          data in different steps: height, weight, and age using Enter editors,
          and gender and activity level using Select editors. Each prompt is
          wrapped in a Pair task with a View editor on the left side to act as
          the label. Such a prompt is shown in
          Figure~\ref{fig:calorie-calulator}.
    \item In the last step the result is displayed using a View editor.
\end{enumerate}

\begin{figure}
\begin{lstlisting}[caption={Task of the calorie calculator (Haskell)},label={sec:artefact:lst:calories},language=Haskell]
data Gender = Male | Female

data ActivityLevel = Sedentary | Low | Active | VeryActive

type Height = Int

type Weight = Int

type Age = Int

calculateCaloriesTask :: Task h Text
calculateCaloriesTask =
    introduction >>? \_ -> do
        (_, height) <- promptHeight
        (_, weight) <- promptWeight
        (_, age) <- promptAge
        (_, gender) <- promptGender
        (_, activityLevel) <- promptActivityLevel
        let calories = calculateCalories gender activityLevel height weight age
        view
        ( "Your resting metabolic rate is: "
            <> display calories
            <> " calories per day."
        )

introduction :: Task h Text
introduction = view <| unlines
    [ "This tool estimates your resting metabolic rate,",
      "i.e. the number of  calories you have to consume",
      "per day to maintain your weight.",
      "Press \"Continue\" to start"
    ]

promptGender :: Task h (Text, Gender)
promptGender =
    view "Select your gender:"
        >< select
            [ "Male" ~> Done Male,
              "Female" ~> Done Female
            ]

promptHeight :: Task h (Text, Height)
promptHeight = view "Enter your height in cm:" >< enter

promptWeight :: Task h (Text, Weight)
promptWeight = view "Enter your weight in kg:" >< enter

promptAge :: Task h (Text, Age)
promptAge = view "Enter your age:" >< enter

promptActivityLevel :: Task h (Text, ActivityLevel)
promptActivityLevel =
    view "What is your activity level?"
        >< select
            [ "Sedentary" ~> Done Sedentary,
              "Low active" ~> Done Low,
              "Active" ~> Done Active,
              "Very Active" ~> Done VeryActive
            ]

-- We omit the actual calculation here since it is a bit lengthy.
calculateCalories :: Gender -> ActivityLevel -> Height -> Weight -> Age -> Int
calculateCalories gender al h w age = ...
\end{lstlisting}
\end{figure}

\begin{figure}
  \begin{center}
    \includegraphics[width=.7\linewidth]{pics/calorie_calculator_height_step_smaller.png}
  \end{center}
    \caption{Prompting the user to enter their height}
    \label{fig:calorie-calulator}
\end{figure}
\subsection{Chat session}
\label{sec:example-chat}

This example uses shared data stores to model a chat session between two
users, as displayed in Figure~\ref{fig:tophat-chat-session}. Each user can write
messages to the chat history on the left hand side using their respective inputs
on the right hand side.

The implementation for this example is given in Listing~\ref{lst:chat-session}.
The function \lstinline{share} creates a data store that can be accessed by
multiple tasks, in this case the two \lstinline{chat} tasks. The \lstinline{<<=}
operator is used to transform the contents of the shared data store.
\begin{figure}
    \centering
    \includegraphics[width=\linewidth]{pics/tophat_ui_chatsession_smaller.png}
    \captionsetup{type=figure}
    \captionof{figure}{A chat session using shared data stores.}
    \label{fig:tophat-chat-session}
\end{figure}

\begin{minipage}{\linewidth}
\begin{lstlisting}[
    caption={A chat Session using shared data stores (Haskell)},
    label={lst:chat-session},
    language=Haskell]
chatSession :: Reflect h => Task h (Text, ((), ()))
chatSession = do
    history <- share ""
    watch history ><
        (chat "Tim" history >< chat "Nico" history)
    where
    chat :: Text -> Store h Text -> Task h ()
    chat name history = repeat <|
        enter >>* ["Send" ~> append history name]

    append :: Store h Text -> Text -> Text -> Task h ()
    append history name msg = do
        history <<= \h ->
        (if h == "" then h else h ++ "\n")
            ++ name ++ ": '"
            ++ msg ++ "'"
\end{lstlisting}
\end{minipage}

\subsection{Tax example}
\label{sec:tax}
For our final example, we revisit the tax program from Section~\ref{sec:top:formal}.

\begin{lstlisting}[caption={Tax example in Haskell},label={sec:tax:code},language=Haskell]
tax :: Task h ((((Amount, Bool), Bool), Date), Date)
tax =
  let today :: Date
      today = 100

      provideDocuments :: Task h (Amount, Date)
      provideDocuments = enter >< enter

      companyConfirm :: Task h Bool
      companyConfirm = enter

      officerApprove :: Date -> Date -> Bool -> Task h Bool
      officerApprove invoiceDate date confirmed =
        view (date - invoiceDate < 365 && confirmed)
   in (provideDocuments >< companyConfirm)
        >>? \((invoiceAmount, invoiceDate), confirmed) ->
          officerApprove invoiceDate today confirmed
            >>? \approved ->
              let subsidyAmount =
                   if approved
                      then min 600 (invoiceAmount `div` 10)
                      else 0
                      in view
             <| unlines
               [ "Subsidy amount: " ++ display subsidyAmount,
                 "Approved: " ++ display approved,
                 "Confirmed: " ++ display confirmed,
                 "Invoice date: " ++ display invoiceDate,
                 "Today: " ++ display today
               ]
\end{lstlisting}

Listing~\ref{sec:tax:code} gives the Haskell code that implements the task.
Compared to the original definition as given in Listing~\ref{lst:tax}, the task is nearly identical.
The only change made is to the final line, where we have opted for a different presentation of the final result, for simplicity's sake.

\begin{figure}[t]
    \subfloat[Step 1: The citizen enters the request info on the left, the installation company confirms on the right]{
        \includegraphics[width=\linewidth]{pics/tophat-ui-tax-2-step-2.png}
        \label{}
    }

    \subfloat[Step 2: The tax office confirms or denies the request]{
    \hspace{.5cm}
    \includegraphics[width=.30\linewidth]{pics/tophat-ui-tax-2-step-3.png}
        \label{}
    }\hspace{1cm}
    \subfloat[Step 3: The final outcome of the request is displayed]{
        \includegraphics[width=.30\linewidth]{pics/tophat-ui-tax-2-step-4-alt.png}
    }
    \caption{Different stages of the tax subsidy application}
    \label{fig:tax}
\end{figure}

Figure~\ref{fig:tax} lists the different stages of the UI for the tax subsidy task.
First, the user requesting the subsidy can enter in information (first two tasks), while the company can confirm or deny.
Then, the tax officer can verify if the conditions are met, and approve the request.
Finally, the outcome is shown.

Since we did not have to modify the task at all, besides a minor presentation detail, this task can still be proven correct using symbolic execution.
This example clearly illustrates the advantage of TopHat with a UI over the current state-of-the-art in the form of iTasks.

\section{TopHat UI Framework}
\label{sec:tophat-user-interface}

In this section we describe our prototype TOP UI framework, which is a
proof-of-concept and not a fully fledged TOP framework. Our application supports
TopHat tasks as mentioned in Section~\ref{sec:tophat}. We limit
ourselves to a select number of datatypes: only integers, booleans, and strings
are supported. Advanced framework features such as multi-user support are out of
scope as well.
We will reflect on this in Section~\ref{sec:conclusion}.
The framework is written in Haskell, and we use the following extensions.
\begin{description}
  \item [OverloadedLists] to allow for a more convenient HashMap notation.
  \item [OverloadedStrings] to allow for a more convenient way of using Text.
  \item [PackageImport and NoImplicitPrelude] to deal with the fact that TopHat defines its own Prelude.
\end{description}
All source code is published on GitHub\footnote{\url{https://github.com/mark-gerarts/ou-afstuderen-artefact}},
along with the examples described below.

Key to our approach is that we leave the task specification of TopHat untouched.
This preserves the nice formal properties for which TopHat has been developed in the first place.
The prototype UI framework completely relies on the TopHat semantics for handling input and rewriting tasks.
The responsibility of the UI framework is to render the task in a web browser, and hand off input that comes in from the user to the TopHat semantics.

\begin{figure}[t]
    \centering
    \includegraphics[width=\linewidth]{pics/architecture.png}
    \captionsetup{type=figure}
    \captionof{figure}{Architecture. Each box represents a main module.}
    \label{fig:architecture}
\end{figure}

The prototype framework is architecturally separated in two parts: the backend
and the frontend. Figure~\ref{fig:architecture} shows the main modules of each
part. The backend is responsible for initializing tasks and handling
communication with TopHat. The frontend renders tasks and allows the user to
interact with them. After a comparative study of existing web server and UI
frameworks~\cite{markmarc2021}, we have selected Servant~\cite{servant} as our webserver and
Halogen~\cite{purescripthalogen} for the UI. Other options are discussed in the
Section~\ref{sec:related-work}.
Section~\ref{sec:artefact:communication} illustrates the communication
between frontend and backend. Section~\ref{sec:artefact:backend} explains
the working of the backend and the frontend is discussed in Section~\ref{sec:artefact:frontend}.

\begin{figure}[t]
    \centering
    \includegraphics[width=0.75\linewidth]{pics/frontendBackendSSD.png}
    \captionsetup{type=figure}
    \captionof{figure}{Communication between frontend and backend. Sequence diagram that displays requests (solid arrows) and responses (dashed arrows). \texttt{update value} and \texttt{reset} are user actions. Task and Input are JSON objects.}
    \label{fig:frontendBackendSSD}
\end{figure}

\subsection{Communication between backend and frontend}
\label{sec:artefact:communication}

Figure \ref{fig:frontendBackendSSD} shows the communication between frontend and
backend. The frontend first requests the initial task, which the backend returns
using a JSON representation of this task. A user can now interact with the
system. In this example, the user updates a value. The frontend sends the input
as JSON to the backend, and the backend responds with the updated task. This
step can be repeated as necessary. In this case, the user resets the
application, which results in the backend resetting back to the initial task.

The frontend is written in PureScript and the backend in Haskell. We choose JSON
as data interchange format, because JSON allows custom data structures, it is
easy to use, and both backend and frontend support JSON out-of-the-box.

\subsection{Backend}
\label{sec:artefact:backend}

The backend is written in Haskell, using Servant~\cite{servant} as the web
server.
It has three main responsibilities, which is reflected in its module structure, shown in Figure~\ref{fig:architecture}:

\begin{enumerate}
    \item The Application module loads the application, defines the web
          server and configures the handlers.
    \item The Communication module handles JSON conversion, both encoding tasks
          to their JSON representation and decoding user input.
    \item The Visualize module is intended for the end user. It exposes
          functions to start the framework, which is demonstrated in
          Listing~\ref{sec:artefact:usage}.
\end{enumerate}

\begin{lstlisting}[caption={Starting the framework (Haskell)},label={sec:artefact:usage},language=Haskell]
import Task (Task, enter, view, (>>?))
import Visualize (visualizeTask)

main :: IO ()
main = visualizeTask greet

greet :: Task h String
greet = enter >>? \result -> view ("Hello " ++ result)
\end{lstlisting}

\paragraph{Application module}

We create an abstract web application (WAI-application) in the Application
module (see the \texttt{application} function in Listing
\ref{sec:artefact:lst:application}). We define the endpoints, the request and
the response formats. For example, see the \texttt{TaskAPI} in Listing
\ref{sec:artefact:lst:application}. The \texttt{server} function provides
handlers to serve the initial task, to handle interaction with the frontend and
to perform a reset. The remainder of the module consists of functions that
expose functionality of TopHat: initializing tasks, deconstructing tasks in a
representation that can be sent to the frontend, and interacting with tasks. We
have only added key signatures to Listing \ref{sec:artefact:lst:application}.

\begin{minipage}{\linewidth}
\begin{lstlisting}[caption={Application module (Haskell)},label={sec:artefact:lst:application},language=Haskell]
module Application (application, State (..)) where

data State h t = State
    { currentTask :: TVar (Task RealWorld t),
      initialised :: Bool,
      originalTask :: Task RealWorld t
    }

type TaskAPI =
    "initial-task" :> Get '[JSON] TaskDescription
    :<|> "interact"
        :> ReqBody '[JSON] JsonInput :> Post '[JSON] TaskDescription
    :<|> "reset" :> Get '[JSON] TaskDescription

type StaticAPI = Get '[HTML] RawHtml :<|> Raw
type API = TaskAPI :<|> StaticAPI

interactIO :: Input Concrete -> Task RealWorld a -> IO (Task RealWorld a)
initialiseIO :: Task RealWorld a -> IO (Task RealWorld a)
describeIO :: Task RealWorld a -> IO TaskDescription

server :: ToJSON t => State h t -> ServerT API (AppM h t)

application :: ToJSON t => State h t -> Application\end{lstlisting}
\end{minipage}

\paragraph{Communication module}

In Listing \ref{sec:artefact:lst:communication} we show the core of the
communication module. We introduce a new datatype, \texttt{TaskDescription},
that holds all data we need to render a task: the task itself
(\texttt{JsonTask}) and its possible inputs (\texttt{InputDescription}), along
with the \texttt{describe} function that extracts this data from a TopHat task.
User input, which is sent back and forth from the client to the server, is
defined in \texttt{JsonInput}.

\begin{lstlisting}[caption={Communication module (Haskell)},label={sec:artefact:lst:communication},language=Haskell]
module Communication (JsonTask (..), TaskDescription (..), describe) where

type JsonTask = Value

type InputDescriptions = List (Input Abstract)

data TaskDescription where
  TaskDescription :: JsonTask -> InputDescriptions -> TaskDescription

instance ToJSON JsonTask

describe :: Members '[Alloc h, Read h] r => Task h t -> Sem r TaskDescription

data JsonInput where
    JsonInput :: Input Concrete -> JsonInput

instance FromJSON JsonInput
\end{lstlisting}

\paragraph{Visualize module}

In Listing \ref{sec:artefact:lst:visualize} we show the signatures of the
visualize module. We use this module to run the web server in production
(\texttt{visualizeTask}) or development (\texttt{visualizeTaskDevel}) mode. We
differentiate between these modes because we implemented live code reloading for
development, which requires a bit of additional setup. Both
\texttt{visualizeTask} and \texttt{visualizeTaskDevel} use the \texttt{initApp}
function. \texttt{InitApp} on its turn invokes the application-function of the
Application Module.

\begin{minipage}{\linewidth}
\begin{lstlisting}[caption={Visualize module (Haskell)},label={sec:artefact:lst:visualize},language=Haskell]
module Visualize (visualizeTask, visualizeTaskDevel) where

initApp :: ToJSON t => Task RealWorld t -> IO Application

visualizeTaskDevel :: ToJSON t => Task RealWorld t -> IO ()

visualizeTask :: ToJSON t => Task RealWorld t -> IO ()\end{lstlisting}
\end{minipage}
\subsection{Frontend}\label{sec:artefact:frontend}

The frontend renders the UI and provides a way for the user to interact with it. The code is written in PureScript using the Halogen framework.
The frontend consists of three main modules and some auxiliary modules. We
explain the main modules:

\begin{enumerate}
    \item The Client module is the communication layer with the backend. It
          defines functions which send requests to the backend and handles the
          responses.
    \item The Task module handles JSON encoding and decoding of our domain's
          datatypes (tasks and user input).
    \item The TaskLoader module is the starting point of Halogen and is
          responsible for rendering the UI.
\end{enumerate}

\paragraph{Client module}

The client module is responsible for the communication between frontend and
backend. The backend sends a response in JSON that consists of two parts: a
\texttt{Task} and a description of possible inputs. We decode this JSON object
into a \texttt{TaskResponse}. See Listing \ref{sec:artefact:lst:client}.

\begin{lstlisting}[caption={Client module (PureScript)},label={sec:artefact:lst:client},language=Haskell]
module App.Client (ApiError, TaskResponse(..), getInitialTask, interact, reset) where

data TaskResponse
    = TaskResponse Task (Array InputDescription)

instance decodeJsonTaskResponse :: DecodeJson TaskResponse

getInitialTask :: Aff (Either ApiError TaskResponse)

interact :: Input -> Aff (Either ApiError TaskResponse)

reset :: Aff (Either ApiError TaskResponse)\end{lstlisting}

\paragraph{Task module}
In the Client module we defined a \texttt{TaskResponse}. This
\texttt{TaskResponse} consists of two parts: a \texttt{Task} and an array of
\texttt{InputDescription}. In the Task module we define the decoding process of
\texttt{Task} and \texttt{InputDescription}. See Listing~\ref{sec:artefact:lst:task}.

\begin{minipage}{\linewidth}
\begin{lstlisting}[caption={Task module (PureScript)},label={sec:artefact:lst:task},language=Haskell]
module App.Task where

data Task
    = Edit Name Editor
    | Select Name Task Labels
    | Pair Task Task
    | Choose Task Task
    | Step Task
    | Trans Task
    | Done
    | Fail

instance showTask :: Show Task

instance decodeJsonTask :: DecodeJson Task

data Input
    = Insert Int Value
    | Decide Int String

instance showInput :: Show Input

instance encodeInput :: EncodeJson Input

data InputDescription
    = InsertDescription Int String
    | OptionDescription Int String

instance showInputDescription :: Show InputDescription

instance decodeJsonInputDescription :: DecodeJson InputDescription
    \end{lstlisting}
\end{minipage}

\paragraph{TaskLoader module}

The TaskLoader module renders the user interface (the \texttt{render} function
in Listing \ref{sec:artefact:lst:taskloader}). The module also contains logic to
handle events (\texttt{handleAction}), for example when a user modifies a value.
Finally, the \texttt{taskLoader} function (see Listing
\ref{sec:artefact:lst:taskloader}) initializes the component.

\begin{lstlisting}[caption={TaskLoader module (PureScript)},label={sec:artefact:lst:taskloader},language=Haskell]
module Component.TaskLoader (taskLoader) where

taskLoader :: forall query input output m. MonadAff m => H.Component query input output m

handleAction :: forall output m. MonadAff m => Action -> H.HalogenM State Action Slots output m Unit

render :: forall m. MonadAff m => State -> HH.ComponentHTML Action Slots m
\end{lstlisting}

\section{Conclusion}
\label{sec:conclusion}

We have demonstrated TopHat UI, a proof-of-concept framework that implements a GUI for Tophat programs.
None of the advanced Clean features used by iTasks were required to do so, as expected.
On top of that, we were able to leave the TopHat language untouched, preserving its formal properties.

Our framework implements all basic requirements for a TOP framework, by supporting tasks, shared data stores, combinators and generics.
The source code for our framework is available online, and can thus be leveraged by developers and researchers to advance the field of Task-Oriented Programming.

\subsection{Future work}

As mentioned in Section~\ref{sec:tophat-user-interface}, TOP features such as multi-user support and richer datatypes are considered future work.
We see no technical or formal reason prohibiting them from being included in future versions of the UI framework.
As with iTasks, the rendering of values, and editors of values, is generic in the type of the value.
Adding support for more complex datatypes would just mean making instances for them for viewing and editing them, similar to how this is done in iTasks.
As for multi-user support, this is a limitation in the current version of TopHat.
Its developers are already working on adding multi-user support.
Once this feature is released, we see no fundamental limitations in supporting this in the UI.
The server framework used in the current implementation, Servant, already has extensive support for user authentication, which could be leveraged~\footnote{\url{https://docs.servant.dev/en/stable/tutorial/Authentication.html}}.

\section{Introduction}

Workflow software is present in most businesses and institutions
nowadays. From health care and first responders, to commerce and industrial
processes. Businesses use workflow software to streamline their processes,
increase efficiency and reduce costs. In these sectors, reliability of software
is crucial.

Previous research into workflow software in the functional
programming community aimed to improve reliability, while at the same time
reducing the effort of development. This led to the development of
Task-Oriented Programming (TOP), a programming paradigm that aims to facilitate
working with multiple people towards a shared goal over the internet. TOP
separates the \emph{what} from the \emph{how}. This separation allows
programmers to focus on the work that has to be done (\emph{what}) instead of
paying attention to design issues, implementation details, operating system
limitations, and environment requirements
(\emph{how})~\cite{achten2015top,plasmeijer2012taskoriented}.

\textit{iTasks}~\cite{achten2015top}, implemented in the functional programming language
Clean~\cite{clean}, is the main TOP framework and has been around for a long time.
iTasks has been used to create real-world applications, such as an incident
coordination tool for the Dutch coast guard~\cite{lijnse2012incidone}. While
this proves its practical usability, iTasks lacks in formalization.
The iTasks semantics are given by its implementation, making it much harder to formally reason about iTasks programs.
Previous attempts to mitigate this issue by some of iTasks' creators involved developing a separate iTasks semantics, which allowed them to perform model-based testing, but no formal verification~\cite{DBLP:conf/ifl/KoopmanPA08}.
Formal program verification is a very powerful tool to ensure the correctness of critical
software, like the incident coordination tool.
TopHat is a Domain-Specific Language (DSL) that paves the way to formally reason about task-oriented
programs~\cite{steenvoorden2019tophat}, by defining a formal TOP semantics.
These semantics have been implemented in Haskell and Idris~\footnote{\url{https://github.com/timjs/tophat-proofs}}.
Idris is a programming language that features dependent types and a totality checker, which is used to prove properties of TopHat programs.

\subsection*{Motivation}
In this paper, we develop an interactive UI for TopHat.
Before the development of TopHat, it was the case that iTasks, TOP and Clean were tied together very strongly.
Previous research even suggests that certain specific Clean features are essential to the implementation of TOP\cite{plasmeijer2012taskoriented}:
uniqueness typing, data generic programming, dynamics~\cite{DBLP:conf/ifl/VervoortP02} and a sophisticated backend using interpreted ABC bytecode on clients \cite{Oortgiese2017distributed}, to name a few.
We want to show that none of those features are essential in implementing a TOP framework with a GUI.
On top of that, we want to demonstrate that this can be achieved without making any changes to the TopHat language and its implementation in Haskell.

We expect this work to bring TOP to a bigger audience.
The current Clean user base is quite small.
Haskell is being used in production code, has a huge number of packages available online and an active community.
Task-oriented programming could benefit from being ported to Haskell, making it available to a large community of both developers and researchers.
Developing an interactive UI for TopHat brings this one step closer.

Motivated by the above, this paper presents a prototype framework written on top of TopHat's
Haskell implementation that is able to create interactive graphical user interfaces of
TopHat programs.

\subsection*{Structure}

The remainder of this paper is structured as follows: we first provide some
background about TOP, including iTasks and TopHat in Section~\ref{sec:top}.
Section~\ref{sec:tophat-user-interface} introduces our TopHat UI prototype.
Section~\ref{sec:examples} demonstrates the capabilities of our framework, including formal reasoning, using several example TopHat programs.
We highlight related work in Section~\ref{sec:related-work}.
Section~\ref{sec:discussion} reflects on the goals and research questions outlined above.
Section~\ref{sec:conclusion} concludes.

\section{Task-Oriented Programming}
\label{sec:top}

This paper builds upon previous TOP research~\cite{plasmeijer2012taskoriented,achten2015top,steenvoorden2019tophat}.
In this section we describe the basic idea of TOP and two TOP
implementations: iTasks and TopHat.

\subsection{Task-Oriented Programming}

TOP is centered around the concept of \textit{tasks}, which specify the work a
user or system has to perform with a high level of abstraction.
The smallest possible task represents the smallest amount of
work a user or system can perform~\cite{plasmeijer2012taskoriented}.

Combining small tasks allows creating large and complex applications
using simple building blocks. Tasks can be combined using combinators:
they can be executed sequentially, in parallel, or conditionally.
These combinators closely resemble how collaboration happens in real life.

TOP aims to facilitate collaborating with multiple people towards a shared goal, over the internet.
Creating complex applications is further facilitated because
tasks are first-class citizens: they can be used as input of functions, they can
be returned from them, and tasks can contain other tasks as value.

Tasks are interactive and input-driven. When a task receives input it is
reevaluated and results in a new task. A task's value can be observed at all
times. Tasks can share information with each other, either directly through
shared data stores, or by passing task values to continuations.

TOP itself focuses on the domain logic, with tasks providing merely a description of
the work that has to be performed. It is left up to a TOP framework to do the
heavy lifting, such as generating the user interface, storing and handling data,
setting up a web server, and authenticating users.
\textit{iTasks}~\cite{achten2015top} is such a
framework, implemented in the functional programming language
Clean~\cite{clean}. An example of a basic task in iTasks is presented in
Listing~\ref{lst:task-itasks}. Developers only have to specify that they
want the user to enter some information. Passing this task description to iTasks generates
an application that prompts the user for their name.

\begin{lstlisting}[language=Haskell,caption={A simple task prompting the user for their name (Clean)},label={lst:task-itasks}]
enterName :: Task String
enterName = Hint "What is your name?" @>> enterInformation []\end{lstlisting}

The TOP paradigm provides an abstraction over workflow software. Instead of
having to write a server, database, user interfaces, etc, programmers just
define what needs to be done. The complete application is then derived from this
specification by the TOP framework. TOP is usually embedded in pure functional programming.

To summarize, TOP is made up of the following three core concepts:

\begin{description}
      \item[Tasks] that describe the work that has to be performed, providing
            an abstraction that separates the \textit{what} from the
            \textit{how}~\cite{achten2015top}.
      \item[Composition] of tasks through combinators, allowing the
            creation of arbitrarily large tasks.
      \item[Data] that is being passed between tasks sequentially and globally.
\end{description}

\subsection{iTasks}
\label{sec:context:itasks}

iTasks~\cite{plasmeijer2007itasks} is a TOP framework that uses
Clean~\cite{brus1987clean} as its host language. It supplements Clean with a set
of combinators, model types, and algorithms that allow the construction of
task-oriented programs.

An example of a basic task was given in Listing~\ref{lst:task-itasks}. iTasks
will automatically generate an entire application for this task. It uses
generics to deduce that a task of type \texttt{String} requires a text input
field. In Listing~\ref{lst:itasks-greet} we
combine the task with a view task using a sequential step combinator. A
user has to enter their name and is greeted by the program after stepping to
the next task. Figure~\ref{fig:itasks-greet} shows how these steps would look in
iTasks.

\begin{lstlisting}[language=Haskell,caption={Combining two tasks with a step combinator (Clean)},label={lst:itasks-greet}]
greet :: Task String
greet = enterName >>!
          \result -> viewInformation [] ("Hello " +++ result)\end{lstlisting}

\begin{figure}[t]
      \centering
      \includegraphics[width=0.47\linewidth]{pics/itask_greeting_1_frame.png}
      \includegraphics[width=0.47\linewidth]{pics/itask_greeting_2_frame.png}
      \captionsetup{type=figure}
      \captionof{figure}{Entering your name (left) and the result after pressing continue (right)}
      \label{fig:itasks-greet}
\end{figure}

iTasks is a work in progress, receiving constant updates and improvements. For
example, a recent addition is the usage of a distributed, dynamic
infrastructure~\cite{Oortgiese2017distributed}. iTasks has formed the basis of
further research as well. Tonic~\cite{stutterheim2014tonic} facilitates the
subject for non-technical people by providing graphical blueprints of iTasks
specifications. It also provides a way to monitor the process while end users
are interacting with the application~\cite{stutterheim2019static}. iTasks acted
as the starting point for research into declarative user interfaces, first for
SVG images~\cite{achten2014itasks} and later as a generalized
solution~\cite{achten2016layout}.

\subsection{TopHat}
\label{sec:tophat}

When software is used in critical applications, it is important that its
behavior can be verified and formally reasoned about. iTasks is primarily
focused on practical applicability, and therefore lacks this formalization.
Testing an iTasks application is time consuming and often incomplete because of
the many different execution paths.

TopHat~\cite{steenvoorden2019tophat} distills TOP's core features
to provide a way to reason about task-oriented programs. By employing
symbolic execution it is possible to formally verify TopHat
programs~\cite{naus2019symbolic}. Symbolic execution has also been used to
provide end-users of tasks with additional feedback~\cite{naus2020generating}.

Our work is based on TopHat's Haskell implementation.
Listing~\ref{lst:tophat-greet} gives the TopHat implementation of the example introduced in Section~\ref{sec:context:itasks}.
Similar to the iTasks code, this task uses a step combinator to ask a user their name and subsequently greet them.

\begin{lstlisting}[language=Haskell,caption={A TopHat task that greets the user (Haskell)},label={lst:tophat-greet}]
greet :: Task h String
greet = enter >>? \result -> view ("Hello " ++ result)\end{lstlisting}

TopHat contains the following set of tasks and combinators:

\begin{description}
      \item[Editors] model user interaction.
            They are typed containers
            that are either empty or hold a value.
            TopHat contains different kinds of editors:
            \begin{description}
                  \item[Update] contains a predefined value.
                  \item[View] is an editor with a view-only value.
                  \item[Enter] is an editor that is initially empty. Filling it transforms it into an Update editor.
                  \item[Watch] displays the value of a shared data store.
                  \item[Change] is an editor that allows to change the value of a shared data store.
            \end{description}
      \item[Done and Fail] are success and failure end tasks.
      \item[Pair] combines two tasks (parallel-and).
      \item[Choose] makes a choice between two tasks (parallel-or).
      \item[Step] sequentially moves from one task to another.
      \item[Share] creates a shared data store.
      \item[Assign] assigns a value to a reference in a shared data store.
\end{description}

\subsection{Formal reasoning}
\label{sec:top:formal}

iTasks defines tasks as a ``state transforming function that reacts to an event, rewrites itself to a reduct and accumulates responses to users''~\cite{plasmeijer2012taskoriented}.
For combinators, iTasks takes the swiss-army-knife-approach.
It defines two combinators that perform a multitude of actions.
From these combinators, more simple ones can be constructed.
For example, the \texttt{>>*} combinator performs sequential composition, allows the user to choose from a list of tasks, allows automatic progressing tasks, guarded tasks, and stepping on exception.
Its definition in the latest version of iTasks is about 100 lines of Clean code, relying on many custom functions~\footnote{\url{https://gitlab.com/clean-and-itasks/itasks-sdk/-/blob/master/Libraries/iTasks/WF/Combinators/Core.icl}}.
While iTasks is certainly an impressive engineering accomplishment, it is unfit for formal reasoning.

TopHat on the other hand defines tasks as a simple datatype, with three base cases and a small number of simple combinators~\cite{steenvoorden2019tophat}.
The TopHat framework takes care of handling events, rewriting and task rendering.
The formal TopHat semantics fits on a single page, and is largely straightforward.

To demonstrate the formal reasoning capabilities of TopHat, a symbolic execution semantics has been developed~\cite{naus2019symbolic}.
For space reasons, we will refrain from repeating syntax and semantics here, but will revisit an example, to use thoughout this paper.

\lstset{emph={invoiceDate,date,confirmed,invoiceAmount,approved}}
\begin{TASK}[float=ht
            ,numbers=right
            ,caption=Subsidy request and approval workflow at the Dutch tax office.
            ,label=lst:tax
            ]
  let today = $\text{25 Sept 2020}$ in
  let provideDocuments = enter Amount <&> enter Date in
  let companyConfirm = edit True <?> edit False in
  let officerApprove = \ invoiceDate. \ date. \ confirmed.
    edit False <?> if (date - invoiceDate < 365 /\ confirmed) |\label{lst:tax:officer-approve-def}|
      then edit True
      else fail in
  provideDocuments <&> companyConfirm >>= |\label{lst:tax:documents-and-company-confirm}|
    \ <<<<invoiceAmount, invoiceDate>>, confirmed>>.
  officerApprove invoiceDate today confirmed >>= \ approved.|\label{lst:tax:officer-approve}|
  let subsidyAmount = if approved
    then min 600 (invoiceAmount / 10) else 0 in
  edit <<subsidyAmount, approved, confirmed, invoiceDate, today>>|\label{lst:tax:result}|
\end{TASK}

Listing~\ref{lst:tax} provides the code for a small example task, implementing the process of applying for a tax subsidy.
This example was inspired by a collaboration with the Dutch Tax office.
The user gets asked to provide documents to back up their tax subsidy request for solar panel installation (line 2).
The installation company has to confirm that they installed the panels (line 3), which can be done in parallel (line 8).
Finally, a tax officer can either approve or deny the request (line 4), depending on certain conditions (line 5).
After the task has been completed, the subsidy amount is being calculated (line 12), and the details are returned in a view (line 13).

For this task, symbolic execution allowed the authors to prove correctness properties over the code, such as functional correctness.
In Section~\ref{sec:tax} we will take a look at generating a UI using the framework presented in the coming section.

\section{Related work}
\label{sec:related-work}

Section~\ref{sec:top} presentend related work on TOP and iTasks.
In this section, we will briefly discuss Functional reactive programming as an alternative to TOP, as well as alternatives for the UI framework and web server we have used during the development of the UI for TopHat.

\subsection{Functional Reactive Programming}

Functional Reactive programming (FRP) is another approach to UI development
using functional programming. FRP is a programming paradigm centered around
interactive event-based applications. It has implementations in multiple
programming languages, such as Haskell and
JavaScript~\cite{Bainomugisha2013reactive}.

FRP consists of two main concepts: \textit{behaviors} and \textit{events}. A
behavior consists of a value and can be mapped to output, for example a label.
Behaviors can depend on other behaviors, so a change in a behavior can propagate
through a network of dependent behaviors. An event only occurs at a certain
point in time and contains a value. Input is mapped to events, for example the
pressing of a key or the position of the mouse cursor. Events can trigger
changes in behaviors.

It is worth noting that, while they share some similarities, FRP and TOP are
conceptually different. FRP is a paradigm for reactive programming, whereas TOP
is a way to model collaboration between users.

\subsection{User Interface frameworks}

We build upon the Halogen framework to create our prototype, but many other UI
frameworks exist in the domain of functional programming.
We discuss three of these briefly below.

Elm~\cite{czaplicki2012elm} refers to both Elm, a functional programming
language that compiles to JavasScript~\cite{elmlang}, and
TEA~\cite{elmarchitecture}, a programming pattern that emerged from it.
Elm's ecosystem consists of a large number of available libraries that help in
creating web applications.

Miso~\cite{haskellmiso} is a Haskell front-end framework inspired by Elm and
Redux. It relies on GHCJS~\cite{ghcjs}, a Haskell-to-JavaScript compiler based
on GHC.

Reflex~\cite{reflexfrp} is an FRP framework written in Haskell with support for
a variety of platforms, including the web, desktop, and mobile. Reflex
applications are modular, which makes growing and refactoring an application
efficient and swift.

We have selected PureScript and Halogen because it is a powerful functional programming language
that fits our problem domain. Halogen provides an excellent developer
experience, has a component based architecture and builds upon PureScript's
power and expressiveness.

\subsection{Web servers}

We have opted for Servant as our web server.
Servant provides combinators to implement our features, which makes
coding less error prone and time-consuming. Servant is up-to-date,
well-maintained, well documented and it is easy to get a working prototype.
Below we discuss Yesod and Warp as possible alternatives for the server used in our implementation.

The Yesod Web Framework~\cite{snoyman} is a Haskell web framework that allows for rapid development of type-safe, RESTful and high performance web applications~\cite{yesod}.
The Yesod Web Framework adds the strengths of Haskell (like type safety) to the web.
Especially on the boundaries of Yesod and the world, for example a user enters input or persistent data is loaded, Yesod adds mechanisms to define the expected types~\cite{yesodBook}. We found that developing a prototype based on Yesod is more difficult than developing a prototype based Servant. We also found that the Yesod Web Framework is too extensive for our purposes~\cite{markmarc2021}.

The Warp web server is a light-weight web server that supports the Web Application Interface (WAI)~\cite{snoyman2011warp}.
It is meant to be easy to use and provide easy composition of web services.
Because of the design choices to achieve this, the code of a Warp prototype is low-level.
This means that implementing all features in this way will be error prone and time-consuming.
Therefore, we have chosen Servant. However, Servant also uses Warp as its web server~\cite{markmarc2021}.


\section{Introduction}

It is natural to expect that some states of a quantum system are more ``quantum'' than the others. To transform this intuitive thought into a qualitative concept, we use the conventional statistical interpretation of quantum mechanics. The quasiprobability distribution functions will be regarded as a source of information about the classicality/quantumness of a state.  Our consideration is based on the ideas borrowed from the geometric probability theory \cite{KlainRota1997} and a commonly accepted opinion that if quasiprobability functions attain negative values, then it is a certain sign of quantum nature (see \cite{Wigner1932}-\cite{Feynman1987} and \cite{FerrieMorrisEmerson2010} with references therein). This observation allows one to specify the notion of ``classical states à la Wigner'' as the states whose Wigner function is positive semidefinite everywhere in the phase space. Based on this definition, several measures of classicality/quantumness have been constructed  \cite{Hillery1987}-\cite{AKA2021}. When dealing with an ensemble of random states, the probability to find a ``classical state'' among the members of an ensemble is an example of these kind of measures \cite{AKhT2020}-\cite{AKR2021}.

In the present article, after the introduction of classicality indicator $\mathcal{Q}$ as the geometric probability, we will compute it for a 3-level quantum system, a qutrit. We will compare the characteristics of classicality of qutrits from three random ensembles: the Hilbert-Schmidt and two other ensembles, associated  with the monotone Riemannian metrics \--- the Bures and the Bogoliubov-Kubo-Mori metrics (cf. \cite{MorozovaChensov1990}-\cite{HiaiKosakiPetzRuskai2013}). To make the presentation self-consistent, in the next sections necessary notions and definitions related to these random ensembles and the Wigner function of a finite-dimensional quantum system will prelude calculations of the corresponding probabilities. Calculating the probabilities for different varieties of states, we analyze the dependence of the classicality measure on the moduli parameter of a qutrit Wigner function.

\section{Unitary invariant ensembles of qudits}

\label{sec:Random}

Let us consider a qudit \--- a quantum system associated with an $N\--$dimensional Hilbert space. The quantum state space $\mathfrak{P}_N$ of an $N\--$level qudit is defined as:
\begin{equation}
\label{eq:StateSpace}
\mathfrak{P}_N =\{\, \varrho \in M_N(\mathbb{C}) \ |\ \varrho=\varrho^\dagger\,,\quad  \varrho \geq 0\,,  \quad \mbox{tr}\left( \varrho \right) = 1  \, \}\,.
\end{equation}
The unitary $U(N)$ automorphism of the Hilbert space of an $N\--$level quantum system induces the adjoint $SU(N)$ transformations of density matrices $\varrho \in \mathfrak{P}_N$\,:
\begin{equation}
\label{eq:UP}
    g\cdot \varrho = g \varrho g^\dagger\,, \qquad  g\in SU(N)\,.
\end{equation}
For a closed system it is assumed that the probability density function of the corresponding  ensemble of $N\--$ dimensional qudits is invariant under (\ref{eq:UP}):
\begin{equation}
\label{eq:InvPDF}
    P(\varrho)= P(g\varrho g^\dagger)\,, \qquad  \forall\ g \in SU(N)\,.
\end{equation}
Further in the report three ensembles of random states respecting this unitary symmetry will be used for evaluation of the measure of classicality. Namely, we will consider the unitary invariant ensembles associated with the following Riemannian metrics on state space:
\begin{itemize}
\item[\--] the Hilbert-Schmidt metric $\mathrm{g_{{}_\mathrm{HS}}}$\,;
\item[\--] the Bures metric $\mathrm{g_{{}_\mathrm{B}}}$\,;
\item[\--] the Bogoliubov-Kubo-Mori metric $\mathrm{g_{{}_\mathrm{BKM}}}$\,.
\end{itemize}
Before dealing with a specific ensemble, it is worth drawing attention to a common property of each of these ensembles emerging due to $SU(N)$ invariance (\ref{eq:InvPDF}).

\paragraph{Stratification and factorization of probability distribution on $\mathfrak{P}_N$\,.}
The invariance property (\ref{eq:InvPDF}) leads to a certain factorization of the probability distribution functions $ P(\varrho)$ into two factors, one depending on $SU(N)\--$invariants solely, and the other being a universal function of the ``angular variables''.
Moreover, the structure  of this factorization is universal for all  states whose unitary orbits are  characterised by the same isotropy group, $H_\alpha \subset SU(N)$\,,  i.e., belong to a class with the same ``orbit type''
\footnote{
Subgroup $H_x \subset SU(N)$ is the \textit{isotropy group (stabilizer)} of point $x\in \mathfrak{P}_N$ and is defined as
\[
H_x =\{\, g\in SU(N)\ | \ g\cdot x =x\, \}\,.
\]
If the conjugacy class of $H$ is denoted  by $[H]$\,, then we say that \textit{the type of the orbit is $[H]$}, if the stabilizer $H_x$ of some/any point $x$ in the orbit belongs to $[H]\,.$
}\,.
Isotropy groups $H_\varrho$ of any point $\varrho  \in \mathfrak{P}_N$ are determined by the algebraic degeneracy of the spectrum of $\varrho$ and are in one-to-one correspondence with the Young diagrams of all possible decompositions of $N$ into non-negative integers. Hence,  we associate the given partition of $N$ with the \textit{stratum}   $\mathfrak{P}_{[H_\alpha]}\,,$ defined as the set of all points of $\mathfrak{P}_N\,,$ whose stabilizer is conjugate to subgroup $H_\alpha$\,:
\begin{equation}
   \mathfrak{P}_{[H_\alpha]}: =\big\{\, x \in \ \mathfrak{P}_N|\   H_x \mbox{~is~conjugate~to}\  H_\alpha \, \big\} \,,
\end{equation}
where  $ \ \alpha = 1, 2, \dots, p(N)$\,. \footnote{The partition function $p(N)$  gives a number of possible partitions of a non-negative integer  ${N}$ into natural numbers.
}
The union of $\mathfrak{P}_{[H_\alpha]}$ results in the state space $\mathfrak{P}_{N}$\,:
\begin{equation}
\label{eq:OrbitDec}
\mathfrak{P}_N=\bigcup_{\mbox{orbit types}}{\mathfrak{P}}_{[H_\alpha]}\,,
\end{equation}
with each component of the decomposition
(\ref{eq:OrbitDec}) consisting  of density matrices with a fixed  algebraic degeneracy,
\begin{equation}
\label{eq:stratumDeg}
\mathfrak{P}_{[H_\alpha]}=
 \bigcup_{\omega \in S_s }{\mathfrak{P}_{k_{\omega(1)},
 k_{\omega(2)},
 \dots, k_{\omega(s)}}}\,.  \end{equation}
In (\ref{eq:stratumDeg}) $S_s$ is a symmetric group acting on a given partition of $N$ into $s$ natural numbers  $k_1, k_2, \dots, k_s\,.$ Algebraically, $\mathfrak{P}_{k_1, k_2, \dots, k_s}$ being a set of states with a fixed degeneracy is defined via the characteristic polynomial of a density matrix:
\footnote{Note that in (\ref{eq:DegSet}) the condition of summing up the degrees of degeneracy to $N$ means that only the maximal rank states are considered.}
\begin{equation}
\label{eq:DegSet}
 \mathfrak{P}_{k_1, k_2, \dots, k_s} = \{\, \varrho\in\mathfrak{P}_N\,, k_i \in \mathbb{Z}_+\, |\,
\det(\varrho-\lambda)=\prod_{i=1}^s (r_i-\lambda)^{k_i}\,, \quad   \sum_{i=1}^s k_i= N \, \}\,.
\end{equation}
Geometrically, the set $\mathfrak{P}_{k_1, k_2, \dots, k_s}$ with $k_1=k_2=\cdots=k_N=1$ represents the interior of an $(N-1)\--$dimensional simplex $C_{N-1}$ of eigenvalues:
\begin{equation}
\label{eq:NorderedSim}
 C_{N-1} := \{\, \boldsymbol{r} \in \mathbb{R}^N \, \biggl| \,
\sum_{i=1}^{N} r_i = 1\,, \quad 1\geq r_1\geq r_2 \geq \dots \geq r_{N-1}\geq r_N \geq 0 \, \}\,,
\end{equation}
while for all other admissible tuples $\boldsymbol{k}=(k_1, k_2, \dots, k_s )$ each $\mathfrak{P}_{k_1, k_2, \dots, k_s}$ represents the union of the faces and edges of the $(N-1)\--$simplex parameterized by the barycentric coordinates of the following kind:
\begin{equation}
\label{eq:spec}
\boldsymbol{r}^{\downarrow}(\varrho)=\{r_1 \overbrace{(1, \dots, 1)}^{k_1}\,;\, r_2\overbrace{(1, \dots, 1)}^{k_2}\,;\, \dots \,;\, r_s\overbrace{(1, \dots, 1)}^{k_s}\}\,.
\end{equation}

Now, bearing in mind the above described stratification of $\mathfrak{P}_N\,,$ it is easy to show the factorization of $SU(N)\--$invariant measures. Indeed, one can be convinced that the Singular Value Decomposition (SVD) of the density matrix from a stratum $\mathfrak{P}_{[H_\alpha]}$ with spectrum of the form (\ref{eq:spec}):
\begin{equation}
\label{eq:SVD}
\varrho=U\mathrm{diag}\left(r_1, r_2 , \dots r_s\right) U^\dagger\,,  \qquad U\in SU(N)/H_\alpha\,,
\end{equation}
reveals the following factorization of the invariant probability distribution (\ref{eq:InvPDF}):
\begin{equation}
   \mathrm{P}(\varrho)=P(r_1,\dots, r_s)\, \mathrm{d}r_1\wedge \cdots \wedge \mathrm{d}r_N\wedge \mathrm{d}\mu_{U(N)/H}\,,
\end{equation}
where the first factor $P(r_1,\dots, r_s)$ represents a measure on
subset $\mathfrak{P}_{k_1,k_2,\dots,k_s}$ of the simplex $\mathcal{C}_{N-1}$, while the second factor is the measure on coset
$U(N)/H$\,.

After a preliminary exposition of this generic property of unitary invariant ensembles, we will now specify the form of the distribution $P(r_1,\dots, r_N)$ for the  Hilbert-Schmidt metric and for an important class of the monotone metrics.

\paragraph{The Hilbert-Schmidt ensemble of qudits.}
Let us consider the metric corresponding to the distance between two infinitesimally close matrices $\varrho-\mathrm{d}\varrho$ and
 $\varrho+\mathrm{d}\varrho$ calculated with respect to the Frobenius norm,
\begin{equation}
 \label{eq:HSGen}
   \mathrm{g_{{}_\mathrm{HS}}} \propto \mathrm{Tr} \left(\mathrm{d}\varrho\otimes\mathrm{d}\varrho\right)\,.
\end{equation}
If a density matrix belongs to the interior of the simplex $C_{N-1}$\,, i.e., the matrix has $N$ distinct non-zero eigenvalues $(k_1=k_2=\cdots=k_N=1)$\,, then the  metric (\ref{eq:HSGen}) defines the standard \textit{Hilbert-Schmidt ensemble} of random full rank $N\--$qudits. A straightforward computation shows that the joint probability distribution of eigenvalues reads
\begin{equation}
P^{\rm HS}(r_1,\dots,r_N) \propto \,
    \delta(1-\sum_{j=1}^N r_j)  \prod_{j<k}^N (r_j-r_k)^2\,,
\end{equation}
and unitary random factors $U$ in SVD decomposition are  distributed according to the Haar measure on the coset $U(N)/U(1)^N$\,.

\paragraph{Degenerate Hilbert-Schmidt qudits} If the full rank density matrix has a spectrum of the form (\ref{eq:spec}) with an arbitrary algebraic degeneracy, then the joint probability distribution of eigenvalues is reduced to the following  expression:
\begin{equation}
P^{\mathrm{HS}}_{k_1, \dots, k_s}(r_1, \dots, r_s) \propto
 \delta(1- \sum_{i=1}^{s} k_i r_i)
    \prod_{i<j}^{1\dots s} (r_i-r_j)^{2 k_i k_j}\,.
 \end{equation}
At the same time the angles in the SVD are distributed according to the Haar measure on the coset $U(N)/U(k_1)\times\cdots\times U(k_s)$\,.

\paragraph{Monotone metrics and monotone ensembles of $N\--$qudits}
Two of the above-mentioned metrics, the Bures and Bogoliubov-Kubo-Mori ones, are members of a special class of unitary covariant monotone metrics. According to \cite{Petz1996}, any monotone metric can be written as
\footnote{
Due to the unitary covariance of the Riemannian metric, it is sufficient to describe monotone metrics evaluated for diagonal  matrices
$D$\,.
}
\begin{equation}
  \mathrm{g}_{{}_D}(X,Y) \propto   \mathrm{Tr}\left(X K^{-1}_D Y \right)\,,
\end{equation}
where $K_D$ is an operator,
\[
K_D=R_D^{1/2}f(L_D R^{-1}_D) R_D^{1/2}\,,
\]
constructed out of the left and right multiplication operators $L_D$ and $R_D$\,, i.e., $L_DX=DX$
and $R_DX=XD$ for $X \in M_N(\mathbb{C})\,,$
and operator monotone function $f$\,, which  is symmetric, i.e., $f(t)=t f(1/t)$\,, and normalized, $f(1)=1$\,.

Assuming that $\varrho$ is a full rank density matrix with a simple spectrum and using the 1-form coordinate basis for simplex, $\mathrm{d}r_i\,,$ and non-coordinate basis on $SU(N)$ group, $w_{ij}:=\left(U^\dagger\mathrm{d}U\right)_{ij}$\,, the non-degenerate monotone metrics can be written as
\begin{equation}
 \label{eq:MonotoneM}
\mathrm{g}_{f}= \frac{1}{4}\sum_{i=1}^N\,
    \frac{\mathrm{d}r_i
    \otimes\mathrm{d}r_i}{r_i}\,  + \frac{1}{2}\,
    \sum_{i< j}^N\,c_f(r_i\,, r_j){(r_i-r_j)^2}\,
    \omega_{ij}\otimes\omega_{ij} \,.
\end{equation}
In (\ref{eq:MonotoneM})  by $c_f(x,y) = \frac{1}{y f(x/y)}$  we  denote the Morozova-Chentsov function corresponding to a monotone function $f(t)$\,.
Note that the Bures and Bogoliubov-Kubo-Mori metrics are associated with  the following choice of monotone function:
\begin{equation}
\label{eq:BKM}
f_{{}_\mathrm{B}}(t) =\frac{1+t}{2}\,,
\qquad
f_{{}_\mathrm{BKM}}(t)= \frac{t-1}{\ln{t}}\,,
\end{equation}
and corresponding Morozova-Chentsov functions,
\begin{equation}
\label{eq:cBW}
c_{{}_\mathrm{B}}(x,y) =\frac2{x+y}\,,
\qquad
c_{{}_\mathrm{BKM}}(x,y)= \frac{\ln{x}-\ln{y}}{x-y}\,.
\end{equation}

\paragraph{Probability measures from monotone metrics.}
For an arbitrary monotone metric evaluated for degenerate qudits, calculations of the joint probability distribution of eigenvalues give:
\begin{equation}
\label{eq:JPDMono}
P^f_{k_1, \dots, k_s}(r_1, \dots, r_s) \propto \frac{\delta\left(1-\sum_{i=1}^{s} k_i r_i\right)}{
\sqrt{r_1\cdot r_2 \cdot \ldots \cdot r_s}} \,
\prod_{i<j}^s c_{f}^{k_i k_j}(r_i, r_j)\, (r_i-r_j)^{2 k_i k_j}\,.
\end{equation}

\section{Wigner function positivity and classicality }

Here, for the  reader's convenience, before giving a definition of the indicator of classicality, we present the basic settings of the Wigner function of a mixed state of a finite-dimensional quantum system.

\paragraph{Wigner function settings}
The Wigner quasiprobability distribution $W^{(\boldsymbol{\nu})}_\varrho(\Omega_N)$ of an $N\--$level qudit is constructed via dual pairing \cite{AKh2017-WF,AKhT2019},
\begin{equation}
\label{eq:WignerFunction}
W^{(\boldsymbol{\nu})}_\varrho(\Omega_N) = \mbox{tr}\left[\varrho
\,\Delta(\Omega_N\,|\,\boldsymbol{\nu})\right]\,,
\end{equation}
of a density matrix $\varrho$ with the Stratonovich-Weyl (SW) kernel $\Delta(\Omega_N\,|\,\boldsymbol{\nu}) \in \mathfrak{P}^\ast_N\,$
from the dual space:
\begin{equation}
\label{eq:SWspace}
    \mathfrak{P}^\ast_N=\{\, X \in M_N(\mathbb{C}) \ |\ X=X^\dagger\,,\quad \mbox{tr}\left( X \right) = 1\,,
    \quad  \mbox{tr}\left( X^2 \right) = N \,\}\,.
\end{equation}
For $N\geq 3$\,, algebraic equations (\ref{eq:SWspace}) admit a family of solutions. As a result, the generic  Wigner function depends on $N-2$ real parameters  $\boldsymbol{\nu}=(\nu_1, \nu_2, \dots, \nu_{N-2} )\,,$ (see details in \cite{AKhT2019}).
The structure of phase space $\Omega_N$  depends on the isotropy group of the SW kernel. For any given isotropy group $H\in U(N)$ of the form
\[
H={U(k_1)\times U(k_2) \times\ldots\times U(k_{s+1})}\,,
\]
we identify the  phase-space $\Omega_N$ with the  complex flag manifold,
$$
\Omega_N \,\to\, \mathbb{F}^N_{d_1, d_2, \dots, d_s}= {U(N)} / {H}\,,
$$
where
$(d_1, d_2, \dots, d_s)$ is a sequence of positive integers with a sum $N$\,, such that $k_1=d_1$ and $k_{i+1}=d_{i+1}-d_i$ with $d_{s+1}=N\,.$ After presenting necessary notions, we are ready to introduce the  definition of the classicality of states.

\paragraph{Classical states and classicality indicator} The ``classical states'' form the subset $\mathfrak{P}_N^{(+)} \subset  \mathfrak{P}_N$ of states  whose Wigner function is non-negative everywhere over the phase space:
\begin{equation}
\label{eq:P+}
   \mathfrak{P}^{(+)}_N = \{\, \varrho \in \mathfrak{P}_N\,\ | \  W_\varrho(z) \geq 0\,, \quad  \forall z\in \Omega_N \, \}\,,
\end{equation}
and similarly, the ``classical states on a fixed stratum'' $ \mathfrak{P}_{H_\alpha}$ are defined as:
\begin{equation}
\label{eq:P+Stratum}
 \mathfrak{P}^{(+)}_{H_\alpha}=
 \mathfrak{P}^{(+)}_N\cap
 \mathfrak{P}_{H_\alpha}\,.
\end{equation}

Based on (\ref{eq:P+}), we define the geometric probability of finding a classical state in an ensemble as
\begin{equation}
\label{eq:QDef}
\mathcal{Q}_N=
    \frac{\mathrm{Volume (Classical ~ States)}}{\mathrm{Volume(All ~ States)}}\,.
\end{equation}
Here  it is assumed that the Riemannian volume is calculated  with respect to the measure dictated  by the probability  distribution function of an ensemble. Probability (\ref{eq:QDef}) shall be considered as the \textit{global indicator of classicality}. Moreover, for classical states (\ref{eq:P+}) on the fixed stratum $\mathfrak{P}_{H_\alpha}$ we define the \textit{$Q\--$indicator of classicality of the stratum}:
\begin{equation}
\label{eq:QDefStratun}
\mathcal{Q}_N[H_\alpha]=
    \frac{\mathrm{Volume (Classical ~ States~on ~\mathfrak{P}_{[H_\alpha]})}}{\mathrm{
    Volume(All ~States~on~\mathfrak{P}_{[H_\alpha]})}}\,.
\end{equation}
According to (\ref{eq:stratumDeg}), stratum $\mathfrak{P}_{[H_\alpha]}$ consists from subsets of matrices with a certain degeneracy type. Hence, owing to the unitary covariance of probability distribution functions (\ref{eq:InvPDF}), the  $\mathcal{Q}\--$indicator depends only on the joint  probability distribution of eigenvalues of the density matrix and can be rewritten as:
\begin{equation}
\label{eq:QOrb}
\mathcal{Q}_N [H_\alpha]=
\frac{\sum_{\omega \in S_s }\int_{\mathcal{C}^{\ast}_{N-1}(H_\alpha)}
    P^f_{k_\omega(1),\dots,k_\omega(s)}(r_1,\dots,r_s)\,
 \mathrm{d}r_1\wedge\dots\wedge\mathrm{d}r_s}{\sum_{\omega \in S_s }\
\int_{\mathcal{C}_{N-1}(H_\alpha)}
 P^f_{k_\omega(1),\dots,k_\omega(s)}(r_1,\dots,r_s)\,
\mathrm{d}r_1\wedge\dots\wedge\mathrm{d}r_s}\,.
\end{equation}
In (\ref{eq:QOrb}) the integral in the denominator represents the volume of the orbit space of stratum $\mathfrak{P}_{[H_\alpha]}$\,. The subset $\mathcal{C}_{N-1}(H_\alpha)$ is a union of faces of the simplex $C_{N-1}$ determined by the isotropy group $[H_\alpha]$\,. The integration in the nominator of (\ref{eq:QOrb}) is over the image of $\mathfrak{P}^+_{[H_\alpha]}$  under the canonical quotient map:
\begin{eqnarray}
\label{eq:OritP+}
\mathcal{C}_{N-1}^\ast(H_\alpha)=  \{\, p(x)\, \ | \ x \in \mathfrak{P}_{H_\alpha}^{(+)}\,\}\,.
\end{eqnarray}
According to \cite{AKhT2019},  the subset (\ref{eq:OritP+}) can be identified with a certain cone in $\mathbb{R}^{N-1}\,.$
Having denoted by $\boldsymbol{r}=\{r_1, r_2, \dots, r_N\}$ the eigenvalues of the density matrix $\varrho$ and by $\boldsymbol{\pi}=\{\pi_1, \pi_2, \dots, \pi_N\}$  the eigenvalues of the SW kernel, both arranged in decreasing  order, we obtain that $\mathcal{C}_{N-1}^\ast(H_\alpha)$ is the following dual cone:
\begin{equation}
\mathcal{C}_{N-1}^\ast(H_\alpha) =  \
\left\{\, \boldsymbol{\pi} \in \mbox{\bf spec}\left(\Delta(\Omega_N)\right) \ \, |\ \,  ( \boldsymbol{r}^\downarrow, \boldsymbol{\pi}^\uparrow) \geq 0,  \quad \forall\, \boldsymbol{r} \in \mathcal{C}_{N-1}(H_\alpha) \, \right\}\,,
\end{equation}
where $( \boldsymbol{r}^\downarrow, \boldsymbol{\pi}^\uparrow) = r_1\pi_{N}+r_2\pi_{N-1} +\dots +r_{N}\pi_1$\,.

\section{Examples}

In this section results of the  calculations of classicality indicators for the random ensembles described in Section  \ref{sec:Random} will be given for  qubit  and qutrit cases.

\subsection{$\boldsymbol{N=2}\,,$ Qubit}

For a single qubit  the  expansion coefficients of the density matrix over the Pauli $\boldsymbol{\sigma}$\--matrices  are  given by components of the  3-dimensional Bloch vector $\boldsymbol{\xi}=(\xi_1, \xi_2, \xi_3)$:
\begin{equation}
\label{eq:qubitDM}
    \varrho = \frac{1}{2}\left(I + (\boldsymbol{\xi}, \boldsymbol{\sigma})
    \right)\,.
\end{equation}
Expressing the eigenvalues of (\ref{eq:qubitDM}) in terms of the  length $r\in (0\,, 1]$ of the Bloch vector
\begin{equation}
\label{eq:qubit-r-param}
    r_1 = \frac{1+r}{2}\,, \quad
    r_2 = \frac{1-r}{2}\,,
\end{equation}
and taking into account that the Wigner function of a qubit is uniquely constructed with the aid of the SW kernel, whose spectrum is:
\begin{equation}
\label{eq:qubitSW}
 \pi_1=\frac{1+\sqrt{3}}{2}\,, \qquad \pi_2=\frac{1-\sqrt{3}}{2}\,,
\end{equation}
we conclude that the Wigner function of a qubit is positive definite inside the Bloch ball of radius ${1}/\sqrt{3}\,.$ Since all states, except  the maximally mixed state $r_1=r_2=1/2\,,$  have the torus $T^2\in SU(2)$ as their  isotropy group, there is only one indicator $\mathcal{Q}_{[T^2]}$ for all possible ensembles of qubits. Hence, for any random ensemble of qubits, characterized by a probability distribution $P(r)\,,$ the expression of the classicality indicator is reduced to the following ratio:
\begin{equation}
\label{eq:Qqubit}
    \mathcal{Q}_{[T^2]}=
    \frac{\displaystyle{\int_{0} ^{\frac{1}{\sqrt{3}}}} P(r) \mathrm{d}r}{\displaystyle{\int_{0}^{1}} P(r) \mathrm{d}r}\,.
\end{equation}

\paragraph{ Hilbert-Schmidt ensemble.} Noting that for the Hilbert-Schmidt ensemble the probability distribution function is $P^{\mathrm{HS}}(r) \propto r^2\,,$ the calculation of (\ref{eq:Qqubit}) gives:
\begin{equation}
\mathcal{Q}^{\mathrm{HS}}_{[T^2]}
= \frac{1}{3\sqrt{3}}\approx
0.19245\,.
\end{equation}

\paragraph{Bures ensemble}
Using the probability distribution function of the Bures ensemble
\(
P^{\mathrm{B}}(r) \propto \frac{r^2}{\sqrt{1-r^2}}\,,
\)
we find the classicality indicator:
\begin{equation}
\mathcal{Q}^{\mathrm{B}}_{[T^2]}  = \frac{2}{\pi} \left(\arcsin \frac{1}{\sqrt{3}} - \frac{\sqrt{2}}{3}\right) \approx 0.0917211\,.
\end{equation}

\paragraph{Bogoliubov-Kubo-Mori ensemble }
Analogously,  calculations with the Bogoliubov-Kubo-Mori measure
$P^{\mathrm{B}}(r) \propto
\frac{r \left(\ln{\frac{1+r}{2}}-\ln{\frac{1-r}{2}}\right)}{\sqrt{1-r^2}}$
result in the classicality indicator:
\begin{eqnarray}
\mathcal{Q}^{\mathrm{BKM}}_{[T^2]}  = \frac{2}{\pi} \left(\arcsin \frac{1}{\sqrt{3}} - \sqrt{\frac{2}{3}} \arcoth \sqrt{3} \right) \approx 0.0495506\,.
\end{eqnarray}

\subsection{$\boldsymbol{N=3}\,,$ Qutrit}
Qutrit state space $\mathfrak{P}_3$ admits the following orbit type decomposition:
\begin{equation}
\label{eq:OTD}
    \mathfrak{P}_3=\mathfrak{P}_{[T^3]}\bigcup
    \mathfrak{P}_{[S(U(2)\times U(1))]}\bigcup
\mathfrak{P}_{[SU(3)]}\,.
\end{equation}
Three strata in (\ref{eq:OTD}) are labeled by the isotropy group or directly by the degeneracy of the density matrices. For full rank states, putting eigenvalues of $\varrho $ in decreasing order, $1 > r_1 > r_2 > r_3 > 0$\,, the components of decomposition  (\ref{eq:OTD}) are described as follows (see geometrical illustration in Fig. \ref{fig:2S+CL}):
\begin{enumerate}
\item the regular stratum $\mathfrak{P}_{[T^3]}$ of maximal dimension 6   consists  of matrices with a simple spectrum,  $1> r_1\neq r_2\neq r_3 > 0$\,. The corresponding orbit space is the face $F_{123}$ of the ordered 2-simplex, the interior of $\triangle AOB$\,,
\item the degenerate 4-dimensional stratum $\mathfrak{P}_{[S(U(2)\times U(1))]}$ with density matrices whose degeneracy is $\boldsymbol{k}=(2,1)$ and $\boldsymbol{k}=(1,2)$\,, i.e.,  $1>r_1\neq r_2=r_3> 0$ and $1>r_1=r_2\neq r_3>0$\,. The corresponding orbit space represents the union of edges $F_{1|23}$ and $F_{12|3}$ of the 2-simplex, two sides of $\triangle AOB$\,,
\item the 0-dimensional stratum $\mathfrak{P}_{[SU(3)]}$ of the maximally mixed state with the triple degeneracy  $\boldsymbol{k}=(3)$\,, $r_1=r_2=r_3=1/3$\,.
\end{enumerate}

\begin{figure}[h!]
\center{
\includegraphics[width=0.4\textwidth]{2S+CL}
}
\caption{The ordered 2-simplex of qutrit eigenvalues  is represented by  $\triangle AOB$\,,  and the hatched region, $\triangle COD\,,$   corresponds to the classical states. Edges $AO/\{A\}$  and $BO/\{B\}$ are locus of degenerate  states $F_{12|3}$ and $F_{1|23}$\,, while their parts $CO/\{O\}$  and $DO/\{O\}$ represent the degenerate classical states $F^+_{12|3}$ and $F^+_{1|23}$\,.
}
\label{fig:2S+CL}
\end{figure}

Taking into account the decreasing order of the eigenvalues,  $1 \geq r_1 \geq r_2 \geq r_3 \geq 0$\,,  the spectrum of qutrit admits the following  parameterization:
\begin{eqnarray}
\label{eq:specrho1}
r_1&=&
\frac{1}{3}-\frac{2r}{\sqrt{3}}\,
\cos\left(\frac{\varphi+2\pi}{3}\right),\\
\label{eq:specrho2}
r_2 &=&
\frac{1}{3}-\frac{2r}{\sqrt{3}}\,
\cos\left(\frac{\varphi+
4\pi}{3}\right),\\
\label{eq:specrho3}
r_3&=&\frac{1}{3}-
\frac{2r}{\sqrt{3}}\,
\cos\left(\frac{\varphi}{3}\right),
\end{eqnarray}
with  $r \in [0, 1/\sqrt{3}]$ and the angle $\varphi \in [0, \pi]$\,.
If  $r$ and $\varphi$ are treated as the polar coordinates on a plane, $\left(r\cos\varphi\,, r\sin\varphi\right)\,,$ then  geometrically the formulae (\ref{eq:specrho1})-(\ref{eq:specrho3}) can be interpreted as a map  between  the  ordered simplex $\mathcal{C}_{2}$  and  the domain of the upper half-plane outlined by the Maclaurin trisectrix:
\begin{equation}
    r(\varphi, 1/\sqrt{3})=\frac{1}{2\sqrt{3} \cos({\varphi}/{3})}\,.
\end{equation}

More precisely, under  transformations  (\ref{eq:specrho1})-(\ref{eq:specrho3}),  the  ordered simplex of eigenvalues $\mathcal{C}_2$
maps to the domain (see Fig. \ref{fig:QutritMacTris})
\begin{equation}
\label{eq:OrbitQutrit}
 F_{123}=\,: \
 \biggl\{\, r \geq 0\,,  \varphi \in [0, \pi]\,\ \biggl|\, \ \cos\left(\frac{\varphi}{3}\right) \leq \frac{1}{2\sqrt{3}r} \, \biggl\}\,.
\end{equation}

\begin{figure}[h!]
\center{
\includegraphics[width=0.4\textwidth]{QutritMacTris.png}
}
\caption{The image of the ordered simplex $\mathcal{C}_2$ on the plane $x=r\cos\varphi\,,\, y=r\sin\varphi\,$ under the mapping (\ref{eq:specrho1})-(\ref{eq:specrho3}).}
\label{fig:QutritMacTris}
\end{figure}

\paragraph{Wigner function of a qutrit}
The master equations (\ref{eq:SWspace}) for eigenvalues of the Stratonovich-Weyl kernel of a qutrit,
\begin{equation}
\label{eq:mod3}
\pi_1+\pi_2+\pi_3=1\,,    \qquad  \pi^2_1+\pi^2_2+\pi^2_3=3 \,,
\end{equation}
define a one-parametric family of the Wigner functions. Due to the permutation symmetry of (\ref{eq:mod3}),
the corresponding moduli space  is  a unit circle factorised by the symmetric group $S_3\,.$ Let $\mu_3$ and $\mu_8$ be  Cartesian coordinates of this arc with a polar angle from the interval $\zeta \in[0, \frac{\pi}{3}]\,,$
 \begin{equation}
\label{eq:muzeta}
\mu_3=\sin\zeta\,, \qquad \mu_8=\cos\zeta\,,
\qquad
\end{equation}
then, providing  the decreasing order of the SW kernel eigenvalues, $\pi_1 \geq \pi_2 \geq \pi_3\,,$ one can represent  the whole class of solutions to  (\ref{eq:mod3}) as:
\begin{eqnarray}
\label{eq:piparam}
\pi_1=  \frac{1}{3}+\frac{2}{\sqrt{3}}\,
\mu_3+\frac{2}{3}\,\mu_8\,,\quad
\pi_2=\frac{1}{3}-\frac{2}{\sqrt{3}}\,\mu_3+\frac{2}{3}\,\mu_8\,, \quad
\pi_3=\frac{1}{3}-\frac{4}{3}\,\mu_8\,.
\end{eqnarray}

\paragraph{Classical states of qutrit.}
The image of classical states from the regular stratum $\mathfrak{P}_{[T^3]}$  to the unitary orbit space is the  interior $F^+_{123}$ of a cone which is cut out from  the simplex  $\mathcal{C}_2$  by the line  (see Fig. \ref{fig:2S+CL})
\begin{equation}
L_{\boldsymbol{\pi}}(\boldsymbol{r})  \, : \qquad  r_1\pi_3+ r_2\pi_2+ r_3\pi_1=0\,,
\end{equation}
while the orbit space of classical states from the stratum $\mathfrak{P}_{S(U(2)\times U(1))}$ consists of  two pieces: $F^+_{1|23}$ and $F^+_{12|3}$\,, corresponding to the matrices of degeneracy types $(2,1)$ and $(1,2)$ respectively.
Using the polar form of parameterization  of the spectrum of a density matrix
(\ref{eq:specrho1})-(\ref{eq:specrho3})
and expressions  (\ref{eq:piparam})
for  the SW kernel eigenvalues,  the cone of classical states on a regular stratum reads:
\begin{eqnarray}
\label{eq:coneclass1}
&& F^+_{123}\, : \biggl\{\, r > 0\,,  \varphi \in (0, \pi)\,\ \biggl|\, \ \cos\left(\frac{\varphi}{3} +\zeta -\frac{\pi}{3}\right) \leq \frac{1}{4\sqrt{3}r}\,\biggl\}\,,
\end{eqnarray}
while the cone of classical states on the degenerate stratum $\mathfrak{P}^{(+)}_{[S(U(2)\times U(1))]}$ is:
\begin{eqnarray}
   \label{eq:coneclass2}
   F^+_{1|23}&=&\left\{\,
   \varphi= 0, \ r \in (0, \frac{1}{2\sqrt{3}})\ \biggl| \
   \cos\left(\zeta-\frac{\pi}{3}\right)
   < \frac{1}{4\sqrt{3}r}
   \,\right\}\,,\\
   F^+_{12|3}&=&
   \left\{\,
   \ \varphi= \pi, \ r \in (0, \frac{1}{\sqrt{3}})\ \biggl| \
   \cos\left( \zeta\right)
   < \frac{1}{4\sqrt{3}r}
   \,\right\}\,.
\end{eqnarray}

\begin{figure}[h!]
\begin{minipage}[h]{0.32\linewidth}
\center{\includegraphics[width=1\linewidth]{QutritLowerBound-zeta0}}
\end{minipage}
\hfill
\begin{minipage}[h]{0.32\linewidth}
\center{\includegraphics[width=1\linewidth]{QutritLowerBound-zetapi6}}
\end{minipage}
\hfill
\begin{minipage}[h]{0.32\linewidth}
\center{\includegraphics[width=1\linewidth]{QutritLowerBound-zetapi3}}
\end{minipage}
\begin{minipage}[h]{0.96\linewidth}
\begin{tabular}{p{0.32\linewidth}p{0.32\linewidth}p{0.32\linewidth}}
\centering
\footnotesize $\zeta=0$ & \centering
\footnotesize $\zeta=\pi/6$ & \centering
\footnotesize $\zeta=\pi/3$ \\
\end{tabular}
\end{minipage}
\caption{The orbit space $F_{123}$ in blue and its subspace $F^+_{123}$ in red for different values of the moduli parameter: $\zeta = 0, \pi/6, \pi/3$\,.}
\label{fig:QutritLowerBound}
\end{figure}

\paragraph{$\mathcal{Q}_3\--$indicator  for Hilbert-Schmidt ensemble of qutrits from regular stratum.}
The regular stratum $\mathfrak{P}_{[T^3]}$ consists of  density matrices with a simple spectrum.  The expression  $\mathcal{Q}_{[T^3]}$ comprises  the integrals  over the face $F_{123}$ and its subset $F^{+}_{123}$\,:
\begin{equation}
\label{eq:Q3T31}
\mathcal{Q}^{\mathrm{ HS}}_{[T^3]}=\frac{\mathrm{vol_{HS}}(F^+_{123})}{\mathrm{vol_{HS}}(F_{123})}\,.
\end{equation}
In (\ref{eq:Q3T31})  the expression $\mathrm{vol_{HS}}(X)$   denotes the Riemannian integral over a region $X$ taken with the measure induced on $X \in \mathcal{C}_2$ from the  Hilbert-Schmidt on $\mathfrak{P}_3$\,,
\begin{eqnarray}
\label{eq:volx}
\mathrm{vol}_{\mathrm{HS}}(X)=
\int_{X}\,
P_{1,1,1}^{\mathrm{HS}}(r_1,r_2,r_3)\,\mathrm{d}r_1\wedge\mathrm{d}r_2\wedge\mathrm{d}r_3\,.
\end{eqnarray}
Taking into account the expression (\ref{eq:HSGen}) for the Hilbert-Schmidt  measure  and the polar form of the parameterization of the qutrit orbit space (\ref{eq:OrbitQutrit}) and of (\ref{eq:coneclass1}),  we obtain  the  indicator of classicality  as a function of the moduli parameter $\zeta$\,:
\begin{equation}
\label{eq:QR}
\mathcal{Q}^{\mathrm{HS}}_{[T^3]}(\zeta) = \frac{20 \cos^2{\left(\zeta -{\pi }/{6}\right)}+1}{128 \left(4\cos^2{\left(\zeta -{\pi }/{6}\right)} -1\right)^5}\,.
\end{equation}

\paragraph{$\mathcal{Q}_3\--$indicator  for   Hilbert-Schmidt ensemble of qutrits from degenerate stratum.}
The stratum
$\mathfrak{P}_{[S(U(2)\times U(1))]}$ has two pieces,  $F_{1|23}$ and $F_{12|3}$, associated with density matrices with degenerate  eigenvalues $r_1=r_2\neq r_3$ and $r_1\neq r_2= r_3$\,, respectively.
Hence,  the $\mathcal{Q}_3\--$indicator for the degenerate stratum of a qutrit reads:
\begin{equation}
\label{eq:Q3U2U1}
\mathcal{Q}^{\mathrm{ HS}}_{[S(U(2)\times U(1))]}=\frac{\mathrm{vol_{HS}}(F^+_{1|23})+\mathrm{vol_{HS}}(F^+_{12|3})}{\mathrm{vol_{HS}}(F_{1|23})+\mathrm{vol_{HS}}(F_{12|3})}\,,
\end{equation}
where we keep the notation previously used for the regular stratum (\ref{eq:volx}),  noticing only that  the dimension of integration over the degenerate orbit state strata has decreased by one:
\begin{eqnarray}
\mathrm{vol}_{\mathrm{HS}}(F_{1|23})=
\int_{F_{1|23}}\,
P_{2,1}^{\mathrm{HS}}(r_1,r_2)\,\mathrm{d}r_1\wedge\mathrm{d}r_2\,.
\end{eqnarray}
The  evaluation of all integrals in (\ref{eq:Q3U2U1}) gives:
\begin{equation}
\label{eq:QD}
   \mathcal{Q}^{\mathrm{ HS}}_{[S(U(2)\times U(1))]}(\zeta) = \frac{1}{1056}\left({\csc ^5\left(\zeta +\frac{\pi }{6}\right)+\sec ^5(\zeta )}\right)\,.
\end{equation}
The functional dependence of the  indicator  $\mathcal{Q}_3^{\mathrm{HS}}$ for the  regular (\ref{eq:QR}) and degenerate  (\ref{eq:QD}) strata is  depicted  in Fig. \ref{fig:Qutrit-Q-Ln}\,. Apart from this,  in Fig. \ref{fig:RatioQregdegenHS} we present the ratio
\begin{equation}
    \mathrm{R^{HS}}(\zeta)=\frac{\mathcal{Q}^{\mathrm{ HS}}_{[S(U(2)\times U(1))]}(\zeta)}{\mathcal{Q}^{\mathrm{ HS}}_{[T^3]}(\zeta)}
\end{equation}
as a certain measure of the relation between the symmetry of a state and its classicality.

\begin{figure}[h!]
     \centering
     \begin{subfigure}[b]{0.4\textwidth}
         \centering
         \includegraphics[width=\textwidth]{Qutrit-Q-Ln}
         \caption{ }
         \label{fig:Qutrit-Q-Ln}
     \end{subfigure}
     \hfill
     \begin{subfigure}[b]{0.4\textwidth}
         \centering
         \includegraphics[width=\textwidth]{RatioQregdegenHS}
         \caption{ }
         \label{fig:RatioQregdegenHS}
     \end{subfigure}
\caption{
(a) $\mathcal{Q}_3\--$indicators of a Hilbert-Schmidt qutrit  as functions of $\zeta $ for the regular  (gray curve) and  degenerate (blue curve) strata. The absolute minimum of both indicators is attained at $\zeta=\pi/6$\,.
(b) The ratio of degenerate to regular  $\mathcal{Q}_3\--$indicators.}
        \label{fig:RHS}
\end{figure}

\paragraph{$\mathcal{Q}_3\--$indicator  for   Bures ensemble of qutrits from regular  stratum.}
Using the generic expressions for the joint probability distributions of eigenvalues for monotone metrics (\ref{eq:JPDMono}) and the technique developed above, we compute the $\mathcal{Q}_3\--$indicators  for the Bures and Bogoliubov-Kubo-Mori ensembles of qutrits. The results of our calculations are presented in  Fig. \ref{fig:Qutrit-Q-B-BKM-Ln}.

\begin{figure}[h!]
     \centering
     \begin{subfigure}[b]{0.4\textwidth}
         \centering
\includegraphics[width=\textwidth]{Qutrit-Q-B-BKM-Ln}
         \caption{ }
\label{fig:Qutrit-Q-B-BKM-Ln}
     \end{subfigure}
     \hfill
\begin{subfigure}[b]{0.4\textwidth}
\centering
    \includegraphics[width=\textwidth]{RatioQregdegenB-BKM}
         \caption{ }
         \label{fig:RatioQregdegenB-BKM}
     \end{subfigure}
\caption{(a) The plot of $\mathcal{Q}_3$ for the  Bures (solid curves) and BKM (dashed curves) ensembles of qutrits from the regular (gray curves) and degenerate (blue curves) strata.
(b) The ratio $R$ of  degenerate to regular  $\mathcal{Q}_3\--$indicators  for the Bures (solid blue) and the BKM (dashed blue) ensembles.}
\label{fig:2}
\end{figure}

\section{Summary}

Bearing in mind the results of the calculations of $\mathcal{Q}_3$\,, we will summarize with a few comments. The indicator of classicality  $\mathcal{Q}_3$\,, being a  functional of the ensemble probability distribution function, at the same time depends on two characteristics  of the SW kernel: its isotropy group $H_\alpha$ and the moduli parameter $\zeta$\,. Our studies of the $\mathcal{Q}_3\--$indicator reveal several interesting  peculiarities concerning their interrelations:
\begin{itemize}
\item There is a certain coherence between the classification of states according to their classicality and their symmetry properties. In particular, it turns out that the states with a ``larger'' symmetry  are more classical, cf. Fig. \ref{fig:RHS} and  Fig. \ref{fig:2}. This observation demands further study and we plan to formalize it in forthcoming publications;
\item The character of the dependence of $\mathcal{Q}_3$ on the type  of the ensemble is monotone, i.e., the values of $\mathcal{Q}_3$ for all strata  are ordered in correspondence with the order of the ensembles, see
Fig. \ref{fig:PairwiseRat};

\item The $\mathcal{Q}_3(\zeta)\--$indicator of the Hilbert-Schmidt ensemble is a symmetric function with respect to the global minimum point, $\zeta=\pi/6$\,, see Fig. \ref{fig:Qutrit-Q-Ln}\,;
\item For monotone metrics the symmetry possessed by the Hilbert-Schmidt ensemble is broken. Data specifying the range of violation is given in Table\,\ref{table:1}.
\end{itemize}

\begin{figure}[h!]
     \centering
     \begin{subfigure}[b]{0.44\textwidth}
         \centering
         \includegraphics[width=\textwidth]{QtrRegRatioslnQlnQ}
         \caption{ }
\label{fig:QtrRegRatioslnQlnQ}
     \end{subfigure}
     \hfill
     \begin{subfigure}[b]{0.44\textwidth}
         \centering
         \includegraphics[width=\textwidth]{QtrDegenRatioslnQlnQ}
         \caption{ }
         \label{fig:QtrDegenRatioslnQlnQ}
     \end{subfigure}
\caption{Pairwise ratios  of  $\mathcal{Q}_3\--$indicators of different ensembles for the regular (a) and for the degenerate  (b) stratum.}
\label{fig:PairwiseRat}
\end{figure}

\begin{table}[h!]
\begin{center}
\begin{tabular}{|p{3cm}|p{3cm}|p{3cm}|p{3cm}|}
\hline\hline
\multicolumn{4}{|c|}{\sc Global $\mathcal{Q}_3\--$indicator vs. moduli parameter}  \\ [0.2ex]
\hline
\hline
{\bf Ensemble }& $\min{\mathcal{Q}_3(\zeta)}$ &$\zeta_{\min}$ & $\mathcal{Q}_3(0)-
\mathcal{Q}_3
({\pi}/{3})$ \\
\hline
Hilbert-Schmidt & 0.0006751 & $\pi/6 \approx 0.523599$ & 0  \\
\hline
BKM  & 0.0000121609 & 0.527798 & 0.0000216102\\
\hline
Bures &
0.0000891011 & 0.525096 & 0.0000472609 \\
\hline
\end{tabular}
\caption{Data on symmetry properties of $\mathcal{Q}_3\--$indicators.}
\label{table:1}
\end{center}
\end{table}

\section*{Acknowledgments}
The work of A.K. was supported in part by  the Shota Rustaveli National Science Foundation of Georgia, Grant FR-19-034.