Skip to content

Commit

Permalink
Unused variable and unused import linter fixes in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mbkumar committed Oct 30, 2023
1 parent a1702b5 commit 23628d0
Show file tree
Hide file tree
Showing 17 changed files with 78 additions and 136 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@ extend-exclude = ["thirdparty"]
"tests/verify_MPI_not_initialized.py" = ["F401"]
"tests/geo/test_plot.py" = ["F401"]
"tests/geo/test_curve.py" = ["F401"]

"tests/mhd/test_virtual_casing.py" = ["F841"]
8 changes: 0 additions & 8 deletions tests/core/test_derivative.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -108,19 +106,13 @@ 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)
assert err < (0.6)**4 * err_old
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):

Expand Down
2 changes: 1 addition & 1 deletion tests/core/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
37 changes: 19 additions & 18 deletions tests/core/test_optimizable.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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.
Expand All @@ -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)
Expand Down Expand Up @@ -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]

Expand Down
28 changes: 12 additions & 16 deletions tests/field/test_boozermagneticfields.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand All @@ -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()
Expand Down
6 changes: 1 addition & 5 deletions tests/field/test_magneticfields.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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([
Expand Down Expand Up @@ -718,7 +714,7 @@ def test_pmopt_dipoles(self):
# check <Bn>
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,
Expand Down
29 changes: 7 additions & 22 deletions tests/field/test_particle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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')

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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')

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading

0 comments on commit 23628d0

Please sign in to comment.