\chapter{High Valence Vertices}\label{ch:high_valence}

High valence (HV) vertices are a mesh feature which cause significant degradation in
DAGMC ray tracing performance. The valence of a vertex in a mesh is defined as
the number of edges connected to that vertex. \textit{High} valence vertices are
defined as vertices connected to an unusually large number of edges. This
region, known as a HV region, will typically take on a fan-like shape
as seen in Figure \ref{fig:hv_examples}.  The geometric origins of HV
regions are typically a planar surface intersected with some form of curved
boundary condition.

\begin{figure}[H]
  \centering
  \includegraphics[scale=0.2]{iter_sideon.eps}
  \includegraphics[scale=0.2]{ds_hv.eps}
  \caption[Examples of HV vertices in production models.]{Examples of HV
    vertices in production models.}
  \label{fig:hv_examples}
\end{figure}

These regions are commonly generated in the faceting algorithms used to produce
DAGMC meshes. This faceting scheme (which comes from ACIS libraries underlying
the CUBIT/Trelis geometry engine) is designed to produce the smallest number of
triangles possible to represent the model within the representation tolerance
specified in DAGMC's surface mesh generation preprocessing. This restriction is
favorable to the rasterization process commonly used to display models
interactively in CAD GUIs. Fewer triangles are better for the purpose
particle tracking in DAGMC as well as long as the geometry is accurately
represented. Even the ideal ray tracing acceleration structure queries for a
given triangle mesh scale as $O(log(N))$, and the size of models being analyzed
using the toolkit provides motivation to keep memory footprints as low as
possible. However, even with fewer triangles undesirable configurations can
impede performance as is shown by a set of tests conducted on models generated
by this faceting scheme.

\section{Previous Work}

A study conducted by Steve Jackson in 2010 on the performance of the MOAB OBB
tree revealed a steep degradation in performance with a decreasing faceting
tolerance or an increasing number of triangles \cite{Tautges_2009}. Using a
DAGMC-based ray fire test program, the performance of DAGMC's ray fire ability
was evaluated for four models. These models include a simple sphere, a notched
or slotted sphere, and an outer volume of an ITER model, shown in Figure
\ref{fig:sj_hv_test_models}.

\begin{figure}[H]
  \centering
    \includegraphics[scale=0.32]{iter_rf_vol.eps}
    \includegraphics[scale=0.42]{ds.eps}
  \caption[CAD models used in ray fire timing.]{Images of the slotted sphere and
    ITER volume used to perform DAGMC ray fire performance tests with increasing
    number of triangles or, equivalently, decreasing faceting tolerance.}
  \label{fig:sj_hv_test_models}
\end{figure}

In each of these tests, the models are tessellated with an increasingly smaller
faceting tolerance with the faceting tolerance being defined as the maximum
distance between the faceted curve or surface and the geometric curve or surface
it resolves. By this definition, the number of triangles needed to represent a
model scales inversely with the value of the faceting tolerance. An increase in
the number of triangles leads to a more complex nature of the surface mesh in
terms of BVH construction and traversal.

The first three models are identical to the ones used to measure ray fire times
in Chapter \ref{ch:simd_bvh}. Finally, the faceting of a volume from an ITER
model is used as a production demonstration of the effect of HV
regions on DAGMC performance (see Figure \ref{fig:hv_examples}).

\begin{figure}[H]
  \centering
  \begin{center}
    \includegraphics[scale=0.5]{sj_2010_orig.eps} \\
    \caption[Previous results of ray fire timings from 2010.]{Results of MOAB
      ray tracing performance tests with decreasing faceting tolerance performed
      by Steve Jackson in June of 2010. Data points represent average time spent
      in firing a ray for random rays originating at the center of each
      model\cite{Tautges_2009}. The ``deathstar'' model is the same as the
      slotted sphere model used in tests performed by the author.}
    \label{fig:sj_hv_test_results}
  \end{center}
\end{figure}

While the sphere model scales well with a decreasing faceting tolerance, the
ITER volume and slotted sphere both have a pronounced increase in average ray
fire time with decreasing faceting tolerance. Knowing that both of the latter
models contain HV regions, it was postulated at the time that these
regions had a significant effect on the scaling.

\begin{sidewaysfigure}
  \centering
  \includegraphics[scale=0.45]{hv_study_MOAB.eps}
  \includegraphics[scale=0.45]{hv_study_MOAB_wsr1.eps}
  \includegraphics[scale=0.45]{hv_study_moab_adaptive.eps}
  \caption[High valence study results for various BVH implementations.]{HV characterization study
    results for all MOAB OBB tree implementations. Top Left: Unmodified MOAB
    results. Top Right: Manual modification of MOAB OBB tree's build
    settings. Bottom: Results with adaptive construction for HV regions.}
  \label{fig:moab_hv_studies}
\end{sidewaysfigure}

\section{High Valence Characterization Test Framework}

In order to isolate a HV region, a test model was manually generated in MOAB
with an artificial HV region (shown in Figure \ref{fig:hv_cube_design}). This
mesh is a modified cube mesh centered on the origin in which one of the
two-triangle surfaces has been replaced by a more complicated planar surface of
triangles including an interior HV region within the face. The HV region was
generated by inserting vertices along the diagonal of the interior box and
connecting them to the opposing corners of the box. This mesh is generated using
two input parameters: the valence of the corner vertices in the interior region
and the relative size of the interior region. A parametric study was then
performed by varying these two parameters in order to characterize the
performance impediment and determine its root cause.

\begin{figure}[H]
  \centering
    \includegraphics[scale=0.33]{hv_study_design.eps}
    \caption[High valence vertex test model.]{Side-on view of the modified cube
      mesh used to study the HV vertex problem.}
    \label{fig:hv_cube_design}
\end{figure}

DAGMC's ray fire test program was used to construct MOAB's BVH and perform ray
queries on this model. This program was used to fire rays with random
direction from the origin of the HV test model while biasing the ray directions
such that they are always incident upon the modified surface containing the HV
region. A parameter sweep was performed by varying the percentage of the surface
covered by the HV region as well as the valence of the region. Each test shown
in this section varies the valence of the corner vertices from 2 to 50,000 and
the relative area of the HV region from 0 to 1. Results of this study provided
insights into performance pathologies for various BVH implementations.

\section{MOAB's BVH}\label{sec:hv_study_MOAB}

From what is known about the construction of MOAB's OBB-BVH, it was expected
that the average ray fire time would be most strongly correlated to the relative
area of the HV region, but would also increase with increasing valence of the
corner vertices. The initial results of this study, shown in Figure
\ref{fig:moab_hv_studies}, meet only one of the expectations however. The ray
fire times become far worse with increase in valence, but for a constant
valence, the smaller relative area models show a longer average ray fire time
than the models with larger relative areas. This suggests that the presence of a
HV region in a surface is detrimental to performance regardless of the
likelihood that a ray intersects with a triangle in that region, which is
counter intuitive. In order to investigate this matter further, a visualization
tool for MOAB's BVH was developed to improve the author's intuition about this
mesh pathology.

\subsection{Visualization and Diagnosis}\label{subsec:hv_vis}

Using the same visitor pattern employed to traverse rays through the hierarchy,
each OBB in the HV model tree was converted into a hexahedral element and saved
in a VTK mesh format. Each hexahedron representing an OBB was tagged
with its depth in the tree as well as the triangle entities it contains, if it
is a leaf node. These mesh files can then be used to visualize the hierarchy
level-by-level and can be superimposed on the geometric mesh. An example of this
OBB visualization for the HV characterization model is shown in Figure
\ref{fig:bad_hv_box}.

\begin{figure}[H]
  \centering
    \includegraphics[scale=0.3]{{obbs_wsr_0.95}.eps}
    \caption[Oriented leaf bounding boxes in a high valence region.]{View of an
      OBB containing many HV region triangles as well as other
      surface triangles. Blue box and triangles: leaf node bounding box and
      associated triangles. Several thousand triangles are represented in the
      solid blue region shown here. Red boxes: Other representative OBBs at the
      same depth in that tree.}
    \label{fig:bad_hv_box}
\end{figure}

Because there are more entities to partition in the HV region, it is expected
the deepest levels of the BVH will contain only OBB's bounding triangles in that
region. It was expected that leaf nodes of the BVH might contain many triangles
of the HV region, causing performance degradation of ray traversal in that many
triangles must be checked for intersection. These types of poorly formed leaf
nodes shift the complexity of the BVH traversal back toward a linear search -
which is sub-optimal. This feature of MOAB's OBB tree were observed, but
visualization of the BVH provided the ability to observe another characteristic
as well. Many leaf nodes containing large numbers of triangles in the HV region
also contained one or two large triangles outside of that region. The inclusion
of these large triangles significantly increases the probability that a
hierarchy traversal will visit that leaf node and thus all of the triangles
contained by that leaf node. This artificial increase in the HV regions
cross-section greatly exacerbates the already poorly created nodes in the tree.

\begin{figure}[H]
  \begin{subfigure}[b]{0.5\textwidth}
    \includegraphics[width=\linewidth]{hv_study_moab_small_v.eps}
  \end{subfigure}
  \hfill
  \begin{subfigure}[b]{0.5\textwidth}
    \includegraphics[width=\linewidth]{hv_study_moab_adaptive_small_v.eps}
  \end{subfigure}
  \caption[Small scale study of the HV characterization using MOAB.]{A small scale version of the
    HV study in Figure \ref{fig:moab_hv_studies} using valences representative of those
    seen in DAGMC models using a linear scale.}
  \label{fig:moab_hv_studies_small_v}
\end{figure}

Due to the nature of the entity ratio heuristic used to divide nodes in the
tree, as the HV region becomes smaller more triangle centroids are shifted onto
one side of the median splitting planes used to divide the nodes which contain
portions of that region. If enough triangle centroids are on this side of the
plane, then the cost of the entity ratio evaluation will exceed the preset upper
limit of the cost (0.95 in MOAB) and the construction process will declare that
node a leaf node. The settings governing this split process can be altered in
MOAB, and changing the worst split ratio to 1.0 significantly improves the
average ray fire time in the HV characterization study, as seen in Figure
\ref{fig:moab_hv_studies}. While the values used for this study are helpful in
understanding the large-scale effects on MOAB's BVH algorithms, a small-scale
version of this study was also performed using a valence value more
representative of those seen in typically DAGMC models. The results of this study
exhibit the same trends as the large scale and provide information on
what the true performance degradation might be in DAGMC simulations.

As expected, the use of this setting largely removes the degradation in performance
caused by the HV region by forcing the continued splitting of entities
in the tree where large leaf nodes would have been created before. This
demonstrates that altering this setting works well for this mesh feature, but it
would be detrimental to the memory footprint of the overall hierarchy in the
general case, causing portions of the OBB tree to be deeper than necessary.

\subsection{Adaptive BVH Construction}\label{subsec:adaptive_construction}

One of the benefits to having a BVH tool which is part of a mesh database like
MOAB is the ability to query for more information about the mesh when
constructing hierarchies like the BVH. This information has been used to detect
HV regions in the mesh and adapt BVH construction to improve the
hierarchy quality in these areas.

\subsubsection{High Valence Detection}\label{subsubsec:hv_detection}

A simple algorithm is used to determine whether or not the entities inside a
leaf node are part of a HV region. Any vertex connected to more than a
user-defined proportion, $\alpha$, of the entities in a given leaf node will be
considered a HV region, indicating that an alternate build method or build
settings should be applied.

\begin{lstlisting}[language=Python,basicstyle=\tiny,caption={Algorithm for detecting HV regions.},label={alg:hv_detect},captionpos=b]
  def detect_hv_region(triangles, alpha):
      assert(a <= 1.0 and a > 0.0)
      connectivity = get_connectivity(triangles)

      for vertex in connectivity:
          # get all entities of dim 2 adjacent to the vertex
          adj_entities = get_adjacencies(vert, to_triangles)

          # determine the number of non-adjacent entities
          overlap = triangles - adj_entities

          if size(overlap)/size(triangles) < 1.0 - alpha:
              return true
      return false
\end{lstlisting}

\subsubsection{Implementation}\label{subsec:adaptive_construction_implementation}

First, MOAB's BVH constructor was modified to tag poorly
formed leaf nodes in the tree. This option will apply a tag to any leaf nodes
which contain more entities then specified in the settings for the tree. These
nodes are then revisited for further refinement later in the build process.

For handling of these poorly formed leaf nodes, a new class was created in MOAB
named the \textit{BVHRefiner}. This class visits each leaf node tagged by the
build process to determine if further refinement is appropriate based on the
available set of mesh features it is capable of adapting to. For each mesh feature
added to the BVH Refine class, a detection method and build method is
required. This class applies these detection methods and altered build methods
to resolve these leaf nodes into improved regions of the tree. The intent of
this design was to support the detection and adaptation to other pathological mesh
features in the future.

In the HV case, the refiner class was instructed to search for any vertex
connected to more than 80\% of the entities in that particular leaf node. If
this condition is met, the leaf node is declared part of a HV region and an
altered build method is applied. For the HV case, this build method has been
established by the characterization tests as the standard build algorithm with
the worst case splitting ratio set to the maximum value of 1.0.

\subsubsection{Application to the HV test model}

This adaptive build method was applied to the HV test model as before. The
results of this test can be seen in Figure \ref{fig:moab_hv_studies}. Using the
adaptive method, the average ray fire time is consistent across both valence and
relative area of the HV region and shows none of the stochastic behavior seen
when manually altering the tree's global build settings.

\subsubsection{Application to Production Models}

This method was applied to several DAGMC production models in order to determine
its effect on simulation run times during transport.

\begin{table}[H]
  \centering
  \begin{tabular}{c c c c c c}
    \toprule
    \textbf{\thead{Model}} & \textbf{\thead{HV \\ regions}} & \textbf{\thead{Run Time \\ reduction}} & \textbf{\thead{Build time \\ increase}} & \textbf{\thead{HV Leaf Visit \\ Relative Frequency}} \\
    \hline
    FNG            & 514                 & 24.2\%                      & 18.5\% & 3.83 \% \\
    ATR            & 755                 & < 3\%                       & 22.9\% & 0.07 \% \\
    UWNR           & 496                 & < 2\%                       & < 5\%  & 3.87 \% \\
    ITER           & 3522                & 29.4\%                      & 5.2\%  & 7.34 \% \\
    \bottomrule
  \end{tabular}
  \caption[Performance results for high valence region refinement in production models.]{Results of
    run time reduction in several DAGMC production models when applying the BVH
    refinement method.}
  \label{tab:bvhrefine_production_results}
\end{table}

As seen in Table \ref{tab:bvhrefine_production_results}, the ATR and UWNR
problem run time is decreased only marginally, but in the ITER and FNG models
the run time is reduced by $\approx\frac{1}{4}$. Given the outcome of this study
it might seem that the high valence regions are visited more often in the ITER
and FNG models, but information gathered during simulation using MOAB's mesh
tagging interface suggests otherwise. A sweep of the high valence parameter,
$\alpha$, for these models is shown in Figure \ref{fig:hv_parameter_study_moab}
which reflects the performance impact shown in Table
\ref{tab:bvhrefine_production_results}. It also describes the relationship
between the simulation run time and the high valence parameter value in the ITER
and FNG models. Even for a relatively high $\alpha$ parameter of 0.9, a
significant reduction in the run time is seen in these models. As the value
decreases, the run time is futher reduced to nearly 30\% of the maximum run time
in the study. The large change at a high value of $\alpha$ indicates that even
coarse detection of high valence regions has a measurable impact on performance.

\begin{figure}[H]
  \centering
  \includesvg{../images/hv_parameter_study_moab}{width=1.0\textwidth}
  \caption[High valence detection parameter study.]{Variation in run time for
    different HV detection parameters on a representative set of DAGMC models
    using the adaptive build method in MOAB.}
  \label{fig:hv_parameter_study_moab}
\end{figure}

\begin{sidewaysfigure}
  \centering
  \includegraphics[scale=0.45]{hv_study_emdag.eps}
  \includegraphics[scale=0.45]{hv_study_SIMD.eps}
  \includegraphics[scale=0.45]{hv_study_SIMD_OBB.eps}
  \includegraphics[scale=0.45]{hv_study_mpbvh_mixed.eps}
  \caption[HV characterization studies using EmDAG and MPBVH.]{HV characterization results for all SIMD-enabled ray tracing
    kernels. Top Left: Results of the HV study for EmDAG. Top Right: Results of
    the HV study using the MPBVH with AABBs. Bottom Left: Results using the
    MPBVH with OBBS. Bottom Right: Results for the MPBVH with an adaptive build
    method which applies OBBs in HV regions.}
  \label{fig:simd_hv_studies}
\end{sidewaysfigure}

The information on the frequency of HV leaf visits in Table
\ref{tab:bvhrefine_production_results} was collected on regions of the triangle
mesh identified as high valence during BVH construction as well as
simulation. Leaf nodes in MOAB's OBB Tree determined to be part of high valence
regions with an HV parameter, $\alpha$, equal to 0.5 were tagged. A counter was
incremented each time one of these tagged HV leaf nodes was visited in
simulation, along with counters for the number of total nodes visited and the
total number of leaf nodes visited. The adaptive building method was not applied
to these simulations to avoid biasing the values for leaf node visits. This
lends some insight into the impact of HV regions on DAGMC simulation
performance. It is interesting to note that, in all of these models, HV leafs are
visited rather infrequently, yet they still have a significant impact on the
performance of the simulation. This isn't surprising given the severity of the
ray fire performance degredation seen in Figure \ref{fig:moab_hv_studies}.

\subsection{Embree's Ray Tracing Kernel}\label{sec:emdag_hv_study}

For all of the tests and simulations performed in Chapter \ref{ch:simd_bvh},
EmDAG was much faster than DAGMC. Using the same ray fire test program in EmDAG,
the HV characterization study was performed with somewhat surprising results.

%% Upon visually inspecting the faceted FNG model, it was
%% seen to contain many HV regions. As an artifact of the variance
%% reduction used in the intended analysis of this model, many planes were inserted
%% in the model in order to break up large cells with highly varying particle
%% intensities. Where these planes intersect the cylindrical volumes of the model,
%% many HV regions result as can be seen in Figure
%% \ref{fng-faceted-models}. As a result it became a curiosity as to whether or
%% not the HV regions were being handled better by EmDAG than they were
%% by DAGMC. In order to test this, the same programs used to do the HV
%% vertex study were built using EmDAG and the parameter study of the relative high
%% valence area and valency was performed. The results in Section \ref{sec:emdag_hv_study}
%% show that EmDAG also struggles with these HV regions. In the worst
%% scenario there is a degradation by two orders of magnitude compared to the best
%% case scenario which is similar to what seen in the unmodified MOAB ray
%% tracer. Additionally, it shows degraded performance in the same way that DAGMC
%% was initially expected to falter - with increasing HV area and
%% valency. This is likely due to the nature of the heuristics used by Embree to
%% construct its acceleration data structures.  Unlike MOAB, however, the BVH
%% building parameters are not as openly available via Embree's interface.There is,
%% however, an option to reduce the size of the HV regions in the mode
%% within the faceting algorithm by defining a length tolerance.

%% \begin{figure}[H]
%%   \small
%%   \begin{center}
%%     \includegraphics[scale=0.3, trim = 200 0 100 0]{fng_facet_tol.png}
%%     \includegraphics[scale=0.25]{fng_len_tol.png}
%%     \caption{The FNG faceted model without (left) and with (right) the length
%%       tolerance applied.}
%%     \label{fng-faceted-models}
%%   \end{center}
%% \end{figure}

%% The length tolerance is a maximum length for any facet edge returned by the CAD
%% engine's faceting algorithm. Providing this value to the preprocessing tool
%% comes at the cost of many more triangles than when supplying only a faceting
%% tolerance. The difference in facet structure between these models can be seen in
%% Figure \ref{fng-faceted-models}.

%% \begin{table}[H]
%%   \small
%%   \begin{center}
%%         \begin{tabular}{|c|c|c|c|c|}
%%       \hline
%%       \textbf{Implementation} & \textbf{ctme (min)} & \textbf{wall time (min)} & \textbf{ratio} & \textbf{lost} \\
%%       \hline
%%       MCNP5 & 209.92 & 205.99 &  1.00 & 0 \\
%%       \hline
%%       DAG-MCNP5 (lt) & 974.99 & 974.75 & 4.73 & 0  \\
%%       \hline
%%       EmDAG-MCNP5 (lt) & 257.49 & 257.60  & 1.25 & 247 \\
%%       \hline
%%     \end{tabular}
%%     \caption{A comparison of transport on the FNG model using a 14.1 MeV
%%       volumetric source over 100M histories for native MCNP, DAG-MCNP, and
%%       EmDAG-MCNP. The DAGMC model was faceted using a length tolerance to
%%       mitigate the effect of HV regions.}
%%     \label{fngemdag}
%%   \end{center}
%% \end{table}

%% By generating a faceted model using the combination of the length and faceting
%% tolerances it was hoped that there would be a marked increase in performance
%% using the EmDAG system and the performance did indeed improve by ~15\%. Due to
%% the increased number of overall triangles on these planar surfaces, there may be
%% competing forces at play. As the length tolerance is reduced, the HV
%% areas will also be reduced, but the overall number of triangles will increase -
%% resulting in inherently deeper BVH and longer traversals. Conversely, as the
%% length tolerance is increased, the number of HV region areas are
%% increase, but the number of redundant triangles is reduced improving the average
%% BVH traversal time enough compensate for a few more rays entering HV
%% regions. This observation leads to the idea that length tolerance of the FNG
%% model could then be optimized. This optimization study, while interesting, will
%% vary model to model and the results will be complex in nature, depending on the
%% underlying geometry and geometry adjacent to those regions, etc. In light of the
%% HV study results indicating that BVH building parameters can be altered
%% to improve performance and accommodate these HV regions, it seems that
%% a better solution is to follow that path over alteration of the mesh globally in
%% the model.

%% This study indicates that the simulation improves when faceting with a length
%% tolerance, but isn't conclusive about the impact of HV regions on
%% EmDAG's ray tracing performance. To better understand this impact, a
%% characterization of EmDAG's reponse for HV regions was conducted.

\subsection{High Valence Characterization}

The same test described in Section \ref{sec:hv_study_MOAB} was performed using
the ray fire test program compile with using EmDAG to fire rays. A different
behavior was expected when using Embree to construct the underlying hierarchies
due to its use of the SAH. Figure \ref{fig:simd_hv_studies} contains the results
of this test run. Using the Embree kernel, the performance degrades in direct
proportion to both valence and the relative area of the HV region. This data
presents the behavior originally expected of MOAB's BVH. Unlike MOAB however,
Embree's use of the surface area heuristic prevents the artificial increase in
probability of visiting triangles in the HV region. Larger triangles adjacent to
this region are more readily separated from the leaf due to the additional cost
they add by increasing a bounding box's surface area and in turn its evaluated
cost. Separation of triangles in the HV region itself is still difficult when
restricted to axis-aligned candidate split planes.

While this data provides evidence that HV regions are problematic for
production-level ray tracing kernels, it is difficult to employ any adaptive
tree construction techniques. Without access to the underlying mesh
representation of the triangle surface, it is difficult to detect HV regions as
implemented in MOAB's OBB tree. This is both a strength and weakness of Embree's
design in that it can build highly efficient data structures using only
primitive point and connectivity data, but it has no infrastructure in place to
interrogate the mesh more deeply. Methods for detecting and adapting to these HV
regions are addressed using the MPBVH, a system with similar characteristics
but with more access to the mesh interface. Due to the similarity in design and
use of AABBs, the MPBVH will act as something of a surrogate for the EMDAG in
terms of its response to HV regions.

\section{Mixed Precision Bounding Volume Hierarchy}\label{sec:simd_hv_study}

\subsection{High Valence Characterization}

The MPBVH kernel created by the author has a similar trend to Embree's kernel
where ray fire times increase proportionally to both the valence and size of the
HV region as seen in Figure \ref{fig:simd_hv_studies}. The author's BVH applies
a modified form of the surface area heuristic as described in Section
\ref{sec:ssah}. Near HV regions this heuristic is able to separate large
triangles from the HV region in the same way as the unmodified surface area
heuristic from Section \ref{sec:heuristics}, but it fails to create a
well-structured tree for triangles that are part of the HV area.

\subsection{Visualization and Diagnosis}

\begin{figure}
  \centering
  \includegraphics[scale=0.5]{hv_leaf_simd_bvh.png}
  \caption[Axis-aligned bounding box in the high valence region.]{MPBVH
    Axis-Aligned leaf node for the HV test model with area fraction 0.5 and a
    valence of 100.}
  \label{fig:hv_leaf_simd_bvh}
\end{figure}

Both Embree and the MOAB SIMD BVH have the shared characteristic of maximum leaf
size of eight primitives due to the way the leaves are encoded. This removes the
possibility that large numbers of triangles in leaf nodes as the cause of
performance degradation, which was the case for MOAB's OBB Tree. For Embree and
the MPBVH, the largest cause of performance degradation is overlapping regions
of the leaf nodes.

Because both of these implementations use AABBs, bounding of high aspect ratio,
off-axis triangles results in bounding boxes with a considerable amount of empty
space in them. An example of such a leaf can be seen in Figure
\ref{fig:hv_overlap_simd_bvh}. In HV regions, this results in the same
space being occupied by a high number of leaf bounding boxes. If a ray is fired
into these overlapping leaves, the end result is a large number of leaf nodes,
and in turn, triangles, visited.

\begin{figure}
  \centering
  \begin{subfigure}[b]{.5\textwidth}
    \centering
    \includegraphics[scale=0.37]{hv_overlap_simd_bvh.png}
  \end{subfigure}%
  \hfill
  \begin{subfigure}[b]{.5\textwidth}
    \centering
    \includegraphics[scale=0.37]{hv_obbs.png}
  \end{subfigure}
  \caption[Bounding boxes of the MPBVH in the high valence
    region.]{Visualization of both axis-aligned and oriented boxes surrounding
    low aspect ratio, off-axis triangles.}
  \label{fig:hv_overlap_simd_bvh}
\end{figure}

To alleviate the effect of the overlapping AABBs in this region, OBBs were
implemented as part of the MPBVH. Figure \ref{fig:simd_hv_studies} shows the
results of the HV characterization study using only OBBs. Because the simplified SAH heuristic is able to separate
large triangles exterior to the HV region into different leaf nodes and the
maximum leaf node size is predetermined, scaling very similar to the MOAB OBB
implementation after HV refinement is applied can be seen, though the overall
speed is somewhat improved due to the single precision implementation.

\subsection{Adaptive BVH Construction}

\subsubsection{OBB Implementation}

The same co-variance method used in MOAB to construct OBBs was applied in the
MPBVH \cite{Weghorst_1984}, but the storage technique used differs in order to
accommodate the SIMD programming involved in the BVH traversal. OBB nodes are
stored as scaled, affine transformations of the global problem space and the
box's lower left corner is stored as a scaled reference point in the oriented
coordinate system. When a ray is intersected with a node it is transformed and
scaled at the same time, but separately, for each of the four OBBs the node
represents. A reciprocal direction is then calculated with respect to the
oriented axes of each box. After this transformation, intersection values and
distances are then returned in the same way they are calculated for a node of
AABBs \cite{Wald_2014}.

As discussed in Chapter \ref{ch:background}, OBB nodes contain additional
information in the form of the affine space transformation and are more
computationally expensive when computing ray transformations. Some of this
computational cost is avoided by incorporating the spatial scaling of the node
into both the affine space and reference point to avoid the additional
computational cost of scaling the parametric values of the ray intersection
later in the calculation.

\subsubsection{OBB Ray Fire Testing}

Tests of the raw ray fire speed using only OBBs were performed using the
MPBVH, which can be seen in Figure
\ref{fig:rf_test_results_obbs}. These tests were conducted primarily as
verification that the exclusive use of OBBs results in a slower ray fire times.

\begin{figure}[H]

  \begin{subfigure}{0.5\textwidth}
    \includegraphics[width=\linewidth]{mpbvh_rf.eps}
  \end{subfigure}%
  \hfill
  \begin{subfigure}{0.5\textwidth}
    \includegraphics[width=\linewidth]{mpbvh_rf_obb.eps}
  \end{subfigure}

  \caption[Ray fire timings for the MPBVH with oriented bounding boxes.]{Ray
    fire tests on three representative DAGMC volumes. Each data point represents
    the average ray fire time for 600k randomly directed rays from the origin of
    each volume. Left: MPBVH with AABBs only. Right: MPBVH with OBBs only.}
  \label{fig:rf_test_results_obbs}
\end{figure}

On average, the ray fire times using OBBs only were about two times slower
than those using only AABBS. The combination of the MPBVH leaf
examination in HV areas with the slower ray fire times of OBBs in the
common case leads to the conclusion that OBBs can be beneficial to ray fire
times, but only if they are used in regions of the model where sibling
AABBs contain large overlaps for these pathological mesh features.

\subsubsection{A Mixed AABB/OBB BVH}

The solution to HV regions when using the SIMD BVH
kernel proposed by the author is to apply OBBs only in regions determined to be
HV using the same detection method described in Section
\ref{subsubsec:hv_detection}. Large leaf nodes being split into smaller nodes
will apply oriented bounding boxes to contain entities if the set of triangles
is determined to be a HV region using the same method discussed in
Section \ref{subsubsec:hv_detection} for MOAB's OBB tree. The results using the mixed tree with
OBBs applied in HV regions are shown in Figure \ref{fig:simd_hv_studies}. A
small-scale of this study is also provided in Figure
\ref{fig:simd_hv_studies_small_v} for valences more commonly seen in DAGMC
models.
The
mixed tree implementation shows some slight degradation in speed with both area
fraction and valence, but overall timing is significantly better, with the worst
case timing still beating out the best case for the OBB-only characterization
test. This indicates that the AABBs are accelerating intersections higher up in
the tree while the OBBs resolve the HV region with minimal overlap,
resulting in an overall improvement in the run times for these regions.

\begin{figure}[H]
  \begin{subfigure}[b]{0.5\textwidth}
    \includegraphics[width=\linewidth]{hv_study_simd_small_v.eps}
  \end{subfigure}
  \hfill
  \begin{subfigure}[b]{0.5\textwidth}
    \includegraphics[width=\linewidth]{hv_study_simd_adaptive_small_v.eps}
  \end{subfigure}
  \caption[Small scale study of the HV characterization using the MPBVH.]{A small scale version of the
    HV study in Figure \ref{fig:simd_hv_studies} using valences representative of those
    seen in DAGMC models using a linear scale.}
  \label{fig:simd_hv_studies_small_v}
\end{figure}

To support a tree containing both AABBs and OBBs, additional encoding of
interior nodes is required so that the appropriate node intersection methods are
applied during traversal. Axis-Aligned and Oriented nodes are identified using
the two remaining bit configurations available for node definitions by
setting the appropriate bits in the node reference objects. These node masks are
stripped from the node reference's integer value to retrieve the pointer to the
node objects themselves with little added overhead in the traversal process.

\subsubsection{Application to Production Models}

The Mixed MPBVH was applied to the same set of production transport tests as the
AABB MPBVH in Section \ref{subsec:mpbvh_production_transport}. Timing results of
these simulations can be found in Figure \ref{fig:hv_parameter_study_mpbvh}.

\begin{figure}[H]
  \centering
  \includesvg{../images/hv_parameter_study_mpbvh}{width=1.0\textwidth}
  \caption[High valence detection parameter study using the MPBVH.]{Variation in run time for
    different HV detection parameters on a representative set of DAGMC models
    using the MPBVH.}
  \label{fig:hv_parameter_study_mpbvh}
\end{figure}

The application of OBBs in HV regions makes little difference in the simulation
run times of ATR or UWNR, but in the FNG model and ITER model the run times are
reduced by up to ~40\% with little additional build times in the BVH and
minimal increase in the memory footprint by replacing some of the AABBs with
OBBs. This reflects the behavior seen in results of Table
\ref{tab:bvhrefine_production_results} for simulations using MOAB's OBB tree. A
study on the HV leaf visit frequency was not performed here due to a limited
ability to mark HV leaf nodes in the MPBVH system.

%\begin{table}
%  \small
%  \begin{center}
%  \begin{tabular}{lcccccccc}
%    \toprule
%    Model & \thead{Regions \\ Identified} & \multicolumn{3}{c}{HV Area
%      ($cm^{2}$)} & \multicolumn{3}{c}{HV Valence} & \thead{HV Leaves / \\ Leaf
%      Visit \%} \\
%         &      & Max    & Min   & Avg    & Max  & Min & Avg    &      \\
%    \hline
%    FNG  & 514  & 1786.3 & 0.013 & 12.91  & 521  & 14  & 179.9  & 3.83 \\
%    ATR  & 836  & 52.74  & 0.01  & 1.86   & 519  & 14  & 58.735 & 0.07 \\
%    UWNR & 499  & 168479 & 0.03  & 2496.3 & 1041 & 31  & 31.63  & 3.87 \\
%    ITER & 3522 & 853827 & 0.02  & 1363.4 & 3082 & 12  & 93.3   & 7.34 \\
%    \bottomrule
%  \end{tabular}
%  \end{center}
%  \caption[High valence region simulation statistics.]{High valence
%    identification and visit statistics for several DAGMC production models. The
%    high valence parameter, $\alpha$, was set to 0.5 for this study.}
%  \label{tab:hv_simulation_stats}
%\end{table}

\subsubsection{Alternative Surface Meshing Methods}

In addition to the faceting tolerance discussed in Section \ref{sec:CAD-MCRT},
other parameters can be applied to the tessellation process in CUBIT/Trelis. One
such parameter is the length tolerance. The length tolerance places an upper
limit on the edge length for any triangle in the resulting surface mesh. Passing
this parameter to the tessellation algorithm along with a faceting tolerance
tends to create more triangles with an aspect ratio $\approx 1$. It also tends
to generate more triangles, particularly when the length tolerance specified is
smaller than the characteristic length of surfaces in the model. Limited edge
lengths also have the effect of reducing the area of HV regions as seen in
Figure \ref{fig:fng_ft-lt} where both the faceting tolerance and length
tolerance were applied to the FNG model. In most cases, the valence of the HV
regions are reduced as well. This is a by-product of the tessellation
algorithm's avoidance of high-aspect ratio triangles. Given that the
performance degradation of ray fire times in the MPBVH scales with both the
valence and HV area, applying a length tolerance during tessellation may be
another pathway to improving performance in these models.

\begin{figure}[H]
  \begin{subfigure}[t]{0.48\textwidth}
    \centering
    \includegraphics[scale=0.2]{fng_facet_tol.png}
    \caption{Faceting Tolerance Only}
  \end{subfigure}
  \hfill
  \begin{subfigure}[t]{0.48\textwidth}
    \centering
    \includegraphics[scale=0.2]{fng_len_tol.png}
    \caption{Faceting and Length Tolerance}
  \end{subfigure}
  \caption[Length tolerance faceting example.]{The effect of applying only the
    faceting tolerance (a) vs. the application of both a faceting tolerance and
    length tolerance (b) in the FNG model. HV regions are separated and made
    smaller when using both tesellation parameters.}
  \label{fig:fng_ft-lt}
\end{figure}

The same set of production test models from Table
\ref{tab:bvhrefine_production_results} were faceted using both faceting and
length tolerances. The corresponding simulations were then performed using DAGMC
with the MPBVH kernel with BVH refinement disabled, meaning it will apply AABBs
only during BVH construction. There are competing factors at play in this
analysis. Because the models will contain many more triangles, the BVH will
inherently become deeper, resulting in a higher number of nodes visited per
traversal. Conversely, the overall number of HV regions will increase, but their
area and valence will be significantly reduced.

\begin{sidewaystable}[p]
  \centering
  \makebox[\textwidth][c]{
  \begin{tabular}{c c c c c c}
    \toprule
    \textbf{\thead{Model}} & \multicolumn{2}{c}{\textbf{\thead{Triangles (M)}}} & \multicolumn{2}{c}{\textbf{\thead{Memory Usage (MB)}}} & \textbf{\thead{Timing Ratio \\ (Faceting Tol. / \\ Faceting \& Length Tol.)}} \\
    &  \thead{Faceting \\ Tolerance} & \thead{Faceting \& \\ Length Tolerance} & \thead{Faceting \\ Tolerance} & \thead{Faceting \& \\ Length Tolerance} & \\
    \hline
    FNG  & 1.17  &  1.76  & 152 & 463  & 1.32 \\
    ATR  & 4.95  & 30.00 & 593 &  2785 & 0.83 \\
    UWNR & 3.34  & 10.10 & 376  & 1770 & 1.01 \\
    ITER & 39.63 & 42.39 & 3841 & 6654 & 1.31 \\
    \bottomrule
  \end{tabular}
  }
  \caption[Length tolerance production model study.]{The results of production
    model simulations when applying both a faceting tolerance and length
    tolerance during model tessellation to reduce HV region severity.}
  \label{tab:length_tol_production_study}
\end{sidewaystable}

Table \ref{tab:length_tol_production_study} shows the results of this study. A
length tolerance of 10 was applied to all production models with the exception
of the ITER model where 25 was used. For all models, results using facet
tolerance only tessellations were not numerically the same as those also
applying the edge length tolerance as well. The same numerical answer for
different tessellations is not expected and results for the models were
statistically similar in all corresponding simulations. In agreement with the
BVH refinement study, the greatest effect on performance was seen in the FNG and
ITER simulations where the run times were reduced by $\approx30\%$. In contrast,
the ATR simulation became almost $20\%$ worse. This is likely caused by the
dramatic increase in the number of triangles for this model which could be
mitigated by increasing the specified length tolerance. It is difficult to know
a priori what faceting tolerance is optimal when tessellating models, but this
study shows that an alternative meshing scheme may be another solution to
mitigating the effect of HV regions on simulation performance.

When using BVH refinement to address HV region performance, the acceleration
data structure is altered to better suit the tessellation. Whereas application
of the length tolerance alters the tessellation to better suit the data
structure by producing triangles more amenable to use of AABBs and reducing HV
region severity. Each approach has its merits. BVH refinement requires no
modification of the input tessellation, but it does require a way to gather more
information about the mesh structure. Alternate tessellation schemes can produce
more friendly to the BVH data structure, but may require additional memory - a
notable constraint in the context of this work (see Section
\ref{sec:mc_mem}). In the future, local re-tessellation of these regions, either
as a preprocessing step or during BVH construction, could provide reduced HV
severity similar to the length tolerance faceting without a dramatic increase in
memory requirements for simulation.

\section{Summary}

This chapter introduced performance degradation caused by a tessellation feature
seen in engineering models for CAD-based MCRT-t. A test model was then
developed to characterize and study the underlying cause of this degradation for
several ray tracing systems. In MOAB's OBB tree, the main cause was leaf nodes
containing large numbers of triangles. The cause of poor ray tracing performance
in this system was a combination of the tree's design and default splitting
heuristic. A simple HV detection algorithm was presented and applied in a
solution where build settings of the splitting heuristic are adjusted for
portions of the tree bounding HV regions. This method was then verified to
remove performance degradation of ray tracing performance in these regions. A
similar process was then repeated for both EmDAG and MPBVH.

In the MPBVH, and presumably in EmDAG, the exclusive use of AABB nodes results
in large overlaps between child boxes. Many negative triangle intersections
result from these overlaps, a similar effect to containing many
triangles in a single leaf node. The solution proposed and verified by the
author is the use of OBBs only in HV regions by applying the same HV detection
method as was used in the MOAB OBB tree. It is important to note, that this was
only possible in the MPBVH due to it's application alongside MOAB, a fully
formed mesh database. The use of mesh-specific concepts such as element
adjacencies makes this detection method simple and efficient. This work was not
duplicated in Embree due to the difficulty involved in obtaining the same set of
information and application of a mixed BVH for ray tracing on triangle elements.

Finally, a study of the adaptive build method to production models is presented
for understanding of the HV parameter's effect on simulation run times. Little
impact was found for some models while a significant reduction was seen in
others. It was also was found that these run times are significantly reduced
despite the fact that a very small number of rays are intersected with triangles
in HV regions as shown in Table \ref{tab:bvhrefine_production_results}.

\section{Future Work}

For the models studied in this chapter, any HV detection parameter below 1.0 was
shown to be effective in reducing simulation run times. This parameter could be
studied and optimized using a broad range of test cases to determine the best
value for use in the general case.

Alternative methods to reducing the HV performance pathology could be explored
as well. Here, BVH data structures were modified to better suit the HV mesh
feature. Conversely, the HV regions could also be modified to better suit the
BVH. A re-meshing of the HV region to contain a more uniform tessellation would
allow a BVH of AABBs to maintain traversal performance without modification to
the BVH build, though this would presumably come at the cost of more triangles
in the model. Re-meshing of HV regions was not explored in this work due to the
concerns for the additional memory cost outlined in Section \ref{sec:mc_mem}.


%-- coding: UTF-8 --
%!TEX program = Xelatex
%%%%%%%%%%%%%%%%% DO NOT CHANGE HERE %%%%%%%%%%%%%%%%%%%% {
\documentclass[12pt,letterpaper]{article}
\usepackage{fullpage}
\usepackage[top=2cm, bottom=4.5cm, left=2.5cm, right=2.5cm]{geometry}
\usepackage{amsmath,amsthm,amsfonts,amssymb,amscd}
\usepackage{lastpage}
\usepackage{enumerate}
\usepackage{fancyhdr}
\usepackage{mathrsfs}
\usepackage{xcolor}
\usepackage{graphicx}
\usepackage{listings}
\usepackage{hyperref}
\usepackage[UTF8]{ctex}
\usepackage[english]{babel} % comment this if you want "more" Chinese

\hypersetup{%
  colorlinks=true,
  linkcolor=blue,
  linkbordercolor={0 0 1}
}

\setlength{\parindent}{0.0in}
\setlength{\parskip}{0.05in}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% }

%%%%%%%%%%%%%%%%%%%%%%%% CHANGE HERE %%%%%%%%%%%%%%%%%%%% {
\newcommand\course{CS000 某课程}
\newcommand\semester{Fall 2019}
\newcommand\hwnumber{1}                 % <-- ASSIGNMENT #
\newcommand\StudentName{Keith Null}           % <-- YOUR Name
\newcommand\StudentID{000000000}           % <-- STUDENT ID #
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% }

%%%%%%%%%%%%%%%%% DO NOT CHANGE HERE %%%%%%%%%%%%%%%%%%%% {
\pagestyle{fancyplain}
\headheight 35pt
\lhead{\StudentName \\ \StudentID}
\chead{\textbf{\Large Assignment \hwnumber}}
\rhead{\course \\ \semester}
\lfoot{}
\cfoot{}
\rfoot{\small\thepage}
\headsep 1.5em
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% }

\begin{document}
    \section*{Part 1}
        \subsection*{Question 1.3}
            \begin{proof}
                Okay, I can prove this.
            \end{proof}
        \subsection*{Question 1.7}
            if $x = 1$, then we have
            \begin{align*}
                f(x) & = x^2 + 2x + 1\\
                      & = (x + 1)^2\\
                      & = 4^{\log_2{(x + 1)}}\\
                      & = 4^1\\
                      & = 4
            \end{align*}
            Done!
    \newpage
    \section*{Part 2}
        \subsection*{Question 4.2}
            This question has multiple subquestions:
            \begin{enumerate}[a.]
                \item This one is trival. I can do it in $O(n)$ time.
                \item Ummm, this is also not difficult.
                \item Oh no, I can't figure this out at all!
            \end{enumerate}
        \subsection*{Question 4.7}
            Let me solve this one in Chinese. \\
            让我用中文来解答这道题目。
\end{document}


\subsection{Full reserve banking}

Let’s introduce a banker to those villagers, who sets up First Shell Bank. This bank is simply a location to store shells. This activity doesn’t really change anything. If Alice needs another fishing rod she still as to persuade the same people to lend her the money, although now this will just involve putting the shells in a different box in the bank.

This bank keeps all of its assets as reserves, and so cannot itself lend to Alice.


%%
%% This is file `./samples/shortsample.tex',
%% generated with the docstrip utility.
%%
%% The original source files were:
%%
%% apa6.dtx  (with options: `shortsample')
%% ----------------------------------------------------------------------
%%
%% apa6 - A LaTeX class for formatting documents in compliance with the
%% American Psychological Association's Publication Manual, 6th edition
%%
%% Copyright (C) 2011-2017 by Brian D. Beitzel <brian at beitzel.com>
%%
%% This work may be distributed and/or modified under the
%% conditions of the LaTeX Project Public License (LPPL), either
%% version 1.3c of this license or (at your option) any later
%% version.  The latest version of this license is in the file:
%%
%% http://www.latex-project.org/lppl.txt
%%
%% Users may freely modify these files without permission, as long as the
%% copyright line and this statement are maintained intact.
%%
%% This work is not endorsed by, affiliated with, or probably even known
%% by, the American Psychological Association.
%%
%% ----------------------------------------------------------------------
%%
\documentclass[jou]{apa6}

\usepackage[american]{babel}

\usepackage{csquotes}
\usepackage[style=apa,sortcites=true,sorting=nyt,backend=biber]{biblatex}
\DeclareLanguageMapping{american}{american-apa}
\addbibresource{bibliography.bib}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Discrete Structures
%% The start of RBS stuff
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Working internal and external links in PDF
\usepackage{hyperref}
% Extra math symbols in LaTeX
\usepackage{amsmath}
\usepackage{gensymb}
\usepackage{amssymb}
% Enumerations with (a), (b), etc.
\usepackage{enumerate}

\let\OLDitemize\itemize
\renewcommand\itemize{\OLDitemize\addtolength{\itemsep}{-6pt}}

\usepackage{etoolbox}
\makeatletter
\preto{\@verbatim}{\topsep=3pt \partopsep=3pt }
\makeatother

% These sizes redefine APA for A4 paper size
\oddsidemargin 0.0in
\evensidemargin 0.0in
\textwidth 6.27in
\headheight 1.0in
\topmargin -24pt
\headheight 12pt
\headsep 12pt
\textheight 9.19in

\title{Discrete Structures (W1): Boolean Expressions}
\author{Kalvis}
\affiliation{RBS}

\leftheader{Discrete Structures (W1)}

\abstract{
You will compile a sample LaTeX document to create
math expressions easily and to satisfy the APA v6 style.
You will also manipulate Boolean expressions on paper and with the Coq.
}

\keywords{\LaTeX, APA style, Coq, Boolean expressions}

\begin{document}
\maketitle

{\em Walk-throughs} are short exercises that we do together. Their
aim is to practice technical skills.

{\bf (W1.1)} Set up MiKTeX and Coq software.

{\bf (W1.2)} Create an APA compliant document with some math
in LaTeX and create a PDF.

{\bf (W1.3)} Identify 6 Boolean operations. Build
their truth tables.

{\bf (W1.4)} Translate English into propositional logic.

{\bf (W1.5)} Use precedence and associativity to draw abstract and concrete syntax trees.

{\bf (W1.6)} Run CoqIDE, check types in Coq, including atomic types,
tuples, function types.

{\bf (W1.7)} Build truth tables for Boolean expressions.

{\bf (W1.8)} Rewrite Boolean expressions as Disjunctive Normal Form (DNF).

{\bf (W1.9)} Prove propositional tautologies with Coq.

{\bf (W1.10)} Reduce word problems to Boolean satisfiability problems.

\section{(W1.1) MiKTeX and Coq}

{\em Note.} Lab computers on the 4th floor should have these
tools installed.
If you wish to run these tools on another Windows OS machine,
make sure you have administrator access (for Coq) and follow
these steps:

\begin{itemize}
\item Download MiKTeX from \url{https://miktex.org/download}
(file name {\tt basic-miktex-2.9.7269-x64.exe}).
\item Visit \url{https://coq.inria.fr/download}.
\item Click on "Coq 8.10.2 is out" and "8.10.2 release of Coq" links.
Download and run {\tt coq-8.10.2-installer-windows-x86\textunderscore{}64.exe}.
\item Create a shortcut on your desktop to run
{\tt c:\textbackslash{}Coq\textbackslash{}bin\textbackslash{}coqide.exe}
\end{itemize}

For Linux or OS X, please ask instructor.

\section{(W1.2) Create and Compile a LaTeX Document}

\begin{itemize}
\item Get $2$ source files.
You can visit \url{https://ctan.org/pkg/apa6} (download and
unpack ZIP, locate {\tt shortsample.tex} and
{\tt bibliography.bib} in subdirectory "samples").
\item Also visit \url{https://bit.ly/2MX7Z09} \textendash
this directory will contain
LaTeX files for our walk-throughs and homeworks. Then compile:
\begin{verbatim}
xelatex shortsample
biber shortsample
xelatex shortsample
\end{verbatim}
\end{itemize}

\section{(W1.3) Identify 6 Boolean operators}

Draw or review truth tables for the following Boolean operators
\parencite[see][p.4]{Rosen2019}.

\begin{itemize}
\item $A \wedge B$ (read: $A$ {\bf and} $B$).
\item $A \vee B$ (read: $A$ {\bf or} $B$).
\item $\neg A$ (read: {\bf not} $A$).
\item $A \rightarrow B$ ({\bf if} $A$ {\bf then} $B$;
$A$ {\bf implies} $B$).
\item $A \leftrightarrow B$ ($A$ {\bf if and only if} $B$;
$A$ {\bf equivalent to} $B$).
\item $A \oplus B$ ({\bf either} $A$ {\bf or} $B$;
$A$ {\bf plus} $B$ {\bf modulo $2$}).
\end{itemize}

\section{(W1.4) Translate English Sentences}

Write these sentences as short Boolean expressions,
explain the meaning of the letters used.

\begin{itemize}
\item Willy gets caught whenever he cheats.
\parencite[see][p.15, Ex24.d]{Rosen2019}.
\item My airplane flight is late iff I have to catch a connecting flight.
\parencite[see][p.16, Ex28.e]{Rosen2019}.
\item The apple trees will bloom if it stays warm for a week.
\parencite[see][p.15, Ex25.b]{Rosen2019}.
\item The trains run late on exactly those days when I take it.
\parencite[see][p.15, Ex27.e]{Rosen2019}.
\item $x=0$ if and only if $x^2 = 0$.
\item For a quadrangle to be a parallelogram it is {\bf necessary} that
both diagonals intersect in their middle points.
\item For a quadrangle to be a parallelogram it is {\bf sufficient} that
both diagonals intersect in their middle points.
\item You can pay using U.S. dollars or euros.
\parencite[see][p.15, Ex27.e]{Rosen2019}.
\end{itemize}

\section{(W1.5) Use precedence and associativity}

Precedence and associativity defines how to restore omitted parentheses
in expressions with more than one operation.
Evaluate from Python command-line:

\begin{itemize}
\item $\mathtt{2+2\%3}$. Is it $\mathtt{(2+2)\%3}$ or $\mathtt{2+(2\%3)}$?
Which is higher precedence \textendash{} addition or remainder?
\item $\mathtt{4*5**2}$. Is it $\mathtt{(4*5)**2}$ or $\mathtt{4+(5*2)}$?
Which is higher precedence \textendash{} multiplication or raising to a power?
\item $\mathtt{31//5//2}$.  Is it $\mathtt{(31//5)//2}$ or $\mathtt{31//(5//2)}$?
Is integer division left or right associative?
\item $\mathtt{2**3**4}$.  Is it $\mathtt{(2**3)**4}$ or $\mathtt{2**(3**4)}$?
Is raising to a power left or right associative?
\item Is addition left or right associative?
\end{itemize}

\section{(W1.6) Run CoqIDE}

Run samples from \textcite[][p.2--8]{Bertot2010}.

\section{(W1.7) Build Truth Tables}

Example: $(p \vee \neg(q \wedge ~r)) \rightarrow (\neg \neg r).$

{\bf (a)} Draw a truth table for the above Boolean expression.
How many combinations can the parameters
$(p,q,r)$ have?

{\bf (b)} Enter this as a Coq proposition using logical
connectives:
\begin{verbatim}
Variable P Q R: Prop.
Check (P \/ (Q /\ ~R)) -> (~~R).
\end{verbatim}

{\bf (c)} Define it as a function from $\mathtt{bool*bool*bool}$
to $\mathtt{bool}$ using prefix operations and compute
some values:
\begin{verbatim}
Require Import Bool.
Definition myfun
  (p:bool) (q:bool) (r:bool) : bool :=
  implb (orb p (negb (andb q (negb p))))
    (negb (negb r)).
Eval compute in myfun true true true.
\end{verbatim}

\section{(W1.8) Rewrite as a DNF}

For the previous Boolean expression write
its Disjunctive Normal Form (DNF).

\section{(W1.9) Prove Tautologies with Coq}

{\em Note.} We suggest that you experiment with
many existing proofs, try to modify them slightly.
This will help, if you attempt proving new things.

\begin{itemize}
\item Visit \url{https://bit.ly/37EMRUq} and run
the examples. They are identical to the CSE 191 Course Notes
\parencite[][p.12--21]{Knepley2019}.
\item Run the examples from the official Coq tutorial
\parencite[see][]{Nahas2012}.
\item Run the examples from the {\em Software Foundations}
book, see Vol.1 Chapter ``Logic in Coq'': \url{https://bit.ly/36DtDhy}.
\end{itemize}

\section{(W1.10) Reduce to Satisfiablility}

\begin{itemize}
\item Write a Boolean expression with $4$ variables $p_1,p_2,p_3,p_4$,
which is satisfied if and only if at least $2$ of these variables
have value {\tt true}.
\item Write a Boolean expression with $4$ variables, which is
satisfied if and only if at least $2$ of the variables are {\tt false}.
\item How many vertices, edges and faces has the polyhedron
shown in Figure 1? Is it regular? How many Boolean variables would
you need to write an expression that is satisfied if and only if
the polyhedron has a Hamiltonian path?
\end{itemize}

\begin{center}
\includegraphics[width=2in]{hamiltonian-paths.png}\\
{\em Figure 1: Hamiltonian Path.}
\end{center}

\printbibliography

\end{document}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% End of RBS stuff
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%
%% Copyright (C) 2011-2017 by Brian D. Beitzel <brian at beitzel.com>
%%
%% This work may be distributed and/or modified under the
%% conditions of the LaTeX Project Public License (LPPL), either
%% version 1.3c of this license or (at your option) any later
%% version.  The latest version of this license is in the file:
%%
%% http://www.latex-project.org/lppl.txt
%%
%% Users may freely modify these files without permission, as long as the
%% copyright line and this statement are maintained intact.
%%
%% This work is not endorsed by, affiliated with, or probably even known
%% by, the American Psychological Association.
%%
%%
%% This work is "maintained" (as per LPPL maintenance status) by
%% Brian D. Beitzel.
%%
%% This work consists of the file  apa6.dtx
%% and the derived files           apa6.ins,
%%                                 apa6.cls,
%%                                 apa6.pdf,
%%                                 README,
%%                                 APAamerican.txt,
%%                                 APAbritish.txt,
%%                                 APAdutch.txt,
%%                                 APAenglish.txt,
%%                                 APAgerman.txt,
%%                                 APAngerman.txt,
%%                                 APAgreek.txt,
%%                                 APAczech.txt,
%%                                 APAturkish.txt,
%%                                 APAendfloat.cfg,
%%                                 apa6.ptex,
%%                                 TeX2WordForapa6.bas,
%%                                 Figure1.pdf,
%%                                 shortsample.tex,
%%                                 longsample.tex, and
%%                                 bibliography.bib.
%%
%%
%% End of file `./samples/shortsample.tex'.