To receive notifications about scheduled maintenance, please subscribe to the mailing-list gitlab-operations@sympa.ethz.ch. You can subscribe to the mailing-list at https://sympa.ethz.ch

Commit bc2c6da5 authored by Cyrill Mast's avatar Cyrill Mast
Browse files

reworked tests

parent 1df8c1de
......@@ -27,7 +27,7 @@ class ARF(ScatteringField, BaseARF):
rho_s: float, c_s: float, rho_f: float, c_f: float,
p_0: float, position: Optional[float],
wave_type: str = "traveling",
particle_type: str = "general", n_max: int = None) -> None:
particle_type: str = "general", n_max: int = 10) -> None:
"""
Initializes the class and sets all parameter needed for the
computation.
......
......@@ -25,7 +25,8 @@ class BaseYosioka(BaseSphereFrequencyComposite):
rho_f: float, c_f: float,
p_0: float, position: Optional[float],
wave_type: str = "traveling",
particle_type: str = "general", n_max: int = None) -> None:
particle_type: str = "general", n_max: int = 10) -> None:
"""
Initializes the class and sets all parameter needed for the
computation.
......@@ -110,6 +111,7 @@ class BaseYosioka(BaseSphereFrequencyComposite):
['Position', 'pos', self.position, 'm'],
['Wavelength', 'lambda', self.field.lambda_f, 'm'],
['Wavetype', 'wavetype', self.wave_type, ''],
['Particle Type', 'particle_type', self.particle_type, ''],
['Number of Iterations', 'n_max', self.n_max, '']
]
for p in param_general:
......
......@@ -29,7 +29,7 @@ class ScatteringField(BaseYosioka, BaseScattering):
rho_s: float, c_s: float, rho_f: float, c_f: float,
p_0: float, position: Optional[float],
wave_type: str = "traveling",
particle_type: str = "general", n_max: int = None) -> None:
particle_type: str = "general", n_max: int = 10) -> None:
"""
Initializes the class and sets all parameter needed for the
computation.
......
import unittest
import numpy as np
from basetest import BaseTest
from gorkov import (
pi,
log, pi,
Yosioka1955, King1934, Gorkov1962)
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']})
# for Palatino and other serif fonts use:
# rc('font',**{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
logger = log
class TestYosiokaARF(BaseTest):
class TestYosioka(BaseTest):
def setUp(self) -> None:
self.line_palette = ["-", "-.", ":", "--", "dotted", "dashdot"]
self.wave_types = ["traveling", "standing"]
# Geometry
self.R_0 = 50e-6
......@@ -43,39 +35,45 @@ class TestYosiokaARF(BaseTest):
n_max = 10
self.cls_general = Yosioka1955.ARF(frequency=self.f,
radius=self.R_0, rho_s=self.rho_s,
radius=self.R_0,
rho_s=self.rho_s, c_s=self.c_s,
rho_f=self.rho_f, c_f=self.c_f,
c_s=self.c_s, p_0=self.p0,
p_0=self.p0,
position=self.pos,
wave_type=self.wave_type,
particle_type="general",
n_max=n_max)
self.cls_special = Yosioka1955.ARF(frequency=self.f,
radius=self.R_0, rho_s=self.rho_s,
radius=self.R_0,
rho_s=self.rho_s, c_s=self.c_s,
rho_f=self.rho_f, c_f=self.c_f,
c_s=self.c_s, p_0=self.p0,
p_0=self.p0,
position=self.pos,
wave_type=self.wave_type,
particle_type="special",
n_max=n_max)
self.cls_bubble = Yosioka1955.ARF(frequency=self.f,
radius=self.R_0, rho_s=self.rho_s,
radius=self.R_0,
rho_s=self.rho_s, c_s=self.c_s,
rho_f=self.rho_f, c_f=self.c_f,
c_s=self.c_s, p_0=self.p0,
p_0=self.p0,
position=self.pos,
wave_type=self.wave_type,
particle_type="bubble", n_max=n_max)
self.cls_sphere = Yosioka1955.ARF(frequency=self.f,
radius=self.R_0, rho_s=self.rho_s,
radius=self.R_0,
rho_s=self.rho_s, c_s=self.c_s,
rho_f=self.rho_f, c_f=self.c_f,
c_s=self.c_s, p_0=self.p0,
p_0=self.p0,
position=self.pos,
wave_type=self.wave_type,
particle_type="sphere", n_max=n_max)
# for comparison
self.cls_king = King1934.ARF(self.f,
self.R_0, self.rho_s,
self.rho_f, self.c_f,
self.p0, self.pos)
# for comparison
self.cls_gorkov = Gorkov1962.ARF(self.f,
self.R_0, self.rho_s, self.c_s,
self.rho_f, self.c_f,
......@@ -134,6 +132,7 @@ class TestYosiokaARF(BaseTest):
print(f'lambda is: {self.compute_xlambda()}')
print(f'order_bubble is: {order_bubble}')
break
self.assign_parameters()
def sphere_change_parameters(self) -> None:
self.R_0 = 50e-6
......@@ -159,6 +158,7 @@ class TestYosiokaARF(BaseTest):
print(f'lambda is: {self.compute_xlambda()}')
print(f'order_sphere is: {order_sphere}')
break
self.assign_parameters()
def assign_parameters(self) -> None:
for key in self.cls_dict:
......@@ -172,6 +172,10 @@ class TestYosiokaARF(BaseTest):
self.cls_dict[key].R_0 = self.R_0
self.cls_dict[key].wave_type = self.wave_type
"""
Tests for coefficients
"""
def test_xlambda(self) -> None:
for _ in range(10):
self.change_and_assign()
......@@ -193,14 +197,11 @@ class TestYosiokaARF(BaseTest):
pass
def test_F(self) -> None:
self.cls_bubble.wave_type = "traveling"
print(self.cls_bubble.density_compressibility_factor)
self.cls_bubble.wave_type = "standing"
print(self.cls_bubble.density_compressibility_factor)
self.cls_sphere.wave_type = "traveling"
print(self.cls_sphere.density_compressibility_factor)
self.cls_sphere.wave_type = "standing"
print(self.cls_sphere.density_compressibility_factor)
for w in self.wave_types:
self.wave_type = w
self.assign_parameters()
print(self.cls_bubble.density_compressibility_factor)
print(self.cls_sphere.density_compressibility_factor)
def test_compute_coefficients(self) -> None:
"""
......@@ -226,33 +227,62 @@ class TestYosiokaARF(BaseTest):
for c in imag_coeff:
self.assertEqual(c, imag_coeff[c])
def test_plot_coefficients(self) -> None:
n = np.arange(10)
K_n = []
M_n = []
coeffs = [K_n, M_n]
self.cls_general.wave_type = "traveling"
self.cls_general.position = 1e-4
for N in n:
K_n.append(abs(self.cls_general.K_n(N)))
M_n.append(abs(self.cls_general.M_n(N)))
for c in coeffs:
c /= c[0]
fig, ax = plt.subplots()
ax.set_xlabel(r"Order $n$")
ax.set_ylabel(r"Absolute value of the complex coefficients")
ax.set_title(r"The coefficients $K_{n}$ and $M_{n}$")
for i, c in enumerate(coeffs):
print(c)
ax.scatter(n, c, linestyle=self.line_palette[i])
ax.set_yscale('log')
# ax.set_xscale('log')
ax.legend([r"$K_n$", r"$M_n$"])
# ax.semilogy(n, abs(B_n_real), linestyle=self.line_palette[1])
# ax.semilogy(n, abs(K_n_real), linestyle=self.line_palette[2])
# ax.semilogy(n, abs(M_n_real), linestyle=self.line_palette[3])
plt.show()
"""
Tests for the scattering field
"""
def test_potentials_interface(self) -> None:
"""
ensures the boundary condition:
The potential at the particle / fluid - interface is similar.
"""
R = np.linspace(0.1 * self.R_0, 10 * self.R_0, 10)
th = np.linspace(0, 2 * pi, 10)
for w in self.wave_types:
self.wave_type = w
self.assign_parameters()
for r in R:
self.R_0 = r
self.assign_parameters()
for theta in th:
for t in range(10):
self.assertAlmostEqual(
self.cls_general.Phi_1(r, theta, t).real,
self.cls_general.Phi_star(r, theta, t).real,
threshold=1e-01)
self.assertAlmostEqual(
self.cls_general.Phi_1(r, theta, t).imag,
self.cls_general.Phi_star(r, theta, t).imag,
threshold=1e-01)
def test_velocities_interface(self) -> None:
"""
ensures the boundary condition:
The velocity at the particle / fluid - interface is the same.
"""
R = np.linspace(0.1 * self.R_0, 10 * self.R_0, 10)
th = np.linspace(0, 2 * pi, 10)
for w in self.wave_types:
self.wave_type = w
self.assign_parameters()
for r in R:
self.R_0 = r
self.assign_parameters()
for theta in th:
a = self.cls_general.radial_particle_velocity(
r, theta, 0)
b = self.cls_general.radial_acoustic_fluid_velocity(
r, theta, 0)
self.assertAlmostEqual(a, b, threshold=1e-1)
a = self.cls_general.tangential_acoustic_fluid_velocity(
r, theta, 0)
b = self.cls_general.tangential_particle_velocity(
r, theta, 0)
self.assertAlmostEqual(a, b, threshold=1e-1)
"""
Tests for the acoustic radiation force
"""
def test_arf(self) -> None:
......@@ -260,7 +290,6 @@ class TestYosiokaARF(BaseTest):
print("traveling wave field")
print("====================")
self.bubble_change_parameters()
self.assign_parameters()
sol = []
for key in self.cls_dict:
self.cls_dict[key].wave_type = "traveling"
......@@ -286,12 +315,10 @@ class TestYosiokaARF(BaseTest):
# self.assertAlmostEqual(sol[0], -sol[4], 1e-2)
def test_special_solutions(self) -> None:
wave_types = ["traveling", "standing"]
for w in wave_types:
for w in self.wave_types:
for key in self.cls_dict:
self.cls_dict[key].wave_type = w
self.sphere_change_parameters()
self.assign_parameters()
self.assertAlmostEqual(
self.cls_gorkov.acoustic_radiation_force(),
......@@ -301,7 +328,6 @@ class TestYosiokaARF(BaseTest):
self.cls_sphere.acoustic_radiation_force(), 3e-1)
self.bubble_change_parameters()
self.assign_parameters()
# self.assertAlmostEqual(
# self.cls_gorkov.acoustic_radiation_force(),
......@@ -311,11 +337,6 @@ class TestYosiokaARF(BaseTest):
# self.cls_bubble.acoustic_radiation_force(), 3e-1)
def test_small_spheres(self) -> None:
plt.style.use("ggplot")
fig, ax = plt.subplots()
ax.set_xlabel(r"$(k_{f} a)^{2}$")
ax.set_ylabel(r"Deviation to general solution in \%")
ax.set_title(r"Small Sphere Approximation")
self.sphere_change_parameters()
self.wave_type = "traveling"
self.assign_parameters()
......@@ -334,22 +355,9 @@ class TestYosiokaARF(BaseTest):
100 * abs(sol_sphere[i] - sol_general[i])
/ sol_general[i] for i in range(len(sol_sphere))
]
ax.semilogx(
ka_squared,
sol_sphere_normalized,
label="small spheres",
color="b")
ax.set_ylim(-10, 100)
ax.set_xlim(1e-3, 1.05)
plt.legend()
plt.show()
print(sol_sphere_normalized)
def test_bubbles(self) -> None:
plt.style.use("ggplot")
fig, ax = plt.subplots()
ax.set_xlabel(r"$(k_{f} a)^{2}$")
ax.set_ylabel(r"Deviation to general solution in \%")
ax.set_title(r"Bubble Approximation")
self.bubble_change_parameters()
self.wave_type = "standing"
self.assign_parameters()
......@@ -369,67 +377,11 @@ class TestYosiokaARF(BaseTest):
abs((sol_bubble[i] - sol_general[i])
/ sol_general[i]) for i in range(len(sol_bubble))
]
ax.plot(ka_squared,
sol_bubble_normalized,
label="bubbles approximation - normalized",
color="b")
# ax.set_xlim(0)
ax.relim()
plt.legend()
plt.show()
print(self.compute_xlambda())
def test_frequency_sweep(self) -> None:
"""
Recreates Fig. 2 from the Yosioka paper
"""
plt.style.use("ggplot")
fig, ax = plt.subplots()
ax.set_xlabel(r"$\frac{k^{*} a}{\sqrt{3 \lambda}}$")
ax.set_ylabel(r"Amplitude of the ARF")
ax.set_title("Bubble Approximation")
self.bubble_change_parameters()
self.wave_type = "traveling"
self.assign_parameters()
frequency = np.linspace(1e3, 2e5, int(1e2))
sol_general = []
sol_bubble = []
x_data = []
for f in frequency:
self.f = f
self.assign_parameters()
x_data.append(
(self.R_0 * self.compute_k_s())
/ (np.sqrt(3 * self.compute_xlambda())))
sol_general.append(self.cls_general.acoustic_radiation_force())
sol_bubble.append(self.cls_bubble.acoustic_radiation_force())
ax.semilogy(
x_data,
sol_bubble,
label="bubble approximation",
color="b",
linestyle="-.")
ax.semilogy(
x_data,
sol_general,
label="general solution",
color="r",
linestyle=":")
plt.legend()
plt.show()
print(sol_bubble_normalized)
def test_arf_traveling(self) -> None:
self.sphere_change_parameters()
self.assign_parameters()
plt.style.use("ggplot")
fig, ax = plt.subplots()
ax.set_xlabel(r"Position")
ax.set_ylabel(r"Amplitude of the ARF (N)")
ax.set_title(r"ARF on different locations")
pos = np.linspace(-1e-2, 1e-2, int(1e3))
legend = []
line_palette = ["-", "-.", ":", "--", "dotted", "dashdot"]
for i, key in enumerate(self.cls_dict):
try:
self.cls_dict[key].wave_type = "traveling"
......@@ -440,24 +392,14 @@ class TestYosiokaARF(BaseTest):
self.cls_dict[key].position = p
arf.append(
self.cls_dict[key].acoustic_radiation_force())
ax.plot(pos, arf, linestyle=line_palette[i])
legend.append(key)
print(arf)
except NotImplementedError:
pass
ax.legend(legend)
plt.show()
def test_arf_standing(self) -> None:
self.sphere_change_parameters()
self.assign_parameters()
plt.style.use("ggplot")
fig, ax = plt.subplots()
ax.set_xlabel(r"Position (m)")
ax.set_ylabel(r"Amplitude of the ARF (N)")
ax.set_title(r"ARF on different locations")
pos = np.linspace(-1e-2, 1e-2, int(1e3))
legend = []
line_palette = ["-", "-.", ":", "--", "dotted", "dashdot"]
for i, key in enumerate(self.cls_dict):
try:
if key == "bubble" or key == "king":
......@@ -468,12 +410,29 @@ class TestYosiokaARF(BaseTest):
self.cls_dict[key].position = p
arf.append(
(self.cls_dict[key].acoustic_radiation_force()))
ax.plot(pos, arf, linestyle=line_palette[i])
legend.append(key)
print(arf)
except NotImplementedError:
pass
ax.legend(legend)
plt.show()
"""
Tests for errors:
"""
def test_default_config(self) -> None:
"""
What happens, when Optional parameters are left out
"""
cls_default = Yosioka1955.ARF(frequency=self.f,
radius=self.R_0, rho_s=self.rho_s,
c_s=self.c_s, rho_f=self.rho_f,
c_f=self.c_f, p_0=self.p0,
position=self.pos,
wave_type=self.wave_type)
print(cls_default)
"""
Tests for str & repr
"""
def test_str(self) -> None:
print(self.cls_general.__str__())
......
import unittest
import matplotlib.pyplot as plt
import numpy as np
from gorkov import (
log, pi, Sphere,
Frequency, InviscidFluid)
from gorkov.solutions.Yosioka1955 import ScatteringField
from basetest import BaseTest
logger = log
class TestScatteringField(BaseTest):
def setUp(self) -> None:
# Geometry
self.R_0 = 1e-6
self.obj_sphere = Sphere(self.R_0)
# Frequency
self.f = 1e5
self.obj_freq = Frequency(self.f)
# Solid parameters
self.c_s = 1e3
self.rho_s = 1.05e3
self.particle_type = "general"
# Solid class
self.solid = InviscidFluid(self.f, self.rho_s, self.c_s)
# Fluid parameters
self.rho_f = 1e3
self.c_f = 1.5e3
# Fluid class
self.fluid = InviscidFluid(self.f, self.rho_f, self.c_f)
# Incident field
self.p_0 = 10e3
self.wave_type = 'traveling'
self.pos = 1e-5
self.theta = pi
self.n_max = 5
self.cls = ScatteringField(self.f, self.R_0,
self.rho_s, self.rho_f, self.c_f,
self.c_s, self.p_0, self.wave_type,
self.particle_type, self.pos,
self.n_max)
self.composite_cls = ScatteringField(self.f, self.R_0,
self.rho_s, self.rho_f, self.c_f,
self.c_s, self.p_0,
self.wave_type,
self.particle_type,
self.pos, self.n_max)
# -------------------------------------------------------------------------
# Scattering fields
# -------------------------------------------------------------------------
def test_potentials(self) -> None:
self.cls.wave_type = 'traveling'
self.cls.n_max = 3
acc = 30
theta = np.linspace(0, 2 * pi, acc)
t = np.linspace(0, 5e-6, acc)
phi = np.zeros((len(theta), len(t)))
for ix, dx in enumerate(theta):
for it, dt in enumerate(t):
phi[ix][it] = self.cls.Phi_1(1e-6, dx, dt).real
theta, t = np.meshgrid(theta, t)
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
ax.plot_surface(theta, t, phi, antialiased=True)
plt.show()
def test_velocities(self) -> None:
self.cls.wave_type = 'traveling'
self.cls.n_max = 3
acc = 30
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
ax.set_xlabel("radius")
ax.set_ylabel("theta")
ax.set_zlabel("Velocity")
plt.ion()
plt.show()
t = np.linspace(5e-7, 5e-5, acc)
for dt in t:
vel = np.zeros([acc, acc])
theta = np.linspace(0, 2 * pi, acc)
r = np.linspace(1e-9, 1e-6, acc)
for i_t, val_t in enumerate(theta):
for i_r, val_r in enumerate(r):
vel[i_r][i_t] = self.cls.radial_particle_velocity(
r=val_r, theta=val_t, t=dt)
angle, radius = np.meshgrid(theta, r)
ax.plot_surface(angle, radius, vel)
plt.pause(0.00000001)
ax.clear()
if __name__ == '__main__':
unittest.main()
import unittest
import numpy as np
from gorkov import (
log, pi)
from test_Yosioka import TestYosioka
import matplotlib.pyplot as plt
from matplotlib import rc
rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']})
# for Palatino and other serif fonts use:
# rc('font',**{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
logger = log
class TestYosiokaPlots(TestYosioka):
t = TestYosioka()
t.setUp()
def test_plot_coefficients(self) -> None:
n = np.arange(10)
K_n = []
M_n = []
coeffs = [K_n, M_n]
self.t.cls_general.wave_type = "traveling"
self.t.cls_general.position = 1e-4
for N in n:
K_n.append(abs(self.t.cls_general.K_n(N)))
M_n.append(abs(self.t.cls_general.M_n(N)))
for c in coeffs:
c /= c[0]
fig, ax = plt.subplots()
ax.set_xlabel(r"Order $n$")
ax.set_ylabel(r"Absolute value of the complex coefficients")
ax.set_title(r"The coefficients $K_{n}$ and $M_{n}$")
for i, c in enumerate(coeffs):
print(c)
ax.scatter(n, c, linestyle=self.line_palette[i])
ax.