#!/usr/bin/env python
#
# Copyright (C) 2011  Chad Hanna
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import numpy
from scipy.interpolate import interp1d
import sys
from gstlal import reference_psd
from pylal.xlal import datatypes
from pylal.xlal.datatypes import lalunit
from optparse import OptionParser

parser = OptionParser(description = __doc__)
parser.add_option("--instrument", help="instrument, e.g. H1")
parser.add_option("--output", metavar = "filename", help = "Set the name of the LIGO light-weight XML file to output")
parser.add_option("--df", metavar = "float", type = "float", default = 0.25, help = "set the frequency resolution to interpolate to, default = 0.25")
parser.add_option("--type", metavar = "ASD|PSD", default = "ASD", help = "input is ASD or PSD, default ASD")

options, filenames = parser.parse_args()

data = numpy.loadtxt(filenames[0], comments = '#')
f = data[:,0]
if options.type == "ASD":
	psd = data[:,1]**2
elif options.type == "PSD":
	psd = data[:,1]
else:
	raise ValueError("--type must be ASD or PSD")

#FIXME hack to pad the series since it doesn't start at 0 :(
f_padded = numpy.concatenate((numpy.arange(0, f[0], options.df), f))
psd_padded = numpy.concatenate((numpy.ones(len(f_padded) - len(f)) * psd[0], psd))

uniformf = numpy.arange(0, f_padded.max(), options.df)
psdinterp = interp1d(f_padded, psd_padded)

psd = psdinterp(uniformf)

psdseries = datatypes.real8frequencyseries.REAL8FrequencySeries(deltaF=options.df, data=psd, sampleUnits=lalunit.LALUnit("s strain^2"), f0=0)
reference_psd.write_psd(options.output, {options.instrument: psdseries})
