
    J/PhY                     8   g d Z ddlZddlmZ ddlmZmZmZm	Z	m
Z
  G d d          Zd Zd Zd	 Zd
 Zd Zd Zd Zd Z G d d          Zd Z G d de          Zd Z G d de          Zd Z G d de          Zd Z G d de          Zd ZddZdS ) )ContrastMatrix	TreatmentPolySumHelmertDiff    N)
PatsyError)repr_pretty_delegaterepr_pretty_implsafe_issubdtypeno_picklingassert_no_picklingc                   &    e Zd ZdZd ZeZd ZeZ	dS )r   a  A simple container for a matrix used for coding categorical factors.

    Attributes:

    .. attribute:: matrix

       A 2d ndarray, where each column corresponds to one column of the
       resulting design matrix, and each row contains the entries for a single
       categorical variable level. Usually n-by-n for a full rank coding or
       n-by-(n-1) for a reduced rank coding, though other options are
       possible.

    .. attribute:: column_suffixes

       A list of strings to be appended to the factor name, to produce the
       final column names. E.g. for treatment coding the entries will look
       like ``"[T.level1]"``.
    c                     t          j        |          | _        || _        | j        j        d         t          |          k    rt          d          d S )N   z(matrix and column_suffixes don't conform)npasarraymatrixcolumn_suffixesshapelenr	   )selfr   r   s      O/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/patsy/contrasts.py__init__zContrastMatrix.__init__*   sO    j((.;Q3#7#777GHHH 87    c                 @    t          || | j        | j        g           d S N)r   r   r   )r   pcycles      r   _repr_pretty_zContrastMatrix._repr_pretty_2   s$    D4;0D"EFFFFFr   N)
__name__
__module____qualname____doc__r   r
   __repr__r    r   __getstate__ r   r   r   r      sJ         &I I I $HG G G LLLr   r   c                  D   t          ddgddggddg          } t          j        | j        t          j        d                    sJ | j        ddgk    sJ t          |            dd l}|                    t          t           dgdggddg           t          |            d S )Nr   r   ab   )r   r   array_equalr   eyer   reprpytestraisesr	   r   )cmr/   s     r   test_ContrastMatrixr2   8   s    	!Q!Q(3*	5	5B>")RVAYY/////#s++++HHHMMM
MM*nsQCj3*EEErr   c                     t          | t                    r| S t          | t                    r5	 |                     d          S # t          $ r t          |           cY S w xY wt          |           S )Nutf-8)
isinstancestrbytesdecodeUnicodeDecodeErrorr.   )objs    r   _obj_to_readable_strr;   K   s}    #s 
	C		 	::g&&&! 	 	 	99	 Cyys   A AAc                      d }  | dd            | dd            | dd            | dd            | d                     d          d            | d                     d	          d
           d S )Nc                 d    t          |           }t          |          t          u sJ ||k    sJ d S r   )r;   typer6   )r:   expectedgots      r   tz$test__obj_to_readable_str.<locals>.tX   s7    "3''CyyChr   r   1g      ?z1.0asdfu   €r4   ziso-8859-15zb'\xa4')encode)rA   s    r   test__obj_to_readable_strrE   W   s      
 AaIIIAc5MMMAffAff Ahoog))) Ahoom$$j11111r   c                        fd|D             S )Nc                 :    g | ]}d t          |          dS )[])r;   ).0levelprefixs     r   
<listcomp>z _name_levels.<locals>.<listcomp>k   s1    QQQ 4U ; ; ; ;<QQQr   r'   )rL   levelss   ` r   _name_levelsrO   j   s    QQQQ&QQQQr   c                  :    t          dddg          ddgk    sJ d S )Nr)   r*   cz[ab]z[ac])rO   r'   r   r   test__name_levelsrR   n   s,    c3Z((VV,<<<<<<<r   c                 |    t          t          j        t          |                     t	          d|                     S )N )r   r   r-   r   rO   )rN   s    r   _dummy_coderU   r   s,    "&V--|B/G/GHHHr   c                    || v r|                      |          S t          |t                    rI|dk     r|t          |           z  }d|cxk    rt          |           k     sn t	          d|d          |S t	          d|d          )Nr   zspecified level z is out of rangez
 not found)indexr5   intr   r	   )rN   	level_refs     r   
_get_levelrZ   v   s    F||I&&&)S!! q==V$IY,,,,V,,,,*YYYPQQQ
*yyyB
C
CCr   c                     t          g dd          dk    sJ t          g dd          dk    sJ t          g dd          dk    sJ t          g dd          dk    sJ dd l} |                     t          t           ddgd           |                     t          t           ddgd	           |                     t          t           ddgd
           d S )Nr)   r*   rQ   r   r+   r*   r   r+   r   r   r)   rQ   )rZ   r/   r0   r	   )r/   s    r   test__get_levelr`      s    oooq))Q....ooor**a////ooos++q0000iii##q((((MMM
MM*j3*a888
MM*j3*b999
MM*j3*c:::::r   c                   *    e Zd ZdZddZd Zd ZeZdS )r   aW  Treatment coding (also known as dummy coding).

    This is the default coding.

    For reduced-rank coding, one level is chosen as the "reference", and its
    mean behaviour is represented by the intercept. Each column of the
    resulting matrix represents the difference between the mean of one level
    and this reference level.

    For full-rank coding, classic "dummy" coding is used, and each column of
    the resulting matrix represents the mean of the corresponding level.

    The reference level defaults to the first level, or can be specified
    explicitly.

    .. ipython:: python

       # reduced rank
       dmatrix("C(a, Treatment)", balanced(a=3))
       # full rank
       dmatrix("0 + C(a, Treatment)", balanced(a=3))
       # Setting a reference level
       dmatrix("C(a, Treatment(1))", balanced(a=3))
       dmatrix("C(a, Treatment('a2'))", balanced(a=3))

    Equivalent to R ``contr.treatment``. The R documentation suggests that
    using ``Treatment(reference=-1)`` will produce contrasts that are
    "equivalent to those produced by many (but not all) SAS procedures".
    Nc                     || _         d S r   	reference)r   rd   s     r   r   zTreatment.__init__   s    "r   c                      t          |          S r   )rU   r   rN   s     r   code_with_interceptzTreatment.code_with_intercept   s    6"""r   c           	         | j         d}nt          || j                   }t          j        t	          |          dz
            }t          j        |d |d d f         t          j        dt	          |          dz
  f          ||d d d f         f          }t          d|d |         ||dz   d          z             }t          ||          S )Nr   r   zT.)	rd   rZ   r   r-   r   vstackzerosrO   r   )r   rN   rd   r-   	contrastsnamess         r   code_without_interceptz Treatment.code_without_intercept   s    >!II"64>::IfS[[1_%%I)QQQ1c&kkAo*>!?!?YZZQRQRQR]AST
 
	 T6*9*#5y1}8O#OPPi///r   r   )	r!   r"   r#   r$   r   rg   rm   r   r&   r'   r   r   r   r      sQ         <# # # ## # #
0 
0 
0 LLLr   r   c                     t                      } |                     g d          }|j        g dk    sJ t          j        |j        g dg dg dg          sJ |                     g d          }|j        ddgk    sJ t          j        |j        ddgd	dgdd	gg          sJ t          d	
                              g d          }|j        ddgk    sJ t          j        |j        d	dgddgdd	gg          sJ t          d
                              g d          }|j        ddgk    sJ t          j        |j        d	dgddgdd	gg          sJ t          d
                              g d          }|j        ddgk    sJ t          j        |j        d	dgddgdd	gg          sJ t                                          g d          }|j        ddgk    sJ t          j        |j        ddgd	dgdd	gg          sJ d S )Nr\   )z[a]z[b]z[c])r   r   r   )r   r   r   )r   r   r   z[T.b]z[T.c]r   r   rc   z[T.a]r*   r^   z[T.1]z[T.0])r   rg   r   r   allcloser   rm   t1r   s     r   test_Treatmentrs      sh   	B##OOO44F!%:%:%:::::;v}yyy)))YYY&GHHHHH&&77F!gw%77777;v}1v1v1v&>?????###::???KKF!gw%77777;v}1v1v1v&>?????$$$;;OOOLLF!gw%77777;v}1v1v1v&>?????%%%<<___MMF!gw%77777;v}1v1v1v&>????? [[//			::F!gw%77777;v}1v1v1v&>???????r   c                   0    e Zd ZdZddZd Zd Zd ZeZ	dS )r   a  Orthogonal polynomial contrast coding.

    This coding scheme treats the levels as ordered samples from an underlying
    continuous scale, whose effect takes an unknown functional form which is
    `Taylor-decomposed`__ into the sum of a linear, quadratic, etc. components.

    .. __: https://en.wikipedia.org/wiki/Taylor_series

    For reduced-rank coding, you get a linear column, a quadratic column,
    etc., up to the number of levels provided.

    For full-rank coding, the same scheme is used, except that the zero-order
    constant polynomial is also included. I.e., you get an intercept column
    included as part of your categorical term.

    By default the levels are treated as equally spaced, but you can override
    this by providing a value for the `scores` argument.

    Examples:

    .. ipython:: python

       # Reduced rank
       dmatrix("C(a, Poly)", balanced(a=4))
       # Full rank
       dmatrix("0 + C(a, Poly)", balanced(a=3))
       # Explicit scores
       dmatrix("C(a, Poly([1, 2, 10]))", balanced(a=3))

    This is equivalent to R's ``contr.poly``. (But note that in R, reduced
    rank encodings are always dummy-coded, regardless of what contrast you
    have set.)
    Nc                     || _         d S r   scores)r   rw   s     r   r   zPoly.__init__   s    r   c                 j   t          |          }| j        }|t          j        |          }t          j        |t
                    }t          |          |k    r#t          d|dt          |          d          ||                                z  }|                    d          t          j        |                              d          z  }t          j	        
                    |          \  }}|t          j        t          j        |                    z  }|t          j        t          j        |dz  d	                    z  }d|d d d
f<   g d}|d t          d|          D             z  }|d |         }|rt!          ||          S t!          |d d dd f         |dd                    S )N)dtypeznumber of levels (z#) does not match number of scores ())r]   r   )r   r]   r+   r   )axisr   )	.Constant.Linear
.Quadratic.Cubicc                     g | ]}d |S )^r'   )rJ   is     r   rM   z%Poly._code_either.<locals>.<listcomp>  s    4441111,444r      )r   rw   r   aranger   floatr	   meanreshapelinalgqrsigndiagsqrtsumranger   )	r   	interceptrN   nrw   raw_polyqrrl   s	            r   _code_eitherzPoly._code_either  s   KK>Yq\\FF%000v;;!*,-AAs6{{{{<   	&++-->>'**bill.B.B7.K.KKy||H%%1	RWRWQZZ   	RWRVAqDq)))***!!!Q$@@@44a4444bqb	 	7!!U+++ "!AAAqrrE(E!""I666r   c                 .    |                      d|          S )NTr   rf   s     r   rg   zPoly.code_with_intercept   s      v...r   c                 .    |                      d|          S )NFr   rf   s     r   rm   zPoly.code_without_intercept#  s      ///r   r   )
r!   r"   r#   r$   r   r   rg   rm   r   r&   r'   r   r   r   r      sa           D   7 7 7>/ / /0 0 0 LLLr   r   c                  H   t                      } |                     g d          }|j        g dk    sJ g dg dg dg}t          |j                   t          j        |j        |          sJ |                     g d          }|j        ddgk    sJ t          |j                   t          j        |j        dd	gd
dgdd	gg          sJ t          g d                              g d          }|j        g dk    sJ t          |j                   t          j        |j        g dg dg dg          sJ t          g d                              g d          }|j        g dk    sJ t          |j                   t          j        |j        g dg dg dg          sJ d
d l}|	                    t          t          d
dg          j        g d           |                     t          t          d                              }|j        g dk    sJ d S )Nr\   )r|   r}   r~   )r   ;f>,p ?)r   r   >,p )r   ;f?r   r}   r~   r   r   r   r   r   )r   
      rv   )r   g
gQ}.?)r   g?Q?g3)r   gGUg?guCz?)r   r      )r   g9UgHA?)r   g)U?gM
lOb)r   gWl?gQ?r      )r|   r}   r~   r   z^4z^5)r   rg   r   printr   r   rp   rm   r/   r0   r	   listr   )rr   r   r?   r/   s       r   	test_Polyr   )  s   	B##OOO44F!%K%K%KKKKK 	655"""444H
 
&-;v}h/////&&77F!i%>>>>>	&-;"$56"#!#45	
     %%%99///JJF!%K%K%KKKKK	&-;777777666	
     %%%99///JJF!%K%K%KKKKK	&-;666666555	
     MMM
MM*d1a&111EWWW##DqNN33F! & & &      r   c                   6    e Zd ZdZddZd Zd Zd Zd Ze	Z
dS )	r   a  Deviation coding (also known as sum-to-zero coding).

    Compares the mean of each level to the mean-of-means. (In a balanced
    design, compares the mean of each level to the overall mean.)

    For full-rank coding, a standard intercept term is added.

    One level must be omitted to avoid redundancy; by default this is the last
    level, but this can be adjusted via the `omit` argument.

    .. warning:: There are multiple definitions of 'deviation coding' in
       use. Make sure this is the one you expect before trying to interpret
       your results!

    Examples:

    .. ipython:: python

       # Reduced rank
       dmatrix("C(a, Sum)", balanced(a=4))
       # Full rank
       dmatrix("0 + C(a, Sum)", balanced(a=4))
       # Omit a different level
       dmatrix("C(a, Sum(1))", balanced(a=3))
       dmatrix("C(a, Sum('a1'))", balanced(a=3))

    This is equivalent to R's `contr.sum`.
    Nc                     || _         d S r   omit)r   r   s     r   r   zSum.__init__  s    			r   c                 ^    | j         t          |          dz
  S t          || j                   S )Nr   )r   r   rZ   rf   s     r   _omit_izSum._omit_i  s,    9v;;?"fdi000r   c                 "   t          |          }|                     |          }t          j        |dz
            }t          j        ||dz
  f          }|d |d d f         |d |d d f<   d||d d f<   ||d d d f         ||dz   d d d f<   |S Nr   r]   )r   r   r   r-   empty)r   rN   r   omit_ir-   outs         r   _sum_contrastzSum._sum_contrast  s    KKf%%fQUmmh1q5z""gvgqqqj/GVGQQQJFAAAI"677AAA:FQJLL!!!O
r   c                     |                      |          }t          j        t          j        t	          |                    |j        f          }dg|j        z   }t          ||          S )N[mean])rm   r   column_stackonesr   r   r   r   )r   rN   contrastr   r   s        r   rg   zSum.code_with_intercept  sZ    ..v66"'#f++"6"6!HII#*x'??fo666r   c                     |                      |          }|                     |          }|d |         ||dz   d          z   }t          |t          d|                    S )Nr   zS.)r   r   r   rO   )r   rN   r   r   included_levelss        r   rm   zSum.code_without_intercept  s_    ##F++f%% &/F6A:<<,@@fl4&I&IJJJr   r   )r!   r"   r#   r$   r   r   r   rg   rm   r   r&   r'   r   r   r   r   m  sr         :   1 1 1  7 7 7K K K LLLr   r   c                  ^   t                      } |                     g d          }|j        g dk    sJ t          j        |j        g dg dg dg          sJ |                     g d          }|j        ddgk    sJ t          j        |j        dd	gd	dgd
d
gg          sJ |                     g d          }|j        ddgk    sJ t          j        |j        dd	gd	dgd
d
gg          sJ t          d          }|                    g d          }|j        g dk    sJ t          j        |j        g dg dg dg          sJ |                    g d          }|j        ddgk    sJ t          j        |j        dd	gd
d
gd	dgg          sJ |                    g d          }|j        ddgk    sJ t          j        |j        d
d
gdd	gd	dgg          sJ t          d          }|                    g d          }|j        g dk    sJ t          j        |j        g dg dg dg          sJ |                    g d          }|j        ddgk    sJ t          j        |j        d
d
gdd	gd	dgg          sJ t          d          }|                    g d          }|j        g dk    sJ t          j        |j        g dg dg dg          sJ |                    g d          }|j        ddgk    sJ t          j        |j        d
d
gdd	gd	dgg          sJ d S )Nr\   )r   [S.a][S.b])r   r   r   )r   r   r   r   r]   r]   r   r   r   r   r]   )r]   ro   r_   z[S.-1]z[S.-2]r   )r   r   [S.c]r   )r   r   r+   z[S.0]z[S.2]r_   )r   r   r   r)   )r   rg   r   r   rp   r   rm   )rr   r   t2t3t4s        r   test_Sumr     s   	B##OOO44F!%A%A%AAAAA;v}yyy)))[[[&IJJJJJ&&77F!gw%77777;v}1v1vBx&@AAAAA&&|||44F!h%99999;v}1v1vBx&@AAAAA	!B##OOO44F!%A%A%AAAAA;v}yyy+++yyy&IJJJJJ&&77F!gw%77777;v}1vBx!Q&@AAAAA&&yyy11F!gw%77777;v}Bx!Q!Q&@AAAAA	"B##OOO44F!%A%A%AAAAA;v}{{{IIIyyy&IJJJJJ&&77F!gw%77777;v}Bx!Q!Q&@AAAAA	#B##OOO44F!%A%A%AAAAA;v}{{{IIIyyy&IJJJJJ&&77F!gw%77777;v}Bx!Q!Q&@AAAAAAAr   c                   (    e Zd ZdZd Zd Zd ZeZdS )r   aN  Helmert contrasts.

    Compares the second level with the first, the third with the average of
    the first two, and so on.

    For full-rank coding, a standard intercept term is added.

    .. warning:: There are multiple definitions of 'Helmert coding' in
       use. Make sure this is the one you expect before trying to interpret
       your results!

    Examples:

    .. ipython:: python

       # Reduced rank
       dmatrix("C(a, Helmert)", balanced(a=4))
       # Full rank
       dmatrix("0 + C(a, Helmert)", balanced(a=4))

    This is equivalent to R's `contr.helmert`.
    c                     t          |          }t          j        ||dz
  f          }t          j        d|          |dd          t          j        |dz
            <   d|t          j        |dz
            <   |S r   )r   r   rj   r   diag_indicestriu_indices)r   rN   r   contrs       r   _helmert_contrastzHelmert._helmert_contrast  sm    KK  !QU$$,.IaOOabb	"/!a%(()(*boa!e$$%r   c           	         t          j        t          j        t          |                    |                     |          f          }t          ddgt          |dd                    z             }t          ||          S )NH.r   r   )r   r   r   r   r   rO   r   r   )r   rN   r   r   s       r   rg   zHelmert.code_with_intercept  sq    ?WS[[!!4#9#9&#A#AB
 
 'tk]T&*=M=M-MNNh888r   c           	      x    |                      |          }t          |t          d|dd                              S )Nr   r   )r   r   rO   r   rN   r   s      r   rm   zHelmert.code_without_intercept	  s7    ))&11hT6!"":(F(FGGGr   N)	r!   r"   r#   r$   r   rg   rm   r   r&   r'   r   r   r   r     sO         .  ,9 9 9H H H LLLr   r   c            	      d   t                      } g ddfD ]}|                     |          }|j        g dk    sJ t          j        |j        g dg dg dg dg          sJ |                     |          }|j        g dk    sJ t          j        |j        g dg d	g d
g dg          sJ d S )Nr)   r*   rQ   d)z[H.intercept][H.b][H.c][H.d])r   r]   r]   r]   )r   r   r]   r]   )r   r   r+   r]   )r   r   r      )r   r   r   )r]   r]   r]   r   )r   r+   r]   )r   r   r   )r   rg   r   r   rp   r   rm   )rr   rN   r   s      r   test_Helmertr     s   	B''')=> 
 
''//%)U)U)UUUUU{M__nnnmmm\\\J
 
 	
 	
 	
 **622%)D)D)DDDDD{MLLL+++zzz999M
 
 	
 	
 	
 	

 
r   c                   (    e Zd ZdZd Zd Zd ZeZdS )r   a  Backward difference coding.

    This coding scheme is useful for ordered factors, and compares the mean of
    each level with the preceding level. So you get the second level minus the
    first, the third level minus the second, etc.

    For full-rank coding, a standard intercept term is added (which gives the
    mean value for the first level).

    Examples:

    .. ipython:: python

       # Reduced rank
       dmatrix("C(a, Diff)", balanced(a=3))
       # Full rank
       dmatrix("0 + C(a, Diff)", balanced(a=3))
    c                 6   t          |          }t          j        ||dz
  f          }t          j        d|          }t          j        ||          }t          j        |dz
            \  }}t          j        |          }||z
  t          |          z  |||         ||         f<   t          j        ||d d d                   }	t          j        |dz
            \  }}t          j        |          }|	t          |          z  |||         dz   ||         f<   |S r   )	r   r   rj   r   repeatr   argsortr   tril_indices)
r   rN   nlevelsr   	int_range	upper_introw_icol_i	col_order	lower_ints
             r   _diff_contrastzDiff._diff_contrast4  s   f++'7Q;/00Ia))	Ii33	w{33u Ju%%	5>5HEM
 M
 5
eIi 001 Ii44R499	w{33uJu%%	8AE'NN8ReI"E)$445r   c                     t          j        t          j        t          |                    |                     |          f          }t          |t          d|                    S )ND.)r   r   r   r   r   r   rO   r   s      r   rg   zDiff.code_with_interceptG  sN    ?BGCKK$8$8$:M:Mf:U:U#VWWhT6(B(BCCCr   c           	      x    |                      |          }t          |t          d|d d                             S )Nr   r]   )r   r   rO   r   s      r   rm   zDiff.code_without_interceptK  s7    &&v..hT6#2#;(G(GHHHr   N)	r!   r"   r#   r$   r   rg   rm   r   r&   r'   r   r   r   r      sR         &  &D D DI I I LLLr   r   c                  Z   t                      } |                     g d          }|j        g dk    sJ t          j        |j        g dg dg dg dg          sJ |                     g d          }|j        g dk    sJ t          j        |j        g dg d	g d
g dg          sJ d S )Nr   )[D.a][D.b][D.c]z[D.d])r                     п)r         ?r   r   )r   r         ?r   )r   r   r         ?)r   r   r   )r   r   r   )r   r   r   )r   r   r   )r   r   r   )r   rg   r   r   rp   r   rm   rq   s     r   	test_diffr   R  s   	B##$8$8$899F!%I%I%IIIII;---,,,+++***		
     &&';';';<<F!%@%@%@@@@@;***)))((('''		
      r   c           
         ||}t          |          r
 |            }t          |t                    r|S t          j        |          }t          |j        t          j                  r6t          |t          dt          |j
        d                                       S | r|                    |          S |                    |          S )Ncustomr   )callabler5   r   r   r   r   ry   numberrO   r   r   rg   rm   )r   rN   r   defaultas_arrays        r   code_contrast_matrixr   s  s     8::(N++ z(##Hx~ry11 
l8U8>!3D-E-EFF
 
 	
  7++F333..v666r   r   ) __all__numpyr   patsyr	   
patsy.utilr
   r   r   r   r   r   r2   r;   rE   rO   rR   rU   rZ   r`   r   rs   objectr   r   r   r   r   r   r   r   r   r'   r   r   <module>r      ss   L
K
K                              D  &	 	 	2 2 2&R R R= = =I I I	D 	D 	D
; 
; 
;1 1 1 1 1 1 1 1h@ @ @0K K K K K6 K K K\A A AH> > > > >& > > >B#B #B #BL9 9 9 9 9f 9 9 9x
 
 
 / / / / /6 / / /d  B7 7 7 7 7 7r   