"""This module implements the chi square test of correlation.

Functions:
score2    Score the difference in the distribution of 2 groups.

"""
from Numeric import sum

import numrec

def score2(X11, X12, X21, X22):
    """score2(X11, X12, X21, X22) -> chsq, prob

    Score the difference in the distribution between 2 groups.  X11
    (etc) are the counts of the observations in a 2-way matrix where
    the two numbers are the row and column of the matrix.

    """
    observed = [
        X11, X12,
        X21, X22
        ]
    observed = map(float, observed)
    total = sum(observed)

    row_sum = [
        observed[0] + observed[1],
        observed[2] + observed[3]
        ]
    col_sum = [
        observed[0] + observed[2],
        observed[1] + observed[3]
        ]

    expected = [None] * 4
    expected[0] = row_sum[0] * col_sum[0] / total
    expected[1] = row_sum[0] * col_sum[1] / total
    expected[2] = row_sum[1] * col_sum[0] / total
    expected[3] = row_sum[1] * col_sum[1] / total

    df, chsq, prob = numrec.chsone(observed, expected, 3)
    return chsq, prob
