##^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Lance Simms, Stanford University 2009
#MeanAndVarianceByBin.py
#
#PURPOSE:
#  To calculate the mean vs. variance of a data set as a function of some 
#  other variable.  For instance, in photon transfer, the variance
#  is seen to be a function of the mean number of integrated photons. 
#
#INPUTS:
#  BinArray: float array
#    The array that contains the values used to sort the data
#  Values:
#    The values that will be binned
#  Min: float
#    The minimum bin value
#  Max: float
#    The maximum bin value
#  N_Bins: float
#    The number of bins to sort the data
#
from numpy import *
import pyfits

def MeanAndVarianceByBin(BinArray, Values, Min, Max, N_Bins):

  #Convert to floats
  Min = float(Min); Max=float(Max); N_Bins=float(N_Bins)

  #Calculate the Range and Bin Increment
  Range  = Max - Min
  BinInc = Range/N_Bins
  Means  = zeros(N_Bins, dtype=float32)
  Vars   = zeros(N_Bins, dtype=float32)
  for Bin, BinNum in zip(arange(Min, Max, BinInc),arange(N_Bins)):
    Crit = (BinArray > Bin) & (BinArray <= Bin+BinInc)
    IndInBin = (where(Crit))[0]
    NumInBin = len(IndInBin)
    Means[BinNum] = mean(Values[IndInBin])
    Vars[BinNum]  = var(Values[IndInBin])
    print str(Bin)+ ", " + str(NumInBin) + " , "+ \
          str(mean(Values[IndInBin])) + " , " \
          + str(std(Values[IndInBin]))+ " , " + str(var(Values[IndInBin]))
  return Means, Vars
