
    	gG!                     Z   d Z ddlmZ ddlmZ ddlmZ ddlmZm	Z	m
Z
mZmZ ddlZddlmZ  G d de      Ze G d	 d
             ZdedefdZdedefdZdedee   fdZdede	eef   fdZddde	eef   dej0                  ej2                     dede	eej0                  e   f   fdZy)z
Classes and functions for reshaping Stan output.

Especially with the addition of tuples, Stan writes
flat arrays of data with a rich internal structure.
    )	dataclass)Enum)prod)AnyDictIterableListTupleNc                       e Zd ZdZdZdZy)VariableType         N)__name__
__module____qualname__SCALARCOMPLEXTUPLE     K/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/stanio/reshape.pyr   r      s    FGEr   r   c                   0   e Zd ZU dZeed<   eed<   eed<   eedf   ed<   eed<   e	d    ed<   dd	e
d
ej                  fdZd
ee   fdZd
efdZd
efdZddej"                  ded
ej"                  fdZddej"                  de
d
ej(                  e   fdZy)Variablea  
    This class represents a single output variable of a Stan model.

    It contains information about the name, dimensions, and type of the
    variable, as well as the indices of where that variable is located in
    the flattened output array Stan models write.

    Generally, this class should not be instantiated directly, but rather
    created by the :func:`parse_header()` function.
    name	start_idxend_idx.
dimensionstypecontentstopreturnc                    | j                   t        j                  k(  r[t        | j                        D cg c]%  \  }}t        |dz         |j                  d      f' }}}t        j                  |      }n[| j                   t        j                  k(  rt        j                  }n-| j                   t        j                  k(  rt        j                  }|rS t        j                  | j                  f      S c c}}w )Nr   F)r!   )r   r   r   	enumerater    strdtypenpr   float64r   
complex128r   )selfr!   iparameltsr&   s         r   r&   zVariable.dtype2   s    99*** !*$-- 8Au QUU[[U[34D  HHTNEYY,---JJEYY,...MMEL88UDOO455s   *C9c                 B    t        | j                  | j                        S N)ranger   r   r*   s    r   columnszVariable.columnsC   s    T^^T\\22r   c                 ,    t        | j                        S r/   )r   r   r1   s    r   num_eltszVariable.num_eltsF   s    DOO$$r   c                 4    | j                   | j                  z
  S r/   )r   r   r1   s    r   elt_sizezVariable.elt_sizeI   s    ||dnn,,r   srcoffsetc           	      J   | j                   |z   }| j                  |z   }| j                  t        j                  k(  r' |d||f   j
                  dg| j                  ddiS | j                  t        j                  k(  rr |d||f   j
                  ddg| j                  ddi}|d d d d df   d|d d dd df   z  z   } |j                         j
                  dg| j                  ddiS | j                  t        j                  k(  rt        j                  t        |j                  d d       t        | j                        ft              }t        | j!                               D ]  }|| j#                         z  | j!                         z  }| j$                  D 	cg c]  }	|	j'                  |||z   	       }
}	t        |
d
   j                  d
         D ]  t)        fd|
D              ||f<      |j
                  dg| j                  ddiS y c c}	w )N.orderFr   y              ?r   )r&   )r8   r   c              3   (   K   | ]	  }|     y wr/   r   ).0eltr+   s     r   	<genexpr>z+Variable._extract_helper.<locals>.<genexpr>b   s     '?3A'?s   )r   r   r   r   r   reshaper   r   squeezer   r'   emptyr   shapeobjectr0   r4   r6   r    _extract_helpertuple)r*   r7   r8   startendretoutidxoffr,   r-   r+   s              @r   rF   zVariable._extract_helperN   s
   'llV#99+++.3sE#I~&..rODOOO3OOYY,...-#c59n%--b!QdooQSQCa1f+SADqD\ 11C(3;;=((IdooISIIYY,,,, hhciin%tDOO'<=VC T]]_- @DMMO+t}}> "& ))#eck)B  tAw}}Q/0 @A"''?$'?"?C3K@@ 3;;r?DOO?3?? -s   %H rE   c                    | j                  |      }|s|j                  | j                               }|j                  dkD  r0 |j                  g |j
                  dd | j                  ddi}|S |j                  d      }|S )a  
        Given an array where the final dimension is the flattened output of a
        Stan model, (e.g. one row of a Stan CSV file), extract the variable
        and reshape it to the correct type and dimensions.

        This will most likely result in copies of the data being made if
        the variable is not a scalar.

        Parameters
        ----------
        src : np.ndarray
            The array to extract from.

            Indicies besides the final dimension are preserved
            in the output.

        object : bool
            If True, the output of tuple types will be an object array,
            otherwise it will use custom dtypes to represent tuples.

        Returns
        -------
        npt.NDArray[Any]
            The extracted variable, reshaped to the correct dimensions.
            If the variable is a tuple, this will be an object array,
            otherwise it will have a dtype of either float64 or complex128.
        r   Nr:   r;   r<   r   )axis)rF   astyper&   ndimrA   rD   r   rB   )r*   r7   rE   rK   s       r   extract_reshapezVariable.extract_reshapee   s    8 ""3'**TZZ\*C88a<#++Ksyy"~KKsKC 
 ++1+%C
r   N)T)r   )r   r   r   __doc__r%   __annotations__intr
   r   r	   boolr'   r&   r   r2   r4   r6   ndarrayrF   nptNDArrayr   rR   r   r   r   r   r      s    	 I NL c3h
:6 6 6"3# 3%# %-# -
@2:: @s @2:: @.$2:: $t $s{{SVGW $r   r   tupr"   c                 2    d| j                  dd      d   z   S )Ndummy_:r   split)rZ   s    r   _munge_first_tupler`      s    ciiQ'***r   r,   c                 N    | j                  d      d   j                  d      d   S )N.r   r]   r^   )r,   s    r   _get_base_namerc      s&    ;;sA$$S)!,,r   headerc                 V   | j                         dz   } | j                  d      }g }d}t        |d         }t        dt	        |      dz
        D ]V  }||   }t        ||dz            }||k7  s d|vr}|j                  d      dd  }d|v sd|v rt
        j                  }	|d d	 }nt
        j                  }	|j                  t        |||dz   t        t        t        |            |	g 
             n|j                  d      d   j                  d      dd  }dj                  t        j                  t        t         |||dz                      }
|j                  t        |||dz   t        t        t        |            t
        j"                  t%        |
      
             |dz   }|}Y |S )Nz,__dummy,r   r   r]   rb   z.realz.imagr:   )r   r   r   r   r   r    )stripr_   rc   r0   lenr   r   r   appendr   rG   maprU   joindictfromkeysr`   r   _from_header)rd   entriesparamsr   r   r+   entry	next_namedimsr   munged_headers              r   rn   rn      s   \\^j(Fll3GFI'!*%D1c'lQ&' (
"71q5>2	%{{3'+e#w%'7'//D9D'..D!"+ !A#(S$#8!!#	 {{3'*005ab9 #MM#&8')aRSe:T"UV! !"+ !A#(S$#8)//!-m!<	 AIDQ(T Mr   c                 T    t        |       D ci c]  }|j                  | c}S c c}w )a  
    Given a comma-separated list of names of Stan outputs, like
    that from the header row of a CSV file, parse it into a dictionary of
    :class:`Variable` objects.

    Parameters
    ----------
    header : str
        Comma separated list of Stan variables, including index information.
        For example, an ``array[2] real foo` would be represented as
        ``foo.1,foo.2``.

    Returns
    -------
    Dict[str, Variable]
        A dictionary mapping the base name of each variable to a :class:`Variable`.
    )rn   r   )rd   r,   s     r   parse_headerrv      s&    $ ,8+?@%EJJ@@@s   %TrE   
parameterssourcerE   c                    | j                         D ci c]   }|j                  |j                  ||      " c}S c c}w )a  
    Given a dictionary of :class:`Variable` objects and a source array,
    extract the variables from the source array and reshape them to the
    correct dimensions.

    Parameters
    ----------
    parameters : Dict[str, Variable]
        A dictionary of :class:`Variable` objects,
        like that returned by :func:`parse_header()`.
    source : npt.NDArray[np.float64]
        The array to extract from.
    object : bool
        If True, the output of tuple types will be an object array,
        otherwise it will use custom dtypes to represent tuples.

    Returns
    -------
    Dict[str, npt.NDArray[Any]]
        A dictionary mapping the base name of each variable to the extracted
        and reshaped data.
    rw   )valuesr   rR   )rx   ry   rE   r,   s       r   stan_variablesr|      sF    <  &&( 	

E))&)@@  s   %;)rS   dataclassesr   enumr   mathr   typingr   r   r   r	   r
   numpyr'   numpy.typingrX   r   r   r%   r`   rc   rn   rv   rY   r(   rV   r|   r   r   r   <module>r      s    "   3 3  4  r r rj+C +C +-# -# -1 1h 1hA Ac8m!4 A2 	S(]#KK

# 	
 
#s{{3
 r   