Exemplo n.º 1
0
    def set_spoints_grid(self, values: Dict[str, Iterable[float]]) -> None:
        """Set a grid of points in sampling space.

        Args:
            values: A dictionary of the following form:

                .. code-block:: python

                    {
                        <coeff name>: [
                            value_1,
                            ...,
                            value_n
                        ]
                    }

                where ``value_1``, ..., ``value_n`` can be complex numbers in
                general.
        """

        # IMPORTANT to keep this order!
        self._coeffs = sorted(list(values.keys()))

        # Now we collect all lists of values.
        values_lists = [values[coeff] for coeff in self._coeffs]
        # Now we build the cartesian product, i.e.
        # [a1, a2, ...] x [b1, b2, ...] x ... x [z1, z2, ...] =
        # [(a1, b1, ..., z1), ..., (a2, b2, ..., z2)]
        self._spoints = np.array(list(itertools.product(*values_lists)))

        self.md["spoints"]["grid"] = failsafe_serialize(values)
Exemplo n.º 2
0
    def set_kmeans_options(self, **kwargs) -> None:
        """Configure clustering algorithms.

        Args:
            **kwargs: Keyword arguments to :func:`sklearn.cluster.KMeans`.
        """
        self._kmeans_kwargs = kwargs
        self.md["kmeans"]["kwargs"] = failsafe_serialize(kwargs)
Exemplo n.º 3
0
    def set_fcluster_options(self, **kwargs) -> None:
        """Set additional keyword options for our call to
        ``scipy.cluster.hierarchy.fcluster``.

        Args:
            kwargs: Keyword arguments

        Returns:
            None
        """
        # set up defaults for clustering here
        # (this way we can overwrite them with additional arguments)
        self._fcluster_kwargs = {"criterion": "distance"}
        self._fcluster_kwargs.update(kwargs)
        self.md["fcluster"]["kwargs"] = failsafe_serialize(
            self._fcluster_kwargs)
Exemplo n.º 4
0
 def test_serialize_identical(self):
     cases = [
         "test",
         3,
         3.123,
         {
             1: 2
         },
         [1, 2, 3],
         [{
             1: 3
         }, {
             3: 4
         }],
         [[1, 2, 3], [4, 5], "xyz"],
     ]
     for case in cases:
         self.assertEqual(metadata.failsafe_serialize(case), case)
     self.assertEqual(metadata.failsafe_serialize(cases), cases)
Exemplo n.º 5
0
 def set_metric(self, *args, **kwargs) -> None:
     self.md["metric"]["args"] = failsafe_serialize(args)
     self.md["metric"]["kwargs"] = failsafe_serialize(kwargs)
     self.metric = metric_selection(*args, **kwargs)
Exemplo n.º 6
0
    def set_dfunction(
        self,
        func: Callable,
        binning: Optional[Sized] = None,
        sampling: Optional[Sized] = None,
        normalize=False,
        xvar="xvar",
        yvar="yvar",
        **kwargs
    ):
        """Set the function that generates the distributions that are later
        clustered (e.g. a differential cross section).

        Args:
            func: A function that takes the point in parameter space
                as the first argument (**Note**: The parameters are given in
                alphabetically order with respect to the parameter name!).
                It should either return a ``float`` or a ``np.ndarray``.
                If the ``binning`` or ``sampling`` options are specified, only
                ``float`` s as return value are allowed.
            binning: If this parameter is set to an array-like object, we will
                integrate the function over the specified bins for every point
                in parameter space.
            sampling: If this parameter is set to an array-like object, we will
                apply the function to these points for every point in parameter
                space.
            normalize: If a binning is specified, normalize the resulting
                distribution.
            xvar: Name of variable on x-axis
            yvar: Name of variable on y-axis
            **kwargs: All other keyword arguments are passed to the function.

        Returns:
            None
        """
        if normalize and binning is None and sampling is None:
            raise ValueError(
                "The setting normalize=True only makes sense if a binning or "
                "sampling is specified."
            )
        if binning is not None and sampling is not None:
            raise ValueError("Please specify EITHER sampling OR binning.")

        # The block below just wants to put some information about the function
        # in the metadata. Can be ignored if you're only interested in what's
        # happening.
        md = self.md["dfunction"]
        try:
            md["name"] = func.__name__
            md["doc"] = func.__doc__
        except AttributeError:
            try:
                # For functools.partial objects
                # noinspection PyUnresolvedReferences
                md["name"] = "functools.partial({})".format(func.func.__name__)
                # noinspection PyUnresolvedReferences
                md["doc"] = func.func.__doc__
            except AttributeError:
                pass

        md["kwargs"] = failsafe_serialize(kwargs)

        md["binning"] = binning

        # This is the important thing: We set all required attributes of the
        # spoint calculator!
        self._spoint_calculator.func = func
        if binning is not None:
            self._spoint_calculator.binning = binning
            self._spoint_calculator.binning_mode = "integrate"
            md["binning"] = list(binning)
            md["binning_mode"] = "integrate"
            md["nbins"] = len(binning) - 1
        elif sampling is not None:
            self._spoint_calculator.binning = sampling
            md["binning"] = list(sampling)
            self._spoint_calculator.binning_mode = "sample"
            md["binning_mode"] = "sample"
            md["nbins"] = len(sampling)

        md["xvar"] = xvar
        md["yvar"] = yvar

        self._spoint_calculator.normalize = normalize
        self._spoint_calculator.kwargs = kwargs