-
-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathcmdstan.py
More file actions
562 lines (498 loc) · 19 KB
/
cmdstan.py
File metadata and controls
562 lines (498 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
"""
Utilities for finding and installing CmdStan
"""
import os
import platform
import subprocess
import sys
from collections import OrderedDict
from typing import Callable, Dict, Optional, Tuple, Union
from tqdm.auto import tqdm
from cmdstanpy import _DOT_CMDSTAN
from .. import progress as progbar
from .logging import get_logger
EXTENSION = '.exe' if platform.system() == 'Windows' else ''
def determine_linux_arch() -> str:
machine = platform.machine()
arch = ""
if machine == "aarch64":
arch = "arm64"
elif machine == "armv7l":
# Telling armel and armhf apart is nontrivial
# c.f. https://forums.raspberrypi.com/viewtopic.php?t=20873
readelf = subprocess.run(
["readelf", "-A", "/proc/self/exe"],
check=True,
stdout=subprocess.PIPE,
text=True,
)
if "Tag_ABI_VFP_args" in readelf.stdout:
arch = "armel"
else:
arch = "armhf"
elif machine == "mips64":
arch = "mips64el"
elif machine == "ppc64el" or machine == "ppc64le":
arch = "ppc64el"
elif machine == "s390x":
arch = "s390x"
return arch
def get_download_url(version: str) -> str:
arch = os.environ.get("CMDSTAN_ARCH", "")
if not arch and platform.system() == "Linux":
arch = determine_linux_arch()
if arch and arch.lower() != "false":
url_end = f'v{version}/cmdstan-{version}-linux-{arch}.tar.gz'
else:
url_end = f'v{version}/cmdstan-{version}.tar.gz'
return f'https://github.com/stan-dev/cmdstan/releases/download/{url_end}'
def validate_dir(install_dir: str) -> None:
"""Check that specified install directory exists, can write."""
if not os.path.exists(install_dir):
try:
os.makedirs(install_dir)
except (IOError, OSError, PermissionError) as e:
raise ValueError(
'Cannot create directory: {}'.format(install_dir)
) from e
else:
if not os.path.isdir(install_dir):
raise ValueError(
'File exists, should be a directory: {}'.format(install_dir)
)
try:
with open('tmp_test_w', 'w'):
pass
os.remove('tmp_test_w') # cleanup
except OSError as e:
raise ValueError(
'Cannot write files to directory {}'.format(install_dir)
) from e
def get_latest_cmdstan(cmdstan_dir: str) -> Optional[str]:
"""
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.
"""
versions = [
name[8:]
for name in os.listdir(cmdstan_dir)
if os.path.isdir(os.path.join(cmdstan_dir, name))
and name.startswith('cmdstan-')
]
if len(versions) == 0:
return None
if len(versions) == 1:
return 'cmdstan-' + versions[0]
# we can only compare numeric versions
versions = [v for v in versions if v[0].isdigit() and v.count('.') == 2]
# munge rc for sort, e.g. 2.25.0-rc1 -> 2.25.-99
for i in range(len(versions)): # # pylint: disable=C0200
if '-rc' in versions[i]:
comps = versions[i].split('-rc')
mmp = comps[0].split('.')
rc_num = comps[1]
patch = str(int(rc_num) - 100)
versions[i] = '.'.join([mmp[0], mmp[1], patch])
versions.sort(key=lambda s: list(map(int, s.split('.'))))
latest = versions[len(versions) - 1]
# unmunge as needed
mmp = latest.split('.')
if int(mmp[2]) < 0:
rc_num = str(int(mmp[2]) + 100)
mmp[2] = "0-rc" + rc_num
latest = '.'.join(mmp)
return 'cmdstan-' + latest
def validate_cmdstan_path(path: str) -> None:
"""
Validate that CmdStan directory exists and binaries have been built.
Throws exception if specified path is invalid.
"""
if not os.path.isdir(path):
raise ValueError(f'No CmdStan directory, path {path} does not exist.')
if not os.path.exists(os.path.join(path, 'makefile')):
raise ValueError(
f'CmdStan installataion missing makefile, path {path} is invalid.'
' You may wish to re-install cmdstan by running command '
'"install_cmdstan --overwrite", or Python code '
'"import cmdstanpy; cmdstanpy.install_cmdstan(overwrite=True)"'
)
def stanc_path() -> str:
"""
Returns the path to the stanc executable in the CmdStan installation.
"""
cmdstan = cmdstan_path()
stanc_exe = os.path.join(cmdstan, 'bin', 'stanc' + EXTENSION)
if not os.path.exists(stanc_exe):
raise ValueError(
f'stanc executable not found in CmdStan installation: {cmdstan}.\n'
'You may need to re-install or re-build CmdStan.',
)
return stanc_exe
def set_cmdstan_path(path: str) -> None:
"""
Validate, then set CmdStan directory path.
"""
validate_cmdstan_path(path)
os.environ['CMDSTAN'] = path
def set_make_env(make: str) -> None:
"""
set MAKE environmental variable.
"""
os.environ['MAKE'] = make
def cmdstan_path() -> str:
"""
Validate, then return CmdStan directory path.
"""
cmdstan = ''
if 'CMDSTAN' in os.environ and len(os.environ['CMDSTAN']) > 0:
cmdstan = os.environ['CMDSTAN']
else:
cmdstan_dir = os.path.expanduser(os.path.join('~', _DOT_CMDSTAN))
if not os.path.exists(cmdstan_dir):
raise ValueError(
'No CmdStan installation found, run command "install_cmdstan"'
'or (re)activate your conda environment!'
)
latest_cmdstan = get_latest_cmdstan(cmdstan_dir)
if latest_cmdstan is None:
raise ValueError(
'No CmdStan installation found, run command "install_cmdstan"'
'or (re)activate your conda environment!'
)
cmdstan = os.path.join(cmdstan_dir, latest_cmdstan)
os.environ['CMDSTAN'] = cmdstan
validate_cmdstan_path(cmdstan)
return os.path.normpath(cmdstan)
def cmdstan_version() -> Optional[Tuple[int, ...]]:
"""
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
"""
try:
makefile = os.path.join(cmdstan_path(), 'makefile')
except ValueError as e:
get_logger().info('No CmdStan installation found.')
get_logger().debug("%s", e)
return None
with open(makefile, 'r') as fd:
contents = fd.read()
start_idx = contents.find('CMDSTAN_VERSION := ')
if start_idx < 0:
get_logger().info(
'Cannot parse version from makefile: %s.',
makefile,
)
return None
start_idx += len('CMDSTAN_VERSION := ')
end_idx = contents.find('\n', start_idx)
version = contents[start_idx:end_idx]
splits = version.split('.')
if len(splits) != 3:
get_logger().info(
'Cannot parse version, expected "<major>.<minor>.<patch>", '
'found: "%s".',
version,
)
return None
return tuple(int(x) for x in splits[0:2])
def cmdstan_version_before(
major: int, minor: int, info: Optional[Dict[str, str]] = None
) -> bool:
"""
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.
"""
cur_version = None
if info is None or 'stan_version_major' not in info:
cur_version = cmdstan_version()
else:
cur_version = (
int(info['stan_version_major']),
int(info['stan_version_minor']),
)
if cur_version is None:
get_logger().info(
'Cannot determine whether version is before %d.%d.', major, minor
)
return False
if cur_version[0] < major or (
cur_version[0] == major and cur_version[1] < minor
):
return True
return False
def cxx_toolchain_path(
version: Optional[str] = None, install_dir: Optional[str] = None
) -> Tuple[str, ...]:
"""
Validate, then activate C++ toolchain directory path.
"""
if platform.system() != 'Windows':
raise RuntimeError(
'Functionality is currently only supported on Windows'
)
if version is not None and not isinstance(version, str):
raise TypeError('Format version number as a string')
logger = get_logger()
if 'CMDSTAN_TOOLCHAIN' in os.environ:
toolchain_root = os.environ['CMDSTAN_TOOLCHAIN']
if os.path.exists(os.path.join(toolchain_root, 'mingw64')):
compiler_path = os.path.join(
toolchain_root,
'mingw64' if (sys.maxsize > 2**32) else 'mingw32',
'bin',
)
if os.path.exists(compiler_path):
tool_path = os.path.join(toolchain_root, 'usr', 'bin')
if not os.path.exists(tool_path):
tool_path = ''
compiler_path = ''
logger.warning(
'Found invalid installion for RTools40 on %s',
toolchain_root,
)
toolchain_root = ''
else:
compiler_path = ''
logger.warning(
'Found invalid installion for RTools40 on %s',
toolchain_root,
)
toolchain_root = ''
elif os.path.exists(os.path.join(toolchain_root, 'mingw_64')):
compiler_path = os.path.join(
toolchain_root,
'mingw_64' if (sys.maxsize > 2**32) else 'mingw_32',
'bin',
)
if os.path.exists(compiler_path):
tool_path = os.path.join(toolchain_root, 'bin')
if not os.path.exists(tool_path):
tool_path = ''
compiler_path = ''
logger.warning(
'Found invalid installion for RTools35 on %s',
toolchain_root,
)
toolchain_root = ''
else:
compiler_path = ''
logger.warning(
'Found invalid installion for RTools35 on %s',
toolchain_root,
)
toolchain_root = ''
else:
rtools40_home = os.environ.get('RTOOLS40_HOME')
cmdstan_dir = os.path.expanduser(os.path.join('~', _DOT_CMDSTAN))
for toolchain_root in (
([rtools40_home] if rtools40_home is not None else [])
+ (
[
os.path.join(install_dir, 'RTools40'),
os.path.join(install_dir, 'RTools35'),
os.path.join(install_dir, 'RTools30'),
os.path.join(install_dir, 'RTools'),
]
if install_dir is not None
else []
)
+ [
os.path.join(cmdstan_dir, 'RTools40'),
os.path.join(os.path.abspath("/"), "RTools40"),
os.path.join(cmdstan_dir, 'RTools35'),
os.path.join(os.path.abspath("/"), "RTools35"),
os.path.join(cmdstan_dir, 'RTools'),
os.path.join(os.path.abspath("/"), "RTools"),
os.path.join(os.path.abspath("/"), "RBuildTools"),
]
):
compiler_path = ''
tool_path = ''
if os.path.exists(toolchain_root):
if version not in ('35', '3.5', '3'):
compiler_path = os.path.join(
toolchain_root,
'mingw64' if (sys.maxsize > 2**32) else 'mingw32',
'bin',
)
if os.path.exists(compiler_path):
tool_path = os.path.join(toolchain_root, 'usr', 'bin')
if not os.path.exists(tool_path):
tool_path = ''
compiler_path = ''
logger.warning(
'Found invalid installation for RTools40 on %s',
toolchain_root,
)
toolchain_root = ''
else:
break
else:
compiler_path = ''
logger.warning(
'Found invalid installation for RTools40 on %s',
toolchain_root,
)
toolchain_root = ''
else:
compiler_path = os.path.join(
toolchain_root,
'mingw_64' if (sys.maxsize > 2**32) else 'mingw_32',
'bin',
)
if os.path.exists(compiler_path):
tool_path = os.path.join(toolchain_root, 'bin')
if not os.path.exists(tool_path):
tool_path = ''
compiler_path = ''
logger.warning(
'Found invalid installation for RTools35 on %s',
toolchain_root,
)
toolchain_root = ''
else:
break
else:
compiler_path = ''
logger.warning(
'Found invalid installation for RTools35 on %s',
toolchain_root,
)
toolchain_root = ''
else:
toolchain_root = ''
if not toolchain_root:
raise ValueError(
'no RTools toolchain installation found, '
'run command line script '
'"python -m cmdstanpy.install_cxx_toolchain"'
)
logger.info('Add C++ toolchain to $PATH: %s', toolchain_root)
os.environ['PATH'] = ';'.join(
list(
OrderedDict.fromkeys(
[compiler_path, tool_path] + os.getenv('PATH', '').split(';')
)
)
)
return compiler_path, tool_path
def install_cmdstan(
version: Optional[str] = None,
dir: Optional[str] = None,
overwrite: bool = False,
compiler: bool = False,
progress: bool = False,
verbose: bool = False,
cores: int = 1,
*,
interactive: bool = False,
) -> bool:
"""
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.
"""
logger = get_logger()
try:
from ..install_cmdstan import (
InstallationSettings,
InteractiveSettings,
run_install,
)
args: Union[InstallationSettings, InteractiveSettings]
if interactive:
if any(
[
version,
dir,
overwrite,
compiler,
progress,
verbose,
cores != 1,
]
):
logger.warning(
"Interactive installation requested but other arguments"
" were used.\n\tThese values will be ignored!"
)
args = InteractiveSettings()
else:
args = InstallationSettings(
version=version,
overwrite=overwrite,
verbose=verbose,
compiler=compiler,
progress=progress,
dir=dir,
cores=cores,
)
run_install(args)
# pylint: disable=broad-except
except Exception as e:
logger.warning('CmdStan installation failed.\n%s', str(e))
return False
if 'git:' in args.version:
folder = f"cmdstan-{args.version.replace(':', '-').replace('/', '_')}"
else:
folder = f"cmdstan-{args.version}"
set_cmdstan_path(os.path.join(args.dir, folder))
return True
@progbar.wrap_callback
def wrap_url_progress_hook() -> Optional[Callable[[int, int, int], None]]:
"""Sets up tqdm callback for url downloads."""
pbar: tqdm = tqdm(
unit='B',
unit_scale=True,
unit_divisor=1024,
colour='blue',
leave=False,
)
def download_progress_hook(
count: int, block_size: int, total_size: int
) -> None:
if pbar.total is None:
pbar.total = total_size
pbar.reset()
downloaded_size = count * block_size
pbar.update(downloaded_size - pbar.n)
if pbar.n >= total_size:
pbar.close()
return download_progress_hook