#!/usr/bin/python3.13
#
# Copyright (C) 2013  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.

from optparse import OptionParser

from gstlal.psd import movingmedian, polyfit
from gstlal.psd import read_psd, write_psd

### A program to fit a PSD to a polynomial
###
###
### Usage cases
### -----------
###
### 1. Fit a PSD to a polynomial with default settings (consider using gstlal_plot_psd to compare the results)::
###
###	$ gstlal_psd_polyfit --output smooth.xml.gz H1refpsd.xml.gz
###
###
### 2. Please add more
###
###

parser = OptionParser(description = __doc__)
parser.add_option("--median-window", type = int, default = 8, help="Median window in sample points to apply running median for removing sharp features. Default 8.  Setting it to 1 effectively disables this filter.")
parser.add_option("--output", metavar = "filename", help = "Set the name of the LIGO light-weight XML file to output")
parser.add_option("--poly-order", type = int, default = 10, help = "Set the order of the fitting polynomial. default 10")
parser.add_option("--low-fit-freq", type = float, default = 30, help = "Set the low frequency at which to begin fitting in Hz. default 30")
parser.add_option("--high-fit-freq", type = float, default = 6500, help = "Set the high frequency at which to stop fitting in Hz. default 6500")

options, filenames = parser.parse_args()

psds = read_psd(filenames[0], verbose=True)

for ifo, psd in psds.items():
	psd = movingmedian(psd, options.median_window)
	psds[ifo] = polyfit(
		psd,
		options.low_fit_freq,
		options.high_fit_freq,
		options.poly_order,
		verbose=True
	)

write_psd(options.output, psds)
