""" -*- mode: python -*-
Create an NTuple with power-law weights and exercise axis bindings
access through PyDataRep.

@author J. Chiang <jchiang@slac.stanford.edu>
"""
#
#$Id: weighted_pl.py.in,v 1.10 2003/09/17 17:38:07 jchiang Exp $
#

import sys
sys.path.reverse()
sys.path.append('@top_srcdir@/python')
sys.path.append('@top_builddir@/python')
sys.path.reverse()

from setPath import *

import random
shoot = random.uniform

pl_wt = lambda x:x**(-2.1)

import hippoplotter as plot
nt = plot.newNTuple( ([], [], [], []), ("x", "y", "wt", "ywt") )

nsamp = 10000
for i in range(nsamp):
    x = shoot(0, 1)
    y = shoot(0, 1)
    nt.addRow( (x, y, pl_wt(x), pl_wt(y)) )

#
# Set the "plot" x-axis range to suppress empty bins at small x values.
#
xcol = nt.getColumn("x")
hist = plot.Histogram( nt, "x", xlog=1, ylog=1,
                               xrange=(min(xcol), max(xcol)) )

dataRep = hist.getDataRep()
dataRep.setWeight( "wt" )

powerlaw = plot.hippo.Function( "PowerLaw", dataRep )
powerlaw.addTo( hist )
powerlaw.fit()

#
# Add a second dataRep to the same plot
#
dataRep2 = plot.hippo.DataRep( "Histogram", nt, ("y", ) )
dataRep2.setWeight( "ywt" )
hist.addDataRep( dataRep2 )

#
# Set the (logrithmic) bin width of dataRep2 to be three times the size as
# that of dataRep.
#
dataRep2.setBinWidth( "x", 3.*dataRep.getBinWidth("x") )

xyhist = plot.XYHist( nt, "x", "y" )
newRep = xyhist.getDataRep()

#
# Set the weight for the 2D data rep
#
newRep.setWeight( "wt" )
xyhist.setLog( "z", 1 )

#
# One must specify the axes and labels exactly or else an exception
# is thrown.
#
newRep.setAxisBinding("X", "wt")
newRep.setAxisBinding("Y", "x")

print "setAxisBinding(s); 3 exception tests follow:"
try:
    newRep.setAxisBinding("x", "wt")
except RuntimeError, e:
    print e

try:
    newRep.setAxisBinding("X", "weight")
except RuntimeError, e:
    print e

try:
    newRep.setAxisBindings(("X", "weight"))
except RuntimeError, e:
    print e

#
# Switch back.
#
newRep.setAxisBindings( ("x", "y") )
