From 27bd13172516b6e9859c3345eb154b82d500c161 Mon Sep 17 00:00:00 2001 From: Rory Conlin Date: Thu, 31 Aug 2023 11:13:14 -0400 Subject: [PATCH] Fix typos and spelling errors --- desc/_version.py | 6 +- desc/basis.py | 2 +- desc/compute/_core.py | 2 +- desc/compute/data_index.py | 2 +- desc/compute/utils.py | 60 ++++++++++--------- desc/continuation.py | 12 ++-- desc/derivatives.py | 6 +- desc/equilibrium/equilibrium.py | 9 +-- desc/geometry/core.py | 2 +- desc/geometry/curve.py | 3 +- desc/geometry/surface.py | 2 +- desc/io/ascii_io.py | 2 +- desc/io/core_io.py | 4 +- desc/io/hdf5_io.py | 4 +- desc/io/input_reader.py | 8 +-- desc/io/pickle_io.py | 4 +- desc/magnetic_fields.py | 14 ++--- desc/objectives/_bootstrap.py | 2 +- desc/objectives/linear_objectives.py | 4 +- desc/objectives/nae_utils.py | 4 +- desc/objectives/objective_funs.py | 4 +- desc/objectives/utils.py | 1 - desc/optimize/_constraint_wrappers.py | 2 +- desc/optimize/_desc_wrappers.py | 4 +- desc/optimize/_scipy_wrappers.py | 4 +- desc/optimize/aug_lagrangian.py | 2 +- desc/optimize/aug_lagrangian_ls.py | 2 +- desc/optimize/optimizer.py | 5 +- desc/optimize/tr_subproblems.py | 10 ++-- desc/optimize/utils.py | 2 +- desc/plotting.py | 85 +++++++++++++-------------- desc/profiles.py | 2 +- desc/random.py | 1 - desc/utils.py | 11 ++-- desc/vmec.py | 9 +-- desc/vmec_utils.py | 6 +- tests/test_bootstrap.py | 2 +- tests/test_configuration.py | 2 +- tests/test_curves.py | 8 +-- tests/test_derivatives.py | 2 +- tests/test_examples.py | 6 +- tests/test_input_output.py | 6 +- tests/test_surfaces.py | 2 +- 43 files changed, 157 insertions(+), 173 deletions(-) diff --git a/desc/_version.py b/desc/_version.py index 2ba473b030..2e0941ce9a 100644 --- a/desc/_version.py +++ b/desc/_version.py @@ -1,5 +1,5 @@ # This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by githubs download-from-tag +# git-archive tarball (such as those provided by github's download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. @@ -292,7 +292,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # TAG-NUM-gHEX mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) if not mo: - # unparseable. Maybe git-describe is misbehaving? + # unparsable. Maybe git-describe is misbehaving? pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out return pieces @@ -409,7 +409,7 @@ def render_pep440_old(pieces): The ".dev0" means dirty. - Eexceptions: + Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: diff --git a/desc/basis.py b/desc/basis.py index 14f70689db..1c7edeea2e 100644 --- a/desc/basis.py +++ b/desc/basis.py @@ -1318,7 +1318,7 @@ def zernike_radial_coeffs(l, m, exact=True): Returns ------- coeffs : ndarray - + Polynomial coefficients for Zernike polynomials, in descending powers of r. Notes ----- diff --git a/desc/compute/_core.py b/desc/compute/_core.py index 732587162d..40f36719b4 100644 --- a/desc/compute/_core.py +++ b/desc/compute/_core.py @@ -175,7 +175,7 @@ def _R_rrt(params, transforms, profiles, data, **kwargs): label="\\partial_{\\rho \\rho \\theta \\theta} R", units="m", units_long="meters", - description="Major radius in lab frame, fouth derivative, wrt radius twice " + description="Major radius in lab frame, fourth derivative, wrt radius twice " "and poloidal angle twice", dim=1, params=["R_lmn"], diff --git a/desc/compute/data_index.py b/desc/compute/data_index.py index f78b358b9d..3dae714d86 100644 --- a/desc/compute/data_index.py +++ b/desc/compute/data_index.py @@ -99,7 +99,7 @@ def _decorator(func): return _decorator -# This allows us to handle subclasses whos data_index stuff should inherit +# This allows us to handle subclasses whose data_index stuff should inherit # from parent classes. # This is the least bad solution I've found, since everything else requires # crazy circular imports diff --git a/desc/compute/utils.py b/desc/compute/utils.py index 423557b141..6b171a3098 100644 --- a/desc/compute/utils.py +++ b/desc/compute/utils.py @@ -12,35 +12,6 @@ from .data_index import data_index -# defines the order in which objective arguments get concatenated into the state vector -arg_order = ( - "R_lmn", - "Z_lmn", - "L_lmn", - "p_l", - "i_l", - "c_l", - "Psi", - "Te_l", - "ne_l", - "Ti_l", - "Zeff_l", - "Ra_n", - "Za_n", - "Rb_lmn", - "Zb_lmn", -) -# map from profile name to equilibrium parameter name -profile_names = { - "pressure": "p_l", - "iota": "i_l", - "current": "c_l", - "electron_temperature": "Te_l", - "electron_density": "ne_l", - "ion_temperature": "Ti_l", - "atomic_number": "Zeff_l", -} - def _parse_parameterization(p): if isinstance(p, str): @@ -1309,3 +1280,34 @@ def body(i, mins): # The above implementation was benchmarked to be more efficient than # alternatives without explicit loops in GitHub pull request #501. return grid.expand(mins, surface_label) + + +# defines the order in which objective arguments get concatenated into the state vector +arg_order = ( + "R_lmn", + "Z_lmn", + "L_lmn", + "p_l", + "i_l", + "c_l", + "Psi", + "Te_l", + "ne_l", + "Ti_l", + "Zeff_l", + "Ra_n", + "Za_n", + "Rb_lmn", + "Zb_lmn", +) + +# map from profile name to equilibrium parameter name +profile_names = { + "pressure": "p_l", + "iota": "i_l", + "current": "c_l", + "electron_temperature": "Te_l", + "electron_density": "ne_l", + "ion_temperature": "Ti_l", + "atomic_number": "Zeff_l", +} diff --git a/desc/continuation.py b/desc/continuation.py index 55100a2639..870c39e094 100644 --- a/desc/continuation.py +++ b/desc/continuation.py @@ -167,7 +167,7 @@ def _solve_axisym( if mres_step == MIN_MRES_STEP: raise RuntimeError( "Automatic continuation failed with mres_step=1, " - + "something is probaby very wrong with your desired equilibrium." + + "something is probably very wrong with your desired equilibrium." ) else: warnings.warn( @@ -297,7 +297,7 @@ def _add_pressure( if pres_step <= MIN_PRES_STEP: raise RuntimeError( "Automatic continuation failed with " - + f"pres_step={pres_step}, something is probaby very wrong with your " + + f"pres_step={pres_step}, something is probably very wrong with your " + "desired equilibrium." ) else: @@ -430,7 +430,7 @@ def _add_shaping( if bdry_step <= MIN_BDRY_STEP: raise RuntimeError( "Automatic continuation failed with " - + f"bdry_step={bdry_step}, something is probaby very wrong with your " + + f"bdry_step={bdry_step}, something is probably very wrong with your " + "desired equilibrium." ) else: @@ -485,7 +485,7 @@ def solve_continuation_automatic( # noqa: C901 Unsolved Equilibrium with the final desired boundary, profiles, resolution. objective : {"force", "energy", "vacuum"} function to solve for equilibrium solution - optimizer : str or Optimzer (optional) + optimizer : str or Optimizer (optional) optimizer to use pert_order : int order of perturbations to use. @@ -609,7 +609,7 @@ def solve_continuation( # noqa: C901 ): """Solve for an equilibrium by continuation method. - Steps through an EquilibriaFamily, solving each equilibrium, and uses pertubations + Steps through an EquilibriaFamily, solving each equilibrium, and uses perturbations to step between different profiles/boundaries. Uses the previous step as an initial guess for each solution. @@ -620,7 +620,7 @@ def solve_continuation( # noqa: C901 Equilibria to solve for at each step. objective : {"force", "energy", "vacuum"} function to solve for equilibrium solution - optimizer : str or Optimzer (optional) + optimizer : str or Optimizer (optional) optimizer to use pert_order : int or array of int order of perturbations to use. If array-like, should be same length as eqfam diff --git a/desc/derivatives.py b/desc/derivatives.py index ec437cb7b3..0224657e3c 100644 --- a/desc/derivatives.py +++ b/desc/derivatives.py @@ -436,7 +436,6 @@ def _compute_grad_or_jac(self, *args, **kwargs): kwargs : dict keyword arguments passed to fun - Returns ------- J : ndarray of float, shape(len(f),len(x)) @@ -702,7 +701,4 @@ def compute(self, *args, **kwargs): return self._compute(*args, **kwargs) -if use_jax: - Derivative = AutoDiffDerivative -else: - Derivative = FiniteDiffDerivative +Derivative = AutoDiffDerivative if use_jax else FiniteDiffDerivative diff --git a/desc/equilibrium/equilibrium.py b/desc/equilibrium/equilibrium.py index 9cda94f9b1..d646ac0094 100644 --- a/desc/equilibrium/equilibrium.py +++ b/desc/equilibrium/equilibrium.py @@ -1626,7 +1626,6 @@ def solve( ``message`` which describes the cause of the termination. See `OptimizeResult` for a description of other attributes. - """ if constraints is None: constraints = get_fixed_boundary_constraints( @@ -2092,7 +2091,7 @@ def solve_continuation( """Solve for an equilibrium by continuation method. Steps through an EquilibriaFamily, solving each equilibrium, and uses - pertubations to step between different profiles/boundaries. + perturbations to step between different profiles/boundaries. Uses the previous step as an initial guess for each solution. @@ -2102,7 +2101,7 @@ def solve_continuation( Equilibria to solve for at each step. objective : str or ObjectiveFunction (optional) function to solve for equilibrium solution - optimizer : str or Optimzer (optional) + optimizer : str or Optimizer (optional) optimizer to use pert_order : int or array of int order of perturbations to use. If array-like, should be same length as @@ -2170,7 +2169,7 @@ def solve_continuation_automatic( Unsolved Equilibrium with the final desired boundary, profiles, resolution. objective : str or ObjectiveFunction (optional) function to solve for equilibrium solution - optimizer : str or Optimzer (optional) + optimizer : str or Optimizer (optional) optimizer to use pert_order : int order of perturbations to use. @@ -2236,8 +2235,6 @@ def equilibria(self, equil): ) self._equilibria = list(equil) - # dunder methods required by MutableSequence - def __getitem__(self, i): return self._equilibria[i] diff --git a/desc/geometry/core.py b/desc/geometry/core.py index 29e358b1e6..1262356e08 100644 --- a/desc/geometry/core.py +++ b/desc/geometry/core.py @@ -69,7 +69,7 @@ def compute( Computed quantity and intermediate variables. """ - # set a default numpts for the SplineXYZCurve + # set a default number of points for the SplineXYZCurve N = self.N if hasattr(self, "N") else self.X.size if isinstance(names, str): names = [names] diff --git a/desc/geometry/curve.py b/desc/geometry/curve.py index 921653d211..0a0975c593 100644 --- a/desc/geometry/curve.py +++ b/desc/geometry/curve.py @@ -751,17 +751,18 @@ def from_values(cls, coords, knots=None, method="cubic", name="", basis="xyz"): If supplied, will be rescaled to lie in [0,2pi] method : str method of interpolation + - `'nearest'`: nearest neighbor interpolation - `'linear'`: linear interpolation - `'cubic'`: C1 cubic splines (aka local splines) - `'cubic2'`: C2 cubic splines (aka natural splines) - `'catmull-rom'`: C1 cubic centripetal "tension" splines + name : str name for this curve basis : {"rpz", "xyz"} basis for input coordinates. Defaults to "xyz" - Returns ------- SplineXYZCurve: SplineXYZCurve diff --git a/desc/geometry/surface.py b/desc/geometry/surface.py index fe3992ac81..381300057e 100644 --- a/desc/geometry/surface.py +++ b/desc/geometry/surface.py @@ -371,7 +371,7 @@ class ZernikeRZToroidalSection(Surface): For L>0, the indexing scheme defines order of the basis functions: ``'ansi'``: ANSI indexing fills in the pyramid with triangles of - decreasing size, ending in a triagle shape. For L == M, + decreasing size, ending in a triangle shape. For L == M, the traditional ANSI pyramid indexing is recovered. For L>M, adds rows to the bottom of the pyramid, increasing L while keeping M constant, giving a "house" shape diff --git a/desc/io/ascii_io.py b/desc/io/ascii_io.py index e9f3bee289..5eeb976e38 100644 --- a/desc/io/ascii_io.py +++ b/desc/io/ascii_io.py @@ -34,7 +34,7 @@ def write_ascii(fname, eq): file.write("NFP = {:3d}\n".format(int(eq.NFP))) file.write("Psi = {:16.8E}\n".format(eq.Psi)) - # boundary paramters + # boundary parameters if eq.sym: nbdry = len(np.nonzero(eq.Rb_lmn)[0]) + len(np.nonzero(eq.Zb_lmn)[0]) file.write("Nbdry = {:3d}\n".format(nbdry)) diff --git a/desc/io/core_io.py b/desc/io/core_io.py index 9d51d93393..f4e13140a8 100644 --- a/desc/io/core_io.py +++ b/desc/io/core_io.py @@ -11,7 +11,7 @@ def __init__(self): self.resolve_base() def __del__(self): - """Close file upon garbage colleciton or explicit deletion with del function.""" + """Close file upon garbage collection or explicit deletion with del function.""" self.close() def close(self): @@ -53,7 +53,7 @@ def resolve_where(self, where): ------- if where is None: base attribute - if where is file with type foundin _file_types_ + if where is file with type found in _file_types_ where """ diff --git a/desc/io/hdf5_io.py b/desc/io/hdf5_io.py index 9faf1282c3..22c3c0d985 100644 --- a/desc/io/hdf5_io.py +++ b/desc/io/hdf5_io.py @@ -115,7 +115,7 @@ def read_obj(self, obj, where=None): ---------- obj : python object instance object must have _io_attrs_ attribute to have attributes read and loaded - where : None or file insance + where : None or file instance specifies where to read obj from """ @@ -217,7 +217,7 @@ def read_list(self, where=None): Parameters ---------- where : None or file instance - specifies wehre to read dict from + specifies where to read dict from """ thelist = [] diff --git a/desc/io/input_reader.py b/desc/io/input_reader.py index 277f3afec7..cc3da73299 100644 --- a/desc/io/input_reader.py +++ b/desc/io/input_reader.py @@ -566,7 +566,7 @@ def parse_inputs(self, fname=None): # noqa: C901 - FIXME: simplify this if inputs["objective"] == "vacuum" and (pres_flag or iota_flag or curr_flag): warnings.warn( "Vacuum objective does not use any profiles, " - + "ignoring presssure, iota, and current" + + "ignoring pressure, iota, and current" ) # sort axis array @@ -901,7 +901,7 @@ def descout_to_input( # noqa: C901 - fxn too complex f.write("\n") f.write("\n# fixed-boundary surface shape\n") - # boundary paramters + # boundary parameters if eq0.sym: for k, (l, m, n) in enumerate(eq0.surface.R_basis.modes): if abs(eq0.Rb_lmn[k]) > 1e-8: @@ -1615,9 +1615,6 @@ def parse_vmec_inputs(vmec_fname, threshold=0): # noqa: C901 - FIXME: simplify return inputs_arr -# NOTE: this has to be outside the class to work with autodoc - - def get_parser(): """Get parser for command line arguments. @@ -1627,6 +1624,7 @@ def get_parser(): argument parser """ + # NOTE: this has to be outside the class to work with autodoc parser = argparse.ArgumentParser( prog="desc", allow_abbrev=True, diff --git a/desc/io/pickle_io.py b/desc/io/pickle_io.py index 795975b658..c07a01b0ed 100644 --- a/desc/io/pickle_io.py +++ b/desc/io/pickle_io.py @@ -57,7 +57,7 @@ def read_obj(self, obj=None, where=None): ---------- obj : python object instance object must have _io_attrs_ attribute to have attributes read and loaded - where : None or file insance + where : None or file instance specifies where to read obj from """ @@ -107,7 +107,7 @@ def write_obj(self, obj, where=None): ---------- obj : python object instance object must have _io_attrs_ attribute to have attributes read and loaded - where : None or file insance + where : None or file instance specifies where to write obj to """ diff --git a/desc/magnetic_fields.py b/desc/magnetic_fields.py index 3cae6117ad..8125ab8a10 100644 --- a/desc/magnetic_fields.py +++ b/desc/magnetic_fields.py @@ -18,7 +18,6 @@ from desc.vmec_utils import ptolemy_identity_fwd, ptolemy_identity_rev -# TODO: vectorize this over multiple coils def biot_savart(eval_pts, coil_pts, current): """Biot-Savart law following [1]. @@ -39,8 +38,9 @@ def biot_savart(eval_pts, coil_pts, current): [1] Hanson & Hirshman, "Compact expressions for the Biot-Savart fields of a filamentary segment" (2002) """ - dvec = jnp.diff(coil_pts, axis=0) - L = jnp.linalg.norm(dvec, axis=-1) + # TODO: vectorize this over multiple coils + d_vec = jnp.diff(coil_pts, axis=0) + L = jnp.linalg.norm(d_vec, axis=-1) Ri_vec = eval_pts[jnp.newaxis, :] - coil_pts[:-1, jnp.newaxis, :] Ri = jnp.linalg.norm(Ri_vec, axis=-1) @@ -50,7 +50,7 @@ def biot_savart(eval_pts, coil_pts, current): Ri_p_Rf = Ri + Rf # 1.0e-7 == mu_0/(4 pi) - Bmag = ( + B_mag = ( 1.0e-7 * current * 2.0 @@ -58,9 +58,9 @@ def biot_savart(eval_pts, coil_pts, current): / (Ri * Rf * (Ri_p_Rf * Ri_p_Rf - (L * L)[:, jnp.newaxis])) ) - # cross product of L*hat(eps)==dvec with Ri_vec, scaled by Bmag - vec = jnp.cross(dvec[:, jnp.newaxis, :], Ri_vec, axis=-1) - B = jnp.sum(Bmag[:, :, jnp.newaxis] * vec, axis=0) + # cross product of L*hat(eps)==d_vec with Ri_vec, scaled by B_mag + vec = jnp.cross(d_vec[:, jnp.newaxis, :], Ri_vec, axis=-1) + B = jnp.sum(B_mag[:, :, jnp.newaxis] * vec, axis=0) return B diff --git a/desc/objectives/_bootstrap.py b/desc/objectives/_bootstrap.py index 9052f2eea0..a10e6b6808 100644 --- a/desc/objectives/_bootstrap.py +++ b/desc/objectives/_bootstrap.py @@ -20,7 +20,7 @@ class BootstrapRedlConsistency(_Objective): This objective function penalizes the difference between the MHD and neoclassical profiles of parallel current, using the Redl - formula for the boostrap current. The scalar objective is defined as + formula for the bootstrap current. The scalar objective is defined as f = ½ ∫dρ [(⟨J⋅B⟩_MHD - ⟨J⋅B⟩_Redl) / (J_ref B_ref)]² diff --git a/desc/objectives/linear_objectives.py b/desc/objectives/linear_objectives.py index 82419f1ebd..f4e4f0fdca 100644 --- a/desc/objectives/linear_objectives.py +++ b/desc/objectives/linear_objectives.py @@ -117,7 +117,7 @@ def build(self, eq=None, use_jit=False, verbose=1): super().build(eq=eq, use_jit=use_jit, verbose=verbose) def compute(self, *args, **kwargs): - """Compute boundary self consistency errror.""" + """Compute boundary self consistency error.""" params, _ = self._parse_args(*args, **kwargs) return jnp.dot(self._A, params["R_lmn"]) - params["Rb_lmn"] @@ -200,7 +200,7 @@ def build(self, eq=None, use_jit=False, verbose=1): super().build(eq=eq, use_jit=use_jit, verbose=verbose) def compute(self, *args, **kwargs): - """Compute boundary self consistency errror.""" + """Compute boundary self consistency error.""" params, _ = self._parse_args(*args, **kwargs) return jnp.dot(self._A, params["Z_lmn"]) - params["Zb_lmn"] diff --git a/desc/objectives/nae_utils.py b/desc/objectives/nae_utils.py index 68d5adf9d8..c9ba0fb41b 100644 --- a/desc/objectives/nae_utils.py +++ b/desc/objectives/nae_utils.py @@ -150,10 +150,10 @@ def _make_RZ_cons_order_rho(qsc, desc_eq, coeffs, bases): ------- Rconstraints : tuple of Objective tuple of constraints of type FixSumModesR, which enforce - the O(rho) behavior of the equilibrium R coefficents to match the NAE. + the O(rho) behavior of the equilibrium R coefficients to match the NAE. Zconstraints : tuple of Objective tuple of constraints of type FixSumModesZ, which enforce - the O(rho) behavior of the equilibrium Z coefficents to match the NAE. + the O(rho) behavior of the equilibrium Z coefficients to match the NAE. """ # r is the ratio r_NAE / rho_DESC r = np.sqrt(2 * abs(desc_eq.Psi / qsc.Bbar) / 2 / np.pi) diff --git a/desc/objectives/objective_funs.py b/desc/objectives/objective_funs.py index ba9f5f6425..353a2f67c8 100644 --- a/desc/objectives/objective_funs.py +++ b/desc/objectives/objective_funs.py @@ -471,13 +471,13 @@ def hess(self, x, constants=None): return jnp.atleast_2d(self._hess(x, constants).squeeze()) def jac_scaled(self, x, constants=None): - """Compute Jacobian matrx of vector form of the objective wrt x.""" + """Compute Jacobian matrix of vector form of the objective wrt x.""" if constants is None: constants = self.constants return jnp.atleast_2d(self._jac_scaled(x, constants).squeeze()) def jac_unscaled(self, x, constants=None): - """Compute Jacobian matrx of vector form of the objective wrt x, unweighted.""" + """Compute Jacobian matrix of vector form of the objective wrt x, unweighted.""" if constants is None: constants = self.constants return jnp.atleast_2d(self._jac_unscaled(x, constants).squeeze()) diff --git a/desc/objectives/utils.py b/desc/objectives/utils.py index c03e8cfae4..4baaef4d62 100644 --- a/desc/objectives/utils.py +++ b/desc/objectives/utils.py @@ -17,7 +17,6 @@ def factorize_linear_constraints(constraints, objective_args): # noqa: C901 and the null space Z st. Axp=b and AZ=0, so that the full space of solutions to Ax=b can be written as x=xp + Zy where y is now unconstrained. - Parameters ---------- constraints : tuple of Objectives diff --git a/desc/optimize/_constraint_wrappers.py b/desc/optimize/_constraint_wrappers.py index 367bf53983..4ceb72c533 100644 --- a/desc/optimize/_constraint_wrappers.py +++ b/desc/optimize/_constraint_wrappers.py @@ -388,7 +388,7 @@ class ProximalProjection(ObjectiveFunction): to an unconstrained optimizer. At each iteration, after a step is taken to reduce the objective, the equilibrium - is perturbed and re-solved to bring it back into force balance. This is analagous + is perturbed and re-solved to bring it back into force balance. This is analogous to a proximal method where each iterate is projected back onto the feasible set. Parameters diff --git a/desc/optimize/_desc_wrappers.py b/desc/optimize/_desc_wrappers.py index 854e51837c..d3b2bb50fc 100644 --- a/desc/optimize/_desc_wrappers.py +++ b/desc/optimize/_desc_wrappers.py @@ -27,7 +27,7 @@ def _optimize_desc_aug_lagrangian( objective, constraint, x0, method, x_scale, verbose, stoptol, options=None ): - """Wrapper for desc.optimize.fmin_lag_ls_stel. + """Wrapper for desc.optimize.fmin_auglag. Parameters ---------- @@ -123,7 +123,7 @@ def _optimize_desc_aug_lagrangian( def _optimize_desc_aug_lagrangian_least_squares( objective, constraint, x0, method, x_scale, verbose, stoptol, options=None ): - """Wrapper for desc.optimize.fmin_lag_ls_stel. + """Wrapper for desc.optimize.lsq_auglag. Parameters ---------- diff --git a/desc/optimize/_scipy_wrappers.py b/desc/optimize/_scipy_wrappers.py index 5974738549..91347e5fe4 100644 --- a/desc/optimize/_scipy_wrappers.py +++ b/desc/optimize/_scipy_wrappers.py @@ -44,7 +44,7 @@ + "optimize.minimize-trustexact.html", "Trust region method using conjugate gradient to solve subproblem. See " + "https://docs.scipy.org/doc/scipy/reference/optimize.minimize-trustncg.html", - "Trust region method using Kyrlov iterations to solve subproblem. See " + "Trust region method using Krylov iterations to solve subproblem. See " + "https://docs.scipy.org/doc/scipy/reference/" + "optimize.minimize-trustkrylov.html", ], @@ -377,7 +377,7 @@ def fun_wrapped(x): return f def jac_wrapped(x): - # record all the xs and jacs we see + # record all the xs and jacobians we see jac_allx.append(x) J = jac(x, objective.constants) jac_allf.append(J) diff --git a/desc/optimize/aug_lagrangian.py b/desc/optimize/aug_lagrangian.py index c4654c9e2e..1c9058eeb1 100644 --- a/desc/optimize/aug_lagrangian.py +++ b/desc/optimize/aug_lagrangian.py @@ -74,7 +74,7 @@ def fmin_auglag( # noqa: C901 - FIXME: simplify this If None, the termination by this condition is disabled. gtol : float or None, optional Absolute tolerance for termination by the norm of the gradient. - Optimizer teriminates when ``max(abs(g)) < gtol``. + Optimizer terminates when ``max(abs(g)) < gtol``. If None, the termination by this condition is disabled. ctol : float, optional Tolerance for stopping based on infinity norm of the constraint violation. diff --git a/desc/optimize/aug_lagrangian_ls.py b/desc/optimize/aug_lagrangian_ls.py index ed3ad42da6..e56bf6e67b 100644 --- a/desc/optimize/aug_lagrangian_ls.py +++ b/desc/optimize/aug_lagrangian_ls.py @@ -73,7 +73,7 @@ def lsq_auglag( # noqa: C901 - FIXME: simplify this If None, the termination by this condition is disabled. gtol : float or None, optional Absolute tolerance for termination by the norm of the gradient. - Optimizer teriminates when ``norm(g) < gtol``, where + Optimizer terminates when ``norm(g) < gtol``, where If None, the termination by this condition is disabled. ctol : float, optional Tolerance for stopping based on infinity norm of the constraint violation. diff --git a/desc/optimize/optimizer.py b/desc/optimize/optimizer.py index 10609b0521..45fbf7ad09 100644 --- a/desc/optimize/optimizer.py +++ b/desc/optimize/optimizer.py @@ -349,7 +349,7 @@ def _maybe_wrap_nonlinear_constraints( f""" Nonlinear constraints detected but method {method} does not support nonlinear constraints. Defaulting to method "proximal-{method}" - In the future this will raise an error. To ignore this warnging, specify + In the future this will raise an error. To ignore this warning, specify a wrapper "proximal-" to convert the nonlinearly constrained problem into an unconstrained one. """ @@ -405,7 +405,7 @@ def _get_default_tols( stoptol.setdefault("ctol", options.pop("ctol", 1e-4)) stoptol.setdefault("maxiter", options.pop("maxiter", 100)) - # if we define an "iteration" as a sucessful step, it can take a few function + # if we define an "iteration" as a successful step, it can take a few function # evaluations per iteration stoptol["max_nfev"] = options.pop("max_nfev", 5 * stoptol["maxiter"] + 1) # pretty much all the methods only evaluate derivatives once per iteration @@ -459,7 +459,6 @@ def register_optimizer( Dictionary of optional keyword arguments to override default solver settings. - Parameters ---------- name : str or array-like of str diff --git a/desc/optimize/tr_subproblems.py b/desc/optimize/tr_subproblems.py index 5b3a9c530a..35775c92b9 100644 --- a/desc/optimize/tr_subproblems.py +++ b/desc/optimize/tr_subproblems.py @@ -19,7 +19,7 @@ def solve_trust_region_dogleg(g, H, trust_radius, initial_alpha=None, **kwargs): trust_radius : float We are allowed to wander only this far away from the origin. initial_alpha : float - initial guess for levenberg-marquadt parameter - unused by this method. + initial guess for Levenberg-Marquardt parameter - unused by this method. Returns ------- @@ -28,7 +28,7 @@ def solve_trust_region_dogleg(g, H, trust_radius, initial_alpha=None, **kwargs): hits_boundary : bool True if the proposed step is on the boundary of the trust region. alpha : float - "levenberg-marquadt" parameter - unused by this method. + "Levenberg-Marquardt" parameter - unused by this method. """ L = chol(H) @@ -79,7 +79,7 @@ def solve_trust_region_2d_subspace(g, H, trust_radius, initial_alpha=None, **kwa trust_radius : float We are allowed to wander only this far away from the origin. initial_alpha : float - initial guess for levenberg-marquadt parameter - unused by this method + initial guess for Levenberg-Marquardt parameter - unused by this method Returns ------- @@ -88,7 +88,7 @@ def solve_trust_region_2d_subspace(g, H, trust_radius, initial_alpha=None, **kwa hits_boundary : bool True if the proposed step is on the boundary of the trust region. alpha : float - "levenberg-marquadt" parameter - unused by this method + "Levenberg-Marquardt" parameter - unused by this method """ L = chol(H) @@ -352,7 +352,7 @@ def update_tr_radius( max_tr : float maximum allowed trust region radius increase_threshold, increase_ratio : float - if ratio > inrease_threshold, trust radius is increased by a factor + if ratio > increase_threshold, trust radius is increased by a factor of increase_ratio decrease_threshold, decrease_ratio : float if ratio < decrease_threshold, trust radius is decreased by a factor diff --git a/desc/optimize/utils.py b/desc/optimize/utils.py index 7981362f62..1a007ebdc7 100644 --- a/desc/optimize/utils.py +++ b/desc/optimize/utils.py @@ -156,7 +156,7 @@ def gershgorin_bounds(H): """Upper and lower bounds for eigenvalues of a square matrix. Given a square matrix ``H`` compute upper - and lower bounds for its eigenvalues (Gregoshgorin Bounds). + and lower bounds for its eigenvalues (Gershgorin Bounds). Defined ref. [1]. References diff --git a/desc/plotting.py b/desc/plotting.py index 7be86471f8..7ce30908bf 100644 --- a/desc/plotting.py +++ b/desc/plotting.py @@ -44,7 +44,7 @@ colorblind_colors = [ (0.0000, 0.4500, 0.7000), # blue - (0.8359, 0.3682, 0.0000), # vermillion + (0.8359, 0.3682, 0.0000), # vermilion (0.0000, 0.6000, 0.5000), # bluish green (0.9500, 0.9000, 0.2500), # yellow (0.3500, 0.7000, 0.9000), # sky blue @@ -123,7 +123,7 @@ def _get_cmap(name, n=None): def _format_ax(ax, is3d=False, rows=1, cols=1, figsize=None, equal=False): - """Check type of ax argument. If ax is not a matplotlib AxesSubplot, initalize one. + """Check type of ax argument. If ax is not a matplotlib AxesSubplot, initialize one. Parameters ---------- @@ -572,7 +572,7 @@ def plot_2d( * ``title_fontsize``: integer, font size of the title * ``xlabel_fontsize``: float, fontsize of the xlabel * ``ylabel_fontsize``: float, fontsize of the ylabel - * ``cmap``: str, matplotib colormap scheme to use, passed to ax.contourf + * ``cmap``: str, matplotlib colormap scheme to use, passed to ax.contourf * ``levels``: int or array-like, passed to contourf Returns @@ -740,7 +740,7 @@ def plot_3d( * ``xlabel_fontsize``: float, fontsize of the xlabel * ``ylabel_fontsize``: float, fontsize of the ylabel * ``zlabel_fontsize``: float, fontsize of the zlabel - * ``alpha``: float btwn [0,1.0], the transparency of the plotted surface + * ``alpha``: float in [0,1.0], the transparency of the plotted surface * ``elev``: float, elevation orientation angle of 3D plot (in the z plane) * ``azim``: float, azimuthal orientation angle of 3D plot (in the x,y plane) * ``dist``: float, distance from the camera to the center point of the plot @@ -847,7 +847,7 @@ def plot_3d( ax.set_title(label, fontsize=title_fontsize) _set_tight_layout(fig) - # need this stuff to make all the axes equal, ax.axis('equal') doesnt work for 3d + # need this stuff to make all the axes equal, ax.axis('equal') doesn't work for 3d x_limits = ax.get_xlim3d() y_limits = ax.get_ylim3d() z_limits = ax.get_zlim3d() @@ -1132,7 +1132,7 @@ def plot_section( * ``title_fontsize``: integer, font size of the title * ``xlabel_fontsize``: float, fontsize of the xlabel * ``ylabel_fontsize``: float, fontsize of the ylabel - * ``cmap``: str, matplotib colormap scheme to use, passed to ax.contourf + * ``cmap``: str, matplotlib colormap scheme to use, passed to ax.contourf * ``levels``: int or array-like, passed to contourf * ``phi``: float, int or array-like. Toroidal angles to plot. If an integer, plot that number equally spaced in [0,2pi/NFP). Default 1 for axisymmetry and @@ -1709,7 +1709,7 @@ def plot_boundaries(eqs, labels=None, phi=None, ax=None, return_data=False, **kw * ``xlabel_fontsize``: float, fontsize of the x label * ``ylabel_fontsize``: float, fontsize of the y label * ``legend``: bool, whether to display legend or not - * ``legend_kw``: dict, any keyword arguments to be pased to ax.legend() + * ``legend_kw``: dict, any keyword arguments to be passed to ax.legend() * ``cmap``: colormap to use for plotting, discretized into len(eqs) colors * ``color``: list of colors to use for each Equilibrium * ``ls``: list of str, line styles to use for each Equilibrium @@ -1874,7 +1874,7 @@ def plot_comparison( * ``figsize``: tuple of length 2, the size of the figure (to be passed to matplotlib) * ``legend``: bool, whether to display legend or not - * ``legend_kw``: dict, any keyword arguments to be pased to ax.legend() + * ``legend_kw``: dict, any keyword arguments to be passed to ax.legend() * ``title_fontsize``: integer, font size of the title * ``xlabel_fontsize``: float, fontsize of the xlabel * ``ylabel_fontsize``: float, fontsize of the ylabel @@ -1898,7 +1898,7 @@ def plot_comparison( fig, ax = plot_comparison(eqs=[eqf[0],eqf[1],eqf[2]], labels=['Axisymmetric w/o pressure', 'Axisymmetric w/ pressure', - 'Nonaxisymmetric w/ pressure', + 'Non-axisymmetric w/ pressure', ], ) @@ -2149,11 +2149,10 @@ def plot_boozer_modes( * ``lw``: float, linewidth * ``ls``: str, linestyle * ``legend``: bool, whether to display legend or not - * ``legend_kw``: dict, any keyword arguments to be pased to ax.legend() + * ``legend_kw``: dict, any keyword arguments to be passed to ax.legend() * ``xlabel_fontsize``: float, fontsize of the xlabel * ``ylabel_fontsize``: float, fontsize of the ylabel - Returns ------- fig : matplotlib.figure.Figure @@ -2303,7 +2302,7 @@ def plot_boozer_surface( * ``figsize``: tuple of length 2, the size of the figure (to be passed to matplotlib) - * ``cmap``: str, matplotib colormap scheme to use, passed to ax.contourf + * ``cmap``: str, matplotlib colormap scheme to use, passed to ax.contourf * ``levels``: int or array-like, passed to contourf * ``title_fontsize``: integer, font size of the title * ``xlabel_fontsize``: float, fontsize of the xlabel @@ -2485,7 +2484,7 @@ def plot_qs_error( # noqa: 16 fxn too complex qs metrics * ``ylabel``: str, ylabel to use for plot * ``legend``: bool, whether to display legend or not - * ``legend_kw``: dict, any keyword arguments to be pased to ax.legend() + * ``legend_kw``: dict, any keyword arguments to be passed to ax.legend() * ``xlabel_fontsize``: float, fontsize of the xlabel * ``ylabel_fontsize``: float, fontsize of the ylabel * ``labels``: list of strs of length 3, labels to apply to each QS error metric @@ -2528,7 +2527,7 @@ def plot_qs_error( # noqa: 16 fxn too complex lw = kwargs.pop("lw", [1, 1, 1]) ylabel = kwargs.pop("ylabel", False) xlabel_fontsize = kwargs.pop("xlabel_fontsize", None) - ylabel_fontsize = kwargs.pop("yxlabel_fontsize", None) + ylabel_fontsize = kwargs.pop("ylabel_fontsize", None) with warnings.catch_warnings(): warnings.simplefilter("ignore") @@ -2791,7 +2790,7 @@ def plot_basis(basis, return_data=False, **kwargs): * ``figsize``: tuple of length 2, the size of the figure (to be passed to matplotlib) - * ``cmap``: str, matplotib colormap scheme to use, passed to ax.contourf + * ``cmap``: str, matplotlib colormap scheme to use, passed to ax.contourf * ``title_fontsize``: integer, font size of the title Returns @@ -2820,8 +2819,6 @@ def plot_basis(basis, return_data=False, **kwargs): title_fontsize = kwargs.pop("title_fontsize", None) if basis.__class__.__name__ == "PowerSeries": - # fixme: lmax unused - lmax = abs(basis.modes[:, 0]).max() grid = LinearGrid(rho=100, endpoint=True) r = grid.nodes[:, 0] fig, ax = plt.subplots(figsize=kwargs.get("figsize", (6, 4))) @@ -2848,8 +2845,6 @@ def plot_basis(basis, return_data=False, **kwargs): return fig, ax elif basis.__class__.__name__ == "FourierSeries": - # fixme nmax unused - nmax = abs(basis.modes[:, 2]).max() grid = LinearGrid(zeta=100, NFP=basis.NFP, endpoint=True) z = grid.nodes[:, 2] fig, ax = plt.subplots(figsize=kwargs.get("figsize", (6, 4))) @@ -3013,18 +3008,18 @@ def plot_basis(basis, return_data=False, **kwargs): return fig, ax -def plot_logo(savepath=None, **kwargs): +def plot_logo(save_path=None, **kwargs): """Plot the DESC logo. Parameters ---------- - savepath : str or path-like + save_path : str or path-like path to save the figure to. File format is inferred from the filename (Default value = None) **kwargs : dict, optional additional plot formatting parameters. - options include ``'Dcolor'``, ``'Dcolor_rho'``, ``'Dcolor_theta'``, - ``'Ecolor'``, ``'Scolor'``, ``'Ccolor'``, ``'BGcolor'``, ``'fig_width'`` + options include ``'D_color'``, ``'D_color_rho'``, ``'D_color_theta'``, + ``'E_color'``, ``'Scolor'``, ``'C_color'``, ``'BGcolor'``, ``'fig_width'`` Returns ------- @@ -3040,7 +3035,7 @@ def plot_logo(savepath=None, **kwargs): .. code-block:: python from desc.plotting import plot_logo - plot_logo(savepath='../_static/images/plotting/plot_logo.png') + plot_logo(save_path='../_static/images/plotting/plot_logo.png') """ eq = np.array( @@ -3094,12 +3089,12 @@ def plot_logo(savepath=None, **kwargs): ) onlyD = kwargs.get("onlyD", False) - Dcolor = kwargs.get("Dcolor", "xkcd:neon purple") - Dcolor_rho = kwargs.get("Dcolor_rho", "xkcd:neon pink") - Dcolor_theta = kwargs.get("Dcolor_theta", "xkcd:neon pink") - Ecolor = kwargs.get("Ecolor", "deepskyblue") + D_color = kwargs.get("D_color", "xkcd:neon purple") + D_color_rho = kwargs.get("D_color_rho", "xkcd:neon pink") + D_color_theta = kwargs.get("D_color_theta", "xkcd:neon pink") + E_color = kwargs.get("E_color", "deepskyblue") Scolor = kwargs.get("Scolor", "deepskyblue") - Ccolor = kwargs.get("Ccolor", "deepskyblue") + C_color = kwargs.get("C_color", "deepskyblue") BGcolor = kwargs.get("BGcolor", "clear") fig_width = kwargs.get("fig_width", 3) fig_height = fig_width / 2 @@ -3191,7 +3186,7 @@ def plot_logo(savepath=None, **kwargs): ax.plot( R.T[:, ::rstep], Z.T[:, ::rstep], - color=Dcolor_rho, + color=D_color_rho, lw=lw * contour_lw_ratio, ls="-", ) @@ -3199,29 +3194,29 @@ def plot_logo(savepath=None, **kwargs): ax.plot( R[:, ::tstep], Z[:, ::tstep], - color=Dcolor_theta, + color=D_color_theta, lw=lw * contour_lw_ratio, ls="-", ) - ax.plot(bdryR, bdryZ, color=Dcolor, lw=lw) + ax.plot(bdryR, bdryZ, color=D_color, lw=lw) if onlyD: - if savepath is not None: - fig.savefig(savepath, facecolor=fig.get_facecolor(), edgecolor="none") + if save_path is not None: + fig.savefig(save_path, facecolor=fig.get_facecolor(), edgecolor="none") return fig, ax # E - ax.plot([Eleft, Eleft + 1], [bottom, top], lw=lw, color=Ecolor, linestyle="-") - ax.plot([Eleft, Eright], [bottom, bottom], lw=lw, color=Ecolor, linestyle="-") + ax.plot([Eleft, Eleft + 1], [bottom, top], lw=lw, color=E_color, linestyle="-") + ax.plot([Eleft, Eright], [bottom, bottom], lw=lw, color=E_color, linestyle="-") ax.plot( [Eleft + 1 / 2, Eright], [bottom + (top + bottom) / 2, bottom + (top + bottom) / 2], lw=lw, - color=Ecolor, + color=E_color, linestyle="-", ) - ax.plot([Eleft + 1, Eright], [top, top], lw=lw, color=Ecolor, linestyle="-") + ax.plot([Eleft + 1, Eright], [top, top], lw=lw, color=E_color, linestyle="-") # S Sy = np.linspace(bottom, top + Soffset, 1000) @@ -3231,10 +3226,10 @@ def plot_logo(savepath=None, **kwargs): # C Cx = Cw / 2 * np.cos(Ctheta) + Cx0 Cy = Ch / 2 * np.sin(Ctheta) + Cy0 - ax.plot(Cx, Cy, lw=lw, color=Ccolor, linestyle="-") + ax.plot(Cx, Cy, lw=lw, color=C_color, linestyle="-") - if savepath is not None: - fig.savefig(savepath, facecolor=fig.get_facecolor(), edgecolor="none") + if save_path is not None: + fig.savefig(save_path, facecolor=fig.get_facecolor(), edgecolor="none") return fig, ax @@ -3402,7 +3397,7 @@ def plot_field_lines_sfl( ) _set_tight_layout(fig) - # need this stuff to make all the axes equal, ax.axis('equal') doesnt work for 3d + # need this stuff to make all the axes equal, ax.axis('equal') doesn't work for 3d x_limits = ax.get_xlim3d() y_limits = ax.get_ylim3d() z_limits = ax.get_zlim3d() @@ -3495,10 +3490,10 @@ def plot_field_lines_real_space( entries are lists corresponding to the field lines for each seed_theta given. Also contains the scipy IVP solutions for info on how each line was integrated. B_interp : dict, only returned if return_B_interp is True - dict of scipy.interpolate.rbf.Rbf or equivalent call signature interplators, + dict of scipy.interpolate.rbf.Rbf or equivalent call signature interpolators, which interpolate the cylindrical components of magnetic field in (R,phi,Z). Dict has the following keys: ['B_R'], ['B_Z'], and ['B_phi'], corresponding to - the interplating object for each cylindrical component of the magnetic field, + the interpolating object for each cylindrical component of the magnetic field, and the interpolators have call signature B(R,phi,Z) = interpolator(R,phi,Z) Notes @@ -3593,7 +3588,7 @@ def plot_field_lines_real_space( ) _set_tight_layout(fig) - # need this stuff to make all the axes equal, ax.axis('equal') doesnt work for 3d + # need this stuff to make all the axes equal, ax.axis('equal') doesn't work for 3d x_limits = ax.get_xlim3d() y_limits = ax.get_ylim3d() z_limits = ax.get_zlim3d() diff --git a/desc/profiles.py b/desc/profiles.py index 26169d22b9..1db526a1de 100644 --- a/desc/profiles.py +++ b/desc/profiles.py @@ -161,7 +161,7 @@ def to_spline(self, knots=20, method="cubic2"): - `'linear'`: linear interpolation - `'cubic'`: C1 cubic splines (aka local splines) - `'cubic2'`: C2 cubic splines (aka natural splines) - - `'catmull-rom'`: C1 cubic centripedal "tension" splines + - `'catmull-rom'`: C1 cubic centripetal "tension" splines Returns ------- diff --git a/desc/random.py b/desc/random.py index e40213d432..e1108342c6 100644 --- a/desc/random.py +++ b/desc/random.py @@ -35,7 +35,6 @@ def random_surface( Where N(m,s) is a normal random variable on with mean m and stdev s, and X_norm = exp(-alpha*(|m| + |n|)) / exp(-alpha) - Parameters ---------- M, N : int diff --git a/desc/utils.py b/desc/utils.py index 30f6568da5..889459b8ed 100644 --- a/desc/utils.py +++ b/desc/utils.py @@ -270,7 +270,7 @@ def issorted(x, axis=None, tol=1e-12): Returns ------- - issorted : bool + is_sorted : bool whether the array is sorted along specified axis """ @@ -294,7 +294,7 @@ def isalmostequal(x, axis=-1, rtol=1e-6, atol=1e-12): relative tolerance for comparison. atol : float absolute tolerance for comparison. - If the following equation is element-wise True, then isalmostequal returns True. + If the following equation is element-wise True, then returns True. absolute(a - b) <= (atol + rtol * absolute(b)) where a= x[0] and b is every other element of x, if flattened array, or if axis is not None, a = x[:,0,:] and b = x[:,i,:] for all i, and @@ -302,7 +302,7 @@ def isalmostequal(x, axis=-1, rtol=1e-6, atol=1e-12): Returns ------- - isalmostequal : bool + is_almost_equal : bool whether the array is equal along specified axis """ @@ -347,13 +347,10 @@ def islinspaced(x, axis=-1, rtol=1e-6, atol=1e-12): relative tolerance for comparison. atol : float absolute tolerance for comparison. - If the following equation is element-wise True for, - then isalmostequal returns True. - absolute(a - b) <= (atol + rtol * absolute(b)) Returns ------- - islinspaced : bool + is_linspaced : bool whether the array is linearly spaced along specified axis """ diff --git a/desc/vmec.py b/desc/vmec.py index 79e8aebd77..e43efd3b7b 100644 --- a/desc/vmec.py +++ b/desc/vmec.py @@ -64,7 +64,7 @@ def load( Notes ----- - To ensure compatibiltiy with different profile representations in VMEC, + To ensure compatibility with different profile representations in VMEC, the resulting equilibrium will always have SplineProfile types for all profiles """ @@ -253,7 +253,7 @@ def save(cls, eq, path, surfs=128, verbose=1): # noqa: C901 - FIXME - simplify file.createDimension("n_tor", N + 1) # number of toroidal Fourier modes file.createDimension("preset", 21) # dimension of profile inputs file.createDimension("ndfmax", 101) # used for am_aux & ai_aux - file.createDimension("time", 100) # used for fsqrt & wdot + file.createDimension("time", 100) # used for fsq* & wdot file.createDimension("dim_00001", 1) file.createDimension("dim_00020", 20) file.createDimension("dim_00100", 100) @@ -518,7 +518,7 @@ def save(cls, eq, path, surfs=128, verbose=1): # noqa: C901 - FIXME - simplify betator[:] = eq.compute("_vol")["_vol"] ctor = file.createVariable("ctor", np.float64) - ctor.long_name = "total toroidal plamsa current" + ctor.long_name = "total toroidal plasma current" ctor.units = "A" grid = LinearGrid(M=eq.M_grid, N=eq.N_grid, rho=[1.0], NFP=NFP) ctor[:] = eq.compute("I", grid=grid)["I"][0] * 2 * np.pi / mu_0 @@ -1408,7 +1408,8 @@ def compute_theta_coords(cls, lmns, xm, xn, s, theta_star, zeta, si=None): s : array-like desired radial coordinates (normalized toroidal magnetic flux) theta_star : array-like - desired straigh field-line poloidal angles (PEST/VMEC-like flux coordinates) + desired straight field-line poloidal angles (PEST/VMEC-like flux + coordinates) zeta : array-like desired toroidal angles (toroidal coordinate phi) si : ndarray diff --git a/desc/vmec_utils.py b/desc/vmec_utils.py index 5194da3bb3..23e82e8013 100644 --- a/desc/vmec_utils.py +++ b/desc/vmec_utils.py @@ -120,7 +120,7 @@ def _modes_x_to_mnsc(vmec_modes, x): cmask = vmec_modes[:, 0] == 1 smask = vmec_modes[:, 0] == -1 _, xm, xn = vmec_modes[cmask].T - if not np.any(cmask): # there are no cos modes, so use smask to get modenumbers + if not np.any(cmask): # there are no cos modes, so use mask to get mode numbers _, xm, xn = vmec_modes[smask].T # concatenate the 0,0 mode xm = np.insert(xm, 0, 0) @@ -175,7 +175,7 @@ def _desc_modes_from_vmec_modes(vmec_modes): def ptolemy_linear_transform(desc_modes, vmec_modes=None, helicity=None, NFP=None): - """Compute linear trasformation matrix equivalent to reverse Ptolemy's identity. + """Compute linear transformation matrix equivalent to reverse Ptolemy's identity. Parameters ---------- @@ -311,7 +311,6 @@ def fourier_to_zernike(m, n, x_mn, basis): return x_lmn -# FIXME: this always returns the full double Fourier basis regardless of symmetry def zernike_to_fourier(x_lmn, basis, rho): """Convert from a Fourier-Zernike basis to a double Fourier series. @@ -336,6 +335,7 @@ def zernike_to_fourier(x_lmn, basis, rho): axis to the boundary. """ + # FIXME: this always returns the full double Fourier basis regardless of symmetry M = basis.M N = basis.N diff --git a/tests/test_bootstrap.py b/tests/test_bootstrap.py index c1a4ceb9c1..b008ffa9a7 100644 --- a/tests/test_bootstrap.py +++ b/tests/test_bootstrap.py @@ -1192,7 +1192,7 @@ def test_BootstrapRedlConsistency_normalization(self): integrand = (data[""] - data[" Redl"]) / (scales["B"] * scales["J"]) expected = 0.5 * sum(grid.weights * integrand**2) / (4 * np.pi**2) print( - "boostrap objectives for scaled configs:", results, " expected:", expected + "bootstrap objectives for scaled configs:", results, " expected:", expected ) # Results are not perfectly identical because ln(Lambda) is not quite invariant. diff --git a/tests/test_configuration.py b/tests/test_configuration.py index b3f58a0caa..2c36abd211 100644 --- a/tests/test_configuration.py +++ b/tests/test_configuration.py @@ -195,7 +195,7 @@ def test_asserts(self): eq = Equilibrium(iota="def") with pytest.raises(TypeError): eq = Equilibrium(current="def") - with pytest.raises(ValueError): # change to typeeror if allow both + with pytest.raises(ValueError): # change to TypeError if allow both eq = Equilibrium(iota="def", current="def") with pytest.raises(ValueError): eq = Equilibrium(iota=None) diff --git a/tests/test_curves.py b/tests/test_curves.py index 45d4dd484d..7d9f5a35e6 100644 --- a/tests/test_curves.py +++ b/tests/test_curves.py @@ -51,7 +51,7 @@ def test_torsion(self): @pytest.mark.unit def test_frenet(self): - """Test frenet-seret frame of circular curve.""" + """Test frenet-serret frame of circular curve.""" c = FourierRZCurve() data = c.compute( ["frenet_tangent", "frenet_normal", "frenet_binormal"], basis="rpz", grid=0 @@ -249,7 +249,7 @@ def test_torsion(self): @pytest.mark.unit def test_frenet(self): - """Test frenet-seret frame of circular curve.""" + """Test frenet-serret frame of circular curve.""" c = FourierXYZCurve() data = c.compute( ["frenet_tangent", "frenet_normal", "frenet_binormal"], basis="rpz", grid=0 @@ -378,7 +378,7 @@ def test_torsion(self): @pytest.mark.unit def test_frenet(self): - """Test frenet-seret frame of circular curve.""" + """Test frenet-serret frame of circular curve.""" c = FourierPlanarCurve() data = c.compute( ["frenet_tangent", "frenet_normal", "frenet_binormal"], basis="xyz", grid=0 @@ -530,7 +530,7 @@ def test_length(self): continue # don't test changing the grid if nearest # since it will give wrong answers for # grids with more than the initial num of knots - # check lengths when changing X,Y,Z from intial values + # check lengths when changing X,Y,Z from initial values # and from changing grids R = 1.1 c.X = R * np.cos(phi) diff --git a/tests/test_derivatives.py b/tests/test_derivatives.py index 8dbf427672..8cb4ed9bf5 100644 --- a/tests/test_derivatives.py +++ b/tests/test_derivatives.py @@ -107,7 +107,7 @@ def f(x): @pytest.mark.unit def test_block_jacobian(self): - """Test calculation of jacoiban using blocked method.""" + """Test calculation of jacobian using blocked method.""" rando = default_rng(seed=0) A = rando.random((19, 17)) diff --git a/tests/test_examples.py b/tests/test_examples.py index 3ea046f4cf..0e58faa07b 100644 --- a/tests/test_examples.py +++ b/tests/test_examples.py @@ -615,7 +615,7 @@ def test_NAE_QSC_solve(): B_nae += -B_mn_nae[i] * np.sin(m * th) * np.cos(n * ph) elif m < 0 and n < 0: B_nae += B_mn_nae[i] * np.sin(m * th) * np.sin(n * ph) - # Eliminate the poloidal angle to focus on the toroidal behaviour + # Eliminate the poloidal angle to focus on the toroidal behavior B_av_nae = np.mean(B_nae, axis=1) np.testing.assert_allclose(B_av_nae, np.ones(np.size(phi)) * qsc.B0, atol=1e-4) @@ -627,7 +627,7 @@ def test_NAE_QIC_solve(): """Test O(rho) NAE QIC constraints solve.""" # get Qic example qsc = Qic.from_paper("QI NFP2 r2", nphi=301, order="r1") - qsc.lasym = False # don't need to consider stell asym for order 1 constraints + qsc.lasym = False # don't need to consider stellarator asym for order 1 constraints ntheta = 75 r = 0.01 N = 11 @@ -717,7 +717,7 @@ def test_NAE_QIC_solve(): B_nae += -B_mn_nae[i] * np.sin(m * th) * np.cos(n * ph) elif m < 0 and n < 0: B_nae += B_mn_nae[i] * np.sin(m * th) * np.sin(n * ph) - # Eliminate the poloidal angle to focus on the toroidal behaviour + # Eliminate the poloidal angle to focus on the toroidal behavior B_av_nae = np.mean(B_nae, axis=1) np.testing.assert_allclose(B_av_nae, np.ones(np.size(phi)) * qsc.B0, atol=2e-2) diff --git a/tests/test_input_output.py b/tests/test_input_output.py index 6cd5319557..da38787b82 100644 --- a/tests/test_input_output.py +++ b/tests/test_input_output.py @@ -1,4 +1,4 @@ -"""Tests for reading/writing intput/output, both ascii and binary.""" +"""Tests for reading/writing input/output, both ascii and binary.""" import os import pathlib @@ -70,7 +70,7 @@ def test_write_desc_input_Nones(tmpdir_factory): # the written file will have ftol = 0.01,0.001 # and the None will have not been written - # if only Nones are passed for just one of the tols, only that one will not + # if only Nones are passed for just one of the tolerances, only that one will not # be written. gtol is used here as that test input_path = "./tests/inputs/DSHAPE" @@ -239,7 +239,7 @@ class TestInputReader: """Tests for the InputReader class.""" argv0 = [] - argv1 = ["nonexistant_input_file"] + argv1 = ["nonexistent_input_file"] argv2 = ["./tests/inputs/MIN_INPUT"] @pytest.mark.unit diff --git a/tests/test_surfaces.py b/tests/test_surfaces.py index 94e389f5fa..e4e79831d8 100644 --- a/tests/test_surfaces.py +++ b/tests/test_surfaces.py @@ -137,7 +137,7 @@ def test_curvature(self): class TestZernikeRZToroidalSection: - """Tests for ZerinkeRZTorioidalSection class.""" + """Tests for ZernikeRZToroidalSection class.""" @pytest.mark.unit def test_area(self):