#!/usr/bin/env python
# Makes a scatter plot with circles having area proportional to the number of
# of events at exactly that (x,y).  The area adjustment is useful for binned
# data, which would otherwise hide multiple events.  For high resolution data,
# it is unlikely that the points would exactly overlap.
# v0.1 6 October, 2008
import sys, re
import simpleSVG
from math import sqrt 
from optparse import OptionParser
usage="usage: %prog infile.dat svgfile.svg [options]"
parser = OptionParser(usage=usage, version="%prog 0.1")
#parser = OptionParser()
parser.add_option("--x1", dest="x1",type="float",help="lower limit to x-axis",default=-1.0)
parser.add_option("--x2", dest="x2",type="float",help="upper limit to x-axis",default= 1.0)
parser.add_option("--y1", dest="y1",type="float",help="lower limit to y-axis",default=-1.0)
parser.add_option("--y2", dest="y2",type="float",help="upper limit to y-axis",default= 1.0)
parser.add_option("--cx", dest="cx",type="int",help="column with x data",default=1)
parser.add_option("--cy", dest="cy",type="int",help="column with y data",default=2)
parser.add_option("-t", dest="title",type="string",help="title")
parser.add_option("--xl", dest="xlab",type="string",help="x-axis label")
parser.add_option("--yl", dest="ylab",type="string",help="y-axis label")
(opt, args) = parser.parse_args()
try:
	infilename=args[0]
except:
	print usage
	sys.exit();
try:
	svgfile=args[1]
except:
	svgfile="out.svg"
#sys.exit()
cx=opt.cx-1
cy=opt.cy-1
b=simpleSVG.svg_class(fname=svgfile)
b.group(fill='black')
b.scale(xmin=opt.x1,xmax=opt.x2,ymin=opt.y1,ymax=opt.y2,leftmarg=80,rightmarg=20)
inf=open(infilename,'r')
b.xaxis()
b.yaxis()
xa=[]
ya=[]
rad=50L #radius of smallest circle (for 1 event) is 50/100 pt, or .5pt
b.group(stroke='red',fill='red')
points={} # dictionary to store number of events at position (x,y).  
while 1:
	aline=inf.readline().strip()
	if not aline: break
	if re.match('\#',aline): continue
	v=aline.split()
	x=v[cx]
	y=v[cy]
	key=x+','+y
	if points.has_key(key):
		points[key]+=1
	else:
		points[key]=1
for key in points.keys():
	num=points[key]
	x,y  = [ float(q) for q in key.split(',')]
	radd=long(rad*sqrt(float(num))) # radd is past as a long integer
	b.circle(x,y,radd)
b.group()
if opt.title: b.text(.56j, .06j,0.,opt.title,font_size="24pt",text_anchor="middle")
if opt.xlab: b.text(.5j,.98j,0.,opt.xlab,font_size="14pt")
if opt.ylab: b.text(.05j,.5j,90.,opt.ylab,font_size="14pt")
b.close()
