Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions cmdstanpy/compilation.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,27 @@ def format_stan_file(
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.
If the Stan program uses ``#include`` statements, the directories
that contain the included files must be passed as ``include-paths``,
otherwise formatting fails.

For example, to format a program whose included files are in the
directory ``stan``:

.. code-block:: python

from pathlib import Path
from cmdstanpy import format_stan_file

format_stan_file(
"model.stan",
stanc_options={"include-paths": [Path("stan").resolve()]},
)

The ``#include`` statements are kept in the formatted output. To replace
them with the contents of the included files, also pass
``canonicalize="includes"``. Note that ``canonicalize`` must be given as
an argument of this function, not inside ``stanc_options``.
"""
stan_file = Path(stan_file).resolve()

Expand Down
23 changes: 23 additions & 0 deletions test/test_compilation.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,29 @@ def test_model_format_options() -> None:
assert formatted.count('(') == 1


def test_model_format_includes() -> None:
stan = os.path.join(DATAFILES_PATH, 'bernoulli_include.stan')

sys_stdout = io.StringIO()
with contextlib.redirect_stdout(sys_stdout):
format_stan_file(
stan, stanc_options={'include-paths': [DATAFILES_PATH]}
)
formatted = sys_stdout.getvalue()
assert '#include divide_real_by_two.stan' in formatted

sys_stdout = io.StringIO()
with contextlib.redirect_stdout(sys_stdout):
format_stan_file(
stan,
canonicalize='includes',
stanc_options={'include-paths': [DATAFILES_PATH]},
)
formatted = sys_stdout.getvalue()
assert '#include' not in formatted
assert 'real divide_real_by_two(real x)' in formatted


def test_compilation_options_resolution() -> None:
out = resolve_cpp_options(None, multithreading=False)
assert not out
Expand Down
Loading