
    %gJ                     2   d 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m	Z	m
Z
mZmZ ddlmZ ddlmZ ddlmZ d	d
lmZ  ej,                         dk(  rdndZdefdZdedefdZdeddfdZdede
e   fdZdeddfdZdeddfdZdeddfdZdefdZ de
ee!df      fdZ"	 d.de!de!d e
e	eef      de#fd!Z$	 d/de
e   de
e   deedf   fd"Z%	 	 	 	 	 	 	 d0d#d$de
e   d%e
e   d&e#d'e#d(e#d)e#d*e!d+e#de#fd,Z&ejN                  de
ee!e!e!gdf      fd-       Z(y)1z.
Utilities for finding and installing CmdStan
    N)OrderedDict)CallableDictOptionalTupleUnion)tqdm)_DOT_CMDSTAN   )progress   )
get_loggerWindowsz.exe returnc                     t        j                         } d}| dk(  rd}|S | dk(  r?t        j                  g ddt        j                  d      }d|j
                  v rd	}|S d
}|S | dk(  rd}|S | dk(  s| dk(  rd}|S | dk(  rd}|S )Nr   aarch64arm64armv7l)readelfz-Az/proc/self/exeT)checkstdouttextTag_ABI_VFP_argsarmelarmhfmips64mips64elppc64elppc64les390x)platformmachine
subprocessrunPIPEr   )r#   archr   s      T/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/cmdstanpy/utils/cmdstan.pydetermine_linux_archr)      s     GD)( K' 
H	 ../??	
 /D K D K 
H	
 K	 
I	I!5 K 
G	K    versionc                     t         j                  j                  dd      }|s!t        j                         dk(  r
t               }|r |j                         dk7  rd|  d|  d| d}n	d|  d|  d}d	| S )
NCMDSTAN_ARCHr   Linuxfalsevz	/cmdstan-z-linux-z.tar.gzz6https://github.com/stan-dev/cmdstan/releases/download/)osenvirongetr"   systemr)   lower)r+   r'   url_ends      r(   get_download_urlr7   0   sz    ::>>."-DHOO%0#%

'gYiyvWEgYiy8CG9MMr*   install_dirc                    t         j                  j                  |       s	 t        j                  |        yt         j                  j                  |       st        dj                  |             	 t        dd      5  	 ddd       t        j                  d       y# t        t
        t        f$ r }t        dj                  |             |d}~ww xY w# 1 sw Y   VxY w# t
        $ r }t        dj                  |             |d}~ww xY w)z9Check that specified install directory exists, can write.zCannot create directory: {}Nz&File exists, should be a directory: {}
tmp_test_wwz"Cannot write files to directory {})r1   pathexistsmakedirsIOErrorOSErrorPermissionError
ValueErrorformatisdiropenremove)r8   es     r(   validate_dirrH   =   s    77>>+&	KK$ ww}}[)8??L 	lC( IIl# /2 	-44[A	   	4;;KH	sG   B 1C  =C?C  C1CCCC   	D	)DD	cmdstan_dirc           	         t        j                  |       D cg c]U  }t         j                  j                  t         j                  j	                  | |            r|j                  d      r|dd W }}t        |      dk(  ryt        |      dk(  rd|d   z   S |D cg c]-  }|d   j                         s|j                  d      dk(  s,|/ }}t        t        |            D ]k  }d||   v s||   j                  d      }|d   j                  d      }|d   }t        t        |      d	z
        }dj	                  |d   |d   |g      ||<   m |j                  d
        |t        |      dz
     }	|	j                  d      }t        |d         dk  r3t        t        |d         d	z         }d|z   |d<   dj	                  |      }	d|	z   S c c}w c c}w )a  
    Given a valid directory path, find all installed CmdStan versions
    and return highest (i.e., latest) version number.

    Assumes directory consists of CmdStan releases, created by
    function `install_cmdstan`, and therefore dirnames have format
    "cmdstan-<maj>.<min>.<patch>" or "cmdstan-<maj>.<min>.<patch>-rc<num>",
    which is CmdStan release practice as of v 2.24.
    cmdstan-   Nr   r   .r   z-rcd   c                 R    t        t        t        | j                  d                  S )NrM   )listmapintsplit)ss    r(   <lambda>z$get_latest_cmdstan.<locals>.<lambda>t   s    Saggcl%; < r*   )keyz0-rc)r1   listdirr<   rD   join
startswithlenisdigitcountrangerS   strrR   sort)
rI   nameversionsr0   icompsmmprc_numpatchlatests
             r(   get_latest_cmdstanrh   U   s    JJ{+77==k489OOJ' 	QRH  8}
8}HQK''#Laqt||~!''#,!:KLHL3x=! <HQKQK%%e,E(..%C1XFFc)*E((CFCFE#:;HQK< MM<M=c(ma'(F ,,s
C
3q6{QSQ[3&'&A#? Ms   AGG6GGr<   c                    t         j                  j                  |       st        d|  d      t         j                  j	                  t         j                  j                  | ddt        z               st        d|  d      y)z
    Validate that CmdStan directory exists and binaries have been built.
    Throws exception if specified path is invalid.
    zNo CmdStan directory, path z does not exist.binstancz*CmdStan installataion missing binaries in z/bin. Re-install cmdstan by running command "install_cmdstan --overwrite", or Python code "import cmdstanpy; cmdstanpy.install_cmdstan(overwrite=True)"N)r1   r<   rD   rB   r=   rX   	EXTENSIONr<   s    r(   validate_cmdstan_pathrn      st    
 77==6tf<LMNN77>>"'',,tUGi4GHI8 ?9 9
 	
 Jr*   c                 @    t        |        | t        j                  d<   y)z4
    Validate, then set CmdStan directory path.
    CMDSTANN)rn   r1   r2   rm   s    r(   set_cmdstan_pathrq      s     $ BJJyr*   makec                 *    | t         j                  d<   y)z*
    set MAKE environmental variable.
    MAKEN)r1   r2   )rr   s    r(   set_make_envru      s     BJJvr*   c                  P   d} dt         j                  v r3t        t         j                  d         dkD  rt         j                  d   } nt         j                  j	                  t         j                  j                  dt                    }t         j                  j                  |      st        d      t        |      }|t        d      t         j                  j                  ||      } | t         j                  d<   t        |        t         j                  j                  |       S )z7
    Validate, then return CmdStan directory path.
    r   rp   r   ~zcNo CmdStan installation found, run command "install_cmdstan"or (re)activate your conda environment!)r1   r2   rZ   r<   
expanduserrX   r
   r=   rB   rh   rn   normpath)cmdstanrI   latest_cmdstans      r(   cmdstan_pathr|      s     GBJJ3rzz)'<#=#A**Y'gg((c<)HIww~~k*:  ,K8!:  '',,{N; '

9'"77G$$r*   .c                     	 t         j                  j                  t               d      } t         j                  j                  |       s#t               j                  dt                      yt        | d      5 }|j                         }ddd       j                  d      }|dk  rt               j                  d	|        y|t        d      z  }|j                  d
|      }||| }|j                  d      }t        |      dk7  rt               j                  d|       yt        d |dd D              S # t        $ r=}t               j                  d       t               j                  d|       Y d}~yd}~ww xY w# 1 sw Y   xY w)ai  
    Parses version string out of CmdStan makefile variable CMDSTAN_VERSION,
    returns Tuple(Major, minor).

    If CmdStan installation is not found or cannot parse version from makefile
    logs warning and returns None.  Lenient behavoir required for CI tests,
    per comment:
    https://github.com/stan-dev/cmdstanpy/pull/321#issuecomment-733817554
    makefilezNo CmdStan installation found.z%sNz=CmdStan installation %s missing makefile, cannot get version.rzCMDSTAN_VERSION := r   z'Cannot parse version from makefile: %s.
rM      zFCannot parse version, expected "<major>.<minor>.<patch>", found: "%s".c              3   2   K   | ]  }t        |        y wN)rR   ).0xs     r(   	<genexpr>z"cmdstan_version.<locals>.<genexpr>   s     -AQ-s   r   )r1   r<   rX   r|   rB   r   infodebugr=   rE   readfindrZ   rS   tuple)r~   rG   fdcontents	start_idxend_idxr+   splitss           r(   cmdstan_versionr      s^   77<<
; 77>>(#KN	
 	h	 779 34I1}5	
 *++ImmD),Gy)G]]3F
6{a	

 -!---G  :;4# s#   (D6 8E?6	E<?3E77E<?Fmajorminorr   c                     d}|d|vrt               }nt        |d         t        |d         f}|t               j                  d| |       y|d   | k  s|d   | k(  r	|d   |k  ryy)	z
    Check that CmdStan version is less than Major.minor version.

    :param major: Major version number
    :param minor: Minor version number

    :return: True if version at or above major.minor, else False.
    Nstan_version_majorstan_version_minorz1Cannot determine whether version is before %d.%d.Fr   r   T)r   rR   r   r   )r   r   r   cur_versions       r(   cmdstan_version_beforer      s     K|+47%' )*+)*+
 ?	
 1~A%KNU$:r*   c                    t        j                         dk7  rt        d      | t        | t              st        d      t               }dt        j                  v rt        j                  d   }t        j                  j                  t        j                  j                  |d            rt        j                  j                  |t        j                  dkD  rdndd      }t        j                  j                  |      r[t        j                  j                  |d	d      }t        j                  j                  |      s1d
}d
}|j                  d|       d
}nd
}|j                  d|       d
}nt        j                  j                  t        j                  j                  |d            rt        j                  j                  |t        j                  dkD  rdndd      }t        j                  j                  |      rZt        j                  j                  |d      }t        j                  j                  |      s,d
}d
}|j                  d|       d
}nd
}|j                  d|       d
}nt        j                  j                  d      }t        j                  j!                  t        j                  j                  dt"                    }||gng |~t        j                  j                  |d      t        j                  j                  |d      t        j                  j                  |d      t        j                  j                  |d      gng z   t        j                  j                  |d      t        j                  j                  t        j                  j%                  d      d      t        j                  j                  |d      t        j                  j                  t        j                  j%                  d      d      t        j                  j                  |d      t        j                  j                  t        j                  j%                  d      d      t        j                  j                  t        j                  j%                  d      d      gz   D ]  }d
}d
}t        j                  j                  |      r| dvrt        j                  j                  |t        j                  dkD  rdndd      }t        j                  j                  |      r[t        j                  j                  |d	d      }t        j                  j                  |      sd
}d
}|j                  d|       d
} nd
}|j                  d|       d
}t        j                  j                  |t        j                  dkD  rdndd      }t        j                  j                  |      r[t        j                  j                  |d      }t        j                  j                  |      sd
}d
}|j                  d|       d
} nd
}|j                  d|       d
}d
} st'        d      |j)                  d|       dj                  t+        t-        j.                  gt        j0                  dd
      j3                  d      z                     t        j                  d<   ||fS )z?
    Validate, then activate C++ toolchain directory path.
    r   z4Functionality is currently only supported on Windowsz!Format version number as a stringCMDSTAN_TOOLCHAINmingw64l        mingw32rj   usrr   z+Found invalid installion for RTools40 on %smingw_64mingw_32z+Found invalid installion for RTools35 on %sRTOOLS40_HOMErw   RTools40RTools35RTools30RTools/RBuildTools)35z3.53z-Found invalid installation for RTools40 on %sz-Found invalid installation for RTools35 on %szkno RTools toolchain installation found, run command line script "python -m cmdstanpy.install_cxx_toolchain"zAdd C++ toolchain to $PATH: %s;PATH)r"   r4   RuntimeError
isinstancer^   	TypeErrorr   r1   r2   r<   r=   rX   sysmaxsizewarningr3   rx   r
   abspathrB   r   rP   r   fromkeysgetenvrS   )r+   r8   loggertoolchain_rootcompiler_path	tool_pathrtools40_homerI   s           r(   cxx_toolchain_pathr     sE    I%B
 	
 :gs#;;<<\Fbjj($7877>>"'',,~yABGGLL!kkE1		M
 ww~~m,GGLLF	ww~~i0 "I$&MNNE& &(N "A" "$WW^^BGGLLDEGGLL"{{U2
M
 ww~~m,GGLL?	ww~~i0 "I$&MNNE& &(N "A" "$

7gg((c<)HI - 9m_r * GGLLj9GGLLj9GGLLj9GGLLh7	 
 [*5RWW__S1:>[*5RWW__S1:>[(3RWW__S18<RWW__S1=AM	$N, MIww~~n-"44$&GGLL&&)kkE&9		%M
 ww~~m4$&GGLL$N	!ww~~i8(*I,.M"NN O . .0N!(*K* *,$&GGLL&'*{{U':
%M
 ww~~m4$&GGLL$G	!ww~~i8(*I,.M"NN O . .0N!(*K* *,!#[M	$^ :
 	

 KK0.A  	*RYYvr-B-H-H-MM	
BJJv )##r*   F)interactivedir	overwritecompilerr   verbosecoresr   c          
         t               }	 ddlm}	m}
m} |r.t        | ||||||dk7  g      r|j                  d        |
       }n |	| ||||||      } ||       d	|j                  v r0d
|j                  j                  dd      j                  dd       }nd
|j                   }t        t        j                  j                  |j                  |             y# t        $ r%}|j                  dt        |             Y d}~yd}~ww xY w)au  
    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``.

    :param version: CmdStan version string, e.g. "2.29.2".
        Defaults to latest CmdStan release.
        If ``git`` is installed, a git tag or branch of stan-dev/cmdstan
        can be specified, e.g. "git:develop".

    :param dir: Path to install directory.  Defaults to hidden directory
        ``$HOME/.cmdstan``.
        If no directory is specified and the above directory does not
        exist, directory ``$HOME/.cmdstan`` will be created and populated.

    :param overwrite:  Boolean value; when ``True``, will overwrite and
        rebuild an existing CmdStan installation.  Default is ``False``.

    :param compiler: Boolean value; when ``True`` on WINDOWS ONLY, use the
        C++ compiler from the ``install_cxx_toolchain`` command or install
        one if none is found.

    :param progress: Boolean value; when ``True``, show a progress bar for
        downloading and unpacking CmdStan.  Default is ``False``.

    :param verbose: Boolean value; when ``True``, show console output from all
        intallation steps, i.e., download, build, and test CmdStan release.
        Default is ``False``.
    :param cores: Integer, number of cores to use in the ``make`` command.
        Default is 1 core.

    :param interactive: Boolean value; if true, ignore all other arguments
        to this function and run in an interactive mode, prompting the user
        to provide the other information manually through the standard input.

        This flag should only be used in interactive environments,
        e.g. on the command line.

    :return: Boolean value; ``True`` for success.
    r   )InstallationSettingsInteractiveSettingsrun_installr   z`Interactive installation requested but other arguments were used.
	These values will be ignored!)r+   r   r   r   r   r   r   zCmdStan installation failed.
%sNFzgit:rK   :-r   _T)r   install_cmdstanr   r   r   anyr   	Exceptionr^   r+   replacerq   r1   r<   rX   r   )r+   r   r   r   r   r   r   r   r   r   r   r   argsrG   folders                  r(   r   r     s   h \F(	
 	
 QJ
 C '(D'#!!D 	D DLL00c:BB3LMNDLL>*RWW\\$((F34  93q6Bs   AC 	D'DDc                  \    t        ddddd      dt        dt        d	t        d
dffd} | S )z(Sets up tqdm callback for url downloads.BTi   blueF)unit
unit_scaleunit_divisorcolourleaver\   
block_size
total_sizer   Nc                     j                   |_         j                          | |z  }j                  |j                  z
         j                  |k\  rj	                          y y r   )totalresetupdatenclose)r\   r   r   downloaded_sizepbars       r(   download_progress_hookz6wrap_url_progress_hook.<locals>.download_progress_hook  sX     ::#DJJJL*,Odff,-66ZJJL  r*   )r	   rR   )r   r   s    @r(   wrap_url_progress_hookr     sK     D		 #	14			 "!r*   r   )NN)NNFFFFr   ))__doc__r1   r"   r$   r   collectionsr   typingr   r   r   r   r   	tqdm.autor	   	cmdstanpyr
   r   r   progbarloggingr   r4   rl   r^   r)   r7   rH   rh   rn   rq   ru   r|   rR   r   boolr   r   r   wrap_callbackr    r*   r(   <module>r      s(   
   
 # 9 9  " " %hoo'94F"	c 6
Nc 
Nc 
Nc d 0)C )HSM )X
 
 
 !3 !4 !s t %c %4/.%S/2 /.f >B"*4S>":	@ AE^$c]^$08^$
38_^$D "e ec]e	#e e 	e
 e e e e 
eP 	"3S/42G)H I " "r*   