Skip to content

Commit bafdf25

Browse files
committed
fix docs
1 parent 6d08792 commit bafdf25

7 files changed

Lines changed: 69 additions & 73 deletions

File tree

desc/integrals/bounce_integral.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -175,9 +175,9 @@ class Bounce2D(_Bounce):
175175
176176
References
177177
----------
178-
.. [1] K. Unalmis et al., "Spectrally accurate, reverse-mode
179-
differentiable bounce-averaging algorithm and its applications,"
180-
Journal of Plasma Physics.
178+
[1] K. Unalmis et al., "Spectrally accurate, reverse-mode
179+
differentiable bounce-averaging algorithm and its applications,"
180+
Journal of Plasma Physics.
181181
182182
Examples
183183
--------

desc/objectives/_coils.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2680,15 +2680,15 @@ class SurfaceCurrentRegularization(_Objective):
26802680
26812681
"""
26822682

2683-
weight_str = (
2684-
"weight : {float, ndarray}, optional"
2685-
"\n\tWeighting to apply to the Objective, relative to other Objectives."
2686-
"\n\tMust be broadcastable to to ``Objective.dim_f``"
2687-
"\n\tWhen used with QuadraticFlux objective, this acts as the regularization"
2688-
"\n\tparameter (with w^2 = lambda), with 0 corresponding to no regularization."
2689-
"\n\tThe larger this parameter is, the less complex the surface current will "
2690-
"be,\n\tbut the worse the normal field."
2691-
)
2683+
weight_str = """
2684+
weight : {float, ndarray}, optional
2685+
Weighting to apply to the Objective, relative to other Objectives.
2686+
Must be broadcastable to to ``Objective.dim_f``.
2687+
When used with QuadraticFlux objective, this acts as the regularization
2688+
parameter (with w^2 = lambda), with 0 corresponding to no regularization.
2689+
The larger this parameter is, the less complex the surface current will
2690+
be, but the worse the normal field.
2691+
"""
26922692
__doc__ = __doc__.rstrip() + collect_docs(
26932693
target_default="``target=0``.",
26942694
bounds_default="``target=0``.",

desc/objectives/_fast_ion.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from desc.integrals._interp_utils import check_nufft
66
from desc.integrals.bounce_integral import Options
77

8-
from .objective_funs import _Objective, collect_docs, doc_bounce
8+
from .objective_funs import _clean_doc, _Objective, collect_docs, doc_bounce
99
from .utils import errorif
1010

1111

@@ -44,7 +44,8 @@ class GammaC(_Objective):
4444
__doc__ = (
4545
__doc__.rstrip()
4646
+ doc_bounce
47-
+ """
47+
+ "\n"
48+
+ _clean_doc("""
4849
Nemov : bool
4950
Whether to use the Γ_c as defined by Nemov et al. or Velasco et al.
5051
Default is Nemov. Set to ``False`` to use Velasco's.
@@ -56,7 +57,7 @@ class GammaC(_Objective):
5657
integrals. At finite resolution, an optimization using Velasco's metric
5758
may need to be evaluated by measuring decrease in Γ_c at a fixed number
5859
of toroidal transits.
59-
""".rstrip()
60+
""")
6061
+ collect_docs(
6162
target_default="``target=0``.",
6263
bounds_default="``target=0``.",
@@ -203,19 +204,21 @@ class GammaLoss(_Objective):
203204

204205
__doc__ = (
205206
__doc__.rstrip()
206-
+ doc_bounce.split(" Parameters\n ----------\n", maxsplit=1)[0]
207-
+ """
207+
+ doc_bounce.split("Parameters\n----------\n", maxsplit=1)[0]
208+
+ _clean_doc("""
208209
Parameters
209210
----------
210211
kind : {"delta", "alpha"}
211212
Select ``"delta"`` for Γ_δ or ``"alpha"`` for Γ_α.
212-
"""
213-
+ doc_bounce.split(" Parameters\n ----------\n", maxsplit=1)[1]
214-
+ """
213+
""")
214+
+ "\n"
215+
+ doc_bounce.split("Parameters\n----------\n", maxsplit=1)[1]
216+
+ "\n"
217+
+ _clean_doc("""
215218
gamma_threshold : float
216219
Threshold for superbanana classification. Must be in ``(0,1)``.
217220
Default is 0.2.
218-
""".rstrip()
221+
""")
219222
+ collect_docs(
220223
target_default="``target=0``.",
221224
bounds_default="``target=0``.",

desc/objectives/linear_objectives.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
from desc.utils import broadcast_tree, errorif, setdefault
2525

2626
from .normalization import compute_scaling_factors
27-
from .objective_funs import _Objective, collect_docs
27+
from .objective_funs import _clean_doc, _Objective, collect_docs
2828

2929

3030
# TODO (#1391): get rid of this class and inherit from FixParameters instead?
@@ -275,7 +275,7 @@ class ShareParameters(_Objective):
275275
"weight": "",
276276
}
277277
)
278-
__doc__ += """
278+
__doc__ += "\n\n" + _clean_doc("""
279279
Examples
280280
--------
281281
.. code-block:: python
@@ -319,7 +319,7 @@ class ShareParameters(_Objective):
319319
]
320320
obj=ShareParameters([full_coilset, coilset2], params=params)
321321
322-
"""
322+
""")
323323
_scalar = False
324324
_linear = True
325325
_fixed = False

desc/objectives/objective_funs.py

Lines changed: 29 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import functools
44
from abc import ABC, abstractmethod
5+
from inspect import cleandoc
56

67
import numpy as np
78

@@ -33,6 +34,12 @@
3334
warnif,
3435
)
3536

37+
38+
def _clean_doc(doc):
39+
"""Return a docstring fragment formatted for concatenation."""
40+
return cleandoc(doc).rstrip()
41+
42+
3643
doc_target = """
3744
target : {float, ndarray}, optional
3845
Target value(s) of the objective. Only used if ``bounds`` is ``None``.
@@ -131,7 +138,7 @@
131138
"jac_chunk_size": doc_jac_chunk_size,
132139
}
133140

134-
doc_bounce = """
141+
doc_bounce = "\n\n" + _clean_doc("""
135142
Notes
136143
-----
137144
Developer notes: Performance will improve significantly by resolving GitHub issues:
@@ -217,13 +224,11 @@
217224
instead of Chebyshev series. Default is ``True``. It can be preferable
218225
to set to ``False`` on equilibria with high ``NFP``, (such cases make
219226
smaller ``Y_B`` feasible), or on GPUs where eigenvalue solves are fast.
220-
""".rstrip()
227+
""")
221228

222229

223-
# Note: If we ever switch to Python 3.13 for building the docs, there will probably
224-
# be some errors since 3.13 changed how tabs are handled in docstrings. This can be
225-
# resolved by deleting the tabs in the collected docstring above and the ones
226-
# that are defined in objectives. Check `test_objective_docstring`.
230+
# Generated fragments are concatenated into class docstrings after Python has already
231+
# applied normal docstring cleaning, so keep them explicitly dedented here.
227232
def collect_docs(
228233
overwrite=None,
229234
target_default="",
@@ -265,7 +270,7 @@ def collect_docs(
265270
String of default parameters for the docstring.
266271
267272
"""
268-
doc_params = ""
273+
doc_params = []
269274

270275
# Copy to allow for objective-specific updates to docs
271276
docs_obj = docs.copy()
@@ -280,39 +285,34 @@ def collect_docs(
280285

281286
for key in docs_obj.keys():
282287
if overwrite is not None and key in overwrite.keys():
283-
doc_params += overwrite[key].rstrip()
288+
doc = _clean_doc(overwrite[key])
289+
if doc:
290+
doc_params.append(doc)
284291
else:
292+
doc = _clean_doc(docs_obj[key])
285293
if key == "target":
286-
target = ""
287294
if target_default != "":
288-
target += " Defaults to " + target_default
289-
doc_params += docs_obj[key].rstrip() + target
295+
doc += " Defaults to " + target_default
296+
doc_params.append(doc)
290297
elif key == "bounds" and bounds_default != "":
291-
doc_params = (
292-
doc_params
293-
+ docs_obj[key].rstrip()
294-
+ " Defaults to "
295-
+ bounds_default
296-
)
298+
doc += " Defaults to " + bounds_default
299+
doc_params.append(doc)
297300
elif key == "loss_function":
298-
loss = ""
299301
if loss_detail is not None:
300-
loss += loss_detail
301-
doc_params += docs_obj[key].rstrip() + loss
302+
doc += loss_detail
303+
doc_params.append(doc)
302304
elif key == "normalize":
303-
norm = ""
304305
if normalize_detail is not None:
305-
norm += normalize_detail
306-
doc_params += docs_obj[key].rstrip() + norm
306+
doc += normalize_detail
307+
doc_params.append(doc)
307308
elif key == "normalize_target":
308-
norm_target = ""
309309
if normalize_target_detail is not None:
310-
norm_target = normalize_target_detail
311-
doc_params += docs_obj[key].rstrip() + norm_target
310+
doc += normalize_target_detail
311+
doc_params.append(doc)
312312
else:
313-
doc_params += docs_obj[key].rstrip()
313+
doc_params.append(doc)
314314

315-
return doc_params
315+
return "\n" + "\n".join(doc_params)
316316

317317

318318
class ObjectiveFunction(IOAble):
@@ -1927,7 +1927,7 @@ def things(self, new):
19271927
self._built = False
19281928

19291929

1930-
_Objective.__doc__ += "".join(value.rstrip("\n") for value in docs.values())
1930+
_Objective.__doc__ += collect_docs()
19311931

19321932
# local functions assigned as attributes aren't hashable so they cause stuff to
19331933
# recompile, so instead we define a hashable class to do the same thing.

docs/conf.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,9 @@
7575
autosummary_generate_overwrite = True
7676
# temporary fix to ignore errors raised in notebooks
7777
nbsphinx_allow_errors = True
78+
# Sphinx 9 cross-references short API parameter names such as ``M``, ``sym``,
79+
# and ``num_nodes`` to every matching Python object in generated autosummary pages.
80+
suppress_warnings = ["ref.python"]
7881

7982
# Add any paths that contain templates here, relative to this directory.
8083
templates_path = ["_templates"]

tests/test_objective_funs.py

Lines changed: 10 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,11 @@
66
This module primarily tests the constructing/building/calling methods.
77
"""
88

9-
import platform
109
import warnings
10+
from inspect import cleandoc
1111

1212
import numpy as np
1313
import pytest
14-
from packaging.version import Version
1514
from qsc import Qsc
1615
from scipy.constants import elementary_charge, mu_0
1716

@@ -4385,25 +4384,16 @@ def test_objective_print_widths():
43854384
@pytest.mark.unit
43864385
def test_objective_docstring():
43874386
"""Test that the objective docstring and collect_docs are consistent."""
4388-
objective_docs = _Objective.__doc__.rstrip()
4389-
if Version(platform.python_version()) >= Version("3.13"):
4390-
doc_header = (
4391-
"Objective (or constraint) used in the optimization of an Equilibrium.\n\n"
4392-
+ "Parameters\n"
4393-
+ "----------\n"
4394-
+ "things : Optimizable or tuple/list of Optimizable\n"
4395-
+ " Objects that will be optimized to satisfy the Objective.\n"
4396-
)
4397-
else:
4398-
doc_header = (
4399-
"Objective (or constraint) used in the optimization of an Equilibrium.\n\n"
4400-
+ " Parameters\n"
4401-
+ " ----------\n"
4402-
+ " things : Optimizable or tuple/list of Optimizable\n"
4403-
+ " Objects that will be optimized to satisfy the Objective.\n"
4404-
)
4387+
objective_docs = cleandoc(_Objective.__doc__).rstrip()
4388+
doc_header = (
4389+
"Objective (or constraint) used in the optimization of an Equilibrium.\n\n"
4390+
+ "Parameters\n"
4391+
+ "----------\n"
4392+
+ "things : Optimizable or tuple/list of Optimizable\n"
4393+
+ " Objects that will be optimized to satisfy the Objective.\n"
4394+
)
44054395
collected_docs = collect_docs().strip()
4406-
collected_docs = doc_header + " " + collected_docs
4396+
collected_docs = doc_header + collected_docs
44074397

44084398
assert objective_docs == collected_docs
44094399

0 commit comments

Comments
 (0)