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(retval)<EOL><DEDENT><DEDENT>return retval<EOL>
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 the minimum and maximum bounds are `0, 2*pi` and `value = 5*pi`, then the returned value will be `pi`. * If `self.min` is a reflected boundary then `value` will be reflected to the right if it is `< self.min`. For example, if `self.min = 10` and `value = 3`, then the returned value will be 17. * If `self.max` is a reflected boundary then `value` will be reflected to the left if it is `> self.max`. For example, if `self.max = 20` and `value = 27`, then the returned value will be 13. * If `self.min` and `self.max` are both reflected boundaries, then `value` will be reflected between the two boundaries until it falls within the bounds. The first reflection occurs off of the maximum boundary. For example, if `self.min = 10`, `self.max = 20`, and `value = 42`, the returned value will be 18 ( the first reflection yields -2, the second 22, and the last 18). * If neither bounds are reflected and cyclic is False, then the value is just returned as-is. Parameters ---------- value : float The value to apply the conditions to. Returns ------- float The value after the conditions are applied; see above for details.
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 ------- bool Whether or not the value is within the bounds after the boundary conditions are applied.
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>"<EOL>"<STR_LIT>" % opt.cpu_affinity_from_env)<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>if requested_cpus == '<STR_LIT>':<EOL><INDENT>logging.error("<STR_LIT>"<EOL>"<STR_LIT>" % opt.cpu_affinity_from_env)<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if requested_cpus is None:<EOL><INDENT>requested_cpus = opt.cpu_affinity<EOL><DEDENT>if requested_cpus is not None:<EOL><INDENT>command = '<STR_LIT>' % (requested_cpus, os.getpid())<EOL>retcode = os.system(command)<EOL>if retcode != <NUM_LIT:0>:<EOL><INDENT>logging.error('<STR_LIT>' %(command, retcode))<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>logging.info("<STR_LIT>" % requested_cpus)<EOL><DEDENT>
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 which the slice's lower bound falls, and whose upper bound is 1 greater than the index of the bin in which the slice's upper bound falls. Steps are not supported in slices.
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(boundaries) - <NUM_LIT:1><EOL>self.minv = boundaries[<NUM_LIT:0>]<EOL>self.maxv = boundaries[-<NUM_LIT:1>]<EOL>
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), LogarithmicBins(1, 25, 3))) >>> x[1, 1] (0, 0) >>> type(x[1]) <class 'pylal.rate.LogarithmicBins'> When used to convert co-ordinates to bin indices, each co-ordinate can be anything the corresponding Bins instance will accept. Note that the co-ordinates to be converted must be a tuple, even if it is only a 1-dimensional co-ordinate.
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=size)<EOL><DEDENT>return arr<EOL>
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 random values for each parameter. Returns ------- structured array The random values in a numpy structured array. If a param was specified, the array will only have an element corresponding to the given parameter. Otherwise, the array will have an element for each parameter in self's params.
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 file that contains the distribution options. section : str Name of the section in the configuration file. variable_args : str The names of the parameters for this distribution, separated by ``VARARGS_DELIM``. These must appear in the "tag" part of the section header. Returns ------- Uniform A distribution instance from the pycbc.inference.prior module.
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 include all of the parameters in self. Returns ------- dict A dictionary of the parameter names and the conditioned values.
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 uniform prior on `[0, 2pi)`. To make the domain cyclic, add `cyclic_domain =`. To specify boundaries that are not `[0, 2pi)`, add `(min|max)-var` arguments, where `var` is the name of the variable. For example, this will initialize a variable called `theta` with a uniform distribution on `[0, 2pi)` without cyclic boundaries: .. code-block:: ini [{section}-theta] name = uniform_angle This will make the domain cyclic on `[0, 2pi)`: .. code-block:: ini [{section}-theta] name = uniform_angle cyclic_domain = Parameters ---------- cp : pycbc.workflow.WorkflowConfigParser A parsed configuration file that contains the distribution options. section : str Name of the section in the configuration file. variable_args : str The names of the parameters for this distribution, separated by ``VARARGS_DELIM``. These must appear in the "tag" part of the section header. Returns ------- UniformAngle A distribution instance from the pycbc.inference.prior module.
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._func(self._bounds[p][<NUM_LIT:1>]),<EOL>size=size))<EOL><DEDENT>return arr<EOL>
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 random values for each parameter. Returns ------- structured array The random values in a numpy structured array. If a param was specified, the array will only have an element corresponding to the given parameter. Otherwise, the array will have an element for each parameter in self's params.
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._azimuthal_angle].apply_conditions(azval)<EOL>return {self._polar_angle: polarval, self._azimuthal_angle: azval}<EOL>
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 were initilialized with. For example, if `polar_angle='theta'` and `azimuthal_angle=`phi`, then the keyword args must be `theta={val1}, phi={val2}`. Returns ------- dict A dictionary of the parameter names and the conditioned values.
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 == self._azimuthal_angle:<EOL><INDENT>arr[p] = self._azimuthaldist.rvs(size=size)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" %(p))<EOL><DEDENT><DEDENT>return arr<EOL>
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 random values for each parameter. Returns ------- structured array The random values in a numpy structured array. If a param was specified, the array will only have an element corresponding to the given parameter. Otherwise, the array will have an element for each parameter in self's params.
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)<EOL><DEDENT>except Error:<EOL><INDENT>azimuthal_angle = cls._default_azimuthal_angle<EOL><DEDENT>if polar_angle not in variable_args:<EOL><INDENT>raise Error("<STR_LIT>"%(<EOL>polar_angle, '<STR_LIT:U+002CU+0020>'.join(variable_args)))<EOL><DEDENT>if azimuthal_angle not in variable_args:<EOL><INDENT>raise Error("<STR_LIT>"%(<EOL>azimuthal_angle) + "<STR_LIT>"%('<STR_LIT:U+002CU+0020>'.join(variable_args)))<EOL><DEDENT>polar_bounds = bounded.get_param_bounds_from_config(<EOL>cp, section, tag,<EOL>polar_angle)<EOL>azimuthal_bounds = bounded.get_param_bounds_from_config(<EOL>cp, section, tag,<EOL>azimuthal_angle)<EOL>azimuthal_cyclic_domain = cp.has_option_tag(section,<EOL>'<STR_LIT>', tag)<EOL>return cls(polar_angle=polar_angle, azimuthal_angle=azimuthal_angle,<EOL>polar_bounds=polar_bounds,<EOL>azimuthal_bounds=azimuthal_bounds,<EOL>azimuthal_cyclic_domain=azimuthal_cyclic_domain)<EOL>
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 provided, the default names and bounds of the polar and azimuthal angles will be used. To specify a different name for each angle, set the `polar-angle` and `azimuthal-angle` attributes. For example: .. code-block:: ini [prior-foo+bar] name = uniform_solidangle polar-angle = foo azimuthal-angle = bar Note that the names of the variable args in the tag part of the section name must match the names of the polar and azimuthal angles. Bounds may also be specified for each angle, as factors of pi. For example: .. code-block:: ini [prior-theta+phi] polar-angle = theta azimuthal-angle = phi min-theta = 0 max-theta = 0.5 This will return a distribution that is uniform in the upper hemisphere. By default, the domain of the azimuthal angle is `[0, 2pi)`. To make this domain cyclic, add `azimuthal_cyclic_domain =`. Parameters ---------- cp : ConfigParser instance The config file. section : str The name of the section. variable_args : str The names of the parameters for this distribution, separated by ``VARARGS_DELIM``. These must appear in the "tag" part of the section header. Returns ------- UniformSolidAngle A distribution instance from the pycbc.inference.prior module.
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.apply_transforms(params, self.transforms)if self.transforms else params<EOL>out = self._constraint(params)<EOL><DEDENT>if isinstance(out, record.FieldArray):<EOL><INDENT>out = out.item() if params.size == <NUM_LIT:1> else out<EOL><DEDENT>return out<EOL>
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>:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT>
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>"]**<NUM_LIT:2>) / <NUM_LIT><EOL>* (params["<STR_LIT>"] + params["<STR_LIT>"])**<NUM_LIT:2>)<EOL>if a + b > <NUM_LIT:1>:<EOL><INDENT>return False<EOL><DEDENT>a = params["<STR_LIT>"]**<NUM_LIT:2><EOL>b = ((<NUM_LIT:1.0> + params["<STR_LIT:q>"])**<NUM_LIT:2> / (<NUM_LIT> * params["<STR_LIT:q>"]**<NUM_LIT:2>)<EOL>* (params["<STR_LIT>"] - params["<STR_LIT>"])**<NUM_LIT:2>)<EOL>if a + b > <NUM_LIT:1>:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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:keepidx+addpts] = draws[mask]<EOL>keepidx += addpts<EOL>remaining = size - keepidx<EOL><DEDENT>return arr<EOL>
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.get_opt_tag(section, '<STR_LIT>', tag)<EOL><DEDENT>else:<EOL><INDENT>rdfreq = '<STR_LIT>'<EOL><DEDENT>if cp.has_option_tag(section, '<STR_LIT>', tag):<EOL><INDENT>damping_time = cp.get_opt_tag(section, '<STR_LIT>', tag)<EOL><DEDENT>else:<EOL><INDENT>damping_time = '<STR_LIT>'<EOL><DEDENT>if not variable_args == set([rdfreq, damping_time]):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>final_mass = bounded.get_param_bounds_from_config(<EOL>cp, section, tag, '<STR_LIT>')<EOL>final_spin = bounded.get_param_bounds_from_config(<EOL>cp, section, tag, '<STR_LIT>')<EOL>extra_opts = {}<EOL>if cp.has_option_tag(section, '<STR_LIT>', tag):<EOL><INDENT>extra_opts['<STR_LIT>'] = float(<EOL>cp.get_opt_tag(section, '<STR_LIT>', tag))<EOL><DEDENT>if cp.has_option_tag(section, '<STR_LIT>', tag):<EOL><INDENT>extra_opts['<STR_LIT>'] = int(<EOL>cp.get_opt_tag(section, '<STR_LIT>', tag))<EOL><DEDENT>return cls(f0=f0, tau=tau,<EOL>final_mass=final_mass, final_spin=final_spin,<EOL>rdfreq=rdfreq, damping_time=damping_time,<EOL>**extra_opts)<EOL>
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 match ``variable_args``. If ``rdfreq`` and ``damping_time`` are not provided, ``variable_args`` are expected to be ``f0`` and ``tau``. Only ``min/max-f0`` and ``min/max-tau`` need to be provided. Example: .. code-block:: ini [{section}-f0+tau] name = uniform_f0_tau min-f0 = 10 max-f0 = 2048 min-tau = 0.0001 max-tau = 0.010 min-final_mass = 10 Parameters ---------- cp : pycbc.workflow.WorkflowConfigParser WorkflowConfigParser instance to read. section : str The name of the section to read. variable_args : str The name of the variable args. These should be separated by ``pycbc.VARARGS_DELIM``. Returns ------- UniformF0Tau : This class initialized with the parameters provided in the config file.
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 is None:<EOL><INDENT>bnds = None<EOL><DEDENT>elif minbnd is None or maxbnd is None:<EOL><INDENT>raise ValueError("<STR_LIT>" %(param) +<EOL>"<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>bndargs = {'<STR_LIT>': minbnd, '<STR_LIT>': maxbnd}<EOL>try:<EOL><INDENT>minbtype = cp.get_opt_tag(section, '<STR_LIT>'.format(param),<EOL>tag)<EOL><DEDENT>except Error:<EOL><INDENT>minbtype = '<STR_LIT>'<EOL><DEDENT>try:<EOL><INDENT>maxbtype = cp.get_opt_tag(section, '<STR_LIT>'.format(param),<EOL>tag)<EOL><DEDENT>except Error:<EOL><INDENT>maxbtype = '<STR_LIT>'<EOL><DEDENT>bndargs.update({'<STR_LIT>': minbtype, '<STR_LIT>': maxbtype})<EOL>cyclic = cp.has_option_tag(section, '<STR_LIT>'.format(param), tag)<EOL>bndargs.update({'<STR_LIT>': cyclic})<EOL>bnds = boundaries.Bounds(**bndargs)<EOL><DEDENT>return bnds<EOL>
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 adding options `btype-min-{param}` and `btype-max-{param}`. Cyclic conditions can be adding option `cyclic-{param}`. If no `btype` arguments are provided, the left bound will be closed and the right open. For example, the following will create right-open bounds for parameter `foo`: .. code-block:: ini [{section}-{tag}] min-foo = -1 max-foo = 1 This would make the boundaries cyclic: .. code-block:: ini [{section}-{tag}] min-foo = -1 max-foo = 1 cyclic-foo = For more details on boundary types and their meaning, see `boundaries.Bounds`. If the parameter is not found in the section will just return None (in this case, all `btype` and `cyclic` arguments are ignored for that parameter). If bounds are specified, both a minimum and maximum must be provided, else a Value or Type Error will be raised. Parameters ---------- cp : ConfigParser instance The config file. section : str The name of the section. tag : str Any tag in the section name. The full section name searched for in the config file is `{section}(-{tag})`. param : str The name of the parameter to retrieve bounds for. Returns ------- bounds : {Bounds instance | None} If bounds were provided, a `boundaries.Bounds` instance representing the bounds. Otherwise, `None`.
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 arg in variable_args] +['<STR_LIT>'.format(arg) for arg in variable_args] +['<STR_LIT>'.format(arg) for arg in variable_args] +list(additional_opts.keys())<EOL>dist_args = {}<EOL>for param in variable_args:<EOL><INDENT>bounds = get_param_bounds_from_config(cp, section, tag, param)<EOL>if bounds_required and bounds is None:<EOL><INDENT>raise ValueError("<STR_LIT>"%(<EOL>param))<EOL><DEDENT>dist_args[param] = bounds<EOL><DEDENT>for key in cp.options("<STR_LIT:->".join([section, tag])):<EOL><INDENT>if key in special_args:<EOL><INDENT>continue<EOL><DEDENT>val = cp.get_opt_tag(section, key, tag)<EOL>try:<EOL><INDENT>val = float(val)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT>dist_args.update({key:val})<EOL><DEDENT>dist_args.update(additional_opts)<EOL>return cls(**dist_args)<EOL>
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.WorkflowConfigParser A parsed configuration file that contains the distribution options. section : str Name of the section in the configuration file. variable_args : str The names of the parameters for this distribution, separated by `prior.VARARGS_DELIM`. These must appear in the "tag" part of the section header. bounds_required : {False, bool} If True, raise a ValueError if a min and max are not provided for every parameter. Otherwise, the prior will be initialized with the parameter set to None. Even if bounds are not required, a ValueError will be raised if only one bound is provided; i.e., either both bounds need to provided or no bounds. additional_opts : {None, dict} Provide additional options to be passed to the distribution class; should be a dictionary specifying option -> value. If an option is provided that also exists in the config file, the value provided will be used instead of being read from the file. Returns ------- cls An instance of the given class.
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. Parameters ---------- \**kwargs : The keyword args should be the name of a parameter and value to apply its boundary conditions to. The arguments need not include all of the parameters in self. Any unrecognized arguments are ignored. Returns ------- dict A dictionary of the parameter names and the conditioned values.
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 file that contains the distribution options. section : str Name of the section in the configuration file. variable_args : str The names of the parameters for this distribution, separated by `prior.VARARGS_DELIM`. These must appear in the "tag" part of the section header. bounds_required : {False, bool} If True, raise a ValueError if a min and max are not provided for every parameter. Otherwise, the prior will be initialized with the parameter set to None. Even if bounds are not required, a ValueError will be raised if only one bound is provided; i.e., either both bounds need to provided or no bounds. Returns ------- BoundedDist A distribution instance from the pycbc.distribution subpackage.
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_a, phi_s)<EOL>s2x = conversions.spin2x_from_mass1_mass2_xi2_phi_a_phi_s(mass1, mass2,<EOL>xi2, phi_a, phi_s)<EOL>s1y = conversions.spin1y_from_xi1_phi_a_phi_s(xi1, phi_a, phi_s)<EOL>s2y = conversions.spin2y_from_mass1_mass2_xi2_phi_a_phi_s(mass1, mass2,<EOL>xi2, phi_a, phi_s)<EOL>s1z = conversions.spin1z_from_mass1_mass2_chi_eff_chi_a(mass1, mass2,<EOL>chi_eff, chi_a)<EOL>s2z = conversions.spin2z_from_mass1_mass2_chi_eff_chi_a(mass1, mass2,<EOL>chi_eff, chi_a)<EOL>test = ((s1x**<NUM_LIT> + s1y**<NUM_LIT> + s1z**<NUM_LIT>) < <NUM_LIT:1.>) &((s2x**<NUM_LIT> + s2y**<NUM_LIT> + s2z**<NUM_LIT>) < <NUM_LIT:1.>)<EOL>return test<EOL>
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><INDENT>phi_a = kwargs['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>phi_a = self.phia_distr.rvs(size=size)['<STR_LIT>']<EOL><DEDENT>try:<EOL><INDENT>phi_s = kwargs['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>phi_s = self.phis_distr.rvs(size=size)['<STR_LIT>']<EOL><DEDENT>try:<EOL><INDENT>chi_eff = kwargs['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>chi_eff = self.chieff_distr.rvs(size=size)['<STR_LIT>']<EOL><DEDENT>try:<EOL><INDENT>chi_a = kwargs['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>chi_a = self.chia_distr.rvs(size=size)['<STR_LIT>']<EOL><DEDENT>try:<EOL><INDENT>xi1 = kwargs['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>xi1 = self.xi1_distr.rvs(size=size)['<STR_LIT>']<EOL><DEDENT>try:<EOL><INDENT>xi2 = kwargs['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>xi2 = self.xi2_distr.rvs(size=size)['<STR_LIT>']<EOL><DEDENT>dtype = [(p, float) for p in self.params]<EOL>arr = numpy.zeros(size, dtype=dtype)<EOL>arr['<STR_LIT>'] = mass1<EOL>arr['<STR_LIT>'] = mass2<EOL>arr['<STR_LIT>'] = phi_a<EOL>arr['<STR_LIT>'] = phi_s<EOL>arr['<STR_LIT>'] = chi_eff<EOL>arr['<STR_LIT>'] = chi_a<EOL>arr['<STR_LIT>'] = xi1<EOL>arr['<STR_LIT>'] = xi2<EOL>return arr<EOL>
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] = draws[mask]<EOL>keepidx += addpts<EOL>remaining = size - keepidx<EOL><DEDENT>return arr<EOL>
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, tag, '<STR_LIT>')<EOL>chi_eff = get_param_bounds_from_config(cp, section, tag, '<STR_LIT>')<EOL>chi_a = get_param_bounds_from_config(cp, section, tag, '<STR_LIT>')<EOL>xi_bounds = get_param_bounds_from_config(cp, section, tag, '<STR_LIT>')<EOL>if cp.has_option('<STR_LIT:->'.join([section, tag]), '<STR_LIT>'):<EOL><INDENT>nsamples = int(cp.get('<STR_LIT:->'.join([section, tag]), '<STR_LIT>'))<EOL><DEDENT>else:<EOL><INDENT>nsamples = None<EOL><DEDENT>return cls(mass1=mass1, mass2=mass2, chi_eff=chi_eff, chi_a=chi_a,<EOL>xi_bounds=xi_bounds, nsamples=nsamples)<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 file that contains the distribution options. section : str Name of the section in the configuration file. variable_args : str The names of the parameters for this distribution, separated by `prior.VARARGS_DELIM`. These must appear in the "tag" part of the section header. Returns ------- IndependentChiPChiEff A distribution instance.
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 += dist.params<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>return dists<EOL>
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 ------- list A list of the parsed distributions.
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 bar', 'cat']` being returned. If the argument does not start and end with '[' and ']', the argument will just be returned as is.
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:U+002CU+0020>'.join(missing_prior)))<EOL><DEDENT>try:<EOL><INDENT>static_args = dict([(key, cp.get_opt_tags(sargs_section, key, []))<EOL>for key in cp.options(sargs_section)])<EOL><DEDENT>except _ConfigParser.NoSectionError:<EOL><INDENT>static_args = {}<EOL><DEDENT>for key in static_args:<EOL><INDENT>val = static_args[key]<EOL>try:<EOL><INDENT>static_args[key] = float(val)<EOL><DEDENT>except ValueError:<EOL><INDENT>static_args[key] = _convert_liststring_to_list(val)<EOL><DEDENT><DEDENT>return variable_args, static_args<EOL>
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 The section to get the parameters that will be varied/need priors defined for them. Default is 'variable_args'. sargs_section : str, optional The section to get the parameters that will remain fixed. Default is 'static_args'. Returns ------- variable_args : list The names of the parameters to vary in the PE run. static_args : dict Dictionary of names -> values giving the parameters to keep fixed.
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<EOL>extra_opts = [key for key in cp.options(section)<EOL>if key not in ["<STR_LIT:name>", "<STR_LIT>"]]<EOL>for key in extra_opts:<EOL><INDENT>val = cp.get(section, key)<EOL>if key == "<STR_LIT>":<EOL><INDENT>val = val.split(_VARARGS_DELIM)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>val = float(val)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>kwargs[key] = val<EOL><DEDENT>cons.append(constraints.constraints[name](constraint_arg,<EOL>transforms=transforms,<EOL>**kwargs))<EOL><DEDENT>return cons<EOL>
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 The section to get the constraints from. Default is 'constraint'. Returns ------- list List of ``Constraint`` objects. Empty if no constraints were provided.
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][<NUM_LIT:1>], self.dim) -numpy.power(self._bounds[p][<NUM_LIT:0>], self.dim)<EOL>arr[p] = numpy.random.uniform(<NUM_LIT:0.0>, <NUM_LIT:1.0>, size=size)<EOL>arr[p] = numpy.power(factor * arr[p] + offset, <NUM_LIT:1.0> / self.dim)<EOL><DEDENT>return arr<EOL>
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 random values for each parameter. Returns ------- structured array The random values in a numpy structured array. If a param was specified, the array will only have an element corresponding to the given parameter. Otherwise, the array will have an element for each parameter in self's params.
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>return <NUM_LIT:0.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.
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>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.
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 file that contains the distribution options. section : str Name of the section in the configuration file. variable_args : str The names of the parameters for this distribution, separated by `prior.VARARGS_DELIM`. These must appear in the "tag" part of the section header. Returns ------- Uniform A distribution instance from the pycbc.inference.prior module.
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.transform({param: kwargs[param]})<EOL><DEDENT>except ValueError as e:<EOL><INDENT>if kwargs[param] in self.bounds[param]:<EOL><INDENT>return <NUM_LIT:0.><EOL><DEDENT>else:<EOL><INDENT>raise ValueError(e)<EOL><DEDENT><DEDENT>kwargs[param] = samples[tparam]<EOL>jacobian *= t.jacobian(samples)<EOL><DEDENT>this_pdf = jacobian * self._kde.evaluate([kwargs[p]<EOL>for p in self._params])<EOL>if len(this_pdf) == <NUM_LIT:1>:<EOL><INDENT>return float(this_pdf)<EOL><DEDENT>else:<EOL><INDENT>return this_pdf<EOL><DEDENT><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.
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 (param,_) in dtype:<EOL><INDENT>try:<EOL><INDENT>tparam = self._tparams[param]<EOL>tdraws = {tparam: draws[param]}<EOL>draws[param] = self._transforms[tparam].inverse_transform(<EOL>tdraws)[param]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>arr[param] = draws[param]<EOL><DEDENT>return arr<EOL>
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 values for each parameter. Returns ------- structured array The random values in a numpy structured array. If a param was specified, the array will only have an element corresponding to the given parameter. Otherwise, the array will have an element for each parameter in self's params.
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 ValueError('<STR_LIT>'<EOL>.format(p, params_file))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>params = [str(k) for k in f.keys()]<EOL><DEDENT>params_values = {p:f[p][:] for p in params}<EOL>try:<EOL><INDENT>bandwidth = f.attrs["<STR_LIT>"]<EOL><DEDENT>except KeyError:<EOL><INDENT>bandwidth = "<STR_LIT>"<EOL><DEDENT>f.close()<EOL>return params_values, bandwidth<EOL>
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 parameter names. Returns ------- dict A dictionary of the parameters mapping `param_name -> array`.
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 arguments can be provided in the same way as described in `get_param_bounds_from_config`. .. code-block:: ini [{section}-{tag}] name = fromfile filename = ra_prior.hdf min-ra = 0 max-ra = 6.28 Parameters ---------- cp : pycbc.workflow.WorkflowConfigParser A parsed configuration file that contains the distribution options. section : str Name of the section in the configuration file. variable_args : str The names of the parameters for this distribution, separated by `prior.VARARGS_DELIM`. These must appear in the "tag" part of the section header. Returns ------- BoundedDist A distribution instance from the pycbc.inference.prior module.
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 ------- dict A dictionary of the parameters after each distribution's `apply_boundary_conditions` function has been applied.
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><DEDENT><DEDENT>vals = numpy.array([samples[arg] for arg in self.variable_args])<EOL>if self(**dict(zip(self.variable_args, vals))) > -numpy.inf:<EOL><INDENT>out[n] = vals<EOL>n += <NUM_LIT:1><EOL><DEDENT><DEDENT>return out<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.stats.truncnorm.rvs((a-mu)/sigma, (b-mu)/sigma,<EOL>loc=self._mean[p], scale=sigma, size=size)<EOL><DEDENT>return arr<EOL>
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 random values for each parameter. Returns ------- structured array The random values in a numpy structured array. If a param was specified, the array will only have an element corresponding to the given parameter. Otherwise, the array will have an element for each parameter in self's params.
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`. In addition, the mean and variance of each parameter can be specified by setting `{param}_mean` and `{param}_var`, respectively. For example, the following would create a truncated Gaussian distribution between 0 and 6.28 for a parameter called `phi` with mean 3.14 and variance 0.5 that is cyclic: .. code-block:: ini [{section}-{tag}] min-phi = 0 max-phi = 6.28 phi_mean = 3.14 phi_var = 0.5 cyclic = Parameters ---------- cp : pycbc.workflow.WorkflowConfigParser A parsed configuration file that contains the distribution options. section : str Name of the section in the configuration file. variable_args : str The names of the parameters for this distribution, separated by `prior.VARARGS_DELIM`. These must appear in the "tag" part of the section header. Returns ------- Gaussain A distribution instance from the pycbc.inference.prior module.
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><DEDENT>return arr<EOL>
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 parameter. Returns ------- structured array The random values in a numpy structured array.
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:1>])<EOL>arr[p] = <NUM_LIT>**(numpy.random.uniform(log_low, log_high, size=size))<EOL><DEDENT>return arr<EOL>
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 random values for each parameter. Returns ------- structured array The random values in a numpy structured array. If a param was specified, the array will only have an element corresponding to the given parameter. Otherwise, the array will have an element for each parameter in self's params.
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} The radial amplitude.
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} The azimuthal angle.
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 ------- theta : {numpy.array, float} The polar angle.
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. Returns ------- rho : {numpy.array, float} The radial amplitude. phi : {numpy.array, float} The azimuthal angle. theta : {numpy.array, float} The polar angle.
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} The polar angle. Returns ------- x : {numpy.array, float} X-coordinate. y : {numpy.array, float} Y-coordinate. z : {numpy.array, float} Z-coordinate.
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 token in getoutput("<STR_LIT>" % '<STR_LIT:U+0020>'.join(pkg_libraries)).split():<EOL><INDENT>if token.startswith("<STR_LIT>"):<EOL><INDENT>libraries.append(token[<NUM_LIT:2>:])<EOL><DEDENT>elif token.startswith("<STR_LIT>"):<EOL><INDENT>library_dirs.append(token[<NUM_LIT:2>:])<EOL><DEDENT>elif token.startswith("<STR_LIT>"):<EOL><INDENT>include_dirs.append(token[<NUM_LIT:2>:])<EOL><DEDENT><DEDENT><DEDENT>return libraries, library_dirs, include_dirs<EOL>
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