From 600323f2421b40b38fa74527ccae801eb01efe68 Mon Sep 17 00:00:00 2001 From: Ray Speth Date: Wed, 13 Sep 2023 14:11:15 -0400 Subject: [PATCH 01/22] [Doc] Minimal working sphinx-gallery integration This includes just the Python "kinetics" examples to start --- doc/sphinx/conf.py | 12 ++++++++++++ doc/sphinx/index.rst | 2 ++ samples/python/README.rst | 2 ++ samples/python/kinetics/README.rst | 2 ++ samples/python/kinetics/blowers_masel.py | 3 +++ samples/python/kinetics/custom_reactions.py | 3 +++ samples/python/kinetics/extract_submechanism.py | 3 +++ samples/python/kinetics/mechanism_reduction.py | 3 +++ samples/python/kinetics/reaction_path.py | 3 ++- 9 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 samples/python/README.rst create mode 100644 samples/python/kinetics/README.rst diff --git a/doc/sphinx/conf.py b/doc/sphinx/conf.py index 6e43679cb6..4cf7b4594f 100644 --- a/doc/sphinx/conf.py +++ b/doc/sphinx/conf.py @@ -42,8 +42,20 @@ 'sphinxarg.ext', 'sphinxcontrib.doxylink', 'sphinx.ext.intersphinx', + 'sphinx_gallery.gen_gallery', ] +sphinx_gallery_conf = { + 'filename_pattern': '\.py', + 'image_srcset': ["2x"], + 'examples_dirs': [ + '../../samples/python/', + ], + 'gallery_dirs': [ + 'examples/examples', + ], +} + autodoc_default_options = { 'members': True, 'show-inheritance': True, diff --git a/doc/sphinx/index.rst b/doc/sphinx/index.rst index 9b6dc882ed..a08cc11b13 100644 --- a/doc/sphinx/index.rst +++ b/doc/sphinx/index.rst @@ -14,3 +14,5 @@ format. yaml/index cython/index matlab/index + + examples/python/index diff --git a/samples/python/README.rst b/samples/python/README.rst new file mode 100644 index 0000000000..1bc42ffd08 --- /dev/null +++ b/samples/python/README.rst @@ -0,0 +1,2 @@ +Python Examples +=============== diff --git a/samples/python/kinetics/README.rst b/samples/python/kinetics/README.rst new file mode 100644 index 0000000000..6a46991bd0 --- /dev/null +++ b/samples/python/kinetics/README.rst @@ -0,0 +1,2 @@ +Kinetics +-------- diff --git a/samples/python/kinetics/blowers_masel.py b/samples/python/kinetics/blowers_masel.py index bc8c41c5af..c1c5f97b8e 100644 --- a/samples/python/kinetics/blowers_masel.py +++ b/samples/python/kinetics/blowers_masel.py @@ -1,4 +1,7 @@ """ +Blowers-Masel reaction rates +============================ + A simple example to demonstrate the difference between Blowers-Masel reaction and elementary reaction. diff --git a/samples/python/kinetics/custom_reactions.py b/samples/python/kinetics/custom_reactions.py index 6aefffe351..b46d78c049 100644 --- a/samples/python/kinetics/custom_reactions.py +++ b/samples/python/kinetics/custom_reactions.py @@ -1,4 +1,7 @@ """ +Custom reaction rates +===================== + An example demonstrating how to use custom reaction objects. For benchmark purposes, an ignition test is run to compare simulation times. diff --git a/samples/python/kinetics/extract_submechanism.py b/samples/python/kinetics/extract_submechanism.py index 2d02ee6c38..e5d8c56ee5 100644 --- a/samples/python/kinetics/extract_submechanism.py +++ b/samples/python/kinetics/extract_submechanism.py @@ -1,4 +1,7 @@ """ +Extracting a sub-mechanism +========================== + An example demonstrating how to use Species and Reaction objects to programmatically extract a reaction submechanism. In this example, the CO/H2 oxidation reactions are extracted from the GRI 3.0 mechanism. diff --git a/samples/python/kinetics/mechanism_reduction.py b/samples/python/kinetics/mechanism_reduction.py index 28ee8a9f50..0a2425adb3 100644 --- a/samples/python/kinetics/mechanism_reduction.py +++ b/samples/python/kinetics/mechanism_reduction.py @@ -1,4 +1,7 @@ """ +Mechanism reduction +=================== + A simplistic approach to mechanism reduction which demonstrates Cantera's features for dynamically manipulating chemical mechanisms. diff --git a/samples/python/kinetics/reaction_path.py b/samples/python/kinetics/reaction_path.py index d5d1a16f1b..2afb64050c 100644 --- a/samples/python/kinetics/reaction_path.py +++ b/samples/python/kinetics/reaction_path.py @@ -1,5 +1,6 @@ """ -Viewing a reaction path diagram. +Viewing a reaction path diagram +=============================== This script uses Graphviz to generate an image. You must have Graphviz installed and the program 'dot' must be on your path for this example to work. From b517f1abc6f94e804311b2ca2c52a7b7003ba443 Mon Sep 17 00:00:00 2001 From: Ray Speth Date: Wed, 13 Sep 2023 19:40:05 -0400 Subject: [PATCH 02/22] [Doc] Build Sphinx docs and run gallery samples in build dir Sphinx-gallery creates new .rst files alongside existing manually maintained documentation, and runs the samples in-place, generating their output files in the source tree. Moving this all to the build directory lets us keep the repo clean. --- .gitignore | 2 -- doc/SConscript | 20 +++++++++++++------- doc/doxygen/Doxyfile | 4 ++-- doc/sphinx/conf.py | 10 +++++----- 4 files changed, 20 insertions(+), 16 deletions(-) diff --git a/.gitignore b/.gitignore index 33b3bd9bc4..40eeedad78 100644 --- a/.gitignore +++ b/.gitignore @@ -51,5 +51,3 @@ environment.y* coverage/ coverage.info .coverage -doc/sphinx/matlab/*.rst -!doc/sphinx/matlab/index.rst diff --git a/doc/SConscript b/doc/SConscript index b4204bc59c..971fbc166e 100644 --- a/doc/SConscript +++ b/doc/SConscript @@ -97,7 +97,7 @@ def get_function_name(function_string): return sig if localenv['doxygen_docs']: - docs = build(localenv.Command('#build/docs/doxygen/html/index.html', + docs = build(localenv.Command('#build/doc/doxygen/html/index.html', 'doxygen/Doxyfile', 'doxygen $SOURCE')) env.Depends(docs, env.Glob('#doc/doxygen/*') + multi_glob(env, '#include/cantera', 'h') + @@ -106,20 +106,26 @@ if localenv['doxygen_docs']: env.Alias('doxygen', docs) install(localenv.RecursiveInstall, '$inst_docdir/doxygen/html', - '#/build/docs/doxygen/html', exclude=['\\.map', '\\.md5']) + '#/build/doc/doxygen/html', exclude=['\\.map', '\\.md5']) if localenv['sphinx_docs']: def build_sphinx(target, source, env): cmd = [env['sphinx_cmd']] + env['sphinx_options'].split() - cmd += ('-b', 'html', '-d', 'build/docs/sphinx/doctrees', 'doc/sphinx', - 'build/docs/sphinx/html') + cmd += ('-b', 'html', '-d', 'build/doc/sphinx/doctrees', 'build/doc/sphinx', + 'build/doc/sphinx/html') code = subprocess.call(cmd, env=env['ENV']) if code: raise Errors.BuildError(target, action=env['sphinx_cmd']) - sphinxdocs = build(localenv.Command('#build/doc/sphinx/html/index.html', + # RecursiveInstall knows to copy modified files, unlike Copy + copy_sphinx = localenv.RecursiveInstall("#build/doc/sphinx", "sphinx") + copy_samples = localenv.RecursiveInstall("#build/doc/samples", "#samples") + + sphinxdocs = build(localenv.Command('build/doc/sphinx/html/index.html', 'sphinx/conf.py', build_sphinx)) env.Alias('sphinx', sphinxdocs) + env.Depends(sphinxdocs, copy_sphinx) + env.Depends(sphinxdocs, copy_samples) env.Depends(sphinxdocs, env['python_module']) # Create a list of MATLAB classes to document. This uses the NamedTuple @@ -208,7 +214,7 @@ if localenv['sphinx_docs']: # every time the source is changed, we don't want to have to commit the # change in the rst file as well as the source - too much code churn. So # we use a template and a SubstFile directive. - c = tempenv.SubstFile('#doc/sphinx/matlab/%s.rst' % page.name, + c = tempenv.SubstFile('#build/doc/sphinx/matlab/%s.rst' % page.name, '#doc/sphinx/matlab/matlab-template.rst.in') build(c) localenv.Depends(sphinxdocs, c) @@ -217,4 +223,4 @@ if localenv['sphinx_docs']: if localenv['doxygen_docs']: localenv.Depends(sphinxdocs, docs) install(localenv.RecursiveInstall, '$inst_docdir/sphinx/html', - '#/build/docs/sphinx/html') + '#build/doc/sphinx/html') diff --git a/doc/doxygen/Doxyfile b/doc/doxygen/Doxyfile index 82b783c4a2..5d19f25530 100644 --- a/doc/doxygen/Doxyfile +++ b/doc/doxygen/Doxyfile @@ -58,7 +58,7 @@ PROJECT_LOGO = doc/sphinx/_static/images/cantera-icon.png # entered, it will be relative to the location where doxygen was started. If # left blank the current directory will be used. -OUTPUT_DIRECTORY = build/docs/doxygen +OUTPUT_DIRECTORY = build/doc/doxygen # If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub- # directories (in 2 levels) under the output directory of each output format and @@ -2197,7 +2197,7 @@ TAGFILES = # tag file that is based on the input files it reads. See section "Linking to # external documentation" for more information about the usage of tag files. -GENERATE_TAGFILE = build/docs/Cantera.tag +GENERATE_TAGFILE = build/doc/Cantera.tag # If the ALLEXTERNALS tag is set to YES, all external class will be listed in # the class index. If set to NO, only the inherited external classes will be diff --git a/doc/sphinx/conf.py b/doc/sphinx/conf.py index 4cf7b4594f..d61006c5fa 100644 --- a/doc/sphinx/conf.py +++ b/doc/sphinx/conf.py @@ -17,7 +17,7 @@ # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath('../../build/python')) +sys.path.insert(0, os.path.abspath('../../python')) sys.path.append(os.path.abspath('.')) sys.path.append(os.path.abspath('./exts')) @@ -49,10 +49,10 @@ 'filename_pattern': '\.py', 'image_srcset': ["2x"], 'examples_dirs': [ - '../../samples/python/', + '../samples/python/', ], 'gallery_dirs': [ - 'examples/examples', + 'examples/python', ], } @@ -99,7 +99,7 @@ def escape_splats(app, what, name, obj, options, lines): autoclass_content = 'both' doxylink = { - 'ct': (os.path.abspath('../../build/docs/Cantera.tag'), + 'ct': (os.path.abspath('../../doc/Cantera.tag'), '../../doxygen/html/') } @@ -134,7 +134,7 @@ def escape_splats(app, what, name, obj, options, lines): # |version| and |release|, also used in various other places throughout the # built documents. -configh = Path('../../include/cantera/base/config.h').read_text() +configh = Path('../../../include/cantera/base/config.h').read_text() # The short X.Y version. version = re.search('CANTERA_SHORT_VERSION "(.*?)"', configh).group(1) # The full version, including alpha/beta/rc tags. From 9b47e1da0382e910c8cc76948a11333e9ee5d889 Mon Sep 17 00:00:00 2001 From: Ray Speth Date: Thu, 14 Sep 2023 15:44:14 -0400 Subject: [PATCH 03/22] [Doc] Use sphinx-tags to enable finding examples by tag --- doc/sphinx/conf.py | 12 ++++++++++++ doc/sphinx/index.rst | 2 ++ samples/python/README.rst | 5 +++++ samples/python/kinetics/blowers_masel.py | 3 ++- samples/python/kinetics/custom_reactions.py | 3 ++- samples/python/kinetics/extract_submechanism.py | 3 ++- samples/python/kinetics/mechanism_reduction.py | 6 ++++-- samples/python/kinetics/reaction_path.py | 3 ++- 8 files changed, 31 insertions(+), 6 deletions(-) diff --git a/doc/sphinx/conf.py b/doc/sphinx/conf.py index d61006c5fa..234e7e77a3 100644 --- a/doc/sphinx/conf.py +++ b/doc/sphinx/conf.py @@ -43,6 +43,8 @@ 'sphinxcontrib.doxylink', 'sphinx.ext.intersphinx', 'sphinx_gallery.gen_gallery', + 'sphinx_tags', + 'sphinx_design', ] sphinx_gallery_conf = { @@ -56,6 +58,16 @@ ], } +# Options for sphinx_tags extension +tags_create_tags = True +tags_create_badges = True +tags_overview_title = "Index of example tags" +tags_page_title = "Tag" +tags_page_header = "Examples with this tag:" +tags_badge_colors = { + "Python": "secondary", +} + autodoc_default_options = { 'members': True, 'show-inheritance': True, diff --git a/doc/sphinx/index.rst b/doc/sphinx/index.rst index a08cc11b13..53639ad1ef 100644 --- a/doc/sphinx/index.rst +++ b/doc/sphinx/index.rst @@ -16,3 +16,5 @@ format. matlab/index examples/python/index + + _tags/tagsindex \ No newline at end of file diff --git a/samples/python/README.rst b/samples/python/README.rst index 1bc42ffd08..182e35f70d 100644 --- a/samples/python/README.rst +++ b/samples/python/README.rst @@ -1,2 +1,7 @@ Python Examples =============== + +.. seealso:: + + To find examples covering a specific topic, see the + :ref:`index of example tags `. diff --git a/samples/python/kinetics/blowers_masel.py b/samples/python/kinetics/blowers_masel.py index c1c5f97b8e..e26c9dff2b 100644 --- a/samples/python/kinetics/blowers_masel.py +++ b/samples/python/kinetics/blowers_masel.py @@ -19,7 +19,8 @@ change of a Blowers-Masel reaction with respect to the delta enthalpy of the reaction. Requires: cantera >= 2.6.0, matplotlib >= 2.0 -Keywords: kinetics, sensitivity analysis + +.. tags:: Python, kinetics, sensitivity analysis """ import cantera as ct diff --git a/samples/python/kinetics/custom_reactions.py b/samples/python/kinetics/custom_reactions.py index b46d78c049..6fe728afd2 100644 --- a/samples/python/kinetics/custom_reactions.py +++ b/samples/python/kinetics/custom_reactions.py @@ -7,7 +7,8 @@ For benchmark purposes, an ignition test is run to compare simulation times. Requires: cantera >= 3.0.0 -Keywords: kinetics, benchmarking, user-defined model + +.. tags:: Python, kinetics, benchmarking, user-defined model """ from timeit import default_timer diff --git a/samples/python/kinetics/extract_submechanism.py b/samples/python/kinetics/extract_submechanism.py index e5d8c56ee5..61ee31e987 100644 --- a/samples/python/kinetics/extract_submechanism.py +++ b/samples/python/kinetics/extract_submechanism.py @@ -11,7 +11,8 @@ contains all of the important species and reactions. Requires: cantera >= 2.6.0, matplotlib >= 2.0 -Keywords: kinetics, combustion, 1D flow, editing mechanisms, plotting + +.. tags:: Python, kinetics, combustion, 1D flow, editing mechanisms, plotting """ from timeit import default_timer diff --git a/samples/python/kinetics/mechanism_reduction.py b/samples/python/kinetics/mechanism_reduction.py index 0a2425adb3..605666876c 100644 --- a/samples/python/kinetics/mechanism_reduction.py +++ b/samples/python/kinetics/mechanism_reduction.py @@ -16,8 +16,10 @@ to adequately simulate the ignition delay problem. Requires: cantera >= 2.6.0, matplotlib >= 2.0 -Keywords: kinetics, combustion, reactor network, editing mechanisms, ignition delay, - plotting + + +.. tags:: Python, kinetics, combustion, reactor network, editing mechanisms, + ignition delay, plotting """ import cantera as ct diff --git a/samples/python/kinetics/reaction_path.py b/samples/python/kinetics/reaction_path.py index 2afb64050c..3b68f7cc14 100644 --- a/samples/python/kinetics/reaction_path.py +++ b/samples/python/kinetics/reaction_path.py @@ -8,7 +8,8 @@ using your operating system's package manager. Requires: cantera >= 2.5.0 -Keywords: kinetics, reaction path analysis, pollutant formation + +.. tags:: Python, kinetics, reaction path analysis, pollutant formation """ from subprocess import run From ae5165e522a179ed2ff1084dbb33cfa278ed3af9 Mon Sep 17 00:00:00 2001 From: Ray Speth Date: Thu, 14 Sep 2023 17:50:16 -0400 Subject: [PATCH 04/22] [Doc] Hide note about download link location --- doc/sphinx/_static/custom.css | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/doc/sphinx/_static/custom.css b/doc/sphinx/_static/custom.css index 18d81f5b40..c9a0bd6fce 100644 --- a/doc/sphinx/_static/custom.css +++ b/doc/sphinx/_static/custom.css @@ -2,3 +2,9 @@ p + div.math { /* Remove post-paragraph space ahead of equation to center vertically */ margin-top: -1.15em; } + +.sphx-glr-download-link-note { + /* Hide top-of-page note about download link at bottom */ + display: none; + visibility: hidden; +} From defa7a57b0952fda011d5eeb5e1ab27088683ef5 Mon Sep 17 00:00:00 2001 From: Ray Speth Date: Thu, 14 Sep 2023 17:50:42 -0400 Subject: [PATCH 05/22] [Doc] Link code in Python examples to API docs --- doc/sphinx/conf.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/doc/sphinx/conf.py b/doc/sphinx/conf.py index 234e7e77a3..bb55871827 100644 --- a/doc/sphinx/conf.py +++ b/doc/sphinx/conf.py @@ -56,6 +56,9 @@ 'gallery_dirs': [ 'examples/python', ], + 'reference_url': { + 'cantera': None, # 'None' means the locally-documented module + } } # Options for sphinx_tags extension From 1594684ee42b032952a63b6f062d887dfa2e3b70 Mon Sep 17 00:00:00 2001 From: Ray Speth Date: Thu, 14 Sep 2023 21:00:55 -0400 Subject: [PATCH 06/22] [Python] Avoid strange behavior from custom module loader This was causing problems with re-importing cantera.with_units.units while running the samples as part of the sphinx-gallery build --- interfaces/cython/cantera/_cantera.pyx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/interfaces/cython/cantera/_cantera.pyx b/interfaces/cython/cantera/_cantera.pyx index 93ea5c8bb3..24509c54da 100644 --- a/interfaces/cython/cantera/_cantera.pyx +++ b/interfaces/cython/cantera/_cantera.pyx @@ -23,11 +23,8 @@ class CythonPackageMetaPathFinder(importlib.abc.MetaPathFinder): return importlib.util.spec_from_loader(fullname, loader) -# injecting custom finder/loaders into sys.meta_path: -def bootstrap_cython_submodules(): - sys.meta_path.append(CythonPackageMetaPathFinder("cantera.")) - -bootstrap_cython_submodules() +# Inject custom finder/loaders into sys.meta_path: +sys.meta_path.append(CythonPackageMetaPathFinder("cantera.")) # Import the contents of the individual .pyx files from ._utils import * @@ -47,3 +44,6 @@ from .units import * from .yamlwriter import * from .constants import * from .preconditioners import * + +# Custom finder/loader no longer needed, so remove it +sys.meta_path.pop() From a0e0e618b2a3041c13c1cafa82c63c6377758647 Mon Sep 17 00:00:00 2001 From: Ray Speth Date: Tue, 19 Sep 2023 20:04:42 -0400 Subject: [PATCH 07/22] Set py:currentmodule to enable link resolution --- doc/sphinx/conf.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/doc/sphinx/conf.py b/doc/sphinx/conf.py index bb55871827..0cf4e1f15a 100644 --- a/doc/sphinx/conf.py +++ b/doc/sphinx/conf.py @@ -61,6 +61,15 @@ } } + +header_prefix = """ +.. py:currentmodule:: cantera + +""" + +import sphinx_gallery.gen_rst +sphinx_gallery.gen_rst.EXAMPLE_HEADER = header_prefix + sphinx_gallery.gen_rst.EXAMPLE_HEADER + # Options for sphinx_tags extension tags_create_tags = True tags_create_badges = True From 0fb9fceeaab1ee623dac888112ebd59b46b6b456 Mon Sep 17 00:00:00 2001 From: Ray Speth Date: Tue, 19 Sep 2023 20:05:04 -0400 Subject: [PATCH 08/22] [Doc] Remove secondary sidebar from example pages This sidebar usually only had a "get page source" link, which isn't very useful for autogenerated pages. --- doc/sphinx/conf.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/doc/sphinx/conf.py b/doc/sphinx/conf.py index 0cf4e1f15a..dba03b04d8 100644 --- a/doc/sphinx/conf.py +++ b/doc/sphinx/conf.py @@ -63,6 +63,8 @@ header_prefix = """ +:html_theme.sidebar_secondary.remove: + .. py:currentmodule:: cantera """ From e13599d1f2312c40a62a4dab302628d21b9f4ee3 Mon Sep 17 00:00:00 2001 From: Ray Speth Date: Tue, 19 Sep 2023 22:02:49 -0400 Subject: [PATCH 09/22] [Doc] Add remaining Python examples to sphinx-gallery Introduce a monkey patch to avoid executing specific examples that won't run under sphinx-gallery. --- doc/sphinx/conf.py | 37 ++++++++++++++++++- samples/python/multiphase/README.rst | 2 + samples/python/multiphase/adiabatic.py | 6 ++- .../python/multiphase/plasma_equilibrium.py | 6 ++- samples/python/onedim/README.rst | 2 + samples/python/onedim/adiabatic_flame.py | 6 ++- samples/python/onedim/burner_flame.py | 6 ++- samples/python/onedim/diffusion_flame.py | 6 ++- .../python/onedim/diffusion_flame_batch.py | 6 ++- .../onedim/diffusion_flame_extinction.py | 6 ++- samples/python/onedim/flame_fixed_T.py | 19 ++++++---- samples/python/onedim/flame_initial_guess.py | 6 ++- .../python/onedim/flamespeed_sensitivity.py | 6 ++- samples/python/onedim/ion_burner_flame.py | 6 ++- samples/python/onedim/ion_free_flame.py | 6 ++- .../onedim/premixed_counterflow_flame.py | 6 ++- .../onedim/premixed_counterflow_twin_flame.py | 13 +++++-- samples/python/onedim/stagnation_flame.py | 6 ++- samples/python/reactors/NonIdealShockTube.py | 7 +++- samples/python/reactors/PorousMediaBurner.py | 36 +++++++++--------- samples/python/reactors/README.rst | 2 + samples/python/reactors/combustor.py | 10 +++-- samples/python/reactors/custom.py | 6 ++- samples/python/reactors/custom2.py | 16 +++++--- samples/python/reactors/fuel_injection.py | 8 +++- samples/python/reactors/ic_engine.py | 6 ++- samples/python/reactors/mix1.py | 8 ++-- samples/python/reactors/periodic_cstr.py | 16 +++++--- samples/python/reactors/pfr.py | 6 ++- samples/python/reactors/piston.py | 13 +++++-- .../reactors/preconditioned_integration.py | 7 +++- samples/python/reactors/reactor1.py | 6 ++- samples/python/reactors/reactor2.py | 12 ++++-- samples/python/reactors/sensitivity1.py | 4 +- samples/python/reactors/surf_pfr.py | 13 ++++--- samples/python/reactors/surf_pfr_chain.py | 16 +++++--- .../surface_chemistry/1D_pfr_surfchem.py | 12 ++++-- samples/python/surface_chemistry/README.rst | 2 + .../surface_chemistry/catalytic_combustion.py | 4 +- .../python/surface_chemistry/diamond_cvd.py | 20 +++++----- .../surface_chemistry/lithium_ion_battery.py | 19 ++++++---- samples/python/surface_chemistry/sofc.py | 21 +++++++---- samples/python/thermo/README.rst | 2 + .../python/thermo/coverage_dependent_surf.py | 10 +++-- samples/python/thermo/critical_properties.py | 5 ++- samples/python/thermo/equivalenceRatio.py | 31 +++++++++++++--- samples/python/thermo/isentropic.py | 9 +++-- samples/python/thermo/isentropic_units.py | 9 +++-- samples/python/thermo/mixing.py | 10 +++-- samples/python/thermo/rankine.py | 6 ++- samples/python/thermo/rankine_units.py | 6 ++- samples/python/thermo/sound_speed.py | 6 ++- samples/python/thermo/sound_speed_units.py | 10 +++-- samples/python/thermo/vapordome.py | 12 +++++- samples/python/transport/README.rst | 2 + samples/python/transport/dusty_gas.py | 14 ++++--- .../transport/multiprocessing_viscosity.py | 8 +++- 57 files changed, 403 insertions(+), 158 deletions(-) create mode 100644 samples/python/multiphase/README.rst create mode 100644 samples/python/onedim/README.rst create mode 100644 samples/python/reactors/README.rst create mode 100644 samples/python/surface_chemistry/README.rst create mode 100644 samples/python/thermo/README.rst create mode 100644 samples/python/transport/README.rst diff --git a/doc/sphinx/conf.py b/doc/sphinx/conf.py index dba03b04d8..804bb9e6d7 100644 --- a/doc/sphinx/conf.py +++ b/doc/sphinx/conf.py @@ -61,6 +61,42 @@ } } +# Override sphinx-gallery's method for determining which examples should be executed. +# There's really no way to achieve this with the `filename_pattern` option, and +# `ignore_pattern` excludes the example entirely. +skip_run = { + # multiprocessing can't see functions defined in __main__ when run by + # sphinx-gallery, at least on macOS. + "multiprocessing_viscosity.py", + # __file__ deliberately not available when run by sphinx-gallery + "flame_fixed_T.py", +} + +def executable_script(src_file, gallery_conf): + """Validate if script has to be run according to gallery configuration. + + Parameters + ---------- + src_file : str + path to python script + + gallery_conf : dict + Contains the configuration of Sphinx-Gallery + + Returns + ------- + bool + True if script has to be executed + """ + filename = Path(src_file).name + if filename in skip_run: + return False + filename_pattern = gallery_conf["filename_pattern"] + execute = re.search(filename_pattern, src_file) and gallery_conf["plot_gallery"] + return execute + +import sphinx_gallery.gen_rst +sphinx_gallery.gen_rst.executable_script = executable_script header_prefix = """ :html_theme.sidebar_secondary.remove: @@ -69,7 +105,6 @@ """ -import sphinx_gallery.gen_rst sphinx_gallery.gen_rst.EXAMPLE_HEADER = header_prefix + sphinx_gallery.gen_rst.EXAMPLE_HEADER # Options for sphinx_tags extension diff --git a/samples/python/multiphase/README.rst b/samples/python/multiphase/README.rst new file mode 100644 index 0000000000..b6b2d91eff --- /dev/null +++ b/samples/python/multiphase/README.rst @@ -0,0 +1,2 @@ +Multiphase +---------- diff --git a/samples/python/multiphase/adiabatic.py b/samples/python/multiphase/adiabatic.py index 87e7319b21..41b65a22ef 100644 --- a/samples/python/multiphase/adiabatic.py +++ b/samples/python/multiphase/adiabatic.py @@ -1,9 +1,13 @@ """ +Adiabatic flame temperature including solid carbon formation +============================================================ + Adiabatic flame temperature and equilibrium composition for a fuel/air mixture as a function of equivalence ratio, including formation of solid carbon. Requires: cantera >= 2.5.0, matplotlib >= 2.0 -Keywords: equilibrium, combustion, multiphase + +.. tags:: Python, equilibrium, combustion, multiphase """ import cantera as ct diff --git a/samples/python/multiphase/plasma_equilibrium.py b/samples/python/multiphase/plasma_equilibrium.py index da7122ff8c..04a6d286ef 100644 --- a/samples/python/multiphase/plasma_equilibrium.py +++ b/samples/python/multiphase/plasma_equilibrium.py @@ -1,9 +1,13 @@ """ +Equilibrium with charged species and multiple condensed phases +============================================================== + An equilibrium example with charged species in the gas phase and multiple condensed phases. Requires: cantera >= 2.5.0, matplotlib >= 2.0 -Keywords: equilibrium, multiphase, plasma, saving output + +.. tags:: Python, equilibrium, multiphase, plasma, saving output """ import cantera as ct diff --git a/samples/python/onedim/README.rst b/samples/python/onedim/README.rst new file mode 100644 index 0000000000..1694c69de2 --- /dev/null +++ b/samples/python/onedim/README.rst @@ -0,0 +1,2 @@ +1D reacting flows +----------------- diff --git a/samples/python/onedim/adiabatic_flame.py b/samples/python/onedim/adiabatic_flame.py index f9363f6769..72e59856c6 100644 --- a/samples/python/onedim/adiabatic_flame.py +++ b/samples/python/onedim/adiabatic_flame.py @@ -1,9 +1,13 @@ """ +Laminar flame speed calculation +=============================== + A freely-propagating, premixed hydrogen flat flame with multicomponent transport properties. Requires: cantera >= 3.0 -Keywords: combustion, 1D flow, premixed flame, multicomponent transport, + +.. tags:: Python, combustion, 1D flow, premixed flame, multicomponent transport, saving output """ diff --git a/samples/python/onedim/burner_flame.py b/samples/python/onedim/burner_flame.py index f59f8023c0..99600b4201 100644 --- a/samples/python/onedim/burner_flame.py +++ b/samples/python/onedim/burner_flame.py @@ -1,8 +1,12 @@ """ +Burner-stabilized flame +======================= + A burner-stabilized lean premixed hydrogen-oxygen flame at low pressure. Requires: cantera >= 3.0 -Keywords: combustion, 1D flow, premixed flame, saving output, + +.. tags:: Python, combustion, 1D flow, premixed flame, saving output, multicomponent transport """ diff --git a/samples/python/onedim/diffusion_flame.py b/samples/python/onedim/diffusion_flame.py index 7b16ad12be..a5818cff5c 100644 --- a/samples/python/onedim/diffusion_flame.py +++ b/samples/python/onedim/diffusion_flame.py @@ -1,8 +1,12 @@ """ +Counterflow diffusion flame +=========================== + An opposed-flow ethane/air diffusion flame Requires: cantera >= 3.0, matplotlib >= 2.0 -Keywords: combustion, 1D flow, diffusion flame, strained flame, plotting, + +.. tags:: Python, combustion, 1D flow, diffusion flame, strained flame, plotting, saving output """ diff --git a/samples/python/onedim/diffusion_flame_batch.py b/samples/python/onedim/diffusion_flame_batch.py index c6c1dee879..33b4bcf682 100644 --- a/samples/python/onedim/diffusion_flame_batch.py +++ b/samples/python/onedim/diffusion_flame_batch.py @@ -2,6 +2,9 @@ # at https://cantera.org/license.txt for license and copyright information. """ +Scaling of diffusion flames with pressure and strain rate +========================================================= + This example creates two batches of counterflow diffusion flame simulations. The first batch computes counterflow flames at increasing pressure, the second at increasing strain rates. @@ -14,7 +17,8 @@ awkward pressure and strain rate, or to create the basis for a flamelet table. Requires: cantera >= 3.0, matplotlib >= 2.0 -Keywords: combustion, 1D flow, extinction, diffusion flame, strained flame, + +.. tags:: Python, combustion, 1D flow, extinction, diffusion flame, strained flame, saving output, plotting """ diff --git a/samples/python/onedim/diffusion_flame_extinction.py b/samples/python/onedim/diffusion_flame_extinction.py index 238a9c1b4a..5c6d75dc66 100644 --- a/samples/python/onedim/diffusion_flame_extinction.py +++ b/samples/python/onedim/diffusion_flame_extinction.py @@ -2,6 +2,9 @@ # at https://cantera.org/license.txt for license and copyright information. """ +Diffusion flame extinction strain rate +====================================== + This example computes the extinction point of a counterflow diffusion flame. A hydrogen-oxygen diffusion flame at 1 bar is studied. @@ -10,7 +13,8 @@ explanation. Also, please don't forget to cite it if you make use of it. Requires: cantera >= 3.0, matplotlib >= 2.0 -Keywords: combustion, 1D flow, diffusion flame, strained flame, extinction, + +.. tags:: Python, combustion, 1D flow, diffusion flame, strained flame, extinction, saving output, plotting """ diff --git a/samples/python/onedim/flame_fixed_T.py b/samples/python/onedim/flame_fixed_T.py index 8b4ca858f7..f95e3298c9 100644 --- a/samples/python/onedim/flame_fixed_T.py +++ b/samples/python/onedim/flame_fixed_T.py @@ -1,9 +1,13 @@ """ +Burner-stabilized flame with imposed temperature profile +======================================================== + A burner-stabilized, premixed methane/air flat flame with multicomponent transport properties and a specified temperature profile. Requires: cantera >= 3.0 -Keywords: combustion, 1D flow, burner-stabilized flame, premixed flame, plotting, + +.. tags:: Python, combustion, 1D flow, burner-stabilized flame, premixed flame, plotting, saving output """ @@ -12,7 +16,7 @@ import cantera as ct -################################################################ +# %% # parameter values p = ct.one_atm # pressure tburner = 373.7 # burner temperature @@ -25,10 +29,9 @@ loglevel = 1 # amount of diagnostic output (0 to 5) refine_grid = True # 'True' to enable refinement -################ create the gas object ######################## -# -# This object will be used to evaluate all thermodynamic, kinetic, and -# transport properties +# %% +# Create the gas object. This object will be used to evaluate all thermodynamic, +# kinetic, and transport properties gas = ct.Solution('gri30.yaml') # set its state to that of the unburned gas at the burner @@ -40,7 +43,8 @@ # set the mass flow rate at the burner f.burner.mdot = mdot -# read temperature vs. position data from a file. +# %% +# Read temperature vs. position data from a file. # The file is assumed to have one z, T pair per line, separated by a comma. # The data file must be stored in the same folder as this script. data_file = Path(__file__).parent.joinpath('tdata.dat') @@ -50,6 +54,7 @@ # set the temperature profile to the values read in f.flame.set_fixed_temp_profile(zloc, tvalues) +# %% # show the initial estimate for the solution f.show() diff --git a/samples/python/onedim/flame_initial_guess.py b/samples/python/onedim/flame_initial_guess.py index 4414a6f354..a66b42313a 100644 --- a/samples/python/onedim/flame_initial_guess.py +++ b/samples/python/onedim/flame_initial_guess.py @@ -1,10 +1,14 @@ """ +Saving, loading, and restarting 1D calculations +=============================================== + A freely-propagating, premixed methane-air flame. Examples of saving and loading a flame and restarting with different initial guesses. Requires: cantera >= 3.0 -Keywords: combustion, 1D flow, flame speed, premixed flame, saving output + +.. tags:: Python, combustion, 1D flow, flame speed, premixed flame, saving output """ import sys from pathlib import Path diff --git a/samples/python/onedim/flamespeed_sensitivity.py b/samples/python/onedim/flamespeed_sensitivity.py index be76729a1c..bdbaea11ad 100644 --- a/samples/python/onedim/flamespeed_sensitivity.py +++ b/samples/python/onedim/flamespeed_sensitivity.py @@ -1,10 +1,14 @@ """ +Laminar flame speed sensitivity analysis +======================================== + Sensitivity analysis for a freely-propagating, premixed methane-air flame. Computes the sensitivity of the laminar flame speed with respect to each reaction rate constant. Requires: cantera >= 2.5.0 -Keywords: combustion, 1D flow, flame speed, premixed flame, sensitivity analysis + +.. tags:: Python, combustion, 1D flow, flame speed, premixed flame, sensitivity analysis """ import cantera as ct diff --git a/samples/python/onedim/ion_burner_flame.py b/samples/python/onedim/ion_burner_flame.py index 18c1c2fbb9..418628691e 100644 --- a/samples/python/onedim/ion_burner_flame.py +++ b/samples/python/onedim/ion_burner_flame.py @@ -1,8 +1,12 @@ """ +Burner-stabilized flame including ionized species +================================================= + A burner-stabilized premixed methane-air flame with charged species. Requires: cantera >= 3.0 -Keywords: combustion, 1D flow, burner-stabilized flame, plasma, premixed flame + +.. tags:: Python, combustion, 1D flow, burner-stabilized flame, plasma, premixed flame """ from pathlib import Path diff --git a/samples/python/onedim/ion_free_flame.py b/samples/python/onedim/ion_free_flame.py index f3df6d1aee..3d33ce2c2e 100644 --- a/samples/python/onedim/ion_free_flame.py +++ b/samples/python/onedim/ion_free_flame.py @@ -1,8 +1,12 @@ """ +Freely-propagating flame with charged species +============================================= + A freely-propagating, premixed methane-air flat flame with charged species. Requires: cantera >= 3.0 -Keywords: combustion, 1D flow, burner-stabilized flame, plasma, premixed flame + +.. tags:: Python, combustion, 1D flow, burner-stabilized flame, plasma, premixed flame """ from pathlib import Path diff --git a/samples/python/onedim/premixed_counterflow_flame.py b/samples/python/onedim/premixed_counterflow_flame.py index 7d3f7f06fc..d2d67078a6 100644 --- a/samples/python/onedim/premixed_counterflow_flame.py +++ b/samples/python/onedim/premixed_counterflow_flame.py @@ -1,11 +1,13 @@ """ -An opposed-flow premixed strained flame +Opposed-flow premixed strained flame +==================================== This script simulates a lean hydrogen-oxygen flame stabilized in a strained flowfield, with an opposed flow consisting of equilibrium products. Requires: cantera >= 3.0 -Keywords: combustion, 1D flow, premixed flame, strained flame + +.. tags:: Python, combustion, 1D flow, premixed flame, strained flame """ from pathlib import Path diff --git a/samples/python/onedim/premixed_counterflow_twin_flame.py b/samples/python/onedim/premixed_counterflow_twin_flame.py index fa98d32873..df3630a494 100644 --- a/samples/python/onedim/premixed_counterflow_twin_flame.py +++ b/samples/python/onedim/premixed_counterflow_twin_flame.py @@ -1,10 +1,15 @@ """ -Simulate two counter-flow jets of reactants shooting into each other. This -simulation differs from the similar premixed_counterflow_flame.py example as the -latter simulates a jet of reactants shooting into products. +Symmetric premixed twin flame +============================= + +Simulate two counter-flow jets of reactants shooting into each other. This simulation +differs from the similar :doc:`premixed_counterflow_flame.py +` example as the latter simulates a jet of reactants +shooting into products. Requires: cantera >= 3.0 -Keywords: combustion, 1D flow, premixed flame, strained flame, plotting + +.. tags:: Python, combustion, 1D flow, premixed flame, strained flame, plotting """ import sys diff --git a/samples/python/onedim/stagnation_flame.py b/samples/python/onedim/stagnation_flame.py index 2086cd7fd4..7e85301d58 100644 --- a/samples/python/onedim/stagnation_flame.py +++ b/samples/python/onedim/stagnation_flame.py @@ -1,5 +1,6 @@ """ -A detached flat flame stabilized at a stagnation point +Detached flat flame stabilized at a stagnation point +==================================================== This script simulates a lean hydrogen-oxygen flame stabilized in a strained flowfield at an axisymmetric stagnation point on a non-reacting surface. The @@ -15,7 +16,8 @@ been previously. (To see this, try setting prune to zero.) Requires: cantera >= 3.0 -Keywords: combustion, 1D flow, premixed flame, strained flame + +.. tags:: Python, combustion, 1D flow, premixed flame, strained flame """ from pathlib import Path diff --git a/samples/python/reactors/NonIdealShockTube.py b/samples/python/reactors/NonIdealShockTube.py index 12d7893756..9227b8a84a 100644 --- a/samples/python/reactors/NonIdealShockTube.py +++ b/samples/python/reactors/NonIdealShockTube.py @@ -1,5 +1,7 @@ -# coding: utf-8 """ +Ignition delay time using the Redlich-Kwong real gas model +========================================================== + Ignition delay time computations in a high-pressure reflected shock tube reactor, comparing ideal gas and Redlich-Kwong real gas models. @@ -17,7 +19,8 @@ you have matplotlib (https://matplotlib.org/) installed. Requires: cantera >= 2.5.0, matplotlib >= 2.0 -Keywords: combustion, reactor network, non-ideal fluid, ignition delay, plotting + +.. tags:: Python, combustion, reactor network, non-ideal fluid, ignition delay, plotting """ # Dependencies: numpy, and matplotlib diff --git a/samples/python/reactors/PorousMediaBurner.py b/samples/python/reactors/PorousMediaBurner.py index 323e942e7e..89556f39cd 100644 --- a/samples/python/reactors/PorousMediaBurner.py +++ b/samples/python/reactors/PorousMediaBurner.py @@ -1,11 +1,9 @@ """ -Short description: reactor cascade model for reactive flows in inert porous media -based on extensible reactors. Showcases adding a temperature equation for a -solid-phase and custom heat transfer/radiation models. +Reactor cascade model for reactive flows in inert porous media +============================================================== -Code by Thorsten Zirwes and Guillaume Vignat -Stanford University & Karlsruhe Institute of Technology (KIT) -2023 +Showcases the use of `ExtensibleReactor` to add a temperature equation for a solid-phase +and custom heat transfer/radiation models. This code implements a reactor cascade model for the simulation of reactive flows in porous media. The gas mixture with fuel and oxidizer flows through @@ -23,9 +21,6 @@ a general way to support an arbitrary number of reactors and an arbitrary number of burner sections with different physical properties. -The implemented equations make use of Cantera's extensible reactor models. -Therefore, Cantera version 2.6.0 or higher is required. - The porous media burner considered in this example is a cylindrical tube filled three different porous materials: a porous ceramic made from a Yttria-stabilized Zirconia Alumina (YZA) section with length of 2 inches and pore density of 40 pores per @@ -35,14 +30,15 @@ made from silicon carbide (SiC) with 3 PPI is used and finally a 1 inch section of SiC with 10 PPI. A flame stabilizes at the interface between the YZA and 3 PPI SiC. +.. code:: none - |--- two inches --- | --- one inch ---| --- one inch --- | - __________________________________________________________ -fuel - + => YZA 40 PPI | SiC 3 PPI | SiC 10 PPI => burnt -air __________________________________________________________ gas + |--- two inches --- | --- one inch ---| --- one inch --- | + __________________________________________________________ + fuel + + => YZA 40 PPI | SiC 3 PPI | SiC 10 PPI => burnt + air __________________________________________________________ gas - inert flame location heat recirculation + inert flame location heat recirculation This example simplifies the complex interaction between heat transport in the gas-phase and solid-phase by using a reactor cascade. While key trends from the measurements can @@ -52,8 +48,9 @@ radiation. For more realistic and quantitative predictions, running 1D simulations with full radiation transport is required. -More details about the governing equations, submodels and physical setup and -corresponding experiments can be found in +Initial code by Thorsten Zirwes and Guillaume Vignat, Stanford University & Karlsruhe +Institute of Technology (KIT). More details about the governing equations, submodels and +physical setup and corresponding experiments can be found in Experimental and numerical investigation of flame stabilization and pollutant formation in matrix stabilized ammonia-hydrogen combustion, @@ -62,8 +59,9 @@ Combustion and Flame, 250 (https://doi.org/10.1016/j.combustflame.2023.112642) Requires: cantera >= 2.6.0, matplotlib >= 2.0 -Keywords: user-defined model, reactor network, combustion, porous media, heat transfer, - radiative heat transfer + +.. tags:: Python, user-defined model, reactor network, combustion, porous media, + heat transfer, radiative heat transfer """ import matplotlib.pyplot as plt diff --git a/samples/python/reactors/README.rst b/samples/python/reactors/README.rst new file mode 100644 index 0000000000..4c8863778a --- /dev/null +++ b/samples/python/reactors/README.rst @@ -0,0 +1,2 @@ +Reactor networks +---------------- diff --git a/samples/python/reactors/combustor.py b/samples/python/reactors/combustor.py index 89df4c5bd4..a8e38e31c8 100644 --- a/samples/python/reactors/combustor.py +++ b/samples/python/reactors/combustor.py @@ -1,4 +1,7 @@ """ +Combustor residence time +======================== + Calculate steady-state solutions for a combustor, modeled as a single well-stirred reactor, for different residence times. @@ -6,13 +9,14 @@ the effect of changing the residence time on completeness of reaction (through the burned gas temperature) and on the total heat release rate. -Demonstrates the use of a MassFlowController where the mass flow rate function +Demonstrates the use of a `MassFlowController` where the mass flow rate function depends on variables other than time by capturing these variables from the -enclosing scope. Also shows the use of a PressureController to create a constant +enclosing scope. Also shows the use of a `PressureController` to create a constant pressure reactor with a fixed volume. Requires: cantera >= 3.0, matplotlib >= 2.0 -Keywords: combustion, reactor network, well-stirred reactor, plotting + +.. tags:: Python, combustion, reactor network, well-stirred reactor, plotting """ import numpy as np diff --git a/samples/python/reactors/custom.py b/samples/python/reactors/custom.py index 911dc0d3fd..6f9128f7e7 100644 --- a/samples/python/reactors/custom.py +++ b/samples/python/reactors/custom.py @@ -1,4 +1,7 @@ """ +Integrating constant pressure ignition using SciPy +================================================== + Solve a constant pressure ignition problem where the governing equations are implemented in Python. @@ -10,7 +13,8 @@ methods as the Sundials CVODES solver used by Cantera. Requires: cantera >= 2.5.0, scipy >= 0.19, matplotlib >= 2.0 -Keywords: combustion, reactor network, ignition delay, user-defined model, plotting + +.. tags:: Python, combustion, reactor network, ignition delay, user-defined model, plotting """ import cantera as ct diff --git a/samples/python/reactors/custom2.py b/samples/python/reactors/custom2.py index 9c519f3274..947a11a84a 100644 --- a/samples/python/reactors/custom2.py +++ b/samples/python/reactors/custom2.py @@ -1,12 +1,15 @@ """ +Using `ExtensibleReactor` to implement wall inertia +=================================================== + Solve an ignition problem where the normal reactor governing equations are extended with additional equations implemented in Python. -This demonstrates an approach for solving problems where Cantera's built-in -reactor models are not sufficient for describing the system in question. Unlike -the 'custom.py' example, in this example Cantera's existing Reactor and -ReactorNet code is still used, with only the modifications to the standard -equations implemented in Python by extending the ExtensibleReactor class. +This demonstrates an approach for solving problems where Cantera's built-in reactor +models are not sufficient for describing the system in question. Unlike the +:doc:`custom.py ` example, in this example Cantera's existing `Reactor` and +`ReactorNet` code is still used, with only the modifications to the standard equations +implemented in Python by extending the `ExtensibleReactor` class. Wall objects in Cantera are normally massless, with the velocity either imposed or proportional to the pressure difference. Here, we simulate a wall where the @@ -15,7 +18,8 @@ variable to the reactor's state vector which represents the wall velocity. Requires: cantera >= 3.0, matplotlib >= 2.0 -Keywords: combustion, reactor network, user-defined model, plotting + +.. tags:: Python, combustion, reactor network, user-defined model, plotting """ import cantera as ct diff --git a/samples/python/reactors/fuel_injection.py b/samples/python/reactors/fuel_injection.py index 602f13ffa5..ceed82ce43 100644 --- a/samples/python/reactors/fuel_injection.py +++ b/samples/python/reactors/fuel_injection.py @@ -1,13 +1,17 @@ """ +Soot precursor formation with time-varying mass flow rate +========================================================= + Simulation of fuel injection into a vitiated air mixture to show formation of soot precursors. Demonstrates the use of a user-supplied function for the mass flow rate through -a MassFlowController, and the use of the SolutionArray class to store results +a `MassFlowController`, and the use of the `SolutionArray` class to store results during reactor network integration and use these results to generate plots. Requires: cantera >= 2.5.0, matplotlib >= 2.0 -Keywords: combustion, reactor network, kinetics, pollutant formation, plotting + +.. tags:: Python, combustion, reactor network, kinetics, pollutant formation, plotting """ import numpy as np diff --git a/samples/python/reactors/ic_engine.py b/samples/python/reactors/ic_engine.py index e7978b6409..99d05590dd 100644 --- a/samples/python/reactors/ic_engine.py +++ b/samples/python/reactors/ic_engine.py @@ -1,12 +1,14 @@ """ -Simulation of a (gaseous) Diesel-type internal combustion engine. +Diesel-type internal combustion engine simulation with gaseous fuel +=================================================================== The simulation uses n-Dodecane as fuel, which is injected close to top dead center. Note that this example uses numerous simplifying assumptions and thus serves for illustration purposes only. Requires: cantera >= 3.0, scipy >= 0.19, matplotlib >= 2.0 -Keywords: combustion, thermodynamics, internal combustion engine, + +.. tags:: Python, combustion, thermodynamics, internal combustion engine, thermodynamic cycle, reactor network, plotting, pollutant formation """ diff --git a/samples/python/reactors/mix1.py b/samples/python/reactors/mix1.py index 63920c6e4a..9cb34feb79 100644 --- a/samples/python/reactors/mix1.py +++ b/samples/python/reactors/mix1.py @@ -1,5 +1,6 @@ """ -Mixing two streams. +Mixing two streams +================== Since reactors can have multiple inlets and outlets, they can be used to implement mixers, splitters, etc. In this example, air and methane are mixed @@ -13,10 +14,11 @@ contain all species that might be present in any upstream reactor. Compare this approach for the transient problem to the method used for the -steady-state problem in thermo/mixing.py. +steady-state problem in :doc:`mixing.py <../thermo/mixing>`. Requires: cantera >= 2.5.0 -Keywords: thermodynamics, reactor network, mixture + +.. tags:: Python, thermodynamics, reactor network, mixture """ import cantera as ct diff --git a/samples/python/reactors/periodic_cstr.py b/samples/python/reactors/periodic_cstr.py index 9a8fd45f12..933deefb36 100644 --- a/samples/python/reactors/periodic_cstr.py +++ b/samples/python/reactors/periodic_cstr.py @@ -1,4 +1,7 @@ -""" +r""" +Continuously stirred tank reactor with periodic behavior +======================================================== + This example illustrates a continuously stirred tank reactor (CSTR) with steady inputs but periodic interior state. @@ -6,19 +9,22 @@ water. But since water has a large efficiency as a third body in the chain termination reaction - H + O2 + M = HO2 + M +.. math:: + + \mathrm{ H + O_2 + M \rightleftharpoons HO_2 + M } as soon as a significant amount of water is produced the reaction stops. After enough time has passed that the water is exhausted from the reactor, the mixture explodes again and the process repeats. This explanation can be verified by -decreasing the rate for reaction 7 in file h2o2.yaml and re-running the +decreasing the rate for reaction 7 in file ``h2o2.yaml`` and re-running the example. -Acknowledgments: The idea for this example and an estimate of the conditions +*Acknowledgments*: The idea for this example and an estimate of the conditions needed to see the oscillations came from Bob Kee, Colorado School of Mines Requires: cantera >= 2.5.0, matplotlib >= 2.0 -Keywords: combustion, reactor network, well-stirred reactor, plotting + +.. tags:: Python, combustion, reactor network, well-stirred reactor, plotting """ import cantera as ct diff --git a/samples/python/reactors/pfr.py b/samples/python/reactors/pfr.py index 84ea319a28..d59ca38224 100644 --- a/samples/python/reactors/pfr.py +++ b/samples/python/reactors/pfr.py @@ -1,10 +1,14 @@ """ +Plug flow reactor modeling approaches +===================================== + This example solves a plug-flow reactor problem of hydrogen-oxygen combustion. The PFR is computed by two approaches: The simulation of a Lagrangian fluid particle, and the simulation of a chain of reactors. Requires: cantera >= 3.0, matplotlib >= 2.0 -Keywords: combustion, reactor network, plug flow reactor + +.. tags:: Python, combustion, reactor network, plug flow reactor """ import cantera as ct diff --git a/samples/python/reactors/piston.py b/samples/python/reactors/piston.py index cf0a248d44..537dbac843 100644 --- a/samples/python/reactors/piston.py +++ b/samples/python/reactors/piston.py @@ -1,9 +1,14 @@ """ +Reactors separated by a moving piston +===================================== + Two reactors separated by a piston that moves with a speed proportional to the pressure difference between the reactors. -Gas 1: a stoichiometric H2/O2/Ar mixture -Gas 2: a wet CO/O2 mixture +- Gas 1: a stoichiometric H2/O2/Ar mixture +- Gas 2: a wet CO/O2 mixture + +.. code:: none ------------------------------------- | || | @@ -13,13 +18,15 @@ | || | ------------------------------------- + The two volumes are connected by an adiabatic free piston. The piston speed is proportional to the pressure difference between the two chambers. Note that each side uses a *different* reaction mechanism Requires: cantera >= 2.5.0, matplotlib >= 2.0 -Keywords: combustion, reactor network, plotting + +.. tags:: Python, combustion, reactor network, plotting """ import sys diff --git a/samples/python/reactors/preconditioned_integration.py b/samples/python/reactors/preconditioned_integration.py index 0ea0ded981..a177d4825d 100644 --- a/samples/python/reactors/preconditioned_integration.py +++ b/samples/python/reactors/preconditioned_integration.py @@ -1,10 +1,13 @@ -# -*- coding: utf-8 -*- """ +Acceleration of reactor integration using a sparse preconditioned solver +======================================================================== + Ideal gas, constant-pressure, adiabatic kinetics simulation that compares preconditioned and non-preconditioned integration of nDodecane. Requires: cantera >= 3.0.0, matplotlib >= 2.0 -Keywords: combustion, reactor network, preconditioner + +.. tags:: Python, combustion, reactor network, preconditioner """ import cantera as ct import numpy as np diff --git a/samples/python/reactors/reactor1.py b/samples/python/reactors/reactor1.py index 81831ac6fd..c37f94fa75 100644 --- a/samples/python/reactors/reactor1.py +++ b/samples/python/reactors/reactor1.py @@ -1,8 +1,10 @@ """ -Constant-pressure, adiabatic kinetics simulation. +Constant-pressure, adiabatic kinetics simulation +================================================ Requires: cantera >= 2.5.0, matplotlib >= 2.0 -Keywords: combustion, reactor network, plotting + +.. tags:: Python, combustion, reactor network, plotting """ import sys diff --git a/samples/python/reactors/reactor2.py b/samples/python/reactors/reactor2.py index 7929b4c846..0f2460faa4 100644 --- a/samples/python/reactors/reactor2.py +++ b/samples/python/reactors/reactor2.py @@ -1,4 +1,7 @@ -""" +r""" +Reactors with walls and heat transfer +===================================== + Two reactors connected with a piston, with heat loss to the environment This script simulates the following situation. A closed cylinder with volume 2 @@ -6,8 +9,8 @@ proportional to the pressure difference between the two sides. It is initially held in place in the middle. One side is filled with 1000 K argon at 20 atm, and the other with a combustible 500 K methane/air mixture at 0.1 atm -(phi = 1.1). At t = 0 the piston is released and begins to move due to the -large pressure difference, compressing and heating the methane/air mixture, +(:math:`\phi = 1.1`). At :math:`t = 0`, the piston is released and begins to move due +to the large pressure difference, compressing and heating the methane/air mixture, which eventually explodes. At the same time, the argon cools as it expands. The piston allows heat transfer between the reactors and some heat is lost through the outer cylinder walls to the environment. @@ -16,7 +19,8 @@ wave propagation. It is somewhat artificial, but nevertheless instructive. Requires: cantera >= 2.5.0, matplotlib >= 2.0 -Keywords: combustion, reactor network, plotting + +.. tags:: combustion, reactor network, plotting """ import sys diff --git a/samples/python/reactors/sensitivity1.py b/samples/python/reactors/sensitivity1.py index 2bad6e8542..9cd7531427 100644 --- a/samples/python/reactors/sensitivity1.py +++ b/samples/python/reactors/sensitivity1.py @@ -1,8 +1,10 @@ """ Constant-pressure, adiabatic kinetics simulation with sensitivity analysis +========================================================================== Requires: cantera >= 2.5.0, matplotlib >= 2.0 -Keywords: combustion, reactor network, sensitivity analysis, plotting + +.. tags:: Python, combustion, reactor network, sensitivity analysis, plotting """ import sys diff --git a/samples/python/reactors/surf_pfr.py b/samples/python/reactors/surf_pfr.py index 439a9bed14..3a8bdee7ae 100644 --- a/samples/python/reactors/surf_pfr.py +++ b/samples/python/reactors/surf_pfr.py @@ -1,12 +1,15 @@ """ -This example solves a plug flow reactor problem with surface chemistry. The specific -problem simulated is the partial oxidation of methane over a platinum catalyst in a -packed bed reactor. This example solves the DAE system directly, using the FlowReactor +Plug flow reactor with surface chemistry +======================================== + +This example simulates the partial oxidation of methane over a platinum catalyst in a +packed bed reactor. This example solves the DAE system directly, using the `FlowReactor` class and the SUNDIALS IDA solver, in contrast to the approximation as a chain of -steady-state WSRs used in surf_pfr_chain.py. +steady-state WSRs used in :doc:`surf_pfr_chain.py `. Requires: cantera >= 3.0.0 -Keywords: catalysis, reactor network, surface chemistry, plug flow reactor, + +.. tags:: Python, catalysis, reactor network, surface chemistry, plug flow reactor, packed bed reactor """ diff --git a/samples/python/reactors/surf_pfr_chain.py b/samples/python/reactors/surf_pfr_chain.py index 85e40e766f..5398d7e829 100644 --- a/samples/python/reactors/surf_pfr_chain.py +++ b/samples/python/reactors/surf_pfr_chain.py @@ -1,12 +1,16 @@ """ -This example solves a plug flow reactor problem, where the chemistry is -surface chemistry. The specific problem simulated is the partial oxidation of -methane over a platinum catalyst in a packed bed reactor. To avoid needing to solve a -DAE system, the PFR is approximated as a chain of successive WSRs. See surf_pfr.py -for a more advanced implementation that solves the DAE system directly. +Plug flow reactor modeled as a chain of well stirred reactors +============================================================= + +This example solves a plug flow reactor problem, where the chemistry is surface +chemistry. The specific problem simulated is the partial oxidation of methane over a +platinum catalyst in a packed bed reactor. To avoid needing to solve a DAE system, the +PFR is approximated as a chain of successive WSRs. See :doc:`surf_pfr.py ` for +a more advanced implementation that solves the DAE system directly. Requires: cantera >= 3.0 -Keywords: catalysis, reactor network, surface chemistry, plug flow reactor, + +.. tags:: Python, catalysis, reactor network, surface chemistry, plug flow reactor, packed bed reactor """ diff --git a/samples/python/surface_chemistry/1D_pfr_surfchem.py b/samples/python/surface_chemistry/1D_pfr_surfchem.py index 6f8ffedbbc..4de94c4386 100644 --- a/samples/python/surface_chemistry/1D_pfr_surfchem.py +++ b/samples/python/surface_chemistry/1D_pfr_surfchem.py @@ -1,4 +1,7 @@ """ +Plug flow reactor: silicon nitride deposition +============================================= + A 1-D steady state plug-flow reactor demonstrating silicon nitride (Si3N4) deposition from ammonia (NH3) and silicon tetrafluoride (SiF4). @@ -7,15 +10,16 @@ Based off the Jupyter notebook created by Yuanjie Jiang, which corresponds to the original example from: -R.S. Larson. "PLUG: A FORTRAN program for the analysis of PLUG flow reactors with -gas-phase and surface chemistry", Sandia Report SAND-96-8211, 1996. -https://doi.org/10.2172/204257 + R.S. Larson. "PLUG: A FORTRAN program for the analysis of PLUG flow reactors with + gas-phase and surface chemistry", Sandia Report SAND-96-8211, 1996. + https://doi.org/10.2172/204257 The results are somewhat different from those in the Larson report in part due to the fact that this example does not include the frictional pressure drop. Requires: cantera >= 3.0, matplotlib >= 2.0 -Keywords: catalysis, plug flow reactor, reactor network, surface chemistry + +.. tags:: Python, catalysis, plug flow reactor, reactor network, surface chemistry """ import numpy as np diff --git a/samples/python/surface_chemistry/README.rst b/samples/python/surface_chemistry/README.rst new file mode 100644 index 0000000000..baaa67d544 --- /dev/null +++ b/samples/python/surface_chemistry/README.rst @@ -0,0 +1,2 @@ +Surface chemistry +----------------- diff --git a/samples/python/surface_chemistry/catalytic_combustion.py b/samples/python/surface_chemistry/catalytic_combustion.py index 58b68840d1..9315641a66 100644 --- a/samples/python/surface_chemistry/catalytic_combustion.py +++ b/samples/python/surface_chemistry/catalytic_combustion.py @@ -1,5 +1,6 @@ """ Catalytic combustion of methane on platinum +=========================================== This script solves a catalytic combustion problem. A stagnation flow is set up, with a gas inlet 10 cm from a platinum surface at 900 K. The lean, @@ -11,7 +12,8 @@ Symp. (Intl.) on Combustion,1996 pp. 1747-1754 Requires: cantera >= 3.0 -Keywords: catalysis, combustion, 1D flow, surface chemistry + +.. tags:: Python, catalysis, combustion, 1D flow, surface chemistry """ import numpy as np diff --git a/samples/python/surface_chemistry/diamond_cvd.py b/samples/python/surface_chemistry/diamond_cvd.py index e9c6ba31ba..2b1047cb75 100644 --- a/samples/python/surface_chemistry/diamond_cvd.py +++ b/samples/python/surface_chemistry/diamond_cvd.py @@ -1,16 +1,18 @@ """ -A CVD example simulating growth of a diamond film - -This example computes the growth rate of a diamond film according to a -simplified version of a particular published growth mechanism (see file -diamond.yaml for details). Only the surface coverage equations are solved here; -the gas composition is fixed. (For an example of coupled gas-phase and -surface, see catalytic_combustion.py.) Atomic hydrogen plays an important -role in diamond CVD, and this example computes the growth rate and surface +Growth of diamond film using CVD +================================ + +This example computes the growth rate of a diamond film according to a simplified +version of a particular published growth mechanism (see file ``diamond.yaml`` for +details). Only the surface coverage equations are solved here; the gas composition is +fixed. (For an example of coupled gas-phase and surface, see +:doc:`catalytic_combustion.py `.) Atomic hydrogen plays an +important role in diamond CVD, and this example computes the growth rate and surface coverages as a function of [H] at the surface for fixed temperature and [CH3]. Requires: cantera >= 2.6.0, pandas >= 0.25.0, matplotlib >= 2.0 -Keywords: surface chemistry, kinetics + +.. tags:: Python, surface chemistry, kinetics """ import csv diff --git a/samples/python/surface_chemistry/lithium_ion_battery.py b/samples/python/surface_chemistry/lithium_ion_battery.py index 1035e104eb..f5a463db77 100644 --- a/samples/python/surface_chemistry/lithium_ion_battery.py +++ b/samples/python/surface_chemistry/lithium_ion_battery.py @@ -1,25 +1,30 @@ """ +Lithium-ion battery +=================== + This example calculates the cell voltage of a lithium-ion battery at given temperature, pressure, current, and range of state of charge (SOC). The thermodynamics are based on a graphite anode and a LiCoO2 cathode, -modeled using the 'BinarySolutionTabulatedThermo' class. +modeled using the :ct:`BinarySolutionTabulatedThermo` class. Further required cell parameters are the electrolyte ionic resistance, the stoichiometry ranges of the active materials (electrode balancing), and the surface area of the active materials. The functionality of this example is presented in greater detail in a jupyter notebook as well as the reference (which also describes the derivation of the -'BinarySolutionTabulatedThermo' class): +:ct:`BinarySolutionTabulatedThermo` class): Reference: -M. Mayur, S. C. DeCaluwe, B. L. Kee, W. G. Bessler, “Modeling and simulation -of the thermodynamics of lithium-ion battery intercalation materials in the -open-source software Cantera,” Electrochim. Acta 323, 134797 (2019), -https://doi.org/10.1016/j.electacta.2019.134797 + + M. Mayur, S. C. DeCaluwe, B. L. Kee, W. G. Bessler, “Modeling and simulation + of the thermodynamics of lithium-ion battery intercalation materials in the + open-source software Cantera,” Electrochim. Acta 323, 134797 (2019), + https://doi.org/10.1016/j.electacta.2019.134797 Requires: cantera >= 2.6.0, matplotlib >= 2.0 -Keywords: surface chemistry, kinetics, electrochemistry, battery, plotting + +.. tags:: Python, surface chemistry, kinetics, electrochemistry, battery, plotting """ import cantera as ct diff --git a/samples/python/surface_chemistry/sofc.py b/samples/python/surface_chemistry/sofc.py index 0cfbb0e26b..06a2146f6f 100644 --- a/samples/python/surface_chemistry/sofc.py +++ b/samples/python/surface_chemistry/sofc.py @@ -1,4 +1,7 @@ """ +Solid oxide fuel cell using elementary kinetics +=============================================== + A simple model of a solid oxide fuel cell. Unlike most SOFC models, this model does not use semi-empirical Butler-Volmer @@ -8,17 +11,19 @@ OCV (it does not need to be separately specified), as well as polarization curves. -NOTE: The parameters here, and in the input file sofc.yaml, are not to be -relied upon for a real SOFC simulation! They are meant to illustrate only how -to do such a calculation in Cantera. While some of the parameters may be close -to real values, others are simply set arbitrarily to give reasonable-looking -results. +.. caution:: + + The parameters here, and in the input file ``sofc.yaml``, are not to be relied upon + for a real SOFC simulation! They are meant to illustrate only how to do such a + calculation in Cantera. While some of the parameters may be close to real values, + others are simply set arbitrarily to give reasonable-looking results. -It is recommended that you read input file sofc.yaml before reading or running -this script! + It is recommended that you read input file ``sofc.yaml`` before reading or running + this script. Requires: cantera >= 2.6.0 -Keywords: kinetics, electrochemistry, surface chemistry, fuel cell + +.. tags:: Python, kinetics, electrochemistry, surface chemistry, fuel cell """ import cantera as ct diff --git a/samples/python/thermo/README.rst b/samples/python/thermo/README.rst new file mode 100644 index 0000000000..4b7a803f88 --- /dev/null +++ b/samples/python/thermo/README.rst @@ -0,0 +1,2 @@ +Thermodynamics +-------------- diff --git a/samples/python/thermo/coverage_dependent_surf.py b/samples/python/thermo/coverage_dependent_surf.py index 82ab0b69af..d4def4e0a0 100644 --- a/samples/python/thermo/coverage_dependent_surf.py +++ b/samples/python/thermo/coverage_dependent_surf.py @@ -1,6 +1,9 @@ """ -This example demonstrates (1). the four different dependency models available -for coverage-dependent enthalpy and entropy calculations and (2). capability +Surface with coverage-dependent thermo +====================================== + +This example demonstrates (1) the four different dependency models available +for coverage-dependent enthalpy and entropy calculations and (2) capability of including self-interaction but also cross-interaction among different surface species. @@ -17,7 +20,8 @@ coverages. Requires: cantera >= 3.0.0, matplotlib >= 2.0 -Keywords: thermodynamics, surface chemistry, catalysis + +.. tags:: Python, thermodynamics, surface chemistry, catalysis """ import cantera as ct diff --git a/samples/python/thermo/critical_properties.py b/samples/python/thermo/critical_properties.py index 2fe5b3d1e8..4f50f2cfd4 100644 --- a/samples/python/thermo/critical_properties.py +++ b/samples/python/thermo/critical_properties.py @@ -1,8 +1,11 @@ """ +Critical state properties +========================= + Print the critical state properties for the fluids for which Cantera has built-in liquid/vapor equations of state. -Keywords: thermodynamics, multiphase, non-ideal fluid +.. tags:: Python, thermodynamics, multiphase, non-ideal fluid """ import cantera as ct diff --git a/samples/python/thermo/equivalenceRatio.py b/samples/python/thermo/equivalenceRatio.py index b8124d5d42..a8b365a05d 100644 --- a/samples/python/thermo/equivalenceRatio.py +++ b/samples/python/thermo/equivalenceRatio.py @@ -1,18 +1,24 @@ """ +Equivalence ratio +================= + This example demonstrates how to set a mixture according to equivalence ratio and mixture fraction. Requires: cantera >= 2.6.0 -Keywords: combustion, thermodynamics, mixture + +.. tags:: Python, combustion, thermodynamics, mixture """ import cantera as ct gas = ct.Solution('gri30.yaml') +# %% # Define the oxidizer composition, here air with 21 mol-% O2 and 79 mol-% N2 air = "O2:0.21,N2:0.79" +# %% # Set the mixture composition according to the stoichiometric mixture # (equivalence ratio phi = 1). The fuel composition in this example # is set to 100 mol-% CH4 and the oxidizer to 21 mol-% O2 and 79 mol-% N2. @@ -20,31 +26,35 @@ # and pressure constant gas.set_equivalence_ratio(phi=1.0, fuel="CH4:1", oxidizer=air) +# %% # If fuel or oxidizer consist of a single species, a short hand notation can be -# used, for example fuel="CH4" is equivalent to fuel="CH4:1". +# used, for example ``fuel="CH4"`` is equivalent to ``fuel="CH4:1"``. # By default, the compositions of fuel and oxidizer are interpreted as mole # fractions. If the compositions are given in mass fractions, an # additional argument can be provided. Here, the fuel is 100 mass-% CH4 # and the oxidizer is 23.3 mass-% O2 and 76.7 mass-% N2 gas.set_equivalence_ratio(1.0, fuel="CH4:1", oxidizer="O2:0.233,N2:0.767", basis='mass') +# %% # This function can be used to compute the equivalence ratio for any mixture. # The first two arguments specify the compositions of the fuel and oxidizer. -# An optional third argument "basis" indicates if fuel and oxidizer compositions +# An optional third argument ``basis``` indicates if fuel and oxidizer compositions # are provided in terms of mass or mole fractions. Default is mole fractions. # Note that for all functions shown here, the compositions are normalized # internally so the species fractions do not have to sum to unity phi = gas.equivalence_ratio(fuel="CH4:1", oxidizer="O2:233,N2:767", basis='mass') print(f"phi = {phi:1.3f}") +# %% # If the compositions of fuel and oxidizer are unknown, the function can # be called without arguments. This assumes that all C, H and S atoms come from # the fuel and all O atoms from the oxidizer. In this example, the fuel was set -# to be pure CH4 and the oxidizer O2:0.233,N2:0.767 so that the assumption is true +# to be pure CH4 and the oxidizer ``O2:0.233, N2:0.767`` so that the assumption is true # and the same equivalence ratio as above is computed phi = gas.equivalence_ratio() print(f"phi = {phi:1.3f}") +# %% # Instead of working with equivalence ratio, mixture fraction can be used. # The mixture fraction is always kg fuel / (kg fuel + kg oxidizer), independent # of the basis argument. For example, the mixture fraction Z can be computed as @@ -52,6 +62,7 @@ Z = gas.mixture_fraction(fuel="CH4:1", oxidizer=air) print(f"Z = {Z:1.3f}") +# %% # By default, the mixture fraction is the Bilger mixture fraction. Instead, # a mixture fraction based on a single element can be used. In this example, # the following two ways of computing Z are the same: @@ -60,16 +71,19 @@ Z = gas.mixture_fraction(fuel="CH4:1", oxidizer=air, element="C") print(f"Z(mixture fraction based on C) = {Z:1.3f}") +# %% # Since the fuel in this example is pure methane and the oxidizer is air, # the mixture fraction is the same as the mass fraction of methane in the mixture print(f"mass fraction of CH4 = {gas['CH4'].Y[0]:1.3f}") +# %% # To set a mixture according to the mixture fraction, the following function # can be used. In this example, the final fuel/oxidizer mixture # contains 5.5 mass-% CH4: gas.set_mixture_fraction(0.055, fuel="CH4:1", oxidizer=air) print(f"mass fraction of CH4 = {gas['CH4'].Y[0]:1.3f}") +# %% # Mixture fraction and equivalence ratio are invariant to the reaction progress. # For example, they stay constant if the mixture composition changes to the burnt # state or for any intermediate state. Fuel and oxidizer compositions for all functions @@ -82,8 +96,9 @@ print(f"phi(burnt) = {phi_burnt:1.3f}") print(f"Z(burnt) = {Z_burnt:1.3f}") +# %% # If fuel and oxidizer compositions are specified consistently, then -# equivalence_ratio and set_equivalence_ratio are consistent as well, as +# ``equivalence_ratio`` and ``set_equivalence_ratio`` are consistent as well, as # shown in the following example with arbitrary fuel and oxidizer compositions: gas.set_equivalence_ratio(2.5, fuel="CH4:1,O2:0.01,CO:0.05,N2:0.1", oxidizer="O2:0.2,N2:0.8,CO2:0.05,CH4:0.01") @@ -92,6 +107,7 @@ oxidizer="O2:0.2,N2:0.8,CO2:0.05,CH4:0.01") print(f"phi = {phi:1.3f}") # prints 2.5 +# %% # Without specifying the fuel and oxidizer compositions, it is assumed that # all C, H and S atoms come from the fuel and all O atoms from the oxidizer, # which is not true for this example. Therefore, the following call gives a @@ -99,6 +115,7 @@ phi = gas.equivalence_ratio() print(f"phi = {phi:1.3f}") +# %% # After computing the mixture composition for a certain equivalence ratio given # a fuel and mixture composition, the mixture can optionally be diluted. The # following function will first create a mixture with equivalence ratio 2 from pure @@ -108,6 +125,7 @@ print(f"mole fraction of H2O = {gas['H2O'].X[0]:1.3f}") # mixture contains 30 mol-% H2O print(f"ratio of H2/O2: {gas['H2'].X[0] / gas['O2'].X[0]:1.3f}") # according to phi=2 +# %% # Another option is to specify the fuel or oxidizer fraction in the final mixture. # The following example creates a mixture with equivalence ratio 2 from pure # hydrogen and oxygen (same as above) and then dilutes it with a mixture of 50 mass-% @@ -116,6 +134,7 @@ fraction={"fuel":0.1}, basis="mass") print(f"mole fraction of H2 = {gas['H2'].Y[0]:1.3f}") # mixture contains 10 mass-% fuel +# %% # To compute the equivalence ratio given a diluted mixture, a list of # species names can be provided which will be considered for computing phi. # In this example, the diluents H2O and CO2 are ignored and only H2 and O2 are @@ -123,11 +142,13 @@ phi = gas.equivalence_ratio(fuel="H2", oxidizer="O2", include_species=["H2", "O2"]) print(f"phi = {phi:1.3f}") # prints 2 +# %% # If instead the diluent should be included in the computation of the equivalence ratio, # the mixture can be set in the following way. Assume the fuel is diluted with # 50 mol-% H2O: gas.set_equivalence_ratio(2.0, fuel="H2:0.5,H2O:0.5", oxidizer=air) +# %% # This creates a mixture with the specified equivalence ratio including the diluent: phi = gas.equivalence_ratio(fuel="H2:0.5,H2O:0.5", oxidizer=air) print(f"phi = {phi:1.3f}") # prints 2 diff --git a/samples/python/thermo/isentropic.py b/samples/python/thermo/isentropic.py index e9b8d9c773..357a5c9837 100644 --- a/samples/python/thermo/isentropic.py +++ b/samples/python/thermo/isentropic.py @@ -1,8 +1,12 @@ """ -Isentropic, adiabatic flow example - calculate area ratio vs. Mach number curve +Isentropic, adiabatic flow +========================== + +Calculate area ratio vs. Mach number curve Requires: cantera >= 2.5.0, matplotlib >= 2.0 -Keywords: thermodynamics, compressible flow, plotting + +.. tags:: Python, thermodynamics, compressible flow, plotting """ import cantera as ct @@ -57,7 +61,6 @@ def isentropic(gas=None): return data - if __name__ == "__main__": print(__doc__) data = isentropic() diff --git a/samples/python/thermo/isentropic_units.py b/samples/python/thermo/isentropic_units.py index a5a1a4f655..3f9fb63042 100644 --- a/samples/python/thermo/isentropic_units.py +++ b/samples/python/thermo/isentropic_units.py @@ -1,10 +1,13 @@ """ -Isentropic, adiabatic flow example - calculate area ratio vs. Mach number curve. -Uses the pint library to include customized units in the calculation. +Isentropic, adiabatic flow (with units) +======================================= +Isentropic, adiabatic flow example - calculate area ratio vs. Mach number curve. +Uses the ``pint`` library to include customized units in the calculation. Requires: Cantera >= 3.0.0, pint -Keywords: thermodynamics, compressible flow, units + +.. tags:: Python, thermodynamics, compressible flow, units """ import cantera.with_units as ctu diff --git a/samples/python/thermo/mixing.py b/samples/python/thermo/mixing.py index 99cad7b91d..6970e5b2e6 100644 --- a/samples/python/thermo/mixing.py +++ b/samples/python/thermo/mixing.py @@ -1,14 +1,16 @@ """ -Mixing two streams using `Quantity` objects. +Mixing using `Quantity` objects +=============================== -In this example, air and methane are mixed in stoichiometric proportions. This -is a simpler, steady-state version of the example ``reactors/mix1.py``. +In this example, air and methane are mixed in stoichiometric proportions. This is a +simpler, steady-state version of the example :doc:`mix1.py <../reactors/mix1>`. Since the goal is to simulate a continuous flow system, the mixing takes place at constant enthalpy and pressure. Requires: cantera >= 2.5.0 -Keywords: thermodynamics, mixture + +.. tags:: Python, thermodynamics, mixture """ import cantera as ct diff --git a/samples/python/thermo/rankine.py b/samples/python/thermo/rankine.py index 43d8d55515..e7907fe9af 100644 --- a/samples/python/thermo/rankine.py +++ b/samples/python/thermo/rankine.py @@ -1,9 +1,13 @@ """ +Rankine cycle +============= + Calculate the efficiency of a Rankine vapor power cycle using a pure fluid model for water. Requires: Cantera >= 2.5.0 -Keywords: thermodynamics, thermodynamic cycle, non-ideal fluid + +.. tags:: Python, thermodynamics, thermodynamic cycle, non-ideal fluid """ import cantera as ct diff --git a/samples/python/thermo/rankine_units.py b/samples/python/thermo/rankine_units.py index cae7d93bc9..91305bcfe5 100644 --- a/samples/python/thermo/rankine_units.py +++ b/samples/python/thermo/rankine_units.py @@ -1,9 +1,13 @@ """ +Rankine cycle (with units) +========================== + Calculate the efficiency of a Rankine vapor power cycle using a pure fluid model for water. Includes the units of quantities in the calculations. Requires: Cantera >= 3.0.0, pint -Keywords: thermodynamics, thermodynamic cycle, non-ideal fluid, units + +.. tags:: Python, thermodynamics, thermodynamic cycle, non-ideal fluid, units """ import cantera.with_units as ctu diff --git a/samples/python/thermo/sound_speed.py b/samples/python/thermo/sound_speed.py index e5294232ff..1ede2d41f9 100644 --- a/samples/python/thermo/sound_speed.py +++ b/samples/python/thermo/sound_speed.py @@ -1,8 +1,12 @@ """ +Sound speeds +============ + Compute the "equilibrium" and "frozen" sound speeds for a gas Requires: cantera >= 3.0.0 -Keywords: thermodynamics, equilibrium + +.. tags:: Python, thermodynamics, equilibrium """ import cantera as ct diff --git a/samples/python/thermo/sound_speed_units.py b/samples/python/thermo/sound_speed_units.py index e4bff02ecf..6bd683e315 100644 --- a/samples/python/thermo/sound_speed_units.py +++ b/samples/python/thermo/sound_speed_units.py @@ -1,9 +1,13 @@ """ -Compute the "equilibrium" and "frozen" sound speeds for a gas. Uses the pint library to -include customized units in the calculation. +Sound speeds (with units) +========================= + +Compute the "equilibrium" and "frozen" sound speeds for a gas. Uses the ``pint`` library +to include customized units in the calculation. Requires: Cantera >= 3.0.0, pint -Keywords: thermodynamics, equilibrium, units + +.. tags:: Python, thermodynamics, equilibrium, units """ import cantera.with_units as ctu diff --git a/samples/python/thermo/vapordome.py b/samples/python/thermo/vapordome.py index 5fa00c05db..10c40d8ffc 100644 --- a/samples/python/thermo/vapordome.py +++ b/samples/python/thermo/vapordome.py @@ -1,10 +1,14 @@ """ +Vapor Dome +========== + This example generates a saturated steam table and plots the vapor dome. The steam table corresponds to data typically found in thermodynamic text books and uses the same customary units. Requires: Cantera >= 2.5.0, matplotlib >= 2.0, pandas >= 1.1.0, numpy >= 1.12 -Keywords: thermodynamics, non-ideal fluid, plotting + +.. tags:: Python, thermodynamics, non-ideal fluid, plotting """ import cantera as ct @@ -21,6 +25,7 @@ 'hf', 'hfg', 'hg', 'sf', 'sfg', 'sg'] +# %% # temperatures correspond to Engineering Thermodynamics, Moran et al. (9th ed), # Table A-2; additional data points are added close to the critical point; # w.min_temp is equal to the triple point temperature @@ -71,18 +76,21 @@ df.sg -= sf0 df.sf -= sf0 +# %% # print and write saturated steam table to csv file print(df) df.to_csv('saturated_steam_T.csv', index=False) +# %% # illustrate the vapor dome in a P-v diagram plt.semilogx(df.vf.values, df.P.values, label='Saturated liquid') plt.semilogx(df.vg.values, df.P.values, label='Saturated vapor') plt.semilogx(df.vg.values[-1], df.P.values[-1], 'o', label='Critical point') plt.xlabel(r'Specific volume - $v$ ($\mathrm{m^3/kg}$)') plt.ylabel(r'Presssure - $P$ (bar)') -plt.legend() +plt.legend(); +# %% # illustrate the vapor dome in a T-s diagram plt.figure() plt.plot(df.sf.values, df['T'].values, label='Saturated liquid') diff --git a/samples/python/transport/README.rst b/samples/python/transport/README.rst new file mode 100644 index 0000000000..ce84aae834 --- /dev/null +++ b/samples/python/transport/README.rst @@ -0,0 +1,2 @@ +Transport +--------- diff --git a/samples/python/transport/dusty_gas.py b/samples/python/transport/dusty_gas.py index 58ccace73e..39f5f70a56 100644 --- a/samples/python/transport/dusty_gas.py +++ b/samples/python/transport/dusty_gas.py @@ -1,13 +1,15 @@ """ -Calculate transport properties in a porous medium using the dusty gas transport model. +Porous media transport using the dusty gas model +================================================ -The Dusty Gas model is a multicomponent transport model for gas transport -through the pores of a stationary porous medium. This example shows how to -create a transport manager that implements the Dusty Gas model and use it to -compute the multicomponent diffusion coefficients and thermal conductivity. +The dusty gas model is a multicomponent transport model for gas transport through the +pores of a stationary porous medium. This example shows how to create a +:ct:`DustyGasTransport` transport manager and use it to compute the multicomponent +diffusion coefficients and thermal conductivity. Requires: cantera >= 2.6.0 -Keywords: transport, multicomponent transport + +.. tags:: Python, transport, multicomponent transport """ import cantera as ct diff --git a/samples/python/transport/multiprocessing_viscosity.py b/samples/python/transport/multiprocessing_viscosity.py index 103fe92a9e..2a1d4a3172 100644 --- a/samples/python/transport/multiprocessing_viscosity.py +++ b/samples/python/transport/multiprocessing_viscosity.py @@ -1,5 +1,8 @@ """ -This example demonstrates how Cantera can be used with the 'multiprocessing' +Parallelizing transport property calculations +============================================= + +This example demonstrates how Cantera can be used with the `multiprocessing` module. Because Cantera Python objects are built on top of C++ objects which cannot be @@ -9,7 +12,8 @@ initialized once per worker process. Requires: cantera >= 2.5.0 -Keywords: transport, benchmarking, parallel computing + +.. tags:: Python, transport, benchmarking, parallel computing """ import multiprocessing From b5f78e87845943fec8dc8e9b1c6c4774c3b1ee19 Mon Sep 17 00:00:00 2001 From: Ray Speth Date: Wed, 20 Sep 2023 11:54:39 -0400 Subject: [PATCH 10/22] [Doc] Add C++ examples to sphinx-gallery --- doc/SConscript | 14 ++++++- doc/sphinx/conf.py | 5 +++ doc/sphinx/index.rst | 1 + samples/cxx/LiC6_electrode/LiC6_electrode.cpp | 9 ++-- samples/cxx/README.rst | 2 + samples/cxx/bvp/BoundaryValueProblem.h | 12 ++++-- samples/cxx/bvp/blasius.cpp | 41 ++++++++++--------- samples/cxx/combustor/combustor.cpp | 11 +++-- samples/cxx/custom/custom.cpp | 32 +++++++++------ samples/cxx/demo/demo.cpp | 9 ++-- samples/cxx/flamespeed/flamespeed.cpp | 12 +++--- samples/cxx/gas_transport/gas_transport.cpp | 7 ++-- samples/cxx/jacobian/derivative_speed.cpp | 7 ++-- samples/cxx/kinetics1/example_utils.h | 5 +++ samples/cxx/kinetics1/kinetics1.cpp | 9 ++-- .../cxx/openmp_ignition/openmp_ignition.cpp | 7 ++-- samples/cxx/rankine/rankine.cpp | 9 ++-- 17 files changed, 111 insertions(+), 81 deletions(-) create mode 100644 samples/cxx/README.rst diff --git a/doc/SConscript b/doc/SConscript index 971fbc166e..503be73495 100644 --- a/doc/SConscript +++ b/doc/SConscript @@ -119,15 +119,25 @@ if localenv['sphinx_docs']: # RecursiveInstall knows to copy modified files, unlike Copy copy_sphinx = localenv.RecursiveInstall("#build/doc/sphinx", "sphinx") - copy_samples = localenv.RecursiveInstall("#build/doc/samples", "#samples") + copy_python_samples = localenv.RecursiveInstall("#build/doc/samples/python", + "#samples/python") sphinxdocs = build(localenv.Command('build/doc/sphinx/html/index.html', 'sphinx/conf.py', build_sphinx)) env.Alias('sphinx', sphinxdocs) env.Depends(sphinxdocs, copy_sphinx) - env.Depends(sphinxdocs, copy_samples) + env.Depends(sphinxdocs, copy_python_samples) env.Depends(sphinxdocs, env['python_module']) + # Gather all C++ samples into a single directory so they can be presented a single + # sub-gallery by sphinx-gallery + cxxfiles = (Glob("#samples/cxx/*/*.cpp") + Glob("#samples/cxx/*/*.h") + + Glob("#samples/cxx/*.rst")) + for cxxfile in cxxfiles: + env.Depends(sphinxdocs, + localenv.Command(f"#build/doc/samples/cxx/{cxxfile.name}", cxxfile, + Copy("$TARGET", "$SOURCE"))) + # Create a list of MATLAB classes to document. This uses the NamedTuple # structure defined at the top of the file. The @Data and @Utilities # classes are fake classes for the purposes of documentation only. Each diff --git a/doc/sphinx/conf.py b/doc/sphinx/conf.py index 804bb9e6d7..31056ca7d0 100644 --- a/doc/sphinx/conf.py +++ b/doc/sphinx/conf.py @@ -49,12 +49,16 @@ sphinx_gallery_conf = { 'filename_pattern': '\.py', + 'example_extensions': {'.py', '.cpp', '.h'}, + "filetype_parsers": {'.h': 'C++'}, 'image_srcset': ["2x"], 'examples_dirs': [ '../samples/python/', + '../samples/cxx/', ], 'gallery_dirs': [ 'examples/python', + 'examples/cxx', ], 'reference_url': { 'cantera': None, # 'None' means the locally-documented module @@ -115,6 +119,7 @@ def executable_script(src_file, gallery_conf): tags_page_header = "Examples with this tag:" tags_badge_colors = { "Python": "secondary", + "C++": "secondary", } autodoc_default_options = { diff --git a/doc/sphinx/index.rst b/doc/sphinx/index.rst index 53639ad1ef..85708291c4 100644 --- a/doc/sphinx/index.rst +++ b/doc/sphinx/index.rst @@ -16,5 +16,6 @@ format. matlab/index examples/python/index + examples/cxx/index _tags/tagsindex \ No newline at end of file diff --git a/samples/cxx/LiC6_electrode/LiC6_electrode.cpp b/samples/cxx/LiC6_electrode/LiC6_electrode.cpp index ec75b4bf36..be0633f401 100644 --- a/samples/cxx/LiC6_electrode/LiC6_electrode.cpp +++ b/samples/cxx/LiC6_electrode/LiC6_electrode.cpp @@ -1,13 +1,12 @@ -/*! - * @file LiC6_electrode.cpp - * - * LiC6 Electrode +/* + * LiC6 electrode + * ============== * * Calculate the open-circuit potential of an LiC6 electrode and activity * coefficients of each species as a function of the mole fraction of * intercalated lithium. * - * Keywords: thermodynamics, electrochemistry, battery + * .. tags:: C++, thermodynamics, electrochemistry, battery */ // This file is part of Cantera. See License.txt in the top-level directory or diff --git a/samples/cxx/README.rst b/samples/cxx/README.rst new file mode 100644 index 0000000000..3bf4d017c6 --- /dev/null +++ b/samples/cxx/README.rst @@ -0,0 +1,2 @@ +C++ Examples +============ diff --git a/samples/cxx/bvp/BoundaryValueProblem.h b/samples/cxx/bvp/BoundaryValueProblem.h index 9e347697e5..2ae637e8fd 100644 --- a/samples/cxx/bvp/BoundaryValueProblem.h +++ b/samples/cxx/bvp/BoundaryValueProblem.h @@ -1,7 +1,11 @@ -/** - * @file BoundaryValueProblem.h - * Simplified interface to the capabilities provided by %Cantera to - * solve boundary value problems. +/* + * Class `BoundaryValueProblem` + * ============================ + * + * Simplified interface to the capabilities provided by Cantera to solve boundary value + * problems. See :doc:`blasius.cpp ` for an example using this class. + * + * .. tags:: C++, user-defined model */ // This file is part of Cantera. See License.txt in the top-level directory or diff --git a/samples/cxx/bvp/blasius.cpp b/samples/cxx/bvp/blasius.cpp index 5e699d1c79..dbd5efe99f 100644 --- a/samples/cxx/bvp/blasius.cpp +++ b/samples/cxx/bvp/blasius.cpp @@ -1,14 +1,13 @@ -/*! - * @file blasius.cpp +/* + * Blasius BVP solver + * ================== * - * Blasius BVP Solver + * This example solves the Blasius boundary value problem for the velocity profile of a + * laminar boundary layer over a flat plate. It uses class ``BoundaryValueProblem``, + * defined in :doc:`BoundaryValueProblem.h `, which provides a + * simplified interface to the boundary value problem capabilities of Cantera. * - * This example solves the Blasius boundary value problem for the velocity - * profile of a laminar boundary layer over a flat plate. It defines class - * BoundaryValueProblem, which provides a simplified interface to the boundary - * value problem capabilities of Cantera. - * - * Keywords: user-defined model + * .. tags:: C++, user-defined model */ // This file is part of Cantera. See License.txt in the top-level directory or @@ -18,18 +17,22 @@ using Cantera::npos; -/** +/* %% * This class solves the Blasius boundary value problem on the domain (0,L): - * @f[ - * \frac{d\zeta}{dz} = u. - * @f] - * @f[ - * \frac{d^2u}{dz^2} + 0.5\zeta \frac{du}{dz} = 0. - * @f] + * + * .. math:: + * \frac{d\zeta}{dz} = u + * + * \frac{d^2u}{dz^2} + 0.5\zeta \frac{du}{dz} = 0 + * * with boundary conditions - * @f[ - * \zeta(0) = 0, u(0) = 0, u(L) = 1. - * @f] + * + * .. math:: + * + * \zeta(0) & = 0 \\ + * u(0) & = 0 \\ + * u(L) & = 1 + * * Note that this is formulated as a system of two equations, with maximum * order of 2, rather than as a single third-order boundary value problem. * For reasons having to do with the band structure of the Jacobian, no diff --git a/samples/cxx/combustor/combustor.cpp b/samples/cxx/combustor/combustor.cpp index d72a343d93..ca347658c9 100644 --- a/samples/cxx/combustor/combustor.cpp +++ b/samples/cxx/combustor/combustor.cpp @@ -1,16 +1,15 @@ -/*! - * @file combustor.cpp +/* + * Adiabatic combustor + * =================== * - * Adiabatic Combustor - * - * Two separate stream - one pure methane and the other air, both at 300 K + * Two separate streams - one pure methane and the other air, both at 300 K * and 1 atm flow into an adiabatic combustor where they mix. We are interested * in the steady-state burning solution. Since at 300 K no reaction will occur * between methane and air, we need to use an 'igniter' to initiate the * chemistry. A simple igniter is a pulsed flow of atomic hydrogen. After the * igniter is turned off, the system approaches the steady burning solution. * - * Keywords: combustion, reactor network, well-stirred reactor + * .. tags:: C++, combustion, reactor network, well-stirred reactor */ // This file is part of Cantera. See License.txt in the top-level directory or diff --git a/samples/cxx/custom/custom.cpp b/samples/cxx/custom/custom.cpp index e60c4e5fdb..d50f66a680 100644 --- a/samples/cxx/custom/custom.cpp +++ b/samples/cxx/custom/custom.cpp @@ -1,13 +1,12 @@ -/*! - * @file custom.cpp - * - * Custom Reactor +/* + * Custom reactor + * ============== * * Solve a closed-system constant pressure ignition problem where the governing * equations are custom-implemented, using Cantera's interface to CVODES to * integrate the equations. * - * Keywords: combustion, reactor network, user-defined model, ignition delay + * .. tags:: C++, combustion, reactor network, user-defined model, ignition delay */ // This file is part of Cantera. See License.txt in the top-level directory or @@ -53,14 +52,21 @@ class ReactorODEs : public FuncEval { m_nEqs = m_nSpecies + 1; } - /** - * Evaluate the ODE right-hand-side function, ydot = f(t,y). - * - overridden from FuncEval, called by the integrator during simulation. - * @param[in] t time. - * @param[in] y solution vector, length neq() - * @param[out] ydot rate of change of solution vector, length neq() - * @param[in] p sensitivity parameter vector, length nparams() - * - note: sensitivity analysis isn't implemented in this example + /* %% + * Evaluate the ODE right-hand-side function, :math:`\dot{y} = f(t,y)`. + * + * Overridden from :ct:`FuncEval`, called by the integrator during simulation. + * + * :param t: + * time + * :param y: + * solution vector, length neq() + * :param ydot: + * rate of change of solution vector, length neq() + * :param p: + * sensitivity parameter vector, length nparams() + * + * note: sensitivity analysis isn't implemented in this example */ void eval(double t, double* y, double* ydot, double* p) override { // the solution vector *y* is [T, Y_1, Y_2, ... Y_K], where T is the diff --git a/samples/cxx/demo/demo.cpp b/samples/cxx/demo/demo.cpp index da6c0c80f1..a721864725 100644 --- a/samples/cxx/demo/demo.cpp +++ b/samples/cxx/demo/demo.cpp @@ -1,13 +1,12 @@ -/*! - * @file demo.cpp - * - * Property Calculation Demo +/* + * Property calculation demo + * ========================= * * This demonstration program builds an object representing a reacting gas * mixture, and uses it to compute thermodynamic properties, chemical * equilibrium, and transport properties. * - * Keywords: tutorial, thermodynamics, equilibrium, transport + * .. tags:: C++, tutorial, thermodynamics, equilibrium, transport */ // This file is part of Cantera. See License.txt in the top-level directory or diff --git a/samples/cxx/flamespeed/flamespeed.cpp b/samples/cxx/flamespeed/flamespeed.cpp index caf48db3ca..09e7749ee0 100644 --- a/samples/cxx/flamespeed/flamespeed.cpp +++ b/samples/cxx/flamespeed/flamespeed.cpp @@ -1,14 +1,16 @@ -/*! - * @file flamespeed.cpp - * +/* * Freely-propagating flame + * ======================== * * C++ demo program to compute flame speeds using GRI-Mech. * - * Usage: flamespeed [equivalence_ratio] [refine_grid] [loglevel] + * Usage: + * + * flamespeed [equivalence_ratio] [refine_grid] [loglevel] * * Requires: cantera >= 3.0 - * Keywords: combustion, 1D flow, premixed flame, flame speed, saving output + * + * .. tags:: C++, combustion, 1D flow, premixed flame, flame speed, saving output */ // This file is part of Cantera. See License.txt in the top-level directory or diff --git a/samples/cxx/gas_transport/gas_transport.cpp b/samples/cxx/gas_transport/gas_transport.cpp index fcd9b0975b..bcbdfdf92d 100644 --- a/samples/cxx/gas_transport/gas_transport.cpp +++ b/samples/cxx/gas_transport/gas_transport.cpp @@ -1,13 +1,12 @@ -/*! - * @file gas_transport.cpp - * +/* * Gas phase transport properties + * ============================== * * Construct a gas phase Solution object and use it to compute viscosity, * thermal conductivity, mixture-averaged diffusion coefficients, and thermal * diffusivities for a range of temperatures. * - * Keywords: tutorial, transport, saving output + * .. tags:: C++, tutorial, transport, saving output */ // This file is part of Cantera. See License.txt in the top-level directory or diff --git a/samples/cxx/jacobian/derivative_speed.cpp b/samples/cxx/jacobian/derivative_speed.cpp index ee63732e4a..c449562757 100644 --- a/samples/cxx/jacobian/derivative_speed.cpp +++ b/samples/cxx/jacobian/derivative_speed.cpp @@ -1,13 +1,12 @@ -/*! - * @file derivative_speed.cpp - * +/* * Benchmark derivative evaluations + * ================================ * * Calculate derivatives of reaction rates of progress and species production and * destruction rates with respect to temperature, pressure, molar concentration, * and mole fractions. Time evaluation for different chemical mechanisms. * - * Keywords: kinetics, benchmarking + * .. tags:: C++, kinetics, benchmarking */ // This file is part of Cantera. See License.txt in the top-level directory or diff --git a/samples/cxx/kinetics1/example_utils.h b/samples/cxx/kinetics1/example_utils.h index 23547ea300..d0a7700017 100644 --- a/samples/cxx/kinetics1/example_utils.h +++ b/samples/cxx/kinetics1/example_utils.h @@ -1,3 +1,8 @@ +// Example utilities +// ================= +// +// Defines some functions used by :doc:`kinetics1.cpp `. + // This file is part of Cantera. See License.txt in the top-level directory or // at https://cantera.org/license.txt for license and copyright information. diff --git a/samples/cxx/kinetics1/kinetics1.cpp b/samples/cxx/kinetics1/kinetics1.cpp index 5cc2ca846a..688abb672d 100644 --- a/samples/cxx/kinetics1/kinetics1.cpp +++ b/samples/cxx/kinetics1/kinetics1.cpp @@ -1,12 +1,11 @@ -/*! - * @file kinetics1.cpp - * - * Zero-dimensional kinetics +/* + * Autoignition in a homogeneous reactor + * ===================================== * * This example simulates autoignition of hydrogen in a constant pressure * reactor and saves the time history to files that can be used for plotting. * - * Keywords: combustion, reactor network, ignition delay, saving output + * .. tags:: C++, combustion, reactor network, ignition delay, saving output */ // This file is part of Cantera. See License.txt in the top-level directory or diff --git a/samples/cxx/openmp_ignition/openmp_ignition.cpp b/samples/cxx/openmp_ignition/openmp_ignition.cpp index f4b44fe88d..2d2a91f71b 100644 --- a/samples/cxx/openmp_ignition/openmp_ignition.cpp +++ b/samples/cxx/openmp_ignition/openmp_ignition.cpp @@ -1,12 +1,11 @@ -/*! - * @file openmp_ignition.cpp - * +/* * Ignition delay calculation with OpenMP + * ====================================== * * This example shows how to use OpenMP to run multiple reactor network * calculations in parallel by using separate Cantera objects for each thread. * - * Keywords: combustion, reactor network, ignition delay, parallel computing + * .. tags:: C++, combustion, reactor network, ignition delay, parallel computing */ // This file is part of Cantera. See License.txt in the top-level directory or diff --git a/samples/cxx/rankine/rankine.cpp b/samples/cxx/rankine/rankine.cpp index 2126874417..8b5bde5c05 100644 --- a/samples/cxx/rankine/rankine.cpp +++ b/samples/cxx/rankine/rankine.cpp @@ -1,12 +1,11 @@ -/*! - * @file rankine.cpp - * - * Open Rankine Cycle +/* + * Open Rankine cycle + * ================== * * Calculate the thermodynamic states and efficiency of an open Rankine cycle * using a pure substance model for water. * - * Keywords: thermodynamics, thermodynamic cycle, non-ideal fluid + * .. tags:: C++, thermodynamics, thermodynamic cycle, non-ideal fluid */ // This file is part of Cantera. See License.txt in the top-level directory or From 783f1621efecd3a3928f6bb9e526aabce4fda49a Mon Sep 17 00:00:00 2001 From: Ray Speth Date: Wed, 20 Sep 2023 14:25:41 -0400 Subject: [PATCH 11/22] Add Fortran examples to sphinx-gallery --- doc/SConscript | 8 ++++++++ doc/sphinx/conf.py | 6 +++++- doc/sphinx/index.rst | 3 ++- samples/f77/SConscript | 2 +- samples/f77/SConstruct.in | 2 +- samples/f77/ctlib.f | 30 +++++++++++++++++------------- samples/f77/demo_ftnlib.cpp | 7 ++++--- samples/f77/{demo.f => f77_demo.f} | 28 ++++++++++++++++++---------- samples/f77/isentropic.f | 14 ++++++++------ samples/f90/README.rst | 4 ++++ samples/f90/demo.f90 | 5 +++-- 11 files changed, 71 insertions(+), 38 deletions(-) rename samples/f77/{demo.f => f77_demo.f} (80%) create mode 100644 samples/f90/README.rst diff --git a/doc/SConscript b/doc/SConscript index 503be73495..9b74cd2814 100644 --- a/doc/SConscript +++ b/doc/SConscript @@ -138,6 +138,14 @@ if localenv['sphinx_docs']: localenv.Command(f"#build/doc/samples/cxx/{cxxfile.name}", cxxfile, Copy("$TARGET", "$SOURCE"))) + # Gather all Fortran (F77 and F90) samples into a single directory + fort_files = (Glob("#samples/f77/*.f") + Glob("#samples/f77/*.cpp") + + Glob("#samples/f90/*.f90") + Glob("#samples/f90/README.rst")) + for fort_file in fort_files: + env.Depends(sphinxdocs, + localenv.Command(f"#build/doc/samples/fortran/{fort_file.name}", + fort_file, Copy("$TARGET", "$SOURCE"))) + # Create a list of MATLAB classes to document. This uses the NamedTuple # structure defined at the top of the file. The @Data and @Utilities # classes are fake classes for the purposes of documentation only. Each diff --git a/doc/sphinx/conf.py b/doc/sphinx/conf.py index 31056ca7d0..84c66c5191 100644 --- a/doc/sphinx/conf.py +++ b/doc/sphinx/conf.py @@ -49,16 +49,18 @@ sphinx_gallery_conf = { 'filename_pattern': '\.py', - 'example_extensions': {'.py', '.cpp', '.h'}, + 'example_extensions': {'.py', '.cpp', '.h', '.f', '.f90'}, "filetype_parsers": {'.h': 'C++'}, 'image_srcset': ["2x"], 'examples_dirs': [ '../samples/python/', '../samples/cxx/', + '../samples/fortran/', ], 'gallery_dirs': [ 'examples/python', 'examples/cxx', + 'examples/fortran', ], 'reference_url': { 'cantera': None, # 'None' means the locally-documented module @@ -120,6 +122,8 @@ def executable_script(src_file, gallery_conf): tags_badge_colors = { "Python": "secondary", "C++": "secondary", + "Fortran 77": "secondary", + "Fortran 90": "secondary", } autodoc_default_options = { diff --git a/doc/sphinx/index.rst b/doc/sphinx/index.rst index 85708291c4..deed1da895 100644 --- a/doc/sphinx/index.rst +++ b/doc/sphinx/index.rst @@ -17,5 +17,6 @@ format. examples/python/index examples/cxx/index + examples/fortran/index - _tags/tagsindex \ No newline at end of file + _tags/tagsindex diff --git a/samples/f77/SConscript b/samples/f77/SConscript index f73e120a95..1fa20bce95 100644 --- a/samples/f77/SConscript +++ b/samples/f77/SConscript @@ -6,7 +6,7 @@ localenv = env.Clone() # (program name, [source files]) samples = [("ctlib", ["ctlib.f"]), - ("demo", ["demo.f"]), + ("demo", ["f77_demo.f"]), ("isentropic", ["isentropic.f"])] ftn_demo = localenv.SharedObject('demo_ftnlib.cpp', diff --git a/samples/f77/SConstruct.in b/samples/f77/SConstruct.in index 838e51d4ca..37d86cda6e 100644 --- a/samples/f77/SConstruct.in +++ b/samples/f77/SConstruct.in @@ -16,7 +16,7 @@ ftnlib = env.SharedObject('demo_ftnlib.cpp') ctlib = env.Program('ctlib', [ftnlib, 'ctlib.f'], LINK='@FORTRAN_LINK@') -demo = env.Program('demo', [ftnlib, 'demo.f'], +demo = env.Program('demo', [ftnlib, 'f77_demo.f'], LINK='@FORTRAN_LINK@') isentropic = env.Program('isentropic', [ftnlib, 'isentropic.f'], LINK='@FORTRAN_LINK@') diff --git a/samples/f77/ctlib.f b/samples/f77/ctlib.f index 1556506b11..e0720c7d6f 100644 --- a/samples/f77/ctlib.f +++ b/samples/f77/ctlib.f @@ -1,27 +1,31 @@ c c CKLIB emulation +c =============== c c This example shows how to implement subroutines that emulate those -c of the Chemkin CKLIB library. This may be useful to port an -c existing Chemkin-based application to Cantera. As shown here, the -c subroutine names begin with 'ct' instead of 'ck', so that Cantera -c and CKLIB subroutines can be both used in an application, if -c desired. It is also possible to rename these subroutines with the -c 'ck' prefix if the application is not linked to the Chemkin CKLIB -c library. In this case, application programs do not need to be -c modified or recompiled - they only need to be relinked. +c of the Chemkin CKLIB library. c -c Relies on the wrapper functions defined in demo_ftnlib.cpp to call the -c Cantera C++ interface. +c This may be useful to port an existing Chemkin-based application +c to Cantera. As shown here, the subroutine names begin with ``ct`` +c instead of ``ck``, so that Cantera and CKLIB subroutines can be +c both used in an application, if desired. It is also possible to +c rename these subroutines with the ``ck`` prefix if the application +c is not linked to the Chemkin CKLIB library. In this case, +c application programs do not need to be modified or recompiled - +c they only need to be relinked. +c +c Relies on the wrapper functions defined in :doc:`demo_ftnlib.cpp +c ` to call the Cantera C++ interface. c c Only a few subroutines are implemented here, but the same idea can c be applied to create Cantera-based versions of any other c subroutines in the CKLIB library. c -c Keywords: tutorial, kinetics +c .. tags:: Fortran 77, tutorial, kinetics -c This file is part of Cantera. See License.txt in the top-level directory or -c at https://cantera.org/license.txt for license and copyright information. +c This file is part of Cantera. See License.txt in the top-level +c directory or at https://cantera.org/license.txt for license and +c copyright information. c----------------------------------------------------------------------- c example driver program diff --git a/samples/f77/demo_ftnlib.cpp b/samples/f77/demo_ftnlib.cpp index bc8782e926..c337d42b93 100644 --- a/samples/f77/demo_ftnlib.cpp +++ b/samples/f77/demo_ftnlib.cpp @@ -1,5 +1,6 @@ -/*! - * demo_ftnlib.cpp +/* + * Fortran 77 wrapper library + * ========================== * * This file is an example of how to write an interface to use Cantera * in Fortran 77 programs. The basic idea is to store pointers to @@ -8,7 +9,7 @@ * * This particular example defines functions that return thermodynamic * properties, transport properties, and kinetic rates for reacting - * ideal gas mixtures. Only a single pointer to an IdealGasPhase object is + * ideal gas mixtures. Only a single pointer to an :ct:`IdealGasPhase` object is * stored, so only one reaction mechanism may be used at any one time in * the application. Of course, it is a simple modification to store * multiple objects if it is desired to use multiple reaction diff --git a/samples/f77/demo.f b/samples/f77/f77_demo.f similarity index 80% rename from samples/f77/demo.f rename to samples/f77/f77_demo.f index 0575715435..facac04c2c 100644 --- a/samples/f77/demo.f +++ b/samples/f77/f77_demo.f @@ -1,13 +1,17 @@ -c Fortran 77 Demo +c Fortran 77 demo +c =============== c -c This program uses functions defined in demo_ftnlib.cpp to create -c an ideal gas mixture and print some of its properties. +c This program uses functions defined in :doc:`demo_ftnlib.cpp +c ` to create an ideal gas mixture and print some of +c its properties. c -c For a C++ version of this program, see ../cxx/demo.cpp. +c For a C++ version of this program, see :doc:`demo.cpp +c <../cxx/demo>`. c c Replace this sample main program with your program c -c Keywords: tutorial, thermodynamics, kinetics, transport +c .. tags:: Fortran 77, tutorial, thermodynamics, kinetics, +c transport c This file is part of Cantera. See License.txt in the top-level directory or c at https://cantera.org/license.txt for license and copyright information. @@ -34,8 +38,11 @@ program demo write(*,10) temperature(), pressure(), density(), $ enthalpy_mole(), entropy_mole(), cp_mole() -c compute the equilibrium state holding the specific -c enthalpy and pressure constant +c %% +c Compute the equilibrium state +c ----------------------------- +c +c Hold the specific enthalpy and pressure constant. call equilibrate('HP') write(*,*) 'Equilibrium state properties:' @@ -50,8 +57,9 @@ program demo $ 'Molar cp: ',g14.5,' J/kmol-K'//) -c +c %% c Reaction information +c -------------------- c irxns = nReactions() @@ -70,9 +78,9 @@ program demo 20 format(a27,3e14.5,' kmol/m3/s') end do -c +c %% c Transport properties -c +c -------------------- dnu = viscosity() dlam = thermalConductivity() call getMixDiffCoeffs(diff) diff --git a/samples/f77/isentropic.f b/samples/f77/isentropic.f index 616c3c60be..e0a27ed09d 100644 --- a/samples/f77/isentropic.f +++ b/samples/f77/isentropic.f @@ -1,11 +1,13 @@ -c Isentropic Flow +c Isentropic flow +c =============== c -c Calculated Mach number vs. area for an isentropic flow. Relies on the -c wrapper functions defined in demo_ftnlib.cpp to call the Cantera C++ -c interface. See also the Python version of this problem in the Python -c examples. +c Calculated Mach number vs. area for an isentropic flow. Relies on +c the wrapper functions defined in :doc:`demo_ftnlib.cpp +c ` to call the Cantera C++ interface. +c See also the Python version of this problem in +c :doc:`isentropic.py <../python/thermo/isentropic>`. c -c Keywords: compressible flow +c .. tags:: Fortran 77, compressible flow c This file is part of Cantera. See License.txt in the top-level directory or c at https://cantera.org/license.txt for license and copyright information. diff --git a/samples/f90/README.rst b/samples/f90/README.rst new file mode 100644 index 0000000000..90db496632 --- /dev/null +++ b/samples/f90/README.rst @@ -0,0 +1,4 @@ +Fortran Examples +================ + +Examples for both Fortran 77 and Fortran 90. diff --git a/samples/f90/demo.f90 b/samples/f90/demo.f90 index 0acc922ae1..3da759a375 100644 --- a/samples/f90/demo.f90 +++ b/samples/f90/demo.f90 @@ -1,9 +1,10 @@ -! Fortran 90 Demo +! Fortran 90 demo +! =============== ! ! This program illustrates using Cantera in Fortran 90 to compute ! thermodynamic, kinetic, and transport properties of a gas mixture. ! -! Keywords: tutorial, equilibrium, thermodynamics, kinetics, transport +! .. tags:: Fortran 90, tutorial, equilibrium, thermodynamics, kinetics, transport ! This file is part of Cantera. See License.txt in the top-level directory or ! at https://cantera.org/license.txt for license and copyright information. From c7284fd87e5a6e6d329ec887a90928633f76769a Mon Sep 17 00:00:00 2001 From: Ray Speth Date: Wed, 20 Sep 2023 14:49:35 -0400 Subject: [PATCH 12/22] Add clib example to sphinx-gallery --- doc/SConscript | 7 +++++++ doc/sphinx/conf.py | 5 ++++- doc/sphinx/index.rst | 1 + samples/clib/README.rst | 6 ++++++ samples/clib/demo.c | 8 ++++++-- 5 files changed, 24 insertions(+), 3 deletions(-) create mode 100644 samples/clib/README.rst diff --git a/doc/SConscript b/doc/SConscript index 9b74cd2814..729abc8361 100644 --- a/doc/SConscript +++ b/doc/SConscript @@ -146,6 +146,13 @@ if localenv['sphinx_docs']: localenv.Command(f"#build/doc/samples/fortran/{fort_file.name}", fort_file, Copy("$TARGET", "$SOURCE"))) + # Gather clib sample files + clib_files = Glob("#samples/clib/*.c") + [File("#samples/clib/README.rst")] + for clib_file in clib_files: + env.Depends(sphinxdocs, + localenv.Command(f"#build/doc/samples/clib/{clib_file.name}", + clib_file, Copy("$TARGET", "$SOURCE"))) + # Create a list of MATLAB classes to document. This uses the NamedTuple # structure defined at the top of the file. The @Data and @Utilities # classes are fake classes for the purposes of documentation only. Each diff --git a/doc/sphinx/conf.py b/doc/sphinx/conf.py index 84c66c5191..2ee5546cf2 100644 --- a/doc/sphinx/conf.py +++ b/doc/sphinx/conf.py @@ -49,17 +49,19 @@ sphinx_gallery_conf = { 'filename_pattern': '\.py', - 'example_extensions': {'.py', '.cpp', '.h', '.f', '.f90'}, + 'example_extensions': {'.py', '.cpp', '.h', '.c', '.f', '.f90'}, "filetype_parsers": {'.h': 'C++'}, 'image_srcset': ["2x"], 'examples_dirs': [ '../samples/python/', '../samples/cxx/', + '../samples/clib/', '../samples/fortran/', ], 'gallery_dirs': [ 'examples/python', 'examples/cxx', + 'examples/clib', 'examples/fortran', ], 'reference_url': { @@ -122,6 +124,7 @@ def executable_script(src_file, gallery_conf): tags_badge_colors = { "Python": "secondary", "C++": "secondary", + "C": "secondary", "Fortran 77": "secondary", "Fortran 90": "secondary", } diff --git a/doc/sphinx/index.rst b/doc/sphinx/index.rst index deed1da895..66045454c4 100644 --- a/doc/sphinx/index.rst +++ b/doc/sphinx/index.rst @@ -17,6 +17,7 @@ format. examples/python/index examples/cxx/index + examples/clib/index examples/fortran/index _tags/tagsindex diff --git a/samples/clib/README.rst b/samples/clib/README.rst new file mode 100644 index 0000000000..3b6b460fa1 --- /dev/null +++ b/samples/clib/README.rst @@ -0,0 +1,6 @@ +C Examples +========== + +These examples demonstrate the usage of Cantera's C interface library, ``clib``, +which can also be used to call Cantera from other languages that are able to +call C functions. diff --git a/samples/clib/demo.c b/samples/clib/demo.c index 770c567e9a..51cb896d4d 100644 --- a/samples/clib/demo.c +++ b/samples/clib/demo.c @@ -1,11 +1,13 @@ -/** +/* * CLib Demo + * ========= * * This program illustrates using Cantera's C-library interface to compute * thermodynamic, kinetic, and transport properties of a gas mixture. In addition, * a simple reactor network simulation is illustrated. * - * Keywords: tutorial, equilibrium, thermodynamics, kinetics, transport, reactor network + * .. tags:: C, tutorial, equilibrium, thermodynamics, kinetics, transport, + * reactor network */ // This file is part of Cantera. See License.txt in the top-level directory or @@ -16,6 +18,7 @@ #include +// sphinx_gallery_start_ignore // The following header files are not used by this example, but are nevertheless added // here to ensure C-compatibility of Cantera's clib includes in continuous testing. #include "cantera/clib/ctfunc.h" @@ -23,6 +26,7 @@ #include "cantera/clib/ctonedim.h" #include "cantera/clib/ctrpath.h" #include "cantera/clib/ctsurf.h" +// sphinx_gallery_end_ignore void exit_with_error() { From 7c2573e5b23b7ed9242f715b2dad095193be3a52 Mon Sep 17 00:00:00 2001 From: Ray Speth Date: Thu, 21 Sep 2023 23:19:09 -0400 Subject: [PATCH 13/22] Add Matlab examples to sphinx-gallery --- doc/SConscript | 4 +- doc/sphinx/conf.py | 8 ++- doc/sphinx/index.rst | 1 + samples/matlab_experimental/PFR_solver.m | 14 +++-- samples/matlab_experimental/README.rst | 5 ++ samples/matlab_experimental/catcomb.m | 58 ++++++++++--------- samples/matlab_experimental/conhp.m | 6 +- samples/matlab_experimental/conuv.m | 6 +- samples/matlab_experimental/diamond_cvd.m | 14 +++-- samples/matlab_experimental/diff_flame.m | 27 ++++----- samples/matlab_experimental/equil.m | 4 +- samples/matlab_experimental/flame.m | 4 +- samples/matlab_experimental/flame1.m | 15 ++--- samples/matlab_experimental/flame2.m | 22 +++---- samples/matlab_experimental/ignite.m | 33 ++++++----- samples/matlab_experimental/ignite_hp.m | 8 ++- samples/matlab_experimental/ignite_uv.m | 8 ++- samples/matlab_experimental/isentropic.m | 4 +- .../matlab_experimental/lithium_ion_battery.m | 18 +++--- samples/matlab_experimental/periodic_cstr.m | 17 ++++-- samples/matlab_experimental/plotSolution.m | 13 ++--- .../matlab_experimental/plug_flow_reactor.m | 19 +++--- samples/matlab_experimental/prandtl1.m | 4 +- samples/matlab_experimental/prandtl2.m | 6 +- samples/matlab_experimental/rankine.m | 7 ++- samples/matlab_experimental/reactor1.m | 6 +- samples/matlab_experimental/reactor2.m | 6 +- samples/matlab_experimental/reactor_ode.m | 18 +++--- samples/matlab_experimental/surf_reactor.m | 6 +- 29 files changed, 203 insertions(+), 158 deletions(-) create mode 100644 samples/matlab_experimental/README.rst diff --git a/doc/SConscript b/doc/SConscript index 729abc8361..7dcff1dbfb 100644 --- a/doc/SConscript +++ b/doc/SConscript @@ -121,12 +121,14 @@ if localenv['sphinx_docs']: copy_sphinx = localenv.RecursiveInstall("#build/doc/sphinx", "sphinx") copy_python_samples = localenv.RecursiveInstall("#build/doc/samples/python", "#samples/python") + copy_matlab_ex_samples = localenv.RecursiveInstall( + "#build/doc/samples/matlab_experimental", "#samples/matlab_experimental") sphinxdocs = build(localenv.Command('build/doc/sphinx/html/index.html', 'sphinx/conf.py', build_sphinx)) env.Alias('sphinx', sphinxdocs) env.Depends(sphinxdocs, copy_sphinx) - env.Depends(sphinxdocs, copy_python_samples) + env.Depends(sphinxdocs, [copy_python_samples, copy_matlab_ex_samples]) env.Depends(sphinxdocs, env['python_module']) # Gather all C++ samples into a single directory so they can be presented a single diff --git a/doc/sphinx/conf.py b/doc/sphinx/conf.py index 2ee5546cf2..c639652b20 100644 --- a/doc/sphinx/conf.py +++ b/doc/sphinx/conf.py @@ -49,20 +49,23 @@ sphinx_gallery_conf = { 'filename_pattern': '\.py', - 'example_extensions': {'.py', '.cpp', '.h', '.c', '.f', '.f90'}, - "filetype_parsers": {'.h': 'C++'}, + 'example_extensions': {'.py', '.cpp', '.h', '.c', '.f', '.f90', '.m'}, + "filetype_parsers": {'.h': 'C++', '.m': 'Matlab'}, + 'ignore_pattern': r'(__.*__\.py|test_examples\.m)', 'image_srcset': ["2x"], 'examples_dirs': [ '../samples/python/', '../samples/cxx/', '../samples/clib/', '../samples/fortran/', + '../samples/matlab_experimental/', ], 'gallery_dirs': [ 'examples/python', 'examples/cxx', 'examples/clib', 'examples/fortran', + 'examples/matlab_experimental', ], 'reference_url': { 'cantera': None, # 'None' means the locally-documented module @@ -125,6 +128,7 @@ def executable_script(src_file, gallery_conf): "Python": "secondary", "C++": "secondary", "C": "secondary", + "Matlab": "secondary", "Fortran 77": "secondary", "Fortran 90": "secondary", } diff --git a/doc/sphinx/index.rst b/doc/sphinx/index.rst index 66045454c4..7ab886d53f 100644 --- a/doc/sphinx/index.rst +++ b/doc/sphinx/index.rst @@ -18,6 +18,7 @@ format. examples/python/index examples/cxx/index examples/clib/index + examples/matlab_experimental/index examples/fortran/index _tags/tagsindex diff --git a/samples/matlab_experimental/PFR_solver.m b/samples/matlab_experimental/PFR_solver.m index 79e056594b..a713291a77 100644 --- a/samples/matlab_experimental/PFR_solver.m +++ b/samples/matlab_experimental/PFR_solver.m @@ -1,10 +1,14 @@ function F = PFR_Solver(x, soln_vector, gas, mdot, A_in, dAdx, k) + %% Plug flow reactor governing equations + % % This function defines the spatial derivatives for an ideal gas plug-flow - % reactor, where the cross-sectional area and pressure are allowed to vary, - % axially. The model is set up by the example file 'PFR.m', - % which points the integrator to this function. The integrator integrates the - % derivatives spatially, to solve the density, temperature, and species mass - % fraction profiles as a function of distance x. + % reactor, where the cross-sectional area and pressure are allowed to vary + % axially. + % + % The model is set up by the example file :doc:`plug_flow_reactor.m + % `, which points the integrator to this function. The integrator + % integrates the derivatives spatially, to solve the density, temperature, and + % species mass fraction profiles as a function of distance x. rho = soln_vector(1); T = soln_vector(2); diff --git a/samples/matlab_experimental/README.rst b/samples/matlab_experimental/README.rst new file mode 100644 index 0000000000..dbeb918df8 --- /dev/null +++ b/samples/matlab_experimental/README.rst @@ -0,0 +1,5 @@ +Matlab (experimental) Examples +============================== + +These examples are written for use with the "experimental" version of the Cantera Matlab +toolbox that was introduced with Cantera 3.0. diff --git a/samples/matlab_experimental/catcomb.m b/samples/matlab_experimental/catcomb.m index ac830166ff..1db198e25b 100644 --- a/samples/matlab_experimental/catcomb.m +++ b/samples/matlab_experimental/catcomb.m @@ -1,4 +1,4 @@ -%% CATCOMB - Catalytic combustion of a stagnation flow on a platinum surface +%% Catalytic combustion of a stagnation flow on a platinum surface % % This script solves a catalytic combustion problem. A stagnation flow % is set up, with a gas inlet 10 cm from a platinum surface at 900 @@ -10,7 +10,7 @@ % The catalytic combustion mechanism is from Deutschmann et al., 26th % Symp. (Intl.) on Combustion,1996 pp. 1747-1754 % -% Keywords: combustion, catalysis, 1D flow, surface chemistry +% .. tags:: Matlab, combustion, catalysis, 1D flow, surface chemistry %% Initialization @@ -29,6 +29,7 @@ mdot = 0.06; % kg/m^2/s transport = 'mixture-averaged'; % transport model +%% % Solve first for a hydrogen/air case for use as the initial estimate for % the methane/air case. @@ -45,19 +46,17 @@ tol_ss = {1.0e-8 1.0e-14}; % {rtol atol} for steady-state problem tol_ts = {1.0e-4 1.0e-9}; % {rtol atol} for time stepping -loglevel = 1; % amount of diagnostic output -% (0 to 5) +loglevel = 1; % amount of diagnostic output (0 to 5) -refine_grid = 1; % 1 to enable refinement, 0 to -% disable +refine_grid = 1; % 1 to enable refinement, 0 to disable %% Create the gas object % % This object will be used to evaluate all thermodynamic, kinetic, % and transport properties % -% The gas phase will be taken from the definition of phase 'gas' in -% input file 'ptcombust.yaml', which is a stripped-down version of +% The gas phase will be taken from the definition of phase ``gas`` in +% input file ``ptcombust.yaml``, which is a stripped-down version of % GRI-Mech 3.0. gas = Solution('ptcombust.yaml', 'gas', transport); @@ -66,20 +65,22 @@ %% Create the interface object % % This object will be used to evaluate all surface chemical production -% rates. It will be created from the interface definition 'Pt_surf' -% in input file 'ptcombust.yaml,' which implements the reaction +% rates. It will be created from the interface definition ``Pt_surf`` +% in input file ``ptcombust.yaml``, which implements the reaction % mechanism of Deutschmann et al., 1995 for catalytic combustion on % platinum. surf_phase = Interface('ptcombust.yaml', 'Pt_surf', gas); surf_phase.TP = {tsurf, surf_phase.P}; -% integrate the coverage equations in time for 1 s, holding the gas +%% +% Integrate the coverage equations in time for 1 s, holding the gas % composition fixed to generate a good starting estimate for the % coverages. surf_phase.advanceCoverages(1.0); +%% % The two objects we just created are independent of the problem % type -- they are useful in zero-D simulations, 1-D simulations, % etc. Now we turn to creating the objects that are specifically @@ -90,7 +91,7 @@ % % The flow object is responsible for evaluating the 1D governing % equations for the flow. We will initialize it with the gas -% object, and assign it the name 'flow'. +% object, and assign it the name ``flow``. flow = AxisymmetricFlow(gas, 'flow'); @@ -100,11 +101,11 @@ flow.setSteadyTolerances('default', tol_ss{:}); flow.setTransientTolerances('default', tol_ts{:}); -%% create the inlet +%% Create the inlet % -% The temperature, mass flux, and composition (relative molar) may be -% specified. This object provides the inlet boundary conditions for -% the flow equations. +% The temperature, mass flux, and composition (relative molar) may be +% specified. This object provides the inlet boundary conditions for +% the flow equations. inlt = Inlet(gas, 'inlet'); @@ -113,10 +114,10 @@ inlt.massFlux = mdot; inlt.setMoleFractions(comp1); -%% create the surface +%% Create the surface % % This object provides the surface boundary conditions for the flow -% equations. By supplying object surface_phase as an argument, the +% equations. By supplying object ``surface_phase`` as an argument, the % coverage equations for its surface species will be added to the % equation set, and used to compute the surface production rates of % the gas-phase species. @@ -124,7 +125,7 @@ surf = ReactingSurface(surf_phase, 'surface'); surf.T = tsurf; -%% create the stack +%% Create the stack % % Once the component parts have been created, they can be assembled % to create the 1D simulation. @@ -148,21 +149,23 @@ stack.setMaxJacAge(4, 5); %% Solution - -% start with the energy equation on +% Start with the energy equation on flow.energyEnabled = true; -% disable the surface coverage equations, and turn off all gas and +%% +% Disable the surface coverage equations, and turn off all gas and % surface chemistry surf.coverageEnabled = false; surf_phase.setMultiplier(0.0); gas.setMultiplier(0.0); -% solve the problem, refining the grid if needed +%% +% Solve the problem, refining the grid if needed stack.solve(1, refine_grid); -% now turn on the surface coverage equations, and turn the +%% +% Now turn on the surface coverage equations, and turn the % chemistry on slowly surf.coverageEnabled = true; @@ -174,14 +177,17 @@ stack.solve(1, refine_grid); end +%% % At this point, we should have the solution for the hydrogen/air % problem. Now switch the inlet to the methane/air composition. inlt.setMoleFractions(comp2); -% set more stringent grid refinement criteria +%% +% Set more stringent grid refinement criteria stack.setRefineCriteria(2, 100.0, 0.15, 0.2); -% solve the problem for the final time +%% +% Solve the problem for the final time stack.solve(loglevel, refine_grid); %% Show statistics diff --git a/samples/matlab_experimental/conhp.m b/samples/matlab_experimental/conhp.m index f4f310b8e1..bd0edc3b8c 100644 --- a/samples/matlab_experimental/conhp.m +++ b/samples/matlab_experimental/conhp.m @@ -1,9 +1,9 @@ function dydt = conhp(t, y, gas, mw) - % CONHP - ODE system for a constant-pressure, adiabatic reactor. + %% ODE system for a constant-pressure, adiabatic reactor % - % Function CONHP evaluates the system of ordinary differential equations + % Function ``CONHP`` evaluates the system of ordinary differential equations % for an adiabatic, constant-pressure, zero-dimensional reactor. - % It assumes that the 'gas' object represents a reacting ideal gas mixture. + % It assumes that the ``gas`` object represents a reacting ideal gas mixture. % Set the state of the gas, based on the current solution vector. gas.Y = y(2:end); diff --git a/samples/matlab_experimental/conuv.m b/samples/matlab_experimental/conuv.m index 934c9c4933..4c60b38670 100644 --- a/samples/matlab_experimental/conuv.m +++ b/samples/matlab_experimental/conuv.m @@ -1,9 +1,9 @@ function dydt = conuv(t, y, gas, mw) - % CONUV ODE system for a constant-volume, adiabatic reactor. + %% ODE system for a constant-volume, adiabatic reactor % - % Function CONUV evaluates the system of ordinary differential + % Function ``CONUV`` evaluates the system of ordinary differential % equations for an adiabatic, constant-volume, zero-dimensional reactor. - % It assumes that the 'gas' object represents a reacting ideal gas mixture. + % It assumes that the ``gas`` object represents a reacting ideal gas mixture. % Set the state of the gas, based on the current solution vector. gas.Y = y(2:end); diff --git a/samples/matlab_experimental/diamond_cvd.m b/samples/matlab_experimental/diamond_cvd.m index 9b6480c5eb..fd5803df71 100644 --- a/samples/matlab_experimental/diamond_cvd.m +++ b/samples/matlab_experimental/diamond_cvd.m @@ -1,16 +1,18 @@ -%% DIAMOND_CVD - A CVD example simulating growth of a diamond film +%% Simulating growth of a diamond film by CVD % % This example computes the growth rate of a diamond film according to a % simplified version of a particular published growth mechanism (see file -% diamond.yaml for details). Only the surface coverage equations are solved +% ``diamond.yaml`` for details). Only the surface coverage equations are solved % here; the gas composition is fixed. (For an example of coupled gas-phase -% and surface, see catalytic_combustion.py.) Atomic hydrogen plays an -% important role in diamond CVD, and this example computes the growth rate -% and surface coverages as a function of [H] at the surface for +% and surface, see :doc:`catcomb.m `). +% +% Atomic hydrogen plays an important role in diamond CVD, and this example computes the +% growth rate and surface coverages as a function of [H] at the surface for % fixed temperature and [CH3]. % % Requires: cantera >= 2.6.0, pandas >= 0.25.0, matplotlib >= 2.0 -% Keywords: surface chemistry, kinetics +% +% .. tags:: Matlab, surface chemistry, kinetics %% Initialization diff --git a/samples/matlab_experimental/diff_flame.m b/samples/matlab_experimental/diff_flame.m index 0aa7aeb32c..021e54f0ef 100644 --- a/samples/matlab_experimental/diff_flame.m +++ b/samples/matlab_experimental/diff_flame.m @@ -1,10 +1,11 @@ -%% DIFF_FLAME - An opposed-flow diffusion flame. +%% Opposed-flow diffusion flame % -% This example uses the CounterFlowDiffusionFlame function to solve an +% This example uses the ``CounterFlowDiffusionFlame`` function to solve an % opposed-flow diffusion flame for Ethane in Air. This example is the same -% as the diffusion_flame.py example without radiation. +% as the :doc:`diffusion_flame.py <../python/onedim/diffusion_flame>` +% example without radiation. % -% Keywords: combustion, 1D flow, diffusion flame, plotting +% .. tags:: Matlab, combustion, 1D flow, diffusion flame, plotting %% Initialization @@ -49,7 +50,7 @@ %% Set-up the flow object % -% For this problem, the AxisymmetricFlow model is needed. Set the state of +% For this problem, the ``AxisymmetricFlow`` model is needed. Set the state of % the flow as the fuel gas object. This is arbitrary and is only used to % initialize the flow object. Set the grid to the initial grid defined % prior, same for the tolerances. @@ -76,11 +77,11 @@ inlet_f.massFlux = mdot_f; inlet_f.setMoleFractions(fuelcomp); -%% Create the flame object. +%% Create the flame object % % Once the inlets have been created, they can be assembled -% to create the flame object. Function CounterFlorDiffusionFlame -% (in Cantera/1D) sets up the initial guess for the solution using a +% to create the flame object. Function ``CounterFlorDiffusionFlame`` +% (in ``Cantera/1D``) sets up the initial guess for the solution using a % Burke-Schumann flame. The input parameters are: fuel inlet object, flow % object, oxidizer inlet object, fuel gas object, oxidizer gas object, and % the name of the oxidizer species as in character format. @@ -94,28 +95,28 @@ fl.solve(loglevel, 0); -%% Enable the energy equation. +%% Enable the energy equation % % The energy equation will now be solved to compute the temperature profile. % We also tighten the grid refinement criteria to get an accurate final -% solution. The explanation of the setRefineCriteria function is located +% solution. The explanation of the ``setRefineCriteria`` function is located % on cantera.org in the Matlab User's Guide and can be accessed by -% help setRefineCriteria +% ``help setRefineCriteria``. f.energyEnabled = true; fl.setRefineCriteria(2, 200.0, 0.1, 0.2); fl.solve(loglevel, refine_grid); -%% Show statistics of solution and elapsed time. +%% Show statistics of solution and elapsed time fl.writeStats; elapsed = cputime - runtime; e = sprintf('Elapsed CPU time: %10.4g', elapsed); disp(e); +%% Plot results % Make a single plot showing temperature and mass fraction of select % species along axial distance from fuel inlet to air inlet. -% z = fl.grid('flow'); % Get grid points of flow spec = fuel.speciesNames; % Get species names in gas diff --git a/samples/matlab_experimental/equil.m b/samples/matlab_experimental/equil.m index db8253fd05..e06aaae1dd 100644 --- a/samples/matlab_experimental/equil.m +++ b/samples/matlab_experimental/equil.m @@ -1,10 +1,10 @@ function equil(g) - %% EQUIL - A chemical equilibrium example. + %% Methane/air chemical equilibrium % % This example computes the adiabatic flame temperature and equilibrium % composition for a methane/air mixture as a function of equivalence ratio. % - % Keywords: combustion, equilibrium, plotting + % .. tags:: Matlab, combustion, equilibrium, plotting clear all close all diff --git a/samples/matlab_experimental/flame.m b/samples/matlab_experimental/flame.m index c0f9db3a4d..12ba9beeb5 100644 --- a/samples/matlab_experimental/flame.m +++ b/samples/matlab_experimental/flame.m @@ -1,6 +1,8 @@ function f = flame(gas, left, flow, right) - % FLAME - create a flame object. + %% Utility for flame setup % + % Used by the :doc:`flame1.m ` and :doc:`flame2.m ` examples. + % Check input parameters if nargin ~= 4 error('wrong number of input arguments.'); diff --git a/samples/matlab_experimental/flame1.m b/samples/matlab_experimental/flame1.m index 00f2f296fc..32c55986b4 100644 --- a/samples/matlab_experimental/flame1.m +++ b/samples/matlab_experimental/flame1.m @@ -1,9 +1,9 @@ -%% FLAME1 - A burner-stabilized flat flame +%% Burner-stabilized flat flame % % This script simulates a burner-stablized lean hydrogen-oxygen flame % at low pressure. % -% Keywords: combustion, 1D flow, burner-stabilized flame, plotting +% .. tags:: Matlab, combustion, 1D flow, burner-stabilized flame, plotting %% Initialization @@ -57,7 +57,7 @@ %% Create the burner % -% The burner is an Inlet object. The temperature, mass flux, +% The burner is an ``Inlet`` object. The temperature, mass flux, % and composition (relative molar) may be specified. burner = Inlet(gas, 'burner'); burner.T = tburner; @@ -67,7 +67,7 @@ %% Create the outlet % % The type of flame is determined by the object that terminates -% the domain. An Outlet object imposes zero gradient boundary +% the domain. An ``Outlet`` object imposes zero gradient boundary % conditions for the temperature and mass fractions, and zero % radial velocity and radial pressure gradient. @@ -76,14 +76,15 @@ %% Create the flame object % % Once the component parts have been created, they can be assembled -% to create the flame object. -% +% to create the flame object (see :doc:`flame.m `). fl = flame(gas, burner, f, s); fl.setMaxJacAge(max_jacobian_age(1), max_jacobian_age(2)); +%% % if the starting solution is to be read from a previously-saved % solution, uncomment this line and edit the file name and solution id. -%restore(fl,'h2flame2.xml', 'energy') + +%restore(fl,'h2flame2.yaml', 'energy') fl.solve(loglevel, refine_grid); diff --git a/samples/matlab_experimental/flame2.m b/samples/matlab_experimental/flame2.m index b410a9b446..8e67e9846c 100644 --- a/samples/matlab_experimental/flame2.m +++ b/samples/matlab_experimental/flame2.m @@ -1,8 +1,8 @@ -%% FLAME2 - An axisymmetric stagnation-point non-premixed flame +%% Axisymmetric stagnation-point non-premixed flame % % This script simulates a stagnation-point ethane-air flame. % -% Keywords: combustion, 1D flow, strained flame, diffusion flame, plotting +% .. tags:: Matlab, combustion, 1D flow, strained flame, diffusion flame, plotting %% Initialization @@ -27,8 +27,7 @@ initial_grid = 0.02 * [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]; % m -tol_ss = {1.0e-5, 1.0e-13}; % {rtol atol} for steady-state -% problem +tol_ss = {1.0e-5, 1.0e-13}; % {rtol atol} for steady-state problem tol_ts = {1.0e-4, 1.0e-13}; % {rtol atol} for time stepping loglevel = 1; % amount of diagnostic output (0 to 5) @@ -55,8 +54,8 @@ %% Create the air inlet % -% The temperature, mass flux, and composition (relative molar) may be -% specified. +% The temperature, mass flux, and composition (relative molar) may be +% specified. inlet_o = Inlet(gas, 'air_inlet'); inlet_o.T = tin; @@ -77,18 +76,19 @@ fl = flame(gas, inlet_o, f, inlet_f); +%% % if the starting solution is to be read from a previously-saved % solution, uncomment this line and edit the file name and solution id. -%restore(fl,'h2flame2.xml', 'energy') -% solve with fixed temperature profile first +%restore(fl,'h2flame2.yaml', 'energy') + +% Solve with fixed temperature profile first fl.solve(loglevel, refine_grid); %% Enable the energy equation % -% The energy equation will now be solved to compute the -% temperature profile. We also tighten the grid refinement -% criteria to get an accurate final solution. +% The energy equation will now be solved to compute the temperature profile. We also +% tighten the grid refinement criteria to get an accurate final solution. f.energyEnabled = true; fl.setRefineCriteria(2, 200.0, 0.1, 0.1); diff --git a/samples/matlab_experimental/ignite.m b/samples/matlab_experimental/ignite.m index b12f5a881a..239b6c0aa3 100644 --- a/samples/matlab_experimental/ignite.m +++ b/samples/matlab_experimental/ignite.m @@ -1,11 +1,12 @@ function plotdata = ignite(g) - %% IGNITE Zero-dimensional kinetics: adiabatic, constant pressure. + %% Adiabatic, constant pressure reactor % - % This example solves the same problem as 'reactor1', but does - % it using one of MATLAB's ODE integrators, rather than using the - % Cantera Reactor class. + % This example solves the same problem as :doc:`reactor1.m `, but does it + % using one of MATLAB's ODE integrators, rather than using the Cantera Reactor + % class. See :doc:`reactor_ode.m ` for the implementation of the + % governing equations. % - % Keywords: combustion, reactor network, ignition delay, plotting + % .. tags:: Matlab, combustion, reactor network, ignition delay, plotting clear all close all @@ -37,36 +38,38 @@ plotdata = output(out, gas); - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % the functions below may be defined arbitrarily to set the reactor + %% Time-varying boundary conditions + % + % The functions below may be defined arbitrarily to set the reactor % boundary conditions - the rate of change of volume, the heat % flux, and the area. - + % % Rate of change of volume. Any arbitrary function may be implemented. + % % Input arguments: - % t time - % vol volume - % gas ideal gas object - + % :t: time + % :vol: volume + % :gas: ideal gas object function v = vdot(t, vol, gas) %v = 0.0; %uncomment for constant volume v = 1.e11 * (gas.P - 101325.0); % holds pressure very % close to 1 atm end + %% % heat flux (W/m^2). function q = heatflux(t, gas) q = 0.0; % adiabatic end + %% % surface area (m^2). Used only to compute heat transfer. function a = area(t, vol) a = 1.0; end - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - % Since the solution variables used by the 'reactor' function are + %% + % Since the solution variables used by the ``reactor`` function are % not necessarily those desired for output, this function is called % after the integration is complete to generate the desired % outputs. diff --git a/samples/matlab_experimental/ignite_hp.m b/samples/matlab_experimental/ignite_hp.m index 3f5ea45064..bb37aa751c 100644 --- a/samples/matlab_experimental/ignite_hp.m +++ b/samples/matlab_experimental/ignite_hp.m @@ -1,8 +1,10 @@ function ignite_hp(gas) - % IGNITE_HP Solves the same ignition problem as 'ignite', but uses - % function conhp instead of reactor. + %% Constant pressure ignition with user-specified equations % - % Keywords: combustion, user-defined model, ignition delay, plotting + % Solves the same ignition problem as :doc:`reactor1.m `, but uses + % function :doc:`conhp.m ` to implement the governing equations. + % + % .. tags:: Matlab, combustion, user-defined model, ignition delay, plotting clear all close all diff --git a/samples/matlab_experimental/ignite_uv.m b/samples/matlab_experimental/ignite_uv.m index 4d7191a573..04e55cedc2 100644 --- a/samples/matlab_experimental/ignite_uv.m +++ b/samples/matlab_experimental/ignite_uv.m @@ -1,8 +1,10 @@ function ignite_uv(gas) - % IGNITE_UV Solves the same ignition problem as 'ignite2', except - % function conuv is used instead of reactor. + %% Constant volume ignition with user-specified equations % - % Keywords: combustion, user-defined model, ignition delay, plotting + % Solves the same ignition problem as :doc:`reactor2.m `, except using + % function :doc:`conuv.m ` to implement the governing equations. + % + % .. tags:: Matlab, combustion, user-defined model, ignition delay, plotting clear all close all diff --git a/samples/matlab_experimental/isentropic.m b/samples/matlab_experimental/isentropic.m index cc3aba99ac..d0ac15ddf1 100644 --- a/samples/matlab_experimental/isentropic.m +++ b/samples/matlab_experimental/isentropic.m @@ -1,10 +1,10 @@ function isentropic(g) - %% ISENTROPIC - isentropic, adiabatic flow example + %% Isentropic, adiabatic flow % % In this example, the area ratio vs. Mach number curve is computed for a % hydrogen/nitrogen gas mixture. % - % Keywords: thermodynamics, compressible flow, plotting + % .. tags:: Matlab, thermodynamics, compressible flow, plotting clear all close all diff --git a/samples/matlab_experimental/lithium_ion_battery.m b/samples/matlab_experimental/lithium_ion_battery.m index 5d487180c2..b0215ab34f 100644 --- a/samples/matlab_experimental/lithium_ion_battery.m +++ b/samples/matlab_experimental/lithium_ion_battery.m @@ -1,25 +1,26 @@ -%% LITHIUM_ION_BATTERY +%% Lithium-ion battery % % This example file calculates the cell voltage of a lithium-ion battery % at given temperature, pressure, current, and range of state of charge (SOC). % % The thermodynamics are based on a graphite anode and a LiCoO2 cathode, -% modeled using the 'BinarySolutionTabulatedThermo' class. +% modeled using the :ct:`BinarySolutionTabulatedThermo` class. % Further required cell parameters are the electrolyte ionic resistance, % the stoichiometry ranges of the active materials (electrode balancing), % and the surface area of the active materials. % % The functionality of this example is presented in greater detail in the % reference (which also describes the derivation of the -% BinarySolutionTabulatedThermo class): +% :ct:`BinarySolutionTabulatedThermo` class). % % Reference: -% M. Mayur, S. C. DeCaluwe, B. L. Kee, W. G. Bessler, “Modeling and simulation -% of the thermodynamics of lithium-ion battery intercalation materials in the -% open-source software Cantera,” Electrochim. Acta 323, 134797 (2019), -% https://doi.org/10.1016/j.electacta.2019.134797 % -% Keywords: surface chemistry, kinetics, electrochemistry, battery, plotting +% M. Mayur, S. C. DeCaluwe, B. L. Kee, W. G. Bessler, “Modeling and simulation +% of the thermodynamics of lithium-ion battery intercalation materials in the +% open-source software Cantera,” Electrochim. Acta 323, 134797 (2019), +% https://doi.org/10.1016/j.electacta.2019.134797 +% +% .. tags:: Matlab, surface chemistry, kinetics, electrochemistry, battery, plotting %% Initialization @@ -43,6 +44,7 @@ S_ca = 1.1167; % [m^2] Cathode total active material surface area S_an = 0.7824; % [m^2] Anode total active material surface area +%% % Electrode balancing: The "balancing" of the electrodes relates the chemical % composition (lithium mole fraction in the active materials) to the macroscopic % cell-level state of charge. diff --git a/samples/matlab_experimental/periodic_cstr.m b/samples/matlab_experimental/periodic_cstr.m index ee4fbe2445..4e9690bc38 100644 --- a/samples/matlab_experimental/periodic_cstr.m +++ b/samples/matlab_experimental/periodic_cstr.m @@ -1,23 +1,28 @@ function periodic_cstr - %% PERIODIC_CSTR - A CSTR with steady inputs but periodic interior state. + %% Continuously stirred tank reactor with periodic behavior + % + % This example illustrates a continuously stirred tank reactor (CSTR) with + % steady inputs but periodic interior state. % % A stoichiometric hydrogen/oxygen mixture is introduced and reacts to % produce water. But since water has a large efficiency as a third body % in the chain termination reaction % - % H + O2 + M = HO2 + M + % .. math:: + % + % \mathrm{ H + O_2 + M \rightleftharpoons HO_2 + M } % % as soon as a significant amount of water is produced the reaction stops. % After enough time has passed that the water is exhausted from the reactor, % the mixture explodes again and the process repeats. This explanation can be - % verified by decreasing the rate for reaction 7 in file 'h2o2.yaml' and + % verified by decreasing the rate for reaction 7 in file ``h2o2.yaml`` and % re-running the example. % - % Acknowledgments: The idea for this example and an estimate of the + % *Acknowledgments*: The idea for this example and an estimate of the % conditions needed to see the oscillations came from Bob Kee, - % Colorado School of Mines + % Colorado School of Mines. % - % Keywords: combustion, reactor network, well-stirred reactor, plotting + % .. tags:: Matlab, combustion, reactor network, well-stirred reactor, plotting clear all close all diff --git a/samples/matlab_experimental/plotSolution.m b/samples/matlab_experimental/plotSolution.m index 03d188e098..9ad7a75777 100644 --- a/samples/matlab_experimental/plotSolution.m +++ b/samples/matlab_experimental/plotSolution.m @@ -1,15 +1,14 @@ function plotSolution(s, domain, component) - % Plot a specified solution component. :: + %% Utility for plotting a specific solution component % % >> plotSolution(s, domain, component) % - % :param s: + % :s: % Instance of class :mat:class:`Sim1D`. - % :param domain: - % Name of domain from which the component should be - % retrieved. - % :param component: - % Name of the component to be plotted. + % :domain: + % Name of domain from which the component should be retrieved. + % :component: + % Name of the component to be plotted n = s.stackIndex(domain); d = s.domains{n}; diff --git a/samples/matlab_experimental/plug_flow_reactor.m b/samples/matlab_experimental/plug_flow_reactor.m index 612b35c242..d0cf7d1b82 100644 --- a/samples/matlab_experimental/plug_flow_reactor.m +++ b/samples/matlab_experimental/plug_flow_reactor.m @@ -1,4 +1,4 @@ -%% Plug_Flow_Reactor (PFR) - to solve PFR equations for reactors +%% Nozzle with compressible flow % % This code snippet is to model a constant area and varying area % (converging and diverging) nozzle as Plug Flow Reactor with given @@ -8,19 +8,20 @@ % % The reactor assumes that the flow follows the Ideal Gas Law. % -% The governing equations used in this code can be referenced at: -% *S.R Turns, An Introduction to Combustion - Concepts and Applications, -% McGraw Hill Education, India, 2012, 206-210.* +% The governing equations used in this code (see :doc:`PFR_solver.m +% `) can be referenced at: +% +% *S.R Turns, An Introduction to Combustion - Concepts and Applications, +% McGraw Hill Education, India, 2012, 206-210.* % % The current example is written for methane combustion, but can be readily % adapted for other chemistries. % -% Developed by Ashwin Kumar/Dr.Joseph Meadows (mgak@vt.edu/jwm84@vt.edu) on 3-June-2020 -% Research Assistant/Assistant Professor -% Advanced Propulsion and Power Laboratory -% Virginia Tech +% Example originally developed by Ashwin Kumar (Research Assistant, mgak@vt.edu) and +% Dr. Joseph Meadows (Assistant Professor, jwm84@vt.edu), Advanced Propulsion and Power +% Laboratory, Virginia Tech. % -% Keywords: combustion, user-defined model, compressible flow, plotting +% .. tags:: Matlab, combustion, user-defined model, compressible flow, plotting %% Initialization diff --git a/samples/matlab_experimental/prandtl1.m b/samples/matlab_experimental/prandtl1.m index c80a2fb636..a6c038cdc5 100644 --- a/samples/matlab_experimental/prandtl1.m +++ b/samples/matlab_experimental/prandtl1.m @@ -1,11 +1,11 @@ function prandtl1(g) - %% PRANDTL1 - Prandtl number for an equilibrium H/O gas mixture. + %% Prandtl number for an equilibrium H/O gas mixture % % This example computes and plots the Prandtl number for a hydrogen / oxygen % mixture in chemical equilibrium for P = 1 atm and a range of temperatures % and elemental O/(O+H) ratios. % - % Keywords: equilibrium, transport, plotting + % .. tags:: Matlab, equilibrium, transport, plotting clear all close all diff --git a/samples/matlab_experimental/prandtl2.m b/samples/matlab_experimental/prandtl2.m index 355c8f020d..bc93a6992b 100644 --- a/samples/matlab_experimental/prandtl2.m +++ b/samples/matlab_experimental/prandtl2.m @@ -1,10 +1,10 @@ function prandtl2(g) - %% PRANDTL2 - Prandtl number for an equilibrium H/O gas mixture. + %% Prandtl number for an equilibrium H/O gas mixture % - % This example does the same thing as prandtl1, but using the + % This example does the same thing as :doc:`prandtl1.m `, but using the % multicomponent expression for the thermal conductivity. % - % Keywords: transport, equilibrium, multicomponent transport, plotting + % .. tags:: Matlab, transport, equilibrium, multicomponent transport, plotting clear all close all diff --git a/samples/matlab_experimental/rankine.m b/samples/matlab_experimental/rankine.m index faec48992b..44de1aedd4 100644 --- a/samples/matlab_experimental/rankine.m +++ b/samples/matlab_experimental/rankine.m @@ -1,6 +1,9 @@ -% RANKINE - This example computes the efficiency of a simple vapor power cycle. +%% Rankine cycle % -% Keywords: thermodynamics, thermodynamic cycle, non-ideal fluid +% Calculate the efficiency of a Rankine vapor power cycle using a pure fluid model +% for water. +% +% .. tags:: Matlab, thermodynamics, thermodynamic cycle, non-ideal fluid clear all close all diff --git a/samples/matlab_experimental/reactor1.m b/samples/matlab_experimental/reactor1.m index 924d5355db..f6d2232a6d 100644 --- a/samples/matlab_experimental/reactor1.m +++ b/samples/matlab_experimental/reactor1.m @@ -1,11 +1,11 @@ function reactor1(g) - %% REACTOR1 Zero-dimensional kinetics: adiabatic, constant pressure. + %% Adiabatic, constant pressure reactor % - % This example illustrates how to use class 'Reactor' for zero-dimensional + % This example illustrates how to use class ``Reactor`` for zero-dimensional % kinetics simulations. Here the parameters are set so that the reactor is % adiabatic and very close to constant pressure. % - % Keywords: combustion, reactor network, ignition delay, plotting + % .. tags:: Matlab, combustion, reactor network, ignition delay, plotting clear all close all diff --git a/samples/matlab_experimental/reactor2.m b/samples/matlab_experimental/reactor2.m index 15270dd173..06cc112b26 100644 --- a/samples/matlab_experimental/reactor2.m +++ b/samples/matlab_experimental/reactor2.m @@ -1,11 +1,11 @@ function reactor2(g) - %% REACTOR2 - Zero-dimensional kinetics: adiabatic, constant volume. + %% Adiabatic, constant volume reactor % - % This example illustrates how to use class 'Reactor' for zero-dimensional + % This example illustrates how to use class ``Reactor`` for zero-dimensional % kinetics simulations. Here the parameters are set so that the reactor is % adiabatic and constant volume. % - % Keywords: combustion, reactor network, ignition delay, plotting + % .. tags:: Matlab, combustion, reactor network, ignition delay, plotting clear all close all diff --git a/samples/matlab_experimental/reactor_ode.m b/samples/matlab_experimental/reactor_ode.m index 836c2cc240..4bd74b9d7d 100644 --- a/samples/matlab_experimental/reactor_ode.m +++ b/samples/matlab_experimental/reactor_ode.m @@ -1,16 +1,16 @@ function dydt = reactor_ode(t, y, gas, vdot, area, heatflux) - %% REACTOR ODE - system for a generic zero-dimensional reactor. + %% ODE system for a generic zero-dimensional reactor % - % Function REACTOR evaluates the system of ordinary differential equations - % for a zero-dimensional reactor with arbitrary heat transfer and - % volume change. + % Function ``REACTOR_ODE`` evaluates the system of ordinary differential equations + % for a zero-dimensional reactor with arbitrary heat transfer and volume change. + % Used in :doc:`ignite.m `. % % Solution vector components: - % y(1) Total internal energy U - % y(2) Volume V - % y(3) Mass of species 1 - % .... - % y(2+nsp) Mass of last species + % :y(1): Total internal energy U + % :y(2): Volume V + % :y(3): Mass of species 1 + % :....: + % :y(2+nsp): Mass of last species % [m, n] = size(y); diff --git a/samples/matlab_experimental/surf_reactor.m b/samples/matlab_experimental/surf_reactor.m index cea9b542ce..e25d438447 100644 --- a/samples/matlab_experimental/surf_reactor.m +++ b/samples/matlab_experimental/surf_reactor.m @@ -1,9 +1,9 @@ -%% SURFREACTOR - Zero-dimensional reactor with surface chemistry +%% Zero-dimensional reactor with surface chemistry % -% This example illustrates how to use class 'Reactor' for zero-dimensional +% This example illustrates how to use class ``Reactor`` for zero-dimensional % simulations including both homogeneous and heterogeneous chemistry. % -% Keywords: catalysis, combustion, reactor network, plotting +% .. tags:: Matlab, catalysis, combustion, reactor network, plotting %% Initialization From 1d151df4f41bfbb3999989b212705b358a2aed4f Mon Sep 17 00:00:00 2001 From: Ray Speth Date: Fri, 22 Sep 2023 23:47:50 -0400 Subject: [PATCH 14/22] Generate plots for examples where this requires the --plot option --- doc/sphinx/conf.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/doc/sphinx/conf.py b/doc/sphinx/conf.py index c639652b20..263755162f 100644 --- a/doc/sphinx/conf.py +++ b/doc/sphinx/conf.py @@ -118,6 +118,27 @@ def executable_script(src_file, gallery_conf): sphinx_gallery.gen_rst.EXAMPLE_HEADER = header_prefix + sphinx_gallery.gen_rst.EXAMPLE_HEADER +# Provide options to examples that only generate plots if an option is specified +class ResetArgv: + wants_plot = { + "adiabatic.py", + "premixed_counterflow_twin_flame.py", + "piston.py", + "reactor1.py", + "reactor2.py", + "sensitivity1.py", + } + def __repr__(self): + return 'ResetArgv' + + def __call__(self, sphinx_gallery_conf, script_vars): + if Path(script_vars['src_file']).name in self.wants_plot: + return ['--plot'] + else: + return [] + +sphinx_gallery_conf["reset_argv"] = ResetArgv() + # Options for sphinx_tags extension tags_create_tags = True tags_create_badges = True From 87aac802b03c9e7ff8434d7a07c29e31b50db8e8 Mon Sep 17 00:00:00 2001 From: Ray Speth Date: Fri, 22 Sep 2023 23:49:20 -0400 Subject: [PATCH 15/22] [Doc] Add separate top-level pages for examples and reference docs --- doc/sphinx/_templates/cantera-org-links.html | 12 --------- doc/sphinx/conf.py | 2 +- doc/sphinx/examples.rst | 21 ++++++++++++++++ doc/sphinx/index.rst | 26 ++++---------------- doc/sphinx/reference.rst | 16 ++++++++++++ 5 files changed, 43 insertions(+), 34 deletions(-) create mode 100644 doc/sphinx/examples.rst create mode 100644 doc/sphinx/reference.rst diff --git a/doc/sphinx/_templates/cantera-org-links.html b/doc/sphinx/_templates/cantera-org-links.html index e28223cf0f..101b250250 100644 --- a/doc/sphinx/_templates/cantera-org-links.html +++ b/doc/sphinx/_templates/cantera-org-links.html @@ -11,12 +11,6 @@ - - - -