#!/home/conda/feedstock_root/build_artifacts/gstlal-inspiral_1694401452756/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_place/bin/python
#
# Copyright (C) 2009-2014  Kipp Cannon, Chad Hanna, Drew Keppel
#
# 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.


#
# =============================================================================
#
#                                   Preamble
#
# =============================================================================
#


try:
	from fpconst import PosInf
except ImportError:
	# fpconst is not part of the standard library and might not be
	# available
	PosInf = float("+inf")
import numpy
from optparse import OptionGroup, OptionParser
import sys
import threading

import gi
gi.require_version('Gst', '1.0')
from gi.repository import GObject, Gst
GObject.threads_init()
Gst.init(None)

import lal

from ligo.lw import ligolw
from ligo.lw import utils as ligolw_utils
from gstlal import datasource
from gstlal import lloidhandler
from gstlal import multirate_datasource
from gstlal import pipeparts
from gstlal import simplehandler


#
# =============================================================================
#
#                                 Command Line
#
# =============================================================================
#


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

	datasource.append_options(parser)

	group = OptionGroup(parser, "PSD Options", "Adjust noise spectrum estimation parameters")
	group.add_option("--psd-fft-length", metavar = "seconds", default = 32, type = "int", help = "The length of the FFT used to used to whiten the data (default is 32 s).")
	group.add_option("--reference-psd", metavar = "filename", help = "Instead of measuring the noise spectrum, load the spectrum from this LIGO light-weight XML file (optional).")
	group.add_option("--track-psd", action = "store_true", help = "Enable dynamic PSD tracking.  Always enabled if --reference-psd is not given.")
	parser.add_option_group(group)

	group = OptionGroup(parser, "Output Options", "Control Output File")
	group.add_option("--output", metavar = "filename", help = "Set the name of the XML file to which to write the histogram data (required).")
	parser.add_option_group(group)

	group = OptionGroup(parser, "Program Behaviour")
	group.add_option("-v", "--verbose", action = "store_true", help = "Be verbose (optional).")
	parser.add_option_group(group)

	options, filenames = parser.parse_args()

	#
	# do this before messing with options object
	#

	process_params = options.__dict__.copy()

	#
	# extract data source configuration
	#

	detectors = datasource.DataSourceInfo.from_optparse(options)

	#
	# check output filename
	#

	if not options.output:
		raise ValueError("--output is required")
	if filenames:
		raise ValueError("unrecognized options: %s" % " ".join(filenames))

	#
	# we're done
	#

	return options, filenames, process_params, detectors


#
# =============================================================================
#
#                                   Handler
#
# =============================================================================
#


class Handler(simplehandler.Handler):
	def __init__(self, mainloop, pipeline, hoft_pdfs, verbose):
		super(Handler, self).__init__(mainloop, pipeline)
		self.lock = threading.Lock()
		self.verbose = verbose
		self.hoft_pdfs = hoft_pdfs

	def appsink_new_buffer(self, elem):
		with self.lock:
			# ugly way to get the instrument name for this data
			# stream.  when we created the appsink element we
			# used "_" characters for a delimiter and made the
			# fisrt part of the name be the instrument
			instrument = elem.get_name().split("_")[0]

			# retrieve the counts array for the PDF
			count = self.hoft_pdfs[instrument].count

			# retrieve the gstreamer buffer object and iterate
			# over the memory objects inside it
			buf = elem.emit("pull-sample").get_buffer()
			buf_is_gap = bool(buf.mini_object.flags & Gst.BufferFlags.GAP)
			if not buf_is_gap:
				for i in range(buf.n_memory()):
					memory = buf.peek_memory(i)
					result, mapinfo = memory.map(Gst.MapFlags.READ)
					assert result
					if mapinfo.data:
						# put samples into the histogram
						for sample in numpy.frombuffer(mapinfo.data, dtype = numpy.float32):
							count[sample,] += 1.
					memory.unmap(mapinfo)


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


#
# parse command line
#


options, filenames, process_params, detectors = parse_command_line()

if True:
	pipeparts.mkchecktimestamps = lambda pipeline, src, *args: src


#
# set up the PSDs
#
# There are three modes for psds in this program
# 1) --reference-psd without --track-psd - a fixed psd (provided by the user) will be used to whiten the data
# 2) --track-psd without --reference-psd - a psd will me measured and used on the fly
# 3) --track-psd with --reference-psd - a psd will be measured on the fly, but the first guess will come from the users provided psd
#


if options.reference_psd is not None:
	psd = lal.series.read_psd_xmldoc(ligolw_utils.load_filename(options.reference_psd, verbose = options.verbose, contenthandler = lal.series.PSDContentHandler))
	if set(detectors.channel_dict) - set(psd):
		raise ValueError("missing PSD(s) for %s" % ", ".join(sorted(set(detectors.channel_dict) - set(psd))))
else:
	psd = dict.fromkeys(all_instruments, None)


#
# Build pipeline and initialize h(t) PDFs
#


if options.verbose:
	print("assembling pipeline ...", file=sys.stderr)

pipeline = Gst.Pipeline(name="gstlal_inspiral")
mainloop = GObject.MainLoop()
hoft_pdfs = {}
hoftdict = {}

for instrument in detectors.channel_dict:
	src, statevector, dqvector = datasource.mkbasicsrc(pipeline, detectors, instrument, options.verbose)
	rate = 2048
	hoftdict[instrument] = multirate_datasource.mkwhitened_multirate_src(
		pipeline,
		src = src,
		rates = set((rate,)),	# just one rate
		instrument = instrument,
		psd = psd[instrument],
		psd_fft_length = options.psd_fft_length,
		ht_gate_threshold = PosInf,	# disable
		track_psd = options.track_psd,
		width = 32,
		statevector = statevector,
		dqvector = dqvector
	)[rate]	# retrieve the element for the one rate we requested

	hoft_pdfs[instrument] = lal.rate.BinnedLnPDF(lal.rate.NDBins((lal.rate.ATanBins(-4., +4., 400),)))

if options.verbose:
	print("done", file=sys.stderr)


#
# construct and configure pipeline handler
#


if options.verbose:
	print("initializing pipeline handler ...", file=sys.stderr)
handler = Handler(
	mainloop = mainloop,
	pipeline = pipeline,
	hoft_pdfs = hoft_pdfs,
	verbose = options.verbose
)
if options.verbose:
	print("... pipeline handler initialized", file=sys.stderr)

if options.verbose:
	print("attaching appsinks to pipeline ...", file=sys.stderr)
appsync = pipeparts.AppSync(appsink_new_buffer = handler.appsink_new_buffer)
appsinks = set(appsync.add_sink(pipeline, src, caps = Gst.Caps.from_string("audio/x-raw"), name = "%s_white_hoft" % instrument) for instrument, src in hoftdict.items())

if options.verbose:
	print("attached %d, done" % len(appsinks), file=sys.stderr)


#
# Run pipeline
#


if options.verbose:
	print("setting pipeline state to ready ...", file=sys.stderr)
if pipeline.set_state(Gst.State.READY) != Gst.StateChangeReturn.SUCCESS:
	raise RuntimeError("pipeline did not enter ready state")
datasource.pipeline_seek_for_gps(pipeline, *detectors.seg)
if options.verbose:
	print("setting pipeline state to playing ...", file=sys.stderr)
if pipeline.set_state(Gst.State.PLAYING) != Gst.StateChangeReturn.SUCCESS:
	raise RuntimeError("pipeline did not enter playing state")
if options.verbose:
	print("running pipeline ...", file=sys.stderr)
mainloop.run()


#
# write output file
#


for pdf in hoft_pdfs.values():
	pdf.normalize()

xmldoc = ligolw.Document()
xmldoc.appendChild(ligolw.LIGO_LW())

for instrument, pdf in hoft_pdfs.items():
	xmldoc.childNodes[-1].appendChild(pdf.to_xml("white_hoft_pdf:%s" % instrument))

ligolw_utils.write_filename(xmldoc, options.output, verbose = options.verbose)

#
# Set pipeline state to NULL
#


if pipeline.set_state(Gst.State.NULL) != Gst.StateChangeReturn.SUCCESS:
	raise RuntimeError("pipeline could not be set to NULL")


#
# done.
#
