
    קgY(                        d Z ddlZddlmZmZ g dZ G d d          Z e            Z e            Ze	                    ej
                  e	                    ej
                  d                         Ze	                    ej                  d             Ze	                    ej                  d	             Ze	                    ej                  e	                    ej                  e	                    ej                  e	                    ej                  d
                                                 Ze	                    ej                  e	                    ej                  e	                    ej                  e	                    ej                  d                                                 Ze	                    ej                  e	                    ej                  d                         Ze	                    ej                  e	                    ej                  e	                    ej                  e	                    ej                  d                                                 Ze	                    ej                  d             Ze	                    ej                  d             Ze	                    ej                  d             Ze	                    ej                  e	                    ej                   d                         Z!e	                    ej"                  e	                    ej"                  d                         Z#e	                    ej$                  d             Z%e	                    ej$                  d             Z&e	                    ej'                  d             Z(e	                    ej'                  d             Z)dS )aF  
PyTorch provides two global :class:`ConstraintRegistry` objects that link
:class:`~torch.distributions.constraints.Constraint` objects to
:class:`~torch.distributions.transforms.Transform` objects. These objects both
input constraints and return transforms, but they have different guarantees on
bijectivity.

1. ``biject_to(constraint)`` looks up a bijective
   :class:`~torch.distributions.transforms.Transform` from ``constraints.real``
   to the given ``constraint``. The returned transform is guaranteed to have
   ``.bijective = True`` and should implement ``.log_abs_det_jacobian()``.
2. ``transform_to(constraint)`` looks up a not-necessarily bijective
   :class:`~torch.distributions.transforms.Transform` from ``constraints.real``
   to the given ``constraint``. The returned transform is not guaranteed to
   implement ``.log_abs_det_jacobian()``.

The ``transform_to()`` registry is useful for performing unconstrained
optimization on constrained parameters of probability distributions, which are
indicated by each distribution's ``.arg_constraints`` dict. These transforms often
overparameterize a space in order to avoid rotation; they are thus more
suitable for coordinate-wise optimization algorithms like Adam::

    loc = torch.zeros(100, requires_grad=True)
    unconstrained = torch.zeros(100, requires_grad=True)
    scale = transform_to(Normal.arg_constraints['scale'])(unconstrained)
    loss = -Normal(loc, scale).log_prob(data).sum()

The ``biject_to()`` registry is useful for Hamiltonian Monte Carlo, where
samples from a probability distribution with constrained ``.support`` are
propagated in an unconstrained space, and algorithms are typically rotation
invariant.::

    dist = Exponential(rate)
    unconstrained = torch.zeros(100, requires_grad=True)
    sample = biject_to(dist.support)(unconstrained)
    potential_energy = -dist.log_prob(sample).sum()

.. note::

    An example where ``transform_to`` and ``biject_to`` differ is
    ``constraints.simplex``: ``transform_to(constraints.simplex)`` returns a
    :class:`~torch.distributions.transforms.SoftmaxTransform` that simply
    exponentiates and normalizes its inputs; this is a cheap and mostly
    coordinate-wise operation appropriate for algorithms like SVI. In
    contrast, ``biject_to(constraints.simplex)`` returns a
    :class:`~torch.distributions.transforms.StickBreakingTransform` that
    bijects its input down to a one-fewer-dimensional space; this a more
    expensive less numerically stable transform but is needed for algorithms
    like HMC.

The ``biject_to`` and ``transform_to`` objects can be extended by user-defined
constraints and transforms using their ``.register()`` method either as a
function on singleton constraints::

    transform_to.register(my_constraint, my_transform)

or as a decorator on parameterized constraints::

    @transform_to.register(MyConstraintClass)
    def my_factory(constraint):
        assert isinstance(constraint, MyConstraintClass)
        return MyTransform(constraint.param1, constraint.param2)

You can create your own registry by creating a new :class:`ConstraintRegistry`
object.
    N)constraints
transforms)ConstraintRegistry	biject_totransform_toc                   0     e Zd ZdZ fdZddZd Z xZS )r   z5
    Registry to link constraints to transforms.
    c                 V    i | _         t                                                       d S N)	_registrysuper__init__)self	__class__s    c/var/www/html/ai-engine/env/lib/python3.11/site-packages/torch/distributions/constraint_registry.pyr   zConstraintRegistry.__init__V   s&        Nc                     | fdS t          t          j                  rt                    t          t                    rt	          t          j                  st          d           | j        <   |S )a  
        Registers a :class:`~torch.distributions.constraints.Constraint`
        subclass in this registry. Usage::

            @my_registry.register(MyConstraintClass)
            def construct_transform(constraint):
                assert isinstance(constraint, MyConstraint)
                return MyTransform(constraint.arg_constraints)

        Args:
            constraint (subclass of :class:`~torch.distributions.constraints.Constraint`):
                A subclass of :class:`~torch.distributions.constraints.Constraint`, or
                a singleton object of the desired class.
            factory (Callable): A callable that inputs a constraint object and returns
                a  :class:`~torch.distributions.transforms.Transform` object.
        Nc                 0                         |           S r
   )register)factory
constraintr   s    r   <lambda>z-ConstraintRegistry.register.<locals>.<lambda>m   s    4==W#E#E r   zLExpected constraint to be either a Constraint subclass or instance, but got )
isinstancer   
Constrainttype
issubclass	TypeErrorr   r   r   r   s   `` r   r   zConstraintRegistry.registerZ   s    $ ?EEEEEE j+"899 	*j))J*d++ 	:.4
 4
 	 k_ikk   &-z"r   c                     	 | j         t          |                   }n4# t          $ r' t          dt          |          j         d          dw xY w ||          S )aq  
        Looks up a transform to constrained space, given a constraint object.
        Usage::

            constraint = Normal.arg_constraints['scale']
            scale = transform_to(constraint)(torch.zeros(1))  # constrained
            u = transform_to(constraint).inv(scale)           # unconstrained

        Args:
            constraint (:class:`~torch.distributions.constraints.Constraint`):
                A constraint object.

        Returns:
            A :class:`~torch.distributions.transforms.Transform` object.

        Raises:
            `NotImplementedError` if no transform has been registered.
        zCannot transform z constraintsN)r   r   KeyErrorNotImplementedError__name__r   s      r   __call__zConstraintRegistry.__call__}   sx    (	nT*%5%56GG 	 	 	%KD$4$4$=KKK 	 wz"""s	    1Ar
   )r!   
__module____qualname____doc__r   r   r"   __classcell__)r   s   @r   r   r   Q   sf             ! ! ! !F# # # # # # #r   r   c                     t           j        S r
   )r   identity_transformr   s    r   _transform_to_realr*      s     ((r   c                 ^    t          | j                  }t          j        || j                  S r
   )r   base_constraintr   IndependentTransformreinterpreted_batch_ndimsr   base_transforms     r   _biject_to_independentr1      s/    z9::N*
<  r   c                 ^    t          | j                  }t          j        || j                  S r
   )r   r,   r   r-   r.   r/   s     r   _transform_to_independentr3      s/    !*"<==N*
<  r   c                 (    t          j                    S r
   )r   ExpTransformr)   s    r   _transform_to_positiver6      s    
 "$$$r   c                     t          j        t          j                    t          j        | j        d          g          S )N   )r   ComposeTransformr5   AffineTransformlower_boundr)   s    r   _transform_to_greater_thanr<      s=    
 &#%%&z'=qAA	
  r   c                     t          j        t          j                    t          j        | j        d          g          S )N)r   r9   r5   r:   upper_boundr)   s    r   _transform_to_less_thanr@      s=     &#%%&z'=rBB	
  r   c                 x   t          | j        t          j                  o
| j        dk    }t          | j        t          j                  o
| j        dk    }|r|rt          j                    S | j        }| j        | j        z
  }t          j        t          j                    t          j        ||          g          S )Nr   r8   )	r   r;   numbersNumberr?   r   SigmoidTransformr9   r:   )r   
lower_is_0
upper_is_1locscales        r   _transform_to_intervalrI      s     	:)7>:: 	("a' 
 	:)7>:: 	("a'   -j -*,,,

 C"Z%;;E&		$	&	&
(B3(N(NO  r   c                 (    t          j                    S r
   )r   StickBreakingTransformr)   s    r   _biject_to_simplexrL          ,...r   c                 (    t          j                    S r
   )r   SoftmaxTransformr)   s    r   _transform_to_simplexrP      s    &(((r   c                 (    t          j                    S r
   )r   LowerCholeskyTransformr)   s    r   _transform_to_lower_choleskyrS      rM   r   c                 (    t          j                    S r
   )r   PositiveDefiniteTransformr)   s    r   _transform_to_positive_definiterV     s     /111r   c                 (    t          j                    S r
   )r   CorrCholeskyTransformr)   s    r   _transform_to_corr_choleskyrY     s     +---r   c                 `    t          j        d | j        D             | j        | j                  S )Nc                 ,    g | ]}t          |          S  r   .0cs     r   
<listcomp>z"_biject_to_cat.<locals>.<listcomp>      ///!1///r   r   CatTransformcseqdimlengthsr)   s    r   _biject_to_catrh     s3    "//z///AS  r   c                 `    t          j        d | j        D             | j        | j                  S )Nc                 ,    g | ]}t          |          S r\   r   r^   s     r   ra   z%_transform_to_cat.<locals>.<listcomp>      222Qa222r   rc   r)   s    r   _transform_to_catrm     s3    "22*/222JNJDV  r   c                 T    t          j        d | j        D             | j                  S )Nc                 ,    g | ]}t          |          S r\   r]   r^   s     r   ra   z$_biject_to_stack.<locals>.<listcomp>  rb   r   r   StackTransformre   rf   r)   s    r   _biject_to_stackrr     s.    $//z///  r   c                 T    t          j        d | j        D             | j                  S )Nc                 ,    g | ]}t          |          S r\   rk   r^   s     r   ra   z'_transform_to_stack.<locals>.<listcomp>%  rl   r   rp   r)   s    r   _transform_to_stackru   "  s.    $22*/222JN  r   )*r%   rB   torch.distributionsr   r   __all__r   r   r   r   realr*   independentr1   r3   positivenonnegativer6   greater_thangreater_than_eqr<   	less_thanr@   intervalhalf_open_intervalrI   simplexrL   rP   lower_choleskyrS   positive_definitepositive_semidefiniterV   corr_choleskyrY   catrh   rm   stackrr   ru   r\   r   r   <module>r      s  A AF  7 7 7 7 7 7 7 7  F# F# F# F# F# F# F# F#R   	!!## K$%%{'(() ) )( &%) K+,,  -, {.//  0/ K())
K+,,{+,,{.//% % 0/ -, -, *)% K,--
K/00{/00{233  43 10 10 .- K)**{,--  .- +* K())
K233{+,,{566  76 -, 43 *)( K'((/ / )(/ {*++) ) ,+)
 {122/ / 32/ {455{8992 2 :9 652 K-..{011. . 21 /.. KO$$  %$ {''  (' K%&&  '& {())  *)  r   