or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-variational.mddata-io-utilities.mdgenerated-quantities.mdindex.mdinstallation-setup.mdmcmc-results.mdmodel-compilation.mdmodel-interface.mdoptimization-results.mdvariational-results.md

model-compilation.mddocs/

0

# Model Compilation

1

2

Functions for compiling and formatting Stan programs, with support for custom compiler options and automatic dependency management. These functions handle the translation of Stan code into executable binaries.

3

4

## Capabilities

5

6

### Compiling Stan Files

7

8

Compile a Stan program file into an executable, with automatic dependency checking and custom compiler options.

9

10

```python { .api }

11

def compile_stan_file(

12

src,

13

force=False,

14

stanc_options=None,

15

cpp_options=None,

16

user_header=None

17

):

18

"""

19

Compile a Stan program file to executable.

20

21

Parameters:

22

- src (str or PathLike): Path to Stan source file (.stan)

23

- force (bool): Force recompilation even if executable is up-to-date

24

- stanc_options (dict, optional): Options passed to stanc compiler

25

- cpp_options (dict, optional): Options passed to C++ compiler

26

- user_header (str or PathLike, optional): Path to user header file

27

28

Returns:

29

str: Path to compiled executable

30

31

Raises:

32

CompilerError: If compilation fails

33

FileNotFoundError: If source file not found

34

"""

35

```

36

37

**Usage Example:**

38

39

```python

40

import cmdstanpy as csp

41

42

# Basic compilation

43

exe_path = csp.compile_stan_file("my_model.stan")

44

45

# Force recompilation with optimization

46

exe_path = csp.compile_stan_file(

47

"my_model.stan",

48

force=True,

49

stanc_options={"O1": True},

50

cpp_options={"STAN_THREADS": True}

51

)

52

53

print(f"Compiled to: {exe_path}")

54

```

55

56

### Formatting Stan Files

57

58

Auto-format Stan code using the stanc formatter, with options for canonical syntax and line length control.

59

60

```python { .api }

61

def format_stan_file(

62

stan_file,

63

overwrite_file=False,

64

canonicalize=False,

65

max_line_length=78,

66

backup=True,

67

stanc_options=None

68

):

69

"""

70

Format Stan program using stanc auto-formatter.

71

72

Parameters:

73

- stan_file (str or PathLike): Path to Stan file to format

74

- overwrite_file (bool): Save formatted code back to original file

75

- canonicalize (bool, str, or list): Canonicalize syntax elements

76

- True: canonicalize all supported elements

77

- str: specific element to canonicalize

78

- list: list of elements to canonicalize

79

- max_line_length (int): Maximum line length for wrapping

80

- backup (bool): Create backup file before overwriting (when overwrite_file=True)

81

- stanc_options (dict, optional): Additional stanc options

82

83

Returns:

84

None

85

86

Raises:

87

RuntimeError: If formatting fails

88

FileNotFoundError: If source file not found

89

"""

90

```

91

92

**Usage Example:**

93

94

```python

95

import cmdstanpy as csp

96

97

# Format file and print to console

98

csp.format_stan_file("messy_model.stan")

99

100

# Format and save back to file with backup

101

csp.format_stan_file(

102

"messy_model.stan",

103

overwrite_file=True,

104

canonicalize=True,

105

max_line_length=100,

106

backup=True

107

)

108

109

# Canonicalize specific syntax elements

110

csp.format_stan_file(

111

"model.stan",

112

canonicalize=["parentheses", "braces"]

113

)

114

```

115

116

## Compiler Options

117

118

### Stanc Options

119

120

Options passed to the Stan compiler (stanc) that control parsing, optimization, and code generation.

121

122

**Common stanc options:**

123

124

- `"O"` (bool): Enable all optimizations

125

- `"O0"` (bool): Disable optimizations

126

- `"O1"` (bool): Enable basic optimizations

127

- `"Oexperimental"` (bool): Enable experimental optimizations

128

- `"warn-pedantic"` (bool): Enable pedantic warnings

129

- `"warn-uninitialized"` (bool): Warn about uninitialized variables

130

- `"auto-format"` (bool): Apply auto-formatting

131

- `"max-line-length"` (int): Maximum line length for formatting

132

- `"canonicalize"` (str or list): Elements to canonicalize

133

134

**Example:**

135

136

```python

137

stanc_opts = {

138

"O1": True,

139

"warn-pedantic": True,

140

"warn-uninitialized": True

141

}

142

143

exe_path = csp.compile_stan_file("model.stan", stanc_options=stanc_opts)

144

```

145

146

### C++ Options

147

148

Options passed to the C++ compiler that control binary optimization and feature flags.

149

150

**Common C++ options:**

151

152

- `"STAN_THREADS"` (bool): Enable threading support

153

- `"STAN_MPI"` (bool): Enable MPI support

154

- `"STAN_OPENCL"` (bool): Enable OpenCL support

155

- `"USER_HEADER"` (str): Path to user header file

156

- Additional makefile variables can be passed as key-value pairs

157

158

**Example:**

159

160

```python

161

cpp_opts = {

162

"STAN_THREADS": True,

163

"USER_HEADER": "my_functions.hpp"

164

}

165

166

exe_path = csp.compile_stan_file("model.stan", cpp_options=cpp_opts)

167

```

168

169

## Advanced Compilation Patterns

170

171

### Custom User Headers

172

173

Include custom C++ functions in Stan models using user headers.

174

175

```python

176

# my_functions.hpp

177

"""

178

#include <stan/math.hpp>

179

180

namespace my_model_namespace {

181

182

template <typename T0>

183

inline T0 my_custom_function(const T0& x) {

184

return stan::math::exp(x) / (1.0 + stan::math::exp(x));

185

}

186

187

}

188

"""

189

190

# Compile with user header

191

exe_path = csp.compile_stan_file(

192

"model_with_custom_functions.stan",

193

user_header="my_functions.hpp"

194

)

195

```

196

197

### Threading Support

198

199

Enable within-chain threading for models with reduce_sum or map_rect operations.

200

201

```python

202

# Compile with threading support

203

exe_path = csp.compile_stan_file(

204

"parallel_model.stan",

205

cpp_options={"STAN_THREADS": True}

206

)

207

```

208

209

### Optimization Levels

210

211

Control Stan compiler optimizations for different use cases.

212

213

```python

214

# Debug build (no optimization, faster compilation)

215

debug_exe = csp.compile_stan_file(

216

"model.stan",

217

stanc_options={"O0": True}

218

)

219

220

# Production build (full optimization)

221

prod_exe = csp.compile_stan_file(

222

"model.stan",

223

stanc_options={"O": True}

224

)

225

226

# Experimental optimizations (may be unstable)

227

experimental_exe = csp.compile_stan_file(

228

"model.stan",

229

stanc_options={"Oexperimental": True}

230

)

231

```

232

233

### Batch Compilation

234

235

Compile multiple models with consistent settings.

236

237

```python

238

import os

239

from pathlib import Path

240

241

models_dir = Path("./stan_models")

242

exe_dir = Path("./executables")

243

exe_dir.mkdir(exist_ok=True)

244

245

compile_options = {

246

"stanc_options": {"O1": True, "warn-pedantic": True},

247

"cpp_options": {"STAN_THREADS": True}

248

}

249

250

for stan_file in models_dir.glob("*.stan"):

251

print(f"Compiling {stan_file.name}...")

252

exe_path = csp.compile_stan_file(stan_file, **compile_options)

253

254

# Move executable to organized directory

255

exe_name = stan_file.stem + (".exe" if os.name == "nt" else "")

256

os.rename(exe_path, exe_dir / exe_name)

257

```