diff --git a/.github/workflows/linting.yml b/.github/workflows/linting.yml index d38f71d6f..43e4ac956 100644 --- a/.github/workflows/linting.yml +++ b/.github/workflows/linting.yml @@ -19,13 +19,6 @@ jobs: with: python-version: ${{ matrix.python-version }} - - name: Install python dependencies - run: | - pip install flake8 + - name: Run ruff + uses: chartboost/ruff-action@v1 - - name: Run linting tests - run: | - export EXCLUDE="E226,E265,E266,E4,E5,E7,W,F" - flake8 --ignore $EXCLUDE src/ - flake8 --ignore $EXCLUDE tests/ - flake8 --ignore $EXCLUDE examples/ diff --git a/examples/1_Simple/just_a_quadratic.py b/examples/1_Simple/just_a_quadratic.py index 78a3c630a..f91e7b8d7 100755 --- a/examples/1_Simple/just_a_quadratic.py +++ b/examples/1_Simple/just_a_quadratic.py @@ -1,6 +1,5 @@ #!/usr/bin/env python3 -import logging from simsopt.objectives.functions import Identity from simsopt.objectives import LeastSquaresProblem from simsopt.solve import least_squares_serial_solve diff --git a/examples/1_Simple/permanent_magnet_simple.py b/examples/1_Simple/permanent_magnet_simple.py index 3276cadb7..f4b87dbfa 100755 --- a/examples/1_Simple/permanent_magnet_simple.py +++ b/examples/1_Simple/permanent_magnet_simple.py @@ -26,7 +26,6 @@ from matplotlib import pyplot as plt from simsopt.field import DipoleField, ToroidalField from simsopt.geo import PermanentMagnetGrid, SurfaceRZFourier -from simsopt.objectives import SquaredFlux from simsopt.solve import GPMO from simsopt.util.permanent_magnet_helper_functions import * diff --git a/examples/1_Simple/stage_two_optimization_minimal.py b/examples/1_Simple/stage_two_optimization_minimal.py index f9a7e287f..3b065e4f9 100755 --- a/examples/1_Simple/stage_two_optimization_minimal.py +++ b/examples/1_Simple/stage_two_optimization_minimal.py @@ -135,7 +135,7 @@ def fun(dofs): """) res = minimize(fun, dofs, jac=True, method='L-BFGS-B', options={'maxiter': MAXITER, 'maxcor': 300, 'iprint': 5}, tol=1e-15) -curves_to_vtk(curves, OUT_DIR + f"curves_opt", close=True) +curves_to_vtk(curves, OUT_DIR + "curves_opt", close=True) pointData = {"B_N": np.sum(bs.B().reshape((nphi, ntheta, 3)) * s.unitnormal(), axis=2)[:, :, None]} s.to_vtk(OUT_DIR + "surf_opt", extra_data=pointData) diff --git a/examples/1_Simple/tracing_fieldlines_QA.py b/examples/1_Simple/tracing_fieldlines_QA.py index b9b2572e9..a3357dd31 100755 --- a/examples/1_Simple/tracing_fieldlines_QA.py +++ b/examples/1_Simple/tracing_fieldlines_QA.py @@ -17,7 +17,6 @@ import time import os import logging -import sys from pathlib import Path import numpy as np diff --git a/examples/2_Intermediate/QSC.py b/examples/2_Intermediate/QSC.py index 195466b49..205c89fb5 100755 --- a/examples/2_Intermediate/QSC.py +++ b/examples/2_Intermediate/QSC.py @@ -1,7 +1,5 @@ #!/usr/bin/env python3 -import logging -import numpy as np from qsc import Qsc from simsopt._core import Optimizable diff --git a/examples/2_Intermediate/boozerQA.py b/examples/2_Intermediate/boozerQA.py index 23eb398e0..ef7e36505 100755 --- a/examples/2_Intermediate/boozerQA.py +++ b/examples/2_Intermediate/boozerQA.py @@ -7,7 +7,7 @@ from simsopt.configs import get_ncsx_data from simsopt.field import BiotSavart, coils_via_symmetries from simsopt.geo import SurfaceXYZTensorFourier, BoozerSurface, curves_to_vtk, boozer_surface_residual, \ - ToroidalFlux, Volume, MajorRadius, CurveLength, CurveCurveDistance, NonQuasiSymmetricRatio, Iotas + Volume, MajorRadius, CurveLength, NonQuasiSymmetricRatio, Iotas from simsopt.objectives import QuadraticPenalty from simsopt.util import in_github_actions @@ -83,7 +83,7 @@ # sum the objectives together JF = J_nonQSRatio + J_iotas + J_major_radius + Jls -curves_to_vtk(curves, OUT_DIR + f"curves_init") +curves_to_vtk(curves, OUT_DIR + "curves_init") boozer_surface.surface.to_vtk(OUT_DIR + "surf_init") # let's fix the coil current @@ -144,7 +144,7 @@ def fun(dofs): MAXITER = 50 if in_github_actions else 1e3 res = minimize(fun, dofs, jac=True, method='BFGS', options={'maxiter': MAXITER}, tol=1e-15) -curves_to_vtk(curves, OUT_DIR + f"curves_opt") +curves_to_vtk(curves, OUT_DIR + "curves_opt") boozer_surface.surface.to_vtk(OUT_DIR + "surf_opt") print("End of 2_Intermediate/boozerQA.py") diff --git a/examples/2_Intermediate/permanent_magnet_MUSE.py b/examples/2_Intermediate/permanent_magnet_MUSE.py index 9f9a9b1d4..534d50331 100755 --- a/examples/2_Intermediate/permanent_magnet_MUSE.py +++ b/examples/2_Intermediate/permanent_magnet_MUSE.py @@ -21,8 +21,6 @@ https://github.com/akaptano/simsopt_permanent_magnet_advanced_scripts.git """ -import os -import pickle import time from pathlib import Path @@ -257,7 +255,6 @@ # surface is at least 64 x 64 resolution. vmec_flag = False if vmec_flag: - from mpi4py import MPI from simsopt.mhd.vmec import Vmec from simsopt.util.mpi import MpiPartition mpi = MpiPartition(ngroups=1) diff --git a/examples/2_Intermediate/permanent_magnet_PM4Stell.py b/examples/2_Intermediate/permanent_magnet_PM4Stell.py index 6febd3aa8..a9a1b0694 100755 --- a/examples/2_Intermediate/permanent_magnet_PM4Stell.py +++ b/examples/2_Intermediate/permanent_magnet_PM4Stell.py @@ -15,7 +15,6 @@ Ken Hammond and the PM4Stell + MAGPIE teams. ''' -import os from pathlib import Path import time diff --git a/examples/2_Intermediate/permanent_magnet_QA.py b/examples/2_Intermediate/permanent_magnet_QA.py index 16fb2f9a4..f263fc2ea 100755 --- a/examples/2_Intermediate/permanent_magnet_QA.py +++ b/examples/2_Intermediate/permanent_magnet_QA.py @@ -31,12 +31,10 @@ are available to OpenMP, e.g. through setting OMP_NUM_THREADS). """ -import os import time from pathlib import Path import numpy as np -from matplotlib import pyplot as plt from simsopt.field import BiotSavart, DipoleField from simsopt.geo import PermanentMagnetGrid, SurfaceRZFourier @@ -242,7 +240,6 @@ # surface is at least 64 x 64 resolution. vmec_flag = False if vmec_flag: - from mpi4py import MPI from simsopt.mhd.vmec import Vmec from simsopt.util.mpi import MpiPartition mpi = MpiPartition(ngroups=1) diff --git a/examples/2_Intermediate/stage_two_optimization.py b/examples/2_Intermediate/stage_two_optimization.py index 3dd147fcf..e71becd7f 100755 --- a/examples/2_Intermediate/stage_two_optimization.py +++ b/examples/2_Intermediate/stage_two_optimization.py @@ -166,7 +166,7 @@ def fun(dofs): ################################################################################ """) res = minimize(fun, dofs, jac=True, method='L-BFGS-B', options={'maxiter': MAXITER, 'maxcor': 300}, tol=1e-15) -curves_to_vtk(curves, OUT_DIR + f"curves_opt_short") +curves_to_vtk(curves, OUT_DIR + "curves_opt_short") pointData = {"B_N": np.sum(bs.B().reshape((nphi, ntheta, 3)) * s.unitnormal(), axis=2)[:, :, None]} s.to_vtk(OUT_DIR + "surf_opt_short", extra_data=pointData) @@ -177,7 +177,7 @@ def fun(dofs): dofs = res.x LENGTH_WEIGHT *= 0.1 res = minimize(fun, dofs, jac=True, method='L-BFGS-B', options={'maxiter': MAXITER, 'maxcor': 300}, tol=1e-15) -curves_to_vtk(curves, OUT_DIR + f"curves_opt_long") +curves_to_vtk(curves, OUT_DIR + "curves_opt_long") pointData = {"B_N": np.sum(bs.B().reshape((nphi, ntheta, 3)) * s.unitnormal(), axis=2)[:, :, None]} s.to_vtk(OUT_DIR + "surf_opt_long", extra_data=pointData) diff --git a/examples/2_Intermediate/stage_two_optimization_stochastic.py b/examples/2_Intermediate/stage_two_optimization_stochastic.py index 085360ce3..ab45f4ede 100755 --- a/examples/2_Intermediate/stage_two_optimization_stochastic.py +++ b/examples/2_Intermediate/stage_two_optimization_stochastic.py @@ -163,10 +163,7 @@ def fun(dofs): JF.x = dofs J = JF.J() grad = JF.dJ() - cl_string = ", ".join([f"{J.J():.3f}" for J in Jls]) - mean_AbsB = np.mean(bs.AbsB()) jf = Jmpi.J() - BdotN = np.mean(np.abs(np.sum(bs.B().reshape((nphi, ntheta, 3)) * s.unitnormal(), axis=2))) outstr = f"J={J:.1e}, ⟨Jf⟩={jf:.1e}" cl_string = ", ".join([f"{J.J():.1f}" for J in Jls]) kap_string = ", ".join(f"{np.max(c.kappa()):.1f}" for c in base_curves) diff --git a/examples/3_Advanced/single_stage_optimization.py b/examples/3_Advanced/single_stage_optimization.py index 5f4dea3e1..546dda7e3 100755 --- a/examples/3_Advanced/single_stage_optimization.py +++ b/examples/3_Advanced/single_stage_optimization.py @@ -8,7 +8,6 @@ """ import os import numpy as np -from mpi4py import MPI from pathlib import Path from scipy.optimize import minimize from simsopt.util import MpiPartition, proc0_print, comm_world @@ -57,7 +56,7 @@ ARCLENGTH_WEIGHT = 1e-9 # Weight for the arclength variation penalty in the objective function ########################################################################################## ########################################################################################## -directory = f'optimization_QH' +directory = 'optimization_QH' vmec_verbose = False # Create output directories this_path = os.path.join(parent_path, directory) @@ -109,7 +108,7 @@ J_LENGTH_PENALTY = LENGTH_CON_WEIGHT * sum([QuadraticPenalty(Jls[i], LENGTH_THRESHOLD) for i in range(len(base_curves))]) JF = Jf + J_CC + J_LENGTH + J_LENGTH_PENALTY + J_CURVATURE + J_MSC ########################################################################################## -proc0_print(f' Starting optimization') +proc0_print(' Starting optimization') ########################################################################################## # Initial stage 2 optimization ########################################################################################## @@ -229,7 +228,7 @@ def fun(dofs, prob_jacobian=None, info={'Nfeval': 0}): pointData = {"B_N": BdotN_surf[:, :, None]} surf.to_vtk(os.path.join(coils_results_path, "surf_opt"), extra_data=pointData) bs.save(os.path.join(coils_results_path, "biot_savart_opt.json")) -vmec.write_input(os.path.join(this_path, f'input.final')) +vmec.write_input(os.path.join(this_path, 'input.final')) proc0_print(f"Aspect ratio after optimization: {vmec.aspect()}") proc0_print(f"Mean iota after optimization: {vmec.mean_iota()}") proc0_print(f"Quasisymmetry objective after optimization: {qs.total()}") diff --git a/examples/3_Advanced/single_stage_optimization_finite_beta.py b/examples/3_Advanced/single_stage_optimization_finite_beta.py index 88b4336d8..1c2696226 100755 --- a/examples/3_Advanced/single_stage_optimization_finite_beta.py +++ b/examples/3_Advanced/single_stage_optimization_finite_beta.py @@ -10,7 +10,6 @@ """ import os import numpy as np -from mpi4py import MPI from math import isnan from pathlib import Path from scipy.optimize import minimize @@ -62,7 +61,7 @@ ARCLENGTH_WEIGHT = 1e-9 # Weight for the arclength variation penalty in the objective function ########################################################################################## ########################################################################################## -directory = f'optimization_QH_finitebeta' +directory = 'optimization_QH_finitebeta' vmec_verbose = False # Create output directories this_path = os.path.join(parent_path, directory) @@ -122,7 +121,7 @@ JF = Jf + J_CC + J_LENGTH + J_LENGTH_PENALTY + J_CURVATURE + J_MSC ########################################################################################## -proc0_print(f' Starting optimization') +proc0_print(' Starting optimization') ########################################################################################## # Initial stage 2 optimization ########################################################################################## @@ -169,7 +168,7 @@ def fun_J(prob, coils_prob): try: vc = VirtualCasing.from_vmec(vmec, src_nphi=vc_src_nphi, trgt_nphi=nphi_VMEC, trgt_ntheta=ntheta_VMEC, filename=None) Jf.target = vc.B_external_normal - except ObjectiveFailure as e: + except ObjectiveFailure: pass bs.set_points(surf.gamma().reshape((-1, 3))) @@ -265,7 +264,7 @@ def fun(dofss, prob_jacobian, info={'Nfeval': 0}): pointData = {"B_N": BdotN_surf[:, :, None]} surf.to_vtk(os.path.join(coils_results_path, "surf_opt"), extra_data=pointData) bs.save(os.path.join(coils_results_path, "biot_savart_opt.json")) -vmec.write_input(os.path.join(this_path, f'input.final')) +vmec.write_input(os.path.join(this_path, 'input.final')) proc0_print(f"Aspect ratio after optimization: {vmec.aspect()}") proc0_print(f"Mean iota after optimization: {vmec.mean_iota()}") proc0_print(f"Quasisymmetry objective after optimization: {qs.total()}") diff --git a/examples/stellarator_benchmarks/1DOF_circularCrossSection_varyAxis_targetIota.py b/examples/stellarator_benchmarks/1DOF_circularCrossSection_varyAxis_targetIota.py index fe66f1558..cc348d432 100755 --- a/examples/stellarator_benchmarks/1DOF_circularCrossSection_varyAxis_targetIota.py +++ b/examples/stellarator_benchmarks/1DOF_circularCrossSection_varyAxis_targetIota.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 import os -from mpi4py import MPI import numpy as np from simsopt.mhd import Vmec diff --git a/examples/stellarator_benchmarks/1DOF_circularCrossSection_varyR0_targetVolume.py b/examples/stellarator_benchmarks/1DOF_circularCrossSection_varyR0_targetVolume.py index 457a1aa77..90d990436 100755 --- a/examples/stellarator_benchmarks/1DOF_circularCrossSection_varyR0_targetVolume.py +++ b/examples/stellarator_benchmarks/1DOF_circularCrossSection_varyR0_targetVolume.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 import numpy as np -from mpi4py import MPI from simsopt.objectives import LeastSquaresProblem from simsopt.mhd import Vmec diff --git a/pyproject.toml b/pyproject.toml index c71eb7de6..f877c5587 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,3 +3,18 @@ requires = ["setuptools>=45", "wheel", "oldest-supported-numpy", "cmake", "ninja build-backend = "setuptools.build_meta" [tools.setuptools_scm] + +[tool.ruff] +src = ["src/simsopt"] +ignore = ["E226","E265","E266","E4","E501","E701","E702","E712","E722","E731","E741","F403","F405","F406","W5"] +extend-exclude = ["thirdparty"] +[tool.ruff.per-file-ignores] +"__init__.py" = ["E402","F401"] +"src/simsopt/field/magneticfieldclasses.py" = ["E743"] +"src/simsopt/mhd/bootstrap.py" = ["F841"] +"src/simsopt/mhd/vmec_diagnostics.py" = ["F841"] +"tests/verify_MPI_not_initialized.py" = ["F401"] +"tests/geo/test_plot.py" = ["F401"] +"tests/geo/test_curve.py" = ["F401"] +"tests/geo/test_surface.py" = ["F401"] +"tests/mhd/test_virtual_casing.py" = ["F841"] diff --git a/run_autopep b/run_autopep index cc6232543..14d401464 100755 --- a/run_autopep +++ b/run_autopep @@ -2,7 +2,8 @@ # https://pycodestyle.pycqa.org/en/latest/intro.html#error-codes set -ex -EXCLUDE="E226,E265,E266,E4,E5,E7,W,F" +# EXCLUDE="E226,E265,E266,E4,E5,E7,W,F" +EXCLUDE="E226,E265,E266,E4,E501,E722,F403,F405,F406,W5" flake8 --ignore $EXCLUDE src/ || (exit 0) flake8 --ignore $EXCLUDE tests/ || (exit 0) flake8 --ignore $EXCLUDE examples/ || (exit 0) diff --git a/run_ruff b/run_ruff new file mode 100755 index 000000000..67fd3dcc8 --- /dev/null +++ b/run_ruff @@ -0,0 +1,7 @@ +#!/bin/bash +# https://pycodestyle.pycqa.org/en/latest/intro.html#error-codes +set -ex + +ruff check . || (exit 0) +ruff check --fix . +ruff check . diff --git a/src/simsopt/_core/optimizable.py b/src/simsopt/_core/optimizable.py index a739004d0..45c9e5d31 100644 --- a/src/simsopt/_core/optimizable.py +++ b/src/simsopt/_core/optimizable.py @@ -1289,7 +1289,6 @@ def upper_bounds(self) -> RealArray: Upper bounds of the free DOFs associated with the current Optimizable object and those of its ancestors """ - opts = self.ancestors + [self] return np.concatenate([opt._dofs.free_upper_bounds for opt in self.unique_dof_lineage]) @upper_bounds.setter diff --git a/src/simsopt/field/coil.py b/src/simsopt/field/coil.py index 86dc2b522..e2ab7dd0b 100644 --- a/src/simsopt/field/coil.py +++ b/src/simsopt/field/coil.py @@ -4,7 +4,7 @@ from simsopt._core.optimizable import Optimizable from simsopt._core.derivative import Derivative from simsopt.geo.curvexyzfourier import CurveXYZFourier -from simsopt.geo.curve import RotatedCurve, Curve +from simsopt.geo.curve import RotatedCurve import simsoptpp as sopp diff --git a/src/simsopt/field/magneticfield.py b/src/simsopt/field/magneticfield.py index 213ce74b9..cfe03ba68 100644 --- a/src/simsopt/field/magneticfield.py +++ b/src/simsopt/field/magneticfield.py @@ -118,9 +118,6 @@ def to_mgrid(self, filename, nr=10, nphi=4, nz=12, rmin=1.0, rmax=2.0, zmin=-0.5 zs = np.linspace(zmin, zmax, nz, endpoint=True) Phi, Z, R = np.meshgrid(phis, zs, rs, indexing='ij') - X = R * np.cos(Phi) - Y = R * np.sin(Phi) - Z = Z RPhiZ = np.zeros((R.size, 3)) RPhiZ[:, 0] = R.flatten() diff --git a/src/simsopt/field/magneticfieldclasses.py b/src/simsopt/field/magneticfieldclasses.py index 9ad1bfba1..101fe80e7 100644 --- a/src/simsopt/field/magneticfieldclasses.py +++ b/src/simsopt/field/magneticfieldclasses.py @@ -46,7 +46,6 @@ def _B_impl(self, B): def _dB_by_dX_impl(self, dB): points = self.get_points_cart_ref() - phi = np.arctan2(points[:, 1], points[:, 0]) R = np.sqrt(np.square(points[:, 0]) + np.square(points[:, 1])) x = points[:, 0] @@ -66,8 +65,6 @@ def _dB_by_dX_impl(self, dB): def _d2B_by_dXdX_impl(self, ddB): points = self.get_points_cart_ref() - x = points[:, 0] - y = points[:, 1] ddB[:] = 2*self.B0*self.R0*np.multiply( 1/(points[:, 0]**2+points[:, 1]**2)**3, np.array([ [[3*points[:, 0]**2+points[:, 1]**3, points[:, 0]**3-3*points[:, 0]*points[:, 1]**2, np.zeros((len(points)))], [ @@ -397,7 +394,6 @@ def _B_impl(self, B): k = np.sqrt(1-np.divide(np.square(alpha), np.square(beta))) ellipek2 = ellipe(k**2) ellipkk2 = ellipk(k**2) - gamma = np.square(points[:, 0]) - np.square(points[:, 1]) B[:] = np.dot(self.rotMatrix, np.array( [self.Inorm*points[:, 0]*points[:, 2]/(2*alpha**2*beta*rho**2+1e-31)*((self.r0**2+r**2)*ellipek2-alpha**2*ellipkk2), self.Inorm*points[:, 1]*points[:, 2]/(2*alpha**2*beta*rho**2+1e-31)*((self.r0**2+r**2)*ellipek2-alpha**2*ellipkk2), @@ -666,7 +662,6 @@ def _toVTK(self, vtkname): mx = np.ascontiguousarray(self.m_vec[:, 0]) my = np.ascontiguousarray(self.m_vec[:, 1]) mz = np.ascontiguousarray(self.m_vec[:, 2]) - mmag = np.sqrt(mx ** 2 + my ** 2 + mz ** 2) mx_normalized = np.ascontiguousarray(mx / self.m_maxima) my_normalized = np.ascontiguousarray(my / self.m_maxima) mz_normalized = np.ascontiguousarray(mz / self.m_maxima) @@ -680,11 +675,12 @@ def _toVTK(self, vtkname): mtheta_normalized = np.ascontiguousarray(mtheta / self.m_maxima) # Save all the data to a vtk file which can be visualized nicely with ParaView - data = {"m": (mx, my, mz), "m_normalized": (mx_normalized, my_normalized, mz_normalized), "m_rphiz": (mr, mphi, mz), "m_rphiz_normalized": (mr_normalized, mphi_normalized, mz_normalized), "m_rphitheta": (mrminor, mphi, mtheta), "m_rphitheta_normalized": (mrminor_normalized, mphi_normalized, mtheta_normalized)} + data = {"m": (mx, my, mz), "m_normalized": (mx_normalized, my_normalized, mz_normalized), + "m_rphiz": (mr, mphi, mz), "m_rphiz_normalized": (mr_normalized, mphi_normalized, mz_normalized), + "m_rphitheta": (mrminor, mphi, mtheta), + "m_rphitheta_normalized": (mrminor_normalized, mphi_normalized, mtheta_normalized)} from pyevtk.hl import pointsToVTK - pointsToVTK( - str(vtkname), ox, oy, oz, data=data - ) + pointsToVTK(str(vtkname), ox, oy, oz, data=data) class Dommaschk(MagneticField): diff --git a/src/simsopt/field/mgrid.py b/src/simsopt/field/mgrid.py index 21c83b91b..e7873ee03 100644 --- a/src/simsopt/field/mgrid.py +++ b/src/simsopt/field/mgrid.py @@ -1,4 +1,3 @@ -import sys import numpy as np from scipy.io import netcdf_file diff --git a/src/simsopt/field/tracing.py b/src/simsopt/field/tracing.py index f5ab3d164..f07947859 100644 --- a/src/simsopt/field/tracing.py +++ b/src/simsopt/field/tracing.py @@ -475,7 +475,6 @@ def compute_resonances(res_tys, res_phi_hits, ma=None, delta=1e-2): theta0 = res_tys[ip][0, 2] zeta0 = res_tys[ip][0, 3] theta0_mod = theta0 % (2*np.pi) - zeta0_mod = zeta0 % (2*np.pi) x0 = s0 * np.cos(theta0) y0 = s0 * np.sin(theta0) else: @@ -550,10 +549,10 @@ def compute_resonances(res_tys, res_phi_hits, ma=None, delta=1e-2): logger.debug(f'(R,Z)r = {np.sqrt(res_tys[ip][indexr,1]**2 + res_tys[ip][indexr,2]**2),res_tys[ip][indexr,3]}') mpol = np.amax([mpoll, mpolm, mpolr]) - index_mpol = np.argmax([mpoll, mpolm, mpolr]) + # index_mpol = np.argmax([mpoll, mpolm, mpolr]) ntor = np.amax([ntorl, ntorm, ntorr]) - index_ntor = np.argmax([ntorl, ntorm, ntorr]) - index = np.amax([index_mpol, index_ntor]) + # index_ntor = np.argmax([ntorl, ntorm, ntorr]) + # index = np.amax([index_mpol, index_ntor]) resonances.append(np.asarray([R0, Z0, phi0, vpar0, t, mpol, ntor])) return resonances diff --git a/src/simsopt/geo/curve.py b/src/simsopt/geo/curve.py index a1d1aab0e..a19fc92a2 100644 --- a/src/simsopt/geo/curve.py +++ b/src/simsopt/geo/curve.py @@ -204,10 +204,8 @@ def dkappa_by_dcoeff_impl(self, dkappa_by_dcoeff): dgamma_by_dphidphi = self.gammadashdash() dgamma_by_dphidcoeff = self.dgammadash_by_dcoeff() dgamma_by_dphidphidcoeff = self.dgammadashdash_by_dcoeff() - num_coeff = dgamma_by_dphidcoeff.shape[2] norm = lambda a: np.linalg.norm(a, axis=1) - inner = lambda a, b: np.sum(a*b, axis=1) numerator = np.cross(dgamma_by_dphi, dgamma_by_dphidphi) denominator = self.incremental_arclength() dkappa_by_dcoeff[:, :] = (1 / (denominator**3*norm(numerator)))[:, None] * np.sum(numerator[:, :, None] * ( @@ -288,7 +286,6 @@ def frenet_frame(self): tdash = (1./l[:, None])**2 * (l[:, None] * gammadashdash - (inner(gammadash, gammadashdash)/l)[:, None] * gammadash ) - kappa = self.kappa n[:, :] = (1./norm(tdash))[:, None] * tdash b[:, :] = np.cross(t, n, axis=1) return t, n, b @@ -327,7 +324,6 @@ def dfrenet_frame_by_dcoeff(self): norm = lambda a: np.linalg.norm(a, axis=1) inner = lambda a, b: np.sum(a*b, axis=1) - inner2 = lambda a, b: np.sum(a*b, axis=2) N = len(self.quadpoints) dt_by_dcoeff, dn_by_dcoeff, db_by_dcoeff = (np.zeros((N, 3, self.num_dofs())), np.zeros((N, 3, self.num_dofs())), np.zeros((N, 3, self.num_dofs()))) diff --git a/src/simsopt/geo/curveperturbed.py b/src/simsopt/geo/curveperturbed.py index 2b2255803..14ce54e16 100644 --- a/src/simsopt/geo/curveperturbed.py +++ b/src/simsopt/geo/curveperturbed.py @@ -3,7 +3,7 @@ import numpy as np from sympy import Symbol, lambdify, exp -from .._core.json import GSONable, GSONDecoder +from .._core.json import GSONable from .._core.util import RealArray import simsoptpp as sopp diff --git a/src/simsopt/geo/curverzfourier.py b/src/simsopt/geo/curverzfourier.py index c92d55a60..fc8eb219c 100644 --- a/src/simsopt/geo/curverzfourier.py +++ b/src/simsopt/geo/curverzfourier.py @@ -1,7 +1,6 @@ import numpy as np import simsoptpp as sopp -from .._core.json import GSONDecoder from .curve import Curve __all__ = ['CurveRZFourier'] diff --git a/src/simsopt/geo/permanent_magnet_grid.py b/src/simsopt/geo/permanent_magnet_grid.py index 7ffbb40bc..88ee65b6a 100644 --- a/src/simsopt/geo/permanent_magnet_grid.py +++ b/src/simsopt/geo/permanent_magnet_grid.py @@ -5,7 +5,7 @@ from pyevtk.hl import pointsToVTK from .._core.descriptor import OneofStrings -from . import Surface, SurfaceRZFourier +from . import Surface import simsoptpp as sopp __all__ = ['PermanentMagnetGrid'] diff --git a/src/simsopt/geo/qfmsurface.py b/src/simsopt/geo/qfmsurface.py index 8378f5ecc..67cd3ad63 100644 --- a/src/simsopt/geo/qfmsurface.py +++ b/src/simsopt/geo/qfmsurface.py @@ -1,4 +1,4 @@ -from scipy.optimize import minimize, NonlinearConstraint +from scipy.optimize import minimize # , NonlinearConstraint from .._core.json import GSONable from .surfaceobjectives import QfmResidual @@ -165,7 +165,7 @@ def minimize_qfm_exact_constraints_SLSQP(self, tol=1e-3, maxiter=1000): con = lambda x: self.qfm_label_constraint(x, derivatives=1)[0] dcon = lambda x: self.qfm_label_constraint(x, derivatives=1)[1] - nlc = NonlinearConstraint(con, 0, 0) + # nlc = NonlinearConstraint(con, 0, 0) eq_constraints = [{'type': 'eq', 'fun': con, 'jac': dcon}] res = minimize( fun, x, jac=True, method='SLSQP', constraints=eq_constraints, diff --git a/src/simsopt/geo/surface.py b/src/simsopt/geo/surface.py index 8221d0e4a..cd055ac8f 100644 --- a/src/simsopt/geo/surface.py +++ b/src/simsopt/geo/surface.py @@ -11,7 +11,7 @@ from .._core.optimizable import Optimizable from .._core.dev import SimsoptRequires from .plotting import fix_matplotlib_3d -from .._core.json import GSONable, GSONDecoder +from .._core.json import GSONable __all__ = ['Surface', 'signed_distance_from_surface', 'SurfaceClassifier', 'SurfaceScaled', 'best_nphi_over_ntheta'] diff --git a/src/simsopt/geo/surfacegarabedian.py b/src/simsopt/geo/surfacegarabedian.py index 36de86a1f..7fcb66c7e 100644 --- a/src/simsopt/geo/surfacegarabedian.py +++ b/src/simsopt/geo/surfacegarabedian.py @@ -3,7 +3,7 @@ import numpy as np import simsoptpp as sopp -from .._core.descriptor import Integer, Float, PositiveInteger, OneofIntegers, OneofStrings +from .._core.descriptor import Integer from .surface import Surface from .surfacerzfourier import SurfaceRZFourier diff --git a/src/simsopt/geo/surfacehenneberg.py b/src/simsopt/geo/surfacehenneberg.py index cf984ab3a..69626c9d4 100644 --- a/src/simsopt/geo/surfacehenneberg.py +++ b/src/simsopt/geo/surfacehenneberg.py @@ -4,7 +4,7 @@ import numpy as np from scipy.optimize import minimize_scalar from scipy.interpolate import interp1d -#import matplotlib.pyplot as plt +# import matplotlib.pyplot as plt import simsoptpp as sopp from .surface import Surface @@ -682,7 +682,7 @@ def gammadash1_impl(self, data): rho += self.get_rhomn(m, n) * cosangle d_rho_d_phi -= self.get_rhomn(m, n) * sinangle * (nfp * n - alpha) R0H2D = np.kron(R0H, np.ones((ntheta, 1))) - Z0H2D = np.kron(Z0H, np.ones((ntheta, 1))) + # Z0H2D = np.kron(Z0H, np.ones((ntheta, 1))) b2D = np.kron(b, np.ones((ntheta, 1))) zeta = b2D * np.sin(theta - alpha * phi) d_R0H2D_d_phi = np.kron(d_R0H_d_phi, np.ones((ntheta, 1))) @@ -693,7 +693,7 @@ def gammadash1_impl(self, data): sinaphi = np.sin(alpha * phi) cosaphi = np.cos(alpha * phi) R = R0H2D + rho * cosaphi - zeta * sinaphi - Z = Z0H2D + rho * sinaphi + zeta * cosaphi + # Z = Z0H2D + rho * sinaphi + zeta * cosaphi d_R_d_phi = d_R0H2D_d_phi + d_rho_d_phi * cosaphi + rho * (-alpha * sinaphi) \ - d_zeta_d_phi * sinaphi - zeta * (alpha * cosaphi) d_Z_d_phi = d_Z0H2D_d_phi + d_rho_d_phi * sinaphi + rho * (alpha * cosaphi) \ diff --git a/src/simsopt/geo/surfaceobjectives.py b/src/simsopt/geo/surfaceobjectives.py index e18ae1a31..bfe3ebf21 100644 --- a/src/simsopt/geo/surfaceobjectives.py +++ b/src/simsopt/geo/surfaceobjectives.py @@ -430,7 +430,6 @@ def parameter_derivatives(surface: Surface, 1d array of size (ndofs) """ N = surface.normal() - norm_N = np.linalg.norm(N, axis=2) dx_by_dc = surface.dgamma_by_dcoeff() N_dot_dx_by_dc = np.einsum('ijk,ijkl->ijl', N, dx_by_dc) nphi = surface.gamma().shape[0] diff --git a/src/simsopt/mhd/profiles.py b/src/simsopt/mhd/profiles.py index f9c3b7ae6..ac4d7528c 100644 --- a/src/simsopt/mhd/profiles.py +++ b/src/simsopt/mhd/profiles.py @@ -16,7 +16,6 @@ from .._core.optimizable import Optimizable from .._core.descriptor import PositiveInteger -from .._core.types import RealArray __all__ = ['Profile', 'ProfilePolynomial', 'ProfileScaled', 'ProfileSpline', 'ProfilePressure', 'ProfileSpec'] diff --git a/src/simsopt/mhd/spec.py b/src/simsopt/mhd/spec.py index c4347275a..f708e57a6 100644 --- a/src/simsopt/mhd/spec.py +++ b/src/simsopt/mhd/spec.py @@ -798,7 +798,7 @@ def run(self, update_guess: bool = True): si.zac[0:mn] = self.axis['zac'] # Set initial guess - if not self.initial_guess is None: + if self.initial_guess is not None: # Set all modes to zero spec.allglobal.mmrzrz[:] = 0 spec.allglobal.nnrzrz[:] = 0 @@ -939,7 +939,7 @@ def run(self, update_guess: bool = True): spec.allglobal.broadcast_inputs() logger.debug('About to call preset') spec.preset() - logger.debug(f'About to call init_outfile') + logger.debug('About to call init_outfile') spec.sphdf5.init_outfile() logger.debug('About to call mirror_input_to_outfile') spec.sphdf5.mirror_input_to_outfile() @@ -948,7 +948,7 @@ def run(self, update_guess: bool = True): spec.allglobal.wrtend() logger.debug('About to call init_convergence_output') spec.sphdf5.init_convergence_output() - logger.debug(f'About to call spec') + logger.debug('About to call spec') spec.spec() logger.debug('About to call diagnostics') spec.final_diagnostics() diff --git a/src/simsopt/mhd/vmec.py b/src/simsopt/mhd/vmec.py index 0214fab0f..6e56e703b 100644 --- a/src/simsopt/mhd/vmec.py +++ b/src/simsopt/mhd/vmec.py @@ -330,14 +330,13 @@ def __init__(self, logger.info('About to call runvmec to readin') vmec.runvmec(self.ictrl, filename, self.verbose, self.fcomm, reset_file) ierr = self.ictrl[1] - logger.info('Done with runvmec. ierr={}. Calling cleanup next.'.format(ierr)) + logger.info(f'Done with runvmec. ierr={ierr}. Calling cleanup next.') # Deallocate arrays allocated by VMEC's fixaray(): vmec.cleanup(False) if ierr != 0: - raise RuntimeError("Failed to initialize VMEC from input file {}. " - "error code {}".format(filename, ierr)) + raise RuntimeError(f"Failed to initialize VMEC from input file {filename}. Error code: {ierr}.") - objstr = " for Vmec " + str(hex(id(self))) + # objstr = " for Vmec " + str(hex(id(self))) # A vmec object has mpol and ntor attributes independent of # the boundary. The boundary surface object is initialized @@ -390,7 +389,7 @@ def boundary(self): @boundary.setter def boundary(self, boundary): - if not boundary is self._boundary: + if boundary is not self._boundary: logging.debug('Replacing surface in boundary setter') self.remove_parent(self._boundary) self._boundary = boundary @@ -403,7 +402,7 @@ def pressure_profile(self): @pressure_profile.setter def pressure_profile(self, pressure_profile): - if not pressure_profile is self._pressure_profile: + if pressure_profile is not self._pressure_profile: logging.debug('Replacing pressure_profile in setter') if self._pressure_profile is not None: self.remove_parent(self._pressure_profile) @@ -418,7 +417,7 @@ def current_profile(self): @current_profile.setter def current_profile(self, current_profile): - if not current_profile is self._current_profile: + if current_profile is not self._current_profile: logging.debug('Replacing current_profile in setter') if self._current_profile is not None: self.remove_parent(self._current_profile) @@ -433,7 +432,7 @@ def iota_profile(self): @iota_profile.setter def iota_profile(self, iota_profile): - if not iota_profile is self._iota_profile: + if iota_profile is not self._iota_profile: logging.debug('Replacing iota_profile in setter') if self._iota_profile is not None: self.remove_parent(self._iota_profile) @@ -583,17 +582,17 @@ def get_input(self): if vi.nzeta != 0: nml += f'NZETA = {vi.nzeta}\n' index = np.max(np.nonzero(vi.ns_array)) - nml += f'NS_ARRAY =' + nml += 'NS_ARRAY =' for j in range(index + 1): nml += f'{vi.ns_array[j]:7}' nml += '\n' index = np.max(np.where(vi.niter_array > 0)) - nml += f'NITER_ARRAY =' + nml += 'NITER_ARRAY =' for j in range(index + 1): nml += f'{vi.niter_array[j]:7}' nml += '\n' index = np.max(np.nonzero(vi.ftol_array)) - nml += f'FTOL_ARRAY =' + nml += 'FTOL_ARRAY =' for j in range(index + 1): nml += f'{vi.ftol_array[j]:7}' nml += '\n' @@ -717,8 +716,7 @@ def run(self): # should logically never occur, so these codes raise a # different exception. if ierr in [0, 5]: - raise RuntimeError(f"runvmec returned an error code that should " \ - "never occur: ierr={ierr}") + raise RuntimeError(f"runvmec returned an error code that should never occur: ierr={ierr}") if ierr != 11: raise ObjectiveFailure(f"VMEC did not converge. ierr={ierr}") diff --git a/src/simsopt/mhd/vmec_diagnostics.py b/src/simsopt/mhd/vmec_diagnostics.py index 86c464c17..e2a217991 100644 --- a/src/simsopt/mhd/vmec_diagnostics.py +++ b/src/simsopt/mhd/vmec_diagnostics.py @@ -164,7 +164,6 @@ def compute(self): d_psi_d_s = -self.vmec.wout.phi[-1] / (2 * np.pi) # First, interpolate in s to get the quantities we need on the surfaces we need. - method = 'linear' interp = interp1d(vmec.s_half_grid, vmec.wout.iotas[1:], fill_value="extrapolate") iota = interp(self.surfaces) @@ -1277,9 +1276,6 @@ def vmec_fieldlines(vs, s, alpha, theta1d=None, phi1d=None, phi_center=0, plot=F mnmax = vs.mnmax xm = vs.xm xn = vs.xn - mnmax_nyq = vs.mnmax_nyq - xm_nyq = vs.xm_nyq - xn_nyq = vs.xn_nyq # Now that we have an s grid, evaluate everything on that grid: iota = vs.iota(s) diff --git a/src/simsopt/objectives/functions.py b/src/simsopt/objectives/functions.py index 09ee5792f..19b33b3c3 100644 --- a/src/simsopt/objectives/functions.py +++ b/src/simsopt/objectives/functions.py @@ -275,13 +275,12 @@ def f(self): def dJ(self): x = self.local_full_x - v1 = x[0] v2 = x[1] t = self.parents[0]() a = self.parents[1]() cosat = np.cos(v2 + t) sinat = np.sin(v2 + t) - # Order of terms in the gradient: v1, v2, t, a + # Order of terms in the gradient: x[0], v2, t, a return np.concatenate((np.array([1.0, -a * sinat]), -a * sinat * self.parents[0].dJ(), cosat * self.parents[1].dJ())) diff --git a/src/simsopt/objectives/least_squares.py b/src/simsopt/objectives/least_squares.py index 16e146f0f..029ca806e 100644 --- a/src/simsopt/objectives/least_squares.py +++ b/src/simsopt/objectives/least_squares.py @@ -18,7 +18,7 @@ from .._core.optimizable import Optimizable from .._core.util import ObjectiveFailure -from .._core.types import RealArray, IntArray, BoolArray +from .._core.types import RealArray __all__ = ['LeastSquaresProblem'] diff --git a/src/simsopt/solve/mpi.py b/src/simsopt/solve/mpi.py index 8b5f8ae44..9c92009ea 100644 --- a/src/simsopt/solve/mpi.py +++ b/src/simsopt/solve/mpi.py @@ -19,7 +19,7 @@ try: from mpi4py import MPI -except ImportError as err: +except ImportError: MPI = None from .._core.optimizable import Optimizable @@ -494,7 +494,6 @@ def nlc_jac(x): if prob.has_nlc: constraint_file.close() - datalog_started = False logger.info("Completed solve.") # Finally, make sure all procs get the optimal state vector. diff --git a/src/simsopt/solve/permanent_magnet_optimization.py b/src/simsopt/solve/permanent_magnet_optimization.py index 5cbfc876d..851476047 100644 --- a/src/simsopt/solve/permanent_magnet_optimization.py +++ b/src/simsopt/solve/permanent_magnet_optimization.py @@ -182,7 +182,7 @@ def relax_and_split(pm_opt, m0=None, **kwargs): """ # change to row-major order for the C++ code - A_obj = np.ascontiguousarray(pm_opt.A_obj) + # A_obj = np.ascontiguousarray(pm_opt.A_obj) ATb = np.ascontiguousarray(np.reshape(pm_opt.ATb, (pm_opt.ndipoles, 3))) # print initial errors and values before optimization @@ -426,17 +426,17 @@ def GPMO(pm_opt, algorithm='baseline', **kwargs): pm_opt.num_nonzeros = num_nonzeros[num_nonzeros != 0] elif algorithm == 'ArbVec_backtracking': # GPMOb with arbitrary vectors if pm_opt.coordinate_flag != 'cartesian': - raise ValueError('ArbVec_backtracking algorithm currently ' \ + raise ValueError('ArbVec_backtracking algorithm currently ' 'only supports dipole grids with \n' 'moment vectors in the Cartesian basis.') nGridPoints = int(A_obj.shape[1]/3) if "m_init" in kwargs.keys(): if kwargs["m_init"].shape[0] != nGridPoints: - raise ValueError('Initialization vector `m_init` must have ' \ - 'as many rows as there are dipoles in the ' \ - 'grid'); + raise ValueError('Initialization vector `m_init` must have ' + 'as many rows as there are dipoles in the ' + 'grid') elif kwargs["m_init"].shape[1] != 3: - raise ValueError('Initialization vector `m_init` must have '\ + raise ValueError('Initialization vector `m_init` must have ' 'three columns') kwargs["x_init"] = contig(kwargs["m_init"] \ / (mmax_vec.reshape(pm_opt.ndipoles, 3))) diff --git a/src/simsopt/util/famus_helpers.py b/src/simsopt/util/famus_helpers.py index b8ddb6565..2856b0666 100644 --- a/src/simsopt/util/famus_helpers.py +++ b/src/simsopt/util/famus_helpers.py @@ -136,7 +136,7 @@ def read_from_file(self, filename, keep_Ic_zeros, downsample): with open(str(filename), 'r') as focusfile: # Ignore the first line in the file - line1 = focusfile.readline() + focusfile.readline() # Record the number of magnets and the momentq line2data = [int(number) for number in \ @@ -164,7 +164,7 @@ def read_from_file(self, filename, keep_Ic_zeros, downsample): self.op = np.zeros(self.nMagnets) # Ignore the third line in the file - line3 = focusfile.readline() + focusfile.readline() # Read the data for each magnet from the file count = 0 @@ -194,7 +194,7 @@ def read_from_file(self, filename, keep_Ic_zeros, downsample): if i == 0: if len(linedata) > self.nProps: try: - testnum = np.double(linedata[12]) + _ = np.double(linedata[12]) self.has_op = True self.nProps = self.nProps + 1 except: diff --git a/src/simsopt/util/permanent_magnet_helper_functions.py b/src/simsopt/util/permanent_magnet_helper_functions.py index ee73d5753..05681280a 100644 --- a/src/simsopt/util/permanent_magnet_helper_functions.py +++ b/src/simsopt/util/permanent_magnet_helper_functions.py @@ -185,7 +185,7 @@ def fun(dofs): ### Run the optimisation ####################################################### ################################################################################ """) - res = minimize(fun, dofs, jac=True, method='L-BFGS-B', options={'maxiter': MAXITER, 'maxcor': 300}, tol=1e-15) + minimize(fun, dofs, jac=True, method='L-BFGS-B', options={'maxiter': MAXITER, 'maxcor': 300}, tol=1e-15) curves_to_vtk(curves, out_dir / "curves_opt") bs.set_points(s.gamma().reshape((-1, 3))) return bs @@ -203,8 +203,8 @@ def trace_fieldlines(bfield, label, s, comm, out_dir=''): comm: MPI COMM_WORLD object for using MPI for tracing. out_dir: Path or string for the output directory for saved files. """ - from simsopt.field.tracing import particles_to_vtk, compute_fieldlines, \ - LevelsetStoppingCriterion, plot_poincare_data, \ + from simsopt.field.tracing import compute_fieldlines, \ + plot_poincare_data, \ IterationStoppingCriterion, SurfaceClassifier out_dir = Path(out_dir) @@ -223,7 +223,7 @@ def trace_fieldlines(bfield, label, s, comm, out_dir=''): fieldlines_tys, fieldlines_phi_hits = compute_fieldlines( bfield, R0, Z0, tmax=tmax_fl, tol=1e-16, comm=comm, - phis=phis, # stopping_criteria=[LevelsetStoppingCriterion(sc_fieldline.dist)]) + phis=phis, stopping_criteria=[IterationStoppingCriterion(20000)]) # make the poincare plots @@ -245,7 +245,7 @@ def make_qfm(s, Bfield): qfm_surface: The identified QfmSurface class object. """ from simsopt.geo.qfmsurface import QfmSurface - from simsopt.geo.surfaceobjectives import QfmResidual, ToroidalFlux, Area, Volume + from simsopt.geo.surfaceobjectives import QfmResidual, Volume # weight for the optimization constraint_weight = 1e0 @@ -259,13 +259,13 @@ def make_qfm(s, Bfield): vol_target = vol.J() qfm_surface = QfmSurface(Bfield, s, vol, vol_target) - res = qfm_surface.minimize_qfm_penalty_constraints_LBFGS(tol=1e-20, maxiter=50, - constraint_weight=constraint_weight) + qfm_surface.minimize_qfm_penalty_constraints_LBFGS(tol=1e-20, maxiter=50, + constraint_weight=constraint_weight) print(f"||vol constraint||={0.5*(s.volume()-vol_target)**2:.8e}, ||residual||={np.linalg.norm(qfm.J()):.8e}") # repeat the optimization for further convergence - res = qfm_surface.minimize_qfm_penalty_constraints_LBFGS(tol=1e-20, maxiter=200, - constraint_weight=constraint_weight) + qfm_surface.minimize_qfm_penalty_constraints_LBFGS(tol=1e-20, maxiter=200, + constraint_weight=constraint_weight) print(f"||vol constraint||={0.5*(s.volume()-vol_target)**2:.8e}, ||residual||={np.linalg.norm(qfm.J()):.8e}") return qfm_surface @@ -380,8 +380,6 @@ def calculate_on_axis_B(bs, s): bs.set_points(bspoints) B0 = np.linalg.norm(bs.B(), axis=-1) B0avg = np.mean(np.linalg.norm(bs.B(), axis=-1)) - surface_area = s.area() - bnormalization = B0avg * surface_area print("Bmag at R = ", R0, ", Z = 0: ", B0) print("toroidally averaged Bmag at R = ", R0, ", Z = 0: ", B0avg) return B0avg @@ -472,12 +470,11 @@ def animate(frame_number): plt.xlabel('Normalized magnitudes') plt.ylabel('Number of dipoles') - ani = animation.FuncAnimation( + animation.FuncAnimation( fig, prepare_animation(bar_container), range(0, m_history.shape[0], 2), repeat=False, blit=True ) - # ani.save(out_dir / 'm_history' + str(i) + '.mp4') def run_Poincare_plots(s_plot, bs, b_dipole, comm, filename_poincare, out_dir=''): @@ -493,7 +490,7 @@ def run_Poincare_plots(s_plot, bs, b_dipole, comm, filename_poincare, out_dir='' out_dir: Path or string for the output directory for saved files. """ from simsopt.field.magneticfieldclasses import InterpolatedField - from simsopt.objectives import SquaredFlux + # from simsopt.objectives import SquaredFlux out_dir = Path(out_dir) @@ -505,13 +502,13 @@ def run_Poincare_plots(s_plot, bs, b_dipole, comm, filename_poincare, out_dir='' phirange = (0, 2 * np.pi / s_plot.nfp, n * 2) zrange = (0, np.max(zs), n // 2) degree = 4 # 2 is sufficient sometimes - nphi = len(s_plot.quadpoints_phi) - ntheta = len(s_plot.quadpoints_theta) + # nphi = len(s_plot.quadpoints_phi) + # ntheta = len(s_plot.quadpoints_theta) bs.set_points(s_plot.gamma().reshape((-1, 3))) b_dipole.set_points(s_plot.gamma().reshape((-1, 3))) - Bnormal = np.sum(bs.B().reshape((nphi, ntheta, 3)) * s_plot.unitnormal(), axis=2) - Bnormal_dipole = np.sum(b_dipole.B().reshape((nphi, ntheta, 3)) * s_plot.unitnormal(), axis=2) - f_B = SquaredFlux(s_plot, b_dipole, -Bnormal).J() + # Bnormal = np.sum(bs.B().reshape((nphi, ntheta, 3)) * s_plot.unitnormal(), axis=2) + # Bnormal_dipole = np.sum(b_dipole.B().reshape((nphi, ntheta, 3)) * s_plot.unitnormal(), axis=2) + # f_B = SquaredFlux(s_plot, b_dipole, -Bnormal).J() make_Bnormal_plots(bs, s_plot, out_dir, "biot_savart_pre_poincare_check") make_Bnormal_plots(b_dipole, s_plot, out_dir, "dipole_pre_poincare_check") make_Bnormal_plots(bs + b_dipole, s_plot, out_dir, "total_pre_poincare_check") diff --git a/src/simsopt/util/polarization_project.py b/src/simsopt/util/polarization_project.py index 20225fb0d..c7a90f154 100644 --- a/src/simsopt/util/polarization_project.py +++ b/src/simsopt/util/polarization_project.py @@ -373,7 +373,6 @@ def polarization_axes(polarizations): pol_axes = np.zeros((0, 3)) pol_type = np.zeros(0, dtype=int) - first_row = 0 i = 0 if not isinstance(polarizations, list): polarizations = [polarizations] diff --git a/tests/core/test_derivative.py b/tests/core/test_derivative.py index 00bb79c61..f14d7128a 100644 --- a/tests/core/test_derivative.py +++ b/tests/core/test_derivative.py @@ -91,14 +91,12 @@ def taylor_test(obj): obj.x = x x = obj.x h = np.random.standard_normal(size=x.shape) - f = obj.J() df = obj.dJ() dfh = np.sum(df * h) err_old = 1e9 for i in range(5, 11): eps = 0.5**i obj.x = x + 3 * eps * h - fppp = obj.J() obj.x = x + 2 * eps * h fpp = obj.J() obj.x = x + eps * h @@ -108,7 +106,6 @@ def taylor_test(obj): obj.x = x - 2 * eps * h fmm = obj.J() obj.x = x - 3 * eps * h - fmmm = obj.J() # print(np.abs((fp-fm)/(2*eps) - dfh)) dfhest = ((1/12) * fmm - (2/3) * fm + (2/3) * fp - (1/12) * fpp)/eps err = np.abs(dfhest - dfh) @@ -116,11 +113,6 @@ def taylor_test(obj): print(err_old/err) err_old = err - # dfhest = ((-1/60)*fmmm + (3/20)*fmm -(3/4)*fm+(3/4)*fp-(3/20)*fpp + (1/60)*fppp)/eps - # err = np.abs(dfhest - dfh) - # print(err_old/err) - # err_old = err - class DerivativeTests(unittest.TestCase): diff --git a/tests/core/test_dev.py b/tests/core/test_dev.py index 95072266f..0a02ab75e 100644 --- a/tests/core/test_dev.py +++ b/tests/core/test_dev.py @@ -5,7 +5,7 @@ except ImportError: np = None -from simsopt._core.dev import SimsoptRequires, deprecated +from simsopt._core.dev import SimsoptRequires from simsopt._core.optimizable import Optimizable diff --git a/tests/core/test_integrated.py b/tests/core/test_integrated.py index fe7b1d702..d1ad153d4 100755 --- a/tests/core/test_integrated.py +++ b/tests/core/test_integrated.py @@ -1,5 +1,4 @@ import unittest -import logging import numpy as np from monty.tempfile import ScratchDir diff --git a/tests/core/test_json.py b/tests/core/test_json.py index 2fe15f701..06c7d58de 100644 --- a/tests/core/test_json.py +++ b/tests/core/test_json.py @@ -435,7 +435,7 @@ def test_numpy(self): x = {"energies": [np.float64(1234.5)]} d = jsanitize(x, strict=True) - assert type(d["energies"][0]) == float + assert isinstance(d["energies"][0], float) # Test data nested in a class x = np.array([[1 + 1j, 2 + 1j], [3 + 1j, 4 + 1j]], dtype="complex64") diff --git a/tests/core/test_optimizable.py b/tests/core/test_optimizable.py index cf9169950..2dc08b5f3 100755 --- a/tests/core/test_optimizable.py +++ b/tests/core/test_optimizable.py @@ -2,14 +2,26 @@ import re import json +try: + import matplotlib +except ImportError: + matplotlib = None +try: + import networkx +except ImportError: + networkx = None +try: + import pygraphviz +except ImportError: + pygraphviz = None + import numpy as np from simsopt._core.json import GSONDecoder, GSONEncoder, SIMSON -from monty.serialization import loadfn, dumpfn from simsopt._core.optimizable import Optimizable, make_optimizable, \ ScaledOptimizable, OptimizableSum, load, save from simsopt.objectives.functions import Identity, Rosenbrock, TestObject1, \ - TestObject2, Beale + Beale from simsopt.objectives.functions import Adder as FAdder @@ -1115,6 +1127,8 @@ def test_get_ancestors(self): ancestors = test_obj2._get_ancestors() self.assertEqual(len(ancestors), 4) + @unittest.skipIf(matplotlib is None or pygraphviz is None or networkx is None, + "Plotting libraries are missing") def test_plot(self): """ Verify that a DAG can be plotted. @@ -1126,19 +1140,6 @@ def test_plot(self): """ show = False - try: - import matplotlib - except ImportError: - return - try: - import networkx - except ImportError: - return - try: - import pygraphviz - except ImportError: - return - # optimizable with no parents adder = Adder(n=3, x0=[1.0, 2.0, 3.0]) G1, pos1 = adder.plot_graph(show=show) @@ -1392,17 +1393,17 @@ def test_adder_dofs_shared_fix_unfix(self): self.assertEqual(adder_orig.J(), adder_shared_dofs.J()) adder_orig.fix("x") - with self.assertRaises(ValueError) as context: + with self.assertRaises(ValueError): adder_shared_dofs.x = [11, 12] adder_shared_dofs.x = [11] adder_orig.unfix("z") - with self.assertRaises(ValueError) as context: + with self.assertRaises(ValueError): adder_shared_dofs.x = [11] adder_shared_dofs.x = [11, 12] adder_shared_dofs.unfix_all() - with self.assertRaises(ValueError) as context: + with self.assertRaises(ValueError): adder_shared_dofs.x = [11, 12] adder_orig.x = [11, 12, 13] diff --git a/tests/core/test_util.py b/tests/core/test_util.py index f9e702d79..4f29ab370 100755 --- a/tests/core/test_util.py +++ b/tests/core/test_util.py @@ -3,7 +3,7 @@ import numpy as np from simsopt._core.util import isnumber, isbool, unique, \ - ObjectiveFailure, finite_difference_steps, nested_lists_to_array + finite_difference_steps, nested_lists_to_array class IsboolTests(unittest.TestCase): diff --git a/tests/field/test_boozermagneticfields.py b/tests/field/test_boozermagneticfields.py index d4f24f21a..ffaa981bc 100644 --- a/tests/field/test_boozermagneticfields.py +++ b/tests/field/test_boozermagneticfields.py @@ -10,12 +10,12 @@ try: import vmec -except ImportError as e: +except ImportError: vmec = None try: from mpi4py import MPI -except ImportError as e: +except ImportError: MPI = None if (MPI is not None) and (vmec is not None): @@ -27,7 +27,6 @@ class TestingAnalytic(unittest.TestCase): def test_boozeranalytic(self): etabar = 1.1 B0 = 1.0 - Bbar = 1.0 N = 0 G0 = 1.1 psi0 = 0.8 @@ -132,8 +131,6 @@ def test_boozerradialinterpolant_finite_beta(self): thetas = np.linspace(0, 2*np.pi, ntheta, endpoint=False) zetas = np.linspace(0, 2*np.pi/vmec_sym.wout.nfp, nzeta, endpoint=False) - dtheta = thetas[1]-thetas[0] - dzeta = zetas[1]-zetas[0] thetas, zetas = np.meshgrid(thetas, zetas) thetas_flat = thetas.flatten() zetas_flat = zetas.flatten() @@ -369,18 +366,18 @@ def test_boozerradialinterpolant_vacuum(self): # zmns/zmnc on full grid # lmnc/lmns on half grid - zmns_full = vmec.wout.zmns[:, 1:] + # zmns_full = vmec.wout.zmns[:, 1:] zmns_half = 0.5*(vmec.wout.zmns[:, 0:-1] + vmec.wout.zmns[:, 1::]) - lmns_full = 0.5*(vmec.wout.lmns[:, 1:-1] + vmec.wout.lmns[:, 2::]) + # lmns_full = 0.5*(vmec.wout.lmns[:, 1:-1] + vmec.wout.lmns[:, 2::]) lmns_half = vmec.wout.lmns[:, 1::] if not bri.stellsym: - lmnc_full = 0.5*(vmec.wout.lmnc[:, 1:-1] + vmec.wout.lmnc[:, 2::]) + # lmnc_full = 0.5*(vmec.wout.lmnc[:, 1:-1] + vmec.wout.lmnc[:, 2::]) lmnc_half = vmec.wout.lmnc[:, 1::] - zmnc_full = vmec.wout.zmnc[:, 1:-1] + # zmnc_full = vmec.wout.zmnc[:, 1:-1] zmnc_half = 0.5*(vmec.wout.zmnc[:, 0:-1] + vmec.wout.zmnc[:, 1::]) else: - lmnc_full = np.zeros_like(lmns_full) - zmnc_full = np.zeros_like(zmns_full) + # lmnc_full = np.zeros_like(lmns_full) + # zmnc_full = np.zeros_like(zmns_full) lmnc_half = np.zeros_like(lmns_half) zmnc_half = np.zeros_like(zmns_half) @@ -607,7 +604,6 @@ def test_interpolatedboozerfield_no_sym(self): order = 3 bri = BoozerRadialInterpolant(vmec, order, mpol=5, ntor=5, rescale=True) - nfp = vmec.wout.nfp n = 12 smin = 0.4 smax = 0.6 @@ -648,11 +644,11 @@ def test_interpolatedboozerfield_no_sym(self): modB = bri.modB() R = bri.R() dRdtheta = bri.dRdtheta() - dRdzeta = bri.dRdzeta() + # dRdzeta = bri.dRdzeta() dRds = bri.dRds() Z = bri.Z() dZdtheta = bri.dZdtheta() - dZdzeta = bri.dZdzeta() + # dZdzeta = bri.dZdzeta() dZds = bri.dZds() dmodBds = bri.dmodBds() dmodBdtheta = bri.dmodBdtheta() @@ -675,11 +671,11 @@ def test_interpolatedboozerfield_no_sym(self): modBh = bsh.modB() Rh = bsh.R() dRdthetah = bsh.dRdtheta() - dRdzetah = bsh.dRdzeta() + # dRdzetah = bsh.dRdzeta() dRdsh = bsh.dRds() Zh = bsh.Z() dZdthetah = bsh.dZdtheta() - dZdzetah = bsh.dZdzeta() + # dZdzetah = bsh.dZdzeta() dZdsh = bsh.dZds() nuh = bsh.nu() dnudthetah = bsh.dnudtheta() diff --git a/tests/field/test_coil.py b/tests/field/test_coil.py index de0befb1f..0b1125b34 100644 --- a/tests/field/test_coil.py +++ b/tests/field/test_coil.py @@ -1,6 +1,5 @@ import unittest import json -import os import numpy as np from monty.tempfile import ScratchDir diff --git a/tests/field/test_fieldline.py b/tests/field/test_fieldline.py index 5958f6c21..1ebcfb09f 100644 --- a/tests/field/test_fieldline.py +++ b/tests/field/test_fieldline.py @@ -9,15 +9,13 @@ from simsopt.field.coil import coils_via_symmetries, Coil, Current from simsopt.geo.curvehelical import CurveHelical from simsopt.geo.curvexyzfourier import CurveXYZFourier -import simsoptpp as sopp logging.basicConfig() try: import pyevtk - with_evtk = True except ImportError: - with_evtk = False + pyevtk = None def validate_phi_hits(phi_hits, nphis): @@ -53,7 +51,7 @@ def test_poincare_toroidal(self): assert np.allclose(res_tys[i][:, 3], 0.) assert np.allclose(np.linalg.norm(res_tys[i][:, 1:3], axis=1), R0[i]) assert validate_phi_hits(res_phi_hits[i], nphis) - if with_evtk: + if pyevtk is not None: particles_to_vtk(res_tys, '/tmp/fieldlines') def test_poincare_tokamak(self): diff --git a/tests/field/test_magneticfields.py b/tests/field/test_magneticfields.py index 51ab1d9b4..e3466c9a5 100644 --- a/tests/field/test_magneticfields.py +++ b/tests/field/test_magneticfields.py @@ -27,7 +27,6 @@ from simsopt.geo import (CurveHelical, CurveRZFourier, CurveXYZFourier, PermanentMagnetGrid, SurfaceRZFourier, create_equally_spaced_curves) -from simsopt.solve import relax_and_split from simsoptpp import dipole_field_Bn TEST_DIR = (Path(__file__).parent / ".." / "test_files").resolve() @@ -157,11 +156,8 @@ def test_scalarpotential_Bfield(self): # Convert to Cartesian coordinates r = np.sqrt(np.power(points[:, 0], 2) + np.power(points[:, 1], 2)) phi = np.arctan2(points[:, 1], points[:, 0]) - z = points[:, 2] B2_cart = np.zeros_like(B2) - # Bx = Br cos(phi) - Bphi sin(phi) B2_cart[:, 0] = B2[:, 0] * np.cos(phi) - B2[:, 1] * np.sin(phi) - # By = Br sin(phi) + Bphi cos(phi) B2_cart[:, 1] = B2[:, 0] * np.sin(phi) + B2[:, 1] * np.cos(phi) B2_cart[:, 2] = B2[:, 2] dB2_by_dX = np.array([ @@ -718,7 +714,7 @@ def test_pmopt_dipoles(self): # check B_opt = np.mean(np.abs(pm_opt.A_obj.dot(dipoles) - pm_opt.b_obj) * np.sqrt(Ngrid / Nnorms)) B_dipole_field = np.mean(np.abs(np.sum((bs.B() + b_dipole.B()).reshape((nphi, ntheta, 3)) * s.unitnormal(), axis=2))) - Bn_dipole_only = np.sum(b_dipole.B().reshape(-1, 3) * s.unitnormal().reshape(-1, 3), axis=1) + # Bn_dipole_only = np.sum(b_dipole.B().reshape(-1, 3) * s.unitnormal().reshape(-1, 3), axis=1) assert np.isclose(B_opt, B_dipole_field) A_dipole = dipole_field_Bn(s.gamma().reshape(-1, 3), pm_opt.dipole_grid_xyz, diff --git a/tests/field/test_mpi_tracing.py b/tests/field/test_mpi_tracing.py index 4b6a1163b..b94248202 100644 --- a/tests/field/test_mpi_tracing.py +++ b/tests/field/test_mpi_tracing.py @@ -15,7 +15,6 @@ from simsopt.field.tracing import trace_particles_starting_on_curve, compute_fieldlines from simsopt.field.magneticfieldclasses import InterpolatedField, UniformInterpolationRule from simsopt.util.constants import PROTON_MASS, ELEMENTARY_CHARGE, ONE_EV -import simsoptpp as sopp class MPITracingTesting(unittest.TestCase): diff --git a/tests/field/test_normal_field.py b/tests/field/test_normal_field.py index 671392ba0..ea639b563 100644 --- a/tests/field/test_normal_field.py +++ b/tests/field/test_normal_field.py @@ -9,7 +9,7 @@ try: import py_spec -except ImportError as e: +except ImportError: py_spec = None from . import TEST_DIR diff --git a/tests/field/test_particle.py b/tests/field/test_particle.py index 63ec9b5a2..d335d5a3e 100644 --- a/tests/field/test_particle.py +++ b/tests/field/test_particle.py @@ -19,26 +19,18 @@ from simsopt.field.magneticfieldclasses import InterpolatedField, UniformInterpolationRule, ToroidalField, PoloidalField from simsopt.util.constants import PROTON_MASS, ELEMENTARY_CHARGE, ONE_EV from simsopt.geo.curverzfourier import CurveRZFourier -import simsoptpp as sopp try: import pyevtk - with_evtk = True except ImportError: - with_evtk = False + pevtk = None try: from mpi4py import MPI except: MPI = None -try: - from simsopt.mhd.vmec import Vmec - vmec_found = True -except ImportError: - vmec_found = False - def validate_phi_hits(phi_hits, bfield, nphis): """ @@ -96,7 +88,7 @@ def __init__(self, *args, **kwargs): bs.set_points(np.asarray([[0., 0., 0.]])).GradAbsB() self.bsh = bsh self.ma = ma - if with_evtk: + if pyevtk is not None: bsh.to_vtk('/tmp/bfield') def test_guidingcenter_vs_fullorbit(self): @@ -124,7 +116,7 @@ def test_guidingcenter_vs_fullorbit(self): ma, bsh, nparticles, tmax=tmax, seed=1, mass=m, charge=q, Ekin=Ekin, umin=umin, umax=umax, phis=[], mode='full') - if with_evtk: + if pyevtk is not None: particles_to_vtk(gc_tys, '/tmp/particles_gc') particles_to_vtk(fo_tys, '/tmp/particles_fo') @@ -168,7 +160,7 @@ def test_guidingcenterphihits(self): quadpoints_theta=np.linspace(0, 1, 2*mpol+1, endpoint=False)) s.fit_to_curve(ma, 0.10, flip_theta=False) sc = SurfaceClassifier(s, h=0.1, p=2) - if with_evtk: + if pyevtk is not None: sc.to_vtk('/tmp/classifier') # check that the axis is classified as inside the domain assert sc.evaluate_xyz(ma.gamma()[:1, :]) > 0 @@ -233,7 +225,7 @@ def test_energy_conservation(self): ma, bsh, nparticles, tmax=tmax, seed=1, mass=m, charge=q, Ekin=Ekin, umin=-0.5, umax=-0.25, phis=[], mode='full', tol=1e-11) - if with_evtk: + if pyevtk is not None: particles_to_vtk(gc_tys, '/tmp/particles_gc') particles_to_vtk(fo_tys, '/tmp/particles_fo') @@ -312,7 +304,7 @@ def test_angularmomentum_conservation(self): ma, bsh, nparticles, tmax=tmax, seed=1, mass=m, charge=q, Ekin=Ekin, umin=-0.5, umax=-0.25, # pitch angle so that we have both par and perp contribution phis=[], mode='gc_vac', tol=1e-11) - if with_evtk: + if pyevtk is not None: particles_to_vtk(gc_tys, '/tmp/particles_gc') # pick 100 random points on each trace @@ -382,7 +374,7 @@ def test_stopping_criteria(self): ma, bsh, nparticles, tmax=tmax, seed=1, mass=m, charge=q, Ekin=Ekin, umin=-0.01, umax=+0.01, phis=[], mode='gc_vac', tol=1e-11, stopping_criteria=[LevelsetStoppingCriterion(sc)]) - if with_evtk: + if pyevtk is not None: particles_to_vtk(gc_tys, '/tmp/particles_gc') assert gc_phi_hits[0][-1][1] == -1 assert np.all(sc.evaluate_xyz(gc_tys[0][:, 1:4]) > 0) @@ -425,7 +417,6 @@ def test_energy_momentum_conservation_boozer(self): # First, test energy and momentum conservation in a QA vacuum field etabar = 1.2 B0 = 1.0 - Bbar = 1.0 G0 = 1.1 psi0 = 0.8 iota0 = 0.4 @@ -483,7 +474,6 @@ def test_energy_momentum_conservation_boozer(self): energy_gc = np.array([]) mu_gc = np.array([]) p_gc = np.array([]) - vParInitial = gc_ty[0, 4] muInitial = mu_inits[i] pInitial = p_inits[i] for j in range(N): @@ -545,7 +535,6 @@ def test_energy_momentum_conservation_boozer(self): energy_gc = np.array([]) mu_gc = np.array([]) p_gc = np.array([]) - vParInitial = gc_ty[0, 4] muInitial = mu_inits[i] pInitial = p_inits[i] for j in range(N): @@ -598,7 +587,6 @@ def test_energy_momentum_conservation_boozer(self): energy_gc = np.array([]) mu_gc = np.array([]) p_gc = np.array([]) - vParInitial = gc_ty[0, 4] muInitial = mu_inits[i] pInitial = p_inits[i] for j in range(N): @@ -638,7 +626,6 @@ def test_compute_poloidal_toroidal_transits(self): # First test for BoozerAnalytic field etabar = 1.2 B0 = 1.0 - Bbar = 1.0 G0 = 1.1 psi0 = 0.8 iota0 = 1.0 @@ -712,7 +699,6 @@ def test_toroidal_flux_stopping_criterion(self): """ etabar = 1.2 B0 = 1.0 - Bbar = 1.0 G0 = 1.1 psi0 = 0.8 iota0 = 1.0 @@ -756,7 +742,6 @@ def test_compute_resonances(self): """ etabar = 1.2 B0 = 1.0 - Bbar = 1.0 R0 = 1.0 G0 = R0*B0 psi0 = B0*(0.1)**2/2 diff --git a/tests/geo/surface_test_helpers.py b/tests/geo/surface_test_helpers.py index 1189135df..6effa0e37 100644 --- a/tests/geo/surface_test_helpers.py +++ b/tests/geo/surface_test_helpers.py @@ -3,7 +3,7 @@ import numpy as np from simsopt.configs import get_ncsx_data from simsopt.field import coils_via_symmetries, BiotSavart -from simsopt.geo import Volume, Area, ToroidalFlux, SurfaceXYZFourier, SurfaceRZFourier, SurfaceXYZTensorFourier, BoozerSurface, MajorRadius +from simsopt.geo import Volume, Area, ToroidalFlux, SurfaceXYZFourier, SurfaceRZFourier, SurfaceXYZTensorFourier, BoozerSurface TEST_DIR = Path(__file__).parent / ".." / "test_files" diff --git a/tests/geo/test_curve.py b/tests/geo/test_curve.py index 5bd49ddc1..ab92b5175 100644 --- a/tests/geo/test_curve.py +++ b/tests/geo/test_curve.py @@ -19,9 +19,8 @@ try: import pyevtk - pyevtk_found = True except ImportError: - pyevtk_found = False + pyevtk = None logger = logging.getLogger(__name__) #logging.basicConfig(level=logging.INFO) @@ -386,7 +385,7 @@ def test_curve_dkappa_by_dphi_derivative(self): with self.subTest(curvetype=curvetype, rotated=rotated): self.subtest_curve_dkappa_by_dphi_derivative(curvetype, rotated) - @unittest.skipIf(not pyevtk_found, "pyevtk not found") + @unittest.skipIf(pyevtk is None, "pyevtk not found") def test_curve_to_vtk(self): curve0 = get_curve(self.curvetypes[0], False) curve1 = get_curve(self.curvetypes[1], True) diff --git a/tests/geo/test_curve_objectives.py b/tests/geo/test_curve_objectives.py index 58035faf8..4fb6c281d 100644 --- a/tests/geo/test_curve_objectives.py +++ b/tests/geo/test_curve_objectives.py @@ -4,7 +4,7 @@ import numpy as np from simsopt.geo import parameters -from simsopt.geo.curve import RotatedCurve, curves_to_vtk, create_equally_spaced_curves +from simsopt.geo.curve import RotatedCurve, create_equally_spaced_curves from simsopt.geo.curvexyzfourier import CurveXYZFourier, JaxCurveXYZFourier from simsopt.geo.curverzfourier import CurveRZFourier from simsopt.geo.curveobjectives import CurveLength, LpCurveCurvature, \ @@ -314,7 +314,6 @@ def test_minimum_distance_candidates_symmetry(self): ) def test_curve_surface_distance(self): - from scipy.spatial.distance import cdist np.random.seed(0) base_curves, base_currents, _ = get_ncsx_data(Nt_coils=10) curves = [c.curve for c in coils_via_symmetries(base_curves, base_currents, 3, True)] @@ -382,8 +381,6 @@ def test_linking_number(self): fullArray = Object1.J() fullArray2 = Object2.J() - deriv1 = Object1.dJ() - deriv2 = Object2.dJ() print("Link Number Testing (should be 0, 1)") print(fullArray) print(fullArray2) diff --git a/tests/geo/test_curve_optimizable.py b/tests/geo/test_curve_optimizable.py index 5fccfed4f..fc8eb4606 100644 --- a/tests/geo/test_curve_optimizable.py +++ b/tests/geo/test_curve_optimizable.py @@ -3,7 +3,6 @@ from monty.tempfile import ScratchDir -from simsopt.geo.curvexyzfourier import CurveXYZFourier, JaxCurveXYZFourier from simsopt.geo.curverzfourier import CurveRZFourier from simsopt.geo.curve import RotatedCurve from simsopt.geo import parameters diff --git a/tests/geo/test_finitebuild.py b/tests/geo/test_finitebuild.py index d1a90ff14..fe890fa29 100644 --- a/tests/geo/test_finitebuild.py +++ b/tests/geo/test_finitebuild.py @@ -1,11 +1,10 @@ import unittest -from .surface_test_helpers import get_surface, get_exact_surface +from .surface_test_helpers import get_surface from simsopt.field.biotsavart import BiotSavart from simsopt.field.coil import Coil, apply_symmetries_to_curves, apply_symmetries_to_currents from simsopt.geo.curveobjectives import CurveLength, CurveCurveDistance from simsopt.geo import CurveFilament, FrameRotation, \ create_multifilament_grid, ZeroRotation, FramedCurveCentroid, FramedCurveFrenet -from simsopt.geo.qfmsurface import QfmSurface from simsopt.objectives.fluxobjective import SquaredFlux from simsopt.objectives.utilities import QuadraticPenalty from simsopt.configs.zoo import get_ncsx_data diff --git a/tests/geo/test_pm_grid.py b/tests/geo/test_pm_grid.py index a680c5849..0a847f64b 100644 --- a/tests/geo/test_pm_grid.py +++ b/tests/geo/test_pm_grid.py @@ -3,15 +3,12 @@ import numpy as np from monty.tempfile import ScratchDir -import simsoptpp as sopp -from simsopt.field import (BiotSavart, Current, DipoleField, InterpolatedField, - coils_via_symmetries, Coil) +from simsopt.field import (BiotSavart, Current, DipoleField, coils_via_symmetries, Coil) from simsopt.geo import (PermanentMagnetGrid, SurfaceRZFourier, SurfaceXYZFourier, create_equally_spaced_curves) from simsopt.objectives import SquaredFlux from simsopt.solve import GPMO, relax_and_split -from pyevtk.hl import pointsToVTK from simsopt.util import * from simsopt.util.polarization_project import (faceedge_vectors, facecorner_vectors, pol_e, pol_f, pol_fe, pol_c, @@ -19,7 +16,6 @@ pol_ec23, pol_fe17, pol_fe23, pol_fe30) -#from . import TEST_DIR TEST_DIR = (Path(__file__).parent / ".." / "test_files").resolve() # File for the desired boundary magnetic surface: diff --git a/tests/geo/test_qfm.py b/tests/geo/test_qfm.py index b8fc78c7d..04dd65000 100644 --- a/tests/geo/test_qfm.py +++ b/tests/geo/test_qfm.py @@ -227,7 +227,6 @@ def subtest_qfm_surface_optimization_convergence(self, surfacetype, c.rotmatT = c.rotmat.T.copy() coils = coils_via_symmetries(curves + curves_flipped, currents + currents_flipped, nfp, False) bs = BiotSavart(coils) - bs_tf = BiotSavart(coils) phis = np.linspace(0, 1/nfp, 20, endpoint=False) thetas = np.linspace(0, 1, 20, endpoint=False) @@ -339,7 +338,6 @@ def subtest_minimize_qfm(self, surfacetype, stellsym): coils = coils_via_symmetries(curves + curves_flipped, currents + currents_flipped, nfp, False) bs = BiotSavart(coils) - bs_tf = BiotSavart(coils) phis = np.linspace(0, 1/nfp, 20, endpoint=False) thetas = np.linspace(0, 1, 20, endpoint=False) diff --git a/tests/geo/test_strainopt.py b/tests/geo/test_strainopt.py index 4735c1b29..428c59c4f 100644 --- a/tests/geo/test_strainopt.py +++ b/tests/geo/test_strainopt.py @@ -23,7 +23,6 @@ def test_strain_opt(self): curve.fix_all() order = 2 np.random.seed(1) - dofs = np.random.standard_normal(size=(2*order+1,)) rotation = FrameRotation(quadpoints, order) rotation.x = np.random.standard_normal(size=(2*order+1,)) if centroid: @@ -38,7 +37,7 @@ def fun(dofs): J.x = dofs grad = J.dJ() return J.J(), grad - res = minimize(fun, J.x, jac=True, method='L-BFGS-B', + minimize(fun, J.x, jac=True, method='L-BFGS-B', options={'maxiter': 100, 'maxcor': 10, 'gtol': 1e-20, 'ftol': 1e-20}, tol=1e-20) assert Jt.J() < 1e-12 assert Jb.J() < 1e-12 diff --git a/tests/geo/test_surface.py b/tests/geo/test_surface.py index 1c34244ad..898d0ebd5 100755 --- a/tests/geo/test_surface.py +++ b/tests/geo/test_surface.py @@ -22,12 +22,6 @@ stellsym_list = [True, False] -try: - import pyevtk - pyevtk_found = True -except ImportError: - pyevtk_found = False - surface_types = ["SurfaceRZFourier", "SurfaceXYZFourier", "SurfaceXYZTensorFourier", "SurfaceHenneberg", "SurfaceGarabedian"] @@ -300,7 +294,7 @@ def test_serialization(self): scale_factors = np.random.random_sample(dof_size) scaled_s = SurfaceScaled(s, scale_factors) scaled_s_str = json.dumps(SIMSON(scaled_s), cls=GSONEncoder) - regen_s = json.loads(scaled_s_str, cls=GSONDecoder) + json.loads(scaled_s_str, cls=GSONDecoder) class BestNphiOverNthetaTests(unittest.TestCase): diff --git a/tests/geo/test_surface_garabedian.py b/tests/geo/test_surface_garabedian.py index 14e98fa72..7e61ab49d 100755 --- a/tests/geo/test_surface_garabedian.py +++ b/tests/geo/test_surface_garabedian.py @@ -11,11 +11,6 @@ stellsym_list = [True, False] -try: - import pyevtk - pyevtk_found = True -except ImportError: - pyevtk_found = False #logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) diff --git a/tests/geo/test_surface_objectives.py b/tests/geo/test_surface_objectives.py index 0f7d82db6..759d3ccaf 100644 --- a/tests/geo/test_surface_objectives.py +++ b/tests/geo/test_surface_objectives.py @@ -14,7 +14,7 @@ def taylor_test1(f, df, x, epsilons=None, direction=None): np.random.seed(1) - f0 = f(x) + f(x) if direction is None: direction = np.random.rand(*(x.shape))-0.5 dfx = df(x)@direction @@ -40,7 +40,7 @@ def taylor_test2(f, df, d2f, x, epsilons=None, direction1=None, direction2=None) if direction2 is None: direction2 = np.random.rand(*(x.shape))-0.5 - f0 = f(x) + f(x) df0 = df(x) @ direction1 d2fval = direction2.T @ d2f(x) @ direction1 if epsilons is None: diff --git a/tests/geo/test_surface_rzfourier.py b/tests/geo/test_surface_rzfourier.py index e568cd518..976f4cfaf 100755 --- a/tests/geo/test_surface_rzfourier.py +++ b/tests/geo/test_surface_rzfourier.py @@ -1,6 +1,5 @@ import unittest from pathlib import Path -import json from qsc import Qsc import numpy as np @@ -15,12 +14,6 @@ stellsym_list = [True, False] -try: - import pyevtk - pyevtk_found = True -except ImportError: - pyevtk_found = False - class SurfaceRZFourierTests(unittest.TestCase): @@ -75,19 +68,6 @@ def test_shared_dof_init(self): self.assertAlmostEqual(s2.area(), true_area, places=4) self.assertAlmostEqual(s2.volume(), true_volume, places=3) - def test_area_volume(self): - """ - Test the calculation of area and volume for an axisymmetric surface - """ - s = SurfaceRZFourier() - s.rc[0, 0] = 1.3 - s.rc[1, 0] = 0.4 - s.zs[1, 0] = 0.2 - - true_area = 15.827322032265993 - true_volume = 2.0528777154265874 - self.assertAlmostEqual(s.area(), true_area, places=4) - self.assertAlmostEqual(s.volume(), true_volume, places=3) def test_get_dofs(self): """ @@ -726,10 +706,8 @@ def test_convert_back(self): filename = TEST_DIR / 'input.li383_low_res' s1 = SurfaceRZFourier.from_vmec_input(filename) #print('Original SurfaceRZFourier dofs:', s1.x) - x1 = s1.x s2 = SurfaceRZPseudospectral.from_RZFourier(s1, r_shift=2.2, a_scale=0.4) s3 = s2.to_RZFourier() - x3 = s3.x #for j, name in enumerate(s1.local_dof_names): # print(name, x1[j], x3[j], x1[j] - x3[j]) np.testing.assert_allclose(s1.full_x, s3.full_x) diff --git a/tests/geo/test_surface_taylor.py b/tests/geo/test_surface_taylor.py index 7b64ed0f7..bd3f968e4 100644 --- a/tests/geo/test_surface_taylor.py +++ b/tests/geo/test_surface_taylor.py @@ -10,7 +10,6 @@ def taylor_test(f, df, x, epsilons=None, direction=None, order=2): np.random.seed(1) - f0 = f(x) if direction is None: direction = np.random.rand(*(x.shape))-0.5 dfx = df(x)@direction @@ -25,12 +24,10 @@ def taylor_test(f, df, x, epsilons=None, direction=None, order=2): fpluseps = f(x + eps * direction) fminuseps = f(x - eps * direction) if order == 2: - fak = 0.3 dfest = (fpluseps-fminuseps)/(2*eps) elif order == 4: fplus2eps = f(x + 2*eps * direction) fminus2eps = f(x - 2*eps * direction) - fak = 0.13 dfest = ((1/12) * fminus2eps - (2/3) * fminuseps + (2/3)*fpluseps - (1/12)*fplus2eps)/eps else: @@ -97,7 +94,6 @@ def taylor_test2(f, df, d2f, x, epsilons=None, direction1=None, if direction2 is None: direction2 = np.random.rand(*(x.shape))-0.5 - f0 = f(x) df0 = df(x) @ direction1 d2fval = direction2.T @ d2f(x) @ direction1 if epsilons is None: diff --git a/tests/geo/test_surface_xyzfourier.py b/tests/geo/test_surface_xyzfourier.py index a6651bfbf..8be7f5ff5 100755 --- a/tests/geo/test_surface_xyzfourier.py +++ b/tests/geo/test_surface_xyzfourier.py @@ -1,22 +1,19 @@ import unittest -import json import tempfile import os import numpy as np -from simsopt.geo import Surface, SurfaceXYZFourier, SurfaceXYZTensorFourier +from simsopt.geo import Surface, SurfaceXYZFourier from .surface_test_helpers import get_surface, get_exact_surface -from simsopt._core.json import GSONDecoder, GSONEncoder, SIMSON from simsopt._core.optimizable import load, save stellsym_list = [True, False] try: import pyevtk - pyevtk_found = True except ImportError: - pyevtk_found = False + pyevtk = None class SurfaceXYZFourierTests(unittest.TestCase): @@ -211,7 +208,7 @@ def test_cross_section_torus(self): R = np.sqrt(cs[i, :, 0]**2 + cs[i, :, 1]**2) Z = cs[i, :, 2] Rp = fftpack.diff(R, period=1.) - Zp = fftpack.diff(Z, period=1.) + fftpack.diff(Z, period=1.) cs_area[i] = np.abs(np.mean(Z*Rp)) exact_area = np.pi * minor_R**2. @@ -270,7 +267,7 @@ class by comparing with an approximation based on cross section R = np.sqrt(cs[:, 0]**2 + cs[:, 1]**2) Z = cs[:, 2] Rp = fftpack.diff(R, period=1.) - Zp = fftpack.diff(Z, period=1.) + fftpack.diff(Z, period=1.) ar = np.mean(Z*Rp) cs_area[idx] = ar @@ -285,7 +282,7 @@ class by comparing with an approximation based on cross section print("AR rel error is:", rel_err) assert rel_err < 1e-5 - @unittest.skipIf(not pyevtk_found, "pyevtk not found") + @unittest.skipIf(pyevtk is None, "pyevtk not found") def test_to_vtk(self): mpol = 4 ntor = 3 diff --git a/tests/geo/test_surfacehenneberg.py b/tests/geo/test_surfacehenneberg.py index 8d479cdc4..4d860d543 100755 --- a/tests/geo/test_surfacehenneberg.py +++ b/tests/geo/test_surfacehenneberg.py @@ -19,11 +19,10 @@ try: import vmec - vmec_found = True except ImportError: - vmec_found = False + vmec = None -if (MPI is not None) and vmec_found: +if (MPI is not None) and vmec is not None: from simsopt.mhd.vmec import Vmec else: Vmec = None @@ -102,12 +101,6 @@ def test_fixed_range(self): """ surf = SurfaceHenneberg(nfp=1, alpha_fac=1, mmax=2, nmax=1) # Order of elements: - names_correct = ['R0nH(0)', 'R0nH(1)', - 'Z0nH(1)', - 'bn(0)', 'bn(1)', - 'rhomn(0,1)', - 'rhomn(1,-1)', 'rhomn(1,0)', 'rhomn(1,1)', - 'rhomn(2,-1)', 'rhomn(2,0)', 'rhomn(2,1)'] surf.fixed_range(20, 20, True) np.testing.assert_equal(surf.local_dofs_free_status, [False]*12) surf.fixed_range(20, 20, False) diff --git a/tests/mhd/test_bootstrap.py b/tests/mhd/test_bootstrap.py index 9a0fdea1f..8ca7e248c 100755 --- a/tests/mhd/test_bootstrap.py +++ b/tests/mhd/test_bootstrap.py @@ -15,12 +15,12 @@ try: import booz_xform -except ImportError as e: +except ImportError: booz_xform = None try: import vmec as vmec_extension -except ImportError as e: +except ImportError: vmec_extension = None logger = logging.getLogger(__name__) diff --git a/tests/mhd/test_boozer.py b/tests/mhd/test_boozer.py index 895455b36..923778489 100755 --- a/tests/mhd/test_boozer.py +++ b/tests/mhd/test_boozer.py @@ -7,17 +7,17 @@ from scipy.io import netcdf_file try: import booz_xform -except ImportError as e: +except ImportError: booz_xform = None try: import vmec -except ImportError as e: +except ImportError: vmec = None try: from mpi4py import MPI -except ImportError as e: +except ImportError: MPI = None from simsopt._core.optimizable import Optimizable @@ -118,19 +118,19 @@ def test_boozer_register(self): b1 = Boozer(None) self.assertEqual(b1.s, set()) # Try registering a single surface: - qs11 = Quasisymmetry(b1, 0.5, 1, 1) + Quasisymmetry(b1, 0.5, 1, 1) self.assertEqual(b1.s, {0.5}) # Register another surface: - qs12 = Quasisymmetry(b1, 0.75, 1, 0) + Quasisymmetry(b1, 0.75, 1, 0) self.assertEqual(b1.s, {0.5, 0.75}) # Register the same surface: - qs13 = Quasisymmetry(b1, 0.75, 1, 0) + Quasisymmetry(b1, 0.75, 1, 0) self.assertEqual(b1.s, {0.5, 0.75}) # Register two surfaces: - qs14 = Quasisymmetry(b1, [0.1, 0.2], 1, 0) + Quasisymmetry(b1, [0.1, 0.2], 1, 0) self.assertEqual(b1.s, {0.1, 0.2, 0.5, 0.75}) # Register two surfaces, with a copy: - qs15 = Quasisymmetry(b1, {0.2, 0.3}, 1, 0) + Quasisymmetry(b1, {0.2, 0.3}, 1, 0) self.assertEqual(b1.s, {0.1, 0.2, 0.3, 0.5, 0.75}) @unittest.skipIf((booz_xform is None) or (vmec is None), @@ -184,9 +184,8 @@ def test_boozer_circular_tokamak(self): # registered surface: # Register a QP target at s = 1: s = 0.9999 - qs4 = Quasisymmetry(b, s, 0, 1) + Quasisymmetry(b, s, 0, 1).J() self.assertEqual(b.s, {0.5, s, 1.0}) - residuals4 = qs4.J() np.testing.assert_allclose(b.bx.compute_surfs, [7, 15]) self.assertEqual(b.s_to_index, {0.5: 0, 1.0: 1, s: 1}) @@ -206,8 +205,7 @@ def test_boozer_circular_tokamak(self): def test_boozer_li383(self): v = Vmec(os.path.join(TEST_DIR, "wout_li383_low_res_reference.nc")) b = Boozer(v, mpol=32, ntor=16) - qs1 = Quasisymmetry(b, [0.0, 1.0], 1, 0) - residuals = qs1.J() + Quasisymmetry(b, [0.0, 1.0], 1, 0).J() np.testing.assert_allclose(b.bx.compute_surfs, [0, 14]) self.assertEqual(b.s_to_index, {0.0: 0, 1.0: 1}) bmnc = b.bx.bmnc_b diff --git a/tests/mhd/test_integrated_vmec_mpi.py b/tests/mhd/test_integrated_vmec_mpi.py index 17186ce25..14b2ddb2e 100755 --- a/tests/mhd/test_integrated_vmec_mpi.py +++ b/tests/mhd/test_integrated_vmec_mpi.py @@ -2,7 +2,6 @@ import logging import numpy as np -from monty.tempfile import ScratchDir try: from mpi4py import MPI except ImportError: @@ -46,7 +45,7 @@ def test_stellopt_scenarios_1DOF_circularCrossSection_varyR0_targetVolume(self): # logging.basicConfig(level=logging.DEBUG) # logger = logging.getLogger('[{}]'.format(MPI.COMM_WORLD.Get_rank()) + __name__) - logger = logging.getLogger(__name__) + logging.getLogger(__name__) for ngroups in range(1, 1 + MPI.COMM_WORLD.Get_size()): for grad in [False, True]: # In the next line, we can adjust how many groups the pool of MPI diff --git a/tests/mhd/test_profiles.py b/tests/mhd/test_profiles.py index eda67f0de..25fa529eb 100755 --- a/tests/mhd/test_profiles.py +++ b/tests/mhd/test_profiles.py @@ -199,13 +199,12 @@ def test_pressure_exception(self): nD = ProfileScaled(ne, 0.55) nT = ProfileScaled(ne, 0.45) TD = ProfilePolynomial(12.0e3 * np.array([1.0, -1.0])) - TT = TD # Try zero profiles: with self.assertRaises(ValueError): - pressure = ProfilePressure() + ProfilePressure() with self.assertRaises(ValueError): - pressure = ProfilePressure(ne) + ProfilePressure(ne) with self.assertRaises(ValueError): - pressure = ProfilePressure(ne, Te, nD) + ProfilePressure(ne, Te, nD) with self.assertRaises(ValueError): - pressure = ProfilePressure(ne, Te, nD, TD, nT) + ProfilePressure(ne, Te, nD, TD, nT) diff --git a/tests/mhd/test_spec.py b/tests/mhd/test_spec.py index 5eb8a789f..0ab5fb536 100755 --- a/tests/mhd/test_spec.py +++ b/tests/mhd/test_spec.py @@ -1,23 +1,19 @@ -from cmath import isnan import logging import os -import shutil import unittest import numpy as np from monty.tempfile import ScratchDir try: - import spec - spec_found = True + import spec as spec_mod except ImportError: - spec_found = False + spec_mod = None try: import pyoculus - pyoculus_found = True except ImportError: - pyoculus_found = False + pyoculus = None try: from mpi4py import MPI @@ -29,7 +25,7 @@ from simsopt.objectives import LeastSquaresProblem from simsopt.solve import least_squares_serial_solve -if (MPI is not None) and spec_found: +if (MPI is not None) and (spec_mod is not None): from simsopt.mhd import Spec, Residue from . import TEST_DIR @@ -38,7 +34,7 @@ # logging.basicConfig(level=logging.DEBUG) -@unittest.skipIf(not spec_found, "SPEC python module not found") +@unittest.skipIf(spec_mod is None, "SPEC python module not found") class SpecTests(unittest.TestCase): def test_init_defaults(self): """ @@ -439,7 +435,7 @@ def test_integrated_stellopt_scenarios_2dof(self): self.assertAlmostEqual(equil.iota(), -0.4114567, places=3) self.assertAlmostEqual(prob.objective(), 7.912501330E-04, places=3) - @unittest.skipIf((not spec_found) or (not pyoculus_found), + @unittest.skipIf((spec_mod is None) or (pyoculus is None), "SPEC python module or pyoculus not found") def test_residue(self): """ diff --git a/tests/mhd/test_virtual_casing.py b/tests/mhd/test_virtual_casing.py index 3b2fc56ac..007afb5a3 100755 --- a/tests/mhd/test_virtual_casing.py +++ b/tests/mhd/test_virtual_casing.py @@ -19,14 +19,12 @@ MPI = None try: - import vmec - vmec_found = True + import vmec as vmec_mod except ImportError: - vmec_found = False + vmec_mod = None from simsopt.mhd.vmec import Vmec from simsopt.mhd.virtual_casing import VirtualCasing -from simsopt.geo.surfacerzfourier import SurfaceRZFourier from . import TEST_DIR logger = logging.getLogger(__name__) @@ -41,7 +39,7 @@ @unittest.skipIf( (virtual_casing is None) or - (MPI is None) or (not vmec_found), + (MPI is None) or (vmec_mod is None), "Need virtual_casing, mpi4py, and vmec python packages") class VirtualCasingVmecTests(unittest.TestCase): @@ -52,13 +50,13 @@ def test_different_initializations(self): """ with ScratchDir("."): filename = os.path.join(TEST_DIR, 'input.li383_low_res') - vc = VirtualCasing.from_vmec(filename, src_nphi=8) + VirtualCasing.from_vmec(filename, src_nphi=8) filename = os.path.join(TEST_DIR, 'wout_20220102-01-053-003_QH_nfp4_aspect6p5_beta0p05_iteratedWithSfincs_reference.nc') - vc = VirtualCasing.from_vmec(filename, src_nphi=9, src_ntheta=10) + VirtualCasing.from_vmec(filename, src_nphi=9, src_ntheta=10) vmec = Vmec(filename) - vc = VirtualCasing.from_vmec(vmec, src_nphi=10) + VirtualCasing.from_vmec(vmec, src_nphi=10) @unittest.skipIf( @@ -199,7 +197,6 @@ def test_stellsym(self): """ filename = os.path.join(TEST_DIR, 'wout_20220102-01-053-003_QH_nfp4_aspect6p5_beta0p05_iteratedWithSfincs_reference.nc') vmec = Vmec(filename) - nfp = vmec.wout.nfp src_nphi = 48 src_ntheta = 12 vc = VirtualCasing.from_vmec(vmec, src_nphi=src_nphi, src_ntheta=src_ntheta, use_stellsym=False) diff --git a/tests/mhd/test_vmec.py b/tests/mhd/test_vmec.py index 24d1647e3..5335ddcc6 100755 --- a/tests/mhd/test_vmec.py +++ b/tests/mhd/test_vmec.py @@ -11,10 +11,9 @@ MPI = None try: - import vmec - vmec_found = True + import vmec as vmec_mod except ImportError: - vmec_found = False + vmec_mod = None from simsopt._core.optimizable import make_optimizable from simsopt.objectives.least_squares import LeastSquaresProblem @@ -153,13 +152,13 @@ def test_error_on_rerun(self): """ filename = os.path.join(TEST_DIR, 'wout_li383_low_res_reference.nc') vmec = Vmec(filename) - iota = vmec.mean_iota() + _ = vmec.mean_iota() vmec.boundary.set_rc(1, 0, 2.0) with self.assertRaises(RuntimeError): - iota2 = vmec.mean_iota() + vmec.mean_iota() -@unittest.skipIf((MPI is not None) and (vmec_found), "Interface to MPI and VMEC found") +@unittest.skipIf((MPI is not None) and (vmec_mod is not None), "Interface to MPI and VMEC found") class VmecTestsWithoutMPIorvmec(unittest.TestCase): def test_runnable_raises(self): """ @@ -168,10 +167,10 @@ def test_runnable_raises(self): """ from simsopt.mhd.vmec import Vmec with self.assertRaises(RuntimeError): - v = Vmec() + Vmec() -@unittest.skipIf((MPI is None) or (not vmec_found), "Valid Python interface to VMEC not found") +@unittest.skipIf((MPI is None) or (vmec_mod is None), "Valid Python interface to VMEC not found") class VmecTests(unittest.TestCase): def test_init_defaults(self): """ @@ -574,7 +573,6 @@ def test_iota_profile(self): # Now try a spline Profile with vmec using splines: vmec.indata.piota_type = 'cubic_spline' iota2.local_unfix_all() - newx = (2.2 - 0.7 * s_spline - 1.1 * s_spline ** 2) iota2.x = (2.2 - 0.7 * s_spline - 1.1 * s_spline ** 2) vmec.run() np.testing.assert_allclose(vmec.wout.iotas[1:], (2.2 - 0.7 * s - 1.1 * s * s)) diff --git a/tests/mhd/test_vmec_diagnostics.py b/tests/mhd/test_vmec_diagnostics.py index 3473dc4b5..82a5c545e 100755 --- a/tests/mhd/test_vmec_diagnostics.py +++ b/tests/mhd/test_vmec_diagnostics.py @@ -8,22 +8,20 @@ from simsopt.mhd.vmec_diagnostics import QuasisymmetryRatioResidual, \ B_cartesian, IotaTargetMetric, IotaWeighted, WellWeighted, \ vmec_splines, vmec_compute_geometry, vmec_fieldlines -from simsopt.objectives.least_squares import LeastSquaresProblem try: import matplotlib - matplotlib_found = True except: - matplotlib_found = False + matplotlib = None try: import vmec -except ImportError as e: +except ImportError: vmec = None try: from mpi4py import MPI -except ImportError as e: +except ImportError: MPI = None from simsopt.mhd.vmec import Vmec @@ -255,8 +253,6 @@ def test_B_cartesian(self): theta, phi = np.meshgrid(theta1D, phi1D) bmnc = 1.5 * vmec.wout.bmnc[:, -1] - 0.5 * vmec.wout.bmnc[:, -2] - xm = vmec.wout.xm_nyq - xn = vmec.wout.xn_nyq angle = vmec.wout.xm_nyq[:, None, None] * theta[None, :, :] \ - vmec.wout.xn_nyq[:, None, None] * phi[None, :, :] B = np.sum(bmnc[:, None, None] * np.cos(angle), axis=0) @@ -464,9 +460,9 @@ def test_1d_matches_3d(self): results1 = vmec_compute_geometry(splines, s, theta, phi) results2 = vmec_compute_geometry(vmec, np.array([s]), theta3d, phi3d) - variables = ["theta_pest", "grad_psi_dot_grad_psi", "B_cross_kappa_dot_grad_psi"] - for v in variables: - np.testing.assert_allclose(eval("results1." + v), eval("results2." + v)) + np.testing.assert_allclose(results1.theta_pest, results2.theta_pest) + np.testing.assert_allclose(results1.grad_psi_dot_grad_psi, results2.grad_psi_dot_grad_psi) + np.testing.assert_allclose(results1.B_cross_kappa_dot_grad_psi, results2.B_cross_kappa_dot_grad_psi) def test_compare_to_desc(self): """ @@ -710,7 +706,7 @@ def test_axisymm(self): fl.toroidal_flux_sign * (B0 / Aminor) * (-np.cos(theta) / R + phi * d_iota_d_r * eps * np.sin(theta)), atol=0.006) - @unittest.skipIf(not matplotlib_found, "Matplotlib python module not found") + @unittest.skipIf(matplotlib is None, "Matplotlib python module not found") def test_plot(self): """ Test the plotting function of vmec_fieldlines() @@ -718,13 +714,13 @@ def test_plot(self): vmec = Vmec(os.path.join(TEST_DIR, 'wout_W7-X_without_coil_ripple_beta0p05_d23p4_tm_reference.nc')) phi = np.linspace(-np.pi / 5, np.pi / 5, 7) - fl = vmec_fieldlines(vmec, s=1, alpha=0, phi1d=phi, plot=True, show=False) + vmec_fieldlines(vmec, s=1, alpha=0, phi1d=phi, plot=True, show=False) theta = np.linspace(-np.pi, np.pi, 100) - fl = vmec_fieldlines(vmec, s=0.5, alpha=np.pi, theta1d=theta, plot=True, show=False) + vmec_fieldlines(vmec, s=0.5, alpha=np.pi, theta1d=theta, plot=True, show=False) alpha = np.linspace(0, 2 * np.pi, 10, endpoint=False) - fl = vmec_fieldlines(vmec, s=[0.25, 0.5], alpha=alpha, phi1d=phi, plot=True, show=False) + vmec_fieldlines(vmec, s=[0.25, 0.5], alpha=alpha, phi1d=phi, plot=True, show=False) if __name__ == "__main__": diff --git a/tests/objectives/test_constrained.py b/tests/objectives/test_constrained.py index f96215ddf..8a3e0d8fd 100755 --- a/tests/objectives/test_constrained.py +++ b/tests/objectives/test_constrained.py @@ -1,5 +1,4 @@ import unittest -import logging import numpy as np from simsopt.objectives.functions import Identity, Rosenbrock, Failer, Affine from simsopt.objectives.constrained import ConstrainedProblem diff --git a/tests/objectives/test_fluxobjective.py b/tests/objectives/test_fluxobjective.py index 173423273..a58d56615 100755 --- a/tests/objectives/test_fluxobjective.py +++ b/tests/objectives/test_fluxobjective.py @@ -61,13 +61,13 @@ def test_definitions(self): np.testing.assert_allclose(J3, should_be3) with self.assertRaises(ValueError): - J4 = SquaredFlux(surf, bs, target, definition="foobar") + SquaredFlux(surf, bs, target, definition="foobar") def check_taylor_test(self, J): dofs = J.x np.random.seed(1) h = np.random.uniform(size=dofs.shape) - J0, dJ0 = J.J(), J.dJ() + dJ0 = J.dJ() dJh = sum(dJ0 * h) err_old = 1e10 for i in range(11, 17): diff --git a/tests/objectives/test_least_squares.py b/tests/objectives/test_least_squares.py index a67d7f535..939dfcfa5 100755 --- a/tests/objectives/test_least_squares.py +++ b/tests/objectives/test_least_squares.py @@ -1,7 +1,6 @@ import unittest -import logging import numpy as np -from simsopt.objectives.functions import Identity, Rosenbrock +from simsopt.objectives.functions import Identity #from simsopt.core.optimizable import Target from simsopt.objectives.least_squares import LeastSquaresProblem @@ -37,11 +36,11 @@ def test_exceptions(self): # sigma cannot be zero with self.assertRaises(ValueError): - lst = LeastSquaresProblem.from_sigma(3, 0, depends_on=iden) + LeastSquaresProblem.from_sigma(3, 0, depends_on=iden) # Weight cannot be negative with self.assertRaises(ValueError): - lst = LeastSquaresProblem(3, -1.0, depends_on=iden) + LeastSquaresProblem(3, -1.0, depends_on=iden) def test_multiple_funcs_single_input(self): iden1 = Identity(x=10) diff --git a/tests/objectives/test_utilities.py b/tests/objectives/test_utilities.py index a522ebcf0..5357cd6cd 100644 --- a/tests/objectives/test_utilities.py +++ b/tests/objectives/test_utilities.py @@ -4,7 +4,7 @@ import numpy as np from simsopt.geo.curvexyzfourier import CurveXYZFourier -from simsopt.geo.curveobjectives import CurveLength, LpCurveCurvature, LpCurveTorsion +from simsopt.geo.curveobjectives import CurveLength, LpCurveTorsion from simsopt.objectives.utilities import MPIObjective, QuadraticPenalty from simsopt.geo import parameters from simsopt._core.json import GSONDecoder, GSONEncoder, SIMSON diff --git a/tests/solve/test_constrained.py b/tests/solve/test_constrained.py index fd8ca889e..a350b1d7e 100755 --- a/tests/solve/test_constrained.py +++ b/tests/solve/test_constrained.py @@ -8,9 +8,9 @@ MPI = None from simsopt._core.optimizable import Optimizable -from simsopt.objectives.functions import Identity, Rosenbrock, Affine +from simsopt.objectives.functions import Rosenbrock from simsopt.objectives.constrained import ConstrainedProblem -from simsopt.solve.serial import constrained_serial_solve, serial_solve +from simsopt.solve.serial import constrained_serial_solve if MPI is not None: from simsopt.util.mpi import MpiPartition from simsopt.solve.mpi import constrained_mpi_solve diff --git a/tests/solve/test_least_squares.py b/tests/solve/test_least_squares.py index ccda66181..a2a04d77f 100755 --- a/tests/solve/test_least_squares.py +++ b/tests/solve/test_least_squares.py @@ -9,7 +9,7 @@ from simsopt.objectives.functions import Identity, Rosenbrock from simsopt.objectives.least_squares import LeastSquaresProblem -from simsopt.solve.serial import least_squares_serial_solve, serial_solve +from simsopt.solve.serial import least_squares_serial_solve if MPI is not None: from simsopt.util.mpi import MpiPartition from simsopt.solve.mpi import least_squares_mpi_solve diff --git a/tests/solve/test_mpi.py b/tests/solve/test_mpi.py index b58ea6d6b..e98574714 100755 --- a/tests/solve/test_mpi.py +++ b/tests/solve/test_mpi.py @@ -9,7 +9,6 @@ MPI = None from simsopt._core.optimizable import Optimizable -from simsopt.objectives.functions import Beale from simsopt.objectives.least_squares import LeastSquaresProblem if MPI is not None: from simsopt.util.mpi import MpiPartition diff --git a/tests/util/test_mpi_partition.py b/tests/util/test_mpi_partition.py index 18bfd36d2..3a3ddfbff 100755 --- a/tests/util/test_mpi_partition.py +++ b/tests/util/test_mpi_partition.py @@ -8,7 +8,7 @@ if MPI is not None: from simsopt.util.mpi import MpiPartition -from simsopt.util import proc0_print, comm_world +from simsopt.util import proc0_print # logging.basicConfig(level=logging.DEBUG) # logger = logging.getLogger('[{}]'.format(MPI.COMM_WORLD.Get_rank()) + __name__)