Files
CoolProp/Web/conf.py
Ian Bell c649586e8c feat(docs): add interactive 3D molecule viewers to fluid pages (#2707)
* feat(docs): add interactive 3D molecule viewers to fluid pages

Use py3Dmol + PubChem SDF data to embed a rotate-and-drag 3D (or 2D
fallback) molecule viewer on each pure fluid documentation page.

- fetch_pubchem_sdf(): downloads 3D conformer SDF from PubChem REST API
  (falls back to 2D), caching results in molecule_sdf/ to avoid repeated
  network calls on doc rebuilds
- generate_3dmol_rst(): inlines the SDF as a JS template literal inside a
  .. raw:: html block — no extra static files needed at Sphinx build time
- FluidGenerator.write(): validates InChIKey with regex before fetching;
  pseudo-pure fluids (Air, R404A, etc.) without InChIKeys are silently skipped
- conf.py: loads 3Dmol.js from CDN via html_js_files
- .gitignore: excludes the generated molecule_sdf/ cache directory

Restores molecule visualisation that was removed in April 2025 (the old
approach tried to embed an image directive inside a CSV table, which is
invalid RST; this implementation places the viewer in the RST template).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(docs): serve 3Dmol.js locally to eliminate CORS errors

Download 3Dmol-min.js to _static/ at Sphinx build time (same pattern
as MathJax) instead of loading it from the CDN via html_js_files.
Serving the script same-origin removes the cross-origin restriction
that caused CORS errors when docs were opened from file:// or a local
dev server.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(docs): correct 3Dmol viewer positioning and initialization timing

3Dmol.js sets its canvas to position:absolute;top:0;left:0 and only
auto-sets the container to position:relative when the container's
inline style.position === "static". An unstyled div has style.position
=== "" so the check fails, and the canvas escapes the container and
anchors to the nearest positioned ancestor in the Sphinx page layout.

Fix: add position:relative explicitly to the viewer container div.

Also defer viewer init via DOMContentLoaded so layout is finalized
before createViewer reads the container dimensions, and call v.resize()
before v.render() to sync the WebGL canvas to the container size.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(docs): disable MathJax SRE to prevent CORS errors on file:// URLs

MathJax 4.0's Speech Rule Engine fetches sre/mathmaps/base.json at
runtime via fetch(). Chrome blocks this when docs are opened from a
local file:// URL (null origin). Disabling enableExplorer and
enableAssistiveMml prevents SRE from initialising entirely.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(docs): load 3Dmol before require.js to fix AMD conflict

sphinx.ext.mathjax injects require.js at priority 500. When 3Dmol
loads after it, AMD detection fires and calls define([], factory)
instead of setting window.$3Dmol directly. Since nothing ever calls
require(['3Dmol-min']), the factory never runs and the viewer silently
fails (infinite setTimeout retry, no console errors).

Setting priority 450 ensures 3Dmol loads before require.js.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(docs): add retry logic to downloads in conf.py using requests

Replace urllib.request.urlretrieve with a requests-based _download()
helper that retries up to 5 times (exponential backoff, factor=2) on
transient HTTP errors and timeouts. Fixes CI build failures when
the MathJax or 3Dmol.js downloads time out.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-04 10:41:10 -04:00

391 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
#
# sampledoc documentation build configuration file, created by
# sphinx-quickstart on Tue Aug 11 05:04:40 2009.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
import subprocess
import sys
from pathlib import Path
import urllib.request
import zipfile
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
def _download(url, dest):
"""Download url to dest with automatic retries on transient failures."""
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=Retry(
total=5, backoff_factor=2, status_forcelist=[429, 500, 502, 503, 504]
)))
response = session.get(url, timeout=60)
response.raise_for_status()
Path(dest).write_bytes(response.content)
import CoolProp
ver = CoolProp.__version__
# The short X.Y version.
version = ver.rsplit('.', 1)[0]
# The full version, including alpha/beta/rc tags.
release = ver
# Some hacking to determine release or nightly build
if ver[-2] == "." and ver[-1].isdigit() >= 0 and ver[-3].isdigit() >= 0:
isRelease = True
else:
isRelease = False
print("------------ Project information ------------")
print("Detected version: %s" % version)
print("Detected release: %s" % release)
print("Public release : %s" % "True" if isRelease else "False")
print("")
if isRelease:
extlinks = {'sfdownloads': (f'http://sourceforge.net/projects/coolprop/files/CoolProp/{release}/%s', f'{release} %s'),
'sfnightly': ('http://sourceforge.net/projects/coolprop/files/CoolProp/nightly/%s', 'nightly %s'),
# 'bbbinaries' : ('http://www.coolprop.dreamhosters.com:8010/binaries/%s',''),
# 'bbsphinx' : ('http://www.coolprop.dreamhosters.com:8010/sphinx/%s','')
}
else:
extlinks = {'sfdownloads': (f'http://sourceforge.net/projects/coolprop/files/CoolProp/{release}/%s', f'{release} %s'),
'sfnightly': ('http://sourceforge.net/projects/coolprop/files/CoolProp/nightly/%s', 'nightly %s'),
# 'bbbinaries' : ('http://www.coolprop.dreamhosters.com:8010/binaries/%s',''),
# 'bbsphinx' : ('http://www.coolprop.dreamhosters.com:8010/sphinx/%s','')
}
import sys, os, datetime
# ~ # If your extensions are in another directory, add it here. If the directory
# ~ # is relative to the documentation root, use os.path.abspath to make it
# ~ # absolute, like shown here.
#~ sys.path.append(os.path.abspath('sphinxext'))
sys.path.insert(0, os.path.abspath('_ext'))
try:
import sphinxcontrib.doxylink
except ImportError:
print('Unable to import sphinxcontrib.doxylink; try to run "pip install sphinxcontrib-doxylink"')
if isRelease:
doxylink = {
'cpapi': ('_static/doxygen/CoolPropDoxyLink.tag', 'http://www.coolprop.org/_static/doxygen/html')
}
else:
doxylink = {
'cpapi': ('_static/doxygen/CoolPropDoxyLink.tag', 'http://www.coolprop.org/dev/_static/doxygen/html')
}
# Execute all the notebooks
for dirpath, dirnames, filenames in Path(__file__).parent.walk():
for file in filenames:
if file.endswith('.ipynb') and '.ipynb_checkpoints' not in str(dirpath) and '_build' not in str(dirpath):
cmd = f'jupyter nbconvert --allow-errors --to notebook --output "{file}" --execute "{file}"'
print(f"About to run: {cmd} in {dirpath}")
subprocess.check_output(cmd, shell=True, cwd=dirpath)
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['IPython.sphinxext.ipython_console_highlighting',
'IPython.sphinxext.ipython_directive',
'sphinx.ext.intersphinx',
'sphinx.ext.autodoc',
'sphinx.ext.mathjax',
'sphinx.ext.extlinks',
'sphinxcontrib.bibtex',
'sphinx.ext.napoleon',
'sphinxcontrib.doxylink',
'matplotlib.sphinxext.plot_directive',
'edit_on_github', # see https://gist.github.com/mgedmin/6052926#file-edit_on_github-pyb
# 'inheritance_diagram',
# 'numpydoc',
# 'breathe'
"nbsphinx",
]
# set path to issue tracker:
issue_tracker_url = "gh:CoolProp/CoolProp"
plot_formats = [('png', 80), ('.pdf')]
index_doc = "index"
numpydoc_show_class_members = False
zfile = Path("MJ.zip")
if not zfile.exists():
_download("https://github.com/mathjax/MathJax/archive/refs/tags/4.0.0.zip", zfile)
with zipfile.ZipFile(zfile) as z:
z.extractall(path=Path(__file__).parent / '_static')
mathjax_path = "MathJax-4.0.0/tex-mml-chtml.js"
assert (Path(__file__).parent / '_static' / mathjax_path).exists()
# Disable the SRE accessibility features that use fetch() to load mathmaps JSON files.
# Those fetch() calls are blocked by CORS when the docs are viewed from file:// URLs.
mathjax3_config = {
'options': {
'enableExplorer': False,
'enableAssistiveMml': False,
}
}
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = {'.rst': 'restructuredtext'}
# The encoding of source files.
source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'contents'
# General information about the project.
d = datetime.datetime.today()
project = u'CoolProp'
copyright = u'2010-{0}, Ian H. Bell and the CoolProp Team'.format(d.year)
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['_build', 'sphinxext']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# This value selects what content will be inserted into the main body of an autoclass directive.
# 'class' - Only the class docstring is inserted. This is the default.
# 'init' - Only the __init__ methods docstring is inserted.
# 'both' - Both the class and the __init__ methods docstring are concatenated and inserted
autoclass_content = 'both'
## Don't generate HTML5 docs, recommendation from https://stackoverflow.com/a/56822558
#html4_writer = True
# Fix the bibtext extension
bibtex_bibfiles = ["../CoolPropBibTeXLibrary.bib"]
# -- Options for HTML output ---------------------------------------------------
try:
import cloud_sptheme as csp
except:
print('unable to import cloud_sptheme as csp; try a "pip install cloud_sptheme"')
# ... some contents omitted ...
# set the html theme
html_theme = "pydata_sphinx_theme"
html_theme_options = {
"navbar_center": ["navbar-center.html"],
}
edit_on_github_project = 'CoolProp/CoolProp'
edit_on_github_branch = 'master'
edit_on_github_path_prefix = 'Web'
# import Cloud
# import cloud_sptheme as csp
# #html_theme = "cloud"
# # NOTE: there is also a red-colored version named "redcloud"
# # ... some contents omitted ...
# # set the theme path to point to cloud's theme data
# html_theme_path = [csp.get_theme_dir()]
# # [optional] set some of the options listed above...
# html_theme_options = {"roottarget": "index",
# "max_width": "13in",
# "logotarget": "index",
# "googleanalytics_id": "UA-53205480-2",
# "default_layout_text_size": "85%",
# "table_style_default_align": "left"
# }
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
## html_theme = 'sphinxdoc'
# html_theme='nature'
# The style sheet to use for HTML and HTML Help pages. A file of that name
# must exist either in Sphinx' static/ path, or in one of the custom paths
# given in html_static_path.
#html_style = 'CoolProp2.css'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = "_static/CoolPropLogo.png"
assert(Path(html_logo).exists())
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# 3Dmol.js — required for the interactive molecule viewers on fluid pages
# Download locally to avoid CORS issues when docs are served from file:// or a local server
_3dmol_js = Path(__file__).parent / '_static' / '3Dmol-min.js'
if not _3dmol_js.exists():
_download('https://3dmol.org/build/3Dmol-min.js', _3dmol_js)
# Priority 450 ensures 3Dmol-min.js loads before require.js (added by sphinx.ext.mathjax
# at priority 500). If 3Dmol loads after require.js, its AMD detection kicks in and
# define([], factory) is called but never executed, silently preventing $3Dmol from being set.
html_js_files = [('3Dmol-min.js', {'priority': 450})]
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Content template for the index page.
#html_index = 'index.html'
# Custom sidebar templates, maps page names to templates.
# html_sidebars = {'index': 'indexsidebar.html',
# }
html_sidebars = {
'**': ['globaltoc.html'],
}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {'index': 'index.html'}
# If false, no module index is generated.
#html_use_modindex = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'sampledocdoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('contents', 'CoolPropdoc.tex', u'CoolProp Documentation',
u'Ian Bell', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True