5
from docutils import nodes
6
from docutils.parsers.rst import Directive
7
from datetime import datetime
19
def replace_scalar_type_names():
20
""" Rename numpy types to use the canonical names to make sphinx behave """
23
Py_ssize_t = ctypes.c_int64 if ctypes.sizeof(ctypes.c_void_p) == 8 else ctypes.c_int32
25
class PyObject(ctypes.Structure):
28
class PyTypeObject(ctypes.Structure):
32
('ob_refcnt', Py_ssize_t),
33
('ob_type', ctypes.POINTER(PyTypeObject)),
37
PyTypeObject._fields_ = [
39
('ob_base', PyObject),
40
('ob_size', Py_ssize_t),
42
('tp_name', ctypes.c_char_p),
49
'byte', 'short', 'intc', 'int_', 'longlong',
50
'ubyte', 'ushort', 'uintc', 'uint', 'ulonglong',
51
'half', 'single', 'double', 'longdouble',
52
'half', 'csingle', 'cdouble', 'clongdouble',
54
typ = getattr(numpy, name)
55
c_typ = PyTypeObject.from_address(id(typ))
56
c_typ.tp_name = _name_cache[typ] = b"numpy." + name.encode('utf8')
59
replace_scalar_type_names()
65
warnings.filterwarnings("ignore", "In the future.*NumPy scalar", FutureWarning)
75
sys.path.insert(0, os.path.abspath('../sphinxext'))
80
'sphinx.ext.intersphinx',
81
'sphinx.ext.coverage',
83
'sphinx.ext.autosummary',
84
'sphinx.ext.graphviz',
85
'sphinx.ext.ifconfig',
86
'matplotlib.sphinxext.plot_directive',
87
'IPython.sphinxext.ipython_console_highlighting',
88
'IPython.sphinxext.ipython_directive',
94
skippable_extensions = [
95
('breathe', 'skip generating C/C++ API from comment blocks.'),
97
for ext, warn in skippable_extensions:
98
ext_exist = importlib.util.find_spec(ext) is not None
100
extensions.append(ext)
102
print(f"Unable to find Sphinx extension '{ext}', {warn}.")
105
templates_path = ['_templates']
108
source_suffix = '.rst'
112
year = datetime.now().year
113
copyright = f'2008-{year}, NumPy Developers'
120
version = re.sub(r'(\d+\.\d+)\.\d+(.*)', r'\1\2', numpy.__version__)
121
version = re.sub(r'(\.dev\d+).*?$', r'\1', version)
123
release = numpy.__version__
124
print("%s %s" % (version, release))
130
today_fmt = '%B %d, %Y'
136
default_role = "autolink"
143
if sys.version_info[:2] >= (3, 12):
144
exclude_patterns += ["reference/distutils.rst"]
147
add_function_parentheses = False
157
class LegacyDirective(Directive):
159
Adapted from docutils/parsers/rst/directives/admonitions.py
161
Uses a default text if the directive does not have contents. If it does,
162
the default text is concatenated to the contents.
164
See also the same implementation in SciPy's conf.py.
167
node_class = nodes.admonition
168
optional_arguments = 1
172
obj = self.arguments[0]
176
text = (f"This {obj} is considered legacy and will no longer receive "
177
"updates. This could also mean it will be removed in future "
181
self.content[0] = text+" "+self.content[0]
184
source, lineno = self.state_machine.get_source_and_line(
192
text = '\n'.join(self.content)
194
admonition_node = self.node_class(rawsource=text)
196
title_text = "Legacy"
197
textnodes, _ = self.state.inline_text(title_text, self.lineno)
198
title = nodes.title(title_text, '', *textnodes)
200
admonition_node += title
202
admonition_node['classes'] = ['admonition-legacy']
204
self.state.nested_parse(self.content, self.content_offset,
206
return [admonition_node]
211
app.add_config_value('python_version_major', str(sys.version_info.major), 'env')
212
app.add_lexer('NumPyC', NumPyLexer)
213
app.add_directive("legacy", LegacyDirective)
221
sys.modules['numpy.char'] = numpy.char
227
html_theme = 'pydata_sphinx_theme'
229
html_favicon = '_static/favicon/favicon.ico'
232
if os.environ.get('CIRCLE_JOB', False) and \
233
os.environ.get('CIRCLE_BRANCH', '') != 'main':
235
switcher_version = os.environ['CIRCLE_BRANCH']
236
elif ".dev" in version:
237
switcher_version = "devdocs"
239
switcher_version = f"{version}"
241
html_theme_options = {
243
"image_light": "_static/numpylogo.svg",
244
"image_dark": "_static/numpylogo_dark.svg",
246
"github_url": "https://github.com/numpy/numpy",
247
"collapse_navigation": True,
249
{"name": "Learn", "url": "https://numpy.org/numpy-tutorials/"},
250
{"name": "NEPs", "url": "https://numpy.org/neps"},
252
"header_links_before_dropdown": 6,
260
"navbar_persistent": [],
262
"version_match": switcher_version,
263
"json_url": "https://numpy.org/doc/_static/versions.json",
265
"show_version_warning_banner": True,
268
html_title = "%s v%s Manual" % (project, version)
269
html_static_path = ['_static']
270
html_last_updated_fmt = '%b %d, %Y'
271
html_css_files = ["numpy.css"]
272
html_context = {"default_mode": "light"}
273
html_use_modindex = True
274
html_copy_source = False
275
html_domain_indices = False
276
html_file_suffix = '.html'
278
htmlhelp_basename = 'numpy'
280
if 'sphinx.ext.pngmath' in extensions:
281
pngmath_use_preview = True
282
pngmath_dvipng_args = ['-gamma', '1.5', '-D', '96', '-bg', 'Transparent']
284
mathjax_path = "scipy-mathjax/MathJax.js?config=scipy-mathjax"
286
plot_html_show_formats = False
287
plot_html_show_source_link = False
290
copybutton_prompt_text = r">>> |\.\.\. |\$ |In \[\d*\]: | {2,5}\.\.\.: | {5,8}: "
291
copybutton_prompt_is_regexp = True
303
latex_engine = 'xelatex'
307
_stdauthor = 'Written by the NumPy community'
309
('reference/index', 'numpy-ref.tex', 'NumPy Reference',
310
_stdauthor, 'manual'),
311
('user/index', 'numpy-user.tex', 'NumPy User Guide',
312
_stdauthor, 'manual'),
327
latex_elements['preamble'] = r'''
328
\newfontfamily\FontForChinese{FandolSong-Regular}[Extension=.otf]
329
\catcode`琴\active\protected\def琴{{\FontForChinese\string琴}}
330
\catcode`春\active\protected\def春{{\FontForChinese\string春}}
331
\catcode`鈴\active\protected\def鈴{{\FontForChinese\string鈴}}
332
\catcode`猫\active\protected\def猫{{\FontForChinese\string猫}}
333
\catcode`傅\active\protected\def傅{{\FontForChinese\string傅}}
334
\catcode`立\active\protected\def立{{\FontForChinese\string立}}
335
\catcode`业\active\protected\def业{{\FontForChinese\string业}}
336
\catcode`(\active\protected\def({{\FontForChinese\string(}}
337
\catcode`)\active\protected\def){{\FontForChinese\string)}}
339
% In the parameters section, place a newline after the Parameters
340
% header. This is default with Sphinx 5.0.0+, so no need for
342
% Unfortunately sphinx.sty 5.0.0 did not bump its version date
343
% so we check rather sphinxpackagefootnote.sty (which exists
344
% since Sphinx 4.0.0).
346
\@ifpackagelater{sphinxpackagefootnote}{2022/02/12}
347
{}% Sphinx >= 5.0.0, nothing to do
350
\let\latexdescription=\description
351
\def\description{\latexdescription{}{} \breaklabel}
352
% but expdlist old LaTeX package requires fixes:
353
% 1) remove extra space
355
\patchcmd\@item{{\@breaklabel} }{{\@breaklabel}}{}{}
356
% 2) fix bug in expdlist's way of breaking the line after long item label
360
% now a hack because Sphinx inserts \leavevmode after term node
361
\def\leavevmode{\def\leavevmode{\unhbox\voidb@x}}%
364
}% Sphinx < 5.0.0 (and assumed >= 4.0.0)
367
% Make Examples/etc section headers smaller and more compact
369
\titleformat{\paragraph}{\normalsize\py@HeaderFamily}%
370
{\py@TitleColor}{0em}{\py@TitleColor}{\py@NormalColor}
371
\titlespacing*{\paragraph}{0pt}{1ex}{0pt}
375
\renewcommand{\chaptermark}[1]{\markboth{\MakeUppercase{\thechapter.\ #1}}{}}
376
\renewcommand{\sectionmark}[1]{\markright{\MakeUppercase{\thesection.\ #1}}}
383
latex_use_modindex = False
391
("index", 'numpy', 'NumPy Documentation', _stdauthor, 'NumPy',
392
"NumPy: array processing for numbers, strings, records, and objects.",
401
intersphinx_mapping = {
402
'neps': ('https://numpy.org/neps', None),
403
'python': ('https://docs.python.org/3', None),
404
'scipy': ('https://docs.scipy.org/doc/scipy', None),
405
'matplotlib': ('https://matplotlib.org/stable', None),
406
'imageio': ('https://imageio.readthedocs.io/en/stable', None),
407
'skimage': ('https://scikit-image.org/docs/stable', None),
408
'pandas': ('https://pandas.pydata.org/pandas-docs/stable', None),
409
'scipy-lecture-notes': ('https://scipy-lectures.org', None),
410
'pytest': ('https://docs.pytest.org/en/stable', None),
411
'numpy-tutorials': ('https://numpy.org/numpy-tutorials', None),
412
'numpydoc': ('https://numpydoc.readthedocs.io/en/latest', None),
413
'dlpack': ('https://dmlc.github.io/dlpack/latest', None)
422
phantom_import_file = 'dump.xml'
425
numpydoc_use_plots = True
431
autosummary_generate = True
436
coverage_ignore_modules = r"""
438
coverage_ignore_functions = r"""
439
test($|_) (some|all)true bitwise_not cumproduct pkgload
442
coverage_ignore_classes = r"""
446
coverage_c_regexes = {}
447
coverage_ignore_c_items = {}
457
plot_include_source = True
458
plot_formats = [('png', 100), 'pdf']
461
phi = (math.sqrt(5) + 1)/2
467
'xtick.labelsize': 8,
468
'ytick.labelsize': 8,
469
'legend.fontsize': 8,
470
'figure.figsize': (3*phi, 3),
471
'figure.subplot.bottom': 0.2,
472
'figure.subplot.left': 0.2,
473
'figure.subplot.right': 0.9,
474
'figure.subplot.top': 0.85,
475
'figure.subplot.wspace': 0.4,
476
'text.usetex': False,
485
from os.path import relpath, dirname
487
for name in ['sphinx.ext.linkcode', 'numpydoc.linkcode']:
490
extensions.append(name)
495
print("NOTE: linkcode extension not found -- no links to source generated")
498
def _get_c_source_file(obj):
499
if issubclass(obj, numpy.generic):
500
return r"_core/src/multiarray/scalartypes.c.src"
501
elif obj is numpy.ndarray:
502
return r"_core/src/multiarray/arrayobject.c"
508
def linkcode_resolve(domain, info):
510
Determine the URL corresponding to Python object
515
modname = info['module']
516
fullname = info['fullname']
518
submod = sys.modules.get(modname)
523
for part in fullname.split('.'):
525
obj = getattr(obj, part)
532
unwrap = inspect.unwrap
533
except AttributeError:
542
if isinstance(obj, type) and obj.__module__ == 'numpy':
543
fn = _get_c_source_file(obj)
547
fn = inspect.getsourcefile(obj)
554
module = inspect.getmodule(obj)
555
if module is not None and not module.__name__.startswith("numpy"):
559
source, lineno = inspect.getsourcelines(obj)
563
fn = relpath(fn, start=dirname(numpy.__file__))
566
linespec = "#L%d-L%d" % (lineno, lineno + len(source) - 1)
570
if 'dev' in numpy.__version__:
571
return "https://github.com/numpy/numpy/blob/main/numpy/%s%s" % (
574
return "https://github.com/numpy/numpy/blob/v%s/numpy/%s%s" % (
575
numpy.__version__, fn, linespec)
577
from pygments.lexers import CLexer
578
from pygments.lexer import inherit
579
from pygments.token import Comment
581
class NumPyLexer(CLexer):
586
(r'@[a-zA-Z_]*@', Comment.Preproc, 'macro'),
595
breathe_projects = dict(numpy=os.path.join("..", "build", "doxygen", "xml"))
596
breathe_default_project = "numpy"
597
breathe_default_members = ("members", "undoc-members", "protected-members")
601
('c:identifier', 'FILE'),
602
('c:identifier', 'size_t'),
603
('c:identifier', 'PyHeapTypeObject'),