forked from Cantera/cantera
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SConstruct
2199 lines (1908 loc) · 86.7 KB
/
SConstruct
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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
SCons build script for Cantera
Basic usage:
'scons help' - Show this help message.
'scons build' - Compile Cantera and the language interfaces using
default options.
'scons clean' - Delete files created while building Cantera.
'scons install' - Install Cantera.
'scons uninstall' - Uninstall Cantera.
'scons test' - Run all tests which did not previously pass or for which the
results may have changed.
'scons test-reset' - Reset the passing status of all tests.
'scons test-clean' - Delete files created while running the tests.
'scons test-help' - List available tests.
'scons test-{python,gtest,legacy}' - Run all Python, GTest, or legacy
(test_problems) test cases, respectively.
'scons test-NAME' - Run the test named "NAME".
'scons build-NAME' - Build the program for the test named "NAME".
'scons build-tests' - Build the programs for all tests.
'scons samples' - Compile the C++ and Fortran samples.
'scons msi' - Build a Windows installer (.msi) for Cantera.
'scons sphinx' - Build the Sphinx documentation
'scons doxygen' - Build the Doxygen documentation
Additional command options:
'scons help --options' - Print a description of user-specifiable options.
'scons help --list-options' - Print formatted list of available options.
'scons help --option=<opt>' - Print the description of a specific option
with name <opt>, for example
'scons help --option=prefix'
'scons <command> -j<X>' - Short form of '--jobs=<X>'. Run the <command> using '<X>'
parallel jobs, for example 'scons build -j4'
'scons <command> -s' - Short form of '--silent' (or '--quiet'). Suppresses output.
"""
# Note that 'scons help' supports additional command options that are intended for
# internal use (debugging or reST parsing of options) and thus are not listed above:
# --defaults ... list default values for all supported platforms
# --restructured-text ... format configuration as reST
# --dev ... add '-dev' to reST output
# --output=<fname> ... send output to file (reST only)
#
# Other features not listed above:
# 'scons sdist' - Build PyPI packages.
# 'scons <command> dump' - Dump the state of the SCons environment to the
# screen instead of doing <command>, for example
# 'scons build dump'. For debugging purposes.
# This f-string is deliberately here to trigger a SyntaxError when
# SConstruct is parsed by Python 2. This seems to be the most robust
# and simplest option that will reliably trigger an error in Python 2
# and provide actionable feedback for users.
f"""
Cantera must be built using Python 3.8 or higher. You can invoke SCons by executing
python3 `which scons`
followed by any desired options.
"""
from pathlib import Path
import sys
import os
import platform
import atexit
import subprocess
import re
import textwrap
from copy import deepcopy
from packaging.specifiers import SpecifierSet
from packaging.version import parse as parse_version
import SCons
from buildutils import (Option, PathOption, BoolOption, EnumOption, Configuration,
logger, remove_directory, remove_file, test_results,
add_RegressionTest, get_command_output, listify, which,
ConfigBuilder, multi_glob, quoted, add_system_include,
checkout_submodule, check_for_python, check_sundials,
config_error, run_preprocessor, make_relative_path_absolute)
# ensure that Python and SCons versions are sufficient for the build process
EnsurePythonVersion(3, 7)
EnsureSConsVersion(3, 0, 0)
if not COMMAND_LINE_TARGETS:
# Print usage help
logger.error("Missing command argument: type 'scons help' for information.")
sys.exit(1)
if os.name not in ["nt", "posix"]:
logger.error(f"Unrecognized operating system {os.name!r}")
sys.exit(1)
valid_commands = ("build", "clean", "install", "uninstall",
"help", "msi", "samples", "sphinx", "doxygen", "dump",
"sdist")
# set default logging level
if GetOption("silent"):
logger.logger.setLevel("ERROR")
else:
logger.logger.setLevel("INFO")
for command in COMMAND_LINE_TARGETS:
if command not in valid_commands and not command.startswith(('test', 'build-')):
logger.error(f"Unrecognized command line target: {command!r}")
sys.exit(1)
if "clean" in COMMAND_LINE_TARGETS:
remove_directory("build")
remove_directory("stage")
remove_directory(".sconf_temp")
remove_directory("test/work")
remove_file(".sconsign.dblite")
remove_file("include/cantera/base/config.h")
remove_file("src/extensions/PythonExtensionManager.os")
remove_file("src/extensions/delegator.h")
remove_file("src/pch/system.h.gch")
remove_directory("include/cantera/ext")
remove_file("config.log")
remove_directory("doc/sphinx/cython/examples")
remove_file("doc/sphinx/cython/examples.rst")
for name in Path(".").glob("*.msi"):
remove_file(name)
for name in Path("site_scons").glob("**/*.pyc"):
remove_file(name)
logger.status("Done removing output files.", print_level=False)
if COMMAND_LINE_TARGETS == ["clean"]:
# Just exit if there's nothing else to do
sys.exit(0)
else:
Alias("clean", [])
if "test-clean" in COMMAND_LINE_TARGETS:
remove_directory("build/test")
remove_directory("test/work")
remove_directory("build/python_local")
python_version = f"{sys.version_info.major}.{sys.version_info.minor}"
logger.info(
f"SCons {SCons.__version__} is using the following Python interpreter:\n"
f" {sys.executable} (Python {python_version})", print_level=False)
cantera_version = "3.1.0a4"
# For use where pre-release tags are not permitted (MSI, sonames)
cantera_pure_version = re.match(r'(\d+\.\d+\.\d+)', cantera_version).group(0)
cantera_short_version = re.match(r'(\d+\.\d+)', cantera_version).group(0)
cantera_git_commit = os.environ.get("CT_GIT_COMMIT")
if not cantera_git_commit:
try:
cantera_git_commit = get_command_output("git", "rev-parse", "--short", "HEAD")
logger.info(f"Building Cantera from git commit {cantera_git_commit!r}")
except (subprocess.CalledProcessError, FileNotFoundError):
cantera_git_commit = "unknown"
else:
logger.info(f"Building Cantera from git commit {cantera_git_commit!r}")
# Python Package Settings
python_min_version = parse_version("3.8")
# Newest Python version not supported/tested by Cantera
python_max_version = parse_version("3.13")
# The string is used to set python_requires in setup.cfg.in
py_requires_ver_str = f">={python_min_version},<{python_max_version}"
if "sdist" in COMMAND_LINE_TARGETS:
if "clean" in COMMAND_LINE_TARGETS:
COMMAND_LINE_TARGETS.remove("clean")
if len(COMMAND_LINE_TARGETS) > 1:
logger.error("'sdist' target cannot be built simultaneously with other targets.")
sys.exit(1)
logger.info("Copying files for sdist...")
subprocess.run(
[
sys.executable,
"interfaces/python_sdist/build_sdist.py",
os.getcwd(),
"/".join((os.getcwd(), "build", "python_sdist")),
cantera_git_commit,
py_requires_ver_str,
cantera_version,
cantera_short_version,
],
check=True,
)
subprocess.run(
[
sys.executable,
"-m",
"build",
"--sdist",
"/".join((os.getcwd(), "build", "python_sdist")),
],
)
message = textwrap.dedent(f"""
****************************************************************
Python sdist 'Cantera-{cantera_version}.tar.gz' created successfully.
The sdist file is in the 'build/python_sdist/dist' directory.
****************************************************************
""")
logger.info(message, print_level=False)
sys.exit(0)
# ******************************************
# *** Specify defaults for SCons options ***
# ******************************************
windows_options = [
Option(
"msvc_version",
"""Version of Visual Studio to use. The default is the newest installed version.
Note that since multiple MSVC toolsets can be installed for a single version of
Visual Studio, you probably want to use ``msvc_toolset_version`` unless you
specifically installed multiple versions of Visual Studio. Windows MSVC only.
""",
""),
Option(
"msvc_toolset_version",
"""Version of the MSVC toolset to use. The default is the default version for
the given ``msvc_version``. Note that the toolset selected here must be
installed in the MSVC version selected by ``msvc_version``. The default
toolsets associated with various Visual Studio versions are:
* '14.1' ('14.1x'): Visual Studio 2017
* '14.2' ('14.2x'): Visual Studio 2019
* '14.3' ('14.3x'): Visual Studio 2022.
For version numbers in parentheses, 'x' is a placeholder for a minor version
number. Windows MSVC only.""",
""),
EnumOption(
"target_arch",
"""Target architecture. The default is the same architecture as the
installed version of Python. Windows only.""",
{"Windows": "amd64"},
("amd64", "x86")),
EnumOption(
"toolchain",
"""The preferred compiler toolchain. If MSVC is not on the path but
'g++' is on the path, 'mingw' is used as a backup. Windows only.""",
{"Windows": "msvc"},
("msvc", "mingw", "intel")),
]
config_options = [
Option(
"AR",
"The archiver to use.",
"${AR}"),
Option(
"CXX",
"The C++ compiler to use.",
"${CXX}"),
Option(
"cxx_flags",
"""Compiler flags passed to the C++ compiler only. Separate multiple
options with spaces, for example, "cxx_flags='-g -Wextra -O3 -std=c++20'"
""",
{
"cl": "/EHsc /std:c++17 /utf-8",
"default": "-std=c++17"
}),
Option(
"CC",
"The C compiler to use. This is only used to compile CVODE.",
"${CC}"),
Option(
"cc_flags",
"""Compiler flags passed to both the C and C++ compilers, regardless of
optimization level.""",
{
"cl": "/MD /nologo /D_SCL_SECURE_NO_WARNINGS /D_CRT_SECURE_NO_WARNINGS",
"clang": "-fcolor-diagnostics",
"default": "",
}),
PathOption(
"prefix",
r"""Set this to the directory where Cantera should be installed. If the Python
executable found during compilation is managed by 'conda', the installation
'prefix' defaults to the corresponding environment and the 'conda' layout
will be used for installation (specifying any of the options 'prefix',
'python_prefix', 'python_cmd', or 'layout' will override this default). On
Windows systems, '$ProgramFiles' typically refers to "C:\Program Files".""",
{"Windows": r"$ProgramFiles\Cantera", "default": "/usr/local"},
PathVariable.PathAccept),
PathOption(
"libdirname",
"""Set this to the directory where Cantera libraries should be installed.
Some distributions (for example, Fedora/RHEL) use 'lib64' instead of 'lib'
on 64-bit systems or could use some other library directory name instead of
'lib', depending on architecture and profile (for example, Gentoo 'libx32'
on x32 profile). If the user didn't set the 'libdirname' configuration
variable, set it to the default value 'lib'""",
"lib", PathVariable.PathAccept),
EnumOption(
"python_package",
"""Set this to 'y' to build the Python interface, including conversion
scripts for CHEMKIN, CTI, and CTML input files. Set this to 'n' to
skip building the Python interface. Building the Python interface
requires the Python headers, Cython, and NumPy. Testing the Python
interface further requires ruamel.yaml and pytest. The default
behavior is to build the full Python module for whichever version of
Python is running SCons if the required prerequisites (NumPy and
Cython) are installed. Note: 'y' is a synonym for 'full' and 'n' is a
synonym for 'none'.""",
# TODO: Remove 'minimal' after Cantera 3.1 is released. Leave it here for now
# to provide migration information.
# TODO: Remove 'none' and 'full' options after Cantera 3.1 is released. Prefer
# simpler 'y' and 'n' options, since we don't need to distinguish from the
# minimal interface.
"default", ("full", "none", "n", "y", "default", "minimal")),
PathOption(
"python_cmd",
"""Cantera needs to know where to find the Python interpreter. If
'PYTHON_CMD' is not set, then the configuration process will use the
same Python interpreter being used by SCons.""",
"${PYTHON_CMD}",
PathVariable.PathAccept),
PathOption(
"python_prefix",
"""Use this option if you want to install the Cantera Python package to
an alternate location. On Unix-like systems, the default is the same
as the 'prefix' option. If the 'python_prefix' option is set to
the empty string or the 'prefix' option is not set, then the package
will be installed to the system default 'site-packages' directory.
To install to the current user's 'site-packages' directory, use
'python_prefix=USER'.""",
{"default": ""},
PathVariable.PathAccept),
EnumOption(
"f90_interface",
"""This variable controls whether the Fortran 90/95 interface will be
built. If set to 'default', the builder will look for a compatible
Fortran compiler in the 'PATH' environment variable, and compile
the Fortran 90 interface if one is found.""",
"default", ("y", "n", "default")),
PathOption(
"FORTRAN",
"""The Fortran (90) compiler. If unspecified, the builder will look for a
compatible compiler (pgfortran, gfortran, ifort, ifx, g95) in the 'PATH'
environment variable. Used only for compiling the Fortran 90 interface.""",
"", PathVariable.PathAccept),
Option(
"FORTRANFLAGS",
"Compilation options for the Fortran (90) compiler.",
"-O3"),
BoolOption(
"coverage",
"""Enable collection of code coverage information with gcov.
Available only when compiling with gcc.""",
False),
BoolOption(
"doxygen_docs",
"Build HTML documentation for the C++ interface using Doxygen.",
False),
BoolOption(
"sphinx_docs",
"Build HTML documentation for Cantera using Sphinx.",
False),
BoolOption(
"run_examples",
"""Run examples to generate plots and outputs for Sphinx Gallery. Disable to
speed up doc builds when not working on the examples or if dependencies of
the examples are not available.""",
True),
PathOption(
"sphinx_cmd",
"Command to use for building the Sphinx documentation.",
"sphinx-build", PathVariable.PathAccept),
Option(
"sphinx_options",
"""Options passed to the 'sphinx_cmd' command line. Separate multiple
options with spaces, for example, "-W --keep-going".""",
"-W --keep-going"),
BoolOption(
"example_data",
"""Install data files used in examples. These files will be accessible on the
Cantera data path using a prefix, such as 'example_data/mech.yaml'""",
True,
),
EnumOption(
"system_eigen",
"""Select whether to use Eigen from a system installation ('y'), from a
Git submodule ('n'), or to decide automatically ('default'). If Eigen
is not installed directly into a system include directory, for example, it
is installed in '/opt/include/eigen3/Eigen', then you will need to add
'/opt/include/eigen3' to 'extra_inc_dirs'.
""",
"default", ("default", "y", "n")),
EnumOption(
"system_fmt",
"""Select whether to use the fmt library from a system installation
('y'), from a Git submodule ('n'), or to decide automatically
('default'). If you do not want to use the Git submodule and fmt
is not installed directly into system include and library
directories, then you will need to add those directories to
'extra_inc_dirs' and 'extra_lib_dirs'. This installation of fmt
must include the shared version of the library, for example,
'libfmt.so'.""",
"default", ("default", "y", "n")),
EnumOption(
"hdf_support",
"""Select whether to support HDF5 container files natively ('y'), disable HDF5
support ('n'), or to decide automatically based on the system configuration
('default'). Native HDF5 support uses the HDF5 library as well as the
header-only HighFive C++ wrapper (see option 'system_highfive'). Specifying
'hdf_include' or 'hdf_libdir' changes the default to 'y'.""",
"default", ("default", "y", "n")),
PathOption(
"hdf_include",
"""The directory where the HDF5 header files are installed. This should be the
directory that contains files 'H5Version.h' and 'H5Public.h', amongst others.
Not needed if the headers are installed in a standard location, for example,
'/usr/include'.""",
"", PathVariable.PathAccept),
PathOption(
"hdf_libdir",
"""The directory where the HDF5 libraries are installed. Not needed if the
libraries are installed in a standard location, for example, '/usr/lib'.""",
"", PathVariable.PathAccept),
EnumOption(
"system_highfive",
"""Select whether to use HighFive from a system installation ('y'), from a
Git submodule ('n'), or to decide automatically ('default'). If HighFive
is not installed directly into a system include directory, for example, it
is installed in '/opt/include/HighFive', then you will need to add
'/opt/include/HighFive' to 'extra_inc_dirs'.""",
"default", ("default", "y", "n")),
EnumOption(
"system_yamlcpp",
"""Select whether to use the yaml-cpp library from a system installation
('y'), from a Git submodule ('n'), or to decide automatically
('default'). If yaml-cpp is not installed directly into system
include and library directories, then you will need to add those
directories to 'extra_inc_dirs' and 'extra_lib_dirs'.""",
"default", ("default", "y", "n")),
EnumOption(
"system_sundials",
"""Select whether to use SUNDIALS from a system installation ('y'), from
a Git submodule ('n'), or to decide automatically ('default').
Specifying 'sundials_include' or 'sundials_libdir' changes the
default to 'y'.""",
"default", ("default", "y", "n")),
PathOption(
"sundials_include",
"""The directory where the SUNDIALS header files are installed. This
should be the directory that contains the "cvodes", "nvector", etc.
subdirectories. Not needed if the headers are installed in a
standard location, for example, '/usr/include'.""",
"", PathVariable.PathAccept),
PathOption(
"sundials_libdir",
"""The directory where the SUNDIALS static libraries are installed.
Not needed if the libraries are installed in a standard location,
for example, '/usr/lib'.""",
"", PathVariable.PathAccept),
EnumOption(
"system_blas_lapack",
"""Select whether to use BLAS/LAPACK from a system installation ('y'), use
Eigen linear algebra support ('n'), or to decide automatically based on
libraries detected on the system ('default'). Specifying 'blas_lapack_libs'
or 'blas_lapack_dir' changes the default to 'y'. On macOS, the 'default'
option uses the Accelerate framework, whereas on other operating systems the
preferred option depends on the CPU manufacturer. In general, OpenBLAS
('openblas') is prioritized over standard libraries ('lapack,blas'), with
Eigen being used if no suitable BLAS/LAPACK libraries are detected. On Intel
CPUs, MKL (Windows: 'mkl_rt' / Linux: 'mkl_rt,dl') has the highest priority,
followed by the other options. Note that Eigen is required whether or not
BLAS/LAPACK libraries are used.""",
"default", ("default", "y", "n")),
Option(
"blas_lapack_libs",
"""Cantera can use BLAS and LAPACK libraries installed on your system if you
have optimized versions available (see option 'system_blas_lapack'). To use
specific versions of BLAS and LAPACK, set 'blas_lapack_libs' to the the list
of libraries that should be passed to the linker, separated by commas, for
example, "lapack,blas" or "lapack,f77blas,cblas,atlas".""",
""),
PathOption(
"blas_lapack_dir",
"""Directory containing the libraries specified by 'blas_lapack_libs'. Not
needed if the libraries are installed in a standard location, for example,
'/usr/lib'.""",
"", PathVariable.PathAccept),
BoolOption(
"lapack_ftn_trailing_underscore",
"""Controls whether the LAPACK functions have a trailing underscore
in the Fortran libraries.""",
True),
BoolOption(
"lapack_ftn_string_len_at_end",
"""Controls whether the LAPACK functions have the string length
argument at the end of the argument list ('yes') or after
each argument ('no') in the Fortran libraries.""",
True),
EnumOption(
"googletest",
"""Select whether to use gtest/gmock from system
installation ('system'), from a Git submodule ('submodule'), to decide
automatically ('default') or don't look for gtest/gmock ('none')
and don't run tests that depend on gtest/gmock.""",
"default", ("default", "system", "submodule", "none")),
Option(
"env_vars",
"""Environment variables to propagate through to SCons. Either the
string 'all' or a comma separated list of variable names, for example,
'LD_LIBRARY_PATH,HOME'.""",
"PATH,LD_LIBRARY_PATH,DYLD_LIBRARY_PATH,PYTHONPATH,USERPROFILE"),
BoolOption(
"use_pch",
"Use a precompiled-header to speed up compilation",
True),
Option(
"pch_flags",
"Compiler flags when using precompiled-header.",
{
"cl": "/FIpch/system.h",
"gcc": "-include src/pch/system.h",
"icx": "-include-pch src/pch/system.h.gch",
"clang": "-include-pch src/pch/system.h.gch",
"default": "",
}),
Option(
"thread_flags",
"Compiler and linker flags for POSIX multithreading support.",
{"Windows": "", "macOS": "", "default": "-pthread"}),
BoolOption(
"optimize",
"""Enable extra compiler optimizations specified by the
'optimize_flags' variable, instead of the flags specified by the
'no_optimize_flags' variable.""",
True),
Option(
"optimize_flags",
"Additional compiler flags passed to the C/C++ compiler when 'optimize=yes'.",
{
"cl": "/O2",
"icx": "-O3 -fp-model precise", # cannot assume finite math
"gcc": "-O3 -Wno-inline",
"default": "-O3",
}),
Option(
"no_optimize_flags",
"Additional compiler flags passed to the C/C++ compiler when 'optimize=no'.",
{"cl": "/Od /Ob0", "default": "-O0"}),
BoolOption(
"debug",
"Enable compiler debugging symbols.",
True),
Option(
"debug_flags",
"Additional compiler flags passed to the C/C++ compiler when 'debug=yes'.",
{"cl": "/Zi /Fd${TARGET}.pdb", "default": "-g"}),
Option(
"no_debug_flags",
"Additional compiler flags passed to the C/C++ compiler when 'debug=no'.",
""),
Option(
"debug_linker_flags",
"Additional options passed to the linker when 'debug=yes'.",
{"cl": "/DEBUG", "default": ""}),
Option(
"no_debug_linker_flags",
"Additional options passed to the linker when 'debug=no'.",
""),
Option(
"warning_flags",
"""Additional compiler flags passed to the C/C++ compiler to enable
extra warnings. Used only when compiling source code that is part
of Cantera (for example, excluding code in the 'ext' directory).""",
{
"cl": "/W3",
"default": "-Wall",
}),
Option(
"extra_inc_dirs",
"""Additional directories to search for header files, with multiple
directories separated by colons (*nix, macOS) or semicolons (Windows).
If an active 'conda' environment is detected, the corresponding include
path is automatically added.""",
""),
Option(
"extra_lib_dirs",
"""Additional directories to search for libraries, with multiple
directories separated by colons (*nix, macOS) or semicolons (Windows).
If an active 'conda' environment is detected, the corresponding library
path is automatically added.""",
""),
PathOption(
"boost_inc_dir",
"""Location of the Boost header files. Not needed if the headers are
installed in a standard location, for example, '/usr/include'.""",
"",
PathVariable.PathAccept),
PathOption(
"stage_dir",
"""Directory relative to the Cantera source directory to be
used as a staging area for building for example, a Debian
package. If specified, 'scons install' will install files
to 'stage_dir/prefix/...'.""",
"",
PathVariable.PathAccept),
EnumOption(
"logging",
"""Select logging level for SCons output. By default, logging messages use
the 'info' level for 'scons build' and the 'warning' level for all other
commands. In case the SCons option '--silent' is passed, all messages below
the 'error' level are suppressed.""",
"default", ("debug", "info", "warning", "error", "default")),
Option(
"gtest_flags",
"""Additional options passed to each GTest test suite, for example,
'--gtest_filter=*pattern*'. Separate multiple options with spaces.""",
""),
BoolOption(
"renamed_shared_libraries",
"""If this option is turned on, the shared libraries that are created
will be renamed to have a '_shared' extension added to their base name.
If not, the base names will be the same as the static libraries.
In some cases this simplifies subsequent linking environments with
static libraries and avoids a bug with using valgrind with
the '-static' linking flag.""",
True),
BoolOption(
"versioned_shared_library",
"""If enabled, create a versioned shared library, with symlinks to the
more generic library name, for example, 'libcantera_shared.so.2.5.0' as the
actual library and 'libcantera_shared.so' and 'libcantera_shared.so.2'
as symlinks.""",
{"mingw": False, "cl": False, "default": True}),
BoolOption(
"use_rpath_linkage",
"""If enabled, link to all shared libraries using 'rpath', that is, a fixed
run-time search path for dynamic library loading.""",
True),
Option(
"openmp_flag",
"""Compiler flags used for multiprocessing (only used to generate sample build
scripts).""",
{
"cl": "/openmp",
"icx": "-qopenmp",
"apple-clang": "-Xpreprocessor -fopenmp",
"default": "-fopenmp",
}),
EnumOption(
"layout",
"""The layout of the directory structure. 'standard' installs files to
several subdirectories under 'prefix', for example, 'prefix/bin',
'prefix/include/cantera', 'prefix/lib' etc. This layout is best used in
conjunction with "prefix='/usr/local'". 'compact' puts all installed files
in the subdirectory defined by 'prefix'. This layout is best with a prefix
like '/opt/cantera'. If the Python executable found during compilation is
managed by 'conda', the layout will default to 'conda' irrespective of
operating system. For the 'conda' layout, the Python package as well as all
libraries and header files are installed into the active 'conda' environment.
Input data, samples, and other files are installed in the 'shared/cantera'
subdirectory of the active 'conda' environment.""",
{"Windows": "compact", "default": "standard"},
("standard", "compact", "conda")),
BoolOption(
"package_build",
"""Used in combination with packaging tools (example: 'conda-build'). If
enabled, the installed package will be independent from host and build
environments, with all external library and include paths removed. Packaged
C++ and Fortran samples assume that users will compile with local SDKs, which
should be backwards compatible with the tools used for the build process.
""",
False),
BoolOption(
"fast_fail_tests",
"If enabled, tests will exit at the first failure.",
False),
BoolOption(
"skip_slow_tests",
"""If enabled, skip a subset of tests that are known to have long runtimes.
Skipping these may be desirable when running with options that cause tests
to run slowly, like disabling optimization or activating code profiling.""",
False),
BoolOption(
"show_long_tests",
"If enabled, duration of slowest tests will be shown.",
False),
BoolOption(
"verbose_tests",
"If enabled, verbose test output will be shown.",
False),
]
config = Configuration()
if "help" in COMMAND_LINE_TARGETS:
AddOption(
"--options", dest="options",
action="store_true", help="Print description of available options")
AddOption(
"--list-options", dest="list",
action="store_true", help="List available options")
AddOption(
"--restructured-text", dest="rest",
action="store_true", help="Format defaults as reST")
AddOption(
"--option", dest="option", nargs=1, type="string",
action="store", help="Output help for specific option")
AddOption(
"--defaults", dest="defaults",
action="store_true", help="All defaults (CLI only)")
AddOption(
"--dev", dest="dev",
action="store_true", help="Append -dev (reST only)")
AddOption(
"--output", dest="output", nargs=1, type="string",
action="store", help="Output file (reST only)")
list = GetOption("list")
rest = GetOption("rest")
defaults = GetOption("defaults") is not None
options = GetOption("options")
option = GetOption("option")
if not (list or rest or defaults or options or option):
# show basic help information
logger.status(__doc__, print_level=False)
sys.exit(0)
if defaults or rest or list:
config.add(windows_options)
config.add(config_options)
if list:
# show formatted list of options
logger.status("\nConfiguration options for building Cantera:\n", print_level=False)
logger.status(config.list_options() + "\n", print_level=False)
sys.exit(0)
if defaults:
try:
# print default values: if option is None, show description for all
# available options, otherwise show description for specified option
logger.status(config.help(option), print_level=False)
sys.exit(0)
except KeyError as err:
message = "Run 'scons help --list-options' to see available options."
logger.error(f"{err}.\n{message}")
sys.exit(1)
dev = GetOption("dev") is not None
try:
# format default values as reST: if option is None, all descriptions are
# rendered, otherwise only the description of specified option is shown
message = config.to_rest(option, dev=dev)
except KeyError as err:
message = "Run 'scons help --list-options' to see available options."
logger.error(f"{err}.\n{message}")
sys.exit(1)
output = GetOption("output")
if output:
# write output to file
output_file = Path(output).with_suffix(".rst")
with open(output_file, "w+") as fid:
fid.write(message)
logger.status(f"Done writing output options to {output_file!r}.",
print_level=False)
else:
logger.status(message, print_level=False)
sys.exit(0)
if "sphinx" in COMMAND_LINE_TARGETS:
# need to buffer all options before system-dependent selections are applied
windows_options_full = deepcopy(windows_options)
config_options_full = deepcopy(config_options)
# **************************************
# *** Read user-configurable options ***
# **************************************
opts = Variables("cantera.conf")
extraEnvArgs = {}
if os.name == "nt":
config.add(windows_options)
config.add(config_options)
config["prefix"].default = (Path(os.environ["ProgramFiles"]) / "Cantera").as_posix()
config.select("Windows")
# On Windows, target the same architecture as the current copy of Python,
# unless the user specified another option.
if "64 bit" not in sys.version:
config["target_arch"].default = "x86"
opts.AddVariables(*config.to_scons(("msvc_version", "msvc_toolset_version", "target_arch")))
windows_compiler_env = Environment()
opts.Update(windows_compiler_env)
# Make an educated guess about the right default compiler
if which("g++") and not which("cl.exe"):
config["toolchain"].default = "mingw"
if windows_compiler_env["msvc_version"] or windows_compiler_env["msvc_toolset_version"]:
config["toolchain"].default = "msvc"
opts.AddVariables(*config.to_scons("toolchain"))
opts.Update(windows_compiler_env)
if windows_compiler_env["toolchain"] == "msvc":
toolchain = ["default"]
if windows_compiler_env["msvc_version"]:
extraEnvArgs["MSVC_VERSION"] = windows_compiler_env["msvc_version"]
if windows_compiler_env["msvc_toolset_version"]:
extraEnvArgs["MSVC_TOOLSET_VERSION"] = windows_compiler_env["msvc_toolset_version"]
msvc_version = (windows_compiler_env["msvc_version"] or
windows_compiler_env.get("MSVC_VERSION"))
logger.info(f"Compiling with MSVC version {msvc_version}", print_level=False)
msvc_toolset = (windows_compiler_env["msvc_toolset_version"] or
windows_compiler_env.get("MSVC_TOOLSET_VERSION") or
f"{msvc_version} (default)")
logger.info(f"Compiling with MSVC toolset {msvc_toolset}", print_level=False)
elif windows_compiler_env["toolchain"] == "mingw":
toolchain = ["mingw", "f90"]
extraEnvArgs["F77"] = None
# Next line fixes https://github.com/SCons/scons/issues/2683
extraEnvArgs["WINDOWS_INSERT_DEF"] = 1
elif windows_compiler_env["toolchain"] == "intel":
toolchain = ["intelc"] # note: untested
extraEnvArgs["TARGET_ARCH"] = windows_compiler_env["target_arch"]
logger.info(f"Compiling for architecture: {windows_compiler_env['target_arch']}",
print_level=False)
logger.info(f"Compiling using the following toolchain(s): {repr(toolchain)}",
print_level=False)
else:
config.add(config_options)
toolchain = ["default"]
env = Environment(tools=toolchain+["textfile", "subst", "recursiveInstall", "UnitsInterfaceBuilder", "wix", "gch"],
ENV={"PATH": os.environ["PATH"]},
toolchain=toolchain,
**extraEnvArgs)
# Copy variables we defined earlier into the construction environment.
# We needed them earlier to support building the sdist without doing
# any other unnecessary config
env["cantera_version"] = cantera_version
env["cantera_pure_version"] = cantera_pure_version
env["cantera_short_version"] = cantera_short_version
env["git_commit"] = cantera_git_commit
env["OS"] = platform.system()
env["OS_BITS"] = int(platform.architecture()[0][:2])
if "cygwin" in env["OS"].lower():
logger.error(f"Error: Operating system {os.name!r} is no longer supported.")
sys.exit(1)
if "FRAMEWORKS" not in env:
env["FRAMEWORKS"] = []
if os.name == "nt":
env["INSTALL_MANPAGES"] = False
# Fixes a linker error in Windows
if "TMP" in os.environ:
env["ENV"]["TMP"] = os.environ["TMP"]
# Fixes issues with Python subprocesses. See http://bugs.python.org/issue13524
env["ENV"]["SystemRoot"] = os.environ["SystemRoot"]
# Fix an issue with Unicode sneaking into the environment on Windows
for key,val in env["ENV"].items():
env["ENV"][key] = str(val)
else:
env["INSTALL_MANPAGES"] = True
add_RegressionTest(env)
opts.AddVariables(*config.to_scons(["AR", "CC", "CXX"], env=env))
opts.Update(env)
# Check if this is actually Apple's clang on macOS
env["using_apple_clang"] = False
if env["OS"] == "Darwin":
result = subprocess.check_output([env.subst("$CC"), "--version"]).decode("utf-8")
if "clang" in result.lower() and ("Xcode" in result or "Apple" in result):
env["using_apple_clang"] = True
config.select("apple-clang")
if "gcc" in env.subst("$CC") or "gnu-cc" in env.subst("$CC"):
config.select("gcc")
elif env["CC"] == "cl": # Visual Studio
config.select("cl")
elif "icc" in env.subst("$CC"):
logger.error("The deprecated Intel compiler suite (icc/icpc) is no longer supported")
elif "icx" in env.subst("$CC"):
config.select("icx")
elif "clang" in env.subst("$CC"):
config.select("clang")
else:
# Assume a GCC compatible compiler if nothing else
logger.warning(f"Unrecognized C compiler {env['CC']!r}")
config.select("gcc")
if env["OS"] == "Windows":
config.select("Windows")
elif env["OS"] == "Darwin":
config.select("macOS")
# SHLIBVERSION fails with MinGW: http://scons.tigris.org/issues/show_bug.cgi?id=3035
if "mingw" in env["toolchain"] :
config.select("mingw")
config.select("default")
config["python_cmd"].default = sys.executable
opts.AddVariables(*config.to_scons())
opts.Update(env)
opts.Save('cantera.conf', env)
# TODO: Remove after Cantera 3.1, when the minimal option is removed from the
# configuration.
if env["python_package"] == "minimal":
logger.error(
"The 'minimal' option for the Python package was removed in Cantera 3.1. "
"Please build the full interface by passing 'python_package=y' or turn off the "
"interface with 'python_package=n'"
)
sys.exit(1)
# Expand ~/ and environment variables used in cantera.conf (variables used on
# the command line will be expanded by the shell)
for option in opts.keys():
original = env[option]
if isinstance(original, str):
modified = os.path.expandvars(os.path.expanduser(env[option]))
if original != modified:
logger.info(f"Expanding {original!r} to {modified!r}")
env[option] = modified
if "help" in COMMAND_LINE_TARGETS:
option = GetOption("option")
try:
# print configuration: if option is None, description is shown for all
# options; otherwise description is shown for specified option
logger.status(config.help(option, env=env), print_level=False)
sys.exit(0)
except KeyError as err:
message = "Run 'scons help --list-options' to see available options."
logger.error(f"{err}.\n{message}")
sys.exit(1)
if 'doxygen' in COMMAND_LINE_TARGETS:
env['doxygen_docs'] = True
if 'sphinx' in COMMAND_LINE_TARGETS:
env['sphinx_docs'] = True
for arg in ARGUMENTS:
if arg not in config:
logger.error(f"Encountered unexpected command line option: {arg!r}")
sys.exit(1)
# Store full config for doc build
if env['sphinx_docs']: