This package contains Python and C code for fitting a Bayesian Gaussian
mixture model using the fast Monte Carlo algorithm of Newman (2025).

Files:
  gaussmix.c: The main C code for the algorithm
  rnglong.c, rnglong.h: Random number generator
  Makefile: Makefile for compiling the code on Unix-style systems such as Linux
  pygaussmix.py: Python wrapper for using the code in Python
  example.py: Example Python application
  license.txt: Licensing
  readme.txt: This readme file

Installation:

The code that actually performs the Monte Carlo is written in the C
programming language for speed.  (C code is typically about 100 times
faster than equivalent code in Python.)  To install this package you must
compile the code, which requires that you have a C compiler, such as gcc on
Linux or Visual Studio on Windows.  On Linux, compilation can be done with
the following command, executed in the directory containing the code:

gcc -O2 -shared -fPIC -o libgaussmix.so gaussmix.c rnglong.c -lm

This will produce a file libgaussmix.so, which should be placed in the directory
where you will be running the code.  A Linux make file is also included for
automated compilation.

On Windows or Mac there are equivalent compilation commands, but the author
does not currently have access to these systems, so the code has not been
tested there.


Use:

The software takes a data set of univariate observations and returns a set
of component assignments of observations to clusters, sampled from the
posterior of the model described in the paper.  Each sample consists of an
integer k representing the number of components, and an array of components
assignments with values 0...k-1, one for each observation.

The package provides two Python object classes, which can be imported from
pygaussmix.

class State(k=None, g=None):

      Objects in this class represent single latent class assignments

      k: integer, number of classes

      g: array of N integers 0...k-1, representing the class to which each
      observation belongs

class Gaussian(x, sigma, a, initial=None):

      This class provides methods for performing the Monte Carlo.

      x: an N-element array of real-valued observations

      sigma: standard deviation of the mixture model, which is assumed known

      a: range over which the means of the Gaussians fall

      initial: a State() object giving the initial state for the Monte
      Carlo.  If no value is given the program assumes an initial state
      with all observations in a single component together.  This is a good
      choice in most cases, so it's normally safe to omit this parameter.


The Gaussian object provides the following methods:

Gaussian.burnin(nsweeps):

	Perform the given number of Monte Carlo sweeps, starting from the
	current state, to "burn in" the calculation.  Markov chain Monte
	Carlo methods, such as the one used here, need to equilibrate,
	meaning the distribution of samples needs to converge from its
	initial state (which is usually a low-probability state) to the
	posterior distribution of the model.  This function does this.

	nsweeps: integer, the number of sweeps to perform to burn in the
	Monte Carlo.  A "sweep" is N Monte Carlo steps, where N is the
	number of observations in the data, as previously.  A typical
	value for thorough burn-in would be nsweeps=2500.

Gaussian.run(nsweeps,tsample,permute=True):

	Perform the given number of sweeps of the Monte Carlo, starting
	from the current state, and record the component assignments of all
	observations at specified intervals.  You can do repeated calls to
	this function and each run will automatically continue from
	wherever the previous one left off, so you can easily pause in the
	middle of a calculation, or go back and take more samples if you
	don't have enough.

	nsweeps: integer, total number of sweeps to perform

	tsample: integer, sampling interval.  The program records the
	component assignments every tsample sweeps.

	permute: bool, whether to permute component labels.  If True (the
        default) the labels are randomly permuted before each sample is
        drawn.  This has no effect on the results, but eliminates the
        possibility of any apparent significance to specific component
        labels, which is formally impossible because of symmetry with
        respect to permutations (so-called label switching).  The
        permutation action is performed efficiently and incurs no
        significant performance penalty.  Omit this parameter unless you
        know what you are doing.

	Return value: numpy array of State() objects, one for each sample,
	each containing a number of components k and a component assignment
	array g.  The length of the array is, by definition, equal to
	nsweeps//tsamples.  For instance, if you ask for 100,000 sweeps and
	a sampling interval of 100, you will get an array of 1000 samples.


Seeding the random number generator:

The code uses the standard Python random number generator, so if you want
to seed the random numbers explicitly you should just call random.seed() as
normal before the start of any calculations.  Repeated runs seeded with the
same seed will then produce identical results, which can be useful for
reproducibility, debugging, and running on parallel architectures.  If no
seed is specified, you will get the default Python behavior, which on most
systems means the program will choose a random seed, for instance from the
system clock or from some operating-system-level source of randomness.


Example application:

Here is a minimal working example of the use of this package.  A copy of this code is in the file example.py.

import random as rng
from numpy import empty,zeros,arange
import numpy.random as nprng
import matplotlib.pyplot as plt
from pygaussmix import Gaussian

N = 1000
k = 5
sigma = 1.0
a = 100.0
spacing = 4.0

burnin = 1000
nsweeps = 100000
tsample = 1
nsamples = nsweeps//tsample

# Seed the random number generators
rng.seed(1)
nprng.seed(1)

# Generate some random data
g = empty(N,int)
x = empty(N,float)
for i in range(N):
    g[i] = rng.randrange(k)
    x[i] = nprng.normal(loc=spacing*g[i],scale=sigma)

# Create the Gaussian object
gaussian = Gaussian(x,sigma,a)

# Run the Monte Carlo
print("Burning in...")
gaussian.burnin(burnin)
print("Sampling...")
samples = gaussian.run(nsweeps,tsample,permute=False)

# Output results
hmax = 20
histogram = zeros(hmax,int)
for s in samples: histogram[s.k] += 1
plt.bar(arange(hmax),histogram/nsamples)
plt.show()
