Merge pull request #296 from majsylw/feature/relaxation

[GSoC 2021] Modelling complex materials
这个提交包含在:
Craig Warren
2021-10-19 14:30:25 +01:00
提交者 GitHub
当前提交 55333df656
共有 19 个文件被更改,包括 3827 次插入4 次删除

查看文件

@@ -179,7 +179,10 @@ class AddSurfaceRoughness(UserObjectGeometry):
surface.surfaceID = requestedsurface
surface.fractalrange = fractalrange
surface.operatingonID = volume.ID
surface.seed = int(seed)
if seed is not None:
surface.seed = int(seed)
else:
surface.seed = seed
surface.weighting = weighting
# List of existing surfaces IDs

查看文件

@@ -66,7 +66,7 @@ class FractalBox(UserObjectGeometry):
rot_pts = rotate_2point_object(pts, self.axis, self.angle, self.origin)
self.kwargs['p1'] = tuple(rot_pts[0, :])
self.kwargs['p2'] = tuple(rot_pts[1, :])
def create(self, grid, uip):
try:
p1 = self.kwargs['p1']
@@ -140,7 +140,10 @@ class FractalBox(UserObjectGeometry):
volume.ID = ID
volume.operatingonID = mixing_model_id
volume.nbins = nbins
volume.seed = int(seed)
if seed is not None:
volume.seed = int(seed)
else:
volume.seed = seed
volume.weighting = weighting
volume.averaging = averagefractalbox
volume.mixingmodel = mixingmodel

查看文件

@@ -209,7 +209,9 @@ def check_cmd_names(processedlines, checkessential=True):
# Commands that there can be multiple instances of in a model
# - these will be lists within the dictionary
multiplecmds = {key: [] for key in ['#geometry_view',
'#geometry_objects_write', '#material',
'#geometry_objects_write', '#material',
'#havriliak_negami', '#jonscher',
'#crim', '#raw_data',
'#soil_peplinski',
'#add_dispersion_debye',
'#add_dispersion_lorentz',

查看文件

@@ -17,6 +17,10 @@
# along with gprMax. If not, see <http://www.gnu.org/licenses/>.
import logging
import os
os.path.join(os.path.dirname(__file__), '..', 'user_libs', 'DebyeFit')
from user_libs.DebyeFit import (HavriliakNegami, Jonscher, Crim, Rawdata)
from .cmds_multiuse import (PMLCFS, AddDebyeDispersion, AddDrudeDispersion,
AddLorentzDispersion, GeometryObjectsWrite,
@@ -170,6 +174,105 @@ def process_multicmds(multicmds):
scene_objects.append(snapshot)
cmdname = '#havriliak_negami'
if multicmds[cmdname] is not None:
for cmdinstance in multicmds[cmdname]:
tmp = cmdinstance.split()
if len(tmp) != 12 and len(tmp) != 13:
logger.exception("'" + cmdname + ': ' + ' '.join(tmp) + "'" + ' requires either twelve or thirteen parameters')
raise ValueError
seed = None
if len(tmp) == 13:
seed = int(tmp[12])
setup = HavriliakNegami(f_min=float(tmp[0]), f_max=float(tmp[1]),
alpha=float(tmp[2]), beta=float(tmp[3]),
e_inf=float(tmp[4]), de=float(tmp[5]), tau_0=float(tmp[6]),
sigma=float(tmp[7]), mu=float(tmp[8]), mu_sigma=float(tmp[9]),
number_of_debye_poles=int(tmp[10]), material_name=tmp[11],
optimizer_options={'seed': seed})
_, properties = setup.run()
multicmds['#material'].append(properties[0].split(':')[1].strip(' \t\n'))
multicmds['#add_dispersion_debye'].append(properties[1].split(':')[1].strip(' \t\n'))
cmdname = '#jonscher'
if multicmds[cmdname] is not None:
for cmdinstance in multicmds[cmdname]:
tmp = cmdinstance.split()
if len(tmp) != 11 and len(tmp) != 12:
logger.exception("'" + cmdname + ': ' + ' '.join(tmp) + "'" + ' requires either eleven or twelve parameters')
raise ValueError
seed = None
if len(tmp) == 12:
seed = int(tmp[11])
setup = Jonscher(f_min=float(tmp[0]), f_max=float(tmp[1]),
e_inf=float(tmp[2]), a_p=float(tmp[3]),
omega_p=float(tmp[4]), n_p=float(tmp[5]),
sigma=float(tmp[6]), mu=float(tmp[7]), mu_sigma=float(tmp[8]),
number_of_debye_poles=int(tmp[9]), material_name=tmp[10],
optimizer_options={'seed': seed})
_, properties = setup.run()
multicmds['#material'].append(properties[0].split(':')[1].strip(' \t\n'))
multicmds['#add_dispersion_debye'].append(properties[1].split(':')[1].strip(' \t\n'))
cmdname = '#crim'
if multicmds[cmdname] is not None:
for cmdinstance in multicmds[cmdname]:
tmp = cmdinstance.split()
if len(tmp) != 10 and len(tmp) != 11:
logger.exception("'" + cmdname + ': ' + ' '.join(tmp) + "'" + ' requires either ten or eleven parameters')
raise ValueError
seed = None
if len(tmp) == 11:
seed = int(tmp[10])
if (tmp[3][0] != '[' and tmp[3][-1] != ']') or (tmp[4][0] != '[' and tmp[4][-1] != ']'):
logger.exception("'" + cmdname + ': ' + ' '.join(tmp) + "'" + ' requires list at 6th and 7th position')
raise ValueError
vol_frac = [float(i) for i in tmp[3].strip('[]').split(',')]
material = [float(i) for i in tmp[4].strip('[]').split(',')]
if len(material) % 3 != 0:
logger.exception("'" + cmdname + ': ' + ' '.join(tmp) + "'" + ' each material requires three parameters: e_inf, de, tau_0')
raise ValueError
materials = [material[n:n+3] for n in range(0, len(material), 3)]
setup = Crim(f_min=float(tmp[0]), f_max=float(tmp[1]), a=float(tmp[2]),
volumetric_fractions=vol_frac, materials=materials,
sigma=float(tmp[5]), mu=float(tmp[6]), mu_sigma=float(tmp[7]),
number_of_debye_poles=int(tmp[8]), material_name=tmp[9],
optimizer_options={'seed': seed})
_, properties = setup.run()
multicmds['#material'].append(properties[0].split(':')[1].strip(' \t\n'))
multicmds['#add_dispersion_debye'].append(properties[1].split(':')[1].strip(' \t\n'))
cmdname = '#raw_data'
if multicmds[cmdname] is not None:
for cmdinstance in multicmds[cmdname]:
tmp = cmdinstance.split()
if len(tmp) != 6 and len(tmp) != 7:
logger.exception("'" + cmdname + ': ' + ' '.join(tmp) + "'" + ' requires either six or seven parameters')
raise ValueError
seed = None
if len(tmp) == 7:
seed = int(tmp[6])
setup = Rawdata(filename=tmp[0], sigma=float(tmp[1]),
mu=float(tmp[2]), mu_sigma=float(tmp[3]),
number_of_debye_poles=int(tmp[4]), material_name=tmp[5],
optimizer_options={'seed': seed})
_, properties = setup.run()
multicmds['#material'].append(properties[0].split(':')[1].strip(' \t\n'))
multicmds['#add_dispersion_debye'].append(properties[1].split(':')[1].strip(' \t\n'))
cmdname = '#material'
if multicmds[cmdname] is not None:
for cmdinstance in multicmds[cmdname]:

查看文件

@@ -0,0 +1,710 @@
# Authors: Iraklis Giannakis, and Sylwia Majchrowska
# E-mail: i.giannakis@ed.ac.uk
#
# This file is part of gprMax.
#
# gprMax is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# gprMax is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with gprMax. If not, see <http://www.gnu.org/licenses/>.
import numpy as np
import os
from matplotlib import pylab as plt
import matplotlib.gridspec as gridspec
from pathlib import Path
import sys
import scipy.interpolate
import warnings
from optimization import PSO_DLS, DA_DLS, DE_DLS
class Relaxation(object):
""" Create Relaxation function object for complex material.
:param sigma: The conductivity (Siemens/metre).
:type sigma: float, non-optional
:param mu: The relative permeability.
:type mu: float, non-optional
:param mu_sigma: The magnetic loss.
:type mu_sigma: float, non-optional
:param material_name: A string containing the given name of
the material (e.g. "Clay").
:type material_name: str, non-optional
:param: number_of_debye_poles: Number of Debye functions used to
approximate the given electric
permittivity.
:type number_of_debye_poles: int, optional
:param: fn: Number of frequency points in frequency grid.
:type fn: int, optional (Default: 50)
:param plot: if True will plot the actual and the approximated
permittivity at the end (neglected as default: False).
:type plot: bool, optional, default:False
:param save: if True will save approximated material parameters
(not neglected as default: True).
:type save: bool, optional, default:True
:param optimizer: chosen optimization method:
Hybrid Particle Swarm-Damped Least-Squares (PSO_DLS),
Dual Annealing (DA) or Differential Evolution (DE)
(Default: PSO_DLS).
:type optimizer: Optimizer class, optional
:param optimizer_options: Additional keyword arguments passed to
optimizer class (Default: empty dict).
:type optimizer_options: dict, optional, default: empty dict
"""
def __init__(self, sigma, mu, mu_sigma,
material_name, f_n=50,
number_of_debye_poles=-1,
plot=True, save=False,
optimizer=PSO_DLS,
optimizer_options={}):
self.name = 'Relaxation function'
self.params = {}
self.number_of_debye_poles = number_of_debye_poles
self.f_n = f_n
self.sigma = sigma
self.mu = mu
self.mu_sigma = mu_sigma
self.material_name = material_name
self.plot = plot
self.save = save
self.optimizer = optimizer(**optimizer_options)
def set_freq(self, f_min, f_max, f_n=50):
""" Interpolate frequency vector using n equally logarithmicaly spaced frequencies.
Args:
f_min (float): First bound of the frequency range
used to approximate the given function (Hz).
f_max (float): Second bound of the frequency range
used to approximate the given function (Hz).
f_n (int): Number of frequency points in frequency grid
(Default: 50).
Note:
f_min and f_max must satisfied f_min < f_max
"""
if abs(f_min - f_max) > 1e12:
warnings.warn(f'The chosen range is realy big. '
f'Consider setting greater number of points '
f'on the frequency grid!')
self.freq = np.logspace(np.log10(f_min),
np.log10(f_max),
int(f_n))
def check_inputs(self):
""" Check the validity of the inputs. """
try:
d = [float(i) for i in
[self.number_of_debye_poles,
self.sigma, self.mu, self.mu_sigma]]
except ValueError:
sys.exit("The inputs should be numeric.")
if not isinstance(self.number_of_debye_poles, int):
sys.exit("The number of Debye poles must be integer.")
if (np.array(d[1:]) < 0).sum() != 0:
sys.exit("The inputs should be positive.")
def calculation(self):
""" Approximate the given relaxation function
(Havriliak-Negami function, Crim, Jonscher) or based on raw data.
"""
raise NotImplementedError()
def print_info(self):
"""Readable string of parameters for given approximation settings.
Returns:
s (str): Info about chosen function and its parameters.
"""
print(f"Approximating {self.name}"
f" using {self.number_of_debye_poles} Debye poles")
print(f"{self.name} parameters: ")
s = ''
for k, v in self.params.items():
s += f"{k:10s} = {v}\n"
print(s)
return f'{self.name}:\n{s}'
def optimize(self):
""" Calling the main optimisation module with defined lower and upper boundaries of search.
Returns:
tau (ndarray): The optimised relaxation times.
weights (ndarray): Resulting optimised weights for the given relaxation times.
ee (float): Average error between the actual and the approximated real part.
rl (ndarray): Real parts of chosen relaxation function
for given frequency points.
im (ndarray): Imaginary parts of chosen relaxation function
for given frequency points.
"""
# Define the lower and upper boundaries of search
lb = np.full(self.number_of_debye_poles,
-np.log10(np.max(self.freq)) - 3)
ub = np.full(self.number_of_debye_poles,
-np.log10(np.min(self.freq)) + 3)
# Call optimizer to minimize the cost function
tau, weights, ee, rl, im = self.optimizer.fit(func=self.optimizer.cost_function,
lb=lb, ub=ub,
funckwargs={'rl': self.rl,
'im': self.im,
'freq': self.freq}
)
return tau, weights, ee, rl, im
def run(self):
""" Solve the problem described by the given relaxation function
(Havriliak-Negami function, Crim, Jonscher)
or data given from a text file.
Returns:
avg_err (float): average fractional error
for relative permittivity (sum)
properties (list(str)): Given material nad Debye expnasion parameters
in a gprMax format.
"""
# Check the validity of the inputs
self.check_inputs()
# Print information about chosen approximation settings
self.print_info()
# Calculate both real and imaginary parts
# for the frequencies included in the vector freq
q = self.calculation()
# Set the real and the imaginary part of the relaxation function
self.rl, self.im = q.real, q.imag
if self.number_of_debye_poles == -1:
print("\n#########",
"Try to automaticaly fit number of Debye poles, up to 20!",
"##########\n", sep="")
error = np.infty # artificial best error starting value
self.number_of_debye_poles = 1
iteration = 1
# stop increasing number of Debye poles if error is smaller then 5%
# or 20 debye poles is reached
while error > 5 and iteration < 21:
# Calling the main optimisation module
tau, weights, ee, rl, im = self.optimize()
err_real, err_imag = self.error(rl + ee, im)
error = err_real + err_imag
self.number_of_debye_poles += 1
iteration += 1
else:
# Calling the main optimisation module
# for choosen number of debye poles
# if one of the weights is negative increase the stabiliser
# and repeat the optimisation
tau, weights, ee, rl, im = self.optimize()
err_real, err_imag = self.error(rl + ee, im)
# Print the results in gprMax format style
properties = self.print_output(tau, weights, ee)
print(f'The average fractional error for:\n'
f'- real part: {err_real}\n'
f'- imaginary part: {err_imag}\n')
if self.save:
self.save_result(properties)
# Plot the actual and the approximate dielectric properties
if self.plot:
self.plot_result(rl + ee, im)
return err_real + err_imag, properties
def print_output(self, tau, weights, ee):
""" Print out the resulting Debye parameters in a gprMax format.
Args:
tau (ndarray): The best known position form optimization module
(optimal design).
weights (ndarray): Resulting optimised weights for the given relaxation times.
ee (float): Average error between the actual and the approximated real part.
Returns:
material_prop (list(str)): Given material nad Debye expnasion parameters
in a gprMax format.
"""
print("Debye expansion parameters: ")
print(f" |{'e_inf':^14s}|{'De':^14s}|{'log(tau_0)':^25s}|")
print("_" * 65)
for i in range(0, len(tau)):
print("Debye {0:}|{1:^14.5f}|{2:^14.5f}|{3:^25.5f}|"
.format(i + 1, ee/len(tau), weights[i],
tau[i]))
print("_" * 65)
# Print the Debye expnasion in a gprMax format
material_prop = []
material_prop.append("#material: {} {} {} {} {}\n".format(ee, self.sigma,
self.mu,
self.mu_sigma,
self.material_name))
print(material_prop[0], end="")
dispersion_prop = "#add_dispersion_debye: {}".format(len(tau))
for i in range(len(tau)):
dispersion_prop += " {} {}".format(weights[i], 10**tau[i])
dispersion_prop += " {}".format(self.material_name)
print(dispersion_prop)
material_prop.append(dispersion_prop + '\n')
return material_prop
def plot_result(self, rl_exp, im_exp):
""" Plot the actual and the approximated electric permittivity,
along with relative error for real and imaginary parts
using a semilogarithm X axes.
Args:
rl_exp (ndarray): Real parts of optimised Debye expansion
for given frequency points (plus average error).
im_exp (ndarray): Imaginary parts of optimised Debye expansion
for given frequency points.
"""
plt.close("all")
fig = plt.figure(figsize=(16, 8), tight_layout=True)
gs = gridspec.GridSpec(2, 1)
ax = fig.add_subplot(gs[0])
ax.grid(b=True, which="major", linewidth=0.2, linestyle="--")
ax.semilogx(self.freq * 1e-6, rl_exp, "b-", linewidth=2.0,
label="Debye Expansion: Real part")
ax.semilogx(self.freq * 1e-6, -im_exp, "k-", linewidth=2.0,
label="Debye Expansion: Imaginary part")
ax.semilogx(self.freq * 1e-6, self.rl, "r.",
linewidth=2.0, label=f"{self.name}: Real part")
ax.semilogx(self.freq * 1e-6, -self.im, "g.", linewidth=2.0,
label=f"{self.name}: Imaginary part")
ax.set_ylim([-1, np.max(np.concatenate([self.rl, -self.im])) + 1])
ax.legend()
ax.set_xlabel("Frequency (MHz)")
ax.set_ylabel("Relative permittivity")
ax = fig.add_subplot(gs[1])
ax.grid(b=True, which="major", linewidth=0.2, linestyle="--")
ax.semilogx(self.freq * 1e-6, (rl_exp - self.rl)/(self.rl + 1), "b-", linewidth=2.0,
label="Real part")
ax.semilogx(self.freq * 1e-6, (-im_exp + self.im)/(self.im + 1), "k-", linewidth=2.0,
label="Imaginary part")
ax.legend()
ax.set_xlabel("Frequency (MHz)")
ax.set_ylabel("Relative approximation error")
plt.show()
def error(self, rl_exp, im_exp):
""" Calculate the average fractional error separately for
relative permittivity (real part) and conductivity (imaginary part)
Args:
rl_exp (ndarray): Real parts of optimised Debye expansion
for given frequency points (plus average error).
im_exp (ndarray): Imaginary parts of optimised Debye expansion
for given frequency points.
Returns:
avg_err_real (float): average fractional error
for relative permittivity (real part)
avg_err_imag (float): average fractional error
for conductivity (imaginary part)
"""
avg_err_real = np.sum(np.abs((rl_exp - self.rl)/(self.rl + 1)) * 100)/len(rl_exp)
avg_err_imag = np.sum(np.abs((-im_exp + self.im)/(self.im + 1)) * 100)/len(im_exp)
return avg_err_real, avg_err_imag
@staticmethod
def save_result(output, fdir="../materials"):
""" Save the resulting Debye parameters in a gprMax format.
Args:
output (list(str)): Material and resulting Debye parameters
in a gprMax format.
fdir (str): Path to saving directory.
"""
if fdir != "../materials" and os.path.isdir(fdir):
file_path = os.path.join(fdir, "my_materials.txt")
elif os.path.isdir("../materials"):
file_path = os.path.join("../materials",
"my_materials.txt")
elif os.path.isdir("materials"):
file_path = os.path.join("materials",
"my_materials.txt")
elif os.path.isdir("user_libs/materials"):
file_path = os.path.join("user_libs", "materials",
"my_materials.txt")
else:
sys.exit("Cannot save material properties "
f"in {os.path.join(fdir, 'my_materials.txt')}!")
fileH = open(file_path, "a")
fileH.write(f"## {output[0].split(' ')[-1]}")
fileH.writelines(output)
fileH.write("\n")
fileH.close()
print(f"Material properties save at: {file_path}")
class HavriliakNegami(Relaxation):
""" Approximate a given Havriliak-Negami function
Havriliak-Negami function = ε_∞ + Δ‎ε / (1 + (2πfjτ)**α)**β,
where f is the frequency in Hz.
:param f_min: First bound of the frequency range
used to approximate the given function (Hz).
:type f_min: float
:param f_max: Second bound of the frequency range
used to approximate the given function (Hz).
:type f_max: float
:param e_inf: The real relative permittivity at infinity frequency
:type e_inf: float
:param alpha: Real positive float number which varies 0 < alpha < 1.
For alpha = 1 and beta !=0 & beta !=1 Havriliak-Negami
transforms to Cole-Davidson function.
:type alpha: float
:param beta: Real positive float number which varies 0 < beta < 1.
For beta = 1 and alpha !=0 & alpha !=1 Havriliak-Negami
transforms to Cole-Cole function.
:type beta: float
:param de: The difference of relative permittivity at infinite frequency
and the relative permittivity at zero frequency.
:type de: float
:param tau_0: Real positive float number, tau_0 is the relaxation time.
:type tau_0: float
"""
def __init__(self, f_min, f_max,
alpha, beta, e_inf, de, tau_0,
sigma, mu, mu_sigma, material_name,
number_of_debye_poles=-1, f_n=50,
plot=False, save=False,
optimizer=PSO_DLS,
optimizer_options={}):
super(HavriliakNegami, self).__init__(sigma=sigma, mu=mu, mu_sigma=mu_sigma,
material_name=material_name, f_n=f_n,
number_of_debye_poles=number_of_debye_poles,
plot=plot, save=save,
optimizer=optimizer,
optimizer_options=optimizer_options)
self.name = 'Havriliak-Negami function'
# Place the lower frequency bound at f_min and the upper frequency bound at f_max
if f_min > f_max:
self.f_min, self.f_max = f_max, f_min
else:
self.f_min, self.f_max = f_min, f_max
# Choosing n frequencies logarithmicaly equally spaced between the bounds given
self.set_freq(self.f_min, self.f_max, self.f_n)
self.e_inf, self.alpha, self.beta, self.de, self.tau_0 = e_inf, alpha, beta, de, tau_0
self.params = {'f_min': self.f_min, 'f_max': self.f_max,
'eps_inf': self.e_inf, 'Delta_eps': self.de, 'tau_0': self.tau_0,
'alpha': self.alpha, 'beta': self.beta}
def check_inputs(self):
""" Check the validity of the Havriliak Negami model's inputs. """
super(HavriliakNegami, self).check_inputs()
try:
d = [float(i) for i in self.params.values()]
except ValueError:
sys.exit("The inputs should be numeric.")
if (np.array(d) < 0).sum() != 0:
sys.exit("The inputs should be positive.")
if self.alpha > 1:
sys.exit("Alpha value must range between 0-1 (0 <= alpha <= 1)")
if self.beta > 1:
sys.exit("Beta value must range between 0-1 (0 <= beta <= 1)")
if self.f_min == self.f_max:
sys.exit("Null frequency range")
def calculation(self):
"""Calculates the Havriliak-Negami function for
the given parameters."""
return self.e_inf + self.de / (
1 + (1j * 2 * np.pi *
self.freq * self.tau_0)**self.alpha
)**self.beta
class Jonscher(Relaxation):
""" Approximate a given Jonsher function
Jonscher function = ε_∞ - ap * (-1j * 2πf / omegap)**n_p,
where f is the frequency in Hz
:param f_min: First bound of the frequency range
used to approximate the given function (Hz).
:type f_min: float
:param f_max: Second bound of the frequency range
used to approximate the given function (Hz).
:type f_max: float
:params e_inf: The real relative permittivity at infinity frequency.
:type e_inf: float, non-optional
:params a_p: Jonscher parameter. Real positive float number.
:type a_p: float, non-optional
:params omega_p: Jonscher parameter. Real positive float number.
:type omega_p: float, non-optional
:params n_p: Jonscher parameter, 0 < n_p < 1.
:type n_p: float, non-optional
"""
def __init__(self, f_min, f_max,
e_inf, a_p, omega_p, n_p,
sigma, mu, mu_sigma,
material_name, number_of_debye_poles=-1,
f_n=50, plot=False, save=False,
optimizer=PSO_DLS,
optimizer_options={}):
super(Jonscher, self).__init__(sigma=sigma, mu=mu, mu_sigma=mu_sigma,
material_name=material_name, f_n=f_n,
number_of_debye_poles=number_of_debye_poles,
plot=plot, save=save,
optimizer=optimizer,
optimizer_options=optimizer_options)
self.name = 'Jonsher function'
# Place the lower frequency bound at f_min and the upper frequency bound at f_max
if f_min > f_max:
self.f_min, self.f_max = f_max, f_min
else:
self.f_min, self.f_max = f_min, f_max
# Choosing n frequencies logarithmicaly equally spaced between the bounds given
self.set_freq(self.f_min, self.f_max, self.f_n)
self.e_inf, self.a_p, self.omega_p, self.n_p = e_inf, a_p, omega_p, n_p
self.params = {'f_min': self.f_min, 'f_max': self.f_max,
'eps_inf': self.e_inf, 'n_p': self.n_p,
'omega_p': self.omega_p, 'a_p': self.a_p}
def check_inputs(self):
""" Check the validity of the inputs. """
super(Jonscher, self).check_inputs()
try:
d = [float(i) for i in self.params.values()]
except ValueError:
sys.exit("The inputs should be numeric.")
if (np.array(d) < 0).sum() != 0:
sys.exit("The inputs should be positive.")
if self.n_p > 1:
sys.exit("n_p value must range between 0-1 (0 <= n_p <= 1)")
if self.f_min == self.f_max:
sys.exit("Error: Null frequency range!")
def calculation(self):
"""Calculates the Q function for the given parameters"""
return self.e_inf + (self.a_p * (2 * np.pi *
self.freq / self.omega_p)**(self.n_p-1)) * (
1 - 1j / np.tan(self.n_p * np.pi/2))
class Crim(Relaxation):
""" Approximate a given CRIM function
CRIM = (Σ frac_i * (ε_∞_i + Δε_i/(1 + 2πfj*τ_i))^a)^(1/a)
:param f_min: First bound of the frequency range
used to approximate the given function (Hz).
:type f_min: float
:param f_max: Second bound of the frequency range
used to approximate the given function (Hz).
:type f_max: float
:param a: Shape factor.
:type a: float, non-optional
:param: volumetric_fractions: Volumetric fraction for each material.
:type volumetric_fractions: ndarray, non-optional
:param materials: Arrays of materials properties, for each material [e_inf, de, tau_0].
:type materials: ndarray, non-optional
"""
def __init__(self, f_min, f_max, a, volumetric_fractions,
materials, sigma, mu, mu_sigma, material_name,
number_of_debye_poles=-1, f_n=50,
plot=False, save=False,
optimizer=PSO_DLS,
optimizer_options={}):
super(Crim, self).__init__(sigma=sigma, mu=mu, mu_sigma=mu_sigma,
material_name=material_name, f_n=f_n,
number_of_debye_poles=number_of_debye_poles,
plot=plot, save=save,
optimizer=optimizer,
optimizer_options=optimizer_options)
self.name = 'CRIM function'
# Place the lower frequency bound at f_min and the upper frequency bound at f_max
if f_min > f_max:
self.f_min, self.f_max = f_max, f_min
else:
self.f_min, self.f_max = f_min, f_max
# Choosing n frequencies logarithmicaly equally spaced between the bounds given
self.set_freq(self.f_min, self.f_max, self.f_n)
self.a = a
self.volumetric_fractions = np.array(volumetric_fractions)
self.materials = np.array(materials)
self.params = {'f_min': self.f_min, 'f_max': self.f_max,
'a': self.a, 'volumetric_fractions': self.volumetric_fractions,
'materials': self.materials}
def check_inputs(self):
""" Check the validity of the inputs. """
super(Crim, self).check_inputs()
try:
d = [float(i) for i in
[self.f_min, self.f_max, self.a]]
except ValueError:
sys.exit("The inputs should be numeric.")
if (np.array(d) < 0).sum() != 0:
sys.exit("The inputs should be positive.")
if len(self.volumetric_fractions) != len(self.materials):
sys.exit("Number of volumetric volumes does not match the dielectric properties")
# Check if the materials are at least two
if len(self.volumetric_fractions) < 2:
sys.exit("The materials should be at least 2")
# Check if the frequency range is null
if self.f_min == self.f_max:
sys.exit("Null frequency range")
# Check if the inputs are positive
f = [i for i in self.volumetric_fractions if i < 0]
if len(f) != 0:
sys.exit("Error: The inputs should be positive")
for i in range(len(self.volumetric_fractions)):
f = [i for i in self.materials[i][:] if i < 0]
if len(f) != 0:
sys.exit("Error: The inputs should be positive")
# Check if the summation of the volumetric fractions equal to one
if np.sum(self.volumetric_fractions) != 1:
sys.exit("Error: The summation of volumetric volumes should be equal to 1")
def print_info(self):
""" Print information about chosen approximation settings """
print(f"Approximating Complex Refractive Index Model (CRIM)"
f" using {self.number_of_debye_poles} Debye poles")
print("CRIM parameters: ")
for i in range(len(self.volumetric_fractions)):
print("Material {}.:".format(i+1))
print("---------------------------------")
print(f"{'Vol. fraction':>27s} = {self.volumetric_fractions[i]}")
print(f"{'e_inf':>27s} = {self.materials[i][0]}")
print(f"{'De':>27s} = {self.materials[i][1]}")
print(f"{'log(tau_0)':>27s} = {np.log10(self.materials[i][2])}")
def calculation(self):
"""Calculates the Crim function for the given parameters"""
return np.sum(np.repeat(self.volumetric_fractions, len(self.freq)
).reshape((-1, len(self.materials)))*(
self.materials[:, 0] + self.materials[:, 1] / (
1 + 1j * 2 * np.pi * np.repeat(self.freq, len(self.materials)
).reshape((-1, len(self.materials))) * self.materials[:, 2]))**self.a,
axis=1)**(1 / self.a)
class Rawdata(Relaxation):
""" Interpolate data given from a text file.
:param filename: text file which contains three columns:
frequency (Hz),Real,Imaginary (separated by comma).
:type filename: str, non-optional
:param delimiter: separator for three data columns
:type delimiter: str, optional (Deafult: ',')
"""
def __init__(self, filename,
sigma, mu, mu_sigma,
material_name, number_of_debye_poles=-1,
f_n=50, delimiter=',',
plot=False, save=False,
optimizer=PSO_DLS,
optimizer_options={}):
super(Rawdata, self).__init__(sigma=sigma, mu=mu, mu_sigma=mu_sigma,
material_name=material_name, f_n=f_n,
number_of_debye_poles=number_of_debye_poles,
plot=plot, save=save,
optimizer=optimizer,
optimizer_options=optimizer_options)
self.delimiter = delimiter
self.filename = Path(filename).absolute()
self.params = {'filename': self.filename}
def check_inputs(self):
""" Check the validity of the inputs. """
super(Rawdata, self).check_inputs()
if not os.path.isfile(self.filename):
sys.exit("File doesn't exists!")
def calculation(self):
""" Interpolate real and imaginary part from data.
Column framework of the input file three columns comma-separated
Frequency(Hz),Real,Imaginary
"""
# Read the file
with open(self.filename) as f:
try:
array = np.array(
[[float(x) for x in line.split(self.delimiter)] for line in f]
)
except ValueError:
sys.exit("Error: The inputs should be numeric")
self.set_freq(min(array[:, 0]), max(array[:, 0]), self.f_n)
rl_interp = scipy.interpolate.interp1d(array[:, 0], array[:, 1],
fill_value="extrapolate")
im_interp = scipy.interpolate.interp1d(array[:, 0], array[:, 2],
fill_value="extrapolate")
return rl_interp(self.freq) - 1j * im_interp(self.freq)
if __name__ == "__main__":
# Kelley et al. parameters
setup = HavriliakNegami(f_min=1e7, f_max=1e11,
alpha=0.91, beta=0.45,
e_inf=2.7, de=8.6-2.7, tau_0=9.4e-10,
sigma=0, mu=0, mu_sigma=0,
material_name="Kelley", f_n=100,
number_of_debye_poles=6,
plot=True, save=False,
optimizer_options={'swarmsize': 30,
'maxiter': 100,
'omega': 0.5,
'phip': 1.4,
'phig': 1.4,
'minstep': 1e-8,
'minfun': 1e-8,
'seed': 111,
'pflag': True})
setup.run()
setup = HavriliakNegami(f_min=1e7, f_max=1e11,
alpha=0.91, beta=0.45,
e_inf=2.7, de=8.6-2.7, tau_0=9.4e-10,
sigma=0, mu=0, mu_sigma=0,
material_name="Kelley", f_n=100,
number_of_debye_poles=6,
plot=True, save=False,
optimizer=DA_DLS,
optimizer_options={'seed': 111})
setup.run()
setup = HavriliakNegami(f_min=1e7, f_max=1e11,
alpha=0.91, beta=0.45,
e_inf=2.7, de=8.6-2.7, tau_0=9.4e-10,
sigma=0, mu=0, mu_sigma=0,
material_name="Kelley", f_n=100,
number_of_debye_poles=6,
plot=True, save=False,
optimizer=DE_DLS,
optimizer_options={'seed': 111})
setup.run()
# Testing setup
setup = Rawdata("examples/Test.txt", 0.1, 1, 0.1, "M1",
number_of_debye_poles=3, plot=True,
optimizer_options={'seed': 111})
setup.run()
np.random.seed(111)
setup = HavriliakNegami(1e12, 1e-3, 0.5, 1, 10, 5,
1e-6, 0.1, 1, 0, "M2",
number_of_debye_poles=6,
plot=True)
setup.run()
setup = Jonscher(1e6, 1e-5, 50, 1, 1e5, 0.7,
0.1, 1, 0.1, "M3",
number_of_debye_poles=4,
plot=True)
setup.run()
f = np.array([0.5, 0.5])
material1 = [3, 25, 1e6]
material2 = [3, 0, 1e3]
materials = np.array([material1, material2])
setup = Crim(1*1e-1, 1e-9, 0.5, f, materials, 0.1,
1, 0, "M4", number_of_debye_poles=2,
plot=True)
setup.run()

674
user_libs/DebyeFit/LICENSE 普通文件
查看文件

@@ -0,0 +1,674 @@
NU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

查看文件

@@ -0,0 +1,356 @@
Fitting multi-pole Debye model to dielectric data
=================================================
All electromagnetic phenomena are governed by the Maxwell's equations, which describing how electric and magnetic fields are distributed due to charges and currents,
and how they are changing in time. gprMax is open source software that simulates electromagnetic wave propagation by using
Yee's algorithm to solve (3+1)D Maxwell’s equations with Finite-Difference Time-Domain (FDTD) method.
The behavior of the electromagnetic wave is closely dependent on the material in which it propagates.
Some dispersive media have quite complex electromagnetic properties depending on the wavelength.
This, for example, means that for different frequencies the wave can propagate with a different speed in different materials.
This significantly affects the solver’s output. The main goal of the GSoC 2021 project was to enhance series of scripts,
which modelled electromagnetic properties of the variety range of materials.
Multi-pole Debye model
======================
Electric permittivity is a complex function with both real and imaginary parts.
In general, as a hard and fast rule, the real part dictates the velocity of the medium while the imaginary part is related to the electromagnetic losses.
The generic form of dispersive media takes a form of
.. math::
\epsilon(\omega) = \epsilon^{'}(\omega) - j\epsilon^{''}(\omega),
where :math:`\omega` is the angular frequency, :math:`\epsilon^{'}` and :math:`\epsilon^{''}` are the real and imaginary parts of the permittivity respectively.
In the ``user_libs`` sub-package is a module called ``DebyeFit`` which can be used to fit a multi-Debye expansion to dielectric data, defined as
.. math::
\epsilon(\omega) = \epsilon_{\infty} + \sum_{i=1}^{N}\frac{\Delta\epsilon_{i}}{1+j\omega t_{0,i}},
where :math:`\epsilon(\omega)` is frequency dependent dielectric permittivity, :math:`\Delta\epsilon` - difference between the real permittivity at zero and infinity frequency.
:math:`\tau_{0}` is relaxation time (s), :math:`\epsilon_{\infty}` - real part of relative permittivity at infinity frequency, and :math:`N` is number of the Debye poles.
The user can choose between Havriliak-Negami, Jonscher, Complex Refractive Index Mixing models, and arbitrary dielectric data derived experimentally
or calculated using some other function to fit the data to a multi-Debye expansion.
<div align="center">
<img src="docs/epsilon.png" width="600"/>
</div>
License
=======
``DebyeFit`` sub-package is currently released under the `GNU General Public License v3 or higher <http://www.gnu.org/copyleft/gpl.html>`_.
Code structure
==============
The ``DebyeFit`` sub-package contains two main scripts:
* ```Debye_fit.py``` with definition of all Relaxation functions classes,
* ```optimization.py``` with definition of three choosen global optimization methods.
Class Relaxation
################
This class is designed for modelling different relaxation functions, like Havriliak-Negami (```Class HavriliakNegami```), Jonscher (```Class Jonscher```), Complex Refractive Index Mixing (```Class CRIM```) models, and arbitrary dielectric data derived experimentally
or calculated using some other function (```Class Rawdata```).
More about ``Class Relaxation`` structure can be found in [relaxation.md](docs/relaxation.md).
Havriliak-Negami Function
*************************
The Havriliak–Negami relaxation is an empirical modification of the Debye relaxation model in electromagnetism, which in additionto the Debye equation has two exponential parameters
.. math::
\epsilon(\omega) = \epsilon_{\infty} + \frac{\Delta\epsilon}{\left(1+\left(j\omega t_{0}\right)^{a}\right)^{b}}
The ``HavriliakNegami`` class has the following structure:
.. code-block:: none
HavriliakNegami(f_min, f_max,
alpha, beta, e_inf, de, tau_0,
sigma, mu, mu_sigma, material_name,
number_of_debye_poles=-1, f_n=50,
plot=False, save=True,
optimizer=PSO_DLS,
optimizer_options={})
* ``f_min`` is first bound of the frequency range used to approximate the given function (Hz),
* ``f_max`` is second bound of the frequency range used to approximate the given function (Hz),
* ``alpha`` is real positive float number which varies 0 < $\alpha$ < 1,
* ``beta`` is real positive float number which varies 0 < $\beta$ < 1,
* ``e_inf`` is a real part of relative permittivity at infinity frequency,
* ``de`` is a difference between the real permittivity at zero and infinity frequency,
* ``tau_0`` is a relaxation time (s),
* ``sigma`` is a conductivity (Siemens/metre),
* ``mu`` is a relative permeability,
* ``mu_sigma`` is a magnetic loss (Ohms/metre),
* ``material_name`` is definition of material name,
* ``number_of_debye_poles`` is choosen number of Debye poles,
* ``f_n`` is choosen number of frequences,
* ``plot`` is a switch to turn on the plotting,
* ``save`` is a switch to turn on the saving final material properties,
* ``optimizer`` is a choosen optimizer to fit model to dielectric data,
* ``optimizer_options`` is a dict for options of choosen optimizer.
Jonscher Function
****************
Jonscher function is mainly used to describe the dielectric properties of concrete and soils. The frequency domain expression of Jonscher
function is given by
.. math::
\epsilon(\omega) = \epsilon_{\infty} + a_{p}*\left( -j*\frac{\omega}{\omega_{p}} \right)^{n}
The ``Jonscher`` class has the following structure:
.. code-block:: none
Jonscher(f_min, f_max,
e_inf, a_p, omega_p, n_p,
sigma, mu, mu_sigma,
material_name, number_of_debye_poles=-1,
f_n=50, plot=False, save=True,
optimizer=PSO_DLS,
optimizer_options={})
* ``f_min`` is first bound of the frequency range used to approximate the given function (Hz),
* ``f_max`` is second bound of the frequency range used to approximate the given function (Hz),
* ``e_inf`` is a real part of relative permittivity at infinity frequency,
* ``a_p``` is a Jonscher parameter. Real positive float number,
* ``omega_p`` is a Jonscher parameter. Real positive float number,
* ``n_p`` Jonscher parameter, 0 < n_p < 1.
Complex Refractive Index Mixing (CRIM) Function
***********************************************
CRIM is the most mainstream approach for estimating the bulk permittivity of heterogeneous materials and has been widely applied for GPR applications. The function takes form of
.. math::
\epsilon(\omega)^{d} = \sum_{i=1}^{m}f_{i}\epsilon_{m,i}(\omega)^{d}
The ``CRIM`` class has the following structure:
.. code-block:: none
CRIM(f_min, f_max, a, volumetric_fractions,
materials, sigma, mu, mu_sigma, material_name,
number_of_debye_poles=-1, f_n=50,
plot=False, save=True,
optimizer=PSO_DLS,
optimizer_options={})
* ``f_min`` is first bound of the frequency range used to approximate the given function (Hz),
* ``f_max`` is second bound of the frequency range used to approximate the given function (Hz),
* ``a`` is a shape factor,
* ``volumetric_fractions`` is a volumetric fraction for each material,
* ``materials`` are arrays of materials properties, for each material [e_inf, de, tau_0].
Rawdata Class
*************
The present package has the ability to model dielectric properties obtained experimentally by fitting multi-Debye functions to data given from a file.
The format of the file should be three columns. The first column contains the frequencies (Hz) associated with the electric permittivity point.
The second column contains the real part of the relative permittivity. The third column contains the imaginary part of the relative permittivity.
The columns should separated by coma by default (is it posible to define different separator).
The ``Rawdata`` class has the following structure:
.. code-block:: none
Rawdata(self, filename,
sigma, mu, mu_sigma,
material_name, number_of_debye_poles=-1,
f_n=50, delimiter =',',
plot=False, save=True,
optimizer=PSO_DLS,
optimizer_options={})
* ``filename`` is a path to text file which contains three columns,
* ``delimiter`` is a separator for three data columns.
Class Optimizer
###############
This class supports global optimization algorithms (particle swarm, duall annealing, evolutionary algorithms) for finding an optimal set of relaxation times that minimise the error between the actual and the approximated electric permittivity and calculate optimised weights for the given relaxation times.
Code written here is mainly based on external libraries, like ```scipy``` and ```pyswarm```.
More about ``Class Optimizer`` structure can be found in [optimization.md](docs/optimization.md).
PSO_DLS Class
*************
Creation of hybrid Particle Swarm-Damped Least Squares optimisation object with predefined parameters.
The current code is a modified edition of the pyswarm package which can be found at https://pythonhosted.org/pyswarm/.
DA_DLS Class
************
Creation of Dual Annealing-Damped Least Squares optimisation object with predefined parameters. The current class is a modified edition of the scipy.optimize package which can be found at:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.dual_annealing.html#scipy.optimize.dual_annealing.
DE_DLS Class
************
Creation of Differential Evolution-Damped Least Squares object with predefined parameters. The current class is a modified edition of the scipy.optimize package which can be found at:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.differential_evolution.html#scipy.optimize.differential_evolution.
DLS function
************
Finding the weights using a non-linear least squares (LS) method, the Levenberg–Marquardt algorithm (LMA or just LM), also known as the damped least-squares (DLS) method.
Examples
########
In directory [examples](./examles), we provided jupyter notebooks, scripts and data to show how use stand alone script ```DebyeFit.py```:
* ```example_DebyeFitting.ipynb```: simple cases of using all available implemented relaxation functions,
* ```example_BiologicalTissues.ipynb```: simple cases of using Cole-Cole function for biological tissues,
* ```example_ColeCole.py```: simple cases of using Cole-Cole function in case of 3, 5 and automatically chosen number of Debye poles,
* ```Test.txt```: raw data for testing ```Rawdata Class```, file contains 3 columns: the first column contains the frequencies (Hz) associated with the value of the permittivity, second column contains the real part of the relative permittivity, and the third one the imaginary part of the relative permittivity. The columns should separated by comma.
Dispersive material commands
============================
gprMax has implemented an optimisation approach to fit a multi-Debye expansion to dielectric data.
The user can choose between Havriliak-Negami, Johnsher and Complex Refractive Index Mixing models, fit arbitrary dielectric data derived experimentally or calculated using some other function.
Notice that Havriliak-Negami is an inclusive function that holds as special cases the widely-used **Cole-Cole** and **Cole-Davidson** functions.
.. note::
The technique employed here as a default is a hybrid linear-nonlinear optimisation proposed by Kelley et. al (2007).
Their method was slightly adjusted to overcome some instability issues and thus making the process more robust and faster.
In particular, in the case of negative weights we inverse the sign in order to introduce a large penalty in the optimisation process thus indirectly constraining the weights
to be always positive. This made dumbing factors unnecessary and consequently they were removed from the algorithm. Furthermore we added the real part to the cost action
to avoid possible instabilities to arbitrary given functions that does not follow the Kramers–Kronig relationship.
.. warning::
* The fitting accuracy depends on the number of the Debye poles as well as the fitted function. It is advised to check if the resulted accuracy is sufficient for your application.
* Increasing the number of Debye poles will make the approximation more accurate but it will increase the overall computational resources of FDTD.
#havriliak_negami:
##################
Allows you to model dielectric properties by fitting multi-Debye functions to Havriliak-Negami function. The syntax of the command is:
.. code-block:: none
#havriliak_negami: f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 i1 str1 [i2]
* ``f1`` is the lower frequency bound (Hz).
* ``f2`` is the upper frequency bound (Hz).
* ``f3`` is the :math:`\alpha` parameter beetwen bonds :math:`\left(0 < \alpha < 1 \right)`.
* ``f4`` is the :math:`\beta` parameter beetwen bonds :math:`\left(0 < \beta < 1 \right)`.
* ``f5`` is the real relative permittivity at infinity frequency, :math:`\epsilon_{\infty}`.
* ``f6`` is the difference between the real permittivity at zero and infinity frequency, :math:`\Delta\epsilon`.
* ``f7`` is the relaxation time (s), :math:`t_{0}`.
* ``f8`` is the conductivity (Siemens/metre), :math:`\sigma`
* ``f9`` is the relative permeability, :math:`\mu_r`
* ``f10`` is the magnetic loss (Ohms/metre), :math:`\sigma_*`
* ``i1`` is the number of Debye poles, set to -1 will be automatically calculated tends to minimize the relative absolut error.
* ``str1`` is an identifier for the material.
* ``i2`` is an optional parameter which controls the seeding of the random number generator used in stochastic global optimizator. By default (if you don't specify this parameter) the random number generator will be seeded by trying to read data from ``/dev/urandom`` (or the Windows analogue) if available or from the clock otherwise.
For example ``#havriliak_negami: 1e4 1e11 0.3 1 3.4 2.7 0.8e-10 4.5e-4 1 0 5 dry_sand`` creates a material called ``dry_sand``, and approximates using five Debye poles a Cole-Cole function with :math:`\epsilon_{\infty}=3.4`, :math:`\Delta\epsilon=2.7`, :math:`t_{0}=8^{-9}` and :math:`a=0.3`.
The resulting output is the set of gprMax commands and optional a plot with the actual and the approximated Cole-Cole function.
#jonscher:
##########
Allows you to model dielectric properties by fitting multi-Debye functions to Jonscher function. The syntax of the command is:
.. code-block:: none
#jonscher: f1 f2 f3 f4 f5 f6 f7 f8 f9 i1 str1 [i2]
* ``f1`` is the lower frequency bound (in Hz).
* ``f2`` is the upper frequency bound (in Hz).
* ``f3`` is the real relative permittivity at infinity frequency, :math:`\epsilon_{\infty}`.
* ``f4`` is the :math:`a_{p}` parameter.
* ``f5`` is the :math:`\omega_{p}` parameter.
* ``f6`` is the :math:`n_{p}` parameter.
* ``f7`` is the conductivity (Siemens/metre), :math:`\sigma`
* ``f8`` is the relative permeability, :math:`\mu_r`
* ``f9`` is the magnetic loss (Ohms/metre), :math:`\sigma_*`
* ``i1`` is the number of Debye poles, set to -1 will be automatically calculated tends to minimize the relative absolut error.
* ``str1`` is an identifier for the material.
* ``i2`` is an optional parameter which controls the seeding of the random number generator used in stochastic global optimizator. By default (if you don't specify this parameter) the random number generator will be seeded by trying to read data from ``/dev/urandom`` (or the Windows analogue) if available or from the clock otherwise.
For example ``#jonscher: 1e6 1e-5 4.39 7.49 5e-10 0.4 0.1 1 0.1 4 Material_Jonscher`` creates a material called ``Material_Jonscher``, and approximates using four Debye poles a Johnsher function with :math:`\epsilon_{\infty}=4.39`, :math:`a_{p}=7.49`, :math:`\omega_{p}=0.5\times 10^{9}` and :math:`n=0.4`.
The resulting output is the set of gprMax commands and optional a plot with the actual and the approximated Johnsher function.
#crim:
######
Allows you to model dielectric properties by fitting multi-Debye functions to CRIM function. The syntax of the command is:
.. code-block:: none
#crim: f1 f2 f3 v1 v2 f4 f5 f6 i1 str1 [i2]
* ``f1`` is the lower frequency bound (in Hz).
* ``f2`` is the upper frequency bound (in Hz).
* ``f3`` is the shape factor, :math:`a`
* ``v1`` is the vector (paramiter given in input file with `[]`) of volumetric fractions [f1, f2 .... ]. The nuber of paramiters depend on number of materials.
* ``v2`` is the vector (paramiter given in input file with `[]`) containing the materials properties [:math:`\epsilon_{1\infty}`, :math:`\Delta\epsilon_{1}`, :math:`t_{0}_{1}`, :math:`\epsilon_{2\infty}`, :math:`\Delta\epsilon_{2}`, :math:`t_{0}_{2}` .... ]. The number of material vector must be divisible by three.
* ``f4`` is the conductivity (Siemens/metre), :math:`\sigma`
* ``f5`` is the relative permeability, :math:`\mu_r`
* ``f6`` is the magnetic loss (Ohms/metre), :math:`\sigma_*`
* ``i1`` is the number of Debye poles, set to -1 will be automatically calculated tends to minimize the relative absolut error.
* ``str1`` is an identifier for the material.
* ``i2`` is an optional parameter which controls the seeding of the random number generator used in stochastic global optimizator. By default (if you don't specify this parameter) the random number generator will be seeded by trying to read data from ``/dev/urandom`` (or the Windows analogue) if available or from the clock otherwise.
For example ``#crim: 1e-1 1e-9 0.5 [0.5,0.1,0.4] [3,25,1e-8,3,25,1e-9,1,10,1e-10] 0 1 0 5 CRIM`` creates a material called ``CRIM``, and approximates using five Debye poles the following CRIM function
.. math::
\epsilon(\omega)^{0.5} = \sum_{i=1}^{m}f_{i}\epsilon_{m,i}(\omega)^{0.5}
.. math::
f = [0.5, 0.1, 0.4]
.. math::
\epsilon_{m,1} = 3 + \frac{25}{1+j\omega\times 10^{-8}}
.. math::
\epsilon_{m,2} = 3 + \frac{25}{1+j\omega\times 10^{-9}}
.. math::
\epsilon_{m,3} = 1 + \frac{10}{1+j\omega\times 10^{-10}}
The resulting output is the set of gprMax commands and optional a plot with the actual and the approximated CRIM function.
#raw_data:
##########
Allows you to model dielectric properties obtained experimentally by fitting multi-Debye functions to data given from a file. The syntax of the command is:
.. code-block:: none
#raw_data: file1 f1 f2 f3 i1 str1 [i2]
* ``file1`` is an path to text file with experimental data points.
* ``f1`` is the conductivity (Siemens/metre), :math:`\sigma`
* ``f2`` is the relative permeability, :math:`\mu_r`
* ``f3`` is the magnetic loss (Ohms/metre), :math:`\sigma_*`
* ``i1`` is the number of Debye poles, set to -1 will be automatically calculated tends to minimize the relative absolut error.
* ``str1`` is an identifier for the material.
* ``i2`` is an optional parameter which controls the seeding of the random number generator used in stochastic global optimizator. By default (if you don't specify this parameter) the random number generator will be seeded by trying to read data from ``/dev/urandom`` (or the Windows analogue) if available or from the clock otherwise.
For example ``#raw_data: user_libs/DebyeFit/examples/Test.txt 0.1 1 0.1 3 Experimental`` creates a material called ``Experimental`` which model dielectric properties obtained experimentally by fitting three Debye poles function to data given from a ``user_libs/DebyeFit/examples/Test.txt`` file.
The resulting output is the set of gprMax commands and optional a plot with the actual and the approximated function.

查看文件

@@ -0,0 +1,11 @@
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from .Debye_Fit import (HavriliakNegami,
Jonscher,
Crim,
Rawdata)
__all__ = [
'HavriliakNegami', 'Jonscher', 'Crim',
'Rawdata'
]

二进制
user_libs/DebyeFit/docs/epsilon.png 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 49 KiB

查看文件

@@ -0,0 +1,48 @@
# Optimization methods of multi-Debye fitting
``Class Optimizer`` supports global optimization algorithms (particle swarm, duall annealing, evolutionary algorithms) for finding an optimal set of relaxation times that minimise the error between the actual and the approximated electric permittivity and calculate optimised weights for the given relaxation times.
Code written here is mainly based on external libraries, like ```scipy``` and ```pyswarm```.
Supported methods:
- [x] hybrid Particle Swarm-Damped Least Squares
- [x] hybrid Dual Annealing-Damped Least Squares
- [x] hybrid Differential Evolution-Damped Least Squares
## Methods
1. __constructor__ - it is called in all childern classes.
It takes the following arguments:
- `maxiter`: maximum number of iterations for the optimizer,
- `seed`: Seed for RandomState.
In constructor the attributes:
- `maxiter`,
- `seed`,
- `calc_weights` (used to fit weight, non-linear least squares (LS) method is used as a default)
are set.
2. __fit__ - it is inherited by all children classes. It calls the optimization function that tries to find an optimal set of relaxation times that minimise the error between the actual and the approximated electric permittivity and calculate optimised weights for the given relaxation times.
It takes the following arguments:
- `func`: objective function to be optimized,
- `lb`: the lower bounds of the design variable(s),
- `ub`: the upper bounds of the design variable(s),
- `funckwargs`: optional arguments takien by objective function.
3. __cost_function__ - it is inherited by all children classes. It calculate cost function as the average error between the actual and the approximated electric permittivity (sum of real and imaginary part).
It takes the following arguments:
- `x`: the logarithm with base 10 of relaxation times of the Debyes poles,
- `rl`: real parts of chosen relaxation function for given frequency points,
- `im`: imaginary parts of chosen relaxation function for given frequency points,
- `freq`: the frequencies vector for defined grid.
4. __calc_relaxation_times__ - it find an optimal set of relaxation times that minimise an objective function using appropriate optimization procedure.
It takes the following arguments:
- `func`: objective function to be optimized,
- `lb`: the lower bounds of the design variable(s),
- `ub`: the upper bounds of the design variable(s),
- `funckwargs`: optional arguments takien by objective function.
Each new class of optimizer should:
- define constructor with appropriate arguments,
- overload __calc_relaxation_times__ method (and optional define __calc_weights__ function in case of hybrid optimization procedure).

查看文件

@@ -0,0 +1,69 @@
# Relaxation classes for multi-Debye fitting
This class is designed for modelling different relaxation functions, like Havriliak-Negami (```Class HavriliakNegami```), Jonscher (```Class Jonscher```), Complex Refractive Index Mixing (```Class CRIM```) models, and arbitrary dielectric data derived experimentally or calculated using some other function (```Class Rawdata```).
Supported relaxation classes:
- [x] Havriliak-Negami,
- [x] Jonscher,
- [x] Complex Refractive Index Mixing,
- [x] Experimental data,
## Methods
1. __constructor__ - it is called in all childern classes, creates Relaxation function object for complex material.
It takes the following arguments:
- ``sigma`` is a conductivity (Siemens/metre),
- ``mu`` is a relative permeability,
- ``mu_sigma`` is a magnetic loss (Ohms/metre),
- ``material_name`` is definition of material name,
- ``number_of_debye_poles`` is choosen number of Debye poles,
- ``f_n`` is choosen number of frequences,
- ``plot`` is a switch to turn on the plotting,
- ``save`` is a switch to turn on the saving final material properties,
- ``optimizer`` is a choosen optimizer to fit model to dielectric data,
- ``optimizer_options`` is a dict for options of choosen optimizer.
Additional parameters:
- ``rl`` calculated real part of chosen relaxation function for given frequency points,
- ``im`` calculated imaginary part of chosen relaxation function for given frequency points.
2. __set_freq__ - it is inherited by all childern classes, interpolates frequency vector using n equally logarithmicaly spaced frequencies.
It takes the following arguments:
- `f_min_`: first bound of the frequency range used to approximate the given function (Hz),
- `f_max`: second bound of the frequency range used to approximate the given function (Hz),
- `f_n`: the number of frequency points in frequency grid (Default: 50).
3. __run__ - it is inherited by all childern classes, solves the problem described by the given relaxation function (main operational method).
It consists of following steps:
1) Check the validity of the inputs using ```check_inputs``` method.
2) Print information about chosen approximation settings using ```print_info``` method.
3) Calculate both real and imaginary parts using ```calculation``` method, and then set ```self.rl``` and ```self.im``` properties.
4) Calling the main optimisation module using ```optimize``` method and calculate error based on ```error``` method.
a) [OPTIONAL] If number of debye poles is set to -1 optimization procedure is repeted until percentage error goes smaller than 5% or 20 Debye poles is reached.
5) Print the results in gprMax format style using ```print_output``` method.
6) [OPTIONAL] Save results in gprMax style using ```save_result``` method.
7) [OPTIONAL] Plot the actual and the approximate dielectric properties using ```plot_result``` method.
4. __check_inputs__ - it is called in all childern classes, finds an optimal set of relaxation times that minimise an objective function using appropriate optimization procedure.
5. __calculation__ - it is inherited by all childern classes, should be definied in all new children classes, approximates the given relaxation function.
6. __print_info__ - it is inherited by all childern classes, prints readable string of parameters for given approximation settings.
7. __optimize__ - it is inherited by all childern classes, calls the main optimisation module with defined lower and upper boundaries of search.
8. __print_output__ - it is inherited by all childern classes, prints out the resulting Debye parameters in a gprMax format.
9. __plot_result__ - it is inherited by all childern classes, plots the actual and the approximated electric permittivity, along with relative error for real and imaginary parts using a semilogarithm X axes.
10. __save_result__ - it is inherited by all childern classes, saves the resulting Debye parameters in a gprMax format.
11. __error__ - it is inherited by all childern classes, calculates the average fractional error separately for relative permittivity (real part) and conductivity (imaginary part).
Each new class of relaxation object should:
- define constructor with appropriate arguments,
- define __check_inputs__ method to check relaxation class specific parameters,
- overload __calculation__ method.

查看文件

@@ -0,0 +1,33 @@
# Getting started
Please see provided examples for the basic usage of ``DebyeFit`` module. We provide jupyter tutorials, and full guidance for quick run with existing relaxation functions and optimizers:
* ```example_DebyeFitting.ipynb```: simple cases of using all available implemented relaxation functions,
* ```example_BiologicalTissues.ipynb```: simple cases of using Cole-Cole function for biological tissues,
* ```example_ColeCole.py```: simple cases of using Cole-Cole function in case of 3, 5 and automatically chosen number of Debye poles.
Main usage of the specific relaxation fucntion based on creation of choosen relaxation model and then calling run method.
```python
# set Havrilak-Negami function with initial parameters
setup = HavriliakNegami(f_min=1e4, f_max=1e11,
alpha=0.3, beta=1,
e_inf=3.4, de=2.7, tau_0=.8e-10,
sigma=0.45e-3, mu=1, mu_sigma=0,
material_name="dry_sand", f_n=100,
plot=True, save=False,
number_of_debye_poles=3,
optimizer_options={'swarmsize':30,
'maxiter':100,
'omega':0.5,
'phip':1.4,
'phig':1.4,
'minstep':1e-8,
'minfun':1e-8,
'seed': 111,
'pflag': True})
# run optimization
setup.run()
```

查看文件

@@ -0,0 +1,41 @@
10000000,29.9213536481435,1.25169556541143
11220184.5430196,29.9010908161542,1.40299702432563
12589254.1179417,29.8756399586587,1.57217537410568
14125375.4462276,29.8436916400072,1.76117429474009
15848931.9246111,29.8036168365262,1.972079339829
17782794.1003892,29.7533952203391,2.20709802135445
19952623.1496888,29.6905309907513,2.46852367160776
22387211.3856834,29.611956285414,2.75867656083315
25118864.3150958,29.5139238169428,3.0798138913592
28183829.3126445,29.3918930811742,3.43399830398795
31622776.6016838,29.2404187150832,3.82291275991739
35481338.9233575,29.0530558254938,4.24760876499865
39810717.0553497,28.8223057349563,4.70817602888384
44668359.2150963,28.5396365567361,5.20332657814755
50118723.3627272,28.1956253280391,5.729897510637
56234132.5190349,27.7802793753847,6.28229678071347
63095734.4480193,27.283598801889,6.85194778826586
70794578.4384137,26.6964309897057,7.42683054876774
79432823.4724282,26.0116311645087,7.99126340085894
89125093.8133746,25.2254715223637,8.52610387978976
100000000,24.339136006498,9.00954486736777
112201845.430197,23.3600192468154,9.41861299029905
125892541.179417,22.302462791172,9.73132391277098
141253754.462276,21.1875720188749,9.92923323827099
158489319.246111,20.0419098344834,9.99991217790304
177827941.003892,18.8951464050085,9.93877751706085
199526231.496888,17.7770654023544,9.74979803763085
223872113.856834,16.714546101342,9.44488182455412
251188643.150958,15.7291491674702,9.04211441899954
281838293.126445,14.8357276987863,8.56331078490773
316227766.016838,14.0421664572876,8.03145189099272
354813389.233576,13.3500622522389,7.46848900052093
398107170.553497,12.7559948799797,6.89379357256362
446683592.150963,12.2530185094144,6.32331224790652
501187233.627271,11.8320839792422,5.76932819987279
562341325.190349,11.4832204965472,5.24065519659195
630957344.480194,11.1964125953287,4.74308431385235
707945784.384137,10.9621824341848,4.27993617324392
794328234.724282,10.7719266477577,3.85261757843109
891250938.133744,10.6180694756136,3.46112404221322
1000000000,10.4940904606372,3.10446192269295

文件差异因一行或多行过长而隐藏

查看文件

@@ -0,0 +1,44 @@
# I. Giannakis, A. Giannopoulos and N. Davidson,
# "Incorporating dispersive electrical properties in FDTD GPR models
# using a general Cole-Cole dispersion function,"
# 2012 14th International Conference on Ground Penetrating Radar (GPR), 2012, pp. 232-236
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from Debye_Fit import HavriliakNegami
if __name__ == "__main__":
# set Havrilak-Negami function with initial parameters
setup = HavriliakNegami(f_min=1e4, f_max=1e11,
alpha=0.3, beta=1,
e_inf=3.4, de=2.7, tau_0=.8e-10,
sigma=0.45e-3, mu=1, mu_sigma=0,
material_name="dry_sand", f_n=100,
plot=True, save=False,
optimizer_options={'swarmsize':30,
'maxiter':100,
'omega':0.5,
'phip':1.4,
'phig':1.4,
'minstep':1e-8,
'minfun':1e-8,
'seed': 111,
'pflag': True})
### Dry Sand in case of 3, 5
# and automatically set number of Debye poles (-1)
for number_of_debye_poles in [3, 5, -1]:
setup.number_of_debye_poles = number_of_debye_poles
setup.run()
### Moist sand
# set Havrilak-Negami function parameters
setup.material_name="moist_sand"
setup.alpha = 0.25
setup.beta = 1
setup.e_inf = 5.6
setup.de = 3.3
setup.tau_0 = 1.1e-10,
setup.sigma = 2e-3
# calculate for different number of Debye poles
for number_of_debye_poles in [3, 5, -1]:
setup.number_of_debye_poles = number_of_debye_poles
setup.run()

文件差异因一行或多行过长而隐藏

查看文件

@@ -0,0 +1,473 @@
# Authors: Iraklis Giannakis, and Sylwia Majchrowska
# E-mail: i.giannakis@ed.ac.uk
#
# This file is part of gprMax.
#
# gprMax is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# gprMax is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with gprMax. If not, see <http://www.gnu.org/licenses/>.
import numpy as np
from matplotlib import pylab as plt
import scipy.optimize
from tqdm import tqdm
class Optimizer(object):
"""
Create choosen optimisation object.
:param maxiter: The maximum number of iterations for the
optimizer (Default: 1000).
:type maxiter: int, optional
:param seed: Seed for RandomState. Must be convertible to 32 bit
unsigned integers (Default: None).
:type seed: int, NoneType, optional
"""
def __init__(self, maxiter=1000, seed=None):
self.maxiter = maxiter
self.seed = seed
self.calc_weights = None
def fit(self, func, lb, ub, funckwargs={}):
"""Call the optimization function that tries to find an optimal set
of relaxation times that minimise the error
between the actual and the approximated electric permittivity
and calculate optimised weights for the given relaxation times.
Args:
func (function): The function to be minimized.
lb (ndarray): The lower bounds of the design variable(s).
ub (ndarray): The upper bounds of the design variable(s).
funckwargs (dict): Additional keyword arguments passed to
objective and constraint function
(Default: empty dict).
Returns:
tau (ndarray): The the best relaxation times.
weights (ndarray): Resulting optimised weights for the given
relaxation times.
ee (float): Average error between the actual and the approximated
real part.
rl (ndarray): Real parts of chosen relaxation function
for given frequency points.
im (ndarray): Imaginary parts of chosen relaxation function
for given frequency points.
"""
np.random.seed(self.seed)
# find the relaxation frequencies using choosen optimization alghoritm
tau, _ = self.calc_relaxation_times(func, lb, ub, funckwargs)
# find the weights using a calc_weights method
if self.calc_weights is None:
raise NotImplementedError()
_, _, weights, ee, rl_exp, im_exp = \
self.calc_weights(tau, **funckwargs)
return tau, weights, ee, rl_exp, im_exp
def calc_relaxation_times(self):
""" Optimisation method that tries to find an optimal set
of relaxation times that minimise the error
between the actual and the approximated electric permittivity.
"""
raise NotImplementedError()
@staticmethod
def cost_function(x, rl, im, freq):
"""
The cost function is the average error between
the actual and the approximated electric permittivity.
Args:
x (ndarray): The logarithm with base 10 of relaxation times
of the Debyes poles.
rl (ndarray): Real parts of chosen relaxation function
for given frequency points.
im (ndarray): Imaginary parts of chosen relaxation function
for given frequency points.
freq (ndarray): The frequencies vector for defined grid.
Returns:
cost (float): Sum of mean absolute errors for real and
imaginary parts.
"""
cost_i, cost_r, _, _, _, _ = DLS(x, rl, im, freq)
return cost_i + cost_r
class PSO_DLS(Optimizer):
""" Create hybrid Particle Swarm-Damped Least Squares optimisation
object with predefined parameters.
:param swarmsize: The number of particles in the swarm (Default: 40).
:type swarmsize: int, optional
:param maxiter: The maximum number of iterations for the swarm
to search (Default: 50).
:type maxiter: int, optional
:param omega: Particle velocity scaling factor (Default: 0.9).
:type omega: float, optional
:param phip: Scaling factor to search away from the particle's
best known position (Default: 0.9).
:type phip: float, optional
:param phig: Scaling factor to search away from the swarm's
best known position (Default: 0.9).
:type phig: float, optional
:param minstep: The minimum stepsize of swarm's best position
before the search terminates (Default: 1e-8).
:type minstep: float, optional
:param minfun: The minimum change of swarm's best objective value
before the search terminates (Default: 1e-8)
:type minfun: float, optional
:param pflag: if True will plot the actual and the approximated
value during optimization process (Default: False).
:type pflag: bool, optional
"""
def __init__(self, swarmsize=40, maxiter=50,
omega=0.9, phip=0.9, phig=0.9,
minstep=1e-8, minfun=1e-8,
pflag=False, seed=None):
super(PSO_DLS, self).__init__(maxiter, seed)
self.swarmsize = swarmsize
self.omega = omega
self.phip = phip
self.phig = phig
self.minstep = minstep
self.minfun = minfun
self.pflag = pflag
self.calc_weights = DLS
def calc_relaxation_times(self, func, lb, ub, funckwargs={}):
"""
A particle swarm optimisation that tries to find an optimal set
of relaxation times that minimise the error
between the actual and the approximated electric permittivity.
The current code is a modified edition of the pyswarm package
which can be found at https://pythonhosted.org/pyswarm/
Args:
func (function): The function to be minimized.
lb (ndarray): The lower bounds of the design variable(s).
ub (ndarray): The upper bounds of the design variable(s).
funckwargs (dict): Additional keyword arguments passed to
objective and constraint function
(Default: empty dict).
Returns:
g (ndarray): The swarm's best known position (relaxation times).
fg (float): The objective value at ``g``.
"""
np.random.seed(self.seed)
# check input parameters
assert len(lb) == len(ub), \
'Lower- and upper-bounds must be the same length'
assert hasattr(func, '__call__'), 'Invalid function handle'
lb = np.array(lb)
ub = np.array(ub)
assert np.all(ub > lb), \
'All upper-bound values must be greater than lower-bound values'
vhigh = np.abs(ub - lb)
vlow = -vhigh
# Initialize objective function
obj = lambda x: func(x=x, **funckwargs)
# Initialize the particle swarm
d = len(lb) # the number of dimensions each particle has
x = np.random.rand(self.swarmsize, d) # particle positions
v = np.zeros_like(x) # particle velocities
p = np.zeros_like(x) # best particle positions
fp = np.zeros(self.swarmsize) # best particle function values
g = [] # best swarm position
fg = np.inf # artificial best swarm position starting value
for i in range(self.swarmsize):
# Initialize the particle's position
x[i, :] = lb + x[i, :] * (ub - lb)
# Initialize the particle's best known position
p[i, :] = x[i, :]
# Calculate the objective's value at the current particle's
fp[i] = obj(p[i, :])
# At the start, there may not be any feasible starting point,
# so just
# give it a temporary "best" point since it's likely to change
if i == 0:
g = p[0, :].copy()
# If the current particle's position is better than the swarm's,
# update the best swarm position
if fp[i] < fg:
fg = fp[i]
g = p[i, :].copy()
# Initialize the particle's velocity
v[i, :] = vlow + np.random.rand(d) * (vhigh - vlow)
# Iterate until termination criterion met
for it in tqdm(range(self.maxiter), desc='Debye fitting'):
rp = np.random.uniform(size=(self.swarmsize, d))
rg = np.random.uniform(size=(self.swarmsize, d))
for i in range(self.swarmsize):
# Update the particle's velocity
v[i, :] = self.omega * v[i, :] + self.phip * rp[i, :] * \
(p[i, :] - x[i, :]) + \
self.phig * rg[i, :] * (g - x[i, :])
# Update the particle's position,
# correcting lower and upper bound
# violations, then update the objective function value
x[i, :] = x[i, :] + v[i, :]
mark1 = x[i, :] < lb
mark2 = x[i, :] > ub
x[i, mark1] = lb[mark1]
x[i, mark2] = ub[mark2]
fx = obj(x[i, :])
# Compare particle's best position
if fx < fp[i]:
p[i, :] = x[i, :].copy()
fp[i] = fx
# Compare swarm's best position to current
# particle's position
if fx < fg:
tmp = x[i, :].copy()
stepsize = np.sqrt(np.sum((g - tmp) ** 2))
if np.abs(fg - fx) <= self.minfun:
print(f'Stopping search: Swarm best objective '
f'change less than {self.minfun}')
return tmp, fx
elif stepsize <= self.minstep:
print(f'Stopping search: Swarm best position '
f'change less than {self.minstep}')
return tmp, fx
else:
g = tmp.copy()
fg = fx
# Dynamically plot the error as the optimisation takes place
if self.pflag:
if it == 0:
xpp = [it]
ypp = [fg]
else:
xpp.append(it)
ypp.append(fg)
PSO_DLS.plot(xpp, ypp)
return g, fg
@staticmethod
def plot(x, y):
"""
Dynamically plot the error as the optimisation takes place.
Args:
x (array): The number of current iterations.
y (array): The objective value at for all x points.
"""
# it clears an axes
plt.cla()
plt.plot(x, y, "b-", linewidth=1.0)
plt.ylim(min(y) - 0.1 * min(y),
max(y) + 0.1 * max(y))
plt.xlim(min(x) - 0.1, max(x) + 0.1)
plt.grid(b=True, which="major", color="k",
linewidth=0.2, linestyle="--")
plt.suptitle("Debye fitting process")
plt.xlabel("Iteration")
plt.ylabel("Average Error")
plt.pause(0.0001)
class DA_DLS(Optimizer):
""" Create Dual Annealing object with predefined parameters.
The current class is a modified edition of the scipy.optimize
package which can be found at:
https://docs.scipy.org/doc/scipy/reference/generated/
scipy.optimize.dual_annealing.html#scipy.optimize.dual_annealing
"""
def __init__(self, maxiter=1000,
local_search_options={}, initial_temp=5230.0,
restart_temp_ratio=2e-05, visit=2.62, accept=-5.0,
maxfun=1e7, no_local_search=False,
callback=None, x0=None, seed=None):
super(DA_DLS, self).__init__(maxiter, seed)
self.local_search_options = local_search_options
self.initial_temp = initial_temp
self.restart_temp_ratio = restart_temp_ratio
self.visit = visit
self.accept = accept
self.maxfun = maxfun
self.no_local_search = no_local_search
self.callback = callback
self.x0 = x0
self.calc_weights = DLS
def calc_relaxation_times(self, func, lb, ub, funckwargs={}):
"""
Find the global minimum of a function using Dual Annealing.
The current class is a modified edition of the scipy.optimize
package which can be found at:
https://docs.scipy.org/doc/scipy/reference/generated/
scipy.optimize.dual_annealing.html#scipy.optimize.dual_annealing
Args:
func (function): The function to be minimized
lb (ndarray): The lower bounds of the design variable(s)
ub (ndarray): The upper bounds of the design variable(s)
funckwargs (dict): Additional keyword arguments passed to
objective and constraint function
(Default: empty dict)
Returns:
x (ndarray): The solution array (relaxation times).
fun (float): The objective value at the best solution.
"""
np.random.seed(self.seed)
result = scipy.optimize.dual_annealing(
func,
bounds=list(zip(lb, ub)),
args=funckwargs.values(),
maxiter=self.maxiter,
local_search_options=self.local_search_options,
initial_temp=self.initial_temp,
restart_temp_ratio=self.restart_temp_ratio,
visit=self.visit,
accept=self.accept,
maxfun=self.maxfun,
no_local_search=self.no_local_search,
callback=self.callback,
x0=self.x0)
print(result.message)
return result.x, result.fun
class DE_DLS(Optimizer):
"""
Create Differential Evolution-Damped Least Squares object
with predefined parameters.
The current class is a modified edition of the scipy.optimize
package which can be found at:
https://docs.scipy.org/doc/scipy/reference/generated/
scipy.optimize.differential_evolution.html#scipy.optimize.differential_evolution
"""
def __init__(self, maxiter=1000,
strategy='best1bin', popsize=15, tol=0.01, mutation=(0.5, 1),
recombination=0.7, callback=None, disp=False, polish=True,
init='latinhypercube', atol=0,
updating='immediate', workers=1,
constraints=(), seed=None):
super(DE_DLS, self).__init__(maxiter, seed)
self.strategy = strategy
self.popsize = popsize
self.tol = tol
self.mutation = mutation
self.recombination = recombination
self.callback = callback
self.disp = disp
self.polish = polish
self.init = init
self.atol = atol
self.updating = updating
self.workers = workers
self.constraints = constraints
self.calc_weights = DLS
def calc_relaxation_times(self, func, lb, ub, funckwargs={}):
"""
Find the global minimum of a function using Differential Evolution.
The current class is a modified edition of the scipy.optimize
package which can be found at:
https://docs.scipy.org/doc/scipy/reference/generated/
scipy.optimize.differential_evolution.html#scipy.optimize.differential_evolution
Args:
func (function): The function to be minimized
lb (ndarray): The lower bounds of the design variable(s)
ub (ndarray): The upper bounds of the design variable(s)
funckwargs (dict): Additional keyword arguments passed to
objective and constraint function
(Default: empty dict)
Returns:
x (ndarray): The solution array (relaxation times).
fun (float): The objective value at the best solution.
"""
np.random.seed(self.seed)
result = scipy.optimize.differential_evolution(
func,
bounds=list(zip(lb, ub)),
args=funckwargs.values(),
strategy=self.strategy,
popsize=self.popsize,
tol=self.tol,
mutation=self.mutation,
recombination=self.recombination,
callback=self.callback,
disp=self.disp,
polish=self.polish,
init=self.init,
atol=self.atol,
updating=self.updating,
workers=self.workers,
constraints=self.constraints)
print(result.message)
return result.x, result.fun
def DLS(logt, rl, im, freq):
"""
Find the weights using a non-linear least squares (LS) method,
the Levenberg–Marquardt algorithm (LMA or just LM),
also known as the damped least-squares (DLS) method.
Args:
logt (ndarray): The best known position form optimization module
(optimal design),
the logarithm with base 10 of relaxation times
of the Debyes poles.
rl (ndarray): Real parts of chosen relaxation function
for given frequency points.
im (ndarray): Imaginary parts of chosen relaxation function
for given frequency points.
freq (ndarray): The frequencies vector for defined grid.
Returns:
cost_i (float): Mean absolute error between the actual and
the approximated imaginary part.
cost_r (float): Mean absolute error between the actual and
the approximated real part (plus average error).
x (ndarray): Resulting optimised weights for the given
relaxation times.
ee (float): Average error between the actual and the approximated
real part.
rp (ndarray): The real part of the permittivity for the optimised
relaxation times and weights for the frequnecies included
in freq.
ip (ndarray): The imaginary part of the permittivity for the optimised
relaxation times and weights for the frequnecies included
in freq.
"""
# The relaxation time of the Debyes are given at as logarithms
# logt=log10(t0) for efficiency during the optimisation
# Here they are transformed back t0=10**logt
tt = 10**logt
# y = Ax, here the A matrix for the real and the imaginary part is builded
d = 1 / (1 + 1j * 2 * np.pi * np.repeat(
freq, len(tt)).reshape((-1, len(tt))) * tt)
# Adding dumping (Levenberg–Marquardt algorithm)
# Solving the overdetermined system y=Ax
x = np.abs(np.linalg.lstsq(d.imag, im, rcond=None)[0])
# x - absolute damped least-squares solution
rp, ip = np.matmul(d.real, x[np.newaxis].T).T[0], np.matmul(
d.imag, x[np.newaxis].T).T[0]
cost_i = np.sum(np.abs(ip-im))/len(im)
ee = np.mean(rl - rp)
if ee < 1:
ee = 1
cost_r = np.sum(np.abs(rp + ee - rl))/len(im)
return cost_i, cost_r, x, ee, rp, ip

查看文件

@@ -0,0 +1,4 @@
matplotlib==3.3.4
numpy==1.20.2
scipy==1.6.2
tqdm==4.61.1

7
user_models/CRIM_test.in 普通文件
查看文件

@@ -0,0 +1,7 @@
#domain: 0.7 0.5 0.004
#dx_dy_dz: 0.004 0.004 0.004
#time_window: 3000
#crim: 1e-1 1e-9 0.5 [0.5,0.5] [3,25,1e6,3,0,1e3] 0.1 1 0 2 M3
#box: 0 0 0 0.07 0.4 0.004 M3