当前位置: 首页>>代码示例>>Python>>正文


Python io.FieldArray类代码示例

本文整理汇总了Python中pycbc.io.FieldArray的典型用法代码示例。如果您正苦于以下问题:Python FieldArray类的具体用法?Python FieldArray怎么用?Python FieldArray使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了FieldArray类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: prior_rvs

    def prior_rvs(self, size=1, prior=None):
        """Returns random variates drawn from the prior.

        If the ``sampling_args`` are different from the ``variable_args``, the
        variates are transformed to the `sampling_args` parameter space before
        being returned.

        Parameters
        ----------
        size : int, optional
            Number of random values to return for each parameter. Default is 1.
        prior : JointDistribution, optional
            Use the given prior to draw values rather than the saved prior.

        Returns
        -------
        FieldArray
            A field array of the random values.
        """
        # draw values from the prior
        if prior is None:
            prior = self._prior
        p0 = prior.rvs(size=size)
        # transform if necessary
        if self._sampling_transforms is not None:
            ptrans = self.apply_sampling_transforms(p0)
            # pull out the sampling args
            p0 = FieldArray.from_arrays([ptrans[arg]
                                         for arg in self._sampling_args],
                                        names=self._sampling_args)
        return p0
开发者ID:spxiwh,项目名称:pycbc,代码行数:31,代码来源:likelihood.py

示例2: likelihood_stats

 def likelihood_stats(self):
     """Returns the log likelihood ratio and log prior as a FieldArray.
     The returned array has shape ntemps x nwalkers x niterations.
     """
     # likelihood has shape ntemps x nwalkers x niterations
     logl = self._sampler.lnlikelihood
     # get prior from posterior
     logp = self._sampler.lnprobability - logl
     # compute the likelihood ratio
     loglr = logl - self.likelihood_evaluator.lognl
     return FieldArray.from_kwargs(loglr=loglr, prior=logp)
开发者ID:gravity-waves,项目名称:pycbc,代码行数:11,代码来源:sampler_emcee.py

示例3: likelihood_stats

 def likelihood_stats(self):
     """Returns the likelihood stats as a FieldArray, with field names
     corresponding to the type of data returned by the likelihood evaluator.
     The returned array has shape nwalkers x niterations. If no additional
     stats were returned to the sampler by the likelihood evaluator, returns
     None.
     """
     stats = numpy.array(self._sampler.blobs)
     if stats.size == 0:
         return None
     arrays = dict([[field, stats[:, :, fi]]
                    for fi, field in
                   enumerate(self.likelihood_evaluator.metadata_fields)])
     return FieldArray.from_kwargs(**arrays).transpose()
开发者ID:gravity-waves,项目名称:pycbc,代码行数:14,代码来源:sampler_base.py

示例4: __init__

    def __init__(self, filename, approximant=None, **kwds):
        ext = os.path.basename(filename)
        if 'xml' in ext:
            self.indoc = ligolw_utils.load_filename(
                filename, False, contenthandler=LIGOLWContentHandler)
            self.table = table.get_table(
                self.indoc, lsctables.SnglInspiralTable.tableName)
            self.table = FieldArray.from_ligolw_table(self.table)

            # inclination stored in xml alpha3 column
            names = list(self.table.dtype.names)
            names = tuple([n if n != 'alpha3' else 'inclination' for n in names]) 
            self.table.dtype.names = names    

        elif 'hdf' in ext:
            f = h5py.File(filename, 'r')
            dtype = []
            data = {}
            for key in f.keys():
                try:
                    data[str(key)] = f[key][:]
                    dtype.append((str(key), data[key].dtype))
                except:
                    pass

            num = len(data[data.keys()[0]])
            self.table = FieldArray(num, dtype=dtype)
            for key in data:
                self.table[key] = data[key]
        else:
            raise ValueError("Unsupported template bank file extension %s" % ext)

        if not hasattr(self.table, 'template_duration'):
            self.table = self.table.add_fields(numpy.zeros(len(self.table),
                                     dtype=numpy.float32), 'template_duration') 
        self.extra_args = kwds  
        self.approximant_str = approximant
开发者ID:millsjc,项目名称:pycbc,代码行数:37,代码来源:bank.py

示例5: likelihood_stats

 def likelihood_stats(self):
     """Returns the likelihood stats as a FieldArray, with field names
     corresponding to the type of data returned by the likelihood evaluator.
     The returned array has shape nwalkers x niterations. If no additional
     stats were returned to the sampler by the likelihood evaluator, returns
     None.
     """
     stats = numpy.array(self._sampler.blobs)
     if stats.size == 0:
         return None
     # we'll force arrays to float; this way, if there are `None`s in the
     # blobs, they will be changed to `nan`s
     arrays = {field: stats[..., fi].astype(float)
               for fi, field in
               enumerate(self.likelihood_evaluator.metadata_fields)}
     return FieldArray.from_kwargs(**arrays).transpose()
开发者ID:cmbiwer,项目名称:pycbc,代码行数:16,代码来源:sampler_base.py

示例6: compute_acls

    def compute_acls(cls, fp, start_index=None, end_index=None):
        """Computes the autocorrleation length for all variable args and
        temperatures in the given file.
        
        Parameter values are averaged over all walkers at each iteration and
        temperature.  The ACL is then calculated over the averaged chain. If
        the returned ACL is `inf`,  will default to the number of current
        iterations.

        Parameters
        -----------
        fp : InferenceFile
            An open file handler to read the samples from.
        start_index : {None, int}
            The start index to compute the acl from. If None, will try to use
            the number of burn-in iterations in the file; otherwise, will start
            at the first sample.
        end_index : {None, int}
            The end index to compute the acl to. If None, will go to the end
            of the current iteration.

        Returns
        -------
        FieldArray
            An ntemps-long `FieldArray` containing the ACL for each temperature
            and for each variable argument, with the variable arguments as
            fields.
        """
        acls = {}
        if end_index is None:
            end_index = fp.niterations
        tidx = numpy.arange(fp.ntemps)
        for param in fp.variable_args:
            these_acls = numpy.zeros(fp.ntemps, dtype=int)
            for tk in tidx:
                samples = cls.read_samples(fp, param, thin_start=start_index,
                                           thin_interval=1, thin_end=end_index,
                                           temps=tk, flatten=False)[param]
                # contract the walker dimension using the mean, and flatten
                # the (length 1) temp dimension
                samples = samples.mean(axis=1)[0,:]
                acl = autocorrelation.calculate_acl(samples)
                if numpy.isinf(acl):
                    acl = samples.size
                these_acls[tk] = acl
            acls[param] = these_acls
        return FieldArray.from_kwargs(**acls)
开发者ID:pannarale,项目名称:pycbc,代码行数:47,代码来源:sampler_emcee.py

示例7: likelihood_stats

 def likelihood_stats(self):
     """Returns the log likelihood ratio and log prior as a FieldArray.
     The returned array has shape ntemps x nwalkers x niterations.
     """
     # likelihood has shape ntemps x nwalkers x niterations
     logl = self._sampler.lnlikelihood
     # get prior from posterior
     logp = self._sampler.lnprobability - logl
     # compute the likelihood ratio
     loglr = logl - self.likelihood_evaluator.lognl
     kwargs = {'loglr': loglr, 'prior': logp}
     # if different coordinates were used for sampling, get the jacobian
     if self.likelihood_evaluator.sampling_transforms is not None:
         samples = self.samples
         # convert to dict
         d = {param: samples[param] for param in samples.fieldnames}
         logj = self.likelihood_evaluator.logjacobian(**d)
         kwargs['logjacobian'] = logj
     return FieldArray.from_kwargs(**kwargs)
开发者ID:johnveitch,项目名称:pycbc,代码行数:19,代码来源:sampler_emcee.py

示例8: compute_acls

    def compute_acls(cls, fp, start_index=None, end_index=None):
        """Computes the autocorrleation length for all variable args for all
        walkers for all temps in the given file. If the returned acl is inf,
        will default to the number of requested iterations.

        Parameters
        -----------
        fp : InferenceFile
            An open file handler to read the samples from.
        start_index : {None, int}
            The start index to compute the acl from. If None, will try to use
            the number of burn-in iterations in the file; otherwise, will start
            at the first sample.
        end_index : {None, int}
            The end index to compute the acl to. If None, will go to the end
            of the current iteration.

        Returns
        -------
        FieldArray
            An ntemps x nwalkers `FieldArray` containing the acl for each
            walker and temp for each variable argument, with the variable
            arguments as fields.
        """
        acls = {}
        if end_index is None:
            end_index = fp.niterations
        tidx = numpy.arange(fp.ntemps)
        widx = numpy.arange(fp.nwalkers)
        for param in fp.variable_args:
            these_acls = numpy.zeros((fp.ntemps, fp.nwalkers), dtype=int)
            for tk in tidx:
                for wi in widx:
                    samples = cls.read_samples(
                            fp, param,
                            thin_start=start_index, thin_interval=1,
                            thin_end=end_index,
                            walkers=wi, temps=tk)[param]
                    acl = autocorrelation.calculate_acl(samples)
                    these_acls[tk, wi] = int(min(acl, samples.size))
            acls[param] = these_acls
        return FieldArray.from_kwargs(**acls)
开发者ID:johnveitch,项目名称:pycbc,代码行数:42,代码来源:sampler_emcee.py

示例9: _oldstyle_read_acls

    def _oldstyle_read_acls(fp):
        """Deprecated: reads acls from older style files.

        Parameters
        ----------
        fp : InferenceFile
            An open file handler to read the acls from.

        Returns
        -------
        FieldArray
            An ntemps-long ``FieldArray`` containing the acls for every
            temperature, with the variable arguments as fields.
        """
        group = fp.samples_group + '/{param}/temp{tk}'
        tidx = numpy.arange(fp.ntemps)
        arrays = {}
        for param in fp.variable_args:
            arrays[param] = numpy.array([
                fp[group.format(param=param, tk=tk)].attrs['acl']
                for tk in tidx])
        return FieldArray.from_kwargs(**arrays)
开发者ID:cmbiwer,项目名称:pycbc,代码行数:22,代码来源:sampler_emcee.py

示例10: read_acls

    def read_acls(fp):
        """Reads the acls of all the walker chains saved in the given file.

        Parameters
        ----------
        fp : InferenceFile
            An open file handler to read the acls from.

        Returns
        -------
        FieldArray
            An nwalkers-long `FieldArray` containing the acl for each walker
            and each variable argument, with the variable arguments as fields.
        """
        group = fp.samples_group + '/{param}/walker{wi}'
        widx = numpy.arange(fp.nwalkers)
        arrays = {}
        for param in fp.variable_args:
            arrays[param] = numpy.array([
                fp[group.format(param=param, wi=wi)].attrs['acl']
                for wi in widx])
        return FieldArray.from_kwargs(**arrays)
开发者ID:bema-ligo,项目名称:pycbc,代码行数:22,代码来源:sampler_base.py

示例11: copy_samples

    def copy_samples(self, other, parameters=None, parameter_names=None,
                     read_args=None, write_args=None):
        """Should copy samples to the other files.

        Parameters
        ----------
        other : InferenceFile
            An open inference file to write to.
        parameters : list of str, optional
            List of parameters to copy. If None, will copy all parameters.
        parameter_names : dict, optional
            Rename one or more parameters to the given name. The dictionary
            should map parameter -> parameter name. If None, will just use the
            original parameter names.
        read_args : dict, optional
            Arguments to pass to ``read_samples``.
        write_args : dict, optional
            Arguments to pass to ``write_samples``.
        """
        # select the samples to copy
        logging.info("Reading samples to copy")
        if parameters is None:
            parameters = self.variable_params
        # if list of desired parameters is different, rename
        if set(parameters) != set(self.variable_params):
            other.attrs['variable_params'] = parameters
        samples = self.read_samples(parameters, **read_args)
        logging.info("Copying {} samples".format(samples.size))
        # if different parameter names are desired, get them from the samples
        if parameter_names:
            arrs = {pname: samples[p] for p, pname in parameter_names.items()}
            arrs.update({p: samples[p] for p in parameters if
                         p not in parameter_names})
            samples = FieldArray.from_kwargs(**arrs)
            other.attrs['variable_params'] = samples.fieldnames
        logging.info("Writing samples")
        other.write_samples(other, samples, **write_args)
开发者ID:bhooshan-gadre,项目名称:pycbc,代码行数:37,代码来源:base_hdf.py

示例12: samples

    def samples(self):
        """Returns the samples in the chain as a FieldArray.

        If the sampling args are not the same as the variable args, the
        returned samples will have both the sampling and the variable args.

        The returned FieldArray has dimension [additional dimensions x]
        nwalkers x niterations.
        """
        # chain is a [additional dimensions x] niterations x ndim array
        samples = self.chain
        sampling_args = self.sampling_args
        # convert to dictionary to apply boundary conditions
        samples = {param: samples[...,ii]
                   for ii,param in enumerate(sampling_args)}
        samples = self.likelihood_evaluator._prior.apply_boundary_conditions(
            **samples)
        # now convert to field array
        samples = FieldArray.from_arrays([samples[param]
                                          for param in sampling_args],
                                         names=sampling_args)
        # apply transforms to go to variable args space
        return self.likelihood_evaluator.apply_sampling_transforms(samples,
            inverse=True)
开发者ID:cmbiwer,项目名称:pycbc,代码行数:24,代码来源:sampler_base.py

示例13: TemplateBank

class TemplateBank(object):
    """ Class to provide some basic helper functions and information
    about elements of an xml template bank.
    """
    def __init__(self, filename, approximant=None, **kwds):
        ext = os.path.basename(filename)
        if 'xml' in ext:
            self.indoc = ligolw_utils.load_filename(
                filename, False, contenthandler=LIGOLWContentHandler)
            self.table = table.get_table(
                self.indoc, lsctables.SnglInspiralTable.tableName)
            self.table = FieldArray.from_ligolw_table(self.table)

            # inclination stored in xml alpha3 column
            names = list(self.table.dtype.names)
            names = tuple([n if n != 'alpha3' else 'inclination' for n in names]) 
            self.table.dtype.names = names    

        elif 'hdf' in ext:
            f = h5py.File(filename, 'r')
            dtype = []
            data = {}
            for key in f.keys():
                try:
                    data[str(key)] = f[key][:]
                    dtype.append((str(key), data[key].dtype))
                except:
                    pass

            num = len(data[data.keys()[0]])
            self.table = FieldArray(num, dtype=dtype)
            for key in data:
                self.table[key] = data[key]
        else:
            raise ValueError("Unsupported template bank file extension %s" % ext)

        if not hasattr(self.table, 'template_duration'):
            self.table = self.table.add_fields(numpy.zeros(len(self.table),
                                     dtype=numpy.float32), 'template_duration') 
        self.extra_args = kwds  
        self.approximant_str = approximant

    @staticmethod
    def parse_option(row, arg):
        safe_dict = {}
        safe_dict.update(row.__dict__)
        safe_dict.update(math.__dict__)
        return eval(arg, {"__builtins__":None}, safe_dict)

    def end_frequency(self, index):
        """ Return the end frequency of the waveform at the given index value
        """
        from pycbc.waveform.waveform import props

        return pycbc.waveform.get_waveform_end_frequency(self.table[index],
                              approximant=self.approximant(index),
                              **self.extra_args)      

    def approximant(self, index):
        """ Return the name of the approximant ot use at the given index
        """
        if self.approximant_str is not None:
            if 'params' in self.approximant_str:
                t = type('t', (object,), {'params' : self.table[index]})
                approximant = str(self.parse_option(t, self.approximant_str)) 
            else:
                approximant = self.approximant_str
        else:
            raise ValueError("Reading approximant from template bank not yet supported")

        return approximant

    def __len__(self):
        return len(self.table)
开发者ID:millsjc,项目名称:pycbc,代码行数:74,代码来源:bank.py

示例14: compute_acfs

    def compute_acfs(cls, fp, start_index=None, end_index=None,
                     per_walker=False, walkers=None, parameters=None,
                     temps=None):
        """Computes the autocorrleation function of the variable args in the
        given file.

        By default, parameter values are averaged over all walkers at each
        iteration. The ACF is then calculated over the averaged chain for each
        temperature. An ACF per-walker will be returned instead if
        ``per_walker=True``.

        Parameters
        -----------
        fp : InferenceFile
            An open file handler to read the samples from.
        start_index : {None, int}
            The start index to compute the acl from. If None, will try to use
            the number of burn-in iterations in the file; otherwise, will start
            at the first sample.
        end_index : {None, int}
            The end index to compute the acl to. If None, will go to the end
            of the current iteration.
        per_walker : optional, bool
            Return the ACF for each walker separately. Default is False.
        walkers : optional, int or array
            Calculate the ACF using only the given walkers. If None (the
            default) all walkers will be used.
        parameters : optional, str or array
            Calculate the ACF for only the given parameters. If None (the
            default) will calculate the ACF for all of the variable args.
        temps : optional, (list of) int or 'all'
            The temperature index (or list of indices) to retrieve. If None
            (the default), the ACF will only be computed for the coldest (= 0)
            temperature chain. To compute an ACF for all temperates pass 'all',
            or a list of all of the temperatures.

        Returns
        -------
        FieldArray
            A ``FieldArray`` of the ACF vs iteration for each parameter. If
            `per-walker` is True, the FieldArray will have shape
            ``ntemps x nwalkers x niterations``. Otherwise, the returned
            array will have shape ``ntemps x niterations``.
        """
        acfs = {}
        if parameters is None:
            parameters = fp.variable_args
        if isinstance(parameters, str) or isinstance(parameters, unicode):
            parameters = [parameters]
        if isinstance(temps, int):
            temps = [temps]
        elif temps == 'all':
            temps = numpy.arange(fp.ntemps)
        elif temps is None:
            temps = [0]
        for param in parameters:
            subacfs = []
            for tk in temps:
                if per_walker:
                    # just call myself with a single walker
                    if walkers is None:
                        walkers = numpy.arange(fp.nwalkers)
                    arrays = [cls.compute_acfs(fp, start_index=start_index,
                                               end_index=end_index,
                                               per_walker=False, walkers=ii,
                                               parameters=param,
                                               temps=tk)[param][0,:]
                              for ii in walkers]
                    # we'll stack all of the walker arrays to make a single
                    # nwalkers x niterations array; when these are stacked
                    # below, we'll get a ntemps x nwalkers x niterations array
                    subacfs.append(numpy.vstack(arrays))
                else:
                    samples = cls.read_samples(fp, param,
                                               thin_start=start_index,
                                               thin_interval=1,
                                               thin_end=end_index,
                                               walkers=walkers, temps=tk,
                                               flatten=False)[param]
                    # contract the walker dimension using the mean, and flatten
                    # the (length 1) temp dimension
                    samples = samples.mean(axis=1)[0,:]
                    thisacf = autocorrelation.calculate_acf(samples).numpy()
                    subacfs.append(thisacf)
            # stack the temperatures
            # FIXME: the following if/else can be condensed to a single line
            # using numpy.stack, once the version requirements are bumped to
            # numpy >= 1.10
            if per_walker:
                nw, ni = subacfs[0].shape
                acfs[param] = numpy.zeros((len(temps), nw, ni), dtype=float)
                for tk in range(len(temps)):
                    acfs[param][tk,...] = subacfs[tk]
            else:
                acfs[param] = numpy.vstack(subacfs)
        return FieldArray.from_kwargs(**acfs)
开发者ID:cmbiwer,项目名称:pycbc,代码行数:96,代码来源:sampler_emcee.py

示例15: copy

    def copy(self, other, parameters=None, parameter_names=None,
             posterior_only=False, **kwargs):
        """Copies data in this file to another file.

        The samples and stats to copy may be down selected using the given
        kwargs. All other data (the "metadata") are copied exactly.

        Parameters
        ----------
        other : str or InferenceFile
            The file to write to. May be either a string giving a filename,
            or an open hdf file. If the former, the file will be opened with
            the write attribute (note that if a file already exists with that
            name, it will be deleted).
        parameters : list of str, optional
            List of parameters to copy. If None, will copy all parameters.
        parameter_names : dict, optional
            Rename one or more parameters to the given name. The dictionary
            should map parameter -> parameter name. If None, will just use the
            original parameter names.
        posterior_only : bool, optional
            Write the samples and likelihood stats as flattened arrays, and
            set other's posterior_only attribute. For example, if this file
            has a parameter's samples written to
            `{samples_group}/{param}/walker{x}`, then other will have all of
            the selected samples from all walkers written to
            `{samples_group}/{param}/`.
        \**kwargs :
            All other keyword arguments are passed to `read_samples`.

        Returns
        -------
        InferenceFile
            The open file handler to other.
        """
        if not isinstance(other, h5py.File):
            # check that we're not trying to overwrite this file
            if other == self.name:
                raise IOError("destination is the same as this file")
            other = InferenceFile(other, 'w')
        # copy metadata over
        self.copy_metadata(other)
        # update other's posterior attribute
        if posterior_only:
            other.attrs['posterior_only'] = posterior_only
        # select the samples to copy
        logging.info("Reading samples to copy")
        if parameters is None:
            parameters = self.variable_args
        # if list of desired parameters is different, rename variable args
        if set(parameters) != set(self.variable_args):
            other.attrs['variable_args'] = parameters
        # if only the posterior is desired, we'll flatten the results
        if not posterior_only and not self.posterior_only:
            kwargs['flatten'] = False
        samples = self.read_samples(parameters, **kwargs)
        logging.info("Copying {} samples".format(samples.size))
        # if different parameter names are desired, get them from the samples
        if parameter_names:
            arrs = {pname: samples[p] for p,pname in parameter_names.items()}
            arrs.update({p: samples[p] for p in parameters
                                        if p not in parameter_names})
            samples = FieldArray.from_kwargs(**arrs)
            other.attrs['variable_args'] = samples.fieldnames
        logging.info("Writing samples")
        other.samples_parser.write_samples_group(other, self.samples_group,
                                                 samples.fieldnames, samples)
        # do the same for the likelihood stats
        logging.info("Reading stats to copy")
        stats = self.read_likelihood_stats(**kwargs)
        logging.info("Writing stats")
        other.samples_parser.write_samples_group(other, self.stats_group,
                                                 stats.fieldnames, stats)
        # if any down selection was done, re-set the burn in iterations and
        # the acl, and the niterations.
        # The last dimension of the samples returned by the sampler should
        # be the number of iterations.
        if samples.shape[-1] != self.niterations:
            other.attrs['acl'] = 1
            other.attrs['burn_in_iterations'] = 0
            other.attrs['niterations'] = samples.shape[-1]
        return other
开发者ID:pannarale,项目名称:pycbc,代码行数:82,代码来源:inference_hdf.py


注:本文中的pycbc.io.FieldArray类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。