• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# mypy: allow-untyped-defs
2import math
3
4import torch
5from torch import inf
6from torch.distributions import constraints
7from torch.distributions.cauchy import Cauchy
8from torch.distributions.transformed_distribution import TransformedDistribution
9from torch.distributions.transforms import AbsTransform
10
11
12__all__ = ["HalfCauchy"]
13
14
15class HalfCauchy(TransformedDistribution):
16    r"""
17    Creates a half-Cauchy distribution parameterized by `scale` where::
18
19        X ~ Cauchy(0, scale)
20        Y = |X| ~ HalfCauchy(scale)
21
22    Example::
23
24        >>> # xdoctest: +IGNORE_WANT("non-deterministic")
25        >>> m = HalfCauchy(torch.tensor([1.0]))
26        >>> m.sample()  # half-cauchy distributed with scale=1
27        tensor([ 2.3214])
28
29    Args:
30        scale (float or Tensor): scale of the full Cauchy distribution
31    """
32    arg_constraints = {"scale": constraints.positive}
33    support = constraints.nonnegative
34    has_rsample = True
35
36    def __init__(self, scale, validate_args=None):
37        base_dist = Cauchy(0, scale, validate_args=False)
38        super().__init__(base_dist, AbsTransform(), validate_args=validate_args)
39
40    def expand(self, batch_shape, _instance=None):
41        new = self._get_checked_instance(HalfCauchy, _instance)
42        return super().expand(batch_shape, _instance=new)
43
44    @property
45    def scale(self):
46        return self.base_dist.scale
47
48    @property
49    def mean(self):
50        return torch.full(
51            self._extended_shape(),
52            math.inf,
53            dtype=self.scale.dtype,
54            device=self.scale.device,
55        )
56
57    @property
58    def mode(self):
59        return torch.zeros_like(self.scale)
60
61    @property
62    def variance(self):
63        return self.base_dist.variance
64
65    def log_prob(self, value):
66        if self._validate_args:
67            self._validate_sample(value)
68        value = torch.as_tensor(
69            value, dtype=self.base_dist.scale.dtype, device=self.base_dist.scale.device
70        )
71        log_prob = self.base_dist.log_prob(value) + math.log(2)
72        log_prob = torch.where(value >= 0, log_prob, -inf)
73        return log_prob
74
75    def cdf(self, value):
76        if self._validate_args:
77            self._validate_sample(value)
78        return 2 * self.base_dist.cdf(value) - 1
79
80    def icdf(self, prob):
81        return self.base_dist.icdf((prob + 1) / 2)
82
83    def entropy(self):
84        return self.base_dist.entropy() - math.log(2)
85