L ibTddlmZmZmZ ddlZgdZGddZGddeZdZGd d e eZ Gd d eZ Gd deZ GddeZ GddeZGddeZGddeZGddeZGddeZGddeZGddeZGdd eZGd!d"eZGd#d$eZGd%d&eZGd'd(eZGd)d*eZGd+d,eZGd-d.eZGd/d0eZGd1d2eZGd3d4eZGd5d6eZ Gd7d8eZ!Gd9d:eZ"eZ#e Z$e Z%e Z&eZ'edZ(ed;Z)eZ*eZ+e%e+d;Z,ed<Z-ed<Z.eZ/eZ0eZ1eZ2ede"Z?y)>)AnyCallableOptionalN) Constraintbooleancat corr_cholesky dependentdependent_property greater_thangreater_than_eq independentinteger_intervalintervalhalf_open_interval is_dependent less_thanlower_choleskylower_triangularMixtureSameFamilyConstraint multinomial nonnegativenonnegative_integerone_hotpositivepositive_semidefinitepositive_definitepositive_integerreal real_vectorsimplexsquarestack symmetric unit_intervalc$eZdZdZdZdZdZdZy)ra Abstract base class for constraints. A constraint object represents a region over which a variable is valid, e.g. within which a variable can be optimized. Attributes: is_discrete (bool): Whether constrained space is discrete. Defaults to False. event_dim (int): Number of rightmost dimensions that together define an event. The :meth:`check` method will remove this many dimensions when computing validity. Frct)z Returns a byte tensor of ``sample_shape + batch_shape`` indicating whether each event in value satisfies this constraint. )NotImplementedErrorselfvalues e/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/torch/distributions/constraints.pycheckzConstraint.checkas "!c:|jjdddzS)Nz()) __class____name__r*s r,__repr__zConstraint.__repr__hs~~&&qr*T11r.N)r2 __module__ __qualname____doc__ is_discrete event_dimr-r4r.r,rrOs KI"2r.rcjeZdZdZeedfd ZedefdZede fdZ eeddZ dZ xZ S) _DependentaI Placeholder for variables whose support depends on other variables. These variables obey no simple coordinate-wise constraints. Args: is_discrete (bool): Optional value of ``.is_discrete`` in case this can be computed statically. If not provided, access to the ``.is_discrete`` attribute will raise a NotImplementedError. event_dim (int): Optional value of ``.event_dim`` in case this can be computed statically. If not provided, access to the ``.event_dim`` attribute will raise a NotImplementedError. r8r9c>||_||_t| yN) _is_discrete _event_dimsuper__init__)r*r8r9r1s r,rCz_Dependent.__init__zs'# r.returncT|jtur td|jS)Nz,.is_discrete cannot be determined statically)r@NotImplementedr(r3s r,r8z_Dependent.is_discretes(    .%&TU U   r.cT|jtur td|jS)Nz*.event_dim cannot be determined statically)rArFr(r3s r,r9z_Dependent.event_dims$ ??n ,%&RS Sr.cl|tur |j}|tur |j}t||S)z Support for syntax to customize static attributes:: constraints.dependent(is_discrete=True, event_dim=1) r=)rFr@rAr<)r*r8r9s r,__call__z_Dependent.__call__s5 . (++K  &IkYGGr.ctd)Nz1Cannot determine validity of dependent constraint) ValueErrorr*xs r,r-z_Dependent.checksLMMr.)r2r5r6r7rFrCpropertyboolr8intr9rIr- __classcell__r1s@r,r<r<ls] '5 !T!! 3 '5 HNr.r<c"t|tS)a Checks if ``constraint`` is a ``_Dependent`` object. Args: constraint : A ``Constraint`` object. Returns: ``bool``: True if ``constraint`` can be refined to the type ``_Dependent``, False otherwise. Examples: >>> import torch >>> from torch.distributions import Bernoulli >>> from torch.distributions.constraints import is_dependent >>> dist = Bernoulli(probs=torch.tensor([0.6], requires_grad=True)) >>> constraint1 = dist.arg_constraints["probs"] >>> constraint2 = dist.arg_constraints["logits"] >>> for constraint in [constraint1, constraint2]: >>> if is_dependent(constraint): >>> continue ) isinstancer<) constraints r,rrs. j* --r.c veZdZdZ d eeddeedefdeedee ddffd Z dedefddfd Z xZ S) _DependentPropertya Decorator that extends @property to act like a `Dependent` constraint when called on a class and act like a property when called on an object. Example:: class Uniform(Distribution): def __init__(self, low, high): self.low = low self.high = high @constraints.dependent_property(is_discrete=False, event_dim=0) def support(self): return constraints.interval(self.low, self.high) Args: fn (Callable): The function to be decorated. is_discrete (bool): Optional value of ``.is_discrete`` in case this can be computed statically. If not provided, access to the ``.is_discrete`` attribute will raise a NotImplementedError. event_dim (int): Optional value of ``.event_dim`` in case this can be computed statically. If not provided, access to the ``.event_dim`` attribute will raise a NotImplementedError. Nr=fn.r8r9rDc@t||||_||_yr?)rBrCr@rA)r*rXr8r9r1s r,rCz_DependentProperty.__init__s! '#r.cFt||j|jS)z Support for syntax to customize static attributes:: @constraints.dependent_property(is_discrete=True, event_dim=1) def support(self): ... r=)rWr@rA)r*rXs r,rIz_DependentProperty.__call__s"" D--  r.r?) r2r5r6r7rFrrrrOrPrCrIrQrRs@r,rWrWsx6,0 $'5#1 $ Xc3h' ( $d^ $ C= $  $  8CH-  2F  r.rWcZeZdZdZfdZedefdZedefdZ dZ dZ xZ S)_IndependentConstraintz Wraps a constraint by aggregating over ``reinterpreted_batch_ndims``-many dims in :meth:`check`, so that an event is valid only if all its independent entries are valid. ct|tsJt|tsJ|dk\sJ||_||_t |yNr)rTrrPbase_constraintreinterpreted_batch_ndimsrBrC)r*r_r`r1s r,rCz_IndependentConstraint.__init__sM/:6663S999(A---.)B& r.rDc.|jjSr?r_r8r3s r,r8z"_IndependentConstraint.is_discrete##///r.cH|jj|jzSr?)r_r9r`r3s r,r9z _IndependentConstraint.event_dims##--0N0NNNr.c|jj|}|j|jkrB|jj|jz}t d|d|j|j |jd|j|jz dz}|jd}|S)NExpected value.dim() >= but got ri) r_r-dimr`r9rKreshapeshapeall)r*r+resultexpecteds r,r-z_IndependentConstraint.checks%%++E2 ::<$88 8++558V8VVH*8*Ieiik]K  LLH6::<$*H*HH IE Q B r.c|jjdddt|jd|jdS)Nr0(z, ))r1r2reprr_r`r3s r,r4z_IndependentConstraint.__repr__ sA..))!"-.aT5I5I0J/K2dNlNlMmmnoor. r2r5r6r7rCrNrOr8rPr9r-r4rQrRs@r,r\r\sQ 0T00O3OO pr.r\cZeZdZdZfdZedefdZedefdZ dZ dZ xZ S)ra Constraint for the :class:`~torch.distribution.MixtureSameFamily` distribution that adds back the rightmost batch dimension before performing the validity check with the component distribution constraint. Args: base_constraint: The ``Constraint`` object of the component distribution of the :class:`~torch.distribution.MixtureSameFamily` distribution. cTt|tsJ||_t|yr?)rTrr_rBrC)r*r_r1s r,rCz$MixtureSameFamilyConstraint.__init__s&/:666. r.rDc.|jjSr?rbr3s r,r8z'MixtureSameFamilyConstraint.is_discrete rcr.c.|jjSr?)r_r9r3s r,r9z%MixtureSameFamilyConstraint.event_dim$s##---r.c|jd|jz }|jj|}|j |jkr)t d|jd|j |j |jz }|j |jd|dz}|jd}|S)z Check validity of ``value`` as a possible outcome of sampling the :class:`~torch.distribution.MixtureSameFamily` distribution. rirfrgNrh) unsqueezer9r_r-rjrKrkrlrm)r*r+unsqueezed_valuernnum_dim_to_keeps r,r-z!MixtureSameFamilyConstraint.check(s !??2+>?%%++,<= 99; '*4>>*:)EIIK=Q  ))+6 -=o > FGB r.c`|jjdt|jdS)Nrqrr)r1r2rsr_r3s r,r4z$MixtureSameFamilyConstraint.__repr__8s,..))*!D1E1E,F+GqIIr.rtrRs@r,rrsN  0T00.3.. Jr.rceZdZdZdZdZy)_Booleanz/ Constrain to the two values `{0, 1}`. Tc|dk(|dk(zS)Nrr0r:r)s r,r-z_Boolean.checkCs uz**r.N)r2r5r6r7r8r-r:r.r,rr<sK+r.rceZdZdZdZdZdZy)_OneHotz' Constrain to one-hot vectors. Tr0c|dk(|dk(z}|jdjd}|jd|zS)Nrr0ri)sumeqrm)r*r+ is_boolean is_normalizeds r,r-z _OneHot.checkOs@qjUaZ0  " ((+ ~~b!M11r.N)r2r5r6r7r8r9r-r:r.r,rrGsKI2r.rc2eZdZdZdZfdZdZdZxZS)_IntegerIntervalzH Constrain to an integer interval `[lower_bound, upper_bound]`. Tc>||_||_t| yr? lower_bound upper_boundrBrCr*rrr1s r,rCz_IntegerInterval.__init__\&& r.cR|dzdk(|j|kz||jkzSNr0rrrr)s r,r-z_IntegerInterval.checkas2 QY!^ 0 0E 9 :etGWGW>W X r.cx|jjdd}|d|jd|jdz }|SNr0 (lower_bound=z, upper_bound=rrr1r2rrr* fmt_strings r,r4z_IntegerInterval.__repr__fJ^^,,QR0 D,,-^Dr.rc2eZdZdZdZfdZdZdZxZS)_IntegerGreaterThanz@ Constrain to an integer interval `[lower_bound, inf)`. Tc0||_t| yr?rrBrCr*rr1s r,rCz_IntegerGreaterThan.__init__rr.c2|dzdk(||jk\zSrrr)s r,r-z_IntegerGreaterThan.checkrr.c^|jjdd}|d|jdz }|SNr0rrrr1r2rrs r,r4z_IntegerGreaterThan.__repr__rr.rrRs@r,rrrr.rceZdZdZdZy)_RealzF Trivially constrain to the extended real line `[-inf, inf]`. c ||k(Sr?r:r)s r,r-z _Real.checks ~r.N)r2r5r6r7r-r:r.r,rrs r.rc.eZdZdZfdZdZdZxZS) _GreaterThanz= Constrain to a real half line `(lower_bound, inf]`. c0||_t| yr?rrs r,rCz_GreaterThan.__init__rr.c |j|kSr?rr)s r,r-z_GreaterThan.checks%''r.c^|jjdd}|d|jdz }|Srrrs r,r4z_GreaterThan.__repr__rr.r2r5r6r7rCr-r4rQrRs@r,rr(r.rc.eZdZdZfdZdZdZxZS)_GreaterThanEqz= Constrain to a real half line `[lower_bound, inf)`. c0||_t| yr?rrs r,rCz_GreaterThanEq.__init__rr.c |j|kSr?rr)s r,r-z_GreaterThanEq.checks5((r.c^|jjdd}|d|jdz }|Srrrs r,r4z_GreaterThanEq.__repr__rr.rrRs@r,rrs)r.rc.eZdZdZfdZdZdZxZS) _LessThanz> Constrain to a real half line `[-inf, upper_bound)`. c0||_t| yr?rrs r,rCz_LessThan.__init__rr.c ||jkSr?rr)s r,r-z_LessThan.checkst''''r.c^|jjdd}|d|jdz }|Srrrs r,r4z_LessThan.__repr__rr.rrRs@r,rrrr.rc.eZdZdZfdZdZdZxZS) _IntervalzD Constrain to a real interval `[lower_bound, upper_bound]`. c>||_||_t| yr?rrs r,rCz_Interval.__init__rr.c@|j|k||jkzSr?rr)s r,r-z_Interval.checks#  E)et7G7G.GHHr.cx|jjdd}|d|jd|jdz }|Srrrs r,r4z_Interval.__repr__rr.rrRs@r,rrs Ir.rc.eZdZdZfdZdZdZxZS)_HalfOpenIntervalzD Constrain to a real interval `[lower_bound, upper_bound)`. c>||_||_t| yr?rrs r,rCz_HalfOpenInterval.__init__rr.c@|j|k||jkzSr?rr)s r,r-z_HalfOpenInterval.checks#  E)ed6F6F.FGGr.cx|jjdd}|d|jd|jdz }|Srrrs r,r4z_HalfOpenInterval.__repr__rr.rrRs@r,rrs Hr.rceZdZdZdZdZy)_Simplexz Constrain to the unit simplex in the innermost (rightmost) dimension. Specifically: `x >= 0` and `x.sum(-1) == 1`. r0ctj|dk\d|jddz jdkzS)Nrrirjr0ư>)torchrmrabsr)s r,r-z_Simplex.checks7yy!,21B0G0G0ID0PQQr.Nr2r5r6r7r9r-r:r.r,rrs IRr.rc$eZdZdZdZdZdZdZy) _Multinomiala3 Constrain to nonnegative integer values summing to at most an upper bound. Note due to limitations of the Multinomial distribution, this currently checks the weaker condition ``value.sum(-1) <= upper_bound``. In the future this may be strengthened to ``value.sum(-1) == upper_bound``. Tr0c||_yr?r)r*rs r,rCz_Multinomial.__init__s &r.cl|dk\jd|jd|jkzS)Nrrir)rmrrrLs r,r-z_Multinomial.checks1Q|||#quuu}8H8H'HIIr.N)r2r5r6r7r8r9rCr-r:r.r,rr sKI'Jr.rceZdZdZdZdZy)_LowerTriangularz8 Constrain to lower-triangular square matrices. c|j}||k(j|jdddzjddS)Nrhrir)trilviewrlmin)r*r+ value_trils r,r-z_LowerTriangular.check%sCZZ\ e#))%++cr*:U*BCGGKANNr.Nrr:r.r,rrsIOr.rceZdZdZdZdZy)_LowerCholeskyzP Constrain to lower-triangular square matrices with positive diagonals. rc|j}||k(j|jdddzjdd}|j dddkDjdd}||zS)Nrrhrir)dim1dim2)rrrlrdiagonal)r*r+rrpositive_diagonals r,r-z_LowerCholesky.check1s{ZZ\ 5 & &u{{3B'7%'? @ D DR H K #^^"^=AFFrJ1M"333r.Nrr:r.r,rr*sI4r.rceZdZdZdZdZy) _CorrCholeskyz} Constrain to lower-triangular square matrices with positive diagonals and each row vector being of unit length. rcxtj|jj|j dzdz}tj j |jd}|dz jj|jd}tj||zS)Nri r?) rfinfodtypeepssizelinalgnormdetachrlermrr-)r*r+tolrow_norm unit_row_norms r,r-z_CorrCholesky.checkCs KK $ ( (5::b> 9B > <<$$U\\^$<!C,,.11#6::r:B %%e,}<z _Cat.__init__..;:a,;r0)rmlistcseqlenlengthsrjrBrC)r*r$rjr&r1s r,rCz _Cat.__init__sw;d;;;;J ?cC N*GG} 4<< C N222 r.rDc:td|jDS)Nc34K|]}|jywr?r8rs r,r z#_Cat.is_discrete..4Q1==4anyr$r3s r,r8z_Cat.is_discrete4$))444r.c:td|jDS)Nc34K|]}|jywr?r9rs r,r z!_Cat.event_dim..s211;;2r+)maxr$r3s r,r9z_Cat.event_dims2 222r.c|j |jcxkr|jksJJg}d}t|j|jD]G\}}|j |j||}|j |j |||z}Itj||jSr^) rjzipr$r&narrowappendr-rr)r*r+checksstartconstrlengthvs r,r-z _Cat.checks |txx5%))+55555!$))T\\: #NFF TXXuf5A MM&,,q/ *FNE #yy**r.)rN r2r5r6r7rCrNrOr8rPr9r-rQrRs@r,rrsH 5T553333+r.rcVeZdZdZdfd ZedefdZedefdZ dZ xZ S)_Stackz Constraint functor that applies a sequence of constraints `cseq` at the submatrices at dimension `dim`, in a way compatible with :func:`torch.stack`. cxtd|DsJt||_||_t|y)Nc3<K|]}t|tywr?rrs r,r z"_Stack.__init__..r!r")rmr#r$rjrBrC)r*r$rjr1s r,rCz_Stack.__init__s4;d;;;;J  r.rDc:td|jDS)Nc34K|]}|jywr?r)rs r,r z%_Stack.is_discrete..r*r+r,r3s r,r8z_Stack.is_discreter.r.cltd|jD}|j|zdkr|dz }|S)Nc34K|]}|jywr?r1rs r,r z#_Stack.event_dim..s1!!++1r+rr0)r2r$rj)r*rjs r,r9z_Stack.event_dims41tyy11 88c>A  1HC r.c |j |jcxkr|jksJJt|j|jDcgc]}|j|j| }}t j t ||jDcgc]\}}|j|c}}|jScc}wcc}}wr?) rjrangerselectrr#r4r$r-)r*r+ivsr;r9s r,r-z _Stack.checks |txx5%))+5555516uzz$((7K1L MAell488Q' M M{{.1"dii.@ AFV\\!_ A488  N As #C+C )rr<rRs@r,r>r>sH  5T553  r.r>r0gr)@typingrrrr__all__rr<rrNrWr\rrrrrrrrrrrrrrrrrrrr rrr>r r rrrrrrrr rrr r rrr%rrr!rrr r"r$rrrr#r:r.r,rLsV+* D ! H22:,N,N^.4. :. b%pZ%pP+J*+J\+z+ 2j 2z2z(*(J:$Z$ $ * * Rz RJ:J& Oz O4Z4"=J="  j  I I :J : : :!+:!+H Z B L '$ * ))!,&q)# w$"  S!      #s# & *#%!  L -/%' r.