Archive for the ‘Mathematics’ Category
GPU Accelerated Expectation Maximization for Gaussian Mixture Models using CUDA
C, CUDA, and Python source code available on GitHub
Introduction
Gaussian Mixture Models [1, 435439] offer a simple way to capture complex densities by employing a linear combination of multivariate normal distributions, each with their own mean, covariance, and mixture coefficient, , s.t. .
Of practical interest is the learning of the number of components and the values of the parameters. Evaluation criteria, such as Akaike and Bayesian, can be used to identify the number of components, or nonparametric models like Dirichlet processes can be used to avoid the matter all together. We won’t cover these techniques here, but will instead focus on finding the values of the parameters given sufficient training data using the ExpectationMaximization algorithm [3], and doing so efficiently on the GPU. Technical considerations will be discussed and the work will conclude with an empirical evaluation of sequential and parallel implementations for the CPU, and a massively parallel implementation for the GPU for varying numbers of components, points, and point dimensions.
Multivariate Normal Distribution
The multivariate normal distribution With mean, , and symmetric, positive definite covariance, , is given by:
From a computational perspective, we will be interested in evaluating the density for values. Thus, a naive implementation would be bounded by due to the matrix determinate in the normalization term. We can improve upon this by computing the Cholesky factorization, , where is a lower triangular matrix [6, 157158]. The factorization requires time and computing the determinate becomes by taking advantage of the fact that . Further, we can precompute the factorization and normalization factor for a given parameterization which leaves us with complexity of the Mahalanobis distance given by the quadratic form in the exponential. Naive computation requires one perform two vector matrix operations and find the inverse of the covariance matrix with worst case behavior . Leveraging the Cholesky factorization, we’ll end up solving a series of triangular systems by forward and backward substitution in and completing an inner product in as given by , , and . Thus, our preinitialization time is and density determination given by . Further optimizations are possible by considering special diagonal cases of the covariance matrix, such as the isotropic, , and nonisotropic, , configurations. For robustness, we’ll stick with the full covariance.
To avoid numerical issues such as overflow and underflow, we’re going to consider throughout the remainder of the work. For estimates of the covariance matrix, we will want more samples than the dimension of the data to avoid a singular covariance matrix [4]. Even with this criteria satisfied, it may still be possible to produce a singular matrix if some of the data are collinear and span a subspace of .
Expectation Maximization
From an unsupervised learning point of view, GMMs can be seen as a generalization of kmeans allowing for partial assignment of points to multiple classes. A possible classifier is given by . Alternatively, multiple components can be used to represent a single class and we argmax over the corresponding subset sums. The utility of of GMMs goes beyond classification, and can be used for regression as well. The ExpectationMaximization (EM) algorithm will be used to find the parameters of of the model by starting with an initial guess for the parameters given by uniform mixing coefficients, means determined by the kmeans algorithm, and spherical covariances for each component. Then, the algorithm iteratively computes probabilities given a fixed set of parameters, then updating those parameters by maximizing the loglikelihood of the data:
Because we are dealing with exponents and logarithms, it’s very easy to end up with underflow and overflow situations, so we’ll continue the trend of working in logspace and also make use of the “logsumexp trick” to avoid these complications:
Where the term is the maximum exponential argument within a stated sum. Within the expectation stage of the algorithm we will compute the posterior distributions of the components conditioned on the training data (we omit the mixing coefficient since it cancels out in the maximization steps of and , and account for it explicitly in the update of ):
The new parameters are resolved within the maximization step:
The algorithm continues back and forth between expectation and maximization stages until the change in log likelihood is less than some epsilon, or a maximum number of user specified iterations has elapsed.
Implementations
Sequential Per iteration complexity given by . We expect because too many dimensions leads to a lot of dead space and too many components results in overfitting of the data. Thus, the dominating term for sequential execution is given by .
Parallel There are two natural data parallelisms that appear in the algorithm. The calculation of the and across points, while the probability densities and parameter updates have natural parallelisms across components. Each POSIX thread runs the full iterative algorithm with individual stages coordinated by barrier synchronization. Resulting complexity is given by for work coordinated across processors.
Massively Parallel The parallel implementation can be taken and mapped over to the GPU with parallelism taken across points and components depending on the terms being computed. There are several types of parallelism that we will leverage under the CUDA programming model. For the calculation of we compute each point in parallel by forming a grid of one dimensional blocks, and use streams with event synchronization to carry out each component in parallel across the streaming multiprocessors. Calculation of the loglikelihood and is done by computing and storing , then updating the storage for , and then performing a parallel reduction over to produce the loglikelihood. Parallel reductions are a core tasks are implemented by first standardizing the input array of points to an supremum power of two, then reducing each block using shared memory, and applying a linear map to the memory so that successive block reductions can be applied. Several additional approaches are discussed in [5]. Once the loglikelihood is computed, the streams are synchronized with the host and the result is copied from the device back to the host. To compute , is copied to a working memory and a maximum parallel reduction is performed. The resulting maximum is used in a separate exponential map for numerical stability when computing the parallel reduction of each component to yield . Updates to the mean and covariances are performed by mapping each term to a working memory allocated for each component’s stream and executing a parallel reduction to yield the updated mean and covariance. Once all component streams have been synchronized, the mixture coefficients and Cholesky decompositions of the covariances is computed with a single kernel invocation parallel in the number of components.
The main design consideration was whether or not use streams. For larger numbers of components, this will result in improved runtime performance, however, it comes at the cost of increased memory usage which limits the size of problems an end user can study with the implementation. Because the primary design goal is performance, the increase in memory was favorable to using less memory and executing each component sequentially.
To optimize the runtime of the implementation nvprof along with the NVIDIA Visual Profiler was used to identify performance bottlenecks. The original implementation was a naive port of the parallel C code which required frequent memory transfers between host and device resulting in significant CUDA API overhead that dominated the runtime. By transferring and allocating memory on the device beforehand, this allowed the implementation to execute primarily on the GPU and eliminate the API overhead. The second primary optimization was using streams and events for parallelization of the component probability densities and parameter updates in the maximization step. In doing so, this allowed for a fold reduction since the components calculations would be performed in parallel. The next optimization step was to streamline the parallel reductions by using block reductions against fast shared block memory minimizing the number of global memory writes instead of performing iterated reductions against sequential addressing that preformed global memory reads and writes for each point. The final optimization step was to used pinned host memory to enable zerocopy transfers from DRAM to the GPU over DMA.
Evaluation
To evaluate the implementations we need a way of generating GMMs and sampling data from the resulting distributions. To sample from a standard univariate normal distribution one can use The BoxMuller transform, Zigguart method, or Ratioofuniforms method [7]. The latter is used here due to its simplicity and efficiency. Sampling from the multivariate normal distribution can by done by sampling a standard normal vector and computing where can be computed by Eigendecomposition, , or Cholesky factorization, . The latter is used since it is more efficient. The GMM describes a generative process whereby we pick a component at random with probability given by its mixture coefficient and then sample the underlying distribution, and perform this process for the desired number of points.
The matter of generating GMMs it more interesting. Here we draw for , alternatively, one could draw . Means are drawn by with so that means are relatively spread out in . The more exciting prospect is how to sample the covariance matrix. This is where the Wishart distribution, for , comes in handy. The Wishart distribution is a model of what the sample covariance matrix should look like given a series of vectors. Based on a method by [8], [9] gives an equally efficient method for sampling by letting and for and .
To evaluate the performance of the different implementations, the wall clock time taken to run the algorithm on a synthetic instance was measured by varying each of the , , and parameters while holding the other two fixed. From an end user perspective wall clock time is preferable to the time the operating system actually devoted to the problem since wall clock time is more valuable. There will be variability in the results since each instance requires a different number of iterations for the log likelihood to converge. Tests were conducted on a Xeon 1245 v5 3.5 Ghz system with 32GB of memory and an NVIDIA GTX 1060 6GB graphics card with 1280 cores.
Since the parameter space is relatively large Figures 25 look at varying one parameter will fixing the others to demonstrate the relative merits of each approach. When the number of points dominates the CUDA approach tends to be 18x faster; the Parallel approach tends to be 3x faster when the dimension is high; and CUDA is suitable when the num of components is high giving a 20x improvement relative to the sequential approach. Thus, when dealing with suitably large datasets, the CUDA based implementation is preferable delivering superior runtime performance without sacrificing quality.
It is important to note that the results obtained from the CUDA solution may differ to those the sequential and parallel approaches. This is due to nondeterministic round off errors associated with executing parallel reductions compared to sequential reductions [2], and differences in the handling of floating point values on the GPU [10], notably, the presence of fused multiple add on NVIDIA GPUs which are more accurate than what is frequently implemented in CPU architectures. The following two synthetic data sets illustrate typical results of the three schemes:
Conclusion
This work demonstrated the utility of using NVIDIA GPUs to train Gaussian mixture models by the Expectation Maximization algorithm. Speedups as high as 20x were observed on synthetic datasets by varying the number of points, components, and data dimension while leaving the others fixed. It is believed that further speedups should be possible with additional passes, and the inclusion of metric data structures to limit which data is considered during calculations. Future work would pursue more memory efficient solutions on the GPU to allow for larger problem instance, and focus on providing higher level language bindings so that it can be better utilized in traditional data science toolchains.
References
 Bishop, C. M. Pattern recognition and machine learning. Springer, 2006.
 Collange, S., Defour, D., Graillat, S., and Lakymhuk, R. Numerical reproducibility for the parallel reduction on multi and manycore architectures. Parallel Computing 49 (2015), 8397.
 Dempster, A. P., Laird, N. M., and Rubin, D. B. Maximum likelihood from incomplete data via the eme algorithm. Journal of the royal statistical society. Series B (methodological) (1977), 138.
 Fan, J., Liao, Y., and Liu, H. An overview of the estimation of large covariance and precision matrices. The Econometrics Journal 19, (2016) C1C32.
 Harris, M. Optimizing cuda. SC07: High Performance Computing with CUDA (2007).
 Kincaid, D., and Cheney, W. Numerical analysis: mathematics of scientific computing. 3 ed. Brooks/Cole, 2002.
 Kinderman, A. J., and Monahan, J. F. Computer generation of random variables using the ratio of uniform deviates. ACM Transactions on Mathematical Software (TOMS) 3, 3 (1977), 257260.
 Odell, P., and Feiveson, A. A Numerical procedure to generate a sample covariance matrix. Journal of the American Statistical Association 61, 313 (1966), 199203.
 Sawyer, S. Wishart distributions and inversewishart sampling. URL: http://www.math.wustl.edu/~sawyer/hmhandouts/Wishart.pdf (2007).
 Whitehead, N., and FitFlorea, A. Precision and performance: Floating point and ieee 754 compliance for nvidia gpus. rn(A + B) 21., 1 (2011), 1874919424.
A Greedy Approximation Algorithm for the Linear Assignment Problem
Starting today, I will be posting some of the related source code for articles on GitHub.
Introduction
The Linear Assignment Problem (LAP) is concerned with uniquely matching an equal number of workers to tasks, , such that the overall cost of the pairings is minimized. A polynomial time algorithm was developed in the late fifties by [6], and further refined by [9], called the Hungarian method. Named so after the work of Hungarian mathematicians König and Egerváry whose theorems in the 1930s form the basis for the method. While the Hungarian Method can solve LAP instances in time, we wish to find faster algorithms even if it means sacrificing optimality in the process. Here we examine a greedy approximation algorithm with runtime in terms of its approximation factor and compare it empirically to the Hungarian method.
Linear Assignment Problem
The above linear program has cost, , and assignment, , matrices that specify the terms of the LAP. This is equivalent to finding a perfect matching in a weighted bipartite graph. A minimal cost may have several possible assignments, but we are only interested in finding just one. It is assumed that no one worker can do all jobs more efficiently by themselves than the distributing work across all workers. Likewise, if the costs are thought of as durations, then the minimum cost is the minimum sequential rather than parallel time taken to complete the tasks.
From a practical point of view, we may relax the integral constraint on and allow all positive realvalued costs. For instances where there are more jobs than workers, and vice versa, dummy entries valued greater than the existing maximum may be added. Minimizing the cost is the default objective, but the maximum cost can be found by finding the optimal assignment for , then finding the cost relative to .
Algorithms
Brute Force Rather than using the mathematical programming or graph theoretic representation of the problem, we can instead view the problem as finding the assignment that minimizes the cost out of all possible assignments:
There are such assignments which can be produced using an iterative version of Heap’s algorithm [5] in time assuming one does differential scoring (opposed to calculating the score for each permutation which would result in an algorithm.)
Random The random algorithm selects a permutation uniformly from the set of all possible assignment permutations in time using the FisherYates shuffle [4]. This obviously does not produce an optimal or nearoptimal solution, but serves as a straw man to compare other results.
Greedy The greedy heuristic continues to cover the row and column of the smallest uncovered entry in the cost matrix until all entries are covered. The resulting set of entries then constitutes the assignment of workers to jobs. An inefficient algorithm can be used to find the smallest entry every iteration, or a more efficient result of can be obtained through the use of a sorted, array indexed hybrid mesh and queue. Let represent a tuple consisting of row, column, and value; the previous entry in the matrix this value, and the next entry in this matrix this value; and the (left, above, right, below) that are adjacent to this node.
Algorithm 1 A greedy algorithm for the LAP.

 // Adjacent node left, above, right, below properties
 // Sort in ascending order by node value
 // Adjacent node previous and next properties

 // Deletes row and col of
Allocating and linking for assignment is ; mesh ; queue . Therefore, initialization requires time. The body of the loop requires a constant time assignment of worker to job, and time to remove the row and column from a matrix using a modified depth first search. Thus, the loop itself accounts for time. The resulting time complexity is therefore .
Breaking ties for the minimum uncovered value can result in different costs. This drawback is shown in the above example were choosing at yields a minimum cost of , where as the one at gives a minimum cost of . The next progression in the design of the greedy algorithm would be to try all minimum positions and keep the top performing paths.
Hungarian The general idea behind the KuhnMunkres algorithm is that if we are given an initial assignment, we can make further assignments and potentially reassign workers until all workers have been tasked with a job. The highlevel sketch of the algorithm starts with an initial assignment. While we have jobs that are unassigned, we look for qualified workers, ie, the zero entries. If a worker is already assigned to a job, but is also qualified for another, then we prime the alternative and continue to the next qualified worker, but if that is the only job the worker is qualified for, then we’d like to reassign any other worker already tasked to that job. This leads to a natural ripple effect represented by an alternating path of starred and primed entries. In Munkres’ paper [9] “starred” zero’s represent assignments of workers to jobs, and “primed” zero’s are alternative assignments. By flipping the bits of the path, we reassign workers to their alternative tasks while ensuring the assignment continues to be minimal by construction. After assigning as many workers as we have to, we then deduct the lowest cost to create a new qualified worker. Thus, every iteration we are guaranteed to make positive progress towards our goal of finding an optimal assignment. This scheme results in the worst case time to complete.
Algorithm 2 The Hungarian method for the LAP.

 Star the first uncovered zero in row , cover the corresponding column for
 All columns not covered
 Uncovered zeros
 Prime the current uncovered zero
 There’s a starred zero in this row
 Uncover the starred zero’s column and cover the row

 Find an alternating augmented path from the primed zero
 Unstar the starred zeros on the path and star the primed zeros on the path
 Remove all the prime markings and cover all stared zeros
 Found path

 over all uncovered
 for all uncovered columns
 for all covered rows
 Uncovered zeros
 Starred zeros // These are all the assignments
To further illustrate the algorithm, consider the following example where starred entries are denoted by red, and primed entries by green:
Analysis
The prevailing convention in the literature is to look at the approximation factor, , to determine how close the results of an approximation algorithm are to optimal [10]. Here this ratio is the expected minimum cost assignment of the algorithm under test to the same quantity given by the expected minimum assignment cost. Let be an a standard exponential random cost matrix. We resort to the exponential distribution for its ease of analyis and prominence in related literature. Cf. the works of [7], [8] for analysis based on .
Exponential Distribution Properties Let have cumulative distribution function and expectation . The distribution demonstrates the memoryless property for expectations . Define the order statistic to be the minimum of draws from . [2] with expectation . If then with expectation .
Expected Minimum Cost The expected minimum assignment cost for is given by [1]:
Which is the generalized harmonic number of order two and converges to . For the generalized harmonic numbers, , for .
Greedy The minimum value of an matrix is given by the order statistic with expectation . The expected value of the minimum cost assignment is not just because the expectation doesn’t take into account the previous iteration’s minimum value. To accomplish this we make use of the memoryless property of the exponential distribution to observe that the expected difference in minimums between iterations is the expected minimum value given by . If we add up all these differences we get the expected minimum value of the k’th iteration; summing all these expectations then yields the expected minimum cost assignment:
This is the harmonic number of order one which does not converge. The resulting approximation factor is:
Random The random algorithm will simply select an assignment permutation, so we are just adding up distributed random variables leading to an expected cost of:
And approximation factor:
From this analysis one concludes that the greedy algorithm has an unbounded approximation factor that grows significantly slower than that of randomly selecting assignments.
Evaluation
To illustrate the preceding results, Figure 1 shows the approximation factor for the greedy algorithm implementations against the derived approximation factor. The simulated results are based on 120 standard exponentially distributed matrices for . Using the same conventions for the approximation factor, Figure 2 illustrates the runtime characteristics of the algorithms after rejecting outliers due to system fluctuations. Results obtained from source code compiled with O3 flags and ran on a Xeon E31245 v5 3.5 Ghz system with 32 GBs of 2133Mhz DDR4 RAM. The algorithms coincide with the theoretical time complexities as shown in Table 2.
Solver  MSE 

GREEDYEFFICIENT  0.002139 
GREEDYNAIVE  0.014161 
HUNGARIAN  0.232998 
Summary
Brute  Random  Greedy  Hungarian  

Complexity  
1  1 
Exact solutions can be delivered by the brute method when a handful of workers are being considered, and the Hungarian method should be considered for all other instances. Approximate solutions can be provided by the greedy algorithm with logarithmic degeneracy while providing a linear factor improvement over the Hungarian method. For inputs greater than those considered, the parallel Auction algorithm [3] is a suitable alternative and the subject of future work.
References
 Aldous, D. J. The limit in the random assignment problem. Random Structures & Algorithms 18, 4 (2001), 381418.
 Balakrishnan, N., and Rao, C. Handbook of statistics 16: Order statisticstheory and methods, 2000.
 Bertsekas, D. P. The auction algorithm: A distributed relaxation method for the assignment problem. Annals of operation research 4, 1 (1988), 105123.
 Durtenfeld, R. Algorithm 235: random permutation. Communications of the ACM 7, 7 (1964), 420.
 Heap, B. Permutations by interchanges. The Computer Journal 6, 3 (1963), 293298.
 Kuhn, H. W. The hungarian method for the assignment problem. Naval research logistics quarterly 2, 12 (1955), 83097.
 Kurtzberg, J. M. On approximation methods for the assignment problem. Journal of the ACM (JACM) 9, 4 (1962), 419439.
 Steele, M. J. Probability and statistics in the service of computer science: illustrations using the assignment problem. Communications in StatisticsTheory and Methods 19, 11 (1990), 43154329.
 Munkres, J. Algorithms for the assignment and transportation problems. Journal of the society for industrial and applied mathematics 5, 1 (1957), 3238.
 Williamson, D. P., and Shmoys, D. B. The design of approximation algorithms. Cambridge university press, 2011.
Using GPUs to solve Spatial FitzHughNagumo Equation Numerically
Introduction
Modeling Action Potentials
In neurophysiology, we wish to model how electrical impulses travel along the complex structures of neurons. In particular, along the axon since it is the principle outbound channel of the neuron. Along the axon are voltage gated ion channels in which concentrations of potassium and sodium are exchanged. During depolarization, a fast influx of sodium causes the voltage to gradually increase. During repolarization, a slow outflux of potassium causes the voltage to decrease gradually. Because the potassium gates are slow to close, there is a negative voltage dip and recovery phase afterwards called hyperpolarization.
Attempts to provide a continuous time model of these phases began with work in the 1950s by Hodgkin and Huxley [HH52]. The duo formulated a fourdimensional nonlinear system of ordinary differential equations based on an electrical circuit model of giant squid axons. This landmark contribution was later simplified in the 1960s by FitzHugh [Fit61]. Here FitzHugh casted the problem in terms of Van der Pol oscillators. This reformulation allowed him to explain the qualitative behavior of the system in terms of a twodimensional excitation/relaxation statespace model. The following year Nagumo [NAY62] extended these equations spatially to model the desired action potential propagation along an axon, and demonstrated its behavior on analog computers. This spatial model will be the focus of this work, and a more comprehensive account of these developments can be found in [Kee02].
FitzHughNagumo Equation
The Spatial FitzHughNagumo equation is a twodimensional nonlinear reactiondiffusion system:

(1) 
Here represents the action potential (voltage) along the axon, and the recovery of the system. Constant is absent from the literature, and is inversely proportional to recovery time.
Mathematical Analysis
The system does not admit a general analytic solution. Mathematical analysis of the system is concerned with the existence and stability of traveling waves with [AK15] providing a thorough account of these aspects. Other analyses are concerned with the statespace model and the relationship of parameters with observed physiological behavior. In particular: selfexcitatory, impulse trains, single traveling wavefronts and impulses, doubly traveling divergent wave impulses, and nonexcitatory behavior that returns the system to a resting state. Since the FitzHughNagumo equations are well understood, more recent literature is focused on higher dimensional and stochastic variants of the system which [Tuc13] discusses in detail.
Numerical Analysis
A survey of the literature revealed several numerical approaches to solving the FitzHughNagumo equations consisting of a Finite Element method with Backward Differentiation Formulae [Ott10], and the Method of Lines [Kee02] approach. In this work, three approaches based on the Finite Difference method are investigated: an explicit scheme, an adaptive explicit scheme, and an implicit scheme; along with their associated sequential CPU bound and parallel GPU bound algorithms.
Explicit Finite Difference Scheme
To study the basic properties of the FitzHughNagumo equations an explicit scheme was devised using forward and central differences for the temporal and spatial derivatives respectively.

(2) 
Truncation errors are linear in time, , and quadratic, , in space. For stability, , implying the use of inconveniently small time steps, however in practice it seems rare to find any mention of in the literature. Each time step can be computed sequentially or in parallel in linear time, . However, there is a significant constant factor improvement delivered by parallel GPU implementations since modern GPUs allow millions of nodes to be updated in parallel giving near constant runtime performance. Further parallelization is possible by trivially distributing contiguous node sets to a combination of multiple machines and multiple GPUs.
Experiments
The explicit scheme was used to investigate the traveling wave and divergent wave behaviors of the FitzHughNagumo equations. Fig. (1) demonstrate the application of a constant impulse, , at the end of an unexcited axon, , giving rise to oscillatory behavior. Fig. (2) shows a Gaussian impulse applied initially to the center of the axon, . As the system evolves, the impulse collapses giving rise to two separate impulses that travel in opposite directions before dissipating at the boundaries returning the axon to a completely unexcited state. Both test cases are qualitatively consistent with the literature and share the following parameters:
(3) 
Error Analysis
Figure 3: Varying values of w.r.t at . fixed to 0.0098. 
Figure 4: Varying values of w.r.t at different values of . fixed to 0.5. 
Two experiments were ran to verify the suggested truncation errors. The numerical solution given by a sufficiently small step size serves as an analytic solution to , which is then used to evaluate how larger steps sizes deviate as measured by the root mean squared error. Fig. (3) looks at varying and shows that as the step size as halved, the resulting RMSE is quartered consistent with the expect quadratic truncation term of the scheme. Similarly, Fig. (4) looks at varying and shows that independent of , halving the step size results in an equally reduced RMSE consistent with the expected linear truncation term of the scheme.
Runtime Performance
Figure 5: Wall time for memory allocation, memory transfers, and core loop for both CPU and GPU. 
Figure 6: Wall time for just core loop for both CPU and GPU. 
Comparison of sequential CPU and parallel GPU bound algorithms is based on the wall time taken to perform a single iteration to calculate and . Reported figures are a function of spatial node quantity and the mean run time of 30 iterations. The main bottleneck to performance is transferring buffers between the host and device. Fig. (5) illustrates this effect. For the largest test case considered, , “GPU w/o tx” delivers 19x faster runtime over “GPU w/ tx” by not transferring intermediate results back to the host. Similarly, it delivers significantly faster runtime over the CPU by a factor of 73x. To better understand this performance boost, Fig. (6) looks at just the core loop execution time. For , the core loops account for only 3.7% and 14.9% of the execution time on the CPU and GPU respectively with the GPU delivering 18x better performance than the CPU. These percentages increase monotonically, and suggest that memory transfers will eventually be dominated by sufficiently large inputs on GPUs with an abundance of memory.
Adaptive Explicit Finite Difference Scheme
While investigating the traveling wavefront solution of the system, numerical oscillations were observed as the simulation zeroed in on the steady state solution. To address this issue, an adaptive explicit scheme was devised. A survey of the literature suggested a family of moving grid methods to solve the FitzHughNagumo system based on a Lagrangian formulation [VBSS90] and a method of lines formulation [Zwa11]. Here a heuristic is used to concentrate grid points where the most change takes place.
The formulation of the scheme is identical to the former section with second order spatial derivatives being approximated by Lagrange interpolating polynomials since the technique supports nonuniform grids. A three point, first order truncation error scheme is used. A five point, third order truncation error scheme was considered, but abandoned in favor of the empirically adequate three point scheme.
(4) 
The first and second spatial derivatives given by the Lagrange interpolating polynomials are used to decide how much detail is needed in the domain in addition to the first temporal derivative given by finite differences. First, a coarse grid is laid down across the entire domain to minimize the expected distance between nodes since the second order derivative has first order truncation error. Next, the magnitude of the first order spatial derivative (second order truncation error) is used to lay down a finer grid when the derivative is greater than a specified threshold. This corresponds to where the waves of the solution are.
Next, the temporal derivative is used to lay down an even finer grid in those areas having an absolute change above a specified threshold. The change in time corresponds to the dynamics of the system, by adding detail in these areas, we can preserve the behavior of the system. Finally, the zeros of the second spatial derivative serve as indicators of inflection points in the solution. These correspond most closely to the location of the traveling wavefronts of the equation. Here, the most detail is provided around a fixed radius of the inflection points since the width of the wavefronts does not depend on parameterization.
Each iteration, the explicit scheme is evaluated on the grid from the previous iteration and those results are then used to perform the grid building scheme. To map the available solution values to the new grid, the points are linearly interpolated if a new grid point falls between two previous points, or mapped directly if there is a stationary grid point between the two iterations. The latter will be the more common case since all grid points are chosen from an underlying uniform grid specified by the user. Linear interpolation will only take place when extra grid points are included in an area.
Experiments
Figure 7: Top: Numerical oscillation of a centered Gaussian impulse with and all other parameters the same as those given in previous section for . Bottom: Eliminated numerical oscillation based on the adaptive explicit scheme.
Fig. (7) is the motivating example for this scheme and demonstrates how numerical oscillations can be avoided by avoiding calculations in regions with stationary solutions. To demonstrate that the scheme works well for other test cases, the more interesting and dynamic divergent impulse test case is shown in Fig. (8). Here we can see that as time progresses, points are allocated to regions of the grid that are most influenced by the system’s dynamics without sacrificing quality. For the time steps shown, the adaptive scheme used 23x fewer nodes than the explicit scheme from the previous section.
Figure 8: Example of adaptive grid on the divergent impulse example for { 15.06, 30.13, 45.05, 60.12, 75.05, 90.11 }. Red lines given by the explicit scheme from the previous section, green dots given by adaptive explicit scheme.
Implicit Finite Difference Scheme
An implicit CrankNicolson scheme is used in this section to solve the FitzHughNagumo equations. To simplify the computations, is solved explicitly using a second order central difference scheme before solving leading to the following formulation:

(5) 
The truncation error for this scheme is with an improved, albeit still restrictive, requirement over the explicit scheme that . Based on this formulation, the righthand side is completely known when is calculated. This gives a simpler expression to consider:
(6) 
Newton’s method is used to solve the nonlinear function with an initial guess equal to the previous time step’s values, . To refine the estimate, the following system is solved iteratively until the magnitude of the refinement, , is less than a specified tolerance or machine epsilon.
(7) 
This formulation gives rise to a tridiagonal Jacobian matrix, , where the first and last row are specified by noflux boundary conditions, and constant offdiagonal entries and variable diagonal entries given by the partial derivatives of each nodal equation.

This tridiagonal system can be solved sequentially in time using the Thomas algorithm or in time using the Cyclic Reduction algorithm of [Hoc65]. Cyclic Reduction begins with a forward phase in which all odd indexed unknowns are eliminated recursively until a or system remains that can be solved directly. Cyclic Reduction ends with a backward phase that walks up the recursion stack to solve for the previously eliminated odd indexed unknowns. Since the algorithm decouples unknowns at each recursion level of the forward and backwards phases, these reductions can be done in parallel in time on the GPU assuming fold parallelism.
Further parallelism can be achieved by solving points explicitly along the domain, then using those results to create implicit subdomains that can be solved using either Thomas or Cyclic Reduction algorithms on a combination of multiple machines and multiple GPUs at the expense of additional communication and coordination.
Error Analysis
Figure 9: Varying values of w.r.t at . fixed to 0.000071. 
Figure 10: Varying values of w.r.t at different values of . fixed to 0.52. 
Evaluation of the spatial error revealed an unexpected linear behavior as shown in Fig. (9). As the spatial step is halved, the resulting error was expected to become quartered, instead it is halved. No clear explanation was discovered to account for this discrepancy. With respect to time, Fig. (10) shows that both the Thomas and Cyclic Reduction algorithms were quadratic as multiple points in time were evaluated. The Thomas algorithm produced aberrations as the step size increased eventually producing numerical instability, while the Cyclic Reduction algorithm was immune to this issue.
Figure 11: Stability of implicit solvers. 
Figure 12: Convergence of implicit solvers. 
In terms of stability, the implicit scheme is stable up to depending on which tridiagonal solver is used, and for comparison, the explicit scheme is stable up to precisely as shown in Fig. (11). The Thomas algorithm demonstrates a slightly weaker stability guarantee than the Cyclic Reduction algorithm becoming unstable around and respectively. In terms of convergence, the Thomas algorithm typically takes more iterations than Cyclic Reduction to obtain the same degree of accuracy as shown in Fig. (12). Taking the sequence of adjustments up to machine epsilon , Thomas algorithm gives suggesting qlinear convergence. Likewise, Cyclic Reduction gives suggesting qquadratic convergence.
Runtime Performance
Figure 13: Performance comparison of CPU and GPU bound Thomas and Cyclic Reduction algorithms. 
Figure 14: Performance comparison of Jacobian solvers. 
Sequential Thomas and Cyclic Reduction routines perform equally well on CPU as shown in Fig. (13). The parallel Cyclic Reduction method did not demonstrate significant performance gains on the GPU. However, looking at just the time taken to solve the Jacobian each iteration (not including initialization or memory transfers), parallel Cyclic Reduction on the GPU was 45x faster than both sequential CPU solvers as shown in Fig. (14).
To explain the poor performance of Cyclic Reduction on the GPU, there are a number of different factors at play. The algorithm is susceptible to warp divergence due to the large number of conditionals that take place. Reliance on global memory access with varying strides contributes to slow performance since shared memory can’t be effectively utilized, and each iteration the adjustments are transferred from device to host to decide if Newton’s method should terminate. These different factors suggest alternative GPU implementations need to be investigated to address these different issues.
Discussion
Work Environment
All results in this paper were based on code written in C#, and compiled using Microsoft Visual Studio Express with Release settings to run on a commodity class Intel Core i72360QM quad core processor. Open source CUDAfy.NET is used to run C# to CUDA translated code on a commodity class NVIDIA GeForce GT 525m having two streaming multiprocessors providing 96 CUDA cores.
Future Work
Numerically, additional work could be done on the adaptive explicit scheme. In preparing the scheme, a cubic splinebased approach was abandoned in favor of simpler approaches due to time pressures. It would be worthwhile to explore how to solve the system on a splinebased “grid”.
In addition, further work could be done to optimize the implementation of the parallel Cyclic Reduction algorithm on the GPU since it delivered disappointing runtime behavior compared to the sequential algorithm on the CPU. [CmWH14] mention several different optimizations to try, and I believe better global memory access will improve runtime at the expense of more complicated addressing. As an alternative to Cyclic Reduction, both [CmWH14] and [ZCO10] detail several different parallel tridiagonal solvers that could be deployed.
In terms of models considered, there are a number of different directions that could be pursued including higher dimensional [MC04], coupled [Cat14]], [Ril06], and stochastic variants [Tuc13] of the spatial FitzHughNagumo equation. Coming from a probabilistic background, I would be interested in investing time in learning how to solve stochastic ordinary and partial differential equations.
Conclusion
Three finite difference schemes were evaluated. An explicit scheme shows great performance on both the CPU and GPU, but it is susceptible to numerical oscillations. To address this issue, an adaptive explicit scheme based on heuristics was devised and is able to eliminate these issues while requiring fewer nodes to produce results onpar with the explicit scheme. An implicit scheme was evaluated which demonstrated a principled, and robust solution for a variety of test cases and is the favored approach of the three evaluated.
References
[AK15] Gianni Arioli and Hans Koch. Existence and stability of traveling pulse solutions of the fitzhughnagumo equation. Nonlinear Analysis: Theory, Methods and Applications, 113:5170, 2015
[Cat14] Anna Cattani. Fitzhughnagumo equations with generalized diffusive coupling. Mathematical Biosciences and Engineering, 11(2):203215, April 2014
[CmWH14] LiWen Chang and Wen mei W. Hwu. A guide for implementing tridiagonal solvers on gpus. In Numerical Computations with GPUs, pages 2944. Springer International Publishing, 2014.
[Fit61] Richard FitzHugh. Impulses and physiological states in theoretical models of nerve membrane. Biophysical journal, 1(6):445, 1961.
[HH52] Alan L. Hodgkin and Andrew F. Huxley. A quantitative description of membrane current and its application to conduction and excitation in nerve. The Journal of physiology, 117(4):500544, 1952.
[Hoc65] R. W. Hockney. A fast direct solution of poisson’s equation using fourier analysis. J. ACM, 12(1):95113, Jan 1965.
[Kee02] James P. Keener. Spatial modeling. In Computational Cell Biology,volume 20 of Interdisciplinary Applied Mathematics, pages 171197. Springer New York, 2002.
[MC04] Maria Murillo and XiaoChuan Cai. A fully implicit parallel algorithm for simulating the nonlinear electrical activity of the heart. Numerical linear algebra with applications, 11(23):261277, 2004.
[NAY62] J. Nagumo, S. Arimoto, and S. Yoshizawa. An active pulse transmission line simulating nerve axon. Proceedings of the IRE, 50(10):20612070, Oct 1962.
[Ott10] Denny Otten. Mathematical models of reaction diffusion systems, their numerical solutions and the freezing method with comsol multiphysics. 2010.
[Ril06] Caroline Jane Riley. Reaction and diffusion on the sierpinkski gasket. PhD thesis, University of Manchester, 2006.
[Tuc13] Henry C. Tuckwell. Stochastic partial differential equations in neurobiology. Linear and nonlinear models for spiking neurons. In Stochastic Biomathematical Models, volume 2058 of Lecture Notes in Mathematics. Springer Berlin Heidelberg, 2013.
[VBSS89] J. G. Verwer, J. G. Blom, and J. M. SanzSerna. An adaptive moving grid method for one dimensional systems of partial differential equations. Journal of Computational Physics, 82(2):454486, 1989.
[ZCO10] Yao Zhang, Jonathan Cohen, and John D. Owens. Fast tridiagonal solvers on the gpu. SIGPLAN Not., 45(5):127136, Jan 2010.
[Zwa11] M. N. Zwarts. A test set for an adaptive moving grid pde solver with timedependent adaptivity. Master’s thesis. Utrecht University, Utrecht, Netherlands, 2011.
Expected Maximum and Minimum of RealValued Continuous Random Variables
Introduction
This is a quick paper exploring the expected maximum and minimum of realvalued continuous random variables for a project that I’m working on. This paper will be somewhat more formal than some of my previous writings, but should be an easy read beginning with some required definitions, problem statement, general solution and specific results for a small handful of continuous probability distributions.
Definitions
Definition (1) : Given the probability space, , consisting of a set representing the sample space, , a , , and a Lebesgue measure, , the following properties hold true:
 Nonnegativity:
 Null empty set:
 Countable additivity of disjoint sets
Definition (2) : Given a realvalued continuous random variable such that , the event the random variable takes on a fixed value, , is the event measured by the probability distribution function . Similarly, the event that the random variable takes on a range of values less than some fixed value, , is the event measured by the cumulative distribution function . By Definition, the following properties hold true:
Defintion (3) : Given a second realvalued continuous random variable, , The joint event will be measured by the joint probability distribution . If and are statistically independent, then .
Definition (4) : Given a realvalued continuous random variable, , the expected value is .
Definition (5) : (Law of the unconscious statistician) Given a realvalued continuous random variable, , and a function, , then is also a realvalued continuous random variable and its expected value is provided the integral converges. Given two realvalued continuous random variables, , and a function, , then is also a realvalued continuous random variable and its expected value is . Under the independence assumption of Definition (3), the expected value becomes .
Remark (1) : For the remainder of this paper, all realvalued continuous random variables will be assumed to be independent.
Problem Statement
Theorem (1) : Given two realvalued continuous random variables , then the expected value of the minimum of the two variables is .
Lemma (1) : Given two realvalued continuous random variables , then the expected value of the maximum of the two variables is
Proof of Lemma (1) :
(Definition (5))
(Definition (1.iii))
(Fubini’s theorem)
(Definition (2.i))
Proof of Theorem (1)
(Definition (4))
(Definition (1.iii))
(Fubini’s theorem)
(Definition (2.iii))
(Definition (2.i))
(Definition (4), Lemma (1))
Remark (2) : For real values , .
Proof Remark (2) : If , then , otherwise . If , then , otherwise . If , then , otherwise, . Therefore,
Worked Continuous Probability Distributions
The following section of this paper derives the expected value of the maximum of realvalued continuous random variables for the exponential distribution, normal distribution and continuous uniform distribution. The derivation of the expected value of the minimum of realvalued continuous random variables is omitted as it can be found by applying Theorem (1).
Exponential Distribution
Definition (6) : Given a realvalued continuous exponentially distributed random variable, , with rate parameter, , the probability density function is for all and zero everywhere else.
Corollary (6.i) The cumulative distribution function of a realvalued continuous exponentially distributed random variable, , is therefore for all and zero everywhere else.
Proof of Corollary (6.i)
Corollary (6.ii) : The expected value of a realvalued continuous exponentially distributed random variable, , is therefore .
Proof of Corollary (6.ii)
The expected value is by Definition (4) and Lemma (2) .
Lemma (2) : Given real values , then .
Proof of Lemma (2) :
Theorem (2) : The expected value of the maximum of the realvalued continuous exponentially distributed random variables , is .
Proof of Theorem (2) :
(Lemma (1))
(Corollary (6.i))
(Integral linearity)
(Lemma (2), Corollary (6.ii))
Normal Distribution
Definition (7) : The following Gaussian integral is the error function for which the following properties hold true:
 Odd function:
 Limiting behavior:
Definition (8) : Given a realvalued continuous normally distributed random variable , , with mean parameter, . and standard deviation parameter, , the probability density function is for all values on the real line.
Corollary (8.i) : The cumulative distribution function of a realvalued continuous normally distributed random variable, , is therefore .
Proof of Corollary (8.i) :
(Definition (2.i))
(Usubstitution with )
(Definition (2.iii))
(Reverse limits of integration)
(Definition (7))
(Definition (7.i))
(Definition (7.ii))
Corollary (8.ii) : The expected value of a realvalued continuous normally distributed random variable, , is therefore .
Proof of Corollary (8.ii) :
(Definition (4))
(Usubstitution with )
(Integral linearity)
(Definition (1.iii))
( is odd, is even)
(Definition (7), Definition (7.ii))
Definition (9) : Given a realvalued continuous normally distributed random variable, , the probability distribution function will be denoted as standard normal probability distribution function, , and the cumulative distribution function as the standard normal cumulative distribution function, . By definition, the following properties hold true:
 Nonstandard probability density function: If , then
 Nonstandard cumulative distribution function: If , then
 Complement:
Definition (10) : [PaRe96] Given and , the following integrals hold true:
Theorem (3) : The expected value of the maximum of the realvalued continuous normally distributed random variables , is .
Lemma (3) : Given realvalued continuous normally distributed random variables , , .
Proof of Lemma (3) :
(Definition (9.i), Definition (9.ii))
(Usubstitution with , )
(Integral linearity)
(Definition (10.i), Definition (10.ii))
Proof of Theorem (3) :
(Lemma (1))
(Definition (11.i), Definition (11.ii))
(Lemma (3))
(Definition (9.iii))
Continuous Uniform Distribution
Definition (11) : Given a realvalued continuous uniformly distributed random variable, , with inclusive boundaries such that , the probability density function is for all and zero everywhere else.
Corollary (11.i) : The cumulative distribution function of a realvalued continuous uniformly distributed random variable, , is therefore .
Proof of Corollary (11.i) :
.
Corollary (11.ii) : The expected value of a realvalued continuous uniformly distributed random variable, , is therefore .
Proof of Corollary (11.ii)
Theorem (4) : The expected value of the maximum of realvalued continuous uniformly distributed random variables , is .
Proof of Theorem (4) :
(Lemma (1))
Case (1) :
Case (2) :
Case (3) :
Case (4) :
Case (5) :
Case (6) :
Summary Table
The following summary table lists the expected value of the maximum of realvalued continuous random variables for the exponential distribution, normal distribution and continuous uniform distribution. The corresponding minimum can be obtained by Theorem (1).
Random Variables  Maximum  

References
[GrSt01] Grimmett, Geoffrey, and David Stirzaker. Probability and Random Processes. Oxford: Oxford UP, 2001. Print.
[PaRe96] Patel, Jagdish K., and Campbell B. Read. Handbook of the Normal Distribution. 2nd ed. New York: Marcel Dekker, 1996. Print.
Tropical Representation of the AllPairs Shortest Path Problem
Motivation
While I was doing my Abstract Algebra research the other month, I came across an interesting way of simplifying the representation of the allpairs shortest path problem using Tropical Geometry. I thought it was pretty clever, so I thought I’d do a quick writeup.
Problem Statement
The allpairs shortest path problem is to identify the minimum path cost, , out of the possible paths between vertices and .
Proposition
Consider a weighted directed graph (digraph), , consisting of vertices, , and directed edges (arcs), , and a function, , yielding the weight of an edge. Only those weights from the positive affinely extended real numbers, , are allowed per the problem statement. The adjacency matrix representation, , of is given by the following matrix:
Now, consider a semiring over whose additive operator, , is given by the minimum function, , and whose multiplicative operator, , is given by addition, . The additive unit is given by infinity, , and the multiplicative unit by zero, . This semiring is the Tropical Semiring . (The namesake of tropical is in honor of Brazilian Imre Simon who developed this branch of mathematics.)
Linear algebra constructs can be tropicalized to yield the familiar definitions for matrix addition and multiplication for matricies and .
Given the two prior statements, the elegant solution to the allpairs shortest path problem is given by taking powers of the adjacency matrix: .
Proof
To see how this works out, start with . The matrix represents the minimum cost between any two adjacent vertices. In other words, the minimum cost for all paths containing a single edge. The next inductive step is to consider paths containing at most two adjacent edges. Squaring the adjacency matrix yields all such paths. When the matrix is squared, each edge is concatenated to all other adjacent edges and the minimum weight of the paths is selected. This thought process can iterated as follows:
The result is a typical Bellman equation. A graph can have at most edges between any two vertices, thus, the solution to the allpairs shortest path problem is given by .
Example
As a worked example, consider the following graph whose set of vertices is given by the set , set of arcs by and weight function, , as labeled on the graph.
The allpairs shortest paths are given by the following calculations where the row and column coordinates correspond to the vertices of . Values in bold denote a change in the shortest path between two vertices.
Computational Complexity
From asymptotic standpoint, tropical matrix multiplication is still on the order of traditional matrix multiplication of . Computing the allpairs shortest path problem using this approach is on the order of since we must perform the tropical matrix multiplication times. Now, This can be improved slightly since tropical matrix multiplication is associative, so we can leverage the repeated squaring approach and reduce the time complexity down to .
The time complexity can be further reduced to using the FloydWarshall Algorithm, which is another dynamic programming approach that is similar in form to the tropical representation of the problem. In essence, it follows the same base case, but it’s recurrence statement only considers a range of vertices with respect to the two vertices being considered. A more in depth review of the algorithm can be found in the references.
References
“FloydWarshall’s Algorithm.” Algorithmist. Web. 12 Apr. 2012.
Cormen, Thomas H., Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. “25.2 The FloydWarshall Algorithm.” Introduction to Algorithms. 2nd ed. Cambridge, MA: MIT, 2001. 62935. Print.
Diestel, Reinhard. Graph theory. Heidelberg New York: Springer, 2010.
Laface, Antonio. Introduction to Tropical Geometry [pdf]. 29 Nov. 2006. Web. 11 Apr. 2012.
Maclagan, Diane, and Bernd Sturmfels. Introduction to Tropical Geometry [pdf]. 4 Nov. 2009. Web. 9 Apr. 2012.
Mohri, Mehryar. “Semiring Frameworks and Algorithms for ShortestDistance Problems” [pdf]. Journal of Automata, Languages and Combinatorics 7 (2002) 3: 32150. 8 Aug. 2002. Web. 31 Mar. 2012.
Minesweeper Agent
Introduction
Lately I’ve been brushing up on probability, statistics and machine learning and thought I’d play around with writing a Minesweeper agent based solely on these fields. The following is an overview of the game’s mechanics, verification of an implementation, some different approaches to writing the agent and some thoughts on the efficacy of each approach.
Minesweeper
Background
Minesweeper was created by Curt Johnson in the late eighties and later ported to Windows by Robert Donner while at Microsoft. With the release of Windows 3.1 in 1992, the game became a staple of the operating system and has since found its way onto multiple platforms and spawned several variants. The game has been shown to be NPComplete, but in practice, algorithms can be developed to solve a board in a reasonable amount of time for the most common board sizes.
Specification
Gameplay 

An agent, , is presented a grid containing uniformly distributed mines. The agent’s objective is to expose all the empty grid locations and none of the mines. Information about the mines’ grid locations is gained by exposing empty grid locations which will indicate how many mines exist within a unit (Chebyshev) distance of the grid location. If the exposed grid location is a mine, then the player loses the game. Otherwise, once all empty locations are exposed, the player wins.  
Initialization 

The board consists of hidden and visible states. To represent the hidden, , and visible state, , of the board, two character matrices of dimension are used.
Characters ‘0’‘8’ represent the number of neighboring mines, character ‘U’ to represent an unexposed grid location and character ‘*’ for a mine. Neighbors of a grid location is the set of grid locations such that . By default, . 

Exposing Cells 

The expose behavior can be thought of as a flood fill on the grid, exposing any empty region bordered by grid locations containing mine counts and the boundaries of the grid.
A matrix, , represents the topography of the board. A value of zero is reserved for sections of the board that have yet to be visited, a value of one for those that have, two for those that are boundaries and three for mines. A stack, , keeps track of locations that should be inspected. If a cell location can be exposed, then each of its neighbors will be added to the stack to be inspected. Those neighbors that have already been inspected will be skipped. Once all the reachable grid locations have been inspected, the process terminates. 
Verification
Methodology
Statistical tests are used to verify the random aspects of the game’s implementation. I will skip the verification of the game’s logic as it requires use of a number of different methods that are better suited for their own post.
There are two random aspects worth thinking about: the distribution of mines and the distribution of success (i.e., not clicking a mine) for random trials. In both scenarios it made since to conduct Pearson’s chisquared test. Under this approach there are two hypotheses:
 : The distribution of experimental data follows the theoretical distribution
 : The distribution experimental data does not follow the theoretical distribution
is accepted when the test statistic, , is less than the critical value, . The critical value is determined by deciding on a pvalue (e.g., 0.05, 0.01, 0.001), , that results in the tail area beneath the chisquared distribution equal to . is the degrees of freedom in the observation.
Mine distribution
The first aspect to verify was that mines were being uniformly placed on the board. For a standard board with mines, the expectation is that each grid location should be assigned times for trials. for this experiment.
In the above experiment, and . Since , this affirms and that the implemented distribution of mines is indeed uniform with a statistical significance of .
Distribution of successful clicks
The second aspect to verify is that the number of random clicks before exposing a mine follows a hypergeometric distribution. The hypergeometric distribution is appropriate since we are sampling (exposing) without replacement (the grid location remains exposed after clicking). This hypothesis relies on a nonfloodfill exposure.
The distribution has four parameters. The first is the number of samples drawn (number of exposures), the second the number of successes in the sample (number of empty exposures), the third the number of successes in the population (empty grid locations) and the last the size of the population (grid locations): .
The expected frequencies for the hypergeometric distribution is given by for trials. in this case.
In the above experiment and . Since , this affirms and that the number of locations exposed prior to exposing a mine follows a hypergeometric distribution with a statistical significance of .
Also included in the plot is the observed distribution for a flood based exposure. As one might expect, the observed frequency of more exposures decreases more rapidly than that of the nonflood based exposure.
Agents
Methodology
Much like how a human player would learn to play the game, I decided that each model would have knowledge of game’s mechanics and no prior experience with the game. An alternative class of agents would have prior experience with the game as the case would be in a human player who had studied other player’s strategies.
To evaluate the effectiveness of the models, each played against a series of randomly generated grids and their respective success rates were captured. Each game was played on a standard beginner’s grid containing between mines.
For those models that refer to a probability measure, , it is assumed that the measure is determined empirically and treated as an estimate of the probability of an event and not as an a priori measure.
Marginal Model
DevelopmentThe first model to consider is the Marginal Model. It is designed to simulate the behavior of a naive player who believes that if he observes a mine at a grid location that the location should be avoid in future trials. The model treats the visible board, , as a matrix of discrete random variables where each grid location is interpreted as either or (a) . This model picks the grid location with the greatest empirical probability of being empty:

Test Results
Since the mine distribution is uniform, the model should be equivalent to selecting locations at random. The expected result is that avoiding previously occupied grid locations is an ineffective strategy as the number of mines increases. This does however, provide an indication of what the success rate should look like for chance alone.
Conditional Model
DevelopmentOne improvement over the Marginal Model is to take into account the visual clues made visible when an empty grid location is exposed. Since an empty grid location represents the number of neighboring mines, the Conditional Model can look at these clues to determine whether or not an unexposed grid location contains a mine. This boils down to determining the probability of . A simplification in calculating the probability is to assume that each piece of evidence is independent. Under this assumption the result is a Naïve Bayes Classifier: As in the case of the Marginal Model, the Conditional Model returns the grid location that it has determined has the greatest probability of being empty given its neighbors:

Test Results
The Naïve Bayes Classifier is regarded as being an effective approach to classifying situations for a number of different tasks. In this case, it doesn’t look like it is effective at classifying mines from nonmines. The results are only slightly better than the Marginal Model.
Graphical Model
DevelopmentOne shortfall of the Conditional Model is that it takes a greedy approach in determining which action to take. A more sophisticated approach is to not just consider the next action, but the possible sequence of actions that will minimize the possibility of exposing a mine. Each of the possible observable grids, , can be thought of as a set of vertices in a graph whose corresponding set of edges represent the transition between a state, , to the next observable state, . Each transition was achieved by performing an action, , on the state. The specific action, , is chosen from a subset of permitted actions given the state. Each transition has a probability, , of taking place. It is possible to pick a path, , through this graph that minimizes the risk by assigning a reward, , to each state and attempting to identify an optimal path, , from the present state that yields the greatest aggregate reward, Solving for is equivalent to solving the Longest Path Problem and can be computed efficiently using a dynamic programming solution.

From the optimal walk, a sequence of optimal actions is determined by mapping over the path. Taking the first action gives the optimal grid location to expose given the current visible state of the board.
This description constitutes a Markov Decision Process. As is the case for most stochastic processes, it is assumed that the process holds the Markov Property; that future states only depend upon the current states and none of the prior states. In addition to being a Markov Decision Process, this is also an example of Reinforcement Learning.
First thing to observe is that the game state space is astronomical. For a standard beginner’s grid there is at most a sesvigintillion possible grids that a player can encounter. Which as an aside, is on the order of the number of atoms in the observable universe! The set of actions at each state is slightly more manageable with at most eightyone actions.
To simplify the state space, I chose to only consider boards and when evaluating a full grid, consider the possible subgrids and evaluate the optimal sequence of actions for each subgrid and pick the maximum reward associated for each subgrid that was evaluated as the action to take on the full grid.
Test Results
The Graphical Model produces results that are only a margin better than those of the Conditional Model.
Semideterministic Model
DevelopmentThe last model I’m going to talk about is a semideterministic model. It works by using the visible grid to infer the topology of the hidden grid and from the hidden grid, the topology that the visible grid can become. The grid can be viewed as a graph. Each grid location is a vertex and an edge is an unexposed grid location’s influence on another grid location’s neighbor mine count. For each of the exposed grid locations on the board, , it’s neighbors, , are all mines when the number of inbound edges , matches the visible mine count . The model produces its inferred version, , of the influence graph by using the determined mine locations . For each of the grid locations that are exposed and the inferred influence matches the visible count, then each of the neighbors about that location can be exposed provided they are not already exposed and not an inferred mine. From this set of possibilities, a mine location is chosen. When no mine locations can be determined, then an alternative model can be used. 
Test Results
Since the model is a more direct attempt at solving the board, its results are superior to the previously presented models. As the number of mines increases, it is more likely that it has to rely on a more probabilistic approach.
Summary
Each of the models evaluated offered incremental improvements over their predecessors. Randomly selecting locations to expose is on par with choosing a location based on previously observed mine locations. The Conditional Model and Graphical Model yield similar results since they both make decisions based on conditioned probabilities. The Semideterministic Model stands alone as the only one model that produced reliable results.
The success rate point improvement between the Condition and Marginal models is most notable for boards consisting of three mines and the improvement between Graphical and Semideterministic models for seven mines. Improvements between Random and Marginal models is negligible and between Conditional and Graphical is minor for all mine counts fewer than seven.
Given the mathematical complexity and nondeterministic nature of the machine learning approaches, (in addition the the complexity and time involved in implementing those approaches) they don’t seem justified when more deterministic and simpler approaches exist. In particular, it seems like most people have implemented their agents using heuristics and algorithms designed to solve constraint satisfaction problems. Nonetheless, this was a good refresher to some of the elementary aspects of probability, statistics and machine learning.
References
“Classification – Naïve Bayes.” Data Mining Algorithms in R. Wikibooks. 3 Nov. 2010. Web. 30 Oct. 2011.
“Windows Minesweeper.” MinesweeperWiki. 8 Sept. 2011. Web. 30 Oct. 2011.
Kaye, Richard. “Minesweeper Is NPcomplete.” [pdf] Mathematical Intelligencer 22.2 (2000): 915. Web. 30 Oct. 2011.
Nakov, Preslav, and Zile Wei. “MINESWEEPER, #MINESWEEPER.” 14 May 2003. Web. 14 Apr. 2012.
Richard, Sutton, and Andrew G. Barto. “3.6 Markov Decision Processes.” Reinforcement Learning: An Introduction. Cambridge, Massachusetts: Bradford Book, 1998. 4 Jan. 2005. Web. 30 Oct. 2011.
Rish, Irene “An Empirical Study of the Naive Bayes Classifer.” [pdf] IJCAI01 Workshop on Empirical Methods in AI (2001). Web. 30 Oct. 2011.
Russell, Stuart J., and Peter Norvig. Artificial Intelligence: A Modern Approach. Upper Saddle River, NJ: Prentice Hall/PearsonEducation., 2003. Print.
Sun, Yijun, and Jian Li. “Adaptive Learning Approach to Landmine Detection.” [pdf] IEEE Transactions of Aerospace and Electronic Systems 41.3 (2005): 19. 10 Jan. 2006. Web. 30 Oct. 2011.
Taylor, John R. An introduction to error analysis: the study of uncertainties in physical measurements. Sausalito, CA: University Science Books, 1997. Print.
Abstract Algebra in C#
Motivation
In C++ it is easy to define arbitrary template methods for computations involving primitive numeric types because all types inherently have arithmetic operations defined. Thus, a programmer need only implement one method for all numeric types. The compiler will infer the use and substitute the type at compile time and emit the appropriate machine instructions. This is C++’s approach to parametric polymorphism.
With the release of C# 2.0 in the fall of 2005, the language finally got a taste of parametric polymorphism in the form of generics. Unfortunately, types in C# do not inherently have arithmetic operations defined, so methods involving computations must use adhoc polymorphism to achieve the same result as in C++. The consequence is a greater bloat in code and an increased maintenance liability.
To get around this design limitation, I’ve decided to leverage C#’s approach to subtype polymorphism and to draw from Abstract Algebra to implement a collection of interfaces allowing for C++ like template functionality in C#. The following is an overview of the mathematical theory used to support and guide the design of my solution. In addition, I will present example problems from mathematics and computer science that can be represented in this solution along with examples how type agnostic computations that can be performed using this solution.
Abstract Algebra
Abstract Algebra is focused on how different algebraic structures behave in the presence of different axioms, operations and sets. In the following three sections, I will go over the fundamental subfields and how they are represented under the solution.
In all three sections, I will represent the distinction between algebraic structures using C# interfaces. The type parameters on these interfaces represent the sets being acted upon by each algebraic structure. This convention is consistent with intuitionistic (i.e., Chruchstyle) type theory embraced by C#’s Common Type System (CTS). Use of parameter constraints will be used when type parameters are intended to be of a specific type. Functions on the set and elements of the set will be represented by methods and properties respectively.
Group Theory
Group Theory is the simplest of subfields of Abstract Algebra dealing with the study of a single binary operation, , acting on a set . There are five axioms used to describe the structures studied under Group Theory:
 Closure:
 Associativity:
 Commutativity :
 Identity:
 Inverse:
The simplest of these structures is the Groupoid satisfying only axiom (1). Any Groupoid also satisfying axiom (2) is known as a Semigroup. Any Semigroup satisfying axiom (4) is a Monoid. Monoid’s also satisfying axiom (5) are known as Groups. Any Group satisfying axiom (3) is an Abelian Group.
public interface IGroupoid<T> { T Operation(T a, T b); } public interface ISemigroup<T> : IGroupoid<T> { } public interface IMonoid<T> : ISemigroup<T> { T Identity { get; } } public interface IGroup<T> : IMonoid<T> { T Inverse(T t); } public interface IAbelianGroup<T> : IGroup<T> { }
Ring Theory
The next logical subfield of Abstract Algebra to study is Ring Theory which is the study of two operations, and , on a single set. In addition to the axioms outlined above, there is an addition axiom for describing how one operations distributes over the other.
 Distributivity:
All of the following ring structures satisfy axiom (6). Rings are distinguished by the properties of their operands. The simplest of these structures is the Ringoid where both operands are given by Groupoids. Any Ringoid whose operands are Semigroups is a Semiring. Any Semiring whose first operand is a Group is a Ring. Any Ring whose second operand is a Monoid is a Ring with Unity. Any Ring with Unity whose second operand is a Group is Division Ring. Any Division Ring whose operands are both Abelian Groups is a Field.
public interface IRingoid<T, A, M> where A : IGroupoid<T> where M : IGroupoid<T> { A Addition { get; } M Multiplication { get; } T Distribute(T a, T b); } public interface ISemiring<T, A, M> : IRingoid<T, A, M> where A : ISemigroup<T> where M : ISemigroup<T> { } public interface IRing<T, A, M> : ISemiring<T, A, M> where A : IGroup<T> where M : ISemigroup<T> { } public interface IRingWithUnity<T, A, M> : IRing<T, A, M> where A : IGroup<T> where M : IMonoid<T> { } public interface IDivisionRing<T, A, M> : IRingWithUnity<T, A, M> where A : IGroup<T> where M : IGroup<T> { } public interface IField<T, A, M> : IDivisionRing<T, A, M> where A : IAbelianGroup<T> where M : IAbelianGroup<T> { }
Module Theory
The last, and more familiar, subfield of Abstract Algebra is Module Theory which deals with structures with an operation, , over two separate sets: and that satisfy the following axioms.
 Distributivity of :
 Distributivity of :
 Associativity of :
All of the following module structures satisfy axioms (7)(9). A Module consists of a scalar Ring and an vector Abelian Group. Any Module whose Ring is a Ring with Unity is a Unitary Module. Any Unitary Module whose Ring with Unity is a Abelian Group is a Vector Space.
public interface IModule< TScalar, TVector, TScalarRing, TScalarAddativeGroup, TScalarMultiplicativeSemigroup, TVectorAddativeAbelianGroup > where TScalarRing : IRing<TScalar, TScalarAddativeGroup, TScalarMultiplicativeSemigroup> where TScalarAddativeGroup : IGroup<TScalar> where TScalarMultiplicativeSemigroup : ISemigroup<TScalar> where TVectorAddativeAbelianGroup : IAbelianGroup<TVector> { TScalarRing Scalar { get; } TVectorAddativeAbelianGroup Vector { get; } TVector Distribute(TScalar t, TVector r); } public interface IUnitaryModule< TScalar, TVector, TScalarRingWithUnity, TScalarAddativeGroup, TScalarMultiplicativeMonoid, TVectorAddativeAbelianGroup > : IModule< TScalar, TVector, TScalarRingWithUnity, TScalarAddativeGroup, TScalarMultiplicativeMonoid, TVectorAddativeAbelianGroup > where TScalarRingWithUnity : IRingWithUnity<TScalar, TScalarAddativeGroup, TScalarMultiplicativeMonoid> where TScalarAddativeGroup : IGroup<TScalar> where TScalarMultiplicativeMonoid : IMonoid<TScalar> where TVectorAddativeAbelianGroup : IAbelianGroup<TVector> { } public interface IVectorSpace< TScalar, TVector, TScalarField, TScalarAddativeAbelianGroup, TScalarMultiplicativeAbelianGroup, TVectorAddativeAbelianGroup > : IUnitaryModule< TScalar, TVector, TScalarField, TScalarAddativeAbelianGroup, TScalarMultiplicativeAbelianGroup, TVectorAddativeAbelianGroup > where TScalarField : IField<TScalar, TScalarAddativeAbelianGroup, TScalarMultiplicativeAbelianGroup> where TScalarAddativeAbelianGroup : IAbelianGroup<TScalar> where TScalarMultiplicativeAbelianGroup : IAbelianGroup<TScalar> where TVectorAddativeAbelianGroup : IAbelianGroup<TVector> { }
Representation of Value Types
The CTS allows for both value and reference types on the .NET Common Language Infrastructure (CLI). The following are examples of how each theory presented above can leverage value types found in the C# language to represent concepts drawn from mathematics.
Enum Value Types and the Dihedral Group
One of the simplest finite groups is the Dihedral Group of order eight, , representing the different orientations of a square, , obtained by reflecting the square about the vertical axis, , and rotating the square by ninety degrees, . The generating set is given by and gives rise to the set These elements are assigned names as follows: , , , , , , and . The relationship between these elements is visualized below:
The easiest way to represent this group as a value type is with an enum.
enum Symmetry { Rot000, Rot090, Rot180, Rot270, RefVer, RefDes, RefHoz, RefAsc }
From this enum we can define the basic Group Theory algebraic structures to take us to .
public class SymmetryGroupoid : IGroupoid<Symmetry> { public Symmetry Operation(Symmetry a, Symmetry b) { // 64 cases } } public class SymmetrySemigroup : SymmetryGroupoid, ISemigroup<Symmetry> { } public class SymmetryMonoid : SymmetrySemigroup, IMonoid<Symmetry> { public Symmetry Identity { get { return Symmetry.Rot000; } } } public class SymmetryGroup : SymmetryMonoid, IGroup<Symmetry> { public Symmetry Inverse(Symmetry a) { switch (a) { case Symmetry.Rot000: return Symmetry.Rot000; case Symmetry.Rot090: return Symmetry.Rot270; case Symmetry.Rot180: return Symmetry.Rot270; case Symmetry.Rot270: return Symmetry.Rot090; case Symmetry.RefVer: return Symmetry.RefVer; case Symmetry.RefDes: return Symmetry.RefAsc; case Symmetry.RefHoz: return Symmetry.RefHoz; case Symmetry.RefAsc: return Symmetry.RefDes; } throw new NotImplementedException(); } }
Integral Value Types and the Commutative Ring with Unity over
C# exposes a number of fixed bit integral value types that allow a programmer to pick an integral value type suitable for the scenario at hand. Operations over these integral value types form a commutative ring with unity whose set is the congruence class where is the number of bits used to represent the integer and is the equivalance class with .
Addition is given by just as multiplication is given by . Both statements are equivalent to the following congruence statements: and respectively.
Under the binary numeral system, modulo is equivalent to ignoring the bits exceeding , or equivalently, where . As a result only the first (right most) bits need to be considered when computing the sum or product of two congruence classes, or in this case, integer values in C#. Thus, in the following implementation, it is not necessary to write any extra code to represent these operations other than writing them in their native form.
The reason why we are limited to a commutative ring with unity instead of a full field is that multiplicative inverses do not exist for all elements. A multiplicative inverse only exists when where is the multiplicative inverse of . For a solution to exist, . Immediately, any even value of will not have a multiplicative inverse in . However, all odd numbers will.
public class AddativeIntegerGroupoid : IGroupoid<long> { public long Operation(long a, long b) { return a + b; } } public class AddativeIntegerSemigroup : AddativeIntegerGroupoid, ISemigroup<long> { } public class AddativeIntegerMonoid : AddativeIntegerSemigroup, IMonoid<long> { public long Identity { get { return 0L; } } } public class AddativeIntegerGroup : AddativeIntegerMonoid, IGroup<long> { public long Inverse(long a) { return a; } } public class AddativeIntegerAbelianGroup : AddativeIntegerGroup, IAbelianGroup<long> { } public class MultiplicativeIntegerGroupoid : IGroupoid<long> { public long Operation(long a, long b) { return a * b; } } public class MultiplicativeIntegerSemigroup : MultiplicativeIntegerGroupoid, ISemigroup<long> { } public class MultiplicativeIntegerMonoid : MultiplicativeIntegerSemigroup, IMonoid<long> { public long Identity { get { return 1L; } } } public class IntegerRingoid : IRingoid<long, AddativeIntegerGroupoid, MultiplicativeIntegerGroupoid> { public AddativeIntegerGroupoid Addition { get; private set;} public MultiplicativeIntegerGroupoid Multiplication { get; private set;} public IntegerRingoid() { Addition = new AddativeIntegerGroupoid(); Multiplication = new MultiplicativeIntegerGroupoid(); } public long Distribute(long a, long b) { return Multiplication.Operation(a, b); } } public class IntegerSemiring : IntegerRingoid, ISemiring<long, AddativeIntegerSemiring, MultiplicativeIntegerSemiring> { public AddativeIntegerSemiring Addition { get; private set;} public MultiplicativeIntegerSemiring Multiplication { get; private set;} public IntegerSemiring() : base() { Addition = new AddativeIntegerSemiring(); Multiplication = new MultiplicativeIntegerSemiring(); } } public class IntegerRing : IntegerSemiring, IRing<long, AddativeIntegerGroup, MultiplicativeIntegerSemigroup>{ public new AddativeIntegerGroup Addition { get; private set; } public IntegerRing() : base() { Addition = new AddativeIntegerGroup(); } } public class IntegerRingWithUnity : IntegerRing, IRingWithUnity<long, AddativeIntegerGroup, MultiplicativeIntegerMonoid> { public MultiplicativeIntegerMonoid Multiplication { get; private set; } public IntegerRingWithUnity() : base() { Multiplication = new MultiplicativeIntegerMonoid(); } }
Floatingpoint Value Types and the Real Vector Space
C# offers three types that approximate the set of Reals: floats, doubles and decimals. Floats are the least representative followed by doubles and decimals. These types are obviously not continuous, but the error involved in rounding calculations with respect to the calculations in question are negligible and for most intensive purposes can be treated as continuous.
As in the previous discussion on the integers, additive and multiplicative classes are defined over the algebraic structures defined in the Group and Ring Theory sections presented above. In addition to these implementations, an additional class is defined to describe a vector.
public class Vector<T> { private T[] vector; public int Dimension { get { return vector.Length; } } public T this[int n] { get { return vector[n]; } set { vector[n] = value; } } public Vector() { vector = new T[2]; } }
With these classes, it is now possible to implement the algebraic structures presented in the Module Theory section from above.
public class RealVectorModule : IModule<double, Vector<double>, RealRing, AddativeRealGroup, MultiplicativeRealSemigroup, VectorAbelianGroup<double>> { public RealRing Scalar { get; private set; } public VectorAbelianGroup<double> Vector { get; private set; } public RealVectorModule() { Scalar = new RealRing(); Vector = new VectorAbelianGroup<double>(new AddativeRealAbelianGroup()); } public Vector<double> Distribute(double t, Vector<double> r) { Vector<double> c = new Vector<double>(); for (int i = 0; i < c.Dimension; i++) c[i] = Scalar.Multiplication.Operation(t, r[i]); return c; } } public class RealVectorUnitaryModule : RealVectorModule, IUnitaryModule<double, Vector<double>, RealRingWithUnity, AddativeRealGroup, MultiplicativeRealMonoid, VectorAbelianGroup<double>> { public new RealRingWithUnity Scalar { get; private set; } public RealVectorUnitaryModule() : base() { Scalar = new RealRingWithUnity(); } } public class RealVectorVectorSpace : RealVectorUnitaryModule, IVectorSpace<double, Vector<double>, RealField, AddativeRealAbelianGroup, MultiplicativeRealAbelianGroup, VectorAbelianGroup<double>> { public new RealField Scalar { get; private set; } public RealVectorVectorSpace() : base() { Scalar = new RealField(); } }
Representation of Reference Types
The following are examples of how each theory presented above can leverage reference types found in the C# language to represent concepts drawn from computer science.
Strings, Computability and Monoids
Strings are the simplest of reference types in C#. From an algebraic structure point of view, the set of possible strings, , generated by an alphabet, , and paired with a concatenation operation, , forms a monoid.
public class StringGroupoid : IGroupoid<string> { public string Operation(String a, String b) { return string.Format("{0}{1}", a, b); } } public class StringSemigroup : StringGroupoid, ISemigroup<string> { } public class StringMonoid : StringSemigroup, IMonoid<string> { public string Identity { get { return string.Empty; } } }
Monoids over strings have a volley of applications in the theory of computation. Syntactic Monoids describe the smallest set that recognizes a formal language. Trace Monoids describe concurrent programming by allowing different characters of an alphabet to represent different types of locks and synchronization points, while the remaining characters represent processes.
Classes, Interfaces, Type Theory and Semirings
Consider the set of types , that are primitive and constructed in C#. The generating set of is the set of primitive reference and value types, , consisting of the types discussed thus far. New types can be defined by defining classes and interfaces.
A simple operation over takes two types, , and yields a third type, , known as a sum type. In type theory, this means that an instance of can be either an instance of or . A second operation over takes two types and yields a third type representing a tuple of the first two types. In other words, .
Both operations form a semigroup and and in conjunction the two form a semiring.
To implement this semiring is a little involved. The .NET library supports emitting dynamic type definitions at runtime. For sum types, this would lead to an inheritance view of the operation. Types and would end up deriving from which means that any sequence of sums would yield an inheritance tree. A product type would result in composition of types with projection operations, , to access and assign the element of the composite. Both type operation implementations are outside the scope of this writeup and I’ll likely revisit this topic in a future writeup.
Delegates and Process Algebras
The third type of reference type to mention is the delegate type which is C#’s approach to creating firstclass functions. The simplest of delegates is the builtin Action delegate which represents a single procedure taking no inputs and returning no value.
Given actions , we can define a possible execution operator, , where either or is executed denoted as . The choice operation forms a commutative semigroup since operations are associative and the operation is commutative .
A product operation, , representing the sequential execution of and then is given by . The sequence operator forms a groupoid with unity since the operation is not associative and there is an identity action representing a void operation resulting in .
Both operations together form a ringoid, since the sequence operation distributes over the choice operation . Meaning that takes place and then or takes places is equivalent to and then takes place or and then takes place.
public class SequenceGroupoidWithUnity<Action> : IGroupoid<Action> { public Action Identity { get { return () => {}; } } public Action Operation(Action a, Action b) { return () => { a(); b(); } } } public class ChoiceGroupoid<Action> : IGroupoid<Action> { public Action Operation(Action a, Action b) { if(DateTime.Now.Ticks % 2 == 0) return a; return b; } }
The process algebra an be extended further to describe parallel computations with an additional operation. The operations given thus far enable one to derive the possible execution paths in a process. This enables one to comprehensively test each execution path to achieve complete test coverage.
Examples
The motivation of this work was to achieve C++’s approach to parametric polymorphism by utilizing C# subtype polymorphism to define the algebraic structure required by a method (akin to the builtin operations on types in C++). To illustrate how these interfaces are to be used, the following example extension methods operate over a collection of a given type and accept the minimal algebraic structure to complete the computation. The result is a single implementation of the calculation that one would expect in C++.
static public class GroupExtensions { static public T Sum<T>(this IEnumerable<T> E, IMonoid<T> m) { return E .FoldL(m.Identity, m.Operation); } } static public class RingoidExtensions { static public T Count<T, R, A, M>(this IEnumerable<R> E, IRingWithUnity<T, A, M> r) where A : IGroup<T> where M : IMonoid<T> { return E .Map((x) => r.Multiplication.Identity) .Sum(r.Addition); } static public T Mean<T, A, M>(this IEnumerable<T> E, IDivisionRing<T, A, M> r) where A : IGroup<T> where M : IGroup<T> { return r.Multiplication.Operation( r.Multiplication.Inverse( E.Count(r) ), E.Sum(r.Addition) ); } static public T Variance<T, A, M>(this IEnumerable<T> E, IDivisionRing<T, A, M> r) where A : IGroup<T> where M : IGroup<T> { T average = E.Mean(r); return r.Multiplication.Operation( r.Multiplication.Inverse( E.Count(r) ), E .Map((x) => r.Addition.Operation(x, r.Addition.Inverse(average))) .Map((x) => r.Multiplication.Operation(x, x) ) .Sum(r.Addition) ); } } static public class ModuleExtensions { static public TV Mean<TS, TV, TSR, TSRA, TSRM, TVA>(this IEnumerable<TV> E, IVectorField<TS, TV, TSR, TSRA, TSRM, TVA> m) where TSR : IField<TS, TSRA, TSRM> where TSRA : IAbelianGroup<TS> where TSRM : IAbelianGroup<TS> where TVA : IAbelianGroup<TV> { return m.Distribute( m.Scalar.Multiplication.Inverse( E.Count(m.Scalar) ), E.FoldL( m.Vector.Identity, m.Vector.Operation ) ); } }
Conclusion
Abstract Algebra comes with a rich history and theory for dealing with different algebraic structures that are easily represented and used in the C# language to perform type agnostic computations. Several examples drawn from mathematics and computer science illustrated how the solution can be used for both value and reference types in C# and be leveraged in the context of a few example type agnostic computations. The main benefit of this approach is that it minimizes the repetitious coding of computations required under the adhoc polymorphism approach adopted by the designers of C# language. The downside is that several structures must be defined for the types being computed over and working with C# parameter constraint system can be unwieldy. While an interesting study, this solution would not be practical in a production setting under the current capabilities of the C# language.
References
Baeten, J.C.M. A Brief History of Process Algebra [pdf]. Department of Computer Science, Technische Universiteit Eindhoven. 31 Mar. 2012.
ECMA International. Standard ECMA335 Common Language Infrastructure [pdf]. 2006.
Fokkink, Wan. Introduction of Process Algebra [pdf]. 2nd ed. Berlin: SpringerVerlang, 2007. 10 Apr. 2007. 31 Mar. 2012.
Goodman, Joshua. Semiring Parsing [pdf]. Computational Linguistics 25 (1999): 573605. Microsoft Research. 31 Mar. 2012.
Hungerford, Thomas. Algebra. New York: Holt, Rinehart and Winston, 1974.
Ireland, Kenneth. A classical introduction to modern number theory. New York: SpringerVerlag, 1990.
Litvinov, G. I., V. P. Maslov, and A. YA Rodionov. Universal Algorithms, Mathematics of Semirings and Parallel Computations [pdf]. Spring Lectures Notes in Computational Science and Engineering. 7 May 2010. 31 Mar. 2012 .
Mazurkiewicz, Antoni. Introduction to Trace Theory [pdf]. Rep. 19 Nov. 1996. Institute of Computer Science, Polish Academy of Sciences. 31 Mar. 2012.
Pierce, Benjamin. Types and programming languages. Cambridge, Mass: MIT Press, 2002.
Stroustrup, Bjarne. The C++ Programming Language. Reading, Mass: AddisonWesley, 1986.