
    %g\                        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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 dd	lmZmZm Z m!Z!m"Z" dd
l#m$Z$ ddl%m&Z' ejP                  dk\  serddl)m*Z* n	ddl)m+Z+ d Z*	 ddl,Z,e,j                   Z- G d de/      Z0 G d de/      Z1de2fdZ3 ejh                  d e3       sdnd      Z5 e3       rdndZ6dee7e7f   fdZ8de7fdZ9de7fdZ: G d d       Z;d!e7d"e2de2fd#Z< G d$ d%      Z=d;d&e2ddfd'Z>d<d&e2d(e2d)e?ddfd*Z@e'j                  deee7gdf      fd+       ZBd;d&e2ddfd,ZC	 d<d&e2d(e2d)e?ddfd-ZD	 	 	 	 d=d.e7d/e2d&e2d(e2d)e?ddfd0ZEd1e7de2fd2ZFd>d1e7d(e2ddfd3ZGd4e7d&e2d(e2ddfd5ZHd6ee=e;f   ddfd7ZIdee7ef   fd8ZJd?d9ZKeLd:k(  r eK        yy# e.$ r Y )w xY w)@a  
Download and install a CmdStan release from GitHub.
Downloads the release tar.gz file to temporary storage.
Retries GitHub requests in order to allow for transient network outages.
Builds CmdStan executables and tests the compiler by building
example model ``bernoulli.stan``.

Optional command line arguments:
   -i, --interactive: flag, when specified ignore other arguments and
                      ask user for settings on STDIN
   -v, --version <release> : version, defaults to latest release version
   -d, --dir <path> : install directory, defaults to '$HOME/.cmdstan
   --overwrite: flag, when specified re-installs existing version
   --progress: flag, when specified show progress bar for CmdStan download
   --verbose: flag, when specified prints output from CmdStan build process
   --cores: int, number of cores to use when building, defaults to 1
   -c, --compiler : flag, add C++ compiler to path (Windows only)
    N)OrderedDict)Path)sleep)TYPE_CHECKINGAnyCallableDictOptionalUnion)tqdm)_DOT_CMDSTAN)cmdstan_path
do_commandpushdvalidate_dirwrap_url_progress_hook)get_download_url   )progress)      )cached_property)	lru_cachec                 8    t         t        d       |             S )N)maxsize)propertyr   )funs    V/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/cmdstanpy/install_cmdstan.pyr   r   9   s    /	$/455    c                       e Zd Zy)CmdStanRetrieveErrorN__name__
__module____qualname__ r   r   r!   r!   H       r   r!   c                       e Zd Zy)CmdStanInstallErrorNr"   r&   r   r   r)   r)   L   r'   r   r)   returnc                  0    t        j                         dk(  S )NWindows)platformsystemr&   r   r   
is_windowsr/   P   s    ??	))r   MAKEmakezmingw32-makez.exe c                  t    i } t         j                  j                  d      }|dj                  |      | d<   | S )zCreate headers dictionary.
GITHUB_PATztoken {}Authorization)osenvirongetformat)headersr4   s     r   get_headersr;   X   s9    G-J#-#4#4Z#@ Nr   c                  p   d} t         j                  j                  | t                     }t	        d      D ]1  }	 t         j                  j                  |      j                         } n t        j                  j                  d
            }|d   }t!        j"                  d|      }||j%                  d      }|S # t         j                  j                  $ rY}t        d       t        |       |dk  r-t        dj                  |dz                t        d       Y d}~t        d	      |d}~ww xY w)z&Report latest CmdStan release version.z=https://api.github.com/repos/stan-dev/cmdstan/releases/latest)r:      zCannot connect to github.   retry ({}/5)r   Nz&Cannot connect to CmdStan github repo.zutf-8tag_namezv?(.+))urllibrequestRequestr;   rangeurlopenreaderrorURLErrorprintr9   r   r!   jsonloadsdecoderesearchgroup)urlrB   iresponseecontenttagmatchs           r   latest_versionrW   a   s   
ICnn$$S+-$@G1X 	~~--g6;;=H jj12G
*
CIIi%Ekk!nJ ||$$ 		-.!H1un++AE23a&8		s   -B??D5AD0$D00D5c                      t         j                  j                  t         j                  j                  dt                    S )N~)r6   path
expanduserjoinr   r&   r   r   home_cmdstanr]   {   s&    77bggll3=>>r   c                   V    e Zd ZdZdddddddddee   dee   ded	ed
edededefdZ	y)InstallationSettingsz/
    A static installation settings object
    NFr   )versiondirr   verbose	overwritecorescompilerr`   ra   r   rb   rc   rd   re   kwargsc                    |r|n	t               | _        |r|n	t               | _        || _        || _        || _        || _        |xr
 t               | _	        |}	y )N)
rW   r`   r]   ra   r   rb   rc   rd   r/   re   )
selfr`   ra   r   rb   rc   rd   re   rf   _s
             r   __init__zInstallationSettings.__init__   sN     #*w~/?3<> "
 1Z\r   )
r#   r$   r%   __doc__r
   strboolintr   rj   r&   r   r   r_   r_      s{     "&! # c]	
      r   r_   answerdefaultc                 :    | j                         } | dv ry| dv ry|S )N)yyesT)nnoF)lower)ro   rp   s     r   yes_norw      s(    \\^FNr   c                       e Zd ZdZedefd       Zedefd       Zedefd       Z	edefd       Z
edefd       Zedefd       Zedefd	       Zy
)InteractiveSettingsa)  
    Installation settings provided on-demand in an interactive format.

    This provides the same set of properties as the ``InstallationSettings``
    object, but rather than them being fixed by the constructor the user is
    asked for input whenever they are accessed for the first time.
    r*   c                 j    t               }t        d       t        d|        t        d      }|r|S |S )Nz(Which version would you like to install?	Default: z'Type version or hit enter to continue: )rW   rI   input)rh   latestro   s      r   r`   zInteractiveSettings.version   s:    !89	&"#@Av+V+r   c                     t               }t        d       t        d|        t        d      }|rt        j                  j                  |      S |S )Nz(Where would you like to install CmdStan?r{   z)Type full path or hit enter to continue: )r]   rI   r|   r6   rZ   r[   )rh   	directoryro   s      r   ra   zInteractiveSettings.dir   sH     N	89	)%&BC-3rww!!&)BBr   c                 \    t        d       t        d       t        d      }t        |d      S )Nz Show installation progress bars?z
Default: y[y/n]: TrI   r|   rw   rh   ro   s     r   r   zInteractiveSettings.progress   s*    01ly!fd##r   c                 \    t        d       t        d       t        d      }t        |d      S )Nz0Show verbose output of the installation process?
Default: nr   Fr   r   s     r   rb   zInteractiveSettings.verbose   s*    @Aly!fe$$r   c                 \    t        d       t        d       t        d      }t        |d      S )Nz(Overwrite existing CmdStan installation?r   r   Fr   r   s     r   rc   zInteractiveSettings.overwrite   s*    89ly!fe$$r   c                     t               syt        d       t        d       t        d       t        d       t        d      }t        |d      S )NFz5Would you like to install the RTools40 C++ toolchain?z(A C++ toolchain is required for CmdStan.ztIf you are not sure if you need the toolchain or not, the most likely case is you do need it, and should answer 'y'.r   r   )r/   rI   r|   rw   r   s     r   re   zInteractiveSettings.compiler   sK    |EF89M	
 	ly!fe$$r   c                     t        j                         xs d}t        d       t        d|        t        d      }	 t	        |t        t        |      d            S # t        $ r Y yw xY w)Nr   zNHow many CPU cores would you like to use for installing and compiling CmdStan?zDefault: 1, Max: z)Enter a number or hit enter to continue: )r6   	cpu_countrI   r|   minmaxrn   
ValueError)rh   max_cpusro   s      r   rd   zInteractiveSettings.cores   sk    <<>&Q%	
 	!(,-BC	xS[!!455 		s   A 	A)(A)N)r#   r$   r%   rk   r   rl   r`   ra   rm   r   rb   rc   re   rn   rd   r&   r   r   ry   ry      s     , , , CS C C $$ $ $ % % % %4 % % %$ % % s  r   ry   rb   c                     t         dg}	 | rt        |       yt        |d       y# t        $ r}t        dt	        |             d}~ww xY w)z
    Run `make clean-all` in the current directory (must be a cmdstan library).

    :param verbose: Boolean value; when ``True``, show output from make command.
    z	clean-allNfd_outz Command "make clean-all" failed
)r0   r   RuntimeErrorr)   rl   )rb   cmdrS   s      r   	clean_allr      sQ     
CPsOs4( P!$Ec!fX"NOOPs   & & 	AAAr   rd   c                    t         dd| g}	 | rt        |       n<|r-t        j                         rt	               }t        |d|       nt        |d       t        j                  j                  t        j                  j                  ddt        z               st        d	t         d
      t        j                  j                  t        j                  j                  ddt        z               st        d	t         d
      t               rt        j                  j                  t        j                         ddddd      }dj                  t        t!        j"                  |gt        j$                  j'                  dd      j)                  d      z                     t        j$                  d<   yy# t
        $ r}t        dt        |             d}~ww xY w)a  
    Run command ``make build`` in the current directory, which must be
    the home directory of a CmdStan version (or GitHub repo).
    By default, displays a progress bar which tracks make command outputs.
    If argument ``verbose=True``, instead of a progress bar, streams
    make command outputs to sys.stdout.  When both ``verbose`` and ``progress``
    are ``False``, runs silently.

    :param verbose: Boolean value; when ``True``, show output from make command.
        Default is ``False``.
    :param progress: Boolean value; when ``True`` display progress progress bar.
        Default is ``True``.
    :param cores: Integer, number of cores to use in the ``make`` command.
        Default is 1 core.
    buildz-jN)r   pbarr   zCommand "make build" failed
binstansummaryzbin/stansummaryz+ not found, please rebuild or report a bug!diagnosestanlib	stan_mathtbb;PATHr2   )r0   r   progbarallow_show_progress_wrap_build_progress_hookr   r)   rl   r6   rZ   existsr\   	EXTENSIONr/   getcwdlistr   fromkeysr7   r8   split)rb   r   rd   r   progress_hookrS   libtbbs          r   r   r     s     Bug,
'CLsO'557!:!<Ms4m<s4(
 77>>"'',,umi.GHI!i[ )0 0
 	
 77>>"'',,uj9.DEF!i[ )0 0
 	

 |IIKUE
 !XX$$Hrzz~~fb9??DD


6   L!$A#a&"JKKLs   A
F7 7	G GGc                  ^    d} dt        ddd|  igddd	      d
t        ddffd}|S )z7Sets up tqdm callback for CmdStan sampler console msgs.z                       z0{desc} ({elapsed}) | {bar} | {postfix[0][value]}valuezBuilding CmdStan bluer2   r   )total
bar_formatpostfixcolourdescpositionliner*   Nc                    | j                  d      rRj                  d       | j                  d   d<   j                  j                  z
         j                          y | j                  d      r| j                  d   d<   y | d d  d| dd   j                  d   d<   j                  d	       j                  d
       y )Nz--- CmdStanDoner   r   z--r   z ... i	Compilingr   )
startswithset_descriptionr   updatert   close)r   msgs_expectedr   s    r   build_progress_hookz6_wrap_build_progress_hook.<locals>.build_progress_hookG  s    ??=)  ('+DLLOG$KK./JJLt$+/Q(.22AhZuT#$ZL+IQ($$[1Ar   )r   rl   )padr   r   r   s     @@r   r   r   9  sV     CME.se456D# $  r   c                    t        ddd      j                  t              }|j                         r|j	                          t
        |j                         g}	 | rt        |       nt        |d       |j                         st        d      y# t        $ r%}t        ddj                  |       d|       d}~ww xY w)	z
    Compile the example model.
    The current directory must be a cmdstan installation, i.e.,
    contains the makefile, Stanc compiler, and all libraries.

    :param verbose: Boolean value; when ``True``, show output from make command.
    examples	bernoulliNr   z	Command " z
" failed:
z!Failed to generate example binary)r   with_suffixr   is_fileunlinkr0   as_posixr   r   r)   r\   )rb   rZ   r   rS   s       r   compile_exampler   X  s     
K5AA)LD||~
!CMsOs4(
 <<>!"EFF 	  M!Ichhsm_Ks"KLLMs   B 	B= B88B=c                     	 t        t                     5  t        |        t        | ||       t	        |        ddd       y# 1 sw Y   yxY w# t
        $ r}t        d      |d}~ww xY w)a  
    Rebuilds the existing CmdStan installation.
    This assumes CmdStan has already been installed,
    though it need not be installed via CmdStanPy for
    this function to work.

    :param verbose: Boolean value; when ``True``, show output from make command.
        Default is ``False``.
    :param progress: Boolean value; when ``True`` display progress progress bar.
        Default is ``True``.
    :param cores: Integer, number of cores to use in the ``make`` command.
        Default is 1 core.
    Nz8Failed to rebuild CmdStan. Are you sure it is installed?)r   r   r   r   r   r   r)   )rb   r   rd   rS   s       r   rebuild_cmdstanr   r  sf     <>" 	%g'8U+G$	% 	% 	%  !F
	s3   A $AA AA A 	A(A##A(cmdstan_versionrc   c                    t        |       5  t        dj                  |              |r^t        j                  j                  d      r?t        dj                  |              t        |       t        dj                  |              t        |||       ddd       t        dj                  |              y# 1 sw Y   $xY w)a  
    Build specified CmdStan version by spawning subprocesses to
    run the Make utility on the downloaded CmdStan release src files.
    Assumes that current working directory is parent of release dir.

    :param cmdstan_version: CmdStan release, corresponds to release dirname.
    :param overwrite: when ``True``, run ``make clean-all`` before building.
    :param verbose: Boolean value; when ``True``, show output from make command.
    zHBuilding version {}, may take several minutes, depending on your system..z8Overwrite requested, remove existing build of version {}zRebuilding version {})r   rd   NzInstalled {})r   rI   r9   r6   rZ   r   r   r   r   rc   rb   r   rd   s        r   install_versionr     s      
	 7((.(?	
 ,VO, g)00ABg67 
.


017 7s   B	B88Cr`   c           	      l   d| v ryd}t        |       }t        d      D ]"  }	 t        j                  j	                  |       $ |S # t        j
                  j                  $ r7}t        d|  d|        t        d|j                          d}Y d }~ |S d }~wt        j
                  j                  $ r}|dk  r.t        d	j                  | |d
z                t        d
       Y d }~t        dj                  | |             t        dj                  |j                               d}Y d }~d }~ww xY w)Ngit:Tr=   zRelease z is unavailable from URL zHTTPError: Fr>   z.checking version {} availability, retry ({}/5)r   z%Release {} is unavailable from URL {}zURLError: {})r   rD   rA   rB   rE   rG   	HTTPErrorrI   coderH   r9   r   reason)r`   is_availablerP   rQ   errrS   s         r   is_version_availabler     s   L
7
#C1X !	!NN""3'!( # ||%% 	HWI%>seDEKz*+ L  ||$$ 	!1uDKKQ
 a9@@#NO.''12 L	!s*   AD3"+B D34.D.'AD..D3c                    | | dk(  rt        d      d| v r^| j                  d      d   }| j                  dd      j                  dd	      }t        d
| d       t	        ddddd|dddd| g
       yt        dj                  |              t        |       }t        d      D ]L  }	 |rt        j                         rt               }nd}t        j                  j                  |d|      \  }} n t        dj                               	 t        d       t)        j*                  |      }
|
j-                         }||j.                  }nd}d|  }||k7  rt1        dj                  ||            t3        j4                         }t7               rd j                  |      }|r`t        j                         rLt9        |
j;                         t=        |
j;                               d!d"#      D ]  }|
j?                  |$        n|
jA                          |
jG                          t        d'|        y# t        j                  j                  $ r+}	t!        dj                  |	j"                  |             |	d}	~	wt        j                  j$                  $ r}	t        dj                  |              t        |	       |dk  r.t        dj                  |dz                t'        d       Y d}	~	Kt        dj                  |              t!        dj                  |             |	d}	~	ww xY w# tB        $ r }	t1        d%| d&tE        |	             |	d}	~	ww xY w# 
jG                          w xY w)(z#Download specified CmdStan version.Nr2   zArgument "version" unspecified.r   :r   -/ri   zCloning CmdStan branch 'z!' from stan-dev/cmdstan on GitHubgitclonez--depth1z--branchz--recursivez--shallow-submodulesz'https://github.com/stan-dev/cmdstan.gitcmdstan-zDownloading CmdStan version {}r=   )filename
reporthookz7HTTPError: {}
Version {} not available from github.com.z5Failed to download CmdStan version {} from github.comr>   r?   z)Version {} not available from github.com.zDownload successful, file: {}zExtracting distributionzAtarfile should contain top-level dir {},but found dir {} instead.z\\?\{}r   F)iterabler   r   leave)memberzFailed to unpack file z
, error:
	zUnpacked download as )$r   r   replacerI   r   r9   r   rD   r   r   r   rA   rB   urlretrieverG   r   r!   r   rH   r   tarfileopennextnamer)   r6   r   r/   r   
getmemberslenextract
extractall	Exceptionrl   r   )r`   r   rU   
tag_folderrP   rQ   r   file_tmpri   rS   tarfirsttop_dircmdstan_dirtargetr   s                   r   retrieve_versionr     sT   'R-:;;mmC #__S#.66sC@
(-NOP&9:,'	
 		
*
1
1'
:;
7
#C1X ! 	G779 +,  !% ..44d} 5 KHa !D 

)
0
0
:;"'(ll8$
jjGG 	*k!%,,2F;,H  <%%f-F335)#..*+	 + 6*+ NN 				!+
/0u ||%% 	&<<BFFFG=
  ||$$ 	GNN
 !H1un++AE23a=DDWMN&;BB7K	Z  !$XJl3q6(C
	
 			sQ   )AH5DL- 5L*&I88 L*AL%05L%%L*-	M6MMM M+ra   c           
         ddl m} ddl m} ddlm} d}t
        j                  j                  d      }||gng t               t
        j                  j                  t
        j                  j                  d      d      t
        j                  j                  t
        j                  j                  d      d	      t
        j                  j                  t
        j                  j                  d      d
      t
        j                  j                  t
        j                  j                  d      d      gz   D ]  }dD ]  }	 |||	      sd} n |s n |st        d        || |d |d       d}	 |	|        y )Nr   )is_installed)run_rtools_install)cxx_toolchain_pathFRTOOLS40_HOMEr   RTools40RToolsRTools35RBuildTools)4035TzInstalling RTools40)ra   r   r`   rb   r  )install_cxx_toolchainr   r   utilsr   r6   r7   r8   r]   rZ   r\   abspathrI   )
ra   rb   r   _is_installed_cxx	_main_cxxr   compiler_foundrtools40_homecxx_loccxx_versions
             r   run_compiler_installr  .  s)   HF)NJJNN?3M'4'@]Ob
RWW__S):6
RWW__S)84
RWW__S):6
RWW__S)=9M   ( 	K +6!%	  #$$"		
 {C(r   argsc           
      F   t        | j                         t        dj                  | j                               | j                  }| j
                  }| j                  r+t        | j                  | j
                  | j                         d| j                  v r2| j                  j                  dd      j                  dd      }d| }nd| j                   }t        | j                        5  t        j                  j                  |      xrF t        j                  j                  t        j                  j                  |dd	d	t        z               }|r| j                   rt#        | j                        r%t        d
j                  | j                               nt%        d| j                   d      t'        j(                  |d       t+        | j                  | j                         t-        ||xr | j                   | j
                  | j                  | j.                         n$t        dj                  | j                               t        |      5  t        d       t1        | j
                         ddd       ddd       y# 1 sw Y   xY w# 1 sw Y   yxY w)z6
    Run a (potentially interactive) installation
    zCmdStan install directory: {}r   r   r   r   ri   r   r   r   zInstalling CmdStan version: {}zVersion zj cannot be downloaded. Connection to GitHub failed. Check firewall settings or ensure this version exists.T)ignore_errorsr   z$CmdStan version {} already installedzTest model compilationN)r   ra   rI   r9   r   rb   re   r  r`   r   r   r6   rZ   r   r\   r   rc   r   r   shutilrmtreer   r   rd   r   )r  ri   rU   r   already_installeds        r   run_installr  R  s    	
)
0
0
:; 	AA}}TXXt||T]]Cll""3,44S#>$SE*$T\\N3	txx  *GGNN?; 
GGLLi'	A
 !DNN#DLL16==dllKL t||n -M M 
 MM/>T\\4==9 /+>jj 8??MN?# 	**+DLL)	*= *  *<	* 	*= *  *s%   -E,J!J:JJ	JJ c                     t        j                  d      } | j                  dddd       | j                  ddd	
       | j                  ddd
       | j                  ddd       | j                  ddd       | j                  ddd       | j                  ddt        d       t	               r| j                  ddddd       t        | j                  t        j                  dd              S )Ninstall_cmdstanz--interactivez-i
store_truezCIgnore other arguments and run the installation in interactive mode)actionhelpz	--versionz-vz|version, defaults to latest release version. If git is installed, you can also specify a git tag or branch, e.g. git:develop)r  z--dirz-dz.install directory, defaults to '$HOME/.cmdstanz--overwritez1flag, when specified re-installs existing versionz	--verbosez=flag, when specified prints output from CmdStan build processz
--progressz;flag, when specified show progress bar for CmdStan downloadz--coresr   z%number of cores to use while building)rp   typer  z
--compilerz-cre   z-flag, add C++ compiler to path (Windows only))destr  r  )	argparseArgumentParseradd_argumentrn   r/   vars
parse_argssysargv)parsers    r   parse_cmdline_argsr#    s9   $$%67F
	      L   @  
 L  
 J  
 4	   | 	@ 	 	
 !!#((12,/00r   c                      t               } | j                  dd      rt        t                      y t        t	        di |        y )NinteractiveFr&   )r#  r8   r  ry   r_   )r  s    r   __main__r&    s5    Dxxu%')*(0401r   r&  )F)FTr   )FFTr   )T)r*   N)Mrk   r  rJ   r6   r-   rM   r  r   r   urllib.errorrA   urllib.requestcollectionsr   pathlibr   timer   typingr   r   r   r	   r
   r   	tqdm.autor   	cmdstanpyr   cmdstanpy.utilsr   r   r   r   r   cmdstanpy.utils.cmdstanr   r2   r   r   version_info	functoolsr   r   readlineri   ImportErrorr   r!   r)   rm   r/   getenvr0   r   rl   r;   rW   r]   r_   rw   ry   r   rn   r   wrap_callbackr   r   r   r   r   r   r  r  r#  r&  r#   r&   r   r   <module>r7     s  $   	  	  
    #   F F  "  5 !v) $6	  	A
	< 		, 	*D * ryyz|H lF	T#s(^  4?c ?
 :3  $ H HVPt P P$3
4 3
4 3
s 3
4 3
l 	8HcUD[,A#B  <GT Gd G6 @A%)9<	: 222 2 	2
 2 
2@# $ :a1c a1T a1T a1H!)c !)D !)D !)T !)H3*e/1EEF 3*4 3*l31DcN 31l2 zJ E  		s   G GG