def get_channel_type(self, det):
     """ Help method to read the channel_dict and print useful messages """
     if self.channel_dict is None:
         raise BilbyPipeError("No channel-dict argument provided")
     if det in self.channel_dict:
         return self.channel_dict[det]
     else:
         raise BilbyPipeError(
             f"Detector {det} not given in the channel-dict")
    def psd_length(self, psd_length):
        if isinstance(psd_length, int):
            self._psd_length = psd_length
            self.psd_duration = psd_length * self.duration

        else:
            raise BilbyPipeError(f"Unable to set psd_length={psd_length}")
 def data_dict(self, data_dict):
     if data_dict is None:
         logger.debug("data-dict set to None")
         self._data_dict = None
     elif isinstance(data_dict, str):
         self._data_dict = convert_string_to_dict(data_dict, "data-dict")
     elif isinstance(data_dict, dict):
         self._data_dict = data_dict
     else:
         raise BilbyPipeError(f"Input data-dict={data_dict} not understood")
    def create_data(self, args):
        """Function to iterate through data generation method

        Note, the data methods are mutually exclusive and only one can be given to
        the parser.

        Parameters
        ----------
        args: Namespace
            Input arguments

        Raises
        ------
        BilbyPipeError:
            If no data is generated

        """

        self.data_set = False
        self.injection = args.injection
        self.injection_numbers = args.injection_numbers
        self.injection_file = args.injection_file
        self.injection_dict = args.injection_dict
        self.gaussian_noise = args.gaussian_noise

        # The following are all mutually exclusive methods to set the data
        if self.gaussian_noise:
            if args.injection_file is not None:
                logger.debug("Using provided injection file")
                self._set_interferometers_from_injection_in_gaussian_noise()
            elif args.injection_dict is not None:
                logger.debug("Using provided injection dict")
                self._set_interferometers_from_injection_in_gaussian_noise()
            elif args.injection is False:
                self._set_interferometers_from_gaussian_noise()
            else:
                raise BilbyPipeError("Unable to set data: no injection file")
        else:
            self._set_interferometers_from_data()

        if self.data_set is False:
            raise BilbyPipeError("Unable to set data")
 def add_calibration_model_to_interferometers(self, ifo):
     if self.calibration_model == "CubicSpline":
         ifo.calibration_model = bilby.gw.calibration.CubicSpline(
             prefix=f"recalib_{ifo.name}_",
             minimum_frequency=ifo.minimum_frequency,
             maximum_frequency=ifo.maximum_frequency,
             n_points=self.spline_calibration_nodes,
         )
     else:
         raise BilbyPipeError(
             f"calibration model {self.calibration_model} not implemented")
 def psd_start_time(self):
     """ The PSD start time relative to segment start time """
     if self._psd_start_time is not None:
         return self._psd_start_time
     elif self.trigger_time is not None:
         psd_start_time = -self.psd_duration
         logger.info(
             f"Using default PSD start time {psd_start_time} relative to start time"
         )
         return psd_start_time
     else:
         raise BilbyPipeError("PSD start time not set")
    def interferometers(self, interferometers):
        for ifo in interferometers:
            if isinstance(ifo, bilby.gw.detector.Interferometer) is False:
                raise BilbyPipeError(
                    f"ifo={ifo} is not a bilby Interferometer")
            if self.minimum_frequency is not None:
                ifo.minimum_frequency = self.minimum_frequency_dict[ifo.name]
            if self.maximum_frequency is not None:
                ifo.maximum_frequency = self.maximum_frequency_dict[ifo.name]
            if self.calibration_model is not None:
                self.add_calibration_model_to_interferometers(ifo)

        self._interferometers = interferometers
        self.data_set = True
        if self.create_plots:
            interferometers.plot_data(outdir=self.data_directory,
                                      label=self.label)
    def _get_data(self,
                  det,
                  channel_type,
                  start_time,
                  end_time,
                  resample=True):
        """Read in data using gwpy

        If the channel_type is "GWOSC", open data is obtained. Otherwise, we
        try to read in the data first using "read" if a data_dict exists and
        then using "get".

        Parameters
        ----------
        channel_type: str
            The full channel name is formed from <det>:<channel_type>, see
            bilby_pipe --help for more information.

        start_time, end_time: float
            GPS start and end time of segment

        Returns
        -------
        data: gwpy.timeseries.TimeSeries
            The loaded data

        Raises
        ------
        BilbyPipeError:
            If there is an issue obtaining the data or with the data itself
        """
        timeslide_val = None
        if hasattr(self, "timeslide_dict"):
            timeslide_val = self.timeslide_dict[det]
            start_time = start_time + timeslide_val
            end_time = end_time + timeslide_val
            logger.info(
                "Applying timeshift of {}. Time range {} - {} => {} - {}".
                format(
                    timeslide_val,
                    start_time - timeslide_val,
                    end_time - timeslide_val,
                    start_time,
                    end_time,
                ))

        if self.ignore_gwpy_data_quality_check is False:
            data_is_good = self._is_gwpy_data_good(start_time, end_time, det)
            if not data_is_good:
                raise BilbyPipeError("Data quality is not good.")

        data = None

        if data is None and channel_type == "GWOSC":
            data = self._gwpy_fetch_open_data(det, start_time, end_time)

        channel = f"{det}:{channel_type}"
        if data is None and self.data_dict is not None:
            data = self._gwpy_read(det, channel, start_time, end_time)
        if data is None:
            data = self._gwpy_get(channel, start_time, end_time)

        if data is None:
            raise BilbyPipeError("Failed to obtain data")
        if np.all(data.value == 0):
            raise BilbyPipeError("Obtained data is all zeros")

        if resample and data.sample_rate.value == self.sampling_frequency:
            logger.info("Sample rate matches data no resampling")
        elif resample:
            message = "Resampling data to sampling_frequency {} using {}"
            if self.resampling_method == "gwpy":
                logger.info(
                    message.format(self.sampling_frequency,
                                   self.resampling_method))
                data = data.resample(self.sampling_frequency)
            elif self.resampling_method == "lal":
                logger.info(
                    message.format(self.sampling_frequency,
                                   self.resampling_method))
                try:
                    lal_timeseries = data.to_lal()
                    lal.ResampleREAL8TimeSeries(
                        lal_timeseries, float(1 / self.sampling_frequency))
                except Exception as e:
                    raise BilbyPipeError(
                        "The lal resampling method has failed with exception {} "
                        "You may wish to try a different resampling method".
                        format(e))
                data = gwpy.timeseries.TimeSeries(
                    lal_timeseries.data.data,
                    epoch=lal_timeseries.epoch,
                    dt=lal_timeseries.deltaT,
                )
            else:
                logger.warning(
                    "Resampling method {} not understood, should be "
                    "'gwpy' or 'lal'.".format(self.resampling_method))
        else:
            logger.info("No data resampling requested")

        if timeslide_val:
            # to match up the time axis for the interferometer network
            data.shift(-timeslide_val)

        return data
 def data_dump(self):
     if hasattr(self, "_data_dump"):
         return self._data_dump
     else:
         raise BilbyPipeError("Data dump not loaded")