~L i0UdZddlmZddlZddlZddlmZmZmZerddl m Z m Z dZ de d<Gd d ZGd d Z dd Z ddZddZy)aAdapted from https://github.com/arogozhnikov/einops/blob/36c7bb16e57d6e57f8f3050f9e07abdf3f00469f/einops/parsing.py. MIT License Copyright (c) 2018 Alex Rogozhnikov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ) annotationsN)Optional TYPE_CHECKINGUnion) CollectionMappingu…str _ellipsisc eZdZdZddZddZy) AnonymousAxiszUsed by `ParsedExpression` to represent an axis with a size (> 1), but no associated identifier. Note: Different instances of this class are not equal to each other, even if they have the same value. crt||_|jdkrtd|jy)Nz0Anonymous axis should have positive length, not )intvalue ValueError)selfrs _/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/functorch/einops/_parsing.py__init__zAnonymousAxis.__init__.s8Z ::>B4::,O  c |jdS)Nz-axis)r)rs r__repr__zAnonymousAxis.__repr__5s**U##rN)rr returnNone)rr )__name__ __module__ __qualname____doc__rrrrr r (s $rr c`eZdZdZddd ddZe d d dZed dZy) ParsedExpressionz`Structure containing information about one side of an `einops`-style pattern (e.g. 'b c (h w)').F)allow_underscoreallow_duplicatescd_d_t_d_g_d|vrid|vr t dtj|ddk7stj|ddk7r t d|jdt}d _ddfd }d}|D]}|d vrR|||d}|d k(r t d g(|dk(s. t dj jdYtj|s |dtfvr ||}}||z }t d|dt d|d| ||yy)a\Parse the expression and store relevant metadata. Args: expression (str): the `einops`-pattern to parse allow_underscore (bool): whether to allow axis identifier names to begin with an underscore allow_duplicates (bool): whether to allow an identifier to appear more than once in the expression FN.z...z6Expression may contain dots only inside ellipsis (...)rzUExpression may contain dots only inside ellipsis (...); only one ellipsis for tensor Tc|jvrr|dk(sstd|d|tk(rejjt'jj td_yj td_ytj|}|r.t|dk(r jj gy yj|\}}|s|std|d ||r t|n|}jj||rd_ jj |gyj |y) N_z2Indexing expression contains duplicate dimension ''FTr)r!zInvalid axis identifier:  ) identifiersrr add compositionappendhas_ellipsis_parenthesizedr isdecimalrcheck_axis_name_return_reasonr has_non_unitary_anonymous_axes) x is_number is_axis_namereason axis_namer"r! bracket_grouprs r add_axis_namez0ParsedExpression.__init__..add_axis_name_sjD$$$(Q#X?O$LQCqQI~  $$Y/ ($$++I66;D3!((36:D3MM!, Q1$,((//3'+'I'I(8(J($ f"\$'@2fX%NOO(1M!$q  $$Y/:>D7 ($$++YK8!((3rz() (zDAxis composition is one-level (brackets inside brackets not allowed))zBrackets are not balancedr'zUnknown character 'r(z'Imbalanced parentheses in expression: ')r2r rr) has_ellipsisr.setr*r1r,rr countreplacer r-isalnum)r expressionr!r"r8current_identifiercharr7s` `` @rrzParsedExpression.__init__<s#(:>';>549+NP * J& LyyU+q0CIIj#4NRS4S k$++E9=J $D CG % 4% 4N" @Du}%1!"45%)"3;$0(b%'MS[$,()DEE$$++M:$(MT"dsI.>&>%-)-&&$.& #6tfA!>??- @0  $FzlRSTU U  ) , - *rctj|sy|ddk(s|ddk(r |dk(r|ryytj|rt j d|t |dvrt j d ty) aCheck if the given axis name is valid, and a message explaining why if not. Valid axes names are python identifiers except keywords, and should not start or end with an underscore. Args: name (str): the axis name to check allow_underscore (bool): whether axis names are allowed to start with an underscore Returns: tuple[bool, str]: whether the axis name is valid, a message explaining why if not )Fznot a valid python identifierrr')T)Fz8axis name should should not start or end with underscorez7It is discouraged to use axes names that are keywords: )axiszQIt is discouraged to use 'axis' as an axis name and will raise an error in future)r isidentifierkeyword iskeywordwarningswarnRuntimeWarning FutureWarning)namer!s rr0z.ParsedExpression.check_axis_name_return_reasons%9 !W^tBx3s{/T  & MdVT"x g!rc6tj|\}}|S)zCheck if the name is a valid axis name. Args: name (str): the axis name to check Returns: bool: whether the axis name is valid )r r0)rNis_validr's rcheck_axis_namez ParsedExpression.check_axis_names'DDTJ !rN)r@r r!boolr"rRrr)F)rNr r!rRrztuple[bool, str])rNr rrR)rrrrr staticmethodr0rQrrrr r 9sj "'!& f.f. f.  f.  f.P,1%) B  rr c` |jd\}}t|vrtdtdt|}t|}|js|jrtd||jr|j rtd|||fS#t$r tddwxYw)aParse an `einops`-style pattern into a left-hand side and right-hand side `ParsedExpression` object. Args: pattern (str): the `einops`-style rearrangement pattern axes_lengths (Mapping[str, int]): any additional length specifications for dimensions Returns: tuple[ParsedExpression, ParsedExpression]: a tuple containing the left-hand side and right-hand side expressions z->z,Pattern must contain a single '->' separatorNr(z#' is not an allowed axis identifierz=Ellipsis found in right side, but not left side of a pattern z9Ellipsis is parenthesis in the left side is not allowed: )splitrr r r;r.)pattern axes_lengthsleft_str right_strleftrights r parse_patternr\sS%mmD1)L 1YK'JKLL H %D Y 'E   !3!3KG9 U   T<<Gy Q   ;% SGHdRSs BB-c|jD]#}t|x}tustd||js |jr t dt j|j|j}t|dkDrt d||j|jz }t|dkDrt d|y)a4Perform expression validations that are specific to the `rearrange` operation. Args: left (ParsedExpression): left-hand side expression right (ParsedExpression): right-hand side expression axes_lengths (Mapping[str, int]): any additional length specifications for dimensions z.rearrange axis lengths must be integers, got: z.rearrange only supports unnamed axes of size 1rzJIdentifiers only on one side of rearrange expression (should be on both): z/Identifiers not found in rearrange expression: N) valuestyper TypeErrorr1rr<symmetric_differencer*lenkeys)rZr[rWlength length_type differenceunmatched_axess rvalidate_rearrange_expressionsrhs%%'< 'K 3@ N   **e.R.RIJJ))$*:*:EQ=n=M N  rc2djd|DS)aJConvert a collection of strings representing first class dims into a comma-separated string. Args: collection (Collection[Union[str, Collection[str]]]): the collection of strings to convert Returns: str: the comma-separated string Examples: >>> comma_separate(("d0",)) 'd0' >>> comma_separate(("d0", "d1", "d2", "d3")) 'd0, d1, d2, d3' >>> comma_separate([("d1", "d4")]) '(d1, d4)' >>> comma_separate([("d0",), (), ("d1",), ("d2",), ("d3", "d4")]) '(d0,), (), (d1,), (d2,), (d3, d4)' z, c3K|]7}t|tr|n dt|t|dk(rdndd9yw)r9r,rEr:N) isinstancer comma_separaterb).0items r z!comma_separate../sO  dC  %&c$i1ns"&EQ G Hs=?)join) collections rrmrms$, 99  r)rVr rWMapping[str, int]rz)tuple[ParsedExpression, ParsedExpression])rZr r[r rWrsrr)rrz'Collection[Union[str, Collection[str]]]rr )r __future__rrHrJtypingrrrcollections.abcrrr __annotations__r r r\rhrmrrrrxs2#113 3$$"XXv" " 1"."J  #3 CT   @r