
    %gFQ                        d Z ddlZddlZddlZddlZddlZddl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mZ ddlmZ ddlmZmZmZmZ dd	lmZ dd
lmZ g dZdddZg dZee ejB                  df   Z" G d d      Z#de de#dee ef   fdZ$	 	 	 	 d%dee e
f   de%deee ef      deee ef      de"de fdZ&dddddddee ejB                  f   d e%d!ee%e ee    f   d"e'd#e%deee ef      ddfd$Z(y)&z.
Makefile options for stanc and C++ compilers
    N)copy)datetime)Path)AnyDictIterableListOptionalUnion)
get_logger)	EXTENSIONcmdstan_pathcmdstan_versioncmdstan_version_before)
do_command)SanitizedOrTmpFilePath)
OO0O1Oexperimentalallow-undefined
use-openclzwarn-uninitializedinclude-pathsnamezwarn-pedanticr   r   )allow_undefinedinclude_paths)z	debug-lexzdebug-parsez	debug-astzdebug-decorated-astzdebug-generate-dataz	debug-mirzdebug-mir-prettyzdebug-optimized-mirzdebug-optimized-mir-prettyzdebug-transformed-mirzdebug-transformed-mir-prettyzdump-stan-math-signatureszauto-formatzprint-canonicalz	print-cppohelpversionc            
       `   e Zd ZdZdddddeeeef      deeeef      deddfdZ	defd	Z
d
edefdZdefdZedeeeeeeee   f   f   fd       Zedeeeeef   f   fd       Zedefd       ZddZddZddZddZddZdeddfdZdee   dee   fdZddee   dee   fdZy)CompilerOptionsa  
    User-specified flags for stanc and C++ compiler.

    Attributes:
        stanc_options - stanc compiler flags, options
        cpp_options - makefile options (NAME=value)
        user_header - path to a user .hpp file to include during compilation
    Nstanc_optionscpp_optionsuser_headerr#   r$   r%   returnc                d    ||ni | _         ||ni | _        |t        |      | _        yd| _        y)zInitialize object.N )_stanc_options_cpp_optionsstr_user_header)selfr#   r$   r%   s       R/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/cmdstanpy/compilation.py__init__zCompilerOptions.__init__P   s;     0=/Hmb+6+BK0;0GC,R    c                 N    dj                  | j                  | j                        S )Nz stanc_options={}, cpp_options={})formatr)   r*   r-   s    r.   __repr__zCompilerOptions.__repr__\   s&    188!2!2
 	
r0   otherc                     | j                         r|yt        |t              sy| j                  |j                  k(  xr4 | j
                  |j                  k(  xr | j                  |j                  k(  S )z$Overrides the default implementationTF)	is_empty
isinstancer!   r)   r#   r*   r$   r,   r%   )r-   r5   s     r.   __eq__zCompilerOptions.__eq__a   sj    ==?u}%15#6#66 7!!U%6%667!!U%6%66	
r0   c                 d    | j                   i k(  xr  | j                  i k(  xr | j                  dk(  S )zTrue if no options specified.r(   )r)   r*   r,   r3   s    r.   r7   zCompilerOptions.is_emptym   s=     2% (!!R'(!!R'	
r0   c                     | j                   S )zStanc compiler options.)r)   r3   s    r.   r#   zCompilerOptions.stanc_optionsu   s     """r0   c                     | j                   S )zC++ compiler options.)r*   r3   s    r.   r$   zCompilerOptions.cpp_optionsz           r0   c                     | j                   S )zuser header.)r,   r3   s    r.   r%   zCompilerOptions.user_header   r=   r0   c                 d    | j                          | j                          | j                          y)z]
        Check compiler args.
        Raise ValueError if invalid options are found.
        N)validate_stanc_optsvalidate_cpp_optsvalidate_user_headerr3   s    r.   validatezCompilerOptions.validate   s(    
 	  " !!#r0   c                 <   | j                   yg }d}d}t        j                         D ]~  \  }}|| j                   v s|rNt               j	                  d||       t        | j                   |         | j                   |<   | j                   |= et               j	                  d|        | j                   j                         D ]  \  }}|t        v r,t               j                  d|       |j                  |       :|t        vrt        d|       |dk(  rM|}t        |t              r|j                  d      }yt        |t              rt        d	t        |       d
      |dk(  r&| j                   
ddi| _        d| j                   d<   |j#                  d      s|rt               j	                  d       d} |D ]  }| j                   |=  ||D 	cg c]$  }	t$        j&                  j)                  |	      r#|	& }
}	t+        |
      r)t        dj-                  dj/                  |
                  |D cg c]>  }t$        j&                  j1                  t$        j&                  j3                  |            @ c}| j                   d<   yyc c}	w c c}w )z
        Check stanc compiler args and consistency between stanc and C++ options.
        Raise ValueError if bad config is found.
        NFz4compiler option "%s" is deprecated, use "%s" insteadz9compiler option "%s" is deprecated and should not be usedzignoring compiler option: %szunknown stanc compiler option: r   ,z=Invalid include-paths, expecting list or string, found type: .r   STAN_OPENCLTRUEr   z^More than one of (O, O1, O2, Oexperimental)optimizations passed. Only the last one willbe usedTzinvalid include paths: {}, )r)   STANC_DEPRECATED_OPTSitemsr   warningr   STANC_IGNORE_OPTSinfoappend
STANC_OPTS
ValueErrorr8   r+   splitlisttyper*   
startswithospathexistsanyr2   joinabspath
expanduser)r-   ignorepaths
has_o_flag
deprecatedreplacementkeyvaloptdir	bad_pathsrW   s               r.   r@   z#CompilerOptions.validate_stanc_opts   s    &
'<'B'B'D 	#JT000L((N"#
 8<++J78D''4 ++J7L((-"	$ ++113 	&HC''!!"@#Fc"J& #B3%!HII'c3'IIcNE#C.$//3Cyk<  $$$,)6(?D%7=D%%m4$L((" "&J9	&<  	)C##C(	)(-IRWW^^C5HIII9~ /66tyy7KL 
 GL4>B 2 24 894D0 I4s   $JJ?AJc                     | j                   ydD ]U  }|| j                   v sd| j                   d<   | j                   |   }t        |t              r|dk  sFt        | d| d       y)z[
        Check cpp compiler args.
        Raise ValueError if bad config is found.
        N)OPENCL_DEVICE_IDOPENCL_PLATFORM_IDrH   rG   r   z- must be a non-negative integer value, found rF   )r*   r8   intrQ   )r-   rb   rc   s      r.   rA   z!CompilerOptions.validate_cpp_opts   s    
 $= 	Cd'''39!!-0'',!#s+sQw$%  ""%a) 	r0   c                    | j                   dk7  ret        j                  j                  | j                         r)t        j                  j	                  | j                         st        d| j                    d      | j                   dd dk7  rt        d| j                          d| j                  vrd	| j                  d<   t        j                  j                  | j                         | _         d
| j                   v rt        d      d| j                  v rD| j                   | j                  d   k7  r(t        d| j                    d| j                  d          | j                   | j                  d<   yy)zV
        User header exists.
        Raise ValueError if bad config is found.
        r(   zUser header file z cannot be foundN.hppz"Header file must end in .hpp, got r   T z9User header must be in a location with no spaces in path!USER_HEADERz/Disagreement in user_header C++ options found!
rI   )	r,   rV   rW   rX   isfilerQ   r)   r[   r*   r3   s    r.   rB   z$CompilerOptions.validate_user_header   sh   
 "t001GGNN4#4#45 '(9(9'::JK    %/ 89J9J8KL  !(;(;;9=##$56 "0A0A BDd''' O 
 !2!22%%):):=)II F(()D,=,=m,L+MO 
 04/@/@Dm,? #r0   c                 Z   |j                   | j                  |j                   | _        n|j                   j                         D ]v  \  }}|dk(  r]t        |t              r2t        |t
              s"|D ]  }| j                  t        |              M| j                  t        |             h|| j                  |<   x |j                  1|j                  j                         D ]  \  }}|| j                  |<    |j                  dk7  r"| j                  dk(  r|j                  | _	        yyy)z1Adds options to existing set of compiler options.Nr   r(   )
r#   r)   rK   r8   r   r+   add_include_pathr$   r*   r,   )r-   new_optsrb   rc   rW   s        r.   addzCompilerOptions.add  s#   !!-""*&.&<&<# ( 6 6 < < > 
7HCo-%c84Z> ), A $ 5 5c$i @A !11#c(;36++C0
7 +$00668 -S),!!#&-  B&4+<+<+B ( 5 5D ,C&r0   rW   c                    t         j                  j                  t         j                  j                  |            }d| j                  vr|g| j                  d<   y|| j                  d   vr| j                  d   j                  |       yy)z6Adds include path to existing set of compiler options.r   N)rV   rW   r[   r\   r)   rO   )r-   rW   s     r.   rr   z CompilerOptions.add_include_path$  st    wwrww11$78$"5"55486D0,,_==077= >r0   filename_in_msgc           	         g }||j                  d|        | j                  t        | j                        dkD  r| j                  j                         D ]p  \  }}|dk(  r8|j                  ddj	                  d | j                  d   D              z          C|dk(  r|j                  d|        ]|j                  d	|        r |S )
Nz--filename-in-msg=r   r   z--include-paths=rE   c              3   N   K   | ]  }t        |      j                           y wN)r   as_posix).0ps     r.   	<genexpr>z0CompilerOptions.compose_stanc.<locals>.<genexpr>8  s%      $% !%Q 0 0 2s   #%r   z--name=z--)rO   r)   lenrK   rZ   )r-   rv   optsrb   rc   s        r.   compose_stanczCompilerOptions.compose_stanc,  s    &KK,_,=>?*s43F3F/G!/K //557 ,S/)KK*(()-)<)<_)M F]KK'#0KK"SE
+, r0   c                 *   | j                  |      D cg c]  }d|j                  dd      z    }}| j                  Pt        | j                        dkD  r8| j                  j	                         D ]  \  }}|j                  | d|         |S c c}w )a  
        Format makefile options as list of strings.

        Parameters
        ----------
        filename_in_msg : str, optional
            filename to be displayed in stanc3 error messages
            (if different from actual filename on disk), by default None
        zSTANCFLAGS+=rn   z\ r   =)r   replacer*   r~   rK   rO   )r-   rv   flagr   rb   rc   s         r.   composezCompilerOptions.composeD  s     **?;
 T\\#u55
 
 (S1B1B-Ca-G --335 ,Sse1SEN+,
s   B)r&   N)rs   r!   r&   Nry   )__name__
__module____qualname____doc__r
   r   r+   r   OptionalPathr/   r4   boolr9   r7   propertyr   rj   r   r#   r$   r%   rC   r@   rA   rB   rt   rr   r	   r   r    r0   r.   r!   r!   F   so    3704$(
P  S#X/
P d38n-	
P
 "
P 

P
# 



C 

D 


$ 
 #tCtS#x}/L)M$MN # # !T#uT3Y'7"78 ! ! !S ! !$GR"$AL6.>S >T >Xc] tCy 0x} S	 r0   r!   	stan_filecompiler_optionsr&   c                 f   t         j                  j                  t               ddt        z         g|j                  d      z   dt        |       gz   }t        j                  |ddd      }|j                  rt        d|  d	|j                         t        j                  |j                        }|S )
z
    Get source info for Stan program file.

    This function is used in the implementation of
    :meth:`CmdStanModel.src_info`, and should not be called directly.
    binstancNz--infoTFcapture_outputtextcheckz*Failed to get source info for Stan model ''. Console:
)rV   rW   rZ   r   r   r   r+   
subprocessrun
returncoderQ   stderrjsonloadsstdout)r   r   cmdprocresults        r.   src_infor   X  s     
lneWy-@	AB

(
(
.	/ S^
$	%  >>#dUKD{-}6
 	
 "ZZ4FMr0   Fsrcforcer#   r$   r%   c                 p   t        |       j                         } | j                         st        d|        t	        |||      }|j                          | j                  t              }|j                         rt        j                  j                  |      | g}|j                  t        t        |       |      j                  dg              t        fd|D              }|s&|s$t!               j#                  d       t        |      S d}	t%        t        |             5 \  }
}t        j                  j'                  |
      d   t        z   }t        j                  j'                  |      d   dz   }t        j                  j                  |      rt        j(                  |       t        j                  j                  |      r/t!               j#                  d	|       t        j(                  |       t!               j+                  d
|
|       t        j,                  dt/        j0                         dk7  rdnd      }|g}|j                  |j3                  | j4                               |j7                  t        |      j9                                t;        j<                         }	 t?        |tA               |       |jG                         }t!               j#                  d|       |	s2|rtI        jJ                  ||       t!               j+                  d|       d|v rn|jM                  d      }|D cg c]  }|jO                  d      s| }}t!               jQ                  dtS        |             t!               jQ                  |       |	r2d|v sd|v rt!               jQ                  d       t        d|  d|       t        |      cddd       S # tB        $ r+}|jE                  dt        |       d       d}	Y d}~Gd}~ww xY w# |jG                         }w xY wc c}w # 1 sw Y   yxY w)a|  
    Compile the given Stan program file.  Translates the Stan code to
    C++, then calls the C++ compiler.

    By default, this function compares the timestamps on the source and
    executable files; if the executable is newer than the source file, it
    will not recompile the file, unless argument ``force`` is ``True``
    or unless the compiler options have been changed.

    :param src: Path to Stan program file.

    :param force: When ``True``, always compile, even if the executable file
        is newer than the source file.  Used for Stan models which have
        ``#include`` directives in order to force recompilation when changes
        are made to the included files.

    :param stanc_options: Options for stanc compiler.
    :param cpp_options: Options for C++ compiler.
    :param user_header: A path to a header file to include during C++
        compilation.
    zstan file does not exist: r"   included_filesc              3   b   K   | ]&  }t         j                  j                  |      kD   ( y wry   )rV   rW   getmtime)r{   included_fileexe_times     r.   r}   z$compile_stan_file.<locals>.<genexpr>  s-      
 GG]+h6
s   ,/z%found newer exe file, not recompilingFr   rm   zRemoving %sz%compiling stan file %s to exe file %sMAKEWindowsmakezmingw32-make)rv   )r   cwdfd_out
TNzConsole output:
%szcompiled model executable: %sWarningz'Stan compiler has produced %d warnings:PCHzprecompiled headerzCmdStan's precompiled header (PCH) files may need to be rebuilt.Please run cmdstanpy.rebuild_cmdstan().
If the issue persists please open a bug reportzFailed to compile Stan model 'r   )*r   resolverX   rQ   r!   rC   with_suffixr   rV   rW   r   extendr   r+   getrY   r   debugr   splitextremoverN   getenvplatformsystemr   r   rO   rz   ioStringIOr   r   RuntimeErrorwritegetvalueshutilr   rR   rU   rL   r~   )r   r   r#   r$   r%   r   
exe_targetr   out_of_datecompilation_failedr   	is_copiedexe_filehpp_filer   r   souteconsolelinesxwarningsr   s                         @r.   compile_stan_filer   q  s   : s)


C::<5cU;<<&#
 +J77##J/SX/0445ErJ	
  
!/
 
 5LFGz?" 
 C	) 9-Ci77##I.q1I=77##H-a06977>>(#IIh77>>(#L}h7IIh3	
 yyoo'94F.
 f

#++CHH+EF

4>**,-{{}	&3LN4@
 mmoG0':!Hj1L=zJMM$'E#(DaALL,CDHDL  9H L  )#77#B$$E 05FwiP  :s9 96  	&JJCF82'!%	& mmoG EQ9 9sW   $FP,-OA7P,:P'P'A<P,	P$ P
P
PPP$$P,,P5N   T)overwrite_filecanonicalizemax_line_lengthbackupr#   r   r   r   r   c                X   t        |       j                         } | j                         st        d|        	 t        j
                  j                  t               ddt        z         gt        |      j                  d      z   t        |       gz   }|rt        dd      rNt        |t              r|j                  d       nt        d	d
j!                  t#               xs d      z   dz         t        |t              r|j                  d|z          nEt        |t$              r$|j                  ddj                  |      z          n|j                  d       t        dd      r|s|j                  d       t        dd      s|j                  d|        n1|dk7  r,t        ddj!                  t#               xs d      z   dz         t'        j(                  |ddd      }|j*                  r#t-               j/                  |j*                         |j0                  }|r\|rf|rFt3        j4                  | t        |       dz   t7        j8                         j;                  d      z          | j=                  |       yt?        |       yy# t        t@        f$ r}	tA        d      |	d}	~	ww xY w)a  
    Run stanc's auto-formatter on the model code. Either saves directly
    back to the file or prints for inspection

    :param stan_file: Path to Stan program file.
    :param overwrite_file: If True, save the updated code to disk, rather
        than printing it. By default False
    :param canonicalize: Whether or not the compiler should 'canonicalize'
        the Stan model, removing things like deprecated syntax. Default is
        False. If True, all canonicalizations are run. If it is a list of
        strings, those options are passed to stanc (new in Stan 2.29)
    :param max_line_length: Set the wrapping point for the formatter. The
        default value is 78, which wraps most lines by the 80th character.
    :param backup: If True, create a stanfile.bak backup before
        writing to the file. Only disable this if you're sure you have other
        copies of the file or are using a version control system like Git.
    :param stanc_options: Additional options to pass to the stanc compiler.
    zFile does not exist: r   r   )r#   N      z--print-canonicalz,Invalid arguments passed for current CmdStanz version({})
Unknownz&--canonicalize requires 2.29 or higherz--canonicalize=rE   z--auto-formatz--max-line-length=r   z4Invalid arguments passed for current CmdStan versionz ({})
z)--max-line-length requires 2.29 or higherTr   z.bak-z%Y%m%d%H%M%SzStanc formatting failed)!r   r   rX   rQ   rV   rW   rZ   r   r   r!   r   r+   r   r8   r   rO   r2   r   r   r   r   r   r   rL   r   r   copyfiler   nowstrftime
write_textprintr   )
r   r   r   r   r   r#   r   outr   r   s
             r.   format_stan_filer     sh   6 Y'')I0<==<=WW\\,.%91DEFM:HHNO 9~ 	 %a,lD1JJ23$F*11+-: C	C  lC0JJ0<?@h7JJ0388L3IIJJJ23 'q"-,JJ'%a,JJ+O+<=>"F""?#4#A	BC=>  nnSDM::L  ,OO!I!"",,.11.AB $$V,&M  % =451<=s   IJ	 <J	 	J)J$$J))FNNN))r   r   r   rV   r   r   r   r   r   pathlibr   typingr   r   r   r	   r
   r   cmdstanpy.utilsr   cmdstanpy.utils.cmdstanr   r   r   r   cmdstanpy.utils.commandr   cmdstanpy.utils.filesystemr   rP   rJ   rM   r+   PathLiker   r!   r   r   r   rj   r   r   r0   r.   <module>r      s   
  	       = = &  / =
 )$ 
 * S"++t+,O Od&5	#s(^6 .2,0 $s	sDy	ss DcN+s $sCx.)	s
 s 	sr !49.2\=S"++%&\= \= c8C=01	\=
 \= \= DcN+\= 
\=r0   