Beispiel #1
0
    def from_yaml_dict(cls, data, pname='parameters', instance=None, *args, **kwargs):
        """Class method: load constraint from a dictionary or list of dicts.

        If it is a dictionary, it should have the form:

        ```{
        'metadata': {...},  # optional, do set attributes of the instance
        'arguments': {...},  # optional, to specify keyword arguments for instantiation,
        'constraints': [...],  # required, the list of constraints
        }

        Alternatively, the list of constraints can be directly given.
        This list should have elements in one of the two possible forms:

        1. Dictionary as returned by `Probability.get_dict`:
        ```{
        pname: [...],  # required, list of constrained parameters
        'values': {
            'distribution': '...',  # required, string identifying ProbabilityDistribution, e.g. 'normal'
            '...': '...',  # required, any arguments for the instantiation of the ProbabilityDistribution
            }
        }
        ```

        2. String representing one or several (to be convolved) constraints:
        ```{
        'my_parameter': '1.0 ± 0.2 ± 0.1 e-3'
        }
        """
        if isinstance(data, dict):
            constraints = data['constraints']
            meta = data.get('metadata', {})
            arguments = data['arguments']
            kwargs.update(arguments)
            inst = instance or cls(*args, **kwargs)
            for m in meta:
                inst.__dict__[m] = meta[m]
        else:
            inst = instance or cls(*args, **kwargs)
            constraints = data.copy()
        for c in constraints:
            if pname not in c:
                if 'values' not in c and len(c) == 1:
                    # this means we probably have a constraint of the
                    # form parameter: constraint_string
                    for k, v in c.items():  # this loop runs only once
                        inst.set_constraint(k, v)
                        break  # just to be sure
                    continue
                else:
                    # in this case something is clearly wrong. Mabye the
                    # wrong "pname" was used.
                    raise ValueError('Key ' + pname + ' not found. '
                                     'Please check the `pname` argument.')
            else:
                parameters = [tuple(p) if isinstance(p, list) else p for p in c[pname]]
                pds = dict2dist(c['values'])
                combined_pd = convolve_distributions(pds)
                inst.add_constraint(parameters, combined_pd)
        return inst
Beispiel #2
0
    def set_constraint(self, parameter, constraint_string=None,
                                        constraint_dict=None):
        r"""Set the constraint on a parameter/observable by specifying a string
        or a dictionary. If several constraints (e.g. several types of
        uncertainty) are given, the total constraint will be the convolution
        of the individual distributions. Existing constraints will be removed.

        Arguments:

        - parameter: parameter string (or tuple)
        - constraint_string: string specifying the constraint that can be e.g.
          of the form `'1.55(3)(1)'` or `'4.0±0.1'`.
        - constraint_dict: dictionary or list of several dictionaries of the
          form `{'distribution': 'distribution_name', 'arg1': val1, ...}`, where
          'distribution_name' is a string name associated to each probability
          distribution (see `flavio.statistics.probability.class_from_string`)
          and `'arg1'`, `val1` are argument/value pairs of the arguments of
          the distribution class's constructor (e.g.`central_value`,
          `standard_deviation` for a normal distribution).

        `constraint_string` and `constraint_dict` must not be present
        simultaneously.
        """
        if constraint_string is not None and constraint_dict is not None:
            raise ValueError("constraint_string and constraint_dict cannot"
                             " be used at the same time.")
        if constraint_string is not None:
            pds = constraints_from_string(constraint_string)
        elif constraint_dict is not None:
            pds = dict2dist(constraint_dict)
        else:
            raise TypeError("Either constraint_string or constraint_dict have"
                            " to be specified.")
        combined_pd = convolve_distributions(pds)
        self.add_constraint([parameter], combined_pd)
Beispiel #3
0
    def from_yaml_dict(cls, data, pname='parameters', instance=None, *args, **kwargs):
        """Class method: load constraint from a dictionary or list of dicts.

        If it is a dictionary, it should have the form:

        ```{
        'metadata': {...},  # optional, do set attributes of the instance
        'arguments': {...},  # optional, to specify keyword arguments for instantiation,
        'constraints': [...],  # required, the list of constraints
        }

        Alternatively, the list of constraints can be directly given.
        This list should have elements in one of the two possible forms:

        1. Dictionary as returned by `Probability.get_dict`:
        ```{
        pname: [...],  # required, list of constrained parameters
        'values': {
            'distribution': '...',  # required, string identifying ProbabilityDistribution, e.g. 'normal'
            '...': '...',  # required, any arguments for the instantiation of the ProbabilityDistribution
            }
        }
        ```

        2. String representing one or several (to be convolved) constraints:
        ```{
        'my_parameter': '1.0 ± 0.2 ± 0.1 e-3'
        }
        """
        if isinstance(data, dict):
            constraints = data['constraints']
            meta = data.get('metadata', {})
            arguments = data['arguments']
            kwargs.update(arguments)
            inst = instance or cls(*args, **kwargs)
            for m in meta:
                inst.__dict__[m] = meta[m]
        else:
            inst = instance or cls(*args, **kwargs)
            constraints = data.copy()
        for c in constraints:
            if pname not in c:
                if 'values' not in c and len(c) == 1:
                    # this means we probably have a constraint of the
                    # form parameter: constraint_string
                    for k, v in c.items():  # this loop runs only once
                        inst.set_constraint(k, v)
                        break  # just to be sure
                    continue
                else:
                    # in this case something is clearly wrong. Mabye the
                    # wrong "pname" was used.
                    raise ValueError('Key ' + pname + ' not found. '
                                     'Please check the `pname` argument.')
            else:
                parameters = [tuple(p) if isinstance(p, list) else p for p in c[pname]]
                pds = dict2dist(c['values'])
                combined_pd = convolve_distributions(pds)
                inst.add_constraint(parameters, combined_pd)
        return inst
Beispiel #4
0
 def set_constraint(self, parameter, constraint_string):
     """Set the constraints on a parameter/observable by specifying a string
     that can be e.g. of the form 1.55(3)(1) or 4.0±0.1. Existing
     constraints will be removed."""
     pds = constraints_from_string(constraint_string)
     combined_pd = convolve_distributions(pds)
     self.add_constraint([parameter], combined_pd)
Beispiel #5
0
    def set_constraint(self, parameter, constraint_string=None,
                                        constraint_dict=None):
        r"""Set the constraint on a parameter/observable by specifying a string
        or a dictionary. If several constraints (e.g. several types of
        uncertainty) are given, the total constraint will be the convolution
        of the individual distributions. Existing constraints will be removed.

        Arguments:

        - parameter: parameter string (or tuple)
        - constraint_string: string specifying the constraint that can be e.g.
          of the form `'1.55(3)(1)'` or `'4.0±0.1'`.
        - constraint_dict: dictionary or list of several dictionaries of the
          form `{'distribution': 'distribution_name', 'arg1': val1, ...}`, where
          'distribution_name' is a string name associated to each probability
          distribution (see `flavio.statistics.probability.class_from_string`)
          and `'arg1'`, `val1` are argument/value pairs of the arguments of
          the distribution class's constructor (e.g.`central_value`,
          `standard_deviation` for a normal distribution).

        `constraint_string` and `constraint_dict` must not be present
        simultaneously.
        """
        if constraint_string is not None and constraint_dict is not None:
            raise ValueError("constraint_string and constraint_dict cannot"
                             " be used at the same time.")
        if constraint_string is not None:
            pds = constraints_from_string(constraint_string)
        elif constraint_dict is not None:
            pds = dict2dist(constraint_dict)
        else:
            raise TypeError("Either constraint_string or constraint_dict have"
                            " to be specified.")
        combined_pd = convolve_distributions(pds)
        self.add_constraint([parameter], combined_pd)