示例#1
0
    def draw(self,
             n: int = 1,
             as_df: bool = False) -> Union[pd.DataFrame, np.record]:
        """
        Draw a sample from the joint distribution and construct a
        dictionary that maps the parameter names to the values
        generated for them.
        
        Arguments:
            n: int
                The number of samples to draw.
            as_dataframe: bool
                If True, returns a pd.DataFrame; else a numpy.recarray


        Returns:
            A `dict` containing a the names and values of a set of
            randomly sampled waveform parameters (e.g., masses, spins,
            position in the sky, ...).
        """
        assert n >= 1, "n must be a positive integer."
        samples = apply_transforms(self.distribution.rvs(size=n),
                                   self.transforms)
        if as_df:
            return pd.DataFrame(samples)
        return samples
示例#2
0
    def _transform_params(self, **params):
        """Applies all transforms to the given params.

        Parameters
        ----------
        \**params :
            Key, value pairs of parameters to apply the transforms to.

        Returns
        -------
        dict
            A dictionary of the transformed parameters.
        """
        # apply inverse transforms to go from sampling parameters to
        # variable args
        if self.sampling_transforms is not None:
            params = self.sampling_transforms.apply(params, inverse=True)
        # apply waveform transforms
        if self.waveform_transforms is not None:
            params = transforms.apply_transforms(params,
                                                 self.waveform_transforms,
                                                 inverse=False)
        # apply boundary conditions
        params = self.prior_distribution.apply_boundary_conditions(**params)
        return params
示例#3
0
    def _transform_params(self, **params):
        """Applies all transforms to the given params.

        Parameters
        ----------
        \**params :
            Key, value pairs of parameters to apply the transforms to.

        Returns
        -------
        dict
            A dictionary of the transformed parameters.
        """
        # apply inverse transforms to go from sampling parameters to
        # variable args
        if self.sampling_transforms is not None:
            params = self.sampling_transforms.apply(params, inverse=True)
        # apply waveform transforms
        if self.waveform_transforms is not None:
            params = transforms.apply_transforms(params,
                                                 self.waveform_transforms,
                                                 inverse=False)
        # apply boundary conditions
        params = self.prior_distribution.apply_boundary_conditions(**params)
        return params
示例#4
0
def draw_samples_from_config(path, num=1, seed=150914):
    r""" Generate sampling points from a standalone .ini file.

    Parameters
    ----------
    path : str
        The path to the .ini file.
    num : int
        The number of samples.
    seed: int
        The random seed for sampling.

    Returns
    --------
    samples : pycbc.io.record.FieldArray
        The parameter values and names of sample(s).

    Examples
    --------
    Draw a sample from the distribution defined in the .ini file:

    >>> import numpy as np
    >>> from pycbc.distributions.utils import draw_samples_from_config

    >>> # A path to the .ini file.
    >>> CONFIG_PATH = "./pycbc_bbh_prior.ini"
    >>> random_seed = np.random.randint(low=0, high=2**32-1)
    >>> sample = draw_samples_from_config(
    >>>          path=CONFIG_PATH, num=1, seed=random_seed)

    >>> # Print all parameters.
    >>> print(sample.fieldnames)
    >>> print(sample)
    >>> # Print a certain parameter, for example 'mass1'.
    >>> print(sample[0]['mass1'])
    """

    np.random.seed(seed)

    # Initialise InterpolatingConfigParser class.
    config_parser = InterpolatingConfigParser()
    # Read the file
    file = open(path, 'r')
    config_parser.read_file(file)
    file.close()

    # Construct class that will draw the samples.
    prior_dists = prior_from_config(cp=config_parser)
    # Draw samples from prior distribution.
    samples = prior_dists.rvs(size=int(num))

    # Apply parameter transformation.
    if any(config_parser.get_subsections('waveform_transforms')):
        waveform_transforms = transforms.read_transforms_from_config(
            config_parser, 'waveform_transforms')
        samples = transforms.apply_transforms(samples, waveform_transforms)

    return samples
示例#5
0
 def _transform_params(self, **params):
     """Adds waveform transforms to parent's ``_transform_params``."""
     params = super(BaseDataModel, self)._transform_params(**params)
     # apply waveform transforms
     if self._waveform_transforms is not None:
         params = transforms.apply_transforms(params,
                                              self._waveform_transforms,
                                              inverse=False)
     return params
示例#6
0
    def from_config(cls, cp, section, tag):
        """ Return instance based on config file

        Return a new instance based on the config file. This will draw from
        a single distribution section provided in the config file and
        apply a single transformation section if desired. If a transformation
        is applied, an inverse mapping is also provided for use in the config
        file.
        """
        from pycbc.distributions import read_distributions_from_config
        from pycbc.transforms import (read_transforms_from_config,
                                      apply_transforms, BaseTransform)
        from pycbc.transforms import transforms as global_transforms

        params = tag.split(VARARGS_DELIM)
        subname = cp.get_opt_tag(section, 'subname', tag)
        size = cp.get_opt_tag(section, 'sample-size', tag)

        distsec = '{}_sample'.format(subname)
        dist = read_distributions_from_config(cp, section=distsec)
        if len(dist) > 1:
            raise ValueError("Fixed sample distrubtion only supports a single"
                             " distribution to sample from.")

        logging.info('Drawing samples for fixed sample distribution:%s', params)
        samples = dist[0].rvs(size=int(float(size)))
        samples = {p: samples[p] for p in samples.dtype.names}

        transec = '{}_transform'.format(subname)
        trans = read_transforms_from_config(cp, section=transec)
        if len(trans) > 0:
            trans = trans[0]
            samples = apply_transforms(samples, [trans])
            p1 = samples[params[0]]

            # We have transformed parameters, so automatically provide the
            # inverse transform for use in passing to waveform approximants
            class Thook(BaseTransform):
                name = subname
                _inputs = trans.outputs
                _outputs = trans.inputs
                p1name = params[0]
                sort = p1.argsort()
                p1sorted = p1[sort]
                def transform(self, maps):
                    idx = numpy.searchsorted(self.p1sorted, maps[self.p1name])
                    out = {p: samples[p][self.sort[idx]] for p in self.outputs}
                    return self.format_output(maps, out)
            global_transforms[Thook.name] = Thook
        return cls(params, samples)
示例#7
0
    def draw(self):
        """
        Draw a sample from the joint distribution and construct a
        dictionary that maps the parameter names to the values
        generated for them.

        Returns:
            A `dict` containing a the names and values of a set of
            randomly sampled waveform parameters (e.g., masses, spins,
            position in the sky, ...).
        """
        values = apply_transforms(self.pval.rvs(), self.trans)[0]
        result = dict(zip(self.var_args, values))

        return result
示例#8
0
 def loglikelihood(self, cube, *extra_args):
     """Log likelihood evaluator that gets passed to multinest.
     """
     params = {p: v for p, v in zip(self.model.variable_params, cube)}
     # apply transforms
     if self.model.sampling_transforms is not None:
         params = self.model.sampling_transforms.apply(params)
     if self.model.waveform_transforms is not None:
         params = apply_transforms(params, self.model.waveform_transforms)
     # apply constraints
     if (self._constraints is not None
             and not all([c(params) for c in self._constraints])):
         return -numpy.inf
     self.model.update(**params)
     return self.model.loglikelihood
示例#9
0
    def apply(self, samples, inverse=False):
        """Applies the sampling transforms to the given samples.

        Parameters
        ----------
        samples : dict or FieldArray
            The samples to apply the transforms to.
        inverse : bool, optional
            Whether to apply the inverse transforms (i.e., go from the sampling
            args to the ``variable_params``). Default is False.

        Returns
        -------
        dict or FieldArray
            The transformed samples, along with the original samples.
        """
        return transforms.apply_transforms(samples, self.sampling_transforms,
                                           inverse=inverse)
示例#10
0
    def apply(self, samples, inverse=False):
        """Applies the sampling transforms to the given samples.

        Parameters
        ----------
        samples : dict or FieldArray
            The samples to apply the transforms to.
        inverse : bool, optional
            Whether to apply the inverse transforms (i.e., go from the sampling
            args to the ``variable_params``). Default is False.

        Returns
        -------
        dict or FieldArray
            The transformed samples, along with the original samples.
        """
        return transforms.apply_transforms(samples, self.sampling_transforms,
                                           inverse=inverse)
示例#11
0
    def __call__(self, params):
        """ Evaluates constraint.
        """

        # cast to FieldArray
        if isinstance(params, dict):
            params = record.FieldArray.from_kwargs(**params)
        elif not isinstance(params, record.FieldArray):
            raise ValueError("params must be dict or FieldArray instance")

        # apply transforms
        params = transforms.apply_transforms(params, self.transforms) \
                     if self.transforms else params

        # apply constraints
        out = self._constraint(params)
        if isinstance(out, record.FieldArray):
            out = out.item() if params.size == 1 else out

        return out
示例#12
0
    def __call__(self, params):
        """ Evaluates constraint.
        """

        # cast to FieldArray
        if isinstance(params, dict):
            params = record.FieldArray.from_kwargs(**params)
        elif not isinstance(params, record.FieldArray):
           raise ValueError("params must be dict or FieldArray instance")

        # apply transforms
        params = transforms.apply_transforms(params, self.transforms) \
                     if self.transforms else params

        # apply constraints
        out = self._constraint(params)
        if isinstance(out, record.FieldArray):
            out = out.item() if params.size == 1 else out

        return out
示例#13
0
    def __call__(self, params):
        """Evaluates constraint.
        """
        # cast to FieldArray
        if isinstance(params, dict):
            params = record.FieldArray.from_kwargs(**params)
        elif not isinstance(params, record.FieldArray):
           raise ValueError("params must be dict or FieldArray instance")

        # try to evaluate; this will assume that all of the needed parameters
        # for the constraint exists in params
        try:
            out = self._constraint(params)
        except NameError:
            # one or more needed parameters don't exist; try applying the
            # transforms
            params = transforms.apply_transforms(params, self.transforms) \
                     if self.transforms else params
            out = self._constraint(params)
        if isinstance(out, record.FieldArray):
            out = out.item() if params.size == 1 else out
        return out
示例#14
0
    def __call__(self, params):
        """ Evaluates constraint.
        """
        # cast to FieldArray
        if isinstance(params, dict):
            params = record.FieldArray.from_kwargs(**params)
        elif not isinstance(params, record.FieldArray):
           raise ValueError("params must be dict or FieldArray instance")

        # try to evaluate; this will assume that all of the needed parameters
        # for the constraint exists in params
        try:
            out = self._constraint(params)
        except NameError:
            # one or more needed parameters don't exist; try applying the
            # transforms
            params = transforms.apply_transforms(params, self.transforms) \
                     if self.transforms else params
            out = self._constraint(params)
        if isinstance(out, record.FieldArray):
            out = out.item() if params.size == 1 else out
        return out
示例#15
0
def injections_from_cli(opts):
    """Gets injection parameters from the inference file(s).

    Parameters
    ----------
    opts : argparser
        Argparser object that has the command-line objects to parse.

    Returns
    -------
    FieldArray
        Array of the injection parameters from all of the input files given
        by ``opts.input_file``.
    """
    input_files = opts.input_file
    if isinstance(input_files, str):
        input_files = [input_files]
    parameters, _ = parse_parameters_opt(opts.parameters)
    if parameters is None:
        with InferenceFile(input_files[0], 'r') as fp:
            parameters = fp.variable_params
    injections = None
    # loop over all input files getting the injection files
    for input_file in input_files:
        # read injections from HDF input file as FieldArray
        these_injs = inject.InjectionSet(
            input_file,
            hdf_group=opts.injection_hdf_group,
        ).table.view(FieldArray)
        if injections is None:
            injections = these_injs
        else:
            injections = injections.append(these_injs)
    # check if need extra parameters than parameters stored in injection file
    _, ts = transforms.get_common_cbc_transforms(parameters,
                                                 injections.fieldnames)
    # add parameters not included in injection file
    injections = transforms.apply_transforms(injections, ts)
    return injections
示例#16
0
    def apply_sampling_transforms(self, samples, inverse=False):
        """Applies the sampling transforms to the given samples.

        If ``sampling_transforms`` is None, just returns the samples.

        Parameters
        ----------
        samples : dict or FieldArray
            The samples to apply the transforms to.
        inverse : bool, optional
            Whether to apply the inverse transforms (i.e., go from the sampling
            args to the variable args). Default is False.

        Returns
        -------
        dict or FieldArray
            The transformed samples, along with the original samples.
        """
        if self._sampling_transforms is None:
            return samples
        return transforms.apply_transforms(samples,
                                           self._sampling_transforms,
                                           inverse=inverse)
示例#17
0
def injections_from_cli(opts):
    """Gets injection parameters from the inference file(s).

    Parameters
    ----------
    opts : argparser
        Argparser object that has the command-line objects to parse.

    Returns
    -------
    FieldArray
        Array of the injection parameters from all of the input files given
        by ``opts.input_file``.
    """
    input_files = opts.input_file
    if isinstance(input_files, str):
        input_files = [input_files]
    parameters, _ = parse_parameters_opt(opts.parameters)
    if parameters is None:
        with InferenceFile(input_files[0], 'r') as fp:
            parameters = fp.variable_args
    injections = None
    # loop over all input files getting the injection files
    for input_file in input_files:
        # read injections from HDF input file as FieldArray
        these_injs = inject.InjectionSet(input_file,
            hdf_group=opts.injection_hdf_group).table.view(FieldArray)
        if injections is None:
            injections = these_injs
        else:
            injections = injections.append(these_injs)
    # check if need extra parameters than parameters stored in injection file
    _, ts = transforms.get_common_cbc_transforms(parameters,
                                                 injections.fieldnames)
    # add parameters not included in injection file
    injections = transforms.apply_transforms(injections, ts)
    return injections
示例#18
0
    def _trytoget(self, statname, fallback, apply_transforms=False, **kwargs):
        r"""Helper function to get a stat from ``_current_stats``.

        If the statistic hasn't been calculated, ``_current_stats`` will raise
        an ``AttributeError``. In that case, the ``fallback`` function will
        be called. If that call is successful, the ``statname`` will be added
        to ``_current_stats`` with the returned value.

        Parameters
        ----------
        statname : str
            The stat to get from ``current_stats``.
        fallback : method of self
            The function to call if the property call fails.
        apply_transforms : bool, optional
            Apply waveform transforms to the current parameters before calling
            the fallback function. Default is False.
        \**kwargs :
            Any other keyword arguments are passed through to the function.

        Returns
        -------
        float :
            The value of the property.
        """
        try:
            return getattr(self._current_stats, statname)
        except AttributeError:
            # apply waveform transforms if requested
            if apply_transforms and self.waveform_transforms is not None:
                self._current_params = transforms.apply_transforms(
                    self._current_params,
                    self.waveform_transforms,
                    inverse=False)
            val = fallback(**kwargs)
            setattr(self._current_stats, statname, val)
            return val
示例#19
0
    def evaluate(self, params, callfunc=None):
        """Evaluates the call function at the given list of parameter values.

        Parameters
        ----------
        params : list
            A list of values. These are assumed to be in the same order as
            variable args.
        callfunc : str, optional
            The name of the function to call. If None, will use
            ``self._callfunc``. Default is None.

        Returns
        -------
        float or tuple :
            If ``return_meta`` is False, the output of the call function. If
            ``return_meta`` is True, a tuple of the output of the call function
            and the meta data.
        """
        params = dict(zip(self._sampling_args, params))
        # apply inverse transforms to go from sampling parameters to
        # variable args
        params = self.apply_sampling_transforms(params, inverse=True)
        # apply boundary conditions
        params = self._prior.apply_boundary_conditions(**params)
        # apply waveform transforms
        if self._waveform_transforms is not None:
            params = transforms.apply_transforms(params,
                                                 self._waveform_transforms,
                                                 inverse=False)
        # apply any boundary conditions to the parameters before
        # generating/evaluating
        if callfunc is not None:
            f = getattr(self, callfunc)
        else:
            f = self._callfunc
        return f(**params)
示例#20
0
def results_from_cli(opts, load_samples=True, **kwargs):
    """
    Loads an inference result file along with any labels associated with it
    from the command line options.

    Parameters
    ----------
    opts : ArgumentParser options
        The options from the command line.
    load_samples : {True, bool}
        Load samples from the results file using the parameters, thin_start,
        and thin_interval specified in the options. The samples are returned
        as a FieldArray instance.

    \**kwargs :
        All other keyword arguments are passed to the InferenceFile's
        read_samples function.

    Returns
    -------
    fp_all : pycbc.io.InferenceFile
        The result file as an InferenceFile. If more than one input file,
        then it returns a list.
    parameters_all : list
        List of the parameters to use, parsed from the parameters option.
        If more than one input file, then it returns a list.
    labels_all : list
        List of labels to associate with the parameters. If more than one
        input file, then it returns a list.
    samples_all : {None, FieldArray}
        If load_samples, the samples as a FieldArray; otherwise, None.
        If more than one input file, then it returns a list.
    """

    # lists for files and samples from all input files
    fp_all = []
    parameters_all = []
    labels_all = []
    samples_all = []

    # loop over all input files
    for input_file in opts.input_file:
        logging.info("Reading input file %s", input_file)

        # read input file
        fp = InferenceFile(input_file, "r")

        # get parameters and a dict of labels for each parameter
        parameters = fp.variable_args if opts.parameters is None \
                         else opts.parameters
        parameters, ldict = parse_parameters_opt(parameters)

        # convert labels dict to list
        labels = []
        for p in parameters:
            try:
                label = ldict[p]
            except KeyError:
                label = fp.read_label(p)
            labels.append(label)

        # load the samples
        if load_samples:
            logging.info("Loading samples")

            # check if need extra parameters for a non-sampling parameter
            file_parameters, ts = transforms.get_common_cbc_transforms(
                                                 parameters, fp.variable_args)

            # read samples from file
            samples = fp.read_samples(
                file_parameters, thin_start=opts.thin_start,
                thin_interval=opts.thin_interval, thin_end=opts.thin_end,
                iteration=opts.iteration,
                samples_group=opts.parameters_group, **kwargs)

            # add parameters not included in file
            samples = transforms.apply_transforms(samples, ts)

        # else do not read samples
        else:
            samples = None

        # add results to lists from all input files
        if len(opts.input_file) > 1:
            fp_all.append(fp)
            parameters_all.append(parameters)
            labels_all.append(labels)
            samples_all.append(samples)

        # else only one input file then do not return lists
        else:
            fp_all = fp
            parameters_all = parameters
            labels_all = labels
            samples_all = samples

    return fp_all, parameters_all, labels_all, samples_all
示例#21
0
def results_from_cli(opts, load_samples=True, **kwargs):
    """
    Loads an inference result file along with any labels associated with it
    from the command line options.

    Parameters
    ----------
    opts : ArgumentParser options
        The options from the command line.
    load_samples : {True, bool}
        Load samples from the results file using the parameters, thin_start,
        and thin_interval specified in the options. The samples are returned
        as a FieldArray instance.

    \**kwargs :
        All other keyword arguments are passed to the InferenceFile's
        read_samples function.

    Returns
    -------
    fp_all : pycbc.io.InferenceFile
        The result file as an InferenceFile. If more than one input file,
        then it returns a list.
    parameters_all : list
        List of the parameters to use, parsed from the parameters option.
        If more than one input file, then it returns a list.
    labels_all : list
        List of labels to associate with the parameters. If more than one
        input file, then it returns a list.
    samples_all : {None, FieldArray}
        If load_samples, the samples as a FieldArray; otherwise, None.
        If more than one input file, then it returns a list.
    """

    # lists for files and samples from all input files
    fp_all = []
    parameters_all = []
    labels_all = []
    samples_all = []

    input_files = opts.input_file
    if isinstance(input_files, str):
        input_files = [input_files]

    # loop over all input files
    for input_file in input_files:
        logging.info("Reading input file %s", input_file)

        # read input file
        fp = InferenceFile(input_file, "r")

        # get parameters and a dict of labels for each parameter
        parameters = fp.variable_args if opts.parameters is None \
                         else opts.parameters
        parameters, ldict = parse_parameters_opt(parameters)

        # convert labels dict to list
        labels = []
        for p in parameters:
            try:
                label = ldict[p]
            except KeyError:
                label = fp.read_label(p)
            labels.append(label)

        # load the samples
        if load_samples:
            logging.info("Loading samples")

            # check if need extra parameters for a non-sampling parameter
            file_parameters, ts = transforms.get_common_cbc_transforms(
                                                 parameters, fp.variable_args)

            # read samples from file
            samples = fp.read_samples(
                file_parameters, thin_start=opts.thin_start,
                thin_interval=opts.thin_interval, thin_end=opts.thin_end,
                iteration=opts.iteration,
                samples_group=opts.parameters_group, **kwargs)

            # add parameters not included in file
            samples = transforms.apply_transforms(samples, ts)

        # else do not read samples
        else:
            samples = None

        # add results to lists from all input files
        if len(input_files) > 1:
            fp_all.append(fp)
            parameters_all.append(parameters)
            labels_all.append(labels)
            samples_all.append(samples)

        # else only one input file then do not return lists
        else:
            fp_all = fp
            parameters_all = parameters
            labels_all = labels
            samples_all = samples

    return fp_all, parameters_all, labels_all, samples_all
示例#22
0
文件: __init__.py 项目: vahi/pycbc
def results_from_cli(opts, load_samples=True, **kwargs):
    """Loads an inference result file along with any labels associated with it
    from the command line options.

    Parameters
    ----------
    opts : ArgumentParser options
        The options from the command line.
    load_samples : bool, optional
        Load the samples from the file.

    Returns
    -------
    fp_all : (list of) BaseInferenceFile type
        The result file as an hdf file. If more than one input file,
        then it returns a list.
    parameters : list of str
        List of the parameters to use, parsed from the parameters option.
    labels : dict
        Dictionary of labels to associate with the parameters.
    samples_all : (list of) FieldArray(s) or None
        If load_samples, the samples as a FieldArray; otherwise, None.
        If more than one input file, then it returns a list.
    \**kwargs :
        Any other keyword arguments that are passed to read samples using
        samples_from_cli
    """

    # lists for files and samples from all input files
    fp_all = []
    samples_all = []

    input_files = opts.input_file
    if isinstance(input_files, str):
        input_files = [input_files]

    # loop over all input files
    for input_file in input_files:
        logging.info("Reading input file %s", input_file)

        # read input file
        fp = loadfile(input_file, "r")

        # load the samples
        if load_samples:
            logging.info("Loading samples")

            # check if need extra parameters for a non-sampling parameter
            file_parameters, ts = _transforms.get_common_cbc_transforms(
                opts.parameters, fp.variable_params)

            # read samples from file
            samples = fp.samples_from_cli(opts, parameters=file_parameters, **kwargs)

            logging.info("Using {} samples".format(samples.size))

            # add parameters not included in file
            samples = _transforms.apply_transforms(samples, ts)

        # else do not read samples
        else:
            samples = None

        # add results to lists from all input files
        if len(input_files) > 1:
            fp_all.append(fp)
            samples_all.append(samples)

        # else only one input file then do not return lists
        else:
            fp_all = fp
            samples_all = samples

    return fp_all, opts.parameters, opts.parameters_labels, samples_all
示例#23
0
def results_from_cli(opts, load_samples=True, **kwargs):
    """
    Loads an inference result file along with any labels associated with it
    from the command line options.

    Parameters
    ----------
    opts : ArgumentParser options
        The options from the command line.
    load_samples : {True, bool}
        Load samples from the results file using the parameters, thin_start,
        and thin_interval specified in the options. The samples are returned
        as a FieldArray instance.

    \**kwargs :
        All other keyword arguments are passed to the InferenceFile's
        read_samples function.

    Returns
    -------
    result_file : pycbc.io.InferenceFile
        The result file as an InferenceFile.
    parameters : list
        List of the parameters to use, parsed from the parameters option.
    labels : list
        List of labels to associate with the parameters.
    samples : {None, FieldArray}
        If load_samples, the samples as a FieldArray; otherwise, None.
    """

    logging.info("Reading input file")
    fp = InferenceFile(opts.input_file, "r")
    parameters = fp.variable_args if opts.parameters is None \
                 else opts.parameters

    # load the labels
    parameters, ldict = parse_parameters_opt(parameters)
    # convert labels dict to list
    labels = []
    for p in parameters:
        try:
            label = ldict[p]
        except KeyError:
            label = fp.read_label(p)
        labels.append(label)

    # load the samples
    if load_samples:
        logging.info("Loading samples")
        # check if need extra parameters for a non-sampling parameter
        file_parameters, ts = transforms.get_common_cbc_transforms(
                                                 parameters, fp.variable_args)
        # read samples from file
        samples = fp.read_samples(file_parameters,
            thin_start=opts.thin_start, thin_interval=opts.thin_interval,
            thin_end=opts.thin_end, iteration=opts.iteration,
            samples_group=opts.parameters_group,
            **kwargs)
        # add parameters not included in file
        samples = transforms.apply_transforms(samples, ts)
    else:
        samples = None

    return fp, parameters, labels, samples
示例#24
0
def results_from_cli(opts, load_samples=True, **kwargs):
    """
    Loads an inference result file along with any labels associated with it
    from the command line options.

    Parameters
    ----------
    opts : ArgumentParser options
        The options from the command line.
    load_samples : {True, bool}
        Load samples from the results file using the parameters, thin_start,
        and thin_interval specified in the options. The samples are returned
        as a FieldArray instance.

    \**kwargs :
        All other keyword arguments are passed to the InferenceFile's
        read_samples function.

    Returns
    -------
    result_file : pycbc.io.InferenceFile
        The result file as an InferenceFile.
    parameters : list
        List of the parameters to use, parsed from the parameters option.
    labels : list
        List of labels to associate with the parameters.
    samples : {None, FieldArray}
        If load_samples, the samples as a FieldArray; otherwise, None.
    """

    logging.info("Reading input file")
    fp = InferenceFile(opts.input_file, "r")
    parameters = fp.variable_args if opts.parameters is None \
                 else opts.parameters

    # load the labels
    parameters, ldict = parse_parameters_opt(parameters)
    # convert labels dict to list
    labels = []
    for p in parameters:
        try:
            label = ldict[p]
        except KeyError:
            label = fp.read_label(p)
        labels.append(label)

    # load the samples
    if load_samples:
        logging.info("Loading samples")
        # check if need extra parameters for a non-sampling parameter
        file_parameters, ts = transforms.get_common_cbc_transforms(
                                                 parameters, fp.variable_args)
        # read samples from file
        samples = fp.read_samples(file_parameters,
            thin_start=opts.thin_start, thin_interval=opts.thin_interval,
            thin_end=opts.thin_end, iteration=opts.iteration,
            samples_group=opts.parameters_group,
            **kwargs)
        # add parameters not included in file
        samples = transforms.apply_transforms(samples, ts)
    else:
        samples = None

    return fp, parameters, labels, samples
示例#25
0
def results_from_cli(opts, load_samples=True, walkers=None):
    """
    Loads an inference result file along with any labels associated with it
    from the command line options.

    Parameters
    ----------
    opts : ArgumentParser options
        The options from the command line.
    load_samples : {True, bool}
        Load samples from the results file using the parameters, thin_start,
        and thin_interval specified in the options. The samples are returned
        as a FieldArray instance.
    walkers : {None, (list of) int}
        If loading samples, the walkers to load from. If None, will load from
        all walkers.

    Returns
    -------
    result_file : pycbc.io.InferenceFile
        The result file as an InferenceFile.
    parameters : list
        List of the parameters to use, parsed from the parameters option.
    labels : list
        List of labels to associate with the parameters.
    samples : {None, FieldArray}
        If load_samples, the samples as a FieldArray; otherwise, None.
    """

    logging.info("Reading input file")
    fp = InferenceFile(opts.input_file, "r")
    parameters = fp.variable_args if opts.parameters is None \
                 else opts.parameters

    # load the labels
    labels = []
    for ii,p in enumerate(parameters):
        if len(p.split(':')) == 2:
            p, label = p.split(':')
            parameters[ii] = p
        else:
            label = fp.read_label(p)
        labels.append(label)

    # load the samples
    if load_samples:
        logging.info("Loading samples")
        # check if need extra parameters for a non-sampling parameter
        file_parameters, ts = transforms.get_common_cbc_transforms(
                                                 parameters, fp.variable_args)
        # read samples from file
        samples = fp.read_samples(
            file_parameters, walkers=walkers,
            thin_start=opts.thin_start, thin_interval=opts.thin_interval,
            thin_end=opts.thin_end, iteration=opts.iteration,
            samples_group=opts.parameters_group)
        # add parameters not included in file
        samples = transforms.apply_transforms(samples, ts)
    else:
        samples = None

    return fp, parameters, labels, samples
示例#26
0
 def draw(self):
     return apply_transforms(self.pval.rvs(), self.trans)[0]
示例#27
0
文件: __init__.py 项目: lbarosi/pycbc
def results_from_cli(opts, load_samples=True, **kwargs):
    """Loads an inference result file along with any labels associated with it
    from the command line options.

    Parameters
    ----------
    opts : ArgumentParser options
        The options from the command line.
    load_samples : bool, optional
        Load the samples from the file.

    Returns
    -------
    fp_all : (list of) BaseInferenceFile type
        The result file as an hdf file. If more than one input file,
        then it returns a list.
    parameters : list of str
        List of the parameters to use, parsed from the parameters option.
    labels : dict
        Dictionary of labels to associate with the parameters.
    samples_all : (list of) FieldArray(s) or None
        If load_samples, the samples as a FieldArray; otherwise, None.
        If more than one input file, then it returns a list.
    \**kwargs :
        Any other keyword arguments that are passed to read samples using
        samples_from_cli
    """

    # lists for files and samples from all input files
    fp_all = []
    samples_all = []

    input_files = opts.input_file
    if isinstance(input_files, str):
        input_files = [input_files]

    # load constraints
    constraints = {}
    if opts.constraint is not None:
        for constraint in opts.constraint:
            if len(constraint.split(':')) == 2:
                constraint, fn = constraint.split(':')
                constraints[fn] = constraint
            # no file provided, make sure there's only one constraint
            elif len(opts.constraint) > 1:
                raise ValueError("must provide a file to apply constraints "
                                 "to if providing more than one constraint")
            else:
                # this means no file, only one constraint, apply to all
                # files
                constraints = {fn: constraint for fn in input_files}

    # loop over all input files
    for input_file in input_files:
        logging.info("Reading input file %s", input_file)

        # read input file
        fp = loadfile(input_file, "r")

        # load the samples
        if load_samples:
            logging.info("Loading samples")

            # check if need extra parameters for a non-sampling parameter
            file_parameters, ts = _transforms.get_common_cbc_transforms(
                opts.parameters, fp.variable_params)

            # read samples from file
            samples = fp.samples_from_cli(opts,
                                          parameters=file_parameters,
                                          **kwargs)

            logging.info("Loaded {} samples".format(samples.size))

            # add parameters not included in file
            samples = _transforms.apply_transforms(samples, ts)

            if input_file in constraints:
                logging.info("Applying constraints")
                mask = samples[constraints[input_file]]
                samples = samples[mask]
                if samples.size == 0:
                    raise ValueError("No samples remain after constraint {} "
                                     "applied".format(constraints[input_file]))
                logging.info("{} samples remain".format(samples.size))

        # else do not read samples
        else:
            samples = None

        # add results to lists from all input files
        if len(input_files) > 1:
            fp_all.append(fp)
            samples_all.append(samples)

        # else only one input file then do not return lists
        else:
            fp_all = fp
            samples_all = samples

    return fp_all, opts.parameters, opts.parameters_labels, samples_all
示例#28
0
def results_from_cli(opts, load_samples=True, walkers=None):
    """
    Loads an inference result file along with any labels associated with it
    from the command line options.

    Parameters
    ----------
    opts : ArgumentParser options
        The options from the command line.
    load_samples : {True, bool}
        Load samples from the results file using the parameters, thin_start,
        and thin_interval specified in the options. The samples are returned
        as a FieldArray instance.
    walkers : {None, (list of) int}
        If loading samples, the walkers to load from. If None, will load from
        all walkers.

    Returns
    -------
    result_file : pycbc.io.InferenceFile
        The result file as an InferenceFile.
    parameters : list
        List of the parameters to use, parsed from the parameters option.
    labels : list
        List of labels to associate with the parameters.
    samples : {None, FieldArray}
        If load_samples, the samples as a FieldArray; otherwise, None.
    """

    logging.info("Reading input file")
    fp = InferenceFile(opts.input_file, "r")
    parameters = fp.variable_args if opts.parameters is None \
                 else opts.parameters

    # load the labels
    labels = []
    for ii, p in enumerate(parameters):
        if len(p.split(':')) == 2:
            p, label = p.split(':')
            parameters[ii] = p
        else:
            label = fp.read_label(p)
        labels.append(label)

    # load the samples
    if load_samples:
        logging.info("Loading samples")
        # check if need extra parameters for a non-sampling parameter
        file_parameters, ts = transforms.get_common_cbc_transforms(
            parameters, fp.variable_args)
        # read samples from file
        samples = fp.read_samples(file_parameters,
                                  walkers=walkers,
                                  thin_start=opts.thin_start,
                                  thin_interval=opts.thin_interval,
                                  thin_end=opts.thin_end,
                                  iteration=opts.iteration,
                                  samples_group=opts.parameters_group)
        # add parameters not included in file
        samples = transforms.apply_transforms(samples, ts)
    else:
        samples = None

    return fp, parameters, labels, samples