This package contains Python and C code for performing Bayesian latent
class analysis using the fast Monte Carlo algorithm of Newman (2025).

Files:
  lca.c: The main C code for the algorithm
  lca.h: C header file for using the code in C
  rnglong.c, rnglong.h: Random number generator
  Makefile: Makefile for compiling the code on Unix-style systems such as Linux
  pylca.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 liblca.so lca.c rnglong.c -lm

This will produce a file liblca.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, which can be thought of as a survey of N
individuals, each of whom gives answers to Q multiple choice questions, and
returns a set of latent class assignments of individuals to classes,
sampled from the posterior of the model described in the paper.  Each
sample consists of an integer k representing the number of classes, and an
array of class assignments with values 0...k-1, one for each individual.

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

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
      individual belongs

class LCA(a, kq, initial=None, alpha=1.0):

      This class provides methods for performing the Monte Carlo.

      a: an N-by-Q numpy array of integers containing the survey response
      data, such that a[i,q] represents individual i's response to question
      q.  Allowed responses are coded as integers starting at 0.  Missing
      data should be coded as its own value.  Thus if the question is "Do
      you like ice cream?" then the possible answers might be coded as 0:
      No, 1: Yes, 2: Don't know, 3: Missing data.

      kq: numpy array of Q integers giving the number of distinct answers
      to each of the Q questions.  This is the number of *possible*
      answers, not the number that were actually given by the respondents.
      Thus, for instance, the question above about ice cream has 4 answers,
      and this would be true even if, say, no one answered "Don't know".
      (Which, really, why would they?  Who doesn't know if they like ice
      cream?)

      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 individuals in a single class together.  This is a good
      choice in most cases, so it's normally safe to omit this parameter.

      alpha: float, the value of the concentration parameter for the
      symmetric Dirichlet prior on the response probabilities.  The default
      value of 1.0 corresponds to a flat (uninformative) prior, which is
      usually a good choice.  Omit this parameter unless you know what you
      are doing.


The LCA object provides the following methods:

LCA.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 individuals in the survey, as previously.  A typical
	value for thorough burn-in would be nsweeps=2500.

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

	Perform the given number of sweeps of the Monte Carlo, starting
	from the current state, and record the class assignments of all
	individuals 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 class
	assignments every tsample sweeps.

	permute: bool, whether to permute class labels.  If True (the
        default) the class 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 class labels,
        which is formally impossible because of symmetry with respect to
        permutations (so-called class 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 classes k and a class 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.


Variables:

Some of the variables belonging to the LCA object can also be useful:

     LCA.state: State() object containing the current Monte Carlo state

     LCA.acceptance: float, the value of the average acceptance ratio for
     the most recent Monte Carlo run (or zero if no run has been performed
     yet).  The acceptance ratio is the fraction of Monte Carlo moves that
     actually change the state of the system.  Typical values range from
     about 0.1 to 0.5.  This ratio can be useful for deciding how
     frequently to draw samples.  Roughly speaking, if the acceptance ratio
     is A then one should draw samples about every 1/A sweeps.  More often
     is fine, but less often than this will result in wasted computer time.


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.  In real life
the length of the sampling run (nsweeps) would usually be longer -- up to
100,000 sweeps or more -- and the sampling interval (tsample) might be
smaller, so a larger number of samples would be generated.  The values used
here are just for demonstration purposes: they avoid printing out a lot of
useless numbers.  A copy of this code is in the file example.py.

from pylca import LCA
from numpy import array

# Simple data set
a = array([[0, 2, 0, 1, 1, 1],
           [0, 0, 0, 1, 1, 1],
           [0, 1, 0, 2, 1, 1],
           [1, 0, 0, 1, 1, 1],
           [0, 0, 0, 0, 1, 1],
           [1, 1, 2, 0, 0, 0],
           [1, 0, 1, 0, 0, 0],
           [1, 2, 1, 0, 1, 0],
           [2, 1, 0, 0, 0, 0],
           [1, 0, 0, 1, 0, 0]], int)
kq = array([3, 3, 3, 3, 2, 2], int)

# Parameters of the MCMC
nburnin,nsweeps = 2500,10000
tsample = 100

# Create the LCA object and pass the data to it
lca = LCA(a,kq)

# Perform a certain number of sweeps to burn in the Monte Carlo
lca.burnin(nburnin)

# Run the Monte Carlo and draw samples
samples = lca.run(nsweeps,tsample)

# Print the samples
for s in samples: print(s.k,s.g)

# Print the acceptance ratio
print("Acceptance ratio =",lca.acceptance)
