#!/usr/bin/python3.13
#
# 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)."""

### This program will measure a power spectral density from data
###
### This program will measure the PSD of data  Its input is anything
### supported by datasource.py.
###
### Graph of the gsreamer pipeline
### ------------------------------
###
### Please see :py:func:`psd.measure_psd`
###
### Usage
### -----
###
### 1. Measure the PSD of frame data found in a file called frame.cache. Note: you can make frame cache with lalapps_path2cache, e.g.,::
###
###	$ gstlal_reference_psd --data-source frames --frame-cache frame.cache \\
###	--gps-start-time=900000000 --gps-end-time=900005000 \\
###	--channel-name=H1=FAKE-STRAIN --channel-name=L1=FAKE-STRAIN \\
###	--write-psd psd.xml.gz --verbose
###
###    See :any:`gstlal_plot_psd` to plot the result
###
### 2. Measuring the PSD of low-latency data (e.g. on CIT cluster)::
###
###	$ gstlal_reference_psd --data-source framexmit --channel-name=L1=FAKE-STRAIN  \\
###	--write-psd psd.xml.gz
###
### 3. Other things are certainly possible, please add them!
###
### Related programs
### ----------------
###
### - :any:`gstlal_plot_psd`
### - :any:`gstlal_plot_psd_horizon`
### - :any:`gstlal_spectrum_movie`
###  

#
# parse command line
#


from optparse import OptionParser

from gstlal import datasource
from gstlal.psd import measure_psd, write_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.DataSourceInfo.from_optparse(options)

psds = {}
for instrument in detectors.channel_dict:
	psds[instrument] = measure_psd(
		detectors,
		instrument,
		options.sample_rate,
		psd_fft_length=options.psd_fft_length,
		verbose=options.verbose,
	)

write_psd(options.write_psd, psds, verbose=options.verbose)
