signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def smaller(self, other): | raise NotImplementedError("<STR_LIT>")<EOL> | A function to determine whether or not `other` is smaller
than the bound. This raises a NotImplementedError; classes that
inherit from this must define it. | f15933:c0:m1 |
def larger(self, other): | return self > other<EOL> | Returns True if `other` is `>`, False otherwise | f15933:c1:m0 |
def smaller(self, other): | return self < other<EOL> | Returns True if `other` is `<`, False otherwise. | f15933:c1:m1 |
def reflect_left(self, value): | if value > self:<EOL><INDENT>value = self.reflect(value)<EOL><DEDENT>return value<EOL> | Only reflects the value if is > self. | f15933:c3:m1 |
def reflect_right(self, value): | if value < self:<EOL><INDENT>value = self.reflect(value)<EOL><DEDENT>return value<EOL> | Only reflects the value if is < self. | f15933:c3:m2 |
def _reflect_well(self, value): | return reflect_well(value, self)<EOL> | Thin wrapper around `reflect_well` that passes self as the `bounds`. | f15933:c4:m7 |
def _apply_cyclic(self, value): | return apply_cyclic(value, self)<EOL> | Thin wrapper around `apply_cyclic` that passes self as the `bounds`. | f15933:c4:m8 |
def apply_conditions(self, value): | retval = value<EOL>if self._cyclic:<EOL><INDENT>retval = apply_cyclic(value, self)<EOL><DEDENT>retval = self._reflect(retval)<EOL>if isinstance(retval, numpy.ndarray) and retval.size == <NUM_LIT:1>:<EOL><INDENT>try:<EOL><INDENT>retval = retval[<NUM_LIT:0>]<EOL><DEDENT>except IndexError:<EOL><INDENT>retval = float(retva... | Applies any boundary conditions to the given value.
The value is manipulated according based on the following conditions:
* If `self.cyclic` is True then `value` is wrapped around to the
minimum (maximum) bound if `value` is `>= self.max` (`< self.min`)
bound. For example, if th... | f15933:c4:m9 |
def contains_conditioned(self, value): | return self.apply_conditions(value) in self<EOL> | Runs `apply_conditions` on the given value before testing whether it
is in bounds. Note that if `cyclic` is True, or both bounds
are reflected, than this will always return True.
Parameters
----------
value : float
The value to test.
Returns
-------
... | f15933:c4:m10 |
def insert_optimization_option_group(parser): | optimization_group = parser.add_argument_group("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>optimization_group.add_argument("<STR_LIT>", help="""<STR_LIT>""")<EOL>optimization_group.add_argument("<STR_LIT>", help="""<STR_LIT>""")<EOL> | Adds the options used to specify optimization-specific options.
Parameters
----------
parser : object
OptionParser instance | f15934:m0 |
def verify_optimization_options(opt, parser): | <EOL>requested_cpus = None<EOL>if opt.cpu_affinity_from_env is not None:<EOL><INDENT>if opt.cpu_affinity is not None:<EOL><INDENT>logging.error("<STR_LIT>")<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>requested_cpus = os.environ.get(opt.cpu_affinity_from_env)<EOL>if requested_cpus is None:<EOL><INDENT>logging.error("<STR_LIT... | Parses the CLI options, verifies that they are consistent and
reasonable, and acts on them if they are
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes
parser : object
OptionParser instance. | f15934:m1 |
def __init__(self, minv, maxv, n): | <EOL>if not isinstance(n, int):<EOL><INDENT>raise TypeError(n)<EOL><DEDENT>if n < <NUM_LIT:1>:<EOL><INDENT>raise ValueError(n)<EOL><DEDENT>if maxv <= minv:<EOL><INDENT>raise ValueError((minv, maxv))<EOL><DEDENT>self.minv = minv<EOL>self.maxv = maxv<EOL>self.n = n<EOL> | Initialize a Bins instance. The three arguments are the
minimum and maximum of the values spanned by the bins, and
the number of bins to place between them. Subclasses may
require additional arguments, or different arguments
altogether. | f15935:c0:m0 |
def __getitem__(self, x): | if isinstance(x, slice):<EOL><INDENT>if x.step is not None:<EOL><INDENT>raise NotImplementedError("<STR_LIT>" % repr(x))<EOL><DEDENT>return slice(self[x.start] if x.start is not None<EOL>else <NUM_LIT:0>, self[x.stop] + <NUM_LIT:1> if x.stop is not None<EOL>else len(self))<EOL><DEDENT>raise NotImplementedError<EOL> | Convert a co-ordinate to a bin index. The co-ordinate can
be a single value, or a Python slice instance describing a
range of values. If a single value is given, it is mapped
to the bin index corresponding to that value. If a slice
is given, it is converted to a slice whose lower bound is
the index of the bin in whi... | f15935:c0:m2 |
def __iter__(self): | raise NotImplementedError<EOL> | If __iter__ does not exist, Python uses __getitem__ with
range(0) as input to define iteration. This is nonsensical
for bin objects, so explicitly unsupport iteration. | f15935:c0:m3 |
def lower(self): | raise NotImplementedError<EOL> | Return an array containing the locations of the lower
boundaries of the bins. | f15935:c0:m4 |
def centres(self): | raise NotImplementedError<EOL> | Return an array containing the locations of the bin
centres. | f15935:c0:m5 |
def upper(self): | raise NotImplementedError<EOL> | Return an array containing the locations of the upper
boundaries of the bins. | f15935:c0:m6 |
def __init__(self, boundaries): | <EOL>if len(boundaries) < <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>boundaries = tuple(boundaries)<EOL>if any(a > b for a, b in zip(boundaries[:-<NUM_LIT:1>], boundaries[<NUM_LIT:1>:])):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.boundaries = boundaries<EOL>self.n = len(boundari... | Initialize a set of custom bins with the bin boundaries.
This includes all left edges plus the right edge. The
boundaries must be monotonic and there must be at least two
elements. | f15935:c1:m0 |
def __getitem__(self, coords): | if isinstance(coords, tuple):<EOL><INDENT>if len(coords) != len(self):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return tuple(map(lambda b, c: b[c], self, coords))<EOL><DEDENT>else:<EOL><INDENT>return tuple.__getitem__(self, coords)<EOL><DEDENT> | When coords is a tuple, it is interpreted as an
N-dimensional co-ordinate which is converted to an N-tuple
of bin indices by the Bins instances in this object.
Otherwise coords is interpeted as an index into the tuple,
and the corresponding Bins instance is returned.
Example:
>>> x = NDBins((LinearBins(1, 25, 3), Log... | f15935:c6:m1 |
def lower(self): | return tuple(b.lower() for b in self)<EOL> | Return a tuple of arrays, where each array contains the
locations of the lower boundaries of the bins in the
corresponding dimension. | f15935:c6:m2 |
def centres(self): | return tuple(b.centres() for b in self)<EOL> | Return a tuple of arrays, where each array contains the
locations of the bin centres for the corresponding
dimension. | f15935:c6:m3 |
def upper(self): | return tuple(b.upper() for b in self)<EOL> | Return a tuple of arrays, where each array contains the
locations of the upper boundaries of the bins in the
corresponding dimension. | f15935:c6:m4 |
def copy(self): | return type(self)(self.bins, self.array.copy())<EOL> | Return a copy of the BinnedArray. The .bins attribute is
shared with the original. | f15935:c7:m4 |
def centres(self): | return self.bins.centres()<EOL> | Return a tuple of arrays containing the bin centres for
each dimension. | f15935:c7:m5 |
def argmin(self): | return tuple(centres[index] for centres, index in<EOL>zip(self.centres(), numpy.unravel_index(self.array.argmin(),<EOL>self.array.shape)))<EOL> | Return the co-ordinates of the bin centre containing the
minimum value. Same as numpy.argmin(), converting the
indexes to bin co-ordinates. | f15935:c7:m6 |
def argmax(self): | return tuple(centres[index] for centres, index in<EOL>zip(self.centres(), numpy.unravel_index(self.array.argmax(),<EOL>self.array.shape)))<EOL> | Return the co-ordinates of the bin centre containing the
maximum value. Same as numpy.argmax(), converting the
indexes to bin co-ordinates. | f15935:c7:m7 |
def logregularize(self, epsilon=<NUM_LIT:2>**-<NUM_LIT>): | self.array[self.array <= <NUM_LIT:0>] = epsilon<EOL>return self<EOL> | Find bins <= 0, and set them to epsilon, This has the
effect of allowing the logarithm of the array to be
evaluated without error. | f15935:c7:m8 |
def incnumerator(self, coords, weight=<NUM_LIT:1>): | self.numerator[coords] += weight<EOL> | Add weight to the numerator bin at coords. | f15935:c8:m3 |
def incdenominator(self, coords, weight=<NUM_LIT:1>): | self.denominator[coords] += weight<EOL> | Add weight to the denominator bin at coords. | f15935:c8:m4 |
def ratio(self): | return self.numerator.array / self.denominator.array<EOL> | Compute and return the array of ratios. | f15935:c8:m5 |
def regularize(self): | self.denominator.array[self.denominator.array == <NUM_LIT:0>] = <NUM_LIT:1><EOL>return self<EOL> | Find bins in the denominator that are 0, and set them to 1.
Presumably the corresponding bin in the numerator is also
0, so this has the effect of allowing the ratio array to be
evaluated without error, returning zeros in those bins that
have had no weight added to them. | f15935:c8:m6 |
def logregularize(self, epsilon=<NUM_LIT:2>**-<NUM_LIT>): | self.numerator.array[self.denominator.array == <NUM_LIT:0>] = epsilon<EOL>self.denominator.array[self.denominator.array == <NUM_LIT:0>] = <NUM_LIT:1><EOL>return self<EOL> | Find bins in the denominator that are 0, and set them to 1,
while setting the corresponding bin in the numerator to
float epsilon. This has the effect of allowing the
logarithm of the ratio array to be evaluated without error. | f15935:c8:m7 |
def centres(self): | return self.numerator.bins.centres()<EOL> | Return a tuple of arrays containing the bin centres for
each dimension. | f15935:c8:m8 |
def _pdf(self, **kwargs): | if kwargs in self:<EOL><INDENT>return self._norm<EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:0.><EOL><DEDENT> | Returns the pdf at the given values. The keyword arguments must
contain all of parameters in self's params. Unrecognized arguments are
ignored. | f15936:c0:m3 |
def _logpdf(self, **kwargs): | if kwargs in self:<EOL><INDENT>return self._lognorm<EOL><DEDENT>else:<EOL><INDENT>return -numpy.inf<EOL><DEDENT> | Returns the log of the pdf at the given values. The keyword
arguments must contain all of parameters in self's params. Unrecognized
arguments are ignored. | f15936:c0:m4 |
def rvs(self, size=<NUM_LIT:1>, param=None): | if param is not None:<EOL><INDENT>dtype = [(param, float)]<EOL><DEDENT>else:<EOL><INDENT>dtype = [(p, float) for p in self.params]<EOL><DEDENT>arr = numpy.zeros(size, dtype=dtype)<EOL>for (p,_) in dtype:<EOL><INDENT>arr[p] = numpy.random.uniform(self._bounds[p][<NUM_LIT:0>],<EOL>self._bounds[p][<NUM_LIT:1>],<EOL>size=s... | Gives a set of random values drawn from this distribution.
Parameters
----------
size : {1, int}
The number of values to generate; default is 1.
param : {None, string}
If provided, will just return values for the given parameter.
Otherwise, returns ra... | f15936:c0:m5 |
@classmethod<EOL><INDENT>def from_config(cls, cp, section, variable_args):<DEDENT> | return super(Uniform, cls).from_config(cp, section, variable_args,<EOL>bounds_required=True)<EOL> | Returns a distribution based on a configuration file. The parameters
for the distribution are retrieved from the section titled
"[`section`-`variable_args`]" in the config file.
Parameters
----------
cp : pycbc.workflow.WorkflowConfigParser
A parsed configuration fil... | f15936:c0:m6 |
@property<EOL><INDENT>def domain(self):<DEDENT> | return self._domain<EOL> | Returns the domain of the distribution. | f15937:c0:m1 |
def apply_boundary_conditions(self, **kwargs): | <EOL>kwargs = dict([[p, self._domain.apply_conditions(val)]<EOL>for p,val in kwargs.items()])<EOL>return super(UniformAngle, self).apply_boundary_conditions(**kwargs)<EOL> | Maps values to be in [0, 2pi) (the domain) first, before applying
any additional boundary conditions.
Parameters
----------
\**kwargs :
The keyword args should be the name of a parameter and value to
apply its boundary conditions to. The arguments need not includ... | f15937:c0:m2 |
@classmethod<EOL><INDENT>def from_config(cls, cp, section, variable_args):<DEDENT> | <EOL>additional_opts = {'<STR_LIT>': cp.has_option_tag(section,<EOL>'<STR_LIT>', variable_args)}<EOL>return bounded.bounded_from_config(cls, cp, section, variable_args,<EOL>bounds_required=False,<EOL>additional_opts=additional_opts)<EOL> | Returns a distribution based on a configuration file.
The parameters for the distribution are retrieved from the section
titled "[`section`-`variable_args`]" in the config file. By default,
only the name of the distribution (`uniform_angle`) needs to be
specified. This will results in a... | f15937:c0:m3 |
def _pdf(self, **kwargs): | if kwargs not in self:<EOL><INDENT>return <NUM_LIT:0.><EOL><DEDENT>return self._norm *self._dfunc(numpy.array([kwargs[p] for p in self._params])).prod()<EOL> | Returns the pdf at the given values. The keyword arguments must
contain all of parameters in self's params. Unrecognized arguments are
ignored. | f15937:c1:m1 |
def _logpdf(self, **kwargs): | if kwargs not in self:<EOL><INDENT>return -numpy.inf<EOL><DEDENT>return self._lognorm +numpy.log(self._dfunc(<EOL>numpy.array([kwargs[p] for p in self._params]))).sum()<EOL> | Returns the log of the pdf at the given values. The keyword
arguments must contain all of parameters in self's params. Unrecognized
arguments are ignored. | f15937:c1:m2 |
def rvs(self, size=<NUM_LIT:1>, param=None): | if param is not None:<EOL><INDENT>dtype = [(param, float)]<EOL><DEDENT>else:<EOL><INDENT>dtype = [(p, float) for p in self.params]<EOL><DEDENT>arr = numpy.zeros(size, dtype=dtype)<EOL>for (p,_) in dtype:<EOL><INDENT>arr[p] = self._arcfunc(numpy.random.uniform(<EOL>self._func(self._bounds[p][<NUM_LIT:0>]),<EOL>self._fun... | Gives a set of random values drawn from this distribution.
Parameters
----------
size : {1, int}
The number of values to generate; default is 1.
param : {None, string}
If provided, will just return values for the given parameter.
Otherwise, returns ra... | f15937:c1:m3 |
def apply_boundary_conditions(self, **kwargs): | polarval = kwargs[self._polar_angle]<EOL>azval = kwargs[self._azimuthal_angle]<EOL>polarval = self._polardist._domain.apply_conditions(polarval)<EOL>azval = self._azimuthaldist._domain.apply_conditions(azval)<EOL>polarval = self._bounds[self._polar_angle].apply_conditions(polarval)<EOL>azval = self._bounds[self._azimut... | Maps the given values to be within the domain of the azimuthal and
polar angles, before applying any other boundary conditions.
Parameters
----------
\**kwargs :
The keyword args must include values for both the azimuthal and
polar angle, using the names they wer... | f15937:c3:m3 |
def _pdf(self, **kwargs): | return self._polardist._pdf(**kwargs) *self._azimuthaldist._pdf(**kwargs)<EOL> | Returns the pdf at the given angles.
Parameters
----------
\**kwargs:
The keyword arguments should specify the value for each angle,
using the names of the polar and azimuthal angles as the keywords.
Unrecognized arguments are ignored.
Returns
-------
float
The value of the pdf at the given values. | f15937:c3:m4 |
def _logpdf(self, **kwargs): | return self._polardist._logpdf(**kwargs) +self._azimuthaldist._logpdf(**kwargs)<EOL> | Returns the logpdf at the given angles.
Parameters
----------
\**kwargs:
The keyword arguments should specify the value for each angle,
using the names of the polar and azimuthal angles as the keywords.
Unrecognized arguments are ignored.
Returns
-------
float
The value of the pdf at the given values. | f15937:c3:m5 |
def rvs(self, size=<NUM_LIT:1>, param=None): | if param is not None:<EOL><INDENT>dtype = [(param, float)]<EOL><DEDENT>else:<EOL><INDENT>dtype = [(p, float) for p in self.params]<EOL><DEDENT>arr = numpy.zeros(size, dtype=dtype)<EOL>for (p,_) in dtype:<EOL><INDENT>if p == self._polar_angle:<EOL><INDENT>arr[p] = self._polardist.rvs(size=size)<EOL><DEDENT>elif p == sel... | Gives a set of random values drawn from this distribution.
Parameters
----------
size : {1, int}
The number of values to generate; default is 1.
param : {None, string}
If provided, will just return values for the given parameter.
Otherwise, returns ra... | f15937:c3:m6 |
@classmethod<EOL><INDENT>def from_config(cls, cp, section, variable_args):<DEDENT> | tag = variable_args<EOL>variable_args = variable_args.split(VARARGS_DELIM)<EOL>try:<EOL><INDENT>polar_angle = cp.get_opt_tag(section, '<STR_LIT>', tag)<EOL><DEDENT>except Error:<EOL><INDENT>polar_angle = cls._default_polar_angle<EOL><DEDENT>try:<EOL><INDENT>azimuthal_angle = cp.get_opt_tag(section, '<STR_LIT>', tag)<EO... | Returns a distribution based on a configuration file.
The section must have the names of the polar and azimuthal angles in
the tag part of the section header. For example:
.. code-block:: ini
[prior-theta+phi]
name = uniform_solidangle
If nothing else is provi... | f15937:c3:m7 |
def __call__(self, params): | <EOL>if isinstance(params, dict):<EOL><INDENT>params = record.FieldArray.from_kwargs(**params)<EOL><DEDENT>elif not isinstance(params, record.FieldArray):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>out = self._constraint(params)<EOL><DEDENT>except NameError:<EOL><INDENT>params = transforms.a... | Evaluates constraint. | f15939:c0:m1 |
def _constraint(self, params): | return params[self.constraint_arg]<EOL> | Evaluates constraint function. | f15939:c0:m2 |
def _constraint(self, params): | return params["<STR_LIT>"] + params["<STR_LIT>"] < self.mtotal<EOL> | Evaluates constraint function. | f15939:c1:m0 |
def _constraint(self, params): | if (params["<STR_LIT>"]**<NUM_LIT:2> + params["<STR_LIT>"]**<NUM_LIT:2> +<EOL>params["<STR_LIT>"]**<NUM_LIT:2>)**<NUM_LIT:2> > <NUM_LIT:1>:<EOL><INDENT>return False<EOL><DEDENT>elif (params["<STR_LIT>"]**<NUM_LIT:2> + params["<STR_LIT>"]**<NUM_LIT:2> +<EOL>params["<STR_LIT>"]**<NUM_LIT:2>)**<NUM_LIT:2> > <NUM_LIT:1>:<E... | Evaluates constraint function. | f15939:c2:m0 |
def _constraint(self, params): | <EOL>if params["<STR_LIT>"] < params["<STR_LIT>"]:<EOL><INDENT>return False<EOL><DEDENT>a = ((<NUM_LIT> * params["<STR_LIT:q>"]**<NUM_LIT:2> + <NUM_LIT> * params["<STR_LIT:q>"])<EOL>/ (<NUM_LIT> + <NUM_LIT> * params["<STR_LIT:q>"]) * params["<STR_LIT>"])**<NUM_LIT:2><EOL>b = ((<NUM_LIT:1.0> + params["<STR_LIT:q>"]**<NU... | Evaluates constraint function. | f15939:c3:m0 |
def rvs(self, size=<NUM_LIT:1>): | size = int(size)<EOL>dtype = [(p, float) for p in self.params]<EOL>arr = numpy.zeros(size, dtype=dtype)<EOL>remaining = size<EOL>keepidx = <NUM_LIT:0><EOL>while remaining:<EOL><INDENT>draws = super(UniformF0Tau, self).rvs(size=remaining)<EOL>mask = self._constraints(draws)<EOL>addpts = mask.sum()<EOL>arr[keepidx:keepid... | Draw random samples from this distribution.
Parameters
----------
size : int, optional
The number of draws to do. Default is 1.
Returns
-------
array
A structured array of the random draws. | f15940:c0:m3 |
@classmethod<EOL><INDENT>def from_config(cls, cp, section, variable_args):<DEDENT> | tag = variable_args<EOL>variable_args = set(variable_args.split(pycbc.VARARGS_DELIM))<EOL>f0 = bounded.get_param_bounds_from_config(cp, section, tag, '<STR_LIT>')<EOL>tau = bounded.get_param_bounds_from_config(cp, section, tag, '<STR_LIT>')<EOL>if cp.has_option_tag(section, '<STR_LIT>', tag):<EOL><INDENT>rdfreq = cp.ge... | Initialize this class from a config file.
Bounds on ``f0``, ``tau``, ``final_mass`` and ``final_spin`` should
be specified by providing ``min-{param}`` and ``max-{param}``. If
the ``f0`` or ``tau`` param should be renamed, ``rdfreq`` and
``damping_time`` should be provided; these must m... | f15940:c0:m4 |
def get_param_bounds_from_config(cp, section, tag, param): | try:<EOL><INDENT>minbnd = float(cp.get_opt_tag(section, '<STR_LIT>'+param, tag))<EOL><DEDENT>except Error:<EOL><INDENT>minbnd = None<EOL><DEDENT>try:<EOL><INDENT>maxbnd = float(cp.get_opt_tag(section, '<STR_LIT>'+param, tag))<EOL><DEDENT>except Error:<EOL><INDENT>maxbnd = None<EOL><DEDENT>if minbnd is None and maxbnd i... | Gets bounds for the given parameter from a section in a config file.
Minimum and maximum values for bounds are specified by adding
`min-{param}` and `max-{param}` options, where `{param}` is the name of
the parameter. The types of boundary (open, closed, or reflected) to create
may also be specified by... | f15941:m0 |
def bounded_from_config(cls, cp, section, variable_args,<EOL>bounds_required=False, additional_opts=None): | tag = variable_args<EOL>variable_args = variable_args.split(VARARGS_DELIM)<EOL>if additional_opts is None:<EOL><INDENT>additional_opts = {}<EOL><DEDENT>special_args = ["<STR_LIT:name>"] +['<STR_LIT>'.format(arg) for arg in variable_args] +['<STR_LIT>'.format(arg) for arg in variable_args] +['<STR_LIT>'.format(arg) for ... | Returns a bounded distribution based on a configuration file. The
parameters for the distribution are retrieved from the section titled
"[`section`-`variable_args`]" in the config file.
Parameters
----------
cls : pycbc.prior class
The class to initialize with.
cp : pycbc.workflow.Workf... | f15941:m1 |
def apply_boundary_conditions(self, **kwargs): | return dict([[p, self._bounds[p].apply_conditions(val)]<EOL>for p,val in kwargs.items() if p in self._bounds])<EOL> | Applies any boundary conditions to the given values (e.g., applying
cyclic conditions, and/or reflecting values off of boundaries). This
is done by running `apply_conditions` of each bounds in self on the
corresponding value. See `boundaries.Bounds.apply_conditions` for
details.
... | f15941:c0:m4 |
def pdf(self, **kwargs): | return self._pdf(**self.apply_boundary_conditions(**kwargs))<EOL> | Returns the pdf at the given values. The keyword arguments must
contain all of parameters in self's params. Unrecognized arguments are
ignored. Any boundary conditions are applied to the values before the
pdf is evaluated. | f15941:c0:m5 |
def _pdf(self, **kwargs): | raise NotImplementedError("<STR_LIT>")<EOL> | The underlying pdf function called by `self.pdf`. This must be set
by any class that inherits from this class. Otherwise, a
`NotImplementedError` is raised. | f15941:c0:m6 |
def logpdf(self, **kwargs): | return self._logpdf(**self.apply_boundary_conditions(**kwargs))<EOL> | Returns the log of the pdf at the given values. The keyword
arguments must contain all of parameters in self's params.
Unrecognized arguments are ignored. Any boundary conditions are
applied to the values before the pdf is evaluated. | f15941:c0:m7 |
def _logpdf(self, **kwargs): | raise NotImplementedError("<STR_LIT>")<EOL> | The underlying log pdf function called by `self.logpdf`. This must
be set by any class that inherits from this class. Otherwise, a
`NotImplementedError` is raised. | f15941:c0:m8 |
@classmethod<EOL><INDENT>def from_config(cls, cp, section, variable_args, bounds_required=False):<DEDENT> | return bounded_from_config(cls, cp, section, variable_args,<EOL>bounds_required=bounds_required)<EOL> | Returns a distribution based on a configuration file. The parameters
for the distribution are retrieved from the section titled
"[`section`-`variable_args`]" in the config file.
Parameters
----------
cp : pycbc.workflow.WorkflowConfigParser
A parsed configuration fil... | f15941:c0:m9 |
def _constraints(self, values): | mass1, mass2, phi_a, phi_s, chi_eff, chi_a, xi1, xi2, _ =conversions.ensurearray(values['<STR_LIT>'], values['<STR_LIT>'],<EOL>values['<STR_LIT>'], values['<STR_LIT>'],<EOL>values['<STR_LIT>'], values['<STR_LIT>'],<EOL>values['<STR_LIT>'], values['<STR_LIT>'])<EOL>s1x = conversions.spin1x_from_xi1_phi_a_phi_s(xi1, phi_... | Applies physical constraints to the given parameter values.
Parameters
----------
values : {arr or dict}
A dictionary or structured array giving the values.
Returns
-------
bool
Whether or not the values satisfy physical | f15942:c0:m1 |
def __contains__(self, params): | isin = all([params in dist for dist in self.distributions.values()])<EOL>if not isin:<EOL><INDENT>return False<EOL><DEDENT>return self._constraints(params)<EOL> | Determines whether the given values are in each parameter's bounds
and satisfy the constraints. | f15942:c0:m2 |
def _draw(self, size=<NUM_LIT:1>, **kwargs): | <EOL>try:<EOL><INDENT>mass1 = kwargs['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>mass1 = self.mass1_distr.rvs(size=size)['<STR_LIT>']<EOL><DEDENT>try:<EOL><INDENT>mass2 = kwargs['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>mass2 = self.mass2_distr.rvs(size=size)['<STR_LIT>']<EOL><DEDENT>try:<EOL><IND... | Draws random samples without applying physical constrains. | f15942:c0:m3 |
def rvs(self, size=<NUM_LIT:1>, **kwargs): | size = int(size)<EOL>dtype = [(p, float) for p in self.params]<EOL>arr = numpy.zeros(size, dtype=dtype)<EOL>remaining = size<EOL>keepidx = <NUM_LIT:0><EOL>while remaining:<EOL><INDENT>draws = self._draw(size=remaining, **kwargs)<EOL>mask = self._constraints(draws)<EOL>addpts = mask.sum()<EOL>arr[keepidx:keepidx+addpts]... | Returns random values for all of the parameters. | f15942:c0:m5 |
@classmethod<EOL><INDENT>def from_config(cls, cp, section, variable_args):<DEDENT> | tag = variable_args<EOL>variable_args = variable_args.split(VARARGS_DELIM)<EOL>if not set(variable_args) == set(cls._params):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>mass1 = get_param_bounds_from_config(cp, section, tag, '<STR_LIT>')<EOL>mass2 = get_param_bounds_from_config(cp, section, ta... | Returns a distribution based on a configuration file. The parameters
for the distribution are retrieved from the section titled
"[`section`-`variable_args`]" in the config file.
Parameters
----------
cp : pycbc.workflow.WorkflowConfigParser
A parsed configuration fil... | f15942:c0:m6 |
def read_distributions_from_config(cp, section="<STR_LIT>"): | dists = []<EOL>variable_args = []<EOL>for subsection in cp.get_subsections(section):<EOL><INDENT>name = cp.get_opt_tag(section, "<STR_LIT:name>", subsection)<EOL>dist = distribs[name].from_config(cp, section, subsection)<EOL>if set(dist.params).isdisjoint(variable_args):<EOL><INDENT>dists.append(dist)<EOL>variable_args... | Returns a list of PyCBC distribution instances for a section in the
given configuration file.
Parameters
----------
cp : WorflowConfigParser
An open config file to read.
section : {"prior", string}
Prefix on section names from which to retrieve the distributions.
Returns
--... | f15943:m0 |
def _convert_liststring_to_list(lstring): | if lstring[<NUM_LIT:0>]=='<STR_LIT:[>' and lstring[-<NUM_LIT:1>]=='<STR_LIT:]>':<EOL><INDENT>lstring = [str(lstring[<NUM_LIT:1>:-<NUM_LIT:1>].split('<STR_LIT:U+002C>')[n].strip().strip("<STR_LIT:'>"))<EOL>for n in range(len(lstring[<NUM_LIT:1>:-<NUM_LIT:1>].split('<STR_LIT:U+002C>')))]<EOL><DEDENT>return lstring<EOL> | Checks if an argument of the configuration file is a string of a list
and returns the corresponding list (of strings).
The argument is considered to be a list if it starts with '[' and ends
with ']'. List elements should be comma separated. For example, passing
`'[foo bar, cat]'` will result in `['foo ... | f15943:m1 |
def read_params_from_config(cp, prior_section='<STR_LIT>',<EOL>vargs_section='<STR_LIT>',<EOL>sargs_section='<STR_LIT>'): | <EOL>variable_args = cp.options(vargs_section)<EOL>subsections = cp.get_subsections(prior_section)<EOL>tags = set([p for tag in subsections for p in tag.split('<STR_LIT:+>')])<EOL>missing_prior = set(variable_args) - tags<EOL>if any(missing_prior):<EOL><INDENT>raise KeyError("<STR_LIT>"<EOL>"<STR_LIT>".format('<STR_LIT... | Loads static and variable parameters from a configuration file.
Parameters
----------
cp : WorkflowConfigParser
An open config parser to read from.
prior_section : str, optional
Check that priors exist in the given section. Default is 'prior.'
vargs_section : str, optional
T... | f15943:m2 |
def read_constraints_from_config(cp, transforms=None,<EOL>constraint_section='<STR_LIT>'): | cons = []<EOL>for subsection in cp.get_subsections(constraint_section):<EOL><INDENT>name = cp.get_opt_tag(constraint_section, "<STR_LIT:name>", subsection)<EOL>constraint_arg = cp.get_opt_tag(<EOL>constraint_section, "<STR_LIT>", subsection)<EOL>kwargs = {}<EOL>section = constraint_section + "<STR_LIT:->" + subsection<... | Loads parameter constraints from a configuration file.
Parameters
----------
cp : WorkflowConfigParser
An open config parser to read from.
transforms : list, optional
List of transforms to apply to parameters before applying constraints.
constraint_section : str, optional
Th... | f15943:m3 |
def rvs(self, size=<NUM_LIT:1>, param=None): | if param is not None:<EOL><INDENT>dtype = [(param, float)]<EOL><DEDENT>else:<EOL><INDENT>dtype = [(p, float) for p in self.params]<EOL><DEDENT>arr = numpy.zeros(size, dtype=dtype)<EOL>for (p,_) in dtype:<EOL><INDENT>offset = numpy.power(self._bounds[p][<NUM_LIT:0>], self.dim)<EOL>factor = numpy.power(self._bounds[p][<N... | Gives a set of random values drawn from this distribution.
Parameters
----------
size : {1, int}
The number of values to generate; default is 1.
param : {None, string}
If provided, will just return values for the given parameter.
Otherwise, returns ra... | f15944:c0:m3 |
def _pdf(self, **kwargs): | for p in self._params:<EOL><INDENT>if p not in kwargs.keys():<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'.format(p))<EOL><DEDENT><DEDENT>if kwargs in self:<EOL><INDENT>pdf = self._norm *numpy.prod([(kwargs[p])**(self.dim - <NUM_LIT:1>)<EOL>for p in self._params])<EOL>return float(pdf)<EOL><DEDENT>else:<EOL><INDENT>re... | Returns the pdf at the given values. The keyword arguments must
contain all of parameters in self's params. Unrecognized arguments are
ignored. | f15944:c0:m4 |
def _logpdf(self, **kwargs): | for p in self._params:<EOL><INDENT>if p not in kwargs.keys():<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'.format(p))<EOL><DEDENT><DEDENT>if kwargs in self:<EOL><INDENT>log_pdf = self._lognorm +(self.dim - <NUM_LIT:1>) *numpy.log([kwargs[p] for p in self._params]).sum()<EOL>return log_pdf<EOL><DEDENT>else:<EOL><INDENT... | Returns the log of the pdf at the given values. The keyword
arguments must contain all of parameters in self's params. Unrecognized
arguments are ignored. | f15944:c0:m5 |
@classmethod<EOL><INDENT>def from_config(cls, cp, section, variable_args):<DEDENT> | return super(UniformPowerLaw, cls).from_config(cp, section,<EOL>variable_args,<EOL>bounds_required=True)<EOL> | Returns a distribution based on a configuration file. The parameters
for the distribution are retrieved from the section titled
"[`section`-`variable_args`]" in the config file.
Parameters
----------
cp : pycbc.workflow.WorkflowConfigParser
A parsed configuration fil... | f15944:c0:m6 |
def _pdf(self, **kwargs): | for p in self._params:<EOL><INDENT>if p not in kwargs.keys():<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>.format(p))<EOL><DEDENT><DEDENT>if kwargs in self:<EOL><INDENT>jacobian = <NUM_LIT:1.><EOL>for param, tparam in self._tparams.items():<EOL><INDENT>t = self._transforms[tparam]<EOL>try:<EOL><INDENT>samples = t.tran... | Returns the pdf at the given values. The keyword arguments must
contain all of parameters in self's params. Unrecognized arguments are
ignored. | f15945:c0:m3 |
def _logpdf(self, **kwargs): | if kwargs not in self:<EOL><INDENT>return -numpy.inf<EOL><DEDENT>else:<EOL><INDENT>return numpy.log(self._pdf(**kwargs))<EOL><DEDENT> | Returns the log of the pdf at the given values. The keyword
arguments must contain all of parameters in self's params.
Unrecognized arguments are ignored. | f15945:c0:m4 |
def rvs(self, size=<NUM_LIT:1>, param=None): | if param is not None:<EOL><INDENT>dtype = [(param, float)]<EOL><DEDENT>else:<EOL><INDENT>dtype = [(p, float) for p in self.params]<EOL><DEDENT>size = int(size)<EOL>arr = numpy.zeros(size, dtype=dtype)<EOL>draws = self._kde.resample(size)<EOL>draws = {param: draws[ii,:] for ii,param in enumerate(self.params)}<EOL>for (p... | Gives a set of random values drawn from the kde.
Parameters
----------
size : {1, int}
The number of values to generate; default is 1.
param : {None, string}
If provided, will just return values for the given parameter.
Otherwise, returns random value... | f15945:c0:m6 |
@staticmethod<EOL><INDENT>def get_kde_from_arrays(*arrays):<DEDENT> | return scipy.stats.gaussian_kde(numpy.vstack(arrays))<EOL> | Constructs a KDE from the given arrays.
\*arrays :
Each argument should be a 1D numpy array to construct the kde from.
The resulting KDE will have dimension given by the number of
parameters. | f15945:c0:m7 |
@classmethod<EOL><INDENT>def from_config(cls, cp, section, variable_args):<DEDENT> | raise NotImplementedError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL> | Raises a NotImplementedError; to load from a config file, use
`FromFile`. | f15945:c0:m8 |
@staticmethod<EOL><INDENT>def get_arrays_from_file(params_file, params=None):<DEDENT> | try:<EOL><INDENT>f = h5py.File(params_file, '<STR_LIT:r>')<EOL><DEDENT>except:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if params is not None:<EOL><INDENT>if not isinstance(params, list):<EOL><INDENT>params = [params]<EOL><DEDENT>for p in params:<EOL><INDENT>if p not in f.keys():<EOL><INDENT>raise ValueErr... | Reads the values of one or more parameters from an hdf file and
returns as a dictionary.
Parameters
----------
params_file : str
The hdf file that contains the values of the parameters.
params : {None, list}
If provided, will just retrieve the given param... | f15945:c1:m2 |
@classmethod<EOL><INDENT>def from_config(cls, cp, section, variable_args):<DEDENT> | return bounded.bounded_from_config(cls, cp, section, variable_args,<EOL>bounds_required=False)<EOL> | Returns a distribution based on a configuration file.
The parameters
for the distribution are retrieved from the section titled
"[`section`-`variable_args`]" in the config file.
The file to construct the distribution from must be provided by setting
`filename`. Boundary argumen... | f15945:c1:m3 |
def apply_boundary_conditions(self, **params): | for dist in self.distributions:<EOL><INDENT>params.update(dist.apply_boundary_conditions(**params))<EOL><DEDENT>return params<EOL> | Applies each distributions' boundary conditions to the given list
of parameters, returning a new list with the conditions applied.
Parameters
----------
**params :
Keyword arguments should give the parameters to apply the
conditions to.
Returns
-... | f15946:c0:m1 |
def __call__(self, **params): | for constraint in self._constraints:<EOL><INDENT>if not constraint(params):<EOL><INDENT>return -numpy.inf<EOL><DEDENT><DEDENT>return sum([d(**params)<EOL>for d in self.distributions]) - self._logpdf_scale<EOL> | Evalualate joint distribution for parameters. | f15946:c0:m2 |
def rvs(self, size=<NUM_LIT:1>): | <EOL>out = record.FieldArray(size, dtype=[(arg, float)<EOL>for arg in self.variable_args])<EOL>n = <NUM_LIT:0><EOL>while n < size:<EOL><INDENT>samples = {}<EOL>for dist in self.distributions:<EOL><INDENT>draw = dist.rvs(<NUM_LIT:1>)<EOL>for param in dist.params:<EOL><INDENT>samples[param] = draw[param][<NUM_LIT:0>]<EOL... | Rejection samples the parameter space. | f15946:c0:m3 |
def _pdf(self, **kwargs): | return numpy.exp(self._logpdf(**kwargs))<EOL> | Returns the pdf at the given values. The keyword arguments must
contain all of parameters in self's params. Unrecognized arguments are
ignored. | f15947:c0:m3 |
def _logpdf(self, **kwargs): | if kwargs in self:<EOL><INDENT>return sum([self._lognorm[p] +<EOL>self._expnorm[p]*(kwargs[p]-self._mean[p])**<NUM_LIT><EOL>for p in self._params])<EOL><DEDENT>else:<EOL><INDENT>return -numpy.inf<EOL><DEDENT> | Returns the log of the pdf at the given values. The keyword
arguments must contain all of parameters in self's params. Unrecognized
arguments are ignored. | f15947:c0:m4 |
def rvs(self, size=<NUM_LIT:1>, param=None): | if param is not None:<EOL><INDENT>dtype = [(param, float)]<EOL><DEDENT>else:<EOL><INDENT>dtype = [(p, float) for p in self.params]<EOL><DEDENT>arr = numpy.zeros(size, dtype=dtype)<EOL>for (p,_) in dtype:<EOL><INDENT>sigma = numpy.sqrt(self._var[p])<EOL>mu = self._mean[p]<EOL>a,b = self._bounds[p]<EOL>arr[p][:] = scipy.... | Gives a set of random values drawn from this distribution.
Parameters
----------
size : {1, int}
The number of values to generate; default is 1.
param : {None, string}
If provided, will just return values for the given parameter.
Otherwise, returns ra... | f15947:c0:m5 |
@classmethod<EOL><INDENT>def from_config(cls, cp, section, variable_args):<DEDENT> | return bounded.bounded_from_config(cls, cp, section, variable_args,<EOL>bounds_required=False)<EOL> | Returns a Gaussian distribution based on a configuration file. The
parameters for the distribution are retrieved from the section titled
"[`section`-`variable_args`]" in the config file.
Boundary arguments should be provided in the same way as described in
`get_param_bounds_from_config`... | f15947:c0:m6 |
def rvs(self, size=<NUM_LIT:1>, param=None): | arr = super(UniformComponentMasses, self).rvs(size=size)<EOL>m1 = conversions.primary_mass(arr['<STR_LIT>'], arr['<STR_LIT>'])<EOL>m2 = conversions.secondary_mass(arr['<STR_LIT>'], arr['<STR_LIT>'])<EOL>arr['<STR_LIT>'][:] = m1<EOL>arr['<STR_LIT>'][:] = m2<EOL>if param is not None:<EOL><INDENT>arr = arr[param]<EOL><DED... | Gives a set of random values drawn from this distribution.
In the returned set, mass2 <= mass1.
Parameters
----------
size : int
The number of values to generate; default is 1.
param : str, optional
If provided, will just return values for the given para... | f15948:c0:m1 |
def rvs(self, size=<NUM_LIT:1>, param=None): | if param is not None:<EOL><INDENT>dtype = [(param, float)]<EOL><DEDENT>else:<EOL><INDENT>dtype = [(p, float) for p in self.params]<EOL><DEDENT>arr = numpy.zeros(size, dtype=dtype)<EOL>for (p,_) in dtype:<EOL><INDENT>log_high = numpy.log10(self._bounds[p][<NUM_LIT:0>])<EOL>log_low = numpy.log10(self._bounds[p][<NUM_LIT:... | Gives a set of random values drawn from this distribution.
Parameters
----------
size : {1, int}
The number of values to generate; default is 1.
param : {None, string}
If provided, will just return values for the given parameter.
Otherwise, returns ra... | f15949:c0:m1 |
def _pdf(self, **kwargs): | if kwargs in self:<EOL><INDENT>vals = numpy.array([numpy.log(<NUM_LIT:10>) * self._norm * kwargs[param]<EOL>for param in kwargs.keys()])<EOL>return <NUM_LIT:1.0> / numpy.prod(vals)<EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:0.><EOL><DEDENT> | Returns the pdf at the given values. The keyword arguments must
contain all of parameters in self's params. Unrecognized arguments are
ignored. | f15949:c0:m2 |
def _logpdf(self, **kwargs): | if kwargs in self:<EOL><INDENT>return numpy.log(self._pdf(**kwargs))<EOL><DEDENT>else:<EOL><INDENT>return -numpy.inf<EOL><DEDENT> | Returns the log of the pdf at the given values. The keyword
arguments must contain all of parameters in self's params. Unrecognized
arguments are ignored. | f15949:c0:m3 |
def cartesian_to_spherical_rho(x, y, z): | return numpy.sqrt(x**<NUM_LIT:2> + y**<NUM_LIT:2> + z**<NUM_LIT:2>)<EOL> | Calculates the magnitude in spherical coordinates from Cartesian
coordinates.
Parameters
----------
x : {numpy.array, float}
X-coordinate.
y : {numpy.array, float}
Y-coordinate.
z : {numpy.array, float}
Z-coordinate.
Returns
-------
rho : {numpy.array, float... | f15950:m0 |
def cartesian_to_spherical_azimuthal(x, y): | y = float(y) if isinstance(y, int) else y<EOL>phi = numpy.arctan2(y, x)<EOL>return phi % (<NUM_LIT:2> * numpy.pi)<EOL> | Calculates the azimuthal angle in spherical coordinates from Cartesian
coordinates. The azimuthal angle is in [0,2*pi].
Parameters
----------
x : {numpy.array, float}
X-coordinate.
y : {numpy.array, float}
Y-coordinate.
Returns
-------
phi : {numpy.array, float}
... | f15950:m1 |
def cartesian_to_spherical_polar(x, y, z): | return numpy.arccos(z / cartesian_to_spherical_rho(x, y, z))<EOL> | Calculates the polar angle in spherical coordinates from Cartesian
coordinates. The polar angle is in [0,pi].
Parameters
----------
x : {numpy.array, float}
X-coordinate.
y : {numpy.array, float}
Y-coordinate.
z : {numpy.array, float}
Z-coordinate.
Returns
-----... | f15950:m2 |
def cartesian_to_spherical(x, y, z): | rho = cartesian_to_spherical_rho(x, y, z)<EOL>phi = cartesian_to_spherical_azimuthal(x, y)<EOL>theta = cartesian_to_spherical_polar(x, y, z)<EOL>return rho, phi, theta<EOL> | Maps cartesian coordinates (x,y,z) to spherical coordinates
(rho,phi,theta) where phi is in [0,2*pi] and theta is in [0,pi].
Parameters
----------
x : {numpy.array, float}
X-coordinate.
y : {numpy.array, float}
Y-coordinate.
z : {numpy.array, float}
Z-coordinate.
Re... | f15950:m3 |
def spherical_to_cartesian(rho, phi, theta): | x = rho * numpy.cos(phi) * numpy.sin(theta)<EOL>y = rho * numpy.sin(phi) * numpy.sin(theta)<EOL>z = rho * numpy.cos(theta)<EOL>return x, y, z<EOL> | Maps spherical coordinates (rho,phi,theta) to cartesian coordinates
(x,y,z) where phi is in [0,2*pi] and theta is in [0,pi].
Parameters
----------
rho : {numpy.array, float}
The radial amplitude.
phi : {numpy.array, float}
The azimuthal angle.
theta : {numpy.array, float}
... | f15950:m4 |
def pkg_config(pkg_libraries): | libraries=[]<EOL>library_dirs=[]<EOL>include_dirs=[]<EOL>for pkg in pkg_libraries:<EOL><INDENT>if os.system('<STR_LIT>' % pkg) == <NUM_LIT:0>:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>".format(pkg))<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if len(pkg_libraries)><NUM_LIT:0> :<EOL><INDENT>for t... | Use pkg-config to query for the location of libraries, library directories,
and header directories
Arguments:
pkg_libries(list): A list of packages as strings
Returns:
libraries(list), library_dirs(list), include_dirs(list) | f15951:m0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.