#!/usr/bin/env python
#
# Copyright (C) 2010  Kipp Cannon, Chad Hanna, Leo Singer
#
# 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.
"""Estimate power spectra from LIGO frames or simulated h(t)."""


#
# parse command line
#


from optparse import OptionParser
from gstlal import datasource
from gstlal import reference_psd


def parse_command_line():
	parser = OptionParser(description = __doc__)

	# generic "source" options
	datasource.append_options(parser)

	# add our own options
	parser.add_option("--write-psd", metavar = "filename", help = "Write measured noise spectrum to this LIGO light-weight XML file (required).")
	parser.add_option("--sample-rate", metavar = "Hz", default = 16384, type = "int", help = "Sample rate at which to generate the PSD, default 16384 Hz")
	parser.add_option("--psd-fft-length", metavar = "s", default = 8, type = "int", help = "FFT length, default 8s")
	parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose (optional).")

	options, filenames = parser.parse_args()

	# check our own options
	if options.write_psd is None:
		raise ValueError("Must specify --write-psd")

	return options, filenames


#
# =============================================================================
#
#                                     Main
#
# =============================================================================
#


options, filenames = parse_command_line()


# parse the generic "source" options, check for inconsistencies is done inside
# the class init method
detectors = datasource.GWDataSourceInfo(options)


reference_psd.write_psd(options.write_psd, dict((instrument, reference_psd.measure_psd(detectors, instrument, options.sample_rate, psd_fft_length = options.psd_fft_length, verbose = options.verbose)) for instrument in detectors.channel_dict), verbose = options.verbose)
